public void testInsert() { using (CodeITDbContext ctx = new CodeITDbContext(1)) { for (int i = 1; i <= 10; i++) { Customer newCustomer = new Customer() { Id = Guid.NewGuid(), Name = string.Format("Customer{0}", i) }; ctx.Customers.Add(newCustomer); } ctx.SaveChanges(); } }
private void UpdateLicenseToDb(string licenseKey) { try { using (CodeITDL.CodeITDbContext ctx = new CodeITDL.CodeITDbContext()) { // Insert customer Guid customerId = new Guid(txtClientId.Text); Customer customer = new Customer(); customer.Id = customerId; customer.Name = txtAdminName.Text; if (ctx.Customers.FirstOrDefault(c => c.Id == customer.Id && c.Name == customer.Name) == null) { ctx.Customers.Add(customer); ctx.SaveChanges(); } else { MessageBox.Show("Failed to create license!", "License failed", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } // Insert user User currentUser = new User(); currentUser.FirstName = txtAdminName.Text; currentUser.UserName = txtAdminUsername.Text; currentUser.Password = txtAdminPassword.Text; currentUser.CreatedOn = DateTime.Now; currentUser.ModifiedOn = DateTime.Now; currentUser.CreatedBy = 1; currentUser.ModifiedBy = 1; Int32 newUserId = -1; if (ctx.Users.FirstOrDefault(u => u.UserName == currentUser.UserName && u.Password == currentUser.Password) == null) { ctx.Users.Add(currentUser); ctx.SaveChanges(); } else { MessageBox.Show("User already exist in the database, license creation failed!", "License failed", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } // Insert License if (ctx.Users.FirstOrDefault(u => u.UserName == currentUser.UserName && u.Password == currentUser.Password) != null) { newUserId = ctx.Users.FirstOrDefault(u => u.UserName == currentUser.UserName && u.Password == currentUser.Password).Id; } if (newUserId != -1) { CodeITDL.License license = new CodeITDL.License(); license.CustomerId = customerId; license.LicenseBytes = Encoding.UTF8.GetBytes(licenseKey); ctx.SaveChanges(); } Int32 licenseId = -1; if (ctx.Licenses.FirstOrDefault(l => l.CustomerId == customerId) != null) { licenseId = ctx.Licenses.FirstOrDefault(l => l.CustomerId == customerId).Id; } // Inser UserLicense if (licenseId != -1) { UserLicense userLicense = new UserLicense(); userLicense.LicenseId = licenseId; userLicense.UserId = newUserId; ctx.SaveChanges(); } else { MessageBox.Show("Failed to create license!", "License failed", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } ctx.SaveChanges(); } } catch (Exception ex) { MessageBox.Show("Failed to create license!", "License failed", MessageBoxButtons.OK, MessageBoxIcon.Warning); } }