private static void ValidateTelemetryPacket(
            DependencyTelemetry remoteDependencyTelemetryActual, string target, string name, string type, bool success, double valueMin, string errorCode)
        {
            Assert.AreEqual(name, remoteDependencyTelemetryActual.Name, true, "Resource name in the sent telemetry is wrong");
            Assert.AreEqual(target, remoteDependencyTelemetryActual.Target, true, "Resource target in the sent telemetry is wrong");
            Assert.AreEqual(type.ToString(), remoteDependencyTelemetryActual.Type, "DependencyKind in the sent telemetry is wrong");
            Assert.AreEqual(success, remoteDependencyTelemetryActual.Success, "Success in the sent telemetry is wrong");
            Assert.AreEqual(errorCode, remoteDependencyTelemetryActual.ResultCode, "ResultCode in the sent telemetry is wrong");

            var valueMinRelaxed = valueMin - 50;

            Assert.IsTrue(
                remoteDependencyTelemetryActual.Duration >= TimeSpan.FromMilliseconds(valueMinRelaxed),
                string.Format(CultureInfo.InvariantCulture, "Value (dependency duration = {0}) in the sent telemetry should be equal or more than the time duration between start and end", remoteDependencyTelemetryActual.Duration));

            var valueMax = valueMin + (valueMin * TimeAccuracyMilliseconds);

            Assert.IsTrue(
                remoteDependencyTelemetryActual.Duration <= TimeSpan.FromMilliseconds(valueMax),
                string.Format(CultureInfo.InvariantCulture, "Value (dependency duration = {0}) in the sent telemetry should not be significantly bigger than the time duration between start and end", remoteDependencyTelemetryActual.Duration));

            string expectedVersion = SdkVersionHelper.GetExpectedSdkVersion(typeof(DependencyTrackingTelemetryModule), prefix: "rddf:");

            Assert.AreEqual(expectedVersion, remoteDependencyTelemetryActual.Context.GetInternalContext().SdkVersion);
        }
Ejemplo n.º 2
0
        private void ValidateTelemetryForDiagnosticSource(DependencyTelemetry item, Uri url, HttpRequestMessage request, bool success, string resultCode)
        {
            Assert.AreEqual(url, item.Data);
            Assert.AreEqual(url.Host, item.Target);
            Assert.AreEqual("GET " + url.AbsolutePath, item.Name);
            Assert.IsTrue(item.Duration > TimeSpan.FromMilliseconds(0), "Duration has to be positive");
            Assert.AreEqual(RemoteDependencyConstants.HTTP, item.Type, "HttpAny has to be dependency kind as it includes http and azure calls");
            Assert.IsTrue(
                item.Timestamp.UtcDateTime < DateTime.UtcNow.AddMilliseconds(20), // DateTime.UtcNow precesion is ~16ms
                "timestamp < now");
            Assert.IsTrue(
                item.Timestamp.UtcDateTime > DateTime.UtcNow.AddSeconds(-5),
                "timestamp > now - 5 sec");

            Assert.AreEqual(resultCode, item.ResultCode);
            Assert.AreEqual(success, item.Success);
            Assert.AreEqual(
                SdkVersionHelper.GetExpectedSdkVersion(typeof(DependencyTrackingTelemetryModule), "rdddsc:"),
                item.Context.GetInternalContext().SdkVersion);

            var requestId = item.Id;

            Assert.IsTrue(requestId.StartsWith('|' + item.Context.Operation.Id + '.'));
            if (request != null)
            {
                Assert.AreEqual(requestId, request.Headers.GetValues(RequestResponseHeaders.RequestIdHeader).Single());
                Assert.AreEqual(requestId, request.Headers.GetValues(RequestResponseHeaders.StandardParentIdHeader).Single());
                Assert.AreEqual(item.Context.Operation.Id, request.Headers.GetValues(RequestResponseHeaders.StandardRootIdHeader).Single());
            }
        }
Ejemplo n.º 3
0
        public void OnActivityStopWithParentTracksTelemetry()
        {
            var parent = new Activity("parent")
                         .AddBaggage("k", "v")
                         .Start();

            var activity = new Activity("System.Net.Http.HttpRequestOut").Start();

            HttpRequestMessage requestMsg = new HttpRequestMessage(HttpMethod.Post, RequestUrlWithScheme);

            this.listener.OnActivityStart(requestMsg);

            HttpResponseMessage responseMsg = new HttpResponseMessage(HttpStatusCode.OK);

            this.listener.OnActivityStop(responseMsg, requestMsg, TaskStatus.RanToCompletion);

            var telemetry = this.sentTelemetry.Single() as DependencyTelemetry;

            Assert.IsNotNull(telemetry);
            Assert.AreEqual(parent.RootId, telemetry.Context.Operation.Id);
            Assert.AreEqual(parent.Id, telemetry.Context.Operation.ParentId);
            Assert.AreEqual(activity.Id, telemetry.Id);
            Assert.AreEqual("v", telemetry.Properties["k"]);

            string expectedVersion =
                SdkVersionHelper.GetExpectedSdkVersion(typeof(DependencyTrackingTelemetryModule), prefix: "rdddsc:");

            Assert.AreEqual(expectedVersion, telemetry.Context.GetInternalContext().SdkVersion);

            // Check the operation details
            this.operationDetailsInitializer.ValidateOperationDetailsCore(telemetry);
        }
Ejemplo n.º 4
0
        private void ValidateTelemetryForDiagnosticSource(DependencyTelemetry item, Uri url, WebRequest request, bool success, string resultCode)
        {
            Assert.AreEqual(url, item.Data);
            Assert.AreEqual(url.Host, item.Target);
            Assert.AreEqual("GET " + url.AbsolutePath, item.Name);
            Assert.IsTrue(item.Duration > TimeSpan.FromMilliseconds(0), "Duration has to be positive");
            Assert.AreEqual(RemoteDependencyConstants.HTTP, item.Type, "HttpAny has to be dependency kind as it includes http and azure calls");
            Assert.IsTrue(
                DateTime.UtcNow.Subtract(item.Timestamp.UtcDateTime).TotalMilliseconds <
                TimeSpan.FromMinutes(1).TotalMilliseconds,
                "timestamp < now");
            Assert.IsTrue(
                item.Timestamp.Subtract(DateTime.UtcNow).TotalMilliseconds >
                -TimeSpan.FromMinutes(1).TotalMilliseconds,
                "now - 1 min < timestamp");
            Assert.AreEqual(resultCode, item.ResultCode);
            Assert.AreEqual(success, item.Success);
            Assert.AreEqual(
                SdkVersionHelper.GetExpectedSdkVersion(typeof(DependencyTrackingTelemetryModule), "rdddsd:"),
                item.Context.GetInternalContext().SdkVersion);

            var requestId = item.Id;

            Assert.AreEqual(requestId, request.Headers["Request-Id"]);
            Assert.AreEqual(requestId, request.Headers["x-ms-request-id"]);
            Assert.IsTrue(requestId.StartsWith('|' + item.Context.Operation.Id + '.'));
        }
        private static void ValidateTelemetryPacketForOnRequestSend(DependencyTelemetry remoteDependencyTelemetryActual, Uri url, string kind, bool?success, double valueMin, string statusCode)
        {
            Assert.AreEqual("GET " + url.AbsolutePath, remoteDependencyTelemetryActual.Name, true, "Resource name in the sent telemetry is wrong");
            string expectedVersion =
                SdkVersionHelper.GetExpectedSdkVersion(typeof(DependencyTrackingTelemetryModule), prefix: "rdddsd:");

            ValidateTelemetryPacket(remoteDependencyTelemetryActual, url, kind, success, valueMin, statusCode, expectedVersion);
        }
Ejemplo n.º 6
0
        private static void ValidateTelemetryPacket(
            DependencyTelemetry remoteDependencyTelemetryActual,
            string target,
            string name,
            string type,
            bool success,
            double minDependencyDurationMs,
            double maxDependencyDurationMs,
            string errorCode,
            Activity parentActivity)
        {
            Assert.AreEqual(name, remoteDependencyTelemetryActual.Name, true, "Resource name in the sent telemetry is wrong");
            Assert.AreEqual(target, remoteDependencyTelemetryActual.Target, true, "Resource target in the sent telemetry is wrong");
            Assert.AreEqual(type.ToString(), remoteDependencyTelemetryActual.Type, "DependencyKind in the sent telemetry is wrong");
            Assert.AreEqual(success, remoteDependencyTelemetryActual.Success, "Success in the sent telemetry is wrong");
            Assert.AreEqual(errorCode, remoteDependencyTelemetryActual.ResultCode, "ResultCode in the sent telemetry is wrong");

            Assert.IsTrue(
                remoteDependencyTelemetryActual.Duration.TotalMilliseconds <= maxDependencyDurationMs,
                $"Dependency duration {remoteDependencyTelemetryActual.Duration.TotalMilliseconds} must be smaller than time between before-start and after-end: '{maxDependencyDurationMs}'");

            Assert.IsTrue(
                remoteDependencyTelemetryActual.Duration.TotalMilliseconds >= minDependencyDurationMs,
                $"Dependency duration {remoteDependencyTelemetryActual.Duration.TotalMilliseconds} must be bigger than time between after-start and before-end '{minDependencyDurationMs}'");

            string expectedVersion = SdkVersionHelper.GetExpectedSdkVersion(typeof(DependencyTrackingTelemetryModule), prefix: "rddf:");

            Assert.AreEqual(expectedVersion, remoteDependencyTelemetryActual.Context.GetInternalContext().SdkVersion);

            if (parentActivity != null)
            {
                if (parentActivity.IdFormat == ActivityIdFormat.W3C)
                {
                    Assert.AreEqual(parentActivity.TraceId.ToHexString(), remoteDependencyTelemetryActual.Context.Operation.Id);
                    Assert.AreEqual(parentActivity.SpanId.ToHexString(), remoteDependencyTelemetryActual.Context.Operation.ParentId);
                    if (parentActivity.TraceStateString != null)
                    {
                        Assert.IsTrue(remoteDependencyTelemetryActual.Properties.ContainsKey("tracestate"));
                        Assert.AreEqual(parentActivity.TraceStateString, remoteDependencyTelemetryActual.Properties["tracestate"]);
                    }
                    else
                    {
                        Assert.IsFalse(remoteDependencyTelemetryActual.Properties.ContainsKey("tracestate"));
                    }
                }
                else
                {
                    Assert.AreEqual(parentActivity.RootId, remoteDependencyTelemetryActual.Context.Operation.Id);
                    Assert.AreEqual(parentActivity.Id, remoteDependencyTelemetryActual.Context.Operation.ParentId);
                }
            }
            else
            {
                Assert.IsNotNull(remoteDependencyTelemetryActual.Context.Operation.Id);
                Assert.IsNull(remoteDependencyTelemetryActual.Context.Operation.ParentId);
            }
        }
        public async Task OnActivityStopTracksTelemetry()
        {
            var activity = new Activity("System.Net.Http.HttpRequestOut")
                           .AddBaggage("k", "v")
                           .Start();

            activity.TraceStateString = "state=some";

            HttpRequestMessage requestMsg = new HttpRequestMessage(HttpMethod.Post, RequestUrlWithScheme);

            using (var listener = this.CreateHttpListener(HttpInstrumentationVersion.V2))
            {
                listener.OnActivityStart(requestMsg);
                var approxStartTime = DateTime.UtcNow;
                activity = Activity.Current;

                await Task.Delay(10);

                HttpResponseMessage responseMsg = new HttpResponseMessage(HttpStatusCode.OK);
                listener.OnActivityStop(responseMsg, requestMsg, TaskStatus.RanToCompletion);

                var telemetry = this.sentTelemetry.Single() as DependencyTelemetry;

                Assert.IsNotNull(telemetry);
                Assert.AreEqual("POST /", telemetry.Name);
                Assert.AreEqual(RequestUrl, telemetry.Target);
                Assert.AreEqual(RemoteDependencyConstants.HTTP, telemetry.Type);
                Assert.AreEqual(RequestUrlWithScheme, telemetry.Data);
                Assert.AreEqual("200", telemetry.ResultCode);
                Assert.AreEqual(true, telemetry.Success);

                Assert.IsTrue(Math.Abs((telemetry.Timestamp - approxStartTime).TotalMilliseconds) < 100);
                Assert.IsTrue(telemetry.Duration.TotalMilliseconds > 10);

                Assert.AreEqual(activity.RootId, telemetry.Context.Operation.Id);
                Assert.IsNull(telemetry.Context.Operation.ParentId);

                Assert.AreEqual(
                    string.Concat('|', telemetry.Context.Operation.Id, '.', activity.SpanId.ToHexString(), '.'),
                    telemetry.Id);
                Assert.AreEqual("v", telemetry.Properties["k"]);

                Assert.AreEqual(32, telemetry.Context.Operation.Id.Length);
                Assert.IsTrue(Regex.Match(telemetry.Context.Operation.Id, @"[a-z][0-9]").Success);

                string expectedVersion =
                    SdkVersionHelper.GetExpectedSdkVersion(typeof(DependencyTrackingTelemetryModule),
                                                           prefix: "rdddsc:");
                Assert.AreEqual(expectedVersion, telemetry.Context.GetInternalContext().SdkVersion);
                Assert.AreEqual("state=some", telemetry.Properties["tracestate"]);

                // Check the operation details
                this.operationDetailsInitializer.ValidateOperationDetailsCore(telemetry);
            }
        }
Ejemplo n.º 8
0
        private void ValidateTelemetryForDiagnosticSource(DependencyTelemetry item, Uri url, HttpRequestMessage request, bool success, string resultCode, bool expectLegacyHeaders, Activity parent = null)
        {
            Assert.AreEqual(url, item.Data);
            Assert.AreEqual(url.Host, item.Target);
            Assert.AreEqual("GET " + url.AbsolutePath, item.Name);
            Assert.IsTrue(item.Duration > TimeSpan.FromMilliseconds(0), "Duration has to be positive");
            Assert.AreEqual(RemoteDependencyConstants.HTTP, item.Type, "HttpAny has to be dependency kind as it includes http and azure calls");
            Assert.IsTrue(
                item.Timestamp.UtcDateTime < DateTime.UtcNow.AddMilliseconds(20), // DateTime.UtcNow precesion is ~16ms
                "timestamp < now");
            Assert.IsTrue(
                item.Timestamp.UtcDateTime > DateTime.UtcNow.AddSeconds(-5),
                "timestamp > now - 5 sec");

            Assert.AreEqual(resultCode, item.ResultCode);
            Assert.AreEqual(success, item.Success);
            Assert.AreEqual(
                SdkVersionHelper.GetExpectedSdkVersion(typeof(DependencyTrackingTelemetryModule), "rdddsc:"),
                item.Context.GetInternalContext().SdkVersion);

            var requestId = item.Id;

            Assert.IsTrue(requestId.StartsWith('|' + item.Context.Operation.Id + '.'));

            if (parent == null)
            {
                // W3C compatible-Id ( should go away when W3C is implemented in .NET https://github.com/dotnet/corefx/issues/30331 TODO)
                Assert.AreEqual(32, item.Context.Operation.Id.Length);
                Assert.IsTrue(Regex.Match(item.Context.Operation.Id, @"[a-z][0-9]").Success);
                // end of workaround test
            }
            else
            {
                Assert.AreEqual(parent.RootId, item.Context.Operation.Id);
            }

            if (request != null)
            {
                Assert.AreEqual(requestId, request.Headers.GetValues(RequestResponseHeaders.RequestIdHeader).Single());
                if (expectLegacyHeaders)
                {
                    Assert.AreEqual(item.Context.Operation.Id, request.Headers.GetValues(RequestResponseHeaders.StandardRootIdHeader).Single());
                    Assert.AreEqual(requestId, request.Headers.GetValues(RequestResponseHeaders.StandardParentIdHeader).Single());
                }
                else
                {
                    Assert.IsFalse(request.Headers.Contains(RequestResponseHeaders.StandardRootIdHeader));
                    Assert.IsFalse(request.Headers.Contains(RequestResponseHeaders.StandardParentIdHeader));
                }
            }

            // Validate the http request was captured
            this.operationDetailsInitializer.ValidateOperationDetailsCore(item);
        }
        public void SdkVersionIsCorrect()
        {
            Logger aiLogger = this.CreateTargetWithGivenInstrumentationKey();

            aiLogger.Debug("Message");

            var telemetry = (TraceTelemetry)this.adapterHelper.Channel.SentItems.First();

            string expectedVersion = SdkVersionHelper.GetExpectedSdkVersion(prefix: "nlog:", loggerType: typeof(ApplicationInsightsTarget));

            Assert.AreEqual(expectedVersion, telemetry.Context.GetInternalContext().SdkVersion);
        }
        public void SdkVersionHasCorrectFormat()
        {
            string expectedVersion = SdkVersionHelper.GetExpectedSdkVersion(typeof(RequestTrackingTelemetryModule), prefix: "web:");

            var context = HttpModuleHelper.GetFakeHttpContext();

            var module = this.RequestTrackingTelemetryModuleFactory();

            module.OnBeginRequest(context);
            module.OnEndRequest(context);

            Assert.Equal(expectedVersion, context.GetRequestTelemetry().Context.GetInternalContext().SdkVersion);
        }
        public void SdkVersionIsCorrect()
        {
            TelemetryConfiguration.Active.TelemetryChannel = this.adapterHelper.Channel;

            using (var listener = new ApplicationInsightsTraceListener(Guid.NewGuid().ToString()))
            {
                listener.WriteLine("A Message to write line");

                TraceTelemetry telemetry = (TraceTelemetry)this.adapterHelper.Channel.SentItems.First();

                string expectedVersion = SdkVersionHelper.GetExpectedSdkVersion(prefix: "sd:");
                Assert.AreEqual(expectedVersion, telemetry.Context.GetInternalContext().SdkVersion);
            }
        }
        public void SdkVersionHasCorrectFormat()
        {
            string expectedVersion = SdkVersionHelper.GetExpectedSdkVersion(typeof(RequestTrackingTelemetryModule), prefix: "web:");

            var context = HttpModuleHelper.GetFakeHttpContext();

            var module = new RequestTrackingTelemetryModule();

            module.Initialize(TelemetryConfiguration.CreateDefault());
            module.OnBeginRequest(context);
            module.OnEndRequest(context);

            Assert.Equal(expectedVersion, context.GetRequestTelemetry().Context.GetInternalContext().SdkVersion);
        }
        public void SdkVersionIsCorrect()
        {
#pragma warning disable CS0618 // Type or member is obsolete
            TelemetryConfiguration.Active.TelemetryChannel = this.adapterHelper.Channel;
#pragma warning restore CS0618 // Type or member is obsolete

            using (var listener = new ApplicationInsightsTraceListener(Guid.NewGuid().ToString()))
            {
                listener.WriteLine("A Message to write line");

                TraceTelemetry telemetry = (TraceTelemetry)this.adapterHelper.Channel.SentItems.First();

                string expectedVersion = SdkVersionHelper.GetExpectedSdkVersion(prefix: "sd:", loggerType: typeof(ApplicationInsightsTraceListener));
                Assert.AreEqual(expectedVersion, telemetry.Context.GetInternalContext().SdkVersion);
            }
        }
        public void TrackedExceptionsHavePrefixUsedForTelemetry()
        {
            string expectedVersion = SdkVersionHelper.GetExpectedSdkVersion(typeof(UnhandledExceptionTelemetryModule), prefix: "unhnd:");

            UnhandledExceptionEventHandler handler = null;

            using (new UnhandledExceptionTelemetryModule(
                       h => handler = h,
                       _ => { },
                       this.moduleChannel))
            {
                handler.Invoke(null, new UnhandledExceptionEventArgs(null, true));
            }

            Assert.Equal(expectedVersion, this.items[0].Context.GetInternalContext().SdkVersion);
        }
Ejemplo n.º 15
0
        public void SdkVersionIsCorrect()
        {
            this.appendableLogger.Logger.Debug("Trace Debug");

            var sentItems = this.appendableLogger.SentItems;

            Assert.AreEqual(1, sentItems.Length);

            var telemetry = (TraceTelemetry)sentItems[0];

            Assert.AreNotEqual(default(DateTimeOffset), telemetry.Context);

            string expectedVersion = SdkVersionHelper.GetExpectedSdkVersion(prefix: "log4net:", loggerType: typeof(AppendableLogger));

            Assert.AreEqual(expectedVersion, telemetry.Context.GetInternalContext().SdkVersion);
        }
        public void TrackedExceptionsHavePrefixUsedForTelemetry()
        {
            string expectedVersion = SdkVersionHelper.GetExpectedSdkVersion(typeof(UnobservedExceptionTelemetryModule), prefix: "unobs:");

            EventHandler <UnobservedTaskExceptionEventArgs> handler = null;

            using (var module = new UnobservedExceptionTelemetryModule(
                       h => handler = h,
                       _ => { }))
            {
                module.Initialize(this.moduleConfiguration);
                handler.Invoke(null, new UnobservedTaskExceptionEventArgs(new AggregateException(string.Empty)));
            }

            Assert.Equal(expectedVersion, this.items[0].Context.GetInternalContext().SdkVersion);
        }
Ejemplo n.º 17
0
        private void ValidateTelemetryForEventSource(DependencyTelemetry item, Uri url, WebRequest requestMsg)
        {
            Assert.AreEqual(url.AbsolutePath, item.Name);

            Assert.AreEqual(
                SdkVersionHelper.GetExpectedSdkVersion(typeof(DependencyTrackingTelemetryModule), "rddf:"),
                item.Context.GetInternalContext().SdkVersion);

            if (requestMsg != null)
            {
                Assert.IsNull(requestMsg.Headers[RequestResponseHeaders.RequestIdHeader]);
                Assert.IsNull(requestMsg.Headers[RequestResponseHeaders.StandardParentIdHeader]);
                Assert.IsNull(requestMsg.Headers[RequestResponseHeaders.StandardRootIdHeader]);
                Assert.IsNull(requestMsg.Headers[RequestResponseHeaders.CorrelationContextHeader]);
            }
        }
Ejemplo n.º 18
0
        public void OnResponseWithSuccessfulResponseEventWithMatchingRequestAndNoTargetInstrumentationKeyHasHeader()
        {
            Guid loggingRequestId         = Guid.NewGuid();
            HttpRequestMessage requestMsg = new HttpRequestMessage(HttpMethod.Post, RequestUrlWithScheme);

            using (var listener = new HttpCoreDiagnosticSourceListener(
                       this.configuration,
                       setComponentCorrelationHttpHeaders: true,
                       correlationDomainExclusionList: new string[] { "excluded.host.com" },
                       injectLegacyHeaders: false,
                       injectRequestIdInW3CMode: true,
                       HttpInstrumentationVersion.V1))
            {
                listener.OnRequest(requestMsg, loggingRequestId);

                Assert.IsTrue(listener.PendingDependencyTelemetry.TryGetValue(requestMsg, out var dependency));

                Assert.AreEqual(0, this.sentTelemetry.Count);

                DependencyTelemetry telemetry = dependency.Telemetry;
                Assert.AreEqual(string.Empty, telemetry.ResultCode);
                Assert.AreEqual(true, telemetry.Success);

                HttpResponseMessage responseMsg = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    RequestMessage = requestMsg
                };

                listener.OnResponse(responseMsg, loggingRequestId);
                Assert.IsFalse(listener.PendingDependencyTelemetry.TryGetValue(requestMsg, out dependency));
                Assert.AreEqual(1, this.sentTelemetry.Count);
                Assert.AreSame(telemetry, this.sentTelemetry.Single());

                Assert.AreEqual(RemoteDependencyConstants.HTTP, telemetry.Type);
                Assert.AreEqual(RequestUrl, telemetry.Target);
                Assert.AreEqual(HttpOkResultCode, telemetry.ResultCode);
                Assert.AreEqual(true, telemetry.Success);

                string expectedVersion =
                    SdkVersionHelper.GetExpectedSdkVersion(typeof(DependencyTrackingTelemetryModule),
                                                           prefix: "rdddsc:");
                Assert.AreEqual(expectedVersion, telemetry.Context.GetInternalContext().SdkVersion);

                // Check the operation details
                this.operationDetailsInitializer.ValidateOperationDetailsCore(telemetry);
            }
        }
        private void ValidateTelemetryForDiagnosticSource(DependencyTelemetry item, Uri url, WebRequest request, bool expectLegacyHeaders)
        {
            var expectedMethod = request != null ? request.Method : "GET";

            Assert.AreEqual(expectedMethod + " " + url.AbsolutePath, item.Name);

            Assert.AreEqual(
                SdkVersionHelper.GetExpectedSdkVersion(typeof(DependencyTrackingTelemetryModule), "rdddsd:"),
                item.Context.GetInternalContext().SdkVersion);

            var requestId = item.Id;

            if (request != null)
            {
                Assert.AreEqual(requestId, request.Headers[RequestResponseHeaders.RequestIdHeader]);

                if (expectLegacyHeaders)
                {
                    Assert.AreEqual(requestId, request.Headers[RequestResponseHeaders.StandardParentIdHeader]);
                    Assert.AreEqual(item.Context.Operation.Id, request.Headers[RequestResponseHeaders.StandardRootIdHeader]);
                }
                else
                {
                    Assert.IsNull(request.Headers[RequestResponseHeaders.StandardParentIdHeader]);
                    Assert.IsNull(request.Headers[RequestResponseHeaders.StandardRootIdHeader]);
                }

                if (Activity.Current != null)
                {
                    var correlationContextHeader = request.Headers[RequestResponseHeaders.CorrelationContextHeader]
                                                   .Split(',');

                    var baggage = Activity.Current.Baggage.Select(kvp => $"{kvp.Key}={kvp.Value}").ToArray();
                    Assert.AreEqual(baggage.Length, correlationContextHeader.Length);

                    foreach (var baggageItem in baggage)
                    {
                        Assert.IsTrue(correlationContextHeader.Contains(baggageItem));
                    }
                }
                else
                {
                    Assert.IsNull(request.Headers[RequestResponseHeaders.CorrelationContextHeader]);
                }
            }
        }
        public void OnActivityStopTracksTelemetry()
        {
            var activity = new Activity("System.Net.Http.HttpRequestOut");

            activity.AddBaggage("k", "v");
            var startTime = DateTime.UtcNow.AddSeconds(-1);

            activity.SetStartTime(startTime);
            activity.Start();

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, RequestUrlWithScheme);

            this.listener.OnActivityStart(request);

            activity = Activity.Current;
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);

            this.listener.OnActivityStop(response, request, TaskStatus.RanToCompletion);

            var telemetry = this.sentTelemetry.Single() as DependencyTelemetry;

            Assert.AreEqual("POST /", telemetry.Name);
            Assert.AreEqual(RequestUrl, telemetry.Target);
            Assert.AreEqual(RemoteDependencyConstants.HTTP, telemetry.Type);
            Assert.AreEqual(RequestUrlWithScheme, telemetry.Data);
            Assert.AreEqual("200", telemetry.ResultCode);
            Assert.AreEqual(true, telemetry.Success);

            Assert.AreEqual(activity.StartTimeUtc, telemetry.Timestamp);
            Assert.IsTrue(1 <= telemetry.Duration.TotalSeconds);
            Assert.IsTrue(2 > telemetry.Duration.TotalSeconds);

            Assert.AreEqual(activity.RootId, telemetry.Context.Operation.Id);
            Assert.AreEqual(activity.ParentId, telemetry.Context.Operation.ParentId);
            Assert.AreEqual(activity.Id, telemetry.Id);
            Assert.AreEqual("v", telemetry.Properties["k"]);

            string expectedVersion =
                SdkVersionHelper.GetExpectedSdkVersion(typeof(DependencyTrackingTelemetryModule), prefix: "rdddsc:");

            Assert.AreEqual(expectedVersion, telemetry.Context.GetInternalContext().SdkVersion);

            // Check the operation details
            this.ValidateOperationDetails(telemetry);
        }
        private void ValidateTelemetryPacket(
            DependencyTelemetry remoteDependencyTelemetryActual,
            Uri uri,
            string type,
            bool success,
            double expectedValue,
            string resultCode,
            bool responseExpected = true)
        {
            Assert.AreEqual("GET " + uri.AbsolutePath, remoteDependencyTelemetryActual.Name, true, "Resource name in the sent telemetry is wrong");
            Assert.AreEqual(uri.Host, remoteDependencyTelemetryActual.Target, true, "Resource target in the sent telemetry is wrong");
            Assert.AreEqual(uri.OriginalString, remoteDependencyTelemetryActual.Data, true, "Resource data in the sent telemetry is wrong");
            Assert.AreEqual(type.ToString(), remoteDependencyTelemetryActual.Type, "DependencyKind in the sent telemetry is wrong");
            Assert.AreEqual(success, remoteDependencyTelemetryActual.Success, "Success in the sent telemetry is wrong");
            Assert.AreEqual(resultCode, remoteDependencyTelemetryActual.ResultCode, "ResultCode in the sent telemetry is wrong");

            // Validate the http request is present
            Assert.IsNotNull(this.request, "Http request was not found within the operation details.");
            Assert.IsNotNull(this.request as WebRequest, "Http request was not the expected type.");

            // If expected -- validate the response
            if (responseExpected)
            {
                Assert.IsNotNull(this.response, "Http response was not found within the operation details.");
                Assert.IsNotNull(this.response as HttpWebResponse, "Http response was not the expected type.");
                Assert.IsNull(this.responseHeaders, "Http response headers were not found within the operation details.");
            }

            var valueMinRelaxed = expectedValue - TimeAccuracyMilliseconds;

            Assert.IsTrue(
                remoteDependencyTelemetryActual.Duration >= TimeSpan.FromMilliseconds(valueMinRelaxed),
                string.Format(CultureInfo.InvariantCulture, "Value (dependency duration = {0}) in the sent telemetry should be equal or more than the time duration between start and end", remoteDependencyTelemetryActual.Duration));

            var valueMax = expectedValue + TimeAccuracyMilliseconds;

            Assert.IsTrue(
                remoteDependencyTelemetryActual.Duration <= TimeSpan.FromMilliseconds(valueMax),
                string.Format(CultureInfo.InvariantCulture, "Value (dependency duration = {0}) in the sent telemetry should not be significantly bigger than the time duration between start and end", remoteDependencyTelemetryActual.Duration));

            string expectedVersion = SdkVersionHelper.GetExpectedSdkVersion(typeof(DependencyTrackingTelemetryModule), prefix: "rddp:");

            Assert.AreEqual(expectedVersion, remoteDependencyTelemetryActual.Context.GetInternalContext().SdkVersion);
        }
Ejemplo n.º 22
0
        private static void ValidateTelemetryPacket(
            DependencyTelemetry remoteDependencyTelemetryActual,
            string expectedName,
            bool expectedSuccess,
            string expectedResultCode,
            double timeBetweenBeginEndInMs)
        {
            Assert.AreEqual(expectedName, remoteDependencyTelemetryActual.Name, true, "Resource name in the sent telemetry is wrong");
            Assert.AreEqual(ExpectedType, remoteDependencyTelemetryActual.Type, "DependencyKind in the sent telemetry is wrong");
            Assert.AreEqual(expectedSuccess, remoteDependencyTelemetryActual.Success, "Success in the sent telemetry is wrong");
            Assert.AreEqual(expectedResultCode, remoteDependencyTelemetryActual.ResultCode, "ResultCode in the sent telemetry is wrong");

            Assert.IsTrue(remoteDependencyTelemetryActual.Duration.TotalMilliseconds <= timeBetweenBeginEndInMs + 1, "Incorrect duration. Collected " + remoteDependencyTelemetryActual.Duration.TotalMilliseconds + " should be less than max " + timeBetweenBeginEndInMs);
            Assert.IsTrue(remoteDependencyTelemetryActual.Duration.TotalMilliseconds >= 0);

            string expectedVersion = SdkVersionHelper.GetExpectedSdkVersion(typeof(DependencyTrackingTelemetryModuleTest), prefix: "rddp:");

            Assert.AreEqual(expectedVersion, remoteDependencyTelemetryActual.Context.GetInternalContext().SdkVersion);
        }
Ejemplo n.º 23
0
        public void ReportsSingleEvent()
        {
            using (var module = new EventSourceTelemetryModule())
            {
                var listeningRequest = new EventSourceListeningRequest();
                listeningRequest.Name = TestEventSource.ProviderName;
                module.Sources.Add(listeningRequest);

                module.Initialize(GetTestTelemetryConfiguration());

                TestEventSource.Default.InfoEvent("Hey!");

                TraceTelemetry telemetry = (TraceTelemetry)this.adapterHelper.Channel.SentItems.Single();
                Assert.AreEqual("Hey!", telemetry.Message);
                Assert.AreEqual("Hey!", telemetry.Properties["information"]);
                Assert.AreEqual(SeverityLevel.Information, telemetry.SeverityLevel);
                string expectedVersion = SdkVersionHelper.GetExpectedSdkVersion(prefix: "evl:", loggerType: typeof(EventSourceTelemetryModule));
                Assert.AreEqual(expectedVersion, telemetry.Context.GetInternalContext().SdkVersion);
            }
        }
        public void OnResponseWithSuccessfulResponseEventWithMatchingRequestAndNoTargetInstrumentationKeyHasHeader()
        {
            Guid loggingRequestId      = Guid.NewGuid();
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, RequestUrlWithScheme);

            this.listener.OnRequest(request, loggingRequestId);

            IOperationHolder <DependencyTelemetry> dependency;

            Assert.IsTrue(this.listener.PendingDependencyTelemetry.TryGetValue(request, out dependency));

            Assert.AreEqual(0, this.sentTelemetry.Count);

            DependencyTelemetry telemetry = dependency.Telemetry;

            Assert.AreEqual(string.Empty, telemetry.ResultCode);
            Assert.AreEqual(true, telemetry.Success);

            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                RequestMessage = request
            };

            this.listener.OnResponse(response, loggingRequestId);
            Assert.IsFalse(this.listener.PendingDependencyTelemetry.TryGetValue(request, out dependency));
            Assert.AreEqual(1, this.sentTelemetry.Count);
            Assert.AreSame(telemetry, this.sentTelemetry.Single());

            Assert.AreEqual(RemoteDependencyConstants.HTTP, telemetry.Type);
            Assert.AreEqual(RequestUrl, telemetry.Target);
            Assert.AreEqual(HttpOkResultCode, telemetry.ResultCode);
            Assert.AreEqual(true, telemetry.Success);

            string expectedVersion =
                SdkVersionHelper.GetExpectedSdkVersion(typeof(DependencyTrackingTelemetryModule), prefix: "rdddsc:");

            Assert.AreEqual(expectedVersion, telemetry.Context.GetInternalContext().SdkVersion);

            // Check the operation details
            this.ValidateOperationDetails(telemetry);
        }
Ejemplo n.º 25
0
        public void ReportsSingleEvent()
        {
            using (var module = new DiagnosticSourceTelemetryModule())
            {
                var testDiagnosticSource = new TestDiagnosticSource();
                var listeningRequest     = new DiagnosticSourceListeningRequest(testDiagnosticSource.Name);
                module.Sources.Add(listeningRequest);

                module.Initialize(GetTestTelemetryConfiguration());

                testDiagnosticSource.Write("Hey!", new { Prop1 = 1234 });

                TraceTelemetry telemetry = (TraceTelemetry)this.adapterHelper.Channel.SentItems.First();
                Assert.AreEqual("Hey!", telemetry.Message);
                Assert.AreEqual(testDiagnosticSource.Name, telemetry.Properties["DiagnosticSource"]);
                Assert.AreEqual(SeverityLevel.Information, telemetry.SeverityLevel);
                Assert.AreEqual(1234.ToString(), telemetry.Properties["Prop1"]);
                string expectedVersion = SdkVersionHelper.GetExpectedSdkVersion(typeof(DiagnosticSourceTelemetryModule), prefix: "dsl:");
                Assert.AreEqual(expectedVersion, telemetry.Context.GetInternalContext().SdkVersion);
            }
        }
Ejemplo n.º 26
0
        public void TestDependencyCollectionEventSource()
        {
            using (var module = new DependencyTrackingTelemetryModule())
            {
                module.DisableDiagnosticSourceInstrumentation = true;
                module.ProfileQueryEndpoint = FakeProfileApiEndpoint;
                module.Initialize(this.config);
                Assert.IsFalse(DependencyTableStore.Instance.IsDesktopHttpDiagnosticSourceActivated);

                var            url     = new Uri("https://www.bing.com/");
                HttpWebRequest request = WebRequest.CreateHttp(url);
                using (request.GetResponse())
                {
                }

                var item = this.sentTelemetry.Single();
                Assert.AreEqual(url, item.Data);
                Assert.AreEqual(url.Host, item.Target);
                Assert.AreEqual(url.AbsolutePath, item.Name);
                Assert.IsTrue(item.Duration > TimeSpan.FromMilliseconds(0), "Duration has to be positive");
                Assert.AreEqual(RemoteDependencyConstants.HTTP, item.Type, "HttpAny has to be dependency kind as it includes http and azure calls");
                Assert.IsTrue(
                    DateTime.UtcNow.Subtract(item.Timestamp.UtcDateTime).TotalMilliseconds <
                    TimeSpan.FromMinutes(1).TotalMilliseconds,
                    "timestamp < now");
                Assert.IsTrue(
                    item.Timestamp.Subtract(DateTime.UtcNow).TotalMilliseconds >
                    -TimeSpan.FromMinutes(1).TotalMilliseconds,
                    "now - 1 min < timestamp");
                Assert.AreEqual("200", item.ResultCode);
                Assert.AreEqual(
                    SdkVersionHelper.GetExpectedSdkVersion(typeof(DependencyTrackingTelemetryModule), "rddf:"),
                    item.Context.GetInternalContext().SdkVersion);

                Assert.IsNull(request.Headers["Request-Id"]);
                Assert.IsNull(request.Headers["x-ms-request-id"]);
                Assert.IsNull(request.Headers["Correlation-Context"]);
            }
        }
        private void ValidateTelemetryForDiagnosticSource(
            DependencyTelemetry item,
            Uri url,
            HttpRequestMessage request,
            bool success,
            string resultCode,
            bool expectLegacyHeaders,
            bool expectW3CHeaders,
            bool expectRequestId,
            bool responseExpected   = true,
            Activity parentActivity = null)
        {
            Assert.AreEqual(url, item.Data);
            Assert.AreEqual($"{url.Host}:{url.Port}", item.Target);
            Assert.AreEqual("GET " + url.AbsolutePath, item.Name);
            Assert.IsTrue(item.Duration > TimeSpan.FromMilliseconds(0), "Duration has to be positive");
            Assert.AreEqual(RemoteDependencyConstants.HTTP, item.Type, "HttpAny has to be dependency kind as it includes http and azure calls");
            Assert.IsTrue(
                item.Timestamp.UtcDateTime < DateTime.UtcNow.AddMilliseconds(20), // DateTime.UtcNow precision is ~16ms
                "timestamp < now");
            Assert.IsTrue(
                item.Timestamp.UtcDateTime > DateTime.UtcNow.AddSeconds(-5),
                "timestamp > now - 5 sec");

            Assert.AreEqual(resultCode, item.ResultCode);
            Assert.AreEqual(success, item.Success);
            Assert.AreEqual(
                SdkVersionHelper.GetExpectedSdkVersion(typeof(DependencyTrackingTelemetryModule), "rdddsc:"),
                item.Context.GetInternalContext().SdkVersion);

            if (parentActivity != null)
            {
                if (parentActivity.IdFormat == ActivityIdFormat.W3C)
                {
                    Assert.AreEqual(parentActivity.TraceId.ToHexString(), item.Context.Operation.Id);
                    Assert.AreEqual(parentActivity.SpanId.ToHexString(), item.Context.Operation.ParentId);
                    if (parentActivity.TraceStateString != null)
                    {
                        Assert.IsTrue(item.Properties.ContainsKey("tracestate"));
                        Assert.AreEqual(parentActivity.TraceStateString, item.Properties["tracestate"]);
                    }
                    else
                    {
                        Assert.IsFalse(item.Properties.ContainsKey("tracestate"));
                    }
                }
                else
                {
                    Assert.AreEqual(parentActivity.RootId, item.Context.Operation.Id);
                    Assert.AreEqual(parentActivity.Id, item.Context.Operation.ParentId);
                    Assert.IsTrue(item.Id.StartsWith('|' + item.Context.Operation.Id + '.'));
                }
            }
            else
            {
                Assert.IsNotNull(item.Context.Operation.Id);
                Assert.IsNull(item.Context.Operation.ParentId);
            }

            if (request != null)
            {
#if DEBUG
                var requestIdHeader = request.Headers.GetValues(RequestResponseHeaders.RequestIdHeader).Single();
#endif

                if (expectW3CHeaders)
                {
                    var traceId = item.Context.Operation.Id;
                    var spanId  = item.Id;
                    var expectedTraceParentHeader = $"00-{traceId}-{spanId}-00";
                    var expectedRequestId         = $"|{traceId}.{spanId}.";

                    Assert.AreEqual(expectedTraceParentHeader, request.Headers.GetValues(W3C.W3CConstants.TraceParentHeader).Single());
                    if (parentActivity?.TraceStateString != null)
                    {
                        Assert.AreEqual(parentActivity.TraceStateString, request.Headers.GetValues(W3C.W3CConstants.TraceStateHeader).Single());
                    }

                    if (expectRequestId)
                    {
                        Assert.AreEqual(expectedRequestId, request.Headers.GetValues(RequestResponseHeaders.RequestIdHeader).Single());
                    }
                    else
                    {
#if NETCOREAPP2_1
                        // even though we don't inject back-compatible request-id, .NET Core 2.0 will inject one that will look like traceparent
                        Assert.AreEqual(expectedTraceParentHeader, request.Headers.GetValues(RequestResponseHeaders.RequestIdHeader).Single());
#elif NETCOREAPP3_1
                        // It appears that .NET CORE 3 does not inject a Request-Id header. Need to verify with Liudmila.
#else
#error This condition is unexpected
#endif
                    }
                }
                else
                {
                    Assert.IsFalse(request.Headers.Contains(W3C.W3CConstants.TraceParentHeader));
                    Assert.IsFalse(request.Headers.Contains(W3C.W3CConstants.TraceStateHeader));
                    Assert.AreEqual(item.Id, request.Headers.GetValues(RequestResponseHeaders.RequestIdHeader).Single());
                }

                if (expectLegacyHeaders)
                {
                    Assert.AreEqual(item.Id, request.Headers.GetValues(RequestResponseHeaders.StandardParentIdHeader).Single());
                    Assert.AreEqual(item.Context.Operation.Id, request.Headers.GetValues(RequestResponseHeaders.StandardRootIdHeader).Single());
                }
                else
                {
                    Assert.IsFalse(request.Headers.Contains(RequestResponseHeaders.StandardParentIdHeader));
                    Assert.IsFalse(request.Headers.Contains(RequestResponseHeaders.StandardRootIdHeader));
                }

                if (parentActivity != null && parentActivity.Baggage.Any())
                {
                    var correlationContextHeader = request.Headers.GetValues(RequestResponseHeaders.CorrelationContextHeader)
                                                   .Single()
                                                   .Split(',')
                                                   .ToArray();
                    var baggage = Activity.Current.Baggage.Select(kvp => $"{kvp.Key}={kvp.Value}").ToArray();
                    Assert.AreEqual(baggage.Length, correlationContextHeader.Length);

                    foreach (var baggageItem in baggage)
                    {
                        Assert.IsTrue(correlationContextHeader.Contains(baggageItem));
                    }
                }
                else
                {
                    Assert.IsFalse(request.Headers.Contains(RequestResponseHeaders.CorrelationContextHeader));
                }
            }

            // Validate the http request was captured
            this.operationDetailsInitializer.ValidateOperationDetailsCore(item, responseExpected);
        }
        public void GetSdkVersionReturnsVersionWithoutPrefixForStringEmpty()
        {
            string expected = SdkVersionHelper.GetExpectedSdkVersion(typeof(RequestTrackingTelemetryModule), prefix: string.Empty);

            Assert.AreEqual(expected, SdkVersionUtils.GetSdkVersion(string.Empty));
        }
        public void GetSdkVersionReturnsVersionWithPrefix()
        {
            string expected = SdkVersionHelper.GetExpectedSdkVersion(typeof(RequestTrackingTelemetryModule), prefix: "lala");

            Assert.AreEqual(expected, SdkVersionUtils.GetSdkVersion("lala"));
        }