コード例 #1
0
        public void OnException(ExceptionContext filterContext)
        {
            var exception = filterContext.Exception;

            if (exception == null)
            {
                return;
            }
            //_logger.Fatal(exception.Message, exception);

            //Send an email if the error is anything other than Not Found.
            if (exception is HttpException && ((HttpException)exception).GetHttpCode() == (int)HttpStatusCode.NotFound)
            {
                return;
            }
            log.Error(exception.ToString());
            try
            {
                WebMailer.EmailError(exception);
            }
            catch (Exception ex)
            {
                log.Error(ex.ToString());
            }
        }
コード例 #2
0
        public override void OnException(HttpActionExecutedContext filterContext)
        {
            if (filterContext.Exception == null)
            {
                return;
            }

            var currentException = filterContext.Exception;
            IEnumerable <string> headerValues;
            var isAjaxCall = false;

            if (filterContext.Request.Headers.TryGetValues("X-Requested-With", out headerValues))
            {
                isAjaxCall = headerValues.FirstOrDefault() == "XMLHttpRequest";
            }

            // HTTPErrorCode doesn't matter when it is ajax call, we should handle it here.
            if (!isAjaxCall &&
                !(currentException is FriendlyException) &&
                new HttpException(null, currentException).GetHttpCode() != 500)
            {
                return;
            }
            var m         = "There was an error processing your request. Please try again in a few moments.";
            var exception = currentException as FriendlyException;

            if (exception == null || _errorCodeFriendlyExceptionEmailExcepts == null || _errorCodeFriendlyExceptionEmailExcepts.All(m1 => m1 != exception.ErrorCode))
            {
                WebMailer.EmailError(currentException);
            }


            if (exception != null)
            {
                m = exception.Message;
            }

            // log the error using log4net.
            _logger.Error(FormatError(filterContext), currentException);

            filterContext.Response = filterContext.Request.CreateResponse(HttpStatusCode.InternalServerError, new
            {
                error       = true,
                message     = m, //currentException.Message,
                urlReferrer = filterContext.Request.RequestUri,
                redirect    = !string.IsNullOrWhiteSpace(exception?.RedirectUrl),
                redirectUrl = exception?.RedirectUrl,
            });
        }
コード例 #3
0
        protected void Application_Error(object sender, EventArgs e)
        {
            var exception = Server.GetLastError();

            if (exception == null)
            {
                return;
            }
            _log.Fatal(exception.Message, exception);

            //Send an email if the error is anything other than Not Found.
            var httpException = exception as HttpException;

            if (httpException != null && httpException.GetHttpCode() == (int)HttpStatusCode.NotFound)
            {
                return;
            }

            WebMailer.EmailError(exception);
        }
コード例 #4
0
        public static bool SendVerificationEmail(string UserID)
        {
            try
            {
                using (var db = new MemberLiteEntities().Init)
                {
                    var u = db.Users.Select(a => new { a.UserID, a.FirstName, a.OtherNames, a.Email, a.VerificationCode })
                            .Where(a => a.UserID == UserID)
                            .FirstOrDefault();

                    if (u == null)
                    {
                        ReturnMessage = "Invalid user";
                        return(false);
                    }

                    string link = new Uri(string.Format(AppConfig.Url + "access/verifyemail?e={0}&c={1}", u.Email, u.VerificationCode)).AbsoluteUri;
                    string body = File.ReadAllText(AppUtility.AppDataPath + "/MailTemplates/EmailVerification.htm");

                    body = body.Replace("{site_name}", AppConfig.Name);
                    body = body.Replace("{site_url}", AppConfig.Url);
                    body = body.Replace("{name}", u.OtherNames + " " + u.FirstName);
                    body = body.Replace("{verify_link}", link);
                    body = body.Replace("{email}", u.Email);
                    body = body.Replace("{support_mail}", WebMailer.Support);

                    if (WebMailer.Send(WebMailer.Alert, u.Email, AppConfig.Name + " - Email Verification", body, true))
                    {
                        ReturnMessage = "Verification message has been sent, please goto your inbox and confirm it now.";
                        return(true);
                    }
                }
            }
            catch (Exception ex)
            {
                CustomErrorLogger.Log(ex.Message);
            }

            ReturnMessage = "Unable to send verification mail";
            return(false);
        }
コード例 #5
0
        public override async void OnException(HttpActionExecutedContext filterContext)
        {
            if (filterContext.Exception == null)
            {
                return;
            }


            var currentException = filterContext.Exception;
            IEnumerable <string> headerValues;
            bool isAjaxCall = false;

            if (filterContext.Request.Headers.TryGetValues("X-Requested-With", out headerValues))
            {
                isAjaxCall = headerValues.FirstOrDefault() == "XMLHttpRequest";
            }

            //if (filterContext.ActionContext.RequestContext.IncludeErrorDetail)
            //    return;

            // HTTPErrorCode doesn't matter when it is ajax call, we should handle it here.
            if (!isAjaxCall &&
                !(currentException is FriendlyException) &&
                new HttpException(null, currentException).GetHttpCode() != 500)
            {
                return;
            }


            WebMailer.EmailError(currentException);

            string m         = "There was an error processing your request. Please try again in a few moments.";
            var    exception = currentException as FriendlyException;

            if (exception != null)
            {
                m = exception.Message;
            }


            // if the request is AJAX return JSON else view.


            // log the error using log4net.
            StringBuilder message = new StringBuilder();

            message.AppendLine(filterContext.Request.RequestUri.ToString());
            using (var headers = filterContext.Request.Headers.GetEnumerator())
            {
                while (headers.MoveNext())
                {
                    message.Append(headers.Current.Key).Append(":").AppendLine(headers.Current.Value?.ToString());
                }
            }
            message.AppendLine(currentException.Message);
            message.AppendLine("content if any and less than 1K:");
            try
            {
                if (filterContext.Request?.Content?.Headers?.ContentLength < 1024)
                {
                    if (filterContext?.ActionContext?.ActionArguments?.Count > 0)
                    {
                        foreach (var arg in filterContext?.ActionContext?.ActionArguments)
                        {
                            message.Append(arg.Key).Append(":").AppendLine(new JavaScriptSerializer().Serialize(arg.Value));
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                message.Append("Error trying to serialize the content, ").AppendLine(ex.Message);
            }

            _logger.Error(message, currentException);

            filterContext.Response = filterContext.Request.CreateResponse(HttpStatusCode.InternalServerError, new
            {
                error       = true,
                message     = m, //currentException.Message,
                urlReferrer = filterContext.Request.RequestUri
            });
        }
コード例 #6
0
        public static bool ResetPassword(string Login)
        {
            string userID = "", email = "", newPwd, fname = "";

            using (var db = new MemberLiteEntities().Init)
            {
                long __phone = 0, val = 0;
                if (Int64.TryParse(Login, out val))
                {
                    __phone = Convert.ToInt64(Login);
                }

                if (Login.Contains("@"))
                {
                    if (AppUtility.ValidateEmail(Login))
                    {
                        var u = db.Users.Select(a => new { a.UserID, a.Email, a.FirstName, a.OtherNames })
                                .Where(a => a.Email == Login).FirstOrDefault();
                        if (u != null)
                        {
                            userID = u.UserID;
                            fname  = u.OtherNames + " " + u.FirstName;
                            email  = Login;
                        }
                        goto notfound;
                    }
                    else
                    {
                        ReturnMessage = "Email address format is incorrect!";
                        return(false);
                    }
                }
                else if (__phone != 0)
                {
                    var u = db.Users.Select(a => new { a.UserID, a.Email, a.Phone, a.FirstName, a.OtherNames })
                            .Where(a => a.Phone == __phone).FirstOrDefault();
                    if (u != null)
                    {
                        userID = u.UserID;
                        fname  = u.FirstName;
                        email  = Login;
                    }
                    goto notfound;
                }
                else
                {
                    ReturnMessage = "Provide your login email or phone number!";
                    return(false);
                }

notfound:
                if (userID == "")
                {
                    ReturnMessage = "User not found! Please try again.";
                    return(false);
                }

                newPwd = AppUtility.GenerateAlphaNumeric(10);

                string userIDHash = Crypto.SHA256Hash(userID);
                string pwd        = Crypto.SHA256Hash(newPwd.ToUpper());
                string finalPwd   = Crypto.SHA256Hash(userIDHash + pwd);

                db.Users.Find(userID).Password = finalPwd;
                db.SaveChanges();
                ReturnMessage = "Password reset ok but could not send email. Pls try again!";
            }

            string msg = File.ReadAllText(AppUtility.AppDataPath + "MailTemplates/PasswordReset.htm");

            msg = msg.Replace("{site_name}", AppConfig.Name);
            msg = msg.Replace("{fullname}", fname);
            msg = msg.Replace("{new_pwd}", newPwd);
            msg = msg.Replace("{site_url}", AppConfig.Url);
            msg = msg.Replace("{support_mail}", WebMailer.Support);

            if (WebMailer.Send(WebMailer.Alert, email, "Password Reset", msg, true))
            {
                ReturnMessage = "Password reset complete! Check your email for a new password.";
            }
            return(true);
        }
コード例 #7
0
        public override void OnException(ExceptionContext filterContext)
        {
            if (filterContext.Exception == null)
            {
                return;
            }

            var  currentException = filterContext.Exception;
            bool isAjaxCall       = filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest";

            if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
            {
                return;
            }

            // HTTPErrorCode doesn't matter when it is ajax call, we should handle it here.
            if (!isAjaxCall &&
                !(currentException is FriendlyException) &&
                !currentException.GetType().IsAssignableFrom(typeof(FriendlyException)) &&
                !currentException.GetType().IsAssignableFrom(typeof(Framework.Exceptions.FriendlyException)) &&
                new HttpException(null, currentException).GetHttpCode() != 500)
            {
                return;
            }

            if (!ExceptionType.IsInstanceOfType(currentException))
            {
                return;
            }

            //Send an email if the error is anything other than Not Found.
            if (filterContext.HttpContext.Response.StatusCode != (int)HttpStatusCode.NotFound)
            {
                WebMailer.EmailError(currentException);
            }

            // if the request is AJAX return JSON else view.
            if (isAjaxCall)
            {
                string    m         = "There was an error processing your request. Please try again in a few moments.";
                Exception exception = currentException as FriendlyException;
                if (exception != null)
                {
                    m = exception.Message;
                }
                else
                {
                    exception = currentException as Framework.Exceptions.FriendlyException;
                    if (exception != null)
                    {
                        m = exception.Message;
                    }
                }

                filterContext.Result = new JsonResult
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = new
                    {
                        error       = true,
                        message     = m, //currentException.Message,
                        urlReferrer = filterContext.HttpContext.Request.UrlReferrer == null ? "" : filterContext.HttpContext.Request.UrlReferrer.OriginalString
                    }
                };
            }
            else
            {
                var controllerName = (string)filterContext.RouteData.Values["controller"];
                var actionName     = (string)filterContext.RouteData.Values["action"];
                var model          = new HandleErrorInfo(currentException, controllerName, actionName);

                filterContext.Result = new ViewResult
                {
                    ViewName   = View,
                    MasterName = Master,
                    ViewData   = new ViewDataDictionary <HandleErrorInfo>(model),
                    TempData   = filterContext.Controller.TempData
                };

                string    messaage  = "";
                Exception exception = currentException as FriendlyException;
                if (exception != null)
                {
                    messaage = exception.Message;
                }
                else
                {
                    exception = currentException as Framework.Exceptions.FriendlyException;
                    if (exception != null)
                    {
                        messaage = exception.Message;
                    }
                }

                if (!string.IsNullOrWhiteSpace(messaage))
                {
                    if (((ViewResult)filterContext.Result).TempData.ContainsKey("ErrorMessage"))
                    {
                        ((ViewResult)filterContext.Result).TempData["ErrorMessage"] = messaage;
                    }
                    else
                    {
                        ((ViewResult)filterContext.Result).TempData.Add("ErrorMessage", messaage);
                    }
                }
            }

            // log the error using log4net.
            string message = filterContext.HttpContext.Request.UrlReferrer == null
                ? ""
                : filterContext.HttpContext.Request.UrlReferrer.OriginalString + "\r\n";

            message += currentException.Message;
            _logger.Error(message, currentException);

            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.Clear();
            filterContext.HttpContext.Response.StatusCode = 500;

            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
        }