public static bool SignOut(string token, out Exception exception) { var result = false; exception = null; try { using (var context = new ContextMaster()) { var session = context.Sessions.SingleOrDefault(s => s.Token == token); if (session == null) { throw (new TokenInvalidException()); } session.DateTimeExpiration = DateTime.UtcNow.Subtract(TimeSpan.FromSeconds(1)); context.SaveChanges(); result = true; } } catch (Exception e) { exception = e; } return(result); }
//public static bool UpdateUser(MasterUserSession masterUserSession, MasterUser masteruser, out Exception exception) //{ // bool result = false; // exception = null; // try // { // using (var context = new ContextMaster()) // { // context.Users.Attach(masteruser); // context.Entry(masteruser).State = System.Data.Entity.EntityState.Modified; // context.SaveChanges(); // context.Dispose(); // result = true; // } // } // catch (Exception ex) { // exception = ex; // } // return (result); //} public static bool AddUser(MasterUserSession masterUserSession, MasterUser masteruser, out Exception exception) { bool result = false; exception = null; try { using (var context = new ContextMaster()) { if (masteruser.DateTimeCreated != null) { masteruser.DateTimeCreated = DateTime.UtcNow; } context.Users.Add(masteruser); context.SaveChanges(); context.Dispose(); result = true; } } catch (Exception ex) { exception = ex; } return(result); }
public static bool UpdateUserRoles(MasterUserSession masterUserSession, long userid, List <MasterRoleType> roletypes, out Exception exception) { bool result = false; exception = null; try { var context = new ContextMaster(); List <MasterUserRole> userroles = context.UserRoles.Where(item => item.UserId == userid).ToList();//context.UserRoles.Where(item=>item.UserId==((long)Convert.ToInt16(roletypes.Any()))).ToList(); foreach (var item in userroles) { //context.UserRoles.Remove(item); context.Entry(item).State = System.Data.Entity.EntityState.Deleted; context.SaveChanges(); } context.Dispose(); context = new ContextMaster(); foreach (var item in roletypes) { MasterUserRole userrole = new MasterUserRole(); userrole.UserId = userid; userrole.RoleId = Convert.ToInt16(item); context.UserRoles.Add(userrole); context.SaveChanges(); } context.Dispose(); result = true; } catch (Exception ex) { exception = ex; } return(result); }
//TOBE DELETED public static void GetAllUsers() { using (var context = new ContextMaster()) { var user = context.Users.First(); user.Email = user.Email + " LOL"; context.SaveChanges(); //return context.Users.First().Email; } }
public static bool CreateSubscription(MasterUserSession MasterUserSession, Subscription subscription, out Subscription outsubscription, out Exception exception) { var result = false; //tenant = null; outsubscription = null; exception = null; try { using (var context = new ContextMaster()) { using (var transaction = context.Database.BeginTransaction()) { try { outsubscription = context.Subscriptions.Add(subscription); context.SaveChanges(); subscription.MasterSubscriptionId = subscription.Id; context.SaveChanges(); transaction.Commit(); result = true; } catch (Exception e) { exception = e; transaction.Rollback(); } } } } catch (Exception e) { exception = e; } return(result); }
public static bool UpdateTenantSubscription(MasterUserSession MasterUserSession, TenantSubscription tenantsubscription, out TenantSubscription outtenantsubscription, out Exception exception) { var result = false; outtenantsubscription = null; exception = null; try { using (var context = new ContextMaster()) { var temp = new TenantSubscription(); temp = context.TenantSubscriptions.FirstOrDefault(t => t.Id == tenantsubscription.Id); temp.IsDemo = tenantsubscription.IsDemo; temp.IsActive = tenantsubscription.IsActive; temp.DateTimeStart = tenantsubscription.DateTimeStart; temp.DateTimeExpires = tenantsubscription.DateTimeExpires; temp.NumberOfFormsAllowed = tenantsubscription.NumberOfFormsAllowed; temp.NumberOfUsersAllowed = tenantsubscription.NumberOfUsersAllowed; temp.NumberOfPagesAllowed = tenantsubscription.NumberOfPagesAllowed; temp.NumberOfTemplatesAllowed = tenantsubscription.NumberOfTemplatesAllowed; temp.NumberOfFormsUsed = tenantsubscription.NumberOfFormsUsed; temp.NumberOfPagesUsed = tenantsubscription.NumberOfPagesUsed; temp.NumberOfUsersUsed = tenantsubscription.NumberOfUsersUsed; temp.NumberOfTemplatesUsed = tenantsubscription.NumberOfTemplatesUsed; temp.AllowScanning = tenantsubscription.AllowScanning; temp.AllowBranding = tenantsubscription.AllowBranding; temp.AllowTemplateWorkflows = tenantsubscription.AllowTemplateWorkflows; context.TenantSubscriptions.Attach(temp); context.Entry(temp).State = System.Data.Entity.EntityState.Modified; context.SaveChanges(); outtenantsubscription = temp; } result = true; } catch (Exception e) { exception = e; } return(result); }
public static bool UpdateUser(MasterUserSession masterUserSession, MasterUser masteruser, out MasterUser outmasteruser, out Exception exception) { bool result = false; outmasteruser = null; exception = null; try { using (var context = new ContextMaster()) { MasterUser user = new MasterUser(); user = context.Users.Where(x => x.Id == masteruser.Id).FirstOrDefault(); user.Address1 = masteruser.Address1; user.Address2 = masteruser.Address2; user.City = masteruser.City; user.Country = masteruser.Country; user.Email = masteruser.Email; user.NameFamily = masteruser.NameFamily; user.NameGiven = masteruser.NameGiven; user.PasswordHash = masteruser.PasswordHash; user.PasswordSalt = masteruser.PasswordSalt; user.PhoneMobile = masteruser.PhoneMobile; user.PhoneWork = masteruser.PhoneWork; user.ActiveDirectoryId = masteruser.ActiveDirectoryId; // user.UserName = masteruser.UserName; user.AuthenticationType = masteruser.AuthenticationType; user.ZipOrPostCode = masteruser.ZipOrPostCode; context.Users.Attach(user); context.Entry(user).State = System.Data.Entity.EntityState.Modified; context.SaveChanges(); context.Dispose(); outmasteruser = user; result = true; } } catch (Exception ex) { exception = ex; } return(result); }
public static bool CreateTenantSubscriptionAndDeactivateExistingTenantSubscription(MasterUserSession MasterUserSession, long existingtenantsubscriptionid, Subscription subscriptionMaster, TenantSubscription tenantsubscriptionMaster, out Exception exception) { var result = false; exception = null; //System.Data.Common.DbTransaction Tran = null; //ContextMaster context = new ContextMaster(); //context.ObjectContext.Connection.Open(); //Tran = context.ObjectContext.Connection.BeginTransaction(); DbContextTransaction masterTrans = null; DbContextTransaction tenantTrans = null; using (var contextMaster = new ContextMaster()) { try { using (masterTrans = contextMaster.Database.BeginTransaction()) { try { var existingSubscriptions = contextMaster.TenantSubscriptions.Where(x => (x.TenantId == existingtenantsubscriptionid) && (x.IsActive == true)).ToList(); foreach (var existingSubnscription in existingSubscriptions) { existingSubnscription.IsActive = false; contextMaster.SaveChanges(); } contextMaster.TenantSubscriptions.Add(tenantsubscriptionMaster); contextMaster.SaveChanges(); tenantsubscriptionMaster.MasterTenantSubscriptionId = tenantsubscriptionMaster.Id; contextMaster.Entry(tenantsubscriptionMaster).State = EntityState.Modified; contextMaster.SaveChanges(); var tenant = contextMaster.Tenants.SingleOrDefault(x => x.Id == tenantsubscriptionMaster.TenantId); if (tenant == null) { throw (new Exception("Unable to Find Tenant in the Master DB.")); } using (var contextTenant = new ContextTenant(tenant.DatabaseConnectionString)) { try { using (tenantTrans = contextTenant.Database.BeginTransaction()) { var existingtenantsubscriptionstenant = contextTenant.TenantSubscriptions.Where(x => (x.IsActive == true)).ToList(); foreach (var existingSubscriptionTenant in existingtenantsubscriptionstenant) { existingSubscriptionTenant.IsActive = false; contextTenant.SaveChanges(); } var subscriptionTenant = contextTenant.Subscriptions.SingleOrDefault(s => s.MasterSubscriptionId == subscriptionMaster.Id); if (subscriptionTenant == null) { subscriptionTenant = subscriptionMaster.Clone(); subscriptionTenant.Id = 0; subscriptionTenant.MasterSubscriptionId = subscriptionMaster.Id; subscriptionTenant.SubscriptionType = EntityMasterTenantType.Tenant; contextTenant.Subscriptions.Add(subscriptionTenant); contextTenant.SaveChanges(); } else { //subscriptionTenant = subscription.Clone(); //subscriptionTenant.MasterTenantId = subscription.Id;//Yeh Maam Nay kerwaya hai. //contextTenant.Entry(subscriptionTenant).State = EntityState.Modified; //contextTenant.SaveChanges(); } var count = contextTenant.Tenants.Count(); if (count != 1) { throw (new Exception($"The number of tenant entries found in the Tenant database was {count} instead of 1.")); } var tenantTenant = contextTenant.Tenants.Single(); var tenantsubscriptionTenant = tenantsubscriptionMaster; var masterTenantSubscriptionId = contextMaster.TenantSubscriptions.AsNoTracking().Where(x => x.IsActive == true).FirstOrDefault().Id; tenantsubscriptionTenant.MasterTenantSubscriptionId = tenantsubscriptionMaster.Id; tenantsubscriptionTenant.Id = 0; tenantsubscriptionTenant.SubscriptionId = subscriptionTenant.Id; tenantsubscriptionTenant.Tenant = null; tenantsubscriptionTenant.TenantId = tenantTenant.Id; tenantsubscriptionTenant.TenantSubscriptionType = EntityMasterTenantType.Tenant; contextTenant.TenantSubscriptions.Add(tenantsubscriptionTenant); contextTenant.SaveChanges(); try { tenantTrans.Commit(); masterTrans.Commit(); } catch { tenantTrans.Rollback(); masterTrans.Rollback(); } result = true; } } catch (Exception ex) { exception = ex; throw; } } } catch (Exception ex) { exception = ex; throw; //Tran.Rollback(); //Tran.Dispose(); } } } catch (Exception ex) { exception = ex; masterTrans.Rollback(); tenantTrans.Rollback(); masterTrans.Dispose(); tenantTrans.Dispose(); } } return(result); }
public static bool CreateTenantSubscription(MasterUserSession MasterUserSession, TenantSubscription tenantsubscription, out TenantSubscription outtenantsubscription, out Exception exception) { var result = false; //tenant = null; outtenantsubscription = null; exception = null; try { using (var context = new ContextMaster()) { DbContextTransaction mastertrans = null; DbContextTransaction tenanttrans = null; try { using (mastertrans = context.Database.BeginTransaction()) { outtenantsubscription = context.TenantSubscriptions.Add(tenantsubscription); context.SaveChanges(); var tenant = context.Tenants.Where(x => x.Id == tenantsubscription.TenantId).FirstOrDefault(); var subscription = context.Subscriptions.Where(x => x.Id == tenantsubscription.SubscriptionId).FirstOrDefault(); using (var contexttenant = new ContextTenant(tenant.DatabaseConnectionString)) { try { using (tenanttrans = contexttenant.Database.BeginTransaction()) { var mastersubscriptionid = subscription.Id; subscription.Id = 0; contexttenant.Subscriptions.Add(subscription); contexttenant.SaveChanges(); tenantsubscription.SubscriptionId = subscription.Id; contexttenant.TenantSubscriptions.Add(tenantsubscription); contexttenant.SaveChanges(); } } catch (Exception ex) { exception = ex; throw ex; } } tenanttrans.Commit(); mastertrans.Commit(); } } catch (Exception ex) { if (mastertrans != null) { mastertrans.Rollback(); mastertrans.Dispose(); } if (tenanttrans != null) { tenanttrans.Rollback(); tenanttrans.Dispose(); } exception = ex; throw ex; } } result = true; } catch (Exception ex) { exception = ex; } return(result); }
/// <summary> /// Authentication using: [Salted password hashing with PBKDF2-SHA1]. /// Implementation available at: [HouseOfSynergy.PowerTools.Library.Security.Cryptography.PasswordHash]. /// The password should never reach here in plain text. It should b encrypted using Sha512 in TypeScript or JavaScript. /// A C# implementation of Sha512 is available at: [HouseOfSynergy.PowerTools.Library.Security.Cryptography.Sha]. /// </summary> /// <param name="sessionType">The origin of the request.</param> /// <param name="username">Username in plain text.</param> /// <param name="passwordHash">Password from client hashed using Sha512.</param> /// <param name="token">The user object fetched.</param> /// <param name="exception">Populates an exception where applicable.</param> /// <returns></returns> public static bool SignIn ( SessionType sessionType, string username, string passwordHash, string clientIpAddress, string userAgent, long ticks, string sessionId, out MasterUserSession masterUserSession, out Exception exception ) { var result = false; var now = DateTime.UtcNow; MasterUser userDatabase = null; MasterSession sessionDatabase = null; exception = null; masterUserSession = null; try { using (var context = new ContextMaster()) { userDatabase = context.Users.SingleOrDefault(u => (u.UserName == username)); if (userDatabase == null) { throw (new UserNotFoundException()); } if (!PasswordHash.ValidatePassword(passwordHash, userDatabase.PasswordHash)) { throw (new AuthenticationException()); } var token = userDatabase.Id.ToString() + EntityConstants.TokenDelimiter + userDatabase.UserName + EntityConstants.TokenDelimiter + userDatabase.AuthenticationType.ToString() + EntityConstants.TokenDelimiter + (userDatabase.ActiveDirectoryId ?? "").Trim() + EntityConstants.TokenDelimiter + "" + EntityConstants.TokenDelimiter + sessionType.ToString() + EntityConstants.TokenDelimiter + EntityConstants.TokenDelimiter + EntityConstants.TokenDelimiter; // TODO: Remove for production. if (AffinityConfiguration.DeploymentLocation == DeploymentLocation.BtsSaleem) { now = now.Add(TimeSpan.FromHours(1)); } sessionDatabase = userDatabase.Sessions.SingleOrDefault ( s => ( (s.DateTimeCreated < now) && (s.DateTimeExpiration > now) && (s.SessionId == sessionId) && (s.Token == token) && (s.UserAgent == userAgent) && (s.IPAddressString == clientIpAddress) && (s.SessionType == sessionType) ) ); var lines = new List <string>(); lines.Add($"--------------------------------------------------------------------------------------------------------------------------------------------------------------"); lines.Add($"SIGNIN"); lines.Add($"Session Found: {sessionDatabase != null}"); lines.Add($"now: {now}"); lines.Add($"SessionId: {sessionId}"); lines.Add($"token: {token}"); lines.Add($"useragent: {userAgent}"); lines.Add($"ipAddressString: {clientIpAddress}"); lines.Add($"sessionType: {sessionType}"); lines.Add($"--------------------------------------------------------------------------------------------------------------------------------------------------------------"); AffinityConfiguration.Messages.Add(string.Join("<br />", lines)); if (sessionDatabase == null) { var guid = Guid.NewGuid(); var rijndaelKey = new byte [GlobalConstants.AlgorithmSymmetricKeySize]; var rijndaelInitializationVector = new byte [GlobalConstants.AlgorithmSymmetricInitializationVectorSize]; var rsaKeyPair = Rsa.GenerateKeyPair(GlobalConstants.AlgorithmAsymmetricKeySize); using (var randomNumberGenerator = RandomNumberGenerator.Create()) { randomNumberGenerator.GetBytes(rijndaelKey); randomNumberGenerator.GetBytes(rijndaelInitializationVector); } do { guid = Guid.NewGuid(); } while (context.Sessions.Any(s => s.Guid == guid)); sessionDatabase = new MasterSession(); sessionDatabase.Guid = guid; sessionDatabase.CultureName = "en"; sessionDatabase.Token = token; sessionDatabase.SessionId = sessionId; sessionDatabase.SessionType = sessionType; sessionDatabase.UserAgent = userAgent; sessionDatabase.IPAddressString = clientIpAddress; sessionDatabase.DeviceType = DeviceType.Unknown; sessionDatabase.DateTimeCreated = now; sessionDatabase.DateTimeExpiration = sessionDatabase.DateTimeCreated.Add(TimeSpan.FromDays(1)); sessionDatabase.RijndaelKey = Convert.ToBase64String(rijndaelKey); sessionDatabase.RijndaelInitializationVector = Convert.ToBase64String(rijndaelInitializationVector); sessionDatabase.RsaKeyPublic = rsaKeyPair.KeyPublic.KeyToString(); sessionDatabase.RsaKeyPrivate = rsaKeyPair.KeyPrivate.KeyToString(); sessionDatabase.User = userDatabase; sessionDatabase.UserId = userDatabase.Id; context.Sessions.Add(sessionDatabase); context.SaveChanges(); } else { sessionDatabase.DateTimeExpiration = DateTime.UtcNow.Add(TimeSpan.FromDays(1)); context.SaveChanges(); } var sessions = userDatabase.Sessions.Where(s => s.DateTimeExpiration < DateTime.UtcNow.Subtract(TimeSpan.FromDays(30))); foreach (var s in sessions) { context.Sessions.Remove(s); } context.SaveChanges(); sessionDatabase = context.Sessions.AsNoTracking().Single(s => s.Id == sessionDatabase.Id); userDatabase = context.Users.AsNoTracking().Include(p => p.Roles).AsNoTracking().Single(u => u.Id == userDatabase.Id); userDatabase.PasswordHash = ""; userDatabase.PasswordSalt = ""; sessionDatabase.RijndaelKey = ""; sessionDatabase.RijndaelInitializationVector = ""; sessionDatabase.RsaKeyPrivate = ""; sessionDatabase.RsaKeyPublic = (sessionType == SessionType.Api) ? sessionDatabase.RsaKeyPublic : ""; masterUserSession = new MasterUserSession(userDatabase, sessionDatabase); result = true; } } catch (Exception e) { exception = e; } return(result); }
public static void ThrowOnInvalidToken ( string token, SessionType sessionType, string username, string clientIpAddress, string userAgent, long ticks, string sessionId, out MasterUserSession masterUserSession ) { MasterUser userDatabase = null; MasterSession sessionDatabase = null; masterUserSession = null; if (clientIpAddress != null) { if (clientIpAddress.Contains(":")) { clientIpAddress = clientIpAddress.Split(new string[] { ":" }, StringSplitOptions.None)[0]; } } using (var context = new ContextMaster()) { var now = DateTime.UtcNow; var sessionsDatabase = context .Sessions .Include(p => p.User) .Where ( s => ( // TODO: Add checks. (s.DateTimeCreated < now) && (s.DateTimeExpiration > now) && (s.SessionId == sessionId) && (s.Token == token) && (s.UserAgent == userAgent) && (s.IPAddressString == clientIpAddress) && (s.SessionType == sessionType) ) ) .ToList(); var lines = new List <string>(); lines.Add($"--------------------------------------------------------------------------------------------------------------------------------------------------------------"); lines.Add($"VALIDATE TOKEN"); lines.Add($"Session Found: {sessionsDatabase != null}"); lines.Add($"now: {now}"); lines.Add($"SessionId: {sessionId}"); lines.Add($"token: {token}"); lines.Add($"useragent: {userAgent}"); lines.Add($"ipAddressString: {clientIpAddress}"); lines.Add($"sessionType: {sessionType}"); lines.Add($"--------------------------------------------------------------------------------------------------------------------------------------------------------------"); AffinityConfiguration.Messages.Add(string.Join("<br />", lines)); if (sessionsDatabase.Count > 1) { // Order by Id (descending). sessionsDatabase.Sort((x, y) => x.Id.CompareTo(y.Id)); do { context.Sessions.Remove(sessionsDatabase.First()); context.SaveChanges(); sessionsDatabase.Remove(sessionsDatabase.First()); }while (sessionsDatabase.Count > 1); context.SaveChanges(); } if (sessionsDatabase.Count < 1) { throw (new TokenInvalidException()); } else if (sessionsDatabase.Count > 1) { throw (new Exception("Multiple session matches were found. This is a dev bug!")); } sessionDatabase = sessionsDatabase.Single(); sessionDatabase = context.Sessions.AsNoTracking().Include(s => s.User).Single(s => s.Id == sessionDatabase.Id); userDatabase = context.Users.AsNoTracking().Include(u => u.Roles).Single(u => u.Id == sessionDatabase.User.Id); masterUserSession = new MasterUserSession(userDatabase, sessionDatabase); } }
public static bool UpdateTenant(MasterUserSession tenantUserSession, Tenant tenant, out Tenant outtenant, out Exception exception) { var result = false; outtenant = null; exception = null; try { using (var context = new ContextMaster()) { var count = context.Tenants.Count(t => t.Id == tenant.Id); if (count == 0) { throw (new Exception("The provided tenant Id was not found.")); } count = context.Tenants.Count(t => ((t.Id != tenant.Id) && (t.Domain.ToLower() == tenant.Domain.ToLower()))); if (count == 1) { throw (new Exception("The provided domain already exists in the system.")); } else if (count > 1) { throw (new Exception("The provided domain exists multiple times in the system.")); } var tempTenant = context.Tenants.Single(t => t.Id == tenant.Id); tempTenant.CompanyName = tenant.CompanyName; tempTenant.Domain = tenant.Domain; tempTenant.ContactOwnerNameGiven = tenant.ContactOwnerNameGiven; tempTenant.ContactOwnerNameFamily = tenant.ContactOwnerNameFamily; tempTenant.ContactOwnerAddress = tenant.ContactOwnerAddress; tempTenant.ContactOwnerCity = tenant.ContactOwnerCity; tempTenant.ContactOwnerState = tenant.ContactOwnerState; tempTenant.ContactOwnerZipCode = tenant.ContactOwnerZipCode; tempTenant.ContactOwnerCountry = tenant.ContactOwnerCountry; tempTenant.ContactOwnerPhone = tenant.ContactOwnerPhone; tempTenant.ContactOwnerFax = tenant.ContactOwnerFax; tempTenant.ContactOwnerEmail = tenant.ContactOwnerEmail; tempTenant.ContactAdministratorNameGiven = tenant.ContactAdministratorNameGiven; tempTenant.ContactAdministratorNameFamily = tenant.ContactAdministratorNameFamily; tempTenant.ContactAdministratorAddress = tenant.ContactAdministratorAddress; tempTenant.ContactAdministratorCity = tenant.ContactAdministratorCity; tempTenant.ContactAdministratorState = tenant.ContactAdministratorState; tempTenant.ContactAdministratorZipCode = tenant.ContactAdministratorZipCode; tempTenant.ContactAdministratorCountry = tenant.ContactAdministratorCountry; tempTenant.ContactAdministratorPhone = tenant.ContactAdministratorPhone; tempTenant.ContactAdministratorFax = tenant.ContactAdministratorFax; tempTenant.ContactAdministratorEmail = tenant.ContactAdministratorEmail; tempTenant.ContactBillingNameGiven = tenant.ContactBillingNameGiven; tempTenant.ContactBillingNameFamily = tenant.ContactBillingNameFamily; tempTenant.ContactBillingAddress = tenant.ContactBillingAddress; tempTenant.ContactBillingCity = tenant.ContactBillingCity; tempTenant.ContactBillingState = tenant.ContactBillingState; tempTenant.ContactBillingZipCode = tenant.ContactBillingZipCode; tempTenant.ContactBillingCountry = tenant.ContactBillingCountry; tempTenant.ContactBillingPhone = tenant.ContactBillingPhone; tempTenant.ContactBillingFax = tenant.ContactBillingFax; tempTenant.ContactBillingEmail = tenant.ContactBillingEmail; tempTenant.ContactTechnicalNameGiven = tenant.ContactTechnicalNameGiven; tempTenant.ContactTechnicalNameFamily = tenant.ContactTechnicalNameFamily; tempTenant.ContactTechnicalAddress = tenant.ContactTechnicalAddress; tempTenant.ContactTechnicalCity = tenant.ContactTechnicalCity; tempTenant.ContactTechnicalState = tenant.ContactTechnicalState; tempTenant.ContactTechnicalZipCode = tenant.ContactTechnicalZipCode; tempTenant.ContactTechnicalCountry = tenant.ContactTechnicalCountry; tempTenant.ContactTechnicalPhone = tenant.ContactTechnicalPhone; tempTenant.ContactTechnicalFax = tenant.ContactTechnicalFax; tempTenant.ContactTechnicalEmail = tenant.ContactTechnicalEmail; context.Tenants.Attach(tempTenant); //context.Entry(tempTenant).State = System.Data.Entity.EntityState.Modified; context.SaveChanges(); outtenant = tempTenant; } result = true; } catch (Exception e) { exception = e; outtenant = tenant; } return(result); }
public static bool CreateTenant(MasterUserSession tenantUserSession, Tenant tenant, out Tenant tenantMaster, out Exception exception) { var result = false; Tenant tenantMasterTemp = null; exception = null; tenantMaster = null; try { using (var context = new ContextMaster()) { using (var transaction = context.Database.BeginTransaction()) { try { var count = context.Tenants.Count(t => t.Domain.ToLower() == tenant.Domain.ToLower()); if (count == 1) { throw (new Exception("The provided domain already exists in the system.")); } else if (count > 1) { throw (new Exception("The provided domain exists multiple times in the system.")); } tenant.DatabaseConnectionString = AzureDBConnectionStringBuilder(tenant.DatabaseConnectionString); tenantMasterTemp = context.Tenants.Add(tenant); context.SaveChanges(); tenantMasterTemp.MasterTenantId = tenantMasterTemp.Id; context.Entry(tenantMasterTemp).State = EntityState.Modified; context.SaveChanges(); if (tenantMasterTemp != null) { var tenantTenant = tenantMasterTemp.Clone(); tenantTenant.Id = 0; tenantTenant.MasterTenantId = tenant.Id; tenantTenant.TenantType = EntityMasterTenantType.Tenant; tenantTenant.AuthenticationType = AuthenticationType.None; ContextTenant.Initialize(tenantTenant.DatabaseConnectionString); // Commented out by Raheel to find a better way to automate the process. //using (var contexttenant = new ContextTenant (tenantTenant.DatabaseConnectionString)) //{ // bool seederresult = DataLayer.Seeders.SeederTenant.Seed (contexttenant, tenantTenant, out exception); // if (seederresult) // { // transaction.Commit (); // tenantMaster = tenantMasterTemp; // } // else // { // transaction.Rollback (); // } //} } } catch (Exception ex) { exception = ex; transaction.Rollback(); tenantMaster = tenant; } } } result = true; } catch (Exception e) { exception = e; tenantMaster = tenant; } return(result); }