Initial commit

This commit is contained in:
Chris Chen
2022-09-08 08:04:32 -07:00
commit 184db15773
4604 changed files with 503905 additions and 0 deletions
+488
View File
@@ -0,0 +1,488 @@
using System;
using System.Globalization;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using Chruch.Net.Models;
using Church.Net.Entity;
namespace Chruch.Net.Controllers
{
[Authorize]
public class AccountController : Controller
{
private ApplicationSignInManager _signInManager;
private ApplicationUserManager _userManager;
public AccountController()
{
}
public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager )
{
UserManager = userManager;
SignInManager = signInManager;
}
public ApplicationSignInManager SignInManager
{
get
{
return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
}
private set
{
_signInManager = value;
}
}
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
//
// GET: /Account/Login
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
// 這不會計算為帳戶鎖定的登入失敗
// 若要啟用密碼失敗來觸發帳戶鎖定,請變更為 shouldLockout: true
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "登入嘗試失試。");
return View(model);
}
}
//
// GET: /Account/VerifyCode
[AllowAnonymous]
public async Task<ActionResult> VerifyCode(string provider, string returnUrl, bool rememberMe)
{
// 需要使用者已透過使用者名稱/密碼或外部登入進行登入
if (!await SignInManager.HasBeenVerifiedAsync())
{
return View("Error");
}
return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/VerifyCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> VerifyCode(VerifyCodeViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// 下列程式碼保護兩個因素碼不受暴力密碼破解攻擊。
// 如果使用者輸入不正確的代碼來表示一段指定的時間,則使用者帳戶
// 會有一段指定的時間遭到鎖定。
// 您可以在 IdentityConfig 中設定帳戶鎖定設定
var result = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, isPersistent: model.RememberMe, rememberBrowser: model.RememberBrowser);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(model.ReturnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "代碼無效。");
return View(model);
}
}
//
// GET: /Account/Register
[AllowAnonymous]
public ActionResult Register()
{
return View();
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new FamilyMember { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
UserManager.AddToRole(user.Id, "FamilyMember");
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
// 如需如何進行帳戶確認及密碼重設的詳細資訊,請前往 https://go.microsoft.com/fwlink/?LinkID=320771
// 傳送包含此連結的電子郵件
// string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
// var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
// await UserManager.SendEmailAsync(user.Id, "確認您的帳戶", "請按一下此連結確認您的帳戶 <a href=\"" + callbackUrl + "\">這裏</a>");
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
// 如果執行到這裡,發生某項失敗,則重新顯示表單
return View(model);
}
//
// GET: /Account/ConfirmEmail
[AllowAnonymous]
public async Task<ActionResult> ConfirmEmail(string userId, string code)
{
if (userId == null || code == null)
{
return View("Error");
}
var result = await UserManager.ConfirmEmailAsync(userId, code);
return View(result.Succeeded ? "ConfirmEmail" : "Error");
}
//
// GET: /Account/ForgotPassword
[AllowAnonymous]
public ActionResult ForgotPassword()
{
return View();
}
//
// POST: /Account/ForgotPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindByNameAsync(model.Email);
if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
{
// 不顯示使用者不存在或未受確認
return View("ForgotPasswordConfirmation");
}
// 如需如何進行帳戶確認及密碼重設的詳細資訊,請前往 https://go.microsoft.com/fwlink/?LinkID=320771
// 傳送包含此連結的電子郵件
// string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
// var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
// await UserManager.SendEmailAsync(user.Id, "重設密碼", "請按 <a href=\"" + callbackUrl + "\">這裏</a> 重設密碼");
// return RedirectToAction("ForgotPasswordConfirmation", "Account");
}
// 如果執行到這裡,發生某項失敗,則重新顯示表單
return View(model);
}
//
// GET: /Account/ForgotPasswordConfirmation
[AllowAnonymous]
public ActionResult ForgotPasswordConfirmation()
{
return View();
}
//
// GET: /Account/ResetPassword
[AllowAnonymous]
public ActionResult ResetPassword(string code)
{
return code == null ? View("Error") : View();
}
//
// POST: /Account/ResetPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ResetPassword(ResetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await UserManager.FindByNameAsync(model.Email);
if (user == null)
{
// 不顯示使用者不存在
return RedirectToAction("ResetPasswordConfirmation", "Account");
}
var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);
if (result.Succeeded)
{
return RedirectToAction("ResetPasswordConfirmation", "Account");
}
AddErrors(result);
return View();
}
//
// GET: /Account/ResetPasswordConfirmation
[AllowAnonymous]
public ActionResult ResetPasswordConfirmation()
{
return View();
}
//
// POST: /Account/ExternalLogin
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ExternalLogin(string provider, string returnUrl)
{
// 要求重新導向至外部登入提供者
return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
}
//
// GET: /Account/SendCode
[AllowAnonymous]
public async Task<ActionResult> SendCode(string returnUrl, bool rememberMe)
{
var userId = await SignInManager.GetVerifiedUserIdAsync();
if (userId == null)
{
return View("Error");
}
var userFactors = await UserManager.GetValidTwoFactorProvidersAsync(userId);
var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/SendCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> SendCode(SendCodeViewModel model)
{
if (!ModelState.IsValid)
{
return View();
}
// 產生並傳送 Token
if (!await SignInManager.SendTwoFactorCodeAsync(model.SelectedProvider))
{
return View("Error");
}
return RedirectToAction("VerifyCode", new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe });
}
//
// GET: /Account/ExternalLoginCallback
[AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
if (loginInfo == null)
{
return RedirectToAction("Login");
}
// 若使用者已經有登入資料,請使用此外部登入提供者登入使用者
var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false });
case SignInStatus.Failure:
default:
// 若使用者沒有帳戶,請提示使用者建立帳戶
ViewBag.ReturnUrl = returnUrl;
ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email });
}
}
//
// POST: /Account/ExternalLoginConfirmation
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
{
if (User.Identity.IsAuthenticated)
{
return RedirectToAction("Index", "Manage");
}
if (ModelState.IsValid)
{
// 從外部登入提供者處取得使用者資訊
var info = await AuthenticationManager.GetExternalLoginInfoAsync();
if (info == null)
{
return View("ExternalLoginFailure");
}
var user = new FamilyMember { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user);
if (result.Succeeded)
{
result = await UserManager.AddLoginAsync(user.Id, info.Login);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
return RedirectToLocal(returnUrl);
}
}
AddErrors(result);
}
ViewBag.ReturnUrl = returnUrl;
return View(model);
}
//
// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
return RedirectToAction("Index", "Home");
}
//
// GET: /Account/ExternalLoginFailure
[AllowAnonymous]
public ActionResult ExternalLoginFailure()
{
return View();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (_userManager != null)
{
_userManager.Dispose();
_userManager = null;
}
if (_signInManager != null)
{
_signInManager.Dispose();
_signInManager = null;
}
}
base.Dispose(disposing);
}
#region Helper
// 新增外部登入時用來當做 XSRF 保護
private const string XsrfKey = "XsrfId";
private IAuthenticationManager AuthenticationManager
{
get
{
return HttpContext.GetOwinContext().Authentication;
}
}
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error);
}
}
private ActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
return RedirectToAction("Index", "Home");
}
internal class ChallengeResult : HttpUnauthorizedResult
{
public ChallengeResult(string provider, string redirectUri)
: this(provider, redirectUri, null)
{
}
public ChallengeResult(string provider, string redirectUri, string userId)
{
LoginProvider = provider;
RedirectUri = redirectUri;
UserId = userId;
}
public string LoginProvider { get; set; }
public string RedirectUri { get; set; }
public string UserId { get; set; }
public override void ExecuteResult(ControllerContext context)
{
var properties = new AuthenticationProperties { RedirectUri = RedirectUri };
if (UserId != null)
{
properties.Dictionary[XsrfKey] = UserId;
}
context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
}
}
#endregion
}
}
@@ -0,0 +1,174 @@
using Church.Net.DAL.EF;
using Church.Net.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
namespace Chruch.Net.Controllers
{
public class HappinessController : Controller
{
private ChurchNetContext db = new ChurchNetContext();
// GET: Happiness
public ActionResult Best(string id)
{
HappinessBEST best;
best = db.HappinessBESTs.FirstOrDefault(h => h.BestId == id);
if (best!=null)
{
ViewBag.BestName = best.Name;
HappinessGroup group = new HappinessGroup();
group = db.HappinessGroups.First(g => g.GroupId == best.GroupId);
group.BestList = new List<HappinessBEST>();
group.BestList.Clear();
group.BestList.Add(best);
group.Weeks = new List<HappinessWeek>();
group.Weeks.Clear();
var qurry = db.HappinessWeeks.OrderBy(o => o.SEQ).ToList();
group.Weeks.Add(qurry.First(g => g.GroupId == best.GroupId & g.Date>= DateTime.Today));
string weekTitle = "";
StringBuilder invitation = new StringBuilder();
invitation.Append($".type('Hi, <strong>{best.Name}</strong>,').break()");
switch (group.Weeks.First().SEQ)
{
case 1:
weekTitle = "真幸福";
invitation.Append("我們想送你一份禮物, ");
invitation.Append("他是人生中最棒的夥伴, ");
invitation.Append("為你帶來超乎想像的幸福感, ");
invitation.Append("值得你用8個星期的時間來認識. ");
invitation.Append("幸福小組,邀你一同了解幸福! ");
break;
case 2:
weekTitle = "真相大白";
invitation.Append(".options({ speed: 155 }).type('我們想送你一份禮物,').pause(500)");
invitation.Append(".options({ speed: 125 }).delete(10)");
invitation.Append(".type('你以為我們這麼偷懶 :-)').break()");
invitation.Append(".type('每周的邀請函內容一樣嗎?').break()");
invitation.Append(".type('當然不是囉~').break()");
invitation.Append(".type('我們可是求新求變,').break()");
invitation.Append(".type('尋找人生新氣象的幸福小組呢~').break()");
invitation.Append(".type('這周想邀請你一起來,').break()");
invitation.Append(".type('破除謊言尋找幸福的真相唷~').break()");
break;
case 3:
weekTitle = "萬世巨星";
invitation.Append(".type('這星期過得好嗎? ').break()");
invitation.Append(".options({ speed: 155 }).type('這週將揭曉一位萬事巨猩唷!')");
invitation.Append(".options({ speed: 125 }).delete(4)");
invitation.Append(".type('巨星唷!').break()");
invitation.Append(".type('想知道是誰要登場了嗎;-)? ').break()");
invitation.Append(".type('千萬別錯過這週的幸福小組唷~ ').break()");
invitation.Append(".type('期待與你幸福有約。 ').break()");
invitation.Append(".type('讓我們一起來經歷平安、喜樂 ').break()");
invitation.Append(".options({ speed: 175 }).type('祝 福 滿 滿!!!')");
break;
case 4:
weekTitle = "幸福連線";
break;
case 5:
weekTitle = "當上帝來敲門";
break;
case 6:
weekTitle = "十字架的勝利";
break;
case 7:
weekTitle = "釋放與自由";
break;
case 8:
weekTitle = "幸福的教會";
break;
default:
break;
}
ViewBag.Title = $"{group.Name}-邀請函之{weekTitle}! for {best.Name}";
ViewBag.InvitationJS = invitation.ToString();
return View(group);
}
return RedirectToAction("Index", "Home");
}
public ActionResult Week(int id)
{
HappinessGroup group = new HappinessGroup();
group = db.HappinessGroups.First();
group.Weeks = new List<HappinessWeek>();
group.Weeks.Clear();
var qurry = db.HappinessWeeks.OrderBy(o => o.SEQ).ToList();
group.Weeks.Add(qurry.First(g => g.GroupId == group.GroupId & g.SEQ == id));
HappinessBEST best;
best = group.BestList.First();
ViewBag.BestName = best.Name;
string weekTitle = "";
StringBuilder invitation = new StringBuilder();
switch (group.Weeks.First().SEQ)
{
case 1:
weekTitle = "真幸福";
break;
case 2:
weekTitle = "真相大白";
invitation.Append($".type('Hi, <strong>{best.Name}</strong>,').break()");
invitation.Append(".options({ speed: 155 }).type('我們想送你一份禮物,').pause(500)");
invitation.Append(".options({ speed: 125 }).delete(10)");
invitation.Append(".type('你以為我們這麼偷懶 :-)').break()");
invitation.Append(".type('每周的邀請函內容一樣嗎?').break()");
invitation.Append(".type('當然不是囉~').break()");
invitation.Append(".type('我們可是求新求變,').break()");
invitation.Append(".type('尋找人生新氣象的幸福小組呢~').break()");
invitation.Append(".type('這周想邀請你一起來,').break()");
invitation.Append(".type('破除謊言尋找幸福的真相唷~').break()");
break;
case 3:
weekTitle = "萬世巨星";
break;
case 4:
weekTitle = "幸福連線";
break;
case 5:
weekTitle = "當上帝來敲門";
break;
case 6:
weekTitle = "十字架的勝利";
break;
case 7:
weekTitle = "釋放與自由";
break;
case 8:
weekTitle = "幸福的教會";
break;
default:
break;
}
ViewBag.Title = $"{group.Name}-邀請函之{weekTitle}! for {group.BestList.First().Name}";
ViewBag.InvitationJS = invitation.ToString();
return View("Best", group);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
+46
View File
@@ -0,0 +1,46 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Chruch.Net.Controllers
{
public class HomeController : Controller
{
public ActionResult Index(string id)
{
if (HttpContext.Request.Url.AbsoluteUri.IndexOf("gls.") > 0 || HttpContext.Request.Url.AbsoluteUri.IndexOf("glsoc.") > 0)
{
if (id == "EN")
{
return View("/Views/Register2019/Index.cshtml");
}
else
{
return View("/Views/Register2019/IndexCn.cshtml");
}
}
//return RedirectToAction("Index", "NewVisitor");
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}
@@ -0,0 +1,483 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Chruch.Net.Models.IceBreak;
using Church.Net.DAL.EF;
using Church.Net.Entity;
using Church.Net.Utility;
using Microsoft.Ajax.Utilities;
namespace Chruch.Net.Controllers
{
public class IceBreakController : _BaseController
{
private ChurchNetContext db = new ChurchNetContext();
// GET: IceBreak
public ActionResult Index()
{
return View();
}
public ActionResult Host()
{
return View();
}
public ActionResult Hi(string id, GamePlayer model)
{
model = new GamePlayer();
model.TempGameRoomId = PlayerInfo.TempGameRoomId;
return View(model);
}
[HttpPost]
public ActionResult Hi(GamePlayer model)
{
if (ModelState.IsValid)
{
PlayerInfo = model;
PlayerInfo.Id = Church.Net.Utility.Format.Get33BaseGuid();
if (PlayerInfo.TempGameRoomId.IsNullOrWhiteSpace())
{
return RedirectToAction("WhoIsSpyPlay");
}
else
{
return RedirectToAction("WhoIsSpyPlayJoin", new { id = PlayerInfo.TempGameRoomId });
}
}
return View(model);
}
#region WhoIsSpy
#region PublicProperty
public List<Models.IceBreak.GameRoom> GameRooms
{
get
{
if (HttpContext.Application["GameRooms"] == null)
{
HttpContext.Application["GameRooms"] = new List<GameRoom>();
}
return (List<GameRoom>)HttpContext.Application["GameRooms"];
}
set => HttpContext.Application["GameRooms"] = value;
}
public string GameRoomId
{
get
{
if (HttpContext.Session["GameRoomId"] == null)
{
HttpContext.Session["GameRoomId"] = "";
}
return (string)HttpContext.Session["GameRoomId"];
}
set => HttpContext.Session["GameRoomId"] = value;
}
public GamePlayer PlayerInfo
{
get
{
if (HttpContext.Session["PlayerInfo"] == null)
{
HttpContext.Session["PlayerInfo"] = new GamePlayer();
}
return (GamePlayer)HttpContext.Session["PlayerInfo"];
}
set => HttpContext.Session["PlayerInfo"] = value;
}
#endregion
#region Console
// GET: IceBreak
public ActionResult WhoIsSpy(string id)
{
if (id.IsNullOrWhiteSpace() && GameRoomId.IsNullOrWhiteSpace())
{
return View("WhoIsSpy", new Models.IceBreak.WhoIsSpyGameRoom());
}
if (GameRooms.Any(g => g.Id == id))
{
GameRoomId = id;
}
else if(!id.IsNullOrWhiteSpace())
{
Models.IceBreak.WhoIsSpyGameRoom model = new WhoIsSpyGameRoom();
if (model.Id.IsNullOrWhiteSpace())
{
Random r = new Random();
model.Id = r.Next(1, 99).ToString("00");
}
model.Id = GameRoomId;
model.SpyAmount = 2;
model.Status = WhoIsSpyProcess.WaitForPlayer;
GameRooms.Add(model);
GameRoomId = model.Id;
}
var gameRoom = GameRooms.FirstOrDefault(room => room.Id == GameRoomId);
return View("WhoIsSpy", (WhoIsSpyGameRoom)gameRoom);
}
[HttpPost]
public ActionResult WhoIsSpyCreate(string id)
{
if (GameRooms.Any(g => g.Id == id))
{
GameRoomId = id;
}
else
{
Models.IceBreak.WhoIsSpyGameRoom model = new WhoIsSpyGameRoom();
model.Id = id;
if (model.Id.IsNullOrWhiteSpace())
{
Random r = new Random();
model.Id = r.Next(1, 99).ToString("00");
}
model.SpyAmount = 2;
model.Status = WhoIsSpyProcess.WaitForPlayer;
GameRooms.Add(model);
GameRoomId = model.Id;
}
return RedirectToAction("WhoIsSpy");
}
[HttpPost]
public ActionResult WhoIsSpyStart(Models.IceBreak.WhoIsSpyGameRoom model)
{
Random r = new Random();
WhoIsSpyGameRoom gameRoom = (WhoIsSpyGameRoom)GameRooms.FirstOrDefault(room => room.Id == GameRoomId);
if (gameRoom == null)
{
return RedirectToAction("WhoIsSpy");
}
gameRoom.SpyAmount = model.SpyAmount;
gameRoom.EmptyAmount = model.EmptyAmount;
if ((gameRoom.TotalPlayer -1) < gameRoom.SpyAmount*2)
{
ShowScriptMsg("臥底人數太多了!", MessageType.Errors);
return View("WhoIsSpy", gameRoom);
}
if (gameRoom.SpyAmount < gameRoom.EmptyAmount * 2)
{
ShowScriptMsg("空白人數太多了!", MessageType.Errors);
return View("WhoIsSpy", gameRoom);
}
//取題目
int totalAnswer = db.WhoIsSpy.Count(a=> !gameRoom.PlayedAnswerId.Contains(a.Id));
if (totalAnswer==0)
{
gameRoom.PlayedAnswerId=new List<int>();
}
WhoIsSpy answer;
answer = db.WhoIsSpy.Where(a => !gameRoom.PlayedAnswerId.Contains(a.Id)).OrderBy(a => a.Id).Skip(r.Next(0, totalAnswer - 1)).First();
gameRoom.PlayedAnswerId.Add(answer.Id);
bool reverseAnswer = r.Next(0, 100) > 50;
gameRoom.Answer = reverseAnswer
? new WhoIsSpyAnswer(answer.Answer1Cht, answer.Answer1Chs, answer.Answer1En, answer.Answer1Image)
: new WhoIsSpyAnswer(answer.Answer2Cht, answer.Answer2Chs, answer.Answer2En, answer.Answer2Image);
gameRoom.SpysAnswer = !reverseAnswer
? new WhoIsSpyAnswer(answer.Answer1Cht, answer.Answer1Chs, answer.Answer1En, answer.Answer1Image)
: new WhoIsSpyAnswer(answer.Answer2Cht, answer.Answer2Chs, answer.Answer2En, answer.Answer2Image);
//Set Player
foreach (var whoIsSpyPlayer in gameRoom.Players)
{
whoIsSpyPlayer.VoteTo = new List<string>();
whoIsSpyPlayer.IsDead = false;
whoIsSpyPlayer.GameStatus = WhoIsSpyProcess.Started;
whoIsSpyPlayer.Answer = gameRoom.Answer;
whoIsSpyPlayer.IsSpy = false;
}
//Set Spy
WhoIsSpyPlayer spy;
for (int g = 1; g <= gameRoom.SpyAmount; g++)
{
do
{
spy = gameRoom.Players[r.Next(0, gameRoom.TotalPlayer - 1)];
} while (spy.IsSpy);
spy.IsSpy = true;
spy.Answer = g <= gameRoom.EmptyAmount ? new WhoIsSpyAnswer() : gameRoom.SpysAnswer;
}
//Start Order
do
{
gameRoom.StartIndex = r.Next(0, gameRoom.TotalPlayer - 1);
} while (gameRoom.Players[gameRoom.StartIndex].IsDead);
gameRoom.Status = WhoIsSpyProcess.Started;
return RedirectToAction("WhoIsSpy");
}
public ActionResult WhoIsSpyClose()
{
GameRooms.RemoveAll(room => room.Id == GameRoomId);
GameRoomId = "";
return RedirectToAction("WhoIsSpy");
}
[HttpPost]
public ActionResult WhoIsSpyNext()
{
var gameRoom = (WhoIsSpyGameRoom)GameRooms.FirstOrDefault(room => room.Id == GameRoomId);
if (gameRoom==null)
{
return RedirectToAction("WhoIsSpy");
}
switch (gameRoom.Status)
{
case WhoIsSpyProcess.WaitForPlayer:
break;
case WhoIsSpyProcess.Started:
//開始
gameRoom.Status = WhoIsSpyProcess.Votting;
gameRoom.VoteAmount = gameRoom.Players.Count(p => p.IsSpy && !p.IsDead);
gameRoom.Players.Shuffle();
foreach (var whoIsSpyPlayer in gameRoom.Players)
{
whoIsSpyPlayer.VoteTo = new List<string>();
whoIsSpyPlayer.ReceviedVotes = 0;
whoIsSpyPlayer.VoteAmount = gameRoom.Players.Count(p => p.IsSpy && !p.IsDead);
whoIsSpyPlayer.VoteOption=new List<WhoIsSpyVoteOption>(gameRoom.Players.Where(p=>p.Id!=whoIsSpyPlayer.Id&&!p.IsDead).Select(p=>new WhoIsSpyVoteOption(p.Id,p.Name)));
}
break;
case WhoIsSpyProcess.Votting:
foreach (var whoIsSpyPlayer in gameRoom.Players.OrderByDescending(p=>p.ReceviedVotes).Take(gameRoom.Players.Count(p => p.IsSpy && !p.IsDead)))
{
whoIsSpyPlayer.IsDead = true;
}
gameRoom.Status = WhoIsSpyProcess.DisplayResult;
break;
case WhoIsSpyProcess.DisplayResult:
if (gameRoom.Players.Count(p => p.IsSpy && !p.IsDead)>= gameRoom.Players.Count(p => !p.IsSpy && !p.IsDead) || gameRoom.Players.Count(p => p.IsSpy && !p.IsDead)==0)
{
gameRoom.Status = WhoIsSpyProcess.End;
}
else
{
gameRoom.Status = WhoIsSpyProcess.Started;
}
break;
case WhoIsSpyProcess.End:
gameRoom.Status = WhoIsSpyProcess.WaitForPlayer;
break;
default:
throw new ArgumentOutOfRangeException();
}
foreach (var whoIsSpyPlayer in gameRoom.Players)
{
whoIsSpyPlayer.GameStatus = gameRoom.Status;
}
return RedirectToAction("WhoIsSpy");
}
public PartialViewResult WhoIsSpyGetPlayerList()
{
var gameRoom = GameRooms.FirstOrDefault(room => room.Id == GameRoomId);
if (gameRoom == null)
{
return null;
}
return PartialView("~/Views/IceBreak/WhoIsSpyPlayerList.cshtml", gameRoom.Players.Select(p => p.Name).ToList());
}
public PartialViewResult WhoIsSpyGetPlayerVoteList()
{
var gameRoom = GameRooms.FirstOrDefault(room => room.Id == GameRoomId);
if (gameRoom == null)
{
return null;
}
return PartialView("~/Views/IceBreak/WhoIsSpyPlayerList.cshtml", gameRoom?.Players.Where(p => !p.IsDead && p.VoteTo.Count == 0).Select(p => p.Name).ToList());
}
#endregion
#region WhoIsSpyPlayer
public ActionResult WhoIsSpyPlay()
{
if (PlayerInfo.Name.IsNullOrWhiteSpace())
{
return RedirectToAction("Hi");
}
var gameRoom = GameRooms.FirstOrDefault(room => room.Id == GameRoomId);
if (gameRoom != null && gameRoom.Players.Exists(p => p.Id == PlayerInfo.Id))
{
return View(gameRoom.Players.FirstOrDefault(p => p.Id == PlayerInfo.Id));
}
return View();
}
public ActionResult WhoIsSpyPlayJoin(string id)
{
var gameRoom = (WhoIsSpyGameRoom)GameRooms.FirstOrDefault(room => room.Id == id);
if (gameRoom == null)
{
ShowScriptMsg("遊戲室不存在,請重新輸入遊戲室編號", MessageType.Warring);
return RedirectToAction("WhoIsSpyPlay");
}
if (PlayerInfo.Name.IsNullOrWhiteSpace())
{
PlayerInfo.TempGameRoomId = id;
return RedirectToAction("Hi");
}
WhoIsSpyPlayer model;
if (!gameRoom.Players.Exists(p => p.Id == PlayerInfo.Id))
{
model = new WhoIsSpyPlayer()
{
Id = PlayerInfo.Id,
Name = PlayerInfo.Name,
RoomId = id,
GameStatus = gameRoom.Status
};
gameRoom.Players.Add(model);
GameRoomId = gameRoom.Id;
}
return RedirectToAction("WhoIsSpyPlay");
}
public ActionResult WhoIsSpyPlayVote(WhoIsSpyPlayer model)
{
try
{
var gameRoom = GameRooms.FirstOrDefault(room => room.Id == GameRoomId);
var player = gameRoom.Players.Find(p => p.Id == model.Id);
player.GameStatus = WhoIsSpyProcess.DisplayResult;
player.VoteTo = model.VoteTo;
foreach (var s in model.VoteTo)
{
gameRoom.Players.Find(p => p.Id == s).ReceviedVotes += 1;
}
}
catch (Exception e)
{
}
return RedirectToAction("WhoIsSpyPlay");
}
public ActionResult WhoIsSpyExit()
{
var gameRoom = GameRooms.FirstOrDefault(room => room.Id == GameRoomId);
gameRoom.Players.RemoveAll(p => p.Id == PlayerInfo.Id);
PlayerInfo.TempGameRoomId = "";
GameRoomId = "";
return RedirectToAction("WhoIsSpyPlay");
}
public JsonResult CheckGameRoomStatu(string id)
{
var gameRoom = GameRooms.FirstOrDefault(room => room.Id == id);
if (gameRoom==null)
{
return Json(WhoIsSpyProcess.Closed);
}
var player = gameRoom.Players.Find(p => p.Id == PlayerInfo.Id);
return Json(player.GameStatus);
}
#endregion
#endregion
}
}
+389
View File
@@ -0,0 +1,389 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using Chruch.Net.Models;
namespace Chruch.Net.Controllers
{
[Authorize]
public class ManageController : Controller
{
private ApplicationSignInManager _signInManager;
private ApplicationUserManager _userManager;
public ManageController()
{
}
public ManageController(ApplicationUserManager userManager, ApplicationSignInManager signInManager)
{
UserManager = userManager;
SignInManager = signInManager;
}
public ApplicationSignInManager SignInManager
{
get
{
return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
}
private set
{
_signInManager = value;
}
}
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
//
// GET: /Manage/Index
public async Task<ActionResult> Index(ManageMessageId? message)
{
ViewBag.StatusMessage =
message == ManageMessageId.ChangePasswordSuccess ? "已變更您的密碼。"
: message == ManageMessageId.SetPasswordSuccess ? "已設定您的密碼。"
: message == ManageMessageId.SetTwoFactorSuccess ? "已設定您的雙因素驗證。"
: message == ManageMessageId.Error ? "發生錯誤。"
: message == ManageMessageId.AddPhoneSuccess ? "已新增您的電話號碼。"
: message == ManageMessageId.RemovePhoneSuccess ? "已移除您的電話號碼。"
: "";
var userId = User.Identity.GetUserId();
var model = new IndexViewModel
{
HasPassword = HasPassword(),
PhoneNumber = await UserManager.GetPhoneNumberAsync(userId),
TwoFactor = await UserManager.GetTwoFactorEnabledAsync(userId),
Logins = await UserManager.GetLoginsAsync(userId),
BrowserRemembered = await AuthenticationManager.TwoFactorBrowserRememberedAsync(userId)
};
return View(model);
}
//
// POST: /Manage/RemoveLogin
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> RemoveLogin(string loginProvider, string providerKey)
{
ManageMessageId? message;
var result = await UserManager.RemoveLoginAsync(User.Identity.GetUserId(), new UserLoginInfo(loginProvider, providerKey));
if (result.Succeeded)
{
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user != null)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
message = ManageMessageId.RemoveLoginSuccess;
}
else
{
message = ManageMessageId.Error;
}
return RedirectToAction("ManageLogins", new { Message = message });
}
//
// GET: /Manage/AddPhoneNumber
public ActionResult AddPhoneNumber()
{
return View();
}
//
// POST: /Manage/AddPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> AddPhoneNumber(AddPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// 產生並傳送 Token
var code = await UserManager.GenerateChangePhoneNumberTokenAsync(User.Identity.GetUserId(), model.Number);
if (UserManager.SmsService != null)
{
var message = new IdentityMessage
{
Destination = model.Number,
Body = "您的安全碼為: " + code
};
await UserManager.SmsService.SendAsync(message);
}
return RedirectToAction("VerifyPhoneNumber", new { PhoneNumber = model.Number });
}
//
// POST: /Manage/EnableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> EnableTwoFactorAuthentication()
{
await UserManager.SetTwoFactorEnabledAsync(User.Identity.GetUserId(), true);
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user != null)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return RedirectToAction("Index", "Manage");
}
//
// POST: /Manage/DisableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DisableTwoFactorAuthentication()
{
await UserManager.SetTwoFactorEnabledAsync(User.Identity.GetUserId(), false);
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user != null)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return RedirectToAction("Index", "Manage");
}
//
// GET: /Manage/VerifyPhoneNumber
public async Task<ActionResult> VerifyPhoneNumber(string phoneNumber)
{
var code = await UserManager.GenerateChangePhoneNumberTokenAsync(User.Identity.GetUserId(), phoneNumber);
// 透過 SMS 提供者傳送 SMS,以驗證電話號碼
return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber });
}
//
// POST: /Manage/VerifyPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var result = await UserManager.ChangePhoneNumberAsync(User.Identity.GetUserId(), model.PhoneNumber, model.Code);
if (result.Succeeded)
{
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user != null)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return RedirectToAction("Index", new { Message = ManageMessageId.AddPhoneSuccess });
}
// 如果執行到這裡,發生某項失敗,則重新顯示表單
ModelState.AddModelError("", "無法驗證號碼");
return View(model);
}
//
// POST: /Manage/RemovePhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> RemovePhoneNumber()
{
var result = await UserManager.SetPhoneNumberAsync(User.Identity.GetUserId(), null);
if (!result.Succeeded)
{
return RedirectToAction("Index", new { Message = ManageMessageId.Error });
}
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user != null)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return RedirectToAction("Index", new { Message = ManageMessageId.RemovePhoneSuccess });
}
//
// GET: /Manage/ChangePassword
public ActionResult ChangePassword()
{
return View();
}
//
// POST: /Manage/ChangePassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ChangePassword(ChangePasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword);
if (result.Succeeded)
{
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user != null)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return RedirectToAction("Index", new { Message = ManageMessageId.ChangePasswordSuccess });
}
AddErrors(result);
return View(model);
}
//
// GET: /Manage/SetPassword
public ActionResult SetPassword()
{
return View();
}
//
// POST: /Manage/SetPassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> SetPassword(SetPasswordViewModel model)
{
if (ModelState.IsValid)
{
var result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword);
if (result.Succeeded)
{
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user != null)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return RedirectToAction("Index", new { Message = ManageMessageId.SetPasswordSuccess });
}
AddErrors(result);
}
// 如果執行到這裡,發生某項失敗,則重新顯示表單
return View(model);
}
//
// GET: /Manage/ManageLogins
public async Task<ActionResult> ManageLogins(ManageMessageId? message)
{
ViewBag.StatusMessage =
message == ManageMessageId.RemoveLoginSuccess ? "已移除外部登入。"
: message == ManageMessageId.Error ? "發生錯誤。"
: "";
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user == null)
{
return View("Error");
}
var userLogins = await UserManager.GetLoginsAsync(User.Identity.GetUserId());
var otherLogins = AuthenticationManager.GetExternalAuthenticationTypes().Where(auth => userLogins.All(ul => auth.AuthenticationType != ul.LoginProvider)).ToList();
ViewBag.ShowRemoveButton = user.PasswordHash != null || userLogins.Count > 1;
return View(new ManageLoginsViewModel
{
CurrentLogins = userLogins,
OtherLogins = otherLogins
});
}
//
// POST: /Manage/LinkLogin
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LinkLogin(string provider)
{
// 要求重新導向至外部登入提供者,以連結目前使用者的登入
return new AccountController.ChallengeResult(provider, Url.Action("LinkLoginCallback", "Manage"), User.Identity.GetUserId());
}
//
// GET: /Manage/LinkLoginCallback
public async Task<ActionResult> LinkLoginCallback()
{
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(XsrfKey, User.Identity.GetUserId());
if (loginInfo == null)
{
return RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error });
}
var result = await UserManager.AddLoginAsync(User.Identity.GetUserId(), loginInfo.Login);
return result.Succeeded ? RedirectToAction("ManageLogins") : RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error });
}
protected override void Dispose(bool disposing)
{
if (disposing && _userManager != null)
{
_userManager.Dispose();
_userManager = null;
}
base.Dispose(disposing);
}
#region Helper
// 新增外部登入時用來當做 XSRF 保護
private const string XsrfKey = "XsrfId";
private IAuthenticationManager AuthenticationManager
{
get
{
return HttpContext.GetOwinContext().Authentication;
}
}
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error);
}
}
private bool HasPassword()
{
var user = UserManager.FindById(User.Identity.GetUserId());
if (user != null)
{
return user.PasswordHash != null;
}
return false;
}
private bool HasPhoneNumber()
{
var user = UserManager.FindById(User.Identity.GetUserId());
if (user != null)
{
return user.PhoneNumber != null;
}
return false;
}
public enum ManageMessageId
{
AddPhoneSuccess,
ChangePasswordSuccess,
SetTwoFactorSuccess,
SetPasswordSuccess,
RemoveLoginSuccess,
RemovePhoneSuccess,
Error
}
#endregion
}
}
@@ -0,0 +1,114 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Chruch.Net.Models;
using Church.Net.DAL.EF;
using Church.Net.Entity;
namespace Chruch.Net.Controllers
{
public class NewVisitorController : _BaseController
{
private ChurchNetContext db = new ChurchNetContext();
// GET: NewVisitor
public ActionResult Index(Church.Net.Entity.NewVisitor model)
{
ViewBag.ReligionId = new SelectList(db.Religions, "ReligionId", "Name");
model.Gender = Enumeration.Gender.Male;
return View(model);
}
public ActionResult Registration(Church.Net.Entity.NewVisitor model)
{
if (model != null)
{
model.Id = Church.Net.Utility.Format.Get33BaseGuid();
model.VisitingDate=DateTime.Now;
ModelState.Clear();
TryValidateModel(model);
//ValidateModel(dNSServer);
}
if (ModelState.IsValid)
{
var file = HttpContext.Request.Files["AttachFile"];
bool hasFile = file != null && !string.IsNullOrEmpty(file.FileName);
string filePath = Server.MapPath("~/NewVisitorsPics/");
//string newFileName = hasFile ? $"{model.Id}{file.FileName.Substring(file.FileName.LastIndexOf("."))}" : "";
string newFileName = hasFile ? $"{model.Id}.jpg" : "";
Directory.CreateDirectory(filePath);
try
{
var logic = new Church.Net.BLL.NewVisitorBLL(this.ConnString);
logic.Add(model);
if (hasFile)
{
Church.Net.Utility.Image.SaveThumbnail(new Bitmap(file.InputStream),
filePath + "\\" + newFileName, 1920, 1080);
//file.SaveAs(filePath + "\\" + newFileName);
}
ShowScriptMsg("一次歡迎,永遠歡迎!",MessageType.Success);
}
catch (Exception e)
{
ShowMsgByEx(e);
}
}
return RedirectToAction("Index");
// return View(model);
}
[HttpGet]
public ActionResult Slider()
{
NewVisitorViewClass model = new NewVisitorViewClass()
{
BeginDate = DateTime.Today,
EndDate = DateTime.Today
};
return View("ImageTextSliderChooseDate", model);
}
[HttpPost]
public ActionResult Slider(NewVisitorViewClass model)
{
DateTime beginDate = DateTime.Today;
DateTime endDate = DateTime.Today.AddDays(1);
beginDate = model.BeginDate;
endDate = model.EndDate.AddDays(1);
var list = new Church.Net.BLL.NewVisitorBLL(this.ConnString).GetAll(visitor =>
visitor.VisitingDate >= beginDate && visitor.VisitingDate <= endDate);
return View(list);
}
public ActionResult Today()
{
DateTime beginDate = DateTime.Today;
DateTime endDate = DateTime.Today.AddDays(1);
var list = new Church.Net.BLL.NewVisitorBLL(this.ConnString).GetAll(visitor =>
visitor.VisitingDate >= beginDate && visitor.VisitingDate <= endDate);
return View("Slider", list);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
@@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Chruch.Net.Controllers
{
public class Register2019Controller : Controller
{
// GET: Register2018
public ActionResult Index(string id)
{
if (id=="EN")
{
return View();
}
else
{
return View("IndexCn");
}
}
}
}
+196
View File
@@ -0,0 +1,196 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
namespace Chruch.Net.Controllers
{
public class _BaseController : Controller
{
#region
protected enum MessageType
{
Warring,
Done,
Success,
Errors,
None
}
protected enum CRUDType
{
None,
Processing,
Create,
Update,
Delete
}
protected enum Active
{
Processing,
Reading,
Adding,
Editing
}
#endregion
private string ResultMessage
{
get
{
if (System.Web.HttpContext.Current.Session["ResultMessage"] != null)
{
return System.Web.HttpContext.Current.Session["ResultMessage"].ToString();
}
return "";
}
set
{
System.Web.HttpContext.Current.Session["ResultMessage"] = value;
}
}
protected string ConnString
{
get
{
if (System.Web.HttpContext.Current.Session["ConnString"] != null)
{
return System.Web.HttpContext.Current.Session["ConnString"].ToString();
}
ConnString= System.Configuration.ConfigurationManager.ConnectionStrings["entityFramework"].ConnectionString;
return ConnString;
}
set
{
System.Web.HttpContext.Current.Session["ConnString"] = value;
}
}
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (!filterContext.HttpContext.Request.IsAjaxRequest())
{
var response = filterContext.HttpContext.Response;
if (response.ContentType == "text/html" &&
!(filterContext.Result is RedirectToRouteResult) &&
!(filterContext.Result is RedirectResult))
{
if (!string.IsNullOrEmpty(ResultMessage))
{
ViewBag.StartScript = ResultMessage;
ResultMessage = "";
}
}
}
}
#region MessageBox
protected void ShowScriptMsg(string description, MessageType MsType = MessageType.None)
{
ShowScriptMsg(description, "", MsType);
}
protected void ShowScriptMsg(string descritpion, string title, MessageType MsType = MessageType.None)
{
StringBuilder stringBuilder = new StringBuilder();
title = title.Replace(Environment.NewLine, "<br>").Replace("'", "\"");
descritpion = descritpion.Replace(Environment.NewLine, "<br>").Replace("'", "\"");
stringBuilder.AppendLine(" swal({ ");
if (!string.IsNullOrWhiteSpace(descritpion))
{
stringBuilder.AppendLine($" html: '{descritpion}', ");
}
switch (MsType)
{
case MessageType.Success:
stringBuilder.AppendLine($" title: '{title} {LanHelper.GetText("Success")}', ");
stringBuilder.AppendLine(" type: \"success\" ");
break;
case MessageType.Warring:
stringBuilder.AppendLine($" title: '{title} {LanHelper.GetText("Warning")}', ");
stringBuilder.AppendLine(" type: \"warning\" ");
break;
case MessageType.Errors:
stringBuilder.AppendLine($" title: '{title} {LanHelper.GetText("Fail")}', ");
stringBuilder.AppendLine(" type: \"error\" ");
break;
case MessageType.Done:
stringBuilder.AppendLine($" title: '{title} {LanHelper.GetText("Done")}', ");
stringBuilder.AppendLine(" type: \"success\" ");
break;
default:
break;
}
stringBuilder.AppendLine("}); ");
ResultMessage = stringBuilder.ToString();
}
protected void ShowScriptMsgAndRedirect(string descritpion, string url, MessageType MsType = MessageType.None)
{
ShowScriptMsgAndRedirect(descritpion, "", url, MsType);
}
protected void ShowScriptMsgAndRedirect(string descritpion, string title, string url, MessageType MsType = MessageType.None)
{
StringBuilder stringBuilder = new StringBuilder();
title = title.Replace(Environment.NewLine, "<br>").Replace("'", "\"");
descritpion = descritpion.Replace(Environment.NewLine, "<br>").Replace("'", "\"");
stringBuilder.AppendLine(" swal({ ");
if (!string.IsNullOrWhiteSpace(descritpion))
{
stringBuilder.AppendLine($" html: '{descritpion}', ");
}
switch (MsType)
{
case MessageType.Success:
stringBuilder.AppendLine($" title: \"{title} {LanHelper.GetText("Success")}\", ");
stringBuilder.AppendLine(" type: \"success\" ");
break;
case MessageType.Warring:
stringBuilder.AppendLine($" title: \"{title} {LanHelper.GetText("Warning")}\", ");
stringBuilder.AppendLine(" type: \"warning\" ");
break;
case MessageType.Errors:
stringBuilder.AppendLine($" title: \"{title} {LanHelper.GetText("Fail")}\", ");
stringBuilder.AppendLine(" type: \"error\" ");
break;
case MessageType.Done:
stringBuilder.AppendLine($" title: \"{title} {LanHelper.GetText("Done")}\", ");
stringBuilder.AppendLine(" type: \"success\" ");
break;
default:
break;
}
stringBuilder.Append("}).then(function () {");
stringBuilder.Append("$.ShowP;");
stringBuilder.Append($"window.location.href = '{url}';");
stringBuilder.Append("});");
ResultMessage = stringBuilder.ToString();
}
protected void ShowMsgByEx(Exception ex)
{
if (ex.GetType() == typeof(ArgumentException))
{
ShowScriptMsg(LanHelper.GetText(ex.Message), "", MessageType.Warring);
}
else
{
ShowScriptMsg(ex.Message, "", MessageType.Errors);
}
}
#endregion
}
}