public async Task <ActionResult> VerifyCode(VerifyCodeModel model) { if (!ModelState.IsValid) { return(View(model)); } try { // The following code protects for brute force attacks against the two factor codes. // If a user enters incorrect codes for a specified amount of time then the user account // will be locked out for a specified amount of time. // You can configure the account lockout settings in IdentityConfig var result = await _accountService.TwoFactorSignInAsync(model); if (result.Succeeded) { return(RedirectToLocal(model.ReturnUrl)); } if (result.IsLockedOut) { return(View(ConstantMessages.AccountConstant.AccountControllerConstant.Lockout)); } else { ModelState.AddModelError("", ConstantMessages.AccountConstant.AccountControllerConstant.InvalidCode); return(View(model)); } } catch (Exception ex) { ErrorViewModel errorModel = GlobalExceptionHandler.GetErrorPage(ex.ToString()); return(View(ConstantMessages.AccountConstant.AccountControllerConstant.ErrorView, errorModel)); } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime appLifetime) { loggerFactory.AddSerilog(); // If you want to dispose of resources that have been resolved in the // application container, register for the "ApplicationStopped" event. appLifetime.ApplicationStopped.Register(OnApplicationStopped); // Global exception handler app.UseExceptionHandler(GlobalExceptionHandler.HandleException()); app.UseCors("MyPolicy"); app.UseMvc(); // auth middleware //app.UseMiddleware<AuthMiddleware>(); // log Request middleware //app.UseMiddleware<SerilogRequestMiddleware>(); //All Other middleware should go below these two since order matters in the request pipeline // // on complete middleware //app.UseMiddleware<OnCompleteMiddleware>(); app.UseAuthentication(); app.UseHttpsRedirection(); app.UseMvc(); //InitialiseAmqConnection(); }
public void InsertOrder(DisplayedOrder order) { Dispatcher.FromThread(OrderManager.UIThread).Invoke(() => { lock (ordersLock) { Orders.Insert(0, order); } //CreateLoggingFiles(); if (File.Exists(orderfile)) { try { using (var sw = new StreamWriter(orderfile, true)) { sw.WriteLine(ListViewHelper.ObjectToLine(order)); } } catch (Exception ex) { GlobalExceptionHandler.HandleException("Order Log", ex); } } }); }
public void AddMessage(Message msg) { Dispatcher.FromThread(OrderManager.UIThread).InvokeAsync(() => { MessageList.Insert(0, msg); CreateLoggingFiles(); if (File.Exists(msgfile)) { try { lock (msgFileLock) { using (var sw = new StreamWriter(msgfile, true)) { sw.WriteLine(ListViewHelper.ObjectToLine(msg)); } } } catch (Exception ex) { GlobalExceptionHandler.HandleException("Message Logging", ex); } } }); }
public void LogEvents(EventMonitorItem[] items) { try { if (items.Length > 0) { listView.BeginUpdate(); foreach (EventMonitorItem item in items) { item.ImageIndex = EventImageIndex; } listView.Items.AddRange(items); listView.AutoResizeColumns(); listView.FocusedItem = null; listView.SelectedItems.Clear(); items[items.Length - 1].EnsureVisible(); items[items.Length - 1].Selected = true; listView.EndUpdate(); } } catch { GlobalExceptionHandler.HandleException(); } }
public void Log(Log log) { Dispatcher.FromThread(OrderManager.UIThread).InvokeAsync(() => { if (LogList.Count > 0 && log.Text == LogList[0].Text && log.Source == LogList[0].Source) { LogList[0].Time = log.Time; } else { log.Text = log.Text.TrimEnd('\n'); LogList.Insert(0, log); if (File.Exists(logfile)) { try { lock (logFileLock) { using (var sw = new StreamWriter(logfile, true)) { sw.WriteLine(ListViewHelper.ObjectToLine(log)); } } } catch (Exception ex) { GlobalExceptionHandler.HandleException("Log", ex); } } } }); }
public async Task <ActionResult> ConfirmEmail(string userId, string code) { try { if (userId == null || code == null) { return(View(ConstantMessages.AccountConstant.AccountControllerConstant.ErrorView)); } var user = await _accountService.FindByIdAsync(_htmlEncoder.Encode(userId)); if (user == null) { return(View(ConstantMessages.AccountConstant.AccountControllerConstant.ErrorView)); } var result = await _accountService.ConfirmEmailAsync(user, _htmlEncoder.Encode(code)); return(View(result.Succeeded ? ConstantMessages.AccountConstant.AccountControllerConstant.ConfirmEmail : ConstantMessages.AccountConstant.AccountControllerConstant.ErrorView)); } catch (Exception ex) { ErrorViewModel errorModel = GlobalExceptionHandler.GetErrorPage(ex.ToString()); return(View(ConstantMessages.AccountConstant.AccountControllerConstant.ErrorView, errorModel)); } }
public static void Main() { FConsole.Title = "SERVER APP"; GlobalExceptionHandler.Setup(); Jit.PreJit(); Core.Db = new JsonDb(); Core.Db.EnsureDbReady(); ReceiveQueue.OnPacket += PacketRouter.Route; ServerSocket.Start(Core.Settings.Port); FConsole.WriteLine("Online"); while (true) { var cmd = FConsole.ReadLine(); switch (cmd) { case "exit": Core.Db.Save(); Environment.Exit(0); break; default: break; } } }
public void RefreshNodes() { Cursor.Current = Cursors.WaitCursor; if (String.IsNullOrWhiteSpace(Filter)) { List <ComTypeTreeNode> nodes = new List <ComTypeTreeNode>(); try { foreach (ComTypeLibrary comTypeLibrary in ComTypeManager.Instance.ComTypeLibraries) { ComTypeLibraryTreeNode comTypeLibraryTreeNode = new ComTypeLibraryTreeNode(comTypeLibrary); nodes.Add(comTypeLibraryTreeNode); RefreshNode(comTypeLibraryTreeNode); } } catch { GlobalExceptionHandler.HandleException(); } Nodes.Clear(); Nodes.AddRange(nodes.ToArray()); } else { RefreshNodesFiltered(); } Cursor.Current = Cursors.Default; }
Task ICommandHandler <PauseCommandDefinition> .Run(Command command) { var backendService = (_runbookViewModel.Model as RunbookModelProxy).Context.Service; try { // NOTE 20160427: Fixes bug #19 if (_runbookViewModel.Runbook.JobID == null) { _runbookViewModel.Runbook.JobID = _jobId; } if (command.Text.Equals("Pause")) { backendService.PauseExecution(_runbookViewModel.Model as RunbookModelProxy, _isTestRun); } else { backendService.ResumeExecution(_runbookViewModel.Model as RunbookModelProxy, _isTestRun); } } catch (Exception ex) { GlobalExceptionHandler.Show(ex); } return(TaskUtility.Completed); }
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs args) { //Exception ex = new Exception("Uncaptured exception for current domain"); Exception ex = (Exception)args.ExceptionObject; GlobalExceptionHandler.HandleException(sender, ex, args, null, true); }
public GlobalExceptionHandlerTests() { _logger = Substitute.For <MockLogger <GlobalExceptionHandler> >(); _requestDelegate = Substitute.For <RequestDelegate>(); _httpResponseHelper = Substitute.For <IHttpResponseHelper>(); _handler = new GlobalExceptionHandler(_requestDelegate, _logger, _httpResponseHelper); }
public async Task <ActionResult> SendCode(bool rememberMe, string returnUrl = null) { try { var user = await _accountService.GetTwoFactorAuthenticationUserAsync(); if (user == null) { return(View(ConstantMessages.AccountConstant.AccountControllerConstant.ErrorView)); } var userFactors = await _accountService.GetValidTwoFactorProvidersAsync(user); var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList(); return(View(new SendCodeModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe })); } catch (Exception ex) { ErrorViewModel errorModel = GlobalExceptionHandler.GetErrorPage(ex.ToString()); return(View(ConstantMessages.AccountConstant.AccountControllerConstant.ErrorView, errorModel)); } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler(options => { GlobalExceptionHandler.handle(options, loggerFactory); }); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseSwagger(); app.UseSwaggerUI(config => { config.SwaggerEndpoint("/swagger/v1/swagger.json", "Account Api"); }); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
public async Task Handle_WhenContextHasHandlerFeatureEnabled_ShouldWriteResponse() { //Arrange var errorMessage = "TestMessage"; _exceptionHandlerFeatureMock .Setup(x => x.Error.Message) .Returns(errorMessage); _featuresMock .Setup(x => x.Get <IExceptionHandlerFeature>()) .Returns(_exceptionHandlerFeatureMock.Object); _responseMock .SetupProperty(x => x.StatusCode) .SetupProperty(x => x.ContentType); _httpContext = new MockHttpContext(_featuresMock.Object, response: _responseMock.Object); var sut = new GlobalExceptionHandler(_exceptionWriterMock.Object, _loggerMock.Object); //Act await sut.Handle(_httpContext); //Assert _exceptionWriterMock.Verify(x => x.WriteResponse(_httpContext), Times.Once); }
async Task ICommandHandler <SaveCommandDefinition> .Run(Command command) { await Task.Run(delegate() { LongRunningOperation.Start(); model.Value = JsonConverter.ToJson(value); model.ViewModel = this; try { Owner.Save(this, command); Owner.Context.AddToVariables(model); } catch (ApplicationException ex) { GlobalExceptionHandler.Show(ex); } // Update the UI to notify that the changes has been saved UnsavedChanges = false; NotifyOfPropertyChange(() => DisplayName); LongRunningOperation.Stop(); }); }
public async Task <ActionResult> VerifyCode(string provider, bool rememberMe, string returnUrl = null) { try { var user = await _accountService.GetTwoFactorAuthenticationUserAsync(); if (user == null) { return(View(ConstantMessages.AccountConstant.AccountControllerConstant.ErrorView)); } // Remove before production #if DEMO if (user != null) { ViewBag.Code = await _accountService.GenerateTwoFactorTokenAsync(user, _htmlEncoder.Encode(provider)); } #endif return(View(new VerifyCodeModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe })); } catch (Exception ex) { ErrorViewModel errorModel = GlobalExceptionHandler.GetErrorPage(ex.ToString()); return(View(ConstantMessages.AccountConstant.AccountControllerConstant.ErrorView, errorModel)); } }
public async Task Handle_WhenContextHasNoHandlerFeatureEnabled_ShouldSetResponseStatusCodeAndContentType() { //Arrange _featuresMock .Setup(x => x.Get <IExceptionHandlerFeature>()) .Returns <IExceptionHandlerFeature>(null); _responseMock .SetupProperty(x => x.StatusCode) .SetupProperty(x => x.ContentType); _httpContext = new MockHttpContext(_featuresMock.Object, response: _responseMock.Object); var expectedBody = _responseMock.Object.Body; var sut = new GlobalExceptionHandler(_exceptionWriterMock.Object, _loggerMock.Object); //Act await sut.Handle(_httpContext); //Assert _responseMock.Object.StatusCode.Should().Be((int)HttpStatusCode.InternalServerError); _responseMock.Object.ContentType.Should().Be("application/json"); _exceptionWriterMock.Verify(x => x.WriteResponse(_httpContext), Times.Never); }
private void btnOk_Click(object sender, RoutedEventArgs e) { try { if (ValidateUser(_model, _isNew)) { var service = new SupportService(User); if (_isNew) { service.InsertUser(_model.Model); } else { service.UpdateUser(_model.Model); } if (!string.IsNullOrEmpty(txtPassword.Password)) { service.UpdateUserPassword(_model.UserName, txtPassword.Password); } this.DialogResult = true; this.Close(); } } catch (Exception ex) { GlobalExceptionHandler.Handle(ex); } }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } if (!env.IsProduction()) { app.UseOpenApi(); app.UseSwaggerUi3(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseCors(); app.UseAuthentication(); app.UseAuthorization(); app.UseExceptionHandler(x => x.Run(GlobalExceptionHandler.Handle(env))); app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapHub <SignalrHub>("/hub"); }); }
protected override void OnStartup(StartupEventArgs e) { MainWindow window = new MainWindow(); window.Show(); _ = new GlobalExceptionHandler(window.MainView); }
public async Task <ActionResult> ResetPassword(ResetPasswordModel model) { try { if (!ModelState.IsValid) { return(View(model)); } var user = await _accountService.FindByNameAsync(_htmlEncoder.Encode(model.Email)); if (user == null) { // Don't reveal that the user does not exist return(RedirectToAction(ConstantMessages.AccountConstant.AccountControllerConstant.ResetPasswordConfirmation, ConstantMessages.AccountConstant.AccountControllerConstant.Account)); } var result = await _accountService.ResetPasswordAsync(user, _htmlEncoder.Encode(model.Code), _htmlEncoder.Encode(model.Password)); if (result.Succeeded) { return(RedirectToAction(ConstantMessages.AccountConstant.AccountControllerConstant.ResetPasswordConfirmation, ConstantMessages.AccountConstant.AccountControllerConstant.Account)); } AddErrors(result); return(View()); } catch (Exception ex) { ErrorViewModel errorModel = GlobalExceptionHandler.GetErrorPage(ex.ToString()); return(View(ConstantMessages.AccountConstant.AccountControllerConstant.ErrorView, errorModel)); } }
private void UpdateRichTextBox(ComTreeNode node) { try { typeInfoRichTextBox.Clear(); if (node == null) { return; } ComTypeInfo comTypeInfo = null; ComPropertyInfo comPropertyInfo = null; ComFunctionInfo comFunctionInfo = null; if (node is ComPtrItemTreeNode) { comFunctionInfo = ((ComPtrItemTreeNode)node).ComFunctionInfo; } else if (node is ComMethodTreeNode) { comFunctionInfo = ((ComMethodTreeNode)node).ComFunctionInfo; } else if (node is ComPropertyTreeNode) { comPropertyInfo = ((ComPropertyTreeNode)node).ComPropertyInfo; } else if (node is ComPtrTreeNode) { ComPtrTreeNode comObjectPropertyTreeNode = (ComPtrTreeNode)node; if (comObjectPropertyTreeNode.ComPropertyInfo != null) { comPropertyInfo = comObjectPropertyTreeNode.ComPropertyInfo; } else { comTypeInfo = comObjectPropertyTreeNode.ComPtr.TryGetComTypeInfo(); } } if (comTypeInfo != null) { typeInfoRichTextBox.DescribeComTypeInfo(comTypeInfo); } else if (comPropertyInfo != null) { typeInfoRichTextBox.DescribeComPropertyInfo(comPropertyInfo); } else if (comFunctionInfo != null) { typeInfoRichTextBox.DescribeComFunctionInfo(comFunctionInfo); } } catch { GlobalExceptionHandler.HandleException(); } }
public static void CatchExceptions(this IAppBuilder appBuilder, HttpConfiguration httpConfiguration) { var exceptionHandler = appBuilder.Properties[OwinProperties.ExceptionHandler] as ExceptionHandler; var globalExceptionHandler = new GlobalExceptionHandler(); globalExceptionHandler.OnExceptionCaught += exception => exceptionHandler?.Invoke(exception); httpConfiguration.Filters.Add(globalExceptionHandler); }
public static int InvokePropertySet(this IDispatch dispatch, int dispid, object value) { int hr = NativeMethods.S_OK; var guid = Guid.Empty; var lcid = NativeMethods.LOCALE_SYSTEM_DEFAULT; var flags = System.Runtime.InteropServices.ComTypes.INVOKEKIND.INVOKE_PROPERTYPUT; var pExcepInfo = default(System.Runtime.InteropServices.ComTypes.EXCEPINFO); uint pArgErr = 0; Variant pVarResult = default(Variant); VariantArgPtr va = new VariantArgPtr(1); var dp = new System.Runtime.InteropServices.ComTypes.DISPPARAMS() { cArgs = va.Count, rgvarg = va, cNamedArgs = 1, rgdispidNamedArgs = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(int))) }; Marshal.WriteInt32(dp.rgdispidNamedArgs, (int)NativeMethods.DISPID_PROPERTYPUT); if (value is VariantWrapper) { Variant variant = new Variant((VariantWrapper)value); Marshal.StructureToPtr(variant, va[0], false); } else { Marshal.GetNativeVariantForObject(value, va[0]); } try { hr = dispatch.Invoke( dispid, ref guid, lcid, flags, ref dp, out pVarResult, ref pExcepInfo, out pArgErr ); } catch { GlobalExceptionHandler.HandleException(); } finally { Marshal.FreeCoTaskMem(dp.rgdispidNamedArgs); va.Dispose(); } return(hr); }
public void GlobalExceptionHandler_Handle() { var handler = new GlobalExceptionHandler(); var context = new ExceptionHandlerContext(new ExceptionContext(new Exception(), new ExceptionContextCatchBlock("Test", true, true), new HttpRequestMessage())); handler.Handle(context); ((TextPlainErrorResult)context.Result).Content.Should().NotBeEmpty(); }
public static void Main() { frm = new KADGen.WinProject.Main(); GlobalExceptionHandler exceptionHandler = new GlobalExceptionHandler(); // Adds the event handler to to the event. Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(exceptionHandler.OnThreadException); System.Windows.Forms.Application.Run(frm); }
public JobHistoryViewModel(RunbookViewModel runbookViewModel) { _runbook = (RunbookModelProxy)runbookViewModel.Model; Owner = _runbook.Context.Service; Jobs = new ObservableCollection <JobModelProxy>(); //AsyncExecution.Run(ThreadPriority.Normal, () => Task.Run(() => { IList <JobModelProxy> draftJobs = null; IList <JobModelProxy> publishedJobs = null; try { if (_runbook.DraftRunbookVersionID.HasValue) { draftJobs = Owner.GetJobs(_runbook.DraftRunbookVersionID.Value); } if (_runbook.PublishedRunbookVersionID.HasValue) { publishedJobs = Owner.GetJobs(_runbook.PublishedRunbookVersionID.Value); } } catch (ApplicationException ex) { GlobalExceptionHandler.Show(ex); } Execute.OnUIThread(() => { if (draftJobs != null) { foreach (var job in draftJobs) { job.BoundRunbookViewModel = runbookViewModel; job.RunbookType = RunbookType.Draft; Jobs.Add(job); } } if (publishedJobs != null) { foreach (var job in publishedJobs) { job.BoundRunbookViewModel = runbookViewModel; job.RunbookType = RunbookType.Published; Jobs.Add(job); } } Jobs = Jobs.OrderBy(j => j.StartTime).ToObservableCollection(); }); }); }
public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationModel model, string returnUrl = null) { try { if (_accountService.IsSignedIn(User)) { return(RedirectToAction(ConstantMessages.AccountConstant.AccountControllerConstant.Lockout, ConstantMessages.AccountConstant.AccountControllerConstant.ManageController)); } if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = await _accountService.GetExternalLoginInfoAsync(); if (info == null) { return(View(ConstantMessages.AccountConstant.AccountControllerConstant.ExternalLoginFailureView)); } var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await _accountService.CreateAsync(user); // NOTE: Used for end to end testing only //Just for automated testing adding a claim named 'ManageStore' - Not required for production var manageClaim = info.Principal.Claims.Where(c => c.Type == ConstantMessages.AccountConstant.AccountControllerConstant.ManageStore).FirstOrDefault(); if (manageClaim != null) { await _accountService.AddClaimAsync(user, manageClaim); } if (result.Succeeded) { result = await _accountService.AddLoginAsync(user, info); if (result.Succeeded) { await _accountService.SignInAsync(user, isPersistent : false); return(RedirectToLocal(returnUrl)); } } AddErrors(result); } ViewBag.ReturnUrl = returnUrl; return(View(model)); } catch (Exception ex) { ErrorViewModel errorModel = GlobalExceptionHandler.GetErrorPage(ex.ToString()); return(View(ConstantMessages.AccountConstant.AccountControllerConstant.ErrorView, errorModel)); } }
private ComTreeNode[] GetChildren(ComPtrTreeNode node) { if (node == null) { return new ComTreeNode[] { } } ; ComTreeNode[] childNodes = new ComTreeNode[] { }; try { childNodes = GetChildren(node.ComPtr); } catch { GlobalExceptionHandler.HandleException(); } List <ComTreeNode> filteredComTreeNodes = new List <ComTreeNode>(); foreach (ComTreeNode childNode in childNodes) { ComPtrTreeNode comPtrTreeNode = childNode as ComPtrTreeNode; ComPropertyTreeNode comPropertyTreeNode = childNode as ComPropertyTreeNode; if (comPtrTreeNode != null) { if ((comPtrTreeNode.ComPtr.IsInvalid) && (_showNullObjects == false)) { continue; } if (comPtrTreeNode.IsCollection) { if ((comPtrTreeNode.IsEmptyCollection) && (_showEmptyCollections == false)) { continue; } } } else if (comPropertyTreeNode != null) { if (_showProperties == false) { continue; } } filteredComTreeNodes.Add(childNode); } SetImageIndex(filteredComTreeNodes.ToArray()); return(filteredComTreeNodes.ToArray()); }