public static IReportFactory AddInfluxDb(
     this IReportFactory factory,
     InfluxDBReporterSettings settings,
     IFilterMetrics filter = null)
 {
     factory.AddProvider(new InfluxDbReporterProvider(settings, filter));
     return(factory);
 }
        private static InfluxDbReporter CreateReporter(ILineProtocolPayloadBuilder payloadBuilder)
        {
            var lineProtocolClientMock = new Mock <ILineProtocolClient>();
            var reportInterval         = TimeSpan.FromSeconds(1);
            var loggerFactory          = new LoggerFactory();
            var settings = new InfluxDBReporterSettings();

            return(new InfluxDbReporter(lineProtocolClientMock.Object,
                                        payloadBuilder, reportInterval, loggerFactory, settings.MetricNameFormatter));
        }
Esempio n. 3
0
        public static IReportFactory AddInfluxDb(this IReportFactory factory,
                                                 string database, Uri baseAddress,
                                                 IMetricsFilter filter = null)
        {
            var settings = new InfluxDBReporterSettings
            {
                InfluxDbSettings = new InfluxDBSettings(database, baseAddress)
            };

            factory.AddInfluxDb(settings, filter);
            return(factory);
        }
        public void can_add_influxdb_provider_with_custom_settings()
        {
            var factory  = SetupReportFactory();
            var settings = new InfluxDBReporterSettings
            {
                HttpPolicy = new HttpPolicy
                {
                    BackoffPeriod = TimeSpan.FromMinutes(1)
                }
            };
            Action action = () => { factory.AddInfluxDb(settings); };

            action.ShouldNotThrow();
        }
Esempio n. 5
0
        public void can_add_influxdb_provider_with_custom_settings_and_filter()
        {
            var metricsMock = new Mock <IMetrics>();
            var factory     = new ReportFactory(metricsMock.Object, new LoggerFactory());
            var settings    = new InfluxDBReporterSettings
            {
                HttpPolicy = new HttpPolicy
                {
                    BackoffPeriod = TimeSpan.FromMinutes(1)
                }
            };
            Action action = () => { factory.AddInfluxDb(settings, new DefaultMetricsFilter()); };

            action.ShouldNotThrow();
        }
        private static IMetricReporter CreateReporter(IMetricPayloadBuilder <LineProtocolPayload> payloadBuilder)
        {
            var reportInterval = TimeSpan.FromSeconds(1);
            var loggerFactory  = new LoggerFactory();
            var settings       = new InfluxDBReporterSettings();

            return(new ReportRunner <LineProtocolPayload>(
                       p => AppMetricsTaskCache.SuccessTask,
                       payloadBuilder,
                       reportInterval,
                       "InfluxDB Reporter",
                       loggerFactory,
                       settings.MetricNameFormatter,
                       settings.DataKeys));
        }
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)
        {
            // AppMetrics. #https://al-hardy.blog/2017/04/28/asp-net-core-monitoring-with-influxdb-grafana/
            var metricsHostBuilder = services.AddMetrics(options =>
            {
                options.WithGlobalTags((globalTags, info) =>
                {
                    globalTags.Add("app", info.EntryAssemblyName);
                    globalTags.Add("env", "stage");
                });
            })
                                     .AddHealthChecks()
                                     .AddJsonSerialization();

            using (var stream = new FileStream("dashboardConfig.json", FileMode.Open))
                using (var reader = new StreamReader(stream))
                {
                    var text = reader.ReadToEnd();
                    DashboardConfig = JObject.Parse(text);
                }

            var dbName   = JsonUtils.GetString("influxDB.dbName", DashboardConfig);
            var dbServer = JsonUtils.GetString("influxDB.servers", DashboardConfig);
            var dbPort   = JsonUtils.GetType <int>("influxDB.port", DashboardConfig, 0);

            if (!String.IsNullOrEmpty(dbName) && !String.IsNullOrEmpty(dbServer))
            {
                var dbUriString = $"http://{dbServer}";
                if (dbPort != 0)
                {
                    dbUriString += ":" + dbPort.ToString();
                }
                var dbUri = new Uri(dbUriString);
                metricsHostBuilder = metricsHostBuilder.AddReporting(
                    factory =>
                {
                    factory.AddInfluxDb(
                        new InfluxDBReporterSettings
                    {
                        InfluxDbSettings = new InfluxDBSettings(dbName, dbUri),
                        ReportInterval   = TimeSpan.FromSeconds(5)
                    });
                });
                serviceMessages.Append($"Reporting to InfluxDB at {dbUriString}\n");
            }

            metricsHostBuilder.AddMetricsMiddleware(options => options.IgnoredHttpStatusCodes = new[] { 404 });



            var reportSetting = new InfluxDBReporterSettings();


            // Add MVC services to the services container.
            services.AddDistributedMemoryCache(); // Adds a default in-memory implementation of IDistributedCache
            services.AddSession(options => options.IdleTimeout = TimeSpan.FromDays(14));
            services.AddMvc(options => options.AddMetricsResourceFilter());
            //services.AddCors();
            services.Configure <AppSettings>(appSettings =>
            {
                // Typed syntax - Configuration.Get<type>("")
                // Configure may not have run at the moment, so this is console printout.
            });
            services.Configure <FamilyModel>(families => {});
            // Add Authentication services.
            services.AddAuthentication(sharedOptions => sharedOptions.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme);

            // Expose Azure AD configuration to controllers
            services.AddOptions();

            services.AddDbContext <WebAppContext>(options => options.UseSqlite(Configuration["Data:ConnectionString"]));
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddSingleton <IFamily, FamilyModel>();
            services.AddScoped <IAzureAdTokenService, DbTokenCache>();
        }
Esempio n. 8
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSession(opt => { opt.Cookie.IsEssential = true; }
                                );
            // AppMetrics. #https://al-hardy.blog/2017/04/28/asp-net-core-monitoring-with-influxdb-grafana/
            var metricsHostBuilder = services.AddMetrics(options =>
            {
                options.WithGlobalTags((globalTags, info) =>
                {
                    globalTags.Add("app", info.EntryAssemblyName);
                    globalTags.Add("env", "stage");
                });
            })
                                     .AddHealthChecks();

            // .AddJsonSerialization();

            using (var stream = new FileStream("dashboardConfig.json", FileMode.Open))
                using (var reader = new StreamReader(stream))
                {
                    var text = reader.ReadToEnd();
                    DashboardConfig = JObject.Parse(text);
                }

            var dbName   = JsonUtils.GetString("influxDB.dbName", DashboardConfig);
            var dbServer = JsonUtils.GetString("influxDB.servers", DashboardConfig);
            var dbPort   = JsonUtils.GetType <int>("influxDB.port", DashboardConfig, 0);

            if (!String.IsNullOrEmpty(dbName) && !String.IsNullOrEmpty(dbServer))
            {
                var dbUriString = $"http://{dbServer}";
                if (dbPort != 0)
                {
                    dbUriString += ":" + dbPort.ToString();
                }
                var dbUri = new Uri(dbUriString);
                metricsHostBuilder = metricsHostBuilder.AddReporting(
                    factory =>
                {
                    factory.AddInfluxDb(
                        new InfluxDBReporterSettings
                    {
                        InfluxDbSettings = new InfluxDBSettings(dbName, dbUri),
                        ReportInterval   = TimeSpan.FromSeconds(5)
                    });
                });
                serviceMessages.Append($"Reporting to InfluxDB at {dbUriString}\n");
            }

            metricsHostBuilder.AddMetricsMiddleware(options => options.IgnoredHttpStatusCodes = new[] { 404 });



            var reportSetting = new InfluxDBReporterSettings();

            // For identity
            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.AddDefaultIdentity<IdentityUser>()
            //    .AddEntityFrameworkStores<ApplicatonDbContext>();

            //services.AddIdentity<IdentityUser, IdentityRole>()
            //    .AddEntityFrameworkStores<ApplicatonDbContext>();

            services.ConfigureApplicationCookie(options =>
            {
                // Cookie settings
                options.Cookie.HttpOnly = true;
                options.ExpireTimeSpan  = TimeSpan.FromMinutes(600);

                options.LoginPath         = "/Identity/Account/Login";
                options.AccessDeniedPath  = "/Identity/Account/AccessDenied";
                options.SlidingExpiration = true;
            });
            var deployAuthenticationConfig = ConfigurationParser.GetConfiguration("DeployAuthentications") as Dictionary <string, object>;
            var deployAuthentication       = new Dictionary <string, bool>(StringComparer.OrdinalIgnoreCase);

            foreach (var pair in deployAuthenticationConfig)
            {
                deployAuthentication[pair.Value as string] = true;
            }
            int numDeployedAuthentication = deployAuthentication.Count;

            var auth           = services.AddAuthentication();
            var authentication = ConfigurationParser.GetConfiguration("Authentications") as Dictionary <string, object>;

            AuthenticationSchemes  = new Dictionary <string, string>();
            AuthenticationCallback = new Dictionary <string, bool>();
            foreach (var pair in authentication)
            {
                bool bUse = (numDeployedAuthentication == 0 || deployAuthentication.ContainsKey(pair.Key));
                if (bUse)
                {
                    var authenticationScheme = pair.Key;
                    var authenticationConfig = pair.Value;

                    var config = authenticationConfig as Dictionary <string, object>;
                    if (Object.ReferenceEquals(config, null))
                    {
                        continue;
                    }
                    Console.WriteLine($"Examine authentication {authenticationScheme}");

                    if (authenticationScheme.IndexOf("WeChat", StringComparison.OrdinalIgnoreCase) >= 0)
                    {
                        auth.AddWeChat(wechatOptions =>
                        {
                            wechatOptions.AppId     = config["AppId"] as string;
                            wechatOptions.AppSecret = config["AppSecret"] as string;
                        }
                                       );
                        Console.WriteLine("Add Wechat Authentication");
                        AuthenticationSchemes[authenticationScheme] = "WeChat";
                    }

                    if (authenticationScheme.IndexOf("Microsoft", StringComparison.OrdinalIgnoreCase) >= 0)
                    {
                        auth.AddMicrosoftAccount(microsoftOption =>
                        {
                            microsoftOption.ClientId     = config["ClientId"] as string;
                            microsoftOption.ClientSecret = config["ClientSecret"] as string;
                        }
                                                 );
                        Console.WriteLine("Add Microsoft Authentication");
                        AuthenticationSchemes[authenticationScheme] = "Microsoft";
                    }

                    if (authenticationScheme.IndexOf("Gmail", StringComparison.OrdinalIgnoreCase) >= 0)
                    {
                        auth.AddGoogle(googleOptions => {
                            googleOptions.ClientId     = config["ClientId"] as string;
                            googleOptions.ClientSecret = config["ClientSecret"] as string;
                        });
                        Console.WriteLine("Add Google Authentication");
                        AuthenticationSchemes[authenticationScheme] = "Google";
                        AuthenticationCallback["signin-google"]     = true;
                    }
                    ;

                    // app.UseOpenIdConnectAuthentication(openIDOpt);
                }
            }



            // Add MVC services to the services container.
            services.AddMvc(options => options.AddMetricsResourceFilter())
            .AddRazorPagesOptions(options =>
            {
                options.Conventions.AddPageRoute("/Identity/Account", "account");
                options.Conventions.AuthorizePage("/Manage");
                options.Conventions.AuthorizeFolder("/Private");
                options.Conventions.AllowAnonymousToPage("/Private/PublicPage");
                options.Conventions.AllowAnonymousToFolder("/Private/PublicPages");
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            // Authorization handlers.


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

            //services.AddCors();
            services.Configure <AppSettings>(appSettings =>
            {
                // Typed syntax - Configuration.Get<type>("")
                // Configure may not have run at the moment, so this is console printout.
            });

            services.AddDataProtection();

            /*
             * // https://github.com/aspnet/DataProtection/issues/189
             * // https://docs.microsoft.com/en-us/aspnet/core/security/data-protection/configuration/overview?tabs=aspnetcore2x&view=aspnetcore-2.2
             * services.AddDataProtection()
             *  .PersistKeysToFileSystem(new DirectoryInfo(@"keys"));*/
            /* .ProtectKeysWithCertificate(
             *  new X509Certificate2("certificate.pfx", "password"))
             *  .UnprotectKeysWithAnyCertificate(
             *  new X509Certificate2("certificate_old_1.pfx", "password_1"),
             *  new X509Certificate2("certificate_old_2.pfx", "password_2"));*/

            services.Configure <FamilyModel>(families => {});
            // Add Authentication services.
            // services.AddAuthentication(sharedOptions => sharedOptions.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme);

            // Expose Azure AD configuration to controllers
            services.AddOptions();

            services.AddDbContext <WebAppContext>(options => options.UseSqlite(Configuration["Data:ConnectionString"]));
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddSingleton <IFamily, FamilyModel>();
            // services.AddScoped<IAzureAdTokenService, DbTokenCache>();
        }