// This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddDbContext <ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            services.AddSwaggerGen(c => {
                c.SwaggerDoc("v1",
                             new OpenApiInfo
                {
                    Title       = "MicroServices - Cadastro de Clientes",
                    Version     = "v1",
                    Description = "Exemplo de API REST criada com o ASP.NET Core 3.0 para CRUD de cadastro de Clientes",
                    Contact     = new OpenApiContact
                    {
                        Name = "Bruno Luiz Purcinelli",
                        Url  = new Uri("https://github.com/brunopurcinelli")
                    }
                });

                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
            });

            Console.WriteLine("**************** RUN SEED ****************");
            DbMigrationHelpers.EnsureSeedData(services.BuildServiceProvider()).GetAwaiter().GetResult();
            Console.WriteLine("************* SEED FINISH!!! *************");
        }
Esempio n. 2
0
        public static void Main(string[] args)
        {
            Console.Title = "JP Project - Server SSO";

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
                         .MinimumLevel.Override("System", LogEventLevel.Warning)
                         .MinimumLevel.Override("Microsoft.AspNetCore.Authentication", LogEventLevel.Information)
                         .Enrich.FromLogContext()
                         .WriteTo.File(@"jpProject_sso_log.txt")
                         .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level}] {SourceContext}{NewLine}{Message:lj}{NewLine}{Exception}{NewLine}", theme: AnsiConsoleTheme.Literate)
                         .CreateLogger();

            var configuration = new ConfigurationBuilder()
                                .AddCommandLine(args)
                                .Build();

            var hostUrl = configuration["hosturl"];

            if (string.IsNullOrEmpty(hostUrl))
            {
                hostUrl = "http://0.0.0.0:5000";
            }

            var host = CreateWebHostBuilder(args).UseUrls(hostUrl).UseConfiguration(configuration).Build();

            // Uncomment this to seed upon startup, alternatively pass in `dotnet run / seed` to seed using CLI
            // await DbMigrationHelpers.EnsureSeedData(host);
            Task.WaitAll(DbMigrationHelpers.EnsureSeedData(host));

            host.Run();
        }
Esempio n. 3
0
        public static async Task Main(string[] args)
        {
            var seed = args.Any(x => x == SeedArgs);

            if (seed)
            {
                args = args.Except(new[] { SeedArgs }).ToArray();
            }

            var host = CreateWebHostBuilder(args)
                       .ConfigureAppConfiguration((builderContext, config) =>
            {
                var appConfig      = config.Build();
                HostingEnvironment = builderContext.HostingEnvironment;
                config.AddConsulConfiguration(builderContext.HostingEnvironment, new Uri(appConfig.GetSection("ConsulUrl").Value), CancellationTokenSource.Token);
                Configuration = config.Build();
                StratusLive.PlatformCore.Logging.LoggerExtensions.CreateLogger(Configuration);
            })
                       .Build();

            // Uncomment this to seed upon startup, alternatively pass in `dotnet run /seed` to seed using CLI
            //await DbMigrationHelpers.EnsureSeedData<IdentityServerConfigurationDbContext, AdminIdentityDbContext, IdentityServerPersistedGrantDbContext, AdminLogDbContext, UserIdentity, UserIdentityRole>(host);
            if (seed)
            {
                await DbMigrationHelpers.EnsureSeedData <IdentityServerConfigurationDbContext, AdminIdentityDbContext, IdentityServerPersistedGrantDbContext, AdminLogDbContext, UserIdentity, UserIdentityRole>(host);
            }

            host.Run();
        }
        public static async Task Main(string[] args)
        {
            var seed = args.Any(x => x == SeedArgs);

            if (seed)
            {
                args = args.Except(new[] { SeedArgs }).ToArray();
            }

            var host = BuildWebHost(args);

            // Uncomment this to seed upon startup, alternatively pass in `dotnet run /seed` to seed using CLI
            seed = true;
            var seedMultiTenant = true;

            if (seed)
            {
                if (seedMultiTenant)
                {
                    await DbMigrationHelpers.EnsureSeedData <IdentityServerConfigurationDbContext, MultiTenantUserIdentityDbContext, IdentityServerPersistedGrantDbContext, AdminLogDbContext, MultiTenantUserIdentity, UserIdentityRole>(host);
                }
                else
                {
                    await DbMigrationHelpers.EnsureSeedData <IdentityServerConfigurationDbContext, AdminIdentityDbContext, IdentityServerPersistedGrantDbContext, AdminLogDbContext, UserIdentity, UserIdentityRole>(host);
                }
            }

            host.Run();
        }
Esempio n. 5
0
 public static async Task EnsureSeedDataAsync(IHost host)
 {
     await DbMigrationHelpers
     .EnsureSeedData <IdentityServerConfigurationDbContext, ApplicationIdentityDbContext,
                      IdentityServerPersistedGrantDbContext, AdminLogDbContext, AdminAuditLogDbContext,
                      ApplicationUser, ApplicationRole, int>(host);
 }
        public static void Main(string[] args)
        {
            var host = CreateWebHostBuilder(args).Build();

            Task.WaitAll(DbMigrationHelpers.EnsureSeedData(host));

            host.Run();
        }
Esempio n. 7
0
        private static async Task ApplyDbMigrationsWithDataSeedAsync(string[] args, IConfigurationRoot configuration, IHost host)
        {
            bool.TryParse(configuration.GetSection("SeedConfiguration:ApplySeed").Value, out var applySeed);
            bool.TryParse(configuration.GetSection("DatabaseMigrationsConfiguration:ApplyDatabaseMigrations").Value, out var applyDatabaseMigrations);

            await DbMigrationHelpers
            .ApplyDbMigrationsWithDataSeedAsync <CoreDbContext>(host, applySeed, applyDatabaseMigrations);
        }
Esempio n. 8
0
        public static async Task Main(string[] args)
        {
            var seed = Environment.GetEnvironmentVariable("IDENTITY_ADMIN_SEED");
            var host = BuildWebHost(args);

            if (seed != null)
            {
                await DbMigrationHelpers.EnsureSeedData <IdentityServerConfigurationDbContext, AdminIdentityDbContext, IdentityServerPersistedGrantDbContext, AdminLogDbContext, UserIdentity, UserIdentityRole>(host);
            }

            host.Run();
        }
Esempio n. 9
0
        public static async Task Main(string[] args)
        {
            var configuration = new ConfigurationBuilder()
                                .AddCommandLine(args)
                                .Build();

            var host = BuildWebHost(args, configuration);

            //NOTE: Uncomment the line below to use seed data
            await DbMigrationHelpers.EnsureSeedData(host, false);

            host.Run();
        }
Esempio n. 10
0
        public static async Task EnsureSeedData(IServiceProvider serviceProvider)
        {
            await DbMigrationHelpers.CheckDatabases(serviceProvider, new JpDatabaseOptions()
            {
                MustThrowExceptionIfDatabaseDontExist = true
            });

            using (var scope = serviceProvider.GetRequiredService <IServiceScopeFactory>().CreateScope())
            {
                var eventStoreDb = scope.ServiceProvider.GetRequiredService <EventStoreContext>();
                await DbMigrationHelpers.ConfigureEventStoreContext(eventStoreDb);
            }
        }
Esempio n. 11
0
        public static async Task Main(string[] args)
        {
            var seed = args.Any(x => x == SeedArgs);

            if (seed)
            {
                args = args.Except(new[] { SeedArgs }).ToArray();
            }

            var host = BuildWebHost(args);

            await DbMigrationHelpers.EnsureSeedData(host);

            host.Run();
        }
Esempio n. 12
0
        public static async Task Main(string[] args)
        {
            #region 确保发行版的工作目录正确

#if !DEBUG
            //通过特殊手段运行应用可能导致工作目录与程序文件所在目录不一致,需要调整,否则配置文件和其他数据无法加载(仅限发布模式,调试模式修改工作目录也可能导致配置和其他数据无法加载)
            var pathToExe         = Process.GetCurrentProcess().MainModule.FileName;
            var pathToContentRoot = Path.GetDirectoryName(pathToExe);
            Directory.SetCurrentDirectory(pathToContentRoot);
#endif

            #endregion

            Log.Logger = new LoggerConfiguration()
                         .ReadFrom.Configuration(Configuration)
                         .CreateLogger();

            try
            {
                var seed = args.Any(x => x == SeedArgs);
                if (seed)
                {
                    args = args.Except(new[] { SeedArgs }).ToArray();
                }

                var host = CreateHostBuilder(args).Build();

                // Uncomment this to seed upon startup, alternatively pass in `dotnet run /seed` to seed using CLI
                // await DbMigrationHelpers.EnsureSeedData<IdentityServerConfigurationDbContext, AdminIdentityDbContext, IdentityServerPersistedGrantDbContext, AdminLogDbContext, AdminAuditLogDbContext, UserIdentity, UserIdentityRole>(host);
                if (seed)
                {
                    await DbMigrationHelpers
                    .EnsureSeedData <IdentityServerConfigurationDbContext, ApplicationIdentityDbContext,
                                     IdentityServerPersistedGrantDbContext, AdminLogDbContext, AdminAuditLogDbContext,
                                     ApplicationUser, ApplicationRole, int>(host);
                }

                host.Run();
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Host terminated unexpectedly");
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
        public static async Task EnsureSeedData(IServiceProvider serviceProvider)
        {
            await DbMigrationHelpers.CheckDatabases(serviceProvider, new JpDatabaseOptions()
            {
                MustThrowExceptionIfDatabaseDontExist = true
            });

            using var scope = serviceProvider.GetRequiredService <IServiceScopeFactory>().CreateScope();

            var eventStoreDb = scope.ServiceProvider.GetRequiredService <EventStoreContext>();
            var storeDbExist = await DbHealthChecker.CheckTableExists <StoredEvent>(eventStoreDb);

            if (!storeDbExist)
            {
                await eventStoreDb.Database.MigrateAsync();
            }
        }
        public static async Task Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                         .ReadFrom.Configuration(Configuration)
                         .CreateLogger();

            try
            {
                var seed = args.Any(x => x == SeedArgs);
                if (seed)
                {
                    args = args.Except(new[] { SeedArgs }).ToArray();
                }

                var host = CreateHostBuilder(args).Build();

                // Uncomment this to seed upon startup, alternatively pass in `dotnet run /seed` to seed using CLI
                await DbMigrationHelpers.EnsureSeedData <IdentityServerConfigurationDbContext,
                                                         AdminIdentityDbContext,
                                                         IdentityServerPersistedGrantDbContext,
                                                         AdminLogDbContext,
                                                         AdminAuditLogDbContext,
                                                         UserIdentity,
                                                         UserIdentityRole>(host);

                //if (seed)
                //{
                //    await DbMigrationHelpers
                //        .EnsureSeedData<IdentityServerConfigurationDbContext, AdminIdentityDbContext,
                //            IdentityServerPersistedGrantDbContext, AdminLogDbContext, AdminAuditLogDbContext,
                //            UserIdentity, UserIdentityRole>(host);
                //}

                host.Run();
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Host terminated unexpectedly");
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
Esempio n. 15
0
        public static async Task <IWebHost> CreateWebHost(string[] args)
        {
            var             config   = new ConfigurationBuilder().AddCommandLine(args).Build();
            IWebHostBuilder builder  = WebHost.CreateDefaultBuilder(args).UseStartup <Startup>();
            string          seeddata = config["init"];
            string          port     = config["port"];

            if (!string.IsNullOrWhiteSpace(port))
            {
                builder.UseUrls($"http://*:{port}");
            }
            var host = builder.Build();

            if (seeddata == "initdatabase")
            {
                await DbMigrationHelpers.EnsureSeedData(host);
            }
            return(host);
        }
        private static async Task ApplyDbMigrationsWithDataSeedAsync(string[] args, IConfiguration configuration, IHost host)
        {
            var applyDbMigrationWithDataSeedFromProgramArguments = args.Any(x => x == SeedArgs);

            if (applyDbMigrationWithDataSeedFromProgramArguments)
            {
                args = args.Except(new[] { SeedArgs }).ToArray();
            }

            var seedConfiguration = configuration.GetSection(nameof(SeedConfiguration)).Get <SeedConfiguration>();
            var databaseMigrationsConfiguration = configuration.GetSection(nameof(DatabaseMigrationsConfiguration))
                                                  .Get <DatabaseMigrationsConfiguration>();

            await DbMigrationHelpers
            .ApplyDbMigrationsWithDataSeedAsync <IdentityServerConfigurationDbContext, AdminIdentityDbContext,
                                                 IdentityServerPersistedGrantDbContext, AdminLogDbContext, AdminAuditLogDbContext,
                                                 IdentityServerDataProtectionDbContext, UserIdentity, UserIdentityRole>(host,
                                                                                                                        applyDbMigrationWithDataSeedFromProgramArguments, seedConfiguration, databaseMigrationsConfiguration);
        }
Esempio n. 17
0
        public static async Task Main(string[] args)
        {
            var seed = args.Any(x => x == SeedArgs);

            if (seed)
            {
                args = args.Except(new[] { SeedArgs }).ToArray();
            }

            var host = BuildWebHost(args);

            // Uncomment this to seed upon startup, alternatively pass in `dotnet run /seed` to seed using CLI
            // await DbMigrationHelpers.EnsureSeedData(host);
            if (seed)
            {
                await DbMigrationHelpers.EnsureSeedData(host);
            }

            host.Run();
        }
Esempio n. 18
0
        public static async Task Main(string[] args)
        {
            args = new string[] { "/seed" };
            var seed = args.Any(x => x == SeedArgs);

            if (seed)
            {
                args = args.Except(new[] { SeedArgs }).ToArray();
            }

            var host = BuildWebHost(args);

            // Uncomment this to seed upon startup, alternatively pass in `dotnet run /seed` to seed using CLI
            // await DbMigrationHelpers.EnsureSeedData<IdentityServerConfigurationDbContext, AdminIdentityDbContext, IdentityServerPersistedGrantDbContext, AdminLogDbContext, UserProfile, ApplicationRole>(host);
            if (seed)
            {
                await DbMigrationHelpers.EnsureSeedData <IdentityServerConfigurationDbContext, MainContext, IdentityServerPersistedGrantDbContext, AdminLogDbContext, UserProfile, ApplicationRole>(host.Services);
            }

            host.Run();
        }
Esempio n. 19
0
        public static void Main(string[] args)
        {
            Console.Title = "JP Project - Server SSO";

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
                         .MinimumLevel.Override("System", LogEventLevel.Warning)
                         .MinimumLevel.Override("Microsoft.AspNetCore.Authentication", LogEventLevel.Information)
                         .Enrich.FromLogContext()
                         .WriteTo.ApplicationInsights(TelemetryConfiguration.Active, TelemetryConverter.Traces)
                         .WriteTo.File(@"jpProject_sso_log-.txt", rollingInterval: RollingInterval.Day, retainedFileCountLimit: 5)
                         .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level}] {SourceContext}{NewLine}{Message:lj}{NewLine}{Exception}{NewLine}", theme: AnsiConsoleTheme.Literate)
                         .CreateLogger();

            var host = CreateWebHostBuilder(args).Build();

            Task.WaitAll(DbMigrationHelpers.EnsureSeedData(host));

            host.Run();
        }
Esempio n. 20
0
        public static void Main(string[] args)
        {
            Console.Title = "JP Project - Server SSO";

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
                         .MinimumLevel.Override("System", LogEventLevel.Warning)
                         .MinimumLevel.Override("Microsoft.AspNetCore.Authentication", LogEventLevel.Information)
                         .Enrich.FromLogContext()
                         .WriteTo.ApplicationInsightsEvents(Environment.GetEnvironmentVariable("APPINSIGHTS_INSTRUMENTATIONKEY"))
                         .WriteTo.File(@"jpProject_sso_log.txt")
                         .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level}] {SourceContext}{NewLine}{Message:lj}{NewLine}{Exception}{NewLine}", theme: AnsiConsoleTheme.Literate)
                         .CreateLogger();

            var host = CreateWebHostBuilder(args).Build();

            // Uncomment this to seed upon startup, alternatively pass in `dotnet run / seed` to seed using CLI
            Task.WaitAll(DbMigrationHelpers.EnsureSeedData(host));

            host.Run();
        }
Esempio n. 21
0
        public static async Task Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                         .ReadFrom.Configuration(Configuration)
                         .CreateLogger();
            try
            {
                var host = CreateHostBuilder(args).Build();
                await DbMigrationHelpers
                .EnsureSeedData <IdentityServerConfigurationDbContext, AdminIdentityDbContext,
                                 IdentityServerPersistedGrantDbContext, AdminLogDbContext, AdminAuditLogDbContext,
                                 UserIdentity, UserIdentityRole>(host);

                host.Run();
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Host terminated unexpectedly");
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
Esempio n. 22
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

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

            //services.AddWebApi(options =>
            //{
            //    options.OutputFormatters.Remove(new XmlDataContractSerializerOutputFormatter());
            //    options.UseCentralRoutePrefix(new RouteAttribute("api/v1"));
            //});
            services.AddMvc(options =>
            {
                options.OutputFormatters.Remove(new XmlDataContractSerializerOutputFormatter());
                options.UseCentralRoutePrefix(new RouteAttribute("api/v1"));
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddAutoMapperSetup();

            services
            .AddFluentSpotifyClient(clientBuilder => clientBuilder
                                    .ConfigurePipeline(pipeline => pipeline
                                                       .AddAspNetCoreAuthorizationCodeFlow(
                                                           spotifyAuthenticationScheme: SpotifyAuthenticationScheme)));
            services
            .AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(
                o =>
            {
                o.LoginPath  = new PathString("/login");
                o.LogoutPath = new PathString("/logout");
            })
            .AddSpotify(
                SpotifyAuthenticationScheme,
                o =>
            {
                o.ClientId     = Configuration.GetSection("SpotifyApi:ClientId").Value;
                o.ClientSecret = Configuration.GetSection("SpotifyApi:ClientSecret").Value;
                o.Scope.Add("playlist-read-private");
                o.Scope.Add("playlist-read-collaborative");
                o.SaveTokens = true;
            });
            services.AddAuthorization(options =>
            {
                options.AddPolicy("CanWriteSalesData", policy => policy.Requirements.Add(new ClaimRequirement("Sales", "Write")));
                options.AddPolicy("CanRemoveSalesData", policy => policy.Requirements.Add(new ClaimRequirement("Sales", "Remove")));
            });

            services.AddSwaggerGen(s =>
            {
                s.SwaggerDoc("v1", new Info
                {
                    Version     = "v1",
                    Title       = "BeBlue Project",
                    Description = "BeBlueAPI Swagger surface"
                });
            });

            // Adding MediatR for Domain Events and Notifications
            services.AddMediatR(typeof(Startup));

            // .NET Native DI Abstraction
            RegisterServices(services);

            //Console.WriteLine("******* SEED EXECUTANDO !!! ****************");
            DbMigrationHelpers.EnsureSeedData(services.BuildServiceProvider()).GetAwaiter().GetResult();
            //Console.WriteLine("******* SEED FINALIZADO !!! ****************");
        }