Ejemplo n.º 1
0
        public void Error(Exception exception, string fmt, params object[] vars)
        {
            var telemetry = new ExceptionTelemetry(exception);
            telemetry.Properties.Add("message", string.Format(fmt, vars));

            telemetryClient.TrackException(telemetry);
        }
        /// <summary>
        /// Emit the provided log event to the sink.
        /// </summary>
        /// <param name="logEvent">The log event to write.</param>
        public void Emit(LogEvent logEvent)
        {
            var renderedMessage = logEvent.RenderMessage(_formatProvider);
            
            // take logEvent and use it for the corresponding ITelemetry counterpart
            if (logEvent.Exception != null)
            {
                var exceptionTelemetry = new ExceptionTelemetry(logEvent.Exception)
                {
                    SeverityLevel = logEvent.Level.ToSeverityLevel(),
                    HandledAt = ExceptionHandledAt.UserCode,
                    Timestamp = logEvent.Timestamp
                };
                
                // write logEvent's .Properties to the AI one
                ForwardLogEventPropertiesToTelemetryProperties(exceptionTelemetry, logEvent, renderedMessage);

                _telemetryClient.TrackException(exceptionTelemetry);
            }
            else
            {
                var eventTelemetry = new EventTelemetry(logEvent.MessageTemplate.Text)
                {
                    Timestamp = logEvent.Timestamp
                };
                
                // write logEvent's .Properties to the AI one
                ForwardLogEventPropertiesToTelemetryProperties(eventTelemetry, logEvent, renderedMessage);
                
                _telemetryClient.TrackEvent(eventTelemetry);
            }
        }
        /// <summary>
        /// Implements on error callback of http module.
        /// </summary>
        public void OnError(HttpContext context)
        {
            if (this.telemetryClient == null)
            {
                throw new InvalidOperationException("Initialize has not been called on this module yet.");
            }

            if (context == null)
            {
                WebEventSource.Log.NoHttpContextWarning();
                return;
            }

            var errors = context.AllErrors;

            if (errors != null && errors.Length > 0)
            {
                foreach (Exception exp in errors)
                {
                    var exceptionTelemetry = new ExceptionTelemetry(exp);

                    if (context.Response.StatusCode >= 500)
                    {
                        exceptionTelemetry.SeverityLevel = SeverityLevel.Critical;
                    }

                    this.telemetryClient.TrackException(exceptionTelemetry);
                }
            }
        }
        public void ExceptionPropertySetterHandlesAggregateExceptionsWithMultipleNestedExceptionsAndTrimsAfterReachingMaxCount()
        {
            const int Overage = 5;
            List<Exception> innerExceptions = new List<Exception>();
            for (int i = 0; i < Constants.MaxExceptionCountToSave + Overage; i++)
            {
                innerExceptions.Add(new Exception((i + 1).ToString(CultureInfo.InvariantCulture)));
            }

            AggregateException rootLevelException = new AggregateException("0", innerExceptions);

            ExceptionTelemetry telemetry = new ExceptionTelemetry { Exception = rootLevelException };

            Assert.Equal(Constants.MaxExceptionCountToSave + 1, telemetry.Exceptions.Count);
            int counter = 0;
            foreach (ExceptionDetails details in telemetry.Exceptions.Take(Constants.MaxExceptionCountToSave))
            {
                Assert.Equal(counter.ToString(CultureInfo.InvariantCulture), details.message);
                counter++;
            }

            ExceptionDetails first = telemetry.Exceptions.First();
            ExceptionDetails last = telemetry.Exceptions.Last();
            Assert.Equal(first.id, last.outerId);
            Assert.Equal(typeof(InnerExceptionCountExceededException).FullName, last.typeName);
            Assert.Equal(
                string.Format(
                    CultureInfo.InvariantCulture,
                    "The number of inner exceptions was {0} which is larger than {1}, the maximum number allowed during transmission. All but the first {1} have been dropped.",
                    1 + Constants.MaxExceptionCountToSave + Overage,
                    Constants.MaxExceptionCountToSave),
                last.message);
        }
        public override async Task Invoke(IOwinContext context)
        {
            var operation = telemetryClient.StartOperation<RequestTelemetry>(context.Request.Path.Value);

            try
            {
                var requestTelemetry = operation.Telemetry;

                await this.Next.Invoke(context);

                requestTelemetry.HttpMethod = context.Request.Method;
                requestTelemetry.Url = context.Request.Uri;
                requestTelemetry.ResponseCode = context.Response.StatusCode.ToString();
                requestTelemetry.Success = context.Response.StatusCode >= 200 && context.Response.StatusCode < 300;

                requestTelemetry.Context.Properties["Deployment-Unit"] = "Dev";
                requestTelemetry.InitializeContextFrom(context);
            }
            catch (Exception exc)
            {
                var telemetry = new ExceptionTelemetry(exc);
                telemetry.HandledAt = ExceptionHandledAt.Unhandled;

                telemetry.InitializeContextFrom(context);
                
                telemetryClient.TrackException(telemetry);
            }
            finally
            {
                telemetryClient.StopOperation(operation);
            }
        }
        /// <summary>
        /// Implements on error callback of http module.
        /// </summary>
        public void OnError(EventWrittenEventArgs args)
        {
            if (this.telemetryClient == null)
            {
                throw new InvalidOperationException();
            }

            var platformContext = this.ResolvePlatformContext();
            var errors = platformContext.AllErrors;

            if (errors != null && errors.Length > 0)
            {
                foreach (Exception exp in errors)
                {
                    var exceptionTelemetry = new ExceptionTelemetry(exp)
                    {
                        HandledAt = ExceptionHandledAt.Platform
                    };

                    if (platformContext.Response.StatusCode >= 500)
                    {
                        exceptionTelemetry.SeverityLevel = SeverityLevel.Critical;
                    }

                    this.telemetryClient.TrackException(exceptionTelemetry);
                }
            }
        }
        public void ConstructorAddsExceptionToExceptionPropertyAndExceptionsCollectionProperty()
        {
            Exception constructorException = new Exception("ConstructorException");
            var testExceptionTelemetry = new ExceptionTelemetry(constructorException);

            Assert.Same(constructorException, testExceptionTelemetry.Exception);
            Assert.Equal(constructorException.Message, testExceptionTelemetry.Exceptions.First().message);
        }
Ejemplo n.º 8
0
    /// <summary>Tracks any exception.</summary>
    public static void TrackException(Exception ex)
    {
#if !DEBUG
        var telex = new Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry(ex);
        telex.HandledAt = Microsoft.ApplicationInsights.DataContracts.ExceptionHandledAt.UserCode;
        _telemetry.TrackException(telex);
#endif
    }
 public ExceptionTelemetryMessage(ExceptionTelemetry telemetry)
 {
     this.Time = telemetry.Timestamp.DateTime;
     this.Name = telemetry.Exception.Message;
     this.Details = "Exception of type: " + telemetry.Exception.Message + "\n\r Happened in: " + telemetry.Exception.StackTrace;
     this.Properties = telemetry.Properties.Count > 0 ? telemetry.Properties : null;
     this.Type = "Exception";
     this.Context = telemetry.Context;
 }
Ejemplo n.º 10
0
 public static void WriteException(String msg, Exception ex)
 {
     #if !DEBUG
       if ( client != null && Enabled ) {
     ExceptionTelemetry telemetry = new ExceptionTelemetry(ex);
     telemetry.Properties.Add("Message", msg);
     client.TrackException(telemetry);
       }
     #endif
 }
 public void LogException(ITelemetry telemetry)
 {
     DC.ExceptionTelemetry ex = new DC.ExceptionTelemetry();
     ex.Exception = (telemetry as ExceptionTelemetry)?.Exception;
     foreach (var item in telemetry.Properties)
     {
         ex.Properties.Add(item.Key, item.Value);
     }
     client.TrackException(ex);
 }
        public void InitializeDoesNotSetLocationIpIfProvidedInline()
        {
            var module = new TestableClientIpHeaderTelemetryInitializer();
            var telemetry = new ExceptionTelemetry();
            telemetry.Context.Location.Ip = "10.10.10.10";

            module.Initialize(telemetry);

            Assert.AreEqual("10.10.10.10", telemetry.Context.Location.Ip);
        }
        public void InitializeSetsParentIdForTelemetryUsingIdFromRequestTelemetry()
        {
            var exceptionTelemetry = new ExceptionTelemetry();
            var source = new TestableOperationCorrelationTelemetryInitializer(null);
            var requestTelemetry = source.FakeContext.CreateRequestTelemetryPrivate();

            source.Initialize(exceptionTelemetry);

            Assert.AreEqual(requestTelemetry.Id, exceptionTelemetry.Context.Operation.ParentId);
        }
        public void ExceptionPropertySetterReplacesExceptionDetailsInExceptionsCollectionProperty()
        {
            Exception constructorException = new Exception("ConstructorException");
            var testExceptionTelemetry = new ExceptionTelemetry(constructorException);

            Exception nextException = new Exception("NextException");
            testExceptionTelemetry.Exception = nextException;

            Assert.Same(nextException, testExceptionTelemetry.Exception);
            Assert.Equal(nextException.Message, testExceptionTelemetry.Exceptions.First().message);
        }
Ejemplo n.º 15
0
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'Program.Seed()'
        public static void Seed()
#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'Program.Seed()'
        {
            using (var scope = MyHost.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                var logger   = services.GetRequiredService <ILogger <Program> >();
                ApplicationDbContext context = services.GetRequiredService <ApplicationDbContext>();
                try
                {
                    context.Database.Migrate();
                }
                catch (Exception e)
                {
                    try
                    {
                        var tc        = new Microsoft.ApplicationInsights.TelemetryClient();
                        var telemetry = new Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry(e);
                        tc.TrackException(telemetry);
                    }
                    catch (Exception ex)
                    {
                        logger.LogError(ex.ToString());
                    }
                    logger.LogError(e.Message, "An error occurred migrating the DB: " + e.ToString());
                    context.Database.EnsureDeleted();
                    context.Database.EnsureCreated();
                }
                // requires using Microsoft.Extensions.Configuration;
                var config = services.GetRequiredService <IConfiguration>();
                // Set password with the Secret Manager tool.
                // dotnet user-secrets set SeedUserPW <pw>
                var testUserPw = config["SeedUserPW"];
                try
                {
                    var env = services.GetService <IHostingEnvironment>();
                    SeedData.Initialize(services, testUserPw, env).Wait();
                }
                catch (Exception ex)
                {
                    try
                    {
                        var tc        = new Microsoft.ApplicationInsights.TelemetryClient();
                        var telemetry = new Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry(ex);
                        tc.TrackException(telemetry);
                    }
                    catch (Exception e1)
                    {
                        logger.LogError(e1.ToString());
                    }
                    logger.LogError(ex.Message, "An error occurred seeding the DB: " + ex.ToString());
                }
            }
        }
        public void TestBasicExceptionPropertiesAfterRequestingControllerThatThrows()
        {
            using (var server = new InProcessServer(assemblyName))
            {
                var expectedExceptionTelemetry = new ExceptionTelemetry();
                expectedExceptionTelemetry.HandledAt = ExceptionHandledAt.Platform;
                expectedExceptionTelemetry.Exception = new InvalidOperationException();

                this.ValidateBasicException(server, "/api/exception", expectedExceptionTelemetry);
            }
        }
Ejemplo n.º 17
0
 public override void Log(ExceptionLoggerContext context)
 {
     if (context != null && context.Exception != null)
     {
         ExceptionTelemetry exception = new ExceptionTelemetry(context.Exception);
         exception.HandledAt = ExceptionHandledAt.Unhandled;
             
         client.TrackException(exception);
     }
     base.Log(context);
 }
Ejemplo n.º 18
0
        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            var excTelemetry = new ExceptionTelemetry((Exception)e.ExceptionObject)
            {
                SeverityLevel = SeverityLevel.Critical,
                HandledAt = ExceptionHandledAt.Unhandled
            };

            _telemetryClient.TrackException(excTelemetry);

            _telemetryClient.Flush();
        }
        private void TaskSchedulerOnUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs unobservedTaskExceptionEventArgs)
        {
            WindowsServerEventSource.Log.TaskSchedulerOnUnobservedTaskException();

            var exp = new ExceptionTelemetry(unobservedTaskExceptionEventArgs.Exception)
            {
                HandledAt = ExceptionHandledAt.Unhandled,
                SeverityLevel = SeverityLevel.Critical,
            };

            this.telemetryClient.TrackException(exp);
        }
Ejemplo n.º 20
0
        protected void Application_Start()
        { 
            // Read instrumentation key from azure web app settings
            string ikeyValue = Environment.GetEnvironmentVariable("APPINSIGHTS_INSTRUMENTATIONKEY");

            if (!string.IsNullOrEmpty(ikeyValue))
            {
                TelemetryConfiguration.Active.InstrumentationKey = ikeyValue;
            }

            try
            {

                AreaRegistration.RegisterAllAreas();

                GlobalConfiguration.Configure(WebApiConfig.Register);
                FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
                RouteConfig.RegisterRoutes(RouteTable.Routes);
                BundleConfig.RegisterBundles(BundleTable.Bundles);
                BindingConfig.RegisterGlobalBindings(ModelBinders.Binders, GlobalConfiguration.Configuration);
                FormatterConfig.RegisterFormatters(GlobalConfiguration.Configuration);

                ReleaseSettings.Settings.Options.PackageListingPath = Server.MapPath("~/Content/packages.json");
                ReleaseSettings.Settings.Initialize();

                PackageSettings.Settings.NugetListingPath = Server.MapPath("~/Content/nuget.json");
                PackageSettings.Settings.Initialize();

                TwitterSettings.Settings.Initialize();

                BuildSettings.Settings.Initialize();

                BlogSettings.Settings.Initialize();

                ContributorSettings.Settings.Options.ContributorListingPath = Server.MapPath("~/Content/committers.json");
                ContributorSettings.Settings.Initialize();
            }
            catch (Exception ex)
            {
                TelemetryClient client = new TelemetryClient();
                ExceptionTelemetry excTelemetry = new ExceptionTelemetry(ex);
                excTelemetry.HandledAt = ExceptionHandledAt.Unhandled;
                client.TrackException(excTelemetry);

                // this exception will terminate the process. Let's wait till telemetry will be delivered
                client.Flush();
                Thread.Sleep(1000);

                throw;
            }
        }
Ejemplo n.º 21
0
        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            if (ChatterBox.Client.Common.Settings.SignalingSettings.AppInsightsEnabled)
            {
                ExceptionTelemetry excTelemetry = new ExceptionTelemetry((Exception)e.Exception);
                excTelemetry.SeverityLevel = SeverityLevel.Critical;
                excTelemetry.HandledAt = ExceptionHandledAt.Unhandled;
                excTelemetry.Timestamp = System.DateTimeOffset.UtcNow;
                var telemetry = new TelemetryClient();
                telemetry.TrackException(excTelemetry);

                telemetry.Flush();
            }
        }
        public void SerializeAsStringMethodSerializesATelemetryCorrectly()
        {
            var exceptionTelemetry = new ExceptionTelemetry();
            string exceptionAsJson = JsonSerializer.SerializeAsString(exceptionTelemetry);

            // Expected: {"name":"Microsoft.ApplicationInsights.Exception","time":"0001-01-01T00:00:00.0000000+00:00","data":{"baseType":"ExceptionData","baseData":{"ver":2,"handledAt":"Unhandled","exceptions":[]}}}
            // Deserialize (Validates a valid JSON string)
            JObject obj = JsonConvert.DeserializeObject<JObject>(exceptionAsJson);

            // Validtes 2 random properties
            Assert.NotNull(exceptionAsJson);
            Assert.Equal("Microsoft.ApplicationInsights.Exception", obj["name"].ToString());
            Assert.Equal("Unhandled", obj["data"]["baseData"]["handledAt"].ToString());
        }
 public override void OnException(ExceptionContext filterContext)
 {
     if (filterContext != null && filterContext.HttpContext != null && filterContext.Exception != null)
     {
         //If customError is Off, then AI HTTPModule will report the exception
         if (filterContext.HttpContext.IsCustomErrorEnabled)
         {
             ExceptionTelemetry exc = new ExceptionTelemetry(filterContext.Exception);
             exc.HandledAt = ExceptionHandledAt.Platform;
             client.TrackException(exc);
         }
         base.OnException(filterContext);
     }
 }
        public void ValidateBasicException(InProcessServer server, string requestPath, ExceptionTelemetry expected)
        {
            DateTimeOffset testStart = DateTimeOffset.Now;
            var httpClient = new HttpClient();
            var task = httpClient.GetAsync(server.BaseHost + requestPath);
            task.Wait(TestTimeoutMs);
            var result = task.Result;

            var actual = server.BackChannel.Buffer.OfType<ExceptionTelemetry>().Single();

            Assert.Equal(expected.Exception.GetType(), actual.Exception.GetType());
            Assert.NotEmpty(actual.Exception.StackTrace);
            Assert.Equal(actual.HandledAt, actual.HandledAt);
            Assert.NotEmpty(actual.Context.Operation.Name);
            Assert.NotEmpty(actual.Context.Operation.Id);
        }
        public async Task Invoke(HttpContext httpContext)
        {
            try
            {
                await this.next.Invoke(httpContext);
            }
            catch (Exception exception)
            {
                var exceptionTelemetry = new ExceptionTelemetry(exception);
                exceptionTelemetry.HandledAt = ExceptionHandledAt.Platform;
                exceptionTelemetry.Context.GetInternalContext().SdkVersion = this.sdkVersion;
                this.telemetryClient.Track(exceptionTelemetry);

                throw;
            }
        }
        public void Trace(HttpRequestMessage request, string category, TraceLevel level, Action<TraceRecord> traceAction)
        {
            if (category == null)
            {
                throw new ArgumentNullException();
            }

            if (traceAction == null)
            {
                throw new ArgumentNullException();
            }

            if (level < TraceLevel.Off || level > TraceLevel.Fatal)
            {
                throw new ArgumentOutOfRangeException();
            }

            var traceRecord = new TraceRecord(request, category, level);
            traceAction(traceRecord);

            this.systemDiagnosticsTraceWriter.TranslateHttpResponseException(traceRecord);

            string message = this.systemDiagnosticsTraceWriter.Format(traceRecord);
            if (!string.IsNullOrEmpty(message))
            {
                var exception = traceRecord.Exception;
                if (exception != null)
                {
                    ExceptionTelemetry et = new ExceptionTelemetry(exception);
                    et.SeverityLevel = GetSeverityLevel(level);

                    var swh = exception as System.Web.Http.HttpResponseException;
                    
                    // Add additional message because exception message is useless
                    if (swh != null)
                    {
                        et.Properties.Add("Response Message", message);
                    }

                    this.client.TrackException(et);
                }
                else
                {
                    this.client.TrackTrace(message, GetSeverityLevel(level));
                }
            }
        }
Ejemplo n.º 27
0
        public static void TrackException(Exception exception, string logFileName = null)
        {
            if (!_initialized)
            {
                return;
            }

            var telemetryClient = new TelemetryClient();
            var telemetry = new ExceptionTelemetry(exception);

            if (!string.IsNullOrWhiteSpace(logFileName))
            {
                telemetry.Properties.Add("LogFile", logFileName);
            }

            telemetryClient.TrackException(telemetry);
            telemetryClient.Flush();
        }
        public override void OnException(ExceptionContext filterContext)
        {
            if (filterContext != null && filterContext.Exception != null)
            {
                var telemetry = new ExceptionTelemetry(filterContext.Exception)
                {
                    Timestamp = DateTimeOffset.UtcNow
                };
                foreach (var item in GetErrorProperties(filterContext.Exception, 0))
                {
                    telemetry.Properties.Add(item.Item1, item.Item2);
                }

                new TelemetryClient().TrackException(telemetry);
            }

            base.OnException(filterContext);
        }
		public void TrackError (TelemetryError error)
		{
			var properties = new Dictionary<string, string>();
			var metrics = new Dictionary<string, double>();

			Enrich (properties, metrics);

			var exception = error.Exception;
			var telemetry = new ExceptionTelemetry (exception);

			foreach (var property in telemetryTranslator.Translate (properties)) {
				telemetry.Properties.Add (property.Key, property.Value);
			}

			foreach (DictionaryEntry dataItem in exception.Data) {
				telemetry.Properties.Add ((string)dataItem.Key, (string)dataItem.Value);
			}

			client.TrackException (telemetry);
		}
        void IWcfTelemetryModule.OnError(IOperationContext operation, Exception error)
        {
            if ( operation == null )
                throw new ArgumentNullException("operation");
            if ( error == null )
                throw new ArgumentNullException("error");
            if ( telemetryClient == null )
                return;

            ExceptionTelemetry telemetry = new ExceptionTelemetry(error);
            if ( error is FaultException )
            {
                telemetry.SeverityLevel = SeverityLevel.Error;
                telemetry.HandledAt = ExceptionHandledAt.UserCode;
            } else
            {
                telemetry.SeverityLevel = SeverityLevel.Critical;
                telemetry.HandledAt = ExceptionHandledAt.Platform;
            }
            telemetryClient.TrackException(error);
        }
Ejemplo n.º 31
0
 public void TrackException(Exception e) {
     ExceptionTelemetry excTelemetry = new ExceptionTelemetry(e);
     excTelemetry.SeverityLevel = SeverityLevel.Critical;
     excTelemetry.HandledAt = ExceptionHandledAt.Unhandled;
     excTelemetry.Timestamp = System.DateTimeOffset.UtcNow;
     _telemetry.TrackException(excTelemetry);
 }
        private void SendException(LoggingEvent loggingEvent)
        {
            try
            {
                var exceptionTelemetry = new ExceptionTelemetry(loggingEvent.ExceptionObject)
                {
                    SeverityLevel = this.GetSeverityLevel(loggingEvent.Level)
                };

                string message = null;
                if (loggingEvent.RenderedMessage != null)
                {
                    message = this.RenderLoggingEvent(loggingEvent);
                }

                if (!string.IsNullOrEmpty(message))
                {
                    exceptionTelemetry.Properties.Add("Message", message);
                }

                this.BuildCustomProperties(loggingEvent, exceptionTelemetry);
                this.telemetryClient.Track(exceptionTelemetry);
            }
            catch (ArgumentNullException exception)
            {
                throw new LogException(exception.Message, exception);
            }
        }
        public void ExceptionTelemetryImplementsISupportAdvancedSamplingContract()
        {
            var telemetry = new ExceptionTelemetry();

            Assert.IsNotNull(telemetry as ISupportAdvancedSampling);
        }
        public void ExceptionTelemetryCreatedBasedOnCustomData()
        {
            // ARRANGE
            var topLevelexceptionDetails = new ExceptionDetailsInfo(1, -1, "TopLevelException", "Top level exception",
                                                                    true, "Top level exception stack", new[]
            {
                new StackFrame("Some.Assembly", "SomeFile.dll", 3, 33, "TopLevelMethod"),
                new StackFrame("Some.Assembly", "SomeOtherFile.dll", 2, 22, "LowerLevelMethod"),
                new StackFrame("Some.Assembly", "YetAnotherFile.dll", 1, 11, "LowLevelMethod")
            });

            var innerExceptionDetails = new ExceptionDetailsInfo(2, 1, "InnerException", "Inner exception", false,
                                                                 "Inner exception stack", new[]
            {
                new StackFrame("Some.Assembly", "ImportantFile.dll", 2, 22, "InnerMethod"),
                new StackFrame("Some.Assembly", "LessImportantFile.dll", 1, 11, "DeeperInnerMethod")
            });

            // ACT
            ExceptionTelemetry item = new ExceptionTelemetry(new[] { topLevelexceptionDetails, innerExceptionDetails },
                                                             SeverityLevel.Error, "ProblemId",
                                                             new Dictionary <string, string>()
            {
                ["property1"] = "value1", ["property2"] = "value2"
            },
                                                             new Dictionary <string, double>()
            {
                ["property1"] = 1, ["property2"] = 2
            });

            item.ExceptionDetailsInfoList[1].Message = "Inner exception modified";
            item.ProblemId = "ProblemId modified";

            // ASSERT
            // use internal fields to validate
            Assert.AreEqual("Top level exception <--- Inner exception modified", item.Message);

            Assert.AreEqual(item.Data.Data.ver, 2);
            Assert.AreEqual(item.Data.Data.problemId, "ProblemId modified");
            Assert.AreEqual(item.Data.Data.severityLevel, Extensibility.Implementation.External.SeverityLevel.Error);

            Assert.AreEqual(item.Data.Data.properties.Count, 2);
            Assert.IsTrue(item.Data.Data.properties.Keys.Contains("property1"));
            Assert.IsTrue(item.Data.Data.properties.Keys.Contains("property2"));
            Assert.IsTrue(item.Data.Data.properties.Values.Contains("value1"));
            Assert.IsTrue(item.Data.Data.properties.Values.Contains("value2"));

            Assert.AreEqual(item.Data.Data.measurements.Count, 2);
            Assert.IsTrue(item.Data.Data.measurements.Keys.Contains("property1"));
            Assert.IsTrue(item.Data.Data.measurements.Keys.Contains("property2"));
            Assert.IsTrue(item.Data.Data.measurements.Values.Contains(1));
            Assert.IsTrue(item.Data.Data.measurements.Values.Contains(2));

            Assert.AreEqual(item.Data.Data.exceptions.Count, 2);

            Assert.AreEqual(item.Data.Data.exceptions.First().id, 1);
            Assert.AreEqual(item.Data.Data.exceptions.First().outerId, -1);
            Assert.AreEqual(item.Data.Data.exceptions.First().typeName, "TopLevelException");
            Assert.AreEqual(item.Data.Data.exceptions.First().message, "Top level exception");
            Assert.AreEqual(item.Data.Data.exceptions.First().hasFullStack, true);
            Assert.AreEqual(item.Data.Data.exceptions.First().stack, "Top level exception stack");
            Assert.AreEqual(item.Data.Data.exceptions.First().parsedStack.Count, 3);

            Assert.AreEqual(item.Data.Data.exceptions.First().parsedStack[0].assembly, "Some.Assembly");
            Assert.AreEqual(item.Data.Data.exceptions.First().parsedStack[0].fileName, "SomeFile.dll");
            Assert.AreEqual(item.Data.Data.exceptions.First().parsedStack[0].level, 3);
            Assert.AreEqual(item.Data.Data.exceptions.First().parsedStack[0].line, 33);
            Assert.AreEqual(item.Data.Data.exceptions.First().parsedStack[0].method, "TopLevelMethod");

            Assert.AreEqual(item.Data.Data.exceptions.First().parsedStack[1].assembly, "Some.Assembly");
            Assert.AreEqual(item.Data.Data.exceptions.First().parsedStack[1].fileName, "SomeOtherFile.dll");
            Assert.AreEqual(item.Data.Data.exceptions.First().parsedStack[1].level, 2);
            Assert.AreEqual(item.Data.Data.exceptions.First().parsedStack[1].line, 22);
            Assert.AreEqual(item.Data.Data.exceptions.First().parsedStack[1].method, "LowerLevelMethod");

            Assert.AreEqual(item.Data.Data.exceptions.First().parsedStack[2].assembly, "Some.Assembly");
            Assert.AreEqual(item.Data.Data.exceptions.First().parsedStack[2].fileName, "YetAnotherFile.dll");
            Assert.AreEqual(item.Data.Data.exceptions.First().parsedStack[2].level, 1);
            Assert.AreEqual(item.Data.Data.exceptions.First().parsedStack[2].line, 11);
            Assert.AreEqual(item.Data.Data.exceptions.First().parsedStack[2].method, "LowLevelMethod");

            Assert.AreEqual(item.Data.Data.exceptions.Last().id, 2);
            Assert.AreEqual(item.Data.Data.exceptions.Last().outerId, 1);
            Assert.AreEqual(item.Data.Data.exceptions.Last().typeName, "InnerException");
            Assert.AreEqual(item.Data.Data.exceptions.Last().message, "Inner exception modified");
            Assert.AreEqual(item.Data.Data.exceptions.Last().hasFullStack, false);
            Assert.AreEqual(item.Data.Data.exceptions.Last().stack, "Inner exception stack");
            Assert.AreEqual(item.Data.Data.exceptions.Last().parsedStack.Count, 2);

            Assert.AreEqual(item.Data.Data.exceptions.Last().parsedStack[0].assembly, "Some.Assembly");
            Assert.AreEqual(item.Data.Data.exceptions.Last().parsedStack[0].fileName, "ImportantFile.dll");
            Assert.AreEqual(item.Data.Data.exceptions.Last().parsedStack[0].level, 2);
            Assert.AreEqual(item.Data.Data.exceptions.Last().parsedStack[0].line, 22);
            Assert.AreEqual(item.Data.Data.exceptions.Last().parsedStack[0].method, "InnerMethod");

            Assert.AreEqual(item.Data.Data.exceptions.Last().parsedStack[1].assembly, "Some.Assembly");
            Assert.AreEqual(item.Data.Data.exceptions.Last().parsedStack[1].fileName, "LessImportantFile.dll");
            Assert.AreEqual(item.Data.Data.exceptions.Last().parsedStack[1].level, 1);
            Assert.AreEqual(item.Data.Data.exceptions.Last().parsedStack[1].line, 11);
            Assert.AreEqual(item.Data.Data.exceptions.Last().parsedStack[1].method, "DeeperInnerMethod");
        }
        public void ExceptionTelemetryReturnsNonNullContext()
        {
            ExceptionTelemetry item = new ExceptionTelemetry();

            Assert.IsNotNull(item.Context);
        }
        public void ConstructorDoesNotSetSeverityLevel()
        {
            var telemetry = new ExceptionTelemetry();

            Assert.AreEqual(null, telemetry.SeverityLevel);
        }
        public void HandledAtReturnsUnhandledByDefault()
        {
            var telemetry = new ExceptionTelemetry();

            Assert.AreEqual(ExceptionHandledAt.Unhandled, telemetry.HandledAt);
        }
        public void ExceptionTelemetryCreatedBasedOnCustomDataConstructsFakeExceptionCorrectly()
        {
            // ARRANGE
            var topLevelexceptionDetails = new ExceptionDetailsInfo(1, -1, "TopLevelException", "Top level exception",
                                                                    true, "Top level exception stack", new[]
            {
                new StackFrame("Some.Assembly", "SomeFile.dll", 3, 33, "TopLevelMethod"),
                new StackFrame("Some.Assembly", "SomeOtherFile.dll", 2, 22, "LowerLevelMethod"),
                new StackFrame("Some.Assembly", "YetAnotherFile.dll", 1, 11, "LowLevelMethod")
            });

            var innerExceptionDetails = new ExceptionDetailsInfo(2, 1, "InnerException", "Inner exception", false,
                                                                 "Inner exception stack", new[]
            {
                new StackFrame("Some.Assembly", "ImportantFile.dll", 2, 22, "InnerMethod"),
                new StackFrame("Some.Assembly", "LessImportantFile.dll", 1, 11, "DeeperInnerMethod")
            });

            var innerInnerExceptionDetails = new ExceptionDetailsInfo(3, 1, "InnerInnerException", "Inner inner exception", false,
                                                                      "Inner inner exception stack", new[]
            {
                new StackFrame("Some.Assembly", "ImportantInnerFile.dll", 2, 22, "InnerInnerMethod"),
                new StackFrame("Some.Assembly", "LessImportantInnerFile.dll", 1, 11, "DeeperInnerInnerMethod")
            });

            ExceptionTelemetry item1 = new ExceptionTelemetry(new[] { topLevelexceptionDetails, innerExceptionDetails, innerInnerExceptionDetails },
                                                              SeverityLevel.Error, "ProblemId",
                                                              new Dictionary <string, string>()
            {
                ["property1"] = "value1", ["property2"] = "value2"
            },
                                                              new Dictionary <string, double>()
            {
                ["property1"] = 1, ["property2"] = 2
            });

            ExceptionTelemetry item2 = new ExceptionTelemetry(new[] { topLevelexceptionDetails, innerExceptionDetails },
                                                              SeverityLevel.Error, "ProblemId",
                                                              new Dictionary <string, string>()
            {
                ["property1"] = "value1", ["property2"] = "value2"
            },
                                                              new Dictionary <string, double>()
            {
                ["property1"] = 1, ["property2"] = 2
            });

            ExceptionTelemetry item3 = new ExceptionTelemetry(new[] { topLevelexceptionDetails },
                                                              SeverityLevel.Error, "ProblemId",
                                                              new Dictionary <string, string>()
            {
                ["property1"] = "value1", ["property2"] = "value2"
            },
                                                              new Dictionary <string, double>()
            {
                ["property1"] = 1, ["property2"] = 2
            });

            ExceptionTelemetry item4 = new ExceptionTelemetry(new ExceptionDetailsInfo[] { },
                                                              SeverityLevel.Error, "ProblemId",
                                                              new Dictionary <string, string>()
            {
                ["property1"] = "value1", ["property2"] = "value2"
            },
                                                              new Dictionary <string, double>()
            {
                ["property1"] = 1, ["property2"] = 2
            });

            // ACT
            Exception exception1 = item1.Exception;
            Exception exception2 = item2.Exception;
            Exception exception3 = item3.Exception;
            Exception exception4 = item4.Exception;

            // ASSERT
            Assert.AreEqual("Top level exception", exception1.Message);
            Assert.AreEqual("Inner exception", exception1.InnerException.Message);
            Assert.AreEqual("Inner inner exception", exception1.InnerException.InnerException.Message);
            Assert.IsNull(exception1.InnerException.InnerException.InnerException);

            Assert.AreEqual("Top level exception", exception2.Message);
            Assert.AreEqual("Inner exception", exception2.InnerException.Message);
            Assert.IsNull(exception2.InnerException.InnerException);

            Assert.AreEqual("Top level exception", exception3.Message);
            Assert.IsNull(exception3.InnerException);

            Assert.AreEqual(string.Empty, exception4.Message);
            Assert.IsNull(exception4.InnerException);
        }