Skip to content

Commit

Permalink
Section 13 - Implement DbInitializer
Browse files Browse the repository at this point in the history
  • Loading branch information
bhrugen committed Sep 28, 2021
1 parent 1e191fb commit 6c40eae
Show file tree
Hide file tree
Showing 4 changed files with 72 additions and 11 deletions.
1 change: 1 addition & 0 deletions BulkyBook.DataAccess/BulkyBook.DataAccess.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

<ItemGroup>
<ProjectReference Include="..\BulkyBook.Models\BulkyBook.Models.csproj" />
<ProjectReference Include="..\BulkyBook.Utility\BulkyBook.Utility.csproj" />
</ItemGroup>

</Project>
60 changes: 57 additions & 3 deletions BulkyBook.DataAccess/DbInitializer/DbInitializer.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
using System;
using BulkyBook.Models;
using BulkyBook.Utility;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
Expand All @@ -8,14 +12,64 @@ namespace BulkyBook.DataAccess.DbInitializer
{
public class DbInitializer : IDbInitializer
{
private readonly UserManager<IdentityUser> _userManager;
private readonly RoleManager<IdentityRole> _roleManager;
private readonly ApplicationDbContext _db;

public DbInitializer(
UserManager<IdentityUser> userManager,
RoleManager<IdentityRole> roleManager,
ApplicationDbContext db)
{
_roleManager = roleManager;
_userManager = userManager;
_db = db;
}


public void Initialize()
{
//migrations if they are not applied
try
{
if (_db.Database.GetPendingMigrations().Count() > 0)
{
_db.Database.Migrate();
}
}
catch (Exception ex)
{

}

//create roles if they are not created
if (!_roleManager.RoleExistsAsync(SD.Role_Admin).GetAwaiter().GetResult())
{
_roleManager.CreateAsync(new IdentityRole(SD.Role_Admin)).GetAwaiter().GetResult();
_roleManager.CreateAsync(new IdentityRole(SD.Role_Employee)).GetAwaiter().GetResult();
_roleManager.CreateAsync(new IdentityRole(SD.Role_User_Indi)).GetAwaiter().GetResult();
_roleManager.CreateAsync(new IdentityRole(SD.Role_User_Comp)).GetAwaiter().GetResult();

//if roles are not created, then we will create admin user as well

_userManager.CreateAsync(new ApplicationUser
{
UserName = "[email protected]",
Email = "[email protected]",
Name = "Bhrugen Patel",
PhoneNumber = "1112223333",
StreetAddress = "test 123 Ave",
State = "IL",
PostalCode = "23422",
City = "Chicago"
}, "Admin123*").GetAwaiter().GetResult();

ApplicationUser user = _db.ApplicationUsers.FirstOrDefault(u => u.Email == "[email protected]");

_userManager.AddToRoleAsync(user, SD.Role_Admin).GetAwaiter().GetResult();

//if roles are not created, then we will create admin user as well

}
return;
}
}
}
8 changes: 1 addition & 7 deletions BulkyBookWeb/Areas/Identity/Pages/Account/Register.cshtml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -125,13 +125,7 @@ public class InputModel

public async Task OnGetAsync(string returnUrl = null)
{
//if (!_roleManager.RoleExistsAsync(SD.Role_Admin).GetAwaiter().GetResult())
//{
// _roleManager.CreateAsync(new IdentityRole(SD.Role_Admin)).GetAwaiter().GetResult();
// _roleManager.CreateAsync(new IdentityRole(SD.Role_Employee)).GetAwaiter().GetResult();
// _roleManager.CreateAsync(new IdentityRole(SD.Role_User_Indi)).GetAwaiter().GetResult();
// _roleManager.CreateAsync(new IdentityRole(SD.Role_User_Comp)).GetAwaiter().GetResult();
//}

ReturnUrl = returnUrl;
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
Input = new InputModel()
Expand Down
14 changes: 13 additions & 1 deletion BulkyBookWeb/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
using BulkyBook.Utility;
using Stripe;
using System;
using BulkyBook.DataAccess.DbInitializer;

var builder = WebApplication.CreateBuilder(args);

Expand All @@ -24,6 +25,7 @@
builder.Services.AddIdentity<IdentityUser,IdentityRole>().AddDefaultTokenProviders()
.AddEntityFrameworkStores<ApplicationDbContext>();
builder.Services.AddScoped<IUnitOfWork, UnitOfWork>();
builder.Services.AddScoped<IDbInitializer, DbInitializer>();
builder.Services.AddSingleton<IEmailSender, EmailSender>();
builder.Services.AddRazorPages().AddRazorRuntimeCompilation();
builder.Services.AddAuthentication().AddFacebook(options =>
Expand Down Expand Up @@ -64,7 +66,7 @@
app.UseRouting();

StripeConfiguration.ApiKey = builder.Configuration.GetSection("Stripe:SecretKey").Get<string>();

SeedDatabase();
app.UseAuthentication();

app.UseAuthorization();
Expand All @@ -75,3 +77,13 @@
pattern: "{area=Customer}/{controller=Home}/{action=Index}/{id?}");

app.Run();


void SeedDatabase()
{
using (var scope = app.Services.CreateScope())
{
var dbInitializer = scope.ServiceProvider.GetRequiredService<IDbInitializer>();
dbInitializer.Initialize();
}
}

0 comments on commit 6c40eae

Please sign in to comment.