/// <summary> /// Updates a user in Active Directory /// </summary> /// <param name="user"></param> /// <param name="isUsingDisplayNameAsNameAttribute"></param> public void UpdateUser(UsersObject user, bool isUsingDisplayNameAsNameAttribute) { PrincipalContext pc = null; UserPrincipalExt up = null; try { pc = new PrincipalContext(ContextType.Domain, this.domainController, this.username, this.password); logger.Debug("Finding user in Active Directory: " + user.UserPrincipalName); up = UserPrincipalExt.FindByIdentity(pc, IdentityType.UserPrincipalName, user.UserPrincipalName); if (up == null) throw new Exception("USER IS UNKNOWN"); else { up.GivenName = user.Firstname; up.DisplayName = user.DisplayName; up.Enabled = user.IsEnabled; if (!string.IsNullOrEmpty(user.Middlename)) up.MiddleName = user.Middlename; else up.MiddleName = null; if (!string.IsNullOrEmpty(user.Lastname)) up.LastName = user.Lastname; else up.LastName = null; if (!string.IsNullOrEmpty(user.Department)) up.Department = user.Department; else up.Department = null; if (isUsingDisplayNameAsNameAttribute) up.Name = user.DisplayName; // Save changes up.Save(); } } catch (Exception ex) { this.logger.Error("Error updating user " + user.UserPrincipalName, ex); throw; } finally { if (up != null) up.Dispose(); if (pc != null) pc.Dispose(); } }
/// <summary> /// Authenticates a user a returns an array of groups they belong to /// </summary> /// <param name="userName"></param> /// <param name="userPassword"></param> /// <returns>Array of groups the user belongs to</returns> public UsersObject Authenticate(string userName, string userPassword) { PrincipalContext pc = null; UserPrincipal up = null; DirectoryEntry de = null; try { pc = new PrincipalContext(ContextType.Domain, this.domainController, this.username, this.password); logger.Debug("Attempting to authenticate user " + userName); // Try to authenticate bool authenticated = pc.ValidateCredentials(userName, userPassword); if (authenticated) { logger.Debug(userName + " successfully authenticated. Attempting to retrieve groups that the user belongs to."); UsersObject loggedInUser = new UsersObject(); up = UserPrincipal.FindByIdentity(pc, IdentityType.UserPrincipalName, userName); de = up.GetUnderlyingObject() as DirectoryEntry; // Set values loggedInUser.UserPrincipalName = up.UserPrincipalName; loggedInUser.DisplayName = up.DisplayName; loggedInUser.Groups = new List<string>(); for (int i = 0; i < de.Properties["memberOf"].Count; i++) { loggedInUser.Groups.Add(de.Properties["memberOf"][i].ToString()); } logger.Debug(userName + " belongs to the following groups: " + String.Join(", ", loggedInUser.Groups)); return loggedInUser; } else return null; } catch (Exception ex) { this.logger.Error("Error authenticating user " + userName, ex); throw; } finally { if (de != null) de.Dispose(); if (up != null) up.Dispose(); if (pc != null) pc.Dispose(); } }
/// <summary> /// Gets detailed user information about a specific user /// </summary> /// <param name="userPrincipalName"></param> /// <returns></returns> public UsersObject GetUser(string userPrincipalName) { PrincipalContext pc = null; UserPrincipalExt up = null; try { pc = new PrincipalContext(ContextType.Domain, this.domainController, this.username, this.password); logger.Debug("Attempting to retrieve user " + userPrincipalName); up = UserPrincipalExt.FindByIdentity(pc, IdentityType.UserPrincipalName, userPrincipalName); if (up == null) throw new Exception("USER_NOT_FOUND"); else { UsersObject returnUser = new UsersObject(); returnUser.UserPrincipalName = up.UserPrincipalName; returnUser.sAMAccountName = up.SamAccountName; returnUser.Firstname = up.GivenName; returnUser.Middlename = up.MiddleName; returnUser.Lastname = up.Surname; returnUser.DisplayName = up.DisplayName; returnUser.Department = up.Department; returnUser.IsEnabled = up.Enabled == null ? true : (bool)up.Enabled; return returnUser; } } catch (Exception ex) { this.logger.Error("Error retrieving user information " + userPrincipalName, ex); throw; } finally { if (up != null) up.Dispose(); if (pc != null) pc.Dispose(); } }
/// <summary> /// Creates a new user /// </summary> /// <param name="user"></param> /// <param name="baseOrganizationalUnit"></param> /// <param name="isUsingDisplayNameAsNameAttribute"></param> public UsersObject NewUser(UsersObject user, string companyUsersPath, bool isUsingDisplayNameAsNameAttribute) { PrincipalContext pc = null; UserPrincipalExt up = null; try { pc = new PrincipalContext(ContextType.Domain, this.domainController, companyUsersPath, this.username, this.password); logger.Debug("Looking to see if user already exists: " + user.UserPrincipalName); bool doesExist = DoesUserPrincipalNameExist(user.UserPrincipalName); if (doesExist) throw new Exception("User already exists"); else { // Find an available sAMAccountName user.sAMAccountName = GetAvailableSamAccountName(user.UserPrincipalName); // User was not found so lets create the new user up = new UserPrincipalExt(pc, user.sAMAccountName, user.Password, true); up.UserPrincipalName = user.UserPrincipalName; up.DisplayName = user.DisplayName; up.PasswordNeverExpires = user.PasswordNeverExpires; if (isUsingDisplayNameAsNameAttribute) up.Name = user.DisplayName; else up.Name = user.UserPrincipalName; if (!string.IsNullOrEmpty(user.Firstname)) up.GivenName = user.Firstname; if (!string.IsNullOrEmpty(user.Middlename)) up.MiddleName = user.Middlename; if (!string.IsNullOrEmpty(user.Lastname)) up.LastName = user.Lastname; if (!string.IsNullOrEmpty(up.Department)) up.Department = user.Department; up.Save(); // Get the user's GUID user.UserGuid = (Guid)up.Guid; // Get the user's distinguished name user.DistinguishedName = up.DistinguishedName; // Return the user with the information return user; } } catch (Exception ex) { this.logger.Error("Error creating new user " + user.UserPrincipalName, ex); throw; } finally { if (up != null) up.Dispose(); if (pc != null) pc.Dispose(); } }
public void UpdateUser(UsersObject updateUser, bool isSuperOrResellerAdmin) { CPDatabase database = null; ADGroup ldapGroup = null; ADUser ldapUser = null; try { database = new CPDatabase(); // Get the user from the database var foundUser = (from u in database.Users where u.UserPrincipalName == updateUser.UserPrincipalName select u).FirstOrDefault(); if (foundUser == null) ThrowEvent(AlertID.FAILED, "Unknown user " + updateUser.UserPrincipalName); else { this.logger.Debug("Found user " + foundUser.UserPrincipalName + " in the database. Continuing..."); // Update the user values foundUser.Firstname = updateUser.Firstname; foundUser.Middlename = updateUser.Middlename; foundUser.Lastname = updateUser.Lastname; foundUser.DisplayName = updateUser.DisplayName; foundUser.Department = updateUser.Department; // Update user in Active Directory ldapUser = new ADUser(StaticSettings.Username, StaticSettings.DecryptedPassword, StaticSettings.PrimaryDC); ldapUser.UpdateUser(updateUser, StaticSettings.AllowCustomNameAttribute); // Only update these values if super admin or reseller admin is modifying the user if (isSuperOrResellerAdmin) { this.logger.Debug("Super admin or reseller is updating user so we can check comapny admin permissions and reseller permissions"); foundUser.IsCompanyAdmin = updateUser.IsCompanyAdmin; foundUser.IsResellerAdmin = updateUser.IsResellerAdmin; // Get permissions from database var userPermissions = (from p in database.UserPermissions where p.UserID == foundUser.ID select p).FirstOrDefault(); // If the user is no longer a company admin then remove permissions from the database if (userPermissions != null && !updateUser.IsCompanyAdmin) { this.logger.Debug("User " + updateUser.UserPrincipalName + " is no longer a comapny admin. Need to remove rights from database and security group"); database.UserPermissions.Remove(userPermissions); // Remove from Admins@ security group ldapGroup = new ADGroup(StaticSettings.Username, StaticSettings.DecryptedPassword, StaticSettings.PrimaryDC); ldapGroup.RemoveMember("Admins@" + updateUser.CompanyCode, updateUser.UserPrincipalName, "upn"); } else if (userPermissions != null && updateUser.IsCompanyAdmin) { this.logger.Debug("User " + updateUser.UserPrincipalName + " is a company admin. Need to update company admin rights in database."); // If user permissions was found and the user is company admin then update the values userPermissions.EnableExchange = updateUser.EnableExchangePerm; userPermissions.DisableExchange = updateUser.DisableExchangePerm; userPermissions.AddDomain = updateUser.AddDomainPerm; userPermissions.DeleteDomain = updateUser.DeleteDomainPerm; userPermissions.EnableAcceptedDomain = updateUser.EnableAcceptedDomainPerm; userPermissions.DisableAcceptedDomain = updateUser.DisableAcceptedDomainPerm; } else if (userPermissions == null && updateUser.IsCompanyAdmin) { this.logger.Debug("User " + updateUser.UserPrincipalName + " does not have any existing company admin rights. We need to add them to the database."); // No existing permissions were found and we need to add to database userPermissions = new UserPermission(); userPermissions.UserID = foundUser.ID; userPermissions.EnableExchange = updateUser.EnableExchangePerm; userPermissions.DisableExchange = updateUser.DisableExchangePerm; userPermissions.AddDomain = updateUser.AddDomainPerm; userPermissions.DeleteDomain = updateUser.DeleteDomainPerm; userPermissions.EnableAcceptedDomain = updateUser.EnableAcceptedDomainPerm; userPermissions.DisableAcceptedDomain = updateUser.DisableAcceptedDomainPerm; database.UserPermissions.Add(userPermissions); // Add to Admins@ security group ldapGroup = new ADGroup(StaticSettings.Username, StaticSettings.DecryptedPassword, StaticSettings.PrimaryDC); ldapGroup.AddMember("Admins@" + updateUser.CompanyCode, updateUser.UserPrincipalName, "upn"); } } else this.logger.Debug("User making changes to " + updateUser.UserPrincipalName + " is not a super admin or reseller admin. We cannot update company admin or reseller admin permissions unless the user making changes is a super or reseller admin."); // Update database database.SaveChanges(); } } catch (Exception ex) { this.logger.Debug("Error updating user " + updateUser.UserPrincipalName, ex); ThrowEvent(AlertID.FAILED, ex.Message); } finally { if (ldapUser != null) ldapUser.Dispose(); if (ldapGroup != null) ldapGroup.Dispose(); if (database != null) database.Dispose(); } }
public void CreateUser(UsersObject newUser) { CPDatabase database = null; ADGroup ldapGroup = null; ADUser ldapUser = null; CloudPanelTransaction newUserTransaction = new CloudPanelTransaction(); try { // Insert into database database = new CPDatabase(); // Make sure the user doesn't already exist var foundUser = (from u in database.Users where u.UserPrincipalName == newUser.UserPrincipalName select u).FirstOrDefault(); if (foundUser != null) ThrowEvent(AlertID.FAILED, "User already exists " + newUser.UserPrincipalName); else { // Get the company's OU where we need to save the user var companyDistinguishedName = (from c in database.Companies where !c.IsReseller where c.CompanyCode == newUser.CompanyCode select c.DistinguishedName).First(); // Check if they are using a custom user's OU if (!string.IsNullOrEmpty(StaticSettings.UsersOU)) companyDistinguishedName = string.Format("OU={0},{1}", StaticSettings.UsersOU, companyDistinguishedName); ldapUser = new ADUser(StaticSettings.Username, StaticSettings.DecryptedPassword, StaticSettings.PrimaryDC); UsersObject createdUser = ldapUser.NewUser(newUser, companyDistinguishedName, StaticSettings.AllowCustomNameAttribute); newUserTransaction.NewUser(createdUser.UserPrincipalName); // Add the users to the groups ldapGroup = new ADGroup(StaticSettings.Username, StaticSettings.DecryptedPassword, StaticSettings.PrimaryDC); ldapGroup.AddMember("AllUsers@" + newUser.CompanyCode, createdUser.UserPrincipalName, "upn"); if (newUser.IsCompanyAdmin) ldapGroup.AddMember("Admins@" + newUser.CompanyCode, createdUser.UserPrincipalName, "upn"); // Insert into database User sqlUser = new User(); sqlUser.UserGuid = createdUser.UserGuid; sqlUser.CompanyCode = createdUser.CompanyCode; sqlUser.sAMAccountName = createdUser.sAMAccountName; sqlUser.UserPrincipalName = createdUser.UserPrincipalName; sqlUser.DistinguishedName = createdUser.DistinguishedName; sqlUser.DisplayName = createdUser.DisplayName; sqlUser.Firstname = createdUser.Firstname; sqlUser.Middlename = createdUser.Middlename; sqlUser.Lastname = createdUser.Lastname; sqlUser.Email = string.Empty; sqlUser.Department = createdUser.Department; sqlUser.IsResellerAdmin = createdUser.IsResellerAdmin; sqlUser.IsCompanyAdmin = createdUser.IsCompanyAdmin; sqlUser.MailboxPlan = 0; sqlUser.TSPlan = 0; sqlUser.LyncPlan = 0; sqlUser.Created = DateTime.Now; sqlUser.AdditionalMB = 0; sqlUser.ActiveSyncPlan = 0; database.Users.Add(sqlUser); // Insert permissions into database if (createdUser.IsCompanyAdmin) { UserPermission newPermissions = new UserPermission(); newPermissions.UserID = sqlUser.ID; newPermissions.EnableExchange = createdUser.EnableExchangePerm; newPermissions.DisableExchange = createdUser.DisableExchangePerm; newPermissions.AddDomain = createdUser.AddDomainPerm; newPermissions.DeleteDomain = createdUser.DeleteDomainPerm; newPermissions.EnableAcceptedDomain = createdUser.EnableAcceptedDomainPerm; newPermissions.DisableAcceptedDomain = createdUser.DisableAcceptedDomainPerm; database.UserPermissions.Add(newPermissions); } database.SaveChanges(); } } catch (Exception ex) { ThrowEvent(AlertID.FAILED, ex.Message); // Rollback on error newUserTransaction.RollBack(); } finally { if (ldapUser != null) ldapUser.Dispose(); if (ldapGroup != null) ldapGroup.Dispose(); if (database != null) database.Dispose(); } }
public void NewMailbox(UsersObject user) { try { this.logger.Debug("Creating new mailbox for "+ user.UserPrincipalName); PSCommand cmd = new PSCommand(); cmd.AddCommand("Enable-Mailbox"); cmd.AddParameter("Identity", user.UserPrincipalName); cmd.AddParameter("PrimarySmtpAddress", user.PrimarySmtpAddress); cmd.AddParameter("AddressBookPolicy", user.CompanyCode + " ABP"); this.logger.Debug("Checking activesync policy for " + user.UserPrincipalName); if (!string.IsNullOrEmpty(user.ActiveSyncName)) cmd.AddParameter("ActiveSyncMailboxPolicy", user.ActiveSyncName); this.logger.Debug("Checking if we are putting this new mailbox in a specific database " + user.UserPrincipalName); if (!string.IsNullOrEmpty(user.CurrentMailboxDatabase)) cmd.AddParameter("Database", user.CurrentMailboxDatabase); cmd.AddParameter("Confirm", false); cmd.AddParameter("DomainController", domainController); powershell.Commands = cmd; this.logger.Debug("Invoking powershell to create new mailbox for " + user.UserPrincipalName); powershell.Invoke(); if (powershell.HadErrors) throw powershell.Streams.Error[0].Exception; } catch (Exception ex) { this.logger.Error("Failed to create new mailbox for " + user.UserPrincipalName, ex); throw; } }
public void CreateMailbox(UsersObject user) { CPDatabase database = null; ExchangePowershell powershell = null; CloudPanelTransaction transaction = new CloudPanelTransaction(); try { database = new CPDatabase(); // Get the user from the database var foundUser = (from u in database.Users where u.UserPrincipalName == user.UserPrincipalName select u).FirstOrDefault(); powershell = new ExchangePowershell(StaticSettings.ExchangeURI, StaticSettings.Username, StaticSettings.DecryptedPassword, StaticSettings.ExchangeUseKerberos, StaticSettings.PrimaryDC); // Get the selected mailbox plan MailboxPlanObject mailboxPlan = GetMailboxPlan(user.MailboxPlan); // Create new mailbox and register transaction powershell.NewMailbox(user); transaction.NewMailbox(user.UserPrincipalName); // Update the mailbox values powershell.UpdateMailbox(user, mailboxPlan); powershell.UpdateCASMailbox(user, mailboxPlan); // Set litigation hold settings if enabled for litigation hold if (user.LitigationHoldEnabled) powershell.NewLitigationHold(user.UserPrincipalName, user.LitigationHoldComment, user.LitigationHoldUrl, user.LitigationHoldDuration); // Set archive settings if enabled for archiving if (user.ArchivingEnabled && user.ArchivePlan > 0) { powershell.NewArchiveMailbox(user); // Set quota on archive } foundUser.Email = user.PrimarySmtpAddress; foundUser.MailboxPlan = user.MailboxPlan; foundUser.AdditionalMB = user.SetMailboxSizeInMB - mailboxPlan.MailboxSizeInMB; foundUser.ExchArchivePlan = user.ArchivePlan; database.SaveChanges(); } catch (Exception ex) { this.logger.Error("Error creating mailbox for " + user.UserPrincipalName, ex); ThrowEvent(AlertID.FAILED, ex.Message); transaction.RollBack(); } finally { if (powershell != null) powershell.Dispose(); if (database != null) database.Dispose(); } }
public UsersObject GetUser(string identity, int exchangeVersion) { try { UsersObject user = new UsersObject(); // // // Get mailbox information // // // PSCommand cmd = new PSCommand(); cmd.AddCommand("Get-Mailbox"); cmd.AddParameter("Identity", identity); cmd.AddParameter("DomainController", this.domainController); powershell.Commands = cmd; Collection<PSObject> obj = powershell.Invoke(); if (obj != null && obj.Count > 0) { foreach (PSObject ps in obj) { this.logger.Debug("Pulling comment information for mailbox " + identity); if (ps.Members["Database"].Value != null) user.CurrentMailboxDatabase = ps.Members["Database"].Value.ToString(); if (ps.Members["DeliverToMailboxAndForward"].Value != null) user.DeliverToMailboxAndForward = bool.Parse(ps.Members["DeliverToMailboxAndForward"].Value.ToString()); if (ps.Members["LitigationHoldEnabled"].Value != null) user.LitigationHoldEnabled = bool.Parse(ps.Members["LitigationHoldEnabled"].Value.ToString()); if (ps.Members["LitigationHoldDuration"].Value != null) { string value = ps.Members["LitigationHoldDuration"].Value.ToString(); if (!value.Equals("Unlimited", StringComparison.CurrentCultureIgnoreCase)) { TimeSpan span = TimeSpan.Parse(value); user.LitigationHoldDuration = span.Days; } } if (ps.Members["HiddenFromAddressListsEnabled"].Value != null) user.MailboxHiddenFromGAL = bool.Parse(ps.Members["HiddenFromAddressListsEnabled"].Value.ToString()); if (ps.Members["RetentionComment"].Value != null) user.LitigationHoldComment = ps.Members["RetentionComment"].Value.ToString(); if (ps.Members["RetentionUrl"].Value != null) user.LitigationHoldUrl = ps.Members["RetentionUrl"].Value.ToString(); if (ps.Members["ForwardingAddress"].Value != null) user.ForwardingTo = ps.Members["ForwardingAddress"].Value.ToString(); if (ps.Members["SamAccountName"].Value != null) user.sAMAccountName = ps.Members["SamAccountName"].Value.ToString(); if (ps.Members["UserPrincipalName"].Value != null) user.UserPrincipalName = ps.Members["UserPrincipalName"].Value.ToString(); if (ps.Members["ThrottlingPolicy"].Value != null) user.ThrottlingPolicy = ps.Members["ThrottlingPolicy"].Value.ToString(); if (ps.Members["Alias"].Value != null) user.ExchangeAlias = ps.Members["Alias"].Value.ToString(); if (ps.Members["PrimarySmtpAddress"].Value != null) user.PrimarySmtpAddress = ps.Members["PrimarySmtpAddress"].Value.ToString(); if (ps.Members["DistinguishedName"].Value != null) user.DistinguishedName = ps.Members["DistinguishedName"].Value.ToString(); if (ps.Members["ArchiveDatabase"].Value != null) user.ArchiveDatabase = ps.Members["ArchiveDatabase"].Value.ToString(); if (ps.Members["ArchiveName"].Value != null) user.ArchiveName = ps.Members["ArchiveName"].Value.ToString(); if (exchangeVersion == 2013) user.HasExchangePicture = bool.Parse(ps.Members["HasPicture"].Value.ToString()); // Get email aliases this.logger.Debug("Pulling email aliases for " + identity); user.EmailAliases = new List<string>(); if (ps.Members["EmailAddresses"].Value != null) { PSObject multiValue = (PSObject)ps.Members["EmailAddresses"].Value; ArrayList addresses = (ArrayList)multiValue.BaseObject; // Convert to string array string[] stringEmailAddresses = (string[])addresses.ToArray(typeof(string)); foreach (string s in stringEmailAddresses) { if (!s.StartsWith("SMTP:")) { user.EmailAliases.Add(s.Replace("smtp:", string.Empty)); } } } } } if (powershell.HadErrors) throw powershell.Streams.Error[0].Exception; // // // Get full access permissions // // // this.logger.Debug("Getting full access permissions for " + identity); user.FullAccessUsers = new List<string>(); cmd = new PSCommand(); cmd.AddCommand("Get-MailboxPermission"); cmd.AddParameter("Identity", identity); cmd.AddParameter("DomainController", this.domainController); powershell.Commands = cmd; obj = powershell.Invoke(); if (obj != null && obj.Count > 0) { foreach (PSObject ps in obj) { // Only get users with a \ in them. Otherwise they are not users if (ps.Members["User"].Value.ToString().Contains("\\")) { this.logger.Debug("Found a user that has a permission to mailbox " + identity + "... now checking if it is deny permission or allow permission"); // We don't care about the deny permissions if (!bool.Parse(ps.Members["Deny"].Value.ToString())) { this.logger.Debug("Found a user that has a permission to mailbox " + identity + ": " + ps.Members["User"].Value.ToString()); // Get the permissions that this user has PSObject multiValue = (PSObject)ps.Members["AccessRights"].Value; ArrayList accessRights = (ArrayList)multiValue.BaseObject; // Convert to string array string[] stringAccessRights = (string[])accessRights.ToArray(typeof(string)); // Fix the sAMAccountName by removing the domain name string sAMAccountName = ps.Members["User"].Value.ToString().Split('\\')[1]; // Check if it is full access or send as if (stringAccessRights.Contains("FullAccess")) user.FullAccessUsers.Add(sAMAccountName); } } } } if (powershell.HadErrors) throw powershell.Streams.Error[0].Exception; // // // Get send-as permissions // // // this.logger.Debug("Getting send-as permissions for " + identity); user.SendAsUsers = new List<string>(); cmd = new PSCommand(); cmd.AddCommand("Get-ADPermission"); cmd.AddParameter("Identity", identity); cmd.AddParameter("DomainController", this.domainController); powershell.Commands = cmd; obj = powershell.Invoke(); if (obj != null && obj.Count > 0) { foreach (PSObject ps in obj) { if (ps.Members["ExtendedRights"].Value != null) { // Only get users with a \ in them. Otherwise they are not users if (ps.Members["User"].Value.ToString().Contains("\\")) { this.logger.Debug("Found a user that has an extended rights permission to mailbox " + identity + "... now checking if it is deny permission or allow permission"); // We don't care about the deny permissions if (!bool.Parse(ps.Members["Deny"].Value.ToString())) { this.logger.Debug("Found a user that has an extended rights permission to mailbox " + identity + ": " + ps.Members["User"].Value.ToString()); // Get the permissions that this user has PSObject multiValue = (PSObject)ps.Members["ExtendedRights"].Value; ArrayList accessRights = (ArrayList)multiValue.BaseObject; // Convert to string array string[] stringAccessRights = (string[])accessRights.ToArray(typeof(string)); // Fix the sAMAccountName by removing the domain name string sAMAccountName = ps.Members["User"].Value.ToString().Split('\\')[1]; // Check if it is full access or send as if (stringAccessRights.Contains("Send-As")) user.SendAsUsers.Add(sAMAccountName); } } } } } if (powershell.HadErrors) throw powershell.Streams.Error[0].Exception; // // // Get send-as permissions // // // this.logger.Debug("Getting send on behalf permissions for " + identity); user.SendOnBehalf = new List<string>(); return user; } catch (Exception ex) { this.logger.Error("Failed to get mailbox information for " + identity, ex); throw; } }
public void NewArchiveMailbox(UsersObject user) { try { this.logger.Debug("Creating new archive mailbox for " + user.UserPrincipalName); if (user.ArchivingEnabled && user.ArchivePlan > 0) { PSCommand cmd = new PSCommand(); cmd.AddCommand("Enable-Mailbox"); cmd.AddParameter("Identity", user.UserPrincipalName); cmd.AddParameter("Archive"); if (!string.IsNullOrEmpty(user.ArchiveDatabase)) cmd.AddParameter("ArchiveDatabase", user.ArchiveDatabase); if (!string.IsNullOrEmpty(user.ArchiveName)) cmd.AddParameter("ArchiveName", user.ArchiveName); cmd.AddParameter("Confirm", false); cmd.AddParameter("DomainController", domainController); powershell.Commands = cmd; Collection<PSObject> obj = powershell.Invoke(); if (powershell.HadErrors) throw powershell.Streams.Error[0].Exception; } else this.logger.Debug("Unable to create archive mailbox because the plan was not set for " + user.UserPrincipalName); } catch (Exception ex) { this.logger.Error("Failed to create new archive mailbox for " + user.UserPrincipalName, ex); throw; } }
public void UpdateMailbox(UsersObject user, MailboxPlanObject mailboxPlan) { try { this.logger.Debug("Updating mailbox for " + user.UserPrincipalName); PSCommand cmd = new PSCommand(); cmd.AddCommand("Set-Mailbox"); cmd.AddParameter("Identity", user.UserPrincipalName); cmd.AddParameter("CustomAttribute1", user.CompanyCode); cmd.AddParameter("DeliverToMailboxAndForward", user.DeliverToMailboxAndForward); cmd.AddParameter("HiddenFromAddressListsEnabled", user.MailboxHiddenFromGAL); cmd.AddParameter("IssueWarningQuota", mailboxPlan.WarningSizeInMB(user.SetMailboxSizeInMB)); cmd.AddParameter("ProhibitSendQuota", user.SetMailboxSizeInMB + "MB"); cmd.AddParameter("ProhibitSendReceiveQuota", user.SetMailboxSizeInMB + "MB"); cmd.AddParameter("MaxReceiveSize", mailboxPlan.MaxReceiveInKB + "KB"); cmd.AddParameter("MaxSendSize", mailboxPlan.MaxSendInKB + "KB"); cmd.AddParameter("RecipientLimits", mailboxPlan.MaxRecipients); cmd.AddParameter("RetainDeletedItemsFor", mailboxPlan.MaxKeepDeletedItemsInDays); cmd.AddParameter("RetainDeletedItemsUntilBackup", true); cmd.AddParameter("UseDatabaseQuotaDefaults", false); cmd.AddParameter("OfflineAddressBook", user.CompanyCode + " OAL"); List<string> emailAddresses = new List<string>(); emailAddresses.Add("SMTP:" + user.PrimarySmtpAddress); foreach (string e in user.EmailAliases) { if (e.StartsWith("sip:", StringComparison.CurrentCultureIgnoreCase)) emailAddresses.Add(e); else if (e.StartsWith("x500:", StringComparison.CurrentCultureIgnoreCase)) emailAddresses.Add(e); else if (e.StartsWith("x400:", StringComparison.CurrentCultureIgnoreCase)) emailAddresses.Add(e); else emailAddresses.Add("smtp:" + e); } cmd.AddParameter("EmailAddresses", emailAddresses.ToArray()); if (!string.IsNullOrEmpty(user.ForwardingTo)) cmd.AddParameter("ForwardingAddress", user.ForwardingTo); if (!string.IsNullOrEmpty(user.ThrottlingPolicy)) cmd.AddParameter("ThrottlingPolicy", user.ThrottlingPolicy); cmd.AddParameter("Confirm", false); cmd.AddParameter("DomainController", domainController); powershell.Commands = cmd; Collection<PSObject> obj = powershell.Invoke(); if (powershell.HadErrors) throw powershell.Streams.Error[0].Exception; } catch (Exception ex) { this.logger.Error("Failed to update mailbox for " + user.UserPrincipalName, ex); throw; } }
public void UpdateCASMailbox(UsersObject user, MailboxPlanObject mailboxPlan) { try { this.logger.Debug("Updating CAS mailbox for " + user.UserPrincipalName); PSCommand cmd = new PSCommand(); cmd.AddCommand("Set-CASMailbox"); cmd.AddParameter("Identity", user.UserPrincipalName); cmd.AddParameter("ActiveSyncEnabled", mailboxPlan.EnableAS); cmd.AddParameter("ECPEnabled", mailboxPlan.EnableECP); cmd.AddParameter("ImapEnabled", mailboxPlan.EnableIMAP); cmd.AddParameter("MAPIEnabled", mailboxPlan.EnableMAPI); cmd.AddParameter("OWAEnabled", mailboxPlan.EnableOWA); cmd.AddParameter("PopEnabled", mailboxPlan.EnablePOP3); // Email Addresses if (!string.IsNullOrEmpty(user.ActiveSyncName)) cmd.AddParameter("ActiveSyncMailboxPolicy", user.ActiveSyncName); else cmd.AddParameter("ActiveSyncMailboxPolicy", null); cmd.AddParameter("Confirm", false); cmd.AddParameter("DomainController", domainController); powershell.Commands = cmd; Collection<PSObject> obj = powershell.Invoke(); if (powershell.HadErrors) throw powershell.Streams.Error[0].Exception; } catch (Exception ex) { this.logger.Error("Failed to set CAS mailbox for " + user.UserPrincipalName, ex); throw; } }
private void SaveNewUser() { UsersObject newUser = new UsersObject(); newUser.CompanyCode = WebSessionHandler.SelectedCompanyCode; newUser.Firstname = txtFirstName.Text; newUser.Middlename = txtMiddleName.Text; newUser.Lastname = txtLastname.Text; newUser.DisplayName = txtDisplayName.Text; newUser.Department = txtDepartment.Text; newUser.UserPrincipalName = string.Format("{0}@{1}", txtLoginName.Text, ddlLoginDomain.SelectedItem.Text); newUser.Password = txtPassword1.Text; newUser.PasswordNeverExpires = cbPasswordNeverExpires.Checked; newUser.IsCompanyAdmin = cbCompanyAdmin.Checked; newUser.IsResellerAdmin = cbResellerAdmin.Checked; if (newUser.IsCompanyAdmin) { newUser.EnableExchangePerm = cbEnableExchange.Checked; newUser.DisableExchangePerm = cbDisableExchange.Checked; newUser.AddDomainPerm = cbAddDomain.Checked; newUser.DeleteDomainPerm = cbDeleteDomain.Checked; newUser.EnableAcceptedDomainPerm = cbEnableAcceptedDomain.Checked; newUser.DisableAcceptedDomainPerm = cbDisableAcceptedDomain.Checked; } UsersViewModel viewModel = new UsersViewModel(); viewModel.ViewModelEvent += viewModel_ViewModelEvent; // Create new user viewModel.CreateUser(newUser); // Audit AuditGlobal.AddAudit(WebSessionHandler.SelectedCompanyCode, HttpContext.Current.User.Identity.Name, ActionID.CreateUser, newUser.UserPrincipalName, null); // Refresh PopulateUsersListView(); }
internal void UpdateExchangeSection() { object userObject = ViewState["CPCurrentEditUser"]; object mailboxObject = ViewState["CPCurrentEditMailbox"]; if (userObject == null) alertmessage.SetMessage(AlertID.FAILED, "Viewstate was null. Please contact support"); else { UsersViewModel viewModel = new UsersViewModel(); viewModel.ViewModelEvent += viewModel_ViewModelEvent; UsersObject user = userObject as UsersObject; if (!cbEditIsMailboxEnabled.Checked && user.MailboxPlan > 0) { // // We are disabling the mailbox for this user // viewModel.DisableMailbox(user.UserPrincipalName); } else if (cbEditIsMailboxEnabled.Checked && user.MailboxPlan == 0) { // // We are creating a new mailbox // this.logger.Debug("Attempting to create new mailbox for " + user.UserPrincipalName); user = new UsersObject(); user.CompanyCode = WebSessionHandler.SelectedCompanyCode; user.UserPrincipalName = hfEditUserPrincipalName.Value; user.PrimarySmtpAddress = string.Format("{0}@{1}", txtEditMailboxEmail.Text.Replace(" ", string.Empty), ddlEditMailboxDomain.SelectedItem.Text); user.ActiveSyncPlan = ddlEditMailboxASPlan.SelectedIndex > 0 ? int.Parse(ddlEditMailboxASPlan.SelectedValue) : 0; user.MailboxPlan = int.Parse(ddlEditMailboxPlan.SelectedValue); user.SetMailboxSizeInMB = int.Parse(hfEditSelectedMailboxSize.Value); user.ForwardingTo = ddlEditMailboxForwardTo.SelectedIndex > 0 ? ddlEditMailboxForwardTo.SelectedValue : string.Empty; user.DeliverToMailboxAndForward = cbEditMailboxForwardBoth.Checked; this.logger.Debug("Validating email addresses for " + user.UserPrincipalName); user.EmailAliases = new List<string>(); if (emailAliases != null) { foreach (MailAliasObject a in emailAliases) { if (!a.Email.Equals(user.PrimarySmtpAddress)) user.EmailAliases.Add(a.Email); } } this.logger.Debug("Validating access permissions for " + user.UserPrincipalName); user.FullAccessUsers = new List<string>(); foreach (int i in ddlEditMailboxFullAccess.GetSelectedIndices()) user.FullAccessUsers.Add(ddlEditMailboxFullAccess.Items[i].Value); user.SendAsUsers = new List<string>(); foreach (int i in ddlEditMailboxSendAs.GetSelectedIndices()) user.SendAsUsers.Add(ddlEditMailboxSendAs.Items[i].Value); user.SendOnBehalf = new List<string>(); foreach (int i in ddlEditMailboxSendOnBehalf.GetSelectedIndices()) user.SendOnBehalf.Add(ddlEditMailboxSendOnBehalf.Items[i].Value); // // Archiving // this.logger.Debug("Validating archiving settings for " + user.UserPrincipalName); if (cbEditMailboxEnableArchiving.Checked) { user.ArchivingEnabled = cbEditMailboxEnableArchiving.Checked; user.ArchiveName = txtEditMailboxArchiveName.Text.Trim(); user.ArchivePlan = ddlEditMailboxArchivePlan.SelectedIndex > 0 ? int.Parse(ddlEditMailboxArchivePlan.SelectedValue) : 0; } else user.ArchivingEnabled = false; // // Litigation Hold // this.logger.Debug("Validating litigation hold settings for " + user.UserPrincipalName); if (cbEditMailboxEnableLitigationHold.Checked) { user.LitigationHoldEnabled = cbEditMailboxEnableLitigationHold.Checked; user.LitigationHoldUrl = txtEditMailboxLitigationHoldURL.Text; user.LitigationHoldComment = txtEditMailboxLitigationHoldComments.Text; if (!string.IsNullOrEmpty(txtEditMailboxLitigationHoldDuration.Text)) { DateTime now = DateTime.Now; DateTime end; DateTime.TryParse(txtEditMailboxLitigationHoldDuration.Text, out end); if (end != null) { TimeSpan duration = end - now; user.LitigationHoldDuration = duration.Days; } else user.LitigationHoldDuration = 0; } else user.LitigationHoldDuration = 0; } viewModel.CreateMailbox(user); } else { // // We are updating an existing mailbox // } } }
internal void UpdateUserSection() { object userObject = ViewState["CPCurrentEditUser"]; if (userObject == null) alertmessage.SetMessage(AlertID.FAILED, "Viewstate was null. Please contact support"); else { UsersObject original = userObject as UsersObject; bool valuesHaveBeenUpdated = false; if (txtEditFirstName.Text != original.Firstname) { valuesHaveBeenUpdated = true; this.logger.Debug(string.Format("{0}: Found new value. Old Value: {0}, New Value: {1}", original.UserPrincipalName, original.Firstname, txtEditFirstName.Text)); } if (txtEditMiddleName.Text != original.Middlename) { valuesHaveBeenUpdated = true; this.logger.Debug(string.Format("{0}: Found new value. Old Value: {0}, New Value: {1}", original.UserPrincipalName, original.Middlename, txtEditMiddleName.Text)); } if (txtEditLastname.Text != original.Lastname) { valuesHaveBeenUpdated = true; this.logger.Debug(string.Format("{0}: Found new value. Old Value: {0}, New Value: {1}", original.UserPrincipalName, original.Lastname, txtEditLastname.Text)); } if (txtEditDisplayName.Text != original.DisplayName) { valuesHaveBeenUpdated = true; this.logger.Debug(string.Format("{0}: Found new value. Old Value: {0}, New Value: {1}", original.UserPrincipalName, original.DisplayName, txtEditDisplayName.Text)); } if (txtEditDepartment.Text != original.Department) { valuesHaveBeenUpdated = true; this.logger.Debug(string.Format("{0}: Found new value. Old Value: {0}, New Value: {1}", original.UserPrincipalName, original.Department, txtEditDepartment.Text)); } if (cbEditEnableUser.Checked != original.IsEnabled) valuesHaveBeenUpdated = true; // Only update these if reseller or super admin if (WebSessionHandler.IsSuperAdmin || WebSessionHandler.IsResellerAdmin) { if (cbEditIsCompanyAdmin.Checked != original.IsCompanyAdmin) valuesHaveBeenUpdated = true; if (cbEditEnableExchange.Checked != original.EnableExchangePerm) valuesHaveBeenUpdated = true; if (cbEditDisableExchange.Checked != original.DisableExchangePerm) valuesHaveBeenUpdated = true; if (cbEditAddDomain.Checked != original.AddDomainPerm) valuesHaveBeenUpdated = true; if (cbEditDeleteDomain.Checked != original.DeleteDomainPerm) valuesHaveBeenUpdated = true; if (cbEditEnableAcceptedDomain.Checked != original.EnableAcceptedDomainPerm) valuesHaveBeenUpdated = true; if (cbEditDisableAcceptedDomain.Checked != original.DisableAcceptedDomainPerm) valuesHaveBeenUpdated = true; if (WebSessionHandler.IsSuperAdmin) { if (cbEditIsResellerAdmin.Checked != original.IsResellerAdmin) valuesHaveBeenUpdated = true; } } // Update user if values have changed if (valuesHaveBeenUpdated) { UsersObject updateUser = new UsersObject(); updateUser.UserPrincipalName = hfEditUserPrincipalName.Value; updateUser.Firstname = txtEditFirstName.Text; updateUser.Middlename = txtEditMiddleName.Text; updateUser.Lastname = txtEditLastname.Text; updateUser.DisplayName = txtEditDisplayName.Text; updateUser.Department = txtEditDepartment.Text; updateUser.IsEnabled = cbEditEnableUser.Checked; updateUser.IsResellerAdmin = cbEditIsResellerAdmin.Checked; updateUser.IsCompanyAdmin = cbEditIsCompanyAdmin.Checked; updateUser.EnableExchangePerm = cbEditEnableExchange.Checked; updateUser.DisableExchangePerm = cbEditDisableExchange.Checked; updateUser.AddDomainPerm = cbEditAddDomain.Checked; updateUser.DeleteDomainPerm = cbEditDeleteDomain.Checked; updateUser.EnableAcceptedDomainPerm = cbEditEnableAcceptedDomain.Checked; updateUser.DisableAcceptedDomainPerm = cbEditDisableAcceptedDomain.Checked; UsersViewModel viewModel = new UsersViewModel(); viewModel.ViewModelEvent += viewModel_ViewModelEvent; viewModel.UpdateUser(updateUser, WebSessionHandler.IsSuperAdmin || WebSessionHandler.IsResellerAdmin); } } }