Ejemplo n.º 1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAutoMapper();

            // services.AddTransient<Seeder>(); uncomment to seed the database
            // services.AddScoped<IRepository, Repository>(); uncomment for use with the database

            // dependency injection for interfacing with in memory data
            services.AddSingleton <IDataContext, InMemoryDataContext>();
            services.AddSingleton <IRepository, InMemoryRepository>();

            services.AddDbContext <HubDbContext>(options => options.UseSqlServer(Configuration["HubDbContext"])
                                                 .ConfigureWarnings(warnings => warnings.Throw(RelationalEventId.QueryClientEvaluationWarning)));


            services.AddMvc()
            .AddJsonOptions(opt => opt.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore)
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(o =>
            {
                o.Authority = Configuration["Jwt:Authority"];
                o.Audience  = Configuration["Jwt:Audience"];
                o.Events    = new JwtBearerEvents()
                {
                    OnAuthenticationFailed = ctx =>
                    {
                        ctx.NoResult();

                        ctx.Response.StatusCode  = 500;
                        ctx.Response.ContentType = "text/plain";
                        if (Environment.IsDevelopment())
                        {
                            return(ctx.Response.WriteAsync(ctx.Exception.ToString()));
                        }

                        return(ctx.Response.WriteAsync("An error occurred processing your authentication"));
                    }
                };
            });


            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Version     = "Alpha",
                    Title       = "BC Gov Hub API service",
                    Description = "The .Net Core 2.1 API for the Hub"
                });
            });

            services.AddHealthChecks(checks =>
            {
                checks.AddSqlCheck("Gcpe.Hub", Configuration["HubDbContext"]);
                // checks.AddUrlCheck("https://github.com");
                checks.AddCheck("Webserver is running", () => HealthCheckResult.Healthy("Ok"));
            });

            services.AddCors();
        }
Ejemplo n.º 2
0
 /// <summary>
 /// Starts the health check and returns <see cref="HealthCheckResult" />
 /// </summary>
 /// <returns>HealthCheckResult</returns>
 public HealthCheckResult StartHealthCheck()
 {
     return(HealthCheckResult.Healthy("RabbitMqMessageReceiver is operational."));
 }
Ejemplo n.º 3
0
        public void ConfigureServices(IServiceCollection services)
        {
            // If using Kestrel:
            services.Configure <KestrelServerOptions>(options =>
            {
                options.AllowSynchronousIO = true;
            });

            // If using IIS:
            services.Configure <IISServerOptions>(options =>
            {
                options.AllowSynchronousIO = true;
            });

            // Bind to CareRecordAPISettings settings from appSettings.json
            careRecordSettings = new CareRecordAPISettings();
            Configuration.Bind("CareRecordSettings", careRecordSettings);
            services.AddSingleton <CareRecordAPISettings>(careRecordSettings);

            services.AddAuthenticationToCareRecord(Configuration);

            //services.AddMvc(options =>
            //{
            //    options.Filters.Add(new GlobalFilter());
            //});

            services.AddCors(options =>
            {
                options.AddPolicy("AllowAllHeaders",
                                  builder =>
                {
                    builder.AllowAnyOrigin()
                    .AllowAnyHeader()
                    .AllowAnyMethod();
                });
            });

            services.AddAutoMapperToCareRecord();

            // AddFhir also calls AddMvcCore
            services.AddFhir(careRecordSettings);
            services.AddFhirFormatters();

            //services.AddMvcCore(options =>
            services.AddMvc(options =>
            {
                options.Filters.Add(new GlobalFilter());

                //Should un-comment this (below two lines) to enable it only for FHIR Parsers
                options.InputFormatters.RemoveType <SystemTextJsonInputFormatter>();
                options.OutputFormatters.RemoveType <SystemTextJsonOutputFormatter>();
            });

            services.AddHttpContextAccessor();

            string SynapseDynamicAPIURI = Configuration.GetSection("DynamicAPISettings").GetSection("uri").Value;

            //services.AddHttpClient();

            //services.AddHttpClient<DynamicAPIClient>(clientConfig =>
            //{
            //    clientConfig.BaseAddress = new Uri(SynapseDynamicAPIURI);
            //});

            services.AddControllers();

            services.AddApiVersioning(config =>
            {
                config.DefaultApiVersion = new ApiVersion(1, 0);
                config.AssumeDefaultVersionWhenUnspecified = true;
                config.ReportApiVersions = true;
                //config.ApiVersionReader = new HeaderApiVersionReader("api-version");
            });

            services.AddVersionedApiExplorer(
                options =>
            {
                // note: the specified format code will format the version as "'v'major[.minor]"
                options.GroupNameFormat           = "'v'V";
                options.SubstituteApiVersionInUrl = true;
                //options.SubstitutionFormat = "'v'V";
            });

            services.AddHealthChecks().AddCheck("self", () => HealthCheckResult.Healthy());

            services.AddSwaggerToCareRecord(Configuration);
        }
Ejemplo n.º 4
0
        public static IServiceCollection AddOptionsAndHealthChecks(this IServiceCollection services, IConfiguration configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            var sql = new SqlServerConnection();

            configuration.Bind("Infra:Connections:Sql", sql);
            services.Configure <SqlServerConnection>(instance => configuration.Bind("Infra:Connections:Sql", instance));
            services.AddScoped(x => x.GetRequiredService <IOptionsSnapshot <SqlServerConnection> >().Value);

            var mongodb = new MongoDbConnection();

            configuration.Bind("Infra:Connections:Mongodb", mongodb);
            services.Configure <MongoDbConnection>(instance => configuration.Bind("Infra:Connections:Mongodb", instance));
            services.AddScoped(x => x.GetRequiredService <IOptionsSnapshot <MongoDbConnection> >().Value);

            var rabbit = new RabbitMqConnection();

            configuration.Bind("Infra:Connections:RabbitMQ", rabbit);
            services.Configure <RabbitMqConnection>(instance => configuration.Bind("Infra:Connections:RabbitMQ", instance));
            services.AddScoped(x => x.GetRequiredService <IOptionsSnapshot <RabbitMqConnection> >().Value);

            var redis = new RedisCacheOptions();

            configuration.Bind("Infra:Connections:Redis", redis);
            services.Configure <RedisCacheOptions>(instance => configuration.Bind("Infra:Connections:Redis", instance));
            services.AddScoped(x => x.GetRequiredService <IOptionsSnapshot <RedisCacheOptions> >().Value);

            services.AddStackExchangeRedisCache(options =>
            {
                options.Configuration = redis.Configuration;
                options.InstanceName  = redis.InstanceName;
            });

            services.AddMassTransitHostedService();
            services.TryAddSingleton(KebabCaseEndpointNameFormatter.Instance);
            services.AddMassTransit(cfg =>
            {
                cfg.SetKebabCaseEndpointNameFormatter();
                cfg.AddBus(factory => Bus.Factory.CreateUsingRabbitMq(x =>
                {
                    x.UseHealthCheck(factory);

                    x.Host(rabbit.Host, rabbit.VirtualHost);
                    x.ConfigureEndpoints(factory);
                }));
            });

            services.AddHealthChecks()
            .AddCheck("api", _ => HealthCheckResult.Healthy())
            .AddRedis(redis.Configuration, "redis")
            .AddMongoDb(mongodb.ConnectionString, mongodb.Collection, "mongodb")
            .AddSqlServer(sql.ConnectionString)
            .AddRabbitMQ(rabbit.ConnectionUri, new SslOption(), "rabbitmq");



            services.AddWrapperizer().AddOutboxServices(options =>
            {
                options.UseSqlServer(sql.ConnectionString,
                                     sqlOptions =>
                {
                    // sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name);

                    sqlOptions.MigrationsHistoryTable("__OutboxMigrationHistory", OutboxEventContext.DefaultSchema);

                    //Configuring Connection Resiliency: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency
                    sqlOptions.EnableRetryOnFailure(15, TimeSpan.FromSeconds(30), null);
                });
            });

            return(services);
        }
Ejemplo n.º 5
0
 public Task <HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = new CancellationToken())
 {
     return(Task.FromResult(HealthCheckResult.Healthy()));
 }
 /// <inheritdoc/>
 public Task <HealthCheckResult> QueryLivenessAsync(HealthCheckContext context, CancellationToken cancellationToken)
 {
     return(Task.FromResult(HealthCheckResult.Healthy("Live")));
 }
        public void ConfigureServices(IServiceCollection services)
        {
            JsonConvert.DefaultSettings = () =>
            {
                JsonSerializerSettings serializerSetting = new JsonSerializerSettings
                {
                    ContractResolver      = new CamelCasePropertyNamesContractResolver(),
                    ReferenceLoopHandling = ReferenceLoopHandling.Serialize
                };

                return(serializerSetting);
            };

            if (RunInDevMode())
            {
                services.AddCors(CorsOptions);
            }

            services
            .AddLogging()
            .AddHealthChecks(checks =>
                             checks.AddValueTaskCheck("HTTP Endpoint", () =>
                                                      new ValueTask <IHealthCheckResult>(HealthCheckResult.Healthy("Ok"))))
            .AddTransient <IIpAddressDetailsApiDao, IpAddressDetailsApiDao>()
            .AddTransient <IEnvironment, EnvironmentWrapper>()
            .AddTransient <IEnvironmentVariables, EnvironmentVariables>()
            .AddTransient <IConnectionInfoAsync, PostgresEnvironmentParameterStoreConnectionInfoAsync>()
            .AddSingleton <IAmazonSimpleSystemsManagement, CachingAmazonSimpleSystemsManagementClient>()
            .AddTransient <IValidator <IpAddressDateRangeRequest>, IpAddressDateRangeRequestValidator>()
            .AddTransient <IDomainValidator, DomainValidator>()
            .AddTransient <IIpAddressDetailsService, IpAddressDetailsService>()
            .AddTransient <IIpAddressDateRangeDetailsBuilder, IpAddressDateRangeDetailsBuilder>()
            .AddTransient <IAsInfoComparer, AsInfoComparer>()
            .AddTransient <IBlocklistDetailsComparer, BlocklistDetailsComparer>()
            .AddTransient <IReverseDnsDetailComparer, ReverseDnsDetailComparer>()
            .AddMailCheckAuthenticationClaimsPrincipleClient()
            .AddSerilogLogging()
            .AddAudit("Aggregate-Report-Api-V2")
            .AddMvc(config =>
            {
                AuthorizationPolicy policy = new AuthorizationPolicyBuilder()
                                             .RequireAuthenticatedUser()
                                             .Build();
                config.Filters.Add(new AuthorizeFilter(policy));
            })
            .AddJsonOptions(options =>
            {
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Serialize;
                options.SerializerSettings.Converters.Add(new StringEnumConverter());
            })
            .AddFluentValidation();

            services
            .AddAuthorization()
            .AddAuthentication(AuthenticationSchemes.Claims)
            .AddMailCheckClaimsAuthentication();
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddSignalR();

            services.AddSingleton <IUserIdProvider, CustomUserIdProvider>();
            services.AddHealthChecks()
            .AddCheck("self", () => HealthCheckResult.Healthy())
            .AddSqlServer(Configuration["ConnectionString"],
                          name: "Ordem de Compra DB Check",
                          tags: new string[] { "OrdemDeCompraDB" });

            services.AddAutoMapper();

            services
            .AddAuthentication("Bearer")
            .AddIdentityServerAuthentication(options =>
            {
                options.ApiName   = "OrdemDeCompra.API";
                options.ApiSecret = "secret";
                options.Authority = Configuration["IdentityUrl"];
                //options.BackchannelHttpHandler = new HttpClientHandler() { Proxy = new WebProxy(Configuration["System:Proxy"]) };
                options.RequireHttpsMetadata = false;
                options.SupportedTokens      = IdentityServer4.AccessTokenValidation.SupportedTokens.Both;
                options.SaveToken            = true;
            });

            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Version     = "v1",
                    Title       = "Casa do Código - Ordem de Compra API",
                    Description = "Uma API contendo funcionalidades da aplicação de e-Commerce:" +
                                  "Criação de pedidos.",
                    TermsOfService = "Nenhum",
                    Contact        = new Contact
                    {
                        Name  = "Marcelo Oliveira",
                        Email = "*****@*****.**",
                        Url   = "https://twitter.com/twmoliveira"
                    },
                    License = new License
                    {
                        Name = "Licença XPTO 4567",
                        Url  = "https://example.com/license"
                    }
                });

                // 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);
            });

            services.ConfigureSwaggerGen(options =>
            {
                // UseFullTypeNameInSchemaIds replacement for .NET Core
                options.CustomSchemaIds(x => x.FullName);
            });

            services.AddDistributedMemoryCache();
            services.AddSession();

            string connectionString = Configuration["ConnectionString"];

            services.AddDbContext <ApplicationContext>(options =>
                                                       options.UseSqlServer(connectionString)
                                                       );

            services.AddScoped <DbContext, ApplicationContext>();
            var serviceProvider = services.BuildServiceProvider();
            var contexto        = serviceProvider.GetService <ApplicationContext>();

            services.AddSingleton <ApplicationContext>(contexto);

            services.AddScoped <IPedidoRepository, PedidoRepository>();

            services.AddScoped <IMediator, NoMediator>();
            services.AddScoped <IRequest <bool>, CreatePedidoCommand>();
            services.AddMediatR(typeof(CreatePedidoCommand).GetTypeInfo().Assembly);
            RegisterRebus(services);
        }
Ejemplo n.º 9
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            RegisterAppInsights(services);

            // Add framework services.
            services.AddMvc(options =>
            {
                options.Filters.Add(typeof(HttpGlobalExceptionFilter));
                options.Filters.Add(typeof(ValidateModelStateFilter));
            }).AddControllersAsServices();

            ConfigureAuthService(services);

            services.AddHealthChecks(checks =>
            {
                checks.AddValueTaskCheck("HTTP Endpoint", () => new ValueTask <IHealthCheckResult>(HealthCheckResult.Healthy("Ok")),
                                         TimeSpan.Zero  //No cache for this HealthCheck, better just for demos
                                         );
            });

            services.Configure <BasketSettings>(Configuration);

            //By connecting here we are making sure that our service
            //cannot start until redis is ready. This might slow down startup,
            //but given that there is a delay on resolving the ip address
            //and then creating the connection it seems reasonable to move
            //that cost to startup instead of having the first request pay the
            //penalty.
            services.AddSingleton <ConnectionMultiplexer>(sp =>
            {
                var settings      = sp.GetRequiredService <IOptions <BasketSettings> >().Value;
                var configuration = ConfigurationOptions.Parse(settings.ConnectionString, true);

                configuration.ResolveDns = true;

                return(ConnectionMultiplexer.Connect(configuration));
            });

            if (Configuration.GetValue <bool>("AzureServiceBusEnabled"))
            {
                services.AddSingleton <IServiceBusPersisterConnection>(sp =>
                {
                    var settings = sp.GetRequiredService <IOptions <BasketSettings> >().Value;
                    var logger   = sp.GetRequiredService <ILogger <DefaultServiceBusPersisterConnection> >();

                    var serviceBusConnection = new ServiceBusConnectionStringBuilder(settings.EventBusConnection);

                    return(new DefaultServiceBusPersisterConnection(serviceBusConnection, logger));
                });
            }
            else
            {
                services.AddSingleton <IRabbitMQPersistentConnection>(sp =>
                {
                    var logger = sp.GetRequiredService <ILogger <DefaultRabbitMQPersistentConnection> >();

                    var settings = sp.GetRequiredService <IOptions <BasketSettings> >().Value;

                    var factory = new ConnectionFactory()
                    {
                        HostName = settings.EventBusConnection
                    };

                    if (!string.IsNullOrEmpty(Configuration["EventBusUserName"]))
                    {
                        factory.UserName = Configuration["EventBusUserName"];
                    }

                    if (!string.IsNullOrEmpty(Configuration["EventBusPassword"]))
                    {
                        factory.Password = Configuration["EventBusPassword"];
                    }

                    var retryCount = 5;
                    if (!string.IsNullOrEmpty(Configuration["EventBusRetryCount"]))
                    {
                        retryCount = int.Parse(Configuration["EventBusRetryCount"]);
                    }

                    return(new DefaultRabbitMQPersistentConnection(factory, logger, retryCount));
                });
            }

            RegisterEventBus(services);

            services.AddSwaggerGen(options =>
            {
                options.DescribeAllEnumsAsStrings();
                options.SwaggerDoc("v1", new Info
                {
                    Title          = "Basket HTTP API",
                    Version        = "v1",
                    Description    = "The Basket Service HTTP API",
                    TermsOfService = "Terms Of Service"
                });

                options.AddSecurityDefinition("oauth2", new OAuth2Scheme
                {
                    Type             = "oauth2",
                    Flow             = "implicit",
                    AuthorizationUrl = $"{Configuration.GetValue<string>("IdentityUrlExternal")}/connect/authorize",
                    TokenUrl         = $"{Configuration.GetValue<string>("IdentityUrlExternal")}/connect/token",
                    Scopes           = new Dictionary <string, string>()
                    {
                        { "basket", "Basket API" }
                    }
                });

                options.OperationFilter <AuthorizeCheckOperationFilter>();
            });

            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                                  builder => builder.AllowAnyOrigin()
                                  .AllowAnyMethod()
                                  .AllowAnyHeader()
                                  .AllowCredentials());
            });
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddTransient <IBasketRepository, RedisBasketRepository>();
            services.AddTransient <IIdentityService, IdentityService>();

            services.AddOptions();

            var container = new ContainerBuilder();

            container.Populate(services);

            return(new AutofacServiceProvider(container.Build()));
        }
Ejemplo n.º 10
0
        protected virtual void ConfigureServices(IServiceCollection services, IConfiguration configuration, IHostEnvironment hostEnvironment, params Assembly[] assemblies)
        {
            var logger = new SerilogLoggerFactory(Log.Logger).CreateLogger <Host>();

            logger.LogInformation("Starting service configuration of {appName}", appName);

            var redisConnectionString = configuration.GetValue("REDIS_CONNECTIONSTRING", string.Empty);

            if (!string.IsNullOrEmpty(redisConnectionString))
            {
                logger.LogInformation("Configuring Redis cache");
                services.AddStackExchangeRedisCache(options =>
                {
                    options.Configuration = redisConnectionString;
                });
                services.AddDataProtection()
                .SetApplicationName(appName)
                .PersistKeysToStackExchangeRedis(ConnectionMultiplexer.Connect(redisConnectionString), $"{appName}-data-protection-keys");
            }
            else
            {
                logger.LogInformation("Configuring in-memory cache");
                services.AddDistributedMemoryCache();
                var dpBuilder = services.AddDataProtection()
                                .SetApplicationName(appName);

                var dataProtectionPath = configuration.GetValue("KEY_RING_PATH", string.Empty);
                if (!string.IsNullOrEmpty(dataProtectionPath))
                {
                    dpBuilder.PersistKeysToFileSystem(new DirectoryInfo(dataProtectionPath));
                }
            }

            services.AddHealthChecks()
            .AddCheck($"ready hc", () => HealthCheckResult.Healthy("ready"), new[] { HealthCheckReadyTag })
            .AddCheck($"live hc", () => HealthCheckResult.Healthy("alive"), new[] { HealthCheckAliveTag });

            services
            .AddHttpContextAccessor()
            .AddResponseCompression(opts => opts.EnableForHttps = true);

            var mvcBuilder = services.AddControllers();

            foreach (var assembly in assemblies)
            {
                mvcBuilder.AddApplicationPart(assembly).AddControllersAsServices();
            }

            services.AddAutoMapper((sp, cfg) => { cfg.ConstructServicesUsing(t => sp.GetRequiredService(t)); }, assemblies);
            services.AddCors(opts => opts.AddDefaultPolicy(policy =>
            {
                // try to get array of origins from section array
                var corsOrigins = configuration.GetSection("app:cors:origins").GetChildren().Select(c => c.Value).ToArray();
                // try to get array of origins from value
                if (!corsOrigins.Any())
                {
                    corsOrigins = configuration.GetValue("app:cors:origins", string.Empty).Split(',');
                }
                corsOrigins = corsOrigins.Where(o => !string.IsNullOrWhiteSpace(o)).ToArray();
                if (corsOrigins.Any())
                {
                    policy.SetIsOriginAllowedToAllowWildcardSubdomains().WithOrigins(corsOrigins);
                }
            }));
            services.Configure <ForwardedHeadersOptions>(options =>
            {
                options.ForwardedHeaders = ForwardedHeaders.All;
                options.KnownNetworks.Clear();
                options.KnownProxies.Clear();
            });

            services.Configure <ExceptionHandlerOptions>(opts => opts.AllowStatusCode404Response = true);

            services.ConfigureComponentServices(configuration, hostEnvironment, logger, assemblies);

            services.TryAddSingleton <ResolverFactory>(new DnsResolverFactory(refreshInterval: TimeSpan.FromSeconds(15)));
            services.TryAddSingleton <LoadBalancerFactory, PickFirstBalancerFactory>();

            services.AddOpenTelemetryTracing(builder =>
            {
                builder
                .AddConsoleExporter()
                .AddSource(appName)
                .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService(serviceName: appName, serviceVersion: "1.0.0.0")).AddHttpClientInstrumentation()
                .AddAspNetCoreInstrumentation()
                .AddGrpcCoreInstrumentation()
                .AddGrpcClientInstrumentation()
                .AddRedisInstrumentation();
            });
            services.AddSingleton(TracerProvider.Default.GetTracer(appName));

            // add background tasks
            services.AddBackgroundTasks(logger, assemblies);
        }
Ejemplo n.º 11
0
        public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration(configuration =>
        {
            configuration.AddCommandLine(args);
            configuration.AddEnvironmentVariables();
        })
        .ConfigureServices((hostContext, services) =>
        {
            services.AddLogging();
            services.AddTransient(svc =>
            {
                var configuration  = svc.GetRequiredService <IConfiguration>();
                var eventGridTopic = configuration.GetValue <string>("EVENTGRID_TOPIC_URI");
                var eventGridKey   = configuration.GetValue <string>("EVENTGRID_AUTH_KEY");


                return(EventGridPublisherBuilder
                       .ForTopic(eventGridTopic)
                       .UsingAuthenticationKey(eventGridKey)
                       .Build());
            });
            services.AddServiceBusQueueMessagePump(configuration => configuration["ARCUS_SERVICEBUS_CONNECTIONSTRING"])
            .WithServiceBusMessageHandler <OrdersAzureServiceBusMessageHandler, Order>();

            services.AddTcpHealthProbes("ARCUS_HEALTH_PORT", builder => builder.AddCheck("sample", () => HealthCheckResult.Healthy()));
        });
Ejemplo n.º 12
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddLogging(configure => configure.AddSerilog(dispose: true));

            // Adjust Kestrel options to allow sync IO
            services.Configure <KestrelServerOptions>(options =>
            {
                options.AllowSynchronousIO = true;
            });

            // Add a memory cache
            services.AddMemoryCache();

            services.AddSoapCore();
            services.AddSingleton <IReceiveFromHubService>(new ReceiveFromHubService(Configuration, Env));


            services.AddSingleton(_loggerFactory.CreateLogger("OneStopUtils"));
            services.AddSingleton(Log.Logger);

            services.AddControllers(config =>
            {
                config.EnableEndpointRouting = false;
                if (!string.IsNullOrEmpty(Configuration["JWT_TOKEN_KEY"]))
                {
                    var policy = new AuthorizationPolicyBuilder()
                                 .RequireAuthenticatedUser()
                                 .Build();
                    config.Filters.Add(new AuthorizeFilter(policy));
                }
            });

            // Note that we do not introduce a default JsonOptions here because we want enums to be presented as numeric values
            // in the API for ease of testing.

            // Other ConfigureServices() code...
            services.AddSwaggerGen(c =>
            {
                c.CustomOperationIds(e => $"{e.ActionDescriptor.RouteValues["controller"]}_{e.HttpMethod}");
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "JAG OneStop Service", Version = "v1"
                });
                c.ParameterFilter <AutoRestParameterFilter>();
                // This is only required because Swashbuckle does not present enums correctly
                c.AddEnumsWithValuesFixFilters();
                string baseUri = Configuration["BASE_URI"];
                if (baseUri != null)
                {
                    // ensure baseUri is in the right format.
                    baseUri = baseUri.TrimEnd('/') + @"/";
                    c.AddSecurityDefinition("bearer", new OpenApiSecurityScheme
                    {
                        Type  = SecuritySchemeType.OAuth2,
                        Flows = new OpenApiOAuthFlows
                        {
                            Implicit = new OpenApiOAuthFlow
                            {
                                AuthorizationUrl = new Uri(baseUri + "api/authentication/redirect/" + Configuration["JWT_TOKEN_KEY"]),
                                Scopes           = new Dictionary <string, string>
                                {
                                    { "openid", "oidc standard" }
                                }
                            }
                        }
                    });
                }

                c.OperationFilter <AuthenticationRequirementsOperationFilter>();
            });

            services.AddIdentity <IdentityUser, IdentityRole>()
            .AddDefaultTokenProviders();

            if (!string.IsNullOrEmpty(Configuration["JWT_TOKEN_KEY"]))
            {
                // Configure JWT authentication
                services.AddAuthentication(o =>
                {
                    o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    o.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
                }).AddJwtBearer(o =>
                {
                    o.SaveToken                 = true;
                    o.RequireHttpsMetadata      = false;
                    o.TokenValidationParameters = new TokenValidationParameters
                    {
                        RequireExpirationTime = false,
                        ValidIssuer           = Configuration["JWT_VALID_ISSUER"],
                        ValidAudience         = Configuration["JWT_VALID_AUDIENCE"],
                        IssuerSigningKey      = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT_TOKEN_KEY"]))
                    };
                });
            }

            services.AddHangfire(config =>
            {
                // Change this line if you wish to have Hangfire use persistent storage.
                config.UseMemoryStorage();
                // enable console logs for jobs
                config.UseConsole();
            });

            // health checks.
            services.AddHealthChecks()
            .AddCheck("one-stop-service", () => HealthCheckResult.Healthy("OK"));
        }
Ejemplo n.º 13
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.Configure <ForwardedHeadersOptions>(options =>
            {
                if (IsK8S)
                {
                    options.ForwardedHeaders =
                        ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
                }
                else
                {
                    options.ForwardedHeaders =
                        ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost;

                    options.ForwardedHostHeaderName  = "x-forwarded-host";
                    options.ForwardedProtoHeaderName = "x-forwarded-proto";
                    options.KnownNetworks.Clear();
                    options.KnownProxies.Clear();
                }
            });

            services.Configure <CookiePolicyOptions>(options =>
            {
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            var connectionString   = Configuration.GetConnectionString("IdentityConnectionString");
            var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

            services.AddDbContext <ApplicationDbContext>(options =>
            {
                options.UseNpgsql(connectionString);
            });

            services.AddHealthChecks()
            .AddCheck("self", () => HealthCheckResult.Healthy())
            .AddNpgSql(connectionString);

            services.AddCors(o => o.AddPolicy("ServerPolicy", builder =>
            {
                builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                .WithExposedHeaders("WWW-Authenticate");
            }));

            services.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            services.AddIdentityServer(options =>
            {
                options.Events.RaiseErrorEvents       = true;
                options.Events.RaiseInformationEvents = true;
                options.Events.RaiseFailureEvents     = true;
                options.Events.RaiseSuccessEvents     = true;
            })
            .AddDeveloperSigningCredential()
            .AddAspNetIdentity <ApplicationUser>()
            .AddConfigurationStore(options =>
            {
                options.ConfigureDbContext = builder =>
                                             builder.UseNpgsql(connectionString, sql => sql.MigrationsAssembly(migrationsAssembly));
            })
            .AddOperationalStore(options =>
            {
                options.ConfigureDbContext = builder =>
                                             builder.UseNpgsql(connectionString, sql => sql.MigrationsAssembly(migrationsAssembly));

                // options.EnableTokenCleanup = false;
                // options.TokenCleanupInterval = 30; // interval in seconds
            });

            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info
                {
                    Title          = "Restaurant - Identity HTTP API",
                    Version        = "v1",
                    TermsOfService = "Terms Of Service"
                });
            });

            services.AddTransient <ILoginViewModelBuilder, LoginViewModelBuilder>();
            services.AddTransient <ILogOutViewModelBuilder, LogOutViewModelBuilder>();
            services.AddTransient <ILoggedOutViewModelBuilder, LoggedOutViewModelBuilder>();
            services.AddTransient <ILoginProvider, LoginProvider>();
            services.AddAutoMapper(typeof(Startup));
        }
Ejemplo n.º 14
0
        public async Task <HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = new CancellationToken())
        {
            var isStorageOk = await _advertStorageService.CheckHealthAsync();

            return(await Task.FromResult(isStorageOk?HealthCheckResult.Healthy("Storage is Healthy") : HealthCheckResult.Unhealthy("Storage is Unhealthy")));
        }
Ejemplo n.º 15
0
        public async Task <HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = new CancellationToken())
        {
            try
            {
                using (var connection = new SqlConnection(_connection))
                {
                    await connection.OpenAsync(cancellationToken);

                    var command = connection.CreateCommand();
                    command.CommandText = "select count(id) from produtos";

                    return(Convert.ToInt32(await command.ExecuteScalarAsync(cancellationToken)) > 0 ? HealthCheckResult.Healthy() : HealthCheckResult.Unhealthy());
                }
            }
            catch (Exception)
            {
                return(HealthCheckResult.Unhealthy());
            }
        }
Ejemplo n.º 16
0
 protected override ValueTask <HealthCheckResult> CheckAsync(CancellationToken token = default)
 {
     return(new ValueTask <HealthCheckResult>(HealthCheckResult.Healthy("OK")));
 }
Ejemplo n.º 17
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)
        {
            var migrationAssembly = typeof(Startup).Assembly.GetName().Name;

            Log.Information(Configuration["ConnectionString"]);
            var connectionString = Configuration["ConnectionString"];

            services.Configure <AccountOptions>(Configuration);
            services.AddDbContext <ApplicationDbContext>(builder => builder.UseMySql(connectionString, m =>
            {
                m.MigrationsAssembly(migrationAssembly);
                //Configuring Connection Resiliency: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency
                m.EnableRetryOnFailure(maxRetryCount: 10, maxRetryDelay: TimeSpan.FromSeconds(30),
                                       errorNumbersToAdd: null);
            }));

            services.AddIdentity <ApplicationUser, ApplicationRole>(config =>
            {
                config.Password.RequiredLength         = 4;
                config.Password.RequireDigit           = false;
                config.Password.RequireNonAlphanumeric = false;
                config.Password.RequireUppercase       = false;
                config.Password.RequireLowercase       = false;
            })
            .AddUserManager <UserManager <ApplicationUser> >()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            services.Configure <CookiePolicyOptions>(options =>
            {
                options.MinimumSameSitePolicy = SameSiteMode.Lax;
            });

            services.AddIdentityServer()
            .AddAspNetIdentity <ApplicationUser>()
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryClients(Config.GetClients())
            .AddDeveloperSigningCredential();

            services.AddCors(options =>
                             options.AddPolicy("AllowAll", p => p.AllowAnyOrigin()
                                               .AllowAnyMethod()
                                               .AllowAnyHeader()));

            services.AddHealthChecks()
            .AddCheck("self", () => HealthCheckResult.Healthy())
            .AddMySql(connectionString, name: "DB");

            services.AddControllersWithViews();

            services.AddOpenTracing();

            services.AddSingleton <ITracer>(serviceProvider =>
            {
                string serviceName = serviceProvider.GetRequiredService <IWebHostEnvironment>().ApplicationName;

                // This will log to a default localhost installation of Jaeger.
                var tracer = new Tracer.Builder(serviceName)
                             .WithSampler(new ConstSampler(true))
                             .Build();

                // Allows code that can't use DI to also access the tracer.
                GlobalTracer.Register(tracer);

                return(tracer);
            });
        }
Ejemplo n.º 18
0
 public Task <HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default(CancellationToken))
 {
     // Some Liveness check
     // Console.WriteLine("Liveness Health check executed.");
     return(Task.FromResult(HealthCheckResult.Healthy()));
 }
Ejemplo n.º 19
0
 public async Task <HealthCheckResult> CheckHealthAsync(HealthCheckContext hcContext, CancellationToken cancellationToken = default)
 {
     return(await context.Database.CanConnectAsync(cancellationToken)
       ? HealthCheckResult.Healthy(context.Database.GetDbConnection().ConnectionString)
       : HealthCheckResult.Unhealthy(context.Database.GetDbConnection().ConnectionString));
 }
Ejemplo n.º 20
0
 protected override HealthCheckResult Check()
 {
     return(HealthCheckResult.Healthy("OK"));
 }
Ejemplo n.º 21
0
        protected override ValueTask <HealthCheckResult> CheckAsync(CancellationToken token = default)
        {
            _database.Open();

            return(new ValueTask <HealthCheckResult>(HealthCheckResult.Healthy()));
        }
Ejemplo n.º 22
0
        public async Task <HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
        {
            await GetGrain().CountAsync();

            return(HealthCheckResult.Healthy("Orleans must establish communication."));
        }
Ejemplo n.º 23
0
 /// <summary>
 ///     Starts the health check and returns <see cref="HealthCheckResult" />
 /// </summary>
 public HealthCheckResult StartHealthCheck()
 {
     return(_cache.Any()
         ? HealthCheckResult.Healthy($"Cache has {_cache.Count()} items.")
         : HealthCheckResult.Healthy("Cache is empty."));
 }
Ejemplo n.º 24
0
        /// <summary>
        /// Perform a query to check how many holidays are registered in the Holidays table in current year.
        /// </summary>
        /// <param name="context">Represent the context information associated.</param>
        /// <param name="cancellationToken">Notification that operations should be canceled.</param>
        /// <returns><see cref="HealthCheckResult"/>The result of a health check</returns>
        public async Task <HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = new CancellationToken())
        {
            try
            {
                DateTime startDate = new DateTime(DateTime.Now.Year, 01, 01);
                DateTime endDate   = new DateTime(DateTime.Now.Year, 12, 31);

                using (var connection = new SqlConnection(_connection))
                {
                    await connection.OpenAsync(cancellationToken);

                    var command = connection.CreateCommand();
                    command.CommandText = $"select count(id) from holidays where holidaydate >= '{startDate.ToSqlDate()}' and holidaydate <= '{endDate.ToSqlDate()}'";

                    var x = Convert.ToInt32(await command.ExecuteScalarAsync(cancellationToken)) > 0 ? HealthCheckResult.Healthy() : HealthCheckResult.Unhealthy();

                    return(Convert.ToInt32(await command.ExecuteScalarAsync(cancellationToken)) > 0 ? HealthCheckResult.Healthy() : HealthCheckResult.Unhealthy());
                }
            }
            catch (Exception ex)
            {
                return(HealthCheckResult.Unhealthy());
            }
        }
Ejemplo n.º 25
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(config =>
            {
                if (!string.IsNullOrEmpty(Configuration["JWT_TOKEN_KEY"]))
                {
                    var policy = new AuthorizationPolicyBuilder()
                                 .RequireAuthenticatedUser()
                                 .Build();
                    config.Filters.Add(new AuthorizeFilter(policy));
                }
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            // Other ConfigureServices() code...

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "JAG SPICE to CARLA Transfer Service", Version = "v1"
                });
                c.DescribeAllEnumsAsStrings();
                c.SchemaFilter <EnumTypeSchemaFilter>();
            });

            services.AddIdentity <IdentityUser, IdentityRole>()
            .AddDefaultTokenProviders();

            if (!string.IsNullOrEmpty(Configuration["JWT_TOKEN_KEY"]))
            {
                // Configure JWT authentication
                services.AddAuthentication(o =>
                {
                    o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    o.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
                }).AddJwtBearer(o =>
                {
                    o.SaveToken                 = true;
                    o.RequireHttpsMetadata      = false;
                    o.TokenValidationParameters = new TokenValidationParameters()
                    {
                        RequireExpirationTime = false,
                        ValidIssuer           = Configuration["JWT_VALID_ISSUER"],
                        ValidAudience         = Configuration["JWT_VALID_AUDIENCE"],
                        IssuerSigningKey      = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT_TOKEN_KEY"]))
                    };
                });
            }

            // Setup Dynamics
            if (!string.IsNullOrEmpty(Configuration["DYNAMICS_ODATA_URI"]))
            {
                services.AddTransient(serviceProvider =>
                {
                    IDynamicsClient client = DynamicsSetupUtil.SetupDynamics(Configuration);
                    return(client);
                });
            }

            if (!string.IsNullOrEmpty(Configuration["SHAREPOINT_ODATA_URI"]))
            {
                SetupSharePoint(services);
            }

            services.AddHangfire(config =>
            {
                // Change this line if you wish to have Hangfire use persistent storage.
                config.UseMemoryStorage();
                // enable console logs for jobs
                config.UseConsole();
            });

            // health checks.
            services.AddHealthChecks()
            .AddCheck("spice-sync", () => HealthCheckResult.Healthy("Ok"))
            .AddCheck <DynamicsHealthCheck>("Dynamics");
        }
Ejemplo n.º 26
0
        public async Task <HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
        {
            var result = await _service.CheckHealthAsync();

            return(result ? HealthCheckResult.Healthy() : HealthCheckResult.Unhealthy());
        }
        public async Task <HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
        {
            try
            {
                var value = Stores.GetOrAdd(_options, o =>
                {
                    var store = new DocumentStore
                    {
                        Urls        = o.Urls,
                        Certificate = o.Certificate
                    };

                    try
                    {
                        store.Initialize();
                        return(new DocumentStoreHolder
                        {
                            Store = store,
                            Legacy = false
                        });
                    }
                    catch (Exception)
                    {
                        try
                        {
                            store.Dispose();
                        }
                        catch
                        {
                            // nothing that we can do
                        }

                        throw;
                    }
                });

                var store = value.Store;

                if (string.IsNullOrWhiteSpace(_options.Database))
                {
                    await CheckServerHealthAsync(store, cancellationToken);

                    return(HealthCheckResult.Healthy());
                }

                try
                {
                    try
                    {
                        await CheckDatabaseHealthAsync(store, _options.Database, value.Legacy, cancellationToken);
                    }
                    catch (ClientVersionMismatchException e) when(e.Message.Contains(nameof(RouteNotFoundException)))
                    {
                        value.Legacy = true;
                        await CheckDatabaseHealthAsync(store, _options.Database, value.Legacy, cancellationToken);
                    }

                    return(HealthCheckResult.Healthy());
                }
                catch (DatabaseDoesNotExistException)
                {
                    return(new HealthCheckResult(context.Registration.FailureStatus, $"RavenDB does not contain '{_options.Database}' database."));
                }
            }
            catch (Exception ex)
            {
                return(new HealthCheckResult(context.Registration.FailureStatus, exception: ex));
            }
        }
Ejemplo n.º 28
0
 protected async override ValueTask <HealthCheckResult> CheckAsync(CancellationToken cancellationToken = new CancellationToken()) =>
 HealthCheckResult.Healthy($"Host = {Environment.MachineName}, Version = {AppVersion}");
Ejemplo n.º 29
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            RegisterAppInsights(services);

            // Add framework services.
            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(Configuration["ConnectionString"],
                                                                              sqlServerOptionsAction: sqlOptions =>
            {
                sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name);
                //Configuring Connection Resiliency: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency
                sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null);
            }));

            services.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            services.Configure <AppSettings>(Configuration);

            if (Configuration.GetValue <string>("IsClusterEnv") == bool.TrueString)
            {
                services.AddDataProtection(opts =>
                {
                    opts.ApplicationDiscriminator = "eshop.identity";
                })
                .PersistKeysToStackExchangeRedis(ConnectionMultiplexer.Connect(Configuration["DPConnectionString"]), "DataProtection-Keys");
            }

            services.AddHealthChecks()
            .AddCheck("self", () => HealthCheckResult.Healthy())
            .AddSqlServer(Configuration["ConnectionString"],
                          name: "IdentityDB-check",
                          tags: new string[] { "IdentityDB" });

            services.AddTransient <ILoginService <ApplicationUser>, EFLoginService>();
            services.AddTransient <IRedirectService, RedirectService>();

            var connectionString   = Configuration["ConnectionString"];
            var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

            // Adds IdentityServer
            services.AddIdentityServer(x =>
            {
                x.IssuerUri = "null";
                x.Authentication.CookieLifetime = TimeSpan.FromHours(2);
            })
            .AddDevspacesIfNeeded(Configuration.GetValue("EnableDevspaces", false))
            .AddSigningCredential(Certificate.Get())
            .AddAspNetIdentity <ApplicationUser>()
            .AddConfigurationStore(options =>
            {
                options.ConfigureDbContext = builder => builder.UseSqlServer(connectionString,
                                                                             sqlServerOptionsAction: sqlOptions =>
                {
                    sqlOptions.MigrationsAssembly(migrationsAssembly);
                    //Configuring Connection Resiliency: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency
                    sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null);
                });
            })
            .AddOperationalStore(options =>
            {
                options.ConfigureDbContext = builder => builder.UseSqlServer(connectionString,
                                                                             sqlServerOptionsAction: sqlOptions =>
                {
                    sqlOptions.MigrationsAssembly(migrationsAssembly);
                    //Configuring Connection Resiliency: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency
                    sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null);
                });
            })
            .Services.AddTransient <IProfileService, ProfileService>();

            //services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
            services.AddControllers();
            services.AddControllersWithViews();
            services.AddRazorPages();

            var container = new ContainerBuilder();

            container.Populate(services);

            return(new AutofacServiceProvider(container.Build()));
        }
 internal override void RegisterChecks(HealthCheckBuilder checks)
 {
     checks
     .AddCheck("Default", () => HealthCheckResult.Healthy("OK"))
     .AddSqlCheck(connectionStringName, _connectionString);
 }