public static HttpResponseMessage BuildExceptionJsonResponse(HttpStatusCode code, Exception ex) { string error = ExceptionHelper.GetMessage(ex); ServerLogger.Error(error); return(BuildJsonResponse(code, null, MessageType.Error, ex.Message)); }
/// <summary> /// Initializes the database or creates a new one if it does not exists already. /// </summary> internal bool Load() { try { using (AuraContext database = new AuraContext()) { bool cine = database.Database.CreateIfNotExists(); if (cine) { ServerLogger.Database("Creating database..."); } else { ServerLogger.Database("Preparing database..."); } return(true); } } catch (Exception) { ServerLogger.Error("Failed to load the database!"); return(false); } }
/// <summary> /// Removes a <see cref="ConnectionCore"/> from the <see cref="Chatroom"/>. /// </summary> public void Leave(ConnectionCore connection) { BroadcastChatMessage(connection, BroadcastType.UserLeftChatRoom); if (ChatroomUsers.Contains(connection)) { ChatroomUsers.Remove(connection); ServerLogger.Chatroom(string.Format("{1}({0}) has disconnected from a chatroom.", connection.ID, connection.ConnectionData.Username)); } else { ServerLogger.Error(string.Format("{1}({0}) cannot disconnect from a chatroom.", connection.ID, connection.ConnectionData.Username)); } if (Private) { connection.SendMessage(new RemovePrivateRoomComposer(ID)); } if (ChatroomUsers.Count == 0) { ServerLogger.Warning(string.Format("Chatroom {0} is empty.", ID.ToString())); connection.ServerManager.ChatroomManager.RemoveChatroom(ID); ServerLogger.Chatroom(string.Format("Chatroom {0} has been deleted.", ID.ToString())); } }
public virtual ActionResult AdminLogin(LoginViewModel model, string returnUrl) { try { if (string.IsNullOrEmpty(model.UserName) || string.IsNullOrEmpty(model.Password)) { ModelState.AddModelError("", "请输入用户名或密码。"); return(View(model)); } string password = EncrypManager.Encode(model.Password); SystemUserDataInfo user = SystemUserService.GetSystemUserDataInfoByLogin(model.UserName, password); if (user != null) { FormsAuthentication.SetAuthCookie(user.UserName, false); CookieUtil.CreateCookie(user.ID, CookieName.IMAdminCurrentUser); return(RedirectToAction("Index", "Admin")); } else { ModelState.AddModelError("", "用户名或密码错误"); } } catch (Exception ex) { ServerLogger.Error("Failed to log in."); ModelState.AddModelError("", ex.Message); return(View(model)); } return(View(model)); }
public static string GetCookie(string CookieName) { string result = "0"; try { if (System.Web.HttpContext.Current.Request.Cookies[CookieName] != null) { System.Web.HttpCookie IMCookie = System.Web.HttpContext.Current.Request.Cookies[CookieName]; // IMCookie.Domain = ""; DateTime endDate = DateTime.Parse(EncrypManager.Decode(IMCookie["e"])); // DateTime endDate = DateTime.Parse(IMCookie["e"]); if (endDate > DateTime.Now) { RemoveCookie(CookieName); System.Web.HttpCookie NewDiyCookie = new System.Web.HttpCookie(CookieName); // NewDiyCookie.Domain = ""; NewDiyCookie.Values.Add("obj", IMCookie["obj"]); NewDiyCookie.Values.Add("e", EncrypManager.Encode(DateTime.Now.AddMinutes(LoginExpirationIntervalMinutes).ToString()));//存储到期时间 System.Web.HttpContext.Current.Response.AppendCookie(NewDiyCookie); result = EncrypManager.Decode(IMCookie["obj"]); // result = IMCookie["obj"]; } } } catch (Exception ex) { ServerLogger.Error(ex.Message); } return(result); }
public static HttpResponseMessage ErrortoJson(Object obj, string ErrorMessage) { HttpResponseMessage result = null; try { String str = ""; if (obj != null) { if (obj is String || obj is Char) { str = obj.ToString(); } else { str = JsonConvert.SerializeObject(obj); } } if (!string.IsNullOrEmpty(ErrorMessage)) { ServerLogger.Error(ErrorMessage); } result = new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError, Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") }; } catch (Exception ex) { result = new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError }; ServerLogger.Error(ex.Message); } return(result); }
public virtual ActionResult AdminLogin(string returnUrl) { SystemUserService.CreateAdminUser(); try { ViewBag.ReturnUrl = returnUrl; } catch (Exception ex) { ServerLogger.Error(ex.Message); } return(View()); }
public override void OnException(HttpActionExecutedContext actionExecutedContext) { StringBuilder lobjLogBuilder = new StringBuilder(); lobjLogBuilder.Append("Error occurred in WebApi."); lobjLogBuilder.Append(string.Format("Controller-{0};", actionExecutedContext.ActionContext.ControllerContext.RouteData.Values["controller"])); lobjLogBuilder.Append(string.Format("ExceptionMessage-{0};", actionExecutedContext.Exception.Message)); // lobjLogBuilder.Append(string.Format("Action-{0};", actionExecutedContext.ActionContext.ControllerContext.RouteData.Values["action"])); //lobjLogBuilder.Append(string.Format("Id-{0};", actionExecutedContext.ActionContext.ControllerContext.RouteData.Values["id"])); ServerLogger.Error(lobjLogBuilder.ToString()); HttpStatusCode code = HttpStatusCode.InternalServerError; // Can provide mode exception if (actionExecutedContext.Exception is MissingDomainObjectException) { code = HttpStatusCode.NotFound; } else if (actionExecutedContext.Exception is DuplicatedDomainObjectException) { code = HttpStatusCode.Conflict; } else if (actionExecutedContext.Exception is MissingRequiredFieldException) { code = HttpStatusCode.NotAcceptable; } else if (actionExecutedContext.Exception is MissingFileObjectException) { code = HttpStatusCode.NotFound; } else if (actionExecutedContext.Exception is ArgumentNullException) { code = HttpStatusCode.BadRequest; } else if (actionExecutedContext.Exception is NotImplementedException) { code = HttpStatusCode.NotImplemented; } else if (actionExecutedContext.Exception is UnauthorizedAccessException) { code = HttpStatusCode.Unauthorized; } actionExecutedContext.Response = ResultJson.BuildExceptionJsonResponse(code, actionExecutedContext.Exception); //base.OnException(actionExecutedContext); }
public static void CreateCookie(object obj, string CookieName) { try { RemoveCookie(CookieName); DateTime NowDate = DateTime.Now; System.Web.HttpCookie IMCookie = new System.Web.HttpCookie(CookieName); //初使化并设置Cookie的名称 //IMCookie.Domain = ""; IMCookie.Values.Add("obj", EncrypManager.Encode(obj.ToString())); // IMCookie.Values.Add("e", EncrypManager.Encode(NowDate.AddMinutes(LoginExpirationIntervalMinutes).ToString())); //存储到期时间 System.Web.HttpContext.Current.Response.AppendCookie(IMCookie); } catch (Exception ex) { ServerLogger.Error(ex.Message); } }
public override void OnException(System.Web.Mvc.ExceptionContext filterContext) { StringBuilder lobjLogBuilder = new StringBuilder(); lobjLogBuilder.Append("Error occurred in controller action."); lobjLogBuilder.Append(string.Format("Controller-{0};", filterContext.RouteData.Values["controller"])); lobjLogBuilder.Append(string.Format("Action-{0};", filterContext.RouteData.Values["action"])); lobjLogBuilder.Append(string.Format("ExceptionMessage-{0};", filterContext.Exception.InnerException.Message)); ServerLogger.Error(lobjLogBuilder.ToString()); filterContext.ExceptionHandled = true; MessageModel msgModel = new MessageModel(MessageType.Error, ExceptionHelper.GetMessage(filterContext.Exception)); ResultDataBag lobjResult = new ResultDataBag(true, msgModel, null); filterContext.Result = new JsonResult() { Data = lobjResult, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; base.OnException(filterContext); }
/// <summary> /// Receives data asynchronously. /// </summary> private void ReceivedData(IAsyncResult ar) { try { int length = _Socket.EndReceive(ar); if (length <= 0) { Dispose(); return; } byte[] packet = new byte[length]; Array.Copy(_Buffer, packet, length); HandleData(packet); ServerLogger.Incoming(string.Format("Received data from {0} with data: {1}", ID, Encoding.UTF8.GetString(packet))); } catch (SocketException) { } catch (Exception e) { ServerLogger.Error(e.Message); } finally { BeginReceive(); } }
/// <summary> /// Accepts a connection. /// </summary> private void AcceptConnection(IAsyncResult ar) { try { Socket handler = Socket.EndAccept(ar); ConnectionCore connection = new ConnectionCore(LastClientID++, handler, this); Connections.TryAdd(connection.ID, connection); } catch (Exception e) { ServerLogger.Error(e.Message); } finally { if (Connected) { Socket.BeginAccept(AcceptConnection, null); } } }
/// <summary> /// Registers and adds a new client to the database. /// </summary> public States Register(string username, string password) { try { using (AuraContext database = new AuraContext()) { var user = database.Clients.FirstOrDefault(client => client.FullName == username); if (user != null) { try { database.Clients.Add(new Client() { FullName = username, Password = password }); database.SaveChanges(); return(States.RegisterCorrect); } catch (Exception e) { ServerLogger.Error(e); return(States.RegisterFailed); } } else { return(States.RegisterAlreadyTaken); } } } catch (Exception e) { ServerLogger.Error(e); return(States.RegisterFailed); } }
public static HttpResponseMessage ErrorToJson(Object obj, HttpStatusCode code, Exception exception) { HttpResponseMessage result = null; try { if (exception != null) { ServerLogger.Error(ExceptionHelper.GetMessage(exception)); } String str = ""; if (obj != null) { if (obj is String || obj is Char) { str = obj.ToString(); } else { str = JsonConvert.SerializeObject(obj); } } result = new HttpResponseMessage { StatusCode = code, Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") }; } catch (Exception ex) { string message = ExceptionHelper.GetMessage(ex); result = new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError, Content = new StringContent(message, Encoding.GetEncoding("UTF-8"), "application/json") }; ServerLogger.Error(ExceptionHelper.GetMessage(ex)); } return(result); }
public static HttpResponseMessage FailtoJson(string Message, HttpStatusCode HttpStatusCode) { HttpResponseMessage result = null; try { if (!string.IsNullOrEmpty(Message)) { ServerLogger.Info(Message); } result = new HttpResponseMessage { StatusCode = HttpStatusCode }; } catch (Exception ex) { result = new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError }; ServerLogger.Error(ex.Message); } return(result); }
private async void OnBuyOutfit([FromSource] Player player, int outfitId) { try { var licenseId = player.Identifiers["license"]; var user = Cache.Users.FirstOrDefault(x => x.LicenseId == licenseId); if (user != null) { var result = await BuyItemForUser(user.Id, Convert.ToInt32(player.Handle), outfitId, ShopItemType.OUTFIT, false); player.TriggerEvent("shop:prompt", result); } else { m_logger.Error($"[OnBuyOutfit] Could not find user {licenseId} in cache"); } } catch (Exception ex) { m_logger.Exception("OnBuyOutfit", ex); } }
public static HttpResponseMessage BuildJsonResponse(HttpStatusCode code, Object resultData, MessageType type, string message) { HttpResponseMessage result = null; try { bool hasMessage = !string.IsNullOrEmpty(message); MessageModel msgModel = hasMessage ? new MessageModel(type, message) : null; ResultDataBag lobjResult = new ResultDataBag(hasMessage, msgModel, resultData); String str = JsonConvert.SerializeObject(lobjResult); result = new HttpResponseMessage { StatusCode = code, Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") }; } catch (Exception ex) { result = new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError, Content = new StringContent(ex.Message, Encoding.GetEncoding("UTF-8"), "application/json") }; ServerLogger.Error(ex.Message); } return(result); }
public static HttpResponseMessage BuildNullJsonResponse(HttpStatusCode code, string Message) { ServerLogger.Error(Message); return(BuildJsonResponse(code, null, MessageType.None, Message)); }