private static bool TryRaiseErrorSignal(ExceptionContext context) { var httpContext = GetHttpContextImpl(context.HttpContext); if (httpContext == null) { return(false); } var signal = ErrorSignal.FromContext(httpContext); if (signal == null) { return(false); } signal.Raise(context.Exception, httpContext); return(true); }
private static bool RaiseErrorSignal(Exception e) { var context = HttpContext.Current; if (context == null) { return(false); } var signal = ErrorSignal.FromContext(context); if (signal == null) { return(false); } signal.Raise(e, context); return(true); }
static T CreateSubjects <T>(Func <ErrorSignal, HttpContextBase, T> resultor) { var mocks = new { Context = new Mock <HttpContextBase> { DefaultValue = DefaultValue.Mock } }; using (var app = new HttpApplication()) { mocks.Context.Setup(c => c.ApplicationInstance).Returns(app); var context = mocks.Context.Object; return(resultor(ErrorSignal.FromContext(context), context)); } }
public override void Log(ExceptionLoggerContext context) { // Retrieve the current HttpContext instance for this request. HttpContext httpContext = GetHttpContext(context.Request); if (httpContext == null) { return; } // Wrap the exception in an HttpUnhandledException so that ELMAH can capture the original error page. Exception exceptionToRaise = new HttpUnhandledException(context.Exception.Message, context.Exception); // Send the exception to ELMAH (for logging, mailing, filtering, etc.). ErrorSignal signal = ErrorSignal.FromContext(httpContext); signal.Raise(exceptionToRaise, httpContext); }
private void Log(ExceptionContext context) { // Retrieve the current HttpContext instance for this request. HttpContext httpContext = context.HttpContext.ApplicationInstance.Context; if (httpContext == null) { return; } // Wrap the exception in an HttpUnhandledException so that ELMAH can capture the original error page. Exception exceptionToRaise = new HttpUnhandledException(message: null, innerException: context.Exception); // Send the exception to ELMAH (for logging, mailing, filtering, etc.). ErrorSignal signal = ErrorSignal.FromContext(httpContext); signal.Raise(exceptionToRaise, httpContext); }
/// <summary> /// Enables the creation of a custom <see cref="T:System.ServiceModel.FaultException`1"/> that is returned from an exception in the course of a service method. /// </summary> /// <param name="error">The <see cref="T:System.Exception"/> object thrown in the course of the service operation.</param> /// <param name="version">The SOAP version of the message.</param> /// <param name="fault">The <see cref="T:System.ServiceModel.Channels.Message"/> object that is returned to the client, or service, in the duplex case.</param> public void ProvideFault(Exception error, MessageVersion version, ref Message fault) { if (error == null) { return; } // Notify ELMAH of the exception. HttpContext context = HttpContext.Current; if (context == null) { ErrorLog.GetDefault(null).Log(new Error(error)); } else { ErrorSignal.FromContext(context).Raise(error, context); } }
private bool TryRaiseErrorSignal(ExceptionContext context) { HttpContext httpContextImpl = GetHttpContextImpl(context.HttpContext); if (httpContextImpl == null) { return(false); } ErrorSignal errorSignal = ErrorSignal.FromContext(httpContextImpl); if (errorSignal == null) { return(false); } errorSignal.Raise(context.Exception.Demystify(), httpContextImpl); return(true); }
public void LogException(Exception ex, RequestBase requestBase) { try { var context = HttpContext.Current; if (context == null) { return; } var signal = ErrorSignal.FromContext(context); if (signal == null) { return; } signal.Raise(ex); } catch (Exception) { //new ErrorHandler(ApiLogPath).HandleError(ex, requestBase); } }
protected override void OnException(ExceptionContext filterContext) { try { var httpContext = filterContext.HttpContext.ApplicationInstance.Context; var signal = ErrorSignal.FromContext(httpContext); signal.Raise(filterContext.Exception, httpContext); filterContext.ExceptionHandled = true; filterContext.HttpContext.Response.Clear(); filterContext.HttpContext.Response.TrySkipIisCustomErrors = true; if (filterContext.HttpContext.Request.IsAjaxRequest() || Request.IsAjaxRequest()) { filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError; filterContext.Result = new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = new ServiceResponse { Message = Resource.ErrorMessage, Data = Common.SerializeObject(filterContext.Exception) } }; } else { System.Web.HttpContext.Current.Response.Redirect(Constants.InternalServerUrl); } if (filterContext.Exception.GetType() == typeof(HttpException)) { HttpException exception = filterContext.Exception as HttpException; filterContext.HttpContext.Response.StatusCode = exception.GetHttpCode(); } } catch (Exception ex) { throw ex; } }
public string DownloadString(Uri url) { try { return(_webClient.DownloadString(url)); } catch (Exception ex) { HttpContext context = HttpContext.Current; if (context != null) { ErrorSignal signal = ErrorSignal.FromContext(context); if (signal != null) { string message = "Could not access url: " + url; Exception exception = new InvalidOperationException(message, ex); signal.Raise(exception); } } return(null); } }
// This method is auto-detected by the OWIN pipeline. DO NOT RENAME IT! public static void Configuration(IAppBuilder app) { // Tune ServicePointManager // (based on http://social.technet.microsoft.com/Forums/en-US/windowsazuredata/thread/d84ba34b-b0e0-4961-a167-bbe7618beb83 and https://msdn.microsoft.com/en-us/library/system.net.servicepointmanager.aspx) ServicePointManager.DefaultConnectionLimit = 500; ServicePointManager.UseNagleAlgorithm = false; ServicePointManager.Expect100Continue = false; // Ensure that SSLv3 is disabled and that Tls v1.2 is enabled. ServicePointManager.SecurityProtocol &= ~SecurityProtocolType.Ssl3; ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12; // Setting time out for all RegEx objects. Noted in remarks at https://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.matchtimeout%28v=vs.110%29.aspx AppDomain.CurrentDomain.SetData("REGEX_DEFAULT_MATCH_TIMEOUT", TimeSpan.FromSeconds(10)); // Register IoC app.UseAutofacInjection(GlobalConfiguration.Configuration); var dependencyResolver = DependencyResolver.Current; // Register Elmah var elmahServiceCenter = new DependencyResolverServiceProviderAdapter(dependencyResolver); ServiceCenter.Current = _ => elmahServiceCenter; // Get config var config = dependencyResolver.GetService <IGalleryConfigurationService>(); var auth = dependencyResolver.GetService <AuthenticationService>(); // Configure machine key for session persistence across slots SessionPersistence.Setup(config); // Refresh the content for the ContentObjectService to guarantee it has loaded the latest configuration on startup. var contentObjectService = dependencyResolver.GetService <IContentObjectService>(); HostingEnvironment.QueueBackgroundWorkItem(async token => { while (!token.IsCancellationRequested) { await contentObjectService.Refresh(); await Task.Delay(ContentObjectService.RefreshInterval, token); } }); // Setup telemetry var instrumentationKey = config.Current.AppInsightsInstrumentationKey; if (!string.IsNullOrEmpty(instrumentationKey)) { TelemetryConfiguration.Active.InstrumentationKey = instrumentationKey; // Add enrichers TelemetryConfiguration.Active.TelemetryInitializers.Add(new ClientInformationTelemetryEnricher()); var telemetryProcessorChainBuilder = TelemetryConfiguration.Active.TelemetryProcessorChainBuilder; // Add processors telemetryProcessorChainBuilder.Use(next => { var processor = new RequestTelemetryProcessor(next); processor.SuccessfulResponseCodes.Add(400); processor.SuccessfulResponseCodes.Add(404); return(processor); }); telemetryProcessorChainBuilder.Use(next => new ClientTelemetryPIIProcessor(next)); var telemetry = dependencyResolver.GetService <TelemetryClientWrapper>(); telemetryProcessorChainBuilder.Use( next => new ExceptionTelemetryProcessor(next, telemetry.UnderlyingClient)); // Note: sampling rate must be a factor 100/N where N is a whole number // e.g.: 50 (= 100/2), 33.33 (= 100/3), 25 (= 100/4), ... // https://azure.microsoft.com/en-us/documentation/articles/app-insights-sampling/ var instrumentationSamplingPercentage = config.Current.AppInsightsSamplingPercentage; if (instrumentationSamplingPercentage > 0 && instrumentationSamplingPercentage < 100) { telemetryProcessorChainBuilder.UseSampling(instrumentationSamplingPercentage); } telemetryProcessorChainBuilder.Build(); } // Configure logging app.SetLoggerFactory(new DiagnosticsLoggerFactory()); // Remove X-AspNetMvc-Version header MvcHandler.DisableMvcResponseHeader = true; if (config.Current.RequireSSL) { // Put a middleware at the top of the stack to force the user over to SSL if (config.Current.ForceSslExclusion == null) { app.UseForceSsl(config.Current.SSLPort); } else { app.UseForceSsl(config.Current.SSLPort, config.Current.ForceSslExclusion); } } // Get the local user auth provider, if present and attach it first Authenticator localUserAuthenticator; if (auth.Authenticators.TryGetValue(Authenticator.GetName(typeof(LocalUserAuthenticator)), out localUserAuthenticator)) { // Configure cookie auth now localUserAuthenticator.Startup(config, app).Wait(); } // Attach external sign-in cookie middleware app.SetDefaultSignInAsAuthenticationType(AuthenticationTypes.External); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = AuthenticationTypes.External, AuthenticationMode = AuthenticationMode.Passive, CookieName = ".AspNet." + AuthenticationTypes.External, ExpireTimeSpan = TimeSpan.FromMinutes(5) }); // Attach non-cookie auth providers var nonCookieAuthers = auth .Authenticators .Where(p => !String.Equals( p.Key, Authenticator.GetName(typeof(LocalUserAuthenticator)), StringComparison.OrdinalIgnoreCase)) .Select(p => p.Value); foreach (var auther in nonCookieAuthers) { auther.Startup(config, app).Wait(); } // Catch unobserved exceptions from threads before they cause IIS to crash: TaskScheduler.UnobservedTaskException += (sender, exArgs) => { // Send to AppInsights try { var telemetryClient = new TelemetryClient(); telemetryClient.TrackException(exArgs.Exception, new Dictionary <string, string>() { { "ExceptionOrigin", "UnobservedTaskException" } }); } catch (Exception) { // this is a tragic moment... swallow Exception to prevent crashing IIS } // Send to ELMAH try { HttpContext current = HttpContext.Current; if (current != null) { var errorSignal = ErrorSignal.FromContext(current); if (errorSignal != null) { errorSignal.Raise(exArgs.Exception, current); } } } catch (Exception) { // more tragedy... swallow Exception to prevent crashing IIS } exArgs.SetObserved(); }; HasRun = true; }
// This method is auto-detected by the OWIN pipeline. DO NOT RENAME IT! public static void Configuration(IAppBuilder app) { // Tune ServicePointManager // (based on http://social.technet.microsoft.com/Forums/en-US/windowsazuredata/thread/d84ba34b-b0e0-4961-a167-bbe7618beb83 and https://msdn.microsoft.com/en-us/library/system.net.servicepointmanager.aspx) ServicePointManager.DefaultConnectionLimit = 500; ServicePointManager.UseNagleAlgorithm = false; ServicePointManager.Expect100Continue = false; // Ensure that SSLv3 is disabled and that Tls v1.2 is enabled. ServicePointManager.SecurityProtocol &= ~SecurityProtocolType.Ssl3; ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12; // Setting time out for all RegEx objects. Noted in remarks at https://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.matchtimeout%28v=vs.110%29.aspx AppDomain.CurrentDomain.SetData("REGEX_DEFAULT_MATCH_TIMEOUT", TimeSpan.FromSeconds(10)); // Register IoC app.UseAutofacInjection(GlobalConfiguration.Configuration); var dependencyResolver = DependencyResolver.Current; // Register Elmah var elmahServiceCenter = new DependencyResolverServiceProviderAdapter(dependencyResolver); ServiceCenter.Current = _ => elmahServiceCenter; // Get config var config = dependencyResolver.GetService <IGalleryConfigurationService>(); var auth = dependencyResolver.GetService <AuthenticationService>(); // Configure machine key for session persistence across slots SessionPersistence.Setup(config); // Refresh the content for the ContentObjectService to guarantee it has loaded the latest configuration on startup. var contentObjectService = dependencyResolver.GetService <IContentObjectService>(); HostingEnvironment.QueueBackgroundWorkItem(async token => { while (!token.IsCancellationRequested) { await contentObjectService.Refresh(); await Task.Delay(ContentObjectService.RefreshInterval, token); } }); // Configure logging app.SetLoggerFactory(new DiagnosticsLoggerFactory()); // Remove X-AspNetMvc-Version header MvcHandler.DisableMvcResponseHeader = true; if (config.Current.RequireSSL) { // Put a middleware at the top of the stack to force the user over to SSL if (config.Current.ForceSslExclusion == null) { app.UseForceSsl(config.Current.SSLPort); } else { app.UseForceSsl(config.Current.SSLPort, config.Current.ForceSslExclusion); } } var tds = new TraceDiagnosticsSource(nameof(OwinStartup), dependencyResolver.GetService <ITelemetryClient>()); if (config.Current.MaxWorkerThreads.HasValue && config.Current.MaxIoThreads.HasValue) { int defaultMaxWorkerThreads, defaultMaxIoThreads; ThreadPool.GetMaxThreads(out defaultMaxWorkerThreads, out defaultMaxIoThreads); tds.Information($"Default maxWorkerThreads: {defaultMaxWorkerThreads}, maxIoThreads: {defaultMaxIoThreads}"); var success = ThreadPool.SetMaxThreads(config.Current.MaxWorkerThreads.Value, config.Current.MaxIoThreads.Value); tds.Information($"Attempt to update max threads to {config.Current.MaxWorkerThreads.Value}, {config.Current.MaxIoThreads.Value}, success: {success}"); } if (config.Current.MinWorkerThreads.HasValue && config.Current.MinIoThreads.HasValue) { int defaultMinWorkerThreads, defaultMinIoThreads; ThreadPool.GetMinThreads(out defaultMinWorkerThreads, out defaultMinIoThreads); tds.Information($"Default minWorkerThreads: {defaultMinWorkerThreads}, minIoThreads: {defaultMinIoThreads}"); var success = ThreadPool.SetMinThreads(config.Current.MinWorkerThreads.Value, config.Current.MinIoThreads.Value); tds.Information($"Attempt to update min threads to {config.Current.MinWorkerThreads.Value}, {config.Current.MinIoThreads.Value}, success: {success}"); } // Get the local user auth provider, if present and attach it first Authenticator localUserAuthenticator; if (auth.Authenticators.TryGetValue(Authenticator.GetName(typeof(LocalUserAuthenticator)), out localUserAuthenticator)) { // Configure cookie auth now localUserAuthenticator.Startup(config, app).Wait(); } // Attach external sign-in cookie middleware app.SetDefaultSignInAsAuthenticationType(AuthenticationTypes.External); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = AuthenticationTypes.External, AuthenticationMode = AuthenticationMode.Passive, CookieName = ".AspNet." + AuthenticationTypes.External, ExpireTimeSpan = TimeSpan.FromMinutes(5) }); // Attach non-cookie auth providers var nonCookieAuthers = auth .Authenticators .Where(p => !String.Equals( p.Key, Authenticator.GetName(typeof(LocalUserAuthenticator)), StringComparison.OrdinalIgnoreCase)) .Select(p => p.Value); foreach (var auther in nonCookieAuthers) { auther.Startup(config, app).Wait(); } var featureFlags = DependencyResolver.Current.GetService <IFeatureFlagCacheService>(); if (featureFlags != null) { StartFeatureFlags(featureFlags); } // Catch unobserved exceptions from threads before they cause IIS to crash: TaskScheduler.UnobservedTaskException += (sender, exArgs) => { // Send to AppInsights try { var telemetryClient = DependencyResolver.Current.GetService <ITelemetryClient>(); telemetryClient.TrackException(exArgs.Exception, new Dictionary <string, string>() { { "ExceptionOrigin", "UnobservedTaskException" } }); } catch (Exception) { // this is a tragic moment... swallow Exception to prevent crashing IIS } // Send to ELMAH try { HttpContext current = HttpContext.Current; if (current != null) { var errorSignal = ErrorSignal.FromContext(current); if (errorSignal != null) { errorSignal.Raise(exArgs.Exception, current); } } } catch (Exception) { // more tragedy... swallow Exception to prevent crashing IIS } exArgs.SetObserved(); }; HasRun = true; }
// This method is auto-detected by the OWIN pipeline. DO NOT RENAME IT! public static void Configuration(IAppBuilder app) { // Tune ServicePointManager // (based on http://social.technet.microsoft.com/Forums/en-US/windowsazuredata/thread/d84ba34b-b0e0-4961-a167-bbe7618beb83 and https://msdn.microsoft.com/en-us/library/system.net.servicepointmanager.aspx) ServicePointManager.DefaultConnectionLimit = 500; ServicePointManager.UseNagleAlgorithm = false; ServicePointManager.Expect100Continue = false; // Register IoC app.UseAutofacInjection(GlobalConfiguration.Configuration); var dependencyResolver = DependencyResolver.Current; // Register Elmah var elmahServiceCenter = new DependencyResolverServiceProviderAdapter(dependencyResolver); ServiceCenter.Current = _ => elmahServiceCenter; // Get config var config = dependencyResolver.GetService <IGalleryConfigurationService>(); var auth = dependencyResolver.GetService <AuthenticationService>(); // Setup telemetry var instrumentationKey = config.Current.AppInsightsInstrumentationKey; if (!string.IsNullOrEmpty(instrumentationKey)) { TelemetryConfiguration.Active.InstrumentationKey = instrumentationKey; // Add enrichers TelemetryConfiguration.Active.TelemetryInitializers.Add(new ClientInformationTelemetryEnricher()); var telemetryProcessorChainBuilder = TelemetryConfiguration.Active.TelemetryProcessorChainBuilder; // Add filters telemetryProcessorChainBuilder.Use(next => new TelemetryResponseCodeFilter(next)); // Note: sampling rate must be a factor 100/N where N is a whole number // e.g.: 50 (= 100/2), 33.33 (= 100/3), 25 (= 100/4), ... // https://azure.microsoft.com/en-us/documentation/articles/app-insights-sampling/ var instrumentationSamplingPercentage = config.Current.AppInsightsSamplingPercentage; if (instrumentationSamplingPercentage > 0 && instrumentationSamplingPercentage < 100) { telemetryProcessorChainBuilder.UseSampling(instrumentationSamplingPercentage); } telemetryProcessorChainBuilder.Build(); } // Configure logging app.SetLoggerFactory(new DiagnosticsLoggerFactory()); // Remove X-AspNetMvc-Version header MvcHandler.DisableMvcResponseHeader = true; if (config.Current.RequireSSL) { // Put a middleware at the top of the stack to force the user over to SSL // if authenticated. app.UseForceSslWhenAuthenticated(config.Current.SSLPort); } // Get the local user auth provider, if present and attach it first Authenticator localUserAuthenticator; if (auth.Authenticators.TryGetValue(Authenticator.GetName(typeof(LocalUserAuthenticator)), out localUserAuthenticator)) { // Configure cookie auth now localUserAuthenticator.Startup(config, app).Wait(); } // Attach external sign-in cookie middleware app.SetDefaultSignInAsAuthenticationType(AuthenticationTypes.External); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = AuthenticationTypes.External, AuthenticationMode = AuthenticationMode.Passive, CookieName = ".AspNet." + AuthenticationTypes.External, ExpireTimeSpan = TimeSpan.FromMinutes(5) }); // Attach non-cookie auth providers var nonCookieAuthers = auth .Authenticators .Where(p => !String.Equals( p.Key, Authenticator.GetName(typeof(LocalUserAuthenticator)), StringComparison.OrdinalIgnoreCase)) .Select(p => p.Value); foreach (var auther in nonCookieAuthers) { auther.Startup(config, app).Wait(); } // Catch unobserved exceptions from threads before they cause IIS to crash: TaskScheduler.UnobservedTaskException += (sender, exArgs) => { // Send to AppInsights try { var telemetryClient = new TelemetryClient(); telemetryClient.TrackException(exArgs.Exception, new Dictionary <string, string>() { { "ExceptionOrigin", "UnobservedTaskException" } }); } catch (Exception) { // this is a tragic moment... swallow Exception to prevent crashing IIS } // Send to ELMAH try { HttpContext current = HttpContext.Current; if (current != null) { var errorSignal = ErrorSignal.FromContext(current); if (errorSignal != null) { errorSignal.Raise(exArgs.Exception, current); } } } catch (Exception) { // more tragedy... swallow Exception to prevent crashing IIS } exArgs.SetObserved(); }; HasRun = true; }
/// <summary> /// Gets the achievements from http://steamcommunity.com/id/[customurl]/[game]/?xml=1. /// </summary> /// <param name="steamUserId">The steam user id.</param> /// <param name="closedOnly">if set to <c>true</c> [closed only].</param> /// <returns></returns> private ICollection <UserAchievement> GetAchievements(string steamUserId, bool closedOnly) { if (steamUserId == null) { throw new ArgumentNullException("steamUserId"); } List <UserAchievement> achievements = new List <UserAchievement>(); IEnumerable <Game> games = GetGames(steamUserId); if (closedOnly) { games = games.Where(g => g.PlayedRecently); } foreach (Game game in games) { Uri xmlStatsUrl = new Uri(game.StatsUrl + "/?xml=1", UriKind.Absolute); Debug.WriteLine(xmlStatsUrl); string xml = _webClient.DownloadString(xmlStatsUrl); if (xml == null) { continue; } IEnumerable <UserAchievement> gameAchievements; try { if (closedOnly) { gameAchievements = _achievementParser.ParseClosed(xml); } else { gameAchievements = _achievementParser.Parse(xml); } } catch (XmlException ex) { // log and ignore invalid achievement xml HttpContext context = HttpContext.Current; if (context != null) { ErrorSignal signal = ErrorSignal.FromContext(context); if (signal != null) { string message = String.Format("Invalid xml for {0} stats: {1}.", game.Name, game.StatsUrl); Exception exception = new InvalidStatsXmlException(message, ex); signal.Raise(exception); } } continue; } if (!gameAchievements.Any()) { continue; } List <UserAchievement> achievementList = gameAchievements.ToList(); Game game1 = game; achievementList.ForEach(a => a.Game = game1); achievements.AddRange(achievementList); } return(achievements); }
private static void RaiseErrorSignal(Exception e) { var context = HttpContext.Current; ErrorSignal.FromContext(context).Raise(e, context); }
public static void Log(System.Web.HttpContext context, string message) { ErrorSignal.FromContext(context).Raise(new Exception(message)); }