hanyadikhetvan-dotnethf/HanyadikHetVan/Program.cs

72 lines
2.6 KiB
C#
Raw Normal View History

2021-05-03 01:30:06 +02:00
using HanyadikHetVan.Data;
2021-05-19 17:56:56 +02:00
using HanyadikHetVan.Data.Entities;
2021-05-03 01:30:06 +02:00
using Microsoft.AspNetCore.Hosting;
2021-05-19 17:56:56 +02:00
using Microsoft.AspNetCore.Identity;
2021-05-03 01:30:06 +02:00
using Microsoft.EntityFrameworkCore;
2021-05-19 17:56:56 +02:00
using Microsoft.Extensions.Configuration;
2021-05-03 01:30:06 +02:00
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
2021-05-19 17:56:56 +02:00
using System;
2021-05-03 01:30:06 +02:00
using System.Threading.Tasks;
namespace HanyadikHetVan
{
public class Program
{
public static async Task Main(string[] args)
{
var host = CreateHostBuilder(args).Build();
using (var scope = host.Services.CreateScope())
{
var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
await context.Database.MigrateAsync();
2021-05-19 17:56:56 +02:00
var roleMgr = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<User>>();
var configuration = scope.ServiceProvider.GetRequiredService<IConfiguration>();
var adminRole = new IdentityRole("admin");
if (!await context.Roles.AnyAsync())
{
await roleMgr.CreateAsync(adminRole);
}
if (!await userManager.Users.AnyAsync())
{
var defaultAdmin = new User
{
UserName = configuration.GetValue<string>("DefaultAdministrator:UserName"),
Email = configuration.GetValue<string>("DefaultAdministrator:Email"),
EmailConfirmed = true,
};
var result = await userManager.CreateAsync(defaultAdmin,
configuration.GetValue<string>("DefaultAdministrator:Password"));
if (!result.Succeeded)
{
throw new Exception("Failed to create the default user.");
}
else
{
var roleResult = await userManager.AddToRoleAsync(defaultAdmin, "admin");
if (!roleResult.Succeeded)
{
throw new Exception("Failed to create the default user.");
}
}
}
2021-05-03 01:30:06 +02:00
}
2021-05-19 17:56:56 +02:00
2021-05-03 01:30:06 +02:00
await host.RunAsync();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}