Esempio n. 1
0
        private void ConfigureApplicationInisghts(IServiceCollection services)
        {
            var aiOptions = new Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions
            {
                EnableAuthenticationTrackingJavaScript = false,
                EnableHeartbeat                 = false,
                EnableAdaptiveSampling          = false,
                AddAutoCollectedMetricExtractor = false,
                EnableQuickPulseMetricStream    = false,
                InstrumentationKey              = Configuration["ApplicationInsights:InstrumentationKey"]
            };

            aiOptions.RequestCollectionOptions.TrackExceptions = true;
            services.AddApplicationInsightsTelemetry(aiOptions);
            foreach (var mod in new[] {
                typeof(PerformanceCollectorModule),
                typeof(QuickPulseTelemetryModule),
                typeof(AppServicesHeartbeatTelemetryModule)
            })
            {
                var modSvc = services.FirstOrDefault(t => t.ImplementationType == mod);
                if (modSvc != null)
                {
                    services.Remove(modSvc);
                }
            }
            services.AddApplicationInsightsTelemetryProcessor <RequestFilterTelemetryProcessor>();
        }
Esempio n. 2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddServiceProfiler(); // Add this line of code to Enable Profiler
            //services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Latest);
            services.AddMvc(options => options.EnableEndpointRouting = false);
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Limone API", Version = "v1"
                });
                // Set the comments path for the Swagger JSON and UI.
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
            });

            Console.WriteLine($"APPINSIGHTS_KEY={Environment.GetEnvironmentVariable("APPINSIGHTS_KEY")}");
            var appInsightsKey = Environment.GetEnvironmentVariable("APPINSIGHTS_KEY");
            var aiOptions      = new Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions();

            aiOptions.EnableAdaptiveSampling = false;
            aiOptions.InstrumentationKey     = appInsightsKey;
            services.AddApplicationInsightsTelemetry(aiOptions);
            services.AddScoped <ServiceBusSender>();
        }
        /// <summary>
        /// Add and configure any of the middleware
        /// </summary>
        /// <param name="services">Collection of service descriptors</param>
        /// <param name="configuration">Configuration of the application</param>
        public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
        {
            var aiOptions = new Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions();

            var config = ConfigHelper.GetConfig();

            string instrumentationKey           = config["ApplicationInsights:InstrumentationKey"];
            bool   enableQuickPulseMetricStream = Convert.ToBoolean(config["ApplicationInsights:Settings:EnableQuickPulseMetricStream"]);
            bool   enableAdaptiveSampling       = Convert.ToBoolean(config["ApplicationInsights:Settings:EnableAdaptiveSampling"]);
            bool   enableHeartbeat = Convert.ToBoolean(config["ApplicationInsights:Settings:EnableHeartbeat"]);
            bool   addAutoCollectedMetricExtractor = Convert.ToBoolean(config["ApplicationInsights:Settings:AddAutoCollectedMetricExtractor"]);

            // Configures instrumentation key
            aiOptions.InstrumentationKey = instrumentationKey;

            // Disables or enables Application Insights features
            aiOptions.EnableQuickPulseMetricStream = enableQuickPulseMetricStream;
            aiOptions.EnableAdaptiveSampling       = enableAdaptiveSampling;
            aiOptions.EnableHeartbeat = enableHeartbeat;
            aiOptions.AddAutoCollectedMetricExtractor = addAutoCollectedMetricExtractor;

            if (string.IsNullOrEmpty(aiOptions.InstrumentationKey))
            {
                // Make sure InsutrmentationKey is not empty
                aiOptions.InstrumentationKey = "11111111-2222-3333-4444-555555555555";
            }
            services.AddApplicationInsightsTelemetry(aiOptions);
        }
Esempio n. 4
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            try
            {
                var appiInsightsOptions = new Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions();
                // Disables adaptive sampling
                appiInsightsOptions.EnableAdaptiveSampling = false;
                // Disables QuickPulse (Live Metrics stream)
                appiInsightsOptions.EnableQuickPulseMetricStream = false;

                services.AddSingleton <IConfiguration>(Configuration)
                .AddSingleton <IHttpClient, StandardHttpClient>()
                .AddSingleton <IHttpContextAccessor, HttpContextAccessor>()
                .AddSingleton <IAuthToken, AuthToken>()
                .AddApplicationInsightsTelemetry(appiInsightsOptions)
                .AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

                // Register the Swagger generator, defining one or more Swagger documents
                services.AddSwaggerGen(c =>
                {
                    c.SwaggerDoc("v1", new Info {
                        Title = "Frontend API", Version = "v1"
                    });
                });

                var container = new ContainerBuilder();
                container.Populate(services);

                return(new AutofacServiceProvider(container.Build()));
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Charge AppInsights options and add the telemetry
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public static IServiceCollection AddAppInsightsTelemetry(this IServiceCollection services, IConfiguration configuration)
        {
            // The following lines enables Application Insights telemetry collection.
            var aiOptions = new Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions();

            // Disable adaptive sampling before custom configuration to have a choice between processors in Configure,
            // according to instructions: https://docs.microsoft.com/en-us/azure/azure-monitor/app/sampling#configure-sampling-settings
            aiOptions.EnableAdaptiveSampling = false;
            services.AddApplicationInsightsTelemetry(aiOptions);

            // Always ignore SignalRTelemetry
            services.AddApplicationInsightsTelemetryProcessor <IgnoreSignalRTelemetryProcessor>();

            // Charge ApplicationInsights options to enable custom configuration of sampling processors
            var aiVirtoOptionsSection = configuration.GetSection("VirtoCommerce:ApplicationInsights");

            services.AddOptions <ApplicationInsightsOptions>().Bind(aiVirtoOptionsSection);

            var aiVirtoOptions = aiVirtoOptionsSection.Get <ApplicationInsightsOptions>() ?? new ApplicationInsightsOptions();

            // Enable SQL dependencies filtering, if need
            if (aiVirtoOptions.IgnoreSqlTelemetryOptions != null)
            {
                services.AddApplicationInsightsTelemetryProcessor <IgnoreSqlTelemetryProcessor>();
            }

            // Force SQL reflection in dependencies, if need
            // See instructions here: https://docs.microsoft.com/en-us/azure/azure-monitor/app/asp-net-dependencies#advanced-sql-tracking-to-get-full-sql-query
            services.ConfigureTelemetryModule <DependencyTrackingTelemetryModule>((module, o) => { module.EnableSqlCommandTextInstrumentation = aiVirtoOptions.EnableSqlCommandTextInstrumentation || aiVirtoOptions.EnableLocalSqlCommandTextInstrumentation; });

            return(services);
        }
        public ApplicationInsightsTelemetryProvider()
        {
            _telemetry = new TelemetryClient();
            /*for developer mode only - enable for testing*/
            var aiOptions = new Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions();

            aiOptions.DeveloperMode = true;
        }
Esempio n. 7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();

            services.AddSingleton <ITelemetryInitializer, MyTelemetryInitializer>();

            var aiOptions = new Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions();

            //aiOptions.EnableAdaptiveSampling = false;
            services.AddApplicationInsightsTelemetry(aiOptions);
            services.AddApplicationInsightsTelemetryProcessor <SynthenicSourceFilter>();
            services.AddApplicationInsightsTelemetryProcessor <FastDependencyCallFilter>();
            services.AddApplicationInsightsTelemetryProcessor <FailedAuthenticationFilter>();
        }
Esempio n. 8
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc($"v1", new OpenApiInfo {
                    Title = "Device Telemetry API", Version = "v1"
                });
            });
            var applicationInsightsOptions = new Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions();

            applicationInsightsOptions.EnableAdaptiveSampling = false;
            services.AddApplicationInsightsTelemetry(applicationInsightsOptions);
            services.AddMvc().AddControllersAsServices().AddNewtonsoftJson();
            services.AddHttpContextAccessor();
            this.ApplicationContainer = new DependencyResolution().Setup(services, this.Configuration);
            return(new AutofacServiceProvider(this.ApplicationContainer));
        }
Esempio n. 9
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            IdentityModelEventSource.ShowPII = true;
            services.AddAuthentication(AzureADDefaults.AuthenticationScheme).AddAzureAD(options => Configuration.Bind("AzureAd", options));
            services.AddControllersWithViews();
            var appInsightsKey = Configuration["ApplicationInsights:InstrumentationKey"];
            var aiOptions      = new Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions();

            aiOptions.EnableAdaptiveSampling = false;
            aiOptions.InstrumentationKey     = appInsightsKey;
            services.AddHttpContextAccessor();
            var accessor = (IHttpContextAccessor)services.Last(s => s.ServiceType == typeof(IHttpContextAccessor)).ImplementationInstance;

            services.AddApplicationInsightsTelemetry(aiOptions);
            services.AddSingleton <ITelemetryInitializer, MyTelemetryInitializer>();
            services.AddSnapshotCollector((configuration) => Configuration.Bind(nameof(SnapshotCollectorConfiguration), configuration));
            // services.AddSingleton(c => new MyTelemetryProcessor(c, accessor));
            var configDescriptor = services.SingleOrDefault(tc => tc.ServiceType == typeof(TelemetryConfiguration));

            if (configDescriptor?.ImplementationFactory != null)
            {
                var implFactory = configDescriptor.ImplementationFactory;
                services.Remove(configDescriptor);

                services.AddSingleton(provider =>
                {
                    if (implFactory.Invoke(provider) is TelemetryConfiguration config)
                    {
                        var newConfig = config;
                        newConfig.ApplicationIdProvider = config.ApplicationIdProvider;
                        newConfig.InstrumentationKey    = config.InstrumentationKey;
                        newConfig.TelemetryProcessorChainBuilder.Use(next => new MyTelemetryProcessor(next, provider.GetRequiredService <IHttpContextAccessor>()));
                        foreach (var processor in config.TelemetryProcessors)
                        {
                            newConfig.TelemetryProcessorChainBuilder.Use(next => processor);
                        }

                        newConfig.TelemetryProcessorChainBuilder.Build();
                        newConfig.TelemetryProcessors.OfType <ITelemetryModule>().ToList().ForEach(module => module.Initialize(newConfig));
                        return(newConfig);
                    }
                    return(null);
                });
            }
        }
Esempio n. 10
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc($"v1", new OpenApiInfo {
                    Title = "Config API", Version = "v1"
                });
            });
            var applicationInsightsOptions = new Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions();

            applicationInsightsOptions.EnableAdaptiveSampling = false;
            services.AddApplicationInsightsTelemetry(applicationInsightsOptions);
            services.AddSingleton(typeof(ITelemetryChannel), new InMemoryChannel()
            {
                MaxTelemetryBufferCapacity = 19898
            });
            services.AddApplicationInsightsTelemetryProcessor <HealthProbeTelemetryProcessor>();
            services.AddMvc().AddControllersAsServices().AddNewtonsoftJson();
            services.AddHttpContextAccessor();
            this.ApplicationContainer = new DependencyResolution().Setup(services, this.Configuration);
            return(new AutofacServiceProvider(this.ApplicationContainer));
        }
Esempio n. 11
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var aiOptions = new Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions();

            aiOptions.EnableAdaptiveSampling = false;

            services.AddApplicationInsightsTelemetry(aiOptions);
            services.Configure <TelemetryConfiguration>(Configuration.GetSection("ApplicationInsights"));

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            // Create the Bot Framework Adapter with error handling enabled.
            services.AddSingleton <IBotFrameworkHttpAdapter, WebSocketEnabledHttpAdapter>();

            services.AddSingleton <ICredentialProvider, DisabledAuthCredentialProvider>();

            // Create the storage we'll be using for state
            services.AddSingleton <IStorage>(new AzureBlobStorage(Configuration["BlobStorageConnectionString"], Configuration["ContainerName"]));

            services.AddHttpClient();

            // Create the bot as a transient. In this case the ASP Controller is expecting an IBot.
            services.AddTransient <IBot, GatewayDynamicsBot>();
        }
Esempio n. 12
0
        public override void Configure(IFunctionsHostBuilder builder)
        {
            var localRoot = Environment.GetEnvironmentVariable("AzureWebJobsScriptRoot");
            var azureRoot = $"{Environment.GetEnvironmentVariable("HOME")}/site/wwwroot";

            var actualRoot = localRoot ?? azureRoot;

            var configBuilder = new ConfigurationBuilder()
                                .SetBasePath(actualRoot)
                                .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                                .AddJsonFile("settings.json", optional: true, reloadOnChange: true)
                                .AddEnvironmentVariables();
            IConfiguration configuration = configBuilder.Build();

            builder.Services.AddSingleton(configuration);

            // TODO Whats this hard-coded app insights doing?
            var appInsightsKey = "8a0becd6-e192-41c4-a6ff-3393bc3bd5df";
            var aiOptions      = new Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions();

            aiOptions.EnableAdaptiveSampling = false;
            aiOptions.InstrumentationKey     = appInsightsKey;
            builder.Services.AddApplicationInsightsTelemetry(aiOptions);
        }
Esempio n. 13
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddServiceProfiler(); // Add this line of code to Enable Profiler
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Scorpio API", Version = "v1"
                });
                // Set the comments path for the Swagger JSON and UI.
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
            });


            var appInsightsKey = Configuration["ApplicationInsights:InstrumentationKey"];
            var aiOptions      = new Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions();

            aiOptions.EnableAdaptiveSampling = false;
            aiOptions.InstrumentationKey     = appInsightsKey;
            services.AddApplicationInsightsTelemetry(aiOptions);
            // services.AddScoped<ServiceBusSender>();
        }
        /// <summary>
        /// Adds components for Application Performance Monitoring for a WebHost.
        /// This includes Application Insights support for:
        ///    - ILogger<T>: logs
        ///    - IAppTelemetry: metrics
        /// </summary>
        /// <param name="services">The service collection</param>
        /// <param name="configuration">Application configuration</param>
        /// <param name="name">The application name to tag logs/metrics with</param>
        /// <returns>The service collection</returns>
        public static IServiceCollection AddApmForWebHost(
            this IServiceCollection services,
            IConfiguration configuration,
            string name)
        {
            var instrumentationKey = GetInstrumentationKey(configuration);
            var options            = new Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions
            {
                InstrumentationKey = instrumentationKey,
                AddAutoCollectedMetricExtractor = true,
                EnableAdaptiveSampling          = false,
                DependencyCollectionOptions     = { EnableLegacyCorrelationHeadersInjection = true },
                RequestCollectionOptions        =
                {
                    InjectResponseHeaders = true,
                    TrackExceptions       = true
                }
            };

            services.AddApplicationInsightsTelemetry(options);
            services.AddApmCommon(configuration, name, instrumentationKey);

            return(services);
        }
Esempio n. 15
0
        public override void Configure(IFunctionsHostBuilder builder)
        {
            var localRoot = Environment.GetEnvironmentVariable("AzureWebJobsScriptRoot");
            var azureRoot = $"{Environment.GetEnvironmentVariable("HOME")}/site/wwwroot";

            var actualRoot = localRoot ?? azureRoot;

            var configBuilder = new ConfigurationBuilder()
                                .SetBasePath(actualRoot)
                                .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                                .AddJsonFile("settings.json", optional: true, reloadOnChange: true)
                                .AddEnvironmentVariables();
            IConfiguration configuration = configBuilder.Build();

            builder.Services.AddSingleton(configuration);
            builder.Services.AddSingleton(configuration.GetSection("MonitoringContext").Get <MonitoringContext>());

            var appInsightsKey = "0220f791-8d97-401c-9916-164d4481cde9";
            var aiOptions      = new Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions();

            aiOptions.EnableAdaptiveSampling = false;
            aiOptions.InstrumentationKey     = appInsightsKey;
            builder.Services.AddApplicationInsightsTelemetry(aiOptions);
        }
Esempio n. 16
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Application Insights Options
            Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions aiOptions
                = new Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions();

            // Disables adaptive sampling.
            aiOptions.EnableAdaptiveSampling = true;
            // Disables QuickPulse (Live Metrics stream).
            aiOptions.EnableQuickPulseMetricStream = true;

            /*
             *  EnablePerformanceCounterCollectionModule
             *      PerformanceCounterCollectionModule aktivieren / deaktivieren
             *          true
             *  EnableRequestTrackingTelemetryModule
             *      RequestTrackingTelemetryModule aktivieren / deaktivieren
             *          true
             *  EnableEventCounterCollectionModule
             *      EventCounterCollectionModule aktivieren / deaktivieren
             *          true
             *  EnableDependencyTrackingTelemetryModule
             *      DependencyTrackingTelemetryModule aktivieren / deaktivieren
             *          true
             *  EnableAppServicesHeartbeatTelemetryModule
             *      AppServicesHeartbeatTelemetryModule aktivieren / deaktivieren
             *          true
             *  EnableAzureInstanceMetadataTelemetryModule
             *      AzureInstanceMetadataTelemetryModule aktivieren / deaktivieren
             *          true
             *  EnableQuickPulseMetricStream
             *      „LiveMetrics“-Feature aktivieren / deaktivieren
             *          true
             *  EnableAdaptiveSampling
             *      Adaptive Stichprobenerstellung aktivieren/ deaktivieren
             *          true
             *  EnableHeartbeat
             *      Heartbeats-Feature aktivieren / deaktivieren, das in regelmäßigen Abständen(Standardwert: 15 Minuten)
             *      eine benutzerdefinierte Metrik namens „HeartBeatState“ mit Informationen zur Laufzeit wie.NET - Version,
             *      ggf.Informationen zur Azure - Umgebung usw.sendet.
             *          true
             *  AddAutoCollectedMetricExtractor
             *      Extraktor für „AutoCollectedMetrics“ aktivieren / deaktivieren, bei dem es sich um einen
             *      Telemetrieprozessor handelt, der vorab aggregierte Metriken zu Anforderungen / Abhängigkeiten sendet,
             *      bevor die Stichprobenerstellung stattfindet.
             *          true
             *  RequestCollectionOptions.TrackExceptions
             *      Berichterstellung über die Nachverfolgung von Ausnahmefehlern durch das Anforderungserfassungsmodul aktivieren / deaktivieren.
             *          In NETSTANDARD2.0 „false“ (da Ausnahmen mit „ApplicationInsightsLoggerProvider“ nachverfolgt werden), andernfalls „true“.
             *
             */
            services.AddSingleton <ITelemetryInitializer, MyTelemetryInitializer>();
            services.AddApplicationInsightsTelemetry(aiOptions);
            services.AddControllersWithViews();
        }
Esempio n. 17
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions aiOptions
                = new Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions();
            // Disables adaptive sampling.
            aiOptions.EnableAdaptiveSampling = true;

            // Disables QuickPulse (Live Metrics stream).
            aiOptions.EnableQuickPulseMetricStream = true;

            services.AddApplicationInsightsTelemetry(aiOptions);
            services.AddControllersWithViews();
        }
Esempio n. 18
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions aiOptions
                = new Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions();
            // Enables adaptive sampling.
            aiOptions.EnableAdaptiveSampling           = true;
            aiOptions.EnableDiagnosticsTelemetryModule = true;

            // Enables QuickPulse (Live Metrics stream).
            aiOptions.EnableQuickPulseMetricStream = true;
            services.AddApplicationInsightsTelemetry(aiOptions);
            services.AddRazorPages();
            services.AddServerSideBlazor();
            services.AddSingleton <WeatherForecastService>();

            services.AddHttpClient <Services.AverageRateApiService>(client =>
            {
                client.BaseAddress = new Uri("https://iliasjmortgageappapim.azure-api.net/");
            });
        }
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            //screw this app insights
            var aiOptions = new Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions();

            aiOptions.EnableAdaptiveSampling = false;

            services.AddApplicationInsightsTelemetry(aiOptions);


            //asp.net core mvc creates an instance of this class
            //so there is no need to make singleton

            //LoggerFactory service
            _loggerFactory.AddDebug();

            //kendo UI
            //services.AddKendo;

            //Themeable Razor View Engine
            services.Configure <RazorViewEngineOptions>(options =>
            {
                options.ViewLocationExpanders.Add(new ThemeableViewLocationExpander());
            });

            //init plugins
            var mvcCoreBuilder = services.AddMvc();

            //services.AddMvcCore();
            PluginManager.Initialize(mvcCoreBuilder.PartManager);

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            //services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();

            //ctl make it from appSettings.json
            var config = new GrandConfig();

            //register autofac dependencies
            var autofacServiceProvider = this.RegisterDependencies(services, config);

            //register mapper configurations
            this.RegisterMapperConfiguration(config);

            //startup tasks
            if (false)//!config.IgnoreStartupTasks)
            {
                this.RunStartupTasks();
            }

            //Install-Package System.Net.Http.WinHttpHandler -Version 4.3.1
            WinHttpHandler httpHandler = new WinHttpHandler()
            {
                SslProtocols = SslProtocols.Tls12
            };
            HttpClient client = new HttpClient(httpHandler);

            //new
            //return new AutofacServiceProvider(applicationContainer);
            //return autofacServiceProvider;
            //previous
            return(autofacServiceProvider);
        }
Esempio n. 20
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddIdentity <User, IdentityRole>(cfg =>
            {
                cfg.User.RequireUniqueEmail = true;
                cfg.Password.RequiredLength = 6;
                //cfg.Password.RequireNonAlphanumeric = true;
            })
            .AddEntityFrameworkStores <LCContext>();

            services.AddScoped <ILCRepository, LCRepository>();

            services.AddDbContext <LCContext>(cfg =>
            {
                cfg.UseSqlServer(Configuration.GetConnectionString("LCConnectionString"));
            }
                                              );

            services.AddTransient <LCSeeder>();

            services.AddCors(options => {
                options.AddPolicy("CorsPolicy", b => {
                    b.AllowAnyMethod();
                    b.AllowAnyHeader();
                    b.AllowCredentials();
                });
            });

            services.AddMvc(option => option.EnableEndpointRouting = false);

            services.AddControllersWithViews();

            services.AddAutoMapper(typeof(Startup));

            Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions aiOptions
                = new Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions();
            // Disables adaptive sampling.
            aiOptions.EnableAdaptiveSampling = false;

            // Disables QuickPulse (Live Metrics stream).
            aiOptions.EnableQuickPulseMetricStream = false;
            services.AddApplicationInsightsTelemetry(aiOptions);
        }
Esempio n. 21
0
        //readonly string MyAllowAllOrigins = "AllowAllOrigins";

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            MyServices = services;

            ConnectionStringToMasterSqlDb = Configuration.GetConnectionString("MasterSqlConnection");
            ConnectionStringSinnersDb     = Configuration.GetConnectionString("DefaultConnection");

            services.AddApplicationInsightsTelemetry(Configuration["APPINSIGHTS_INSTRUMENTATIONKEY"]);

            // Use this if MyCustomTelemetryInitializer can be constructed without DI injected parameters
            services.AddSingleton <ITelemetryInitializer>(new MyTelemetryInitializer());

            services.AddCors(options =>
            {
                options.AddPolicy("AllowOrigin",
                                  builder =>
                {
                    builder.AllowAnyOrigin()
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .SetIsOriginAllowedToAllowWildcardSubdomains();
                });
                options.AddDefaultPolicy(
                    builder =>
                {
                    builder.WithOrigins("https://www.shadowsprawl.com");
                });
            });

            // Configure SnapshotCollector from application settings
            //services.Configure<SnapshotCollectorConfiguration>(Configuration.GetSection(nameof(SnapshotCollectorConfiguration)));

            // Add SnapshotCollector telemetry processor.
            //services.AddSingleton<ITelemetryProcessorFactory>(sp => new SnapshotCollectorTelemetryProcessorFactory(sp));
            Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions aiOptions
                = new Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions();
            // Disables adaptive sampling.
            aiOptions.EnableAdaptiveSampling = true;

            // Disables QuickPulse (Live Metrics stream).
            aiOptions.EnableQuickPulseMetricStream = true;

            services.AddApplicationInsightsTelemetry(aiOptions);



            //var tcbuilder = TelemetryConfiguration.Active.TelemetryProcessorChainBuilder;
            //tcbuilder.Use(next => new GroupNotFoundFilter(next));

            //// If you have more processors:
            //tcbuilder.Use(next => new ExceptionDataProcessor(next));



            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => false;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddResponseCompression(options =>
            {
                options.Providers.Add <BrotliCompressionProvider>();
                options.Providers.Add <GzipCompressionProvider>();
                //options.Providers.Add<CustomCompressionProvider>();
                //options.MimeTypes =
                //    ResponseCompressionDefaults.MimeTypes.Concat(
                //        new[] { "image/svg+xml" });
            });


            services.Configure <FormOptions>(options =>
            {
                options.MultipartBodyLengthLimit = 100000000;
            });

            services.AddDbContext <ApplicationDbContext>(options =>
            {
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection"),
                    builder =>
                {
                    //builder.EnableRetryOnFailure(5);
                });
                options.EnableDetailedErrors();
            });

            services.AddScoped <SignInManager <ApplicationUser>, SignInManager <ApplicationUser> >();


            services.AddIdentity <ApplicationUser, ApplicationRole>(options =>
            {
            })
            .AddRoleManager <RoleManager <ApplicationRole> >()
            .AddRoles <ApplicationRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders()
            .AddSignInManager();

            services.AddTransient <IEmailSender, EmailSender>();
            services.Configure <AuthMessageSenderOptions>(Configuration);

            //// Add application services.
            //services.AddTransient<IEmailSender, EmailSender>();

            ////services.AddSingleton<IEmailSender, EmailSender>();
            //services.Configure<AuthMessageSenderOptions>(Configuration);



            services.AddMvc(options =>
            {
                var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();
                var filter = new AuthorizeFilter(policy);
                options.Filters.Add(filter);
                options.EnableEndpointRouting = false;
            }).SetCompatibilityVersion(CompatibilityVersion.Latest)
            .AddRazorPagesOptions(options =>
            {
                //options.AllowAreas = true;
                //options.Conventions.AuthorizePage("/Home/Contact");
                options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Manage");
                options.Conventions.AuthorizeAreaPage("Identity", "/Account/Logout");
                options.Conventions.AuthorizeAreaPage("Identity", "/Account/ChummerLogin/Logout");
            })
            .AddNewtonsoftJson(x =>
            {
                x.SerializerSettings.ReferenceLoopHandling      = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
                x.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
                x.SerializerSettings.Converters.Add(new StringEnumConverter());
                x.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
            });
            // order is vital, this *must* be called *after* AddNewtonsoftJson()
            services.AddSwaggerGenNewtonsoftSupport();



            services.AddAuthentication(options =>
            {
                options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            //.AddFacebook(facebookOptions =>
            //{
            //    facebookOptions.AppId = Configuration["Authentication.Facebook.AppId"];
            //    facebookOptions.AppSecret = Configuration["Authentication.Facebook.AppSecret"];
            //    facebookOptions.BackchannelHttpHandler = new FacebookBackChannelHandler();
            //    facebookOptions.UserInformationEndpoint = "https://graph.facebook.com/v2.8/me?fields=id,name,email,first_name,last_name";
            //})
            //.AddGoogle(options =>
            //{
            //    options.ClientId = Configuration["Authentication.Google.ClientId"];
            //    options.ClientSecret = Configuration["Authentication.Google.ClientSecret"];
            //    options.CallbackPath = new PathString("/ExternalLogin");
            //})
            .AddCookie("Cookies", options =>
            {
                options.LoginPath        = new PathString("/Identity/Account/Login");
                options.AccessDeniedPath = new PathString("/Identity/Account/AccessDenied");
                options.LogoutPath       = "/Identity/Account/Logout";
                options.Cookie.Name      = "Cookies";
                options.Cookie.HttpOnly  = false;
                options.ExpireTimeSpan   = TimeSpan.FromDays(5 * 365);
                options.LoginPath        = "/Identity/Account/Login";
                // ReturnUrlParameter requires
                //using Microsoft.AspNetCore.Authentication.Cookies;
                options.ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
                options.SlidingExpiration  = false;
            })
            ;

            services.Configure <IdentityOptions>(options =>
            {
                // Password settings.
                options.Password.RequireDigit           = false;
                options.Password.RequireLowercase       = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequiredLength         = 5;
                options.Password.RequiredUniqueChars    = 0;

                // Lockout settings.
                options.Lockout.DefaultLockoutTimeSpan  = TimeSpan.FromMinutes(5);
                options.Lockout.MaxFailedAccessAttempts = 5;
                options.Lockout.AllowedForNewUsers      = true;

                // User settings.
                options.User.AllowedUserNameCharacters =
                    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
                options.User.RequireUniqueEmail = true;
#if DEBUG
                options.SignIn.RequireConfirmedEmail = false;
#else
                options.SignIn.RequireConfirmedEmail = true;
#endif
                options.SignIn.RequireConfirmedPhoneNumber = false;
            });

            services.ConfigureApplicationCookie(options =>
            {
                // Cookie settings
                options.LogoutPath       = "/Identity/Account/Logout";
                options.AccessDeniedPath = "/Identity/Account/AccessDenied";
                options.Cookie.Name      = "Cookies";
                options.Cookie.HttpOnly  = false;
                options.ExpireTimeSpan   = TimeSpan.FromDays(5 * 365);
                options.LoginPath        = "/Identity/Account/Login";
                // ReturnUrlParameter requires
                //using Microsoft.AspNetCore.Authentication.Cookies;
                options.ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
                options.SlidingExpiration  = false;
                //options.Events.OnRedirectToAccessDenied = context => {

                //    // Your code here.
                //    // e.g.
                //    throw new Not();
                //};
            });



            services.AddVersionedApiExplorer(options =>
            {
                options.GroupNameFormat = "'v'VVV";
                // note: this option is only necessary when versioning by url segment. the SubstitutionFormat
                // can also be used to control the format of the API version in route templates
                options.SubstituteApiVersionInUrl = true;
            })
            .AddAuthorization();
            services.AddDatabaseDeveloperPageExceptionFilter();
            services.AddApiVersioning(o =>
            {
                o.ReportApiVersions = true;
                o.DefaultApiVersion = new ApiVersion(1, 0);
                o.AssumeDefaultVersionWhenUnspecified = true;
                //o.ApiVersionReader = new HeaderApiVersionReader("api-version");
                //o.Conventions.Controller<Controllers.V1.SINnerController>().HasApiVersion(new ApiVersion(1, 0));
                //o.Conventions.Controller<Controllers.V2.SINnerController>().HasApiVersion(new ApiVersion(2, 0));
            });

            services.AddSwaggerExamples();

            services.AddSwaggerGen(options =>
            {
                //options.AddSecurityDefinition("Bearer",
                //    new ApiKeyScheme {
                //        In = "header",
                //        Description = "Please enter JWT with Bearer into field",
                //        Name = "Authorization",
                //        Type = "apiKey" });
                //options.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
                //{
                //    { "Bearer", Enumerable.Empty<string>() },
                //});
                // resolve the IApiVersionDescriptionProvider service
                // note: that we have to build a temporary service provider here because one has not been created yet
                options.UseAllOfToExtendReferenceSchemas();

                AddSwaggerApiVersionDescriptions(services, options);



                //options.OperationFilter<FileUploadOperation>();

                // add a custom operation filter which sets default values
                //options.OperationFilter<SwaggerDefaultValues>();

                //options.DescribeAllEnumsAsStrings();

                options.ExampleFilters();

                options.OperationFilter <AddResponseHeadersFilter>();


                // Set the comments path for the Swagger JSON and UI.
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                options.IncludeXmlComments(xmlPath);

                //options.MapType<FileResult>(() => new Schema
                //{
                //    Type = "file",
                //});
                //options.MapType<FileStreamResult>(() => new Schema
                //{
                //    Type = "file",
                //});
            });
            services.AddAzureAppConfiguration();


            //services.AddDistributedMemoryCache(); // Adds a default in-memory implementation of IDistributedCache
            //services.AddSession();

            //services.AddHttpsRedirection(options =>
            //{
            //    options.HttpsPort = 443;
            //});

            //services.Configure<ApiBehaviorOptions>(options =>
            //{
            //    options.SuppressModelStateInvalidFilter = true;
            //});
        }
Esempio n. 22
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration
            //https://weblog.west-wind.com/posts/2016/May/23/Strongly-Typed-Configuration-Settings-in-ASPNET-Core
            //https://www.codefluff.com/getting-configuration-settings-asp-net-core-mvc/
            // Adds services required for using options.
            services.AddOptions();

            // Register the ConfigurationBuilder instance which MyOptions binds against.
            var x = Configuration.GetSection("AppSettings:ApplicationName");

#if SQLLITE_DEBUG
            var connection = Configuration["Data:Sqlite:ConnectionString"];
#elif SQLPSS66_DEBUG
            var connection = Configuration["Data:Sqlpss66:ConnectionString"];
#elif SQL
            var connection = Configuration["Data:Sql:ConnectionString"];
#elif RELEASE
            var connection = Configuration["Data:SqlReleasepss66:ConnectionString"];
#endif



            //inject OptionsAppSettings objects for _Layout.cshtml vession and baseUrl
            //the options => requires an OptionsAppSettings() constructor to set the value.
            //The GetSection() call is overidden
            services.Configure <OptionsAppSettings>(options => Configuration.GetSection("OptionsAppSettings"));

            //next line inits an AppSettings object with the 'connectionstring' from app_config.json
            //this is method to inject parms into the ExpenseDbContext in Expenses.core for the app
            //When testing the core, you can provide your own appsettings values
            //AppSettings object does not have a constructor. The values must come from json config file
            //options => is not used cuz there is no AppSettings constructor.
#if SQLLITE_DEBUG
            services.Configure <AppSettings>(Configuration.GetSection("Data:Sqlite"));
#elif SQLPSS66_DEBUG
            services.Configure <AppSettings>(Configuration.GetSection("Data:Sqlpss66"));
#elif SQL
            services.Configure <AppSettings>(Configuration.GetSection("Data:Sql"));
#elif RELEASE
            services.Configure <AppSettings>(Configuration.GetSection("Data:SqlReleasepss66"));
#endif

            //services.Configure<OptionsDB>(options => Configuration.GetSection("ConnectionStrings"));
            // *If* you need access to generic IConfiguration this is **required**
            services.AddSingleton <IConfiguration>(Configuration);

            // Add framework services.

            //https://stackoverflow.com/questions/39864550/how-to-get-base-url-without-accessing-a-request
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();



            services
            .AddMvc()
            .AddJsonOptions(a => a.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver());


#if SQLLITE_DEBUG
            services.AddEntityFrameworkSqlite().AddDbContext <ExpenseDbContext>();
#else
            services.AddEntityFrameworkSqlServer().AddDbContext <ExpenseDbContext>();
#endif


            services.AddScoped <ILogger <ExpenseDbContext>, Logger <ExpenseDbContext> >();
            services.AddScoped <NotImplementedExceptionFilter>();

            services.AddScoped <IEntityMapper, ExpenseEntityMapper>();
            services.AddScoped <IUserInfo, UserInfo>();

            //Dependency injection
            services.AddScoped <IPoultryFeedService, PoultryFeedService>();
            services.AddScoped <IPoultryFeedRepository, PoultryFeedRepository>();
            services.AddScoped <ILogger <PoultryFeedService>, Logger <PoultryFeedService> >();

            services.AddScoped <IFarmService, FarmService>();
            services.AddScoped <IFarmRepository, FarmRepository>();
            services.AddScoped <ILogger <FarmService>, Logger <FarmService> >();

            //https://stackoverflow.com/questions/40156377/disable-application-insights-sampling-with-the-asp-net-core-libraries
            //enable sampling
            //see program.cs to enable
            //   //.UseApplicationInsights()
            // _layout.cshtml uncomment to enable
            //          @*@inject Microsoft.ApplicationInsights.AspNetCore.JavaScriptSnippet JavaScriptSnippet*@
            //  @*@Html.Raw(JavaScriptSnippet.FullScript)*@
            var aiOptions = new Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions();
            aiOptions.EnableAdaptiveSampling = false;
            //services.AddApplicationInsightsTelemetry( aiOptions);


            // Add application services.
            //https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection
            //services.AddTransient<IEmailSender, AuthMessageSender>();
            //services.AddTransient<ISmsSender, AuthMessageSender>();
        }