Example #1
0
        /// <summary>
        /// Failure callback.
        /// </summary>
        /// <param name="exception">Exception</param>
        /// <param name="eventMessage">EventMessage instance.</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        private async Task FailureCallback(Exception exception, EventMessage eventMessage)
        {
            int statusCode   = (int)HttpStatusCode.BadRequest;
            var responsebody = exception.ToString();

            if (exception is HttpException)
            {
                HttpException httpException = (HttpException)exception;
                statusCode   = httpException.GetHttpCode();
                responsebody = httpException.GetHtmlErrorMessage();
            }
            else if (exception is ErrorResponseException)
            {
                ErrorResponseException errorResponseException = (ErrorResponseException)exception;
                statusCode   = (int)errorResponseException.Response.StatusCode;
                responsebody = errorResponseException.Response.ToString();
            }

            this.logProvider.LogError($"Failed to send {eventMessage.MessageType} card.", exception, new Dictionary <string, string>
            {
                { "EventId", eventMessage.EventId },
                { "OccurrenceId", eventMessage.OccurrenceId },
                { "eventActivity", eventMessage.Activity.ToString() },
                { "LastAttemptStatusCode", statusCode.ToString() },
                { "LastAttemptTime", DateTime.UtcNow.ToString() },
            });

            await this.UpdateMessageSendResult(eventMessage.Id, statusCode, DateTime.Now, responsebody);
        }
Example #2
0
        public void Constructor2b_Deny_Unrestricted()
        {
            HttpException e = new HttpException("message", new Exception());

            e.GetHtmlErrorMessage(); // null for ms, non-null for mono
            Assert.AreEqual(500, e.GetHttpCode(), "HttpCode");
        }
Example #3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Error"/> class
        /// from a given <see cref="Exception"/> instance and
        /// <see cref="HttpContext"/> instance representing the HTTP
        /// context during the exception.
        /// </summary>
        public Error(Exception e, HttpContext context)
        {
            if (e == null)
            {
                throw new ArgumentNullException("e");
            }

            _exception = e;
            Exception baseException = e.GetBaseException();

            _hostName = Environment.MachineName;
            _typeName = baseException.GetType().FullName;
            _message  = baseException.Message;
            _source   = baseException.Source;
            _detail   = e.ToString();
            _user     = Thread.CurrentPrincipal.Identity.Name ?? "";
            _time     = DateTime.Now;

            HttpException httpException = e as HttpException;

            if (httpException != null)
            {
                _statusCode         = httpException.GetHttpCode();
                _webHostHtmlMessage = httpException.GetHtmlErrorMessage() ?? "";
            }

            if (context != null)
            {
                HttpRequest request = context.Request;
                _serverVariables = CopyCollection(request.ServerVariables);
                _queryString     = CopyCollection(request.QueryString);
                _form            = CopyCollection(request.Form);
                _cookies         = CopyCollection(request.Cookies);
            }
        }
Example #4
0
        public int SetErrorLog(HttpException exception, string userIp, string browser, string browserVersion)
        {
            objAppErrorSchema.ErrorCode      = exception.ErrorCode.ToString();
            objAppErrorSchema.Message        = exception.Message;
            objAppErrorSchema.Type           = exception.GetType().ToString();
            objAppErrorSchema.StackTrace     = exception.StackTrace;
            objAppErrorSchema.InnerException = Convert.ToString(exception.InnerException);
            objAppErrorSchema.HtmlError      = (exception.GetHtmlErrorMessage() == null) ? string.Empty : exception.GetHtmlErrorMessage();
            objAppErrorSchema.UserIp         = userIp;
            objAppErrorSchema.Browser        = browser;
            objAppErrorSchema.BrowserVersion = browserVersion;

            int exceptionId;

            try
            {
                exceptionId = objappErrorBL.SaveAppErrorDeatails(objAppErrorSchema);
            }
            catch (Exception ex)
            {
                exceptionId = -1;
                throw ex;
            }
            finally
            {
            }

            return(exceptionId);
        }
Example #5
0
        private static void LogHttpException(HttpException ex, HttpContext context, RouteData routeData, BaseController controller)
        {
            int    httpCode = ex.GetHttpCode();
            string message  = string.Empty;

            if (httpCode == 404)
            {
                LogFileNotFound(ex, context, routeData, controller);
                return;
            }
            if ((httpCode == 400) && (routeData != null))
            {
                //if 400 came from a controller, handle it in the bad request log, not system (error) log
                LogBadRequest(ex, context, routeData, controller);
                return;
            }

            message = "Http Exception " + httpCode + " " + ex.GetHtmlErrorMessage()
                      + "  \n-Message: " + ex.Message
                      + "  \n-Source: " + ex.Source
                      + "  \n-WebEventCode: " + ex.WebEventCode
                      + "  \n-ErrorCode: " + ex.ErrorCode
                      + "  \n-TargetSiteName: " + ex.TargetSite.Name
                      + "  \n-StackTrace: " + ex.StackTrace;

            LogException(message, ex, Models.SystemEventLevel.Error, context, routeData, controller);
        }
Example #6
0
 private Task HandleHttpException(IOwinContext context, HttpException httpException)
 {
     context.Response.StatusCode   = httpException.GetHttpCode();
     context.Response.ReasonPhrase = httpException.GetHtmlErrorMessage();
     _traceFilter.Trace(context, TraceLevel.Error, () => GetType().Name + " HttpException caught with status code " + context.Response.StatusCode);
     return(Task.Factory.StartNew(() => { }));
 }
Example #7
0
        void OnAuthorizeRequest(object sender, EventArgs args)
        {
            HttpApplication app     = (HttpApplication)sender;
            HttpContext     context = app.Context;

            if (context == null || context.SkipAuthorization)
            {
                return;
            }

            HttpRequest req = context.Request;

#if NET_2_0
            AuthorizationSection config = (AuthorizationSection)WebConfigurationManager.GetSection("system.web/authorization", req.Path, context);
#else
            AuthorizationConfig config = (AuthorizationConfig)context.GetConfig("system.web/authorization");
            if (config == null)
            {
                return;
            }
#endif
            if (!config.IsValidUser(context.User, req.HttpMethod))
            {
                HttpException e        = new HttpException(401, "Unauthorized");
                HttpResponse  response = context.Response;

                response.StatusCode = 401;
                response.Write(e.GetHtmlErrorMessage());
                app.CompleteRequest();
            }
        }
        static void SendEmail(HttpException exception, string appName, MailAddress from, MailAddress to)
        {
            Trace.TraceInformation("[RazorRenderExceptionHelper]: Preparing to send email to developer");
            string body = exception.GetHtmlErrorMessage();
            bool   html = true;

            if (string.IsNullOrWhiteSpace(body))
            {
                body = exception.ToString();
                html = false;
            }

            string subject = string.Format("Exception for app: {0}, at {1}", appName, DateTime.Now);

            EmailExtensions.SendEmail(from, to, subject, body, !html,
                                      (message, ex) =>
            {
                if (ex == null)
                {
                    Trace.TraceInformation("[RazorRenderExceptionHelper]: Email was sent to {0}",
                                           to);
                }
                else
                {
                    Trace.TraceError("[RazorRenderExceptionHelper]: Failed to send email. {0}", ex.Message);
                    LogEvent.Raise(exception.Message, exception.GetBaseException());
                }
            });
        }
Example #9
0
        /// <summary>
        /// 应用程序出错
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Application_Error(object sender, EventArgs e)
        {
            // 在出现未处理的错误时运行的代码
            Exception ex = Server.GetLastError().GetBaseException();

            Server.ClearError();
            if (ex.GetType() == typeof(HttpException))
            {
                HttpException httpEx = (HttpException)ex;
                LogHelper.LogErrorMsg(ex, "--------应用程序出错!--------" + httpEx.GetHtmlErrorMessage());
            }
            else
            {
                LogHelper.LogErrorMsg(ex, "--------应用程序出错!--------" + ex.StackTrace);
            }

            //ResponseMessage msg = new ResponseMessage(-1);
            //string errorMsg = ex.Message;
            //msg.message = errorMsg;
            //Context.Response.AddHeader("Content-type", "text/html;charset=UTF-8");

            //if (errorMsg.Contains("未找到"))
            //    Context.Response.StatusCode = (int)HttpStatusCode.NotFound;
            //else
            //    Context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
            //Context.Response.Write(msg.ToJson());
        }
Example #10
0
        /// <summary>
        /// Logs an exception to database (or file) and emails the developer
        /// </summary>
        /// <param name="ex">The Exception to log</param>
        public static void LogException(Exception ex)
        {
            Log log = new Log();

            log.Setup();
            log.Type       = "Exception";
            log.Message    = ex.Message;
            log.StackTrace = ex.StackTrace;

            try
            {
                HttpException httpException = ex as HttpException;
                log.HtmlMessage = httpException.GetHtmlErrorMessage();
            }
            catch { }

            try
            {
                log.LogToDatabase();
            }
            catch
            {
                // if unable to log to database, then log to file
                log.LogToFile();
            }

            // as this is an error, also send an email to the developer
            // 2013-10-07 removed as it clogs up inbox without being meaningful
            //log.LogToEmail();
        }
        public void ProcessRequest()
        {
            string error = null;

            _inUnhandledException = false;

            try
            {
                //System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace();
                //byte[] b = Encoding.GetBytes("Here's the trace: <br /><br />" + t.ToString());
                //_worker.Write(b, 0, b.Length);

                //AssertFileAccessible();
                HttpRuntime.ProcessRequest(this);
            }
            catch (HttpException ex)
            {
                _inUnhandledException = true;
                error = ex.GetHtmlErrorMessage();
            }
            catch (Exception ex)
            {
                _inUnhandledException = true;
                var hex = new HttpException(400, "Bad request", ex);
                error = hex.GetHtmlErrorMessage();
            }

            if (!_inUnhandledException)
            {
                return;
            }

            //error = "HELLLO FROM WebFormsWorkerRequest";

            if (error.Length == 0)
            {
                error = String.Format("<html><head><title>Runtime Error</title></head><body>An exception ocurred:<pre>{0}</pre></body></html>", "Unknown error");
            }

            try
            {
                SendStatus(400, "Bad request");
                SendUnknownResponseHeader("Connection", "close");
                SendUnknownResponseHeader("Date", DateTime.Now.ToUniversalTime().ToString("r"));

                Encoding enc = Encoding.UTF8;

                byte[] bytes = enc.GetBytes(error);

                SendUnknownResponseHeader("Content-Type", "text/html; charset=" + enc.WebName);
                SendUnknownResponseHeader("Content-Length", bytes.Length.ToString());
                SendResponseFromMemory(bytes, bytes.Length);
                FlushResponse(true);
            }
            catch (Exception)
            { // should "never" happen
                throw;
            }
        }
Example #12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Error"/> class
        /// from a given <see cref="Exception"/> instance and
        /// <see cref="HttpContext"/> instance representing the HTTP
        /// context during the exception.
        /// </summary>

        public Error(Exception e, HttpContextBase context)
        {
            if (e == null)
            {
                throw new ArgumentNullException("e");
            }

            _exception = e;
            Exception baseException = e.GetBaseException();

            //
            // Load the basic information.
            //

            _hostName = Environment.TryGetMachineName(context);
            _typeName = baseException.GetType().FullName;
            _message  = baseException.Message;
            _source   = baseException.Source;
            _detail   = e.ToString();
            _user     = Thread.CurrentPrincipal.Identity.Name ?? string.Empty;
            _time     = DateTime.Now;

            //
            // If this is an HTTP exception, then get the status code
            // and detailed HTML message provided by the host.
            //

            HttpException httpException = e as HttpException;

            if (httpException != null)
            {
                _statusCode         = httpException.GetHttpCode();
                _webHostHtmlMessage = httpException.GetHtmlErrorMessage() ?? string.Empty;
            }

            //
            // If the HTTP context is available, then capture the
            // collections that represent the state request as well as
            // the user.
            //

            if (context != null)
            {
                IPrincipal webUser = context.User;
                if (webUser != null &&
                    (webUser.Identity.Name ?? string.Empty).Length > 0)
                {
                    _user = webUser.Identity.Name;
                }

                HttpRequestBase request = context.Request;

                _serverVariables = CopyCollection(request.ServerVariables);
                _queryString     = CopyCollection(request.QueryString);
                _form            = CopyCollection(request.Form);
                _cookies         = CopyCollection(request.Cookies);
            }
        }
Example #13
0
        public void ProcessRequest()
        {
            string error = null;

            inUnhandledException = false;

            try {
                AssertFileAccessible();
                HttpRuntime.ProcessRequest(this);
            } catch (HttpException ex) {
                inUnhandledException = true;
                error = ex.GetHtmlErrorMessage();
            } catch (Exception ex) {
                inUnhandledException = true;
                HttpException hex = new HttpException(400, "Bad request", ex);
                if (hex != null)                 // just a precaution
                {
                    error = hex.GetHtmlErrorMessage();
                }
                else
                {
                    error = String.Format(defaultExceptionHtml, ex.Message);
                }
            }

            if (!inUnhandledException)
            {
                return;
            }

            if (error.Length == 0)
            {
                error = String.Format(defaultExceptionHtml, "Unknown error");
            }

            try {
                SendStatus(400, "Bad request");
                SendUnknownResponseHeader("Connection", "close");
                SendUnknownResponseHeader("Date", DateTime.Now.ToUniversalTime().ToString("r"));

                Encoding enc = Encoding.UTF8;
                if (enc == null)
                {
                    enc = Encoding.ASCII;
                }

                byte[] bytes = enc.GetBytes(error);

                SendUnknownResponseHeader("Content-Type", "text/html; charset=" + enc.WebName);
                SendUnknownResponseHeader("Content-Length", bytes.Length.ToString());
                SendResponseFromMemory(bytes, bytes.Length);
                FlushResponse(true);
            } catch (Exception ex) {             // should "never" happen
                throw ex;
            }
        }
        // Return true if we succeed
        private bool ParseHttpException(HttpException e)
        {
            int   i;
            Match match = null;

            String errorMessage = e.GetHtmlErrorMessage();

            if (errorMessage == null)
            {
                return(false);
            }

            // Use regular expressions to scrape the message output
            // for meaningful data. One problem: Some parts of the
            // output are optional, and any regular expression that
            // uses the ()? syntax doesn't pick it up. So, we have
            // to have all the different combinations of expressions,
            // and use each one in order.

            EnsureSearchExpressions();
            for (i = 0; i < _expressionCount; i++)
            {
                match = _searchExpressions[i].Match(errorMessage);
                if (match.Success)
                {
                    break;
                }
            }

            if (i == _expressionCount)
            {
                return(false);
            }

            this.Type        = TrimAndClean(match.Result("${title}"));
            this.Description = TrimAndClean(match.Result("${description}"));
            if (i <= 1)
            {
                // These expressions were able to match the miscellaneous
                // title/text section.
                this.MiscTitle = TrimAndClean(match.Result("${misctitle}"));
                this.MiscText  = TrimAndClean(match.Result("${misctext}"));
            }
            if (i == 0)
            {
                // This expression was able to match the file/line #
                // section.
                this.File       = TrimAndClean(match.Result("${file}"));
                this.LineNumber = TrimAndClean(match.Result("${linenumber}"));
            }

            return(true);
        }
Example #15
0
 private static string TryGetHtmlErrorMessage(HttpException e)
 {
     try
     {
         string message = e.GetHtmlErrorMessage();
         return(string.IsNullOrWhiteSpace(message) ? e.Message : message);
     }
     catch (SecurityException)
     {
     }
     return(e.Message);
 }
Example #16
0
        public CrudResponse handleHttpFourAndFiveHundredErrors(CrudResponse response, HttpException error, int id)
        {
            response.ChangedEntityId = id;

            Message message = new Message();

            message.DetailMessage = error.GetHtmlErrorMessage();
            message.Severity      = error.ErrorCode.ToString();
            message.Type          = error.GetType().ToString();

            response.Messages.Add(message);

            response.ErrorCode    = error.GetHttpCode().ToString();
            response.ErrorMessage = error.Message;
            return(response);
        }
        public void ProcessRequest()
        {
            string error = null;

            inUnhandledException = false;

            try {
                AssertFileAccessible();
                HttpRuntime.ProcessRequest(this);
            } catch (HttpException ex) {
                inUnhandledException = true;
                error = ex.GetHtmlErrorMessage();
            } catch (Exception ex) {
                inUnhandledException = true;
                var hex = new HttpException(400, "Bad request", ex);
                error = hex.GetHtmlErrorMessage();
            }

            if (!inUnhandledException)
            {
                return;
            }

            if (error.Length == 0)
            {
                error = String.Format(DEFAULT_EXCEPTION_HTML, "Unknown error");
            }

            try {
                SendStatus(400, "Bad request");
                SendUnknownResponseHeader("Connection", "close");
                SendUnknownResponseHeader("Date", DateTime.Now.ToUniversalTime().ToString("r"));

                Encoding enc = Encoding.UTF8;

                byte[] bytes = enc.GetBytes(error);

                SendUnknownResponseHeader("Content-Type", "text/html; charset=" + enc.WebName);
                SendUnknownResponseHeader("Content-Length", bytes.Length.ToString());
                SendResponseFromMemory(bytes, bytes.Length);
                FlushResponse(true);
            } catch (Exception ex) {             // should "never" happen
                Logger.Write(LogLevel.Error, "Error while processing a request: ");
                Logger.Write(ex);
                throw;
            }
        }
Example #18
0
 private void DealErroy()
 {
     HttpException erroy = new HttpException();
     string strCode = erroy.ErrorCode.ToString();
     string strMsg = erroy.Message;
     erroy.HelpLink = "sss";
     Response.Write("ErrorCode:" + strCode + "<br />");
     Response.Write("Message:" + strMsg + "<br />");
     Response.Write("HelpLink:" + erroy.HelpLink + "<br />");
     Response.Write("Source:" + erroy.Source + "<br />");
     Response.Write("TargetSite:" + erroy.TargetSite + "<br />");
     Response.Write("InnerException:" + erroy.InnerException + "<br />");
     Response.Write("StackTrace:" + erroy.StackTrace + "<br />");
     Response.Write("GetHtmlErrorMessage:" + erroy.GetHtmlErrorMessage() + "<br />");
     Response.Write("erroy.GetHttpCode().ToString():" + erroy.GetHttpCode().ToString() + "<br />");
     Response.Write("erroy.Data.ToString()::" + erroy.Data.ToString() + "<br />");
 }
Example #19
0
		void OnAuthorizeRequest (object sender, EventArgs args)
		{
			HttpApplication app = (HttpApplication) sender;
			HttpContext context = app.Context;
			if (context == null || context.SkipAuthorization)
				return;

			HttpRequest req = context.Request;
			AuthorizationSection config = (AuthorizationSection) WebConfigurationManager.GetSection ("system.web/authorization", req.Path, context);
			if (!config.IsValidUser (context.User, req.HttpMethod)) {
				HttpException e = new HttpException (401, "Unauthorized");
				HttpResponse response = context.Response;
				
				response.StatusCode = 401;
				response.Write (e.GetHtmlErrorMessage ());
				app.CompleteRequest ();
			}
		}
Example #20
0
        private static void writeUnauthorizedResponseHtml(HttpContext context)
        {
            // Let's try to get the ASP.NET runtime to give us the HTML for a
            // security exception. If we can't get this, then we'll write out
            // our own default message. A derived implementation may want to
            // also want to involve custom error messages for production
            // scenarios, which is not done here.

            HttpException error = new HttpException(401, null, new SecurityException());
            string        html  = error.GetHtmlErrorMessage() ?? string.Empty;

            if (html.Length == 0)
            {
                html = defaultUnauthorizedResponseHtml;
            }

            context.Response.Write(html);
        }
Example #21
0
        private static string GetErrorDescription(Exception exception)
        {
            HttpException httpEx;

            if (exception == null)
            {
                return("NO EXCEPTION");
            }
            if ((httpEx = exception as HttpException) != null)
            {
                return(httpEx.GetHtmlErrorMessage());
            }

            // Not an HTTP exception, so try a few hacks (ordered from bad to worse!) to get a nice error message.

            // Hack 1: wrap it in an HttpException.

            httpEx = new HttpException("Dummy HttpException created by the ServerError page.", exception);

            var html = httpEx.GetHtmlErrorMessage();

            if (html != null)
            {
                return(html);
            }

            // Hack 2: use Reflection to call internal framework methods.

            try
            {
                html = GetErrorDescriptionUsingReflection(httpEx);
            }
            catch (Exception)
            {
            }
            if (html != null)
            {
                return(html);
            }

            // Hack 3: get the string representation and HTML-encode it.

            return(HttpUtility.HtmlEncode(exception.ToString()));
        }
Example #22
0
        public static DbResult LogError(HttpException lastError, string page)
        {
            Exception err = lastError;

            if (lastError.InnerException != null)
            {
                err = lastError.InnerException;
            }
            var dao = new Dao();

            var errPage    = dao.FilterString(page);
            var errMsg     = dao.FilterString(err.Message);
            var errDetails = dao.FilterString(lastError.GetHtmlErrorMessage());

            var user = "******";
            var sql  = $@"EXEC proc_ErrorLogs @flag = 'i', @errorPage={errPage}, @errorMsg={errMsg}, @errorDetails={errDetails}, @user = {user}";

            var db = dao.ParseDbResult(sql);

            return(db);
        }
Example #23
0
        protected void Application_Error()
        {
            var    err     = Server.GetLastError() as Exception;
            string errorId = string.Empty;
            var    dr      = new DbResult();

            if (err != null)
            {
                var           page          = HttpContext.Current.Request.Url.ToString();
                var           urlReferrer   = HttpContext.Current.Request.UrlReferrer;
                HttpException httpException = err as HttpException;
                string        errorCode     = string.Empty;
                string        errDetails    = string.Empty;
                if (httpException != null) // keep record of HttpException
                {
                    int httpCode = httpException.GetHttpCode();

                    errorCode  = Convert.ToString(httpCode);
                    errorId    = Convert.ToString(errorCode);
                    errDetails = GlobalHelper.FilterString(httpException.GetHtmlErrorMessage());
                }

                CommonLibraryService commonLibraryService = new CommonLibraryService();

                if (Session["userName"] != null && (errorCode != "500" || errorCode != "501" || errorCode != "502" || errorCode != "503"))
                {
                    dr = commonLibraryService.LogError(err, page, GetAbsoluteUri(urlReferrer));
                }


                Server.ClearError();

                if (!string.IsNullOrEmpty(dr.Id) && dr.Id != "0")
                {
                    errorId = dr.Id.ToString();
                }
                Application["code"] = errorId + '|' + errorCode.ToString();
                this.Response.RedirectToRoute("Default", new { controller = "Error", action = "Error" });
            }
        }
Example #24
0
        internal static void LogError(HttpException Apperr, string page)
        {
            Exception err = Apperr;

            if (Apperr.InnerException != null)
            {
                err = Apperr.InnerException;
            }

            var errPage    = FilterString(page);
            var errMsg     = FilterString(err.Message);
            var errDetails = FilterString(Apperr.GetHtmlErrorMessage());

            var log = new Shared.Common.ErrorLogsCommon()
            {
                ErrorPage   = errPage,
                ErrorMsg    = errMsg,
                ErrorDetail = errDetails,
                User        = "",// GetUser()
            };

            var buss     = new Business.Business.StaticData.StaticDataBusiness();
            var response = buss.InsertErrorLog(log);

            // Send internal mail to developer
            if (response.ErrorCode.Equals(1))
            {
                if (!HttpContext.Current.Response.IsRequestBeingRedirected)
                {
                    HttpContext.Current.Response.Redirect("/Home?log=" + response.Id);
                }
            }
            else
            {
                if (!HttpContext.Current.Response.IsRequestBeingRedirected)
                {
                    HttpContext.Current.Response.Redirect("/Error?id=" + response.Id);
                }
            }
        }
Example #25
0
        private static string TryGetHtmlErrorMessage(HttpException e)
        {
            Debug.Assert(e != null);

            try
            {
                return(e.GetHtmlErrorMessage());
            }
            catch (SecurityException se)
            {
                // In partial trust environments, HttpException.GetHtmlErrorMessage()
                // has been known to throw:
                // System.Security.SecurityException: Request for the
                // permission of type 'System.Web.AspNetHostingPermission' failed.
                //
                // See issue #179 for more background:
                // http://code.google.com/p/elmah/issues/detail?id=179

                Trace.WriteLine(se);
                return(null);
            }
        }
Example #26
0
        private static string GetErrorDescriptionUsingReflection(HttpException httpEx)
        {
            var formatterType = typeof(HttpException).Assembly.GetType("System.Web.UnhandledErrorFormatter", false, false);

            if (formatterType == null)
            {
                return(null);
            }

            var method = typeof(HttpException).GetMethod("SetFormatter", BindingFlags.Instance | BindingFlags.NonPublic);

            if (method == null)
            {
                return(null);
            }

            var formatter = Activator.CreateInstance(formatterType, BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { httpEx.InnerException }, null);

            method.Invoke(httpEx, new[] { formatter });

            return(httpEx.GetHtmlErrorMessage());
        }
Example #27
0
        protected void Application_Error(object sender, EventArgs e)
        {
            // Get the error details
            HttpException lastErrorWrapper =
                Server.GetLastError() as HttpException;

            Models.BookmarkRequestStatus status = new Models.BookmarkRequestStatus();
            status.Status     = false;
            status.StatusType = Models.BookmarkRequestStatus.BookmarkStatusType.RouteException;
            switch (lastErrorWrapper.GetHttpCode())
            {
            case 404:
                status.Text = "No page found";
                break;

            default:
                status.Text = lastErrorWrapper.GetHtmlErrorMessage();
                break;
            }
            Response.Write(status.toJson());
            Server.ClearError();
        }
Example #28
0
        internal static void HandleError(HttpApplication app, Exception exception, bool HandledByUser)
        {
            try
            {
                Tenor.Configuration.Tenor config = Tenor.Configuration.Tenor.Current;

                if (exception == null)
                {
                    throw new ArgumentNullException("exception");
                }

                if (config.Exceptions.LogMode == LogMode.None ||
                    (config.Exceptions.LogMode == LogMode.Email && config.Exceptions.Emails.Count == 0) ||
                    (config.Exceptions.LogMode == LogMode.File &&
                     (string.IsNullOrEmpty(config.Exceptions.FilePath) || !Directory.Exists(config.Exceptions.FilePath))))
                {
                    return;
                }

                string requestUrl = string.Empty;
                if (app != null)
                {
                    requestUrl = app.Request.Url.GetLeftPart(UriPartial.Authority) + app.Request.RawUrl;
                }

                string title = (HandledByUser ? "Handled" : "Unhandled").ToString() + " Exception: " + requestUrl + " (" + DateTime.Now.ToString() + ")";

                string body = string.Empty;

                try
                {
                    HttpException htmlex = exception as HttpException;
                    if (htmlex != null)
                    {
                        body = htmlex.GetHtmlErrorMessage();
                    }
                }
                catch { }

                if (body.Trim().Length < 10)
                {
                    body = BuildExceptionDetails(app, exception);
                }

                body = BuildExtraInfo(app, exception, body);

                if (config.Exceptions.LogMode == LogMode.Email)
                {
                    Mail.MailMessage errmail = new Mail.MailMessage();

                    foreach (EmailElement email in config.Exceptions.Emails)
                    {
                        errmail.To.Add(new System.Net.Mail.MailAddress(email.Email, email.Name));
                    }

                    if (errmail.To.Count == 0)
                    {
                        errmail.Dispose();
                        return;
                    }

                    errmail.Subject      = title;
                    errmail.IsBodyHtml   = true;
                    errmail.BodyEncoding = System.Text.Encoding.UTF8;
                    errmail.Body         = body;

                    errmail.Send();
                }
                else if (config.Exceptions.LogMode == LogMode.File)
                {
                    string path = config.Exceptions.FilePath;
                    if (!path.EndsWith("\\"))
                    {
                        path += "\\";
                    }
                    File.WriteAllText(string.Format("{1}\\{0:yyyy-MM-dd-HH-mm-ss}.html", DateTime.Now, path), body, System.Text.Encoding.UTF8);
                }
            }
            catch { }
        }
        protected void Application_Error(object sender, EventArgs e)
        {
            Exception exception = Server.GetLastError();

            //Error logging omitted

            HttpException httpException   = exception as HttpException;
            RouteData     routeData       = new RouteData();
            IController   errorController = new Controllers.ErrorController();

            routeData.Values.Add("controller", "Error");
            routeData.Values.Add("area", "");
            routeData.Values.Add("ex", exception);

            if (httpException != null)
            {
                //this is a basic exampe of how you can choose to handle your errors based on http status codes.
                switch (httpException.GetHttpCode())
                {
                case 400:
                    Debug.WriteLine("HIBA: " + httpException.GetHttpCode().ToString() + ", " + httpException.GetHtmlErrorMessage().ToString());
                    Response.Clear();

                    // bad request
                    routeData.Values.Add("action", "BadRequest");

                    Server.ClearError();
                    // Call the controller with the route
                    errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));

                    break;

                case 404:
                    Debug.WriteLine("HIBA: " + httpException.GetHttpCode().ToString() + ", " + httpException.GetHtmlErrorMessage().ToString());
                    Response.Clear();

                    // page not found
                    routeData.Values.Add("action", "PageNotFound");

                    Server.ClearError();
                    // Call the controller with the route
                    errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));

                    break;

                case 500:
                    Debug.WriteLine("HIBA: " + httpException.GetHttpCode().ToString() + ", " + httpException.GetHtmlErrorMessage().ToString());
                    // server error
                    routeData.Values.Add("action", "ServerError");

                    Server.ClearError();
                    // Call the controller with the route
                    errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
                    break;

                case 403:
                    Debug.WriteLine("HIBA: " + httpException.GetHttpCode().ToString() + ", " + httpException.GetHtmlErrorMessage().ToString());
                    // server error
                    routeData.Values.Add("action", "UnauthorisedRequest");

                    Server.ClearError();
                    // Call the controller with the route
                    errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
                    break;

                //add cases for other http errors you want to handle, otherwise HTTP500 will be returned as the default.
                default:
                    Debug.WriteLine("HIBA: " + httpException.GetHttpCode().ToString() + ", " + httpException.GetHtmlErrorMessage().ToString());
                    // server error
                    routeData.Values.Add("action", "ServerError");

                    Server.ClearError();
                    // Call the controller with the route
                    errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
                    break;
                }
            }
            //All other exceptions should result in a 500 error as they are issues with unhandled exceptions in the code
            else
            {
                Debug.WriteLine("HIBA: " + exception.Message.ToString() + ", " + exception.Source.ToString() + exception.Data);
                routeData.Values.Add("action", "ServerError");
                Server.ClearError();
                // Call the controller with the route

                errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
            }
        }
Example #30
0
        public void ProcessRequest(HttpWorkerRequest wr = null)
        {
            string error = null;

            inUnhandledException = false;

            var             ctx = HttpContext.Current?.Application;
            HttpApplication app = null;

            // StateRuntime state = null;

            string[] args = Environment.GetCommandLineArgs();
            if (Debugger.IsAttached && args.Length >= 5)
            {
                PreApplicationStartMethodAttribute[] attributes = null;
                string   dll      = null;
                Assembly assembly = null;
                try {
                    dll        = args[4];
                    assembly   = Assembly.LoadFrom(this.HostPath + "bin/" + dll);
                    attributes = (PreApplicationStartMethodAttribute[])assembly
                                 .GetCustomAttributes(typeof(PreApplicationStartMethodAttribute), inherit: true);
                } catch {}
                PreApplicationStartMethodAttribute att = attributes.FirstOrDefault();
                if (att != null)
                {
                    var type   = att.Type;
                    var m      = att.MethodName;
                    var method = type.GetMethod(m, BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase,
                                                binder: null,
                                                types: Type.EmptyTypes,
                                                modifiers: null);
                    if (method != null)
                    {
                        method.Invoke(null, BindingFlags.Static, null, null, CultureInfo.CurrentCulture);
                    }
                    // Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
                }
            }

            /*  if (ctx == null)
             * {
             *  state = new StateRuntime();
             *      if (HttpContext.Current != null)
             *              app = HttpContext.Current.ApplicationInstance as HttpApplication;
             *              // HttpApplicationFactory.GetApplicationInstance(HttpContext.Current)
             * }   */

            HttpResponse response = null;
            var          request  = HttpContext.Current?.Request;

            try {
                AssertFileAccessible();

                response = HttpContext.Current?.Response;
                HttpRuntime.ProcessRequest(this);

                IHttpHandler hand = AppDomain.CurrentDomain.GetData("web:app") as IHttpHandler;
                app = hand as HttpApplication;

                /* if (hand != null) {
                 *      response = HttpContext.Current?.Response;
                 *      hand.ProcessRequest(new HttpContext(request, response));
                 * }  */
            } catch (HttpException ex) {
                inUnhandledException = true;
                error = ex.GetHtmlErrorMessage();
            } catch (Exception ex) {
                inUnhandledException = true;
                var hex = new HttpException(400, "Bad request", ex);
                error = hex.GetHtmlErrorMessage();
            }

            if (!inUnhandledException)
            {
                return;
            }

            if (error.Length == 0)
            {
                error = String.Format(DEFAULT_EXCEPTION_HTML, "Unknown error");
            }

            try {
                SendStatus(400, "Bad request");
                SendUnknownResponseHeader("Connection", "close");
                SendUnknownResponseHeader("Date", DateTime.Now.ToUniversalTime().ToString("r"));

                Encoding enc = Encoding.UTF8;

                byte[] bytes = enc.GetBytes(error);

                SendUnknownResponseHeader("Content-Type", "text/html; charset=" + enc.WebName);
                SendUnknownResponseHeader("Content-Length", bytes.Length.ToString());
                SendResponseFromMemory(bytes, bytes.Length);
                FlushResponse(true);
            } catch (Exception ex) {             // should "never" happen
                Logger.Write(LogLevel.Error, "Error while processing a request: ");
                Logger.Write(ex);
                throw;
            }
        }
Example #31
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Error"/> class
        /// from a given <see cref="Exception"/> instance and
        /// <see cref="HttpContext"/> instance representing the HTTP
        /// context during the exception.
        /// </summary>

        public Error(Exception e, HttpContext context)
        {
            if (e == null)
            {
                throw new ArgumentNullException("e");
            }

            _exception = e;
            Exception baseException = e.GetBaseException();

            //
            // Load the basic information.
            //

            _hostName = Environment.TryGetMachineName(context);
            _typeName = baseException.GetType().FullName;
            _message  = baseException.Message;
            _source   = baseException.Source;
            _detail   = getExceptionDetail(e, baseException);
            _user     = Thread.CurrentPrincipal.Identity.Name ?? string.Empty;
            _time     = DateTime.Now;

            //
            // If this is an HTTP exception, then get the status code
            // and detailed HTML message provided by the host.
            //

            HttpException httpException = e as HttpException;

            if (httpException != null)
            {
                _statusCode         = httpException.GetHttpCode();
                _webHostHtmlMessage = httpException.GetHtmlErrorMessage() ?? string.Empty;
            }

            //
            // If the HTTP context is available, then capture the
            // collections that represent the state request as well as
            // the user.
            //

            if (context != null)
            {
                IPrincipal webUser = context.User;
                if (webUser != null &&
                    (webUser.Identity.Name ?? string.Empty).Length > 0)
                {
                    _user = webUser.Identity.Name;
                }

                HttpRequest request = context.Request;

                _serverVariables = CopyCollection(request.ServerVariables);
                _cookies         = CopyCollection(request.Cookies);

                try
                {
                    _queryString = CopyCollection(request.QueryString);
                    _form        = CopyCollection(request.Form);
                }
                catch (HttpRequestValidationException requestValidationException)
                {
                    //
                    // .NET 4.0 will raise this exception if dangerous content is
                    // detected in the request QueryString or Form collections.
                    // In these cases, we will continue to log the exception without
                    // the QueryString or Form data.  We cannot get to this data without
                    // targeting the .NET 4.0 framework and accessing the UnvalidatedRequestValues.
                    //

                    Trace.WriteLine(requestValidationException);
                }
            }
        }
        // Return true if we succeed
        private bool ParseHttpException(HttpException e)
        {
            int i;
            Match match = null;

            String errorMessage = e.GetHtmlErrorMessage();
            if (errorMessage == null)
            {
                return false;
            }

            // Use regular expressions to scrape the message output
            // for meaningful data. One problem: Some parts of the 
            // output are optional, and any regular expression that
            // uses the ()? syntax doesn't pick it up. So, we have
            // to have all the different combinations of expressions,
            // and use each one in order.

            EnsureSearchExpressions();
            for (i = 0; i < _expressionCount; i++)
            {
                match = _searchExpressions[i].Match(errorMessage);
                if (match.Success)
                {
                    break;
                }
            }

            if (i == _expressionCount)
            {
                return false;
            }

            this.Type        = TrimAndClean(match.Result("${title}"));
            this.Description = TrimAndClean(match.Result("${description}"));
            if (i <= 1)
            {
                // These expressions were able to match the miscellaneous
                // title/text section.
                this.MiscTitle = TrimAndClean(match.Result("${misctitle}"));
                this.MiscText  = TrimAndClean(match.Result("${misctext}"));
            }
            if (i == 0)
            {
                // This expression was able to match the file/line # 
                // section.
                this.File        = TrimAndClean(match.Result("${file}"));
                this.LineNumber  = TrimAndClean(match.Result("${linenumber}"));
            }

            return true;
        }