private ApplicationError OnException(Exception ex, CorrelationId correlationId) { if (ex == null) throw new ArgumentNullException(nameof(ex)); var unwrapped = UnwrapTargetInvocation(ex); var reflectionTypeLoadException = unwrapped as ReflectionTypeLoadException; if (reflectionTypeLoadException?.LoaderExceptions != null) { foreach (var loadException in reflectionTypeLoadException.LoaderExceptions) { _logger.Error("Could not load types", loadException); } } var dbEntityValidationException = unwrapped as DbEntityValidationException; _logger.Error("Request throws exception", unwrapped); if (dbEntityValidationException?.EntityValidationErrors != null) { foreach (var dbEntityValidationResult in dbEntityValidationException.EntityValidationErrors) { foreach (var dbValidationError in dbEntityValidationResult.ValidationErrors) { _logger.Error( $"Entity {dbEntityValidationResult.Entry.Entity.GetType()} error property {dbValidationError.PropertyName}. Error message {dbValidationError.ErrorMessage}"); } } } var res = new ApplicationError { Exception = unwrapped, CorrelationId = correlationId, Code = GetStatusCodeByException(unwrapped), Message = unwrapped.Message, IncludeErrorDetails = _includeErrorDetailsResolver.IncludeErrorDetails ?? false }; return res; }
public static void WriteErrorLog(string message) { FileTarget target = new FileTarget(); target.Layout = "${longdate} ${logger} ${message}"; target.FileName = "${basedir}/Trace/ChemInformLog.txt"; target.KeepFileOpen = false; target.Encoding = "iso-8859-2"; AsyncTargetWrapper wrapper = new AsyncTargetWrapper(); wrapper.WrappedTarget = target; wrapper.QueueLimit = 5000; wrapper.OverflowAction = AsyncTargetWrapperOverflowAction.Discard; NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(wrapper, NLog.LogLevel.Trace); Logger logger = LogManager.GetLogger(GlobalVariables.ProjectName); logger.Trace(message); try { ApplicationError appError = new ApplicationError(); appError.UserName = GlobalVariables.UserName; appError.RoleName = GlobalVariables.RoleName; appError.AppError = message; CommonDB.SaveApplicationErrors(appError); } catch { } }
public static bool SaveApplicationErrors(ApplicationError appError) { bool blStatus = false; try { using (OracleConnection dbCon = ConnectionDB.GetOracleConnection()) { using (OracleCommand oraCmd = new OracleCommand()) { oraCmd.CommandText = "COMMON.INSERT_APP_ERRORS"; oraCmd.CommandType = CommandType.StoredProcedure; oraCmd.Connection = dbCon; oraCmd.Parameters.Add("PIC_USER_NAME", OracleDbType.Varchar2).Value = appError.UserName; oraCmd.Parameters.Add("PIC_ROLE_NAME ", OracleDbType.Varchar2).Value = appError.RoleName; oraCmd.Parameters.Add("PIC_APP_ERRORS ", OracleDbType.Varchar2).Value = appError.AppError; dbCon.Open(); oraCmd.ExecuteNonQuery(); dbCon.Close(); blStatus = true; } } } catch (Exception ex) { throw ex; } return(blStatus); }
public FormattedError Format(ApplicationError applicationError) { return(Format(new List <ApplicationError> { applicationError })); }
/// <summary>联系信息</summary> /// <returns></returns> public ActionResult Avatar() { // 所属应用信息 ApplicationInfo application = ViewBag.application = AppsContext.Instance.ApplicationService[APPLICATION_NAME]; IMemberInfo member = MembershipManagement.Instance.MemberService[this.Account.Id]; if (member == null) { ApplicationError.Write(404); } ViewBag.member = member; IAccountInfo account = MembershipManagement.Instance.AccountService[member.Account.Id]; string avatar_180x180 = string.Empty; if (string.IsNullOrEmpty(account.CertifiedAvatar)) { avatar_180x180 = MembershipConfigurationView.Instance.AvatarVirtualFolder + "default_180x180.png"; } else { avatar_180x180 = account.CertifiedAvatar.Replace("{avatar}", MembershipConfigurationView.Instance.AvatarVirtualFolder); } ViewBag.avatar_180x180 = avatar_180x180; return(View("/views/main/account/settings/avatar.cshtml")); }
public override void OnException(ExceptionContext context) { ApplicationError apiError = null; if (context.Exception is DomainErrorException) { apiError = ((DomainErrorException)context.Exception)?.Error; context.HttpContext.Response.StatusCode = (context.Exception as ApiException)?.StatusCode ?? ApiException.DefaultStatusCode; context.Exception = null; } else if (context.Exception is UnauthorizedAccessException) { apiError = new ApplicationError("unauthorized", "Unauthorized Access"); context.HttpContext.Response.StatusCode = StatusCodes.Status401Unauthorized; } else { #if !DEBUG var msg = "An unexpected error occurred."; string stack = null; #else var msg = context.Exception.GetBaseException().Message; var stack = context.Exception.StackTrace; #endif apiError = new ApplicationError("unexpected_error", msg) { Detail = stack }; context.HttpContext.Response.StatusCode = StatusCodes.Status500InternalServerError; } context.Result = new ObjectResult(apiError); base.OnException(context); }
public void StopToAccumulateScore() { if (!_isAccumulating) { return; } try { UpdateState(ScoreAccumulatingState.Stopping); _tokenSource.Cancel(false); _accumulateTask.Wait(); } catch (Exception ex) { ApplicationError.HandleUnexpectedError(ex); } finally { UpdateState(ScoreAccumulatingState.Stopped); _tokenSource.Dispose(); _tokenSource = null; _isAccumulating = false; } }
public DataTable SearchProductDetail(PropertyModels obj_BLL) { oDataTable = new DataTable(); try { oBuilder = new SqlConnectionStringBuilder(_connectionString); oConnection = new SqlConnection(oBuilder.ConnectionString); oDataAdapter = new SqlDataAdapter("Jobs_SearchProductDetail", oConnection); oDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure; oDataAdapter.SelectCommand.Parameters.AddWithValue("@FT_FromAmt", obj_BLL.FT_FromAmt); oDataAdapter.SelectCommand.Parameters.AddWithValue("@FT_ToAmt", obj_BLL.FT_ToAmt); oDataAdapter.SelectCommand.Parameters.AddWithValue("@FT_NAME", obj_BLL.FT_NAME); oDataAdapter.SelectCommand.Parameters.AddWithValue("@FT_PROD_CODE", obj_BLL.FT_PROD_CODE); oDataAdapter.SelectCommand.Parameters.AddWithValue("@FT_CAT_ID", obj_BLL.FT_CAT_ID); oDataAdapter.SelectCommand.Parameters.AddWithValue("@FT_SUBCAT_ID", obj_BLL.FT_SUBCAT_ID); using (oConnection) { oConnection.Open(); oDataAdapter.Fill(oDataTable); } } catch (Exception ex) { ApplicationError.LogErrors(ex); } return(oDataTable); }
public async Task LeaveRoom(LeaveRoomRequest request) { try { var ctx = new ValidationContext(request); var results = new List <ValidationResult>(); Validator.TryValidateObject(request, ctx, results, true); if (results.Count > 0) { throw new ApplicationError("[LeaveRoom]", 4); } var response = await _roomService.LeaveRoom(request); await Groups.RemoveFromGroupAsync(Context.ConnectionId, response.roomIdentifier.ToString()); await Clients.OthersInGroup(response.roomIdentifier.ToString()).BrLeftRoom(response); //user who left the room does not care anymore about the others. response.users = null; await Clients.Caller.LeftRoom(response); } catch (Exception e) { var errorResponse = ApplicationError.GetError <JoinRoomResponse>(e, "[LeaveRoom]"); _logger.LogError(e.Message); await Clients.Caller.JoinedRoom(errorResponse); } }
public async Task CreateUser(CreateUserRequest request) { try { request.socketId = Context.ConnectionId; var ctx = new ValidationContext(request); var results = new List <ValidationResult>(); Validator.TryValidateObject(request, ctx, results, true); if (results.Count > 0) { throw new ApplicationError("[CreateUser]", 4); } var response = await _userService.CreateUser(request); await Clients.Caller.UserCreated(response); } catch (Exception e) { var errorResponse = ApplicationError.GetError <CreateUserResponse>(e, "[CreateUser]"); _logger.LogError(e.Message); await Clients.Caller.UserCreated(errorResponse); } }
public async Task CreateMessage(CreateMessageRequest request) { try { var ctx = new ValidationContext(request); var results = new List <ValidationResult>(); Validator.TryValidateObject(request, ctx, results, true); if (results.Count > 0) { throw new ApplicationError("[CreateMessage]", 4); } var response = await _messageService.CreateMessage(request); await Clients.Caller.MessageCreated(response); await Clients.OthersInGroup(response.roomIdentifier.ToString()).BrMessageCreated(response); } catch (Exception e) { var errorResponse = ApplicationError.GetError <CreateMessageResponse>(e, "[CreateMessage]"); _logger.LogError(e.Message); await Clients.Caller.MessageCreated(errorResponse); } }
public async Task JoinRoom(JoinRoomRequest request) { try { var ctx = new ValidationContext(request); var results = new List <ValidationResult>(); Validator.TryValidateObject(request, ctx, results, true); if (results.Count > 0) { throw new ApplicationError("[JoinRoom]", 4); } var response = await _roomService.JoinRoom(request); await Groups.AddToGroupAsync(Context.ConnectionId, response.roomIdentifier.ToString()); await Clients.Caller.JoinedRoom(response); // do not broadcast all the messages for already joined users. response.messages = null; await Clients.OthersInGroup(response.roomIdentifier.ToString()).BrJoinedRoom(response); } catch (Exception e) { var errorResponse = ApplicationError.GetError <JoinRoomResponse>(e, "[JoinRoom]"); _logger.LogError(e.Message); await Clients.Caller.JoinedRoom(errorResponse); } }
protected IHttpActionResult ErrorResponse(HttpStatusCode code, string message) { var error = new ApplicationError(message); var msg = Request.CreateResponse(code, error, new JsonMediaTypeFormatter()); return(ResponseMessage(msg)); }
private void Manage() { //Response.Write(ExpenseShareBAL.ManageExpenseShare(Request.QueryString).ToJSON()); try { string result = ExpenseShareBAL.ManageExpenseShare(Request.QueryString, Request.Form); //var revolvingfund = new ExpenseShare //{ // //ESID = Convert.ToInt32(result.Split(',')[0]), // ESID = Convert.ToInt32(result[0]), //}; var expenseshare = new ExpenseShare { ESID = Convert.ToInt32(result.Split(',')[0]), ESDate = result.Split(',')[1], Particulars = result.Split(',')[2], AmtExpenseShare = Convert.ToDecimal(result.Split(',')[3]) }; Response.Write(expenseshare.ToJSON()); } catch (Exception ex) { var appError = new ApplicationError { ErrorMessage = ex.Message, ErrorCode = 999 }; Response.Write(appError.ToJSON()); } }
public static void Handle(IApplicationBuilder AApplication) { AApplication.Run(async AHttpContext => { var LExceptionHandlerPathFeature = AHttpContext.Features.Get <IExceptionHandlerPathFeature>(); var LException = LExceptionHandlerPathFeature.Error; AHttpContext.Response.ContentType = "application/json"; string LResult; switch (LException) { case BusinessException LBusinessException: { var LAppError = new ApplicationError(LBusinessException.ErrorCode, LBusinessException.Message); LResult = JsonConvert.SerializeObject(LAppError); AHttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest; break; } default: { var LAppError = new ApplicationError(nameof(ErrorCodes.ERROR_UNEXPECTED), ErrorCodes.ERROR_UNEXPECTED); LResult = JsonConvert.SerializeObject(LAppError); AHttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError; break; } } await AHttpContext.Response.WriteAsync(LResult); }); }
/// <summary> /// Handles the Load event of the Page control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected void Page_Load(object sender, EventArgs e) { string at = "Starting"; try { if (!IsPostBack) { at = "InitMahine"; m_StateMachineEngine.InitMahine(); } at = "Event handlers"; m_SaveButton.Click += new EventHandler(m_StateMachineEngine.SaveButton_Click); m_NewButton.Click += new EventHandler(m_StateMachineEngine.NewButton_Click); m_CancelButton.Click += new EventHandler(m_StateMachineEngine.CancelButton_Click); m_EditButton.Click += new EventHandler(m_StateMachineEngine.EditButton_Click); m_DeleteButton.Click += new EventHandler(m_StateMachineEngine.DeleteButton_Click); m_ExportButton.Click += new EventHandler(m_StateMachineEngine.m_ExportButton_Click); } catch (Exception ex) { ApplicationError _ae = new ApplicationError("Page_Load", "", ex.Message, ex); this.Controls.Add(_ae.CreateMessage(at, true)); } }
private void ManageAddUpdate() { try { string result = RepoReAppraisalBAL.ManageAddUpdate(Request.QueryString); var brecon = result; Response.Write(brecon.ToJSON()); //string result = BankReconBAL.Manage(Request.QueryString, Request.Form); //var brecon = result; //Response.Write(brecon.ToJSON()); } catch (Exception ex) { var appError = new ApplicationError { ErrorMessage = ex.Message, ErrorCode = 999 }; Response.Write(appError.ToJSON()); } //Response.Write(BankReconBAL.Manage(Request.QueryString).ToJSON()); }
/// <summary>表单内容界面</summary> /// <returns></returns> public ActionResult Form(string options) { // 所属应用信息 ApplicationInfo application = ViewBag.application = AppsContext.Instance.ApplicationService[BugConfiguration.ApplicationName]; // 管理员身份标记 bool isAdminToken = ViewBag.isAdminToken = AppsSecurity.IsAdministrator(this.Account, application.ApplicationName); // ------------------------------------------------------- // 业务数据处理 // ------------------------------------------------------- JsonData request = JsonMapper.ToObject(options == null ? "{}" : options); // 实体数据标识 string id = !request.Keys.Contains("id") ? string.Empty : request["id"].ToString(); // 文档编辑模式 DocEditMode docEditMode = DocEditMode.Unkown; // 实体数据信息 BugInfo param = null; if (string.IsNullOrEmpty(id)) { param = new BugInfo(); param.Id = DigitalNumberContext.Generate("Table_Bug_Key_Id"); // 设置编辑模式【新建】 docEditMode = DocEditMode.New; } else { param = BugContext.Instance.BugService.FindOne(id); if (param == null) { ApplicationError.Write(404); } // 设置编辑模式【编辑】 docEditMode = DocEditMode.Edit; } // ------------------------------------------------------- // 数据加载 // ------------------------------------------------------- ViewBag.Title = string.Format("{0}-{1}-{2}", (string.IsNullOrEmpty(param.Title) ? "新问题" : param.Title), application.ApplicationDisplayName, this.SystemName); // 加载当前业务实体类名称 ViewBag.entityClassName = KernelContext.ParseObjectType(param.GetType()); // 加载当前业务实体数据 ViewBag.param = param; // 加载当前文档编辑模式 ViewBag.docEditMode = docEditMode; return(View("/views/main/bugs/bug-form.cshtml")); }
public static Error FormatError(this ApplicationError applicationError) { return(new Error { Status = (int)applicationError.HttpStatusCode, Code = applicationError.Exception.Code, Title = applicationError.Exception.Message }); }
public void OnError(ApplicationError error) { EventHandler <ApplicationError> eventHandler = this.OnFailed; if (eventHandler != null) { eventHandler(this, error); } }
/// <summary> /// Analyzes the input file and writes the output to the AppConf.OutputFileName file. /// First checks if the output file already exists and if it is ok to overwrite it. /// </summary> /// <returns><c>true</c> if the analysis succeeded.</returns> public bool Analyze() { if (File.Exists(AppConf.OutputFileName) && !AppConf.OverWriteOutputFile) { ApplicationError.Add("Output file already exists", DefaultErrorMessageId); return(false); } return(PrepareEDFFiles() && _neuroLoopGain.Analyze()); }
public static void SetupApplicationError(string controller, string action, string errormessage) { ApplicationError error = new ApplicationError(); error.Controller = controller; error.Action = action; error.ErrorMessage = errormessage; HttpContext.Current.Session["ApplicationError"] = error; }
private void dgvCrashes_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { int index = dgvCrashes.CurrentRow.Index; Guid crashId = new Guid(dgvCrashes.Rows[index].Cells["ApplicationErrorId"].Value.ToString()); ApplicationError crash = new ApplicationError(crashId); frmQualityAssurancePopup frmQAPopup = new frmQualityAssurancePopup(crash); frmQAPopup.FormClosed += frmQualityAssurancePopup_FormClosed; }
private Task HandleExceptionAsync(HttpContext httpContext, Exception exception) { var applicationError = ApplicationError.From(exception); _logger.LogError(applicationError, applicationError.Message); httpContext.Response.StatusCode = applicationError.StatusCode; httpContext.Response.ContentType = "application/json"; return(httpContext.Response.WriteAsync(ApplicationError.From(exception).ToString())); }
private void SetInterconnectionData(ClearenceInterconnectionnData e) { if (m_ControlState.ClearanceID.CompareTo(e.ID) == 0) { return; } try { m_ControlState.ClearanceID = e.ID; ListItem _cs = m_SelectGroupRadioButtonList.Items.FindByValue(CurrentClearance.ProcedureCode); if (_cs == null) { this.ShowActionResult(GenericStateMachineEngine.ActionResult.NotValidated("ThisClearanceCannotBeEditedItIsNotCompensationGoodClearance".GetLocalizedString())); m_ControlState.ReadOnly = true; m_ControlState.ClearanceID = String.Empty; m_ControlState.ClearanceTitle = String.Empty; m_ClearenceTextBox.Text = String.Empty; return; } m_ControlState.IsModified = true; m_ControlState.ClearanceTitle = e.Title; m_ClearenceTextBox.Text = e.Title; m_SelectGroupRadioButtonList.SelectedIndex = -1; _cs.Selected = true; m_ControlState.ReadOnly = false; QueryAssigned(); string _export = "3151"; switch (CurrentClearance.ClearenceProcedure.Value) { case ClearenceProcedure._3151: case ClearenceProcedure._3171: break; case ClearenceProcedure._4051: case ClearenceProcedure._4071: _export = "4051"; break; case ClearenceProcedure._5100: case ClearenceProcedure._5171: case ClearenceProcedure._7100: case ClearenceProcedure._7171: case ClearenceProcedure.Invalid: case ClearenceProcedure.None: default: break; } m_ProcedureRadioButtonList.SelectedValue = _export; } catch (Exception _ex) { ApplicationError _errr = new ApplicationError("SetInterconnectionData", "ClearenceInterconnectionnData", _ex.Message, _ex); this.Controls.Add(_errr.CreateMessage(_errr.At, true)); } }
/// <summary>主页</summary> /// <returns></returns> public ActionResult Setting() { // 所属应用信息 ApplicationInfo application = ViewBag.application = AppsContext.Instance.ApplicationService[APPLICATION_NAME]; if (!AppsSecurity.IsAdministrator(KernelContext.Current.User, application.ApplicationName)) { ApplicationError.Write(401); } return(View("/views/main/applications/application-feature-setting.cshtml")); }
private void WriteAutheticationResponse(string errorMessage) { var customError = new ApplicationError(ApplicationConstants.ErrorCodes.AutheticationError, errorMessage); var serializedError = _applicationSerializationService.Serialize(customError); Context.Response.StatusCode = (int)HttpStatusCode.Unauthorized; Context.Response.ContentType = ApplicationConstants.Authentication.AuthenticationResponseContentType; Context.Response.WriteAsync(serializedError).Wait(); }
private ObjectResult ProcessResult <T>(T content, ApplicationError error, HttpStatusCode statusCode) where T : class { //workaround for HttpNoContentOutputFormatter if (statusCode == HttpStatusCode.OK && content == null) { return(new OkObjectResult(string.Empty)); } return(error == null? StatusCode((int)statusCode, content) : StatusCode((int)statusCode, error)); }
private void SetInterconnectionData(InvoiceContentInterconnectionnData e) { try { m_ControlState.InvoiceContentID = e.ID; } catch (Exception _ex) { ApplicationError _errr = new ApplicationError("SetInterconnectionData", "InvoiceContentInterconnectionnData", _ex.Message, _ex); this.Controls.Add(_errr.CreateMessage(_errr.At, true)); } }
private static void LogException(Exception exception) { DateTime timestamp = DateTime.Now; ApplicationError err = new ApplicationError(); err.TimeStamp = timestamp; err.Data = exception.Data.ToString(); err.Message = exception.Message; err.Source = exception.Source; err.StackTrace = exception.StackTrace; err.SaveRecordToDatabase(Guid.Empty); }
// // GET: /ApplicationError/ public ActionResult Index() { try { ApplicationError error = (ApplicationError)Session["ApplicationError"]; ViewData["Controller"] = error.Controller; ViewData["Action"] = error.Action; ViewData["ErrorMessage"] = error.ErrorMessage; } catch { } return(View()); }
public virtual void HandleError(ApplicationError applicationError) { applicationError.ResetResponse(); var httpContextWrapper = new HttpContextWrapper(applicationError.HttpContext); var routeData = new RouteData() .WithValue("controller", this.GetControllerName()) .WithValue("action", GetActionName(applicationError.StatusCode)) .WithValue("exception", applicationError.LastException); var requestContext = new RequestContext(httpContextWrapper, routeData); ((IController)this).Execute(requestContext); }