|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Data; |
| 4 | +using System.Data.SqlClient; |
| 5 | +using System.Linq; |
| 6 | +using System.Reflection; |
| 7 | +using System.Resources; |
| 8 | +using System.Text; |
| 9 | +using System.Threading.Tasks; |
| 10 | +using log4net; |
| 11 | +using Microsoft.AspNet.Identity; |
| 12 | +using Microsoft.AspNet.Identity.EntityFramework; |
| 13 | + |
| 14 | +namespace AlwaysEncryptedSample.Models |
| 15 | +{ |
| 16 | + public static class DbInit |
| 17 | + { |
| 18 | + private static ILog log = LogManager.GetLogger(typeof(DbInit)); |
| 19 | + |
| 20 | + /// <summary> |
| 21 | + /// Create the Authentication <see cref="System.Data.Entity.DbContext"/> if it does not exist. |
| 22 | + /// </summary> |
| 23 | + /// <param name="log"></param> |
| 24 | + public static void CreateAuthContext(string nameOrConnectionString = "DefaultConnection") |
| 25 | + { |
| 26 | + using (var authDbCtx = AuthDbContext.Create(nameOrConnectionString)) |
| 27 | + { |
| 28 | + authDbCtx.Database.Log = (dbLog => log.Debug(dbLog)); |
| 29 | + log.Info("Initialization tests for Authorization Schema"); |
| 30 | + if (!authDbCtx.Roles.Any()) |
| 31 | + { |
| 32 | + log.Info("No roles found in database. Creating roles"); |
| 33 | + var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(authDbCtx)); |
| 34 | + roleManager.Create(new IdentityRole("DBAs")); // Gives database internals access |
| 35 | + roleManager.Create(new IdentityRole("Credit Card Admins")); // Gives access to CC info |
| 36 | + } |
| 37 | + |
| 38 | + if (!authDbCtx.Users.Any()) |
| 39 | + { |
| 40 | + log.Info("No users found in database. Creating users"); |
| 41 | + var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(authDbCtx)); |
| 42 | + userManager.Create(new ApplicationUser |
| 43 | + { |
| 44 | + Id = "Administrator", |
| 45 | + |
| 46 | + UserName = "Administrator", |
| 47 | + EmailConfirmed = true, |
| 48 | + PasswordHash = userManager.PasswordHasher.HashPassword("Alm0nds!"), |
| 49 | + }); |
| 50 | + |
| 51 | + userManager.AddToRole("Administrator", "DBAs"); |
| 52 | + |
| 53 | + userManager.Create(new ApplicationUser |
| 54 | + { |
| 55 | + |
| 56 | + Id = "CCAdmin", |
| 57 | + UserName = "CCAdmin", |
| 58 | + EmailConfirmed = true, |
| 59 | + PasswordHash = userManager.PasswordHasher.HashPassword("Appl3s") |
| 60 | + }); |
| 61 | + userManager.AddToRole("CCAdmin", "Credit Card Admins"); |
| 62 | + } |
| 63 | + |
| 64 | + authDbCtx.SaveChanges(); |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + /// <summary> |
| 69 | + /// Create the Purchasing <see cref="System.Data.Entity.DbContext"/> if it does not exist. |
| 70 | + /// </summary> |
| 71 | + /// <param name="log"></param> |
| 72 | + public static void CreatePurchasingContext(string nameOrConnectionString = "DefaultConnection") |
| 73 | + { |
| 74 | + using (var context = ApplicationDbContext.Create(nameOrConnectionString)) |
| 75 | + { |
| 76 | + // TODO: Perhaps rethink doing this. |
| 77 | + // TODO: Consider using DatabaseLogFormatter to better format the logging. |
| 78 | + context.Database.Log = (dbLog => log.Debug(dbLog)); |
| 79 | + log.Info("Initialization tests for Application Schema"); |
| 80 | + //TODO: Could probably be sped up, but its O(n^2) where n = 4 |
| 81 | + foreach (var newCCN in CreditCardNetwork.GetNetworks()) |
| 82 | + { |
| 83 | + if (!context.CreditCardNetworks.Any(ccn => ccn.Id == newCCN.Id)) |
| 84 | + { |
| 85 | + context.CreditCardNetworks.Add(newCCN); |
| 86 | + } |
| 87 | + } |
| 88 | + context.SaveChanges(); |
| 89 | + } |
| 90 | + } |
| 91 | + |
| 92 | + /// <summary> |
| 93 | + /// Creates a database if it doesn't exist. |
| 94 | + /// </summary> |
| 95 | + /// <param name="builder">Connection string builder to the database we want to create.</param> |
| 96 | + /// <returns> |
| 97 | + /// <c>true</c> if the database existed or we were able to create it, <c>false</c> if we could not try |
| 98 | + /// </returns> |
| 99 | + /// <remarks> |
| 100 | + /// |
| 101 | + /// </remarks> |
| 102 | + public static bool CreateDatabase(SqlConnectionStringBuilder builder) |
| 103 | + { |
| 104 | + var dbName = builder.InitialCatalog; |
| 105 | + |
| 106 | + // Can't connect to a db that doesn't already exist. |
| 107 | + builder.InitialCatalog = "tempdb"; |
| 108 | + using (var cn = new SqlConnection(builder.ConnectionString)) |
| 109 | + using (var cmd = cn.CreateCommand()) |
| 110 | + { |
| 111 | + cmd.CommandText = |
| 112 | + "IF DB_ID(@dbName) IS NULL " + |
| 113 | + "EXEC ('CREATE DATABASE ' + @dbName + '; " + |
| 114 | + "ALTER DATABASE ' + @dbName + ' SET RECOVERY SIMPLE;')"; |
| 115 | + cmd.Parameters.AddWithValue("@dbName", dbName); |
| 116 | + try |
| 117 | + { |
| 118 | + cn.Open(); |
| 119 | + cmd.ExecuteNonQuery(); |
| 120 | + } |
| 121 | + catch (SqlException) |
| 122 | + { |
| 123 | + //TODO: Send this exception somewhere. |
| 124 | + return false; |
| 125 | + } |
| 126 | + } |
| 127 | + return true; |
| 128 | + } |
| 129 | + |
| 130 | + public static void InitLog4NetDb(IDbConnection cn) |
| 131 | + { |
| 132 | + //TODO: Make the database if it doesn't exist. |
| 133 | + var rm = new ResourceManager |
| 134 | + ("AlwaysEncryptedSample.Models.Properties.Resources", Assembly.GetExecutingAssembly()); |
| 135 | + var sql = rm.GetString("Log4NetDDL"); |
| 136 | + using (var cmd = cn.CreateCommand()) |
| 137 | + { |
| 138 | + /* |
| 139 | + * EF Code first does a good job of autocreating the database if it doesn't |
| 140 | + * exist. However, since we want log4net to log EF activity to the database |
| 141 | + * we have a chicken or egg problem. |
| 142 | + */ |
| 143 | + |
| 144 | + cn.Open(); |
| 145 | + /* |
| 146 | + * ADO.NET doesn't parse batches (read support the GO statement). |
| 147 | + * Because CREATE SCHEMA is extra picky we need this. |
| 148 | + */ |
| 149 | + cmd.CommandText = "SELECT COUNT(*) FROM sys.schemas WHERE name = 'Logging';"; |
| 150 | + if ((int)cmd.ExecuteScalar() == 0) |
| 151 | + { |
| 152 | + cmd.CommandText = "CREATE SCHEMA [Logging]"; |
| 153 | + cmd.ExecuteNonQuery(); |
| 154 | + } |
| 155 | + cmd.CommandText = sql; |
| 156 | + cmd.ExecuteNonQuery(); |
| 157 | + cn.Close(); |
| 158 | + } |
| 159 | + } |
| 160 | + } |
| 161 | +} |
0 commit comments