PageRenderTime 44ms CodeModel.GetById 10ms RepoModel.GetById 0ms app.codeStats 1ms

/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

  1. // Copyright (c) 2015, Outercurve Foundation.
  2. // All rights reserved.
  3. //
  4. // Redistribution and use in source and binary forms, with or without modification,
  5. // are permitted provided that the following conditions are met:
  6. //
  7. // - Redistributions of source code must retain the above copyright notice, this
  8. // list of conditions and the following disclaimer.
  9. //
  10. // - Redistributions in binary form must reproduce the above copyright notice,
  11. // this list of conditions and the following disclaimer in the documentation
  12. // and/or other materials provided with the distribution.
  13. //
  14. // - Neither the name of the Outercurve Foundation nor the names of its
  15. // contributors may be used to endorse or promote products derived from this
  16. // software without specific prior written permission.
  17. //
  18. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  19. // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
  22. // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  23. // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  24. // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
  25. // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  27. // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. using System;
  29. using System.IO;
  30. using System.Collections;
  31. using System.Collections.Generic;
  32. using System.Collections.ObjectModel;
  33. using System.Text;
  34. using System.Reflection;
  35. using System.Globalization;
  36. using System.Configuration;
  37. using System.DirectoryServices;
  38. using System.Security;
  39. using System.Security.Principal;
  40. using System.Security.AccessControl;
  41. using System.Management.Automation;
  42. using System.Management.Automation.Runspaces;
  43. using WebsitePanel.Providers;
  44. using WebsitePanel.Providers.Common;
  45. using WebsitePanel.Providers.HostedSolution;
  46. using WebsitePanel.Providers.Utils;
  47. using WebsitePanel.Server.Utils;
  48. using WebsitePanel.Providers.ResultObjects;
  49. using Microsoft.Exchange.Data.Directory.Recipient;
  50. using Microsoft.Win32;
  51. using Microsoft.Exchange.Data;
  52. using Microsoft.Exchange.Data.Directory;
  53. using Microsoft.Exchange.Data.Storage;
  54. namespace WebsitePanel.Providers.HostedSolution
  55. {
  56. public class Exchange2007 : HostingServiceProviderBase, IExchangeServer
  57. {
  58. #region Static constructor
  59. static Exchange2007()
  60. {
  61. AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(ResolveExchangeAssembly);
  62. ExchangeRegistryPath = "SOFTWARE\\Microsoft\\Exchange\\Setup";
  63. }
  64. #endregion
  65. #region Constants
  66. private const string CONFIG_CLEAR_QUERYBASEDN = "WebsitePanel.Exchange.ClearQueryBaseDN";
  67. #endregion
  68. #region Properties
  69. internal string RootOU
  70. {
  71. get { return ProviderSettings["RootOU"]; }
  72. }
  73. internal string StorageGroup
  74. {
  75. get { return ProviderSettings["StorageGroup"]; }
  76. }
  77. internal string MailboxDatabase
  78. {
  79. get { return ProviderSettings["MailboxDatabase"]; }
  80. }
  81. internal bool PublicFolderDistributionEnabled
  82. {
  83. get { return ProviderSettings.GetBool("PublicFolderDistributionEnabled"); }
  84. }
  85. internal int KeepDeletedItemsDays
  86. {
  87. get { return Int32.Parse(ProviderSettings["KeepDeletedItemsDays"]); }
  88. }
  89. internal int KeepDeletedMailboxesDays
  90. {
  91. get { return Int32.Parse(ProviderSettings["KeepDeletedMailboxesDays"]); }
  92. }
  93. internal string RootDomain
  94. {
  95. get { return ServerSettings.ADRootDomain; }
  96. }
  97. internal string MailboxCluster
  98. {
  99. get { return ProviderSettings["MailboxCluster"]; }
  100. }
  101. internal string PrimaryDomainController
  102. {
  103. get { return ProviderSettings["PrimaryDomainController"]; }
  104. }
  105. internal string PublicFolderServer
  106. {
  107. get { return ProviderSettings["PublicFolderServer"]; }
  108. }
  109. internal string OABGenerationServer
  110. {
  111. get { return ProviderSettings["OABServer"]; }
  112. }
  113. internal static string ExchangeRegistryPath
  114. {
  115. get;
  116. set;
  117. }
  118. internal virtual string ExchangeSnapInName
  119. {
  120. get { return "Microsoft.Exchange.Management.PowerShell.Admin"; }
  121. }
  122. #endregion
  123. #region IExchangeServer Members
  124. #region Common
  125. public bool CheckAccountCredentials(string username, string password)
  126. {
  127. return CheckAccountCredentialsInternal(username, password);
  128. }
  129. #endregion
  130. #region Organizations
  131. /// <summary>
  132. /// Extend existing organization with exchange functionality
  133. /// </summary>
  134. /// <param name="organizationId"></param>
  135. /// <param name="securityGroup"></param>
  136. /// <returns></returns>
  137. public Organization ExtendToExchangeOrganization(string organizationId, string securityGroup, bool IsConsumer)
  138. {
  139. return ExtendToExchangeOrganizationInternal(organizationId, securityGroup, IsConsumer);
  140. }
  141. /// <summary>
  142. /// Creates organization OAB on the Client Access Server
  143. /// </summary>
  144. /// <param name="organizationId"></param>
  145. /// <param name="securityGroup"></param>
  146. /// <returns></returns>
  147. public Organization CreateOrganizationOfflineAddressBook(string organizationId, string securityGroup, string oabVirtualDir)
  148. {
  149. return CreateOrganizationOfflineAddressBookInternal(organizationId, securityGroup, oabVirtualDir);
  150. }
  151. /// <summary>
  152. /// Updates organization OAB
  153. /// </summary>
  154. /// <param name="oabId"></param>
  155. public void UpdateOrganizationOfflineAddressBook(string oabId)
  156. {
  157. UpdateOrganizationOfflineAddressBookInternal(oabId);
  158. }
  159. public string GetOABVirtualDirectory()
  160. {
  161. return GetOABVirtualDirectoryInternal();
  162. }
  163. public Organization CreateOrganizationAddressBookPolicy(string organizationId, string gal, string addressBook, string roomList, string oab)
  164. {
  165. return CreateOrganizationAddressBookPolicyInternal(organizationId, gal, addressBook, roomList, oab);
  166. }
  167. public bool DeleteOrganization(string organizationId, string distinguishedName,
  168. string globalAddressList, string addressList, string roomList, string offlineAddressBook,
  169. string securityGroup, string addressBookPolicy, List<ExchangeDomainName> acceptedDomains)
  170. {
  171. return DeleteOrganizationInternal(organizationId, distinguishedName, globalAddressList,
  172. addressList, roomList, offlineAddressBook, securityGroup, addressBookPolicy, acceptedDomains);
  173. }
  174. public void SetOrganizationStorageLimits(string organizationDistinguishedName, long issueWarningKB, long prohibitSendKB,
  175. long prohibitSendReceiveKB, int keepDeletedItemsDays)
  176. {
  177. SetOrganizationStorageLimitsInternal(organizationDistinguishedName, issueWarningKB, prohibitSendKB,
  178. prohibitSendReceiveKB, keepDeletedItemsDays);
  179. }
  180. public ExchangeItemStatistics[] GetMailboxesStatistics(string organizationDistinguishedName)
  181. {
  182. return GetMailboxesStatisticsInternal(organizationDistinguishedName);
  183. }
  184. #endregion
  185. #region Domains
  186. public string[] GetAuthoritativeDomains()
  187. {
  188. return GetAuthoritativeDomainsInternal();
  189. }
  190. public void AddAuthoritativeDomain(string domain)
  191. {
  192. CreateAuthoritativeDomainInternal(domain);
  193. }
  194. public void DeleteAuthoritativeDomain(string domain)
  195. {
  196. DeleteAuthoritativeDomainInternal(domain);
  197. }
  198. public void ChangeAcceptedDomainType(string domainName, ExchangeAcceptedDomainType domainType)
  199. {
  200. ChangeAcceptedDomainTypeInternal(domainName, domainType);
  201. }
  202. #endregion
  203. #region Mailboxes
  204. public ExchangeMailbox GetMailboxPermissions(string organizationId, string accountName)
  205. {
  206. return GetMailboxPermissionsInternal(organizationId, accountName, null);
  207. }
  208. public void SetMailboxPermissions(string organizationId, string accountName, string[] sendAsAccounts, string[] fullAccessAccounts)
  209. {
  210. SetMailboxPermissionsInternal(organizationId, accountName, sendAsAccounts, fullAccessAccounts);
  211. }
  212. public void DeleteMailbox(string accountName)
  213. {
  214. DeleteMailboxInternal(accountName);
  215. }
  216. public ExchangeMailbox GetMailboxGeneralSettings(string accountName)
  217. {
  218. return GetMailboxGeneralSettingsInternal(accountName);
  219. }
  220. public void SetMailboxGeneralSettings(string accountName, bool hideFromAddressBook, bool disabled)
  221. {
  222. SetMailboxGeneralSettingsInternal(accountName, hideFromAddressBook, disabled);
  223. }
  224. public ExchangeMailbox GetMailboxMailFlowSettings(string accountName)
  225. {
  226. return GetMailboxMailFlowSettingsInternal(accountName);
  227. }
  228. public void SetMailboxMailFlowSettings(string accountName, bool enableForwarding,
  229. string forwardingAccountName, bool forwardToBoth, string[] sendOnBehalfAccounts,
  230. string[] acceptAccounts, string[] rejectAccounts, bool requireSenderAuthentication)
  231. {
  232. SetMailboxMailFlowSettingsInternal(accountName, enableForwarding, forwardingAccountName,
  233. forwardToBoth, sendOnBehalfAccounts, acceptAccounts, rejectAccounts, requireSenderAuthentication);
  234. }
  235. public ExchangeMailbox GetMailboxAdvancedSettings(string accountName)
  236. {
  237. return GetMailboxAdvancedSettingsInternal(accountName);
  238. }
  239. public void SetMailboxAdvancedSettings(string organizationId, string accountName, bool enablePOP,
  240. bool enableIMAP, bool enableOWA, bool enableMAPI, bool enableActiveSync,
  241. long issueWarningKB, long prohibitSendKB, long prohibitSendReceiveKB, int keepDeletedItemsDays, int maxRecipients, int maxSendMessageSizeKB,
  242. int maxReceiveMessageSizeKB, bool enabledLitigationHold, long recoverabelItemsSpace, long recoverabelItemsWarning, string litigationHoldUrl, string litigationHoldMsg)
  243. {
  244. SetMailboxAdvancedSettingsInternal(organizationId, accountName, enablePOP, enableIMAP, enableOWA,
  245. enableMAPI, enableActiveSync, issueWarningKB,
  246. prohibitSendKB, prohibitSendReceiveKB, keepDeletedItemsDays, maxRecipients, maxSendMessageSizeKB, maxReceiveMessageSizeKB,
  247. enabledLitigationHold, recoverabelItemsSpace, recoverabelItemsWarning, litigationHoldUrl, litigationHoldMsg );
  248. }
  249. public ExchangeEmailAddress[] GetMailboxEmailAddresses(string accountName)
  250. {
  251. return GetMailboxEmailAddressesInternal(accountName);
  252. }
  253. public void SetMailboxEmailAddresses(string accountName, string[] emailAddresses)
  254. {
  255. SetMailboxEmailAddressesInternal(accountName, emailAddresses);
  256. }
  257. public void SetMailboxPrimaryEmailAddress(string accountName, string emailAddress)
  258. {
  259. SetMailboxPrimaryEmailAddressInternal(accountName, emailAddress);
  260. }
  261. public ExchangeMailboxStatistics GetMailboxStatistics(string id)
  262. {
  263. return GetMailboxStatisticsInternal(id);
  264. }
  265. #endregion
  266. #region Contacts
  267. public void CreateContact(string organizationId, string organizationDistinguishedName,
  268. string contactDisplayName, string contactAccountName, string contactEmail, string defaultOrganizationDomain)
  269. {
  270. CreateContactInternal(organizationId, organizationDistinguishedName, contactDisplayName,
  271. contactAccountName, contactEmail, defaultOrganizationDomain);
  272. }
  273. public void DeleteContact(string accountName)
  274. {
  275. DeleteContactInternal(accountName);
  276. }
  277. public ExchangeContact GetContactGeneralSettings(string accountName)
  278. {
  279. return GetContactGeneralSettingsInternal(accountName);
  280. }
  281. public void SetContactGeneralSettings(string accountName, string displayName, string email,
  282. bool hideFromAddressBook, string firstName, string initials, string lastName, string address,
  283. string city, string state, string zip, string country, string jobTitle, string company,
  284. string department, string office, string managerAccountName, string businessPhone, string fax,
  285. string homePhone, string mobilePhone, string pager, string webPage, string notes, int useMapiRichTextFormat, string defaultOrganizationDomain)
  286. {
  287. SetContactGeneralSettingsInternal(accountName, displayName, email, hideFromAddressBook,
  288. firstName, initials, lastName, address, city, state, zip, country, jobTitle,
  289. company, department, office, managerAccountName, businessPhone, fax, homePhone,
  290. mobilePhone, pager, webPage, notes, useMapiRichTextFormat, defaultOrganizationDomain);
  291. }
  292. public ExchangeContact GetContactMailFlowSettings(string accountName)
  293. {
  294. return GetContactMailFlowSettingsInternal(accountName);
  295. }
  296. public void SetContactMailFlowSettings(string accountName, string[] acceptAccounts, string[] rejectAccounts, bool requireSenderAuthentication)
  297. {
  298. SetContactMailFlowSettingsInternal(accountName, acceptAccounts, rejectAccounts, requireSenderAuthentication);
  299. }
  300. #endregion
  301. #region Distribution lists
  302. public void CreateDistributionList(string organizationId, string organizationDistinguishedName,
  303. string displayName, string accountName, string name, string domain, string managedBy, string[] addressLists)
  304. {
  305. CreateDistributionListInternal(organizationId, organizationDistinguishedName, displayName,
  306. accountName, name, domain, managedBy, addressLists);
  307. }
  308. public void DeleteDistributionList(string accountName)
  309. {
  310. DeleteDistributionListInternal(accountName);
  311. }
  312. public ExchangeDistributionList GetDistributionListGeneralSettings(string accountName)
  313. {
  314. return GetDistributionListGeneralSettingsInternal(accountName);
  315. }
  316. public void SetDistributionListGeneralSettings(string accountName, string displayName,
  317. bool hideFromAddressBook, string managedBy, string[] members, string notes, string[] addressLists)
  318. {
  319. SetDistributionListGeneralSettingsInternal(accountName, displayName, hideFromAddressBook,
  320. managedBy, members, notes, addressLists);
  321. }
  322. public void AddDistributionListMembers(string accountName, string[] memberAccounts, string[] addressLists)
  323. {
  324. AddDistributionListMembersInternal(accountName, memberAccounts, addressLists);
  325. }
  326. public void RemoveDistributionListMembers(string accountName, string[] memberAccounts, string[] addressLists)
  327. {
  328. RemoveDistributionListMembersInternal(accountName, memberAccounts, addressLists);
  329. }
  330. public ExchangeDistributionList GetDistributionListMailFlowSettings(string accountName)
  331. {
  332. return GetDistributionListMailFlowSettingsInternal(accountName);
  333. }
  334. public void SetDistributionListMailFlowSettings(string accountName, string[] acceptAccounts,
  335. string[] rejectAccounts, bool requireSenderAuthentication, string[] addressLists)
  336. {
  337. SetDistributionListMailFlowSettingsInternal(accountName, acceptAccounts, rejectAccounts, requireSenderAuthentication, addressLists);
  338. }
  339. public ExchangeEmailAddress[] GetDistributionListEmailAddresses(string accountName)
  340. {
  341. return GetDistributionListEmailAddressesInternal(accountName);
  342. }
  343. public void SetDistributionListEmailAddresses(string accountName, string[] emailAddresses, string[] addressLists)
  344. {
  345. SetDistributionListEmailAddressesInternal(accountName, emailAddresses, addressLists);
  346. }
  347. public void SetDistributionListPrimaryEmailAddress(string accountName, string emailAddress, string[] addressLists)
  348. {
  349. SetDistributionListPrimaryEmailAddressInternal(accountName, emailAddress, addressLists);
  350. }
  351. public ExchangeDistributionList GetDistributionListPermissions(string organizationId, string accountName)
  352. {
  353. return GetDistributionListPermissionsInternal(organizationId, accountName, null);
  354. }
  355. public void SetDistributionListPermissions(string organizationId, string accountName, string[] sendAsAccounts, string[] sendOnBehalfAccounts, string[] addressLists)
  356. {
  357. SetDistributionListPermissionsInternal(organizationId, accountName, sendAsAccounts, sendOnBehalfAccounts, addressLists);
  358. }
  359. #endregion
  360. #region Public folders
  361. public void CreatePublicFolder(string organizationDistinguishedName, string organizationId, string securityGroup, string parentFolder,
  362. string folderName, bool mailEnabled, string accountName, string name, string domain)
  363. {
  364. CreatePublicFolderInternal(organizationId, securityGroup, parentFolder, folderName,
  365. mailEnabled, accountName, name, domain);
  366. }
  367. public void DeletePublicFolder(string organizationId, string folder)
  368. {
  369. DeletePublicFolderInternal(folder);
  370. }
  371. public void EnableMailPublicFolder(string organizationId, string folder, string accountName,
  372. string name, string domain)
  373. {
  374. EnableMailPublicFolderInternal(organizationId, folder, accountName, name, domain);
  375. }
  376. public void DisableMailbox(string id)
  377. {
  378. DisableMailboxInternal(id);
  379. }
  380. internal virtual void DisableMailboxInternal(string id)
  381. {
  382. ExchangeLog.LogStart("DisableMailboxIntenal");
  383. Runspace runSpace = null;
  384. try
  385. {
  386. runSpace = OpenRunspace();
  387. RemoveDevicesInternal(runSpace, id);
  388. Command cmd = new Command("Disable-Mailbox");
  389. cmd.Parameters.Add("Identity", id);
  390. cmd.Parameters.Add("Confirm", false);
  391. ExecuteShellCommand(runSpace, cmd);
  392. }
  393. finally
  394. {
  395. CloseRunspace(runSpace);
  396. }
  397. ExchangeLog.LogEnd("DisableMailboxIntenal");
  398. }
  399. public void DisableMailPublicFolder(string organizationId, string folder)
  400. {
  401. DisableMailPublicFolderInternal(folder);
  402. }
  403. public ExchangePublicFolder GetPublicFolderGeneralSettings(string organizationId, string folder)
  404. {
  405. return GetPublicFolderGeneralSettingsInternal(folder);
  406. }
  407. public void SetPublicFolderGeneralSettings(string organizationId, string folder, string newFolderName,
  408. bool hideFromAddressBook, ExchangeAccount[] accounts)
  409. {
  410. SetPublicFolderGeneralSettingsInternal(folder, newFolderName, hideFromAddressBook, accounts);
  411. }
  412. public ExchangePublicFolder GetPublicFolderMailFlowSettings(string organizationId, string folder)
  413. {
  414. return GetPublicFolderMailFlowSettingsInternal(folder);
  415. }
  416. public void SetPublicFolderMailFlowSettings(string organizationId, string folder,
  417. string[] acceptAccounts, string[] rejectAccounts, bool requireSenderAuthentication)
  418. {
  419. SetPublicFolderMailFlowSettingsInternal(folder, acceptAccounts, rejectAccounts, requireSenderAuthentication);
  420. }
  421. public ExchangeEmailAddress[] GetPublicFolderEmailAddresses(string organizationId, string folder)
  422. {
  423. return GetPublicFolderEmailAddressesInternal(folder);
  424. }
  425. public void SetPublicFolderEmailAddresses(string organizationId, string folder, string[] emailAddresses)
  426. {
  427. SetPublicFolderEmailAddressesInternal(folder, emailAddresses);
  428. }
  429. public void SetPublicFolderPrimaryEmailAddress(string organizationId, string folder, string emailAddress)
  430. {
  431. SetPublicFolderPrimaryEmailAddressInternal(folder, emailAddress);
  432. }
  433. public ExchangeItemStatistics[] GetPublicFoldersStatistics(string organizationId, string[] folders)
  434. {
  435. return GetPublicFoldersStatisticsInternal(folders);
  436. }
  437. public string[] GetPublicFoldersRecursive(string organizationId, string parent)
  438. {
  439. return GetPublicFoldersRecursiveInternal(parent);
  440. }
  441. public long GetPublicFolderSize(string organizationId, string folder)
  442. {
  443. return GetPublicFolderSizeInternal(folder);
  444. }
  445. #endregion
  446. #region ActiveSync
  447. public void CreateOrganizationActiveSyncPolicy(string organizationId)
  448. {
  449. CreateOrganizationActiveSyncPolicyInternal(organizationId);
  450. }
  451. public ExchangeActiveSyncPolicy GetActiveSyncPolicy(string organizationId)
  452. {
  453. return GetActiveSyncPolicyInternal(organizationId);
  454. }
  455. public void SetActiveSyncPolicy(string id, bool allowNonProvisionableDevices, bool attachmentsEnabled,
  456. int maxAttachmentSizeKB, bool uncAccessEnabled, bool wssAccessEnabled, bool devicePasswordEnabled,
  457. bool alphanumericPasswordRequired, bool passwordRecoveryEnabled, bool deviceEncryptionEnabled,
  458. bool allowSimplePassword, int maxPasswordFailedAttempts, int minPasswordLength, int inactivityLockMin,
  459. int passwordExpirationDays, int passwordHistory, int refreshInterval)
  460. {
  461. SetActiveSyncPolicyInternal(id, allowNonProvisionableDevices, attachmentsEnabled,
  462. maxAttachmentSizeKB, uncAccessEnabled, wssAccessEnabled,
  463. devicePasswordEnabled, alphanumericPasswordRequired, passwordRecoveryEnabled,
  464. deviceEncryptionEnabled, allowSimplePassword, maxPasswordFailedAttempts,
  465. minPasswordLength, inactivityLockMin, passwordExpirationDays, passwordHistory, refreshInterval);
  466. }
  467. #endregion
  468. #region Mobile devices
  469. public ExchangeMobileDevice[] GetMobileDevices(string accountName)
  470. {
  471. return GetMobileDevicesInternal(accountName);
  472. }
  473. public ExchangeMobileDevice GetMobileDevice(string id)
  474. {
  475. return GetMobileDeviceInternal(id);
  476. }
  477. public void WipeDataFromDevice(string id)
  478. {
  479. WipeDataFromDeviceInternal(id);
  480. }
  481. public void CancelRemoteWipeRequest(string id)
  482. {
  483. CancelRemoteWipeRequestInternal(id);
  484. }
  485. public void RemoveDevice(string id)
  486. {
  487. RemoveDeviceInternal(id);
  488. }
  489. #endregion
  490. #endregion
  491. #region IHostingServiceProvider Members
  492. public override void ChangeServiceItemsState(ServiceProviderItem[] items, bool enabled)
  493. {
  494. foreach (ServiceProviderItem item in items)
  495. {
  496. if (item is Organization)
  497. {
  498. try
  499. {
  500. // make E2K7 mailboxes disabled
  501. Organization org = item as Organization;
  502. ChangeOrganizationState(org.DistinguishedName, enabled);
  503. }
  504. catch (Exception ex)
  505. {
  506. Log.WriteError(String.Format("Error switching '{0}' {1}", item.Name, item.GetType().Name), ex);
  507. }
  508. }
  509. }
  510. }
  511. public override void DeleteServiceItems(ServiceProviderItem[] items)
  512. {
  513. foreach (ServiceProviderItem item in items)
  514. {
  515. try
  516. {
  517. if (item is Organization)
  518. {
  519. Organization org = item as Organization;
  520. DeleteOrganization(org.OrganizationId, org.DistinguishedName, org.GlobalAddressList,
  521. org.AddressList, org.RoomsAddressList, org.OfflineAddressBook, org.SecurityGroup, org.AddressBookPolicy, null);
  522. }
  523. else if (item is ExchangeDomain)
  524. {
  525. DeleteAcceptedDomain(null, item.Name);
  526. }
  527. }
  528. catch (Exception ex)
  529. {
  530. Log.WriteError(String.Format("Error deleting '{0}' {1}", item.Name, item.GetType().Name), ex);
  531. }
  532. }
  533. }
  534. public override ServiceProviderItemDiskSpace[] GetServiceItemsDiskSpace(ServiceProviderItem[] items)
  535. {
  536. List<ServiceProviderItemDiskSpace> itemsDiskspace = new List<ServiceProviderItemDiskSpace>();
  537. // update items with diskspace
  538. foreach (ServiceProviderItem item in items)
  539. {
  540. if (item is Organization)
  541. {
  542. try
  543. {
  544. Log.WriteStart(String.Format("Calculating '{0}' disk space", item.Name));
  545. Organization org = item as Organization;
  546. // calculate disk space
  547. ServiceProviderItemDiskSpace diskspace = new ServiceProviderItemDiskSpace();
  548. diskspace.ItemId = item.Id;
  549. diskspace.DiskSpace = CalculateOrganizationDiskSpace(org.OrganizationId, org.DistinguishedName);
  550. itemsDiskspace.Add(diskspace);
  551. Log.WriteEnd(String.Format("Calculating '{0}' disk space", item.Name));
  552. }
  553. catch (Exception ex)
  554. {
  555. Log.WriteError(String.Format("Error calculating '{0}' Exchange organization disk space", item.Name), ex);
  556. }
  557. }
  558. }
  559. return itemsDiskspace.ToArray();
  560. }
  561. #endregion
  562. #region Common
  563. private bool CheckAccountCredentialsInternal(string username, string password)
  564. {
  565. try
  566. {
  567. string path = ConvertDomainName(RootDomain);
  568. DirectoryEntry entry = new DirectoryEntry(path, username, password);
  569. //Bind to the native AdsObject to force authentication.
  570. object obj = entry.NativeObject;
  571. DirectorySearcher search = new DirectorySearcher(entry);
  572. search.Filter = string.Format("(userPrincipalName={0})", username);
  573. search.PropertiesToLoad.Add("cn");
  574. SearchResult result = search.FindOne();
  575. if (result == null)
  576. {
  577. return false;
  578. }
  579. //Update the new path to the user in the directory.
  580. path = result.Path;
  581. string filterAttribute = (string)result.Properties["cn"][0];
  582. }
  583. catch (Exception)
  584. {
  585. return false;
  586. //throw new Exception("Error authenticating user. " + ex.Message);
  587. }
  588. return true;
  589. }
  590. #endregion
  591. #region Organizations
  592. /// <summary>
  593. /// Creates organization on Mail Server
  594. /// </summary>
  595. /// <param name="organizationId"></param>
  596. /// <returns></returns>
  597. internal virtual Organization ExtendToExchangeOrganizationInternal(string organizationId, string securityGroup, bool IsConsumer)
  598. {
  599. ExchangeLog.LogStart("CreateOrganizationInternal");
  600. ExchangeLog.DebugInfo(" Organization Id: {0}", organizationId);
  601. ExchangeTransaction transaction = StartTransaction();
  602. Organization info = new Organization();
  603. Runspace runSpace = null;
  604. try
  605. {
  606. runSpace = OpenRunspace();
  607. string server = GetServerName();
  608. string securityGroupPath = AddADPrefix(securityGroup);
  609. //Create mail enabled organization security group
  610. EnableMailSecurityDistributionGroup(runSpace, securityGroup, organizationId);
  611. transaction.RegisterMailEnabledDistributionGroup(securityGroup);
  612. UpdateSecurityDistributionGroup(runSpace, securityGroup, organizationId, IsConsumer);
  613. //create GAL
  614. string galId = CreateGlobalAddressList(runSpace, organizationId);
  615. transaction.RegisterNewGlobalAddressList(galId);
  616. ExchangeLog.LogInfo(" Global Address List: {0}", galId);
  617. UpdateGlobalAddressList(runSpace, galId, securityGroupPath);
  618. //create AL
  619. string alId = CreateAddressList(runSpace, organizationId);
  620. transaction.RegisterNewAddressList(alId);
  621. ExchangeLog.LogInfo(" Address List: {0}", alId);
  622. UpdateAddressList(runSpace, alId, securityGroupPath);
  623. //create RAL
  624. string ralId = CreateRoomsAddressList(runSpace, organizationId);
  625. transaction.RegisterNewRoomsAddressList(ralId);
  626. ExchangeLog.LogInfo(" Rooms Address List: {0}", ralId);
  627. UpdateAddressList(runSpace, ralId, securityGroupPath);
  628. //create ActiveSync policy
  629. string asId = CreateActiveSyncPolicy(runSpace, organizationId);
  630. transaction.RegisterNewActiveSyncPolicy(asId);
  631. ExchangeLog.LogInfo(" ActiveSync Policy: {0}", asId);
  632. //storage group
  633. string storageGroupId = CreateStorageGroup(runSpace, StorageGroup, server);
  634. ExchangeLog.LogInfo(" Storage Group: {0}", storageGroupId);
  635. //mailbox database
  636. string databaseId = CreateMailboxDatabase(runSpace, MailboxDatabase, storageGroupId);
  637. ExchangeLog.LogInfo(" Database: {0}", databaseId);
  638. info.AddressList = alId;
  639. info.GlobalAddressList = galId;
  640. info.RoomsAddressList = ralId;
  641. info.OrganizationId = organizationId;
  642. info.Database = databaseId;
  643. }
  644. catch (Exception ex)
  645. {
  646. ExchangeLog.LogError("CreateOrganizationInternal", ex);
  647. RollbackTransaction(transaction);
  648. throw;
  649. }
  650. finally
  651. {
  652. CloseRunspace(runSpace);
  653. }
  654. ExchangeLog.LogEnd("CreateOrganizationInternal");
  655. return info;
  656. }
  657. private void CheckServiceSettings()
  658. {
  659. if (!ServerSettings.ADEnabled)
  660. throw new Exception("Active Directory is not enabled. Check server settings.");
  661. if (string.IsNullOrEmpty(RootDomain))
  662. throw new Exception("Active Directory root domain is not specified. Check server settings.");
  663. if (string.IsNullOrEmpty(RootOU))
  664. throw new Exception("Active Directory root organizational unit is not specified. Check provider settings.");
  665. if (string.IsNullOrEmpty(PrimaryDomainController))
  666. throw new Exception("Primary Domain Controller is not specified. Check provider settings.");
  667. }
  668. private string GetOABVirtualDirectoryInternal()
  669. {
  670. ExchangeLog.LogStart("GetOABVirtualDirectoryInternal");
  671. Runspace runSpace = null;
  672. string virtualDir = null;
  673. try
  674. {
  675. runSpace = OpenRunspace();
  676. string server = GetServerName();
  677. Command cmd = new Command("Get-OabVirtualDirectory");
  678. cmd.Parameters.Add("Server", server);
  679. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  680. if (result.Count > 0)
  681. {
  682. virtualDir = ObjToString(GetPSObjectProperty(result[0], "Identity"));
  683. }
  684. }
  685. finally
  686. {
  687. CloseRunspace(runSpace);
  688. }
  689. ExchangeLog.LogEnd("GetOABVirtualDirectoryInternal");
  690. return virtualDir;
  691. }
  692. private Organization CreateOrganizationOfflineAddressBookInternal(string organizationId, string securityGroup, string oabVirtualDir)
  693. {
  694. ExchangeLog.LogStart("CreateOrganizationOfflineAddressBookInternal");
  695. ExchangeLog.LogInfo(" Organization Id: {0}", organizationId);
  696. ExchangeLog.LogInfo(" Security Group: {0}", securityGroup);
  697. ExchangeLog.LogInfo(" OAB Virtual Dir: {0}", oabVirtualDir);
  698. ExchangeTransaction transaction = StartTransaction();
  699. Organization info = new Organization();
  700. Runspace runSpace = null;
  701. try
  702. {
  703. runSpace = OpenRunspace();
  704. string server = GetOABGenerationServerName();
  705. //create OAB
  706. string oabId = CreateOfflineAddressBook(runSpace, organizationId, server, oabVirtualDir);
  707. transaction.RegisterNewOfflineAddressBook(oabId);
  708. string securityGroupId = AddADPrefix(securityGroup);
  709. UpdateOfflineAddressBook(runSpace, oabId, securityGroupId);
  710. info.OfflineAddressBook = oabId;
  711. }
  712. catch (Exception ex)
  713. {
  714. ExchangeLog.LogError("CreateOrganizationOfflineAddressBookInternal", ex);
  715. RollbackTransaction(transaction);
  716. throw;
  717. }
  718. finally
  719. {
  720. CloseRunspace(runSpace);
  721. }
  722. ExchangeLog.LogEnd("CreateOrganizationOfflineAddressBookInternal");
  723. return info;
  724. }
  725. private string GetOABGenerationServerName()
  726. {
  727. string ret = null;
  728. if (!string.IsNullOrEmpty(OABGenerationServer))
  729. ret = OABGenerationServer;
  730. else
  731. ret = GetServerName();
  732. return ret;
  733. }
  734. private void UpdateOrganizationOfflineAddressBookInternal(string oabId)
  735. {
  736. ExchangeLog.LogStart("UpdateOrganizationOfflineAddressBookInternal");
  737. ExchangeLog.LogInfo(" Id: {0}", oabId);
  738. Runspace runSpace = null;
  739. try
  740. {
  741. runSpace = OpenRunspace();
  742. Command cmd = new Command("Update-OfflineAddressBook");
  743. cmd.Parameters.Add("Identity", oabId);
  744. ExecuteShellCommand(runSpace, cmd);
  745. }
  746. finally
  747. {
  748. CloseRunspace(runSpace);
  749. }
  750. ExchangeLog.LogEnd("UpdateOrganizationOfflineAddressBookInternal");
  751. }
  752. internal virtual Organization CreateOrganizationAddressBookPolicyInternal(string organizationId, string gal, string addressBook, string roomList, string oab)
  753. {
  754. Organization info = new Organization();
  755. return info;
  756. }
  757. internal virtual bool DeleteOrganizationInternal(string organizationId, string distinguishedName,
  758. string globalAddressList, string addressList, string roomsAddressList, string offlineAddressBook, string securityGroup, string addressBookPolicy, List<ExchangeDomainName> acceptedDomains)
  759. {
  760. ExchangeLog.LogStart("DeleteOrganizationInternal");
  761. bool ret = true;
  762. Runspace runSpace = null;
  763. try
  764. {
  765. runSpace = OpenRunspace();
  766. string ou = ConvertADPathToCanonicalName(distinguishedName);
  767. //organization cannot be deleted when mailboxes, contacts or distribution groups exist
  768. /*bool canDelete = CanDeleteOrganization(runSpace, organizationId, ou);
  769. if (!canDelete)
  770. {
  771. throw new Exception("Organization cannot be deleted as it contains mailboxes, " +
  772. "contacts, distribution lists or public folders.\nDelete organization items first.");
  773. }*/
  774. if (!DeleteOrganizationMailboxes(runSpace, ou))
  775. ret = false;
  776. if (!DeleteOrganizationContacts(runSpace, ou))
  777. ret = false;
  778. if (!DeleteOrganizationDistributionLists(runSpace, ou))
  779. ret = false;
  780. if (!DeleteOrganizationPublicFolders(runSpace, organizationId))
  781. ret = false;
  782. //delete OAB
  783. try
  784. {
  785. if (!string.IsNullOrEmpty(offlineAddressBook))
  786. DeleteOfflineAddressBook(runSpace, offlineAddressBook);
  787. }
  788. catch (Exception ex)
  789. {
  790. ret = false;
  791. ExchangeLog.LogError("Could not delete Offline Address Book " + offlineAddressBook, ex);
  792. }
  793. //delete AL
  794. try
  795. {
  796. if (!string.IsNullOrEmpty(addressList))
  797. DeleteAddressList(runSpace, addressList);
  798. }
  799. catch (Exception ex)
  800. {
  801. ret = false;
  802. ExchangeLog.LogError("Could not delete Address List " + addressList, ex);
  803. }
  804. //delete RAL (Rooms Address List)
  805. try
  806. {
  807. if (!string.IsNullOrEmpty(roomsAddressList))
  808. DeleteAddressList(runSpace, roomsAddressList);
  809. }
  810. catch (Exception ex)
  811. {
  812. ret = false;
  813. ExchangeLog.LogError("Could not delete Rooms Address List " + roomsAddressList, ex);
  814. }
  815. //delete GAL
  816. try
  817. {
  818. if (!string.IsNullOrEmpty(globalAddressList))
  819. DeleteGlobalAddressList(runSpace, globalAddressList);
  820. }
  821. catch (Exception ex)
  822. {
  823. ret = false;
  824. ExchangeLog.LogError("Could not delete Global Address List " + globalAddressList, ex);
  825. }
  826. //delete ActiveSync policy
  827. try
  828. {
  829. DeleteActiveSyncPolicy(runSpace, organizationId);
  830. }
  831. catch (Exception ex)
  832. {
  833. ret = false;
  834. ExchangeLog.LogError("Could not delete ActiveSyncPolicy " + organizationId, ex);
  835. }
  836. //disable mail security distribution group
  837. try
  838. {
  839. DisableMailSecurityDistributionGroup(runSpace, securityGroup);
  840. }
  841. catch (Exception ex)
  842. {
  843. ret = false;
  844. ExchangeLog.LogError("Could not disable mail security distribution group " + securityGroup, ex);
  845. }
  846. if (!DeleteOrganizationAcceptedDomains(runSpace, acceptedDomains))
  847. ret = false;
  848. }
  849. catch (Exception ex)
  850. {
  851. ret = false;
  852. ExchangeLog.LogError("DeleteOrganizationInternal", ex);
  853. throw;
  854. }
  855. finally
  856. {
  857. CloseRunspace(runSpace);
  858. }
  859. ExchangeLog.LogEnd("DeleteOrganizationInternal");
  860. return ret;
  861. }
  862. private bool CanDeleteOrganization(Runspace runSpace, string organizationId, string ou)
  863. {
  864. ExchangeLog.LogStart("CanDeleteOrganization");
  865. bool ret = true;
  866. Command cmd = new Command("Get-Mailbox");
  867. cmd.Parameters.Add("OrganizationalUnit", ou);
  868. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  869. if (result != null && result.Count > 0)
  870. ret = false;
  871. if (ret)
  872. {
  873. cmd = new Command("Get-MailContact");
  874. cmd.Parameters.Add("OrganizationalUnit", ou);
  875. result = ExecuteShellCommand(runSpace, cmd);
  876. if (result != null && result.Count > 0)
  877. ret = false;
  878. }
  879. if (ret)
  880. {
  881. cmd = new Command("Get-DistributionGroup");
  882. cmd.Parameters.Add("OrganizationalUnit", ou);
  883. cmd.Parameters.Add("RecipientTypeDetails", "MailUniversalDistributionGroup");
  884. result = ExecuteShellCommand(runSpace, cmd);
  885. if (result != null && result.Count > 0)
  886. ret = false;
  887. }
  888. if (ret)
  889. {
  890. cmd = new Command("Get-PublicFolder");
  891. cmd.Parameters.Add("Identity", "\\" + organizationId);
  892. cmd.Parameters.Add("GetChildren", new SwitchParameter(true));
  893. if (!string.IsNullOrEmpty(PublicFolderServer))
  894. cmd.Parameters.Add("Server", PublicFolderServer);
  895. result = ExecuteShellCommand(runSpace, cmd);
  896. if (result != null && result.Count > 0)
  897. ret = false;
  898. }
  899. ExchangeLog.LogEnd("CanDeleteOrganization");
  900. return ret;
  901. }
  902. internal bool DeleteOrganizationMailboxes(Runspace runSpace, string ou)
  903. {
  904. ExchangeLog.LogStart("DeleteOrganizationMailboxes");
  905. bool ret = true;
  906. Command cmd = new Command("Get-Mailbox");
  907. cmd.Parameters.Add("OrganizationalUnit", ou);
  908. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  909. if (result != null && result.Count > 0)
  910. {
  911. foreach (PSObject obj in result)
  912. {
  913. string id = null;
  914. try
  915. {
  916. id = ObjToString(GetPSObjectProperty(obj, "Identity"));
  917. RemoveDevicesInternal(runSpace, id);
  918. RemoveMailbox(runSpace, id);
  919. }
  920. catch (Exception ex)
  921. {
  922. ret = false;
  923. ExchangeLog.LogError(string.Format("Can't delete mailbox {0}", id), ex);
  924. }
  925. }
  926. }
  927. ExchangeLog.LogEnd("DeleteOrganizationMailboxes");
  928. return ret;
  929. }
  930. internal bool DeleteOrganizationContacts(Runspace runSpace, string ou)
  931. {
  932. ExchangeLog.LogStart("DeleteOrganizationContacts");
  933. bool ret = true;
  934. Command cmd = new Command("Get-MailContact");
  935. cmd.Parameters.Add("OrganizationalUnit", ou);
  936. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  937. if (result != null && result.Count > 0)
  938. {
  939. foreach (PSObject obj in result)
  940. {
  941. string id = null;
  942. try
  943. {
  944. id = ObjToString(GetPSObjectProperty(obj, "Identity"));
  945. RemoveContact(runSpace, id);
  946. }
  947. catch (Exception ex)
  948. {
  949. ret = false;
  950. ExchangeLog.LogError(string.Format("Can't delete contact {0}", id), ex);
  951. }
  952. }
  953. }
  954. ExchangeLog.LogEnd("DeleteOrganizationContacts");
  955. return ret;
  956. }
  957. internal bool DeleteOrganizationDistributionLists(Runspace runSpace, string ou)
  958. {
  959. ExchangeLog.LogStart("DeleteOrganizationDistributionLists");
  960. bool ret = true;
  961. Command cmd = new Command("Get-DistributionGroup");
  962. cmd.Parameters.Add("OrganizationalUnit", ou);
  963. cmd.Parameters.Add("RecipientTypeDetails", "MailUniversalDistributionGroup");
  964. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  965. if (result != null && result.Count > 0)
  966. {
  967. foreach (PSObject obj in result)
  968. {
  969. string id = null;
  970. try
  971. {
  972. id = ObjToString(GetPSObjectProperty(obj, "Identity"));
  973. RemoveDistributionGroup(runSpace, id);
  974. }
  975. catch (Exception ex)
  976. {
  977. ret = false;
  978. ExchangeLog.LogError(string.Format("Can't delete distribution list {0}", id), ex);
  979. }
  980. }
  981. }
  982. ExchangeLog.LogEnd("DeleteOrganizationDistributionLists");
  983. return ret;
  984. }
  985. private bool DeleteOrganizationPublicFolders(Runspace runSpace, string organizationId)
  986. {
  987. ExchangeLog.LogStart("DeleteOrganizationPublicFolders");
  988. bool ret = true;
  989. //Delete public folders.
  990. string publicFolder = "\\" + organizationId;
  991. try
  992. {
  993. RemovePublicFolder(runSpace, publicFolder);
  994. }
  995. catch (Exception ex)
  996. {
  997. ret = false;
  998. ExchangeLog.LogError(string.Format("Can't delete public folder {0}", publicFolder), ex);
  999. }
  1000. ExchangeLog.LogEnd("DeleteOrganizationPublicFolders");
  1001. return ret;
  1002. }
  1003. internal bool DeleteOrganizationAcceptedDomains(Runspace runSpace, List<ExchangeDomainName> acceptedDomains)
  1004. {
  1005. ExchangeLog.LogStart("DeleteOrganizationAcceptedDomains");
  1006. bool ret = true;
  1007. if (acceptedDomains != null)
  1008. {
  1009. foreach (ExchangeDomainName domain in acceptedDomains)
  1010. {
  1011. try
  1012. {
  1013. DeleteAcceptedDomain(runSpace, domain.DomainName);
  1014. }
  1015. catch (Exception ex)
  1016. {
  1017. ExchangeLog.LogError(string.Format("Failed to delete accepted domain {0}", domain), ex);
  1018. ret = false;
  1019. }
  1020. }
  1021. }
  1022. ExchangeLog.LogEnd("DeleteOrganizationAcceptedDomains");
  1023. return ret;
  1024. }
  1025. private void SetOrganizationStorageLimitsInternal(string organizationDistinguishedName, long issueWarningKB,
  1026. long prohibitSendKB, long prohibitSendReceiveKB, int keepDeletedItemsDays)
  1027. {
  1028. ExchangeLog.LogStart("SetOrganizationStorageLimitsInternal");
  1029. ExchangeLog.DebugInfo("Organization Id: {0}", organizationDistinguishedName);
  1030. Runspace runSpace = null;
  1031. try
  1032. {
  1033. runSpace = OpenRunspace();
  1034. string org = ConvertADPathToCanonicalName(organizationDistinguishedName);
  1035. Unlimited<ByteQuantifiedSize> issueWarningQuota = ConvertKBToUnlimited(issueWarningKB);
  1036. Unlimited<ByteQuantifiedSize> prohibitSendQuota = ConvertKBToUnlimited(prohibitSendKB);
  1037. Unlimited<ByteQuantifiedSize> prohibitSendReceiveQuota = ConvertKBToUnlimited(prohibitSendReceiveKB);
  1038. EnhancedTimeSpan retainDeletedItemsFor = ConvertDaysToEnhancedTimeSpan(keepDeletedItemsDays);
  1039. Command cmd = new Command("Get-Mailbox");
  1040. cmd.Parameters.Add("OrganizationalUnit", org);

Large files files are truncated, but you can click here to view the full file