public void can_open_log_folder_when_there_is_a_log_folder() { // ARRANGE _applicationService.SetupGet(x => x.LogFolder).Returns(@"c:\temp\log.txt"); var viewModel = new ExceptionViewModel(null, _applicationService.Object); // ACT var canExecute = viewModel.OpenLogFolderCommand.CanExecute(null); // ASSERT Assert.That(canExecute, Is.True); }
public void can_not_open_log_folder_when_there_is_no_log_folder() { // ARRANGE _applicationService.SetupGet(x => x.LogFolder).Returns((string)null); var viewModel = new ExceptionViewModel(null, _applicationService.Object); // ACT var canExecute = viewModel.OpenLogFolderCommand.CanExecute(null); // ASSERT Assert.That(canExecute, Is.False); }
public void ShowExceptionDialog_Expected_WindowManagerInvokedForViewModel() { var vm = new ExceptionViewModel(); Mock <IWindowManager> mockWinManager = new Mock <IWindowManager>(); mockWinManager.Setup(c => c.ShowDialog(It.IsAny <BaseViewModel>(), null, null)).Verifiable(); vm.WindowNavigation = mockWinManager.Object; vm.Show(); mockWinManager.Verify(mgr => mgr.ShowDialog(It.IsAny <ExceptionViewModel>(), null, null), Times.Once()); }
public void restart_application() { // ARRANGE _applicationService.Setup(x => x.Exit()); var viewModel = new ExceptionViewModel(null, _applicationService.Object); // ACT viewModel.RestartCommand.Execute(null); // ASSERT _applicationService.Verify(); }
public void Send_Where_OutputPathAlreadyExists_Expected_FileIOException() { //Create file which is to conflict with the output path of the recorder FileInfo conflictingPath = new FileInfo(GetUniqueOutputPath(".txt")); conflictingPath.Create().Close(); var vm = new ExceptionViewModel { OutputPath = conflictingPath.FullName }; vm.SendReport(); }
public void TestAtMessageReturnererFejlbeskedFraException() { var fixture = new Fixture(); fixture.Customize <IntranetGuiRepositoryException>(e => e.FromFactory(() => new IntranetGuiRepositoryException(fixture.Create <string>(), fixture.Create <Exception>()))); var exception = fixture.Create <IntranetGuiRepositoryException>(); var exceptionViewModel = new ExceptionViewModel(exception); Assert.That(exceptionViewModel, Is.Not.Null); Assert.That(exceptionViewModel.Message, Is.Not.Null); Assert.That(exceptionViewModel.Message, Is.Not.Empty); Assert.That(exceptionViewModel.Message, Is.EqualTo(exception.Message)); }
public void WhenExceptionUpdatedShouldUpdateMessages() { // Arrange var vm = new ExceptionViewModel(); var inner1 = new ArgumentNullException("i", "An argument was null"); var inner0 = new InvalidOperationException("Terrible failure", inner1); // Act vm.Header = "Something broke"; vm.Exception = inner0; // Assert Assert.That(vm.Messages, Is.EquivalentTo(new[] { "Something broke", "InvalidOperationException: " + inner0.Message, "ArgumentNullException: " + inner1.Message })); }
public void can_copy_exception_to_clipboard_when_exception_is_null() { // ARRANGE var message = "This is the message"; var exception = new Exception(message); var viewModel = new ExceptionViewModel(exception, _applicationService.Object); // ACT var canExecute = viewModel.CopyCommand.CanExecute(null); // ASSERT Assert.That(canExecute, Is.True); }
public void opens_log_folder() { // ARRANGE _applicationService.SetupGet(x => x.LogFolder).Returns(@"c:\temp\log.txt"); _applicationService.Setup(x => x.OpenFolder(@"c:\temp\log.txt")); var viewModel = new ExceptionViewModel(null, _applicationService.Object); // ACT viewModel.OpenLogFolderCommand.Execute(null); // ASSERT _applicationService.Verify(); }
private object GetModel(Exception ex) { var error = new ExceptionViewModel { ExceptionMessage = ex.Message }; if (_hostingEnvironment.IsDebugMode) { error.ExceptionType = ex.GetType(); error.StackTrace = ex.StackTrace; } return(error); }
public void OnException(ExceptionContext exceptionContext) { var exception = new ExceptionViewModel() { ExceptionMessage = exceptionContext.Exception.Message, StackTrace = exceptionContext.Exception.StackTrace, ControllerName = exceptionContext.RouteData.Values["controller"].ToString(), ActionName = exceptionContext.RouteData.Values["action"].ToString(), Date = DateTime.Now }; ExceptionService.CreateException(exception.ToBllException()); exceptionContext.ExceptionHandled = false; }
public IActionResult ExceptionHandler() { var exception = HttpContext.Features.Get <IExceptionHandlerPathFeature>(); var viewModel = new ExceptionViewModel { Path = exception.Path, Message = exception.Error.Message, StackTrace = exception.Error.StackTrace, }; _logger.LogError(viewModel.ToString()); return(View("Exception", viewModel)); }
public void copy_exception_to_clipboard() { // ARRANGE var message = "This is the message"; var exception = new Exception(message); _applicationService.Setup(x => x.CopyToClipboard(exception.ToString())); var viewModel = new ExceptionViewModel(exception, _applicationService.Object); // ACT viewModel.CopyCommand.Execute(null); // ASSERT _applicationService.Verify(); }
/// <summary> /// Creates the exception view model. /// </summary> /// <param name="e">The exception for this viewmodel.</param> /// <param name="environmentModel">The environment model.</param> /// <param name="isCritical">The severity of the error.</param> /// <returns></returns> /// <date>2013/01/16</date> /// <author> /// Jurie.smit /// </author> public static IExceptionViewModel CreateViewModel(Exception e, IEnvironmentModel environmentModel, ErrorSeverity isCritical = ErrorSeverity.Default) { // PBI 9598 - 2013.06.10 - TWR : added environmentModel parameter var vm = new ExceptionViewModel { OutputText = CreateStringValue(e, null, true).ToString(), StackTrace = e.StackTrace, OutputPath = GetUniqueOutputPath(".txt"), DisplayName = isCritical == ErrorSeverity.Critical ? StringResources.CritErrorTitle : StringResources.ErrorTitle, }; var attachedFiles = new Dictionary <string, string>(); vm.Exception.Clear(); vm.Exception.Add(Create(e, isCritical == ErrorSeverity.Critical)); return(vm); }
public void SendEmailTest() { var exception = new ArgumentException("test message"); var exceptionViewModel = new ExceptionViewModel(exception); var today = DateTime.Now; var fileName = Path.ChangeExtension(today.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), "log"); using (var stream = File.Create(fileName)) { stream.WriteByte(20); } // Send to a real address so that it succeeds, but an inactive account so we don't spam anyone. exceptionViewModel.DestinationAddress = "*****@*****.**"; exceptionViewModel.SendEmail(); Thread.Sleep(500); File.Delete(fileName); }
/// <summary> /// Creates the exception view model. /// </summary> /// <param name="e">The exception for this viewmodel.</param> /// <param name="server">The environment model.</param> /// <param name="isCritical">The severity of the error.</param> /// <returns></returns> /// <date>2013/01/16</date> /// <author> /// Jurie.smit /// </author> public static async Task <IExceptionViewModel> CreateViewModel(Exception e, IServer server, ErrorSeverity isCritical = ErrorSeverity.Default) { // PBI 9598 - 2013.06.10 - TWR : added environmentModel parameter var vm = new ExceptionViewModel(new AsyncWorker()) { OutputText = CreateStringValue(e, null, true).ToString(), StackTrace = e.StackTrace, OutputPath = GetUniqueOutputPath(".txt"), DisplayName = isCritical == ErrorSeverity.Critical ? StringResources.CritErrorTitle : StringResources.ErrorTitle }; vm.GetStudioLogFile(); vm.ServerLogFile = await ExceptionViewModel.GetServerLogFile(); vm.Exception.Clear(); vm.Exception.Add(Create(e, isCritical == ErrorSeverity.Critical)); return(vm); }
public override void OnException(ExceptionContext context) { if (context.Exception is DomainException) { ExceptionViewModel model = new ExceptionViewModel { Message = context.Exception.Message }; context.Result = new ViewResult { ViewName = "CustomException", ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()) { Model = model } }; } }
public IActionResult Error(int prodId, string exceptStr) { string[] tempArray = exceptStr.Split(new string[] { "&&" }, StringSplitOptions.None); Product tempProd = new Product(); foreach (var item in _context.Product) { if (item.Id == prodId) { tempProd = item; } } var model = new ExceptionViewModel { Product = tempProd, errors = tempArray }; return(View(model)); }
private void ShowExceptionDialog(Exception ex, string source) { Logger.LogException(ex, source); // TODO: what is this exception? if (ex is NullReferenceException && ex.Source == "MaterialDesignExtensions") { return; } ExceptionWindow window = new ExceptionWindow(); ExceptionViewModel viewModel = new ExceptionViewModel(); viewModel.Exception = ex; if (matchAssemblyException(ex.GetInnermostException())) { viewModel.MissingDependencyLink = "https://www.microsoft.com/en-us/download/details.aspx?id=48145"; } window.DataContext = viewModel; window.ShowDialog(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { LogHelper.logger.Info("Service is starting up"); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseExceptionHandler(errorApp => { errorApp.Run(async context => { ExceptionViewModel exceptionModel; var exception = context.Features.Get <IExceptionHandlerFeature>(); LogHelper.logger.Error(exception.Error); Type exceptionType = exception.Error.GetType(); context.Response.ContentType = "application/json"; #if DEBUG string infoLink = $"{context.Request.Scheme}://{context.Request.Host.Host}:{context.Request.Host.Port}/swagger/index.html"; #else string infoLink = $"https://github.com/lodgify/public-money-recruitment-be-test" #endif if (exceptionType.Name == "ApplicationException") { context.Response.StatusCode = 422; exceptionModel = new ExceptionViewModel(exception.Error.Message, infoLink); } else { context.Response.StatusCode = 500; exceptionModel = new ExceptionViewModel("Ooops. Something went wrong.", infoLink); } await context.Response.WriteAsync(exceptionModel.ConvertToJson(), System.Text.Encoding.UTF8); }); }); app.UseMvc(); app.UseSwagger(); app.UseSwaggerUI(opts => opts.SwaggerEndpoint("/swagger/v1/swagger.json", "VacationRental v1")); LogHelper.logger.Info("Service has started successfully"); }
private async Task HandleExceptionAsync(HttpContext context, HttpStatusCodeException HttpStatusCodeException) { context.Response.StatusCode = HttpStatusCodeException.StatusCode; var errorMessage = new ExceptionViewModel() { StatusCode = context.Response.StatusCode, ErrorMessage = HttpStatusCodeException.ErrorMessage }; var stringWriter = new StringWriter(); using (JsonWriter textWriter = new JsonTextWriter(stringWriter)) { var serializer = new JsonSerializer(); serializer.Serialize(textWriter, errorMessage); textWriter.Flush(); } string jSerializeObjectstring = stringWriter.ToString(); await context.Response.WriteAsync(jSerializeObjectstring); }
public virtual IActionResult Index(int?statusCode, int?subStatusCode) { var model = new ExceptionViewModel { StatusCode = statusCode ?? 500, SubStatusCode = subStatusCode }; model.Description = this.GetDescription(model.StatusCode, model.SubStatusCode); model.DetailedDescription = this.GetDetailedDescription(model.StatusCode, model.SubStatusCode); if (this.HostingEnvironment.IsDevelopment()) { model.Exception = this.HttpContext.Features.Get <IExceptionHandlerFeature>()?.Error; } model.Heading = this.GetStatusLabel(model.StatusCode, model.SubStatusCode) + " " + this.GetStatusDescription(model.StatusCode); this.Response.StatusCode = model.StatusCode; return(this.View(model)); }
private void ThrowAnException() { try { try { throw new WebException("Unable to navigate to webpage, 'wonga.com'"); } catch (Exception ex) { throw new InvalidOperationException("An exception occurred all up in your app", ex); } } catch (Exception ex) { Exception = new ExceptionViewModel() { Header = "An error has occurred", Exception = ex, }; } }
private void PerformSanityChecks() { XLToolbox.UserSettings.UserSettings userSettings = XLToolbox.UserSettings.UserSettings.Default; Logger.Info("Performing sanity checks"); ExceptionViewModel evm = new ExceptionViewModel(null); Logger.Info("+++ Excel version: {0}, {1}", evm.ExcelVersion, evm.ExcelBitness); Logger.Info("+++ OS version: {0}, {1}", evm.OS, evm.OSBitness); Logger.Info("+++ CLR version: {0}, {1}", evm.CLR, evm.ProcessBitness); Logger.Info("+++ VSTOR version: {0}", evm.VstoRuntime); Logger.Info("+++ Bovender version: {0}", evm.BovenderFramework); // Deactivating the VBA add-in can cause crashes; we now do it in the installer // XLToolbox.Legacy.LegacyToolbox.DeactivateObsoleteVbaAddin(); if (userSettings.Running) { XLToolbox.Logging.LogFileViewModel vm = new XLToolbox.Logging.LogFileViewModel(); if (userSettings.EnableLogging) { vm.InjectInto <XLToolbox.Logging.IncompleteShutdownLoggingEnabled>().ShowInForm(); } else { vm.InjectInto <XLToolbox.Logging.IncompleteShutdownLoggingDisabled>().ShowInForm(); } userSettings.SheetManagerVisible = false; } if (userSettings.Exception != null) { Bovender.UserSettings.UserSettingsExceptionViewModel vm = new Bovender.UserSettings.UserSettingsExceptionViewModel(userSettings); vm.InjectInto <XLToolbox.Mvvm.Views.UserSettingsExceptionView>().ShowDialogInForm(); } userSettings.Running = true; userSettings.Save(); Logger.Info("Sanity checks completed"); }
public IActionResult Post([FromBody] ExceptionViewModel model) { Guid id = Guid.Empty; if (!Guid.TryParse(HttpContext.GetRouteData().Values["id"].ToString(), out id)) { return(BadRequest("Token format is incorrect")); } try { _exceptionService.HandleException(id, Mapper.Map <IExceptionInfo>(model)); } catch (InvalidTokenException e) { return(NotFound(e.Message)); } catch { return(BadRequest()); } return(Ok()); }
public class MVCCustomExceptionFilter : HandleErrorAttribute {// FilterAttribute, IExceptionFilter /// <summary> /// Called when an unhandled exception arises. /// Exception filters are the easiest solution for processing the subset unhandled exceptions related to a specific action or controller. /// </summary> /// <param name="filterContext">Derived from ControllerContext /// Useful ControllerContext prop: /// Controller => Return the controller object for this request /// HttpContext => Provides access to details of a request and access to the response /// IsChildAction /// RequestContext => Provides access to the HttpContext and the routing data, both of which are available through other properties /// RouteData => Returns the routing data for this request /// Useful ExceptionContext prop: /// ActionDescriptor => Provides details of the action method /// Result => The result for action method; a filter can cancel request by setting this property to a non-null value /// Exception => the unhandled exception /// ExceptionHandled => Returns true if another filter has marked the exception as handled /// </param> public override void OnException(ExceptionContext filterContext) { base.OnException(filterContext); //First Check if Exception all ready Handle Or Check Is Custom error Handle is enable // If custom errors are disabled, we need to let the normal ASP.NET exception handler // execute so that the user can see useful debugging information. if (filterContext.ExceptionHandled /*|| !filterContext.HttpContext.IsCustomErrorEnabled*/) { return; } var statusCode = (int)HttpStatusCode.InternalServerError; if (filterContext.Exception is HttpException) { statusCode = new HttpException(null, filterContext.Exception).GetHttpCode(); } //prepare error info object var controllerName = filterContext.RouteData.Values["controller"].ToString(); var actionName = filterContext.RouteData.Values["action"].ToString(); var errormodel = new HandleErrorInfo(filterContext.Exception, controllerName, actionName); // if the request is AJAX return JSON else view. At Ajax request time, If any exception occurred then its will return error view , which is not a good things if (filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest") { filterContext.Result = new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = new { error = true, message = filterContext.Exception.Message, errorObj = JsonConvert.SerializeObject(errormodel, new JsonSerializerSettings { Formatting = Formatting.Indented, //TypeNameHandling = TypeNameHandling.Objects, ContractResolver = new CamelCasePropertyNamesContractResolver() }), source = filterContext.Exception.Source }, ContentEncoding = System.Text.Encoding.UTF8, ContentType = "application/json" }; } else { var modules = HttpContext.Current.ApplicationInstance.Modules; //exception + httpModules var exceptContext = new ExceptionViewModel { Model = filterContext, Modules = modules.AllKeys .Select(x => new Tuple <string, string>(x.StartsWith("__Dynamic") ? string.Format("Dynamic: {0},{1},{2}", x.Split('_', ',')[3], x.Split('_', ',')[4], x.Split('_', ',')[5]) : x, modules[x].GetType().Name)) .OrderBy(x => x.Item1).ToArray() }; filterContext.Result = (new ViewResult() { ViewName = "Errors", MasterName = "_Layout.HttpErrors", //ViewData = new ViewDataDictionary(error model), ViewData = new ViewDataDictionary <ExceptionViewModel>(exceptContext), TempData = filterContext.Controller.TempData }); } //mark exception as handled (other filters not doing attempting work) Debug.WriteLine(filterContext.Exception.Message); // Prepare the response code. filterContext.ExceptionHandled = true; //filterContext.HttpContext.Response.Clear(); if (!filterContext.HttpContext.Request.IsLocal) { filterContext.HttpContext.Response.StatusCode = statusCode; } // Certain versions of IIS will sometimes use their own error page when // they detect a server error. Setting this property indicates that we // want it to try to render ASP.NET MVC's error page instead. filterContext.HttpContext.Response.TrySkipIisCustomErrors = true; }
public static void UserDisplay(this Exception ex) { ExceptionViewModel vm = new ExceptionViewModel(ex); new ExceptionDialog(vm).ShowDialog(); }
/// <summary> /// Class constructor from paramters /// </summary> /// <param name="processItems"></param> public PageManagerViewModel(IProcessItems processItems) : this() { mProcessItems = processItems; ViewException = new ExceptionViewModel(); }
public ExceptionDialog(ExceptionViewModel vm) { DataContext = vm; InitializeComponent(); }
public ExceptionView() { InitializeComponent(); ViewModel = new ExceptionViewModel(); DataContext = ViewModel; }