public static IServiceCollection AddApplicationInsights(this IServiceCollection services, IConfiguration configuration)
        {
            // Register the settings for "ApplicationInsights" section as a service for injection from DI container
            var applicationInsightsSettings = new ApplicationInsightsSettings();

            configuration.Bind(ApplicationInsightsSettings.ApplicationInsightsSectionKey, applicationInsightsSettings);
            services.AddSingleton(applicationInsightsSettings);

            // Use telemetry initializers when you want to enrich telemetry with additional information
            services.AddSingleton <ITelemetryInitializer, CloudRoleTelemetryInitializer>();

            // Remove a specific built-in telemetry initializer
            var telemetryInitializerToRemove = services.FirstOrDefault <ServiceDescriptor>
                                                   (t => t.ImplementationType == typeof(AspNetCoreEnvironmentTelemetryInitializer));

            if (telemetryInitializerToRemove != null)
            {
                services.Remove(telemetryInitializerToRemove);
            }

            // You can add custom telemetry processors to TelemetryConfiguration by using the extension method AddApplicationInsightsTelemetryProcessor on IServiceCollection.
            // You use telemetry processors in advanced filtering scenarios
            services.AddApplicationInsightsTelemetryProcessor <StaticWebAssetsTelemetryProcessor>();

            // The following line enables Application Insights telemetry collection.
            services.AddApplicationInsightsTelemetry();

            return(services);
        }
Esempio n. 2
0
        private static IConfiguration BuildAppConfiguration(IConfigurationBuilder builder, WebHostBuilderContext hostingContext)
        {
            var            environment   = hostingContext.HostingEnvironment;
            IConfiguration configuration = builder.Build();

            if (environment.IsDevelopment())
            {
                builder.AddUserSecrets(Assembly.Load(new AssemblyName(environment.ApplicationName)), optional: true);
            }

            // TODO : Work out why the instrumentation key below is ignored, the correct instrumentation key seems to be only
            // set if it is present in the appsettings.json or is passed to the overloaded extensions method on IWebHostBuilder called UseApplicationInsights.
            var applicationInsightsSettings = new ApplicationInsightsSettings();

            configuration.BindOrThrow("ApplicationInsights", applicationInsightsSettings);
            builder.AddApplicationInsightsSettings(developerMode: environment.IsDevelopment(), instrumentationKey: applicationInsightsSettings.InstrumentationKey);

            KeyVaultSettings keyVaultSettings = new KeyVaultSettings();

            configuration.BindOrThrow("KeyVaultSettings", keyVaultSettings);

            builder.AddAzureKeyVault(
                keyVaultSettings.DnsName,
                keyVaultSettings.AppUserClientId,
                keyVaultSettings.AppUserClientSecret);

            return(configuration);
        }
Esempio n. 3
0
        public async Task InvokeErrorHandler_ExceptionTest()
        {
            var applicationInsightsMock = new ApplicationInsightsSettings()
            {
                InstrumentationKey = "118047f1-b165-4bff-9471-e87fd3fe167c"
            };

            _applicationInsightsMock.Setup(x => x.Value)
            .Returns(applicationInsightsMock);

            _webHostEnvironmentMock.Setup(x => x.EnvironmentName)
            .Returns("Development");

            var httpContext             = new DefaultHttpContext().Request.HttpContext;
            var exceptionHandlerFeature = new ExceptionHandlerFeature()
            {
                Error = new Exception("Mock error exception")
            };

            httpContext.Features.Set <IExceptionHandlerFeature>(exceptionHandlerFeature);

            var errorHandlerMiddleware = new ErrorHandlerMiddleware(_applicationInsightsMock.Object, _webHostEnvironmentMock.Object);
            await errorHandlerMiddleware.Invoke(httpContext);

            Assert.NotNull(errorHandlerMiddleware);
        }
Esempio n. 4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // For use in ReadUsingOptionsPattern page
            services.Configure <PositionOptions>(
                Configuration.GetSection(PositionOptions.Position)
                );

            // Register the settings for "OAuthSettings" section
            var settings = new OAuthSettings();

            Configuration.Bind(OAuthSettings.OAuthSection, settings);
            services.AddSingleton(settings);

            // ProjectService Registration
            services.AddScoped <IProjectService, ProjectService>();

            // ProjectRepository Registration
            services.AddScoped <IProjectRepository, ProjectRepository>();

            // Register the ApplicationDbContext
            // Create the database by following steps that use migrations to create it:
            // - dotnet tool install --global dotnet-ef
            // - dotnet add package Microsoft.EntityFrameworkCore.Design
            // - dotnet ef migrations add InitialCreate
            // - dotnet ef database update
            // This installs dotnet ef and the design package which is required to run the command on a project.
            // The migrations command scaffolds a migration to create the initial set of tables for the model.
            // The database update command creates the database and applies the new migration to it.
            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(Configuration.GetConnectionString("Default")));

            // The following line enables Application Insights telemetry collection.
            services.AddApplicationInsightsTelemetry();

            // Register the settings for "ApplicationInsights" section as a service for injection from DI container
            var applicationInsightsSettings = new ApplicationInsightsSettings();

            Configuration.Bind(ApplicationInsightsSettings.ApplicationInsightsSectionKey, applicationInsightsSettings);
            services.AddSingleton(applicationInsightsSettings);

            // Use telemetry initializers when you want to enrich telemetry with additional information
            services.AddSingleton <ITelemetryInitializer, CloudRoleTelemetryInitializer>();

            // Remove a specific built-in telemetry initializer
            var telemetryInitializerToRemove = services.FirstOrDefault <ServiceDescriptor>
                                                   (t => t.ImplementationType == typeof(AspNetCoreEnvironmentTelemetryInitializer));

            if (telemetryInitializerToRemove != null)
            {
                services.Remove(telemetryInitializerToRemove);
            }

            // You can add custom telemetry processors to TelemetryConfiguration by using the extension method AddApplicationInsightsTelemetryProcessor on IServiceCollection.
            // You use telemetry processors in advanced filtering scenarios
            services.AddApplicationInsightsTelemetryProcessor <StaticWebAssetsTelemetryProcessor>();

            services.AddRazorPages();
        }
        public static ITelemetry Enrich(this ITelemetry telemetry, ApplicationInsightsSettings settings)
        {
            if (!String.IsNullOrWhiteSpace(settings.CloudRoleName))
            {
                telemetry.Context.Cloud.RoleName = settings.CloudRoleName;
            }

            return(telemetry);
        }
Esempio n. 6
0
        public static void Main(string[] args)
        {
            var config = new ConfigurationBuilder()
                         .AddJsonFile("appsettings.json", optional: false)
                         .Build();
            ApplicationInsightsSettings app_insights_settings = new ApplicationInsightsSettings();

            config.GetSection("ApplicationInsights").Bind(app_insights_settings);
            CreateWebHostBuilder(args, app_insights_settings).Build().Run();
        }
        public static void AddApplicationInsights(this IServiceCollection services,
                                                  ApplicationInsightsSettings applicationInsightsSettings)
        {
            services.AddSingleton(b =>
            {
                var telemetryConfiguration = new TelemetryConfiguration(applicationInsightsSettings.InstrumentationKey);
                return(new QuickPulseTelemetryModuleBuilder(telemetryConfiguration).Build());
            });

            // init never resolved singleton
            services.BuildServiceProvider().GetService <QuickPulseTelemetryModule>();
        }
        public static IServiceCollection AddApplicationInsights(this IServiceCollection services, IConfiguration configuration)
        {
            var settings = new ApplicationInsightsSettings(configuration);

            if (settings.Enabled)
            {
                services
                .AddApplicationInsightsTelemetry(settings.Key);
            }

            return(services);
        }
Esempio n. 9
0
        public async Task InvokeErrorHandler_NotExceptionTestAsync()
        {
            var applicationInsightsMock = new ApplicationInsightsSettings("118047f1-b165-4bff-9471-e87fd3fe167c");

            _applicationInsightsMock.Setup(x => x.Value)
            .Returns(applicationInsightsMock);

            _hostingEnvironmentMock.Setup(x => x.EnvironmentName)
            .Returns("Development");

            var httpContext = new DefaultHttpContext().Request.HttpContext;

            var errorHandlerMiddleware = new ErrorHandlerMiddleware(_applicationInsightsMock.Object, _hostingEnvironmentMock.Object);
            await errorHandlerMiddleware.Invoke(httpContext);

            Assert.NotNull(errorHandlerMiddleware);
        }
        public void Enrich_CloudRoleNameIsConfigured_EnrichesTelemetryWithCloudRoleName()
        {
            // Arrange

            var settings = new ApplicationInsightsSettings
            {
                CloudRoleName = "Some Role",
            };

            var telemetry = new TraceTelemetry();

            // Act

            telemetry.Enrich(settings);

            // Assert

            Assert.AreEqual("Some Role", telemetry.Context.Cloud.RoleName);
        }
        public void Enrich_CloudRoleNameIsNotConfigured_DoesNotEnrichTelemetryWithCloudRoleName(string missingValue)
        {
            // Arrange

            var settings = new ApplicationInsightsSettings
            {
                CloudRoleName = missingValue,
            };

            var telemetry = new TraceTelemetry();

            // Act

            telemetry.Enrich(settings);

            // Assert

            Assert.IsNull(telemetry.Context.Cloud.RoleName);
        }
Esempio n. 12
0
 public static IWebHostBuilder CreateWebHostBuilder(string[] args,
                                                    ApplicationInsightsSettings app_insights_settings) =>
 WebHost.CreateDefaultBuilder(args)
 .UseIIS()
 .UseStartup <Startup>()
 .ConfigureLogging(
     builder =>
 {
     // Providing an instrumentation key here is required if you're using
     // standalone package Microsoft.Extensions.Logging.ApplicationInsights
     // or if you want to capture logs from early in the application startup
     // pipeline from Startup.cs or Program.cs itself.
     builder.AddApplicationInsights(app_insights_settings.InstrumentationKey);
     // Optional: Apply filters to control what logs are sent to Application Insights.
     // The following configures LogLevel Information or above to be sent to
     // Application Insights for all categories.
     builder.AddFilter <Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>
         ("", LogLevel.Information);
 }
     );
Esempio n. 13
0
        public async Task InvokeLogHandler_Test()
        {
            var applicationInsightsMock = new ApplicationInsightsSettings()
            {
                InstrumentationKey = "118047f1-b165-4bff-9471-e87fd3fe167c"
            };

            _applicationInsightsMock.Setup(x => x.Value)
            .Returns(applicationInsightsMock);

            var httpContext = new DefaultHttpContext().Request.HttpContext;

            var logMiddleware = new LogMiddleware(async(innerHttpContext) =>
            {
                await innerHttpContext.Response.WriteAsync("Response body mock");
            }, _applicationInsightsMock.Object);

            await logMiddleware.Invoke(httpContext, _identityServiceMock.Object);

            Assert.NotNull(logMiddleware);
        }
 public ErrorHandlerMiddleware(IOptions <ApplicationInsightsSettings> options, IWebHostEnvironment webHostEnvironment)
 {
     _applicationInsights = options.Value;
     _webHostEnvironment  = webHostEnvironment;
 }
Esempio n. 15
0
 public LogMiddleware(RequestDelegate next, IOptions <ApplicationInsightsSettings> options)
 {
     _next = next;
     _applicationInsights = options.Value;
 }
 public LogMiddleware(RequestDelegate next, IOptions <ApplicationInsightsSettings> options, IWebHostEnvironment environment)
 {
     _next = next;
     _applicationInsights = options.Value;
     _environment         = environment;
 }
Esempio n. 17
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, TelemetryConfiguration configuration, ApplicationInsightsSettings applicationInsightsSettings)
        {
            configuration.DisableTelemetry = applicationInsightsSettings.DisableTelemetry;

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
            });
        }
Esempio n. 18
0
 public CloudRoleNameTelemetryInitializer(IOptions <ApplicationInsightsSettings> options)
 {
     this.settings = options?.Value ?? throw new ArgumentNullException(nameof(options));
 }
Esempio n. 19
0
 public ErrorHandlerMiddleware(IOptions <ApplicationInsightsSettings> options, IHostingEnvironment hostingEnvironment)
 {
     _applicationInsights = options.Value;
     _hostingEnvironment  = hostingEnvironment;
 }