コード例 #1
0
        public ViewResult HandleException(ExceptionContext filterContext, IErrorLogService errorLogService = null)
        {
            filterContext.ExceptionHandled = true;

            var exception = filterContext.Exception;

            if (_errorLogService == null)
            {
                _errorLogService =
                    (RollingFileErrorLogProvider)DependencyResolver.Current.GetService(typeof(IErrorLogService));
            }

            if (errorLogService == null)
            {
                errorLogService = _errorLogService;
            }

            errorLogService.LogFatal(this, exception.Message, exception);

            var viewResult = View("Error", new HandleErrorInfo(exception,
                                                               filterContext.RouteData.Values["controller"].ToString(),
                                                               filterContext.RouteData.Values["action"].ToString()));

            return(viewResult);
        }
        public X509Certificate2 GetValidCertificateFromStoreByThumbprint(StoreLocation storeLocation, string thumbprint)
        {
            if (string.IsNullOrEmpty(thumbprint))
            {
                throw new ArgumentNullException(nameof(thumbprint));
            }

            var certificateThumbprint = Regex.Replace(thumbprint, @"[^\da-zA-z]", string.Empty).ToUpper();
            var certificateStore      = new X509Store(storeLocation);

            X509Certificate2Collection certificatesFound = null;

            try
            {
                certificateStore.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
                var certificateCollection = certificateStore.Certificates;
                certificatesFound =
                    certificateCollection.Find(X509FindType.FindByThumbprint, certificateThumbprint, true);
            }
            catch (Exception certificateStoreOperationException)
            {
                _log.LogFatal(certificateStoreOperationException,
                              string.Format(CertificateStoreExceptionErrorMessage, thumbprint));
            }
            finally
            {
                certificateStore.Close();
            }

            if (certificatesFound == null)
            {
                throw new NoNullAllowedException(nameof(certificatesFound));
            }

            if (certificatesFound.Count == 0)
            {
                throw new CryptographicException(string.Format(NoCertificateFoundErrorMessage, thumbprint));
            }

            return(certificatesFound[0]);
        }
        public X509Certificate2 GetValidCertificateFromEmbeddedResource()
        {
            const string testPwd       = "";
            const string demoPwd       = "";
            const string productionPwd = "";

            if (_applicationConfiguration.GetCurrentEnvironment() == AppEnvironmentEnum.Test)
            {
                var testApplicationCertificate = new X509Certificate2("", testPwd);

                LogExtraInformation(
                    "",
                    testApplicationCertificate,
                    testPwd,
                    CertificateTypeEnum.TestApplication
                    );

                certificate = testApplicationCertificate;
            }
            else if (_applicationConfiguration.GetCurrentEnvironment() == AppEnvironmentEnum.Demo)
            {
                var demoApplicationCertificate = new X509Certificate2("", demoPwd);

                LogExtraInformation(
                    "",
                    demoApplicationCertificate,
                    demoPwd,
                    CertificateTypeEnum.DemoApplication
                    );

                certificate = demoApplicationCertificate;
            }
            else if (_applicationConfiguration.GetCurrentEnvironment() == AppEnvironmentEnum.Production)
            {
                _errorLog.LogInfo(
                    this,
                    string.Format("APP_CERT_PRE_FETCH_CHECK", certificate == null)
                    );

                X509Certificate2 productionApplicationCertificate = null;

                try
                {
                    _errorLog.LogInfo(this,
                                      string.Format("APP_CERT_LENGTH_OF_EMBEDDED_RESOURCE", ""?.Length)
                                      );

                    productionApplicationCertificate = new X509Certificate2("", productionPwd);
                }
                catch (Exception certificateException)
                {
                    _errorLog.LogFatal(this, certificateException.Message, certificateException);
                }

                _errorLog.LogInfo(
                    this,
                    string.Format("APP_CERT_GOT_CERT_FROM_EMBEDDED_RESOURCE",
                                  productionApplicationCertificate?.SubjectName.Name)
                    );

                certificate = productionApplicationCertificate;
            }

            // deal breaker....
            if (certificate == null)
            {
                throw new NoNullAllowedException(nameof(certificate));
            }


            if (_applicationConfiguration.ShouldVerifyCertificateExpirationDate())
            {
                var validationResult = VerifyCertificateExpirationDate(certificate, CertificateTypeEnum.Application);
            }

            return(certificate);
        }
コード例 #4
0
        protected void Application_Error(object sender, EventArgs e)
        {
            #region requires this way of error handling

            try
            {
                if (_logger == null)
                {
                    _logger = DependencyResolver.Current.GetService <IErrorLogService>();
                }

                _helper        = DependencyResolver.Current.GetService <IGlobalAsaxHelpers>();
                _cookieStorage = DependencyResolver.Current.GetService <ICookieStorageService>();
            }
            catch (Exception exception)
            {
                // _logger.Error("",exception);
            }

            _controllerRouteAction = _helper.PopulateControllerRouteActionFromContext(ExtractContextFromSender(sender));

            var ex = Server.GetLastError();

            var controller = new ErrorController(_cookieStorage, null, null);
            var routeData  = new RouteData();

            var httpContext = ExtractContextFromSender(sender);

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

                    _logger?.LogFatal(this, "=================================================");
                    _logger?.LogFatal(this,
                                      $"{DateTime.UtcNow}: HTTP error [ {httpEx.GetHttpCode()} ] at [ {_controllerRouteAction.CurrentController}/{_controllerRouteAction.CurrentAction} ] {Environment.NewLine} [ {ex} {Environment.NewLine} ]");
                    _logger?.LogFatal(this, "");
                }
                else
                {
                    _logger?.LogFatal(this, "=================================================");
                    _logger?.LogFatal(this,
                                      $"{DateTime.UtcNow}: error '{ex.Message}' at {_controllerRouteAction.CurrentController}/{_controllerRouteAction.CurrentAction} {Environment.NewLine} [ {ex} {Environment.NewLine}  ]");
                    _logger?.LogFatal(this, "");
                }
            }

            if (_controllerRouteAction.CurrentController.Equals("Account") &&
                _controllerRouteAction.CurrentAction.Equals("Login") && (( HttpException )ex).GetHttpCode() == 500 &&
                ex.Message.Contains("anti-forgery"))
            {
                Response.Redirect(UrlConfigHelper.GetRoot() + "Account/Login", true);
            }

            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"]     = "Error";

            controller.ViewData.Model = new ErrorViewModel(ex, _controllerRouteAction.CurrentController,
                                                           _controllerRouteAction.CurrentAction);

            (( IController )controller).Execute(new RequestContext(new HttpContextWrapper(httpContext), routeData));

            #endregion requires this way of error handling
        }