public void CanUpdateSettingsFromServer() { var config = new ExceptionlessConfiguration(DependencyResolver.Default); config.ApiKey = "LhhP1C9gijpSKCslHHCvwdSIz298twx271n1l6xw"; config.Settings["LocalSetting"] = "1"; config.Settings["LocalSettingToOverride"] = "1"; var submissionClient = new Mock<ISubmissionClient>(); submissionClient.Setup(m => m.PostEvents(It.IsAny<IEnumerable<Event>>(), config, It.IsAny<IJsonSerializer>())) .Callback(() => SettingsManager.CheckVersion(1, config)) .Returns(() => new SubmissionResponse(202, "Accepted")); submissionClient.Setup(m => m.GetSettings(config, It.IsAny<IJsonSerializer>())) .Returns(() => new SettingsResponse(true, new SettingsDictionary { { "Test", "Test" }, { "LocalSettingToOverride", "2" } }, 1)); config.Resolver.Register<ISubmissionClient>(submissionClient.Object); var client = new ExceptionlessClient(config); Assert.Equal(2, client.Configuration.Settings.Count); Assert.False(client.Configuration.Settings.ContainsKey("Test")); Assert.Equal("1", client.Configuration.Settings["LocalSettingToOverride"]); client.SubmitEvent(new Event { Type = "Log", Message = "Test" }); client.ProcessQueue(); Assert.True(client.Configuration.Settings.ContainsKey("Test")); Assert.Equal("2", client.Configuration.Settings["LocalSettingToOverride"]); Assert.Equal(3, client.Configuration.Settings.Count); var storage = config.Resolver.GetFileStorage() as InMemoryObjectStorage; Assert.NotNull(config.GetQueueName()); Assert.True(storage.Exists(config.GetQueueName() + "\\server-settings.json")); config.Settings.Clear(); config.ApplySavedServerSettings(); Assert.True(client.Configuration.Settings.ContainsKey("Test")); Assert.Equal("2", client.Configuration.Settings["LocalSettingToOverride"]); Assert.Equal(2, client.Configuration.Settings.Count); }
public void SendSimpleErrorNotification() { PersistentEvent ev = null; var client = new ExceptionlessClient("123456789"); try { throw new Exception("Happy days are here again..."); } catch (Exception ex) { var builder = ex.ToExceptionless(client: client); EventEnrichmentManager.Enrich(new EventEnrichmentContext(client, builder.EnrichmentContextData), builder.Target); ev = Mapper.Map<PersistentEvent>(builder.Target); } ev.Id = "1"; ev.OrganizationId = "1"; ev.ProjectId = "1"; ev.StackId = "1"; var mailer = IoC.GetInstance<Mailer>(); mailer.SendNoticeAsync(Settings.Current.TestEmailAddress, new EventNotification { Event = ev, IsNew = true, IsCritical = true, IsRegression = false, TotalOccurrences = 1, ProjectName = "Testing" }).Wait(); }
public static bool Read(ClientConfiguration configuration, ExceptionlessClient client) { try { // step 1: read attributes into settings ReadAttributes(configuration, client); #if !SILVERLIGHT && !PORTABLE40 // step 2: read app.config into settings ReadApplicationConfiguration(configuration, client); #endif // step 3: load settings saved to disk ReadSavedConfiguration(configuration, client); // set default values ReadDefaults(configuration, client); // fix up paths with |DataDirectory| ExpandPaths(configuration); return true; } catch (Exception ex) { client.Log.FormattedError(ex, "Error reading configuration: {0}", ex.Message); return false; } }
public static RequestInfo Collect(NancyContext context, ExceptionlessClient client) { if (context == null) return null; var info = new RequestInfo { ClientIpAddress = context.Request.UserHostAddress, HttpMethod = context.Request.Method }; if (context.Request.Headers.UserAgent != null) info.UserAgent = context.Request.Headers.UserAgent; if (context.Request.Url != null) { info.Host = context.Request.Url.HostName; info.IsSecure = context.Request.Url.IsSecure; info.Path = context.Request.Url.BasePath + context.Request.Url.Path; info.Port = context.Request.Url.Port ?? 80; } if (context.Request.Headers.Referrer != null) info.Referrer = context.Request.Headers.Referrer; info.Cookies = context.Request.Cookies.ToDictionary(client); if (context.Request.Url != null && !String.IsNullOrWhiteSpace(context.Request.Url.Query)) info.QueryString = HttpUtility.ParseQueryString(context.Request.Url.Query).ToDictionary(client); return info; }
public void ErrorPlugin_IgnoredProperties() { var exception = new MyApplicationException("Test") { IgnoredProperty = "Test", RandomValue = "Test" }; var errorPlugins = new List<IEventPlugin> { new ErrorPlugin(), new SimpleErrorPlugin() }; foreach (var plugin in errorPlugins) { var client = new ExceptionlessClient(); var context = new EventPluginContext(client, new Event()); context.ContextData.SetException(exception); plugin.Run(context); IData error = context.Event.GetError() as IData ?? context.Event.GetSimpleError(); Assert.NotNull(error); Assert.True(error.Data.ContainsKey(Error.KnownDataKeys.ExtraProperties)); var json = error.Data[Error.KnownDataKeys.ExtraProperties] as string; Assert.Equal("{\"ignored_property\":\"Test\",\"random_value\":\"Test\"}", json); client.Configuration.AddDataExclusions("Ignore*"); context = new EventPluginContext(client, new Event()); context.ContextData.SetException(exception); plugin.Run(context); error = context.Event.GetError() as IData ?? context.Event.GetSimpleError(); Assert.NotNull(error); Assert.True(error.Data.ContainsKey(Error.KnownDataKeys.ExtraProperties)); json = error.Data[Error.KnownDataKeys.ExtraProperties] as string; Assert.Equal("{\"random_value\":\"Test\"}", json); } }
internal ExceptionlessPluginContext(ExceptionlessClient client, IEnumerable<KeyValuePair<string, object>> data = null) { Client = client; Data = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); if (data != null) { foreach (var kvp in data) Data.Add(kvp); } }
public void EnvironmentInfo_IncorrectEventType(string eventType) { var client = new ExceptionlessClient(); var context = new EventPluginContext(client, new Event { Type = eventType }); var plugin = new EnvironmentInfoPlugin(); plugin.Run(context); Assert.Equal(0, context.Event.Data.Count); }
public void WillLockConfig() { var client = new ExceptionlessClient(); client.Configuration.Resolver.Register<ISubmissionClient, InMemorySubmissionClient>(); client.Configuration.ApiKey = "LhhP1C9gijpSKCslHHCvwdSIz298twx271n1l6xw"; client.SubmitEvent(new Event()); Assert.Throws<ArgumentException>(() => client.Configuration.ApiKey = "blah"); Assert.Throws<ArgumentException>(() => client.Configuration.ServerUrl = "blah"); }
public void EnvironmentInfo_ShouldAddSessionStart() { var client = new ExceptionlessClient(); var context = new EventPluginContext(client, new Event { Type = Event.KnownTypes.SessionStart }); var plugin = new EnvironmentInfoPlugin(); plugin.Run(context); Assert.Equal(1, context.Event.Data.Count); Assert.NotNull(context.Event.Data[Event.KnownDataKeys.EnvironmentInfo]); }
/// <summary> /// Sets the properties from an exception. /// </summary> /// <param name="exception">The exception to populate properties from.</param> /// <param name="client"> /// The ExceptionlessClient instance used for configuration. If a client is not specified, it will use /// ExceptionlessClient.Default. /// </param> public static SimpleError ToSimpleErrorModel(this Exception exception, ExceptionlessClient client = null) { if (client == null) client = ExceptionlessClient.Default; var log = client.Configuration.Resolver.GetLog(); Type type = exception.GetType(); var error = new SimpleError { Message = GetMessage(exception), Type = type.FullName, StackTrace = exception.StackTrace }; var exclusions = _exceptionExclusions.Union(client.Configuration.DataExclusions).ToList(); try { if (exception.Data != null) { foreach (object k in exception.Data.Keys) { string key = k != null ? k.ToString() : null; if (String.IsNullOrEmpty(key) || key.AnyWildcardMatches(exclusions, true)) continue; var item = exception.Data[k]; if (item == null) continue; error.Data[key] = item; } } } catch (Exception ex) { log.Error(typeof(ExceptionlessClient), ex, "Error populating Data: " + ex.Message); } try { var extraProperties = type.GetPublicProperties().Where(p => !p.Name.AnyWildcardMatches(exclusions, true)).ToDictionary(p => p.Name, p => { try { return p.GetValue(exception, null); } catch {} return null; }); extraProperties = extraProperties.Where(kvp => !ValueIsEmpty(kvp.Value)).ToDictionary(kvp => kvp.Key, kvp => kvp.Value); if (extraProperties.Count > 0 && !error.Data.ContainsKey(SimpleError.KnownDataKeys.ExtraProperties)) { error.AddObject(new ExtendedDataInfo { Data = extraProperties, Name = SimpleError.KnownDataKeys.ExtraProperties, IgnoreSerializationErrors = true, MaxDepthToSerialize = 5 }, client); } } catch {} if (exception.InnerException != null) error.Inner = exception.InnerException.ToSimpleErrorModel(client); return error; }
public static RequestInfo Collect(ExceptionlessClient client, HttpContextBase context) { if (context == null) return null; var info = new RequestInfo { HttpMethod = context.Request.HttpMethod, UserAgent = context.Request.UserAgent, Path = String.IsNullOrEmpty(context.Request.Path) ? "/" : context.Request.Path }; try { info.ClientIpAddress = context.Request.UserHostAddress; } catch (ArgumentException ex) { client.Log.Error(ex, "An error occurred while setting the Client Ip Address."); } try { info.IsSecure = context.Request.IsSecureConnection; } catch (ArgumentException ex) { client.Log.Error(ex, "An error occurred while setting Is Secure Connection."); } if (context.Request.Url != null) info.Host = context.Request.Url.Host; if (context.Request.UrlReferrer != null) info.Referrer = context.Request.UrlReferrer.ToString(); if (context.Request.Url != null) info.Port = context.Request.Url.Port; info.Cookies = context.Request.Cookies.ToDictionary(client); if (context.Request.Form.Count > 0) info.PostData = context.Request.Form.ToDictionary(client); else if (context.Request.ContentLength > 0 && context.Request.ContentLength < 1024 * 4) { try { context.Request.InputStream.Position = 0; using (var inputStream = new StreamReader(context.Request.InputStream)) info.PostData = inputStream.ReadToEnd(); } catch (Exception ex) { info.PostData = "Error retrieving POST data: " + ex.Message; } } else if (context.Request.ContentLength > 0) { string value = Math.Round(context.Request.ContentLength / 1024m, 0).ToString("N0"); info.PostData = String.Format("Data is too large ({0}) to be included.", value + "kb"); } try { info.QueryString = context.Request.QueryString.ToDictionary(client); } catch (Exception ex) { client.Log.Error(ex, "An error occurred while getting the cookies"); } return info; }
private static Dictionary<string, string> ToDictionary(this IEnumerable<KeyValuePair<string, string>> cookies, ExceptionlessClient client) { var d = new Dictionary<string, string>(); foreach (var kv in cookies.Where(pair => !String.IsNullOrEmpty(pair.Key) && !pair.Key.AnyWildcardMatches(_ignoredCookies, true) && !pair.Key.AnyWildcardMatches(client.Configuration.DataExclusions, true))) { if (!d.ContainsKey(kv.Key)) d.Add(kv.Key, kv.Value); } return d; }
private static Error ToErrorModelInternal(Exception exception, ExceptionlessClient client, bool isInner = false) { var log = client.Configuration.Resolver.GetLog(); Type type = exception.GetType(); var error = new Error { Message = exception.GetMessage(), Type = type.FullName }; if (!isInner) error.Modules = GetLoadedModules(log); error.PopulateStackTrace(error, exception, log); try { PropertyInfo info = type.GetProperty("HResult", BindingFlags.NonPublic | BindingFlags.Instance); if (info != null) error.Code = info.GetValue(exception, null).ToString(); } catch (Exception) { } try { if (exception.TargetSite != null) { error.TargetMethod = new Method(); error.TargetMethod.PopulateMethod(error, exception.TargetSite); } } catch (Exception ex) { log.Error(typeof(ExceptionlessClient), ex, "Error populating TargetMethod: " + ex.Message); } try { var exclusions = _exceptionExclusions.Union(client.Configuration.DataExclusions); var extraProperties = type.GetPublicProperties().Where(p => !p.Name.AnyWildcardMatches(exclusions, true)).ToDictionary(p => p.Name, p => { try { return p.GetValue(exception, null); } catch { } return null; }); extraProperties = extraProperties.Where(kvp => !ValueIsEmpty(kvp.Value)).ToDictionary(kvp => kvp.Key, kvp => kvp.Value); if (extraProperties.Count > 0 && !error.Data.ContainsKey(Error.KnownDataKeys.ExtraProperties)) { error.AddObject(new ExtendedDataInfo { Data = extraProperties, Name = Error.KnownDataKeys.ExtraProperties, IgnoreSerializationErrors = true, MaxDepthToSerialize = 5 }, client); } } catch { } if (exception.InnerException != null) error.Inner = ToErrorModelInternal(exception.InnerException, client, true); return error; }
public void EnvironmentInfo_CanRunInParallel() { var client = new ExceptionlessClient(); var ev = new Event { Type = Event.KnownTypes.SessionStart }; var plugin = new EnvironmentInfoPlugin(); Parallel.For(0, 10000, i => { var context = new EventPluginContext(client, ev); plugin.Run(context); Assert.Equal(1, context.Event.Data.Count); Assert.NotNull(context.Event.Data[Event.KnownDataKeys.EnvironmentInfo]); }); }
public override void ActivateOptions() { if (String.IsNullOrEmpty(ApiKey) && String.IsNullOrEmpty(ServerUrl)) return; _client = new ExceptionlessClient(config => { if (!String.IsNullOrEmpty(ApiKey) && ApiKey != "API_KEY_HERE") config.ApiKey = ApiKey; if (!String.IsNullOrEmpty(ServerUrl)) config.ServerUrl = ServerUrl; config.UseInMemoryStorage(); }); }
protected override void InitializeTarget() { base.InitializeTarget(); if (!String.IsNullOrEmpty(ApiKey) || !String.IsNullOrEmpty(ServerUrl)) _client = new ExceptionlessClient(config => { if (!String.IsNullOrEmpty(ApiKey) && ApiKey != "API_KEY_HERE") config.ApiKey = ApiKey; if (!String.IsNullOrEmpty(ServerUrl)) config.ServerUrl = ServerUrl; config.UseInMemoryStorage(); }); }
private static Dictionary<string, string> ToDictionary(this IEnumerable<CookieHeaderValue> cookies, ExceptionlessClient client) { var d = new Dictionary<string, string>(); foreach (CookieHeaderValue cookie in cookies) { foreach (CookieState innerCookie in cookie.Cookies.Where(k => !String.IsNullOrEmpty(k.Name) && !k.Name.AnyWildcardMatches(_ignoredCookies, true) && !k.Name.AnyWildcardMatches(client.Configuration.DataExclusions, true))) { if (innerCookie != null && !d.ContainsKey(innerCookie.Name)) d.Add(innerCookie.Name, innerCookie.Value); } } return d; }
public void CanCancel() { var client = new ExceptionlessClient(); foreach (var plugin in client.Configuration.Plugins) client.Configuration.RemovePlugin(plugin.Key); client.Configuration.AddPlugin("cancel", 1, ctx => ctx.Cancel = true); client.Configuration.AddPlugin("add-tag", 2, ctx => ctx.Event.Tags.Add("Was Not Canceled")); var context = new EventPluginContext(client, new Event()); EventPluginManager.Run(context); Assert.True(context.Cancel); Assert.Equal(0, context.Event.Tags.Count); }
public void CanConfigureClientUsingActionMethod() { const string version = "1.2.3"; var client = new ExceptionlessClient(c => { c.ApiKey = "LhhP1C9gijpSKCslHHCvwdSIz298twx271n1l6xw"; c.ServerUrl = "http://localhost:45000"; c.SetVersion(version); }); Assert.Equal("LhhP1C9gijpSKCslHHCvwdSIz298twx271n1l6xw", client.Configuration.ApiKey); Assert.Equal("http://localhost:45000", client.Configuration.ServerUrl); Assert.Equal(version, client.Configuration.DefaultData[Event.KnownDataKeys.Version].ToString()); }
public static RequestInfo Collect(HttpActionContext context, ExceptionlessClient client) { if (context == null) return null; var info = new RequestInfo { ClientIpAddress = context.Request.GetClientIpAddress(), HttpMethod = context.Request.Method.Method }; if (context.Request.Headers.UserAgent != null) info.UserAgent = context.Request.Headers.UserAgent.ToString(); if (context.Request.RequestUri != null) { info.Host = context.Request.RequestUri.Host; info.IsSecure = context.Request.RequestUri.Scheme == "https"; info.Path = String.IsNullOrEmpty(context.Request.RequestUri.LocalPath) ? "/" : context.Request.RequestUri.LocalPath; info.Port = context.Request.RequestUri.Port; } if (context.Request.Headers.Referrer != null) info.Referrer = context.Request.Headers.Referrer.ToString(); info.Cookies = context.Request.Headers.GetCookies().ToDictionary(client); //if (context.Request.Form.Count > 0) { // info.PostData = context.Request.Form.AllKeys.Distinct().Where(k => !String.IsNullOrEmpty(k) && !_ignoredFormFields.Contains(k)).ToDictionary(k => k, k => { // try { // return context.Request.Form.Get(k); // } catch (Exception ex) { // return ex.Message; // } // }); //} else if (context.Request.ContentLength > 0 && context.Request.ContentLength < 1024 * 4) { // try { // context.Request.InputStream.Position = 0; // using (var inputStream = new StreamReader(context.Request.InputStream)) { // info.PostData = inputStream.ReadToEnd(); // } // } catch (Exception ex) { // info.PostData = "Error retrieving POST data: " + ex.Message; // } //} else if (context.Request.ContentLength > 0) { // string value = Math.Round(context.Request.ContentLength / 1024m, 0).ToString("N0"); // info.PostData = String.Format("Data is too large ({0}) to be included.", value + "kb"); //} info.QueryString = context.Request.RequestUri.ParseQueryString().ToDictionary(client); return info; }
public void ShouldUseReferenceIds() { var client = new ExceptionlessClient(); foreach (var plugin in client.Configuration.Plugins) client.Configuration.RemovePlugin(plugin.Key); var context = new EventPluginContext(client, new Event { Type = Event.KnownTypes.Error }); EventPluginManager.Run(context); Assert.Null(context.Event.ReferenceId); client.Configuration.UseReferenceIds(); context = new EventPluginContext(client, new Event { Type = Event.KnownTypes.Error }); EventPluginManager.Run(context); Assert.NotNull(context.Event.ReferenceId); }
public void CreateNewConfiguration() { DeleteConfig(); var client = new ExceptionlessClient(); LocalConfigurationDictionary localConfiguration = LocalConfigurationDictionary.Create(DEFAULT_STORE, client); Assert.NotNull(localConfiguration); Assert.False(localConfiguration.IsDirty); Assert.NotEqual(Guid.Empty, localConfiguration.InstallIdentifier); using (var store = new IsolatedStorageDirectory(DEFAULT_STORE)) { Assert.True(store.FileExists(CONFIG_FILENAME)); Console.WriteLine(store.ReadFileAsString(CONFIG_FILENAME)); } }
public static void UnregisterApplicationDispatcherUnhandledExceptionHandler(this ExceptionlessClient client) { if (_onApplicationDispatcherUnhandledException == null) { return; } if (System.Windows.Application.Current != null) { System.Windows.Application.Current.DispatcherUnhandledException -= _onApplicationDispatcherUnhandledException; } _onApplicationDispatcherUnhandledException = null; }
public void EnvironmentInfo_ShouldAddSessionStart() { var client = new ExceptionlessClient(); var context = new EventEnrichmentContext(client); var ev = new Event { Type = Event.KnownTypes.SessionStart }; var enrichment = new EnvironmentInfoEnrichment(); enrichment.Enrich(context, ev); Assert.Equal(1, ev.Data.Count); Assert.NotNull(ev.Data[Event.KnownDataKeys.EnvironmentInfo]); }
public EventEnrichmentContext(ExceptionlessClient client, IEnumerable <KeyValuePair <string, object> > contextData = null) { Client = client; ContextData = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase); if (contextData == null) { return; } foreach (var kvp in contextData) { ContextData.Add(kvp); } }
public void PrivateInformation_WillSetIdentity() { var client = new ExceptionlessClient(); var plugin = new SetEnvironmentUserPlugin(); var context = new EventPluginContext(client, new Event { Type = Event.KnownTypes.Log, Message = "test" }); plugin.Run(context); var user = context.Event.GetUserIdentity(); Assert.Equal(Environment.UserName, user.Identity); }
public void IsDirtyTests() { DeleteConfig(); var client = new ExceptionlessClient(); LocalConfigurationDictionary localConfiguration = LocalConfigurationDictionary.Create(DEFAULT_STORE, client); Assert.NotNull(localConfiguration); Assert.False(localConfiguration.IsDirty); localConfiguration.StartCount++; Assert.True(localConfiguration.IsDirty); // TODO: this fails because of line 63 in ObservableConcurrentDictionary. It fails to fire the event in real time. Assert.True(localConfiguration.Save()); Assert.False(localConfiguration.IsDirty); }
public static void UnregisterOnProcessExitHandler(this ExceptionlessClient client) { if (client == null) { throw new ArgumentNullException(nameof(client)); } if (_onProcessExit == null) { return; } AppDomain.CurrentDomain.ProcessExit -= _onProcessExit; _onProcessExit = null; }
public void EnvironmentInfo_CanRunInParallel() { var client = new ExceptionlessClient(); var ev = new Event { Type = Event.KnownTypes.Session }; var plugin = new EnvironmentInfoPlugin(); Parallel.For(0, 10000, i => { var context = new EventPluginContext(client, ev); plugin.Run(context); Assert.Equal(1, context.Event.Data.Count); Assert.NotNull(context.Event.Data[Event.KnownDataKeys.EnvironmentInfo]); }); }
public static void UnregisterAppDomainUnhandledExceptionHandler(this ExceptionlessClient client) { if (client == null) { throw new ArgumentNullException(nameof(client)); } if (_onAppDomainUnhandledException == null) { return; } AppDomain.CurrentDomain.UnhandledException -= _onAppDomainUnhandledException; _onAppDomainUnhandledException = null; }
public static void UnregisterApplicationThreadExceptionHandler(this ExceptionlessClient client) { if (client == null) { throw new ArgumentNullException(nameof(client)); } if (_onApplicationThreadException == null) { return; } System.Windows.Forms.Application.ThreadException -= _onApplicationThreadException; _onApplicationThreadException = null; }
/// <summary>Creates a new Exceptionless sink.</summary> /// <param name="loggerConfiguration">The logger configuration.</param> /// <param name="additionalOperation">Any additional operation to run against the build exceptions</param> /// <param name="includeProperties">If false it suppressed sending the Serilog properties to Exceptionless</param> /// <param name="restrictedToMinimumLevel">The minimum log event level required in order to write an event to the sink.</param> /// <param name="client">Optional instance of <see cref="ExceptionlessClient"/> to use.</param> /// <returns>The <see cref="LoggerConfiguration"/>.</returns> /// <exception cref="ArgumentNullException"></exception> public static LoggerConfiguration Exceptionless( this LoggerSinkConfiguration loggerConfiguration, Func <EventBuilder, EventBuilder> additionalOperation = null, bool includeProperties = true, LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum, ExceptionlessClient client = null ) { if (loggerConfiguration == null) { throw new ArgumentNullException(nameof(loggerConfiguration)); } return(loggerConfiguration.Sink(new ExceptionlessSink(additionalOperation, includeProperties, client), restrictedToMinimumLevel)); }
private void Run(ExceptionlessClient client) { bool failed = true; var callback = client.Configuration.ServerCertificateValidationCallback; client.Configuration.ServerCertificateValidationCallback = x => { failed = false; return(callback(x)); }; var submissionClient = client.Configuration.Resolver.Resolve <ISubmissionClient>(); var response = submissionClient.GetSettings(client.Configuration, 1, null); Assert.Contains(" 404 ", response.Message); Assert.False(failed, "Validation Callback was not invoked"); }
public static void UnregisterHttpApplicationErrorHandler(this ExceptionlessClient client, HttpApplication app) { if (client == null) { throw new ArgumentNullException(nameof(client)); } if (_onHttpApplicationError == null) { return; } app.Error -= _onHttpApplicationError; _onHttpApplicationError = null; }
public static void SubmitNotFoundWithCheck(this ExceptionlessClient client, string url) { try { using (var webClient = new WebClient()) using (var stream = webClient.OpenRead("http://www.google.com")) { client.SubmitNotFound(url); } } catch { //Client just has no internet connection } }
public void IgnoreDuplicate() { ExceptionlessClient client = GetClient(); try { throw new ApplicationException(); } catch (Exception ex) { client.SubmitError(ex); client.SubmitError(ex); } List <Manifest> manifests = client.Queue.GetManifests().ToList(); Assert.Equal(1, manifests.Count); }
public static void UnregisterAppDomainUnhandledExceptionHandler(this ExceptionlessClient client, AppDomain appDomain = null) { if (_onAppDomainUnhandledException == null) { return; } if (appDomain == null) { appDomain = AppDomain.CurrentDomain; } appDomain.UnhandledException -= _onAppDomainUnhandledException; _onAppDomainUnhandledException = null; }
public static void UnregisterTaskSchedulerUnobservedTaskExceptionHandler(this ExceptionlessClient client) { if (client == null) { throw new ArgumentNullException(nameof(client)); } if (_onTaskSchedulerOnUnobservedTaskException == null) { return; } TaskScheduler.UnobservedTaskException -= _onTaskSchedulerOnUnobservedTaskException; _onTaskSchedulerOnUnobservedTaskException = null; }
public void CanUpdateSettingsFromServer() { var config = new ExceptionlessConfiguration(DependencyResolver.Default) { ApiKey = "LhhP1C9gijpSKCslHHCvwdSIz298twx271n1l6xw", Settings = { ["LocalSetting"] = "1", ["LocalSettingToOverride"] = "1" } }; var submissionClient = new Mock <ISubmissionClient>(); submissionClient.Setup(m => m.PostEvents(It.IsAny <IEnumerable <Event> >(), config, It.IsAny <IJsonSerializer>())) .Callback(() => SettingsManager.CheckVersion(1, config)) .Returns(() => new SubmissionResponse(202, "Accepted")); submissionClient.Setup(m => m.GetSettings(config, 0, It.IsAny <IJsonSerializer>())) .Returns(() => new SettingsResponse(true, new SettingsDictionary { { "Test", "Test" }, { "LocalSettingToOverride", "2" } }, 1)); config.Resolver.Register <ISubmissionClient>(submissionClient.Object); var client = new ExceptionlessClient(config); Assert.Equal(2, client.Configuration.Settings.Count); Assert.False(client.Configuration.Settings.ContainsKey("Test")); Assert.Equal("1", client.Configuration.Settings["LocalSettingToOverride"]); client.SubmitEvent(new Event { Type = "Log", Message = "Test" }); client.ProcessQueue(); Assert.True(client.Configuration.Settings.ContainsKey("Test")); Assert.Equal("2", client.Configuration.Settings["LocalSettingToOverride"]); Assert.Equal(3, client.Configuration.Settings.Count); var storage = config.Resolver.GetFileStorage() as InMemoryObjectStorage; Assert.NotNull(storage); Assert.NotNull(config.GetQueueName()); Assert.True(storage.Exists(Path.Combine(config.GetQueueName(), "server-settings.json"))); config.Settings.Clear(); config.ApplySavedServerSettings(); Assert.True(client.Configuration.Settings.ContainsKey("Test")); Assert.Equal("2", client.Configuration.Settings["LocalSettingToOverride"]); Assert.Equal(2, client.Configuration.Settings.Count); }
public void CanConfigureClientUsingActionMethod() { const string version = "1.2.3"; var client = new ExceptionlessClient(c => { c.ApiKey = "e3d51ea621464280bbcb79c11fd6483e"; c.ServerUrl = Settings.Current.BaseURL; c.EnableSSL = false; c.SetVersion(version); }); Assert.Equal("e3d51ea621464280bbcb79c11fd6483e", client.Configuration.ApiKey); Assert.Equal("http://localhost:45000", client.Configuration.ServerUrl); Assert.False(client.Configuration.EnableSSL); Assert.Equal(version, client.Configuration.DefaultData[Event.KnownDataKeys.Version].ToString()); }
public void DuplicatesAllowedAfter2Seconds() { ExceptionlessClient client = GetClient(); try { throw new ApplicationException(); } catch (Exception ex) { client.SubmitError(ex); Thread.Sleep(TimeSpan.FromSeconds(2)); client.SubmitError(ex); } List <Manifest> manifests = client.Queue.GetManifests().ToList(); Assert.Equal(2, manifests.Count); }
protected override void InitializeTarget() { base.InitializeTarget(); if (!String.IsNullOrEmpty(ApiKey) || !String.IsNullOrEmpty(ServerUrl)) { _client = new ExceptionlessClient(config => { config.ApiKey = ApiKey; config.ServerUrl = ServerUrl; }); } else { _client = ExceptionlessClient.Default; } }
public void ConfigurationDefaults_IgnoredProperties() { var client = new ExceptionlessClient(); client.Configuration.DefaultData.Add("Message", "Test"); var context = new EventPluginContext(client, new Event()); var plugin = new ConfigurationDefaultsPlugin(); plugin.Run(context); Assert.Equal(1, context.Event.Data.Count); Assert.Equal("Test", context.Event.Data["Message"]); client.Configuration.AddDataExclusions("Ignore*"); client.Configuration.DefaultData.Add("Ignored", "Test"); plugin.Run(context); Assert.Equal(1, context.Event.Data.Count); Assert.Equal("Test", context.Event.Data["Message"]); }
public void ReadCorruptedConfiguration() { Assert.False(String.IsNullOrEmpty(DEFAULT_STORE)); var client = new ExceptionlessClient(); using (var dir = new IsolatedStorageDirectory(DEFAULT_STORE)) dir.WriteFile(CONFIG_FILENAME, "<blah/>>>"); Exception exception = Record.Exception(() => { client.IsConfigurationUpdateNeeded(); LocalConfigurationDictionary localConfiguration = LocalConfigurationDictionary.Create(DEFAULT_STORE, client); Assert.NotNull(localConfiguration); }); Assert.Null(exception); }
protected override void InitializeTarget() { base.InitializeTarget(); _client = new ExceptionlessClient(config => { if (!String.IsNullOrEmpty(ApiKey) && ApiKey != "API_KEY_HERE") { config.ApiKey = ApiKey; } if (!String.IsNullOrEmpty(ServerUrl)) { config.ServerUrl = ServerUrl; } config.UseInMemoryStorage(); }); }
/// <summary> /// 读取配置文件,并使其生效。如果未找到配置文件,则抛出异常 /// </summary> /// <param name="repository"></param> /// <param name="configFilePath">配置文件全路径</param> /// <param name="useExceptionless">是否启用Exceptionless</param> public static void SetConfig(ILoggerRepository repository, string configFilePath, bool useExceptionless = false) { _repository = repository; var fileInfo = new FileInfo(configFilePath); if (!fileInfo.Exists) { throw new Exception("未找到配置文件" + configFilePath); } XmlConfigurator.ConfigureAndWatch(_repository, fileInfo); _bLog2Exceptionless = useExceptionless; if (_bLog2Exceptionless) { exceptionlessClient = ExceptionlessClient.Default; } }
/// <inheritdoc/> protected override (IFullLogger logger, IMockLogTarget mockTarget) GetLogger(LogLevel minimumLogLevel) { var logTarget = new InMemoryExceptionlessLogTarget(); var exceptionlessClient = new ExceptionlessClient(); exceptionlessClient.Configuration.ApiKey = "someapikey"; var exceptionlessMinLogLevel = _splat2Exceptionless[minimumLogLevel]; exceptionlessClient.Configuration.UseInMemoryLogger(exceptionlessMinLogLevel); exceptionlessClient.Configuration.SetDefaultMinLogLevel(exceptionlessMinLogLevel); exceptionlessClient.Configuration.AddPlugin("Use Mock Log Target Interceptor", context => PluginAction(context, logTarget)); var inner = new ExceptionlessSplatLogger(typeof(ExceptionlessLoggerTests), exceptionlessClient); return(new WrappingFullLogger(inner), logTarget); }
/// <summary> /// 构造方法 Exceptionless自托管 /// </summary> public Exceptionsless() { if (LogServiceCollectionExtensions.Connection == null) { throw new ArgumentNullException("请注入Exceptionsless连接对象!"); } string apikey = LogServiceCollectionExtensions.Connection.exceptionslessOptions.Apikey; // LogConfig.GetExceptionslessConfig().Apikey; string serverUrl = LogServiceCollectionExtensions.Connection.exceptionslessOptions.ServerUrl; // LogConfig.GetExceptionslessConfig().ServerUrl; if (string.IsNullOrEmpty(apikey) || string.IsNullOrEmpty(serverUrl)) { throw new Exception("Exceptionless的apikey或serverUrl不能为空!"); } client = GetExceptionlessClient(apikey, serverUrl); }
public ActionResult <bool> LogTest() { ExceptionlessClient client = new ExceptionlessClient(c => { c.ApiKey = "KU7iGcLAMZWMOT69SUZuqtWwwaUZ8RlndbQUKyo8"; c.ServerUrl = "http://139.219.140.7:8001/"; }); client.SubmitLog("测试Exceptionless"); //client.SubmitLog("测试Exceptionless", LogLevel.Info); //client.SubmitLog("测试Exceptionless", LogLevel.Trace); //client.SubmitLog("测试Exceptionless", LogLevel.Warn); //client.SubmitLog("测试Exceptionless", LogLevel.Error); //client.SubmitLog(typeof(ValuesController).FullName, "测试Exceptionless", LogLevel.Error); //client.SubmitFeatureUsage("MyFeature"); //client.CreateFeatureUsage("MyFeature") // .AddTags("ExceptionlessTag", "Demo") // .Submit(); //var user = new { Name = "Damon"}; //client.CreateFeatureUsage("MyFeature") // .AddTags("ExceptionlessTag", "Demo") // .AddObject(user, "UserInfo")// 添加一个对象信息 // .SetProperty("Cellphone", "13100000000")// 设置手机号 // .SetReferenceId(Guid.NewGuid().ToString("N"))// 为事件设定一个编号,以便于你搜索 // .MarkAsCritical()// 标记为关键异常 // .SetGeo(43, 44)// 设置地理位置坐标 // .SetUserIdentity("userId", "userName")// 设置触发异常的用户信息 // .SetUserDescription("emailAddress", "")// 设置触发用户的一些描述 // .Submit(); //try //{ // string s = null; // string s1 = s.ToString(); //} //catch (Exception e) //{ // client.SubmitException(e); //} return(true); }
private static Dictionary<string, string> ToDictionary(this NameValueCollection values, ExceptionlessClient client) { var d = new Dictionary<string, string>(); foreach (string key in values.AllKeys) { if (key.AnyWildcardMatches(_ignoredFormFields, true) || key.AnyWildcardMatches(client.Configuration.DataExclusions, true)) continue; try { string value = values.Get(key); d.Add(key, value); } catch (Exception ex) { if (!d.ContainsKey(key)) d.Add(key, ex.Message); } } return d; }
public void CanReadConfiguration() { var client = new ExceptionlessClient(); ClientConfiguration config = ClientConfiguration.Create(client); Assert.NotNull(config); Assert.True(config.ContainsKey("AttributeOnly")); Assert.Equal(config["AttributeOnly"], "Attribute"); Assert.True(config.ContainsKey("UserNamespaces")); Assert.Equal(config["UserNamespaces"], "Exceptionless,FromConfig"); Assert.True(config.ContainsKey("ConfigAndAttribute")); Assert.Equal(config["ConfigAndAttribute"], "Config"); Assert.True(config.ContainsKey("AppConfigOnly")); Assert.Equal(config["AppConfigOnly"], "Config"); }
public static EventBuilder CreateFromLogEvent(this ExceptionlessClient client, LogEventInfo ev) { var builder = ev.Exception != null?client.CreateException(ev.Exception) : client.CreateLog(ev.FormattedMessage); builder.Target.Date = ev.TimeStamp; builder.SetSource(ev.LoggerName); if (ev.Exception == null) { builder.AddObject(ev.Level.Name, "Level"); } foreach (var p in ev.Properties) { builder.AddObject(p.Value, p.Key.ToString()); } return(builder); }
public void CanCancel() { var client = new ExceptionlessClient(); foreach (var plugin in client.Configuration.Plugins) { client.Configuration.RemovePlugin(plugin.Key); } client.Configuration.AddPlugin("cancel", 1, ctx => ctx.Cancel = true); client.Configuration.AddPlugin("add-tag", 2, ctx => ctx.Event.Tags.Add("Was Not Canceled")); var context = new EventPluginContext(client, new Event()); EventPluginManager.Run(context); Assert.True(context.Cancel); Assert.Equal(0, context.Event.Tags.Count); }
public void ConfigurationDefaults_SerializedProperties() { var client = new ExceptionlessClient(); client.Configuration.DefaultData.Add(Event.KnownDataKeys.EnvironmentInfo, new EnvironmentInfo { MachineName = "blake" }); client.Configuration.DefaultData.Add(Event.KnownDataKeys.Error, new Error { Message = "blake" }); client.Configuration.DefaultData.Add(Event.KnownDataKeys.Level, "Debug"); client.Configuration.DefaultData.Add(Event.KnownDataKeys.ManualStackingKey, "blake"); client.Configuration.DefaultData.Add(Event.KnownDataKeys.RequestInfo, new RequestInfo { Host = "blake" }); client.Configuration.DefaultData.Add(Event.KnownDataKeys.SimpleError, new SimpleError { Message = "blake" }); client.Configuration.DefaultData.Add(Event.KnownDataKeys.SubmissionMethod, "test"); client.Configuration.DefaultData.Add(Event.KnownDataKeys.TraceLog, new List<string>()); client.Configuration.DefaultData.Add(Event.KnownDataKeys.UserDescription, new UserDescription("*****@*****.**", "blake")); client.Configuration.DefaultData.Add(Event.KnownDataKeys.UserInfo, new UserInfo("blake")); client.Configuration.DefaultData.Add(Event.KnownDataKeys.Version, "1.0"); var serializer = client.Configuration.Resolver.GetJsonSerializer(); var context = new EventPluginContext(client, new Event()); var plugin = new ConfigurationDefaultsPlugin(); plugin.Run(context); Assert.Equal(11, context.Event.Data.Count); Assert.True(context.Event.Data[Event.KnownDataKeys.EnvironmentInfo] is string); Assert.Equal("blake", context.Event.GetEnvironmentInfo().MachineName); Assert.Equal("blake", context.Event.GetEnvironmentInfo(serializer).MachineName); Assert.True(context.Event.Data[Event.KnownDataKeys.Error] is string); Assert.Equal("blake", context.Event.GetError().Message); Assert.Equal("blake", context.Event.GetError(serializer).Message); Assert.Equal("Debug", context.Event.Data[Event.KnownDataKeys.Level]); Assert.Equal("blake", context.Event.Data[Event.KnownDataKeys.ManualStackingKey]); Assert.True(context.Event.Data[Event.KnownDataKeys.RequestInfo] is string); Assert.Equal("blake", context.Event.GetRequestInfo().Host); Assert.Equal("blake", context.Event.GetRequestInfo(serializer).Host); Assert.True(context.Event.Data[Event.KnownDataKeys.SimpleError] is string); Assert.Equal("blake", context.Event.GetSimpleError().Message); Assert.Equal("blake", context.Event.GetSimpleError(serializer).Message); Assert.Equal("test", context.Event.Data[Event.KnownDataKeys.SubmissionMethod]); Assert.True(context.Event.Data[Event.KnownDataKeys.TraceLog] is string); Assert.True(context.Event.Data[Event.KnownDataKeys.UserDescription] is string); Assert.Equal("blake", context.Event.GetUserDescription().Description); Assert.Equal("blake", context.Event.GetUserDescription(serializer).Description); Assert.True(context.Event.Data[Event.KnownDataKeys.UserInfo] is string); Assert.Equal("blake", context.Event.GetUserIdentity().Identity); Assert.Equal("blake", context.Event.GetUserIdentity(serializer).Identity); Assert.Equal("1.0", context.Event.Data[Event.KnownDataKeys.Version]); }
public void ConfigurationDefaults_EnsureNoDuplicateTagsOrData() { var client = new ExceptionlessClient(); var context = new EventPluginContext(client, new Event()); var plugin = new ConfigurationDefaultsPlugin(); plugin.Run(context); Assert.Equal(0, context.Event.Tags.Count); client.Configuration.DefaultTags.Add(Event.KnownTags.Critical); plugin.Run(context); Assert.Equal(1, context.Event.Tags.Count); Assert.Equal(0, context.Event.Data.Count); client.Configuration.DefaultData.Add("Message", new { Exceptionless = "Is Awesome!" }); for (int index = 0; index < 2; index++) { plugin.Run(context); Assert.Equal(1, context.Event.Tags.Count); Assert.Equal(1, context.Event.Data.Count); } }
public void IgnoreUserAgentPlugin_DiscardBot() { var client = new ExceptionlessClient(); client.Configuration.AddUserAgentBotPatterns("*Bot*"); var plugin = new IgnoreUserAgentPlugin(); var ev = new Event(); var context = new EventPluginContext(client, ev); plugin.Run(context); Assert.False(context.Cancel); ev.AddRequestInfo(new RequestInfo { UserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/601.4.4 (KHTML, like Gecko) Version/9.0.3 Safari/601.4.4" }); context = new EventPluginContext(client, ev); plugin.Run(context); Assert.False(context.Cancel); ev.AddRequestInfo(new RequestInfo { UserAgent = "Mozilla/5.0 (compatible; bingbot/2.0 +http://www.bing.com/bingbot.htm)" }); context = new EventPluginContext(client, ev); plugin.Run(context); Assert.True(context.Cancel); }
public static ExceptionlessClientInfo Collect(ExceptionlessClient client, bool includePrivateInfo = true) { if (includePrivateInfo) { return new ExceptionlessClientInfo { Version = ThisAssembly.AssemblyInformationalVersion, InstallIdentifier = client.LocalConfiguration.InstallIdentifier.ToString(), InstallDate = client.LocalConfiguration.InstallDate, StartCount = client.LocalConfiguration.StartCount, SubmitCount = client.LocalConfiguration.SubmitCount, Platform = ".NET" }; } return new ExceptionlessClientInfo { Version = ThisAssembly.AssemblyInformationalVersion, InstallDate = client.LocalConfiguration.InstallDate, StartCount = client.LocalConfiguration.StartCount, SubmitCount = client.LocalConfiguration.SubmitCount, Platform = ".NET" }; }