示例#1
0
        public static async Task Main(string[] args)
        {
            var host = CreateHostBuilder(args).Build();

            using var scope = host.Services.CreateScope();
            var services      = scope.ServiceProvider;
            var loggerFactory = services.GetRequiredService <ILoggerFactory>();

            try
            {
                var context = services.GetRequiredService <ApplicationDbContext>();
                if (context.Database.GetPendingMigrations().Count() > 0)
                {
                    context.Database.Migrate();//installs pending migrations.
                }
                await ApplicationContextSeed.SeedAsync(context, loggerFactory);
            }
            catch (Exception ex)
            {
                var logger = loggerFactory.CreateLogger <Program>();//Program is the class we want to associate the error with.
                logger.LogError(ex, "An error occured during migration");
            }

            host.Run();
        }
示例#2
0
        public static async Task Main(string[] args)
        {
            var host = CreateHostBuilder(args)
                       .Build();

            using (var scope = host.Services.CreateScope())
            {
                var services      = scope.ServiceProvider;
                var loggerFactory = services.GetRequiredService <ILoggerFactory>();
                try
                {
                    // При первом запуске заполняем бд данными

                    var catalogContext = services.GetRequiredService <ApplicationContext>();
                    await ApplicationContextSeed.SeedAsync(catalogContext, loggerFactory);
                }
                catch (Exception ex)
                {
                    var logger = loggerFactory.CreateLogger <Program>();
                    logger.LogError(ex, "An error occurred seeding the DB.");
                    return;
                }
            }

            host.Run();
        }
        /// <summary>
        /// Build services factory.
        /// </summary>
        /// <param name="host">Application Host.</param>
        public static void Build(IHost host)
        {
            host = host ?? throw new ArgumentNullException(nameof(host));

            using var scope = host.Services.CreateScope();
            var services = scope.ServiceProvider;

            RuntimeMigrations.Initialize(services);
            ApplicationContextSeed.Initialize(services);
        }
        public static void Seed(this IApplicationBuilder applicationBuilder)
        {
            using (var serviceScope = applicationBuilder
                                      .ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope())
            {
                var context = serviceScope.ServiceProvider.GetService <ApplicationDbContext>();

                ApplicationContextSeed.SeedAsync(context).GetAwaiter().GetResult();
            }
        }
示例#5
0
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder = builder ?? throw new ArgumentNullException(nameof(builder));

            builder.UseEnvironment("Testing");

            builder.ConfigureServices(services =>
            {
                services.AddEntityFrameworkInMemoryDatabase();

                var provider = services
                               .AddEntityFrameworkInMemoryDatabase()
                               .BuildServiceProvider();

                services.AddDbContext <ApplicationContext>(options =>
                {
                    options.UseInMemoryDatabase("InMemoryDbForTesting");
                    options.UseInternalServiceProvider(provider);
                });

                services.AddDbContext <ApplicationContext>(options =>
                {
                    options.UseInMemoryDatabase("Identity");
                    options.UseInternalServiceProvider(provider);
                });

                var sp = services.BuildServiceProvider();

                using (var scope = sp.CreateScope())
                {
                    var scopedServices = scope.ServiceProvider;

                    var db            = scopedServices.GetRequiredService <ApplicationContext>();
                    var loggerFactory = scopedServices.GetRequiredService <ILoggerFactory>();
                    var logger        = scopedServices.GetRequiredService <ILogger <WebTestFixture> >();

                    db.Database.EnsureCreated();

                    try
                    {
                        var userManager = scopedServices.GetRequiredService <UserManager <ApplicationUser> >();
                        var roleManager = scopedServices.GetRequiredService <RoleManager <IdentityRole> >();

                        ApplicationContextSeed.IdentitySeedAsync(db, userManager, roleManager).Wait();
                    }
                    catch (Exception ex)
                    {
                        logger.LogError(ex, $"An error occurred seeding the " +
                                        "database with test messages. Error: {ex.Message}");
                    }
                }
            });
        }
示例#6
0
        public static async Task Main(string[] args)
        {
            var host = CreateHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope())
            {
                // context db seed
                var services = scope.ServiceProvider;
                await ApplicationContextSeed.SeedAsync(services);
            }

            await host.RunAsync();
        }
示例#7
0
        private static IWebHost CreateDatabaseIfNotExists(this IWebHost host)
        {
            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                try
                {
                    var context = services.GetRequiredService <ApplicationContext>();
                    ApplicationContextSeed.Initialize(context);
                }
                catch (Exception ex) { Console.WriteLine(ex); }
            }

            return(host);
        }
示例#8
0
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder.UseEnvironment("Testing");

            builder.ConfigureServices(services =>
            {
                services.AddEntityFrameworkInMemoryDatabase();

                var provider = services
                               .AddEntityFrameworkInMemoryDatabase()
                               .BuildServiceProvider();

                services.AddDbContext <ApplicationContext>(options =>
                {
                    options.UseInMemoryDatabase("DBForTesting");
                    options.UseInternalServiceProvider(provider);
                });

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

                var sp = services.BuildServiceProvider();

                using (var scope = sp.CreateScope())
                {
                    var scopedServices = scope.ServiceProvider;

                    var db = scopedServices.GetRequiredService <ApplicationContext>();

                    db.Database.EnsureCreated();

                    try
                    {
                        var userManager = scopedServices.GetRequiredService <UserManager <ApplicationUser> >();
                        var roleManager = scopedServices.GetRequiredService <RoleManager <IdentityRole> >();

                        IdentityContextSeed.SeedAsync(userManager, roleManager).Wait();
                        ApplicationContextSeed.SeedAsync(db, userManager, "/img/example_image.jpg").Wait();
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.Message);
                    }
                }
            });
        }
示例#9
0
        /// <summary>
        /// Заполнить базу данных.
        /// </summary>
        /// <param name="serviceProvider">Провайдер сервисов.</param>
        public static void Initialize(IServiceProvider serviceProvider)
        {
            try
            {
                var contextOptions = serviceProvider.GetRequiredService <DbContextOptions <ApplicationContext> >();
                var userManager    = serviceProvider.GetRequiredService <UserManager <ApplicationUser> >();
                var roleManager    = serviceProvider.GetRequiredService <RoleManager <IdentityRole> >();

                using var applicationContext = new ApplicationContext(contextOptions);

                ApplicationContextSeed.IdentitySeedAsync(applicationContext, userManager, roleManager).GetAwaiter().GetResult();

                Log.Information(logInformationMessage);
            }
            catch (Exception ex)
            {
                Log.Error(ex, logErrorMessage);
            }
        }
示例#10
0
        public static async Task Main(string[] args)
        {
            var host = CreateHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope()) {
                var services      = scope.ServiceProvider;
                var loggerFactory = services.GetRequiredService <ILoggerFactory>();
                try {
                    var context     = services.GetRequiredService <ApplicationContext>();
                    var userManager = services.GetRequiredService <UserManager <ApplicationUser> >();
                    await context.Database.MigrateAsync();

                    await ApplicationContextSeed.SeedDataAsync(context, userManager, loggerFactory);
                } catch (Exception ex) {
                    var logger = loggerFactory.CreateLogger <Program>();
                    logger.LogError(ex, "An error occured while seeding the database.");
                }
            }
            host.Run();
        }
示例#11
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            #region Database
            //DB configuration
            var buildType = Configuration.GetValue <string>("BuildType");
            if (buildType == "sqlite")
            {
                services.AddDbContext <ApplicationContext>(op =>
                {
                    op.UseSqlite(Configuration.GetConnectionString("TestSqliteConnection"));
                });
            }
            else if (buildType == "sqlserver")
            {
                services.AddDbContext <ApplicationContext>(options =>
                                                           options.UseSqlServer(Configuration.GetConnectionString("TestSqlServerConnection")));
            }
            else if (buildType == "azure")
            {
                services.AddDbContext <ApplicationContext>(options =>
                                                           options.UseSqlServer(Configuration.GetConnectionString("AzureDBConnection")));
            }
            else if (buildType == "testconnection")
            {
                services.AddDbContext <ApplicationContext>(op =>
                {
                    op.UseSqlite("FileName = testDB.db");
                });

                var sp = services.BuildServiceProvider();
                ApplicationContextSeed.Seed(sp.GetService <ApplicationContext>());
            }
            #endregion

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

            services.ConfigureApplicationCookie(op =>
            {
                op.LoginPath      = "/login/signin";
                op.ExpireTimeSpan = TimeSpan.FromMinutes(30);
            });

            services.Configure <IdentityOptions>(op =>
            {
                //Configure password requirements
                op.Password.RequireDigit           = false;
                op.Password.RequiredLength         = 5;
                op.Password.RequireLowercase       = true;
                op.Password.RequireUppercase       = false;
                op.Password.RequireNonAlphanumeric = false;

                op.User.RequireUniqueEmail = true;
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("test",
                                  policy => policy.Requirements.Add(new ConfirmedEmailRequirement()));

                options.AddPolicy("DriverOnly",
                                  policy => policy.Requirements.Add(new ViewerTypeRequirement(
                                                                        new ViewerType[] { ViewerType.Driver })));

                options.AddPolicy("PassangerOnly",
                                  policy => policy.Requirements.Add(new ViewerTypeRequirement(
                                                                        new ViewerType[] { ViewerType.Passanger })));

                options.AddPolicy("DriverAndPassangerOnly",
                                  policy => policy.Requirements.Add(new ViewerTypeRequirement(
                                                                        new ViewerType[] { ViewerType.Driver, ViewerType.Passanger })));
            });

            #region SetupDI
            services.AddTransient <INotificationProvider, HtmlNotificationProvider>();
            services.AddTransient <INotificationBodyProvider, HtmlNotificationBodyProvider>();
            services.AddTransient <IAuthorizationHandler, ConfirmedEmailHandler>();
            services.AddTransient <IViewerTypeProvider, ViewerTypeProvider>();
            services.AddTransient <IAuthorizationHandler, ViewerTypeHandler>();
            services.AddTransient <ITripDetailsViewModelProvider, TripDetailsViewModelProvider>();
            services.AddTransient <IRatesAndCommentRepository, RatesAndCommentRepository>();
            services.AddTransient <ITripUserRepository, TripUserRepository>();
            services.AddTransient <ITripDetailsRepository, TripDetailsRepository>();
            services.AddTransient <IApplicationUserViewModelGenerator, ApplicationUserViewModelGenerator>();
            services.AddTransient <IApplicationUserRepository, ApplicationUserRepository>();
            services.AddTransient <ITripDetailsCreator, TripDetailsCreator>();
            services.AddTransient <IIdentityResultErrorCreator, IdentityResultErrorTextCreator>();
            services.AddTransient <IEmailAddressValidator, EmailAddressValidator>();
            services.AddTransient <IAccountManager, AccountManager>();
            services.AddTransient <IViewerTypeMapper, ViewerTypeMapper>();
            services.AddScoped <ITripDetailsViewModelCreatorFactory, TripDetailViewModelCreatorFactory>();
            services.AddTransient <IAccountEmailConfirmatorFactory, AccountEmailConfirmatorFactory>();
            services.AddTransient <IPasswordResetFactory, PasswordResetFactory>();
            services.AddTransient <IChatEntryRepository, ChatEntryRepository>();
            services.AddTransient <ISpecificationEvaluator, SpecificationEvaluator>();
            services.AddTransient <IIncludeManager, IncludeManager>();
            services.AddTransient <IPdfCreator, PdfCreator>();
            services.AddTransient <ITripDetailsViewModelConverter, TripDetailsViewModelConverter>();
            services.AddTransient <IOfferStateEmailSender, OfferStateEmailSender>();
            services.AddTransient <IMessageBodyProvider, OfferStateMessageProvider>();
            services.AddTransient <ITripTimeCollisionChecker, TripTimeCollisionChecker>();


            services.AddSingleton <IIncludeChainProvider>(sp =>
            {
                return(new IncludeChainProvider()
                       .AddChain(new TripDetailsIncluder())
                       .AddChain(new UserIncluder())
                       .AddChain(new TripUserCollectionIncluder()));
            });

            #region EmailConfirmation
            services.AddTransient <AccountConfirmationProvider>();
            services.AddTransient <AccountTokenProvider>();
            services.AddTransient <PasswordResetConfirmationProvider>();
            services.AddTransient <PasswordResetTokenProvider>();

            services.AddTransient <Func <ConfirmatorType, IMessageBodyProvider> >((sp) =>
                                                                                  (type) =>
            {
                switch (type)
                {
                case ConfirmatorType.Account:
                    return(new AccountMessageProvider());

                case ConfirmatorType.PasswordReset:
                    return(new PasswordResetMessageProvider());

                default:
                    return(null);
                }
            });

            services.AddTransient <Func <ConfirmatorType, IConfirmationProvider> >((sp) =>
                                                                                   (type) =>
            {
                switch (type)
                {
                case ConfirmatorType.Account:
                    return(sp.GetService <AccountConfirmationProvider>());

                case ConfirmatorType.PasswordReset:
                    return(sp.GetService <PasswordResetConfirmationProvider>());

                default:
                    return(null);
                }
            });

            services.AddTransient <Func <ConfirmatorType, IConfirmationTokenProvider> >((sp) =>
                                                                                        (type) =>
            {
                switch (type)
                {
                case ConfirmatorType.Account:
                    return(sp.GetService <AccountTokenProvider>());

                case ConfirmatorType.PasswordReset:
                    return(sp.GetService <PasswordResetTokenProvider>());

                default:
                    return(null);
                }
            });
            #endregion

            #region EmailServiceSetup
            services.AddTransient <IEmailService, EmailService>();
            services.AddTransient <ISmtpClientProvider, GmailSmtpClientProvider>();
            services.AddTransient <IContentBuilder>((fac) =>
            {
                return(new ContentBuilder(
                           new System.Text.RegularExpressions.Regex(
                               Configuration.GetValue <string>("MessageTemplateRegex"))));
            });

            services.AddTransient <ICredentialsProvider>((fac) =>
            {
                return(new CredentialsProvider(Configuration.GetValue <string>("CredentialsFile")));
            });

            services.AddTransient <ITemplateProvider>((fac) =>
            {
                return(new JsonTemplateProvider(Configuration.GetValue <string>("TemplateFile")));
            });
            #endregion

            #region FileManagement
            services.AddTransient <IFileIdProvider, FileIdProvider>();
            services.AddTransient <IFileRemover, FileRemover>();
            services.AddTransient <IFileReader <string>, TextFileReader>();
            services.AddTransient <IFileSaverFactory, FileSaverFactory>();
            services.AddTransient <IFileManagerFactory, FileManagerFactory>();
            services.AddTransient <JsonFileManager, JsonFileManager>();
            services.AddTransient <PngFileManager, PngFileManager>();
            #endregion
            #endregion

            services.AddDistributedMemoryCache();
            services.AddSession(op =>
            {
                op.IdleTimeout        = TimeSpan.FromMinutes(1);
                op.Cookie.HttpOnly    = true;
                op.Cookie.IsEssential = true;
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddSignalR();
        }