public TradesMigrationService(
            ICandlesHistoryRepository candlesHistoryRepository,
            TradesMigrationHealthService tradesMigrationHealthService,
            ILogFactory logFactory,
            IHealthNotifier healthNotifier,
            string sqlConnString,
            int sqlQueryBatchSize,
            TimeSpan sqlTimeout,
            int candlesPersistenceQueueMaxSize
            )
        {
            _candlesHistoryRepository     = candlesHistoryRepository ?? throw new ArgumentNullException(nameof(candlesHistoryRepository));
            _tradesMigrationHealthService = tradesMigrationHealthService ?? throw new ArgumentNullException(nameof(tradesMigrationHealthService));
            _logFactory     = logFactory;
            _healthNotifier = healthNotifier;

            if (logFactory == null)
            {
                throw new ArgumentNullException(nameof(logFactory));
            }

            _log = logFactory.CreateLog(this);

            _sqlConnString     = sqlConnString;
            _sqlQueryBatchSize = sqlQueryBatchSize;
            _sqlTimeout        = sqlTimeout;
            _candlesPersistenceQueueMaxSize = Convert.ToInt32(candlesPersistenceQueueMaxSize * 1.1);  // Safe reserve
        }
        public TradesSqlHistoryRepository(
            string sqlConnString,
            int sqlQueryBatchSize,
            TimeSpan sqlTimeout,
            ILogFactory logFactory,
            IHealthNotifier healthNotifier,
            DateTime?migrateByDate,
            string assetPairId,
            string searchToken
            )
        {
            _sqlQueryBatchSize = sqlQueryBatchSize;
            _sqlConnString     = !string.IsNullOrWhiteSpace(sqlConnString) ? sqlConnString : throw new ArgumentNullException(nameof(sqlConnString));
            _sqlTimeout        = sqlTimeout;
            _healthNotifier    = healthNotifier;

            if (logFactory == null)
            {
                throw new ArgumentNullException(nameof(logFactory));
            }

            _log = logFactory.CreateLog(this);

            StartingRowOffset = 0; // Will read everything.

            AssetPairId   = assetPairId;
            SearchToken   = searchToken;
            MigrateByDate = migrateByDate;
        }
コード例 #3
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            try
            {
                services.AddMvc()
                .AddJsonOptions(options =>
                {
                    options.SerializerSettings.ContractResolver =
                        new Newtonsoft.Json.Serialization.DefaultContractResolver();
                });

                services.AddSwaggerGen(options =>
                {
                    options.DefaultLykkeConfiguration("v1", "PayAuth API");
                });

                Mapper.Initialize(cfg =>
                {
                    cfg.AddProfiles(GetType().Assembly);
                    cfg.AddProfiles(typeof(Services.AutoMapperProfile));
                });

                Mapper.Configuration.AssertConfigurationIsValid();

                var builder = new ContainerBuilder();

                var appSettings = Configuration.LoadSettings <AppSettings>(opt => { });

                services.AddLykkeLogging(
                    appSettings.ConnectionString(x => x.PayAuthService.Db.LogsConnString),
                    "PayAuthLog",
                    appSettings.CurrentValue.SlackNotifications.AzureQueue.ConnectionString,
                    appSettings.CurrentValue.SlackNotifications.AzureQueue.QueueName);

                builder.RegisterModule(new ServiceModule(appSettings.Nested(x => x.PayAuthService)));

                builder.RegisterModule(new CqrsModule(
                                           appSettings.Nested(x => x.PayAuthService.Cqrs),
                                           appSettings.CurrentValue.PayAuthService.ResetPasswordUrlTemplate));

                builder.Populate(services);

                ApplicationContainer = builder.Build();

                Log = ApplicationContainer.Resolve <ILogFactory>().CreateLog(this);

                HealthNotifier = ApplicationContainer.Resolve <IHealthNotifier>();

                return(new AutofacServiceProvider(ApplicationContainer));
            }
            catch (Exception ex)
            {
                Log?.Critical(ex);
                throw;
            }
        }
コード例 #4
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            try
            {
                services.AddMvc()
                .AddJsonOptions(options =>
                {
                    options.SerializerSettings.ContractResolver =
                        new Newtonsoft.Json.Serialization.DefaultContractResolver();
                });

                services.AddSwaggerGen(options =>
                {
                    options.DefaultLykkeConfiguration("v1", "PayCallback API");
                });

                var builder     = new ContainerBuilder();
                var appSettings = Configuration.LoadSettings <AppSettings>();
                _monitoringServiceUrl = appSettings.CurrentValue.MonitoringServiceClient?.MonitoringServiceUrl;

                services.AddLykkeLogging
                (
                    appSettings.ConnectionString(x => x.PayCallbackService.Db.LogsConnString),
                    "PayCallbackLog",
                    appSettings.CurrentValue.SlackNotifications.AzureQueue.ConnectionString,
                    appSettings.CurrentValue.SlackNotifications.AzureQueue.QueueName
                );

                builder.RegisterModule(new ServiceModule(appSettings.Nested(x => x.PayCallbackService)));

                builder.Populate(services);

                ApplicationContainer = builder.Build();

                _log            = ApplicationContainer.Resolve <ILogFactory>().CreateLog(this);
                _healthNotifier = ApplicationContainer.Resolve <IHealthNotifier>();

                Mapper.Initialize(cfg =>
                {
                    cfg.AddProfiles(typeof(Models.AutoMapperProfile));
                    cfg.AddProfiles(typeof(AzureRepositories.AutoMapperProfile));
                    cfg.AddProfiles(typeof(Services.AutoMapperProfile));
                });

                Mapper.AssertConfigurationIsValid();

                return(new AutofacServiceProvider(ApplicationContainer));
            }
            catch (Exception ex)
            {
                _log?.Error(ex);
                throw;
            }
        }
コード例 #5
0
        public AppLifetimeHandler(
            ILogFactory logFactory,
            IHealthNotifier healthNotifier,
            IStartupManager startupManager,
            IShutdownManager shutdownManager,
            IWebHostEnvironment hostingEnvironment)
        {
            _logFactory         = logFactory ?? throw new ArgumentNullException(nameof(logFactory));
            _healthNotifier     = healthNotifier ?? throw new ArgumentNullException(nameof(healthNotifier));
            _startupManager     = startupManager ?? throw new ArgumentNullException(nameof(startupManager));
            _shutdownManager    = shutdownManager ?? throw new ArgumentNullException(nameof(shutdownManager));
            _hostingEnvironment = hostingEnvironment ?? throw new ArgumentNullException(nameof(hostingEnvironment));

            _log = logFactory.CreateLog(this);
        }
コード例 #6
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            try
            {
                services.AddMvc(options =>
                {
                    options.InputFormatters.Insert(0, new RawRequestBodyInputFormatter());
                })
                .AddJsonOptions(options =>
                {
                    options.SerializerSettings.ContractResolver =
                        new Newtonsoft.Json.Serialization.DefaultContractResolver();
                });

                services.AddSwaggerGen(options =>
                {
                    options.DefaultLykkeConfiguration("v1", "PaySign API");
                    options.OperationFilter <FileUploadOperationFilter>();
                });

                var builder     = new ContainerBuilder();
                var appSettings = Configuration.LoadSettings <AppSettings>();

                services.AddLykkeLogging
                (
                    appSettings.ConnectionString(x => x.PaySignService.Db.LogsConnString),
                    "PaySignLog",
                    appSettings.CurrentValue.SlackNotifications.AzureQueue.ConnectionString,
                    appSettings.CurrentValue.SlackNotifications.AzureQueue.QueueName
                );

                builder.RegisterModule(new ServiceModule(appSettings.Nested(x => x.PaySignService)));
                builder.Populate(services);
                ApplicationContainer = builder.Build();

                _log            = ApplicationContainer.Resolve <ILogFactory>().CreateLog(this);
                _healthNotifier = ApplicationContainer.Resolve <IHealthNotifier>();

                return(new AutofacServiceProvider(ApplicationContainer));
            }
            catch (Exception ex)
            {
                _log?.Critical(ex);
                throw;
            }
        }
コード例 #7
0
        public AppLifetimeHandler(
            ILogFactory logFactory,
            IHealthNotifier healthNotifier,
            IStartupManager startupManager,
            IShutdownManager shutdownManager,
            IWebHostEnvironment hostingEnvironment,
            IConfigurationRoot configurationRoot,
            IReloadingManager <MonitoringServiceClientSettings> monitoringServiceClientSettings)
        {
            _logFactory         = logFactory ?? throw new ArgumentNullException(nameof(logFactory));
            _healthNotifier     = healthNotifier ?? throw new ArgumentNullException(nameof(healthNotifier));
            _startupManager     = startupManager ?? throw new ArgumentNullException(nameof(startupManager));
            _shutdownManager    = shutdownManager ?? throw new ArgumentNullException(nameof(shutdownManager));
            _hostingEnvironment = hostingEnvironment ?? throw new ArgumentNullException(nameof(hostingEnvironment));
            _configurationRoot  = configurationRoot ?? throw new ArgumentNullException(nameof(configurationRoot));
            _monitoringServiceClientSettings = monitoringServiceClientSettings ?? throw new ArgumentNullException(nameof(monitoringServiceClientSettings));

            _log = logFactory.CreateLog(this);
        }
コード例 #8
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            try
            {
                services.AddMvc()
                .AddJsonOptions(options =>
                {
                    options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                    options.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter {
                        CamelCaseText = true
                    });
                });

                services.AddSwaggerGen(options =>
                {
                    options.DefaultLykkeConfiguration("v1", "LoggingAdapter API");
                });

                var builder     = new ContainerBuilder();
                var appSettings = Configuration.LoadSettings <AppSettings>();

                services.AddLykkeLogging(
                    appSettings.Nested(s => s.LoggingAdapterService.Db.LogsConnString),
                    "LoggingAdapter",
                    appSettings.Nested(s => s.SlackNotifications.AzureQueue.ConnectionString).CurrentValue,
                    appSettings.Nested(s => s.SlackNotifications.AzureQueue.QueueName).CurrentValue);

                builder.Populate(services);
                builder.RegisterModule(new ServiceModule(appSettings));
                ApplicationContainer = builder.Build();


                Log            = ApplicationContainer.Resolve <ILogFactory>().CreateLog(this);
                HealthNotifier = ApplicationContainer.Resolve <IHealthNotifier>();

                return(new AutofacServiceProvider(ApplicationContainer));
            }
            catch (Exception ex)
            {
                Log?.Critical(ex);
                throw;
            }
        }
コード例 #9
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 http://go.microsoft.com/fwlink/?LinkID=398940
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(o =>
            {
                o.Filters.Add(new HandleAllExceptionsFilterFactory());
                o.Filters.Add(new ForceLogoutUserFilterFactory());
                o.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
                o.ModelBinderProviders.Insert(0, new DecimalInvariantModelBinderProvider());
            });

            services.AddApplicationInsightsTelemetry(Configuration);

            services.AddAuthentication("Cookie")
            .AddCookie("Cookie", options =>
            {
                options.LoginPath         = new PathString("/Home/Index/");
                options.AccessDeniedPath  = new PathString("/Home/Index/");
                options.SlidingExpiration = true;
                options.ExpireTimeSpan    = TimeSpan.FromMinutes(1);
            });

            var appSettings = Configuration.LoadSettings <BackOfficeBundle>();

            _monitoringServiceUrl = appSettings.CurrentValue.MonitoringServiceClient?.MonitoringServiceUrl;
            _supportedBrowsers    = appSettings.CurrentValue.PayBackOffice.SupportedBrowsers;

            services.AddLykkeLogging
            (
                appSettings.ConnectionString(x => x.PayBackOffice.Db.LogsConnString),
                "LogBackoffce",
                appSettings.CurrentValue.SlackNotifications.AzureQueue.ConnectionString,
                appSettings.CurrentValue.SlackNotifications.AzureQueue.QueueName
            );

            ApplicationContainer = Dependencies.BindDependecies(services, Configuration);

            _log            = ApplicationContainer.Resolve <ILogFactory>().CreateLog(this);
            _healthNotifier = ApplicationContainer.Resolve <IHealthNotifier>();

            return(new AutofacServiceProvider(ApplicationContainer));
        }
コード例 #10
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime appLifetime)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            _healthNotifier = app.ApplicationServices.GetService <IHealthNotifier>();
            _removeOldSpentOutputsPeriodicalHandler = app.ApplicationServices.GetService <RemoveOldSpentOutputsPeriodicalHandler>();
            _healStatusPeriodicalHandler            = app.ApplicationServices.GetService <UpdateHealStatusPeriodicalHandler>();
            app.UseMiddleware(typeof(ApiErrorHandler));
            app.UseLykkeForwardedHeaders();
            app.UseMvc();
            app.UseSwagger();
            app.UseSwaggerUI(x =>
            {
                x.RoutePrefix = "swagger/ui";
                x.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
            });
            app.UseStaticFiles();

            appLifetime.ApplicationStarted.Register(() => StartApplication().GetAwaiter().GetResult());
            appLifetime.ApplicationStopped.Register(() => CleanUp().GetAwaiter().GetResult());
        }
コード例 #11
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            try
            {
                services.AddMvc()
                .AddJsonOptions(options =>
                {
                    options.SerializerSettings.ContractResolver =
                        new Newtonsoft.Json.Serialization.DefaultContractResolver();
                });

                services.AddSwaggerGen(opt => opt.DefaultLykkeConfiguration("v1", "PayInternal API"));

                EntityMetamodel.Configure(new AnnotationsBasedMetamodelProvider());

                var builder = new ContainerBuilder();

                var appSettings = Configuration.LoadSettings <AppSettings>(options =>
                {
                    options.SetConnString(x => x.SlackNotifications.AzureQueue.ConnectionString);
                    options.SetQueueName(x => x.SlackNotifications.AzureQueue.QueueName);
                    options.SenderName = "PayInternal API";
                });

                _monitoringServiceUrl = appSettings.CurrentValue.MonitoringServiceClient?.MonitoringServiceUrl;

                services.AddLykkeLogging(
                    appSettings.ConnectionString(x => x.PayInternalService.Db.LogsConnString),
                    "PayInternalLog",
                    appSettings.CurrentValue.SlackNotifications.AzureQueue.ConnectionString,
                    appSettings.CurrentValue.SlackNotifications.AzureQueue.QueueName);

                builder.RegisterModule(new AzureRepositories.AutofacModule(
                                           appSettings.Nested(o => o.PayInternalService.Db.MerchantOrderConnString),
                                           appSettings.Nested(o => o.PayInternalService.Db.MerchantConnString),
                                           appSettings.Nested(o => o.PayInternalService.Db.PaymentRequestConnString),
                                           appSettings.Nested(o => o.PayInternalService.Db.TransferConnString)));

                builder.RegisterModule(new Services.AutofacModule(
                                           appSettings.CurrentValue.PayInternalService.ExpirationPeriods,
                                           appSettings.CurrentValue.PayInternalService.TransactionConfirmationCount,
                                           appSettings.CurrentValue.PayInternalService.Blockchain.WalletAllocationPolicy.Policies,
                                           appSettings.CurrentValue.PayInternalService.AssetPairsLocalStorage.AssetPairs,
                                           appSettings.CurrentValue.PayInternalService.CacheSettings,
                                           appSettings.CurrentValue.PayInternalService.RetryPolicy));

                builder.RegisterModule(new ServiceModule(appSettings));
                builder.RegisterModule(new CqrsModule(appSettings));

                builder.Populate(services);

                ApplicationContainer = builder.Build();

                Log = ApplicationContainer.Resolve <ILogFactory>().CreateLog(this);

                HealthNotifier = ApplicationContainer.Resolve <IHealthNotifier>();

                Mapper.Initialize(cfg =>
                {
                    cfg.ConstructServicesUsing(ApplicationContainer.Resolve);
                    cfg.AddProfiles(typeof(AutoMapperProfile));
                    cfg.AddProfiles(typeof(AzureRepositories.AutoMapperProfile));
                    cfg.AddProfiles(typeof(Services.AutoMapperProfile));
                });

                Mapper.AssertConfigurationIsValid();

                return(new AutofacServiceProvider(ApplicationContainer));
            }
            catch (Exception ex)
            {
                Log?.Critical(ex);
                throw;
            }
        }
コード例 #12
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            try
            {
                services.AddMvc()
                .AddJsonOptions(options =>
                {
                    options.SerializerSettings.Converters.Add(new StringEnumConverter());
                    options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();
                });

                services.AddSwaggerGen(options =>
                {
                    options.DefaultLykkeConfiguration(ApiVersion, ApiName);
                });

                var settingsManager = Configuration.LoadSettings <AppSettings>(options =>
                {
                    options.SetConnString(x => x.SlackNotifications.AzureQueue.ConnectionString);
                    options.SetQueueName(x => x.SlackNotifications.AzureQueue.QueueName);
                    options.SenderName = $"{AppEnvironment.Name} {AppEnvironment.Version}";
                });

                var appSettings = settingsManager.CurrentValue;

                if (appSettings.MonitoringServiceClient != null)
                {
                    _monitoringServiceUrl = appSettings.MonitoringServiceClient.MonitoringServiceUrl;
                }

                services.AddLykkeLogging(
                    settingsManager.ConnectionString(s => s.NeoApiService.Db.LogsConnString),
                    "NeoApiJobLog",
                    appSettings.SlackNotifications.AzureQueue.ConnectionString,
                    appSettings.SlackNotifications.AzureQueue.QueueName,
                    logBuilder =>
                {
                    logBuilder.AddAdditionalSlackChannel("BlockChainIntegration", opt =>
                    {
                        opt.MinLogLevel = Microsoft.Extensions.Logging.LogLevel.Information;
                        opt.IncludeHealthNotifications();
                    });

                    logBuilder.AddAdditionalSlackChannel("BlockChainIntegrationImportantMessages", opt =>
                    {
                        opt.MinLogLevel = Microsoft.Extensions.Logging.LogLevel.Warning;
                        opt.IncludeHealthNotifications();
                    });
                });

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

                var modules = new IModule[]
                {
                    new JobModule(appSettings.NeoApiService),
                    new CommonServicesModule(settingsManager),
                    new AzureRepositoriesModule(settingsManager),
                };

                foreach (var module in modules)
                {
                    builder.RegisterModule(module);
                }

                ApplicationContainer = builder.Build();

                var logFactory = ApplicationContainer.Resolve <ILogFactory>();
                _log            = logFactory.CreateLog(this);
                _healthNotifier = ApplicationContainer.Resolve <IHealthNotifier>();

                return(new AutofacServiceProvider(ApplicationContainer));
            }
            catch (Exception ex)
            {
                if (_log == null)
                {
                    Console.WriteLine(ex);
                }
                else
                {
                    _log.Critical(ex);
                }
                throw;
            }
        }
コード例 #13
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            try
            {
                services.AddMvc()
                .AddJsonOptions(options =>
                {
                    options.SerializerSettings.ContractResolver =
                        new Newtonsoft.Json.Serialization.DefaultContractResolver();
                });

                services.AddSwaggerGen(options =>
                {
                    options.DefaultLykkeConfiguration("v1", "BlockchainOperationsExecutor API");
                });

                var builder     = new ContainerBuilder();
                var appSettings = Configuration.LoadSettings <AppSettings>(o =>
                {
                    o.SetConnString(s => s.SlackNotifications.AzureQueue.ConnectionString);
                    o.SetQueueName(s => s.SlackNotifications.AzureQueue.QueueName);
                    o.SenderName = $"{AppEnvironment.Name} {AppEnvironment.Version}";
                });
                var settings = appSettings.CurrentValue;

                services.AddLykkeLogging(
                    appSettings.ConnectionString(s => s.BlockchainOperationsExecutorJob.Db.LogsConnString),
                    "BlockchainOperationsExecutorLog",
                    settings.SlackNotifications.AzureQueue.ConnectionString,
                    settings.SlackNotifications.AzureQueue.QueueName,
                    options =>
                {
                    options.AddAdditionalSlackChannel("CommonBlockChainIntegration", o =>
                    {
                        o.MinLogLevel = Microsoft.Extensions.Logging.LogLevel.Information;
                        o.SpamGuard.DisableGuarding();
                        o.IncludeHealthNotifications();
                    });
                    options.AddAdditionalSlackChannel("CommonBlockChainIntegrationImportantMessages", o =>
                    {
                        o.MinLogLevel = Microsoft.Extensions.Logging.LogLevel.Warning;
                        o.SpamGuard.DisableGuarding();
                        o.IncludeHealthNotifications();
                    });
                });

                builder.Populate(services);

                builder.RegisterModule(new JobModule(
                                           settings.Assets,
                                           settings.BlockchainOperationsExecutorJob.ChaosKitty));
                builder.RegisterModule(
                    new RepositoriesModule(appSettings.Nested(x => x.BlockchainOperationsExecutorJob.Db)));
                builder.RegisterModule(new BlockchainsModule(
                                           settings.BlockchainOperationsExecutorJob,
                                           settings.BlockchainsIntegration,
                                           settings.BlockchainSignFacadeClient));
                builder.RegisterModule(
                    new CqrsModule(settings.BlockchainOperationsExecutorJob.Cqrs));

                ApplicationContainer = builder.Build();

                var logFactory = ApplicationContainer.Resolve <ILogFactory>();
                Log             = logFactory.CreateLog(this);
                _healthNotifier = ApplicationContainer.Resolve <IHealthNotifier>();

                return(new AutofacServiceProvider(ApplicationContainer));
            }
            catch (Exception ex)
            {
                Log?.Critical(ex);
                throw;
            }
        }
コード例 #14
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            try
            {
                var appSettings = Configuration.Get <AppSettings>();

                services.AddAuthentication(opts =>
                {
                    opts.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    opts.DefaultChallengeScheme    = CookieAuthenticationDefaults.AuthenticationScheme;
                })
                .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, o =>
                {
                    o.LoginPath      = new PathString("/Account/SignIn");
                    o.ExpireTimeSpan = TimeSpan.FromMinutes(int.Parse(Configuration["UserLoginTime"]));
                });

                services.AddAuthorization(options =>
                {
                    options.DefaultPolicy = new AuthorizationPolicyBuilder(CookieAuthenticationDefaults.AuthenticationScheme).RequireAuthenticatedUser().Build();
                });

                services.AddMemoryCache();

                services.AddMvc();

                services.AddSwaggerGen(options =>
                {
                    options.DefaultLykkeConfiguration("v1", "SettingsServiceV2 API");
                    options.OperationFilter <ApiKeyHeaderOperationFilter>();
                });

                var builder = new ContainerBuilder();

                var settings = ConstantReloadingManager.From(appSettings);

                services.AddLykkeLogging(
                    settings.ConnectionString(x => x.ConnectionString),
                    "SettingsServiceLog",
                    appSettings.SlackNotificationsConnString,
                    appSettings.SlackNotificationsQueueName
                    );

                builder.RegisterModule(new AppModule(settings));
                builder.RegisterModule(new DbModule(settings));
                //builder.RegisterModule(new RabbitModule(settings, Log, _consoleLogger));
                builder.Populate(services);

                var provider = new AnnotationsBasedMetamodelProvider();
                EntityMetamodel.Configure(provider);

                ApplicationContainer = builder.Build();

                Log            = ApplicationContainer.Resolve <ILogFactory>().CreateLog(this);
                HealthNotifier = ApplicationContainer.Resolve <IHealthNotifier>();

                return(new AutofacServiceProvider(ApplicationContainer));
            }
            catch (Exception ex)
            {
                Log?.Critical(ex);
                throw;
            }
        }
コード例 #15
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            try
            {
                services.AddMvc()
                .AddJsonOptions(options =>
                {
                    options.SerializerSettings.ContractResolver =
                        new Newtonsoft.Json.Serialization.DefaultContractResolver();
                });

                services.AddSwaggerGen(options =>
                {
                    options.SwaggerDoc(
                        "v1",
                        new Info
                    {
                        Version = "v1",
                        Title   = "Lykke.Service.PayInvoice API"
                    });

                    options.DescribeAllEnumsAsStrings();
                    options.EnableXmsEnumExtension();
                    options.EnableXmlDocumentation();

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

                EntityMetamodel.Configure(new AnnotationsBasedMetamodelProvider());

                Mapper.Initialize(cfg =>
                {
                    cfg.AddProfiles(typeof(AutoMapperProfile));
                    cfg.AddProfiles(typeof(Services.AutoMapperProfile));
                    cfg.AddProfiles(typeof(Repositories.AutoMapperProfile));
                });

                Mapper.AssertConfigurationIsValid();

                var builder     = new ContainerBuilder();
                var appSettings = Configuration.LoadSettings <AppSettings>(options => {});
                if (appSettings.CurrentValue.MonitoringServiceClient != null)
                {
                    _monitoringServiceUrl = appSettings.CurrentValue.MonitoringServiceClient.MonitoringServiceUrl;
                }

                services.AddLykkeLogging(
                    appSettings.ConnectionString(x => x.PayInvoiceService.Db.LogsConnectionString),
                    "PayInvoiceLog",
                    appSettings.CurrentValue.SlackNotifications.AzureQueue.ConnectionString,
                    appSettings.CurrentValue.SlackNotifications.AzureQueue.QueueName);

                builder.RegisterModule(
                    new Repositories.AutofacModule(appSettings.Nested(o => o.PayInvoiceService.Db.DataConnectionString)));

                builder.RegisterModule(new Services.AutofacModule(
                                           appSettings.CurrentValue.PayInvoiceService.CacheExpirationPeriods,
                                           appSettings.CurrentValue.PayInvoiceService.DistributedCacheSettings,
                                           appSettings.CurrentValue.PayInvoiceService.RetryPolicy,
                                           appSettings.CurrentValue.PayInvoiceService.PayInvoicePortalUrl));

                builder.RegisterModule(new AutofacModule(appSettings));

                builder.RegisterModule(new CqrsModule(appSettings.Nested(x => x.PayInvoiceService.Cqrs)));

                builder.Populate(services);
                ApplicationContainer = builder.Build();

                Log = ApplicationContainer.Resolve <ILogFactory>().CreateLog(this);

                HealthNotifier = ApplicationContainer.Resolve <IHealthNotifier>();

                return(new AutofacServiceProvider(ApplicationContainer));
            }
            catch (Exception ex)
            {
                Log?.Critical(ex);
                throw;
            }
        }
コード例 #16
0
 public Log(ILogger logger, IHealthNotifier healthNotifier)
 {
     _logger         = new ErrorsHandlingLoggerDecorator(logger);
     _healthNotifier = healthNotifier;
 }
コード例 #17
0
        /// <summary>
        /// Registers calling application in monitoring service based on application url from environemnt variable.
        /// </summary>
        /// <param name="configuration">Application configuration that is used for environemnt variable search.</param>
        /// <param name="monitoringServiceUrl">Monitoring service url.</param>
        /// <param name="healthNotifier">Health notifier</param>
        /// <returns></returns>
        public static async Task RegisterInMonitoringServiceAsync(
            [NotNull] this IConfigurationRoot configuration,
            [NotNull] string monitoringServiceUrl,
            [NotNull] IHealthNotifier healthNotifier)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            var disableAutoRegistrationStr = configuration[DisableAutoRegistrationEnvVarName];

            if (bool.TryParse(disableAutoRegistrationStr, out bool disableAutoRegistration) && disableAutoRegistration)
            {
                return;
            }

            if (string.IsNullOrWhiteSpace(monitoringServiceUrl))
            {
                throw new ArgumentException("Argument is empty", nameof(monitoringServiceUrl));
            }

            if (healthNotifier == null)
            {
                throw new ArgumentNullException(nameof(healthNotifier));
            }

            var podTag = configuration[PodNameEnvVarName] ?? string.Empty;

            try
            {
                var myMonitoringUrl = configuration[MyMonitoringUrlEnvVarName];
                if (string.IsNullOrWhiteSpace(myMonitoringUrl))
                {
                    myMonitoringUrl = MissingEnvVarUrl;
                    healthNotifier.Notify(
                        $"{MyMonitoringUrlEnvVarName} environment variable is not found. Using {myMonitoringUrl} for monitoring registration",
                        podTag);
                }

                var myMonitoringName = configuration[MyMonitoringNameEnvVarName];
                if (string.IsNullOrWhiteSpace(myMonitoringName))
                {
                    myMonitoringName = PlatformServices.Default.Application.ApplicationName;
                }

                var monitoringService = new MonitoringServiceFacade(monitoringServiceUrl);

                try
                {
                    var monitoringRegistration = await monitoringService.GetService(myMonitoringName);

                    if (monitoringRegistration.Url == myMonitoringUrl)
                    {
                        return;
                    }

                    healthNotifier.Notify($"There is a registration for {myMonitoringName} in monitoring service!", podTag);

                    myMonitoringUrl = MissingEnvVarUrl;
                    var instanceTag = string.IsNullOrEmpty(podTag) ? Guid.NewGuid().ToString() : podTag;
                    myMonitoringName = $"{myMonitoringName}-{instanceTag}";
                }
                catch
                {
                    //Duplicated registration is not found - proceed with usual registration
                }

                await monitoringService.MonitorUrl(
                    new UrlMonitoringObjectModel
                {
                    Url         = myMonitoringUrl,
                    ServiceName = myMonitoringName,
                });

                healthNotifier.Notify($"Auto-registered in Monitoring with name {myMonitoringName} on {myMonitoringUrl}", podTag);
            }
            catch (Exception ex)
            {
                healthNotifier.Notify(ex.ToAsyncString(), podTag);
            }
        }
 public void SendNotification(IHealthNotifier healthNotifier, LogInformationDto logInformation)
 {
     healthNotifier.Notify(PrepareHealthMessage(logInformation), logInformation.Context);
 }
コード例 #19
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            try
            {
                services.AddMvc()
                .AddJsonOptions(options =>
                {
                    options.SerializerSettings.Converters.Add(new StringEnumConverter());
                    options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();
                });

                services.AddSwaggerGen(options =>
                {
                    options.DefaultLykkeConfiguration(ApiVersion, ApiName);
                });

                var settingsManager = Configuration.LoadSettings <AppSettings>(options =>
                {
                    options.SetConnString(x => x.SlackNotifications.AzureQueue.ConnectionString);
                    options.SetQueueName(x => x.SlackNotifications.AzureQueue.QueueName);
                    options.SenderName = $"{AppEnvironment.Name} {AppEnvironment.Version}";
                });

                var appSettings = settingsManager.CurrentValue;

                if (appSettings.MonitoringServiceClient != null)
                {
                    _monitoringServiceUrl = appSettings.MonitoringServiceClient.MonitoringServiceUrl;
                }

                services.AddLykkeLogging(
                    settingsManager.ConnectionString(s => s.PayTelegramReporterJob.Db.LogsConnString),
                    "PayTelegramReporterJobLog",
                    appSettings.SlackNotifications.AzureQueue.ConnectionString,
                    appSettings.SlackNotifications.AzureQueue.QueueName);

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

                builder.RegisterModule(new JobModule(appSettings.PayTelegramReporterJob, settingsManager.Nested(x => x.PayTelegramReporterJob)));

                ApplicationContainer = builder.Build();

                var logFactory = ApplicationContainer.Resolve <ILogFactory>();
                _log            = logFactory.CreateLog(this);
                _healthNotifier = ApplicationContainer.Resolve <IHealthNotifier>();

                return(new AutofacServiceProvider(ApplicationContainer));
            }
            catch (Exception ex)
            {
                if (_log == null)
                {
                    Console.WriteLine(ex);
                }
                else
                {
                    _log.Critical(ex);
                }
                throw;
            }
        }
コード例 #20
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            try
            {
                services.AddHttpClient();
                services.AddMvc()
                .AddJsonOptions(options =>
                {
                    options.SerializerSettings.ContractResolver =
                        new Newtonsoft.Json.Serialization.DefaultContractResolver();
                });

                services.AddSwaggerGen(options =>
                {
                    options.DefaultLykkeConfiguration("v1", "JobStellarApi API");
                });

                EntityMetamodel.Configure(new AnnotationsBasedMetamodelProvider());

                var builder     = new ContainerBuilder();
                var appSettings = Configuration.LoadSettings <AppSettings>(options =>
                {
                    options.SetConnString(x => x.SlackNotifications.AzureQueue.ConnectionString);
                    options.SetQueueName(x => x.SlackNotifications.AzureQueue.QueueName);
                    options.SenderName = AppEnvironment.Name;
                });

                services.AddSingleton <Lykke.Service.Stellar.Api.Core.Settings.AppSettings>(appSettings.CurrentValue);

                services.AddLykkeLogging(
                    appSettings.ConnectionString(x => x.StellarApiService.Db.LogsConnString),
                    "JobStellarApiLog",
                    appSettings.CurrentValue.SlackNotifications.AzureQueue.ConnectionString,
                    appSettings.CurrentValue.SlackNotifications.AzureQueue.QueueName,
                    logBuilder =>
                {
                    logBuilder.AddAdditionalSlackChannel("BlockChainIntegration", options =>
                    {
                        options.MinLogLevel = Microsoft.Extensions.Logging.LogLevel.Information;     // Let it be explicit
                    });

                    logBuilder.AddAdditionalSlackChannel("BlockChainIntegrationImportantMessages", options =>
                    {
                        options.MinLogLevel = Microsoft.Extensions.Logging.LogLevel.Warning;
                    });
                }
                    );

                builder.RegisterChaosKitty(appSettings.CurrentValue.StellarApiService.ChaosKitty);
                builder.RegisterModule(new StellarJobModule(appSettings.Nested(x => x.StellarApiJob)));
                builder.RegisterModule(new RepositoryModule(appSettings.Nested(x => x.StellarApiService)));
                builder.RegisterModule(new ServiceModule(appSettings.Nested(x => x.StellarApiService)));
                builder.Populate(services);

                ApplicationContainer = builder.Build();

                Log            = ApplicationContainer.Resolve <ILogFactory>().CreateLog(this);
                HealthNotifier = ApplicationContainer.Resolve <IHealthNotifier>();

                return(new AutofacServiceProvider(ApplicationContainer));
            }
            catch (Exception ex)
            {
                Log?.Critical(ex);
                throw;
            }
        }
コード例 #21
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            try
            {
                services.AddMvc()
                .AddJsonOptions(options =>
                {
                    options.SerializerSettings.ContractResolver =
                        new DefaultContractResolver();
                });

                services.AddSwaggerGen(options =>
                {
                    options.DefaultLykkeConfiguration("v1", "BlockchainWallets API");
                });

                var builder     = new ContainerBuilder();
                var appSettings = Configuration.LoadSettings <AppSettings>(o =>
                {
                    o.SetConnString(s => s.SlackNotifications.AzureQueue.ConnectionString);
                    o.SetQueueName(s => s.SlackNotifications.AzureQueue.QueueName);
                    o.SenderName = $"{AppEnvironment.Name} {AppEnvironment.Version}";
                });

                var slackSettings = appSettings.CurrentValue.SlackNotifications;


                services.AddLykkeLogging(
                    appSettings.ConnectionString(x => x.BlockchainWalletsService.Db.LogsConnString),
                    "BlockchainWalletsLog",
                    slackSettings.AzureQueue.ConnectionString,
                    slackSettings.AzureQueue.QueueName,
                    logging =>
                {
                    logging.AddAdditionalSlackChannel("CommonBlockChainIntegration");
                    logging.AddAdditionalSlackChannel("CommonBlockChainIntegrationImportantMessages", options =>
                    {
                        options.MinLogLevel = Microsoft.Extensions.Logging.LogLevel.Warning;
                    });
                }
                    );

                builder
                .RegisterModule(new CqrsModule(appSettings.CurrentValue.BlockchainWalletsService.Cqrs))
                .RegisterModule(new RepositoriesModule(appSettings.Nested(x => x.BlockchainWalletsService.Db)))
                .RegisterModule(new ServiceModule(
                                    appSettings.CurrentValue.BlockchainsIntegration,
                                    appSettings.CurrentValue.BlockchainSignFacadeClient,
                                    appSettings.CurrentValue,
                                    appSettings.CurrentValue.AssetsServiceClient,
                                    appSettings.CurrentValue.BlockchainWalletsService));

                builder.Populate(services);

                ApplicationContainer = builder.Build();

                Log            = ApplicationContainer.Resolve <ILogFactory>().CreateLog(this);
                HealthNotifier = ApplicationContainer.Resolve <IHealthNotifier>();

                return(new AutofacServiceProvider(ApplicationContainer));
            }
            catch (Exception ex)
            {
                if (Log != null)
                {
                    Log.Critical(ex);
                }
                else
                {
                    FatalErrorStdOut(ex);
                }

                throw;
            }
        }
コード例 #22
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            try
            {
                services.AddMvc()
                .AddJsonOptions(options =>
                {
                    options.SerializerSettings.ContractResolver =
                        new Newtonsoft.Json.Serialization.DefaultContractResolver();
                });

                services.AddSwaggerGen(options =>
                {
                    options.DefaultLykkeConfiguration("v1", "BlockchainCashoutProcessor API");
                });

                var appSettings = Configuration.LoadSettings <AppSettings>(options =>
                {
                    options.SetConnString(x => x.SlackNotifications.AzureQueue.ConnectionString);
                    options.SetQueueName(x => x.SlackNotifications.AzureQueue.QueueName);
                    options.SenderName = "Lykke.Job.BlockchainCashoutProcessor";
                });

                services.AddLykkeLogging(
                    appSettings.Nested(x => x.BlockchainCashoutProcessorJob.Db.LogsConnString),
                    "BlockchainCashoutProcessorLog",
                    appSettings.CurrentValue.SlackNotifications.AzureQueue.ConnectionString,
                    appSettings.CurrentValue.SlackNotifications.AzureQueue.QueueName,
                    options =>
                {
                    options.AddAdditionalSlackChannel(
                        "CommonBlockChainIntegration",
                        slackOptions =>
                    {
                        slackOptions.MinLogLevel = Microsoft.Extensions.Logging.LogLevel.Information;
                        slackOptions.IncludeHealthNotifications();
                        slackOptions.SpamGuard.DisableGuarding();
                    });

                    options.AddAdditionalSlackChannel(
                        "CommonBlockChainIntegrationImportantMessages",
                        slackOptions =>
                    {
                        slackOptions.MinLogLevel = Microsoft.Extensions.Logging.LogLevel.Warning;
                        slackOptions.IncludeHealthNotifications();
                        slackOptions.SpamGuard.DisableGuarding();
                    });
                });

                var builder = new ContainerBuilder();

                builder.RegisterModule(new JobModule(
                                           appSettings.CurrentValue.Assets,
                                           appSettings.CurrentValue.BlockchainCashoutProcessorJob.ChaosKitty,
                                           appSettings.CurrentValue.MatchingEngineClient));
                builder.RegisterModule(new RepositoriesModule(
                                           appSettings.Nested(x => x.BlockchainCashoutProcessorJob.Db)));
                builder.RegisterModule(new BlockchainsModule(
                                           appSettings.CurrentValue.BlockchainsIntegration,
                                           appSettings.CurrentValue.BlockchainWalletsServiceClient));
                builder.RegisterModule(new CqrsModule(
                                           appSettings.CurrentValue.BlockchainCashoutProcessorJob.Cqrs,
                                           appSettings.CurrentValue.BlockchainCashoutProcessorJob.Workflow,
                                           appSettings.CurrentValue.BlockchainCashoutProcessorJob.Batching));

                services.AddHttpClient(HttpClientNames.Opsgenie, client =>
                {
                    if (appSettings.CurrentValue.Opsgenie == null)
                    {
                        return;
                    }

                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("GenieKey", appSettings.CurrentValue.Opsgenie.ApiKey);
                    client.BaseAddress = new Uri(appSettings.CurrentValue.Opsgenie.ServiceUrl);
                });

                builder.Populate(services);

                ApplicationContainer = builder.Build();

                Log            = ApplicationContainer.Resolve <ILogFactory>().CreateLog(this);
                HealthNotifier = ApplicationContainer.Resolve <IHealthNotifier>();

                return(new AutofacServiceProvider(ApplicationContainer));
            }
            catch (Exception ex)
            {
                Log?.Critical(ex);
                throw;
            }
        }
コード例 #23
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            try
            {
                var appSettings = Configuration.LoadSettings<AppSettings>();
                
                services.AddMvc()
                    .AddJsonOptions(options =>
                    {
                        options.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
                    });

                services.AddSignalR();

                services.AddAuthentication(opts =>
                    {
                        opts.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                        opts.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;

                    })
                    .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, o =>

                    {
                        o.LoginPath = new PathString("/auth/signin");
                        o.ExpireTimeSpan = appSettings.CurrentValue.PayInvoicePortal.UserLoginTime;
                        o.Events.OnRedirectToLogin = (context) =>
                        {
                            if (context.Request.Path.HasValue &&
                                context.Request.Path.Value.StartsWith("/api/") &&
                                context.Response.StatusCode == (int) HttpStatusCode.OK)
                            {
                                context.Response.StatusCode = (int) HttpStatusCode.Unauthorized;
                            }
                            else
                            {
                                /*
                                because sandbox external url configured on prod nginx to redirect
                                to another nginx url (as sandbox located in another kube)
                                the context.RedirectUri is not right in this case  
                                and has to be changed to external prod url
                                */
                                if (DeploymentEnvironment == DeploymentEnvironment.Sandbox &&
                                    !string.IsNullOrEmpty(PortalTestnetUrl))
                                {
                                    var oldRedirectUri = context.RedirectUri;

                                    var hostUrl = context.RedirectUri.Substring(0,
                                        context.RedirectUri.IndexOf(o.LoginPath.ToString(), StringComparison.Ordinal));

                                    if (hostUrl != PortalTestnetUrl.TrimEnd('/'))
                                    {
                                        context.RedirectUri =
                                            context.RedirectUri.Replace(hostUrl, PortalTestnetUrl.TrimEnd('/'));

                                        Log?.Info(
                                            $"OnRedirectToLogin, old RedirectUri: {oldRedirectUri}, " +
                                            $"new RedirectUri: {context.RedirectUri}, " +
                                            $@"context: {
                                                new
                                                {
                                                    context.Request.Host,
                                                    context.Request.Path,
                                                    context.Request.QueryString,
                                                    context.Request.Scheme
                                                }}");
                                    }
                                }

                                context.Response.Redirect(context.RedirectUri);
                            }

                            return Task.FromResult(0);
                        };
                    });
                
                services.AddAuthorization(options =>
                    {
                        options.DefaultPolicy =
                            new AuthorizationPolicyBuilder(CookieAuthenticationDefaults.AuthenticationScheme)
                                .RequireAuthenticatedUser().Build();
                    });

                Mapper.Initialize(cfg =>
                {
                    cfg.AddProfiles(typeof(AutoMapperProfile));
                    cfg.AddProfiles(typeof(Services.AutoMapperProfile));
                });

                Mapper.AssertConfigurationIsValid();

                var builder = new ContainerBuilder();

                services.AddLykkeLogging(
                    appSettings.ConnectionString(x => x.PayInvoicePortal.Db.LogsConnectionString),
                    "PayInvoicePortalLog",
                    appSettings.CurrentValue.SlackNotifications.AzureQueue.ConnectionString,
                    appSettings.CurrentValue.SlackNotifications.AzureQueue.QueueName);

                BlockchainExplorerUrl = appSettings.CurrentValue.PayInvoicePortal.BlockchainExplorerUrl;
                EthereumBlockchainExplorerUrl = appSettings.CurrentValue.PayInvoicePortal.EthereumBlockchainExplorerUrl;
                PortalTestnetUrl = appSettings.CurrentValue.PayInvoicePortal.PortalTestnetUrl;
                DeploymentEnvironment = appSettings.CurrentValue.PayInvoicePortal.DeploymentEnvironment.ParseEnum(DeploymentEnvironment.Prod);
                EnableSignup = appSettings.CurrentValue.PayInvoicePortal.EnableSignup;
                ApiaryDocsDomain = appSettings.CurrentValue.PayInvoicePortal.ApiaryDocsDomain;
                _monitoringServiceUrl = appSettings.CurrentValue.MonitoringServiceClient?.MonitoringServiceUrl;

                builder.RegisterModule(new Repositories.AutofacModule(
                    appSettings.Nested(o => o.PayInvoicePortal.Db.SubscriptionConnectionString)));
                builder.RegisterModule(new Services.AutofacModule(
                    appSettings.CurrentValue.PayInvoicePortal.CacheExpirationPeriods,
                    appSettings.CurrentValue.PayInvoicePortal.EnableSignup,
                    appSettings.CurrentValue.AssetsMap));
                builder.RegisterModule(new AutofacModule(appSettings));
                builder.Populate(services);
                ApplicationContainer = builder.Build();

                Log = ApplicationContainer.Resolve<ILogFactory>().CreateLog(this);

                HealthNotifier = ApplicationContainer.Resolve<IHealthNotifier>();

                return new AutofacServiceProvider(ApplicationContainer);
            }
            catch (Exception ex)
            {
                Log?.Critical(ex);
                throw;
            }
        }
コード例 #24
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            try
            {
                services.AddMvc()
                .AddJsonOptions(options =>
                {
                    options.SerializerSettings.Converters.Add(new StringEnumConverter());
                    options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                });

                services.AddSwaggerGen(options => { options.DefaultLykkeConfiguration(ApiVersion, ApiName); });

                var settingsManager = Configuration.LoadSettings <AppSettings>(options =>
                {
                    options.SetConnString(x => x.SlackNotifications.AzureQueue.ConnectionString);
                    options.SetQueueName(x => x.SlackNotifications.AzureQueue.QueueName);
                    options.SenderName = $"{AppEnvironment.Name} {AppEnvironment.Version}";
                });

                var appSettings = settingsManager.CurrentValue;
                if (appSettings.MonitoringServiceClient != null)
                {
                    _monitoringServiceUrl = appSettings.MonitoringServiceClient.MonitoringServiceUrl;
                }
                services.AddLykkeLogging(
                    settingsManager.ConnectionString(s => s.Bitcoin.Db.LogsConnString),
                    "BitcoinJobLog",
                    appSettings.SlackNotifications.AzureQueue.ConnectionString,
                    appSettings.SlackNotifications.AzureQueue.QueueName,
                    logging =>
                {
                    logging.AddAdditionalSlackChannel("BlockChainIntegration");
                    logging.AddAdditionalSlackChannel("BlockChainIntegrationImportantMessages",
                                                      options => { options.MinLogLevel = LogLevel.Warning; });
                });

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

                builder.RegisterModule(new BitcoinJobModule(settingsManager));
                builder.RegisterModule(new RepositoryModule(settingsManager));
                builder.RegisterModule(new ServiceModule(settingsManager));

                ApplicationContainer = builder.Build();

                var logFactory = ApplicationContainer.Resolve <ILogFactory>();
                _log            = logFactory.CreateLog(this);
                _healthNotifier = ApplicationContainer.Resolve <IHealthNotifier>();

                var provider = new AnnotationsBasedMetamodelProvider();
                EntityMetamodel.Configure(provider);

                return(new AutofacServiceProvider(ApplicationContainer));
            }
            catch (Exception ex)
            {
                if (_log == null)
                {
                    Console.WriteLine(ex);
                }
                else
                {
                    _log.Critical(ex);
                }
                throw;
            }
        }
コード例 #25
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            try
            {
                var appSettings = Configuration.LoadSettings <AppSettings>();

                services.AddMvcCore().AddVersionedApiExplorer(opt =>
                {
                    opt.GroupNameFormat           = "'v'VVV";
                    opt.SubstituteApiVersionInUrl = true;
                });

                services.AddMvc()
                .AddJsonOptions(options =>
                {
                    options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                    options.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
                });

                services.AddApiVersioning(opt =>
                {
                    opt.ReportApiVersions = true;
                    opt.AssumeDefaultVersionWhenUnspecified = true;
                    opt.DefaultApiVersion = new ApiVersion(1, 0);
                });

                services.AddSwaggerGen(options =>
                {
                    var provider = services.BuildServiceProvider().GetRequiredService <IApiVersionDescriptionProvider>();

                    foreach (var description in provider.ApiVersionDescriptions)
                    {
                        options.SwaggerDoc(
                            $"{description.GroupName}",
                            new Info
                        {
                            Version     = description.GroupName,
                            Title       = "PayAPI",
                            Description =
                                @"**Lykke PayAPI** is the set of API methods aimed to provide customers the out-of-the-box functionality for their 
clients to make payments in BTC, ETH and other assets depending on customer needs.

#### Allowed HTTPs requests:
- **POST** : To create resource 
- **PUT** : To update resource
- **GET** : To get a resource or list of resources
- **DELETE** : To delete resource

#### Description Of Usual Server Responses:
- 200 `OK` - the request was successful (some API calls may return 201 instead).
- 201 `Created` - the request was successful and a resource was created.
- 204 `No Content` - the request was successful but there is no representation to return (i.e. the response is empty).
- 400 `Bad Request` - the request could not be understood or was missing required parameters.
- 401 `Unauthorized` - authentication failed or user doesn't have permissions for requested operation.
- 403 `Forbidden` - access denied.
- 404 `Not Found` - resource was not found."
                        });

                        options.DescribeAllEnumsAsStrings();
                        options.EnableXmsEnumExtension();

                        #region EnableXmlDocumentation
                        var basePath      = PlatformServices.Default.Application.ApplicationBasePath;
                        var entryAssembly = Assembly.GetEntryAssembly();

                        //Set the comments path for the swagger json and ui.
                        var xmlPath = Path.Combine(basePath, $"{entryAssembly.GetName().Name}.xml");

                        if (File.Exists(xmlPath))
                        {
                            options.IncludeXmlComments(xmlPath);
                        }
                        #endregion

                        options.MakeResponseValueTypesRequired();
                        // this filter produced null exception: options.OperationFilter<FormFileUploadOperationFilter>();
                    }

                    options.OperationFilter <SwaggerDefaultValues>();
                    options.OperationFilter <HeaderAccessOperationFilter>();
                    options.OperationFilter <SwaggerExtensionsFilter>();
                });

                services.AddAuthentication(options =>
                {
                    options.DefaultAuthenticateScheme = LykkePayConstants.AuthenticationScheme;
                    options.DefaultChallengeScheme    = LykkePayConstants.AuthenticationScheme;
                })
                .AddScheme <LykkePayAuthOptions, LykkePayAuthHandler>(LykkePayConstants.AuthenticationScheme,
                                                                      LykkePayConstants.AuthenticationScheme, options => { })
                .AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer           = true,
                        ValidIssuer              = appSettings.CurrentValue.PayAPI.JwtSecurity.Issuer,
                        ValidateAudience         = true,
                        ValidAudience            = appSettings.CurrentValue.PayAPI.JwtSecurity.Audience,
                        ValidateLifetime         = true,
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey         = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(appSettings.CurrentValue.PayAPI.JwtSecurity.Key))
                    };
                });

                var builder = new ContainerBuilder();

                services.AddLykkeLogging
                (
                    appSettings.ConnectionString(x => x.PayAPI.Db.LogsConnString),
                    "PayAPILog",
                    appSettings.CurrentValue.SlackNotifications.AzureQueue.ConnectionString,
                    appSettings.CurrentValue.SlackNotifications.AzureQueue.QueueName
                );

                builder.RegisterModule(new ServiceModule(appSettings));
                builder.Populate(services);
                ApplicationContainer = builder.Build();

                _log            = ApplicationContainer.Resolve <ILogFactory>().CreateLog(this);
                _healthNotifier = ApplicationContainer.Resolve <IHealthNotifier>();

                Mapper.Initialize(cfg =>
                {
                    cfg.AddProfiles(typeof(AutoMapperProfile));
                    cfg.AddProfiles(typeof(Services.AutoMapperProfile));
                });

                Mapper.AssertConfigurationIsValid();

                return(new AutofacServiceProvider(ApplicationContainer));
            }
            catch (Exception ex)
            {
                _log?.Critical(ex);
                throw;
            }
        }