コード例 #1
0
        private static void Initialize()
        {
            lock (InitLock)
            {
                if (!_initialized)
                {
                    var provider = new CompositeMetamodelProvider()
                                   .AddProvider
                                   (
                        new AnnotationsBasedMetamodelProvider()
                                   )
                                   .AddProvider
                                   (
                        new ConventionBasedMetamodelProvider()
                        .AddTypeSerializerRule
                        (
                            t => t == typeof(BigInteger),
                            s => new BigIntegerSerializer()
                        )
                                   );

                    EntityMetamodel.Configure(provider);

                    _initialized = true;
                }
            }
        }
コード例 #2
0
 /// <summary>
 ///    This method is called from assembly's module constructor.
 /// </summary>
 public static void Initialize()
 {
     EntityMetamodel.Configure
     (
         provider: CreateMetamodelProvider()
     );
 }
コード例 #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", "PayInternal API");
                    options.OperationFilter <FileUploadOperationFilter>();
                });

                EntityMetamodel.Configure(new AnnotationsBasedMetamodelProvider());

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

                Log = CreateLogWithSlack(services, appSettings);

                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),
                                           Log));

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

                builder.RegisterModule(new ServiceModule(appSettings, Log));

                builder.Populate(services);

                ApplicationContainer = builder.Build();

                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?.WriteFatalErrorAsync(nameof(Startup), nameof(ConfigureServices), "", ex).GetAwaiter().GetResult();
                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", "StellarApi API");
                });

                EntityMetamodel.Configure(new AnnotationsBasedMetamodelProvider());

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

                Log = CreateLogWithSlack(services, appSettings);

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

                return(new AutofacServiceProvider(ApplicationContainer));
            }
            catch (Exception ex)
            {
                Log?.WriteFatalErrorAsync(nameof(Startup), nameof(ConfigureServices), "", ex).GetAwaiter().GetResult();
                throw;
            }
        }
コード例 #5
0
        public override string GetPropertyTableName(string propertyName)
        {
            int?index = EntityMetamodel.GetPropertyIndexOrNull(propertyName);

            if (!index.HasValue)
            {
                return(null);
            }
            return(tableNames[propertyTableNumbers[index.Value]]);
        }
コード例 #6
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", "LegalEntities API");
                });

                EntityMetamodel.Configure(new AnnotationsBasedMetamodelProvider());

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

                Mapper.AssertConfigurationIsValid();

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

                Log = CreateLogWithSlack(services, appSettings);

                builder.RegisterModule(new Services.AutofacModule());
                builder.RegisterModule(new AzureRepositories.AutofacModule(
                                           appSettings.Nested(o => o.LegalEntitiesService.Db.DataConnectionString), Log));
                builder.RegisterModule(new AutofacModule(
                                           appSettings.CurrentValue.PersonalDataServiceClient,
                                           appSettings.CurrentValue.AssetsServiceClient,
                                           appSettings.CurrentValue.LegalEntitiesService.AssetsCacheExpirationPeriod,
                                           services,
                                           Log));
                builder.Populate(services);
                ApplicationContainer = builder.Build();

                return(new AutofacServiceProvider(ApplicationContainer));
            }
            catch (Exception ex)
            {
                Log?.WriteFatalErrorAsync(nameof(Startup), nameof(ConfigureServices), "", ex).GetAwaiter().GetResult();
                throw;
            }
        }
コード例 #7
0
        public void Configure(IApplicationBuilder app, IHostEnvironment env, IApplicationLifetime appLifetime)
        {
            try
            {
                ApplicationContainer = app.ApplicationServices.GetAutofacRoot();

                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseHsts();
                }

                app.UseCorrelation();
#if DEBUG
                app.UseLykkeMiddleware(ServiceName, ex => ex.ToString());
#else
                app.UseLykkeMiddleware(ServiceName, ex => new ErrorResponse {
                    ErrorMessage = ex.Message
                });
#endif

                app.UseRouting();
                app.UseAuthentication();
                app.UseAuthorization();
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllers();
                });
                app.UseSwagger();
                app.UseSwaggerUI(a => a.SwaggerEndpoint("/swagger/v1/swagger.json", "Main Swagger"));

                appLifetime.ApplicationStarted.Register(() => StartApplication().Wait());
                appLifetime.ApplicationStopping.Register(() => StopApplication().Wait());
                appLifetime.ApplicationStopped.Register(() => CleanUp().Wait());

                var provider = new AnnotationsBasedMetamodelProvider();

                EntityMetamodel.Configure(provider);
            }
            catch (Exception ex)
            {
                Log?.WriteFatalErrorAsync(nameof(Startup), nameof(ConfigureServices), "", ex).Wait();
                throw;
            }
        }
コード例 #8
0
        static IServiceCollection AddBlockchainCommonRepositories(this IServiceCollection services,
                                                                  IReloadingManager <string> connectionStringManager)
        {
            services = services ??
                       throw new ArgumentNullException(nameof(services));

            connectionStringManager = connectionStringManager ??
                                      throw new ArgumentNullException(nameof(connectionStringManager));

            EntityMetamodel.Configure(new AnnotationsBasedMetamodelProvider());

            services.AddSingleton(sp => new AssetRepository(connectionStringManager, sp.GetRequiredService <ILogFactory>()));
            services.AddSingleton(sp => new DepositWalletRepository(connectionStringManager, sp.GetRequiredService <ILogFactory>()));
            services.AddSingleton(sp => new OperationRepository(connectionStringManager, sp.GetRequiredService <ILogFactory>()));

            return(services);
        }
コード例 #9
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            try
            {
                services.AddMvc()
                .AddJsonOptions(options =>
                {
                    options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                    options.SerializerSettings.Converters.Add(new StringEnumConverter
                    {
                        CamelCaseText = true
                    });
                });

                services.AddSwaggerGen(options =>
                {
                    options.DefaultLykkeConfiguration("v1", "Zcash.Api API");
                    options.DescribeAllEnumsAsStrings();
                    options.DescribeStringEnumsInCamelCase();
                });

                EntityMetamodel.Configure(new AnnotationsBasedMetamodelProvider());

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

                Log = CreateLogWithSlack(services, appSettings);

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

                return(new AutofacServiceProvider(ApplicationContainer));
            }
            catch (Exception ex)
            {
                Log?.WriteFatalErrorAsync(nameof(Startup), nameof(ConfigureServices), "", ex).GetAwaiter().GetResult();
                throw;
            }
        }
コード例 #10
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            return(services.BuildServiceProvider <AppSettings>(options =>
            {
                EntityMetamodel.Configure(new AnnotationsBasedMetamodelProvider());

                options.SwaggerOptions = _swaggerOptions;

                options.Logs = logs =>
                {
                    logs.AzureTableName = "BitcoinApiLog";
                    logs.AzureTableConnectionStringResolver = settings => settings.Bitcoin.Db.LogsConnString;

                    logs.Extended = extendedLogs =>
                    {
                        extendedLogs.AddAdditionalSlackChannel("BlockChainIntegration");
                        extendedLogs.AddAdditionalSlackChannel("BlockChainIntegrationImportantMessages",
                                                               channelOptions => { channelOptions.MinLogLevel = LogLevel.Warning; });
                    };
                };
            }));
        }
コード例 #11
0
 /// <summary>
 /// Returns <c>true</c> if the entity in <paramref name="persister"/>
 /// ('root') has a direct or indirect association with another
 /// entity that is associated back to 'root' through a 'composit-id' and
 /// 'key-many-to-one'.
 /// </summary>
 /// <param name="persister"></param>
 /// <returns></returns>
 private bool IsReferencedByCompositeId(IEntityPersister persister)
 {
     try
     {
         bool result = false;
         if (IsReferencedByCompositeIdCache.ContainsKey(persister.EntityMetamodel))
         {
             result = this.IsReferencedByCompositeIdCache[persister.EntityMetamodel];
         }
         else
         {
             EntityMetamodel em =
                 this.GetReferrerByCompositeId(
                     persister.EntityMetamodel,
                     persister.EntityMetamodel,
                     false,
                     new Iesi.Collections.Generic.HashedSet <EntityMetamodel>());
             if (em == null)
             {
                 result = false;
             }
             else
             {
                 result = true;
             }
             lock (this)
             {
                 this.IsReferencedByCompositeIdCache[persister.EntityMetamodel] = result;
             }
         }
         return(result);
     }
     catch (Exception ex)
     {
         log.Error("Unespected ERROR!", ex);
         throw;
     }
 }
コード例 #12
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            EntityMetamodel.Configure(new AnnotationsBasedMetamodelProvider());

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

            Mapper.AssertConfigurationIsValid();

            return(services.BuildServiceProvider <AppSettings>(options =>
            {
                options.SwaggerOptions = _swaggerOptions;

                options.Logs = logs =>
                {
                    logs.AzureTableName = "AssetDisclaimersLog";
                    logs.AzureTableConnectionStringResolver = settings => settings.AssetDisclaimersService.Db.LogsConnectionString;
                };
            }));
        }
コード例 #13
0
        public RepositoryFactory(
            ILog log,
            IReloadingManager <DbSettings> settings)
        {
            _log = log;
            _connectionString = settings.ConnectionString(x => x.DataConnectionString);

            var provider = new CompositeMetamodelProvider()
                           .AddProvider
                           (
                new AnnotationsBasedMetamodelProvider()
                           )
                           .AddProvider
                           (
                new ConventionBasedMetamodelProvider()
                .AddTypeSerializerRule
                (
                    t => t == typeof(BigInteger),
                    s => new BigIntegerSerializer()
                )
                           );

            EntityMetamodel.Configure(provider);
        }
コード例 #14
0
		protected AbstractEntityPersister(PersistentClass persistentClass, ICacheConcurrencyStrategy cache,
																			ISessionFactoryImplementor factory)
		{
			this.factory = factory;
			this.cache = cache;
			isLazyPropertiesCacheable = persistentClass.IsLazyPropertiesCacheable;
			cacheEntryStructure = factory.Settings.IsStructuredCacheEntriesEnabled
															? (ICacheEntryStructure)new StructuredCacheEntry(this)
															: (ICacheEntryStructure)new UnstructuredCacheEntry();

			entityMetamodel = new EntityMetamodel(persistentClass, factory);

			if (persistentClass.HasPocoRepresentation)
			{
				//TODO: this is currently specific to pojos, but need to be available for all entity-modes
				foreach (Subclass subclass in persistentClass.SubclassIterator)
				{
					entityNameBySubclass[subclass.MappedClass] = subclass.EntityName;
				}
			}

			batchSize = persistentClass.BatchSize.HasValue ? persistentClass.BatchSize.Value : factory.Settings.DefaultBatchFetchSize;
			hasSubselectLoadableCollections = persistentClass.HasSubselectLoadableCollections;

			propertyMapping = new BasicEntityPropertyMapping(this);

			#region IDENTIFIER

			identifierColumnSpan = persistentClass.Identifier.ColumnSpan;
			rootTableKeyColumnNames = new string[identifierColumnSpan];
			identifierAliases = new string[identifierColumnSpan];

			rowIdName = persistentClass.RootTable.RowId;

			loaderName = persistentClass.LoaderName;

			// TODO NH: Not safe cast to Column
			int i = 0;
			foreach (Column col in persistentClass.Identifier.ColumnIterator)
			{
				rootTableKeyColumnNames[i] = col.GetQuotedName(factory.Dialect);
				identifierAliases[i] = col.GetAlias(factory.Dialect, persistentClass.RootTable);
				i++;
			}

			#endregion

			#region VERSION

			if (persistentClass.IsVersioned)
			{
				foreach (Column col in persistentClass.Version.ColumnIterator)
				{
					versionColumnName = col.GetQuotedName(factory.Dialect);
					break; //only happens once
				}
			}
			else
			{
				versionColumnName = null;
			}

			#endregion

			#region WHERE STRING

			sqlWhereString = !string.IsNullOrEmpty(persistentClass.Where) ? "( " + persistentClass.Where + ") " : null;
			sqlWhereStringTemplate = sqlWhereString == null
																? null
																: Template.RenderWhereStringTemplate(sqlWhereString, factory.Dialect,
																																		 factory.SQLFunctionRegistry);

			#endregion

			#region PROPERTIES

			// NH: see consistence with the implementation on EntityMetamodel where we are disabling lazy-properties for no lazy entities
			bool lazyAvailable = IsInstrumented(EntityMode.Poco) && entityMetamodel.IsLazy;

			int hydrateSpan = entityMetamodel.PropertySpan;
			propertyColumnSpans = new int[hydrateSpan];
			propertySubclassNames = new string[hydrateSpan];
			propertyColumnAliases = new string[hydrateSpan][];
			propertyColumnNames = new string[hydrateSpan][];
			propertyColumnFormulaTemplates = new string[hydrateSpan][];
			propertyUniqueness = new bool[hydrateSpan];
			propertySelectable = new bool[hydrateSpan];
			propertyColumnUpdateable = new bool[hydrateSpan][];
			propertyColumnInsertable = new bool[hydrateSpan][];
			var thisClassProperties = new HashSet<Property>();

			lazyProperties = new HashedSet<string>();
			List<string> lazyNames = new List<string>();
			List<int> lazyNumbers = new List<int>();
			List<IType> lazyTypes = new List<IType>();
			List<string[]> lazyColAliases = new List<string[]>();

			i = 0;
			bool foundFormula = false;
			foreach (Property prop in persistentClass.PropertyClosureIterator)
			{
				thisClassProperties.Add(prop);

				int span = prop.ColumnSpan;
				propertyColumnSpans[i] = span;
				propertySubclassNames[i] = prop.PersistentClass.EntityName;
				string[] colNames = new string[span];
				string[] colAliases = new string[span];
				string[] templates = new string[span];
				int k = 0;
				foreach (ISelectable thing in prop.ColumnIterator)
				{
					colAliases[k] = thing.GetAlias(factory.Dialect, prop.Value.Table);
					if (thing.IsFormula)
					{
						foundFormula = true;
						templates[k] = thing.GetTemplate(factory.Dialect, factory.SQLFunctionRegistry);
					}
					else
					{
						colNames[k] = thing.GetTemplate(factory.Dialect, factory.SQLFunctionRegistry);
					}
					k++;
				}
				propertyColumnNames[i] = colNames;
				propertyColumnFormulaTemplates[i] = templates;
				propertyColumnAliases[i] = colAliases;

				if (lazyAvailable && prop.IsLazy)
				{
					lazyProperties.Add(prop.Name);
					lazyNames.Add(prop.Name);
					lazyNumbers.Add(i);
					lazyTypes.Add(prop.Value.Type);
					lazyColAliases.Add(colAliases);
				}

				propertyColumnUpdateable[i] = prop.Value.ColumnUpdateability;
				propertyColumnInsertable[i] = prop.Value.ColumnInsertability;

				propertySelectable[i] = prop.IsSelectable;

				propertyUniqueness[i] = prop.Value.IsAlternateUniqueKey;

				i++;
			}
			hasFormulaProperties = foundFormula;
			lazyPropertyColumnAliases = lazyColAliases.ToArray();
			lazyPropertyNames = lazyNames.ToArray();
			lazyPropertyNumbers = lazyNumbers.ToArray();
			lazyPropertyTypes = lazyTypes.ToArray();

			#endregion

			#region SUBCLASS PROPERTY CLOSURE

			List<string> columns = new List<string>();
			List<bool> columnsLazy = new List<bool>();
			List<string> aliases = new List<string>();
			List<string> formulas = new List<string>();
			List<string> formulaAliases = new List<string>();
			List<string> formulaTemplates = new List<string>();
			List<bool> formulasLazy = new List<bool>();
			List<IType> types = new List<IType>();
			List<string> names = new List<string>();
			List<string> classes = new List<string>();
			List<string[]> templates2 = new List<string[]>();
			List<string[]> propColumns = new List<string[]>();
			List<FetchMode> joinedFetchesList = new List<FetchMode>();
			List<CascadeStyle> cascades = new List<CascadeStyle>();
			List<bool> definedBySubclass = new List<bool>();
			List<int[]> propColumnNumbers = new List<int[]>();
			List<int[]> propFormulaNumbers = new List<int[]>();
			List<bool> columnSelectables = new List<bool>();
			List<bool> propNullables = new List<bool>();

			foreach (Property prop in persistentClass.SubclassPropertyClosureIterator)
			{
				names.Add(prop.Name);
				classes.Add(prop.PersistentClass.EntityName);
				bool isDefinedBySubclass = !thisClassProperties.Contains(prop);
				definedBySubclass.Add(isDefinedBySubclass);
				propNullables.Add(prop.IsOptional || isDefinedBySubclass); //TODO: is this completely correct?
				types.Add(prop.Type);

				string[] cols = new string[prop.ColumnSpan];
				string[] forms = new string[prop.ColumnSpan];
				int[] colnos = new int[prop.ColumnSpan];
				int[] formnos = new int[prop.ColumnSpan];
				int l = 0;
				bool lazy = prop.IsLazy && lazyAvailable;
				foreach (ISelectable thing in prop.ColumnIterator)
				{
					if (thing.IsFormula)
					{
						string template = thing.GetTemplate(factory.Dialect, factory.SQLFunctionRegistry);
						formnos[l] = formulaTemplates.Count;
						colnos[l] = -1;
						formulaTemplates.Add(template);
						forms[l] = template;
						formulas.Add(thing.GetText(factory.Dialect));
						formulaAliases.Add(thing.GetAlias(factory.Dialect));
						formulasLazy.Add(lazy);
					}
					else
					{
						string colName = thing.GetTemplate(factory.Dialect, factory.SQLFunctionRegistry);
						colnos[l] = columns.Count; //before add :-)
						formnos[l] = -1;
						columns.Add(colName);
						cols[l] = colName;
						aliases.Add(thing.GetAlias(factory.Dialect, prop.Value.Table));
						columnsLazy.Add(lazy);
						columnSelectables.Add(prop.IsSelectable);
					}
					l++;
				}
				propColumns.Add(cols);
				templates2.Add(forms);
				propColumnNumbers.Add(colnos);
				propFormulaNumbers.Add(formnos);

				joinedFetchesList.Add(prop.Value.FetchMode);
				cascades.Add(prop.CascadeStyle);
			}
			subclassColumnClosure = columns.ToArray();
			subclassColumnAliasClosure = aliases.ToArray();
			subclassColumnLazyClosure = columnsLazy.ToArray();
			subclassColumnSelectableClosure = columnSelectables.ToArray();

			subclassFormulaClosure = formulas.ToArray();
			subclassFormulaTemplateClosure = formulaTemplates.ToArray();
			subclassFormulaAliasClosure = formulaAliases.ToArray();
			subclassFormulaLazyClosure = formulasLazy.ToArray();

			subclassPropertyNameClosure = names.ToArray();
			subclassPropertySubclassNameClosure = classes.ToArray();
			subclassPropertyTypeClosure = types.ToArray();
			subclassPropertyNullabilityClosure = propNullables.ToArray();
			subclassPropertyFormulaTemplateClosure = templates2.ToArray();
			subclassPropertyColumnNameClosure = propColumns.ToArray();
			subclassPropertyColumnNumberClosure = propColumnNumbers.ToArray();
			subclassPropertyFormulaNumberClosure = propFormulaNumbers.ToArray();

			subclassPropertyCascadeStyleClosure = cascades.ToArray();
			subclassPropertyFetchModeClosure = joinedFetchesList.ToArray();

			propertyDefinedOnSubclass = definedBySubclass.ToArray();

			#endregion

			// Handle any filters applied to the class level
			filterHelper = new FilterHelper(persistentClass.FilterMap, factory.Dialect, factory.SQLFunctionRegistry);

			temporaryIdTableName = persistentClass.TemporaryIdTableName;
			temporaryIdTableDDL = persistentClass.TemporaryIdTableDDL;
		}
コード例 #15
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;
            }
        }
コード例 #16
0
 public MatrixFileTuplizer(EntityMetamodel entityMetamodel, PersistentClass mappedEntity)
     : base(entityMetamodel, mappedEntity)
 {
 }
コード例 #17
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;
            }
        }
コード例 #18
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;
            }
        }
コード例 #19
0
 public EntityTuplizer(EntityMetamodel entityMetamodel, PersistentClass mappedEntity)
     : base(entityMetamodel, mappedEntity)
 {
 }
コード例 #20
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            Mapper.Initialize(x => x.AddProfile(typeof(AutoMapperProfile)));
            services.AddSingleton(Mapper.Instance);

            var conventionProvider = new ConventionBasedMetamodelProvider()
                                     .AddTypeValueTypesMergingStrategyRule(
                t => true,
                ValueTypeMergingStrategy.Forbid);

            var provider = new CompositeMetamodelProvider()
                           .AddProvider(new AnnotationsBasedMetamodelProvider())
                           .AddProvider(conventionProvider);

            EntityMetamodel.Configure(provider);

            return(services.BuildServiceProvider <AppSettings>(options =>
            {
                options.SwaggerOptions = _swaggerOptions;

                options.Logs = logs =>
                {
                    logs.AzureTableName = "KycSpiderLog";
                    logs.AzureTableConnectionStringResolver = settings => settings.KycSpiderService.Db.LogsConnection.ConnectionString;

                    // TODO: You could add extended logging configuration here:

                    /*
                     * logs.Extended = extendedLogs =>
                     * {
                     *  // For example, you could add additional slack channel like this:
                     *  extendedLogs.AddAdditionalSlackChannel("KycSpider", channelOptions =>
                     *  {
                     *      channelOptions.MinLogLevel = LogLevel.Information;
                     *  });
                     * };
                     */
                };

                // TODO: Extend the service configuration

                /*
                 * options.Extend = (sc, settings) =>
                 * {
                 *  sc
                 *      .AddOptions()
                 *      .AddAuthentication(MyAuthOptions.AuthenticationScheme)
                 *      .AddScheme<MyAuthOptions, KeyAuthHandler>(MyAuthOptions.AuthenticationScheme, null);
                 * };
                 */

                // TODO: You could add extended Swagger configuration here:

                /*
                 * options.Swagger = swagger =>
                 * {
                 *  swagger.IgnoreObsoleteActions();
                 * };
                 */
            }));
        }
コード例 #21
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;
            }
        }
コード例 #22
0
    /// <summary>
    /// Recursive Helper for <see cref="IsReferencedByCompositeId(IEntityPersister)"/>.
    /// </summary>
    /// <param name="rootEM"></param>
    /// <param name="nestedEM"></param>
    /// <param name="neestedIsCompositeId"></param>
    /// <param name="visitedList"></param>
    /// <returns></returns>
    private EntityMetamodel GetReferrerByCompositeId(
        EntityMetamodel rootEM,
        EntityMetamodel nestedEM,
        bool neestedIsCompositeId,
        ICollection <EntityMetamodel> visitedList)
    {
        EntityMetamodel emResult = null;

        if (visitedList.Contains(nestedEM))
        {
            return(emResult);
        }
        else
        {
            visitedList.Add(nestedEM);
            ISessionFactoryImplementor sessionImplementor = rootEM.SessionFactory;
            if (nestedEM.IdentifierProperty.Type is IAbstractComponentType)
            {
                IAbstractComponentType componentType = (IAbstractComponentType)nestedEM.IdentifierProperty.Type;
                for (int i = 0; i < componentType.Subtypes.Length; i++)
                {
                    IType subType = componentType.Subtypes[i];
                    if (!subType.IsAnyType &&
                        subType.IsAssociationType &&
                        subType is IAssociationType)
                    {
                        IAssociationType associationType      = (IAssociationType)subType;
                        string           associatedEntityName = null;
                        try
                        {
                            //for 'Collection Types', sometimes 'Element Type' is not an 'Entity Type'
                            associatedEntityName = associationType.GetAssociatedEntityName(sessionImplementor);
                        }
                        catch (MappingException me)
                        {
                            //I think it will never happen because a
                            //"Composit Id" can not have a property that
                            //uses 'NHibernate.Type.CollectionType'.
                            //But just in case ...
                            if (log.IsDebugEnabled)
                            {
                                log.Debug("Can not perform 'GetAssociatedEntityName'. " +
                                          "Considering it is not an entity type: '" +
                                          nestedEM.IdentifierProperty.Name + "." +
                                          componentType.PropertyNames[i] + "'"
                                          , me);
                            }
                        }
                        if (associatedEntityName != null)
                        {
                            IEntityPersister persisterNextNested = sessionImplementor.GetEntityPersister(associatedEntityName);
                            if (rootEM == persisterNextNested.EntityMetamodel)
                            {
                                emResult = nestedEM;
                                return(emResult);
                            }
                            else
                            {
                                emResult = this.GetReferrerByCompositeId(
                                    rootEM,
                                    persisterNextNested.EntityMetamodel,
                                    true,
                                    visitedList);
                                if (emResult != null)
                                {
                                    return(emResult);
                                }
                            }
                        }
                    }
                }
            }
            for (int i = 0; i < nestedEM.Properties.Length; i++)
            {
                StandardProperty property = nestedEM.Properties[i];
                if (!property.Type.IsAnyType &&
                    property.Type.IsAssociationType &&
                    property.Type is IAssociationType)
                {
                    IAssociationType associationType      = (IAssociationType)property.Type;
                    string           associatedEntityName = null;
                    try
                    {
                        //for 'Collection Types', sometimes 'Element Type' is not an 'Entity Type'
                        associatedEntityName = associationType.GetAssociatedEntityName(sessionImplementor);
                    }
                    catch (MappingException me)
                    {
                        if (log.IsDebugEnabled)
                        {
                            log.Debug("Can not perform 'GetAssociatedEntityName'. " +
                                      "Considering it is not an entity type: '" +
                                      nestedEM.EntityType.Name + "." +
                                      nestedEM.PropertyNames[i] + "'",
                                      me);
                        }
                    }
                    if (associatedEntityName != null)
                    {
                        IEntityPersister persisterNextNested = sessionImplementor.GetEntityPersister(associatedEntityName);
                        emResult = this.GetReferrerByCompositeId(
                            rootEM,
                            persisterNextNested.EntityMetamodel,
                            false,
                            visitedList);
                        if (emResult != null)
                        {
                            return(emResult);
                        }
                    }
                }
            }
        }
        return(null);
    }
コード例 #23
0
        public static void RegisterDbModule(
            this ContainerBuilder builder,
            string connectionString,
            string userConnectionString,
            string secretsConnString)
        {
            var provider = new AnnotationsBasedMetamodelProvider();

            EntityMetamodel.Configure(provider);

            var conString        = ConstantReloadingManager.From(connectionString);
            var userConString    = ConstantReloadingManager.From(userConnectionString);
            var secretsConString = ConstantReloadingManager.From(secretsConnString);

            builder.Register(c =>
                             new ServiceTokenRepository(
                                 AzureTableStorage <ServiceTokenEntity> .Create(conString, "ServiceToken", c.Resolve <ILogFactory>())))
            .As <IServiceTokenRepository>()
            .SingleInstance();

            builder.Register(c =>
                             new UserRepository(
                                 AzureTableStorage <UserEntity> .Create(userConString, "User", c.Resolve <ILogFactory>())))
            .As <IUserRepository>()
            .SingleInstance();

            builder.Register(c =>
                             new RoleRepository(
                                 AzureTableStorage <RoleEntity> .Create(userConString, "Role", c.Resolve <ILogFactory>())))
            .As <IRoleRepository>()
            .SingleInstance();

            builder.Register(c =>
                             new UserSignInHistoryRepository(
                                 AzureTableStorage <UserSignInHistoryEntity> .Create(userConString, "UserSignInHistory", c.Resolve <ILogFactory>())))
            .As <IUserSignInHistoryRepository>()
            .SingleInstance();

            builder.Register(c =>
                             new TokensRepository(
                                 AzureTableStorage <TokenEntity> .Create(conString, "Tokens", c.Resolve <ILogFactory>())))
            .As <ITokensRepository>()
            .SingleInstance();

            builder.Register(c =>
                             new KeyValuesRepository(
                                 AzureTableStorage <KeyValueEntity> .Create(conString, "KeyValues", c.Resolve <ILogFactory>()),
                                 c.Resolve <IKeyValueHistoryRepository>()))
            .As <IKeyValuesRepository>()
            .SingleInstance();

            builder.Register(c =>
                             new KeyValuesRepository(
                                 AzureTableStorage <KeyValueEntity> .Create(secretsConString, "SecretKeyValues", c.Resolve <ILogFactory>()),
                                 c.Resolve <IKeyValueHistoryRepository>()))
            .As <ISecretKeyValuesRepository>()
            .SingleInstance();

            builder.Register(c =>
                             new LockRepository(AzureTableStorage <LockEntity> .Create(conString, "Lock", c.Resolve <ILogFactory>())))
            .As <ILockRepository>()
            .SingleInstance();

            builder.Register(c =>
                             new AccountTokenHistoryRepository(
                                 AzureTableStorage <AccountTokenHistoryEntity> .Create(conString, "AccessTokenHistory", c.Resolve <ILogFactory>())))
            .As <IAccountTokenHistoryRepository>()
            .SingleInstance();

            builder.Register(c =>
                             new ServiceTokenHistoryRepository(
                                 AzureTableStorage <ServiceTokenHistoryEntity> .Create(conString, "ServiceTokenHistory", c.Resolve <ILogFactory>())))
            .As <IServiceTokenHistoryRepository>()
            .SingleInstance();

            builder.Register(c =>
                             new RepositoriesRepository(
                                 AzureTableStorage <RepositoryEntity> .Create(conString, "Repositories", c.Resolve <ILogFactory>())))
            .As <IRepositoriesRepository>()
            .SingleInstance();

            builder.Register(c =>
                             new ConnectionUrlHistoryRepository(
                                 AzureTableStorage <ConnectionUrlHistory> .Create(conString, "ConnectionUrlHistory", c.Resolve <ILogFactory>())))
            .As <IConnectionUrlHistoryRepository>()
            .SingleInstance();

            builder.Register(c =>
                             new RepositoriesUpdateHistoryRepository(
                                 AzureTableStorage <RepositoryUpdateHistoryEntity> .Create(conString, "RepositoryUpdateHistory", c.Resolve <ILogFactory>())))
            .As <IRepositoriesUpdateHistoryRepository>()
            .SingleInstance();

            builder.Register(c =>
                             new NetworkRepository(
                                 AzureTableStorage <NetworkEntity> .Create(conString, "Networks", c.Resolve <ILogFactory>())))
            .As <INetworkRepository>()
            .SingleInstance();

            builder.Register(c =>
                             new UserActionHistoryRepository(
                                 AzureTableStorage <UserActionHistoryEntity> .Create(userConString, "UserActionHistory", c.Resolve <ILogFactory>()),
                                 new AzureBlobStorage(userConString.CurrentValue), "useractionhistoryparam"))
            .As <IUserActionHistoryRepository>()
            .SingleInstance();

            builder.Register(c =>
                             new KeyValueHistoryRepository(
                                 AzureTableStorage <KeyValueHistory> .Create(conString, "KeyValueHistory", c.Resolve <ILogFactory>()),
                                 new AzureBlobStorage(conString.CurrentValue), "keyvaluehistory"))
            .As <IKeyValueHistoryRepository>()
            .SingleInstance();

            builder.RegisterInstance(
                new RepositoryDataRepository(new AzureBlobStorage(conString.CurrentValue), "settings", "history")
                ).As <IRepositoryDataRepository>().SingleInstance();

            builder.RegisterInstance(
                new JsonDataRepository(new AzureBlobStorage(conString.CurrentValue), "settings", "history", "generalsettings.json")
                ).As <IJsonDataRepository>().SingleInstance();

            builder.RegisterInstance(
                new AccessDataRepository(new AzureBlobStorage(conString.CurrentValue), "access", "accesshistory", "accessHistory.json")
                ).As <IAccessDataRepository>().SingleInstance();
        }
コード例 #24
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;
            }
        }