public static void DoesNotAddQuickPulseProcessorToConfigurationIfExplicitlyControlledThroughParameter()
            {
                var exisitingProcessorCount = GetTelemetryProcessorsCountInConfiguration <QuickPulseTelemetryProcessor>(TelemetryConfiguration.Active);
                var serviceOptions          = new ApplicationInsightsServiceOptions();

                serviceOptions.EnableQuickPulseMetricStream = false;
                var services = CreateServicesAndAddApplicationinsightsTelemetry(null, "http://localhost:1234/v2/track/", serviceOptions, false);
                IServiceProvider serviceProvider = services.BuildServiceProvider();
                var telemetryConfiguration       = serviceProvider.GetRequiredService <TelemetryConfiguration>();
                var updatedCount = GetTelemetryProcessorsCountInConfiguration <QuickPulseTelemetryProcessor>(telemetryConfiguration);

                Assert.Equal(updatedCount, exisitingProcessorCount);
            }
            public static void AddsAddaptiveSamplingServiceToTheConfigurationInFullFrameworkWithServiceOptions()
            {
                var exisitingProcessorCount = GetTelemetryProcessorsCountInConfiguration <AdaptiveSamplingTelemetryProcessor>(TelemetryConfiguration.Active);
                var serviceOptions          = new ApplicationInsightsServiceOptions();

                serviceOptions.EnableAdaptiveSampling = true;
                var services = CreateServicesAndAddApplicationinsightsTelemetry(null, "http://localhost:1234/v2/track/", serviceOptions, false);
                IServiceProvider serviceProvider = services.BuildServiceProvider();
                var telemetryConfiguration       = serviceProvider.GetRequiredService <TelemetryConfiguration>();
                var updatedCount = GetTelemetryProcessorsCountInConfiguration <AdaptiveSamplingTelemetryProcessor>(telemetryConfiguration);

                Assert.Equal(updatedCount, exisitingProcessorCount + 1);
            }
Beispiel #3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="T:TelemetryConfigurationOptionsSetup"/> class.
 /// </summary>
 public TelemetryConfigurationOptionsSetup(
     IServiceProvider serviceProvider,
     IOptions <ApplicationInsightsServiceOptions> applicationInsightsServiceOptions,
     IEnumerable <ITelemetryInitializer> initializers,
     IEnumerable <ITelemetryModule> modules,
     IEnumerable <ITelemetryProcessorFactory> telemetryProcessorFactories)
 {
     this.applicationInsightsServiceOptions = applicationInsightsServiceOptions.Value;
     this.initializers = initializers;
     this.modules      = modules;
     this.telemetryProcessorFactories = telemetryProcessorFactories;
     this.telemetryChannel            = serviceProvider.GetService <ITelemetryChannel>();
 }
Beispiel #4
0
        /// <summary>
        /// Read from configuration
        /// Config.json will look like this:
        /// <para>
        ///      "ApplicationInsights": {
        ///          "InstrumentationKey": "11111111-2222-3333-4444-555555555555"
        ///          "TelemetryChannel": {
        ///              EndpointAddress: "http://dc.services.visualstudio.com/v2/track",
        ///              DeveloperMode: true
        ///          }
        ///      }
        /// </para>
        /// Values can also be read from environment variables to support azure web sites configuration:
        /// </summary>
        /// <param name="config">Configuration to read variables from.</param>
        /// <param name="serviceOptions">Telemetry configuration to populate.</param>
        internal static void AddTelemetryConfiguration(IConfiguration config,
                                                       ApplicationInsightsServiceOptions serviceOptions)
        {
            string instrumentationKey = config[InstrumentationKeyForWebSites];

            if (string.IsNullOrWhiteSpace(instrumentationKey))
            {
                instrumentationKey = config[InstrumentationKeyFromConfig];
            }

            if (!string.IsNullOrWhiteSpace(instrumentationKey))
            {
                serviceOptions.InstrumentationKey = instrumentationKey;
            }

            string developerModeValue = config[DeveloperModeForWebSites];

            if (string.IsNullOrWhiteSpace(developerModeValue))
            {
                developerModeValue = config[DeveloperModeFromConfig];
            }

            if (!string.IsNullOrWhiteSpace(developerModeValue))
            {
                bool developerMode = false;
                if (bool.TryParse(developerModeValue, out developerMode))
                {
                    serviceOptions.DeveloperMode = developerMode;
                }
            }

            string endpointAddress = config[EndpointAddressForWebSites];

            if (string.IsNullOrWhiteSpace(endpointAddress))
            {
                endpointAddress = config[EndpointAddressFromConfig];
            }

            if (!string.IsNullOrWhiteSpace(endpointAddress))
            {
                serviceOptions.EndpointAddress = endpointAddress;
            }

            var version = config[VersionKeyFromConfig];

            if (!string.IsNullOrWhiteSpace(version))
            {
                serviceOptions.ApplicationVersion = version;
            }
        }
        public static IServiceCollection AddDFCLogging(this IServiceCollection services, string instrumentationKey)
        {
            var applicationInsightsServiceOptions = new ApplicationInsightsServiceOptions
            {
                InstrumentationKey = instrumentationKey,
            };

            services.AddApplicationInsightsTelemetry(applicationInsightsServiceOptions);

            services.AddScoped <ICorrelationIdProvider, RequestHeaderCorrelationIdProvider>();
            services.AddScoped <ILogService, ApplicationInsightsLogService>();

            return(services);
        }
        /// <summary>
        ///     Configure application Insights
        /// </summary>
        public static void ConfigureAI(this IServiceCollection services)
        {
            ApplicationInsightsServiceOptions aiOptions = new ApplicationInsightsServiceOptions
            {
                EnableDebugLogger = false
            };

            services.AddSingleton <ITelemetryInitializer, CloudRoleInitializer>();
            services.AddApplicationInsightsTelemetry(aiOptions);
            services.ConfigureTelemetryModule <Microsoft.ApplicationInsights.AspNetCore.RequestTrackingTelemetryModule>
                ((req, o) => req.CollectionOptions.TrackExceptions = false);

            services.AddSingleton <ITelemetryClientFactory, TelemetryClientFactory>();
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Dependency Injection of 1OS(AI/1DS) modules
            ApplicationInsightsServiceOptions aiOptions = new ApplicationInsightsServiceOptions
            {
                EnableAdaptiveSampling = false,
                InstrumentationKey     = "key",
            };

            services.AddApplicationInsightsTelemetry(aiOptions);
            services.AddSingleton <ITelemetryInitializer, AdditionalQosPropertiesInitializer>();

            services.AddControllers();
        }
Beispiel #8
0
        private void AddApplicationInsights(IServiceCollection services)
        {
            services.AddSingleton <ITelemetryInitializer>(new RequestBodyTelemetryInitializer(new HttpContextAccessor()));
            services.AddApplicationInsightsTelemetryProcessor <RequestBodyTelemetryFilter>();
            services.AddApplicationInsightsTelemetryProcessor <UserTelemetryFilter>();

            var options = new ApplicationInsightsServiceOptions
            {
                EnableAdaptiveSampling = false,
                InstrumentationKey     = _configuration["ApplicationInsights:InstrumentationKey"]
            };

            services.AddApplicationInsightsTelemetry(options);
        }
Beispiel #9
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();

            var aiOpts = new ApplicationInsightsServiceOptions
            {
                EnableHeartbeat = true
            };
            services.AddApplicationInsightsTelemetry(aiOpts);
            services.AddApplicationInsightsKubernetesEnricher();
            services.AddSingleton<ITelemetryInitializer, CloudRoleTelemetryInitializer>();

            services.AddMvc();
        }
Beispiel #10
0
        public void ConfigureServices(IServiceCollection services)
        {
            var options = new ApplicationInsightsServiceOptions
            {
                InstrumentationKey = Configuration["ApplicationInsights:InstrumentationKey"]
            };

            if (InDevelopmentMode)
            {
                options.DeveloperMode = true;
            }

            // Configure AppInsights based on appsettings.json file
            services.AddApplicationInsightsTelemetry(options);
        }
        /// <summary>
        /// Read configuration from appSettings.json, appsettings.{env.EnvironmentName}.json,
        /// IConfiguation used in an application and EnvironmentVariables.
        /// Bind configuration to ApplicationInsightsServiceOptions.
        /// Values can also be read from environment variables to support azure web sites configuration.
        /// </summary>
        /// <param name="config">Configuration to read variables from.</param>
        /// <param name="serviceOptions">Telemetry configuration to populate.</param>
        internal static void AddTelemetryConfiguration(
            IConfiguration config,
            ApplicationInsightsServiceOptions serviceOptions)
        {
            try
            {
#if NETSTANDARD2_0 || NET461
                config.GetSection(ApplicationInsightsSectionFromConfig).Bind(serviceOptions);
                config.GetSection(TelemetryChannelSectionFromConfig).Bind(serviceOptions);
#endif

                if (config.TryGetValue(primaryKey: ConnectionStringEnvironmentVariable, backupKey: ConnectionStringFromConfig, value: out string connectionStringValue))
                {
                    serviceOptions.ConnectionString = connectionStringValue;
                }

                if (config.TryGetValue(primaryKey: InstrumentationKeyForWebSites, backupKey: InstrumentationKeyFromConfig, value: out string instrumentationKey))
                {
                    serviceOptions.InstrumentationKey = instrumentationKey;
                }

                if (config.TryGetValue(primaryKey: DeveloperModeForWebSites, backupKey: DeveloperModeFromConfig, value: out string developerModeValue))
                {
                    if (bool.TryParse(developerModeValue, out bool developerMode))
                    {
                        serviceOptions.DeveloperMode = developerMode;
                    }
                }

                if (config.TryGetValue(primaryKey: EndpointAddressForWebSites, backupKey: EndpointAddressFromConfig, value: out string endpointAddress))
                {
                    serviceOptions.EndpointAddress = endpointAddress;
                }

                if (config.TryGetValue(primaryKey: VersionKeyFromConfig, value: out string version))
                {
                    serviceOptions.ApplicationVersion = version;
                }
            }
            catch (Exception ex)
            {
#if AI_ASPNETCORE_WEB
                AspNetCoreEventSource.Instance.LogError(ex.ToInvariantString());
#else
                WorkerServiceEventSource.Instance.LogError(ex.ToInvariantString());
#endif
            }
        }
Beispiel #12
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var endpointAddress = new EndpointAddress();

            services.AddSingleton <EndpointAddress>(endpointAddress);

            ApplicationInsightsServiceOptions applicationInsightsOptions = new ApplicationInsightsServiceOptions();

            applicationInsightsOptions.AddAutoCollectedMetricExtractor = false;
            applicationInsightsOptions.DeveloperMode      = true;
            applicationInsightsOptions.EndpointAddress    = endpointAddress.ConnectionString;
            applicationInsightsOptions.InstrumentationKey = "foo";

            services.AddApplicationInsightsTelemetry(applicationInsightsOptions);
            services.AddMvc();
        }
        public static IServiceCollection AddCustomLogger(this IServiceCollection services, IConfiguration configuration)
        {
            string instrumentationkey = configuration.GetValue <string>("Telemetry:InstrumentationKey");
            var    aiOptions          = new ApplicationInsightsServiceOptions
            {
                InstrumentationKey     = instrumentationkey,
                EnableAdaptiveSampling = false,
                EnableAppServicesHeartbeatTelemetryModule = true,
                EnablePerformanceCounterCollectionModule  = true,
                EnableRequestTrackingTelemetryModule      = true,
                EnableDependencyTrackingTelemetryModule   = true
            };

            services.AddApplicationInsightsTelemetry(aiOptions);

            return(services.AddScoped <ICustomLogger, AiLogger>());
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var aiOptions = new ApplicationInsightsServiceOptions();

            // aiOptions.ConnectionString = "InstrumentationKey=457e0aaf-fd2a-4e37-8df1-18c95bb66ca3;IngestionEndpoint=https://westus-0.in.applicationinsights.azure.com/";
            aiOptions.ConnectionString = "InstrumentationKey=37b3dc54-9164-46b5-9b59-2d690c6fb409;IngestionEndpoint=https://westus-0.in.applicationinsights.azure.com/";
            aiOptions.EnableHeartbeat  = false;
            aiOptions.EnablePerformanceCounterCollectionModule = false;
            services.AddApplicationInsightsTelemetry(aiOptions);
            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "standardmetricdemo", Version = "v1"
                });
            });
        }
Beispiel #15
0
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder.ConfigureServices(services =>
            {
                services.AddLogging(loggingBuilder =>
                                    loggingBuilder.AddFilter <ApplicationInsightsLoggerProvider>("Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager", LogLevel.None));

                services.AddSingleton <ITelemetryChannel>(new StubChannel()
                {
                    OnSend = (item) => this.sentItems.Add(item)
                });
                var aiOptions = new ApplicationInsightsServiceOptions();
                aiOptions.AddAutoCollectedMetricExtractor = false;
                aiOptions.EnableAdaptiveSampling          = false;
                aiOptions.InstrumentationKey = "ikey";
                services.AddApplicationInsightsTelemetry(aiOptions);
            });
        }
Beispiel #16
0
        public static IResult <IServiceCollection> AddTelemetry <TProcessor>(
            this IServiceCollection services,
            ApplicationInsightsServiceOptions options
            ) where
        TProcessor : ITelemetryProcessor
        {
            try
            {
                services.AddSingleton <ITelemetryInitializer, Initializer>();
                services.AddApplicationInsightsTelemetry(options);
                services.AddApplicationInsightsTelemetryProcessor <TProcessor>();

                return(services.ToSuccess());
            }
            catch (Exception e)
            {
                return(e.Message.ToFailure <IServiceCollection>());
            }
        }
        /// <summary>
        /// Copy the properties from this <see cref="ApplicationInsightsServiceOptions"/> to a target instance.
        /// </summary>
        /// <param name="target">Target instance to copy properties to.</param>
        internal void CopyPropertiesTo(ApplicationInsightsServiceOptions target)
        {
            if (this.DeveloperMode != null)
            {
                target.DeveloperMode = this.DeveloperMode;
            }

            if (!string.IsNullOrEmpty(this.EndpointAddress))
            {
                target.EndpointAddress = this.EndpointAddress;
            }

            if (!string.IsNullOrEmpty(this.InstrumentationKey))
            {
                target.InstrumentationKey = this.InstrumentationKey;
            }

            if (!string.IsNullOrEmpty(this.ConnectionString))
            {
                target.ConnectionString = this.ConnectionString;
            }

            target.ApplicationVersion           = this.ApplicationVersion;
            target.EnableAdaptiveSampling       = this.EnableAdaptiveSampling;
            target.EnableDebugLogger            = this.EnableDebugLogger;
            target.EnableQuickPulseMetricStream = this.EnableQuickPulseMetricStream;
            target.EnableHeartbeat = this.EnableHeartbeat;
            target.AddAutoCollectedMetricExtractor            = this.AddAutoCollectedMetricExtractor;
            target.EnablePerformanceCounterCollectionModule   = this.EnablePerformanceCounterCollectionModule;
            target.EnableDependencyTrackingTelemetryModule    = this.EnableDependencyTrackingTelemetryModule;
            target.EnableAppServicesHeartbeatTelemetryModule  = this.EnableAppServicesHeartbeatTelemetryModule;
            target.EnableAzureInstanceMetadataTelemetryModule = this.EnableAzureInstanceMetadataTelemetryModule;
            target.EnableDiagnosticsTelemetryModule           = this.EnableDiagnosticsTelemetryModule;

#if NETSTANDARD2_0
            target.EnableEventCounterCollectionModule = this.EnableEventCounterCollectionModule;
#endif
#if AI_ASPNETCORE_WEB
            target.EnableAuthenticationTrackingJavaScript  = this.EnableAuthenticationTrackingJavaScript;
            target.EnableRequestTrackingTelemetryModule    = this.EnableRequestTrackingTelemetryModule;
            target.EnableActiveTelemetryConfigurationSetup = this.EnableActiveTelemetryConfigurationSetup;
#endif
        }
        public static void AddMigrationToolServicesForUnitTests(this IServiceCollection context)
        {
            // Add Fake AI Endpoint
            var aiOptions = new ApplicationInsightsServiceOptions
            {
                EndpointAddress = "http://localhost:8888/v2/track"
            };

            context.AddApplicationInsightsTelemetryWorkerService(aiOptions);
            context.AddSingleton <ITelemetryLogger, TelemetryClientAdapter>();
            // Logging for Unit Tests
            var loggers = new LoggerConfiguration().MinimumLevel.Verbose().Enrich.FromLogContext();

            loggers.WriteTo.Logger(logger => logger
                                   .WriteTo.Debug(restrictedToMinimumLevel: LogEventLevel.Verbose));
            Log.Logger = loggers.CreateLogger();
            Log.Logger.Information("Logger is initialized");
            context.AddLogging(loggingBuilder => loggingBuilder.AddSerilog(dispose: true));
        }
Beispiel #19
0
 /// <summary>
 /// Adds Application Insights services into service collection.
 /// </summary>
 /// <param name="services">The <see cref="IServiceCollection"/> instance.</param>
 /// <param name="options">The options instance used to configure with.</param>
 /// <returns>
 /// The <see cref="IServiceCollection"/>.
 /// </returns>
 public static IServiceCollection AddApplicationInsightsTelemetry(this IServiceCollection services,
                                                                  ApplicationInsightsServiceOptions options)
 {
     services.AddApplicationInsightsTelemetry();
     services.Configure((ApplicationInsightsServiceOptions o) =>
     {
         o.ApplicationVersion     = options.ApplicationVersion;
         o.DeveloperMode          = options.DeveloperMode;
         o.EnableAdaptiveSampling = options.EnableAdaptiveSampling;
         o.EnableAuthenticationTrackingJavaScript = options.EnableAuthenticationTrackingJavaScript;
         o.EnableDebugLogger            = options.EnableDebugLogger;
         o.EnableQuickPulseMetricStream = options.EnableQuickPulseMetricStream;
         o.EndpointAddress    = options.EndpointAddress;
         o.InstrumentationKey = options.InstrumentationKey;
         o.EnableHeartbeat    = options.EnableHeartbeat;
         o.AddAutoCollectedMetricExtractor = options.AddAutoCollectedMetricExtractor;
     });
     return(services);
 }
Beispiel #20
0
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder.ConfigureServices(services =>
            {
                services.AddSingleton <ITelemetryChannel>(new StubChannel()
                {
                    OnSend = (item) => this.sentItems.Add(item)
                });
                var aiOptions = new ApplicationInsightsServiceOptions();
                aiOptions.AddAutoCollectedMetricExtractor = false;
                aiOptions.EnableAdaptiveSampling          = false;
                aiOptions.InstrumentationKey = "ikey";
                services.AddApplicationInsightsTelemetry(aiOptions);

                // Build the service provider.
                var sp = services.BuildServiceProvider();
                var tc = sp.GetRequiredService <TelemetryClient>();
            });
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var mvcBuilder = services.AddControllersWithViews().AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.ContractResolver     = new DefaultContractResolver();
                options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
            });

#if DEBUG
            if (Env.IsDevelopment())
            {
                mvcBuilder.AddRazorRuntimeCompilation();
            }
#endif

            var aiOptions = new ApplicationInsightsServiceOptions
            {
                EnableAdaptiveSampling = false
            };
            services.AddApplicationInsightsTelemetry(aiOptions);

            services.AddDbContext <BunningsProductCatalogContext>(options =>
                                                                  options.UseLazyLoadingProxies().UseSqlServer(
                                                                      Configuration.GetConnectionString("BunningsProductCatalogContext")));

            services.AddMvcCore().AddNewtonsoftJson(
                options => options.SerializerSettings.ReferenceLoopHandling =
                    ReferenceLoopHandling.Ignore);

            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
            services.AddScoped <IUnitOfWork, UnitOfWork>();
            services.AddScoped <IRepositoryProvider, RepositoryProvider>();
            services.AddSingleton <RepositoryFactories>();
            services.AddScoped <IProductService, ProductService>();
            services.AddScoped <ICompanyService, CompanyService>();
            services.AddScoped <ICompanyProductService, CompanyProductService>();
            services.AddScoped <ICompanyProductBarcodeService, CompanyProductBarcodeService>();
            services.AddScoped <ISupplierService, SupplierService>();
            services.AddScoped <ICsvService <ImportSupplierDto>, CsvService <ImportSupplierDto> >();
            services.AddScoped <ICsvService <ImportCompanyProductDto>, CsvService <ImportCompanyProductDto> >();
            services.AddScoped <ICsvService <ImportCompanyProductBarcodeDto>, CsvService <ImportCompanyProductBarcodeDto> >();
            services.AddScoped <ICsvService <ProductCatalogDto>, CsvService <ProductCatalogDto> >();
        }
        private static ApplicationInsightsServiceOptions setTelemetryClientOptions(ApplicationInsightsServiceOptions aiOptions, string appInsightsKey)
        {
            aiOptions.InstrumentationKey = appInsightsKey;

            //aiOptions.InstrumentationKey = _configuration.GetValue<string>("ApplicationInsights_InstrumentationKey");

            // Disables adaptive sampling.
            aiOptions.EnableAdaptiveSampling = false;

            // Collects Requests Telemetry
            aiOptions.EnableRequestTrackingTelemetryModule = true;
            // よくわからんけど有効
            aiOptions.EnableEventCounterCollectionModule = true;
            // Collects Depdndency Telemetry
            aiOptions.EnableDependencyTrackingTelemetryModule = true;
            // Disables QuickPulse (Live Metrics stream).
            aiOptions.EnableQuickPulseMetricStream = false;

            return(aiOptions);
        }
Beispiel #23
0
        private static void SetupAppInsights(IConfiguration configuration, IServiceCollection services)
        {
            ApplicationInsightsServiceOptions aiOptions = new ApplicationInsightsServiceOptions();
            var appInsightsDependencyConfigValue        = configuration.GetValue <bool>("ApplicationInsights:EnableDependencyTrackingTelemetryModule");

            //dependency tracking is disabled by default as it is quite expensive
            aiOptions.EnableDependencyTrackingTelemetryModule = appInsightsDependencyConfigValue;

            //by default instrumentation key is taken from config
            //Alternatively, specify the instrumentation key in either of the following environment variables.
            //APPINSIGHTS_INSTRUMENTATIONKEY or ApplicationInsights:InstrumentationKey
            services.AddApplicationInsightsTelemetryWorkerService(aiOptions);

            var appInsightsAuthApiKey = configuration.GetValue <string>("ApplicationInsights:AuthenticationApiKey");

            if (!string.IsNullOrWhiteSpace(appInsightsAuthApiKey))
            {
                services.ConfigureTelemetryModule <QuickPulseTelemetryModule> ((module, o) =>
                                                                               module.AuthenticationApiKey = appInsightsAuthApiKey);
            }
        }
Beispiel #24
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers(o => o.AllowEmptyInputInBodyModelBinding = true);
            services.AddRazorPages().AddRazorPagesOptions(options => options.Conventions.AllowAnonymousToPage("/"));

            services.AddAuthentication("BasicAuthentication").AddScheme <AuthenticationSchemeOptions, BasicAuthHandler>("BasicAuthentication", null);

            services.AddHttpClient();

            var appInsightOptions = new ApplicationInsightsServiceOptions
            {
                DeveloperMode = true,
                EnableEventCounterCollectionModule = false,
            };

            services.AddApplicationInsightsTelemetry(appInsightOptions);

            services.AddScoped <IGitHubClient, GitHubClient>(sp => {
                return(new GitHubClient(new ProductHeaderValue("Covid19-ita-Report-api"))
                {
                    Credentials = new Credentials(Configuration.GetSection("GitHubConfig:GitHubApiKey").Value)
                });
            });
            services.AddSingleton <CosmosSerializer, CosmosCovidSerializer>();
            services.AddSingleton <ICosmosClientFactory, CosmosClientFactory>();
            services.AddSingleton <ICosmosServiceFactory, CosmosServiceFactory>();
            services.AddScoped <IDataCollectorSerializer, JsonDataCollectorSerializer>();
            services.AddScoped <IDataCollectorSerializer, CsvDataCollectorSerializer>();
            services.AddScoped <IDataCollector, DataCollector>();
            services.AddScoped <ICosmosRepository, CosmosRepository>();
            services.AddTransient <DbConnection>(sp => new SqlConnection(Configuration.GetConnectionString("covidDb")));

            // Register configurations
            services.Configure <CosmosRepositoryOptions>(o => o.Databases = Configuration.GetSection("cosmos:databases")
                                                                            .GetChildren().ToDictionary(d => d.Key, d => d.GetSection("containers")
                                                                                                        .GetChildren()
                                                                                                        .ToDictionary(c => c.Key, c => c.Value)));
            services.Configure <CosmosClientFactoryOptions>(Configuration.GetSection("cosmos"));
            services.Configure <GitHubConfig>(Configuration.GetSection("GitHubConfig"));
        }
Beispiel #25
0
        public void TestRequestWithNonW3CCompatibleNonHierrachicalRequestIdHeader()
        {
            IWebHostBuilder Config(IWebHostBuilder builder)
            {
                return(builder.ConfigureServices(services =>
                {
                    var aiOptions = new ApplicationInsightsServiceOptions();
                    // disable Dependency tracking (i.e. header injection)
                    aiOptions.EnableDependencyTrackingTelemetryModule = false;
                    services.AddApplicationInsightsTelemetry(aiOptions);
                }));
            }

            using (var server = new InProcessServer(assemblyName, this.output, Config))
            {
                const string RequestPath = "/api/values";

                var expectedRequestTelemetry = new RequestTelemetry();
                expectedRequestTelemetry.Name         = "GET Values/Get";
                expectedRequestTelemetry.ResponseCode = "200";
                expectedRequestTelemetry.Success      = true;
                expectedRequestTelemetry.Url          = new Uri(server.BaseHost + RequestPath);

                var headers = new Dictionary <string, string>
                {
                    // Request-ID Correlation Header
                    { "Request-Id", "somerandomidnotinanyformat" },
                    { "Request-Context", "appId=value" },
                    { "Correlation-Context", "k1=v1,k2=v2" }
                };

                var actualRequest = this.ValidateRequestWithHeaders(server, RequestPath, headers, expectedRequestTelemetry);

                Assert.NotEqual("noncompatible", actualRequest.tags["ai.operation.id"]);
                Assert.Contains("somerandomidnotinanyformat", actualRequest.tags["ai.operation.parentId"]);
                Assert.Equal("somerandomidnotinanyformat", actualRequest.data.baseData.properties["ai_legacyRootId"]);
                Assert.Equal("v1", actualRequest.data.baseData.properties["k1"]);
                Assert.Equal("v2", actualRequest.data.baseData.properties["k2"]);
            }
        }
Beispiel #26
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var appInsightsConnectionString = Environment.GetEnvironmentVariable(AppInsightsConnectionStringEnvironmentVariableName);

            if (!string.IsNullOrEmpty(appInsightsConnectionString))
            {
                var options = new ApplicationInsightsServiceOptions
                {
                    EnableAdaptiveSampling = false,
                    EnablePerformanceCounterCollectionModule = false
                };
                services.AddApplicationInsightsTelemetry(options);
            }

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
            {
                options.LoginPath  = "/login";
                options.LogoutPath = "/logout";
            });
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            });

            services.AddSingleton <IArticlesRepository, DiskArticlesRepository>();
            services.AddScoped <IArticlesService, ArticlesService>();

            services.AddSingleton <IArticleInfoRepository, DiskArticleInfoRepository>();
            services.AddSingleton <ITagsRepository, DiskTagsRepository>();

            services.AddSingleton <IPagesRepository, DiskPagesRepository>();
            services.AddScoped <IPagesService, PagesService>();

            services.AddSingleton <ISiteConfigurationRepository, DiskSiteConfigurationRepository>();
            services.AddSingleton <IImagesRepository, DiskImagesRepository>();

            services.AddRazorPages();
        }
Beispiel #27
0
        public void VerifyAddAIWorkerServiceRespectsAIOptions()
        {
            var services = new ServiceCollection();

            // ACT
            var aiOptions = new ApplicationInsightsServiceOptions();

            aiOptions.AddAutoCollectedMetricExtractor = false;
            aiOptions.EnableAdaptiveSampling          = false;
            aiOptions.EnableQuickPulseMetricStream    = false;
            aiOptions.InstrumentationKey = "keyfromaioption";
            services.AddApplicationInsightsTelemetryWorkerService(aiOptions);

            // VALIDATE
            IServiceProvider serviceProvider = services.BuildServiceProvider();
            var telemetryConfiguration       = serviceProvider.GetRequiredService <TelemetryConfiguration>();

            Assert.Equal("keyfromaioption", telemetryConfiguration.InstrumentationKey);
            Assert.DoesNotContain(telemetryConfiguration.DefaultTelemetrySink.TelemetryProcessors, proc => proc.GetType().Name.Contains("AutocollectedMetricsExtractor"));
            Assert.DoesNotContain(telemetryConfiguration.DefaultTelemetrySink.TelemetryProcessors, proc => proc.GetType().Name.Contains("AdaptiveSamplingTelemetryProcessor"));
            Assert.DoesNotContain(telemetryConfiguration.DefaultTelemetrySink.TelemetryProcessors, proc => proc.GetType().Name.Contains("QuickPulseTelemetryProcessor"));
        }
        public void GivenCustomConfiguration_ThenUseCustomConfiguration()
        {
            // Arrange

            var configuration = new ConfigurationBuilder()
                                .AddInMemoryCollection(new Dictionary <string, string>
            {
                { "ApplicationInsights:ApplicationVersion", "test-local" },
                { "ApplicationInsights:EnableAdaptiveSampling", "False" },
                { "ApplicationInsights:TelemetryChannel:DeveloperMode", "true" },
                { "ApplicationInsights:InstrumentationKey", "instrumentation-key" }
            })
                                .Build();

            // Act

            var webHost = WebHost
                          .CreateDefaultBuilder()
                          .UseStartup <ConfigurableStartup>()
                          .UseConfiguration(configuration)
                          .Build();

            // Assert

            var configuredOptions = webHost.Services.GetService <IOptions <ApplicationInsightsServiceOptions> >();

            Assert.NotNull(configuredOptions.Value);

            var expectedOptions = new ApplicationInsightsServiceOptions
            {
                EnableAdaptiveSampling = false,
                ApplicationVersion     = "test-local",
                DeveloperMode          = true,
                InstrumentationKey     = "instrumentation-key"
            };

            configuredOptions.Value.Should().BeEquivalentTo(expectedOptions);
        }
        public void TestRequestWithNoCorrelationHeaders()
        {
            IWebHostBuilder Config(IWebHostBuilder builder)
            {
                return(builder.ConfigureServices(services =>
                {
                    var aiOptions = new ApplicationInsightsServiceOptions();
                    // disable Dependency tracking (i.e. header injection)
                    aiOptions.EnableDependencyTrackingTelemetryModule = false;
                    services.AddApplicationInsightsTelemetry(aiOptions);
                }));
            }

            using (var server = new InProcessServer(assemblyName, this.output, Config))
            {
                const string RequestPath = "/api/values/1";

                var expectedRequestTelemetry = new RequestTelemetry();
                expectedRequestTelemetry.Name         = "GET Values/Get [id]";
                expectedRequestTelemetry.ResponseCode = "200";
                expectedRequestTelemetry.Success      = true;
                expectedRequestTelemetry.Url          = new System.Uri(server.BaseHost + RequestPath);

                Dictionary <string, string> requestHeaders = new Dictionary <string, string>()
                {
                    // No Request-ID, No TraceParent
                    { "Request-Context", "appId=value" },
                };

                var item = this.ValidateBasicRequest(server, RequestPath, expectedRequestTelemetry);

                Assert.Equal(32, item.tags["ai.operation.id"].Length);
                Assert.True(Regex.Match(item.tags["ai.operation.id"], @"[a-z][0-9]").Success);

                Assert.False(item.tags.ContainsKey("ai.operation.parentId"));
            }
        }
Beispiel #30
0
            public static void AppApplicationInsightsTelemetryFromApplicationInsightsServiceOptionsCopiesAllSettings()
            {
                ServiceCollection services = ApplicationInsightsExtensionsTests.GetServiceCollectionWithContextAccessor();
                ApplicationInsightsServiceOptions options = new ApplicationInsightsServiceOptions()
                {
                    ApplicationVersion     = "test",
                    DeveloperMode          = true,
                    EnableAdaptiveSampling = false,
                    EnableAuthenticationTrackingJavaScript = false,
                    EnableDebugLogger            = true,
                    EnableQuickPulseMetricStream = false,
                    EndpointAddress    = "http://test",
                    EnableHeartbeat    = false,
                    InstrumentationKey = "test"
                };

                services.AddApplicationInsightsTelemetry(options);
                ApplicationInsightsServiceOptions servicesOptions = null;

                services.Configure((ApplicationInsightsServiceOptions o) =>
                {
                    servicesOptions = o;
                });

                IServiceProvider       serviceProvider        = services.BuildServiceProvider();
                TelemetryConfiguration telemetryConfiguration = serviceProvider.GetTelemetryConfiguration();

                Type optionsType = typeof(ApplicationInsightsServiceOptions);

                PropertyInfo[] properties = optionsType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
                Assert.True(properties.Length > 0);
                foreach (PropertyInfo property in properties)
                {
                    Assert.Equal(property.GetValue(options).ToString(), property.GetValue(servicesOptions).ToString());
                }
            }