Beispiel #1
0
 ///  <summary>
 ///  Configure a <b><see cref="IDbContextInstanceOptions"/> <b><see cref="DbContextOptionsBuilder{TContext}"/></b> to use MySQL</b>
 ///  </summary>
 ///  <param name="dbContextInstanceOptions">A <b><see cref="IDbContextInstanceOptions"/></b> instance as reference</param>
 public static void ConfigureMySQL(ref IDbContextInstanceOptions dbContextInstanceOptions)
 {
     dbContextInstanceOptions.OptionsBuilder.UseMySql(dbContextInstanceOptions.connectionString, ServerVersion.AutoDetect(dbContextInstanceOptions.connectionString));
 }
Beispiel #2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            string mySqlConnectionStr = Configuration.GetConnectionString("MysqlConnection");

            services.AddDbContext <ApplicationDbContext>(options =>
                                                         //options.UseSqlServer(
                                                         //    Configuration.GetConnectionString("DefaultConnection")));
                                                         options.UseMySql(mySqlConnectionStr, ServerVersion.AutoDetect(mySqlConnectionStr)));

            services.AddDefaultIdentity <IdentityUser>(options => {
                options.SignIn.RequireConfirmedAccount  = false;
                options.Password.RequireNonAlphanumeric = false;    // Do not require special characters
            }).AddRoles <IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>();
            services.AddHttpContextAccessor(); // get current username
            services.AddRazorPages();
            services.AddServerSideBlazor();
            services.AddScoped <AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider <IdentityUser> >();
        }
        public void ConfigureServices(IServiceCollection services)
        {
            JwtSecurityTokenHandler.DefaultMapInboundClaims = false;

            services.AddDockerDataProtection("/var/opt/dpkeys");

            var projectDbConnectionString = _configuration.GetConnectionString("ProjectDb");
            var projectDbServerVersion    = ServerVersion.AutoDetect(projectDbConnectionString);

            services
            .AddDbContext <ProjectDbContext>(options =>
            {
                options.UseMySql(projectDbConnectionString, projectDbServerVersion);
            })
            .AddDbContext <ProposalDbContext>(options =>
            {
                options.UseSqlServer(_configuration.GetConnectionString("ProposalDb"));
            });

            services.AddDatabaseDeveloperPageExceptionFilter();

            services.AddMemoryCache();

            services
            .AddAuthentication(Constants.AuthenticationSchemes.Default)
            .AddCookie(Constants.AuthenticationSchemes.Default, options =>
            {
                options.ExpireTimeSpan    = TimeSpan.FromDays(1);
                options.SlidingExpiration = true;
                options.Cookie.HttpOnly   = true;
                // options.Cookie.SameSite = SameSiteMode.Strict;
                options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
            })
            .AddCookie(Constants.AuthenticationSchemes.External)
            .AddOpenIdConnect(options =>
            {
                options.SignInScheme = Constants.AuthenticationSchemes.External;

                options.ResponseType = OidcConstants.ResponseTypes.Code;

                options.Scope.Clear();
                options.Scope.Add(OidcConstants.StandardScopes.OpenId);
                options.Scope.Add("urn:dccn:identity:uid");

                options.GetClaimsFromUserInfoEndpoint = true;

                options.ClaimActions.MapUniqueJsonKey(ClaimTypes.UserId, "urn:dccn:uid");
            });

            services
            .AddRazorPages()
            .AddMvcLocalization()
            .AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.Converters.Add(new StringEnumConverter());
            })
            .AddFluentValidation(options =>
            {
                options.LocalizationEnabled = true;
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("RequireAdministrationRole", policy => policy.RequireRole(Role.Administration.GetName()));
                options.AddPolicy("RequireSupervisorRole", policy => policy.RequireRole(Role.Supervisor.GetName()));
                options.AddPolicy("RequireAuthorityRole", policy => policy.RequireRole(Role.Authority.GetName()));
            });

            services.AddSignalR();

            services.AddClientAccessTokenManagement((services, configure) =>
            {
                var options = services.GetRequiredService <IOptions <ProjectDb2Options> >().Value;
                configure.Clients.Add("project-database-core-api", new ClientCredentialsTokenRequest
                {
                    Address      = options.TokenEndpoint,
                    ClientId     = options.ClientId,
                    ClientSecret = options.ClientSecret,
                    Scope        = "urn:dccn:pdb:core-api:query urn:dccn:pdb:core-api:mutate",
                });
            });

            services
            .AddProjectDb2Client()
            .ConfigureHttpClient((services, client) =>
            {
                var options        = services.GetRequiredService <IOptions <ProjectDb2Options> >().Value;
                client.BaseAddress = new Uri(options.CoreApiBaseUri);
            }, builder =>
            {
                builder.AddClientAccessTokenHandler("project-database-core-api");
            });

            services.AddOptions <OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme)
            .Configure <IOptions <AuthOptions> >((options, authOptions) =>
            {
                var auth             = authOptions.Value;
                options.Authority    = auth.Authority;
                options.ClientId     = auth.ClientId;
                options.ClientSecret = auth.ClientSecret;
            });

            services
            .Configure <AuthOptions>(_configuration.GetSection(AuthOptions.SectionName))
            .Configure <EmailOptions>(_configuration.GetSection(EmailOptions.SectionName))
            .Configure <FormOptions>(_configuration.GetSection(FormOptions.SectionName))
            .Configure <RepositoryApiOptions>(_configuration.GetSection(RepositoryApiOptions.SectionName))
            .Configure <ProjectDb2Options>(_configuration.GetSection(ProjectDb2Options.SectionName));

            services
            .AddHostedService <ProposalDbChangeListener>()
            .AddTransient <IUserManager, UserManager>()
            .AddTransient <ISignInManager, SignInManager>()
            .AddScoped <IAuthorizationHandler, FormAuthorizationHandler>()
            .AddScoped <IAuthorizationHandler, FormSectionAuthorizationHandler>()
            .AddScoped <IAuthorizationHandler, ApprovalAuthorizationHandler>()
            .AddSingleton <ILabProvider, LabProvider>()
            .AddTransient <IProjectDbExporter, ProjectDbExporter>()
            .AddTransient <IProjectDb2Exporter, ProjectDb2Exporter>()
            .AddTransient <IAuthorityProvider, AuthorityProvider>()
            .AddSingleton <IStringLocalizerFactory, TomlStringLocalizerFactory>(s => new TomlStringLocalizerFactory(s, "Messages.toml"))
            .AddTransient(typeof(IStringLocalizer <>), typeof(TomlStringLocalizer <>))
            .AddTransient <IStringLocalizer, TomlStringLocalizer>()
            .AddRepositoryApiClient()
            .AddFormSectionHandlers()
            .AddFormSectionValidators()
            .AddEmail("/Email/Templates");
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            string connectionDb = Configuration.GetConnectionString("MySqlConnection");

            string databaseAddress = Environment.GetEnvironmentVariable("DB_HOST");
            string login           = Environment.GetEnvironmentVariable("LOGIN_DB");
            string mdp             = Environment.GetEnvironmentVariable("PASSWORD_DB");
            string dbName          = Environment.GetEnvironmentVariable("DB_NAME");

            connectionDb = connectionDb.Replace("USERNAME", login)
                           .Replace("YOURPASSWORD", mdp)
                           .Replace("YOURDB", dbName)
                           .Replace("YOURDATABASE", databaseAddress);

            services.AddDbContext <ApplicationDbContext>(options => options.UseMySql(connectionDb, ServerVersion.AutoDetect(connectionDb)));

            services.AddDefaultIdentity <IdentityUser>(options => options.SignIn.RequireConfirmedAccount = false)
            .AddRoles <IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>();

            services.AddRazorPages();
            services.AddServerSideBlazor();

            services.AddScoped <AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider <IdentityUser> >();
            services.AddDatabaseDeveloperPageExceptionFilter();

            // Service SQL de AccessData.
            services.AddSingleton(new SqlContextAccess(connectionDb));

            // Service de Radzen
            services.AddScoped <DialogService>();
            services.AddScoped <NotificationService>();
            services.AddScoped <TooltipService>();
            services.AddScoped <ContextMenuService>();

            // Pour téléchargement de fichier.
            services.AddBlazorDownloadFile();

            services.AddBlazoredModal();

            services.AddHttpContextAccessor();
            services.AddScoped <CurrentUserService>();
            services.AddScoped <IDataAccess, DataService>();

            services.AddScoped <IUsersViewModel, UsersViewModel>();
            services.AddScoped <IGestionLog, GestionLogViewModel>();
            services.AddScoped <IMesTableauxViewModel, MesTableauxViewModel>();
            services.AddScoped <INewTableViewModel, NewTableViewModel>();
            services.AddScoped <ITableauViewModel, TableauViewModel>();
        }
Beispiel #5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(o =>
            {
                o.Authority            = Configuration["Jwt:Authority"];
                o.Audience             = Configuration["Jwt:Audience"];
                o.RequireHttpsMetadata = false;
                o.Events = new JwtBearerEvents()
                {
                    OnAuthenticationFailed = c =>
                    {
                        c.Response.StatusCode  = 500;
                        c.Response.ContentType = "text/plain";
                        return(c.Response.WriteAsync(c.Exception.ToString()));
                    }
                };
            });

            services.AddDbContextPool <DatabaseContext>(options => {
                var connectionString = Configuration.GetConnectionString("DefaultConnection");
                var serverVersion    = ServerVersion.AutoDetect(connectionString);
                options.UseMySql(connectionString, serverVersion);
            });

            services.AddTransient <IProductRepository, ProductRepository>();

            services.AddControllers();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Products.API", Version = "v1"
                });
                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description  = @"Put **_ONLY_** your JWT Bearer token on textbox below!",
                    Name         = "JWT Authentication",
                    BearerFormat = "JWT",
                    In           = ParameterLocation.Header,
                    Type         = SecuritySchemeType.Http,
                    Scheme       = "Bearer"
                });

                c.AddSecurityRequirement(new OpenApiSecurityRequirement()
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id   = "Bearer"
                            },
                            Scheme = "oauth2",
                            Name   = "Bearer",
                            In     = ParameterLocation.Header,
                        },
                        new List <string>()
                    }
                });
            });

            services.AddMvc().AddMetrics();
        }
Beispiel #6
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            services.AddEntityFrameworkMySql()
            .AddDbContext <ToDoListContext>(options => options
                                            .UseMySql(Configuration["ConnectionStrings:DefaultConnection"], ServerVersion.AutoDetect(Configuration["ConnectionStrings:DefaultConnection"])));
            services.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <ToDoListContext>()
            .AddDefaultTokenProviders();
            services.Configure <IdentityOptions>(options =>
            {
                options.Password.RequireDigit           = false;
                options.Password.RequiredLength         = 0;
                options.Password.RequireLowercase       = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequiredUniqueChars    = 0;
            });
        }
Beispiel #7
0
 /// <summary>
 /// Configures the context to use MySql
 /// </summary>
 public static DbContextOptionsBuilder UseMySql(this DbContextOptionsBuilder builder, string connectionString) =>
 builder.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString), db => db
                  .MigrationsAssembly(typeof(MySqlElsaContextFactory).Assembly.GetName().Name)
                  .MigrationsHistoryTable(ElsaContext.MigrationsHistoryTable, ElsaContext.ElsaSchema)
                  .SchemaBehavior(MySqlSchemaBehavior.Ignore));
        public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration config)
        {
            if (Environment.GetEnvironmentVariable("USE_IN_MEMORY") == "1" || Environment.GetEnvironmentVariable("USE_IN_MEMORY") == null)
            {
                services.AddDbContext <AppDbContext>(options =>
                {
                    options.UseInMemoryDatabase("db");
                });
            }
            else
            {
                services.AddDbContext <AppDbContext>(options =>
                {
                    options.UseMySql(config.GetConnectionString("DatabaseConnectionString"), ServerVersion.AutoDetect(config.GetConnectionString("DatabaseConnectionString")));
                });
            }
            services.AddScoped <IYearCourseRepository, YearCourseRepository>();

            services.AddScoped <IKeyRepository, KeyRepository>();

            services.AddScoped <ISubjectRepository, SubjectRepository>();

            services.AddScoped <IGroupRepository, GroupRepository>();

            services.AddScoped <IUnitOfWork, UnitOfWork>();

            services.AddMediatR(typeof(BaseResult));

            services.AddScoped(typeof(IPipelineBehavior <,>), typeof(RequestAuthorizationBehavior <,>));

            return(services);
        }
        public void ConfigureServices(IServiceCollection services)
        {
            OnConfiguringServices(services);

            services.AddHttpContextAccessor();
            services.AddScoped <HttpClient>(serviceProvider =>
            {
                var uriHelper = serviceProvider.GetRequiredService <NavigationManager>();

                return(new HttpClient
                {
                    BaseAddress = new Uri(uriHelper.BaseUri)
                });
            });

            services.AddHttpClient();
            services.AddScoped <LocalhostService>();

            services.AddDbContext <Flashcardgenerator.Data.LocalhostContext>(options =>
            {
                options.UseMySql(Configuration.GetConnectionString("localhostConnection"), ServerVersion.AutoDetect(Configuration.GetConnectionString("localhostConnection")));
            });

            services.AddRazorPages();
            services.AddServerSideBlazor().AddHubOptions(o =>
            {
                o.MaximumReceiveMessageSize = 10 * 1024 * 1024;
            });

            services.AddScoped <DialogService>();
            services.AddScoped <NotificationService>();
            services.AddScoped <TooltipService>();
            services.AddScoped <ContextMenuService>();
            services.AddScoped <GlobalsService>();
            services.AddBlazorDownloadFile(ServiceLifetime.Scoped);


            try
            {
                System.IO.DirectoryInfo di = new DirectoryInfo("wwwroot/temp");

                foreach (System.IO.FileInfo file in di.GetFiles())
                {
                    file.Delete();
                }
                foreach (DirectoryInfo dir in di.GetDirectories())
                {
                    dir.Delete(true);
                }
            } catch (Exception e)
            {
                Console.WriteLine("Unable to clear temp directory.");
            }


            try
            {
                Aspose.Words.License license = new Aspose.Words.License();
                var licenseResource          = "Flashcardgenerator.Aspose.Words.lic";

                license.SetLicense(licenseResource);

                Console.WriteLine("License set successfully.");
            }
            catch (Exception e)
            {
                // We do not ship any license with this example, visit the Aspose site to obtain either a temporary or permanent license.
                Console.WriteLine("\nThere was an error setting the license: " + e.Message);
            }


            OnConfigureServices(services);
        }
Beispiel #10
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            string mySqlConnectionStr = Configuration.GetConnectionString("DefaultConnection");

            services.AddDbContextPool <MyDBContext>(options => options.UseMySql(mySqlConnectionStr, ServerVersion.AutoDetect(mySqlConnectionStr)));

            services.AddCors(options =>
            {
                options.AddPolicy(name: MyAllowSpecificOrigins,
                                  builder =>
                {
                    builder.WithOrigins("http://example.com",
                                        "http://localhost:3000").AllowAnyHeader().AllowAnyMethod();
                });
            });
            services.AddControllers().AddNewtonsoftJson();
        }
Beispiel #11
0
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddDbContext <CretaceousParkContext>(opt =>
                                                   opt.UseMySql(Configuration["ConnectionStrings:DefaultConnection"], ServerVersion.AutoDetect(Configuration["ConnectionStrings:DefaultConnection"])));
     services.AddControllers();
     services.AddSwaggerGen(c =>
     {
         c.SwaggerDoc("v1", new OpenApiInfo
         {
             Version     = "v1",
             Title       = "Cretaceous Park API",
             Description = "A simple example ASP.NET Core Web API",
             Contact     = new OpenApiContact
             {
                 Name  = "Dani Renner",
                 Email = "*****@*****.**",
                 Url   = new Uri("https://www.github.com/dani-renner"),
             },
             License = new OpenApiLicense
             {
                 Name = "Use under MIT License",
                 Url  = new Uri("https://opensource.org/licenses/MIT"),
             }
         });
         var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
         var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
         c.IncludeXmlComments(xmlPath);
     });
 }
Beispiel #12
0
        public void ConfigureServices(IServiceCollection services)
        {
            var connection = Configuration["ConnectionStrings:BankSystemDatabase"];

            services.AddDbContext <BankSystemContext>(options => options.UseLazyLoadingProxies().UseMySql(connection, ServerVersion.AutoDetect(connection)));

            services.AddControllers()
            .AddNewtonsoftJson(options =>
                               options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                               );

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

            services.AddCors(options =>
            {
                options.AddDefaultPolicy(policy =>
                                         policy.AllowAnyHeader()
                                         .AllowAnyMethod()
                                         .AllowAnyOrigin()
                                         );
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
        }
Beispiel #13
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <ApplicationContext>(options =>
                                                       options.UseMySql(Configuration.GetConnectionString("PhoneConversation"), ServerVersion.AutoDetect(Configuration.GetConnectionString("PhoneConversation"))));

            services.AddControllersWithViews();
        }
Beispiel #14
0
        public static void AddSqlServerRepositories(this IServiceCollection services, GlobalSettings globalSettings)
        {
            var selectedDatabaseProvider = globalSettings.DatabaseProvider;
            var provider         = SupportedDatabaseProviders.SqlServer;
            var connectionString = string.Empty;

            if (!string.IsNullOrWhiteSpace(selectedDatabaseProvider))
            {
                switch (selectedDatabaseProvider.ToLowerInvariant())
                {
                case "postgres":
                case "postgresql":
                    provider         = SupportedDatabaseProviders.Postgres;
                    connectionString = globalSettings.PostgreSql.ConnectionString;
                    break;

                case "mysql":
                case "mariadb":
                    provider         = SupportedDatabaseProviders.MySql;
                    connectionString = globalSettings.MySql.ConnectionString;
                    break;

                default:
                    break;
                }
            }

            var useEf = (provider != SupportedDatabaseProviders.SqlServer);

            if (useEf)
            {
                if (string.IsNullOrWhiteSpace(connectionString))
                {
                    throw new Exception($"Database provider type {provider} was selected but no connection string was found.");
                }
                LinqToDBForEFTools.Initialize();
                services.AddAutoMapper(typeof(EntityFrameworkRepos.UserRepository));
                services.AddDbContext <EntityFrameworkRepos.DatabaseContext>(options =>
                {
                    if (provider == SupportedDatabaseProviders.Postgres)
                    {
                        options.UseNpgsql(connectionString);
                    }
                    else if (provider == SupportedDatabaseProviders.MySql)
                    {
                        options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString));
                    }
                });
                services.AddSingleton <ICipherRepository, EntityFrameworkRepos.CipherRepository>();
                services.AddSingleton <ICollectionCipherRepository, EntityFrameworkRepos.CollectionCipherRepository>();
                services.AddSingleton <ICollectionRepository, EntityFrameworkRepos.CollectionRepository>();
                services.AddSingleton <IDeviceRepository, EntityFrameworkRepos.DeviceRepository>();
                services.AddSingleton <IEmergencyAccessRepository, EntityFrameworkRepos.EmergencyAccessRepository>();
                services.AddSingleton <IFolderRepository, EntityFrameworkRepos.FolderRepository>();
                services.AddSingleton <IGrantRepository, EntityFrameworkRepos.GrantRepository>();
                services.AddSingleton <IGroupRepository, EntityFrameworkRepos.GroupRepository>();
                services.AddSingleton <IInstallationRepository, EntityFrameworkRepos.InstallationRepository>();
                services.AddSingleton <IMaintenanceRepository, EntityFrameworkRepos.MaintenanceRepository>();
                services.AddSingleton <IOrganizationRepository, EntityFrameworkRepos.OrganizationRepository>();
                services.AddSingleton <IOrganizationSponsorshipRepository, EntityFrameworkRepos.OrganizationSponsorshipRepository>();
                services.AddSingleton <IOrganizationUserRepository, EntityFrameworkRepos.OrganizationUserRepository>();
                services.AddSingleton <IPolicyRepository, EntityFrameworkRepos.PolicyRepository>();
                services.AddSingleton <ISendRepository, EntityFrameworkRepos.SendRepository>();
                services.AddSingleton <ISsoConfigRepository, EntityFrameworkRepos.SsoConfigRepository>();
                services.AddSingleton <ISsoUserRepository, EntityFrameworkRepos.SsoUserRepository>();
                services.AddSingleton <ITaxRateRepository, EntityFrameworkRepos.TaxRateRepository>();
                services.AddSingleton <ITransactionRepository, EntityFrameworkRepos.TransactionRepository>();
                services.AddSingleton <IU2fRepository, EntityFrameworkRepos.U2fRepository>();
                services.AddSingleton <IUserRepository, EntityFrameworkRepos.UserRepository>();
                services.AddSingleton <IProviderRepository, EntityFrameworkRepos.ProviderRepository>();
                services.AddSingleton <IProviderUserRepository, EntityFrameworkRepos.ProviderUserRepository>();
                services.AddSingleton <IProviderOrganizationRepository, EntityFrameworkRepos.ProviderOrganizationRepository>();
            }
            else
            {
                services.AddSingleton <ICipherRepository, SqlServerRepos.CipherRepository>();
                services.AddSingleton <ICollectionCipherRepository, SqlServerRepos.CollectionCipherRepository>();
                services.AddSingleton <ICollectionRepository, SqlServerRepos.CollectionRepository>();
                services.AddSingleton <IDeviceRepository, SqlServerRepos.DeviceRepository>();
                services.AddSingleton <IEmergencyAccessRepository, SqlServerRepos.EmergencyAccessRepository>();
                services.AddSingleton <IFolderRepository, SqlServerRepos.FolderRepository>();
                services.AddSingleton <IGrantRepository, SqlServerRepos.GrantRepository>();
                services.AddSingleton <IGroupRepository, SqlServerRepos.GroupRepository>();
                services.AddSingleton <IInstallationRepository, SqlServerRepos.InstallationRepository>();
                services.AddSingleton <IMaintenanceRepository, SqlServerRepos.MaintenanceRepository>();
                services.AddSingleton <IOrganizationRepository, SqlServerRepos.OrganizationRepository>();
                services.AddSingleton <IOrganizationSponsorshipRepository, SqlServerRepos.OrganizationSponsorshipRepository>();
                services.AddSingleton <IOrganizationUserRepository, SqlServerRepos.OrganizationUserRepository>();
                services.AddSingleton <IPolicyRepository, SqlServerRepos.PolicyRepository>();
                services.AddSingleton <ISendRepository, SqlServerRepos.SendRepository>();
                services.AddSingleton <ISsoConfigRepository, SqlServerRepos.SsoConfigRepository>();
                services.AddSingleton <ISsoUserRepository, SqlServerRepos.SsoUserRepository>();
                services.AddSingleton <ITaxRateRepository, SqlServerRepos.TaxRateRepository>();
                services.AddSingleton <IEmergencyAccessRepository, SqlServerRepos.EmergencyAccessRepository>();
                services.AddSingleton <IProviderRepository, SqlServerRepos.ProviderRepository>();
                services.AddSingleton <IProviderUserRepository, SqlServerRepos.ProviderUserRepository>();
                services.AddSingleton <IProviderOrganizationRepository, SqlServerRepos.ProviderOrganizationRepository>();
                services.AddSingleton <ITransactionRepository, SqlServerRepos.TransactionRepository>();
                services.AddSingleton <IU2fRepository, SqlServerRepos.U2fRepository>();
                services.AddSingleton <IUserRepository, SqlServerRepos.UserRepository>();
            }

            if (globalSettings.SelfHosted)
            {
                if (useEf)
                {
                    services.AddSingleton <IEventRepository, EntityFrameworkRepos.EventRepository>();
                }
                else
                {
                    services.AddSingleton <IEventRepository, SqlServerRepos.EventRepository>();
                }
                services.AddSingleton <IInstallationDeviceRepository, NoopRepos.InstallationDeviceRepository>();
                services.AddSingleton <IMetaDataRepository, NoopRepos.MetaDataRepository>();
            }
            else
            {
                services.AddSingleton <IEventRepository, TableStorageRepos.EventRepository>();
                services.AddSingleton <IInstallationDeviceRepository, TableStorageRepos.InstallationDeviceRepository>();
                services.AddSingleton <IMetaDataRepository, TableStorageRepos.MetaDataRepository>();
            }
        }
Beispiel #15
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            string mySqlConnectionStr = Configuration.GetConnectionString("DefaultConnection");

            services.AddDbContextPool <InfludashContext>(options => options.UseMySql(mySqlConnectionStr, ServerVersion.AutoDetect(mySqlConnectionStr)));

            services.AddControllers().AddNewtonsoftJson();
            services.AddTokenAuthentication(Configuration);

            services.AddCors(options =>
            {
                options.AddPolicy(
                    name: myOrigins,
                    builder =>
                {
                    builder.WithOrigins(Configuration["Cors:frontend"])
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials();
                });
            });

            services.AddHangfire(x => x.UseStorage(new MySqlStorage(mySqlConnectionStr, new MySqlStorageOptions {
                PrepareSchemaIfNecessary = true
            })));
            services.AddHangfireServer();

            services.AddMemoryCache();
        }
Beispiel #16
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var mySqlConnectionStr = Configuration.GetConnectionString("DefaultConnection");

            services.AddDbContextPool <CompanyContext>(options => options.UseMySql(mySqlConnectionStr, ServerVersion.AutoDetect(mySqlConnectionStr)));
            services.AddControllersWithViews();
        }
Beispiel #17
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //JWT
            var existe             = Configuration.GetSection("AppTokenSettings").Exists();
            var appSettingsSection = Configuration.GetSection("AppTokenSettings");

            services.Configure <AppSettings>(appSettingsSection);

            var appsSettings = appSettingsSection.Get <AppSettings>();
            var key          = Encoding.ASCII.GetBytes(appsSettings.Secret);

            string mySqlConnection = Configuration.GetConnectionString("IdentityConnection");

            services.AddDbContext <AppDbContext>(options => options.UseMySql(mySqlConnection, ServerVersion.AutoDetect(mySqlConnection)));
            //IDENTITY
            services.AddIdentity <User, IdentityRole>(options =>
            {
                options.User.RequireUniqueEmail = false;
            })
            .AddEntityFrameworkStores <AppDbContext>()
            .AddDefaultTokenProviders();

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = false;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key),
                    ValidateIssuer           = false,
                    ValidateAudience         = false
                };
            });

            services.AddTransient(_ => new DapperDb(Configuration.GetConnectionString("SqlServerConnection")));

            services.AddApplicationInjections().AddInfraInjections();

            services.AddCors();
            services.AddControllers();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "ConsultaUserApi", Version = "v1"
                });
            });
        }
Beispiel #18
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            string connectionString = Configuration.GetConnectionString("PizzaDelivery");

            services.AddDbContext <ApplicationContext>(options =>
                                                       options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString)));

            services.AddControllersWithViews();
        }
Beispiel #19
0
        /// <summary>
        /// Register DbContexts for IdentityServer ConfigurationStore and PersistedGrants and Identity
        /// Configure the connection strings in AppSettings.json
        /// </summary>
        /// <typeparam name="TConfigurationDbContext"></typeparam>
        /// <typeparam name="TPersistedGrantDbContext"></typeparam>
        /// <typeparam name="TIdentityDbContext"></typeparam>
        /// <param name="services"></param>
        /// <param name="identityConnectionString"></param>
        /// <param name="configurationConnectionString"></param>
        /// <param name="persistedGrantConnectionString"></param>
        public static void RegisterMySqlDbContexts <TIdentityDbContext, TConfigurationDbContext,
                                                    TPersistedGrantDbContext, TDataProtectionDbContext>(this IServiceCollection services,
                                                                                                        string identityConnectionString, string configurationConnectionString,
                                                                                                        string persistedGrantConnectionString, string dataProtectionConnectionString)
            where TIdentityDbContext : DbContext
            where TPersistedGrantDbContext : DbContext, IAdminPersistedGrantDbContext
            where TConfigurationDbContext : DbContext, IAdminConfigurationDbContext
            where TDataProtectionDbContext : DbContext, IDataProtectionKeyContext
        {
            var migrationsAssembly = typeof(DatabaseExtensions).GetTypeInfo().Assembly.GetName().Name;

            // Config DB for identity
            services.AddDbContext <TIdentityDbContext>(options =>
                                                       options.UseMySql(identityConnectionString,
                                                                        ServerVersion.AutoDetect(identityConnectionString),
                                                                        sql => sql.MigrationsAssembly(migrationsAssembly)));

            // Config DB from existing connection
            services.AddConfigurationDbContext <TConfigurationDbContext>(options =>
                                                                         options.ConfigureDbContext = b => b.UseMySql(configurationConnectionString,
                                                                                                                      ServerVersion.AutoDetect(configurationConnectionString),
                                                                                                                      sql => sql.MigrationsAssembly(migrationsAssembly)));

            // Operational DB from existing connection
            services.AddOperationalDbContext <TPersistedGrantDbContext>(options =>
                                                                        options.ConfigureDbContext = b => b.UseMySql(persistedGrantConnectionString,
                                                                                                                     ServerVersion.AutoDetect(persistedGrantConnectionString),
                                                                                                                     sql => sql.MigrationsAssembly(migrationsAssembly)));

            // DataProtectionKey DB from existing connection
            services.AddDbContext <TDataProtectionDbContext>(options =>
                                                             options.UseMySql(dataProtectionConnectionString,
                                                                              ServerVersion.AutoDetect(dataProtectionConnectionString),
                                                                              optionsSql => optionsSql.MigrationsAssembly(migrationsAssembly)));
        }
Beispiel #20
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var mySqlConnectionStr = Configuration.GetConnectionString("connectionString");

            services.AddDbContext <DataContext>(options => options.UseMySql(mySqlConnectionStr, ServerVersion.AutoDetect(mySqlConnectionStr)));

            services.AddTransient <ICATRepository, CATRepository>();
            services.AddTransient <ICustomerRepository, CustomerRepository>();
            services.AddTransient <IAccessRepository, AccessRepository>();
            services.AddTransient <CATHandler, CATHandler>();
            services.AddTransient <CustomerHandler, CustomerHandler>();
            services.AddTransient <AccessHandler, AccessHandler>();

            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "API", Version = "v1"
                });
            });
        }
Beispiel #21
0
        public static IServiceCollection AddIsuCorpTestData(this IServiceCollection services, IConfiguration configuration)
        {
            var connectionString = configuration.GetConnectionString("DefaultConnection");

            services.AddDbContextPool <DataContext>(options => options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString)));

            services.AddTransient <TestData>(); // TODO: This is for testing only.
            services.AddTransient <IUnitOfWork, EFCoreUnitOfWork>();

            // TODO: add services
            return(services);
        }
Beispiel #22
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            string mySqlConnection = Configuration.GetConnectionString("DefaultConnection");

            services.AddDbContextPool <ProdutoContext>(options => options.UseMySql(mySqlConnection, ServerVersion.AutoDetect(mySqlConnection)));

            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "WebApi_MySql8", Version = "v1"
                });
            });
        }
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddDbContext <MessageBoardContext>(opt =>
                                                 opt.UseMySql(Configuration["ConnectionStrings:DefaultConnection"], ServerVersion.AutoDetect(Configuration["ConnectionStrings:DefaultConnection"])));
     services.AddControllers();
 }
Beispiel #24
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            string mySqlConnectionStr = Configuration.GetConnectionString("DefaultConnection");

            services.AddDbContextPool <SqlDbContext>(options => options.UseMySql(mySqlConnectionStr, ServerVersion.AutoDetect(mySqlConnectionStr)));
            services.AddAuthorization();
            services.AddScoped <IRepositoryWrapper, RepositoryWrapper>();
            services.AddControllers();
            services.AddAutoMapper(typeof(Startup));
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "FootballLeagueAPI", Version = "v1"
                });
            });
        }
Beispiel #25
0
 protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
 {
     SetLog(optionsBuilder);
     optionsBuilder.UseMySql(ConnectionString, ServerVersion.AutoDetect(ConnectionString));
     base.OnConfiguring(optionsBuilder);
 }
Beispiel #26
0
        protected override void OnConfiguring(DbContextOptionsBuilder options)
        {
            var connStr     = Configuration.GetSection("dbConfig")["connectionString"];
            var efcoreBuild =
                Configuration.GetSection("dbConfig")["efcoreBuild"] != null; // Used for building migrations

            options.UseMySql(connStr,
                             efcoreBuild ? MariaDbServerVersion.LatestSupportedServerVersion : ServerVersion.AutoDetect(connStr));
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var myConnectionString = Configuration.GetConnectionString("DefaultConnection");

            services.AddDbContext <ApplicationDbContext>(options => options.UseMySql(myConnectionString, ServerVersion.AutoDetect(myConnectionString)));
            services.AddRouting(r => r.LowercaseUrls = true);        //configure lowercase urls
            services.AddControllersWithViews();
        }
Beispiel #28
0
        public void ConfigureServices(IServiceCollection services)
        {
            string connectionDb = Configuration.GetConnectionString("MySqlConnection");

            // *** Dans le cas ou une utilisation avec DOCKER
            // *** voir post sur : https://www.ctrl-alt-suppr.dev/2021/02/01/connectionstring-et-image-docker/
            string databaseAddress = Environment.GetEnvironmentVariable("DB_HOST");
            string login           = Environment.GetEnvironmentVariable("LOGIN_DB");
            string mdp             = Environment.GetEnvironmentVariable("PASSWORD_DB");
            string dbName          = Environment.GetEnvironmentVariable("DB_NAME");

            connectionDb = connectionDb.Replace("USERNAME", login)
                           .Replace("YOURPASSWORD", mdp)
                           .Replace("YOURDB", dbName)
                           .Replace("YOURDATABASE", databaseAddress);

            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseMySql(connectionDb, ServerVersion.AutoDetect(connectionDb)));

            services.AddDefaultIdentity <IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
            .AddRoles <IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>();

            services.AddRazorPages();
            services.AddServerSideBlazor();
            services.AddScoped <AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider <IdentityUser> >();
            services.AddDatabaseDeveloperPageExceptionFilter();

            // Service SQL de AccessData.
            services.AddSingleton(new SqlContext(connectionDb));

            // Pour JWT auth
            var key = Configuration["KeyPourJwt"];

            services.AddAuthentication(x =>
            {
                // Si ajout de cette ligne, plus possible de s'authentifier sur le site.
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = true;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(key)),
                    ValidateIssuer           = false,
                    ValidateAudience         = false,
                };
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("RequestAdmin", policy =>
                                  policy.RequireRole("Admin"));

                options.AddPolicy("ManagerRequest", policy =>
                                  policy.RequireRole("Manager", "Admin"));

                options.AddPolicy("MemberRequest", policy =>
                                  policy.RequireRole("Member", "Manager", "Admin"));
            });

            services.AddScoped <IJwtAuthenticationManager, JwtAuthenticationManager>();
        }
Beispiel #29
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            services.AddEntityFrameworkMySql()
            .AddDbContext <BestRestaurantsContext>(options => options
                                                   .UseMySql(Configuration["ConnectionStrings:DefaultConnection"], ServerVersion.AutoDetect(Configuration["ConnectionStrings:DefaultConnection"])));
        }
Beispiel #30
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            string mySqlConnectionStr = Configuration.GetConnectionString("ConnectionString");

            services.AddDbContextPool <CarparkDbContext>(options => options.UseMySql(mySqlConnectionStr, ServerVersion.AutoDetect(mySqlConnectionStr)));

            services.AddControllers();
            services.AddCors(options =>
            {
                options.AddPolicy("AllowAllOrigins",
                                  builder => builder.AllowAnyOrigin());
            });
            services.AddTransient <IMemberService, MemberService>();
            services.AddTransient <ICarparkService, CarparkService>();
            services.AddTransient <IMemberRepository, MemberRepository>();

            services.Configure <AppSettings>(Configuration.GetSection("AppSettings"));
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Carpark system", Version = "v1"
                });
                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Type         = SecuritySchemeType.Http,
                    Scheme       = "Bearer",
                    BearerFormat = "JWT",
                    Description  = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name         = "Authorization"
                });
                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference {
                                Type = ReferenceType.SecurityScheme, Id = "Bearer"
                            }
                        },
                        new[] { "readAccess", "writeAccess" }
                    }
                });
            });
        }