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;");
 }
        private DependencyTrackingTelemetryModule CreateDependencyTrackingModule(
            bool enableDiagnosticSource,
            bool enableW3C,
            bool enableRequestIdInW3CMode,
            bool injectLegacyHeaders)
        {
            Activity.DefaultIdFormat      = enableW3C ? ActivityIdFormat.W3C : ActivityIdFormat.Hierarchical;
            Activity.ForceDefaultIdFormat = true;

            var module = new DependencyTrackingTelemetryModule();

            if (!enableDiagnosticSource)
            {
                module.DisableDiagnosticSourceInstrumentation = true;
            }

            module.EnableLegacyCorrelationHeadersInjection = injectLegacyHeaders;
            module.EnableRequestIdHeaderInjectionInW3CMode = enableRequestIdInW3CMode;

            module.Initialize(this.config);
            Assert.AreEqual(enableDiagnosticSource, DependencyTableStore.IsDesktopHttpDiagnosticSourceActivated);

            return(module);
        }
예제 #3
0
        private static DependencyTrackingTelemetryModule BuildDependencyTrackingTelemetryModule()
        {
            List <string> excludeComponentCorrelationHttpHeadersOnDomains = new List <string>
            {
                "core.windows.net",
                "core.chinacloudapi.cn",
                "core.cloudapi.de",
                "core.usgovcloudapi.net",
                "localhost",
                "127.0.0.1"
            };

            DependencyTrackingTelemetryModule depModule = new DependencyTrackingTelemetryModule();

            foreach (string excludeComponent in excludeComponentCorrelationHttpHeadersOnDomains)
            {
                depModule.ExcludeComponentCorrelationHttpHeadersOnDomains.Add(excludeComponent);
            }

            depModule.IncludeDiagnosticSourceActivities.Add("Microsoft.Azure.ServiceBus");
            depModule.IncludeDiagnosticSourceActivities.Add("Microsoft.Azure.EventHubs");

            return(depModule);
        }
        public async Task TestDependencyCollectionWithW3COnRequestIdOff()
        {
            using (var module = new DependencyTrackingTelemetryModule())
            {
                module.EnableRequestIdHeaderInjectionInW3CMode = false;
                module.Initialize(this.config);

                var parent = new Activity("parent")
                             .Start();

                var url     = new Uri(localhostUrl);
                var request = new HttpRequestMessage(HttpMethod.Get, url);
                using (new LocalServer(localhostUrl))
                {
                    await new HttpClient().SendAsync(request);
                }

                // DiagnosticSource Response event is fired after SendAsync returns on netcoreapp1.*
                // let's wait until dependency is collected
                Assert.IsTrue(SpinWait.SpinUntil(() => this.sentTelemetry != null, TimeSpan.FromSeconds(1)));

                this.ValidateTelemetryForDiagnosticSource(
                    item: this.sentTelemetry.Single(),
                    url: url,
                    request: request,
                    success: true,
                    resultCode: "200",
                    expectLegacyHeaders: false,
                    expectW3CHeaders: true,
                    expectRequestId: false,
                    responseExpected: true,
                    parentActivity: parent);

                parent.Stop();
            }
        }
        private static void SetupTelemetrics()
        {
            if (GlobalConfig.ErrorReporting)
            {
                Configuration = TelemetryConfiguration.CreateDefault();
                Configuration.InstrumentationKey =
                    Encoding.ASCII.GetString(Convert.FromBase64String(GlobalConfig.AppInsightsKey));

                var module = new DependencyTrackingTelemetryModule();

                module.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("core.windows.net");
                module.IncludeDiagnosticSourceActivities.Add("Microsoft.Azure.ServiceBus");
                module.IncludeDiagnosticSourceActivities.Add("Microsoft.Azure.EventHubs");

                Configuration.TelemetryInitializers.Add(
                    new ApplicationInsightsInitializer(Configuration.InstrumentationKey));
                Configuration.TelemetryInitializers.Add(new OperationCorrelationTelemetryInitializer());
                Configuration.TelemetryInitializers.Add(new HttpDependenciesParsingTelemetryInitializer());

                module.Initialize(Configuration);

                AiContext = new TelemetryClient(Configuration);
            }
        }
예제 #6
0
        public static TelemetryClient InitializeTelemetryClient(
            IConfiguration config,
            string cloudRoleName,
            string cloudRoleInstance)
        {
            var telemetryConfig = TelemetryConfiguration.CreateDefault();

            telemetryConfig.InstrumentationKey = config["APPINSIGHTS_INSTRUMENTATIONKEY"];
            var insights = new TelemetryClient(telemetryConfig);
            //insights.TrackTrace("Examples.Pipeline.MessageGenerator.Main");
            var module = new DependencyTrackingTelemetryModule();

            module.IncludeDiagnosticSourceActivities.Add("Microsoft.Azure.ServiceBus");
            module.IncludeDiagnosticSourceActivities.Add("Microsoft.Azure.EventHubs");
            module.Initialize(telemetryConfig);
            telemetryConfig.TelemetryInitializers.Add(new OperationCorrelationTelemetryInitializer());
            QuickPulseTelemetryProcessor processor = null;

            telemetryConfig.TelemetryProcessorChainBuilder
            .Use((next) =>
            {
                processor = new QuickPulseTelemetryProcessor(next);
                return(processor);
            })
            .Build();

            var QuickPulse = new QuickPulseTelemetryModule();

            QuickPulse.Initialize(telemetryConfig);
            QuickPulse.RegisterTelemetryProcessor(processor);

            insights.Context.Cloud.RoleName     = cloudRoleName;
            insights.Context.Cloud.RoleInstance = cloudRoleInstance;

            return(insights);
        }
예제 #7
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app,
                              IWebHostEnvironment env,
                              IOptions <AppInsightsOptions> options,
                              TelemetryConfiguration configuration,
                              DependencyTrackingTelemetryModule module)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            module.Initialize(configuration);
        }
예제 #8
0
        void SetUpTelemetryClient()
        {
            var module = new DependencyTrackingTelemetryModule();

            // Currently it seems have a problem https://github.com/microsoft/ApplicationInsights-dotnet-server/issues/536
            module.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("core.windows.net");
            module.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("127.0.0.1");

            TelemetryConfiguration config = TelemetryConfiguration.CreateDefault();

#pragma warning disable CS0618 // Type or member is obsolete
            var telemetryInitializer = new DurableTaskCorrelationTelemetryInitializer();
#pragma warning restore CS0618 // Type or member is obsolete
                               // TODO It should be suppressed by DependencyTrackingTelemetryModule, however, it doesn't work currently.
                               // Once the bug is fixed, remove this settings.
            telemetryInitializer.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("127.0.0.1");
            config.TelemetryInitializers.Add(telemetryInitializer);

            config.InstrumentationKey = Environment.GetEnvironmentVariable("APPINSIGHTS_INSTRUMENTATIONKEY");

            module.Initialize(config);

            telemetryClient = new TelemetryClient(config);
        }
예제 #9
0
        private static void InitializeTelemetry()
        {
            var isDebugging = Debugger.IsAttached;
            var config      = TelemetryConfiguration.CreateDefault();

            if (!isDebugging)
            {
                config.InstrumentationKey = "9fcef3c7-f401-41c7-9e91-1f6029c8dcc3";
            }

            var dependencyTracking = new DependencyTrackingTelemetryModule();

            dependencyTracking.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("core.windows.net");
            dependencyTracking.Initialize(config);

            config.TelemetryInitializers.Add(new HttpDependenciesParsingTelemetryInitializer());
            var channel = new InMemoryChannel {
                DeveloperMode = isDebugging
            };

            config.TelemetryChannel = channel;

            s_telemetryClient = new TelemetryClient(config);
        }
예제 #10
0
        public static void Run()
        {
            TelemetryConfiguration configuration = new TelemetryConfiguration();

            configuration.InstrumentationKey = "fb8a0b03-235a-4b52-b491-307e9fd6b209";

            // automatically track dependency calls
            var dependencies = new DependencyTrackingTelemetryModule();

            dependencies.Initialize(configuration);

            // automatically correlate all telemetry data with request
            configuration.TelemetryInitializers.Add(new OperationCorrelationTelemetryInitializer());

            // set default properties for all telemetry items
            configuration.TelemetryInitializers.Add(new DefaultTelemetryInitializer());

            // send all event telemetry to a different iKey
            configuration.TelemetryInitializers.Add(new BusinessTelemetryInitializer());

            // configure all telemetry to be sent to a single node
            configuration.TelemetryInitializers.Add(new NodeNameTelemetryInitializer());

            // initialize price calculation logic
            var state = new _State();

            state.Initialize();

            // enable sampling
            configuration.TelemetryProcessorChainBuilder
            // this telemetry processor will be executed first for all telemetry items to calculate the size and # of items
            .Use((next) => { return(new PriceCalculatorTelemetryProcessor(next, state.Collected)); })

            // this telemetry processor will be execuyted ONLY when telemetry is sampled in
            .Use((next) => { return(new PriceCalculatorTelemetryProcessor(next, state.Sent)); })
            .Build();


            TelemetryClient client = new TelemetryClient(configuration);

            var iterations = 0;

            // configure metrics collection
            MetricManager metricManager    = new MetricManager(client);
            var           itemsProcessed   = metricManager.CreateMetric("Iterations");
            var           processingFailed = metricManager.CreateMetric("Failed processing");
            var           processingSize   = metricManager.CreateMetric("Processing size");

            while (!state.IsTerminated)
            {
                iterations++;

                using (var operaiton = client.StartOperation <RequestTelemetry>("Process item"))
                {
                    client.TrackEvent("test");
                    client.TrackTrace("Something happened", SeverityLevel.Information);

                    try
                    {
                        HttpClient http = new HttpClient();
                        var        task = http.GetStringAsync("http://bing.com");
                        task.Wait();

                        // metrics aggregation. Metrics are aggregated and sent once per minute
                        itemsProcessed.Track(1);
                        processingSize.Track(task.Result.Length);
                        processingFailed.Track(0);

                        // raw metric telemetry. Each call represents a document.
                        client.TrackMetric("[RAW] Response size", task.Result.Length);
                    }
                    catch (Exception exc)
                    {
                        // raw metric telemetry
                        client.TrackMetric("[RAW] Successful responses", 0);

                        // metrics aggregation:
                        processingFailed.Track(1);

                        client.TrackException(exc);
                        operaiton.Telemetry.Success = false;
                    }
                    finally
                    {
                        client.TrackMetric("[RAW] Iterations", 1);
                        itemsProcessed.Track(1);
                    }

                    //                    client.StopOperation(operaiton);
                    //                    Console.WriteLine($"Iteration {iterations}. Elapesed time: {operaiton.Telemetry.Duration}");
                }
            }

            // send all metrics before exiting the program
            metricManager.Flush();

            Console.WriteLine($"Program sent 100K of telemetry in {iterations} iterations!");
            Console.ReadLine();
        }
예제 #11
0
        /// <summary>
        /// Adds Application Insights services into service collection.
        /// </summary>
        /// <param name="services">The <see cref="IServiceCollection"/> instance.</param>
        /// <param name="options">The action used to configure the options.</param>
        /// <returns>
        /// The <see cref="IServiceCollection"/>.
        /// </returns>
        public static IServiceCollection AddApplicationInsightsTelemetry(this IServiceCollection services)
        {
            if (!IsApplicationInsightsAdded(services))
            {
                services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>();

                services.AddSingleton <ITelemetryInitializer, AzureWebAppRoleEnvironmentTelemetryInitializer>();
                services.AddSingleton <ITelemetryInitializer, DomainNameRoleInstanceTelemetryInitializer>();
                services.AddSingleton <ITelemetryInitializer, ComponentVersionTelemetryInitializer>();
                services.AddSingleton <ITelemetryInitializer, ClientIpHeaderTelemetryInitializer>();
                services.AddSingleton <ITelemetryInitializer, OperationNameTelemetryInitializer>();
                services.AddSingleton <ITelemetryInitializer, ApplicationInsights.AspNetCore.TelemetryInitializers.OperationCorrelationTelemetryInitializer>();
                services.AddSingleton <ITelemetryInitializer, SyntheticTelemetryInitializer>();
                services.AddSingleton <ITelemetryInitializer, WebSessionTelemetryInitializer>();
                services.AddSingleton <ITelemetryInitializer, WebUserTelemetryInitializer>();
                services.AddSingleton <ITelemetryInitializer, AspNetCoreEnvironmentTelemetryInitializer>();
                services.AddSingleton <ITelemetryInitializer, HttpDependenciesParsingTelemetryInitializer>();
                services.AddSingleton <ITelemetryModule, DependencyTrackingTelemetryModule>(provider => {
                    var module          = new DependencyTrackingTelemetryModule();
                    var excludedDomains = module.ExcludeComponentCorrelationHttpHeadersOnDomains;
                    excludedDomains.Add("core.windows.net");
                    excludedDomains.Add("core.chinacloudapi.cn");
                    excludedDomains.Add("core.cloudapi.de");
                    excludedDomains.Add("core.usgovcloudapi.net");
                    excludedDomains.Add("localhost");
                    excludedDomains.Add("127.0.0.1");

                    var includedActivities = module.IncludeDiagnosticSourceActivities;
                    includedActivities.Add("Microsoft.Azure.EventHubs");
                    includedActivities.Add("Microsoft.Azure.ServiceBus");

                    return(module);
                });

#if NET451 || NET46
                services.AddSingleton <ITelemetryModule, PerformanceCollectorModule>();
#endif
                services.AddSingleton <TelemetryConfiguration>(provider => provider.GetService <IOptions <TelemetryConfiguration> >().Value);

                services.AddSingleton <ICorrelationIdLookupHelper>(provider => new CorrelationIdLookupHelper(() => provider.GetService <IOptions <TelemetryConfiguration> >().Value));

                services.AddSingleton <TelemetryClient>();

                services.AddSingleton <ApplicationInsightsInitializer, ApplicationInsightsInitializer>();
                services.AddSingleton <IApplicationInsightDiagnosticListener, HostingDiagnosticListener>();
                services.AddSingleton <IApplicationInsightDiagnosticListener, MvcDiagnosticsListener>();

                // Using startup filter instead of starting DiagnosticListeners directly because
                // AspNetCoreHostingDiagnosticListener injects TelemetryClient that injects TelemetryConfiguration
                // that requires IOptions infrastructure to run and initialize
                services.AddSingleton <IStartupFilter, ApplicationInsightsStartupFilter>();

                services.AddSingleton <JavaScriptSnippet>();
                services.AddSingleton <ApplicationInsightsLoggerEvents>();

                services.AddOptions();
                services.AddSingleton <IOptions <TelemetryConfiguration>, TelemetryConfigurationOptions>();
                services.AddSingleton <IConfigureOptions <TelemetryConfiguration>, TelemetryConfigurationOptionsSetup>();
            }
            return(services);
        }
예제 #12
0
        public static async Task RunAsync(CancellationToken token)
        {
            // set Instrumentation Key
            var configuration = new TelemetryConfiguration();

            configuration.InstrumentationKey = "fb8a0b03-235a-4b52-b491-307e9fd6b209";

            // automatically track dependency calls
            var dependencies = new DependencyTrackingTelemetryModule();

            dependencies.Initialize(configuration);

            // automatically correlate all telemetry data with request
            configuration.TelemetryInitializers.Add(new OperationCorrelationTelemetryInitializer());

            // initialize state for the telemetry size calculation
            var collectedItems = new ProcessedItems();
            var sentItems      = new ProcessedItems();

            // build telemetry processing pipeline
            configuration.TelemetryProcessorChainBuilder

            // this telemetry processor will be executed first for all telemetry items to calculate the size and # of items
            .Use((next) => { return(new SizeCalculatorTelemetryProcessor(next, collectedItems)); })

            // this is a standard fixed sampling processor that will let only 10%
            .Use((next) =>
            {
                return(new SamplingTelemetryProcessor(next)
                {
                    IncludedTypes = "Dependency",
                    SamplingPercentage = 10,
                });
            })

            // this is a standard adaptive sampling telemetry processor that will sample in/out any telemetry item it receives
            .Use((next) =>
            {
                return(new AdaptiveSamplingTelemetryProcessor(next)
                {
                    ExcludedTypes = "Event",                                     // exclude custom events from being sampled
                    MaxTelemetryItemsPerSecond = 1,                              // default: 5 calls/sec
                    SamplingPercentageIncreaseTimeout = TimeSpan.FromSeconds(1), // default: 2 min
                    SamplingPercentageDecreaseTimeout = TimeSpan.FromSeconds(1), // default: 30 sec
                    EvaluationInterval = TimeSpan.FromSeconds(1),                // default: 15 sec
                    InitialSamplingPercentage = 25,                              // default: 100%
                });
            })

            // this telemetry processor will be execuyted ONLY when telemetry is sampled in
            .Use((next) => { return(new SizeCalculatorTelemetryProcessor(next, sentItems)); })
            .Build();

            var client = new TelemetryClient(configuration);

            // configure metrics collection
            MetricManager metricManager = new MetricManager(client);
            var           reductionsize = metricManager.CreateMetric("Reduction Size");

            var iteration = 0;
            var http      = new HttpClient();

            while (!token.IsCancellationRequested)
            {
                iteration++;

                using (var operation = client.StartOperation <RequestTelemetry>("Process item"))
                {
                    client.TrackEvent("test", new Dictionary <string, string>()
                    {
                        { "iteration", iteration.ToString() }
                    });
                    client.TrackTrace($"Iteration {iteration} happened", SeverityLevel.Information);

                    try
                    {
                        await http.GetStringAsync("http://bing.com");
                    }
                    catch (Exception exc)
                    {
                        client.TrackException(exc);
                        operation.Telemetry.Success = false;
                    }

                    client.StopOperation(operation);
                    Console.WriteLine($"Iteration {iteration}. Elapsed time: {operation.Telemetry.Duration}. Collected Telemetry: {collectedItems.Size}/{collectedItems.Count}. Sent Telemetry: {sentItems.Size}/{sentItems.Count}. Ratio: {1.0 * collectedItems.Size / sentItems.Size}");

                    reductionsize.Track(collectedItems.Size - sentItems.Size);
#pragma warning disable 0618
                    client.TrackMetric("[RAW] Reduction Size", collectedItems.Size - sentItems.Size);
#pragma warning restore 0618
                }
            }
        }
예제 #13
0
        public static async Task RunAsync(CancellationToken token)
        {
            // set Instrumentation Key
            var configuration = new TelemetryConfiguration();

            configuration.InstrumentationKey = "fb8a0b03-235a-4b52-b491-307e9fd6b209";

            // automatically track dependency calls
            var dependencies = new DependencyTrackingTelemetryModule();

            dependencies.Initialize(configuration);

            // automatically correlate all telemetry data with request
            configuration.TelemetryInitializers.Add(new OperationCorrelationTelemetryInitializer());

            // initialize state for the telemetry size calculation
            var collectedItems = new ProcessedItems();
            var sentItems      = new ProcessedItems();

            // enable sampling
            configuration.TelemetryProcessorChainBuilder

            // this telemetry processor will be executed first for all telemetry items to calculate the size and # of items
            .Use((next) => { return(new SizeCalculatorTelemetryProcessor(next, collectedItems)); })

            // exemplify dependency telemetry that is faster than 100 msec
            .Use((next) => { return(new DependencyExampleTelemetryProcessor(next)); })

            // sample all telemetry to 10%
            .Use((next) =>
            {
                return(new SamplingTelemetryProcessor(next)
                {
                    SamplingPercentage = 10,
                });
            })

            // this telemetry processor will be execuyted ONLY when telemetry is sampled in
            .Use((next) => { return(new SizeCalculatorTelemetryProcessor(next, sentItems)); })
            .Build();

            var client = new TelemetryClient(configuration);

            var iteration = 0;
            var http      = new HttpClient();

            while (!token.IsCancellationRequested)
            {
                using (var operation = client.StartOperation <RequestTelemetry>("Process item"))
                {
                    client.TrackEvent("IterationStarted", properties: new Dictionary <string, string>()
                    {
                        { "iteration", iteration.ToString() }
                    });
                    client.TrackTrace($"Iteration {iteration} started", SeverityLevel.Information);

                    try
                    {
                        await http.GetStringAsync("http://bing.com");
                    }
                    catch (Exception exc)
                    {
                        client.TrackException(exc);
                        operation.Telemetry.Success = false;
                    }

                    client.StopOperation(operation);
                    Console.WriteLine($"Iteration {iteration}. Elapsed time: {operation.Telemetry.Duration}. Collected Telemetry: {collectedItems.Size}/{collectedItems.Count}. Sent Telemetry: {sentItems.Size}/{sentItems.Count}. Ratio: {1.0 * collectedItems.Size / sentItems.Size}");
                    iteration++;
                }
            }
        }
예제 #14
0
        private static void RegisterApplicationInsightsTelemetryModules(TelemetryConfiguration configuration)
        {
            RegisterApplicationInsightsTelemetryModule(
                new AppServicesHeartbeatTelemetryModule(),
                configuration);

            RegisterApplicationInsightsTelemetryModule(
                new AzureInstanceMetadataTelemetryModule(),
                configuration);

            RegisterApplicationInsightsTelemetryModule(
                new DeveloperModeWithDebuggerAttachedTelemetryModule(),
                configuration);

            RegisterApplicationInsightsTelemetryModule(
                new UnhandledExceptionTelemetryModule(),
                configuration);

            RegisterApplicationInsightsTelemetryModule(
                new UnobservedExceptionTelemetryModule(),
                configuration);

            var requestTrackingModule = new RequestTrackingTelemetryModule();

            requestTrackingModule.Handlers.Add("Microsoft.VisualStudio.Web.PageInspector.Runtime.Tracing.RequestDataHttpHandler");
            requestTrackingModule.Handlers.Add("System.Web.StaticFileHandler");
            requestTrackingModule.Handlers.Add("System.Web.Handlers.AssemblyResourceLoader");
            requestTrackingModule.Handlers.Add("System.Web.Optimization.BundleHandler");
            requestTrackingModule.Handlers.Add("System.Web.Script.Services.ScriptHandlerFactory");
            requestTrackingModule.Handlers.Add("System.Web.Handlers.TraceHandler");
            requestTrackingModule.Handlers.Add("System.Web.Services.Discovery.DiscoveryRequestHandler");
            requestTrackingModule.Handlers.Add("System.Web.HttpDebugHandler");
            RegisterApplicationInsightsTelemetryModule(
                requestTrackingModule,
                configuration);

            RegisterApplicationInsightsTelemetryModule(
                new ExceptionTrackingTelemetryModule(),
                configuration);

            RegisterApplicationInsightsTelemetryModule(
                new AspNetDiagnosticTelemetryModule(),
                configuration);

            var dependencyTrackingModule = new DependencyTrackingTelemetryModule();

            dependencyTrackingModule.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("core.windows.net");
            dependencyTrackingModule.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("core.chinacloudapi.cn");
            dependencyTrackingModule.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("core.cloudapi.de");
            dependencyTrackingModule.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("core.usgovcloudapi.net");
            dependencyTrackingModule.IncludeDiagnosticSourceActivities.Add("Microsoft.Azure.EventHubs");
            dependencyTrackingModule.IncludeDiagnosticSourceActivities.Add("Microsoft.Azure.ServiceBus");
            RegisterApplicationInsightsTelemetryModule(
                dependencyTrackingModule,
                configuration);

            RegisterApplicationInsightsTelemetryModule(
                new PerformanceCollectorModule(),
                configuration);

            RegisterApplicationInsightsTelemetryModule(
                new QuickPulseTelemetryModule(),
                configuration);
        }
        public static IServiceCollection AddApplicationInsights(this IServiceCollection services)
        {
            services.TryAddSingleton <ISdkVersionProvider, WebJobsSdkVersionProvider>();

            // Bind to the configuration section registered with
            services.AddOptions <ApplicationInsightsLoggerOptions>()
            .Configure <ILoggerProviderConfiguration <ApplicationInsightsLoggerProvider> >((options, config) =>
            {
                config.Configuration?.Bind(options);
            });

            services.AddSingleton <ITelemetryInitializer, HttpDependenciesParsingTelemetryInitializer>();
            services.AddSingleton <ITelemetryInitializer, WebJobsRoleEnvironmentTelemetryInitializer>();
            services.AddSingleton <ITelemetryInitializer, WebJobsSanitizingInitializer>();
            services.AddSingleton <ITelemetryInitializer, WebJobsTelemetryInitializer>();

            services.AddSingleton <ITelemetryModule, QuickPulseTelemetryModule>();

            services.AddSingleton <ITelemetryModule>(provider =>
            {
                ApplicationInsightsLoggerOptions options = provider.GetService <IOptions <ApplicationInsightsLoggerOptions> >().Value;
                if (options.EnablePerformanceCountersCollection)
                {
                    return(new PerformanceCollectorModule());
                }

                return(NullTelemetryModule.Instance);
            });

            services.AddSingleton <IApplicationIdProvider, ApplicationInsightsApplicationIdProvider>();

            services.AddSingleton <ITelemetryModule, DependencyTrackingTelemetryModule>(provider =>
            {
                var options = provider.GetService <IOptions <ApplicationInsightsLoggerOptions> >().Value;

                var dependencyCollector = new DependencyTrackingTelemetryModule();
                var excludedDomains     = dependencyCollector.ExcludeComponentCorrelationHttpHeadersOnDomains;
                excludedDomains.Add("core.windows.net");
                excludedDomains.Add("core.chinacloudapi.cn");
                excludedDomains.Add("core.cloudapi.de");
                excludedDomains.Add("core.usgovcloudapi.net");
                excludedDomains.Add("localhost");
                excludedDomains.Add("127.0.0.1");

                var includedActivities = dependencyCollector.IncludeDiagnosticSourceActivities;
                includedActivities.Add("Microsoft.Azure.ServiceBus");

                dependencyCollector.EnableW3CHeadersInjection = options.HttpAutoCollectionOptions.EnableW3CDistributedTracing;
                return(dependencyCollector);
            });

            services.AddSingleton <ITelemetryModule>(provider =>
            {
                var options = provider.GetService <IOptions <ApplicationInsightsLoggerOptions> >().Value;
                if (options.HttpAutoCollectionOptions.EnableHttpTriggerExtendedInfoCollection)
                {
                    var appIdProvider = provider.GetService <IApplicationIdProvider>();

                    return(new RequestTrackingTelemetryModule(appIdProvider)
                    {
                        CollectionOptions = new RequestCollectionOptions
                        {
                            TrackExceptions = false, // webjobs/functions track exceptions themselves
                            EnableW3CDistributedTracing = options.HttpAutoCollectionOptions.EnableW3CDistributedTracing,
                            InjectResponseHeaders = options.HttpAutoCollectionOptions.EnableResponseHeaderInjection
                        }
                    });
                }

                return(NullTelemetryModule.Instance);
            });

            services.AddSingleton <ITelemetryModule, AppServicesHeartbeatTelemetryModule>();

            services.AddSingleton <ITelemetryChannel, ServerTelemetryChannel>();
            services.AddSingleton <TelemetryConfiguration>(provider =>
            {
                ApplicationInsightsLoggerOptions options = provider.GetService <IOptions <ApplicationInsightsLoggerOptions> >().Value;
                LoggerFilterOptions filterOptions        = CreateFilterOptions(provider.GetService <IOptions <LoggerFilterOptions> >().Value);

                ITelemetryChannel channel     = provider.GetService <ITelemetryChannel>();
                TelemetryConfiguration config = TelemetryConfiguration.CreateDefault();

                IApplicationIdProvider appIdProvider   = provider.GetService <IApplicationIdProvider>();
                ISdkVersionProvider sdkVersionProvider = provider.GetService <ISdkVersionProvider>();
                // Because of https://github.com/Microsoft/ApplicationInsights-dotnet-server/issues/943
                // we have to touch (and create) Active configuration before initializing telemetry modules
                // Active configuration is used to report AppInsights heartbeats
                // role environment telemetry initializer is needed to correlate heartbeats to particular host

                var activeConfig = TelemetryConfiguration.Active;
                if (!string.IsNullOrEmpty(options.InstrumentationKey) &&
                    string.IsNullOrEmpty(activeConfig.InstrumentationKey))
                {
                    activeConfig.InstrumentationKey = options.InstrumentationKey;
                }

                if (!activeConfig.TelemetryInitializers.OfType <WebJobsRoleEnvironmentTelemetryInitializer>().Any())
                {
                    activeConfig.TelemetryInitializers.Add(new WebJobsRoleEnvironmentTelemetryInitializer());
                    activeConfig.TelemetryInitializers.Add(new WebJobsTelemetryInitializer(sdkVersionProvider));
                    if (options.HttpAutoCollectionOptions.EnableW3CDistributedTracing)
                    {
                        // W3C distributed tracing is enabled by the feature flag inside ApplicationInsights SDK
                        // W3COperationCorrelationTelemetryInitializer will go away once W3C is implemented
                        // in the DiagnosticSource (.NET)

                        TelemetryConfiguration.Active.TelemetryInitializers.Add(new W3COperationCorrelationTelemetryInitializer());
                    }
                }

                SetupTelemetryConfiguration(
                    config,
                    options,
                    channel,
                    provider.GetServices <ITelemetryInitializer>(),
                    provider.GetServices <ITelemetryModule>(),
                    appIdProvider,
                    filterOptions);

                return(config);
            });

            services.AddSingleton <TelemetryClient>(provider =>
            {
                TelemetryConfiguration configuration = provider.GetService <TelemetryConfiguration>();
                TelemetryClient client = new TelemetryClient(configuration);

                ISdkVersionProvider versionProvider            = provider.GetService <ISdkVersionProvider>();
                client.Context.GetInternalContext().SdkVersion = versionProvider?.GetSdkVersion();

                return(client);
            }
                                                    );

            services.AddSingleton <ILoggerProvider, ApplicationInsightsLoggerProvider>();

            return(services);
        }
        public static IHostBuilder CreateHostBuilder(string[] args)
        {
            return(Host.CreateDefaultBuilder(args)
                   .UseWindowsService()
                   .ConfigureAppConfiguration(cfg =>
            {
                cfg.SetBasePath(AppDomain.CurrentDomain.BaseDirectory);
            })
                   .ConfigureLogging((context, builder) =>
            {
                builder.AddConsole();
                builder.SetMinimumLevel(LogLevel.Trace);
            })
                   .ConfigureServices((hostContext, services) =>
            {
                var hostConfig = hostContext.Configuration;
                var module = new DependencyTrackingTelemetryModule();
                module.IncludeDiagnosticSourceActivities.Add("MassTransit");

                TelemetryConfiguration configuration = TelemetryConfiguration.CreateDefault();
                configuration.InstrumentationKey = "<your instrumentation key>";
                configuration.TelemetryInitializers.Add(new HttpDependenciesParsingTelemetryInitializer());

                module.Initialize(configuration);

                var loggerOptions = new ApplicationInsightsLoggerOptions();
                var applicationInsightsLoggerProvider = new ApplicationInsightsLoggerProvider(Options.Create(configuration),
                                                                                              Options.Create(loggerOptions));
                ILoggerFactory factory = new LoggerFactory();
                factory.AddProvider(applicationInsightsLoggerProvider);
                LogContext.ConfigureCurrentLogContext(factory);

                services.AddMassTransit(x =>
                {
                    x.AddConsumersFromNamespaceContaining <SubmitOrderConsumer>();
                    x.AddBus(context => Bus.Factory.CreateUsingAzureServiceBus(
                                 configurator =>
                    {
                        var host =
                            configurator.Host(hostConfig["AzureServiceBusConnectionString"],
                                              h => { });

                        configurator.ReceiveEndpoint("submit-order", e =>
                        {
                            e.Consumer <SubmitOrderConsumer>();
                        });

                        configurator.ReceiveEndpoint("order-observer", e =>
                        {
                            e.Consumer <OrderSubmittedConsumer>();
                        });

                        configurator.ReceiveEndpoint("order-state", e =>
                        {
                            var machine = new OrderStateMachine();
                            var repository = new InMemorySagaRepository <OrderState>();

                            e.StateMachineSaga(machine, repository);

                            EndpointConvention.Map <OrderProcessed>(e.InputAddress);
                        });

                        configurator.ReceiveEndpoint("execute-process-order", e =>
                        {
                            e.ExecuteActivityHost <ProcessOrderActivity, ProcessOrderArguments>();

                            EndpointConvention.Map <ProcessOrderArguments>(e.InputAddress);
                        });
                    }));
                });

                services.AddHostedService <WindowsService>();
            }));
        }
예제 #17
0
        public static void Run()
        {
            TelemetryConfiguration configuration = new TelemetryConfiguration();

            configuration.InstrumentationKey = "fb8a0b03-235a-4b52-b491-307e9fd6b209";

            // automatically track dependency calls
            var dependencies = new DependencyTrackingTelemetryModule();

            dependencies.Initialize(configuration);

            // automatically correlate all telemetry data with request
            configuration.TelemetryInitializers.Add(new OperationCorrelationTelemetryInitializer());

            //// initialize price calculation logic
            var state = new _State();

            state.Initialize();

            // enable sampling
            configuration.TelemetryProcessorChainBuilder
            // this telemetry processor will be executed first for all telemetry items to calculate the size and # of items
            .Use((next) => { return(new PriceCalculatorTelemetryProcessor(next, state.Collected)); })

            // this is a standard fixed sampling processor that will let only 10%
            .Use((next) =>
            {
                return(new SamplingTelemetryProcessor(next)
                {
                    IncludedTypes = "Dependency",
                    SamplingPercentage = 10
                });
            })

            // this is a standard adaptive sampling telemetry processor that will sample in/out any telemetry item it receives
            .Use((next) =>
            {
                return(new AdaptiveSamplingTelemetryProcessor(next)
                {
                    ExcludedTypes = "Event",                                     // exclude custom events from being sampled
                    MaxTelemetryItemsPerSecond = 1,                              //default: 5 calls/sec
                    SamplingPercentageIncreaseTimeout = TimeSpan.FromSeconds(1), //default: 2 min
                    SamplingPercentageDecreaseTimeout = TimeSpan.FromSeconds(1), //default: 30 sec
                    EvaluationInterval = TimeSpan.FromSeconds(1),                //default: 15 sec
                    InitialSamplingPercentage = 25                               //default: 100%
                });
            })

            // this telemetry processor will be execuyted ONLY when telemetry is sampled in
            .Use((next) => { return(new PriceCalculatorTelemetryProcessor(next, state.Sent)); })
            .Build();


            TelemetryClient client = new TelemetryClient(configuration);

            var iterations = 0;


            while (!state.IsTerminated)
            {
                iterations++;

                using (var operaiton = client.StartOperation <RequestTelemetry>("Process item"))
                {
                    client.TrackEvent("test");
                    client.TrackTrace("Something happened", SeverityLevel.Information);

                    try
                    {
                        HttpClient http = new HttpClient();
                        var        task = http.GetStringAsync("http://bing.com");
                        task.Wait();
                    }
                    catch (Exception exc)
                    {
                        client.TrackException(exc);
                        operaiton.Telemetry.Success = false;
                    }

                    //client.StopOperation(operaiton);
                    //Console.WriteLine($"Iteration {iterations}. Elapesed time: {operaiton.Telemetry.Duration}");
                }
            }

            Console.WriteLine($"Program sent 100K of telemetry in {iterations} iterations!");
            Console.ReadLine();
        }
예제 #18
0
        public static async Task RunAsync(CancellationToken token)
        {
            // set Instrumentation Key
            var configuration = new TelemetryConfiguration();

            configuration.InstrumentationKey = "fb8a0b03-235a-4b52-b491-307e9fd6b209";

            // automatically track dependency calls
            var dependencies = new DependencyTrackingTelemetryModule();

            dependencies.Initialize(configuration);

            // automatically correlate all telemetry data with request
            configuration.TelemetryInitializers.Add(new OperationCorrelationTelemetryInitializer());

            QuickPulseTelemetryProcessor processor = null;

            // enable Live Metrics
            configuration.TelemetryProcessorChainBuilder

            // adding LiveMetrics telemetry processor
            .Use((next) =>
            {
                processor = new QuickPulseTelemetryProcessor(next);
                return(processor);
            })

            .Build();

            var quickPulse = new QuickPulseTelemetryModule();

            quickPulse.Initialize(configuration);
            quickPulse.RegisterTelemetryProcessor(processor);

            var client = new TelemetryClient(configuration);

            var iteration = 0;
            var http      = new HttpClient();
            var rnd       = new Random();

            while (!token.IsCancellationRequested)
            {
                iteration++;

                using (var operation = client.StartOperation <RequestTelemetry>("Process item"))
                {
                    client.TrackEvent("test", new Dictionary <string, string>()
                    {
                        { "iteration", iteration.ToString() }
                    });
                    client.TrackTrace($"Iteration {iteration} happened", SeverityLevel.Information);

                    var status = rnd.Next() < rnd.Next();
                    try
                    {
                        if (status)
                        {
                            throw new Exception($"Failure during processing of iteration #{iteration}");
                        }

                        await http.GetStringAsync("http://bing.com");
                    }
                    catch (Exception exc)
                    {
                        client.TrackException(exc);
                    }
                    finally
                    {
                        client.StopOperation <RequestTelemetry>(operation);
                        operation.Telemetry.Success = status;

                        Console.WriteLine($"Iteration {iteration}. Elapsed time: {operation.Telemetry.Duration}. Success: {operation.Telemetry.Success}");
                    }
                }
            }
        }
        public async Task TestDependencyCollectionNoParentActivity()
        {
            ITelemetry sentTelemetry = null;

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

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

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

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

                var url = new Uri("http://bing.com");

                var request = new HttpRequestMessage(HttpMethod.Get, url);
                await new HttpClient().SendAsync(request);

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

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

                var requestId = item.Id;
                Assert.AreEqual(requestId, request.Headers.GetValues("Request-Id").Single());
                Assert.AreEqual(requestId, request.Headers.GetValues("x-ms-request-id").Single());
                Assert.IsTrue(requestId.StartsWith('|' + item.Context.Operation.Id + '.'));
            }
        }
예제 #20
0
        public static async Task Main(string[] args)
        {
            var isService = !(Debugger.IsAttached || args.Contains("--console"));

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
                         .Enrich.FromLogContext()
                         .WriteTo.Console()
                         .CreateLogger();

            var builder = new HostBuilder()
                          .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.AddJsonFile("appsettings.json", true);
                config.AddEnvironmentVariables();

                if (args != null)
                {
                    config.AddCommandLine(args);
                }
            })
                          .ConfigureServices((hostContext, services) =>
            {
                _module = new DependencyTrackingTelemetryModule();
                _module.IncludeDiagnosticSourceActivities.Add("MassTransit");

                TelemetryConfiguration configuration = TelemetryConfiguration.CreateDefault();
                configuration.InstrumentationKey     = "6b4c6c82-3250-4170-97d3-245ee1449276";
                configuration.TelemetryInitializers.Add(new HttpDependenciesParsingTelemetryInitializer());

                _telemetryClient = new TelemetryClient(configuration);

                services.TryAddSingleton(KebabCaseEndpointNameFormatter.Instance);
                services.AddMassTransit(cfg =>
                {
                    cfg.AddConsumersFromNamespaceContaining <ReadFileConsumer>();

                    cfg.UsingRabbitMq(ConfigureBus);
                });
                services.AddHostedService <MassTransitConsoleHostedService>();
            })
                          .ConfigureLogging((hostingContext, logging) =>
            {
                logging.AddSerilog(dispose: true);
                logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                logging.AddConsole();
            });

            ;

            if (isService)
            {
                await builder.UseWindowsService().Build().RunAsync();
            }
            else
            {
                await builder.RunConsoleAsync();
            }

            _module?.Dispose();
            _telemetryClient?.Flush();

            Log.CloseAndFlush();
        }
예제 #21
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        /// <param name="services">An instance of <see cref="IServiceCollection"/>.</param>
        public void ConfigureServices(IServiceCollection services)
        {
            this.ConfigureServicesCommon(services);

            _ = services.AddMvc();
            _ = services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "NotificationService", Version = "v1"
                });
            });

            ITelemetryInitializer[] itm = new ITelemetryInitializer[1];
            var envInitializer          = new EnvironmentInitializer
            {
                Service         = this.Configuration[AIConstants.ServiceConfigName],
                ServiceLine     = this.Configuration[AIConstants.ServiceLineConfigName],
                ServiceOffering = this.Configuration[AIConstants.ServiceOfferingConfigName],
                ComponentId     = this.Configuration[AIConstants.ComponentIdConfigName],
                ComponentName   = this.Configuration[AIConstants.ComponentNameConfigName],
                EnvironmentName = this.Configuration[AIConstants.EnvironmentName],
                IctoId          = "IctoId",
            };

            itm[0] = envInitializer;

            NotificationProviders.Common.Logger.LoggingConfiguration loggingConfiguration = new NotificationProviders.Common.Logger.LoggingConfiguration
            {
                IsTraceEnabled  = true,
                TraceLevel      = (SeverityLevel)Enum.Parse(typeof(SeverityLevel), this.Configuration[ConfigConstants.AITraceLelelConfigKey]),
                EnvironmentName = this.Configuration[AIConstants.EnvironmentName],
            };

            var tconfig = TelemetryConfiguration.CreateDefault();

            tconfig.InstrumentationKey = this.Configuration[ConfigConstants.AIInsrumentationConfigKey];

            DependencyTrackingTelemetryModule depModule = new DependencyTrackingTelemetryModule();

            depModule.Initialize(tconfig);

            RequestTrackingTelemetryModule requestTrackingTelemetryModule = new RequestTrackingTelemetryModule();

            requestTrackingTelemetryModule.Initialize(tconfig);

            _ = services.AddSingleton <NotificationProviders.Common.Logger.ILogger>(_ => new NotificationProviders.Common.Logger.AILogger(loggingConfiguration, tconfig, itm));

            _ = services.AddScoped <IEmailManager, EmailManager>(s =>
                                                                 new EmailManager(
                                                                     this.Configuration,
                                                                     s.GetService <IRepositoryFactory>(),
                                                                     s.GetService <ILogger>(),
                                                                     s.GetService <IMailTemplateManager>(),
                                                                     s.GetService <ITemplateMerge>()))
                .AddScoped <IEmailServiceManager, EmailServiceManager>(s =>
                                                                       new EmailServiceManager(this.Configuration, s.GetService <IRepositoryFactory>(), s.GetService <ICloudStorageClient>(), s.GetService <ILogger>(),
                                                                                               s.GetService <INotificationProviderFactory>(), s.GetService <IEmailManager>()))
                .AddScoped <ITemplateMerge, TemplateMerge>()
                .AddSingleton <IEmailAccountManager, EmailAccountManager>()
                .AddScoped <INotificationProviderFactory, NotificationProviderFactory>();

            NotificationProviderType providerType = (NotificationProviderType)Enum.Parse(typeof(NotificationProviderType), this.Configuration[ConfigConstants.NotificationProviderType]);

            if (NotificationProviderType.DirectSend == providerType)
            {
                this.ConfigureDirectSendServices(services);
            }
            else if (NotificationProviderType.SMTP == providerType)
            {
                this.ConfigureSMTPServices(services);
            }
            else
            {
                this.ConfigureGraphServices(services);
            }
        }
예제 #22
0
        public static IServiceCollection AddApplicationInsights(this IServiceCollection services)
        {
            services.TryAddSingleton <ISdkVersionProvider, WebJobsSdkVersionProvider>();

            // Bind to the configuration section registered with
            services.AddOptions <ApplicationInsightsLoggerOptions>()
            .Configure <ILoggerProviderConfiguration <ApplicationInsightsLoggerProvider> >((options, config) =>
            {
                config.Configuration?.Bind(options);
            });

            services.AddSingleton <ITelemetryInitializer, HttpDependenciesParsingTelemetryInitializer>();
            services.AddSingleton <ITelemetryInitializer, WebJobsRoleEnvironmentTelemetryInitializer>();
            services.AddSingleton <ITelemetryInitializer, WebJobsTelemetryInitializer>();
            services.AddSingleton <ITelemetryInitializer, WebJobsSanitizingInitializer>();
            services.AddSingleton <ITelemetryModule, QuickPulseTelemetryModule>();

            services.AddSingleton <IApplicationIdProvider, ApplicationInsightsApplicationIdProvider>();

            services.AddSingleton <ITelemetryModule, DependencyTrackingTelemetryModule>(provider =>
            {
                var dependencyCollector = new DependencyTrackingTelemetryModule();
                var excludedDomains     = dependencyCollector.ExcludeComponentCorrelationHttpHeadersOnDomains;
                excludedDomains.Add("core.windows.net");
                excludedDomains.Add("core.chinacloudapi.cn");
                excludedDomains.Add("core.cloudapi.de");
                excludedDomains.Add("core.usgovcloudapi.net");
                excludedDomains.Add("localhost");
                excludedDomains.Add("127.0.0.1");

                var includedActivities = dependencyCollector.IncludeDiagnosticSourceActivities;
                includedActivities.Add("Microsoft.Azure.ServiceBus");

                return(dependencyCollector);
            });
            services.AddSingleton <ITelemetryModule, AppServicesHeartbeatTelemetryModule>();

            services.AddSingleton <ITelemetryChannel, ServerTelemetryChannel>();
            services.AddSingleton <TelemetryConfiguration>(provider =>
            {
                ApplicationInsightsLoggerOptions options = provider.GetService <IOptions <ApplicationInsightsLoggerOptions> >().Value;
                LoggerFilterOptions filterOptions        = CreateFilterOptions(provider.GetService <IOptions <LoggerFilterOptions> >().Value);

                ITelemetryChannel channel     = provider.GetService <ITelemetryChannel>();
                TelemetryConfiguration config = TelemetryConfiguration.CreateDefault();

                IApplicationIdProvider appIdProvider = provider.GetService <IApplicationIdProvider>();

                // Because of https://github.com/Microsoft/ApplicationInsights-dotnet-server/issues/943
                // we have to touch (and create) Active configuration before initializing telemetry modules
                // Active configuration is used to report AppInsights heartbeats
                // role environment telemetry initializer is needed to correlate heartbeats to particular host

                var activeConfig = TelemetryConfiguration.Active;
                if (!string.IsNullOrEmpty(options.InstrumentationKey) &&
                    string.IsNullOrEmpty(activeConfig.InstrumentationKey))
                {
                    activeConfig.InstrumentationKey = options.InstrumentationKey;
                }

                if (!activeConfig.TelemetryInitializers.OfType <WebJobsRoleEnvironmentTelemetryInitializer>().Any())
                {
                    activeConfig.TelemetryInitializers.Add(
                        new WebJobsRoleEnvironmentTelemetryInitializer());
                }

                SetupTelemetryConfiguration(
                    config,
                    options,
                    channel,
                    provider.GetServices <ITelemetryInitializer>(),
                    provider.GetServices <ITelemetryModule>(),
                    appIdProvider,
                    filterOptions);

                return(config);
            });

            services.AddSingleton <TelemetryClient>(provider =>
            {
                TelemetryConfiguration configuration = provider.GetService <TelemetryConfiguration>();
                TelemetryClient client = new TelemetryClient(configuration);

                ISdkVersionProvider versionProvider            = provider.GetService <ISdkVersionProvider>();
                client.Context.GetInternalContext().SdkVersion = versionProvider?.GetSdkVersion();

                return(client);
            });

            services.AddSingleton <ILoggerProvider, ApplicationInsightsLoggerProvider>();

            return(services);
        }
예제 #23
0
        static void Main_backup(string[] args)
        {
            var state = new _State();

            state.Initialize();

            TelemetryConfiguration configuration = new TelemetryConfiguration();

            configuration.InstrumentationKey = "fb8a0b03-235a-4b52-b491-307e9fd6b209";

            var telemetryChannel = new ServerTelemetryChannel();

            telemetryChannel.Initialize(configuration);
            configuration.TelemetryChannel = telemetryChannel;


            // data collection modules
            var dependencies = new DependencyTrackingTelemetryModule();

            dependencies.Initialize(configuration);

            // telemetry initializers
            configuration.TelemetryInitializers.Add(new AppVersionTelemetryInitializer());
            configuration.TelemetryInitializers.Add(new DefaultTelemetryInitializer());
            configuration.TelemetryInitializers.Add(new BusinessTelemetryInitializer());
            configuration.TelemetryInitializers.Add(new NodeNameTelemetryInitializer());
            configuration.TelemetryInitializers.Add(new OperationCorrelationTelemetryInitializer());

            // telemetry processors
            configuration.TelemetryProcessorChainBuilder
            .Use((next) => { return(new PriceCalculatorTelemetryProcessor(next, state.Collected)); })
//                .Use((next) => { return new MyTelemetryProcessor(next); })
//                .Use((next) => { return new CleanAutoCollecctedTelemetryProcessor(next); })
//                .Use((next) => { return new ExampleTelemetryProcessor(next); })
            // send only 10% of all dependency data
            .Use((next) =>
            {
                return(new SamplingTelemetryProcessor(next)
                {
                    IncludedTypes = "Dependency",
                    SamplingPercentage = 10
                });
            })
            // start sampling when load exceeds 2 events per second for all telemetry types except events
            .Use((next) =>
            {
                return(new AdaptiveSamplingTelemetryProcessor(next)
                {
                    ExcludedTypes = "Event",
                    MaxTelemetryItemsPerSecond = 2,
                    SamplingPercentageIncreaseTimeout = TimeSpan.FromSeconds(1),
                    SamplingPercentageDecreaseTimeout = TimeSpan.FromSeconds(1),
                    EvaluationInterval = TimeSpan.FromSeconds(1),
                    InitialSamplingPercentage = 25
                });
            })
            .Use((next) => { return(new PriceCalculatorTelemetryProcessor(next, state.Sent)); })
            .Build();

            TelemetryClient client = new TelemetryClient(configuration);

            var iterations = 0;


            MetricManager metricManager    = new MetricManager(client);
            var           itemsProcessed   = metricManager.CreateMetric("Items processed");
            var           processingFailed = metricManager.CreateMetric("Failed processing");
            var           processingSize   = metricManager.CreateMetric("Processing size");


            while (!state.IsTerminated)
            {
                iterations++;

                using (var operaiton = client.StartOperation <RequestTelemetry>("Process item"))
                {
                    client.TrackEvent("test");
                    client.TrackTrace("Something happened");

                    try
                    {
                        HttpClient http = new HttpClient();
                        var        task = http.GetStringAsync("http://bing.com");
                        task.Wait();

                        // metrics aggregation:
                        //itemsProcessed.Track(1);
                        //processingSize.Track(task.Result.Length);
                        //processingFailed.Track(0);

                        //client.TrackMetric("Response size", task.Result.Length);
                        //client.TrackMetric("Successful responses", 1);
                    }
                    catch (Exception exc)
                    {
                        //client.TrackMetric("Successful responses", 0);
                        //operaiton.Telemetry.Success = false;

                        // metrics aggregation:
                        //processingFailed.Track(1);
                    }
                }
            }

            Console.WriteLine($"Program sent 1Mb of telemetry in {iterations} iterations!");
            Console.ReadLine();
        }
예제 #24
0
        static async Task Main(string[] args)
        {
            var isService = !(Debugger.IsAttached || args.Contains("--console"));

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
                         .Enrich.FromLogContext()
                         .WriteTo.Console()
                         .WriteTo.Seq("http://localhost:5341")
                         .CreateLogger();

            var builder = new HostBuilder()
                          .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.AddJsonFile("appsettings.json", true);
                config.AddEnvironmentVariables();

                if (args != null)
                {
                    config.AddCommandLine(args);
                }
            })
                          .ConfigureServices((hostContext, services) =>
            {
                _module = new DependencyTrackingTelemetryModule();
                _module.IncludeDiagnosticSourceActivities.Add("MassTransit");

                TelemetryConfiguration configuration = TelemetryConfiguration.CreateDefault();
                configuration.InstrumentationKey     = "0bd7dab0-5809-4ce5-b477-c89271124a54";
                configuration.TelemetryInitializers.Add(new HttpDependenciesParsingTelemetryInitializer());

                _telemetryClient = new TelemetryClient(configuration);

                _module.Initialize(configuration);

                services.AddScoped <AcceptOrderActivity>();

                services.AddScoped <RoutingSlipBatchEventConsumer>();

                services.TryAddSingleton(KebabCaseEndpointNameFormatter.Instance);
                services.AddMassTransit(cfg =>
                {
                    cfg.AddConsumersFromNamespaceContaining <SubmitOrderConsumer>();
                    cfg.AddActivitiesFromNamespaceContaining <AllocateInventoryActivity>();

                    cfg.AddSagaStateMachine <OrderStateMachine, OrderState>(typeof(OrderStateMachineDefinition))
                    .EntityFrameworkRepository(r =>
                    {
                        r.AddDbContext <DbContext, OrderStateDbContext>((provider, builder) =>
                        {
                            builder.UseSqlServer("Server=tcp:gertjvr.database.windows.net,1433;Initial Catalog=gertjvr;Persist Security Info=False;User ID=gertjvr;Password=Works4me!;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;", m =>
                            {
                                m.MigrationsAssembly(Assembly.GetExecutingAssembly().GetName().Name);
                                m.MigrationsHistoryTable($"__{nameof(OrderStateDbContext)}");
                            });
                        });
                    });

                    cfg.UsingAzureServiceBus(ConfigureBus);

                    cfg.AddRequestClient <AllocateInventory>();
                });

                services.AddHostedService <MassTransitConsoleHostedService>();
            })
                          .ConfigureLogging((hostingContext, logging) =>
            {
                logging.AddSerilog(dispose: true);
                logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
            });

            if (isService)
            {
                await builder.UseWindowsService().Build().RunAsync();
            }
            else
            {
                await builder.RunConsoleAsync();
            }

            _telemetryClient?.Flush();
            _module?.Dispose();

            Log.CloseAndFlush();
        }
예제 #25
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        /// <param name="services">An instance of <see cref="IServiceCollection"/>.</param>
        public void ConfigureServices(IServiceCollection services)
        {
            this.ConfigureServicesCommon(services);

            _ = services.AddMvc();
            _ = services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "NotificationService", Version = "v1"
                });
            });

            ITelemetryInitializer[] itm = new ITelemetryInitializer[1];
            var envInitializer          = new EnvironmentInitializer
            {
                Service         = this.Configuration[Constants.ServiceConfigName],
                ServiceLine     = this.Configuration[Constants.ServiceLineConfigName],
                ServiceOffering = this.Configuration[Constants.ServiceOfferingConfigName],
                ComponentId     = this.Configuration[Constants.ComponentIdConfigName],
                ComponentName   = this.Configuration[Constants.ComponentNameConfigName],
                EnvironmentName = this.Configuration[Constants.EnvironmentName],
                IctoId          = "IctoId",
            };

            itm[0] = envInitializer;

            NotificationProviders.Common.Logger.LoggingConfiguration loggingConfiguration = new NotificationProviders.Common.Logger.LoggingConfiguration
            {
                IsTraceEnabled  = true,
                TraceLevel      = (SeverityLevel)Enum.Parse(typeof(SeverityLevel), this.Configuration["ApplicationInsights:TraceLevel"]),
                EnvironmentName = this.Configuration[Constants.EnvironmentName],
            };

            var tconfig = TelemetryConfiguration.CreateDefault();

            tconfig.InstrumentationKey = this.Configuration["ApplicationInsights:InstrumentationKey"];

            DependencyTrackingTelemetryModule depModule = new DependencyTrackingTelemetryModule();

            depModule.Initialize(tconfig);

            RequestTrackingTelemetryModule requestTrackingTelemetryModule = new RequestTrackingTelemetryModule();

            requestTrackingTelemetryModule.Initialize(tconfig);

            _ = services.AddSingleton <NotificationProviders.Common.Logger.ILogger>(_ => new NotificationProviders.Common.Logger.AILogger(loggingConfiguration, tconfig, itm));


            _ = services.AddSingleton <SendAccountConfiguration>(new SendAccountConfiguration()
            {
                DisplayName = this.Configuration["DirectSendSetting:DisplayName"],
            });

            if (int.TryParse(this.Configuration["DirectSendSetting:SmtpPort"], out int port))
            {
                _ = services.AddSingleton <ISmtpConfiguration>(new SmtpConfiguration()
                {
                    SmtpPort   = port,
                    SmtpServer = this.Configuration["DirectSendSetting:SmtpServer"]
                });
            }

            _ = services.AddSingleton <ISmtpClientFactory, DSSmtpClientFactory>()
                .AddSingleton <ISmtpClientPool, SmtpClientPool>()
                .AddSingleton <IEmailService, DirectSendMailService>();

            _ = services.AddScoped <INotificationReportManager, NotificationReportManager>()
                .AddScoped <IEmailManager, EmailManager>(s =>
                                                         new EmailManager(
                                                             this.Configuration,
                                                             s.GetService <IRepositoryFactory>(),
                                                             s.GetService <ILogger>(),
                                                             s.GetService <IMailTemplateManager>(),
                                                             s.GetService <ITemplateMerge>()))
                .AddScoped <IEmailServiceManager, EmailServiceManager>(s =>
                                                                       new EmailServiceManager(this.Configuration, s.GetService <IRepositoryFactory>(), s.GetService <ICloudStorageClient>(), s.GetService <ILogger>(),
                                                                                               s.GetService <INotificationProviderFactory>(), s.GetService <IEmailManager>()))
                .AddScoped <IRepositoryFactory, RepositoryFactory>()
                .AddScoped <EmailNotificationRepository>()
                .AddScoped <IEmailNotificationRepository, EmailNotificationRepository>(s => s.GetService <EmailNotificationRepository>())
                .AddScoped <TableStorageEmailRepository>()
                .AddScoped <IEmailNotificationRepository, TableStorageEmailRepository>(s => s.GetService <TableStorageEmailRepository>())
                .AddScoped <ITableStorageClient, TableStorageClient>()
                .AddScoped <IMailTemplateManager, MailTemplateManager>()
                .AddScoped <IMailTemplateRepository, MailTemplateRepository>()
                .AddScoped <IMailAttachmentRepository, MailAttachmentRepository>()
                .AddScoped <ITemplateMerge, TemplateMerge>()
                .AddSingleton <IEmailAccountManager, EmailAccountManager>()
                .AddScoped <INotificationProviderFactory, NotificationProviderFactory>()
                .AddScoped <DirectSendNotificationProvider>(s => new DirectSendNotificationProvider(this.Configuration, s.GetService <IEmailService>(), s.GetService <ILogger>(), s.GetService <IEmailManager>()))
                .AddScoped <INotificationProvider, DirectSendNotificationProvider>()
                .AddScoped <MSGraphNotificationProvider>(s => new MSGraphNotificationProvider(this.Configuration, s.GetService <IEmailAccountManager>(), s.GetService <ILogger>(),
                                                                                              Options.Create(this.Configuration.GetSection("MSGraphSetting").Get <MSGraphSetting>()), Options.Create(this.Configuration.GetSection("PollyRetrySetting").Get <RetrySetting>()),
                                                                                              s.GetService <ITokenHelper>(), s.GetService <IMSGraphProvider>(), s.GetService <IEmailManager>()))
                .AddScoped <INotificationProvider, MSGraphNotificationProvider>();
        }
예제 #26
0
        public static IServiceCollection AddApplicationInsights(this IServiceCollection services)
        {
            // Bind to the configuration section registered with
            services.AddOptions <ApplicationInsightsLoggerOptions>()
            .Configure <ILoggerProviderConfiguration <ApplicationInsightsLoggerProvider> >((options, config) =>
            {
                config.Configuration?.Bind(options);
            });

            services.AddSingleton <ITelemetryInitializer, HttpDependenciesParsingTelemetryInitializer>();
            services.AddSingleton <ITelemetryInitializer, WebJobsRoleEnvironmentTelemetryInitializer>();
            services.AddSingleton <ITelemetryInitializer, WebJobsTelemetryInitializer>();
            services.AddSingleton <ITelemetryInitializer, WebJobsSanitizingInitializer>();
            services.AddSingleton <ITelemetryModule, QuickPulseTelemetryModule>();

            services.AddSingleton <IApplicationIdProvider, ApplicationInsightsApplicationIdProvider>();

            services.AddSingleton <ITelemetryModule, DependencyTrackingTelemetryModule>(provider =>
            {
                var dependencyCollector = new DependencyTrackingTelemetryModule();
                var excludedDomains     = dependencyCollector.ExcludeComponentCorrelationHttpHeadersOnDomains;
                excludedDomains.Add("core.windows.net");
                excludedDomains.Add("core.chinacloudapi.cn");
                excludedDomains.Add("core.cloudapi.de");
                excludedDomains.Add("core.usgovcloudapi.net");
                excludedDomains.Add("localhost");
                excludedDomains.Add("127.0.0.1");

                var includedActivities = dependencyCollector.IncludeDiagnosticSourceActivities;
                includedActivities.Add("Microsoft.Azure.ServiceBus");

                return(dependencyCollector);
            });
            services.AddSingleton <ITelemetryModule, AppServicesHeartbeatTelemetryModule>();

            services.AddSingleton <ITelemetryChannel, ServerTelemetryChannel>();
            services.AddSingleton <TelemetryConfiguration>(provider =>
            {
                ApplicationInsightsLoggerOptions options = provider.GetService <IOptions <ApplicationInsightsLoggerOptions> >().Value;
                LoggerFilterOptions filterOptions        = CreateFilterOptions(provider.GetService <IOptions <LoggerFilterOptions> >().Value);

                ITelemetryChannel channel     = provider.GetService <ITelemetryChannel>();
                TelemetryConfiguration config = TelemetryConfiguration.CreateDefault();

                IApplicationIdProvider appIdProvider = provider.GetService <IApplicationIdProvider>();

                SetupTelemetryConfiguration(
                    config,
                    options.InstrumentationKey,
                    options.SamplingSettings,
                    options.SnapshotConfiguration,
                    channel,
                    provider.GetServices <ITelemetryInitializer>(),
                    provider.GetServices <ITelemetryModule>(),
                    appIdProvider,
                    filterOptions);

                return(config);
            });

            services.AddSingleton <TelemetryClient>(provider =>
            {
                TelemetryConfiguration configuration = provider.GetService <TelemetryConfiguration>();
                TelemetryClient client = new TelemetryClient(configuration);

                string assemblyVersion = GetAssemblyFileVersion(typeof(JobHost).Assembly);
                client.Context.GetInternalContext().SdkVersion = $"webjobs: {assemblyVersion}";

                return(client);
            });

            services.AddSingleton <ILoggerProvider, ApplicationInsightsLoggerProvider>();

            return(services);
        }
예제 #27
0
        public static void Run()
        {
            TelemetryConfiguration configuration = new TelemetryConfiguration();

            configuration.InstrumentationKey = "ad4a5cd4-9fb3-4e4e-9b9c-9f43e9939bfa";

            // automatically track dependency calls
            var dependencies = new DependencyTrackingTelemetryModule();

            dependencies.Initialize(configuration);

            // automatically correlate all telemetry data with request
            configuration.TelemetryInitializers.Add(new OperationCorrelationTelemetryInitializer());

            // initialize state for the telemetry size calculation
            ProcessedItems CollectedItems = new ProcessedItems();
            ProcessedItems SentItems      = new ProcessedItems();

            // build telemetry processing pipeline
            configuration.TelemetryProcessorChainBuilder
            // this telemetry processor will be executed first for all telemetry items to calculate the size and # of items
            .Use((next) => { return(new SizeCalculatorTelemetryProcessor(next, CollectedItems)); })

            // this is a standard fixed sampling processor that will let only 10%
            .Use((next) =>
            {
                return(new SamplingTelemetryProcessor(next)
                {
                    IncludedTypes = "Dependency",
                    SamplingPercentage = 10
                });
            })

            // this is a standard adaptive sampling telemetry processor that will sample in/out any telemetry item it receives
            .Use((next) =>
            {
                return(new AdaptiveSamplingTelemetryProcessor(next)
                {
                    ExcludedTypes = "Event",                                     // exclude custom events from being sampled
                    MaxTelemetryItemsPerSecond = 1,                              //default: 5 calls/sec
                    SamplingPercentageIncreaseTimeout = TimeSpan.FromSeconds(1), //default: 2 min
                    SamplingPercentageDecreaseTimeout = TimeSpan.FromSeconds(1), //default: 30 sec
                    EvaluationInterval = TimeSpan.FromSeconds(1),                //default: 15 sec
                    InitialSamplingPercentage = 25                               //default: 100%
                });
            })

            // this telemetry processor will be execuyted ONLY when telemetry is sampled in
            .Use((next) => { return(new SizeCalculatorTelemetryProcessor(next, SentItems)); })
            .Build();

            TelemetryClient client = new TelemetryClient(configuration);

            var iteration = 0;

            while (true)
            {
                using (var operaiton = client.StartOperation <RequestTelemetry>("Process item"))
                {
                    client.TrackEvent("IterationStarted", new Dictionary <string, string>()
                    {
                        { "iteration", iteration.ToString() }
                    });
                    client.TrackTrace($"Iteration {iteration} started", SeverityLevel.Information);

                    try
                    {
                        var task = (new HttpClient()).GetStringAsync("http://bing.com");
                        task.Wait();
                    }
                    catch (Exception exc)
                    {
                        client.TrackException(exc);
                        operaiton.Telemetry.Success = false;
                    }
                    client.StopOperation(operaiton);
                    Console.WriteLine($"Iteration {iteration}. Elapesed time: {operaiton.Telemetry.Duration}. Collected Telemetry: {CollectedItems.size}/{CollectedItems.count}. Sent Telemetry: {SentItems.size}/{SentItems.count}. Ratio: {1.0 * CollectedItems.size / SentItems.size}");
                    iteration++;
                }
            }
        }
예제 #28
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        /// <param name="services">An instance of <see cref="IServiceCollection"/>.</param>
        public void ConfigureServicesCommon(IServiceCollection services)
        {
            _ = services.AddAuthorization(configure =>
            {
                configure.AddPolicy(Constants.AppNameAuthorizePolicy, policy =>
                {
                    policy.Requirements.Add(new AppNameAuthorizeRequirement());
                });
                configure.AddPolicy(Constants.AppAudienceAuthorizePolicy, policy =>
                {
                    policy.Requirements.Add(new AppAudienceAuthorizeRequirement());
                });
            });
            _ = services.AddSingleton <IAuthorizationHandler, AppNameAuthorizePolicyHandler>(s => new AppNameAuthorizePolicyHandler(s.GetService <IHttpContextAccessor>(), this.Configuration));
            _ = services.AddSingleton <IAuthorizationHandler, AppAudienceAuthorizePolicyHandler>(s => new AppAudienceAuthorizePolicyHandler(s.GetService <IHttpContextAccessor>(), this.Configuration));

            _ = services.AddControllers();

            _ = services.AddApplicationInsightsTelemetry();
            _ = services.AddScoped(typeof(ValidateModelAttribute));

            _ = services.AddOptions();
            _ = services.Configure <MSGraphSetting>(this.Configuration.GetSection("MSGraphSetting"));
            _ = services.Configure <MSGraphSetting>(s => s.ClientCredential = this.Configuration["MSGraphSettingClientCredential"]);
            _ = services.Configure <MSGraphSetting>(s => s.ClientId = this.Configuration["MSGraphSettingClientId"]);
            _ = services.Configure <CosmosDBSetting>(this.Configuration.GetSection("CosmosDB"));
            _ = services.Configure <CosmosDBSetting>(s => s.Key = this.Configuration["CosmosDBKey"]);
            _ = services.Configure <CosmosDBSetting>(s => s.Uri = this.Configuration["CosmosDBURI"]);
            _ = services.Configure <StorageAccountSetting>(this.Configuration.GetSection("StorageAccount"));
            _ = services.Configure <StorageAccountSetting>(s => s.ConnectionString = this.Configuration["StorageAccountConnectionString"]);
            _ = services.Configure <UserTokenSetting>(this.Configuration.GetSection("UserTokenSetting"));
            _ = services.Configure <RetrySetting>(this.Configuration.GetSection("RetrySetting"));

            _ = services.AddSingleton <IConfiguration>(this.Configuration);
            _ = services.AddSingleton <IEncryptionService, EncryptionService>();
            _ = services.AddSingleton <IKeyEncryptionKey, CryptographyClient>(cc => new CryptographyClient(new Uri(this.Configuration["KeyVault:RSAKeyUri"]), new DefaultAzureCredential()));

            _ = services.AddTransient <IHttpContextAccessor, HttpContextAccessor>()
                .AddScoped <ICosmosLinqQuery, CustomCosmosLinqQuery>()
                .AddSingleton <ICosmosDBQueryClient, CosmosDBQueryClient>()
                .AddSingleton <ICloudStorageClient, CloudStorageClient>()
                .AddScoped <ITokenHelper, TokenHelper>()
                .AddHttpClient <IMSGraphProvider, MSGraphProvider>();

            _ = services.AddHttpContextAccessor();

            _ = services.AddAuthentication("Bearer").AddJwtBearer(options =>
            {
                options.Authority    = this.Configuration["Authority"];
                options.ClaimsIssuer = this.Configuration["BearerTokenAuthentication:Issuer"];
                options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
                {
                    ValidateIssuer = true,
                    ValidAudiences = this.Configuration["BearerTokenAuthentication:ValidAudiences"].Split(Constants.SplitCharacter),
                };
            });

            ITelemetryInitializer[] itm = new ITelemetryInitializer[1];
            var envInitializer          = new EnvironmentInitializer
            {
                Service         = this.Configuration[Constants.ServiceConfigName],
                ServiceLine     = this.Configuration[Constants.ServiceLineConfigName],
                ServiceOffering = this.Configuration[Constants.ServiceOfferingConfigName],
                ComponentId     = this.Configuration[Constants.ComponentIdConfigName],
                ComponentName   = this.Configuration[Constants.ComponentNameConfigName],
                EnvironmentName = this.Configuration[Constants.EnvironmentName],
                IctoId          = "IctoId",
            };

            itm[0] = envInitializer;

            LoggingConfiguration loggingConfiguration = new LoggingConfiguration
            {
                IsTraceEnabled  = true,
                TraceLevel      = (SeverityLevel)Enum.Parse(typeof(SeverityLevel), this.Configuration["ApplicationInsights:TraceLevel"]),
                EnvironmentName = this.Configuration[Constants.EnvironmentName],
            };

            var tconfig = TelemetryConfiguration.CreateDefault();

            tconfig.InstrumentationKey = this.Configuration["ApplicationInsights:InstrumentationKey"];

            DependencyTrackingTelemetryModule depModule = new DependencyTrackingTelemetryModule();

            depModule.Initialize(tconfig);

            RequestTrackingTelemetryModule requestTrackingTelemetryModule = new RequestTrackingTelemetryModule();

            requestTrackingTelemetryModule.Initialize(tconfig);

            _ = services.AddSingleton <ILogger>(_ => new AILogger(loggingConfiguration, tconfig, itm));
        }
예제 #29
0
        /// <inheritdoc/>
        public override void Configure(IFunctionsHostBuilder builder)
        {
            var azureFuncConfig = builder?.Services?.BuildServiceProvider()?.GetService <IConfiguration>();
            var configBuilder   = new ConfigurationBuilder();

            _ = configBuilder.AddConfiguration(azureFuncConfig);
            var configFolder = Directory.GetParent(Assembly.GetExecutingAssembly().Location).Parent?.FullName;

            _ = configBuilder.SetBasePath(configFolder);
            _ = configBuilder.AddJsonFile("functionSettings.json");
            _ = configBuilder.AddEnvironmentVariables();

            var configuration = configBuilder.Build();

            MaxDequeueCount = configuration.GetSection(ConfigConstants.MaxDequeueCountConfigKey);

            AzureKeyVaultConfigurationOptions azureKeyVaultConfigurationOptions = new AzureKeyVaultConfigurationOptions(configuration[ConfigConstants.KeyVaultUrlConfigKey])
            {
                ReloadInterval = TimeSpan.FromSeconds(double.Parse(configuration[Constants.KeyVaultConfigRefreshDurationSeconds])),
            };

            _             = configBuilder.AddAzureKeyVault(azureKeyVaultConfigurationOptions);
            configuration = configBuilder.Build();
            _             = configBuilder.AddAzureAppConfiguration(options =>
            {
                var settings = options.Connect(configuration[ConfigConstants.AzureAppConfigConnectionstringConfigKey])
                               .Select(KeyFilter.Any, "Common").Select(KeyFilter.Any, "QueueProcessor");
                _ = settings.ConfigureRefresh(refreshOptions =>
                {
                    _ = refreshOptions.Register(key: configuration[ConfigConstants.ForceRefreshConfigKey], refreshAll: true, label: LabelFilter.Null);
                });
            });

            configuration = configBuilder.Build();

            ITelemetryInitializer[] itm = new ITelemetryInitializer[1];
            var envInitializer          = new EnvironmentInitializer
            {
                Service         = configuration[AIConstants.ServiceConfigName],
                ServiceLine     = configuration[AIConstants.ServiceLineConfigName],
                ServiceOffering = configuration[AIConstants.ServiceOfferingConfigName],
                ComponentId     = configuration[AIConstants.ComponentIdConfigName],
                ComponentName   = configuration[AIConstants.ComponentNameConfigName],
                EnvironmentName = configuration[AIConstants.EnvironmentName],
                IctoId          = "IctoId",
            };

            itm[0] = envInitializer;
            LoggingConfiguration loggingConfiguration = new LoggingConfiguration
            {
                IsTraceEnabled  = true,
                TraceLevel      = (SeverityLevel)Enum.Parse(typeof(SeverityLevel), configuration[ConfigConstants.AITraceLelelConfigKey]),
                EnvironmentName = configuration[AIConstants.EnvironmentName],
            };

            var tconfig = TelemetryConfiguration.CreateDefault();

            tconfig.InstrumentationKey = configuration[ConfigConstants.AIInsrumentationConfigKey];

            DependencyTrackingTelemetryModule depModule = new DependencyTrackingTelemetryModule();

            depModule.Initialize(tconfig);

            RequestTrackingTelemetryModule requestTrackingTelemetryModule = new RequestTrackingTelemetryModule();

            requestTrackingTelemetryModule.Initialize(tconfig);

            _ = builder.Services.AddSingleton <ILogger>(_ => new AILogger(loggingConfiguration, tconfig, itm));

            StorageType storageType = (StorageType)Enum.Parse(typeof(StorageType), configuration?[ConfigConstants.StorageType]);

            if (storageType == StorageType.DocumentDB)
            {
                _ = builder.Services.Configure <CosmosDBSetting>(configuration.GetSection(ConfigConstants.CosmosDBConfigSectionKey));
                _ = builder.Services.Configure <CosmosDBSetting>(s => s.Key = configuration[ConfigConstants.CosmosDBKeyConfigKey]);
                _ = builder.Services.Configure <CosmosDBSetting>(s => s.Uri = configuration[ConfigConstants.CosmosDBURIConfigKey]);
                _ = builder.Services.AddScoped <ICosmosLinqQuery, CustomCosmosLinqQuery>();
                _ = builder.Services.AddSingleton <ICosmosDBQueryClient, CosmosDBQueryClient>();
            }

            _ = builder.Services.Configure <StorageAccountSetting>(configuration.GetSection(ConfigConstants.StorageAccountConfigSectionKey));
            _ = builder.Services.Configure <StorageAccountSetting>(s => s.ConnectionString = configuration[ConfigConstants.StorageAccountConnectionStringConfigKey]);
            _ = builder.Services.AddSingleton <IConfiguration>(configuration);
            _ = builder.Services.AddScoped <IRepositoryFactory, RepositoryFactory>();
            _ = builder.Services.AddScoped <EmailNotificationRepository>();
            _ = builder.Services.AddScoped <IEmailNotificationRepository, EmailNotificationRepository>(s => s.GetService <EmailNotificationRepository>());
            _ = builder.Services.AddScoped <TableStorageEmailRepository>();
            _ = builder.Services.AddScoped <IEmailNotificationRepository, TableStorageEmailRepository>(s => s.GetService <TableStorageEmailRepository>());
            _ = builder.Services.AddScoped <ITableStorageClient, TableStorageClient>();
            _ = builder.Services.AddHttpClient <IHttpClientHelper, HttpClientHelper>();
        }
예제 #30
0
        static async Task Main(string[] args)
        {
            var isService = !(Debugger.IsAttached || args.Contains("--console"));

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
                         .Enrich.FromLogContext()
                         .WriteTo.Console()
                         .CreateLogger();

            var builder = new HostBuilder()
                          .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.AddJsonFile("appsettings.json", true);
                config.AddEnvironmentVariables();

                if (args != null)
                {
                    config.AddCommandLine(args);
                }
            })
                          .ConfigureServices((hostContext, services) =>
            {
                _module = new DependencyTrackingTelemetryModule();
                _module.IncludeDiagnosticSourceActivities.Add("MassTransit");

                TelemetryConfiguration configuration = TelemetryConfiguration.CreateDefault();
                configuration.InstrumentationKey     = "6b4c6c82-3250-4170-97d3-245ee1449278";
                configuration.TelemetryInitializers.Add(new HttpDependenciesParsingTelemetryInitializer());

                _telemetryClient = new TelemetryClient(configuration);

                _module.Initialize(configuration);

                services.AddScoped <AcceptOrderActivity>();

                services.AddScoped <RoutingSlipBatchEventConsumer>();

                services.TryAddSingleton(KebabCaseEndpointNameFormatter.Instance);
                services.AddMassTransit(cfg =>
                {
                    cfg.AddConsumersFromNamespaceContaining <SubmitOrderConsumer>();
                    cfg.AddActivitiesFromNamespaceContaining <AllocateInventoryActivity>();

                    cfg.AddSagaStateMachine <OrderStateMachine, OrderState>(typeof(OrderStateMachineDefinition))
                    .MongoDbRepository(r =>
                    {
                        r.Connection   = "mongodb://127.0.0.1";
                        r.DatabaseName = "orders";
                    });

                    cfg.AddBus(ConfigureBus);

                    cfg.AddRequestClient <AllocateInventory>();
                });

                services.AddHostedService <MassTransitConsoleHostedService>();
            })
                          .ConfigureLogging((hostingContext, logging) =>
            {
                logging.AddSerilog(dispose: true);
                logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
            });

            if (isService)
            {
                await builder.UseWindowsService().Build().RunAsync();
            }
            else
            {
                await builder.RunConsoleAsync();
            }

            _telemetryClient?.Flush();
            _module?.Dispose();

            Log.CloseAndFlush();
        }
예제 #31
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        /// <param name="services">An instance of <see cref="IServiceCollection"/>.</param>
        public void ConfigureServicesCommon(IServiceCollection services)
        {
            _ = services.AddAzureAppConfiguration();

            _ = services.AddAuthorization(configure =>
            {
                configure.AddPolicy(ApplicationConstants.AppNameAuthorizePolicy, policy =>
                {
                    policy.Requirements.Add(new AppNameAuthorizeRequirement());
                });
                configure.AddPolicy(ApplicationConstants.AppIdAuthorizePolicy, policy =>
                {
                    policy.Requirements.Add(new AppIdAuthorizeRequirement());
                });
            });
            _ = services.AddSingleton <IAuthorizationHandler, AppNameAuthorizePolicyHandler>(s => new AppNameAuthorizePolicyHandler(s.GetService <IHttpContextAccessor>(), this.Configuration));
            _ = services.AddSingleton <IAuthorizationHandler, AppIdAuthorizePolicyHandler>(s => new AppIdAuthorizePolicyHandler(s.GetService <IHttpContextAccessor>(), this.Configuration));

            _ = services.AddControllers();

            _ = services.AddApplicationInsightsTelemetry();
            _ = services.AddScoped(typeof(ValidateModelAttribute));
            _ = services.AddOptions();

            _ = services.Configure <StorageAccountSetting>(this.Configuration.GetSection(ConfigConstants.StorageAccountConfigSectionKey));
            _ = services.Configure <StorageAccountSetting>(s => s.ConnectionString = this.Configuration[ConfigConstants.StorageAccountConnectionStringConfigKey]);
            _ = services.Configure <UserTokenSetting>(this.Configuration.GetSection(ConfigConstants.UserTokenSettingConfigSectionKey));
            _ = services.Configure <RetrySetting>(this.Configuration.GetSection(ConfigConstants.RetrySettingConfigSectionKey));

            _ = services.AddSingleton <IConfiguration>(this.Configuration);
            _ = services.AddSingleton <IEncryptionService, EncryptionService>();
            _ = services.AddSingleton <IKeyEncryptionKey, CryptographyClient>(cc => new CryptographyClient(new Uri(this.Configuration[ConfigConstants.KeyVaultRSAUriConfigKey]), new DefaultAzureCredential()));

            _ = services.AddTransient <IHttpContextAccessor, HttpContextAccessor>()
                .AddSingleton <ICloudStorageClient, CloudStorageClient>()
                .AddScoped <ITokenHelper, TokenHelper>()
                .AddScoped <IRepositoryFactory, RepositoryFactory>()
                .AddSingleton <IEmailAccountManager, EmailAccountManager>();

            StorageType storageType = (StorageType)Enum.Parse(typeof(StorageType), this.Configuration?[ConfigConstants.StorageType]);

            if (storageType == StorageType.DocumentDB)
            {
                this.ConfigureCosmosDB(services);
            }

            ConfigureStorageAccountServices(services);

            _ = services.AddHttpContextAccessor();

            _ = services.AddAuthentication(ApplicationConstants.BearerAuthenticationScheme).AddJwtBearer(options =>
            {
                options.Authority    = this.Configuration[ConfigConstants.BearerTokenIssuerConfigKey];
                options.ClaimsIssuer = this.Configuration[ConfigConstants.BearerTokenIssuerConfigKey];
                options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
                {
                    ValidateIssuer = false,
                    ValidAudiences = this.Configuration[ConfigConstants.BearerTokenValidAudiencesConfigKey].Split(ApplicationConstants.SplitCharacter),
                };
            });

            ITelemetryInitializer[] itm = new ITelemetryInitializer[1];
            var envInitializer          = new EnvironmentInitializer
            {
                Service         = this.Configuration[AIConstants.ServiceConfigName],
                ServiceLine     = this.Configuration[AIConstants.ServiceLineConfigName],
                ServiceOffering = this.Configuration[AIConstants.ServiceOfferingConfigName],
                ComponentId     = this.Configuration[AIConstants.ComponentIdConfigName],
                ComponentName   = this.Configuration[AIConstants.ComponentNameConfigName],
                EnvironmentName = this.Configuration[AIConstants.EnvironmentName],
                IctoId          = "IctoId",
            };

            itm[0] = envInitializer;

            LoggingConfiguration loggingConfiguration = new LoggingConfiguration
            {
                IsTraceEnabled  = true,
                TraceLevel      = (SeverityLevel)Enum.Parse(typeof(SeverityLevel), this.Configuration[ConfigConstants.AITraceLelelConfigKey]),
                EnvironmentName = this.Configuration[AIConstants.EnvironmentName],
            };

#pragma warning disable CA2000 // Dispose objects before losing scope
            var tconfig = TelemetryConfiguration.CreateDefault();
#pragma warning restore CA2000 // Dispose objects before losing scope
            tconfig.InstrumentationKey = this.Configuration[ConfigConstants.AIInsrumentationConfigKey];

#pragma warning disable CA2000 // Dispose objects before losing scope
            DependencyTrackingTelemetryModule depModule = new DependencyTrackingTelemetryModule();
#pragma warning restore CA2000 // Dispose objects before losing scope
            depModule.Initialize(tconfig);

#pragma warning disable CA2000 // Dispose objects before losing scope
            RequestTrackingTelemetryModule requestTrackingTelemetryModule = new RequestTrackingTelemetryModule();
#pragma warning restore CA2000 // Dispose objects before losing scope
            requestTrackingTelemetryModule.Initialize(tconfig);

            _ = services.AddSingleton <ILogger>(_ => new AILogger(loggingConfiguration, tconfig, itm));
        }