/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution/Exchange2007.cs
C# | 7163 lines | 6511 code | 455 blank | 197 comment | 183 complexity | 06e8d02eae888fefb18868e0196b6ba6 MD5 | raw file
Possible License(s): BSD-3-Clause, Unlicense, MPL-2.0-no-copyleft-exception, LGPL-2.0
Large files files are truncated, but you can click here to view the full file
- // Copyright (c) 2015, Outercurve Foundation.
- // All rights reserved.
- //
- // Redistribution and use in source and binary forms, with or without modification,
- // are permitted provided that the following conditions are met:
- //
- // - Redistributions of source code must retain the above copyright notice, this
- // list of conditions and the following disclaimer.
- //
- // - Redistributions in binary form must reproduce the above copyright notice,
- // this list of conditions and the following disclaimer in the documentation
- // and/or other materials provided with the distribution.
- //
- // - Neither the name of the Outercurve Foundation nor the names of its
- // contributors may be used to endorse or promote products derived from this
- // software without specific prior written permission.
- //
- // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
- // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
- // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- using System;
- using System.IO;
- using System.Collections;
- using System.Collections.Generic;
- using System.Collections.ObjectModel;
- using System.Text;
- using System.Reflection;
- using System.Globalization;
- using System.Configuration;
- using System.DirectoryServices;
- using System.Security;
- using System.Security.Principal;
- using System.Security.AccessControl;
-
- using System.Management.Automation;
- using System.Management.Automation.Runspaces;
-
- using WebsitePanel.Providers;
- using WebsitePanel.Providers.Common;
- using WebsitePanel.Providers.HostedSolution;
- using WebsitePanel.Providers.Utils;
- using WebsitePanel.Server.Utils;
- using WebsitePanel.Providers.ResultObjects;
- using Microsoft.Exchange.Data.Directory.Recipient;
- using Microsoft.Win32;
-
- using Microsoft.Exchange.Data;
- using Microsoft.Exchange.Data.Directory;
- using Microsoft.Exchange.Data.Storage;
-
- namespace WebsitePanel.Providers.HostedSolution
- {
- public class Exchange2007 : HostingServiceProviderBase, IExchangeServer
- {
- #region Static constructor
- static Exchange2007()
- {
- AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(ResolveExchangeAssembly);
- ExchangeRegistryPath = "SOFTWARE\\Microsoft\\Exchange\\Setup";
- }
- #endregion
-
- #region Constants
- private const string CONFIG_CLEAR_QUERYBASEDN = "WebsitePanel.Exchange.ClearQueryBaseDN";
- #endregion
-
- #region Properties
-
- internal string RootOU
- {
- get { return ProviderSettings["RootOU"]; }
- }
-
- internal string StorageGroup
- {
- get { return ProviderSettings["StorageGroup"]; }
- }
-
- internal string MailboxDatabase
- {
- get { return ProviderSettings["MailboxDatabase"]; }
- }
-
- internal bool PublicFolderDistributionEnabled
- {
- get { return ProviderSettings.GetBool("PublicFolderDistributionEnabled"); }
- }
-
- internal int KeepDeletedItemsDays
- {
- get { return Int32.Parse(ProviderSettings["KeepDeletedItemsDays"]); }
- }
-
- internal int KeepDeletedMailboxesDays
- {
- get { return Int32.Parse(ProviderSettings["KeepDeletedMailboxesDays"]); }
- }
-
- internal string RootDomain
- {
- get { return ServerSettings.ADRootDomain; }
- }
-
- internal string MailboxCluster
- {
- get { return ProviderSettings["MailboxCluster"]; }
- }
-
- internal string PrimaryDomainController
- {
- get { return ProviderSettings["PrimaryDomainController"]; }
- }
-
- internal string PublicFolderServer
- {
- get { return ProviderSettings["PublicFolderServer"]; }
- }
-
- internal string OABGenerationServer
- {
- get { return ProviderSettings["OABServer"]; }
- }
-
- internal static string ExchangeRegistryPath
- {
- get;
- set;
- }
-
- internal virtual string ExchangeSnapInName
- {
- get { return "Microsoft.Exchange.Management.PowerShell.Admin"; }
- }
-
- #endregion
-
- #region IExchangeServer Members
-
- #region Common
- public bool CheckAccountCredentials(string username, string password)
- {
- return CheckAccountCredentialsInternal(username, password);
- }
- #endregion
-
- #region Organizations
-
- /// <summary>
- /// Extend existing organization with exchange functionality
- /// </summary>
- /// <param name="organizationId"></param>
- /// <param name="securityGroup"></param>
- /// <returns></returns>
- public Organization ExtendToExchangeOrganization(string organizationId, string securityGroup, bool IsConsumer)
- {
- return ExtendToExchangeOrganizationInternal(organizationId, securityGroup, IsConsumer);
- }
-
- /// <summary>
- /// Creates organization OAB on the Client Access Server
- /// </summary>
- /// <param name="organizationId"></param>
- /// <param name="securityGroup"></param>
- /// <returns></returns>
- public Organization CreateOrganizationOfflineAddressBook(string organizationId, string securityGroup, string oabVirtualDir)
- {
- return CreateOrganizationOfflineAddressBookInternal(organizationId, securityGroup, oabVirtualDir);
- }
-
- /// <summary>
- /// Updates organization OAB
- /// </summary>
- /// <param name="oabId"></param>
- public void UpdateOrganizationOfflineAddressBook(string oabId)
- {
- UpdateOrganizationOfflineAddressBookInternal(oabId);
- }
-
-
- public string GetOABVirtualDirectory()
- {
- return GetOABVirtualDirectoryInternal();
- }
-
- public Organization CreateOrganizationAddressBookPolicy(string organizationId, string gal, string addressBook, string roomList, string oab)
- {
- return CreateOrganizationAddressBookPolicyInternal(organizationId, gal, addressBook, roomList, oab);
- }
-
- public bool DeleteOrganization(string organizationId, string distinguishedName,
- string globalAddressList, string addressList, string roomList, string offlineAddressBook,
- string securityGroup, string addressBookPolicy, List<ExchangeDomainName> acceptedDomains)
- {
- return DeleteOrganizationInternal(organizationId, distinguishedName, globalAddressList,
- addressList, roomList, offlineAddressBook, securityGroup, addressBookPolicy, acceptedDomains);
- }
-
- public void SetOrganizationStorageLimits(string organizationDistinguishedName, long issueWarningKB, long prohibitSendKB,
- long prohibitSendReceiveKB, int keepDeletedItemsDays)
- {
- SetOrganizationStorageLimitsInternal(organizationDistinguishedName, issueWarningKB, prohibitSendKB,
- prohibitSendReceiveKB, keepDeletedItemsDays);
- }
-
- public ExchangeItemStatistics[] GetMailboxesStatistics(string organizationDistinguishedName)
- {
- return GetMailboxesStatisticsInternal(organizationDistinguishedName);
- }
- #endregion
-
- #region Domains
-
- public string[] GetAuthoritativeDomains()
- {
- return GetAuthoritativeDomainsInternal();
- }
-
- public void AddAuthoritativeDomain(string domain)
- {
- CreateAuthoritativeDomainInternal(domain);
- }
-
- public void DeleteAuthoritativeDomain(string domain)
- {
- DeleteAuthoritativeDomainInternal(domain);
- }
-
- public void ChangeAcceptedDomainType(string domainName, ExchangeAcceptedDomainType domainType)
- {
- ChangeAcceptedDomainTypeInternal(domainName, domainType);
- }
- #endregion
-
- #region Mailboxes
-
- public ExchangeMailbox GetMailboxPermissions(string organizationId, string accountName)
- {
- return GetMailboxPermissionsInternal(organizationId, accountName, null);
- }
-
- public void SetMailboxPermissions(string organizationId, string accountName, string[] sendAsAccounts, string[] fullAccessAccounts)
- {
- SetMailboxPermissionsInternal(organizationId, accountName, sendAsAccounts, fullAccessAccounts);
- }
-
- public void DeleteMailbox(string accountName)
- {
- DeleteMailboxInternal(accountName);
- }
-
- public ExchangeMailbox GetMailboxGeneralSettings(string accountName)
- {
- return GetMailboxGeneralSettingsInternal(accountName);
- }
-
- public void SetMailboxGeneralSettings(string accountName, bool hideFromAddressBook, bool disabled)
- {
- SetMailboxGeneralSettingsInternal(accountName, hideFromAddressBook, disabled);
- }
-
- public ExchangeMailbox GetMailboxMailFlowSettings(string accountName)
- {
- return GetMailboxMailFlowSettingsInternal(accountName);
- }
-
- public void SetMailboxMailFlowSettings(string accountName, bool enableForwarding,
- string forwardingAccountName, bool forwardToBoth, string[] sendOnBehalfAccounts,
- string[] acceptAccounts, string[] rejectAccounts, bool requireSenderAuthentication)
- {
- SetMailboxMailFlowSettingsInternal(accountName, enableForwarding, forwardingAccountName,
- forwardToBoth, sendOnBehalfAccounts, acceptAccounts, rejectAccounts, requireSenderAuthentication);
- }
-
- public ExchangeMailbox GetMailboxAdvancedSettings(string accountName)
- {
- return GetMailboxAdvancedSettingsInternal(accountName);
- }
-
- public void SetMailboxAdvancedSettings(string organizationId, string accountName, bool enablePOP,
- bool enableIMAP, bool enableOWA, bool enableMAPI, bool enableActiveSync,
- long issueWarningKB, long prohibitSendKB, long prohibitSendReceiveKB, int keepDeletedItemsDays, int maxRecipients, int maxSendMessageSizeKB,
- int maxReceiveMessageSizeKB, bool enabledLitigationHold, long recoverabelItemsSpace, long recoverabelItemsWarning, string litigationHoldUrl, string litigationHoldMsg)
- {
- SetMailboxAdvancedSettingsInternal(organizationId, accountName, enablePOP, enableIMAP, enableOWA,
- enableMAPI, enableActiveSync, issueWarningKB,
- prohibitSendKB, prohibitSendReceiveKB, keepDeletedItemsDays, maxRecipients, maxSendMessageSizeKB, maxReceiveMessageSizeKB,
- enabledLitigationHold, recoverabelItemsSpace, recoverabelItemsWarning, litigationHoldUrl, litigationHoldMsg );
- }
-
- public ExchangeEmailAddress[] GetMailboxEmailAddresses(string accountName)
- {
- return GetMailboxEmailAddressesInternal(accountName);
- }
-
- public void SetMailboxEmailAddresses(string accountName, string[] emailAddresses)
- {
- SetMailboxEmailAddressesInternal(accountName, emailAddresses);
- }
-
- public void SetMailboxPrimaryEmailAddress(string accountName, string emailAddress)
- {
- SetMailboxPrimaryEmailAddressInternal(accountName, emailAddress);
- }
-
- public ExchangeMailboxStatistics GetMailboxStatistics(string id)
- {
- return GetMailboxStatisticsInternal(id);
- }
- #endregion
-
- #region Contacts
- public void CreateContact(string organizationId, string organizationDistinguishedName,
- string contactDisplayName, string contactAccountName, string contactEmail, string defaultOrganizationDomain)
- {
- CreateContactInternal(organizationId, organizationDistinguishedName, contactDisplayName,
- contactAccountName, contactEmail, defaultOrganizationDomain);
- }
-
- public void DeleteContact(string accountName)
- {
- DeleteContactInternal(accountName);
- }
-
- public ExchangeContact GetContactGeneralSettings(string accountName)
- {
- return GetContactGeneralSettingsInternal(accountName);
- }
-
- public void SetContactGeneralSettings(string accountName, string displayName, string email,
- bool hideFromAddressBook, string firstName, string initials, string lastName, string address,
- string city, string state, string zip, string country, string jobTitle, string company,
- string department, string office, string managerAccountName, string businessPhone, string fax,
- string homePhone, string mobilePhone, string pager, string webPage, string notes, int useMapiRichTextFormat, string defaultOrganizationDomain)
- {
- SetContactGeneralSettingsInternal(accountName, displayName, email, hideFromAddressBook,
- firstName, initials, lastName, address, city, state, zip, country, jobTitle,
- company, department, office, managerAccountName, businessPhone, fax, homePhone,
- mobilePhone, pager, webPage, notes, useMapiRichTextFormat, defaultOrganizationDomain);
- }
-
- public ExchangeContact GetContactMailFlowSettings(string accountName)
- {
- return GetContactMailFlowSettingsInternal(accountName);
- }
-
- public void SetContactMailFlowSettings(string accountName, string[] acceptAccounts, string[] rejectAccounts, bool requireSenderAuthentication)
- {
- SetContactMailFlowSettingsInternal(accountName, acceptAccounts, rejectAccounts, requireSenderAuthentication);
- }
- #endregion
-
- #region Distribution lists
- public void CreateDistributionList(string organizationId, string organizationDistinguishedName,
- string displayName, string accountName, string name, string domain, string managedBy, string[] addressLists)
- {
- CreateDistributionListInternal(organizationId, organizationDistinguishedName, displayName,
- accountName, name, domain, managedBy, addressLists);
- }
-
- public void DeleteDistributionList(string accountName)
- {
- DeleteDistributionListInternal(accountName);
- }
-
- public ExchangeDistributionList GetDistributionListGeneralSettings(string accountName)
- {
- return GetDistributionListGeneralSettingsInternal(accountName);
- }
-
- public void SetDistributionListGeneralSettings(string accountName, string displayName,
- bool hideFromAddressBook, string managedBy, string[] members, string notes, string[] addressLists)
- {
- SetDistributionListGeneralSettingsInternal(accountName, displayName, hideFromAddressBook,
- managedBy, members, notes, addressLists);
- }
-
- public void AddDistributionListMembers(string accountName, string[] memberAccounts, string[] addressLists)
- {
- AddDistributionListMembersInternal(accountName, memberAccounts, addressLists);
- }
-
-
- public void RemoveDistributionListMembers(string accountName, string[] memberAccounts, string[] addressLists)
- {
- RemoveDistributionListMembersInternal(accountName, memberAccounts, addressLists);
- }
-
- public ExchangeDistributionList GetDistributionListMailFlowSettings(string accountName)
- {
- return GetDistributionListMailFlowSettingsInternal(accountName);
- }
-
- public void SetDistributionListMailFlowSettings(string accountName, string[] acceptAccounts,
- string[] rejectAccounts, bool requireSenderAuthentication, string[] addressLists)
- {
- SetDistributionListMailFlowSettingsInternal(accountName, acceptAccounts, rejectAccounts, requireSenderAuthentication, addressLists);
- }
-
- public ExchangeEmailAddress[] GetDistributionListEmailAddresses(string accountName)
- {
- return GetDistributionListEmailAddressesInternal(accountName);
- }
-
- public void SetDistributionListEmailAddresses(string accountName, string[] emailAddresses, string[] addressLists)
- {
- SetDistributionListEmailAddressesInternal(accountName, emailAddresses, addressLists);
- }
-
- public void SetDistributionListPrimaryEmailAddress(string accountName, string emailAddress, string[] addressLists)
- {
- SetDistributionListPrimaryEmailAddressInternal(accountName, emailAddress, addressLists);
- }
-
- public ExchangeDistributionList GetDistributionListPermissions(string organizationId, string accountName)
- {
- return GetDistributionListPermissionsInternal(organizationId, accountName, null);
- }
-
- public void SetDistributionListPermissions(string organizationId, string accountName, string[] sendAsAccounts, string[] sendOnBehalfAccounts, string[] addressLists)
- {
- SetDistributionListPermissionsInternal(organizationId, accountName, sendAsAccounts, sendOnBehalfAccounts, addressLists);
- }
- #endregion
-
- #region Public folders
- public void CreatePublicFolder(string organizationDistinguishedName, string organizationId, string securityGroup, string parentFolder,
- string folderName, bool mailEnabled, string accountName, string name, string domain)
- {
- CreatePublicFolderInternal(organizationId, securityGroup, parentFolder, folderName,
- mailEnabled, accountName, name, domain);
- }
-
- public void DeletePublicFolder(string organizationId, string folder)
- {
- DeletePublicFolderInternal(folder);
- }
-
- public void EnableMailPublicFolder(string organizationId, string folder, string accountName,
- string name, string domain)
- {
- EnableMailPublicFolderInternal(organizationId, folder, accountName, name, domain);
- }
-
- public void DisableMailbox(string id)
- {
- DisableMailboxInternal(id);
- }
-
- internal virtual void DisableMailboxInternal(string id)
- {
- ExchangeLog.LogStart("DisableMailboxIntenal");
- Runspace runSpace = null;
- try
- {
- runSpace = OpenRunspace();
-
- RemoveDevicesInternal(runSpace, id);
-
- Command cmd = new Command("Disable-Mailbox");
- cmd.Parameters.Add("Identity", id);
- cmd.Parameters.Add("Confirm", false);
- ExecuteShellCommand(runSpace, cmd);
- }
-
- finally
- {
-
- CloseRunspace(runSpace);
- }
- ExchangeLog.LogEnd("DisableMailboxIntenal");
- }
- public void DisableMailPublicFolder(string organizationId, string folder)
- {
- DisableMailPublicFolderInternal(folder);
- }
-
- public ExchangePublicFolder GetPublicFolderGeneralSettings(string organizationId, string folder)
- {
- return GetPublicFolderGeneralSettingsInternal(folder);
- }
-
- public void SetPublicFolderGeneralSettings(string organizationId, string folder, string newFolderName,
- bool hideFromAddressBook, ExchangeAccount[] accounts)
- {
- SetPublicFolderGeneralSettingsInternal(folder, newFolderName, hideFromAddressBook, accounts);
- }
- public ExchangePublicFolder GetPublicFolderMailFlowSettings(string organizationId, string folder)
- {
- return GetPublicFolderMailFlowSettingsInternal(folder);
- }
-
- public void SetPublicFolderMailFlowSettings(string organizationId, string folder,
- string[] acceptAccounts, string[] rejectAccounts, bool requireSenderAuthentication)
- {
- SetPublicFolderMailFlowSettingsInternal(folder, acceptAccounts, rejectAccounts, requireSenderAuthentication);
- }
-
- public ExchangeEmailAddress[] GetPublicFolderEmailAddresses(string organizationId, string folder)
- {
- return GetPublicFolderEmailAddressesInternal(folder);
- }
-
- public void SetPublicFolderEmailAddresses(string organizationId, string folder, string[] emailAddresses)
- {
- SetPublicFolderEmailAddressesInternal(folder, emailAddresses);
- }
-
- public void SetPublicFolderPrimaryEmailAddress(string organizationId, string folder, string emailAddress)
- {
- SetPublicFolderPrimaryEmailAddressInternal(folder, emailAddress);
- }
-
- public ExchangeItemStatistics[] GetPublicFoldersStatistics(string organizationId, string[] folders)
- {
- return GetPublicFoldersStatisticsInternal(folders);
- }
-
- public string[] GetPublicFoldersRecursive(string organizationId, string parent)
- {
- return GetPublicFoldersRecursiveInternal(parent);
- }
-
- public long GetPublicFolderSize(string organizationId, string folder)
- {
- return GetPublicFolderSizeInternal(folder);
- }
- #endregion
-
- #region ActiveSync
- public void CreateOrganizationActiveSyncPolicy(string organizationId)
- {
- CreateOrganizationActiveSyncPolicyInternal(organizationId);
- }
-
-
- public ExchangeActiveSyncPolicy GetActiveSyncPolicy(string organizationId)
- {
- return GetActiveSyncPolicyInternal(organizationId);
- }
-
- public void SetActiveSyncPolicy(string id, bool allowNonProvisionableDevices, bool attachmentsEnabled,
- int maxAttachmentSizeKB, bool uncAccessEnabled, bool wssAccessEnabled, bool devicePasswordEnabled,
- bool alphanumericPasswordRequired, bool passwordRecoveryEnabled, bool deviceEncryptionEnabled,
- bool allowSimplePassword, int maxPasswordFailedAttempts, int minPasswordLength, int inactivityLockMin,
- int passwordExpirationDays, int passwordHistory, int refreshInterval)
- {
- SetActiveSyncPolicyInternal(id, allowNonProvisionableDevices, attachmentsEnabled,
- maxAttachmentSizeKB, uncAccessEnabled, wssAccessEnabled,
- devicePasswordEnabled, alphanumericPasswordRequired, passwordRecoveryEnabled,
- deviceEncryptionEnabled, allowSimplePassword, maxPasswordFailedAttempts,
- minPasswordLength, inactivityLockMin, passwordExpirationDays, passwordHistory, refreshInterval);
- }
- #endregion
-
- #region Mobile devices
- public ExchangeMobileDevice[] GetMobileDevices(string accountName)
- {
- return GetMobileDevicesInternal(accountName);
- }
- public ExchangeMobileDevice GetMobileDevice(string id)
- {
- return GetMobileDeviceInternal(id);
- }
- public void WipeDataFromDevice(string id)
- {
- WipeDataFromDeviceInternal(id);
- }
- public void CancelRemoteWipeRequest(string id)
- {
- CancelRemoteWipeRequestInternal(id);
- }
- public void RemoveDevice(string id)
- {
- RemoveDeviceInternal(id);
- }
- #endregion
-
- #endregion
-
- #region IHostingServiceProvider Members
-
- public override void ChangeServiceItemsState(ServiceProviderItem[] items, bool enabled)
- {
- foreach (ServiceProviderItem item in items)
- {
- if (item is Organization)
- {
- try
- {
- // make E2K7 mailboxes disabled
- Organization org = item as Organization;
- ChangeOrganizationState(org.DistinguishedName, enabled);
- }
- catch (Exception ex)
- {
- Log.WriteError(String.Format("Error switching '{0}' {1}", item.Name, item.GetType().Name), ex);
- }
- }
- }
- }
-
- public override void DeleteServiceItems(ServiceProviderItem[] items)
- {
- foreach (ServiceProviderItem item in items)
- {
- try
- {
- if (item is Organization)
- {
- Organization org = item as Organization;
- DeleteOrganization(org.OrganizationId, org.DistinguishedName, org.GlobalAddressList,
- org.AddressList, org.RoomsAddressList, org.OfflineAddressBook, org.SecurityGroup, org.AddressBookPolicy, null);
- }
- else if (item is ExchangeDomain)
- {
- DeleteAcceptedDomain(null, item.Name);
- }
- }
- catch (Exception ex)
- {
- Log.WriteError(String.Format("Error deleting '{0}' {1}", item.Name, item.GetType().Name), ex);
- }
- }
- }
-
- public override ServiceProviderItemDiskSpace[] GetServiceItemsDiskSpace(ServiceProviderItem[] items)
- {
- List<ServiceProviderItemDiskSpace> itemsDiskspace = new List<ServiceProviderItemDiskSpace>();
-
- // update items with diskspace
- foreach (ServiceProviderItem item in items)
- {
- if (item is Organization)
- {
- try
- {
- Log.WriteStart(String.Format("Calculating '{0}' disk space", item.Name));
- Organization org = item as Organization;
- // calculate disk space
- ServiceProviderItemDiskSpace diskspace = new ServiceProviderItemDiskSpace();
- diskspace.ItemId = item.Id;
- diskspace.DiskSpace = CalculateOrganizationDiskSpace(org.OrganizationId, org.DistinguishedName);
- itemsDiskspace.Add(diskspace);
-
- Log.WriteEnd(String.Format("Calculating '{0}' disk space", item.Name));
- }
- catch (Exception ex)
- {
- Log.WriteError(String.Format("Error calculating '{0}' Exchange organization disk space", item.Name), ex);
- }
- }
- }
-
- return itemsDiskspace.ToArray();
- }
-
- #endregion
-
- #region Common
- private bool CheckAccountCredentialsInternal(string username, string password)
- {
- try
- {
- string path = ConvertDomainName(RootDomain);
- DirectoryEntry entry = new DirectoryEntry(path, username, password);
- //Bind to the native AdsObject to force authentication.
- object obj = entry.NativeObject;
-
- DirectorySearcher search = new DirectorySearcher(entry);
-
- search.Filter = string.Format("(userPrincipalName={0})", username);
- search.PropertiesToLoad.Add("cn");
- SearchResult result = search.FindOne();
-
- if (result == null)
- {
- return false;
- }
-
- //Update the new path to the user in the directory.
- path = result.Path;
- string filterAttribute = (string)result.Properties["cn"][0];
- }
- catch (Exception)
- {
- return false;
- //throw new Exception("Error authenticating user. " + ex.Message);
- }
- return true;
- }
- #endregion
-
- #region Organizations
-
- /// <summary>
- /// Creates organization on Mail Server
- /// </summary>
- /// <param name="organizationId"></param>
- /// <returns></returns>
- internal virtual Organization ExtendToExchangeOrganizationInternal(string organizationId, string securityGroup, bool IsConsumer)
- {
- ExchangeLog.LogStart("CreateOrganizationInternal");
- ExchangeLog.DebugInfo(" Organization Id: {0}", organizationId);
-
- ExchangeTransaction transaction = StartTransaction();
- Organization info = new Organization();
- Runspace runSpace = null;
- try
- {
- runSpace = OpenRunspace();
-
- string server = GetServerName();
- string securityGroupPath = AddADPrefix(securityGroup);
-
- //Create mail enabled organization security group
- EnableMailSecurityDistributionGroup(runSpace, securityGroup, organizationId);
- transaction.RegisterMailEnabledDistributionGroup(securityGroup);
- UpdateSecurityDistributionGroup(runSpace, securityGroup, organizationId, IsConsumer);
-
- //create GAL
- string galId = CreateGlobalAddressList(runSpace, organizationId);
- transaction.RegisterNewGlobalAddressList(galId);
- ExchangeLog.LogInfo(" Global Address List: {0}", galId);
- UpdateGlobalAddressList(runSpace, galId, securityGroupPath);
-
- //create AL
- string alId = CreateAddressList(runSpace, organizationId);
- transaction.RegisterNewAddressList(alId);
- ExchangeLog.LogInfo(" Address List: {0}", alId);
- UpdateAddressList(runSpace, alId, securityGroupPath);
-
- //create RAL
- string ralId = CreateRoomsAddressList(runSpace, organizationId);
- transaction.RegisterNewRoomsAddressList(ralId);
- ExchangeLog.LogInfo(" Rooms Address List: {0}", ralId);
- UpdateAddressList(runSpace, ralId, securityGroupPath);
-
- //create ActiveSync policy
- string asId = CreateActiveSyncPolicy(runSpace, organizationId);
- transaction.RegisterNewActiveSyncPolicy(asId);
- ExchangeLog.LogInfo(" ActiveSync Policy: {0}", asId);
-
- //storage group
- string storageGroupId = CreateStorageGroup(runSpace, StorageGroup, server);
- ExchangeLog.LogInfo(" Storage Group: {0}", storageGroupId);
-
- //mailbox database
- string databaseId = CreateMailboxDatabase(runSpace, MailboxDatabase, storageGroupId);
- ExchangeLog.LogInfo(" Database: {0}", databaseId);
-
- info.AddressList = alId;
- info.GlobalAddressList = galId;
- info.RoomsAddressList = ralId;
- info.OrganizationId = organizationId;
- info.Database = databaseId;
-
- }
- catch (Exception ex)
- {
- ExchangeLog.LogError("CreateOrganizationInternal", ex);
- RollbackTransaction(transaction);
- throw;
- }
- finally
- {
-
- CloseRunspace(runSpace);
- }
- ExchangeLog.LogEnd("CreateOrganizationInternal");
- return info;
- }
-
- private void CheckServiceSettings()
- {
- if (!ServerSettings.ADEnabled)
- throw new Exception("Active Directory is not enabled. Check server settings.");
- if (string.IsNullOrEmpty(RootDomain))
- throw new Exception("Active Directory root domain is not specified. Check server settings.");
- if (string.IsNullOrEmpty(RootOU))
- throw new Exception("Active Directory root organizational unit is not specified. Check provider settings.");
- if (string.IsNullOrEmpty(PrimaryDomainController))
- throw new Exception("Primary Domain Controller is not specified. Check provider settings.");
- }
-
- private string GetOABVirtualDirectoryInternal()
- {
- ExchangeLog.LogStart("GetOABVirtualDirectoryInternal");
- Runspace runSpace = null;
- string virtualDir = null;
- try
- {
- runSpace = OpenRunspace();
-
-
- string server = GetServerName();
- Command cmd = new Command("Get-OabVirtualDirectory");
- cmd.Parameters.Add("Server", server);
-
- Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
-
- if (result.Count > 0)
- {
- virtualDir = ObjToString(GetPSObjectProperty(result[0], "Identity"));
- }
- }
- finally
- {
-
- CloseRunspace(runSpace);
- }
- ExchangeLog.LogEnd("GetOABVirtualDirectoryInternal");
- return virtualDir;
- }
-
- private Organization CreateOrganizationOfflineAddressBookInternal(string organizationId, string securityGroup, string oabVirtualDir)
- {
- ExchangeLog.LogStart("CreateOrganizationOfflineAddressBookInternal");
- ExchangeLog.LogInfo(" Organization Id: {0}", organizationId);
- ExchangeLog.LogInfo(" Security Group: {0}", securityGroup);
- ExchangeLog.LogInfo(" OAB Virtual Dir: {0}", oabVirtualDir);
-
- ExchangeTransaction transaction = StartTransaction();
-
- Organization info = new Organization();
-
- Runspace runSpace = null;
- try
- {
- runSpace = OpenRunspace();
-
-
- string server = GetOABGenerationServerName();
-
- //create OAB
- string oabId = CreateOfflineAddressBook(runSpace, organizationId, server, oabVirtualDir);
- transaction.RegisterNewOfflineAddressBook(oabId);
-
- string securityGroupId = AddADPrefix(securityGroup);
- UpdateOfflineAddressBook(runSpace, oabId, securityGroupId);
-
- info.OfflineAddressBook = oabId;
- }
- catch (Exception ex)
- {
- ExchangeLog.LogError("CreateOrganizationOfflineAddressBookInternal", ex);
- RollbackTransaction(transaction);
- throw;
- }
- finally
- {
-
- CloseRunspace(runSpace);
- }
- ExchangeLog.LogEnd("CreateOrganizationOfflineAddressBookInternal");
-
-
- return info;
- }
-
- private string GetOABGenerationServerName()
- {
- string ret = null;
- if (!string.IsNullOrEmpty(OABGenerationServer))
- ret = OABGenerationServer;
- else
- ret = GetServerName();
- return ret;
- }
-
- private void UpdateOrganizationOfflineAddressBookInternal(string oabId)
- {
- ExchangeLog.LogStart("UpdateOrganizationOfflineAddressBookInternal");
- ExchangeLog.LogInfo(" Id: {0}", oabId);
-
- Runspace runSpace = null;
- try
- {
- runSpace = OpenRunspace();
- Command cmd = new Command("Update-OfflineAddressBook");
- cmd.Parameters.Add("Identity", oabId);
- ExecuteShellCommand(runSpace, cmd);
- }
- finally
- {
- CloseRunspace(runSpace);
- }
- ExchangeLog.LogEnd("UpdateOrganizationOfflineAddressBookInternal");
- }
-
- internal virtual Organization CreateOrganizationAddressBookPolicyInternal(string organizationId, string gal, string addressBook, string roomList, string oab)
- {
- Organization info = new Organization();
- return info;
- }
-
-
- internal virtual bool DeleteOrganizationInternal(string organizationId, string distinguishedName,
- string globalAddressList, string addressList, string roomsAddressList, string offlineAddressBook, string securityGroup, string addressBookPolicy, List<ExchangeDomainName> acceptedDomains)
- {
- ExchangeLog.LogStart("DeleteOrganizationInternal");
- bool ret = true;
-
- Runspace runSpace = null;
- try
- {
- runSpace = OpenRunspace();
-
-
- string ou = ConvertADPathToCanonicalName(distinguishedName);
-
- //organization cannot be deleted when mailboxes, contacts or distribution groups exist
- /*bool canDelete = CanDeleteOrganization(runSpace, organizationId, ou);
- if (!canDelete)
- {
- throw new Exception("Organization cannot be deleted as it contains mailboxes, " +
- "contacts, distribution lists or public folders.\nDelete organization items first.");
- }*/
-
- if (!DeleteOrganizationMailboxes(runSpace, ou))
- ret = false;
-
- if (!DeleteOrganizationContacts(runSpace, ou))
- ret = false;
-
- if (!DeleteOrganizationDistributionLists(runSpace, ou))
- ret = false;
-
- if (!DeleteOrganizationPublicFolders(runSpace, organizationId))
- ret = false;
-
-
- //delete OAB
- try
- {
- if (!string.IsNullOrEmpty(offlineAddressBook))
- DeleteOfflineAddressBook(runSpace, offlineAddressBook);
- }
- catch (Exception ex)
- {
- ret = false;
- ExchangeLog.LogError("Could not delete Offline Address Book " + offlineAddressBook, ex);
- }
-
- //delete AL
- try
- {
- if (!string.IsNullOrEmpty(addressList))
- DeleteAddressList(runSpace, addressList);
- }
- catch (Exception ex)
- {
- ret = false;
- ExchangeLog.LogError("Could not delete Address List " + addressList, ex);
- }
-
- //delete RAL (Rooms Address List)
- try
- {
- if (!string.IsNullOrEmpty(roomsAddressList))
- DeleteAddressList(runSpace, roomsAddressList);
- }
- catch (Exception ex)
- {
- ret = false;
- ExchangeLog.LogError("Could not delete Rooms Address List " + roomsAddressList, ex);
- }
-
- //delete GAL
- try
- {
- if (!string.IsNullOrEmpty(globalAddressList))
- DeleteGlobalAddressList(runSpace, globalAddressList);
- }
- catch (Exception ex)
- {
- ret = false;
- ExchangeLog.LogError("Could not delete Global Address List " + globalAddressList, ex);
- }
-
- //delete ActiveSync policy
- try
- {
- DeleteActiveSyncPolicy(runSpace, organizationId);
- }
- catch (Exception ex)
- {
- ret = false;
- ExchangeLog.LogError("Could not delete ActiveSyncPolicy " + organizationId, ex);
- }
-
- //disable mail security distribution group
- try
- {
- DisableMailSecurityDistributionGroup(runSpace, securityGroup);
- }
- catch (Exception ex)
- {
- ret = false;
- ExchangeLog.LogError("Could not disable mail security distribution group " + securityGroup, ex);
- }
-
- if (!DeleteOrganizationAcceptedDomains(runSpace, acceptedDomains))
- ret = false;
- }
- catch (Exception ex)
- {
- ret = false;
- ExchangeLog.LogError("DeleteOrganizationInternal", ex);
- throw;
- }
- finally
- {
-
- CloseRunspace(runSpace);
- }
- ExchangeLog.LogEnd("DeleteOrganizationInternal");
- return ret;
- }
-
- private bool CanDeleteOrganization(Runspace runSpace, string organizationId, string ou)
- {
- ExchangeLog.LogStart("CanDeleteOrganization");
- bool ret = true;
-
- Command cmd = new Command("Get-Mailbox");
- cmd.Parameters.Add("OrganizationalUnit", ou);
- Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
- if (result != null && result.Count > 0)
- ret = false;
-
- if (ret)
- {
- cmd = new Command("Get-MailContact");
- cmd.Parameters.Add("OrganizationalUnit", ou);
- result = ExecuteShellCommand(runSpace, cmd);
- if (result != null && result.Count > 0)
- ret = false;
- }
-
- if (ret)
- {
- cmd = new Command("Get-DistributionGroup");
- cmd.Parameters.Add("OrganizationalUnit", ou);
- cmd.Parameters.Add("RecipientTypeDetails", "MailUniversalDistributionGroup");
- result = ExecuteShellCommand(runSpace, cmd);
- if (result != null && result.Count > 0)
- ret = false;
- }
-
- if (ret)
- {
- cmd = new Command("Get-PublicFolder");
- cmd.Parameters.Add("Identity", "\\" + organizationId);
- cmd.Parameters.Add("GetChildren", new SwitchParameter(true));
- if (!string.IsNullOrEmpty(PublicFolderServer))
- cmd.Parameters.Add("Server", PublicFolderServer);
-
- result = ExecuteShellCommand(runSpace, cmd);
- if (result != null && result.Count > 0)
- ret = false;
- }
-
- ExchangeLog.LogEnd("CanDeleteOrganization");
- return ret;
- }
-
- internal bool DeleteOrganizationMailboxes(Runspace runSpace, string ou)
- {
- ExchangeLog.LogStart("DeleteOrganizationMailboxes");
- bool ret = true;
-
- Command cmd = new Command("Get-Mailbox");
- cmd.Parameters.Add("OrganizationalUnit", ou);
- Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
- if (result != null && result.Count > 0)
- {
- foreach (PSObject obj in result)
- {
- string id = null;
- try
- {
- id = ObjToString(GetPSObjectProperty(obj, "Identity"));
- RemoveDevicesInternal(runSpace, id);
-
- RemoveMailbox(runSpace, id);
- }
- catch (Exception ex)
- {
- ret = false;
- ExchangeLog.LogError(string.Format("Can't delete mailbox {0}", id), ex);
- }
- }
- }
-
- ExchangeLog.LogEnd("DeleteOrganizationMailboxes");
- return ret;
- }
-
- internal bool DeleteOrganizationContacts(Runspace runSpace, string ou)
- {
- ExchangeLog.LogStart("DeleteOrganizationContacts");
- bool ret = true;
-
- Command cmd = new Command("Get-MailContact");
- cmd.Parameters.Add("OrganizationalUnit", ou);
- Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
- if (result != null && result.Count > 0)
- {
- foreach (PSObject obj in result)
- {
- string id = null;
- try
- {
- id = ObjToString(GetPSObjectProperty(obj, "Identity"));
- RemoveContact(runSpace, id);
- }
- catch (Exception ex)
- {
- ret = false;
- ExchangeLog.LogError(string.Format("Can't delete contact {0}", id), ex);
- }
- }
- }
-
- ExchangeLog.LogEnd("DeleteOrganizationContacts");
- return ret;
- }
-
- internal bool DeleteOrganizationDistributionLists(Runspace runSpace, string ou)
- {
- ExchangeLog.LogStart("DeleteOrganizationDistributionLists");
- bool ret = true;
-
- Command cmd = new Command("Get-DistributionGroup");
- cmd.Parameters.Add("OrganizationalUnit", ou);
- cmd.Parameters.Add("RecipientTypeDetails", "MailUniversalDistributionGroup");
- Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
- if (result != null && result.Count > 0)
- {
- foreach (PSObject obj in result)
- {
- string id = null;
- try
- {
- id = ObjToString(GetPSObjectProperty(obj, "Identity"));
- RemoveDistributionGroup(runSpace, id);
- }
- catch (Exception ex)
- {
- ret = false;
- ExchangeLog.LogError(string.Format("Can't delete distribution list {0}", id), ex);
- }
- }
- }
-
- ExchangeLog.LogEnd("DeleteOrganizationDistributionLists");
- return ret;
- }
-
- private bool DeleteOrganizationPublicFolders(Runspace runSpace, string organizationId)
- {
- ExchangeLog.LogStart("DeleteOrganizationPublicFolders");
- bool ret = true;
-
- //Delete public folders.
- string publicFolder = "\\" + organizationId;
- try
- {
- RemovePublicFolder(runSpace, publicFolder);
- }
- catch (Exception ex)
- {
- ret = false;
- ExchangeLog.LogError(string.Format("Can't delete public folder {0}", publicFolder), ex);
- }
- ExchangeLog.LogEnd("DeleteOrganizationPublicFolders");
- return ret;
- }
-
-
- internal bool DeleteOrganizationAcceptedDomains(Runspace runSpace, List<ExchangeDomainName> acceptedDomains)
- {
- ExchangeLog.LogStart("DeleteOrganizationAcceptedDomains");
-
- bool ret = true;
-
- if (acceptedDomains != null)
- {
-
- foreach (ExchangeDomainName domain in acceptedDomains)
- {
- try
- {
- DeleteAcceptedDomain(runSpace, domain.DomainName);
- }
- catch (Exception ex)
- {
- ExchangeLog.LogError(string.Format("Failed to delete accepted domain {0}", domain), ex);
- ret = false;
- }
- }
- }
- ExchangeLog.LogEnd("DeleteOrganizationAcceptedDomains");
- return ret;
- }
-
- private void SetOrganizationStorageLimitsInternal(string organizationDistinguishedName, long issueWarningKB,
- long prohibitSendKB, long prohibitSendReceiveKB, int keepDeletedItemsDays)
- {
- ExchangeLog.LogStart("SetOrganizationStorageLimitsInternal");
- ExchangeLog.DebugInfo("Organization Id: {0}", organizationDistinguishedName);
-
- Runspace runSpace = null;
- try
- {
- runSpace = OpenRunspace();
-
-
- string org = ConvertADPathToCanonicalName(organizationDistinguishedName);
-
- Unlimited<ByteQuantifiedSize> issueWarningQuota = ConvertKBToUnlimited(issueWarningKB);
- Unlimited<ByteQuantifiedSize> prohibitSendQuota = ConvertKBToUnlimited(prohibitSendKB);
- Unlimited<ByteQuantifiedSize> prohibitSendReceiveQuota = ConvertKBToUnlimited(prohibitSendReceiveKB);
- EnhancedTimeSpan retainDeletedItemsFor = ConvertDaysToEnhancedTimeSpan(keepDeletedItemsDays);
-
- Command cmd = new Command("Get-Mailbox");
- cmd.Parameters.Add("OrganizationalUnit", org);
- …
Large files files are truncated, but you can click here to view the full file