示例#1
0
        protected void Application_Error(object sender, EventArgs e)
        {
            var httpContext = ((MvcApplication)sender).Context;

            var currentRouteData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));
            var currentController = " ";
            var currentAction = " ";

            if (currentRouteData != null)
            {
                if (currentRouteData.Values["controller"] != null && !String.IsNullOrEmpty(currentRouteData.Values["controller"].ToString()))
                {
                    currentController = currentRouteData.Values["controller"].ToString();
                }

                if (currentRouteData.Values["action"] != null && !String.IsNullOrEmpty(currentRouteData.Values["action"].ToString()))
                {
                    currentAction = currentRouteData.Values["action"].ToString();
                }
            }

            var ex = Server.GetLastError();

            var controller = new ErrorController();
            var routeData = new RouteData();
            var action = "Index";

            if (ex is HttpException)
            {
                var httpEx = ex as HttpException;

                switch (httpEx.GetHttpCode())
                {
                    case 404:
                        action = "NotFound";
                        break;

                    // others if any
                    case 401:
                    case 403:
                        action = "NoAuthor";
                        break;

                    default:
                        action = "Index";
                        break;
                }
            }

            httpContext.ClearError();
            httpContext.Response.Clear();
            httpContext.Response.StatusCode = ex is HttpException ? ((HttpException)ex).GetHttpCode() : 500;
            httpContext.Response.TrySkipIisCustomErrors = true;
            routeData.Values["controller"] = "Error";
            routeData.Values["action"] = action;

            controller.ViewData.Model = new HandleErrorInfo(ex, currentController, currentAction);
            ((IController)controller).Execute(new RequestContext(new HttpContextWrapper(httpContext), routeData));
        }
        public void Index_returns_the_error_view()
        {
            var target = new ErrorController().WithContext(false);

            var result = target.Index() as ViewResult;

            Assert.NotNull(result);
            Assert.Equal("Error", result.ViewName);
        }
示例#3
0
        protected void Application_Error(object sender, EventArgs e)
        {
            var httpContext = ((MvcApplication)sender).Context;

            if (!httpContext.IsCustomErrorEnabled)
            {
                return;
            }

            var exception = Server.GetLastError();
            Server.ClearError();
            var httpException = exception as HttpException;
            var controller = new ErrorController();

            var routeData = new RouteData();
            routeData.Values["controller"] = "Error";
            routeData.Values["action"] = "Index";

            if (httpException != null)
            {
                if (httpException.GetHttpCode() == 404 || httpException.GetHttpCode() == 400)
                {
                    routeData.Values["action"] = "NotFound";
                }
                Response.StatusCode = httpException.GetHttpCode();
            }
            else
            {
                Response.StatusCode = 500;

            }

            // Avoid IIS7 getting involved
            Response.TrySkipIisCustomErrors = true;

            // Execute the error controller
            if (routeData.Values["action"].ToString() == "Index")
            {
                ErrorViewModel errorVM = new ErrorViewModel(true);
                errorVM.ErrorID = Guid.NewGuid().ToString();
                controller.ViewData.Model = errorVM;
                //Logging goes here
                //var logger = new Log4netLogger("GlobalAsaxLog");
                ILogger logger = UnityConfigurator.GetConfiguredContainer().Resolve<ILogger>(new ParameterOverride("name", "GlobalAsaxExpLog"));

                logger.Error("GlobalAsax Exception Log [ " + errorVM.ErrorID + " ]", exception);
            }
            httpContext.Response.ContentType = "text/html";

            ((IController)controller).Execute(new RequestContext(new HttpContextWrapper(httpContext), routeData));
        }
        public void Index_sets_status_code_to_500_if_parameter_is_not_a_valid_HTTP_status()
        {
            var mockResponse = new Mock<HttpResponseBase>();

            mockResponse.SetupProperty(x => x.StatusCode, 200);

            var target = new ErrorController().WithContext(false, mockResponse: mockResponse);

            var result = target.Index(0) as ViewResult;

            Assert.NotNull(result);
            Assert.Equal("Error", result.ViewName);
            Assert.Equal(500, mockResponse.Object.StatusCode);
        }
        public void Put_Returns_HttpStatusCodeResult_403_Test()
        {
            // Arrange
            Mock<IErrorService> service = new Mock<IErrorService>();

            service.Setup(x => x.ValidateToken(It.IsAny<string>())).Returns(false);

            ErrorController controller = new ErrorController(new TestableElmahErrorHelper(), service.Object);

            // Act
            HttpStatusCodeResult result = controller.Log("", null) as HttpStatusCodeResult;

            // Assert
            Assert.Equal(403, result.StatusCode);
        }
示例#6
0
        protected void Application_Error(object sender, EventArgs e)
        {
            //return;
            var exception = Server.GetLastError();
            Response.Clear();

            var httpException = exception as HttpException;

            var routeData = new RouteData();
            routeData.Values.Add("controller", "Error");

            if (httpException == null)
            {
                routeData.Values.Add("action", "Index");
            }
            else //It's an Http Exception, Let's handle it.
            {
                switch (httpException.GetHttpCode())
                {
                    case 404:
                        // Page not found.
                        routeData.Values.Add("action", "HttpError404");
                        break;
                    case 505:
                        // Server error.
                        routeData.Values.Add("action", "HttpError505");
                        break;

                        // Here you can handle Views to other error codes.
                        // I choose a General error template
                    default:
                        routeData.Values.Add("action", "Index");
                        break;
                }
            }

            // Pass exception details to the target error View.
            routeData.Values.Add("error", exception);

            // Clear the error on server.
            Server.ClearError();

            // Call target Controller and pass the routeData.
            IController errorController = new ErrorController();
            errorController.Execute(new RequestContext(
                                        new HttpContextWrapper(Context), routeData));
        }
示例#7
0
        public void Start()
        {
            // Load data file
            _ec = ErrorController.Instance;
            _dc = DataController.Instance;

            saveInfo = new SaveInfo();

            if (!_dc.LoadData<SaveInfo>(ref saveInfo))
            {
                _dc.AddData(saveInfo);
                _dc.SaveAll();
            }

            // Check window elements

            if (ActionButtons.Length != SaveInfo.SavesCount)
            {
                _ec.PushError("Bad number of load buttons.", this, ErrorType.Error, true);
                return;
            }

            // Disable control buttons

            StartButton.GetComponent<Button>().interactable = false;

            DeleteButton.GetComponent<Button>().interactable = false;
            DeleteButton.GetComponentInChildren<Text>().text = _deleteButtonText;
            DeleteButton.GetComponent<Button>().onClick.AddListener(() => DeleteGame());

            // Set actions to buttons

            for (int i = 0; i < ActionButtons.Length; i++)
            {
                Button button = ActionButtons[i].GetComponent<Button>();
                int index = i;

                if (button == null)
                {
                    _ec.PushError("Bad element in action buttons list.", this, ErrorType.Error, true);
                    return;
                }

                button.onClick.AddListener(() => ActionButtonClick(index));
                button.GetComponentInChildren<Text>().text = saveInfo.Info[i].IsNewGame ? "Start new game" : saveInfo.Info[i].Name;
            }
        }
示例#8
0
        private void ExecuteErrorController(HttpContext httpContext, HttpException exception)
        {
            var routeData = new RouteData();

            routeData.Values["controller"] = "Error";

            if (exception != null && exception.GetHttpCode() == (int)HttpStatusCode.NotFound)
            {
                routeData.Values["action"] = "NotFound";
            }
            else
            {
                routeData.Values["action"] = "InternalServerError";
            }

            using (Controller controller = new ErrorController())
            {
                @IController controller1 = ((IController)controller);
                controller1.Execute(new RequestContext(new HttpContextWrapper(httpContext), routeData));
            }
        }
        public void ErrorsOtherErrors()
        {
            // setup
            var httpContext   = new DefaultHttpContext();
            var actionContext = new ActionContext(
                httpContext,
                new RouteData(),
                new Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor());

            var controller        = new ErrorController();
            var controllerContext = new ControllerContext(actionContext);

            controllerContext.HttpContext.Response.StatusCode = 500;
            controller.ControllerContext = controllerContext;

            // action
            var result = controller.Errors() as ViewResult;

            // assert
            Assert.IsType(typeof(ViewResult), result);
        }
示例#10
0
        protected void Application_PostRequestHandlerExecute()
        {
            // error
            if (new int[] { 403, 404, 500 }.Contains(Context.Response.StatusCode) && !Request.Url.AbsolutePath.StartsWith("/rest/"))
            {
                Response.Clear();

                var rd = new RouteData();
                rd.DataTokens["area"]   = "AreaName"; // In case controller is in another area
                rd.Values["controller"] = "Error";

                switch (Context.Response.StatusCode)
                {
                case 403:
                    rd.Values["action"] = "UserNotAuthorized";
                    break;

                case 404:
                    rd.Values["action"] = "PageNotFound";
                    break;

                case 500:
                    rd.Values["action"] = "InternalServerError";
                    break;
                }
                //Act as 400 and not 500 if api call has failed
                if (Context.Response.StatusCode == 500 && Context.Request.Path.Contains("/rest/"))
                {
                    Context.Response.StatusCode = 400;
                    byte[] bytes = System.Text.Encoding.UTF8.GetBytes("Bad request");
                    using (var stream = Context.Response.OutputStream)
                        stream.Write(bytes, 0, bytes.Length);
                }
                else
                {
                    IController c = new ErrorController();
                    c.Execute(new RequestContext(new HttpContextWrapper(Context), rd));
                }
            }
        }
示例#11
0
        private void ExecuteErrorController(HttpContext httpContext, HttpException exception)
        {
            var routeData = new RouteData();

            routeData.Values["controller"] = "Error";

            if (exception != null && exception.GetHttpCode() == (int)HttpStatusCode.NotFound)
            {
                routeData.Values["action"] = "NotFound";
            }
            else if (exception != null && exception.GetHttpCode() == (int)HttpStatusCode.ExpectationFailed)
            {
                routeData.Values["action"] = "InternalServerError";
            }
            else if (exception != null && exception.GetHttpCode() == (int)HttpStatusCode.InternalServerError)
            {
                routeData.Values["action"] = "InternalServerError";
            }
            else if (exception != null && exception.GetHttpCode() == (int)HttpStatusCode.RequestTimeout)
            {
                routeData.Values["action"] = "InternalServerError";
            }
            else if (exception != null && exception.GetHttpCode() == (int)HttpStatusCode.Forbidden)
            {
                routeData.Values["action"] = "InternalServerError";
            }
            else if (exception.GetHttpCode() == (int)HttpStatusCode.Unauthorized)
            {
                routeData.Values["action"] = "Unauthorized";
            }
            else
            {
                routeData.Values["action"] = "InternalServerError";
            }

            using (Controller controller = new ErrorController())
            {
                ((IController)controller).Execute(new RequestContext(new HttpContextWrapper(httpContext), routeData));
            }
        }
示例#12
0
        public static void HandleError(HttpContext context, Exception exception)
        {
            var httpException = exception as HttpException;

            context.Response.Clear();

            var routeData = new RouteData();

            routeData.Values["controller"] = "Error";
            routeData.Values["action"]     = "Unknown";
            routeData.Values["exception"]  = exception;

            context.Response.StatusCode = 500;

            if (httpException != null)
            {
                context.Response.StatusCode = httpException.GetHttpCode();

                switch (context.Response.StatusCode)
                {
                case 403:
                    routeData.Values["action"] = "Forbidden";
                    break;

                case 404:
                    routeData.Values["action"] = "NotFound";
                    break;
                }
            }

            IController errorsController = new ErrorController();

            var rc = new RequestContext(new HttpContextWrapper(context), routeData);

            try {
                errorsController.Execute(rc);
            } catch (Exception e) {
                context.Response.Write(string.Format("Error rendering error page: {0}<br><br>{1}", e.Message, e.StackTrace));
            }
        }
示例#13
0
        protected void Application_Error(object sender, EventArgs e)
        {
            var httpContext       = ((MvcApplication)sender).Context;
            var currentController = string.Empty;
            var currentAction     = string.Empty;
            var currentRouteData  = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));
            var ex = Server.GetLastError();

            if (currentRouteData != null)
            {
                if (!string.IsNullOrEmpty(currentRouteData.Values["controller"]?.ToString()))
                {
                    currentController = currentRouteData.Values["controller"].ToString();
                }

                if (!string.IsNullOrEmpty(currentRouteData.Values["action"]?.ToString()))
                {
                    currentAction = currentRouteData.Values["action"].ToString();
                }
                var errorMsg =
                    $"An unhandled exception occurs in the controller:{currentController}, action:{currentAction}";
                _log.Error(errorMsg + "\n" + ex);
            }

            var controller = new ErrorController();
            var routeData  = new RouteData();

            routeData.Values.Add("controller", "Error");
            routeData.Values.Add("action", "Index");

            var httpException = ex as HttpException;

            routeData.Values["errorCode"] = httpException?.GetHttpCode();

            httpContext.ClearError();
            Server.ClearError();
            httpContext.Response.Clear();
            Response.ContentType = "text/html";
            ((IController)controller).Execute(new System.Web.Routing.RequestContext(new HttpContextWrapper(httpContext), routeData));
        }
示例#14
0
        private void ShowCustomErrorPage(Exception exception)
        {
            var httpException = exception as HttpException ?? new HttpException(500, "Internal Server Error", exception);

            Response.Clear();
            var routeData = new RouteData();

            routeData.Values.Add("controller", "Error");
            routeData.Values.Add("fromAppErrorEvent", true);

            switch (httpException.GetHttpCode())
            {
            case 401:
                routeData.Values.Add("action", "HttpError401");
                break;

            case 403:
                routeData.Values.Add("action", "HttpError403");
                break;

            case 404:
                routeData.Values.Add("action", "HttpError404");
                break;

            case 500:
                routeData.Values.Add("action", "HttpError500");
                break;

            default:
                routeData.Values.Add("action", "GeneralError");
                routeData.Values.Add("httpStatusCode", httpException.GetHttpCode());
                break;
            }

            Server.ClearError();

            IController controller = new ErrorController();

            controller.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
        }
示例#15
0
        protected void Application_Error(object sender, EventArgs e)
        {
            var ex = Server.GetLastError();

            if (ex == null)
            {
                return;
            }

            int    httpStatus;
            string errorControllerAction;

            Helpers.GetHttpStatus(ex, out httpStatus);

            switch (httpStatus)
            {
            case 404: errorControllerAction = "NotFound"; break;

            default:
                Helpers.LogWebError(Constants.ProductName, Constants.LayerName, ex);
                errorControllerAction = "Index"; break;
            }

            var httpContext = ((MvcApplication)sender).Context;

            httpContext.ClearError();
            httpContext.Response.Clear();
            httpContext.Response.StatusCode             = httpStatus;
            httpContext.Response.TrySkipIisCustomErrors = true;

            var routeData = new RouteData();

            routeData.Values["controller"] = "Error";
            routeData.Values["action"]     = errorControllerAction;

            var controller = new ErrorController();

            ((IController)controller)
            .Execute(new RequestContext(new HttpContextWrapper(httpContext), routeData));
        }
示例#16
0
 // Invoked by Elmah. http://stackoverflow.com/a/2049364/507339
 void ErrorLog_Logged(object sender, ErrorLoggedEventArgs e)
 {
     Trace.TraceError("Logged ELMAH error with ID: " + e.Entry.Id);
     if (e.Entry.Error.StatusCode == 0 || e.Entry.Error.StatusCode == 500)
     {
         IController errorController = new ErrorController();
         var         routeData       = new RouteData();
         routeData.Values["action"]     = "LoggedElmahError";
         routeData.Values["controller"] = "Error";
         routeData.Values["error"]      = e.Entry;
         try
         {
             // Set the tournament Id for convenience. MAkes the navigation menu still work in context of a tournament
             routeData.Values["tournamentId"] =
                 HttpContext.Current.Request.RequestContext.RouteData.Values["tournamentId"];
         }
         catch (Exception) { }
         errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
         Response.StatusCode = 500;
         Response.End();
     }
 }
示例#17
0
        protected void Application_EndRequest()
        {
            //Show 404 layoutet page
            if (Context.Response.StatusCode == 404)
            {
                string systemInfo = "404 not founf";
                systemInfo += "> > > Requested URI: " + HttpContext.Current.Request.Url.AbsoluteUri.ToString();
                systemInfo += "\n\r> > > Referrer: " + HttpContext.Current.Request.UrlReferrer;
                systemInfo += "\n\r> > > Authenticated: " + HttpContext.Current.User.Identity.IsAuthenticated;
                systemInfo += "\n\r> > >▶ UserName: "******"area"]   = ""; // In case controller is in another area
                rd.Values["controller"] = "Error";
                rd.Values["action"]     = "PageNotFound";

                IController c = new ErrorController();
                c.Execute(new RequestContext(new HttpContextWrapper(Context), rd));
            }
        }
示例#18
0
        public void Init()
        {
            var errors = new List <ErrorLog>
            {
                new ErrorLog {
                    Application = "CATS", Host = "http://123.234.214", Message = "Message1", ErrorLogID = Guid.NewGuid(), Sequence = 12, Source = "", PartitionID = 1, StatusCode = 404, TimeUtc = DateTime.Now, Type = "", User = "******"
                },
                new ErrorLog {
                    Application = "CATS", Host = "http://123.234.214", Message = "Message2", ErrorLogID = Guid.NewGuid(), Sequence = 11, Source = "", PartitionID = 1, StatusCode = 500, TimeUtc = DateTime.Now, Type = "", User = "******"
                },
                new ErrorLog {
                    Application = "HUBS", Host = "http://111.234.214", Message = "Message3", ErrorLogID = Guid.NewGuid(), Sequence = 14, Source = "", PartitionID = 1, StatusCode = 500, TimeUtc = DateTime.Now, Type = "", User = "******"
                },
                new ErrorLog {
                    Application = "HUBS", Host = "http://111.234.214", Message = "Message4", ErrorLogID = Guid.NewGuid(), Sequence = 10, Source = "", PartitionID = 1, StatusCode = 404, TimeUtc = DateTime.Now, Type = "", User = "******"
                },
            };
            var errorService = new Mock <IErrorLogService>();

            errorService.Setup(t => t.GetAllErrorLog()).Returns(errors);
            _errorController = new ErrorController(errorService.Object);
        }
示例#19
0
        protected void Application_Error()
        {
            var ex = Server.GetLastError();

            Response.Clear();

            HttpException httpException = ex as HttpException;

            if (httpException != null)
            {
                RouteData routeData = new RouteData();
                routeData.Values.Add("controller", "Error");
                switch (httpException.GetHttpCode())
                {
                case 404:
                    // page not found
                    routeData.Values.Add("action", "Index");
                    break;

                case 500:
                    // server error
                    routeData.Values.Add("action", "Index");
                    break;

                default:
                    routeData.Values.Add("action", "Index");
                    break;
                }

                routeData.Values.Add("error", ex);
                // clear error on server
                Server.ClearError();
                var appError = SanitizarError(httpException);
                routeData.Values.Add("appError", appError);
                IController ctl = new ErrorController();
                ctl.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
                // at this point how to properly pass route data to error controller?
            }
        }
        public void GetItems_ShouldReturnOkResult()
        {
            //Arrange
            var mockService = new Mock <IErrorService>();

            mockService.Setup(x => x.List(null, null, false))
            .Returns(errors);

            var expected = errors;

            var controller = new ErrorController(mockService.Object, mapper);

            //Act
            var contentResult = controller.List(null, null);

            //Assert
            Assert.IsType <OkObjectResult>(contentResult.Result);
            var actual = (contentResult.Result as OkObjectResult).Value as IEnumerable <ErrorDTO>;

            Assert.NotNull(actual);
            Assert.Equal(expected.Count, actual.Count());
        }
示例#21
0
    public override HttpActionDescriptor SelectAction(HttpControllerContext controllerContext)
    {
        HttpActionDescriptor descriptor = null;

        try
        {
            descriptor = base.SelectAction(controllerContext);
        }
        catch (HttpResponseException e)
        {
            var routeData = controllerContext.RouteData;
            routeData.Values.Clear();
            routeData.Values["action"]   = "Main";
            routeData.Values["code"]     = e.Response.StatusCode;
            routeData.Values["language"] = controllerContext.Request?.Headers?.AcceptLanguage?.FirstOrDefault()?.Value ?? "en";
            IHttpController httpController = new ErrorController();
            controllerContext.Controller           = httpController;
            controllerContext.ControllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, "Error", httpController.GetType());
            descriptor = base.SelectAction(controllerContext);
        }
        return(descriptor);
    }
示例#22
0
        protected void Application_Error()
        {
            Exception exception = Server.GetLastError();

            Response.Clear();

            if (exception is HttpException && ((HttpException)exception).WebEventCode == 3004)
            {
                Server.ClearError();
                Response.Redirect("Upload?FileTooLarge=", true);
                return;
            }

            RouteData routeData = new RouteData();

            routeData.Values.Add("controller", "Error");

            routeData.Values.Add("action", "Index");

            routeData.Values.Add("error", exception);

            Server.ClearError();

            IController errorController = new ErrorController();

            try
            {
                errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
            }
            finally
            {
                ((ErrorController)errorController).Dispose();
            }

            if (Response.IsClientConnected)
            {
                Response.End();
            }
        }
示例#23
0
        protected void Application_EndRequest()
        {
            try
            {
                if (Context.Response.StatusCode == 404)
                {
                    Response.Clear();

                    var rd = new RouteData();
                    rd.DataTokens["area"]   = "AreaName"; // In case controller is in another area
                    rd.Values["controller"] = "Errors";
                    rd.Values["action"]     = "NotFound";

                    IController c = new ErrorController();
                    c.Execute(new RequestContext(new HttpContextWrapper(Context), rd));
                }
            }catch (Exception ex)
            {
                Errores err = new Errores();
                err.SetError(ex, "Application_EndRequest");
            }
        }
示例#24
0
        //protected void Application_EndRequest(Object sender, EventArgs e)
        //{
        //    IoCConfig.GetInstance<IUow>().Commit();
        //}

        protected void Application_Error(object sender, EventArgs e)
        {
            if (AppSettings.ShowErrorPage == true)
            {
                Exception lastError = Server.GetLastError();
                Server.ClearError();

                int statusCode = 0;

                if (lastError.GetType() == typeof(HttpException))
                {
                    statusCode = ((HttpException)lastError).GetHttpCode();
                }
                else
                {
                    // Not an HTTP related error so this is a problem in our code, set status to
                    // 500 (internal server error)
                    statusCode = 500;
                }

                HttpContextWrapper contextWrapper = new HttpContextWrapper(this.Context);

                RouteData routeData = new RouteData();
                routeData.Values.Add("controller", "Error");
                routeData.Values.Add("action", "Index");
                routeData.Values.Add("otherException", null);
                routeData.Values.Add("statusCode", statusCode);
                routeData.Values.Add("exception", lastError);
                routeData.Values.Add("message", lastError.Message);
                routeData.Values.Add("isAjaxRequet", contextWrapper.Request.IsAjaxRequest());

                IController controller = new ErrorController();

                RequestContext requestContext = new RequestContext(contextWrapper, routeData);

                controller.Execute(requestContext);
                Response.End();
            }
        }
示例#25
0
        public void Application_Error(Object sender, EventArgs e)
        {
            Exception ex = Server.GetLastError();

            Server.ClearError();

            if (ex != null)
            {
                int statusCode = 500;
                if (ex.GetType() == typeof(HttpException))
                {
                    statusCode = ((HttpException)ex).GetHttpCode();
                }

                //log and email error here; so we get full error

                //if(new HttpRequestWrapper(Context.Request).IsAjaxRequest())
                //{
                //    Context.Response.ContentType = "application/json";
                //    Context.Response.StatusCode = statusCode;
                //    Context.Response.Write(
                //        JsonConvert.SerializeObject(new { Message = ex.Message, StackTrace = ex.StackTrace })
                //        );
                //    Response.End();
                //    return;
                //}

                RouteData rd = new RouteData();
                rd.Values.Add("controller", "Error");
                rd.Values.Add("action", "Error");
                rd.Values.Add("exception", ex);
                rd.Values.Add("statuscode", statusCode);
                Session["_ERROR_"] = ex;
                Response.TrySkipIisCustomErrors = true;
                IController c = new ErrorController();
                c.Execute(new RequestContext(new HttpContextWrapper(Context), rd));
                Response.End();
            }
        }
 public bool ExistsDispatchProviderDocumentItem(int DispatchProviderDocumentItemId, out string errorMessage)
 {
     errorMessage = "";
     try
     {
         DispatchProviderDocumentItem obj = null;
         using (var context = new Entity())
         {
             obj = context.DispatchProviderDocumentItem.Where(r => r.DispatchProviderDocumentItemId != DispatchProviderDocumentItemId).FirstOrDefault();
             if (obj == null)
             {
                 return(false);
             }
             return(true);
         }
     }
     catch (Exception ex)
     {
         errorMessage = ErrorController.GetErrorMessage(ex);
         return(false);
     }
 }
示例#27
0
        public void ErrorControllerErrorActionReturnsSuccess()
        {
            // Arrange
            string expectedUrl     = $"/{ApplicationController.AlertPathName}/500";
            var    errorController = new ErrorController(fakeLogger)
            {
                ControllerContext = new ControllerContext()
                {
                    HttpContext = new DefaultHttpContext(),
                },
            };

            // Act
            var result = errorController.Error();

            // Assert
            var statusResult = Assert.IsType <RedirectResult>(result);

            statusResult.Url.Should().Be(expectedUrl);
            A.Equals(false, statusResult.Permanent);
            errorController.Dispose();
        }
        protected void Application_Error(object sender, EventArgs e)
        {
            Exception exception = Server.GetLastError();

            Response.Clear();

            HttpException httpException = exception as HttpException;
            RouteData     routeData     = new RouteData();

            routeData.Values.Add("controller", "Error");

            if (httpException != null)
            {
                switch (httpException.GetHttpCode())
                {
                case 404:
                    // page not found
                    routeData.Values.Add("action", "HttpError404");
                    break;

                case 500:
                    // server error
                    routeData.Values.Add("action", "HttpError500");
                    break;

                default:
                    routeData.Values.Add("action", "httpErrorGeneral");
                    break;
                }

                // clear error on server
                Server.ClearError();
                Response.TrySkipIisCustomErrors = true;
            }

            IController errorController = new ErrorController();

            errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
        }
        protected void Application_Error(object sender, EventArgs e)
        {
            Response.Clear();
            Exception     exception     = Server.GetLastError();
            HttpException httpException = exception as HttpException;
            RouteData     routeData     = new RouteData();

            routeData.Values.Add("controller", "Error");
            if (exception == null)
            {
                routeData.Values.Add("action", "Index");
            }
            else if (httpException == null)
            {
                routeData.Values.Add("action", "Index");
            }
            else
            {
                switch (httpException.GetHttpCode())
                {
                case 404:
                    routeData.Values.Add("action", "HttpError404");
                    break;

                case 500:
                    routeData.Values.Add("action", "HttpError500");
                    break;

                default:
                    routeData.Values.Add("action", "General");
                    break;
                }
            }
            routeData.Values.Add("error", exception.Message);
            Server.ClearError();
            IController errorController = new ErrorController();

            errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
        }
        public void SetupController()
        {
            response = new Mock <HttpResponseBase>();
            response.SetupProperty(r => r.StatusCode);

            var context = new Mock <HttpContextBase>();

            context.Setup(c => c.Response).Returns(response.Object);

            var routeData = new RouteData();

            routeData.Values["controller"] = "AController";
            routeData.Values["action"]     = "AnAction";

            var reqCtx = new RequestContext(context.Object, routeData);

            controller = new ErrorController();

            var ctlCtx = new ControllerContext(reqCtx, controller);

            controller.ControllerContext = ctlCtx;
        }
示例#31
0
        protected void Application_Error(object sender, EventArgs e)
        {
            // Grab information about the last error occurred
            var exception = Server.GetLastError();

            // Clear the response stream
            var httpContext = ((HttpApplication)sender).Context;

            httpContext.Response.Clear();
            httpContext.ClearError();
            httpContext.Response.TrySkipIisCustomErrors = true;
            var routeData = new RouteData();

            routeData.Values["controller"] = "error";
            routeData.Values["action"]     = "index";
            routeData.Values["exception"]  = exception;
            using (var controller = new ErrorController())
            {
                ((IController)controller).Execute(
                    new RequestContext(new HttpContextWrapper(httpContext), routeData));
            }
        }
示例#32
0
        private void ShowCustomErrorPage(Exception exception)
        {
            var httpException = exception as HttpException ?? new HttpException(500, "Internal Server Error", exception);

            Response.Clear();
            var routeData = new RouteData();
            routeData.Values.Add("controller", "Error");
            routeData.Values.Add("fromAppErrorEvent", true);

            switch (httpException.GetHttpCode())
            {
                case 401:
                    routeData.Values.Add("action", "HttpError401");
                    break;

                case 403:
                    routeData.Values.Add("action", "HttpError403");
                    break;

                case 404:
                    routeData.Values.Add("action", "HttpError404");
                    break;

                case 500:
                    routeData.Values.Add("action", "HttpError500");
                    break;

                default:
                    routeData.Values.Add("action", "GeneralError");
                    routeData.Values.Add("httpStatusCode", httpException.GetHttpCode());
                    break;
            }

            Server.ClearError();

            IController controller = new ErrorController();
            controller.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
        }
        public DispatchProviderDocumentItem Save(DispatchProviderDocumentItem objSource, out string errorMessage)
        {
            errorMessage = "";
            try
            {
                using (var context = new Entity())
                {
                    CommonEnums.PageActionEnum action = new CommonEnums.PageActionEnum();

                    using (TransactionScope transaction = new TransactionScope())
                    {
                        DispatchProviderDocumentItem row = context.DispatchProviderDocumentItem.Where(r => r.DispatchProviderDocumentItemId == objSource.DispatchProviderDocumentItemId).FirstOrDefault();
                        if (row == null)
                        {
                            row = new DispatchProviderDocumentItem();
                            Copy(objSource, ref row);
                            context.DispatchProviderDocumentItem.Add(row);
                            action = CommonEnums.PageActionEnum.Create;
                        }
                        else
                        {
                            Copy(objSource, ref row);
                            action = CommonEnums.PageActionEnum.Update;
                        }
                        context.SaveChanges();
                        //string description = "Se ha añadido un nuevo item a la guia con id:"+row.DispatchProviderDocumentId+", el id del item es:" + row.DispatchProviderDocumentItemId;
                        //new DcPageLog().Save(action, description);
                        transaction.Complete();
                        return(row);
                    }
                }
            }
            catch (Exception ex)
            {
                errorMessage = ErrorController.GetErrorMessage(ex);
                return(null);
            }
        }
示例#34
0
        protected void Application_Error(object sender, EventArgs e)
        {
            Exception     exception     = Server.GetLastError();
            HttpException httpException = exception as HttpException;
            RouteData     data          = new RouteData();

            data.Values.Add("controller", "Error");
            if (httpException == null)
            {
                data.Values.Add("action", "Index");
            }
            else
            {
                switch (httpException.GetHttpCode())
                {
                case 401:
                    data.Values.Add("action", "http401");
                    break;

                case 404:
                    data.Values.Add("action", "http404");
                    break;

                case 405:
                    data.Values.Add("action", "http405");
                    break;

                default:
                    data.Values.Add("action", "general");
                    break;
                }
            }
            Server.ClearError();
            Response.TrySkipIisCustomErrors = true;
            IController error = new ErrorController();

            error.Execute(new RequestContext(new HttpContextWrapper(Context), data));
        }
示例#35
0
        protected void Application_Error(Object sender, EventArgs e)
        {
            Exception     exception     = Server.GetLastError();
            HttpException httpException = exception as HttpException;
            //ApiException apiException = exception as ApiException;

            var isNotFound = false;

            //if (apiException != null)
            //{
            //    isNotFound = apiException.ErrorCode == 404;
            //}
            if (httpException != null)
            {
                isNotFound = httpException.GetHttpCode() == 404;
            }

            if (isNotFound)
            {
                RouteData routeData = new RouteData();
                routeData.Values.Add("controller", "Error");
                routeData.Values.Add("action", "Http404");
                // Clear the error, otherwise, we will always get the default error page.
                Server.ClearError();
                // Call the controller with the route
                IController errorController = new ErrorController();
                errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
            }

            //Log exception
            var log = LogManager.GetCurrentClassLogger();

            log.Error(exception);

            //Response.Clear();
            //Server.ClearError();
            //Response.TrySkipIisCustomErrors = true;
        }
示例#36
0
        protected void Application_Error(object sender, EventArgs e)
        {
            try
            {
                var exception = Server.GetLastError();

                LogExtension.LogError("Application Error - Server's Last Error", exception,
                                      MethodBase.GetCurrentMethod());

                var httpException = exception as HttpException;

                var httpStatusCode = (exception is HttpException) ? httpException.GetHttpCode() : 0;

                var routeData = new RouteData();

                if (httpStatusCode == 404)
                {
                    routeData.Values.Add("controller", "Error");
                    routeData.Values.Add("action", "HttpError404");
                    LogExtension.LogError("Application Error 404", httpException, MethodBase.GetCurrentMethod());
                }
                else
                {
                    routeData.Values.Add("controller", "Error");
                    routeData.Values.Add("action", "HttpError500");
                    LogExtension.LogError("Application Error 500", httpException, MethodBase.GetCurrentMethod());
                }

                Server.ClearError();
                Response.Clear();
                IController errorController = new ErrorController();
                errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
            }
            catch (Exception ex)
            {
                LogExtension.LogError("Error in Application Error ", ex, MethodBase.GetCurrentMethod());
            }
        }
        void Application_Error(object sender, EventArgs e)
        {
            Exception exception = Server.GetLastError();

            Server.ClearError();

            RouteData routeData = new RouteData();

            routeData.Values.Add("controller", "Error");
            routeData.Values.Add("exception", exception);
            var statusCode = ((HttpException)exception).GetHttpCode();

            if (exception.GetType() == typeof(HttpException))
            {
                string action;
                switch (statusCode)
                {
                case 404:
                    // page not found
                    action = "HttpError404";
                    break;

                case 500:
                    // server error
                    action = "HttpError500";
                    break;

                default:
                    action = "General";
                    break;
                }
                routeData.Values.Add("statusCode", statusCode);
                routeData.Values.Add("action", action);
                IController controller = new ErrorController();
                controller.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
                Response.End();
            }
        }
示例#38
0
        protected void Application_Error()
        {
            var exception     = Server.GetLastError();
            var httpException = exception as HttpException;

            Response.Clear();
            Server.ClearError();
            var routeData = new RouteData();

            routeData.Values["controller"] = "Errors";
            routeData.Values["action"]     = "General";
            routeData.Values["exception"]  = exception;
            Response.StatusCode            = 500;
            if (httpException != null)
            {
                Response.StatusCode = httpException.GetHttpCode();
                switch (Response.StatusCode)
                {
                case 403:
                    routeData.Values["action"] = "Http403";
                    break;

                case 404:
                    routeData.Values["action"] = "Http404";
                    break;

                case 500:
                    routeData.Values["action"] = "Http500";
                    break;
                }
            }
            Response.TrySkipIisCustomErrors = true;
            IController errorController = new ErrorController();
            var         wrapper         = new HttpContextWrapper(Context);
            var         rc = new RequestContext(wrapper, routeData);

            errorController.Execute(rc);
        }
        public void Log_Returns_HttpStatusCodeResult_200_Test()
        {
            // Arrange
            TestableElmahErrorHelper helper = new TestableElmahErrorHelper();
            Mock<IErrorService> service = new Mock<IErrorService>();

            service.Setup(x => x.ValidateToken(It.IsAny<string>())).Returns(true);
            service.Setup(x => x.ValidateErrorInfo(It.IsAny<ErrorInfo>())).Returns(true);

            ErrorController controller = new ErrorController(helper, service.Object);

            ErrorInfo info = new ErrorInfo(new Exception("Test-Exception"));

            string xml = Utility.SerializeXml(info);
            string error = Convert.ToBase64String(Encoding.UTF8.GetBytes(xml));

            // Act
            HttpStatusCodeResult result = controller.Log("Test-Token", error) as HttpStatusCodeResult;

            // Assert
            Assert.Equal(200, result.StatusCode);
            Assert.NotNull(helper.Error);
        }
示例#40
0
        private void ShowCustomErrorPage(Exception exception)
        {
            var httpException = exception as HttpException ?? new HttpException(500, "Internal Server Error", exception);

            exception.ToExceptionless()
                .Submit();

            this.SaveExceptionToDatabase(httpException);

            this.Response.Clear();

            var routeData = new RouteData();
            routeData.Values.Add("controller", "Error");
            routeData.Values.Add("fromAppErrorEvent", true);

            switch (httpException.GetHttpCode())
            {
                case 403:
                    routeData.Values.Add("action", "AccessDenied");
                    break;

                case 404:
                    routeData.Values.Add("action", "NotFound");
                    break;

                case 500:
                    routeData.Values.Add("action", "ServerError");
                    break;

                default:
                    routeData.Values.Add("action", "OtherHttpStatusCode");
                    routeData.Values.Add("httpStatusCode", httpException.GetHttpCode());
                    break;
            }

            this.Server.ClearError();
            this.Response.TrySkipIisCustomErrors = true;
            this.Response.Headers.Add("Content-Type", "text/html");
            IController controller = new ErrorController();
            controller.Execute(new RequestContext(new HttpContextWrapper(this.Context), routeData));
        }
示例#41
0
        protected void Application_Error()
        {
            var exception = Server.GetLastError();
            Server.ClearError();

            var routeData = new RouteData();
            routeData.Values.Add("controller", "Error");
            routeData.Values.Add("action", "Index");
            routeData.Values.Add("exception", exception);
            routeData.Values.Add("loggedExceptionGuid", Guid.NewGuid());
            routeData.Values.Add("statusCode",
                exception.GetType() == typeof(HttpException)
                    ? ((HttpException)exception).GetHttpCode()
                    : 500);

            // TODO: Add fail-safe exception logging here - maybe

            IController errorController = new ErrorController();
            errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
            Response.End();
        }
        /// <param name="request">The request from the GlobalAsax is behaves differently!</param>
        public static void HandlerApplication_Error(HttpRequest request, HttpContext context, bool isWebRequest)
        {
            if (Navigator.Manager == null || !Navigator.Manager.Initialized)
                return;

            Exception ex = CleanException(context.Server.GetLastError());
            context.Server.ClearError();

            context.Response.StatusCode = GetHttpError(ex);
            context.Response.TrySkipIisCustomErrors = true;

            HandleErrorInfo hei = new HandleErrorInfo(ex, "Global.asax", "Application_Error");

            if (LogException != null)
                LogException(hei);

            if (isWebRequest)
            {
                HttpContextBase contextBase = context.Request.RequestContext.HttpContext;

                IController controller = new ErrorController { Result = GetResult(contextBase, hei) }; 

                var rd = new RouteData
                { 
                    Values= 
                    {
                        { "Controller", "Error"},
                        { "Action", "Error"}
                    }
                };

                controller.Execute(new RequestContext(contextBase, rd));  
            }
        }
 /// <summary>
 /// Display an alert dialog with a summary of all failed tasks
 /// </summary>
 protected void Alert()
 {
     _controller.Invoke(delegate
         {
             if (getExceptions().size() == 1)
             {
                 BackgroundException failure =
                     getExceptions().get(0) as BackgroundException;
                 string footer = Preferences.instance().getProperty("website.help");
                 if (null != failure.getPath())
                 {
                     footer = Preferences.instance().getProperty("website.help") + "/" +
                              failure.getPath().getSession().getHost().getProtocol().
                                  getProvider();
                 }
                 DialogResult result =
                     _controller.WarningBox(failure.getReadableTitle(),
                                            failure.getMessage(),
                                            failure.getDetailedCauseMessage(),
                                            hasTranscript() ? getTranscript() : null,
                                            String.Format("{0}", Locale.localizedString("Try Again", "Alert")),
                                            true, footer);
                 Callback(result);
             }
             else
             {
                 ICollection<BackgroundException> backgroundExceptions =
                     Utils.ConvertFromJavaList<BackgroundException>(getExceptions());
                 ErrorController errorController =
                     new ErrorController(ObjectFactory.GetInstance<IErrorView>(),
                                         backgroundExceptions, getTranscript());
                 DialogResult result = errorController.View.ShowDialog(_controller.View);
                 Callback(result);
             }
         }, true);
 }
示例#44
0
        protected void Application_Error()
        {
            var exception = Server.GetLastError();

            // We still need to log everything
            ILogger log = LogManager.GetLogger();
            log.Error("Handling exception: ", exception);

            Response.Clear();
            Server.ClearError();

            var routeData = new RouteData();
            routeData.Values["controller"] = "Error";
            routeData.Values["action"] = "Error500";
            routeData.Values["exception"] = exception;
            Response.StatusCode = 500;
            Response.TrySkipIisCustomErrors = true;

            var httpException = exception as HttpException;
            if (httpException != null)
            {
                Response.StatusCode = httpException.GetHttpCode();
                switch (Response.StatusCode)
                {
                    //case 403:
                    //	routeData.Values["action"] = "Http403";
                    //	break;
                    case 404:
                        routeData.Values["action"] = "Error404";
                        break;
                }
            }

            IController errorsController = new ErrorController();
            var rc = new RequestContext(new HttpContextWrapper(Context), routeData);
            errorsController.Execute(rc);
        }
示例#45
0
 /// <summary>
 /// Displays a self contained error page without redirecting.
 /// Depends on ErrorController.ShowError() to exist
 /// </summary>
 /// <param name="title"></param>
 /// <param name="message"></param>
 /// <param name="redirectTo"></param>
 /// <returns></returns>
 protected internal ActionResult DisplayErrorPage(string title, string message, string redirectTo = null)
 {
     ErrorController controller = new ErrorController();
     controller.InitializeForced(ControllerContext.RequestContext);
     return controller.ShowError(title, message, redirectTo);
 }
        // Handles all application errors and calls for the right view on the errorcontroller http://stackoverflow.com/a/5229581/426840
        protected void Application_Error()
        {
            var exception = Server.GetLastError();
            var httpException = exception as HttpException;

            var logger = AutoFac.Container.Resolve<ILogger>();

            var logId = exception != null ?
                logger.Fatal(exception.Message, exception) :
                logger.Error("Unhandled error"); // This will probably never be called, but added to be sure

            // Don't execute error controller for custom error mesages when custom error is disabled
            if (!HttpContext.Current.IsCustomErrorEnabled) return;

            Response.Clear();
            Server.ClearError();

            Response.StatusCode = 500;

            // Avoid IIS messing with custome errors http://stackoverflow.com/a/1719474/426840
            // Also http://stackoverflow.com/a/2345742/426840 for web.config
            Response.TrySkipIisCustomErrors = true;

            if (httpException != null)
            {
                Response.StatusCode = httpException.GetHttpCode();
            }

            var routeData = new RouteData();
            routeData.Values["controller"] = "Error";
            routeData.Values["action"] = Response.StatusCode != 404 ? "Index" : "NotFound";
            routeData.Values["exception"] = exception;
            routeData.Values["logId"] = logId;

            IController errorsController = new ErrorController();

            var rc = new RequestContext(new HttpContextWrapper(Context), routeData);

            errorsController.Execute(rc);
        }