DatabaseInitializer.cs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. // ======================================
  2. // Author: Ebenezer Monney
  3. // Email: info@ebenmonney.com
  4. // Copyright (c) 2017 www.ebenmonney.com
  5. //
  6. // ==> Gun4Hire: contact@ebenmonney.com
  7. // ======================================
  8. using DAL.Models;
  9. using Microsoft.AspNetCore.Identity;
  10. using Microsoft.EntityFrameworkCore;
  11. using Microsoft.Extensions.Logging;
  12. using System;
  13. using System.Collections.Generic;
  14. using System.Linq;
  15. using System.Text;
  16. using System.Threading.Tasks;
  17. using DAL.Core;
  18. using DAL.Core.Interfaces;
  19. namespace DAL
  20. {
  21. public interface IDatabaseInitializer
  22. {
  23. Task SeedAsync();
  24. }
  25. public class DatabaseInitializer : IDatabaseInitializer
  26. {
  27. private readonly ApplicationDbContext _context;
  28. private readonly IAccountManager _accountManager;
  29. private readonly ILogger _logger;
  30. public DatabaseInitializer(ApplicationDbContext context, IAccountManager accountManager, ILogger<DatabaseInitializer> logger)
  31. {
  32. _accountManager = accountManager;
  33. _context = context;
  34. _logger = logger;
  35. }
  36. public async Task SeedAsync()
  37. {
  38. await _context.Database.MigrateAsync().ConfigureAwait(false);
  39. if (!await _context.Users.AnyAsync())
  40. {
  41. const string adminRoleName = "administrator";
  42. const string userRoleName = "user";
  43. await ensureRoleAsync(adminRoleName, "Default administrator", ApplicationPermissions.GetAllPermissionValues());
  44. await ensureRoleAsync(userRoleName, "Default user", new string[] { });
  45. await createUserAsync("admin", "tempP@ss123", "Inbuilt Administrator", "admin@ebenmonney.com", "+1 (123) 000-0000", new string[] { adminRoleName });
  46. await createUserAsync("user", "tempP@ss123", "Inbuilt Standard User", "user@ebenmonney.com", "+1 (123) 000-0001", new string[] { userRoleName });
  47. }
  48. if (!await _context.Customers.AnyAsync() && !await _context.ProductCategories.AnyAsync())
  49. {
  50. Customer cust_1 = new Customer
  51. {
  52. Name = "Ebenezer Monney",
  53. Email = "contact@ebenmonney.com",
  54. Gender = Gender.Male,
  55. DateCreated = DateTime.UtcNow,
  56. DateModified = DateTime.UtcNow
  57. };
  58. Customer cust_2 = new Customer
  59. {
  60. Name = "Itachi Uchiha",
  61. Email = "uchiha@narutoverse.com",
  62. PhoneNumber = "+81123456789",
  63. Address = "Some fictional Address, Street 123, Konoha",
  64. City = "Konoha",
  65. Gender = Gender.Male,
  66. DateCreated = DateTime.UtcNow,
  67. DateModified = DateTime.UtcNow
  68. };
  69. Customer cust_3 = new Customer
  70. {
  71. Name = "John Doe",
  72. Email = "johndoe@anonymous.com",
  73. PhoneNumber = "+18585858",
  74. Address = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio.
  75. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet",
  76. City = "Lorem Ipsum",
  77. Gender = Gender.Male,
  78. DateCreated = DateTime.UtcNow,
  79. DateModified = DateTime.UtcNow
  80. };
  81. Customer cust_4 = new Customer
  82. {
  83. Name = "Jane Doe",
  84. Email = "Janedoe@anonymous.com",
  85. PhoneNumber = "+18585858",
  86. Address = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio.
  87. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet",
  88. City = "Lorem Ipsum",
  89. Gender = Gender.Male,
  90. DateCreated = DateTime.UtcNow,
  91. DateModified = DateTime.UtcNow
  92. };
  93. ProductCategory prodCat_1 = new ProductCategory
  94. {
  95. Name = "None",
  96. Description = "Default category. Products that have not been assigned a category",
  97. DateCreated = DateTime.UtcNow,
  98. DateModified = DateTime.UtcNow
  99. };
  100. Product prod_1 = new Product
  101. {
  102. Name = "BMW M6",
  103. Description = "Yet another masterpiece from the world's best car manufacturer",
  104. BuyingPrice = 109775,
  105. SellingPrice = 114234,
  106. UnitsInStock = 12,
  107. IsActive = true,
  108. ProductCategory = prodCat_1,
  109. DateCreated = DateTime.UtcNow,
  110. DateModified = DateTime.UtcNow
  111. };
  112. Product prod_2 = new Product
  113. {
  114. Name = "Nissan Patrol",
  115. Description = "A true man's choice",
  116. BuyingPrice = 78990,
  117. SellingPrice = 86990,
  118. UnitsInStock = 4,
  119. IsActive = true,
  120. ProductCategory = prodCat_1,
  121. DateCreated = DateTime.UtcNow,
  122. DateModified = DateTime.UtcNow
  123. };
  124. Order ordr_1 = new Order
  125. {
  126. Discount = 500,
  127. Cashier = await _context.Users.FirstAsync(),
  128. Customer = cust_1,
  129. DateCreated = DateTime.UtcNow,
  130. DateModified = DateTime.UtcNow,
  131. OrderDetails = new List<OrderDetail>()
  132. {
  133. new OrderDetail() {UnitPrice = prod_1.SellingPrice, Quantity=1, Product = prod_1 },
  134. new OrderDetail() {UnitPrice = prod_2.SellingPrice, Quantity=1, Product = prod_2 },
  135. }
  136. };
  137. Order ordr_2 = new Order
  138. {
  139. Cashier = await _context.Users.FirstAsync(),
  140. Customer = cust_2,
  141. DateCreated = DateTime.UtcNow,
  142. DateModified = DateTime.UtcNow,
  143. OrderDetails = new List<OrderDetail>()
  144. {
  145. new OrderDetail() {UnitPrice = prod_2.SellingPrice, Quantity=1, Product = prod_2 },
  146. }
  147. };
  148. _context.Customers.Add(cust_1);
  149. _context.Customers.Add(cust_2);
  150. _context.Customers.Add(cust_3);
  151. _context.Customers.Add(cust_4);
  152. _context.Products.Add(prod_1);
  153. _context.Products.Add(prod_2);
  154. _context.Orders.Add(ordr_1);
  155. _context.Orders.Add(ordr_2);
  156. await _context.SaveChangesAsync();
  157. }
  158. }
  159. private async Task ensureRoleAsync(string roleName, string description, string[] claims)
  160. {
  161. if ((await _accountManager.GetRoleByNameAsync(roleName)) == null)
  162. {
  163. ApplicationRole applicationRole = new ApplicationRole(roleName, description);
  164. var result = await this._accountManager.CreateRoleAsync(applicationRole, claims);
  165. if (!result.Item1)
  166. throw new Exception($"Seeding \"{description}\" role failed. Errors: {string.Join(Environment.NewLine, result.Item2)}");
  167. }
  168. }
  169. private async Task<ApplicationUser> createUserAsync(string userName, string password, string fullName, string email, string phoneNumber, string[] roles)
  170. {
  171. ApplicationUser applicationUser = new ApplicationUser
  172. {
  173. UserName = userName,
  174. FullName = fullName,
  175. Email = email,
  176. PhoneNumber = phoneNumber,
  177. EmailConfirmed = true,
  178. IsEnabled = true
  179. };
  180. var result = await _accountManager.CreateUserAsync(applicationUser, roles, password);
  181. if (!result.Item1)
  182. throw new Exception($"Seeding \"{userName}\" user failed. Errors: {string.Join(Environment.NewLine, result.Item2)}");
  183. return applicationUser;
  184. }
  185. }
  186. }