|
| 1 | +using Bulky.Model.Models; |
| 2 | +using Bulky.Utility; |
| 3 | +using BulkyWeb.Data; |
| 4 | +using Microsoft.AspNetCore.Identity; |
| 5 | +using Microsoft.EntityFrameworkCore; |
| 6 | +using System; |
| 7 | +using System.Collections.Generic; |
| 8 | +using System.Linq; |
| 9 | +using System.Security.Cryptography.Pkcs; |
| 10 | +using System.Text; |
| 11 | +using System.Threading.Tasks; |
| 12 | + |
| 13 | +namespace Bulky.DataAccess.DbInitialize |
| 14 | +{ |
| 15 | + public class DBInitializer : IDbinitializer |
| 16 | + { |
| 17 | + private readonly ApplicationDbContext _db; |
| 18 | + private readonly RoleManager<IdentityRole> _roleManager; |
| 19 | + private readonly UserManager<IdentityUser> _userManager; |
| 20 | + |
| 21 | + public DBInitializer(ApplicationDbContext db, RoleManager<IdentityRole> roleManager, UserManager<IdentityUser> userManager) |
| 22 | + { |
| 23 | + _db = db; |
| 24 | + _roleManager = roleManager; |
| 25 | + _userManager = userManager; |
| 26 | + } |
| 27 | + |
| 28 | + public void Initialize() |
| 29 | + { |
| 30 | + //Add Migration if panding |
| 31 | + try |
| 32 | + { |
| 33 | + if(_db.Database.GetPendingMigrations().Count() > 0) { |
| 34 | + _db.Database.Migrate(); |
| 35 | + } |
| 36 | + }catch(Exception ex) |
| 37 | + { |
| 38 | + throw new Exception(ex.ToString()); |
| 39 | + } |
| 40 | + |
| 41 | + //Create role of not exist |
| 42 | + if (!_roleManager.RoleExistsAsync(SD.Role_Customer).GetAwaiter().GetResult()) |
| 43 | + { |
| 44 | + _roleManager.CreateAsync(new IdentityRole(SD.Role_Customer)).GetAwaiter().GetResult(); |
| 45 | + _roleManager.CreateAsync(new IdentityRole(SD.Role_Admin)).GetAwaiter().GetResult(); |
| 46 | + _roleManager.CreateAsync(new IdentityRole(SD.Role_Employee)).GetAwaiter().GetResult(); |
| 47 | + _roleManager.CreateAsync(new IdentityRole(SD.Role_Company)).GetAwaiter().GetResult(); |
| 48 | + |
| 49 | + |
| 50 | + //Create Admin User |
| 51 | + _userManager.CreateAsync(new ApplicationUser |
| 52 | + { |
| 53 | + UserName = "Admin@gmail.com", |
| 54 | + Email = "Admin@gmail.com", |
| 55 | + Name = "Dhyan Moradiya", |
| 56 | + PhoneNumber = "1234567890", |
| 57 | + StreetAddress = "My address", |
| 58 | + State = "GJ", |
| 59 | + PostalCode = "1234567890", |
| 60 | + City = "ABC", |
| 61 | + |
| 62 | + }, "Test@123").GetAwaiter().GetResult(); |
| 63 | + |
| 64 | + ApplicationUser user = _db.ApplicationUsers.FirstOrDefault(u => u.Email == "Admin@gmail.com"); |
| 65 | + _userManager.AddToRoleAsync(user, SD.Role_Admin).GetAwaiter().GetResult(); |
| 66 | + } |
| 67 | + |
| 68 | + } |
| 69 | + } |
| 70 | +} |
0 commit comments