/// <summary>
        /// Initializes a new instance of the <see cref="ProfilerHttpProcessing"/> class.
        /// </summary>
        public ProfilerHttpProcessing(TelemetryConfiguration configuration, string agentVersion, ObjectInstanceBasedOperationHolder telemetryTupleHolder, bool setCorrelationHeaders, ICollection<string> correlationDomainExclusionList)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            if (telemetryTupleHolder == null)
            {
                throw new ArgumentNullException("telemetryTupleHolder");
            }

            if (correlationDomainExclusionList == null)
            {
                throw new ArgumentNullException("correlationDomainExclusionList");
            }

            this.applicationInsightsUrlFilter = new ApplicationInsightsUrlFilter(configuration);
            this.TelemetryTable = telemetryTupleHolder;
            this.telemetryClient = new TelemetryClient(configuration);
            this.correlationDomainExclusionList = correlationDomainExclusionList;
            this.setCorrelationHeaders = setCorrelationHeaders;

            // Since dependencySource is no longer set, sdk version is prepended with information which can identify whether RDD was collected by profiler/framework
            // For directly using TrackDependency(), version will be simply what is set by core
            string prefix = "rdd" + RddSource.Profiler + ":";
            this.telemetryClient.Context.GetInternalContext().SdkVersion = SdkVersionUtils.GetSdkVersion(prefix);
            if (!string.IsNullOrEmpty(agentVersion))
            {
                this.telemetryClient.Context.GetInternalContext().AgentVersion = agentVersion;
            }
        }
        public void RichPayloadEventSourceEventSentTest()
        {
            var client = new TelemetryClient();
            client.InstrumentationKey = Guid.NewGuid().ToString();

            using (var listener = new Microsoft.ApplicationInsights.TestFramework.TestEventListener())
            {
                listener.EnableEvents(RichPayloadEventSource.Log.EventSourceInternal, EventLevel.Verbose, RichPayloadEventSource.Keywords.Events);

                var item = new EventTelemetry("TestEvent");
                item.Context.Properties.Add("property1", "value1");
                item.Context.User.Id = "testUserId";
                item.Context.Operation.Id = Guid.NewGuid().ToString();

                client.TrackEvent(item);

                var actualEvent = listener.Messages.FirstOrDefault();

                Assert.IsNotNull(actualEvent);
                Assert.AreEqual(client.InstrumentationKey, actualEvent.Payload[0]);

                object[] tags = actualEvent.Payload[1] as object[];
                Assert.AreEqual("ai.user.id", ((Dictionary<string, object>)(tags[0]))["Key"]);
                Assert.AreEqual("testUserId", ((Dictionary<string, object>)(tags[0]))["Value"]);

                Assert.AreEqual("ai.operation.id", ((Dictionary<string, object>)(tags[1]))["Key"]);
                Assert.AreEqual(item.Context.Operation.Id, ((Dictionary<string, object>)(tags[1]))["Value"]);

                Assert.IsNotNull(actualEvent.Payload[2]);
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ProfilerSqlProcessing"/> class.
        /// </summary>
        internal ProfilerSqlProcessing(TelemetryConfiguration configuration, string agentVersion, ObjectInstanceBasedOperationHolder telemetryTupleHolder)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            if (telemetryTupleHolder == null)
            {
                throw new ArgumentNullException("telemetryHolder");
            }

            this.TelemetryTable = telemetryTupleHolder;
            this.telemetryClient = new TelemetryClient(configuration);

            // Since dependencySource is no longer set, sdk version is prepended with information which can identify whether RDD was collected by profiler/framework

            // For directly using TrackDependency(), version will be simply what is set by core
            string prefix = "rdd" + RddSource.Profiler + ":";
            this.telemetryClient.Context.GetInternalContext().SdkVersion = SdkVersionUtils.GetSdkVersion(prefix);
            if (!string.IsNullOrEmpty(agentVersion))
            {
                this.telemetryClient.Context.GetInternalContext().AgentVersion = agentVersion;
            }
        }
 /// <summary>
 /// The function that needs to be called before sending a request to the server. Creates and initializes dependency telemetry item.
 /// </summary>
 /// <param name="telemetryClient">Telemetry client object to initialize the context of the telemetry item.</param>
 internal static DependencyTelemetry BeginTracking(TelemetryClient telemetryClient)
 {
     var telemetry = new DependencyTelemetry();
     telemetry.Start();
     telemetryClient.Initialize(telemetry);
     PretendProfilerIsAttached = false;
     return telemetry;
 }
        /// <summary>
        /// Initializes the Appender and perform instrumentationKey validation.
        /// </summary>
        public override void ActivateOptions()
        {
            base.ActivateOptions();
            this.telemetryClient = new TelemetryClient();
            if (!string.IsNullOrEmpty(this.InstrumentationKey))
            {
                this.telemetryClient.Context.InstrumentationKey = this.InstrumentationKey;
            }

            this.telemetryClient.Context.GetInternalContext().SdkVersion = SdkVersionUtils.GetSdkVersion("log4net:");
        }
        /// <summary>
        /// Initializes the Target and perform instrumentationKey validation.
        /// </summary>
        /// <exception cref="NLogConfigurationException">Will throw when <see cref="InstrumentationKey"/> is not set.</exception>
        protected override void InitializeTarget()
        {
            base.InitializeTarget();
            this.telemetryClient = new TelemetryClient();
            if (!string.IsNullOrEmpty(this.InstrumentationKey))
            {
                this.telemetryClient.Context.InstrumentationKey = this.InstrumentationKey;
            }

            this.telemetryClient.Context.GetInternalContext().SdkVersion = "NLog: " + GetAssemblyVersion();
        }
        /// <summary>
        /// Initializes the Appender and perform instrumentationKey validation.
        /// </summary>
        public override void ActivateOptions()
        {
            base.ActivateOptions();
            this.telemetryClient = new TelemetryClient();
            if (!string.IsNullOrEmpty(this.InstrumentationKey))
            {
                this.telemetryClient.Context.InstrumentationKey = this.InstrumentationKey;
            }

            this.telemetryClient.Context.GetInternalContext().SdkVersion = "Log4Net: " + GetAssemblyVersion();
        }
 public void TestInitialize()
 {
     var configuration = new TelemetryConfiguration();
     this.sendItems = new List<ITelemetry>();
     configuration.TelemetryChannel = new StubTelemetryChannel { OnSend = item => this.sendItems.Add(item) };
     configuration.InstrumentationKey = Guid.NewGuid().ToString();
     configuration.TelemetryInitializers.Add(new MockTelemetryInitializer());
     this.telemetryClient = new TelemetryClient(configuration);
     this.webRequest = WebRequest.Create(new Uri("http://bing.com"));
     this.sqlRequest = new SqlCommand("select * from table;");
     ClientServerDependencyTracker.PretendProfilerIsAttached = true;
 }
 public void TestInitialize()
 {
     var configuration = new TelemetryConfiguration();
     this.sendItems = new List<ITelemetry>();
     configuration.TelemetryChannel = new StubTelemetryChannel { OnSend = item => this.sendItems.Add(item) };
     configuration.InstrumentationKey = Guid.NewGuid().ToString();
     configuration.TelemetryInitializers.Add(new MockTelemetryInitializer());
     DependencyTrackingTelemetryModule module = new DependencyTrackingTelemetryModule();
     module.Initialize(configuration);
     this.telemetryClient = new TelemetryClient(configuration);
     var operationHolder = this.telemetryClient.StartOperation<DependencyTelemetry>("operationName");
     this.telemetry = operationHolder.Telemetry;
     this.webRequest = WebRequest.Create(new Uri("http://bing.com"));
     this.sqlRequest = new SqlCommand("select * from table;");
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="HttpProcessingFramework"/> class.
        /// </summary>
        internal HttpProcessingFramework(TelemetryClient client, TelemetryConfiguration configuration, ISamplingPolicy samplingPolicy = null)
            : base(samplingPolicy)
        {
            if (client == null)
            {
                throw new ArgumentNullException("client");
            }

            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            this.telemetryClient = client;
            this.telemetryConfiguration = configuration;
        }
        private TelemetryClient GetTelemetryClient(TelemetryConfiguration sourceConfiguration)
        {
            this.channel.EndpointAddress = sourceConfiguration.TelemetryChannel.EndpointAddress;

            var newConfiguration = new TelemetryConfiguration
            {
                TelemetryChannel = this.channel
            };

            CopyConfiguration(sourceConfiguration, newConfiguration);

            var telemetryClient = new TelemetryClient(newConfiguration);
            telemetryClient.Context.GetInternalContext().SdkVersion = "unhnd: " + SdkVersionUtils.GetAssemblyVersion();

            return telemetryClient;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="PortalDiagnosticsSender"/> class. 
        /// </summary>
        public PortalDiagnosticsSender(
            TelemetryConfiguration configuration,
            IDiagnoisticsEventThrottlingManager throttlingManager)
        {
            if (null == configuration)
            {
                throw new ArgumentNullException("configuration");
            }

            if (null == throttlingManager)
            {
                throw new ArgumentNullException("throttlingManager");
            }

            this.telemetryClient = new TelemetryClient(configuration);

            this.throttlingManager = throttlingManager;
        }
        /// <summary>
        /// Initializes the telemetry module.
        /// </summary>
        /// <param name="configuration">Telemetry Configuration used for creating TelemetryClient for sending exceptions to ApplicationInsights.</param>
        public void Initialize(TelemetryConfiguration configuration)
        {
            // Core SDK creates 1 instance of a module but calls Initialize multiple times
            if (!this.isInitialized)
            {
                lock (this.lockObject)
                {
                    if (!this.isInitialized)
                    {
                        this.isInitialized = true;

                        this.telemetryClient = new TelemetryClient(configuration);
                        this.telemetryClient.Context.GetInternalContext().SdkVersion = "unobs: " + SdkVersionUtils.GetAssemblyVersion();

                        this.registerAction(this.TaskSchedulerOnUnobservedTaskException);
                    }
                }
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="FrameworkSqlProcessing"/> class.
        /// </summary>
        internal FrameworkSqlProcessing(TelemetryConfiguration configuration, CacheBasedOperationHolder telemetryTupleHolder)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            if (telemetryTupleHolder == null)
            {
                throw new ArgumentNullException("telemetryHolder");
            }

            this.TelemetryTable = telemetryTupleHolder;
            this.telemetryClient = new TelemetryClient(configuration);

            // Since dependencySource is no longer set, sdk version is prepended with information which can identify whether RDD was collected by profiler/framework
        
            // For directly using TrackDependency(), version will be simply what is set by core
            this.telemetryClient.Context.GetInternalContext().SdkVersion = string.Format(CultureInfo.InvariantCulture, "rdd{0}: {1}", RddSource.Framework, SdkVersionUtils.GetAssemblyVersion());
        }
        public ApplicationInsightsEventListener(IConfigurationProvider configurationProvider, IHealthReporter healthReporter) : base(configurationProvider, healthReporter)
        {
            if (this.Disabled)
            {
                return;
            }

            Debug.Assert(configurationProvider != null);

            telemetry = new TelemetryClient();
            telemetry.Context.InstrumentationKey = configurationProvider.GetValue(AppInsightsKeyName);

            this.Sender = new ConcurrentEventSender<EventData>(
                eventBufferSize: 1000,
                maxConcurrency: 2,
                batchSize: 100,
                noEventsDelay: TimeSpan.FromMilliseconds(1000),
                transmitterProc: this.SendEventsAsync,
                healthReporter: healthReporter);
        }
        internal FrameworkHttpProcessing(TelemetryConfiguration configuration, CacheBasedOperationHolder telemetryTupleHolder)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            if (telemetryTupleHolder == null)
            {
                throw new ArgumentNullException("telemetryTupleHolder");
            }

            this.applicationInsightsUrlFilter = new ApplicationInsightsUrlFilter(configuration);
            this.TelemetryTable = telemetryTupleHolder;
            this.telemetryClient = new TelemetryClient(configuration);

            // Since dependencySource is no longer set, sdk version is prepended with information which can identify whether RDD was collected by profiler/framework

            // For directly using TrackDependency(), version will be simply what is set by core
            string prefix = "rdd" + RddSource.Framework + ":";
            this.telemetryClient.Context.GetInternalContext().SdkVersion = SdkVersionUtils.GetSdkVersion(prefix);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ProfilerHttpProcessing"/> class.
        /// </summary>
        public ProfilerHttpProcessing(TelemetryConfiguration configuration, string agentVersion, ObjectInstanceBasedOperationHolder telemetryTupleHolder)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            if (telemetryTupleHolder == null)
            {
                throw new ArgumentNullException("telemetryTupleHolder");
            }

            this.applicationInsightsUrlFilter = new ApplicationInsightsUrlFilter(configuration);
            this.TelemetryTable = telemetryTupleHolder;
            this.telemetryClient = new TelemetryClient(configuration);

            // Since dependencySource is no longer set, sdk version is prepended with information which can identify whether RDD was collected by profiler/framework
            // For directly using TrackDependency(), version will be simply what is set by core
            this.telemetryClient.Context.GetInternalContext().SdkVersion = string.Format(CultureInfo.InvariantCulture, "rdd{0}: {1}", RddSource.Profiler, SdkVersionUtils.GetAssemblyVersion());
            if (!string.IsNullOrEmpty(agentVersion))
            {
                this.telemetryClient.Context.GetInternalContext().AgentVersion = agentVersion;
            }
        }
 private static TelemetryConfiguration GetConfigurationFromClient(TelemetryClient telemetryClient)
 {
     // This is a hack. It will go away when this code will become a part of Application Insights Core
     return (TelemetryConfiguration)typeof(TelemetryClient).GetField("configuration", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(telemetryClient);
 }
        /// <summary>
        /// Initialize method is called after all configuration properties have been loaded from the configuration.
        /// </summary>
        public void Initialize(TelemetryConfiguration configuration)
        {
            if (!this.IsInitialized)
            {
                lock (this.lockObject)
                {
                    if (!this.IsInitialized)
                    {
                        PerformanceCollectorEventSource.Log.ModuleIsBeingInitializedEvent(
                            string.Format(
                                CultureInfo.InvariantCulture,
                                "Custom counters count: '{0}'",
                                Counters?.Count ?? 0));

                        if (configuration == null)
                        {
                            throw new ArgumentNullException(nameof(configuration));
                        }

                        if (!this.defaultCountersInitialized)
                        {
                            // The following are the counters support in all cases.
                            this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\Process(??APP_WIN32_PROC??)\% Processor Time", @"\Process(??APP_WIN32_PROC??)\% Processor Time"));
                            this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\Process(??APP_WIN32_PROC??)\% Processor Time Normalized", @"\Process(??APP_WIN32_PROC??)\% Processor Time Normalized"));
                            this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\Process(??APP_WIN32_PROC??)\Private Bytes", @"\Process(??APP_WIN32_PROC??)\Private Bytes"));

#if NET452         // The following are Asp.Net specific counters.
                            this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\ASP.NET Applications(??APP_W3SVC_PROC??)\Requests/Sec", @"\ASP.NET Applications(??APP_W3SVC_PROC??)\Requests/Sec"));
                            this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\.NET CLR Exceptions(??APP_CLR_PROC??)\# of Exceps Thrown / sec", @"\.NET CLR Exceptions(??APP_CLR_PROC??)\# of Exceps Thrown / sec"));
                            this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\ASP.NET Applications(??APP_W3SVC_PROC??)\Request Execution Time", @"\ASP.NET Applications(??APP_W3SVC_PROC??)\Request Execution Time"));
                            this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\ASP.NET Applications(??APP_W3SVC_PROC??)\Requests In Application Queue", @"\ASP.NET Applications(??APP_W3SVC_PROC??)\Requests In Application Queue"));
#endif

                            if (this.collector.GetType().Name.Equals("WebAppPerformanceCollector", StringComparison.OrdinalIgnoreCase) || this.collector.GetType().Name.Equals("StandardPerformanceCollector", StringComparison.OrdinalIgnoreCase))
                            {
                                // The systemwide Memory counter is enabled in WebApps.
                                this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\Memory\Available Bytes", @"\Memory\Available Bytes"));
                                this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\Process(??APP_WIN32_PROC??)\IO Data Bytes/sec", @"\Process(??APP_WIN32_PROC??)\IO Data Bytes/sec"));
                            }

                            if (this.collector.GetType().Name.Equals("StandardPerformanceCollector", StringComparison.OrdinalIgnoreCase))
                            {
                                // Only time total CPU counter is available is if we are using StandardPerformanceCollector.
                                this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\Processor(_Total)\% Processor Time", @"\Processor(_Total)\% Processor Time"));
                            }
                        }

                        if (!this.EnableIISExpressPerformanceCounters && IsRunningUnderIisExpress())
                        {
                            PerformanceCollectorEventSource.Log.RunningUnderIisExpress();
                            return;
                        }

                        this.telemetryConfiguration = configuration;
                        this.client = new TelemetryClient(configuration);
                        this.client.Context.GetInternalContext().SdkVersion = SdkVersionUtils.GetSdkVersion(PerformanceCounterUtility.SDKVersionPrefix());

                        this.lastRefreshTimestamp = DateTime.MinValue;

                        this.timer = new Timer(this.TimerCallback);

                        // schedule the first tick
                        this.timer.ScheduleNextTick(this.collectionPeriod);
                        this.IsInitialized = true;
                    }
                }
            }
        }
Пример #20
0
 public FacetsController(AppInsightsConfig appInsightsConfig, SearchConfig searchConfig, TelemetryClient telemetryClient, BlobStorageConfig storageConfig)
 {
     _appInsightsConfig = appInsightsConfig;
     _searchConfig      = searchConfig;
     _telemetryClient   = telemetryClient;
     _telemetryClient.InstrumentationKey = _appInsightsConfig.InstrumentationKey;
     _storageConfig = storageConfig;
     _searchClient  = new SearchClient(_searchConfig, _telemetryClient);
 }
        public void GetMetric_SendsData()
        {
            IList <ITelemetry>     sentTelemetry;
            TelemetryConfiguration telemetryPipeline = Util.CreateAITelemetryConfig(out sentTelemetry);
            TelemetryClient        client            = new TelemetryClient(telemetryPipeline);

            {
                Metric metric = client.GetMetric("CowsSold");
                Assert.IsNotNull(metric);
                Assert.AreEqual(0, metric.DimensionsCount);
                Assert.AreEqual("CowsSold", metric.MetricId);
                Assert.AreEqual(MetricConfigurations.Common.Measurement(), metric.GetConfiguration());

                metric.TrackValue(0.5);
                metric.TrackValue(0.6);
                Assert.ThrowsException <InvalidOperationException>(() => metric.TryTrackValue(1.5, "A"));
                Assert.ThrowsException <InvalidOperationException>(() => metric.TryTrackValue(2.5, "A", "X"));

                telemetryPipeline.GetMetricManager().Flush();
                Assert.AreEqual(1, sentTelemetry.Count);
                Util.ValidateNumericAggregateValues(sentTelemetry[0], "CowsSold", 2, 1.1, 0.6, 0.5, 0.05);
                Assert.AreEqual(1, sentTelemetry[0].Context.Properties.Count);
                Assert.IsTrue(sentTelemetry[0].Context.Properties.ContainsKey(Util.AggregationIntervalMonikerPropertyKey));
                sentTelemetry.Clear();

                metric.TrackValue(0.7);
                metric.TrackValue(0.8);

                telemetryPipeline.GetMetricManager().Flush();
                Assert.AreEqual(1, sentTelemetry.Count);
                Util.ValidateNumericAggregateValues(sentTelemetry[0], "CowsSold", 2, 1.5, 0.8, 0.7, 0.05);
                Assert.AreEqual(1, sentTelemetry[0].Context.Properties.Count);
                Assert.IsTrue(sentTelemetry[0].Context.Properties.ContainsKey(Util.AggregationIntervalMonikerPropertyKey));
                sentTelemetry.Clear();
            }
            {
                Metric metric = client.GetMetric("CowsSold", "Color", MetricConfigurations.Common.Accumulator());
                Assert.IsNotNull(metric);
                Assert.AreEqual(1, metric.DimensionsCount);
                Assert.AreEqual("CowsSold", metric.MetricId);
                Assert.AreEqual(MetricConfigurations.Common.Accumulator(), metric.GetConfiguration());

                metric.TryTrackValue(0.5, "Purple");
                metric.TryTrackValue(0.6, "Purple");
                Assert.ThrowsException <InvalidOperationException>(() => metric.TryTrackValue(2.5, "A", "X"));

                telemetryPipeline.GetMetricManager().Flush();
                Assert.AreEqual(1, sentTelemetry.Count);
                Util.ValidateNumericAggregateValues(sentTelemetry[0], "CowsSold", 1, 1.1, 1.1, 0.5, null);
                Assert.AreEqual(2, sentTelemetry[0].Context.Properties.Count);
                Assert.IsTrue(sentTelemetry[0].Context.Properties.ContainsKey(Util.AggregationIntervalMonikerPropertyKey));
                Assert.AreEqual("Purple", sentTelemetry[0].Context.Properties["Color"]);
                sentTelemetry.Clear();

                metric.TryTrackValue(0.7, "Purple");
                metric.TryTrackValue(0.8, "Purple");

                telemetryPipeline.GetMetricManager().Flush();
                Assert.AreEqual(1, sentTelemetry.Count);
                Util.ValidateNumericAggregateValues(sentTelemetry[0], "CowsSold", 1, 2.6, 2.6, 0.5, null);
                Assert.AreEqual(2, sentTelemetry[0].Context.Properties.Count);
                Assert.IsTrue(sentTelemetry[0].Context.Properties.ContainsKey(Util.AggregationIntervalMonikerPropertyKey));
                Assert.AreEqual("Purple", sentTelemetry[0].Context.Properties["Color"]);
                sentTelemetry.Clear();
            }
            {
                Metric metric = client.GetMetric("CowsSold", "Color", "Size", MetricConfigurations.Common.Accumulator());
                Assert.IsNotNull(metric);
                Assert.AreEqual(2, metric.DimensionsCount);
                Assert.AreEqual("CowsSold", metric.MetricId);
                Assert.AreEqual(MetricConfigurations.Common.Accumulator(), metric.GetConfiguration());

                metric.TryTrackValue(0.5, "Purple", "Large");
                metric.TryTrackValue(0.6, "Purple", "Large");

                telemetryPipeline.GetMetricManager().Flush();
                Assert.AreEqual(2, sentTelemetry.Count);

                MetricTelemetry[] orderedTelemetry = sentTelemetry
                                                     .OrderByDescending((t) => ((MetricTelemetry)t).Count * 10000 + ((MetricTelemetry)t).Sum)
                                                     .Select((t) => (MetricTelemetry)t)
                                                     .ToArray();

                // This one is from the prev section:
                Util.ValidateNumericAggregateValues(orderedTelemetry[0], "CowsSold", 1, 2.6, 2.6, 0.5, null);
                Assert.AreEqual(2, orderedTelemetry[0].Context.Properties.Count);
                Assert.IsTrue(orderedTelemetry[0].Context.Properties.ContainsKey(Util.AggregationIntervalMonikerPropertyKey));
                Assert.AreEqual("Purple", orderedTelemetry[0].Context.Properties["Color"]);

                Util.ValidateNumericAggregateValues(orderedTelemetry[1], "CowsSold", 1, 1.1, 1.1, 0.5, null);
                Assert.AreEqual(3, orderedTelemetry[1].Context.Properties.Count);
                Assert.IsTrue(orderedTelemetry[1].Context.Properties.ContainsKey(Util.AggregationIntervalMonikerPropertyKey));
                Assert.AreEqual("Purple", orderedTelemetry[1].Context.Properties["Color"]);
                Assert.AreEqual("Large", orderedTelemetry[1].Context.Properties["Size"]);
                sentTelemetry.Clear();

                metric.TryTrackValue(0.7, "Purple", "Large");
                metric.TryTrackValue(0.8, "Purple", "Small");

                telemetryPipeline.GetMetricManager().Flush();
                Assert.AreEqual(3, sentTelemetry.Count);

                orderedTelemetry = sentTelemetry
                                   .OrderByDescending((t) => ((MetricTelemetry)t).Count * 10000 + ((MetricTelemetry)t).Sum)
                                   .Select((t) => (MetricTelemetry)t)
                                   .ToArray();

                // This one is from the prev section:
                Util.ValidateNumericAggregateValues(orderedTelemetry[0], "CowsSold", 1, 2.6, 2.6, 0.5, null);
                Assert.AreEqual(2, orderedTelemetry[0].Context.Properties.Count);
                Assert.IsTrue(orderedTelemetry[0].Context.Properties.ContainsKey(Util.AggregationIntervalMonikerPropertyKey));
                Assert.AreEqual("Purple", orderedTelemetry[0].Context.Properties["Color"]);

                Util.ValidateNumericAggregateValues(orderedTelemetry[1], "CowsSold", 1, 1.8, 1.8, 0.5, null);
                Assert.AreEqual(3, orderedTelemetry[1].Context.Properties.Count);
                Assert.IsTrue(orderedTelemetry[1].Context.Properties.ContainsKey(Util.AggregationIntervalMonikerPropertyKey));
                Assert.AreEqual("Purple", orderedTelemetry[1].Context.Properties["Color"]);
                Assert.AreEqual("Large", orderedTelemetry[1].Context.Properties["Size"]);

                Util.ValidateNumericAggregateValues(orderedTelemetry[2], "CowsSold", 1, 0.8, 0.8, 0.8, null);
                Assert.AreEqual(3, orderedTelemetry[2].Context.Properties.Count);
                Assert.IsTrue(orderedTelemetry[2].Context.Properties.ContainsKey(Util.AggregationIntervalMonikerPropertyKey));
                Assert.AreEqual("Purple", orderedTelemetry[2].Context.Properties["Color"]);
                Assert.AreEqual("Small", orderedTelemetry[2].Context.Properties["Size"]);

                sentTelemetry.Clear();
            }

            Util.CompleteDefaultAggregationCycle(telemetryPipeline.GetMetricManager());
            telemetryPipeline.Dispose();
        }
 public ExceptionTrackingMiddleware(RequestDelegate next, TelemetryClient client)
 {
     this.next = next;
     this.telemetryClient = client;
     this.sdkVersion = SdkVersionUtils.VersionPrefix + SdkVersionUtils.GetAssemblyVersion();
 }
        public void GetMetric_RespectsAggregationScope()
        {
            IList <ITelemetry>     sentTelemetry1, sentTelemetry2;
            TelemetryConfiguration telemetryPipeline1 = Util.CreateAITelemetryConfig(out sentTelemetry1);
            TelemetryConfiguration telemetryPipeline2 = Util.CreateAITelemetryConfig(out sentTelemetry2);
            TelemetryClient        client11           = new TelemetryClient(telemetryPipeline1);
            TelemetryClient        client12           = new TelemetryClient(telemetryPipeline1);
            TelemetryClient        client21           = new TelemetryClient(telemetryPipeline2);

            Metric metricA111 = client11.GetMetric("Metric A", "Dim1", MetricConfigurations.Common.Measurement(), MetricAggregationScope.TelemetryConfiguration);

            metricA111.TrackValue(101);
            metricA111.TrackValue(102);
            metricA111.TryTrackValue(111, "Val");
            metricA111.TryTrackValue(112, "Val");

            Metric metricA112 = client11.GetMetric("Metric A", "Dim1", MetricConfigurations.Common.Measurement());

            metricA112.TrackValue(103);
            metricA112.TrackValue(104);
            metricA112.TryTrackValue(113, "Val");
            metricA112.TryTrackValue(114, "Val");

            Metric metricA113 = client11.GetMetric("Metric A", "Dim1");

            metricA113.TrackValue(105);
            metricA113.TrackValue(106);
            metricA113.TryTrackValue(115, "Val");
            metricA113.TryTrackValue(116, "Val");

            Assert.AreSame(metricA111, metricA112);
            Assert.AreSame(metricA111, metricA113);
            Assert.AreSame(metricA112, metricA113);

            MetricSeries series1, series2;

            Assert.IsTrue(metricA111.TryGetDataSeries(out series1));
            Assert.IsTrue(metricA112.TryGetDataSeries(out series2));
            Assert.AreSame(series1, series2);
            Assert.IsTrue(metricA113.TryGetDataSeries(out series2));
            Assert.AreSame(series1, series2);
            Assert.IsTrue(metricA112.TryGetDataSeries(out series1));
            Assert.AreSame(series1, series2);

            Assert.IsTrue(metricA111.TryGetDataSeries(out series1, "Val"));
            Assert.IsTrue(metricA112.TryGetDataSeries(out series2, "Val"));
            Assert.AreSame(series1, series2);
            Assert.IsTrue(metricA113.TryGetDataSeries(out series2, "Val"));
            Assert.AreSame(series1, series2);
            Assert.IsTrue(metricA112.TryGetDataSeries(out series1, "Val"));
            Assert.AreSame(series1, series2);

            Metric metricA121 = client12.GetMetric("Metric A", "Dim1", MetricConfigurations.Common.Measurement(), MetricAggregationScope.TelemetryConfiguration);

            metricA121.TrackValue(107);
            metricA121.TrackValue(108);
            metricA121.TryTrackValue(117, "Val");
            metricA121.TryTrackValue(118, "Val");

            Assert.AreSame(metricA111, metricA121);

            Metric metricA211 = client21.GetMetric("Metric A", "Dim1", MetricConfigurations.Common.Measurement(), MetricAggregationScope.TelemetryConfiguration);

            metricA211.TrackValue(201);
            metricA211.TrackValue(202);
            metricA211.TryTrackValue(211, "Val");
            metricA211.TryTrackValue(212, "Val");

            Assert.AreNotSame(metricA111, metricA211);

            Metric metricA11c1 = client11.GetMetric("Metric A", "Dim1", MetricConfigurations.Common.Measurement(), MetricAggregationScope.TelemetryClient);

            metricA11c1.TrackValue(301);
            metricA11c1.TrackValue(302);
            metricA11c1.TryTrackValue(311, "Val");
            metricA11c1.TryTrackValue(312, "Val");

            Metric metricA11c2 = client11.GetMetric("Metric A", "Dim1", MetricConfigurations.Common.Measurement(), MetricAggregationScope.TelemetryClient);

            metricA11c2.TrackValue(303);
            metricA11c2.TrackValue(304);
            metricA11c2.TryTrackValue(313, "Val");
            metricA11c2.TryTrackValue(314, "Val");

            Assert.AreNotSame(metricA111, metricA11c1);
            Assert.AreSame(metricA11c1, metricA11c2);

            Assert.IsTrue(metricA11c1.TryGetDataSeries(out series1));
            Assert.IsTrue(metricA11c1.TryGetDataSeries(out series2));
            Assert.AreSame(series1, series2);

            Assert.IsTrue(metricA11c1.TryGetDataSeries(out series1, "Val"));
            Assert.IsTrue(metricA11c1.TryGetDataSeries(out series2, "Val"));
            Assert.AreSame(series1, series2);

            Metric metricA12c1 = client12.GetMetric("Metric A", "Dim1", MetricConfigurations.Common.Measurement(), MetricAggregationScope.TelemetryClient);

            metricA12c1.TrackValue(305);
            metricA12c1.TrackValue(306);
            metricA12c1.TryTrackValue(315, "Val");
            metricA12c1.TryTrackValue(316, "Val");

            Assert.AreNotSame(metricA11c1, metricA12c1);

            client11.GetMetricManager(MetricAggregationScope.TelemetryClient).Flush();
            client12.GetMetricManager(MetricAggregationScope.TelemetryClient).Flush();
            client21.GetMetricManager(MetricAggregationScope.TelemetryClient).Flush();
            telemetryPipeline1.GetMetricManager().Flush();
            telemetryPipeline2.GetMetricManager().Flush();

            Assert.AreEqual(6, sentTelemetry1.Count);
            Assert.AreEqual(2, sentTelemetry2.Count);

            MetricTelemetry[] orderedTelemetry = sentTelemetry1
                                                 .OrderByDescending((t) => ((MetricTelemetry)t).Count * 10000 + ((MetricTelemetry)t).Sum)
                                                 .Select((t) => (MetricTelemetry)t)
                                                 .ToArray();

            Util.ValidateNumericAggregateValues(orderedTelemetry[0], "Metric A", 8, 916, 118, 111, 2.29128784747792);
            Assert.AreEqual(2, orderedTelemetry[0].Context.Properties.Count);
            Assert.IsTrue(orderedTelemetry[0].Context.Properties.ContainsKey(Util.AggregationIntervalMonikerPropertyKey));
            Assert.AreEqual("Val", orderedTelemetry[0].Context.Properties["Dim1"]);

            Util.ValidateNumericAggregateValues(orderedTelemetry[1], "Metric A", 8, 836, 108, 101, 2.29128784747792);
            Assert.AreEqual(1, orderedTelemetry[1].Context.Properties.Count);
            Assert.IsTrue(orderedTelemetry[1].Context.Properties.ContainsKey(Util.AggregationIntervalMonikerPropertyKey));

            Util.ValidateNumericAggregateValues(orderedTelemetry[2], "Metric A", 4, 1250, 314, 311, 1.11803398874989);
            Assert.AreEqual(2, orderedTelemetry[2].Context.Properties.Count);
            Assert.IsTrue(orderedTelemetry[2].Context.Properties.ContainsKey(Util.AggregationIntervalMonikerPropertyKey));
            Assert.AreEqual("Val", orderedTelemetry[2].Context.Properties["Dim1"]);

            Util.ValidateNumericAggregateValues(orderedTelemetry[3], "Metric A", 4, 1210, 304, 301, 1.11803398874989);
            Assert.AreEqual(1, orderedTelemetry[3].Context.Properties.Count);
            Assert.IsTrue(orderedTelemetry[3].Context.Properties.ContainsKey(Util.AggregationIntervalMonikerPropertyKey));

            Util.ValidateNumericAggregateValues(orderedTelemetry[4], "Metric A", 2, 631, 316, 315, 0.5);
            Assert.AreEqual(2, orderedTelemetry[4].Context.Properties.Count);
            Assert.IsTrue(orderedTelemetry[4].Context.Properties.ContainsKey(Util.AggregationIntervalMonikerPropertyKey));
            Assert.AreEqual("Val", orderedTelemetry[4].Context.Properties["Dim1"]);

            Util.ValidateNumericAggregateValues(orderedTelemetry[5], "Metric A", 2, 611, 306, 305, 0.5);
            Assert.AreEqual(1, orderedTelemetry[5].Context.Properties.Count);
            Assert.IsTrue(orderedTelemetry[5].Context.Properties.ContainsKey(Util.AggregationIntervalMonikerPropertyKey));

            orderedTelemetry = sentTelemetry2
                               .OrderByDescending((t) => ((MetricTelemetry)t).Count * 10000 + ((MetricTelemetry)t).Sum)
                               .Select((t) => (MetricTelemetry)t)
                               .ToArray();

            Util.ValidateNumericAggregateValues(orderedTelemetry[0], "Metric A", 2, 423, 212, 211, 0.5);
            Assert.AreEqual(2, orderedTelemetry[0].Context.Properties.Count);
            Assert.IsTrue(orderedTelemetry[0].Context.Properties.ContainsKey(Util.AggregationIntervalMonikerPropertyKey));
            Assert.AreEqual("Val", orderedTelemetry[0].Context.Properties["Dim1"]);

            Util.ValidateNumericAggregateValues(orderedTelemetry[1], "Metric A", 2, 403, 202, 201, 0.5);
            Assert.AreEqual(1, orderedTelemetry[1].Context.Properties.Count);
            Assert.IsTrue(orderedTelemetry[1].Context.Properties.ContainsKey(Util.AggregationIntervalMonikerPropertyKey));


            Metric metricB21c1 = client21.GetMetric("Metric B", MetricConfigurations.Common.Measurement(), MetricAggregationScope.TelemetryClient);

            TelemetryClient client22 = new TelemetryClient(telemetryPipeline2);
            TelemetryClient client23 = new TelemetryClient(telemetryPipeline2);

            Assert.AreNotSame(metricB21c1, client22.GetMetric("Metric B", MetricConfigurations.Common.Measurement(), MetricAggregationScope.TelemetryClient));
            Assert.AreSame(metricB21c1, client21.GetMetric("Metric B", MetricConfigurations.Common.Measurement(), MetricAggregationScope.TelemetryClient));
            Assert.ThrowsException <ArgumentException>(() => client21.GetMetric("Metric B", MetricConfigurations.Common.Accumulator(), MetricAggregationScope.TelemetryClient));
            Assert.IsNotNull(client23.GetMetric("Metric B", MetricConfigurations.Common.Accumulator(), MetricAggregationScope.TelemetryClient));

            Metric metricB211 = client21.GetMetric("Metric B", MetricConfigurations.Common.Measurement(), MetricAggregationScope.TelemetryConfiguration);

            TelemetryClient client24 = new TelemetryClient(telemetryPipeline2);
            TelemetryClient client25 = new TelemetryClient(telemetryPipeline2);

            Assert.AreSame(metricB211, client24.GetMetric("Metric B", MetricConfigurations.Common.Measurement(), MetricAggregationScope.TelemetryConfiguration));
            Assert.AreSame(metricB211, client21.GetMetric("Metric B", MetricConfigurations.Common.Measurement(), MetricAggregationScope.TelemetryConfiguration));
            Assert.ThrowsException <ArgumentException>(() => client21.GetMetric("Metric B", MetricConfigurations.Common.Accumulator(), MetricAggregationScope.TelemetryConfiguration));
            Assert.ThrowsException <ArgumentException>(() => client25.GetMetric("Metric B", MetricConfigurations.Common.Accumulator(), MetricAggregationScope.TelemetryConfiguration));

            Assert.ThrowsException <ArgumentException>(() => client11.GetMetric("Metric C", MetricConfigurations.Common.Accumulator(), (MetricAggregationScope)42));

            Util.CompleteDefaultAggregationCycle(
                client11.GetMetricManager(MetricAggregationScope.TelemetryClient),
                client12.GetMetricManager(MetricAggregationScope.TelemetryClient),
                client21.GetMetricManager(MetricAggregationScope.TelemetryClient),
                client22.GetMetricManager(MetricAggregationScope.TelemetryClient),
                client23.GetMetricManager(MetricAggregationScope.TelemetryClient),
                client24.GetMetricManager(MetricAggregationScope.TelemetryClient),
                client25.GetMetricManager(MetricAggregationScope.TelemetryClient),
                telemetryPipeline2.GetMetricManager(),
                telemetryPipeline1.GetMetricManager());

            telemetryPipeline1.Dispose();
            telemetryPipeline2.Dispose();
        }
        public void GetMetric_DetectsMetricConfigurationConflicts()
        {
            IList <ITelemetry>     sentTelemetry;
            TelemetryConfiguration telemetryPipeline = Util.CreateAITelemetryConfig(out sentTelemetry);
            TelemetryClient        client            = new TelemetryClient(telemetryPipeline);

            {
                Metric m1 = client.GetMetric("M01");
                Assert.IsNotNull(m1);

                Metric m2 = client.GetMetric("M01");
                Assert.AreSame(m1, m2);

                m2 = client.GetMetric("M01 ");
                Assert.AreSame(m1, m2);

                m2 = client.GetMetric("M01", MetricConfigurations.Common.Measurement());
                Assert.AreSame(m1, m2);

                m2 = client.GetMetric("M01", metricConfiguration: null);
                Assert.AreSame(m1, m2);

                Assert.ThrowsException <ArgumentException>(() => client.GetMetric("M01", MetricConfigurations.Common.Accumulator()));

                IMetricConfiguration config1 = new SimpleMetricConfiguration(10, 10, new MetricSeriesConfigurationForMeasurement(false));
                IMetricConfiguration config2 = new SimpleMetricConfiguration(10, 10, new MetricSeriesConfigurationForMeasurement(false));
                Assert.AreEqual(config1, config2);
                Assert.AreNotSame(config1, config2);

                m1 = client.GetMetric("M02", config1);
                Assert.IsNotNull(m1);

                m2 = client.GetMetric("M02", config2);
                Assert.AreSame(m1, m2);

                m2 = client.GetMetric("M02", metricConfiguration: null);
                Assert.AreSame(m1, m2);

                config2 = new SimpleMetricConfiguration(10, 101, new MetricSeriesConfigurationForMeasurement(false));
                Assert.AreNotEqual(config1, config2);
                Assert.AreNotSame(config1, config2);

                Assert.ThrowsException <ArgumentException>(() => client.GetMetric("M02", config2));
                Assert.ThrowsException <ArgumentException>(() => client.GetMetric("M02 ", config2));
            }
            {
                Metric m1 = client.GetMetric("M11", "Dim1");
                Assert.IsNotNull(m1);

                Metric m2 = client.GetMetric("M11", "Dim1");
                Assert.AreSame(m1, m2);

                m2 = client.GetMetric(" M11", "Dim1");
                Assert.AreSame(m1, m2);

                m2 = client.GetMetric("M11", " Dim1");
                Assert.AreSame(m1, m2);

                m2 = client.GetMetric(" M11", " Dim1", MetricConfigurations.Common.Measurement());
                Assert.AreSame(m1, m2);

                m2 = client.GetMetric("M11", "Dim1", metricConfiguration: null);
                Assert.AreSame(m1, m2);

                Assert.ThrowsException <ArgumentException>(() => client.GetMetric("M11", "Dim1 ", MetricConfigurations.Common.Accumulator()));

                IMetricConfiguration config1 = new SimpleMetricConfiguration(10, 10, new MetricSeriesConfigurationForMeasurement(false));
                IMetricConfiguration config2 = new SimpleMetricConfiguration(10, 10, new MetricSeriesConfigurationForMeasurement(false));
                Assert.AreEqual(config1, config2);
                Assert.AreNotSame(config1, config2);

                m1 = client.GetMetric("M12 ", "Dim1", config1);
                Assert.IsNotNull(m1);

                m2 = client.GetMetric("M12", "Dim1 ", config2);
                Assert.AreSame(m1, m2);

                m2 = client.GetMetric("M12", "Dim1", metricConfiguration: null);
                Assert.AreSame(m1, m2);

                config2 = new SimpleMetricConfiguration(10, 101, new MetricSeriesConfigurationForMeasurement(false));
                Assert.AreNotEqual(config1, config2);
                Assert.AreNotSame(config1, config2);

                Assert.ThrowsException <ArgumentException>(() => client.GetMetric("M12", "Dim1", config2));
                Assert.ThrowsException <ArgumentException>(() => client.GetMetric("M12 ", "Dim1", config2));
            }
            {
                Metric m1 = client.GetMetric("M21", "Dim1", "Dim2");
                Assert.IsNotNull(m1);

                Metric m2 = client.GetMetric("M21", "Dim1", "Dim2");
                Assert.AreSame(m1, m2);

                m2 = client.GetMetric(" M21", "Dim1", "Dim2");
                Assert.AreSame(m1, m2);

                m2 = client.GetMetric("M21", " Dim1", "Dim2");
                Assert.AreSame(m1, m2);

                m2 = client.GetMetric("M21", "Dim1", " Dim2");
                Assert.AreSame(m1, m2);

                m2 = client.GetMetric(" M21", " Dim1", "Dim2", MetricConfigurations.Common.Measurement());
                Assert.AreSame(m1, m2);

                m2 = client.GetMetric("M21", "Dim1", "Dim2 ", metricConfiguration: null);
                Assert.AreSame(m1, m2);

                Assert.ThrowsException <ArgumentException>(() => client.GetMetric("M21", "Dim1 ", "Dim2", MetricConfigurations.Common.Accumulator()));

                IMetricConfiguration config1 = new SimpleMetricConfiguration(10, 10, new MetricSeriesConfigurationForMeasurement(false));
                IMetricConfiguration config2 = new SimpleMetricConfiguration(10, 10, new MetricSeriesConfigurationForMeasurement(false));
                Assert.AreEqual(config1, config2);
                Assert.AreNotSame(config1, config2);

                m1 = client.GetMetric("M22 ", "Dim1", "Dim2 ", config1);
                Assert.IsNotNull(m1);

                m2 = client.GetMetric("M22", "Dim1 ", "Dim2", config2);
                Assert.AreSame(m1, m2);

                m2 = client.GetMetric("M22", "Dim1", "Dim2", metricConfiguration: null);
                Assert.AreSame(m1, m2);

                config2 = new SimpleMetricConfiguration(10, 101, new MetricSeriesConfigurationForMeasurement(false));
                Assert.AreNotEqual(config1, config2);
                Assert.AreNotSame(config1, config2);

                Assert.ThrowsException <ArgumentException>(() => client.GetMetric("M22", "Dim1", "Dim2", config2));
                Assert.ThrowsException <ArgumentException>(() => client.GetMetric("M22 ", "Dim1", "Dim2", config2));
            }
            {
                Metric m0 = client.GetMetric("Xxx");
                Metric m1 = client.GetMetric("Xxx", "Dim1");
                Metric m2 = client.GetMetric("Xxx", "Dim1", "Dim2");

                Assert.IsNotNull(m0);
                Assert.IsNotNull(m1);
                Assert.IsNotNull(m2);

                Assert.AreNotSame(m0, m1);
                Assert.AreNotSame(m0, m2);
                Assert.AreNotSame(m1, m2);

                Assert.AreSame(m0.GetConfiguration(), m1.GetConfiguration());
                Assert.AreSame(m0.GetConfiguration(), m2.GetConfiguration());
                Assert.AreSame(m1.GetConfiguration(), m2.GetConfiguration());

                Assert.AreSame(MetricConfigurations.Common.Measurement(), m0.GetConfiguration());
            }

            Util.CompleteDefaultAggregationCycle(telemetryPipeline.GetMetricManager());
            telemetryPipeline.Dispose();
        }
Пример #25
0
 public HubFeeder(TelemetryClient telemetryClient)
 {
     _telemetryClient = telemetryClient;
 }
 public ApplicationInsightsLogger(TelemetryClient client, string categoryName)
 {
     _telemetryClient = client;
     _categoryName    = categoryName ?? DefaultCategoryName;
     _isUserFunction  = LogCategories.IsFunctionUserCategory(categoryName);
 }
Пример #27
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BaseController"/> class.
 /// </summary>
 /// <param name="telemetryClient">The Application Insights telemetry client.</param>
 public BaseController(TelemetryClient telemetryClient)
 {
     this.telemetryClient = telemetryClient;
 }
Пример #28
0
 public PinServicesController(TelemetryClient telemetry)
 {
     this._telemetry = telemetry;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="ApplicationInsightsTelemetryProvider" /> class.
 /// </summary>
 public ApplicationInsightsTelemetryProvider()
 {
     this.telemetry = new TelemetryClient();
 }
Пример #30
0
 public ApplicationInsightsLogService(ICorrelationIdProvider correlationIdProvider, TelemetryClient telemetryClient)
 {
     this.correlationIdProvider = correlationIdProvider;
     this.telemetryClient       = telemetryClient;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="MessagesController"/> class.
 /// </summary>
 /// <param name="bot">The Icebreaker bot instance</param>
 /// <param name="telemetryClient">The telemetry client instance</param>
 public MessagesController(IcebreakerBot bot, TelemetryClient telemetryClient)
 {
     this.bot             = bot;
     this.telemetryClient = telemetryClient;
 }
Пример #32
0
 public ApplicationInsightsTelemetryClient(TelemetryClient telemetryClient, JavaScriptSnippet snippet)
 {
     _appInsights = telemetryClient;
     _javascript  = snippet;
 }
Пример #33
0
        public async Task ProccessByFileAsync(string fileName, string functionName, TraceWriter log, TelemetryClient _telemetry)
        {
            LoggerHelper.WriteTrace(functionName, $"Recuperando el fichero {fileName} | a las {DateTime.UtcNow.ToString("dd/MM/yyyy HH-mm-ss")}", log, TraceLevel.Info, _telemetry);

            HotelsJson   hotelList = new HotelsJson();
            List <Hotel> hoteles   = new List <Hotel>();

            var serializer = new JsonSerializer();

            hotelList = JsonConvert.DeserializeObject <HotelsJson>(await BlobHelper.GetAsText(fileName, "demo"));
            hoteles   = hotelList.Hotel.ToList();

            LoggerHelper.WriteTrace(functionName, $"Recuperando {hoteles.Count()} hoteles en la oferta | {DateTime.UtcNow.ToString("dd/MM/yyyy HH-mm-ss")}", log, TraceLevel.Info, _telemetry);

            List <Hotel> hotelesLowCost  = new List <Hotel>();
            List <Hotel> hotelesPremiere = new List <Hotel>();
            List <Hotel> hotelesLuxury   = new List <Hotel>();

            hotelesLowCost  = hoteles.Where(o => o.minPrice <= 200).ToList();
            hotelesPremiere = hoteles.Where(o => o.minPrice > 200).ToList();
            hotelesLuxury   = hoteles.Where(o => o.category == "5").ToList();

            AzureServiceBusHelper.CreateQueue(ConfigurationManager.AppSettings["AzureWebJobsServiceBus"], QueueNames.LowCost);

            foreach (var hotel in hotelesLowCost)
            {
                AzureServiceBusHelper.SendMessage(ConfigurationManager.AppSettings["AzureWebJobsServiceBus"], QueueNames.LowCost, JsonConvert.SerializeObject(hotel));
                LoggerHelper.WriteTrace(functionName, $"Detectado hotel {QueueNames.LowCost} | {DateTime.UtcNow.ToString("dd/MM/yyyy HH-mm-ss")}", log, TraceLevel.Info, _telemetry);
            }

            AzureServiceBusHelper.CreateQueue(ConfigurationManager.AppSettings["AzureWebJobsServiceBus"], QueueNames.Premiere);

            foreach (var hotel in hotelesPremiere)
            {
                AzureServiceBusHelper.SendMessage(ConfigurationManager.AppSettings["AzureWebJobsServiceBus"], QueueNames.Premiere, JsonConvert.SerializeObject(hotel));
                LoggerHelper.WriteTrace(functionName, $"Detectado hotel {QueueNames.Premiere} | {DateTime.UtcNow.ToString("dd/MM/yyyy HH-mm-ss")}", log, TraceLevel.Info, _telemetry);
            }

            AzureServiceBusHelper.CreateQueue(ConfigurationManager.AppSettings["AzureWebJobsServiceBus"], QueueNames.Luxury);

            foreach (var hotel in hotelesLuxury)
            {
                AzureServiceBusHelper.SendMessage(ConfigurationManager.AppSettings["AzureWebJobsServiceBus"], QueueNames.Luxury, JsonConvert.SerializeObject(hotel));
                LoggerHelper.WriteTrace(functionName, $"Detectado hotel {QueueNames.Luxury} | {DateTime.UtcNow.ToString("dd/MM/yyyy HH-mm-ss")}", log, TraceLevel.Info, _telemetry);
            }

            LoggerHelper.WriteTrace(functionName, $"Se han procesado los {hoteles.Count()} hoteles | {DateTime.UtcNow.ToString("dd/MM/yyyy HH-mm-ss")}", log, TraceLevel.Info, _telemetry);
        }
Пример #34
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ApplicationContext"/> class.
        /// </summary>
        /// <param name="configuration">A reference to the application configuration.</param>
        /// <param name="cancellationTokenSource">A reference to the master cancellation token source.</param>
        /// <param name="telemetryClient">A reference to the telemetry client.</param>
        /// <param name="openTibiaDbContextGenerationFunc">A reference to a function to generate the OpenTibia database context.</param>
        public ApplicationContext(IConfiguration configuration, CancellationTokenSource cancellationTokenSource, TelemetryClient telemetryClient, Func <IOpenTibiaDbContext> openTibiaDbContextGenerationFunc)
        {
            configuration.ThrowIfNull(nameof(configuration));
            cancellationTokenSource.ThrowIfNull(nameof(cancellationTokenSource));
            telemetryClient.ThrowIfNull(nameof(telemetryClient));
            openTibiaDbContextGenerationFunc.ThrowIfNull(nameof(openTibiaDbContextGenerationFunc));

            this.Configuration           = configuration;
            this.CancellationTokenSource = cancellationTokenSource;
            this.TelemetryClient         = telemetryClient;

            this.contextGenerationFunction = openTibiaDbContextGenerationFunc;
        }
        /// <summary>
        /// Initialize method is called after all configuration properties have been loaded from the configuration.
        /// </summary>
        public void Initialize(TelemetryConfiguration configuration)
        {
            if (!this.isInitialized)
            {
                lock (this.lockObject)
                {
                    if (!this.isInitialized)
                    {
                        PerformanceCollectorEventSource.Log.ModuleIsBeingInitializedEvent(
                            string.Format(
                                CultureInfo.InvariantCulture,
                                "Custom counters count: '{0}'",
                                this.Counters != null ? this.Counters.Count : 0));

                        if (configuration == null)
                        {
                            throw new ArgumentNullException("configuration");
                        }

                        if (!this.defaultCountersInitialized)
                        {
                            this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\Process(??APP_WIN32_PROC??)\% Processor Time", @"\Process(??APP_WIN32_PROC??)\% Processor Time"));
                            this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\Memory\Available Bytes", @"\Memory\Available Bytes"));
                            this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\ASP.NET Applications(??APP_W3SVC_PROC??)\Requests/Sec", @"\ASP.NET Applications(??APP_W3SVC_PROC??)\Requests/Sec"));
                            this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\.NET CLR Exceptions(??APP_CLR_PROC??)\# of Exceps Thrown / sec", @"\.NET CLR Exceptions(??APP_CLR_PROC??)\# of Exceps Thrown / sec"));
                            this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\ASP.NET Applications(??APP_W3SVC_PROC??)\Request Execution Time", @"\ASP.NET Applications(??APP_W3SVC_PROC??)\Request Execution Time"));
                            this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\Process(??APP_WIN32_PROC??)\Private Bytes", @"\Process(??APP_WIN32_PROC??)\Private Bytes"));
                            this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\Process(??APP_WIN32_PROC??)\IO Data Bytes/sec", @"\Process(??APP_WIN32_PROC??)\IO Data Bytes/sec"));
                            this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\ASP.NET Applications(??APP_W3SVC_PROC??)\Requests In Application Queue", @"\ASP.NET Applications(??APP_W3SVC_PROC??)\Requests In Application Queue"));
                            this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\Processor(_Total)\% Processor Time", @"\Processor(_Total)\% Processor Time"));
                        }

                        if (!this.EnableIISExpressPerformanceCounters && IsRunningUnderIisExpress())
                        {
                            PerformanceCollectorEventSource.Log.RunningUnderIisExpress();
                            return;
                        }

                        this.telemetryConfiguration = configuration;
                        this.client = new TelemetryClient(configuration);
                        this.client.Context.GetInternalContext().SdkVersion = SdkVersionUtils.GetSdkVersion(PerformanceCounterUtility.SDKVersionPrefix());

                        this.lastRefreshTimestamp = DateTime.MinValue;

                        this.timer = new Timer(this.TimerCallback);

                        // schedule the first tick
                        this.timer.ScheduleNextTick(this.collectionPeriod);
                        this.isInitialized = true;
                    }
                }
            }
        }
        /// <summary>
        /// Initializes the telemetry module.
        /// </summary>
        /// <param name="configuration">Telemetry Configuration used for creating TelemetryClient for sending exception statistics to Application Insights.</param>
        public void Initialize(TelemetryConfiguration configuration)
        {
            // Core SDK creates 1 instance of a module but calls Initialize multiple times
            if (!this.isInitialized)
            {
                lock (this.lockObject)
                {
                    if (!this.isInitialized)
                    {
                        this.isInitialized = true;

                        this.telemetryClient = new TelemetryClient(configuration);
                        this.telemetryClient.Context.GetInternalContext().SdkVersion = SdkVersionUtils.GetSdkVersion("exstat:");

                        this.metricManager = new MetricManager(this.telemetryClient);

                        this.registerAction(this.CalculateStatistics);
                    }
                }
            }
        }
 /// <summary>
 /// Initializes the telemetry module.
 /// </summary>
 /// <param name="configuration">Telemetry configuration to use for initialization.</param>
 public void Initialize(TelemetryConfiguration configuration)
 {
     this.telemetryClient = new TelemetryClient(configuration);
     this.telemetryClient.Context.GetInternalContext().SdkVersion = "web: " + SdkVersionUtils.GetAssemblyVersion();
 }
        /// <summary>
        /// Initialize method is called after all configuration properties have been loaded from the configuration.
        /// </summary>
        public void Initialize(TelemetryConfiguration configuration)
        {
            if (!this.isInitialized)
            {
                lock (this.lockObject)
                {
                    if (!this.isInitialized)
                    {
                        PerformanceCollectorEventSource.Log.ModuleIsBeingInitializedEvent(
                            string.Format(
                                CultureInfo.InvariantCulture,
                                "Custom counters count: '{0}'",
                                this.Counters != null ? this.Counters.Count : 0));

                        if (configuration == null)
                        {
                            throw new ArgumentNullException("configuration");
                        }

                        this.telemetryConfiguration = configuration;
                        this.client = new TelemetryClient(configuration);

                        this.lastRefreshTimestamp = DateTime.MinValue;

                        this.timer = new Timer(this.TimerCallback);

                        // schedule the first tick
                        // we skip the first collection interval to allow process to load otherwise deadlock may occur 
                        this.timer.ScheduleNextTick(this.collectionPeriod);
                        this.isInitialized = true;
                    }
                }
            }
        }
Пример #39
0
 public ConsoleMetricReporter(TelemetryClient telemetryClient)
 {
     this.telemetryClient = telemetryClient;
     telemetryClient.InstrumentationKey = "2fb6d9cb-c098-4ee9-a5b9-df1da328d483";
 }
        public void GetMetric_RespectsMetricConfiguration()
        {
            IList <ITelemetry>     sentTelemetry;
            TelemetryConfiguration telemetryPipeline = Util.CreateAITelemetryConfig(out sentTelemetry);
            TelemetryClient        client            = new TelemetryClient(telemetryPipeline);

            {
                Metric metric = client.GetMetric("M1");
                Assert.IsNotNull(metric);
                Assert.AreEqual(0, metric.DimensionsCount);
                Assert.AreEqual("M1", metric.MetricId);
                Assert.AreEqual(MetricConfigurations.Common.Measurement(), metric.GetConfiguration());
                Assert.AreSame(MetricConfigurations.Common.Measurement(), metric.GetConfiguration());

                MetricSeries series;
                Assert.IsTrue(metric.TryGetDataSeries(out series));
                Assert.AreEqual(MetricConfigurations.Common.Measurement().SeriesConfig, series.GetConfiguration());
                Assert.AreSame(MetricConfigurations.Common.Measurement().SeriesConfig, series.GetConfiguration());
            }
            {
                Metric metric = client.GetMetric("M2", MetricConfigurations.Common.Measurement());
                Assert.IsNotNull(metric);
                Assert.AreEqual(0, metric.DimensionsCount);
                Assert.AreEqual("M2", metric.MetricId);
                Assert.AreEqual(MetricConfigurations.Common.Measurement(), metric.GetConfiguration());
                Assert.AreSame(MetricConfigurations.Common.Measurement(), metric.GetConfiguration());

                MetricSeries series;
                Assert.IsTrue(metric.TryGetDataSeries(out series));
                Assert.AreEqual(MetricConfigurations.Common.Measurement().SeriesConfig, series.GetConfiguration());
                Assert.AreSame(MetricConfigurations.Common.Measurement().SeriesConfig, series.GetConfiguration());
            }
            {
                Metric metric = client.GetMetric("M3", MetricConfigurations.Common.Accumulator());
                Assert.IsNotNull(metric);
                Assert.AreEqual(0, metric.DimensionsCount);
                Assert.AreEqual("M3", metric.MetricId);
                Assert.AreEqual(MetricConfigurations.Common.Accumulator(), metric.GetConfiguration());
                Assert.AreSame(MetricConfigurations.Common.Accumulator(), metric.GetConfiguration());

                MetricSeries series;
                Assert.IsTrue(metric.TryGetDataSeries(out series));
                Assert.AreEqual(MetricConfigurations.Common.Accumulator().SeriesConfig, series.GetConfiguration());
                Assert.AreSame(MetricConfigurations.Common.Accumulator().SeriesConfig, series.GetConfiguration());
            }
            {
                IMetricConfiguration config = new SimpleMetricConfiguration(10, 10, new MetricSeriesConfigurationForMeasurement(true));
                Metric metric = client.GetMetric("M4", config);
                Assert.IsNotNull(metric);
                Assert.AreEqual(0, metric.DimensionsCount);
                Assert.AreEqual("M4", metric.MetricId);
                Assert.AreEqual(config, metric.GetConfiguration());
                Assert.AreSame(config, metric.GetConfiguration());

                MetricSeries series;
                Assert.IsTrue(metric.TryGetDataSeries(out series));
                Assert.AreEqual(new MetricSeriesConfigurationForMeasurement(true), series.GetConfiguration());
                Assert.AreNotSame(new MetricSeriesConfigurationForMeasurement(true), series.GetConfiguration());
            }
            {
                Metric metric = client.GetMetric("M5", "Dim1");
                Assert.IsNotNull(metric);
                Assert.AreEqual(1, metric.DimensionsCount);
                Assert.AreEqual("Dim1", metric.GetDimensionName(1));
                Assert.AreEqual("M5", metric.MetricId);
                Assert.AreEqual(MetricConfigurations.Common.Measurement(), metric.GetConfiguration());
                Assert.AreSame(MetricConfigurations.Common.Measurement(), metric.GetConfiguration());

                MetricSeries series;
                Assert.IsTrue(metric.TryGetDataSeries(out series));
                Assert.AreEqual(MetricConfigurations.Common.Measurement().SeriesConfig, series.GetConfiguration());
                Assert.AreSame(MetricConfigurations.Common.Measurement().SeriesConfig, series.GetConfiguration());
                Assert.IsTrue(metric.TryGetDataSeries(out series, "Dim1Val"));
                Assert.AreEqual(MetricConfigurations.Common.Measurement().SeriesConfig, series.GetConfiguration());
                Assert.AreSame(MetricConfigurations.Common.Measurement().SeriesConfig, series.GetConfiguration());
            }
            {
                Metric metric = client.GetMetric("M6", "Dim1", MetricConfigurations.Common.Measurement());
                Assert.IsNotNull(metric);
                Assert.AreEqual(1, metric.DimensionsCount);
                Assert.AreEqual("Dim1", metric.GetDimensionName(1));
                Assert.AreEqual("M6", metric.MetricId);
                Assert.AreEqual(MetricConfigurations.Common.Measurement(), metric.GetConfiguration());
                Assert.AreSame(MetricConfigurations.Common.Measurement(), metric.GetConfiguration());

                MetricSeries series;
                Assert.IsTrue(metric.TryGetDataSeries(out series));
                Assert.AreEqual(MetricConfigurations.Common.Measurement().SeriesConfig, series.GetConfiguration());
                Assert.AreSame(MetricConfigurations.Common.Measurement().SeriesConfig, series.GetConfiguration());
                Assert.IsTrue(metric.TryGetDataSeries(out series, "Dim1Val"));
                Assert.AreEqual(MetricConfigurations.Common.Measurement().SeriesConfig, series.GetConfiguration());
                Assert.AreSame(MetricConfigurations.Common.Measurement().SeriesConfig, series.GetConfiguration());
            }
            {
                Metric metric = client.GetMetric("M7", "Dim1", MetricConfigurations.Common.Accumulator());
                Assert.IsNotNull(metric);
                Assert.AreEqual(1, metric.DimensionsCount);
                Assert.AreEqual("Dim1", metric.GetDimensionName(1));
                Assert.AreEqual("M7", metric.MetricId);
                Assert.AreEqual(MetricConfigurations.Common.Accumulator(), metric.GetConfiguration());
                Assert.AreSame(MetricConfigurations.Common.Accumulator(), metric.GetConfiguration());

                MetricSeries series;
                Assert.IsTrue(metric.TryGetDataSeries(out series));
                Assert.AreEqual(MetricConfigurations.Common.Accumulator().SeriesConfig, series.GetConfiguration());
                Assert.AreSame(MetricConfigurations.Common.Accumulator().SeriesConfig, series.GetConfiguration());
                Assert.IsTrue(metric.TryGetDataSeries(out series, "Dim1Val"));
                Assert.AreEqual(MetricConfigurations.Common.Accumulator().SeriesConfig, series.GetConfiguration());
                Assert.AreSame(MetricConfigurations.Common.Accumulator().SeriesConfig, series.GetConfiguration());
            }
            {
                IMetricConfiguration config = new SimpleMetricConfiguration(10, 10, new MetricSeriesConfigurationForMeasurement(true));
                Metric metric = client.GetMetric("M8", "Dim1", config);
                Assert.IsNotNull(metric);
                Assert.AreEqual(1, metric.DimensionsCount);
                Assert.AreEqual("Dim1", metric.GetDimensionName(1));
                Assert.AreEqual("M8", metric.MetricId);
                Assert.AreEqual(config, metric.GetConfiguration());
                Assert.AreSame(config, metric.GetConfiguration());

                MetricSeries series;
                Assert.IsTrue(metric.TryGetDataSeries(out series));
                Assert.AreEqual(config.SeriesConfig, series.GetConfiguration());
                Assert.AreSame(config.SeriesConfig, series.GetConfiguration());
                Assert.IsTrue(metric.TryGetDataSeries(out series, "Dim1Val"));
                Assert.AreEqual(new MetricSeriesConfigurationForMeasurement(true), series.GetConfiguration());
                Assert.AreNotSame(new MetricSeriesConfigurationForMeasurement(true), series.GetConfiguration());
            }
            {
                Metric metric = client.GetMetric("M9", "Dim1", "Dim2");
                Assert.IsNotNull(metric);
                Assert.AreEqual(2, metric.DimensionsCount);
                Assert.AreEqual("Dim1", metric.GetDimensionName(1));
                Assert.AreEqual("Dim2", metric.GetDimensionName(2));
                Assert.AreEqual("M9", metric.MetricId);
                Assert.AreEqual(MetricConfigurations.Common.Measurement(), metric.GetConfiguration());
                Assert.AreSame(MetricConfigurations.Common.Measurement(), metric.GetConfiguration());

                MetricSeries series;
                Assert.IsTrue(metric.TryGetDataSeries(out series));
                Assert.AreEqual(MetricConfigurations.Common.Measurement().SeriesConfig, series.GetConfiguration());
                Assert.AreSame(MetricConfigurations.Common.Measurement().SeriesConfig, series.GetConfiguration());
                Assert.IsTrue(metric.TryGetDataSeries(out series, "Dim1Val", "Dim2val"));
                Assert.AreEqual(MetricConfigurations.Common.Measurement().SeriesConfig, series.GetConfiguration());
                Assert.AreSame(MetricConfigurations.Common.Measurement().SeriesConfig, series.GetConfiguration());
            }
            {
                Metric metric = client.GetMetric("M10", "Dim1", "Dim2", MetricConfigurations.Common.Measurement());
                Assert.IsNotNull(metric);
                Assert.AreEqual(2, metric.DimensionsCount);
                Assert.AreEqual("Dim1", metric.GetDimensionName(1));
                Assert.AreEqual("Dim2", metric.GetDimensionName(2));
                Assert.AreEqual("M10", metric.MetricId);
                Assert.AreEqual(MetricConfigurations.Common.Measurement(), metric.GetConfiguration());
                Assert.AreSame(MetricConfigurations.Common.Measurement(), metric.GetConfiguration());

                MetricSeries series;
                Assert.IsTrue(metric.TryGetDataSeries(out series));
                Assert.AreEqual(MetricConfigurations.Common.Measurement().SeriesConfig, series.GetConfiguration());
                Assert.AreSame(MetricConfigurations.Common.Measurement().SeriesConfig, series.GetConfiguration());
                Assert.IsTrue(metric.TryGetDataSeries(out series, "Dim1Val", "Dim2val"));
                Assert.AreEqual(MetricConfigurations.Common.Measurement().SeriesConfig, series.GetConfiguration());
                Assert.AreSame(MetricConfigurations.Common.Measurement().SeriesConfig, series.GetConfiguration());
            }
            {
                Metric metric = client.GetMetric("M11", "Dim1", "Dim2", MetricConfigurations.Common.Accumulator());
                Assert.IsNotNull(metric);
                Assert.AreEqual(2, metric.DimensionsCount);
                Assert.AreEqual("Dim1", metric.GetDimensionName(1));
                Assert.AreEqual("Dim2", metric.GetDimensionName(2));
                Assert.AreEqual("M11", metric.MetricId);
                Assert.AreEqual(MetricConfigurations.Common.Accumulator(), metric.GetConfiguration());
                Assert.AreSame(MetricConfigurations.Common.Accumulator(), metric.GetConfiguration());

                MetricSeries series;
                Assert.IsTrue(metric.TryGetDataSeries(out series));
                Assert.AreEqual(MetricConfigurations.Common.Accumulator().SeriesConfig, series.GetConfiguration());
                Assert.AreSame(MetricConfigurations.Common.Accumulator().SeriesConfig, series.GetConfiguration());
                Assert.IsTrue(metric.TryGetDataSeries(out series, "Dim1Val", "Dim2val"));
                Assert.AreEqual(MetricConfigurations.Common.Accumulator().SeriesConfig, series.GetConfiguration());
                Assert.AreSame(MetricConfigurations.Common.Accumulator().SeriesConfig, series.GetConfiguration());
            }
            {
                IMetricConfiguration config = new SimpleMetricConfiguration(10, 10, new MetricSeriesConfigurationForMeasurement(true));
                Metric metric = client.GetMetric("M12", "Dim1", "Dim2", config);
                Assert.IsNotNull(metric);
                Assert.AreEqual(2, metric.DimensionsCount);
                Assert.AreEqual("Dim1", metric.GetDimensionName(1));
                Assert.AreEqual("Dim2", metric.GetDimensionName(2));
                Assert.AreEqual("M12", metric.MetricId);
                Assert.AreEqual(config, metric.GetConfiguration());
                Assert.AreSame(config, metric.GetConfiguration());

                MetricSeries series;
                Assert.IsTrue(metric.TryGetDataSeries(out series));
                Assert.AreEqual(config.SeriesConfig, series.GetConfiguration());
                Assert.AreSame(config.SeriesConfig, series.GetConfiguration());
                Assert.IsTrue(metric.TryGetDataSeries(out series, "Dim1Val", "Dim2val"));
                Assert.AreEqual(new MetricSeriesConfigurationForMeasurement(true), series.GetConfiguration());
                Assert.AreNotSame(new MetricSeriesConfigurationForMeasurement(true), series.GetConfiguration());
                Assert.AreSame(config.SeriesConfig, series.GetConfiguration());
            }

            Util.CompleteDefaultAggregationCycle(telemetryPipeline.GetMetricManager());
        }
Пример #41
0
 public TelemetryLogger(TelemetryClient telemetryClient)
 {
     this.telemetryClient = telemetryClient;
 }
Пример #42
0
 /// <summary>
 /// Initializes a new instance.
 /// </summary>
 /// <param name="telemetryClient"></param>
 /// <param name="parentOperationId"></param>
 public ApplicationInsightsTrackingParticipant(TelemetryClient telemetryClient, string parentOperationId = null)
 {
     this.telemetryClient   = telemetryClient ?? throw new ArgumentNullException(nameof(telemetryClient));
     this.parentOperationId = parentOperationId;
 }
Пример #43
0
 public Worker(ILogger <Worker> logger, TelemetryClient tc)
 {
     _logger = logger;
     this.tc = tc;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="WorkerRoleBase{TSettings}"/> class.
 /// </summary>
 /// <exception cref="ArgumentException">
 /// The specified name is null.
 /// </exception>
 /// <exception cref="ArgumentException">
 /// The specified name is longer than <see cref="ServiceBase.MaxNameLength"/>.
 /// </exception>
 /// <exception cref="ArgumentException">
 /// The specified name contains forward slash characters.
 /// </exception>
 /// <exception cref="ArgumentException">
 /// The specified name contains backslash characters.
 /// </exception>
 /// <exception cref="ArgumentNullException">
 /// <paramref name="settings"/> is null.
 /// </exception>
 /// <exception cref="ArgumentNullException">
 /// <paramref name="telemetryClient"/> is null.
 /// </exception>
 protected WorkerRoleBase(string serviceName, TSettings settings, TelemetryClient telemetryClient, bool runOnce)
     : this(serviceName, settings, telemetryClient, runOnce, log : null)
 {
 }
Пример #45
0
 public HomeController(ILogger <HomeController> logger, TelemetryClient telemetry)
 {
     _logger    = logger;
     _telemetry = telemetry;
 }
        /// <summary>
        /// Helper method to setup shared context and call the desired tracking for testing.
        /// </summary>
        /// <param name="keywords">The event keywords to enable.</param>
        /// <param name="item">The telemetry item to track.</param>
        /// <param name="track">The tracking callback to execute.</param>
        private void DoTracking(EventKeywords keywords, ITelemetry item, Action<TelemetryClient, ITelemetry> track)
        {
            var client = new TelemetryClient();
            client.InstrumentationKey = Guid.NewGuid().ToString();

            using (var listener = new Microsoft.ApplicationInsights.TestFramework.TestEventListener())
            {
                listener.EnableEvents(RichPayloadEventSource.Log.EventSourceInternal, EventLevel.Verbose, keywords);

                item.Context.Properties.Add("property1", "value1");
                item.Context.User.Id = "testUserId";
                item.Context.Operation.Id = Guid.NewGuid().ToString();

                track(client, item);

                var actualEvent = listener.Messages.FirstOrDefault();

                Assert.IsNotNull(actualEvent);
                Assert.AreEqual(client.InstrumentationKey, actualEvent.Payload[0]);

                int keysFound = 0;
                object[] tags = actualEvent.Payload[1] as object[];
                foreach (object tagObject in tags)
                {
                    Dictionary<string, object> tag = (Dictionary<string, object>)tagObject;
                    Assert.IsNotNull(tag);
                    string key = (string)tag["Key"];
                    object value = tag["Value"];
                    if (!string.IsNullOrWhiteSpace(key))
                    {
                        if (key == "ai.user.id")
                        {
                            Assert.AreEqual("testUserId", value);
                            ++keysFound;
                        }
                        else if (key == "ai.operation.id")
                        {
                            Assert.AreEqual(item.Context.Operation.Id, value);
                            ++keysFound;
                        }
                    }
                }

                Assert.AreEqual(2, keysFound);
                Assert.IsNotNull(actualEvent.Payload[2]);
            }
        }
        public void RddTestHttpProcessingProfilerOnBeginAddsRootIdHeader()
        {
            var request = WebRequest.Create(this.testUrl);

            Assert.IsNull(request.Headers[RequestResponseHeaders.StandardRootIdHeader]);

            var client = new TelemetryClient(this.configuration);
            using (var op = client.StartOperation<RequestTelemetry>("request"))
            {
                this.httpProcessingProfiler.OnBeginForGetResponse(request);
                Assert.IsNotNull(request.Headers[RequestResponseHeaders.StandardRootIdHeader]);
                Assert.AreEqual(request.Headers[RequestResponseHeaders.StandardRootIdHeader], op.Telemetry.Context.Operation.Id);
            }
        }
 public TelemetryClientProxy(IApplicationInsightsConfig config, IBuildConfig buildConfig)
 {
     _client = new TelemetryClient(new TelemetryConfiguration(config.InstrumentationKey));
     _client.Context.Cloud.RoleName = config.RoleName;
     _isDebug = (BuildConfig)buildConfig == BuildConfig.Debug;
 }
 public FeedbackNoRequestHandler(TelemetryClient telemetryClient, IcebreakerBot bot, BotRepository repository)
 {
     _telemetryClient = telemetryClient;
     _bot = bot;
     _repository = repository;
 }
Пример #50
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ExceptionFilter" /> class.
 /// </summary>
 /// <param name="logger">An instance of ILogger</param>
 /// <param name="filterOptions">An instance of the ExceptionFilterOptions class</param>
 /// <param name="applicationInsightsOptions">An instance of Application Insights option</param>
 public ExceptionFilter(ILogger <ExceptionFilter> logger)
 {
     this.loggerException = logger;
     this.telemetryClient = new TelemetryClient();
 }
 /// <summary>
 /// Function that needs to be invoked after the request call to the sever. Computes the duration of the request and tracks the dependency telemetry
 /// item.
 /// </summary>
 /// <param name="telemetryClient">Telemetry client object to track the telemetry item.</param>
 /// <param name="telemetry">Telemetry item to compute the duration and track.</param>
 internal static void EndTracking(TelemetryClient telemetryClient, DependencyTelemetry telemetry)
 {
     telemetry.Stop();
     telemetryClient.Track(telemetry);
 }
Пример #52
0
 protected DiagnosticsEventHandlerBase(TelemetryConfiguration configuration)
 {
     this.TelemetryClient = new TelemetryClient(configuration);
 }
Пример #53
0
        private async Task <ImportStats> ProcessIdentifiers(Artist artist, HttpResponseMessage res, ArtistUpstreamSource src, string showIdentifier, PerformContext ctx)
        {
            var stats = new ImportStats();

            var json = await res.Content.ReadAsStringAsync();

            var root = JsonConvert.DeserializeObject <Relisten.Vendor.ArchiveOrg.SearchRootObject>(
                json.Replace("\"0000-01-01T00:00:00Z\"", "null") /* serious...wtf archive */,
                new Relisten.Vendor.ArchiveOrg.TolerantArchiveDateTimeConverter()
                );

            ctx?.WriteLine($"Checking {root.response.docs.Count} archive.org results");

            var prog = ctx?.WriteProgressBar();

            var identifiersWithoutMP3s = new HashSet <string>();

            await root.response.docs.AsyncForEachWithProgress(prog, async doc =>
            {
                try
                {
                    var currentIsTargetedShow = doc.identifier == showIdentifier;

                    if (showIdentifier != null && !currentIsTargetedShow)
                    {
                        return;
                    }

                    var dbShow = existingSources.GetValue(doc.identifier);

                    var maxSourceInformation = existingSourceReviewInformation.GetValue(doc.identifier);
                    var isNew = dbShow == null;
                    var needsToUpdateReviews = maxSourceInformation != null && doc._iguana_index_date > maxSourceInformation.review_max_updated_at;

                    if (currentIsTargetedShow || isNew || needsToUpdateReviews)
                    {
                        ctx?.WriteLine("Pulling https://archive.org/metadata/{0}", doc.identifier);

                        var detailRes   = await http.GetAsync(DetailsUrlForIdentifier(doc.identifier));
                        var detailsJson = await detailRes.Content.ReadAsStringAsync();
                        var detailsRoot = JsonConvert.DeserializeObject <Relisten.Vendor.ArchiveOrg.Metadata.RootObject>(
                            detailsJson,
                            new Vendor.ArchiveOrg.TolerantStringConverter()
                            );

                        if (detailsRoot.is_dark ?? false)
                        {
                            ctx?.WriteLine("\tis_dark == true, skipping...");
                            return;
                        }

                        var properDate = FixDisplayDate(detailsRoot.metadata);

                        if (properDate != null)
                        {
                            using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                            {
                                try {
                                    stats += await ImportSingleIdentifier(artist, dbShow, doc, detailsRoot, src, properDate, ctx);
                                }
                                catch (NoVBRMp3FilesException) {
                                    identifiersWithoutMP3s.Add(doc.identifier);
                                }

                                scope.Complete();
                            }
                        }
                        else
                        {
                            ctx?.WriteLine("\tSkipped {0} because it has an invalid, unrecoverable date: {1}", doc.identifier, detailsRoot.metadata.date);
                        }
                    }
                }
                catch (Exception e)
                {
                    ctx?.WriteLine($"Error processing {doc.identifier}:");
                    ctx?.LogException(e);

                    var telementry = new TelemetryClient();

                    telementry.TrackException(e, new Dictionary <string, string> {
                        { "upstream_identifier", doc.identifier }
                    });
                }
            });

            // we want to keep all the shows from this import--aside from ones that no longer have MP3s
            var showsToKeep = root.response.docs
                              .Select(d => d.identifier)
                              .Except(identifiersWithoutMP3s)
            ;

            // find sources that no longer exist
            var deletedSourceUpstreamIdentifiers = existingSources
                                                   .Select(kvp => kvp.Key)
                                                   .Except(showsToKeep)
                                                   .ToList()
            ;

            ctx?.WriteLine($"Removing {deletedSourceUpstreamIdentifiers.Count} sources " +
                           $"that are in the database but no longer on Archive.org: {string.Join(',', deletedSourceUpstreamIdentifiers)}");
            stats.Removed += await _sourceService.RemoveSourcesWithUpstreamIdentifiers(deletedSourceUpstreamIdentifiers);

            ctx?.WriteLine("Rebuilding shows...");

            // update shows
            await RebuildShows(artist);

            ctx?.WriteLine("--> rebuilt shows!");
            ctx?.WriteLine("Rebuilding years...");

            // update years
            await RebuildYears(artist);

            ctx?.WriteLine("--> rebuilt years!");

            return(stats);
        }
        /// <summary>
        /// Initialize method is called after all configuration properties have been loaded from the configuration.
        /// </summary>
        public void Initialize(TelemetryConfiguration configuration)
        {
            if (!this.isInitialized)
            {
                lock (this.lockObject)
                {
                    if (!this.isInitialized)
                    {
                        PerformanceCollectorEventSource.Log.ModuleIsBeingInitializedEvent(
                            string.Format(
                                CultureInfo.InvariantCulture,
                                "Custom counters count: '{0}'",
                                this.Counters != null ? this.Counters.Count : 0));

                        if (configuration == null)
                        {
                            throw new ArgumentNullException("configuration");
                        }

                        if (!this.EnableIISExpressPerformanceCounters && IsRunningUnderIisExpress())
                        {
                            PerformanceCollectorEventSource.Log.RunningUnderIisExpress();
                            return;
                        }

                        this.telemetryConfiguration = configuration;
                        this.client = new TelemetryClient(configuration);

                        this.lastRefreshTimestamp = DateTime.MinValue;

                        this.timer = new Timer(this.TimerCallback);

                        // schedule the first tick
                        this.timer.ScheduleNextTick(this.collectionPeriod);
                        this.isInitialized = true;
                    }
                }
            }
        }
Пример #55
0
 public AmazonController(ILogger <PsStoreController> logger, TelemetryClient telemetry)
 {
     this._logger   = logger;
     this._urlStore = @"https://www.amazon.it/s?k={0}";
     this.telemetry = telemetry;
 }
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "users")]
            [RequestBodyType(typeof(User), "User")]
            HttpRequest req, ILogger log, ExecutionContext context)
        {
            log.LogInformation($"{context?.FunctionName} processed a HTTP request.");
            // TelemetryClient.Context.Operation.Id = context?.InvocationId.ToString(); // No longer needed?

            string requestBody = new StreamReader(req.Body).ReadToEnd();
            var    user        = JsonConvert.DeserializeObject <User>(requestBody);

            if (user is null)
            {
                return(new BadRequestObjectResult("No user definition specified in body."));
            }

            if (string.IsNullOrWhiteSpace(user.Id))
            {
                user.Id = Guid.NewGuid().ToString();
            }

            if (string.IsNullOrWhiteSpace(user.PartitionKey))
            {
                user.PartitionKey = user.Id;
            }

            if (string.IsNullOrWhiteSpace(user.DocumentType))
            {
                user.DocumentType = "user";
            }

            var missingProperties = new List <string>();


            // Check required user properties are present otherwise return 400.

            if (string.IsNullOrWhiteSpace(user.PrimaryEmailAddress))
            {
                missingProperties.Add("primaryEmailAddress");
            }
            if (string.IsNullOrWhiteSpace(user.FirstName))
            {
                missingProperties.Add("firstName");
            }
            if (string.IsNullOrWhiteSpace(user.LastName))
            {
                missingProperties.Add("lastName");
            }

            if (missingProperties.Count > 0)
            {
                return(new BadRequestObjectResult($"User definition is missing required properties... {((missingProperties.Count > 1) ? string.Join(", ", missingProperties) : missingProperties[0])}."));
            }


            // CHECK USER NOT IN GRAPH

            try
            {
                var filterProperties = new { userName = user.UserName, primaryEmailAddress = user.PrimaryEmailAddress };
                var query            = GremlinHelper.GetVertexQuery(filterProperties, true);
                var response         = new GraphResponse(await GremlinClient.SubmitAsync <dynamic>(query));

                GremlinHelper.ThrowIfResponseInvalid(response);

                if (response.Entities != null && response.Entities.Count() > 0)
                {
                    return(new ConflictObjectResult("User already exists (graph)."));
                }
            }
            catch (ResponseException ex)
            {
                GremlinHelper.HandleGraphResponseException(ex, log, context, TelemetryClient);
            }
            catch (Exception ex)
            {
                GremlinHelper.HandleGeneralException(ex, log, context, TelemetryClient);
            }


            // CREATE USER ON B2C

            if (string.IsNullOrWhiteSpace(user.Password))
            {
                user.Password = Guid.NewGuid().ToString();
                user.CustomProperties.Add("PasswordAutoGenerated", "true");
            }

            var b2cUser = new B2CUser()
            {
                DisplayName = user.Id, // We do not store user profile data on B2C identity - simply use the customer user id for display name.
                UserAttribute_CustomerUserId = user.Id,
                SignInNames = new List <B2CSignInName>()
                {
                    new B2CSignInName()
                    {
                        Type = "emailAddress", Value = user.PrimaryEmailAddress
                    }
                },
                PasswordProfile = new B2CPasswordProfile()
                {
                    Password = user.Password,
                    ForceChangePasswordNextLogin = false
                }
            };

            // Remove password value from user object.
            user.Password = null;

            try
            {
                var b2cCreatedUserResult = await B2CGraphClient.CreateUser(b2cUser, log);

                var b2cCreatedUser = JsonConvert.DeserializeObject <dynamic>(b2cCreatedUserResult);
                user.IdentityId = b2cCreatedUser?.objectId;
                user.UserStatus = UserStatus.Active;
            }
            catch (B2CUserExistsException)
            {
                // User already exists on B2C
                return(new ConflictObjectResult("User already exists (identity)."));
            }
            catch (B2CPasswordComplexityException)
            {
                return(new BadRequestObjectResult("The specified password does not comply with password complexity requirements. Please provide a different password."));
            }
            catch (Exception ex)
            {
                var ignoreTask = Task.Run(() =>
                {
                    log.LogError($"{context?.FunctionName} Create B2C User Error: {ex.Message}");
                    TelemetryClient.TrackException(ex, new Dictionary <string, string>()
                    {
                        { "ExceptionType", "B2CUserCreateError" }, { "UserName", user?.UserName }, { "EmailAddress", user?.PrimaryEmailAddress }
                    }, null);
                });

                return(new OkObjectResult("Failed to create user (identity).")
                {
                    StatusCode = 500
                });
            }


            // CREATE USER IN GRAPH

            try
            {
                var query    = GremlinHelper.CreateVertexQuery(user, log);
                var response = new GraphResponse(await GremlinClient.SubmitAsync <dynamic>(query));

                GremlinHelper.ThrowIfResponseInvalid(response);

                GremlinHelper.GraphTelemetryEvent(TelemetryClient, "GraphVertexCreate", response, "vertex", "user");

                user = response.GetEntityAsType <User>();
            }
            catch (ResponseException ex)
            {
                GremlinHelper.HandleGraphResponseException(ex, log, context, TelemetryClient);
            }
            catch (Exception ex)
            {
                GremlinHelper.HandleGeneralException(ex, log, context, TelemetryClient);
            }

            return(user != null ?
                   new OkObjectResult(user)
            {
                StatusCode = 201
            } :
                   new OkObjectResult("Failed to create user.")
            {
                StatusCode = 500
            });
        }
Пример #57
0
 public VirgoQueueHandler(TelemetryConfiguration configuration)
 {
     _telemetryClient = new TelemetryClient(configuration);
 }