public static void AddNorthwindDataAccess(this IServiceCollection services,
                                                  string connectionString, DbTypeEnum dbtype)
        {
            //Default behaviour SQLite
            var options = new DbContextOptionsBuilder <NorthwindDatabaseContext>().UseSqlite(connectionString)
                          .Options;

            if (dbtype == DbTypeEnum.SQLServer)
            {
                options = new DbContextOptionsBuilder <NorthwindDatabaseContext>()
                          .UseSqlServer(connectionString)
                          .Options;
            }

            services.AddScoped <NorthwindDatabaseContext>((ctx) => new NorthwindDatabaseContext(options, dbtype));

            if (connectionString.Contains("memory", System.StringComparison.InvariantCultureIgnoreCase))
            {
                dbConnection = new SqliteConnection(connectionString);
                dbConnection.Open();
                //when we have an in-memory database we must have a main connection which lasts till the end of the process
                //elsewhere the database will be destroyed immediatelly after any other connection ends
                //this is why we never close this connection
            }

            //we must generate critical data in the database (customers, categories, etc.)
            CriticalDataGenerator dataGenerator = new CriticalDataGenerator(new NorthwindDatabaseContext(options, dbtype));

            dataGenerator.GenerateTestDataAsync().Wait();

            services.AddTransient <IProductDao, ProductDao>();
            services.AddTransient <ICategoryDao, CategoryDao>();
            services.AddTransient <IOrderDao, OrderDao>();
            services.AddTransient <ICustomerDao, CustomerDao>();
        }
예제 #2
0
        public ConnService(DbTypeEnum dbtype = DbTypeEnum.SqlServer, string connStr = "")
        {
            if (connection == null)
            {
                switch (dbtype)
                {
                case DbTypeEnum.SqlLite:
                    connection = new SqliteConnection(ConnectionDatabaseStr(StaticStr.DatabaseConnectionStr));
                    break;

                case DbTypeEnum.SqlServer:
                    connection = new SqlConnection(StaticStr.DatabaseConnectionStr);
                    break;
                    //case DbTypeEnum.MySql:
                    //    connection = new MySql.Data.MySqlClient.MySqlConnection(connStr);
                    //    break;
                    //case DbTypeEnum.PostgreSQL:
                    //    connection = new Npgsql.NpgsqlConnection(connStr);
                    //    break;
                    //default:
                    //    connection = new SqlConnection(StaticToolHelp.ConnectionDatabaseStr);
                    //    break;
                }
                connection.Open();
            }
        }
예제 #3
0
 //数据访问基础类--构造函数
 public DbHelper(string dbIns, DbTypeEnum dbType)
 {
     //var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json");
     //var Configuration = builder.Build();
     //this.ConntionString = Configuration.GetConnectionString(dbIns);
     this.ConntionString = CPUtils.Configuration.GetSection("ConnectionStrings")[dbIns];
     this.DbType         = dbType;
 }
예제 #4
0
 public NorthwindDatabaseContext(DbContextOptions <NorthwindDatabaseContext> options, DbTypeEnum dbtype)
     : base(options)
 {
     this.dbtype = dbtype;
     this.Database.SetCommandTimeout(TimeSpan.FromMinutes(2));
     if (dbtype == DbTypeEnum.SQLite)
     {
         this.Database.ExecuteSqlRaw("PRAGMA journal_mode=WAL");
     }
 }
예제 #5
0
        public override sealed DbDataAdapter Create()
        {
            DbTypeEnum dbType = _DbUtils.GetDbTypeEnum(Connection);

            if (dbType == DbTypeEnum.MYSQL || dbType == DbTypeEnum.MARIADB)
            {
                return(new MySqlDataAdapter(Sql, (MySqlConnection)Connection));
            }
            else if (dbType == DbTypeEnum.ORACLE)
            {
                return(new OracleDataAdapter(Sql, (OracleConnection)Connection));
            }

            throw new Exception("Database Vendor Not Supported!");
        }
예제 #6
0
        public ISqlBuilder Create(string database, bool isUpper = true)
        {
            DbTypeEnum dbType = getDbTypeEnum();

            if (dbType == DbTypeEnum.MYSQL || dbType == DbTypeEnum.MARIADB)
            {
                return(new MySqlSqlBuilder(database, isUpper));
            }
            else if (dbType == DbTypeEnum.ORACLE)
            {
                return(new OracleSqlBuilder(database, isUpper));
            }

            throw new Exception("Wrong Database Type/Vendor!");
        }
예제 #7
0
        private string BuildSqlConnectionString(string part1, string part2)
        {
            _dbType = DbTypeEnum.SqlServer;

            part1 = ("" + part1).Trim();
            part2 = ("" + part2).Trim();

            if (string.IsNullOrWhiteSpace(part1) || string.IsNullOrWhiteSpace(part2))
            {
                return("");
            }

            string scnn = "";

            switch (part1.ToUpper())
            {
            case SQL_MARKER:
                _dbType = DbTypeEnum.SqlServer;
                scnn    = part2;
                break;

            case OLEDB_MARKER:
                _dbType = DbTypeEnum.Oledb;
                scnn    = part2;
                break;

            case ODBC_MARKER:
                _dbType = DbTypeEnum.Odbc;
                scnn    = part2;
                break;

            case FAKE_MARKER:
                _dbType = DbTypeEnum.BuildInFake;
                scnn    = part2;
                break;

            default:
                scnn = string.Format("Server={0};Database={1};Trusted_Connection=True;", part1, part2);
                break;
            }

            if (scnn.ToLower().Contains(FAKE_SQL_SINATURE))
            {
                _dbType = DbTypeEnum.BuildInFake;
            }

            return(scnn);
        }
예제 #8
0
        public override sealed DbConnection Create()
        {
            DbTypeEnum dbType = _DbUtils._convert(Server.db_type);

            if (dbType == DbTypeEnum.MYSQL || dbType == DbTypeEnum.MARIADB)
            {
                return(string.IsNullOrEmpty(ConnectionString) ? new MySqlConnection() : new MySqlConnection(ConnectionString));
            }
            else if (dbType == DbTypeEnum.ORACLE)
            {
                return(string.IsNullOrEmpty(ConnectionString) ? new OracleConnection() : new OracleConnection(ConnectionString));
            }
            // Other dbs here...

            throw new SqlException("Database Vendor Not Supported!");
        }
예제 #9
0
        static ISQLAnalysisFactory GetSQLAnalysisFactory(DbTypeEnum dbType)
        {
            ISQLAnalysisFactory factory = null;
            switch (dbType)
            {
                case DbTypeEnum.MySQL:
                    factory = new MySQLAnalysisFactory();
                    break;
                case DbTypeEnum.Sybase:
                    factory = new SybaseAnalysisFactory();
                    break;
                case DbTypeEnum.MSSQLServer:
                    factory = new MSSQLServerAnalysisFactory();
                    break;
                case DbTypeEnum.Oracle:
                    throw new NotImplementedException("暂不支持Oracle数据库!");
            }

            return factory;
        }
예제 #10
0
        /// <summary>
        /// 获取数据库的操作对象,根据配置信息
        /// </summary>
        /// <param name="connKey">配置项的配置Key值</param>
        /// <returns></returns>
        public static DapperHelper GetDapperHelper(string connKey)
        {
            //先看连接的缓存,如果在缓存中存在,则直接返回缓存内容。
            if (dbHelperTemps.ContainsKey(connKey))
            {
                return(dbHelperTemps[connKey]);
            }

            DbTypeEnum typeEnum = DbTypeEnum.No;
            ConnectionStringSettings connSetting = GetConnSetting(connKey);

            switch (connSetting.ProviderName)
            {
            case "System.Data.SqlClient":       //SqlServer数据库的处理
                typeEnum = DbTypeEnum.SqlServer;
                break;

            case "System.Data.SqlLite":
                typeEnum = DbTypeEnum.SQLite;
                break;

            case "System.Data.OracleClient":
                typeEnum = DbTypeEnum.Oracle;
                break;

            case "MySql.Data.MySqlClient":
                typeEnum = DbTypeEnum.MySql;
                break;

            default:
                break;
            }
            DapperHelper dapperHelper = new DapperHelper(connSetting.ConnectionString, typeEnum);

            dbHelperTemps.Add("dbconn", dapperHelper);

            return(dapperHelper);
        }
예제 #11
0
        static ISQLAnalysisFactory GetSQLAnalysisFactory(DbTypeEnum dbType)
        {
            ISQLAnalysisFactory factory = null;

            switch (dbType)
            {
            case DbTypeEnum.MySQL:
                factory = new MySQLAnalysisFactory();
                break;

            case DbTypeEnum.Sybase:
                factory = new SybaseAnalysisFactory();
                break;

            case DbTypeEnum.MSSQLServer:
                factory = new MSSQLServerAnalysisFactory();
                break;

            case DbTypeEnum.Oracle:
                throw new NotImplementedException("暂不支持Oracle数据库!");
            }

            return(factory);
        }
예제 #12
0
 /// <summary>
 /// Получает
 /// </summary>
 /// <param name="dbType"></param>
 /// <returns>Фабрика строки соединения для указанного типа БД</returns>
 /// <exception cref="InvalidOperationException">Если данный тип не зарегистрирован</exception>
 public static IConnectionOptions GetConnectionOptions(DbTypeEnum dbType)
 {
     return(DataBases.TryGetValue(dbType, out var value)
         ? value
         : throw new InvalidOperationException($"Тип БД {dbType} не зарегистрирован"));
 }
예제 #13
0
 /// <summary>
 /// Создание обертки над объектом подключения к указанной БД
 /// </summary>
 /// <param name="dbType">Тип БД</param>
 /// <returns>Объект подключения к указанной БД</returns>
 public static DataContext GetDataContext(DbTypeEnum dbType)
 {
     return(new DataContext(GetConnectionOptions(dbType)));
 }
예제 #14
0
 /// <summary>
 /// Регистрация различных БД
 /// </summary>
 /// <param name="dbType">Тип БД</param>
 /// <param name="connectionOptions">Строка подключения</param>
 public static void RegisterConnectionOptions(DbTypeEnum dbType, IConnectionOptions connectionOptions)
 {
     DataBases.Add(dbType, connectionOptions);
 }
예제 #15
0
 /// <summary>
 /// Constructor used for context initialization
 /// </summary>
 /// <param name="connString"></param>
 /// <param name="dbType"></param>
 public DatabaseContext(string connString, DbTypeEnum dbType)
 {
     SetDbInfo(connString, dbType);
 }
예제 #16
0
        public static IFieldTypeAnalysisProvider GetFieldTypeAnalysisProvider(DbTypeEnum dbType)
        {
            ISQLAnalysisFactory factory = GetSQLAnalysisFactory(dbType);

            return(factory.GetFieldTypeAnalysisProvider());
        }
예제 #17
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            if (_env.IsDevelopment())
            {
                ;
            }
            else if (_env.IsStaging())
            {
                ;
            }

            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
            services.AddMediatR(Assembly.GetExecutingAssembly());

            services.AddApplicationServices(Configuration, _env, _logger);

            #region Add HttpClient

            services.AddHttpClient(Core.ConstatCsro.ClientNames.MANAGEMENT_AZURE_EndPoint, (client) =>
            {
                client.Timeout     = TimeSpan.FromMinutes(Core.ConstatCsro.ClientNames.MANAGEMENT_TimeOut_Mins);
                client.BaseAddress = new Uri(Core.ConstatCsro.ClientNames.MANAGEMENT_AZURE_EndPoint);
                client.DefaultRequestHeaders.Add("Accept", "application/json");
            }).ConfigurePrimaryHttpMessageHandler(() =>
            {
                return(new HttpClientHandler()
                {
                    AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip | DecompressionMethods.Brotli,
                    UseCookies = false
                });
            })
            .SetHandlerLifetime(TimeSpan.FromMinutes(5))
            .AddPolicyHandler(PollyHelper.GetRetryPolicy())
            .AddPolicyHandler(PollyHelper.GetRetryPolicy());
            ;

            string ApiEndpointAuth = Configuration.GetValue <string>(ConstatCsro.EndPoints.ApiEndpointAuth);
            services.AddHttpClient(Core.ConstatCsro.EndPoints.ApiEndpointAuth, (client) =>
            {
                client.Timeout     = TimeSpan.FromMinutes(ConstatCsro.ClientNames.API_TimeOut_Mins);
                client.BaseAddress = new Uri(ApiEndpointAuth);
                client.DefaultRequestHeaders.Add("Accept", "application/json");
            }).ConfigurePrimaryHttpMessageHandler(() =>
            {
                return(new HttpClientHandler()
                {
                    AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip | DecompressionMethods.Brotli,
                    UseCookies = false
                });
            })
            .SetHandlerLifetime(TimeSpan.FromMinutes(5))
            .AddPolicyHandler(PollyHelper.GetRetryPolicy())
            .AddPolicyHandler(PollyHelper.GetRetryPolicy());
            ;

            #endregion

            //services.Configure<MicrosoftIdentityOptions>(options =>
            //{
            //    options.ResponseType = OpenIdConnectResponseType.Code;
            //    if (UseKeyVault && !string.IsNullOrWhiteSpace(azureAdOptions.ClientSecret))
            //        options.ClientSecret = azureAdOptions.ClientSecret;
            //    if (UseKeyVault)
            //        LogSecretVariableValueStartValue(ClientSecretVaultName, azureAdOptions.ClientSecret);
            //});

            #region Auth

            services.AddAuthorization(options =>
            {
                // By default, all incoming requests will be authorized according to the default policy
                //Will automatical sign in user
                //options.FallbackPolicy = options.DefaultPolicy;

                options.AddPolicy(PoliciesCsro.IsAdminPolicy, policy => policy.RequireClaim(ClaimTypes.Role, RolesCsro.Admin));
            });

            //TODO replace with rest or GRPC service
            services.AddScoped <IRestUserService, RestUserService>();
            services.AddScoped <IClaimsTransformation, ClaimsTransformation>();

            #endregion

            services.AddApplicationInsightsTelemetry();
            services.AddControllers();
            services.AddMvc(options =>
            {
                options.Filters.Add(new CsroValidationFilter());
            })
            .AddFluentValidation(options =>
            {
                //options.RegisterValidatorsFromAssemblyContaining<Startup>();
                options.RegisterValidatorsFromAssemblyContaining <Server.Services.Validation.BaseAbstractValidator>();
            });

            services.AddScoped <IApiIdentity, ApiIdentity>();
            services.AddScoped <IEmailService, EmailService>();
            services.AddSingleton <IMessageBus, AzServiceBusMessageBus>();

            services.AddTransient <IAzureVmManagementService, AzureVmManagementService>();
            services.AddTransient <ISubcriptionService, SubcriptionService>();
            services.AddTransient <ISubcriptionSPNService, SubcriptionSPNService>();
            services.AddTransient <IResourceGroupervice, ResourceGroupervice>();
            services.AddTransient <ISubcriptionRepository, SubcriptionRepository>();

            services.AddSingleton <ICacheProvider, CacheProvider>(); //testing

            //services.AddApplicationInsightsTelemetry(Configuration["APPINSIGHTS_CONNECTIONSTRING"]);

            //services.AddControllers(options => options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute()));
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = _namespace, Version = "v1"
                });
            });

            #region SDK services

            services.AddTransient <IVmSdkService, VmSdkService>();
            services.AddTransient <ISubscriptionSdkService, SubscriptionSdkService>();
            services.AddTransient <IAdService, AdService>();
            services.AddTransient <IGsnowService, FakeGsnowService>();

            bool UseChainTokenCredential = Configuration.GetValue <bool>("UseChainTokenCredential");
            if (UseChainTokenCredential)
            {
                services.AddTransient <ICsroTokenCredentialProvider, ChainnedCsroTokenCredentialProvider>(); //for personal
                //services.AddTransient<ICsroTokenCredentialProvider, ChainnedCsroTokenCredentialProvider>((op) =>
                //{
                //    var pr = new ChainnedCsroTokenCredentialProvider(azureAdOptions);
                //    return pr;
                //}); //for personal
            }
            else
            {
                services.AddTransient <ICsroTokenCredentialProvider, CsroTokenCredentialProvider>(); //for work
            }
            #endregion

            #region DbContext

            DbTypeEnum DbTypeEnum = DbTypeEnum.Unknown;
            try
            {
                DbTypeEnum = Configuration.GetValue <DbTypeEnum>(nameof(DbTypeEnum));
            }
            catch { }

            if (DbTypeEnum == DbTypeEnum.Unknown)
            {
                throw new Exception($"Unable to read {nameof(DbTypeEnum)} from config. Please set value to SqlServer, InMemory for testing or.....");
            }

            services.AddDbContext <AppVersionContext>(options =>
            {
                if (DbTypeEnum == DbTypeEnum.SqlLite)
                {
                    options.UseSqlite(Configuration.GetConnectionString(KeyVaultConfig.ConnectionStrings.ApiDb), x => x.MigrationsAssembly(_namespace));
                }
                else if (DbTypeEnum == DbTypeEnum.InMemory)
                {
                    options.UseInMemoryDatabase(databaseName: KeyVaultConfig.ConnectionStrings.ApiDb);
                }
                else
                {
                    options.UseSqlServer(Configuration.GetConnectionString(KeyVaultConfig.ConnectionStrings.ApiDb), x => x.MigrationsAssembly(_namespace));
                }
            });

            services.AddDbContext <CustomersDbContext>(options =>
            {
                var cs = Configuration.GetConnectionString(KeyVaultConfig.ConnectionStrings.CustomerDb);
                if (DbTypeEnum == DbTypeEnum.SqlLite)
                {
                    options.UseSqlite(Configuration.GetConnectionString(KeyVaultConfig.ConnectionStrings.CustomerDb), x => x.MigrationsAssembly(_namespace));
                }
                else if (DbTypeEnum == DbTypeEnum.InMemory)
                {
                    options.UseInMemoryDatabase(databaseName: KeyVaultConfig.ConnectionStrings.CustomerDb);
                }
                else //SqlServer
                {
                    options.UseSqlServer(Configuration.GetConnectionString(KeyVaultConfig.ConnectionStrings.CustomerDb), x => x.MigrationsAssembly(_namespace));
                }
            });

            //services.AddDbContext<TokenCacheContext>(options =>
            //{
            //    if (DbTypeEnum == DbTypeEnum.SqlLite)
            //        options.UseSqlite(Configuration.GetConnectionString(KeyVaultConfig.ConnectionStrings.TokenCacheDb));
            //    else
            //        options.UseSqlServer(Configuration.GetConnectionString(KeyVaultConfig.ConnectionStrings.TokenCacheDb));

            //});

            #endregion

            #region Repositories
            services.AddScoped(typeof(IRepository <>), typeof(AppRepository <>));

            services.AddScoped <ITicketRepository, TicketRepository>();
            services.AddScoped <IVersionRepository, VersionRepository>();
            services.AddScoped <IVmTicketRepository, VmTicketRepository>();
            services.AddScoped <ICustomerRepository, CustomerRepository>();
            services.AddScoped <IVmTicketHistoryRepository, VmTicketHistoryRepository>();

            #endregion

            var busConfig = Configuration.GetSection(nameof(BusConfig)).Get <BusConfig>();
            if (busConfig == null)
            {
                _logger.LogWarning($"No {nameof(BusConfig)} found.");
            }
            else
            {
                _logger.LogInformation($"{nameof(BusConfig)} is {busConfig} ", busConfig);
                if (busConfig.IsBusEnabled && busConfig.BusTypeEnum == BusTypeEnum.AzureServiceBus)
                {
                    services.AddHostedService <AzServiceBusConsumer>(sp =>
                    {
                        //var serviceProvider = sp;
                        var serviceProvider = _serviceProvider;
                        //var apiIdentity = serviceProvider.GetService<IApiIdentity>();
                        //var ctx = serviceProvider.GetService<AdoContext>();
                        //IRepository<AdoProject> obj = new Repository<AdoProject>(ctx, apiIdentity);

                        IConfiguration configuration = serviceProvider.GetService <IConfiguration>();
                        IMessageBus messageBus       = serviceProvider.GetService <IMessageBus>();
                        IMediator mediator           = serviceProvider.GetService <IMediator>();
                        IMapper mapper = serviceProvider.GetService <IMapper>();
                        ILogger <AzServiceBusConsumer> logger = serviceProvider.GetService <ILogger <AzServiceBusConsumer> >();
                        return(new AzServiceBusConsumer(configuration, messageBus, mediator, mapper, logger));
                    });
                }
            }

            services.AddHealthChecks().AddDbContextCheck <CustomersDbContext>("Customers DB");
            services.AddHealthChecks().AddDbContextCheck <AppVersionContext>("Api DB");
            if (busConfig != null && busConfig.IsBusEnabled && busConfig.BusTypeEnum == BusTypeEnum.AzureServiceBus)
            {
                services.AddHealthChecks()
                .AddAzureServiceBusTopicHealthCheck(Configuration["ConnectionStrings:AzureServiceBus"],
                                                    Configuration["ServiceBusConfig:VmOperationRequesTopic"], "ServiceBus: Vm Operation Topic", HealthStatus.Unhealthy);
            }
            _serviceProvider = services.BuildServiceProvider();
        }
 /// <summary>
 /// 设置数据库配置
 /// </summary>
 /// <param name="options">数据上下文选项构建器</param>
 /// <param name="connectionString">连接字符串</param>
 /// <param name="dbTypeName">数据库类型名称SqlServer,MySql,Sqlite,Npgsql</param>
 /// <param name="assemblyName">数据模型所在的程序集名称</param>
 /// <returns></returns>
 public static DbContextOptionsBuilder SetOptionsBuilder(this DbContextOptionsBuilder options, string connectionString, DbTypeEnum dbTypeName, string assemblyName)
 {
     return(dbTypeName switch
     {
         DbTypeEnum.SqlServer => options.UseSqlServer(connectionString,
                                                      builder => { builder.MigrationsAssembly(assemblyName).UseRelationalNulls(); }),
         DbTypeEnum.MySql => options.UseMySql(connectionString, new MySqlServerVersion(new Version(8, 0, 25)),
                                              builder =>
         {
             builder.MigrationsAssembly(assemblyName).UseRelationalNulls();
             //builder.ServerVersion(new Version(5, 7, 17), ServerType.MySql);
         }),
         DbTypeEnum.Sqlite => options.UseSqlite(connectionString,
                                                builder => { builder.MigrationsAssembly(assemblyName).UseRelationalNulls(); }),
         DbTypeEnum.Npgsql => options.UseNpgsql(connectionString,
                                                builder => { builder.MigrationsAssembly(assemblyName).UseRelationalNulls(); }),
         _ => throw new System.Exception("未实现的数据库")
     });
예제 #19
0
 public static IFieldTypeAnalysisProvider GetFieldTypeAnalysisProvider(DbTypeEnum dbType)
 {
     ISQLAnalysisFactory factory = GetSQLAnalysisFactory(dbType);
     return factory.GetFieldTypeAnalysisProvider();
 }
예제 #20
0
 public static IDbStructAnalysisProvider GetDbStructAnalysisProvider(DbTypeEnum dbType)
 {
     ISQLAnalysisFactory factory = GetSQLAnalysisFactory(dbType);
     return factory.GetDbStructAnalysisProvider();
 }
예제 #21
0
파일: Db.cs 프로젝트: Cocon90/Cocon90.Db
 /// <summary>
 /// Gets the data helper.
 /// <para>If MySQL DB dbType is "Mysql" dbConnString  like "Server=127.0.0.1;Port=3306;Database=world;Uid=root;Pwd=123456;" </para>
 /// <para>If MsSql DB dbType is "SqlServer" dbConnString  like "Server=127.0.0.1;Port=3306;Database=world;Uid=root;Pwd=123456;" </para>
 /// <para>If Sqlite DB dbType is "Sqlite" dbConnString  like "Data Source=${app}\\testdb.db3" </para>
 /// </summary>
 public static IDataHelper GetDataHelper(DbTypeEnum dbTypeName, string dbConnString)
 {
     return(GetDataHelper(dbTypeName.ToString(), dbConnString));
 }
예제 #22
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
            services.AddMediatR(Assembly.GetExecutingAssembly());

            services.AddApplicationServices(Configuration, _env, _logger);

            string ApiEndpointAuth = Configuration.GetValue <string>(ConstatCsro.EndPoints.ApiEndpointAuth);

            services.AddHttpClient(Core.ConstatCsro.EndPoints.ApiEndpointAuth, (client) =>
            {
                client.Timeout     = TimeSpan.FromMinutes(ConstatCsro.ClientNames.API_TimeOut_Mins);
                client.BaseAddress = new Uri(ApiEndpointAuth);
                client.DefaultRequestHeaders.Add("Accept", "application/json");
            }).ConfigurePrimaryHttpMessageHandler(() =>
            {
                return(new HttpClientHandler()
                {
                    AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip | DecompressionMethods.Brotli,
                    UseCookies = false
                });
            })
            .SetHandlerLifetime(TimeSpan.FromMinutes(5))
            .AddPolicyHandler(PollyHelper.GetRetryPolicy())
            .AddPolicyHandler(PollyHelper.GetRetryPolicy());
            ;

            #region Auth

            services.AddAuthorization(options =>
            {
                // By default, all incoming requests will be authorized according to the default policy
                //Will automatical sign in user
                //options.FallbackPolicy = options.DefaultPolicy;

                options.AddPolicy(PoliciesCsro.CanApproveAdoRequestPolicy, policy => policy.RequireClaim(ClaimTypesCsro.CanApproveAdoRequestClaim, true.ToString()));
            });

            //TODO replace with rest or GRPC service
            services.AddScoped <IRestUserService, RestUserService>();
            services.AddScoped <IClaimsTransformation, ClaimsTransformation>();

            #endregion

            services.AddApplicationInsightsTelemetry();
            services.AddControllers();
            services.AddMvc(options =>
            {
                options.Filters.Add(new CsroValidationFilter());
            })
            .AddFluentValidation(options =>
            {
                //options.RegisterValidatorsFromAssemblyContaining<Startup>();
                options.RegisterValidatorsFromAssemblyContaining <Validation.BaseAdoAbstractValidator>();
            });


            services.AddScoped <IApiIdentity, ApiIdentity>();
            services.AddScoped <IEmailService, EmailService>();
            services.AddSingleton <IMessageBus, AzServiceBusMessageBus>();

            services.AddTransient <IProjectAdoServices, ProjectAdoServices>();
            services.AddTransient <IProcessAdoServices, ProcessAdoServices>();
            services.AddSingleton <ICacheProvider, CacheProvider>(); //testing
            services.AddTransient <IPropertyMappingService, AdoPropertyMappingService>();

            //services.AddSingleton<IServiceBusConsumer, AzServiceBusConsumer>();

            services.AddScoped <IAdoProjectApproverService, AdoProjectApproverService>();
            services.AddScoped <IGenerateEmailForApprovalService, GenerateEmailForApprovalService>();
            services.AddScoped <IAdoProjectAccessRepository, AdoProjectAccessRepository>();

            //services.AddControllers(options => options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute()));
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = _namespace, Version = "v1"
                });
            });

            #region DbContext

            DbTypeEnum DbTypeEnum = DbTypeEnum.Unknown;
            try
            {
                DbTypeEnum = Configuration.GetValue <DbTypeEnum>(nameof(DbTypeEnum));
            }
            catch { }

            services.AddDbContext <AdoContext>(options =>
            {
                if (DbTypeEnum == DbTypeEnum.SqlLite)
                {
                    options.UseSqlite(Configuration.GetConnectionString(KeyVaultConfig.ConnectionStrings.AdoDb), x => x.MigrationsAssembly(_namespace));
                }
                else if (DbTypeEnum == DbTypeEnum.InMemory)
                {
                    options.UseInMemoryDatabase(databaseName: KeyVaultConfig.ConnectionStrings.AdoDb);
                }
                else
                {
                    options.UseSqlServer(Configuration.GetConnectionString(KeyVaultConfig.ConnectionStrings.AdoDb), x => x.MigrationsAssembly(_namespace));
                }
            });

            //services.AddDbContext<TokenCacheContext>(options =>
            //{
            //    if (UseSqlLiteDb)
            //        options.UseSqlite(Configuration.GetConnectionString(KeyVaultConfig.ConnectionStrings.TokenCacheDb));
            //    else
            //        options.UseSqlServer(Configuration.GetConnectionString(KeyVaultConfig.ConnectionStrings.TokenCacheDb));

            //});

            #endregion

            #region Repositories

            services.AddScoped(typeof(IRepository <>), typeof(AdoRepository <>));
            services.AddScoped <IAdoProjectHistoryRepository, AdoProjectHistoryRepository>();
            services.AddScoped <IAdoProjectRepository, AdoProjectRepository>();

            #endregion

            var busConfig = Configuration.GetSection(nameof(BusConfig)).Get <BusConfig>();
            if (busConfig == null)
            {
                _logger.LogWarning($"No {nameof(BusConfig)} found.");
            }
            else
            {
                _logger.LogInformation($"{nameof(BusConfig)} is {busConfig} ", busConfig);
                //_logger.LogInformation("BusConfig is {busConfig} ", busConfig);
                if (busConfig.IsBusEnabled && busConfig.BusTypeEnum == BusTypeEnum.AzureServiceBus)
                {
                    //should be last to hav all dependencies
                    services.AddHostedService <ProjectApprovalHostedService>(sp =>
                    {
                        var serviceProvider          = services.BuildServiceProvider();
                        var apiIdentity              = serviceProvider.GetService <IApiIdentity>();
                        var ctx                      = serviceProvider.GetService <AdoContext>();
                        IRepository <AdoProject> obj = new Repository <AdoProject>(ctx, apiIdentity);
                        var logger                   = sp.GetService <ILogger <ProjectApprovalHostedService> >();
                        IGenerateEmailForApprovalService generateEmailForApprovalService = serviceProvider.GetService <IGenerateEmailForApprovalService>();
                        return(new ProjectApprovalHostedService(generateEmailForApprovalService, logger));
                    });

                    services.AddHostedService <AzServiceBusConsumer>(sp =>
                    {
                        var serviceProvider = services.BuildServiceProvider();
                        //var serviceProvider = sp;
                        var apiIdentity = serviceProvider.GetService <IApiIdentity>();
                        var ctx         = serviceProvider.GetService <AdoContext>();
                        IRepository <AdoProject> obj = new Repository <AdoProject>(ctx, apiIdentity);

                        IConfiguration configuration               = serviceProvider.GetService <IConfiguration>();
                        IMessageBus messageBus                     = serviceProvider.GetService <IMessageBus>();
                        IMediator mediator                         = serviceProvider.GetService <IMediator>();
                        IProjectAdoServices projectAdoServices     = serviceProvider.GetService <IProjectAdoServices>();
                        IAdoProjectRepository adoProjectRepository = serviceProvider.GetService <IAdoProjectRepository>();
                        IAdoProjectHistoryRepository adoProjectHistoryRepository = serviceProvider.GetService <IAdoProjectHistoryRepository>();
                        IMapper mapper = serviceProvider.GetService <IMapper>();
                        ILogger <AzServiceBusConsumer> logger = serviceProvider.GetService <ILogger <AzServiceBusConsumer> >();
                        return(new AzServiceBusConsumer(configuration, messageBus, mediator, projectAdoServices, adoProjectRepository, adoProjectHistoryRepository, mapper, logger));
                    });
                }
            }
        }
예제 #23
0
 private void SetDbInfo(string connString, DbTypeEnum dbType)
 {
     ConnString = connString;
     DbType     = dbType;
 }
예제 #24
0
파일: _Fun.cs 프로젝트: bruce66tw/Base
        //session type(web only), 1:session, 2:redis, 3:custom(config must set SessionService field, use Activator)
        //public static int SessionServiceType = 1;
        #endregion

        /*
         * //constructor
         * static _Fun()
         * {
         * }
         */

        /// <summary>
        /// initial db environment for Ap with db function !!
        /// </summary>
        public static void Init(IServiceProvider di, DbTypeEnum dbType = DbTypeEnum.MSSql,
                                AuthTypeEnum authType = AuthTypeEnum.None, bool dynamicLocale = false)
        {
            //set instance variables
            _di            = di;
            _dbType        = dbType;
            _authType      = authType;
            _dynamicLocale = dynamicLocale;

            #region set smtp
            var smtp = Config.Smtp;
            if (smtp != "")
            {
                try
                {
                    var cols = smtp.Split(',');
                    Smtp = new SmtpDto()
                    {
                        Host      = cols[0],
                        Port      = int.Parse(cols[1]),
                        Ssl       = bool.Parse(cols[2]),
                        Id        = cols[3],
                        Pwd       = cols[4],
                        FromEmail = cols[5],
                        FromName  = cols[6]
                    };
                }
                catch
                {
                    _Log.Error("config Smtp is wrong(7 cols): Host,Port,Ssl,Id,Pwd,FromEmail,FromName");
                }
            }
            #endregion

            #region set DB variables
            //0:select, 1:order by, 2:start row(base 0), 3:rows count
            switch (_dbType)
            {
            case DbTypeEnum.MSSql:
                DbDtFormat = "yyyy-MM-dd HH:mm:ss";
                //JsDtFormat = "yyyy/M/d HH:mm:ss";

                //for sql 2012, more easy
                //note: offset/fetch not sql argument
                ReadPageSql   = @"
select {0} {1}
offset {2} rows fetch next {3} rows only
";
                DeleteRowsSql = "delete {0} where {1} in ({2})";
                break;

            case DbTypeEnum.MySql:
                DbDtFormat = "YYYY-MM-DD HH:mm:SS";

                ReadPageSql = @"
select {0} {1}
limit {2},{3}
";
                //TODO: set delete sql for MySql
                //DeleteRowsSql =
                break;

            case DbTypeEnum.Oracle:
                DbDtFormat = "YYYY/MM/DD HH24:MI:SS";

                //for Oracle 12c after(same as mssql)
                ReadPageSql = @"
Select {0} {1}
Offset {2} Rows Fetch Next {3} Rows Only
";
                //TODO: set delete sql for Oracle
                //DeleteRowsSql =
                break;
            }
            #endregion
        }
예제 #25
0
        public static IDbStructAnalysisProvider GetDbStructAnalysisProvider(DbTypeEnum dbType)
        {
            ISQLAnalysisFactory factory = GetSQLAnalysisFactory(dbType);

            return(factory.GetDbStructAnalysisProvider());
        }
예제 #26
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
            services.AddMediatR(Assembly.GetExecutingAssembly());

            services.AddApplicationServices(Configuration, _env, _logger);

            #region Auth

            services.AddAuthorization(options =>
            {
                // By default, all incoming requests will be authorized according to the default policy
                //Will automatical sign in user
                //options.FallbackPolicy = options.DefaultPolicy;

                //options.AddPolicy(PoliciesCsro.CanApproveAdoRequest, policy => policy.RequireClaim(ClaimTypesCsro.CanApproveAdoRequest, true.ToString()));
                options.AddPolicy(PoliciesCsro.IsAdminPolicy, policy => policy.RequireClaim(ClaimTypes.Role, RolesCsro.Admin));
            });

            services.AddScoped <IApiIdentity, ApiIdentity>();

            //TODO replace with rest or GRPC service
            services.AddScoped <ILocalUserService, DbUserService>();
            services.AddScoped <IClaimsTransformation, AuthClaimsTransformation>();
            services.AddSingleton <ICacheProvider, CacheProvider>(); //testing

            #endregion

            services.AddApplicationInsightsTelemetry();
            services.AddControllers();
            services.AddMvc(options =>
            {
                options.Filters.Add(new CsroValidationFilter());
            })
            .AddFluentValidation(options =>
            {
                //options.RegisterValidatorsFromAssemblyContaining<Startup>();
                //options.RegisterValidatorsFromAssemblyContaining<Validation.BaseAdoAbstractValidator>();
            });

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "CSRO.Server.Auth.Api", Version = "v1"
                });
            });

            #region DbContext

            DbTypeEnum DbTypeEnum = DbTypeEnum.Unknown;
            try
            {
                DbTypeEnum = Configuration.GetValue <DbTypeEnum>(nameof(DbTypeEnum));
            }
            catch { }
            services.AddDbContext <UserContext>(options =>
            {
                if (DbTypeEnum == DbTypeEnum.SqlLite)
                {
                    options.UseSqlite(Configuration.GetConnectionString(KeyVaultConfig.ConnectionStrings.AuthDb), x => x.MigrationsAssembly(_namespace));
                }
                else if (DbTypeEnum == DbTypeEnum.InMemory)
                {
                    options.UseInMemoryDatabase(databaseName: KeyVaultConfig.ConnectionStrings.AuthDb);
                }
                else
                {
                    options.UseSqlServer(Configuration.GetConnectionString(KeyVaultConfig.ConnectionStrings.AuthDb), x => x.MigrationsAssembly(_namespace));
                }
            });

            #endregion

            #region Repositories

            services.AddScoped(typeof(IRepository <>), typeof(UserRepository <>));
            services.AddScoped <IUserRoleRepository, UserRoleRepository>();
            services.AddScoped <IUserClaimRepository, UserClaimRepository>();

            #endregion

            services.AddHealthChecks().AddDbContextCheck <UserContext>("Users DB");
        }
예제 #27
0
 /// <summary>
 /// 初始化方法
 /// </summary>
 /// <param name="connStr"></param>
 /// <param name="dbType"></param>
 public DapperHelper(string connStr, DbTypeEnum dbType)
 {
     this.connStr = connStr;
     this.dbType  = dbType;
 }