public void MetricThreePropsCompare()
        {
            var channel = new StubTelemetryChannel();
            var client = GetTestTelemetryClient(channel);

            bool stopSending = false;

            var delayTask = Task.Delay(10000).ContinueWith((t) =>
            {
                stopSending = true;
            });

            while (!stopSending)
            {
                double val = new Random().NextDouble() * 100;
                string city = val > 50 ? "Seattle" : "New York";
                string currency = ((int)val % 2) == 0 ? "Dollar" : "Pound";
                string animal = ((int)val % 2) == 0 ? "Bear" : "Drop Bear";

                client.TrackMetric("simple", val);
                client.TrackAggregateMetric("agg", val, city, currency, animal);

                Thread.Sleep((int)val);
            }

            delayTask.Wait();
            Task.Delay(6000).Wait();

            channel.AssertSingleAndAggMetricsAreEqual();
        }
Beispiel #2
0
        public void TrackUsesInstrumentationKeyFromEnvironmentIfEmptyInCode()
        {
            PlatformSingleton.Current = new StubPlatform();

            ITelemetry sentTelemetry = null;
            var        channel       = new StubTelemetryChannel {
                OnSend = telemetry => sentTelemetry = telemetry
            };
            var configuration = new TelemetryConfiguration {
                TelemetryChannel = channel
            };
            var client = new TelemetryClient(configuration);

            string expectedKey = Guid.NewGuid().ToString();

            configuration.InstrumentationKey = Guid.NewGuid().ToString();                      // Set in config
            Environment.SetEnvironmentVariable("APPINSIGHTS_INSTRUMENTATIONKEY", expectedKey); // Set via env. variable
            Assert.DoesNotThrow(() => client.TrackTrace("Test Message"));

            Assert.Equal(expectedKey, sentTelemetry.Context.InstrumentationKey);

            Environment.SetEnvironmentVariable("APPINSIGHTS_INSTRUMENTATIONKEY", null);

            PlatformSingleton.Current = null;
        }
        public void TrackUsesInstrumentationKeyFromClientContextIfSetInCodeFirst()
        {
            ClearActiveTelemetryConfiguration();
            PlatformSingleton.Current = new StubPlatform();
            string message = "Test Message";

            ITelemetry sentTelemetry = null;
            var        channel       = new StubTelemetryChannel {
                OnSend = telemetry => sentTelemetry = telemetry
            };
            var configuration = new TelemetryConfiguration(string.Empty, channel);
            var client        = new TelemetryClient(configuration);

            string environmentKey = Guid.NewGuid().ToString();
            string expectedKey    = Guid.NewGuid().ToString();

            Environment.SetEnvironmentVariable("APPINSIGHTS_INSTRUMENTATIONKEY", environmentKey); // Set via the environment variable.

            client.Context.InstrumentationKey = expectedKey;
            Assert.DoesNotThrow(() => client.TrackTrace(message));
            Assert.Equal(expectedKey, sentTelemetry.Context.InstrumentationKey);

            Environment.SetEnvironmentVariable("APPINSIGHTS_INSTRUMENTATIONKEY", null);

            PlatformSingleton.Current = null;
        }
Beispiel #4
0
        public void ModuleKeepsIntervalSteadyWhenMetricsAreLongToCollect()
        {
            var sentItems = new List <ITelemetry>();
            var channel   = new StubTelemetryChannel()
            {
                OnSend = (item) => { sentItems.Add(item); }
            };
            var config = new TelemetryConfiguration();

            config.TelemetryChannel   = channel;
            config.InstrumentationKey = "dummy";
            var startTime = DateTimeOffset.Now;

            AggregateMetricsTelemetryModule module = new AggregateMetricsTelemetryModule();

            module.FlushInterval = TimeSpan.FromSeconds(6);

            module.Initialize(config);

            var client = new TelemetryClient(config);

            client.Gauge("test", () => { Thread.Sleep(TimeSpan.FromSeconds(1)); return(10); });

            Thread.Sleep(TimeSpan.FromSeconds(15));

            Assert.AreEqual(2, sentItems.Count);
            var metric0 = (MetricTelemetry)sentItems[0];
            var metric1 = (MetricTelemetry)sentItems[1];

            var timeDelta = metric1.Timestamp - metric0.Timestamp - TimeSpan.FromSeconds(6);

            Assert.IsTrue(timeDelta.TotalMilliseconds < 50, "Actual: " + timeDelta);
        }
Beispiel #5
0
        public void SinkProcessorsAreInvoked()
        {
            var configuration = new TelemetryConfiguration();

            var sentTelemetry = new List <ITelemetry>(1);
            var channel       = new StubTelemetryChannel();

            channel.OnSend = (telemetry) => sentTelemetry.Add(telemetry);
            configuration.TelemetryChannel = channel;

            var chainBuilder = new TelemetryProcessorChainBuilder(configuration, configuration.DefaultTelemetrySink);

            configuration.DefaultTelemetrySink.TelemetryProcessorChainBuilder = chainBuilder;
            chainBuilder.Use((next) =>
            {
                var first       = new StubTelemetryProcessor(next);
                first.OnProcess = (telemetry) => telemetry.Context.Properties.Add("SeenByFirst", "true");
                return(first);
            });
            chainBuilder.Use((next) =>
            {
                var second       = new StubTelemetryProcessor(next);
                second.OnProcess = (telemetry) => telemetry.Context.Properties.Add("SeenBySecond", "true");
                return(second);
            });

            var client = new TelemetryClient(configuration);

            client.TrackTrace("t1");

            Assert.IsFalse(configuration.TelemetryProcessors.OfType <StubTelemetryProcessor>().Any()); // Both processors belong to the sink, not to the common chain.
            Assert.AreEqual(1, sentTelemetry.Count);
            Assert.IsTrue(sentTelemetry[0].Context.Properties.ContainsKey("SeenByFirst"));
            Assert.IsTrue(sentTelemetry[0].Context.Properties.ContainsKey("SeenBySecond"));
        }
Beispiel #6
0
        public static ITelimena GetCrackedTelimena(ICollection <ITelemetry> sentTelemetry, Guid telemetryKey, string userName, bool excludeStartingEvent = false)
        {
            var startupInfo = new TelimenaStartupInfo(telemetryKey, Helpers.TeliUri)
            {
                UserInfo = new TelimenaClient.Model.UserInfo()
                {
                    UserIdentifier = userName
                }
            };
            var telimena = TelimenaFactory.Construct(startupInfo);
            StubTelemetryChannel channel = new StubTelemetryChannel
            {
                OnSend = t =>
                {
                    EventTelemetry ev = t as EventTelemetry;
                    if (excludeStartingEvent && ev?.Name == "TelimenaSessionStarted")
                    {
                        return;
                    }
                    sentTelemetry.Add(t);
                }
            };
            TelemetryModule module = telimena.GetFieldValue <TelemetryModule>("telemetryModule");

            SetStaticFieldValue(module, "isSessionStartedEventSent", false);

            TelemetryClient client = module.GetPropertyValue <TelemetryClient>("TelemetryClient");
            var             config = client.GetPropertyValue <TelemetryConfiguration>("TelemetryConfiguration");

            config.SetPropertyValue("TelemetryChannel", channel);


            return(telimena);
        }
Beispiel #7
0
        public void CommonTelemetryProcessorsAreInvoked()
        {
            var configuration = new TelemetryConfiguration();

            var sentTelemetry = new List <ITelemetry>(1);
            var channel       = new StubTelemetryChannel();

            channel.OnSend = (telemetry) => sentTelemetry.Add(telemetry);
            configuration.TelemetryChannel = channel;

            var chainBuilder = new TelemetryProcessorChainBuilder(configuration);

            configuration.TelemetryProcessorChainBuilder = chainBuilder;
            chainBuilder.Use((next) =>
            {
                var first       = new StubTelemetryProcessor(next);
                first.OnProcess = (telemetry) => telemetry.Context.Properties.Add("SeenByFirst", "true");
                return(first);
            });
            chainBuilder.Use((next) =>
            {
                var second       = new StubTelemetryProcessor(next);
                second.OnProcess = (telemetry) => telemetry.Context.Properties.Add("SeenBySecond", "true");
                return(second);
            });

            var client = new TelemetryClient(configuration);

            client.TrackTrace("t1");

            Assert.AreEqual(1, sentTelemetry.Count);
            Assert.IsTrue(sentTelemetry[0].Context.Properties.ContainsKey("SeenByFirst"));
            Assert.IsTrue(sentTelemetry[0].Context.Properties.ContainsKey("SeenBySecond"));
        }
        public void TrackWritesTelemetryToDebugOutputIfIKeyEmpty()
        {
            ClearActiveTelemetryConfiguration();
            string actualMessage = null;
            var    debugOutput   = new StubDebugOutput
            {
                OnWriteLine = message =>
                {
                    System.Diagnostics.Debug.WriteLine("1");
                    actualMessage = message;
                },
                OnIsAttached = () => true,
            };

            PlatformSingleton.Current = new StubPlatform {
                OnGetDebugOutput = () => debugOutput
            };
            var channel = new StubTelemetryChannel {
                DeveloperMode = true
            };
            var configuration = new TelemetryConfiguration(string.Empty, channel);
            var client        = new TelemetryClient(configuration);

            client.Track(new StubTelemetry());

            Assert.True(actualMessage.StartsWith("Application Insights Telemetry (unconfigured): "));
            PlatformSingleton.Current = null;
        }
Beispiel #9
0
        private TelemetryConfiguration CreateDefaultConfig(HttpContext fakeContext, string rootIdHeaderName = null, string parentIdHeaderName = null, string instrumentationKey = null)
        {
            var telemetryChannel = new StubTelemetryChannel()
            {
                EndpointAddress = "https://endpointaddress",
                OnSend          = item => this.sentTelemetry.Enqueue(item)
            };

            var configuration = new TelemetryConfiguration
            {
                TelemetryChannel      = telemetryChannel,
                InstrumentationKey    = TestInstrumentationKey1,
                ApplicationIdProvider = new MockApplicationIdProvider(TestInstrumentationKey1, TestApplicationId1)
            };

            configuration.TelemetryInitializers.Add(new Extensibility.OperationCorrelationTelemetryInitializer());

            var telemetryInitializer = new TestableOperationCorrelationTelemetryInitializer(fakeContext);

            if (rootIdHeaderName != null)
            {
                telemetryInitializer.RootOperationIdHeaderName = rootIdHeaderName;
            }

            if (parentIdHeaderName != null)
            {
                telemetryInitializer.ParentOperationIdHeaderName = parentIdHeaderName;
            }

            configuration.TelemetryInitializers.Add(telemetryInitializer);

            return(configuration);
        }
Beispiel #10
0
        public void Initialize()
        {
            this.sentTelemetry = new List <DependencyTelemetry>();

            this.channel = new StubTelemetryChannel
            {
                OnSend = telemetry =>
                {
                    // The correlation id lookup service also makes http call, just make sure we skip that
                    DependencyTelemetry depTelemetry = telemetry as DependencyTelemetry;
                    if (depTelemetry != null)
                    {
                        this.sentTelemetry.Add(depTelemetry);
                    }
                },
                EndpointAddress = FakeProfileApiEndpoint
            };

            this.config = new TelemetryConfiguration
            {
                InstrumentationKey = IKey,
                TelemetryChannel   = this.channel
            };

            this.config.TelemetryInitializers.Add(new OperationCorrelationTelemetryInitializer());
        }
Beispiel #11
0
        public void SimpleTrackMetricCompare()
        {
            var channel = new StubTelemetryChannel();
            var client  = GetTestTelemetryClient(channel);

            bool stopSending = false;

            var delayTask = Task.Delay(10000).ContinueWith((t) =>
            {
                stopSending = true;
            });

            while (!stopSending)
            {
                double val = new Random().NextDouble() * 100;
                client.TrackMetric("simple", val);
                client.TrackAggregateMetric("agg", val);

                Thread.Sleep((int)val);
            }

            delayTask.Wait();
            Task.Delay(6000).Wait();

            channel.AssertSingleAndAggMetricsAreEqual();
        }
Beispiel #12
0
        public void SimpleModuleUsage()
        {
            var sentItems = new List <ITelemetry>();
            var channel   = new StubTelemetryChannel()
            {
                OnSend = (item) => { sentItems.Add(item); }
            };
            var config = new TelemetryConfiguration();

            config.TelemetryChannel   = channel;
            config.InstrumentationKey = "dummy";

            AggregateMetricsTelemetryModule module = new AggregateMetricsTelemetryModule();

            module.FlushInterval = TimeSpan.FromSeconds(6);

            module.Initialize(config);

            var client = new TelemetryClient(config);

            client.Gauge("test", () => { return(10); });

            Thread.Sleep(TimeSpan.FromSeconds(7));

            Assert.AreEqual(1, sentItems.Count);
            var metric = (MetricTelemetry)sentItems[0];

            Assert.AreEqual("test", metric.Name);
            Assert.AreEqual(10, metric.Value);
        }
        public void TrackRespectsInstrumentaitonKeySetByTelemetryInitializer()
        {
            var sentTelemetry = new List <ITelemetry>();
            var channel       = new StubTelemetryChannel {
                OnSend = t => sentTelemetry.Add(t)
            };

            // No instrumentation key set here.
            var configuration = new TelemetryConfiguration(string.Empty, channel);

            var initializedTelemetry = new List <ITelemetry>();
            var telemetryInitializer = new StubTelemetryInitializer();

            telemetryInitializer.OnInitialize = item =>
            {
                item.Context.InstrumentationKey = "Foo";
                initializedTelemetry.Add(item);
            };

            configuration.TelemetryInitializers.Add(telemetryInitializer);

            var client = new TelemetryClient(configuration);

            var telemetry = new StubTelemetry();

            client.Track(telemetry);

            Assert.Equal(1, sentTelemetry.Count);
            Assert.Equal(1, initializedTelemetry.Count);
        }
        internal static TelemetryConfiguration CreateTelemetryConfigWithExtractor(IList <ITelemetry> telemetrySentToChannel,
                                                                                  Func <ITelemetryProcessor, AutocollectedMetricsExtractor> extractorFactory)
        {
            ITelemetryChannel channel = new StubTelemetryChannel {
                OnSend = (t) => telemetrySentToChannel.Add(t)
            };
            string iKey = Guid.NewGuid().ToString("D");
            TelemetryConfiguration telemetryConfig = new TelemetryConfiguration(iKey, channel);

            var channelBuilder = new TelemetryProcessorChainBuilder(telemetryConfig);

            channelBuilder.Use(extractorFactory);
            channelBuilder.Build();

            TelemetryProcessorChain processors = telemetryConfig.TelemetryProcessorChain;

            foreach (ITelemetryProcessor processor in processors.TelemetryProcessors)
            {
                ITelemetryModule m = processor as ITelemetryModule;
                if (m != null)
                {
                    m.Initialize(telemetryConfig);
                }
            }


            return(telemetryConfig);
        }
Beispiel #15
0
        public void ReplacingTelemetryChannelOnConfiguraitonReplacesItForDefaultSink()
        {
            var configuration = new TelemetryConfiguration();

            var firstSentTelemetry = new List <ITelemetry>(1);
            var firstChannel       = new StubTelemetryChannel();

            firstChannel.OnSend            = (telemetry) => firstSentTelemetry.Add(telemetry);
            configuration.TelemetryChannel = firstChannel;

            var client = new TelemetryClient(configuration);

            client.TrackTrace("t1");

            Assert.AreEqual(1, firstSentTelemetry.Count);

            var secondSentTelemetry = new List <ITelemetry>(1);
            var secondChannel       = new StubTelemetryChannel();

            secondChannel.OnSend           = (telemetry) => secondSentTelemetry.Add(telemetry);
            configuration.TelemetryChannel = secondChannel;

            client.TrackTrace("t1");

            Assert.AreEqual(1, firstSentTelemetry.Count);
            Assert.AreEqual(1, secondSentTelemetry.Count);
        }
Beispiel #16
0
        public void MetricTwoPropsCompare()
        {
            var channel = new StubTelemetryChannel();
            var client  = GetTestTelemetryClient(channel);

            bool stopSending = false;

            var delayTask = Task.Delay(10000).ContinueWith((t) =>
            {
                stopSending = true;
            });

            while (!stopSending)
            {
                double val      = new Random().NextDouble() * 100;
                string city     = val > 50 ? "Seattle" : "New York";
                string currency = ((int)val % 2) == 0 ? "Dollar" : "Pound";

                client.TrackMetric("simple", val);
                client.TrackAggregateMetric("agg", val, city, currency);

                Thread.Sleep((int)val);
            }

            delayTask.Wait();
            Task.Delay(6000).Wait();

            channel.AssertSingleAndAggMetricsAreEqual();
        }
Beispiel #17
0
        public void TrackWritesTelemetryToDebugOutputIfIKeyNotEmpty()
        {
            string actualMessage = null;
            var    debugOutput   = new StubDebugOutput
            {
                OnWriteLine  = message => actualMessage = message,
                OnIsAttached = () => true,
            };

            PlatformSingleton.Current = new StubPlatform {
                OnGetDebugOutput = () => debugOutput
            };
            var channel = new StubTelemetryChannel {
                DeveloperMode = true
            };
            var configuration = new TelemetryConfiguration
            {
                TelemetryChannel   = channel,
                InstrumentationKey = "123"
            };
            var client = new TelemetryClient(configuration);

            client.Track(new StubTelemetry());

            Assert.True(actualMessage.StartsWith("Application Insights Telemetry: "));
            PlatformSingleton.Current = null;
        }
 public SessionTelemetryModuleTest()
 {
     this.platform = new StubPlatform { OnGetApplicationSettings = () => this.settings };
     this.channel = new StubTelemetryChannel { OnSend = t => this.sentTelemetry.Add(t) };
     this.configuration = new TelemetryConfiguration { TelemetryChannel = this.channel, InstrumentationKey = "Test Key" };
     ServiceLocator.AddService<IApplicationService>(new ApplicationService());
     TelemetryConfiguration.Active = configuration;
     HockeyClient.Current.AsInternal().IsTelemetryInitialized = true;
 }
        public void TrackMethodDoesNotThrowWhenInstrumentationKeyIsEmptyAndNotSendingTheTelemetryItem()
        {
            var channel = new StubTelemetryChannel {
                ThrowError = true
            };

            TelemetryConfiguration.Active = new TelemetryConfiguration(string.Empty, channel);
            Assert.DoesNotThrow(() => new TelemetryClient().Track(new StubTelemetry()));
        }
        public async Task TestDependencyCollectionWithParentActivity()
        {
            ITelemetry sentTelemetry = null;

            var channel = new StubTelemetryChannel
            {
                OnSend = telemetry =>
                {
                    // The correlation id lookup service also makes http call, just make sure we skip that
                    DependencyTelemetry depTelemetry = telemetry as DependencyTelemetry;
                    if (depTelemetry != null &&
                        !depTelemetry.Data.StartsWith(FakeProfileApiEndpoint, StringComparison.OrdinalIgnoreCase))
                    {
                        Assert.IsNull(sentTelemetry);
                        sentTelemetry = telemetry;
                    }
                },
                EndpointAddress = FakeProfileApiEndpoint
            };

            var config = new TelemetryConfiguration
            {
                InstrumentationKey = IKey,
                TelemetryChannel   = channel
            };

            config.TelemetryInitializers.Add(new OperationCorrelationTelemetryInitializer());

            using (var module = new DependencyTrackingTelemetryModule())
            {
                module.ProfileQueryEndpoint = FakeProfileApiEndpoint;
                module.Initialize(config);

                var parent = new Activity("parent").AddBaggage("k", "v").SetParentId("|guid.").Start();

                var url     = new Uri("http://bing.com");
                var request = new HttpRequestMessage(HttpMethod.Get, url);
                await new HttpClient().SendAsync(request);

                // on netcoreapp1.0 DiagnosticSource event is fired asycronously, let's wait for it
                Assert.IsTrue(SpinWait.SpinUntil(() => sentTelemetry != null, TimeSpan.FromSeconds(1)));

                parent.Stop();

                var item = (DependencyTelemetry)sentTelemetry;
                Assert.AreEqual("200", item.ResultCode);

                var requestId = item.Id;
                Assert.AreEqual(requestId, request.Headers.GetValues("Request-Id").Single());
                Assert.AreEqual(requestId, request.Headers.GetValues("x-ms-request-id").Single());
                Assert.IsTrue(requestId.StartsWith(parent.Id));
                Assert.AreNotEqual(parent.Id, requestId);
                Assert.AreEqual("v", item.Context.Properties["k"]);

                Assert.AreEqual("k=v", request.Headers.GetValues("Correlation-Context").Single());
            }
        }
        public void NewTelemetryConfigurationWithChannelUsesSpecifiedChannel()
        {
            StubTelemetryChannel   stubChannel = new StubTelemetryChannel();
            TelemetryConfiguration config      = new TelemetryConfiguration(string.Empty, stubChannel);

            Assert.Same(stubChannel, config.TelemetryChannel);
            FieldInfo shouldDisposeChannelField = typeof(TelemetryConfiguration).GetField("shouldDisposeChannel", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);

            Assert.False((bool)shouldDisposeChannelField.GetValue(config));
        }
        public void TelemetryChannelCanBeSetByUserToReplaceDefaultChannelForTesting()
        {
            var configuration = new TelemetryConfiguration();

            var customChannel = new StubTelemetryChannel();

            configuration.TelemetryChannel = customChannel;

            Assert.AreSame(customChannel, configuration.TelemetryChannel);
        }
        private TelemetryClient InitializeTelemetryClient(ICollection <ITelemetry> sentTelemetry)
        {
            var channel = new StubTelemetryChannel {
                OnSend = t => sentTelemetry.Add(t)
            };
            var telemetryConfiguration = new TelemetryConfiguration(Guid.NewGuid().ToString(), channel);
            var client = new TelemetryClient(telemetryConfiguration);

            return(client);
        }
Beispiel #24
0
        public void ModuleWillKeepIntervalWithThreadsStarvation()
        {
            var sentItems = new List <ITelemetry>();
            var channel   = new StubTelemetryChannel()
            {
                OnSend = (item) => { sentItems.Add(item); }
            };
            var config = new TelemetryConfiguration();

            config.TelemetryChannel   = channel;
            config.InstrumentationKey = "dummy";

            AggregateMetricsTelemetryModule module = new AggregateMetricsTelemetryModule();

            module.FlushInterval = TimeSpan.FromSeconds(6);

            module.Initialize(config);

            var startTime = DateTime.Now;

            var client = new TelemetryClient(config);

            client.Gauge("test", () => { return(10); });

            int workerThread;
            int ioCompletionThread;

            ThreadPool.GetMaxThreads(out workerThread, out ioCompletionThread);
            try
            {
                ThreadPool.SetMaxThreads(10, 10);
                for (int i = 0; i < 50; i++)
                {
                    new Task(() => {
                        Debug.WriteLine("task started");
                        Thread.Sleep(TimeSpan.FromSeconds(10));
                        Debug.WriteLine("task finihed");
                    }).Start();
                }

                Thread.Sleep(TimeSpan.FromSeconds(7));

                Assert.AreEqual(1, sentItems.Count);
                var metric = (MetricTelemetry)sentItems[0];
                Assert.AreEqual("test", metric.Name);
                Assert.AreEqual(10, metric.Value);
                Assert.IsTrue(metric.Timestamp.Subtract(startTime).Seconds <= 6, "Actual: " + metric.Timestamp.Subtract(startTime).Seconds);
                Assert.IsTrue(metric.Timestamp.Subtract(startTime).Seconds >= 5, "Actual: " + metric.Timestamp.Subtract(startTime).Seconds);
            }
            finally
            {
                ThreadPool.SetMaxThreads(workerThread, ioCompletionThread);
            }
        }
        private static void Metrics_SpecifiedPipeline(TelemetryConfiguration telemetryPipeline)
        {
            telemetryPipeline.InstrumentationKey = Guid.NewGuid().ToString("D");

            MetricManager manager1 = telemetryPipeline.GetMetricManager();

            Assert.IsNotNull(manager1);

            MetricManager manager2 = telemetryPipeline.GetMetricManager();

            Assert.IsNotNull(manager2);

            Assert.AreEqual(manager1, manager2);
            Assert.AreSame(manager1, manager2);
            Assert.IsTrue(Object.ReferenceEquals(manager1, manager2));

            StubTelemetryChannel telemetryCollector = new StubTelemetryChannel();

            telemetryPipeline.TelemetryChannel = telemetryCollector;
            Assert.AreSame(telemetryCollector, telemetryPipeline.TelemetryChannel);

            //CollectingTelemetryInitializer telemetryCollector = new CollectingTelemetryInitializer();
            //defaultTelemetryPipeline.TelemetryInitializers.Add(coll);

            IMetricSeriesConfiguration seriesConfig = new MetricSeriesConfigurationForMeasurement(restrictToUInt32Values: false);

            manager1.CreateNewSeries("ns", "Metric A", seriesConfig).TrackValue(42);
            manager1.CreateNewSeries("ns", "Metric A", seriesConfig).TrackValue("18");
            manager2.CreateNewSeries("ns", "Metric A", seriesConfig).TrackValue(10000);
            manager2.CreateNewSeries("ns", "Metric B", seriesConfig).TrackValue(-0.001);
            manager1.Flush();

            Assert.AreEqual(4, telemetryCollector.TelemetryItems.Count);

            Assert.IsInstanceOfType(telemetryCollector.TelemetryItems[0], typeof(MetricTelemetry));
            Assert.AreEqual("Metric B", ((MetricTelemetry)telemetryCollector.TelemetryItems[0]).Name);
            Assert.AreEqual(1, ((MetricTelemetry)telemetryCollector.TelemetryItems[0]).Count);
            Assert.AreEqual(-0.001, ((MetricTelemetry)telemetryCollector.TelemetryItems[0]).Sum);

            Assert.IsInstanceOfType(telemetryCollector.TelemetryItems[1], typeof(MetricTelemetry));
            Assert.AreEqual("Metric A", ((MetricTelemetry)telemetryCollector.TelemetryItems[1]).Name);
            Assert.AreEqual(1, ((MetricTelemetry)telemetryCollector.TelemetryItems[1]).Count);
            Assert.AreEqual(10000, ((MetricTelemetry)telemetryCollector.TelemetryItems[1]).Sum);

            Assert.IsInstanceOfType(telemetryCollector.TelemetryItems[2], typeof(MetricTelemetry));
            Assert.AreEqual("Metric A", ((MetricTelemetry)telemetryCollector.TelemetryItems[2]).Name);
            Assert.AreEqual(1, ((MetricTelemetry)telemetryCollector.TelemetryItems[2]).Count);
            Assert.AreEqual(18, ((MetricTelemetry)telemetryCollector.TelemetryItems[2]).Sum);

            Assert.IsInstanceOfType(telemetryCollector.TelemetryItems[3], typeof(MetricTelemetry));
            Assert.AreEqual("Metric A", ((MetricTelemetry)telemetryCollector.TelemetryItems[3]).Name);
            Assert.AreEqual(1, ((MetricTelemetry)telemetryCollector.TelemetryItems[3]).Count);
            Assert.AreEqual(42, ((MetricTelemetry)telemetryCollector.TelemetryItems[3]).Sum);
        }
        public void NewTelemetryConfigurationWithInstrumentationKeyAndChannelUsesSpecifiedKeyAndChannel()
        {
            string expectedKey = "expected";
            StubTelemetryChannel   stubChannel = new StubTelemetryChannel();
            TelemetryConfiguration config      = new TelemetryConfiguration(expectedKey, stubChannel);

            Assert.Equal(expectedKey, config.InstrumentationKey);
            Assert.Same(stubChannel, config.TelemetryChannel);
            FieldInfo shouldDisposeChannelField = typeof(TelemetryConfiguration).GetField("shouldDisposeChannel", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);

            Assert.False((bool)shouldDisposeChannelField.GetValue(config));
        }
        public void NewTelemetryConfigurationWithChannelUsesSpecifiedChannel()
        {
            StubTelemetryChannel stubChannel = new StubTelemetryChannel();
            bool channelDisposed             = false;

            stubChannel.OnDispose += () => { channelDisposed = true; };
            TelemetryConfiguration config = new TelemetryConfiguration(string.Empty, stubChannel);

            Assert.AreSame(stubChannel, config.TelemetryChannel);
            config.Dispose();
            Assert.IsFalse(channelDisposed);
        }
Beispiel #28
0
        public void TrackDoesNotTryAddingDeveloperModeCustomPropertyWhenTelemetryDoesNotSupportCustomProperties()
        {
            var channel = new StubTelemetryChannel {
                DeveloperMode = true
            };
            var configuration = new TelemetryConfiguration {
                TelemetryChannel = channel, InstrumentationKey = "Test Key"
            };
            var client = new TelemetryClient(configuration);

            Assert.DoesNotThrow(() => client.Track(new SessionStateTelemetry()));
        }
        public void TrackDoesNotTryAddingDeveloperModeCustomPropertyWhenTelemetryDoesNotSupportCustomProperties()
        {
            var channel = new StubTelemetryChannel {
                DeveloperMode = true
            };
            var configuration = new TelemetryConfiguration("Test Key", channel);
            var client        = new TelemetryClient(configuration);

#pragma warning disable 618
            Assert.DoesNotThrow(() => client.Track(new SessionStateTelemetry()));
#pragma warning disable 618
        }
        private TelemetryClient InitializeTelemetryClient(List <ITelemetry> sentTelemetry)
        {
            var channel = new StubTelemetryChannel {
                OnSend = t => sentTelemetry.Add(t)
            };
            var telemetryConfiguration = new TelemetryConfiguration {
                InstrumentationKey = Guid.NewGuid().ToString(), TelemetryChannel = channel
            };

            var client = new TelemetryClient(telemetryConfiguration);

            return(client);
        }
        public void TestInit()
        {
            this.sendItems = new List <ITelemetry>();
            var stubTelemetryChannel = new StubTelemetryChannel {
                OnSend = item => this.sendItems.Add(item)
            };

            this.configuration = new TelemetryConfiguration
            {
                InstrumentationKey = Guid.NewGuid().ToString(),
                TelemetryChannel   = stubTelemetryChannel
            };
        }
        public void CommonTelemetryChannelIsDefaultSinkTelemetryChannel()
        {
            var configuration = new TelemetryConfiguration();

            var c1 = new StubTelemetryChannel();
            var c2 = new StubTelemetryChannel();

            configuration.TelemetryChannel = c1;
            Assert.AreSame(c1, configuration.TelemetryChannel);

            configuration.DefaultTelemetrySink.TelemetryChannel = c2;
            Assert.AreSame(c2, configuration.TelemetryChannel);
        }
        public void TestInitialize()
        {
            this.items = new List<ITelemetry>();

            this.moduleChannel = new StubTelemetryChannel { OnSend = telemetry => this.items.Add(telemetry) };

            TelemetryConfiguration.Active.TelemetryChannel = new StubTelemetryChannel
            {
                EndpointAddress = "http://test.com"
            };
            TelemetryConfiguration.Active.InstrumentationKey = "MyKey";
            TelemetryConfiguration.Active.TelemetryInitializers.Clear();            
        }
        public void TestInitialize()
        {
            this.items = new List<ITelemetry>();

            var moduleChannel = new StubTelemetryChannel
            {
                OnSend = telemetry => this.items.Add(telemetry),
                EndpointAddress = "http://test.com"
            };

            this.moduleConfiguration = new TelemetryConfiguration
            {
                TelemetryChannel = moduleChannel,
                InstrumentationKey = "MyKey",
            };
        }
        public void TelemetryChannelCanBeSetByUserToReplaceDefaultChannelForTesting()
        {
            var configuration = new TelemetryConfiguration();

            var customChannel = new StubTelemetryChannel();
            configuration.TelemetryChannel = customChannel;

            Assert.Same(customChannel, configuration.TelemetryChannel);
        }
        public void SimpleTrackMetricCompare()
        {
            var channel = new StubTelemetryChannel();
            var client = GetTestTelemetryClient(channel);

            bool stopSending = false;

            var delayTask = Task.Delay(10000).ContinueWith((t) =>
            {
                stopSending = true;
            });

            while (!stopSending)
            {
                double val = new Random().NextDouble() * 100;
                client.TrackMetric("simple", val);
                client.TrackAggregateMetric("agg", val);

                Thread.Sleep((int)val);
            }

            delayTask.Wait();
            Task.Delay(6000).Wait();

            channel.AssertSingleAndAggMetricsAreEqual();
        }
 public void TestCleanup()
 {
     this.moduleChannel = null;
     this.items.Clear();
 }
        public void OnEndTracksRequest()
        {
            var sendItems = new List<ITelemetry>();
            var stubTelemetryChannel = new StubTelemetryChannel { OnSend = item => sendItems.Add(item) };
            var configuration = new TelemetryConfiguration
            {
                InstrumentationKey = Guid.NewGuid().ToString(),
                TelemetryChannel = stubTelemetryChannel
            };

            var module = new RequestTrackingTelemetryModule();
            module.Initialize(configuration);
            module.OnBeginRequest(null);
            module.OnEndRequest(null);

            Assert.Equal(1, sendItems.Count);
        }