PageRenderTime 84ms CodeModel.GetById 16ms 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
  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);
  1041. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  1042. foreach (PSObject obj in result)
  1043. {
  1044. string id = ObjToString(GetPSObjectProperty(obj, "Identity"));
  1045. cmd = new Command("Set-Mailbox");
  1046. cmd.Parameters.Add("Identity", id);
  1047. cmd.Parameters.Add("IssueWarningQuota", issueWarningQuota);
  1048. cmd.Parameters.Add("ProhibitSendQuota", prohibitSendQuota);
  1049. cmd.Parameters.Add("ProhibitSendReceiveQuota", prohibitSendReceiveQuota);
  1050. cmd.Parameters.Add("RetainDeletedItemsFor", retainDeletedItemsFor);
  1051. ExecuteShellCommand(runSpace, cmd);
  1052. }
  1053. }
  1054. finally
  1055. {
  1056. CloseRunspace(runSpace);
  1057. }
  1058. ExchangeLog.LogEnd("SetOrganizationStorageLimitsInternal");
  1059. }
  1060. private ExchangeItemStatistics[] GetMailboxesStatisticsInternal(string organizationDistinguishedName)
  1061. {
  1062. ExchangeLog.LogStart("GetMailboxesStatisticsInternal");
  1063. ExchangeLog.DebugInfo("Organization Id: {0}", organizationDistinguishedName);
  1064. List<ExchangeItemStatistics> ret = new List<ExchangeItemStatistics>();
  1065. Runspace runSpace = null;
  1066. try
  1067. {
  1068. runSpace = OpenRunspace();
  1069. string org = ConvertADPathToCanonicalName(organizationDistinguishedName);
  1070. Command cmd = new Command("Get-Mailbox");
  1071. cmd.Parameters.Add("OrganizationalUnit", org);
  1072. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  1073. foreach (PSObject obj in result)
  1074. {
  1075. string id = ObjToString(GetPSObjectProperty(obj, "Identity"));
  1076. cmd = new Command("Get-MailboxStatistics");
  1077. cmd.Parameters.Add("Identity", id);
  1078. result = ExecuteShellCommand(runSpace, cmd);
  1079. if (result != null && result.Count > 0)
  1080. {
  1081. PSObject mailbox = result[0];
  1082. ExchangeItemStatistics info = new ExchangeItemStatistics();
  1083. info.ItemName = (string)GetPSObjectProperty(mailbox, "DisplayName");
  1084. Unlimited<ByteQuantifiedSize> totalItemSize =
  1085. (Unlimited<ByteQuantifiedSize>)GetPSObjectProperty(mailbox, "TotalItemSize");
  1086. info.TotalSizeMB = ConvertUnlimitedToMB(totalItemSize);
  1087. uint? itemCount = (uint?)GetPSObjectProperty(mailbox, "ItemCount");
  1088. info.TotalItems = ConvertNullableToInt32(itemCount);
  1089. DateTime? lastLogoffTime = (DateTime?)GetPSObjectProperty(mailbox, "LastLogoffTime");
  1090. DateTime? lastLogonTime = (DateTime?)GetPSObjectProperty(mailbox, "LastLogonTime");
  1091. info.LastLogoff = ConvertNullableToDateTime(lastLogoffTime);
  1092. info.LastLogon = ConvertNullableToDateTime(lastLogonTime);
  1093. ret.Add(info);
  1094. }
  1095. }
  1096. }
  1097. finally
  1098. {
  1099. CloseRunspace(runSpace);
  1100. }
  1101. ExchangeLog.LogEnd("GetMailboxesStatisticsInternal");
  1102. return ret.ToArray();
  1103. }
  1104. private void ChangeOrganizationState(string organizationDistinguishedName, bool enabled)
  1105. {
  1106. ExchangeLog.LogStart("ChangeOrganizationState");
  1107. ExchangeLog.DebugInfo("Organization: {0}", organizationDistinguishedName);
  1108. Runspace runSpace = null;
  1109. try
  1110. {
  1111. string ouName = ConvertADPathToCanonicalName(organizationDistinguishedName);
  1112. runSpace = OpenRunspace();
  1113. Command cmd = new Command("Get-Mailbox");
  1114. cmd.Parameters.Add("OrganizationalUnit", ouName);
  1115. cmd.Parameters.Add("Filter", "CustomAttribute2 -ne 'disabled'");
  1116. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  1117. foreach (PSObject obj in result)
  1118. {
  1119. string id = (string)GetPSObjectProperty(obj, "DistinguishedName");
  1120. ChangeMailboxState(id, enabled);
  1121. }
  1122. }
  1123. finally
  1124. {
  1125. CloseRunspace(runSpace);
  1126. }
  1127. ExchangeLog.LogEnd("ChangeOrganizationState");
  1128. }
  1129. private long CalculateOrganizationDiskSpace(string organizationId, string organizationDistinguishedName)
  1130. {
  1131. ExchangeLog.LogStart("CalculateOrganizationDiskSpace");
  1132. ExchangeLog.DebugInfo("Organization Id: {0}", organizationId);
  1133. long size = 0;
  1134. Runspace runSpace = null;
  1135. try
  1136. {
  1137. runSpace = OpenRunspace();
  1138. size += CalculateMailboxDiskSpace(runSpace, organizationDistinguishedName);
  1139. size += CalculatePublicFolderDiskSpace(runSpace, "\\" + organizationId);
  1140. }
  1141. finally
  1142. {
  1143. CloseRunspace(runSpace);
  1144. }
  1145. ExchangeLog.LogEnd("CalculateOrganizationDiskSpace");
  1146. return size;
  1147. }
  1148. private long CalculateMailboxDiskSpace(Runspace runSpace, string organizationDistinguishedName)
  1149. {
  1150. ExchangeLog.LogStart("CalculateMailboxDiskSpace");
  1151. ExchangeLog.DebugInfo("Organization DN: {0}", organizationDistinguishedName);
  1152. long size = 0;
  1153. string org = ConvertADPathToCanonicalName(organizationDistinguishedName);
  1154. Command cmd = new Command("Get-Mailbox");
  1155. cmd.Parameters.Add("OrganizationalUnit", org);
  1156. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  1157. foreach (PSObject obj in result)
  1158. {
  1159. string id = ObjToString(GetPSObjectProperty(obj, "Identity"));
  1160. cmd = new Command("Get-MailboxStatistics");
  1161. cmd.Parameters.Add("Identity", id);
  1162. result = ExecuteShellCommand(runSpace, cmd);
  1163. if (result != null && result.Count > 0)
  1164. {
  1165. Unlimited<ByteQuantifiedSize> totalItemSize =
  1166. (Unlimited<ByteQuantifiedSize>)GetPSObjectProperty(result[0], "TotalItemSize");
  1167. size += ConvertUnlimitedToBytes(totalItemSize);
  1168. }
  1169. }
  1170. ExchangeLog.LogEnd("CalculateMailboxDiskSpace");
  1171. return size;
  1172. }
  1173. internal virtual long CalculatePublicFolderDiskSpace(Runspace runSpace, string folder)
  1174. {
  1175. ExchangeLog.LogStart("CalculatePublicFolderDiskSpace");
  1176. ExchangeLog.DebugInfo("Folder: {0}", folder);
  1177. long size = 0;
  1178. Command cmd = new Command("Get-PublicFolderDatabase");
  1179. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  1180. if (result != null && result.Count > 0)
  1181. {
  1182. cmd = new Command("Get-PublicFolderStatistics");
  1183. cmd.Parameters.Add("Identity", folder);
  1184. if (!string.IsNullOrEmpty(PublicFolderServer))
  1185. cmd.Parameters.Add("Server", PublicFolderServer);
  1186. result = ExecuteShellCommand(runSpace, cmd);
  1187. if (result != null && result.Count > 0)
  1188. {
  1189. PSObject obj = result[0];
  1190. Unlimited<ByteQuantifiedSize> totalItemSize =
  1191. (Unlimited<ByteQuantifiedSize>)GetPSObjectProperty(obj, "TotalItemSize");
  1192. size += ConvertUnlimitedToBytes(totalItemSize);
  1193. }
  1194. cmd = new Command("Get-PublicFolder");
  1195. cmd.Parameters.Add("Identity", folder);
  1196. cmd.Parameters.Add("GetChildren", new SwitchParameter(true));
  1197. if (!string.IsNullOrEmpty(PublicFolderServer))
  1198. cmd.Parameters.Add("Server", PublicFolderServer);
  1199. result = ExecuteShellCommand(runSpace, cmd);
  1200. foreach (PSObject obj in result)
  1201. {
  1202. string id = ObjToString(GetPSObjectProperty(obj, "Identity"));
  1203. size += CalculatePublicFolderDiskSpace(runSpace, id);
  1204. }
  1205. }
  1206. else
  1207. size = 0;
  1208. ExchangeLog.LogEnd("CalculatePublicFolderDiskSpace");
  1209. return size;
  1210. }
  1211. #endregion
  1212. #region Mailboxes
  1213. private void SetExtendedRights(Runspace runSpace, string identity, string user, string rights)
  1214. {
  1215. ExchangeLog.LogStart("SetExtendedRights");
  1216. Command cmd = new Command("Add-ADPermission");
  1217. cmd.Parameters.Add("Identity", identity);
  1218. cmd.Parameters.Add("User", user);
  1219. cmd.Parameters.Add("ExtendedRights", rights);
  1220. ExecuteShellCommand(runSpace, cmd);
  1221. ExchangeLog.LogEnd("SetExtendedRights");
  1222. }
  1223. private void SetMailboxPermission(Runspace runSpace, string accountName, string user, string accessRights)
  1224. {
  1225. ExchangeLog.LogStart("SetMailboxPermission");
  1226. Command cmd = new Command("Add-MailboxPermission");
  1227. cmd.Parameters.Add("Identity", accountName);
  1228. cmd.Parameters.Add("User", user);
  1229. cmd.Parameters.Add("AccessRights", accessRights);
  1230. ExecuteShellCommand(runSpace, cmd);
  1231. ExchangeLog.LogEnd("SetMailboxPermission");
  1232. }
  1233. private ExchangeAccount[] GetMailboxSendAsAccounts(Runspace runSpace, string organizationId, string accountName)
  1234. {
  1235. ExchangeLog.LogStart("GetMailboxSendAsAccounts");
  1236. string cn = GetMailboxCommonName(runSpace, accountName);
  1237. ExchangeAccount[] ret = GetSendAsAccounts(runSpace, organizationId, cn);
  1238. ExchangeLog.LogEnd("GetMailboxSendAsAccounts");
  1239. return ret;
  1240. }
  1241. private ExchangeAccount[] GetSendAsAccounts(Runspace runSpace, string organizationId, string accountId)
  1242. {
  1243. ExchangeLog.LogStart("GetSendAsAccounts");
  1244. Command cmd = new Command("Get-ADPermission");
  1245. cmd.Parameters.Add("Identity", accountId);
  1246. Collection<PSObject> results = ExecuteShellCommand(runSpace, cmd);
  1247. List<ExchangeAccount> accounts = new List<ExchangeAccount>();
  1248. foreach (PSObject current in results)
  1249. {
  1250. string user = GetPSObjectProperty(current, "User").ToString();
  1251. Array extendedRights = GetPSObjectProperty(current, "ExtendedRights") as Array;
  1252. if (extendedRights != null)
  1253. {
  1254. foreach (object obj in extendedRights)
  1255. {
  1256. string strRightName = obj.ToString();
  1257. if (string.Compare(strRightName, "Send-as", true) == 0)
  1258. {
  1259. ExchangeAccount account = GetOrganizationAccount(runSpace, organizationId, user);
  1260. if (account != null)
  1261. accounts.Add(account);
  1262. }
  1263. }
  1264. }
  1265. }
  1266. ExchangeLog.LogEnd("GetSendAsAccounts");
  1267. return accounts.ToArray();
  1268. }
  1269. private ExchangeAccount[] GetMailBoxFullAccessAcounts(Runspace runSpace, string organizationId, string accountName)
  1270. {
  1271. ExchangeLog.LogStart("GetMailBoxFullAccessAcounts");
  1272. Command cmd = new Command("Get-MailboxPermission");
  1273. cmd.Parameters.Add("Identity", accountName);
  1274. Collection<PSObject> results = ExecuteShellCommand(runSpace, cmd);
  1275. List<ExchangeAccount> accounts = new List<ExchangeAccount>();
  1276. foreach (PSObject current in results)
  1277. {
  1278. string user = GetPSObjectProperty(current, "User").ToString();
  1279. Array accessRights = GetPSObjectProperty(current, "AccessRights") as Array;
  1280. if (accessRights != null)
  1281. {
  1282. foreach (object obj in accessRights)
  1283. {
  1284. string strRightName = obj.ToString();
  1285. if (string.Compare(strRightName, "FullAccess", true) == 0)
  1286. {
  1287. ExchangeAccount account = GetOrganizationAccount(runSpace, organizationId, user);
  1288. if (account != null)
  1289. accounts.Add(account);
  1290. }
  1291. }
  1292. }
  1293. }
  1294. ExchangeLog.LogEnd("GetMailBoxFullAccessAcounts");
  1295. return accounts.ToArray();
  1296. }
  1297. private ExchangeMailbox GetMailboxPermissionsInternal(string organizationId, string accountName, Runspace runspace)
  1298. {
  1299. ExchangeLog.LogStart("GetMailboxPermissionsInternal");
  1300. if (string.IsNullOrEmpty(accountName))
  1301. throw new ArgumentNullException("accountName");
  1302. ExchangeMailbox exchangeMailbox = null;
  1303. bool closeRunspace = false;
  1304. try
  1305. {
  1306. if (runspace == null)
  1307. {
  1308. runspace = OpenRunspace();
  1309. closeRunspace = true;
  1310. }
  1311. exchangeMailbox = new ExchangeMailbox();
  1312. exchangeMailbox.FullAccessAccounts = GetMailBoxFullAccessAcounts(runspace, organizationId, accountName);
  1313. exchangeMailbox.SendAsAccounts = GetMailboxSendAsAccounts(runspace, organizationId, accountName);
  1314. }
  1315. catch (Exception ex)
  1316. {
  1317. ExchangeLog.LogError(ex);
  1318. throw ex;
  1319. }
  1320. finally
  1321. {
  1322. if (closeRunspace)
  1323. CloseRunspace(runspace);
  1324. }
  1325. ExchangeLog.LogEnd("GetMailboxPermissionsInternal");
  1326. return exchangeMailbox;
  1327. }
  1328. private void SetSendAsPermissions(Runspace runSpace, ExchangeAccount[] existingAccounts, string accountId, string[] accounts)
  1329. {
  1330. ExchangeLog.LogStart("SetSendAsPermissions");
  1331. if (string.IsNullOrEmpty(accountId))
  1332. throw new ArgumentNullException("accountId");
  1333. if (accounts == null)
  1334. throw new ArgumentNullException("accounts");
  1335. ExchangeTransaction transaction = null;
  1336. try
  1337. {
  1338. transaction = StartTransaction();
  1339. string[] resAccounts = MergeADPermission(runSpace, existingAccounts, accountId, accounts, transaction);
  1340. foreach (string id in resAccounts)
  1341. {
  1342. SetExtendedRights(runSpace, accountId, id, "Send-as");
  1343. transaction.AddSendAsPermission(accountId, id);
  1344. }
  1345. }
  1346. catch (Exception)
  1347. {
  1348. RollbackTransaction(transaction);
  1349. throw;
  1350. }
  1351. ExchangeLog.LogEnd("SetSendAsPermissions");
  1352. }
  1353. private void SetMailboxPermissionsInternal(string organizationId, string accountName, string[] sendAsAccounts, string[] fullAccessAccounts)
  1354. {
  1355. ExchangeLog.LogStart("SetMailboxPermissionsInternal");
  1356. if (string.IsNullOrEmpty(accountName))
  1357. throw new ArgumentNullException("accountName");
  1358. if (sendAsAccounts == null)
  1359. throw new ArgumentNullException("sendAsAccounts");
  1360. if (fullAccessAccounts == null)
  1361. throw new ArgumentNullException("fullAccessAccounts");
  1362. Runspace runSpace = null;
  1363. try
  1364. {
  1365. runSpace = OpenRunspace();
  1366. string cn = GetMailboxCommonName(runSpace, accountName);
  1367. ExchangeMailbox mailbox = GetMailboxPermissionsInternal(organizationId, accountName, runSpace);
  1368. SetSendAsPermissions(runSpace, mailbox.SendAsAccounts, cn, sendAsAccounts);
  1369. SetMailboxFullAccessPermissions(runSpace, mailbox.FullAccessAccounts, accountName, fullAccessAccounts);
  1370. }
  1371. catch (Exception ex)
  1372. {
  1373. ExchangeLog.LogError(ex);
  1374. throw;
  1375. }
  1376. finally
  1377. {
  1378. CloseRunspace(runSpace);
  1379. }
  1380. ExchangeLog.LogEnd("SetMailboxPermissionsInternal");
  1381. }
  1382. internal void RemoveMailboxAccessPermission(Runspace runSpace, string accountName, string account, string accessRights)
  1383. {
  1384. ExchangeLog.LogStart("RemoveMailboxFullAccessPermission");
  1385. Command cmd = new Command("Remove-MailboxPermission");
  1386. cmd.Parameters.Add("Identity", accountName);
  1387. cmd.Parameters.Add("User", account);
  1388. cmd.Parameters.Add("AccessRights", accessRights);
  1389. cmd.Parameters.Add("Confirm", false);
  1390. ExecuteShellCommand(runSpace, cmd);
  1391. ExchangeLog.LogEnd("RemoveMailboxFullAccessPermission");
  1392. }
  1393. private string[] MergeMailboxFullAccessPermissions(Runspace runSpace, ExchangeAccount[] existingAccounts, string accountName, string[] newAccounts, ExchangeTransaction transaction)
  1394. {
  1395. ExchangeLog.LogStart("MergeMailboxFullAccessPermissions");
  1396. List<string> temp = new List<string>(newAccounts);
  1397. Array.Sort(newAccounts);
  1398. foreach (ExchangeAccount exist in existingAccounts)
  1399. {
  1400. if (Array.BinarySearch<string>(newAccounts, exist.AccountName, StringComparer.Create(CultureInfo.InvariantCulture, true)) >= 0)
  1401. {
  1402. temp.Remove(exist.AccountName);
  1403. continue;
  1404. }
  1405. RemoveMailboxAccessPermission(runSpace, accountName, exist.AccountName, "FullAccess");
  1406. transaction.RemoveMailboxFullAccessPermission(accountName, exist.AccountName);
  1407. }
  1408. ExchangeLog.LogEnd("MergeMailboxFullAccessPermissions");
  1409. return temp.ToArray();
  1410. }
  1411. private void SetMailboxFullAccessPermissions(Runspace runSpace, ExchangeAccount[] existingAccounts, string accountName, string[] accounts)
  1412. {
  1413. ExchangeLog.LogStart("SetMailboxFullAccessPermissions");
  1414. if (string.IsNullOrEmpty(accountName))
  1415. throw new ArgumentNullException("accountName");
  1416. if (accounts == null)
  1417. throw new ArgumentNullException("accounts");
  1418. ExchangeTransaction transaction = StartTransaction();
  1419. try
  1420. {
  1421. string[] resAccounts = MergeMailboxFullAccessPermissions(runSpace, existingAccounts, accountName, accounts, transaction);
  1422. foreach (string id in resAccounts)
  1423. {
  1424. SetMailboxPermission(runSpace, accountName, id, "FullAccess");
  1425. transaction.AddMailBoxFullAccessPermission(accountName, id);
  1426. }
  1427. }
  1428. catch (Exception)
  1429. {
  1430. RollbackTransaction(transaction);
  1431. throw;
  1432. }
  1433. ExchangeLog.LogEnd("SetMailboxFullAccessPermissions");
  1434. }
  1435. private void RemoveADPermission(Runspace runSpace, string identity, string account, string accessRights, string extendedRights, string properties)
  1436. {
  1437. ExchangeLog.LogStart("RemoveADPermission");
  1438. Command cmd = new Command("Remove-ADPermission");
  1439. cmd.Parameters.Add("Identity", identity);
  1440. cmd.Parameters.Add("User", account);
  1441. cmd.Parameters.Add("InheritanceType", "All");
  1442. cmd.Parameters.Add("AccessRights", accessRights);
  1443. cmd.Parameters.Add("ExtendedRights", extendedRights);
  1444. cmd.Parameters.Add("ChildObjectTypes", null);
  1445. cmd.Parameters.Add("InheritedObjectType", null);
  1446. cmd.Parameters.Add("Properties", properties);
  1447. cmd.Parameters.Add("Confirm", false);
  1448. ExecuteShellCommand(runSpace, cmd);
  1449. ExchangeLog.LogEnd("RemoveADPermission");
  1450. }
  1451. private void AddADPermission(Runspace runSpace, string identity, string user, string accessRights, string extendedRights, string properties)
  1452. {
  1453. ExchangeLog.LogStart("AddADPermission");
  1454. Command cmd = new Command("Add-ADPermission");
  1455. cmd.Parameters.Add("Identity", identity);
  1456. cmd.Parameters.Add("User", user);
  1457. cmd.Parameters.Add("AccessRights", accessRights);
  1458. cmd.Parameters.Add("ExtendedRights", extendedRights);
  1459. cmd.Parameters.Add("Properties", properties);
  1460. //cmd.Parameters.Add("Confirm", false);
  1461. ExecuteShellCommand(runSpace, cmd);
  1462. ExchangeLog.LogEnd("AddADPermission");
  1463. }
  1464. private string[] MergeADPermission(Runspace runSpace, ExchangeAccount[] existingAccounts, string identity, string[] newAccounts, ExchangeTransaction transaction)
  1465. {
  1466. ExchangeLog.LogStart("MergeADPermission");
  1467. List<string> temp = new List<string>(newAccounts);
  1468. Array.Sort<string>(newAccounts);
  1469. foreach (ExchangeAccount current in existingAccounts)
  1470. {
  1471. if (Array.BinarySearch<string>(newAccounts, current.AccountName, StringComparer.Create(CultureInfo.InvariantCulture, true)) >= 0)
  1472. {
  1473. temp.Remove(current.AccountName);
  1474. continue;
  1475. }
  1476. RemoveADPermission(runSpace, identity, current.AccountName, null, "Send-as", null);
  1477. transaction.RemoveSendAsPermission(identity, current.AccountName);
  1478. }
  1479. ExchangeLog.LogEnd("MergeADPermission");
  1480. return temp.ToArray();
  1481. }
  1482. public string CreateMailEnableUser(string upn, string organizationId, string organizationDistinguishedName,
  1483. string securityGroup, string organizationDomain,
  1484. ExchangeAccountType accountType,
  1485. string mailboxDatabase, string offlineAddressBook, string addressBookPolicy,
  1486. string accountName, bool enablePOP, bool enableIMAP,
  1487. bool enableOWA, bool enableMAPI, bool enableActiveSync,
  1488. long issueWarningKB, long prohibitSendKB, long prohibitSendReceiveKB, int keepDeletedItemsDays,
  1489. int maxRecipients, int maxSendMessageSizeKB, int maxReceiveMessageSizeKB, bool hideFromAddressBook, bool IsConsumer, bool enabledLitigationHold, long recoverabelItemsSpace, long recoverabelItemsWarning)
  1490. {
  1491. return CreateMailEnableUserInternal(upn, organizationId, organizationDistinguishedName, accountType,
  1492. mailboxDatabase, offlineAddressBook, addressBookPolicy,
  1493. accountName, enablePOP, enableIMAP,
  1494. enableOWA, enableMAPI, enableActiveSync,
  1495. issueWarningKB, prohibitSendKB, prohibitSendReceiveKB,
  1496. keepDeletedItemsDays, maxRecipients, maxSendMessageSizeKB, maxReceiveMessageSizeKB, hideFromAddressBook, IsConsumer, enabledLitigationHold, recoverabelItemsSpace, recoverabelItemsWarning);
  1497. }
  1498. internal virtual string CreateMailEnableUserInternal(string upn, string organizationId, string organizationDistinguishedName, ExchangeAccountType accountType,
  1499. string mailboxDatabase, string offlineAddressBook, string addressBookPolicy,
  1500. string accountName, bool enablePOP, bool enableIMAP,
  1501. bool enableOWA, bool enableMAPI, bool enableActiveSync,
  1502. long issueWarningKB, long prohibitSendKB, long prohibitSendReceiveKB, int keepDeletedItemsDays,
  1503. int maxRecipients, int maxSendMessageSizeKB, int maxReceiveMessageSizeKB, bool hideFromAddressBook, bool IsConsumer,bool enabledLitigationHold, long recoverabelItemsSpace, long recoverabelItemsWarning)
  1504. {
  1505. ExchangeLog.LogStart("CreateMailEnableUserInternal");
  1506. ExchangeLog.DebugInfo("Organization Id: {0}", organizationId);
  1507. string ret = null;
  1508. ExchangeTransaction transaction = StartTransaction();
  1509. Runspace runSpace = null;
  1510. int attempts = 0;
  1511. string id = null;
  1512. Version exchangeVersion = GetExchangeVersion();
  1513. try
  1514. {
  1515. runSpace = OpenRunspace();
  1516. Command cmd = null;
  1517. Collection<PSObject> result = null;
  1518. //try to enable mail user for 10 times
  1519. while (true)
  1520. {
  1521. try
  1522. {
  1523. //create mailbox
  1524. cmd = new Command("Enable-Mailbox");
  1525. cmd.Parameters.Add("Identity", upn);
  1526. cmd.Parameters.Add("Alias", accountName);
  1527. if (!(mailboxDatabase == "*" && exchangeVersion >= new Version(14, 0)))
  1528. cmd.Parameters.Add("Database", mailboxDatabase);
  1529. if (accountType == ExchangeAccountType.Equipment)
  1530. cmd.Parameters.Add("Equipment");
  1531. else if (accountType == ExchangeAccountType.Room)
  1532. cmd.Parameters.Add("Room");
  1533. result = ExecuteShellCommand(runSpace, cmd);
  1534. id = CheckResultObjectDN(result);
  1535. }
  1536. catch (Exception ex)
  1537. {
  1538. ExchangeLog.LogError(ex);
  1539. }
  1540. if (id != null)
  1541. break;
  1542. if (attempts > 9)
  1543. throw new Exception(
  1544. string.Format("Could not enable mail user '{0}' ", accountName));
  1545. attempts++;
  1546. ExchangeLog.LogWarning("Attempt #{0} to enable mail user failed!", attempts);
  1547. // wait 5 sec
  1548. System.Threading.Thread.Sleep(5000);
  1549. }
  1550. //transaction.RegisterNewMailbox(id);
  1551. string windowsEmailAddress = ObjToString(GetPSObjectProperty(result[0], "WindowsEmailAddress"));
  1552. //update mailbox
  1553. cmd = new Command("Set-Mailbox");
  1554. cmd.Parameters.Add("Identity", id);
  1555. cmd.Parameters.Add("OfflineAddressBook", offlineAddressBook);
  1556. cmd.Parameters.Add("EmailAddressPolicyEnabled", false);
  1557. cmd.Parameters.Add("CustomAttribute1", organizationId);
  1558. cmd.Parameters.Add("CustomAttribute3", windowsEmailAddress);
  1559. cmd.Parameters.Add("PrimarySmtpAddress", upn);
  1560. cmd.Parameters.Add("WindowsEmailAddress", upn);
  1561. cmd.Parameters.Add("UseDatabaseQuotaDefaults", new bool?(false));
  1562. cmd.Parameters.Add("UseDatabaseRetentionDefaults", false);
  1563. cmd.Parameters.Add("IssueWarningQuota", ConvertKBToUnlimited(issueWarningKB));
  1564. cmd.Parameters.Add("ProhibitSendQuota", ConvertKBToUnlimited(prohibitSendKB));
  1565. cmd.Parameters.Add("ProhibitSendReceiveQuota", ConvertKBToUnlimited(prohibitSendReceiveKB));
  1566. cmd.Parameters.Add("RetainDeletedItemsFor", ConvertDaysToEnhancedTimeSpan(keepDeletedItemsDays));
  1567. cmd.Parameters.Add("RecipientLimits", ConvertInt32ToUnlimited(maxRecipients));
  1568. cmd.Parameters.Add("MaxSendSize", ConvertKBToUnlimited(maxSendMessageSizeKB));
  1569. cmd.Parameters.Add("MaxReceiveSize", ConvertKBToUnlimited(maxReceiveMessageSizeKB));
  1570. cmd.Parameters.Add("HiddenFromAddressListsEnabled", hideFromAddressBook);
  1571. ExecuteShellCommand(runSpace, cmd);
  1572. //update AD object
  1573. string globalAddressListName = this.GetGlobalAddressListName(organizationId);
  1574. string globalAddressListDN = this.GetGlobalAddressListDN(runSpace, globalAddressListName);
  1575. string path = AddADPrefix(id);
  1576. DirectoryEntry mailbox = GetADObject(path);
  1577. // check if msExchQueryBaseDN must be cleared for Exchange 2010 SP1
  1578. bool clearQueryBaseDN = false;
  1579. if (ConfigurationManager.AppSettings[CONFIG_CLEAR_QUERYBASEDN] != null)
  1580. clearQueryBaseDN = Boolean.Parse(ConfigurationManager.AppSettings[CONFIG_CLEAR_QUERYBASEDN]);
  1581. if (!(clearQueryBaseDN && (exchangeVersion >= new Version(14, 1))))
  1582. SetADObjectPropertyValue(mailbox, "msExchQueryBaseDN", globalAddressListDN);
  1583. //SetADObjectPropertyValue(mailbox, "msExchUseOAB", offlineAddressBook);
  1584. mailbox.CommitChanges();
  1585. mailbox.Close();
  1586. //Client Access
  1587. cmd = new Command("Set-CASMailbox");
  1588. cmd.Parameters.Add("Identity", id);
  1589. cmd.Parameters.Add("ActiveSyncEnabled", enableActiveSync);
  1590. if (enableActiveSync)
  1591. {
  1592. cmd.Parameters.Add("ActiveSyncMailboxPolicy", organizationId);
  1593. }
  1594. cmd.Parameters.Add("OWAEnabled", enableOWA);
  1595. cmd.Parameters.Add("MAPIEnabled", enableMAPI);
  1596. cmd.Parameters.Add("PopEnabled", enablePOP);
  1597. cmd.Parameters.Add("ImapEnabled", enableIMAP);
  1598. ExecuteShellCommand(runSpace, cmd);
  1599. //calendar settings
  1600. if (accountType == ExchangeAccountType.Equipment || accountType == ExchangeAccountType.Room)
  1601. {
  1602. SetCalendarSettings(runSpace, id);
  1603. }
  1604. ret = string.Format("{0}\\{1}", GetNETBIOSDomainName(), accountName);
  1605. ExchangeLog.LogEnd("CreateMailEnableUserInternal");
  1606. return ret;
  1607. }
  1608. catch (Exception ex)
  1609. {
  1610. ExchangeLog.LogError("CreateMailEnableUserInternal", ex);
  1611. RollbackTransaction(transaction);
  1612. throw;
  1613. }
  1614. finally
  1615. {
  1616. CloseRunspace(runSpace);
  1617. }
  1618. }
  1619. /*
  1620. private string CreateMailboxInternal(string organizationId, string organizationDistinguishedName,
  1621. string mailboxDatabase, string securityGroup, string offlineAddressBook, ExchangeAccountType accountType,
  1622. string displayName,
  1623. string accountName, string name, string domain, string password, bool enablePOP, bool enableIMAP,
  1624. bool enableOWA, bool enableMAPI, bool enableActiveSync,
  1625. int issueWarningKB, int prohibitSendKB, int prohibitSendReceiveKB, int keepDeletedItemsDays)
  1626. {
  1627. ExchangeLog.LogStart("CreateMailboxInternal");
  1628. ExchangeLog.DebugInfo("Organization Id: {0}", organizationId);
  1629. ExchangeLog.DebugInfo("Name: {0}", name);
  1630. ExchangeLog.DebugInfo("Domain: {0}", domain);
  1631. string ret = null;
  1632. ExchangeTransaction transaction = StartTransaction();
  1633. Runspace runSpace = null;
  1634. Version exchangeVersion = GetExchangeVersion();
  1635. try
  1636. {
  1637. runSpace = OpenRunspace();
  1638. string upn = string.Format("{0}@{1}", name, domain);
  1639. SecureString securePassword = SecurityUtils.ConvertToSecureString(password);
  1640. string ouName = ConvertADPathToCanonicalName(organizationDistinguishedName);
  1641. //create mailbox
  1642. Command cmd = new Command("New-Mailbox");
  1643. cmd.Parameters.Add("Name", accountName);
  1644. cmd.Parameters.Add("OrganizationalUnit", ouName);
  1645. cmd.Parameters.Add("UserPrincipalName", upn);
  1646. cmd.Parameters.Add("SamAccountName", accountName);
  1647. cmd.Parameters.Add("Alias", accountName);
  1648. cmd.Parameters.Add("DisplayName", displayName);
  1649. cmd.Parameters.Add("Password", securePassword);
  1650. cmd.Parameters.Add("ResetPasswordOnNextLogon", false);
  1651. if (!(mailboxDatabase == "*" && exchangeVersion >= new Version(14, 0)))
  1652. cmd.Parameters.Add("Database", mailboxDatabase);
  1653. if (accountType == ExchangeAccountType.Equipment)
  1654. cmd.Parameters.Add("Equipment");
  1655. else if (accountType == ExchangeAccountType.Room)
  1656. cmd.Parameters.Add("Room");
  1657. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  1658. string id = GetResultObjectDN(result);
  1659. transaction.RegisterNewMailbox(id);
  1660. string windowsEmailAddress = ObjToString(GetPSObjectProperty(result[0], "WindowsEmailAddress"));
  1661. string adpstring = GetAddressPolicyName(organizationId);
  1662. //update mailbox
  1663. cmd = new Command("Set-Mailbox");
  1664. cmd.Parameters.Add("Identity", id);
  1665. cmd.Parameters.Add("OfflineAddressBook", offlineAddressBook);
  1666. cmd.Parameters.Add("EmailAddressPolicyEnabled", false);
  1667. cmd.Parameters.Add("CustomAttribute1", organizationId);
  1668. cmd.Parameters.Add("CustomAttribute3", windowsEmailAddress);
  1669. cmd.Parameters.Add("PrimarySmtpAddress", upn);
  1670. cmd.Parameters.Add("WindowsEmailAddress", upn);
  1671. bool enableSP2abp = false;
  1672. if (ConfigurationManager.AppSettings[CONFIG_ENABLESP2ABP] != null)
  1673. enableSP2abp = Boolean.Parse(ConfigurationManager.AppSettings[CONFIG_ENABLESP2ABP]);
  1674. if (enableSP2abp && (exchangeVersion >= new Version(14, 2)))
  1675. cmd.Parameters.Add("AddressBookPolicy", adpstring);
  1676. cmd.Parameters.Add("UseDatabaseQuotaDefaults", new bool?(false));
  1677. cmd.Parameters.Add("UseDatabaseRetentionDefaults", false);
  1678. cmd.Parameters.Add("IssueWarningQuota", ConvertKBToUnlimited(issueWarningKB));
  1679. cmd.Parameters.Add("ProhibitSendQuota", ConvertKBToUnlimited(prohibitSendKB));
  1680. cmd.Parameters.Add("ProhibitSendReceiveQuota", ConvertKBToUnlimited(prohibitSendReceiveKB));
  1681. cmd.Parameters.Add("RetainDeletedItemsFor", ConvertDaysToEnhancedTimeSpan(keepDeletedItemsDays));
  1682. ExecuteShellCommand(runSpace, cmd);
  1683. //update AD object
  1684. string globalAddressListName = GetGlobalAddressListName(organizationId);
  1685. string globalAddressListDN = GetGlobalAddressListDN(runSpace, globalAddressListName);
  1686. string path = AddADPrefix(id);
  1687. DirectoryEntry mailbox = GetADObject(path);
  1688. // check if msExchQueryBaseDN must be cleared for Exchange 2010 SP1
  1689. bool clearQueryBaseDN = false;
  1690. if (ConfigurationManager.AppSettings[CONFIG_CLEAR_QUERYBASEDN] != null)
  1691. clearQueryBaseDN = Boolean.Parse(ConfigurationManager.AppSettings[CONFIG_CLEAR_QUERYBASEDN]);
  1692. if (!(clearQueryBaseDN && (exchangeVersion >= new Version(14, 1))))
  1693. SetADObjectPropertyValue(mailbox, "msExchQueryBaseDN", globalAddressListDN);
  1694. //SetADObjectPropertyValue(mailbox, "msExchUseOAB", offlineAddressBook);
  1695. mailbox.CommitChanges();
  1696. mailbox.Close();
  1697. //Client Access
  1698. cmd = new Command("Set-CASMailbox");
  1699. cmd.Parameters.Add("Identity", id);
  1700. cmd.Parameters.Add("ActiveSyncEnabled", enableActiveSync);
  1701. if (enableActiveSync)
  1702. {
  1703. cmd.Parameters.Add("ActiveSyncMailboxPolicy", organizationId);
  1704. }
  1705. cmd.Parameters.Add("OWAEnabled", enableOWA);
  1706. cmd.Parameters.Add("MAPIEnabled", enableMAPI);
  1707. cmd.Parameters.Add("PopEnabled", enablePOP);
  1708. cmd.Parameters.Add("ImapEnabled", enableIMAP);
  1709. ExecuteShellCommand(runSpace, cmd);
  1710. //add to the security group
  1711. cmd = new Command("Add-DistributionGroupMember");
  1712. cmd.Parameters.Add("Identity", securityGroup);
  1713. cmd.Parameters.Add("Member", id);
  1714. ExecuteShellCommand(runSpace, cmd);
  1715. //calendar settings
  1716. if (accountType == ExchangeAccountType.Equipment || accountType == ExchangeAccountType.Room)
  1717. {
  1718. SetCalendarSettings(runSpace, id);
  1719. }
  1720. ret = string.Format("{0}\\{1}", GetNETBIOSDomainName(), accountName);
  1721. ExchangeLog.LogEnd("CreateMailboxInternal");
  1722. return ret;
  1723. }
  1724. catch (Exception ex)
  1725. {
  1726. ExchangeLog.LogError("CreateMailboxInternal", ex);
  1727. RollbackTransaction(transaction);
  1728. throw;
  1729. }
  1730. finally
  1731. {
  1732. CloseRunspace(runSpace);
  1733. }
  1734. }
  1735. */
  1736. internal virtual void SetCalendarSettings(Runspace runspace, string id)
  1737. {
  1738. ExchangeLog.LogStart("SetCalendarSettings");
  1739. Command cmd = new Command("Set-MailboxCalendarSettings");
  1740. cmd.Parameters.Add("Identity", id);
  1741. cmd.Parameters.Add("AutomateProcessing", CalendarProcessingFlags.AutoAccept);
  1742. ExecuteShellCommand(runspace, cmd);
  1743. ExchangeLog.LogEnd("SetCalendarSettings");
  1744. }
  1745. internal virtual void DeleteMailboxInternal(string accountName)
  1746. {
  1747. ExchangeLog.LogStart("DeleteMailboxInternal");
  1748. ExchangeLog.DebugInfo("Account Name: {0}", accountName);
  1749. Runspace runSpace = null;
  1750. try
  1751. {
  1752. runSpace = OpenRunspace();
  1753. RemoveDevicesInternal(runSpace, accountName);
  1754. RemoveMailbox(runSpace, accountName);
  1755. }
  1756. finally
  1757. {
  1758. CloseRunspace(runSpace);
  1759. }
  1760. ExchangeLog.LogEnd("DeleteMailboxInternal");
  1761. }
  1762. internal void RemoveMailbox(Runspace runSpace, string id)
  1763. {
  1764. ExchangeLog.LogStart("RemoveMailbox");
  1765. Command cmd = new Command("Remove-Mailbox");
  1766. cmd.Parameters.Add("Identity", id);
  1767. cmd.Parameters.Add("Permanent", false);
  1768. cmd.Parameters.Add("Confirm", false);
  1769. ExecuteShellCommand(runSpace, cmd);
  1770. ExchangeLog.LogEnd("RemoveMailbox");
  1771. }
  1772. private void DisableMailbox(Runspace runSpace, string id)
  1773. {
  1774. ExchangeLog.LogStart("DisableMailbox");
  1775. Command cmd = new Command("Disable-Mailbox");
  1776. cmd.Parameters.Add("Identity", id);
  1777. cmd.Parameters.Add("Confirm", false);
  1778. ExecuteShellCommand(runSpace, cmd);
  1779. ExchangeLog.LogEnd("DisableMailbox");
  1780. }
  1781. private string GetMailboxCommonName(Runspace runSpace, string accountName)
  1782. {
  1783. ExchangeLog.LogStart("GetMailboxCommonName");
  1784. Collection<PSObject> result = GetMailboxObject(runSpace, accountName);
  1785. PSObject mailbox = result[0];
  1786. string cn = GetPSObjectProperty(mailbox, "Name") as string;
  1787. ExchangeLog.LogEnd("GetMailboxCommonName");
  1788. return cn;
  1789. }
  1790. internal virtual ExchangeAccount GetManager(DirectoryEntry entry)
  1791. {
  1792. ExchangeAccount retUser = null;
  1793. string path = ActiveDirectoryUtils.GetADObjectStringProperty(entry, ADAttributes.Manager);
  1794. if (!string.IsNullOrEmpty(path))
  1795. {
  1796. path = ActiveDirectoryUtils.AddADPrefix(path, PrimaryDomainController);
  1797. if (ActiveDirectoryUtils.AdObjectExists(path))
  1798. {
  1799. DirectoryEntry user = ActiveDirectoryUtils.GetADObject(path);
  1800. retUser = new ExchangeAccount();
  1801. retUser.DisplayName = ActiveDirectoryUtils.GetADObjectStringProperty(user, ADAttributes.DisplayName);
  1802. retUser.AccountName = ActiveDirectoryUtils.GetADObjectStringProperty(user, ADAttributes.Name);
  1803. }
  1804. }
  1805. return retUser;
  1806. }
  1807. internal virtual ExchangeMailbox GetMailboxGeneralSettingsInternal(string accountName)
  1808. {
  1809. ExchangeLog.LogStart("GetMailboxGeneralSettingsInternal");
  1810. ExchangeLog.DebugInfo("Account: {0}", accountName);
  1811. ExchangeMailbox info = new ExchangeMailbox();
  1812. info.AccountName = accountName;
  1813. Runspace runSpace = null;
  1814. try
  1815. {
  1816. runSpace = OpenRunspace();
  1817. Collection<PSObject> result = GetMailboxObject(runSpace, accountName);
  1818. PSObject mailbox = result[0];
  1819. string id = GetResultObjectDN(result);
  1820. string path = AddADPrefix(id);
  1821. DirectoryEntry entry = GetADObject(path);
  1822. //ADAccountOptions userFlags = (ADAccountOptions)entry.Properties["userAccountControl"].Value;
  1823. //info.Disabled = ((userFlags & ADAccountOptions.UF_ACCOUNTDISABLE) != 0);
  1824. info.Disabled = (bool)entry.InvokeGet("AccountDisabled");
  1825. info.DisplayName = (string)GetPSObjectProperty(mailbox, "DisplayName");
  1826. info.HideFromAddressBook = (bool)GetPSObjectProperty(mailbox, "HiddenFromAddressListsEnabled");
  1827. Command cmd = new Command("Get-User");
  1828. cmd.Parameters.Add("Identity", accountName);
  1829. result = ExecuteShellCommand(runSpace, cmd);
  1830. PSObject user = result[0];
  1831. info.FirstName = (string)GetPSObjectProperty(user, "FirstName");
  1832. info.Initials = (string)GetPSObjectProperty(user, "Initials");
  1833. info.LastName = (string)GetPSObjectProperty(user, "LastName");
  1834. info.Address = (string)GetPSObjectProperty(user, "StreetAddress");
  1835. info.City = (string)GetPSObjectProperty(user, "City");
  1836. info.State = (string)GetPSObjectProperty(user, "StateOrProvince");
  1837. info.Zip = (string)GetPSObjectProperty(user, "PostalCode");
  1838. info.Country = CountryInfoToString((CountryInfo)GetPSObjectProperty(user, "CountryOrRegion"));
  1839. info.JobTitle = (string)GetPSObjectProperty(user, "Title");
  1840. info.Company = (string)GetPSObjectProperty(user, "Company");
  1841. info.Department = (string)GetPSObjectProperty(user, "Department");
  1842. info.Office = (string)GetPSObjectProperty(user, "Office");
  1843. info.ManagerAccount = GetManager(entry); //GetExchangeAccount(runSpace, ObjToString(GetPSObjectProperty(user, "Manager")));
  1844. info.BusinessPhone = (string)GetPSObjectProperty(user, "Phone");
  1845. info.Fax = (string)GetPSObjectProperty(user, "Fax");
  1846. info.HomePhone = (string)GetPSObjectProperty(user, "HomePhone");
  1847. info.MobilePhone = (string)GetPSObjectProperty(user, "MobilePhone");
  1848. info.Pager = (string)GetPSObjectProperty(user, "Pager");
  1849. info.WebPage = (string)GetPSObjectProperty(user, "WebPage");
  1850. info.Notes = (string)GetPSObjectProperty(user, "Notes");
  1851. }
  1852. finally
  1853. {
  1854. CloseRunspace(runSpace);
  1855. }
  1856. ExchangeLog.LogEnd("GetMailboxGeneralSettingsInternal");
  1857. return info;
  1858. }
  1859. private void SetMailboxGeneralSettingsInternal(string accountName, bool hideFromAddressBook, bool disabled)
  1860. {
  1861. ExchangeLog.LogStart("SetMailboxGeneralSettingsInternal");
  1862. ExchangeLog.DebugInfo("Account: {0}", accountName);
  1863. Runspace runSpace = null;
  1864. try
  1865. {
  1866. runSpace = OpenRunspace();
  1867. Collection<PSObject> result = GetMailboxObject(runSpace, accountName);
  1868. PSObject mailbox = result[0];
  1869. string id = GetResultObjectDN(result);
  1870. string path = AddADPrefix(id);
  1871. DirectoryEntry entry = GetADObject(path);
  1872. entry.InvokeSet("AccountDisabled", disabled);
  1873. entry.CommitChanges();
  1874. Command cmd = new Command("Set-Mailbox");
  1875. cmd.Parameters.Add("Identity", accountName);
  1876. cmd.Parameters.Add("HiddenFromAddressListsEnabled", hideFromAddressBook);
  1877. cmd.Parameters.Add("CustomAttribute2", (disabled ? "disabled" : null));
  1878. ExecuteShellCommand(runSpace, cmd);
  1879. }
  1880. finally
  1881. {
  1882. CloseRunspace(runSpace);
  1883. }
  1884. ExchangeLog.LogEnd("SetMailboxGeneralSettingsInternal");
  1885. }
  1886. private void ChangeMailboxState(string id, bool enabled)
  1887. {
  1888. string path = AddADPrefix(id);
  1889. DirectoryEntry entry = GetADObject(path);
  1890. entry.InvokeSet("AccountDisabled", !enabled);
  1891. entry.CommitChanges();
  1892. }
  1893. private ExchangeMailbox GetMailboxMailFlowSettingsInternal(string accountName)
  1894. {
  1895. ExchangeLog.LogStart("GetMailboxMailFlowSettings");
  1896. ExchangeLog.DebugInfo("Account: {0}", accountName);
  1897. ExchangeMailbox info = new ExchangeMailbox();
  1898. info.AccountName = accountName;
  1899. Runspace runSpace = null;
  1900. try
  1901. {
  1902. runSpace = OpenRunspace();
  1903. Collection<PSObject> result = GetMailboxObject(runSpace, accountName);
  1904. PSObject mailbox = result[0];
  1905. string forwardingAddress = ObjToString(GetPSObjectProperty(mailbox, "ForwardingAddress"));
  1906. if (string.IsNullOrEmpty(forwardingAddress))
  1907. {
  1908. info.EnableForwarding = false;
  1909. info.ForwardingAccount = null;
  1910. info.DoNotDeleteOnForward = false;
  1911. }
  1912. else
  1913. {
  1914. info.EnableForwarding = true;
  1915. info.ForwardingAccount = GetExchangeAccount(runSpace, forwardingAddress);
  1916. info.DoNotDeleteOnForward = (bool)GetPSObjectProperty(mailbox, "DeliverToMailboxAndForward");
  1917. }
  1918. info.SendOnBehalfAccounts = GetSendOnBehalfAccounts(runSpace, mailbox);
  1919. info.AcceptAccounts = GetAcceptedAccounts(runSpace, mailbox);
  1920. info.RejectAccounts = GetRejectedAccounts(runSpace, mailbox);
  1921. info.MaxRecipients =
  1922. ConvertUnlimitedToInt32((Unlimited<int>)GetPSObjectProperty(mailbox, "RecipientLimits"));
  1923. info.MaxSendMessageSizeKB =
  1924. ConvertUnlimitedToKB((Unlimited<ByteQuantifiedSize>)GetPSObjectProperty(mailbox, "MaxSendSize"));
  1925. info.MaxReceiveMessageSizeKB =
  1926. ConvertUnlimitedToKB((Unlimited<ByteQuantifiedSize>)GetPSObjectProperty(mailbox, "MaxReceiveSize"));
  1927. info.RequireSenderAuthentication = (bool)GetPSObjectProperty(mailbox, "RequireSenderAuthenticationEnabled");
  1928. }
  1929. finally
  1930. {
  1931. CloseRunspace(runSpace);
  1932. }
  1933. ExchangeLog.LogEnd("GetMailboxMailFlowSettings");
  1934. return info;
  1935. }
  1936. private void SetMailboxMailFlowSettingsInternal(string accountName, bool enableForwarding,
  1937. string forwardingAccountName, bool forwardToBoth, string[] sendOnBehalfAccounts,
  1938. string[] acceptAccounts, string[] rejectAccounts, bool requireSenderAuthentication)
  1939. {
  1940. ExchangeLog.LogStart("SetMailboxMailFlowSettingsInternal");
  1941. ExchangeLog.DebugInfo("Account: {0}", accountName);
  1942. Runspace runSpace = null;
  1943. try
  1944. {
  1945. runSpace = OpenRunspace();
  1946. Command cmd = new Command("Set-Mailbox");
  1947. cmd.Parameters.Add("Identity", accountName);
  1948. if (enableForwarding)
  1949. {
  1950. cmd.Parameters.Add("ForwardingAddress", forwardingAccountName);
  1951. cmd.Parameters.Add("DeliverToMailboxAndForward", forwardToBoth);
  1952. }
  1953. else
  1954. {
  1955. cmd.Parameters.Add("ForwardingAddress", null);
  1956. cmd.Parameters.Add("DeliverToMailboxAndForward", false);
  1957. }
  1958. cmd.Parameters.Add("GrantSendOnBehalfTo", SetSendOnBehalfAccounts(runSpace, sendOnBehalfAccounts));
  1959. MultiValuedProperty<ADObjectId> ids = null;
  1960. MultiValuedProperty<ADObjectId> dlIds = null;
  1961. SetAccountIds(runSpace, acceptAccounts, out ids, out dlIds);
  1962. cmd.Parameters.Add("AcceptMessagesOnlyFrom", ids);
  1963. cmd.Parameters.Add("AcceptMessagesOnlyFromDLMembers", dlIds);
  1964. SetAccountIds(runSpace, rejectAccounts, out ids, out dlIds);
  1965. cmd.Parameters.Add("RejectMessagesFrom", ids);
  1966. cmd.Parameters.Add("RejectMessagesFromDLMembers", dlIds);
  1967. cmd.Parameters.Add("RequireSenderAuthenticationEnabled", requireSenderAuthentication);
  1968. ExecuteShellCommand(runSpace, cmd);
  1969. }
  1970. finally
  1971. {
  1972. CloseRunspace(runSpace);
  1973. }
  1974. ExchangeLog.LogEnd("SetMailboxMailFlowSettingsInternal");
  1975. }
  1976. internal virtual ExchangeMailbox GetMailboxAdvancedSettingsInternal(string accountName)
  1977. {
  1978. ExchangeLog.LogStart("GetMailboxAdvancedSettingsInternal");
  1979. ExchangeLog.DebugInfo("Account: {0}", accountName);
  1980. ExchangeMailbox info = new ExchangeMailbox();
  1981. info.AccountName = accountName;
  1982. Runspace runSpace = null;
  1983. try
  1984. {
  1985. runSpace = OpenRunspace();
  1986. Collection<PSObject> result = GetMailboxObject(runSpace, accountName);
  1987. PSObject mailbox = result[0];
  1988. info.IssueWarningKB =
  1989. ConvertUnlimitedToKB((Unlimited<ByteQuantifiedSize>)GetPSObjectProperty(mailbox, "IssueWarningQuota"));
  1990. info.ProhibitSendKB =
  1991. ConvertUnlimitedToKB((Unlimited<ByteQuantifiedSize>)GetPSObjectProperty(mailbox, "ProhibitSendQuota"));
  1992. info.ProhibitSendReceiveKB =
  1993. ConvertUnlimitedToKB((Unlimited<ByteQuantifiedSize>)GetPSObjectProperty(mailbox, "ProhibitSendReceiveQuota"));
  1994. info.KeepDeletedItemsDays =
  1995. ConvertEnhancedTimeSpanToDays((EnhancedTimeSpan)GetPSObjectProperty(mailbox, "RetainDeletedItemsFor"));
  1996. //Client Access
  1997. Command cmd = new Command("Get-CASMailbox");
  1998. cmd.Parameters.Add("Identity", accountName);
  1999. result = ExecuteShellCommand(runSpace, cmd);
  2000. mailbox = result[0];
  2001. info.EnableActiveSync = (bool)GetPSObjectProperty(mailbox, "ActiveSyncEnabled");
  2002. info.EnableOWA = (bool)GetPSObjectProperty(mailbox, "OWAEnabled");
  2003. info.EnableMAPI = (bool)GetPSObjectProperty(mailbox, "MAPIEnabled");
  2004. info.EnablePOP = (bool)GetPSObjectProperty(mailbox, "PopEnabled");
  2005. info.EnableIMAP = (bool)GetPSObjectProperty(mailbox, "ImapEnabled");
  2006. //Statistics
  2007. cmd = new Command("Get-MailboxStatistics");
  2008. cmd.Parameters.Add("Identity", accountName);
  2009. result = ExecuteShellCommand(runSpace, cmd);
  2010. if (result.Count > 0)
  2011. {
  2012. PSObject statistics = result[0];
  2013. Unlimited<ByteQuantifiedSize> totalItemSize =
  2014. (Unlimited<ByteQuantifiedSize>)GetPSObjectProperty(statistics, "TotalItemSize");
  2015. info.TotalSizeMB = ConvertUnlimitedToMB(totalItemSize);
  2016. uint? itemCount = (uint?)GetPSObjectProperty(statistics, "ItemCount");
  2017. info.TotalItems = ConvertNullableToInt32(itemCount);
  2018. DateTime? lastLogoffTime = (DateTime?)GetPSObjectProperty(statistics, "LastLogoffTime"); ;
  2019. DateTime? lastLogonTime = (DateTime?)GetPSObjectProperty(statistics, "LastLogonTime"); ;
  2020. info.LastLogoff = ConvertNullableToDateTime(lastLogoffTime);
  2021. info.LastLogon = ConvertNullableToDateTime(lastLogonTime);
  2022. }
  2023. else
  2024. {
  2025. info.TotalSizeMB = 0;
  2026. info.TotalItems = 0;
  2027. info.LastLogoff = DateTime.MinValue;
  2028. info.LastLogon = DateTime.MinValue;
  2029. }
  2030. //domain
  2031. info.Domain = GetNETBIOSDomainName();
  2032. }
  2033. finally
  2034. {
  2035. CloseRunspace(runSpace);
  2036. }
  2037. ExchangeLog.LogEnd("GetMailboxAdvancedSettingsInternal");
  2038. return info;
  2039. }
  2040. internal virtual void SetMailboxAdvancedSettingsInternal(string organizationId, string accountName, bool enablePOP, bool enableIMAP,
  2041. bool enableOWA, bool enableMAPI, bool enableActiveSync, long issueWarningKB, long prohibitSendKB,
  2042. long prohibitSendReceiveKB, int keepDeletedItemsDays, int maxRecipients, int maxSendMessageSizeKB,
  2043. int maxReceiveMessageSizeKB, bool enabledLitigationHold, long recoverabelItemsSpace, long recoverabelItemsWarning,
  2044. string litigationHoldUrl, string litigationHoldMsg)
  2045. {
  2046. ExchangeLog.LogStart("SetMailboxAdvancedSettingsInternal");
  2047. ExchangeLog.DebugInfo("Account: {0}", accountName);
  2048. Runspace runSpace = null;
  2049. try
  2050. {
  2051. runSpace = OpenRunspace();
  2052. Command cmd = new Command("Set-Mailbox");
  2053. cmd.Parameters.Add("Identity", accountName);
  2054. cmd.Parameters.Add("IssueWarningQuota", ConvertKBToUnlimited(issueWarningKB));
  2055. cmd.Parameters.Add("ProhibitSendQuota", ConvertKBToUnlimited(prohibitSendKB));
  2056. cmd.Parameters.Add("ProhibitSendReceiveQuota", ConvertKBToUnlimited(prohibitSendReceiveKB));
  2057. cmd.Parameters.Add("RetainDeletedItemsFor", ConvertDaysToEnhancedTimeSpan(keepDeletedItemsDays));
  2058. cmd.Parameters.Add("RecipientLimits", ConvertInt32ToUnlimited(maxRecipients));
  2059. cmd.Parameters.Add("MaxSendSize", ConvertKBToUnlimited(maxSendMessageSizeKB));
  2060. cmd.Parameters.Add("MaxReceiveSize", ConvertKBToUnlimited(maxReceiveMessageSizeKB));
  2061. ExecuteShellCommand(runSpace, cmd);
  2062. //Client Access
  2063. cmd = new Command("Set-CASMailbox");
  2064. cmd.Parameters.Add("Identity", accountName);
  2065. cmd.Parameters.Add("ActiveSyncEnabled", enableActiveSync);
  2066. if (enableActiveSync)
  2067. {
  2068. cmd.Parameters.Add("ActiveSyncMailboxPolicy", organizationId);
  2069. }
  2070. cmd.Parameters.Add("OWAEnabled", enableOWA);
  2071. cmd.Parameters.Add("MAPIEnabled", enableMAPI);
  2072. cmd.Parameters.Add("PopEnabled", enablePOP);
  2073. cmd.Parameters.Add("ImapEnabled", enableIMAP);
  2074. ExecuteShellCommand(runSpace, cmd);
  2075. }
  2076. finally
  2077. {
  2078. CloseRunspace(runSpace);
  2079. }
  2080. ExchangeLog.LogEnd("SetMailboxAdvancedSettingsInternal");
  2081. }
  2082. private ExchangeEmailAddress[] GetMailboxEmailAddressesInternal(string accountName)
  2083. {
  2084. ExchangeLog.LogStart("GetMailboxEmailAddressesInternal");
  2085. ExchangeLog.DebugInfo("Account: {0}", accountName);
  2086. List<ExchangeEmailAddress> list = new List<ExchangeEmailAddress>();
  2087. Runspace runSpace = null;
  2088. try
  2089. {
  2090. runSpace = OpenRunspace();
  2091. Collection<PSObject> result = GetMailboxObject(runSpace, accountName);
  2092. PSObject mailbox = result[0];
  2093. string primaryEmail = null;
  2094. string windowsEmail = null;
  2095. SmtpAddress smtpAddress = (SmtpAddress)GetPSObjectProperty(mailbox, "PrimarySmtpAddress");
  2096. if (smtpAddress != null)
  2097. primaryEmail = smtpAddress.ToString();
  2098. //SmtpAddress winAddress = (SmtpAddress)GetPSObjectProperty(mailbox, "WindowsEmailAddress");
  2099. windowsEmail = ObjToString(GetPSObjectProperty(mailbox, "CustomAttribute3"));
  2100. ProxyAddressCollection emails = (ProxyAddressCollection)GetPSObjectProperty(mailbox, "EmailAddresses");
  2101. foreach (ProxyAddress email in emails)
  2102. {
  2103. //skip windows email
  2104. if (string.Equals(email.AddressString, windowsEmail, StringComparison.OrdinalIgnoreCase))
  2105. continue;
  2106. ExchangeEmailAddress item = new ExchangeEmailAddress();
  2107. item.Email = email.AddressString;
  2108. item.Primary = string.Equals(item.Email, primaryEmail, StringComparison.OrdinalIgnoreCase);
  2109. list.Add(item);
  2110. }
  2111. }
  2112. finally
  2113. {
  2114. CloseRunspace(runSpace);
  2115. }
  2116. ExchangeLog.LogEnd("GetMailboxEmailAddressesInternal");
  2117. return list.ToArray();
  2118. }
  2119. private void SetMailboxEmailAddressesInternal(string accountName, string[] emailAddresses)
  2120. {
  2121. ExchangeLog.LogStart("SetMailboxEmailAddressesInternal");
  2122. ExchangeLog.DebugInfo("Account: {0}", accountName);
  2123. Runspace runSpace = null;
  2124. try
  2125. {
  2126. runSpace = OpenRunspace();
  2127. Collection<PSObject> result = GetMailboxObject(runSpace, accountName);
  2128. PSObject mailbox = result[0];
  2129. //SmtpAddress winAddress = (SmtpAddress)GetPSObjectProperty(mailbox, "WindowsEmailAddress");
  2130. //if (winAddress != null)
  2131. // windowsEmail = winAddress.ToString();
  2132. string windowsEmail = ObjToString(GetPSObjectProperty(mailbox, "CustomAttribute3"));
  2133. ProxyAddressCollection emails = new ProxyAddressCollection();
  2134. ProxyAddress proxy = null;
  2135. string upn = null;
  2136. if (emailAddresses != null)
  2137. {
  2138. foreach (string email in emailAddresses)
  2139. {
  2140. proxy = ProxyAddress.Parse(email);
  2141. emails.Add(proxy);
  2142. if (proxy.IsPrimaryAddress)
  2143. {
  2144. upn = proxy.AddressString;
  2145. }
  2146. }
  2147. }
  2148. //add system windows email
  2149. if (!string.IsNullOrEmpty(windowsEmail))
  2150. {
  2151. emails.Add(ProxyAddress.Parse(windowsEmail));
  2152. }
  2153. Command cmd = new Command("Set-Mailbox");
  2154. cmd.Parameters.Add("Identity", accountName);
  2155. cmd.Parameters.Add("EmailAddresses", emails);
  2156. if (!string.IsNullOrEmpty(upn))
  2157. {
  2158. cmd.Parameters.Add("UserPrincipalName", upn);
  2159. cmd.Parameters.Add("WindowsEmailAddress", upn);
  2160. }
  2161. ExecuteShellCommand(runSpace, cmd);
  2162. }
  2163. finally
  2164. {
  2165. CloseRunspace(runSpace);
  2166. }
  2167. ExchangeLog.LogEnd("SetMailboxEmailAddressesInternal");
  2168. }
  2169. private void SetMailboxPrimaryEmailAddressInternal(string accountName, string emailAddress)
  2170. {
  2171. ExchangeLog.LogStart("SetMailboxPrimaryEmailAddressInternal");
  2172. ExchangeLog.DebugInfo("Account: {0}", accountName);
  2173. Runspace runSpace = null;
  2174. try
  2175. {
  2176. runSpace = OpenRunspace();
  2177. SmtpAddress primaryEmail = new SmtpAddress(emailAddress);
  2178. Command cmd = new Command("Set-Mailbox");
  2179. cmd.Parameters.Add("Identity", accountName);
  2180. cmd.Parameters.Add("PrimarySmtpAddress", primaryEmail);
  2181. //cmd.Parameters.Add("UserPrincipalName", primaryEmail);
  2182. //cmd.Parameters.Add("WindowsEmailAddress", primaryEmail);
  2183. ExecuteShellCommand(runSpace, cmd);
  2184. }
  2185. finally
  2186. {
  2187. CloseRunspace(runSpace);
  2188. }
  2189. ExchangeLog.LogEnd("SetMailboxPrimaryEmailAddressInternal");
  2190. }
  2191. private ExchangeAccount[] GetSendOnBehalfAccounts(Runspace runSpace, PSObject exchangeObject)
  2192. {
  2193. List<ExchangeAccount> list = new List<ExchangeAccount>();
  2194. IList<ADObjectId> ids =
  2195. (IList<ADObjectId>)GetPSObjectProperty(exchangeObject, "GrantSendOnBehalfTo");
  2196. foreach (ADObjectId id in ids)
  2197. {
  2198. ExchangeAccount account = GetExchangeAccount(runSpace, id.ToString());
  2199. if (account != null)
  2200. list.Add(account);
  2201. }
  2202. return list.ToArray();
  2203. }
  2204. internal MultiValuedProperty<ADObjectId> SetSendOnBehalfAccounts(Runspace runspace, string[] accounts)
  2205. {
  2206. if (accounts == null || accounts.Length == 0)
  2207. return MultiValuedProperty<ADObjectId>.Empty;
  2208. else
  2209. {
  2210. MultiValuedProperty<ADObjectId> ids = new MultiValuedProperty<ADObjectId>();
  2211. string dn = null;
  2212. foreach (string account in accounts)
  2213. {
  2214. dn = GetRecipientDistinguishedName(runspace, account);
  2215. ids.Add(new ADObjectId(dn));
  2216. }
  2217. return ids;
  2218. }
  2219. }
  2220. private ExchangeAccount[] GetAcceptedAccounts(Runspace runSpace, PSObject mailbox)
  2221. {
  2222. List<ExchangeAccount> list = new List<ExchangeAccount>();
  2223. ExchangeAccount account = null;
  2224. IList<ADObjectId> ids =
  2225. (IList<ADObjectId>)GetPSObjectProperty(mailbox, "AcceptMessagesOnlyFrom");
  2226. foreach (ADObjectId id in ids)
  2227. {
  2228. account = GetExchangeAccount(runSpace, id.ToString());
  2229. if (account != null)
  2230. list.Add(account);
  2231. }
  2232. ids = (IList<ADObjectId>)GetPSObjectProperty(mailbox, "AcceptMessagesOnlyFromDLMembers");
  2233. foreach (ADObjectId id in ids)
  2234. {
  2235. account = GetExchangeAccount(runSpace, id.ToString());
  2236. if (account != null)
  2237. list.Add(account);
  2238. }
  2239. return list.ToArray();
  2240. }
  2241. private void SetAccountIds(Runspace runspace, string[] accounts,
  2242. out MultiValuedProperty<ADObjectId> ids, out MultiValuedProperty<ADObjectId> dlIds)
  2243. {
  2244. ids = MultiValuedProperty<ADObjectId>.Empty;
  2245. dlIds = MultiValuedProperty<ADObjectId>.Empty;
  2246. if (accounts == null || accounts.Length == 0)
  2247. return;
  2248. ids = new MultiValuedProperty<ADObjectId>();
  2249. dlIds = new MultiValuedProperty<ADObjectId>();
  2250. string dn = null;
  2251. string type = null;
  2252. foreach (string account in accounts)
  2253. {
  2254. type = GetRecipientType(runspace, account, out dn);
  2255. if (type == "MailUniversalDistributionGroup")
  2256. dlIds.Add(new ADObjectId(dn));
  2257. else
  2258. ids.Add(new ADObjectId(dn));
  2259. }
  2260. if (ids.Count == 0)
  2261. ids = MultiValuedProperty<ADObjectId>.Empty;
  2262. if (dlIds.Count == 0)
  2263. dlIds = MultiValuedProperty<ADObjectId>.Empty;
  2264. }
  2265. private ExchangeAccount[] GetRejectedAccounts(Runspace runSpace, PSObject mailbox)
  2266. {
  2267. List<ExchangeAccount> list = new List<ExchangeAccount>();
  2268. ExchangeAccount account = null;
  2269. IList<ADObjectId> ids =
  2270. (IList<ADObjectId>)GetPSObjectProperty(mailbox, "RejectMessagesFrom");
  2271. foreach (ADObjectId id in ids)
  2272. {
  2273. account = GetExchangeAccount(runSpace, id.ToString());
  2274. if (account != null)
  2275. list.Add(account);
  2276. }
  2277. ids = (IList<ADObjectId>)GetPSObjectProperty(mailbox, "RejectMessagesFromDLMembers");
  2278. foreach (ADObjectId id in ids)
  2279. {
  2280. account = GetExchangeAccount(runSpace, id.ToString());
  2281. if (account != null)
  2282. list.Add(account);
  2283. }
  2284. return list.ToArray();
  2285. }
  2286. internal ExchangeAccount GetExchangeAccount(Runspace runSpace, string id)
  2287. {
  2288. return GetOrganizationAccount(runSpace, null, id);
  2289. }
  2290. internal ExchangeAccount GetOrganizationAccount(Runspace runSpace, string organizationId, string id)
  2291. {
  2292. if (string.IsNullOrEmpty(id))
  2293. return null;
  2294. ExchangeAccount ret = null;
  2295. Command cmd = new Command("Get-Recipient");
  2296. cmd.Parameters.Add("Identity", id);
  2297. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  2298. if (result != null && result.Count > 0)
  2299. {
  2300. //check for organization
  2301. if (!string.IsNullOrEmpty(organizationId))
  2302. {
  2303. string attr1 = (string)GetPSObjectProperty(result[0], "CustomAttribute1");
  2304. if (!string.Equals(organizationId, attr1, StringComparison.InvariantCultureIgnoreCase))
  2305. return ret;
  2306. }
  2307. ret = new ExchangeAccount();
  2308. ret.AccountName = (string)GetPSObjectProperty(result[0], "Alias");
  2309. ret.DisplayName = (string)GetPSObjectProperty(result[0], "DisplayName");
  2310. ret.PrimaryEmailAddress = ObjToString(GetPSObjectProperty(result[0], "PrimarySmtpAddress"));
  2311. ret.AccountType = ParseAccountType(ObjToString(GetPSObjectProperty(result[0], "RecipientType")));
  2312. if (ret.AccountType == ExchangeAccountType.Contact)
  2313. {
  2314. string email = ObjToString(GetPSObjectProperty(result[0], "ExternalEmailAddress"));
  2315. if (!string.IsNullOrEmpty(email) && email.StartsWith("SMTP:"))
  2316. ret.PrimaryEmailAddress = email.Substring(5);
  2317. }
  2318. }
  2319. return ret;
  2320. }
  2321. private ExchangeAccountType ParseAccountType(string type)
  2322. {
  2323. ExchangeAccountType ret = ExchangeAccountType.Mailbox;
  2324. switch (type)
  2325. {
  2326. case "UserMailbox":
  2327. ret = ExchangeAccountType.Mailbox;
  2328. break;
  2329. case "MailContact":
  2330. ret = ExchangeAccountType.Contact;
  2331. break;
  2332. case "MailUniversalDistributionGroup":
  2333. ret = ExchangeAccountType.DistributionList;
  2334. break;
  2335. case "PublicFolder":
  2336. ret = ExchangeAccountType.PublicFolder;
  2337. break;
  2338. }
  2339. return ret;
  2340. }
  2341. private string GetRecipientDistinguishedName(Runspace runSpace, string id)
  2342. {
  2343. if (string.IsNullOrEmpty(id))
  2344. return null;
  2345. string dn = null;
  2346. Command cmd = new Command("Get-Recipient");
  2347. cmd.Parameters.Add("Identity", id);
  2348. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  2349. if (result != null && result.Count > 0)
  2350. {
  2351. dn = (string)GetPSObjectProperty(result[0], "DistinguishedName");
  2352. }
  2353. return dn;
  2354. }
  2355. private string GetRecipientType(Runspace runSpace, string id, out string name)
  2356. {
  2357. name = null;
  2358. if (string.IsNullOrEmpty(id))
  2359. return null;
  2360. string type = null;
  2361. Command cmd = new Command("Get-Recipient");
  2362. cmd.Parameters.Add("Identity", id);
  2363. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  2364. if (result != null && result.Count > 0)
  2365. {
  2366. name = (string)GetPSObjectProperty(result[0], "DistinguishedName");
  2367. type = GetPSObjectProperty(result[0], "RecipientType").ToString();
  2368. }
  2369. return type;
  2370. }
  2371. virtual internal ExchangeMailboxStatistics GetMailboxStatisticsInternal(string id)
  2372. {
  2373. ExchangeLog.LogStart("GetMailboxStatisticsInternal");
  2374. ExchangeLog.DebugInfo("Account: {0}", id);
  2375. ExchangeMailboxStatistics info = new ExchangeMailboxStatistics();
  2376. Runspace runSpace = null;
  2377. try
  2378. {
  2379. runSpace = OpenRunspace();
  2380. Collection<PSObject> result = GetMailboxObject(runSpace, id);
  2381. PSObject mailbox = result[0];
  2382. string dn = GetResultObjectDN(result);
  2383. string path = AddADPrefix(dn);
  2384. DirectoryEntry entry = GetADObject(path);
  2385. info.Enabled = !(bool)entry.InvokeGet("AccountDisabled");
  2386. info.DisplayName = (string)GetPSObjectProperty(mailbox, "DisplayName");
  2387. SmtpAddress smtpAddress = (SmtpAddress)GetPSObjectProperty(mailbox, "PrimarySmtpAddress");
  2388. if (smtpAddress != null)
  2389. info.PrimaryEmailAddress = smtpAddress.ToString();
  2390. info.MaxSize = ConvertUnlimitedToBytes((Unlimited<ByteQuantifiedSize>)GetPSObjectProperty(mailbox, "ProhibitSendReceiveQuota"));
  2391. DateTime? whenCreated = (DateTime?)GetPSObjectProperty(mailbox, "WhenCreated");
  2392. info.AccountCreated = ConvertNullableToDateTime(whenCreated);
  2393. //Client Access
  2394. Command cmd = new Command("Get-CASMailbox");
  2395. cmd.Parameters.Add("Identity", id);
  2396. result = ExecuteShellCommand(runSpace, cmd);
  2397. mailbox = result[0];
  2398. info.ActiveSyncEnabled = (bool)GetPSObjectProperty(mailbox, "ActiveSyncEnabled");
  2399. info.OWAEnabled = (bool)GetPSObjectProperty(mailbox, "OWAEnabled");
  2400. info.MAPIEnabled = (bool)GetPSObjectProperty(mailbox, "MAPIEnabled");
  2401. info.POPEnabled = (bool)GetPSObjectProperty(mailbox, "PopEnabled");
  2402. info.IMAPEnabled = (bool)GetPSObjectProperty(mailbox, "ImapEnabled");
  2403. //Statistics
  2404. cmd = new Command("Get-MailboxStatistics");
  2405. cmd.Parameters.Add("Identity", id);
  2406. result = ExecuteShellCommand(runSpace, cmd);
  2407. if (result.Count > 0)
  2408. {
  2409. PSObject statistics = result[0];
  2410. Unlimited<ByteQuantifiedSize> totalItemSize =
  2411. (Unlimited<ByteQuantifiedSize>)GetPSObjectProperty(statistics, "TotalItemSize");
  2412. info.TotalSize = ConvertUnlimitedToBytes(totalItemSize);
  2413. uint? itemCount = (uint?)GetPSObjectProperty(statistics, "ItemCount");
  2414. info.TotalItems = ConvertNullableToInt32(itemCount);
  2415. DateTime? lastLogoffTime = (DateTime?)GetPSObjectProperty(statistics, "LastLogoffTime");
  2416. DateTime? lastLogonTime = (DateTime?)GetPSObjectProperty(statistics, "LastLogonTime");
  2417. info.LastLogoff = ConvertNullableToDateTime(lastLogoffTime);
  2418. info.LastLogon = ConvertNullableToDateTime(lastLogonTime);
  2419. }
  2420. else
  2421. {
  2422. info.TotalSize = 0;
  2423. info.TotalItems = 0;
  2424. info.LastLogoff = DateTime.MinValue;
  2425. info.LastLogon = DateTime.MinValue;
  2426. }
  2427. }
  2428. finally
  2429. {
  2430. CloseRunspace(runSpace);
  2431. }
  2432. ExchangeLog.LogEnd("GetMailboxStatisticsInternal");
  2433. return info;
  2434. }
  2435. virtual internal Collection<PSObject> GetMailboxObject(Runspace runSpace, string id)
  2436. {
  2437. Command cmd = new Command("Get-Mailbox");
  2438. cmd.Parameters.Add("Identity", id);
  2439. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  2440. return result;
  2441. }
  2442. #endregion
  2443. #region Contacts
  2444. private void CreateContactInternal(
  2445. string organizationId,
  2446. string organizationDistinguishedName,
  2447. string contactDisplayName,
  2448. string contactAccountName,
  2449. string contactEmail,
  2450. string defaultOrganizationDomain)
  2451. {
  2452. ExchangeLog.LogStart("CreateContactInternal");
  2453. ExchangeLog.DebugInfo("Organization Id: {0}", organizationId);
  2454. ExchangeLog.DebugInfo("Name: {0}", contactDisplayName);
  2455. ExchangeLog.DebugInfo("Account: {0}", contactAccountName);
  2456. ExchangeLog.DebugInfo("Email: {0}", contactEmail);
  2457. ExchangeTransaction transaction = StartTransaction();
  2458. Runspace runSpace = null;
  2459. try
  2460. {
  2461. runSpace = OpenRunspace();
  2462. string ouName = ConvertADPathToCanonicalName(organizationDistinguishedName);
  2463. string tempEmail = string.Format("{0}@{1}", Guid.NewGuid().ToString("N"), defaultOrganizationDomain);
  2464. //create contact
  2465. Command cmd = new Command("New-MailContact");
  2466. cmd.Parameters.Add("Name", contactAccountName);
  2467. cmd.Parameters.Add("DisplayName", contactDisplayName);
  2468. cmd.Parameters.Add("OrganizationalUnit", ouName);
  2469. cmd.Parameters.Add("Alias", contactAccountName);
  2470. cmd.Parameters.Add("ExternalEmailAddress", tempEmail);
  2471. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  2472. string id = GetResultObjectDN(result);
  2473. transaction.RegisterNewContact(id);
  2474. //update contact
  2475. cmd = new Command("Set-MailContact");
  2476. cmd.Parameters.Add("Identity", contactAccountName);
  2477. cmd.Parameters.Add("EmailAddressPolicyEnabled", false);
  2478. cmd.Parameters.Add("CustomAttribute1", organizationId);
  2479. cmd.Parameters.Add("WindowsEmailAddress", tempEmail);
  2480. ExecuteShellCommand(runSpace, cmd);
  2481. SetContactEmail(id, contactEmail);
  2482. }
  2483. catch (Exception ex)
  2484. {
  2485. ExchangeLog.LogError("CreateContactInternal", ex);
  2486. RollbackTransaction(transaction);
  2487. throw;
  2488. }
  2489. finally
  2490. {
  2491. CloseRunspace(runSpace);
  2492. }
  2493. ExchangeLog.LogEnd("CreateContactInternal");
  2494. }
  2495. private void DeleteContactInternal(string accountName)
  2496. {
  2497. ExchangeLog.LogStart("DeleteContactInternal");
  2498. ExchangeLog.DebugInfo("Account Name: {0}", accountName);
  2499. Runspace runSpace = null;
  2500. try
  2501. {
  2502. runSpace = OpenRunspace();
  2503. RemoveContact(runSpace, accountName);
  2504. }
  2505. finally
  2506. {
  2507. CloseRunspace(runSpace);
  2508. }
  2509. ExchangeLog.LogEnd("DeleteContactInternal");
  2510. }
  2511. private void RemoveContact(Runspace runSpace, string id)
  2512. {
  2513. ExchangeLog.LogStart("RemoveContact");
  2514. Command cmd = new Command("Remove-MailContact");
  2515. cmd.Parameters.Add("Identity", id);
  2516. cmd.Parameters.Add("Confirm", false);
  2517. ExecuteShellCommand(runSpace, cmd);
  2518. ExchangeLog.LogEnd("RemoveContact");
  2519. }
  2520. private ExchangeContact GetContactGeneralSettingsInternal(string accountName)
  2521. {
  2522. ExchangeLog.LogStart("GetContactGeneralSettingsInternal");
  2523. ExchangeLog.DebugInfo("Account: {0}", accountName);
  2524. ExchangeContact info = new ExchangeContact();
  2525. info.AccountName = accountName;
  2526. Runspace runSpace = null;
  2527. try
  2528. {
  2529. runSpace = OpenRunspace();
  2530. Command cmd = new Command("Get-MailContact");
  2531. cmd.Parameters.Add("Identity", accountName);
  2532. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  2533. PSObject contact = result[0];
  2534. string id = GetResultObjectDN(result);
  2535. info.DisplayName = (string)GetPSObjectProperty(contact, "DisplayName");
  2536. info.HideFromAddressBook = (bool)GetPSObjectProperty(contact, "HiddenFromAddressListsEnabled");
  2537. info.EmailAddress = GetContactEmail(id);
  2538. info.UseMapiRichTextFormat = (int)GetPSObjectProperty(contact, "UseMapiRichTextFormat");
  2539. cmd = new Command("Get-Contact");
  2540. cmd.Parameters.Add("Identity", accountName);
  2541. result = ExecuteShellCommand(runSpace, cmd);
  2542. PSObject user = result[0];
  2543. info.FirstName = (string)GetPSObjectProperty(user, "FirstName");
  2544. info.Initials = (string)GetPSObjectProperty(user, "Initials");
  2545. info.LastName = (string)GetPSObjectProperty(user, "LastName");
  2546. info.Address = (string)GetPSObjectProperty(user, "StreetAddress");
  2547. info.City = (string)GetPSObjectProperty(user, "City");
  2548. info.State = (string)GetPSObjectProperty(user, "StateOrProvince");
  2549. info.Zip = (string)GetPSObjectProperty(user, "PostalCode");
  2550. info.Country = CountryInfoToString((CountryInfo)GetPSObjectProperty(user, "CountryOrRegion"));
  2551. info.JobTitle = (string)GetPSObjectProperty(user, "Title");
  2552. info.Company = (string)GetPSObjectProperty(user, "Company");
  2553. info.Department = (string)GetPSObjectProperty(user, "Department");
  2554. info.Office = (string)GetPSObjectProperty(user, "Office");
  2555. info.ManagerAccount = GetExchangeAccount(runSpace, ObjToString(GetPSObjectProperty(user, "Manager")));
  2556. info.BusinessPhone = (string)GetPSObjectProperty(user, "Phone");
  2557. info.Fax = (string)GetPSObjectProperty(user, "Fax");
  2558. info.HomePhone = (string)GetPSObjectProperty(user, "HomePhone");
  2559. info.MobilePhone = (string)GetPSObjectProperty(user, "MobilePhone");
  2560. info.Pager = (string)GetPSObjectProperty(user, "Pager");
  2561. info.WebPage = (string)GetPSObjectProperty(user, "WebPage");
  2562. info.Notes = (string)GetPSObjectProperty(user, "Notes");
  2563. info.SAMAccountName = string.Format("{0}\\{1}", GetNETBIOSDomainName(), (string)GetPSObjectProperty(user, "Name"));
  2564. }
  2565. finally
  2566. {
  2567. CloseRunspace(runSpace);
  2568. }
  2569. ExchangeLog.LogEnd("GetContactGeneralSettingsInternal");
  2570. return info;
  2571. }
  2572. private void SetContactEmail(string id, string email)
  2573. {
  2574. string cn = ActiveDirectoryUtils.AddADPrefix(id, PrimaryDomainController);
  2575. DirectoryEntry de = ActiveDirectoryUtils.GetADObject(cn);
  2576. ActiveDirectoryUtils.SetADObjectPropertyValue(de, "targetAddress", "SMTP:" + email);
  2577. //ActiveDirectoryUtils.SetADObjectPropertyValue(de, "mail", email);
  2578. de.CommitChanges();
  2579. }
  2580. private string GetContactEmail(string id)
  2581. {
  2582. string cn = ActiveDirectoryUtils.AddADPrefix(id, PrimaryDomainController);
  2583. DirectoryEntry de = ActiveDirectoryUtils.GetADObject(cn);
  2584. string email = ActiveDirectoryUtils.GetADObjectStringProperty(de, "targetAddress");
  2585. if (email != null && email.ToLower().StartsWith("smtp:"))
  2586. email = email.Substring(5);
  2587. return email;
  2588. }
  2589. private void SetContactGeneralSettingsInternal(string accountName, string displayName, string email,
  2590. bool hideFromAddressBook, string firstName, string initials, string lastName, string address,
  2591. string city, string state, string zip, string country, string jobTitle, string company,
  2592. string department, string office, string managerAccountName, string businessPhone, string fax,
  2593. string homePhone, string mobilePhone, string pager, string webPage, string notes, int useMapiRichTextFormat, string defaultDomain)
  2594. {
  2595. ExchangeLog.LogStart("SetContactGeneralSettingsInternal");
  2596. ExchangeLog.DebugInfo("Account: {0}", accountName);
  2597. Runspace runSpace = null;
  2598. try
  2599. {
  2600. runSpace = OpenRunspace();
  2601. Command cmd = new Command("Get-MailContact");
  2602. cmd.Parameters.Add("Identity", accountName);
  2603. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  2604. string id = GetResultObjectDN(result);
  2605. string tempEmail = SmtpAddressToString((SmtpAddress)GetPSObjectProperty(result[0], "PrimarySmtpAddress"));
  2606. string[] parts = tempEmail.Split('@');
  2607. if (parts != null && parts.Length > 0)
  2608. tempEmail = parts[0] + '@' + defaultDomain;
  2609. cmd = new Command("Set-MailContact");
  2610. cmd.Parameters.Add("Identity", accountName);
  2611. cmd.Parameters.Add("DisplayName", displayName);
  2612. cmd.Parameters.Add("HiddenFromAddressListsEnabled", hideFromAddressBook);
  2613. cmd.Parameters.Add("ExternalEmailAddress", tempEmail);
  2614. cmd.Parameters.Add("UseMapiRichTextFormat", (UseMapiRichTextFormat)useMapiRichTextFormat);
  2615. cmd.Parameters.Add("WindowsEmailAddress", tempEmail);
  2616. ExecuteShellCommand(runSpace, cmd);
  2617. cmd = new Command("Set-Contact");
  2618. cmd.Parameters.Add("Identity", accountName);
  2619. cmd.Parameters.Add("FirstName", firstName);
  2620. cmd.Parameters.Add("Initials", initials);
  2621. cmd.Parameters.Add("LastName", lastName);
  2622. cmd.Parameters.Add("StreetAddress", address);
  2623. cmd.Parameters.Add("City", city);
  2624. cmd.Parameters.Add("StateOrProvince", state);
  2625. cmd.Parameters.Add("PostalCode", zip);
  2626. cmd.Parameters.Add("CountryOrRegion", ParseCountryInfo(country));
  2627. cmd.Parameters.Add("Title", jobTitle);
  2628. cmd.Parameters.Add("Company", company);
  2629. cmd.Parameters.Add("Department", department);
  2630. cmd.Parameters.Add("Office", office);
  2631. cmd.Parameters.Add("Manager", managerAccountName);
  2632. cmd.Parameters.Add("Phone", businessPhone);
  2633. cmd.Parameters.Add("Fax", fax);
  2634. cmd.Parameters.Add("HomePhone", homePhone);
  2635. cmd.Parameters.Add("MobilePhone", mobilePhone);
  2636. cmd.Parameters.Add("Pager", pager);
  2637. cmd.Parameters.Add("WebPage", webPage);
  2638. cmd.Parameters.Add("Notes", notes);
  2639. ExecuteShellCommand(runSpace, cmd);
  2640. SetContactEmail(id, email);
  2641. }
  2642. finally
  2643. {
  2644. CloseRunspace(runSpace);
  2645. }
  2646. ExchangeLog.LogEnd("SetContactGeneralSettingsInternal");
  2647. }
  2648. private ExchangeContact GetContactMailFlowSettingsInternal(string accountName)
  2649. {
  2650. ExchangeLog.LogStart("GetContactMailFlowSettingsInternal");
  2651. ExchangeLog.DebugInfo("Account: {0}", accountName);
  2652. ExchangeContact info = new ExchangeContact();
  2653. info.AccountName = accountName;
  2654. Runspace runSpace = null;
  2655. try
  2656. {
  2657. runSpace = OpenRunspace();
  2658. Command cmd = new Command("Get-MailContact");
  2659. cmd.Parameters.Add("Identity", accountName);
  2660. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  2661. PSObject contact = result[0];
  2662. info.AcceptAccounts = GetAcceptedAccounts(runSpace, contact);
  2663. info.RejectAccounts = GetRejectedAccounts(runSpace, contact);
  2664. info.RequireSenderAuthentication = (bool)GetPSObjectProperty(contact, "RequireSenderAuthenticationEnabled");
  2665. }
  2666. finally
  2667. {
  2668. CloseRunspace(runSpace);
  2669. }
  2670. ExchangeLog.LogEnd("GetContactMailFlowSettingsInternal");
  2671. return info;
  2672. }
  2673. private void SetContactMailFlowSettingsInternal(string accountName, string[] acceptAccounts,
  2674. string[] rejectAccounts, bool requireSenderAuthentication)
  2675. {
  2676. ExchangeLog.LogStart("SetContactMailFlowSettingsInternal");
  2677. ExchangeLog.DebugInfo("Account: {0}", accountName);
  2678. Runspace runSpace = null;
  2679. try
  2680. {
  2681. runSpace = OpenRunspace();
  2682. Command cmd = new Command("Set-MailContact");
  2683. cmd.Parameters.Add("Identity", accountName);
  2684. MultiValuedProperty<ADObjectId> ids = null;
  2685. MultiValuedProperty<ADObjectId> dlIds = null;
  2686. SetAccountIds(runSpace, acceptAccounts, out ids, out dlIds);
  2687. cmd.Parameters.Add("AcceptMessagesOnlyFrom", ids);
  2688. cmd.Parameters.Add("AcceptMessagesOnlyFromDLMembers", dlIds);
  2689. SetAccountIds(runSpace, rejectAccounts, out ids, out dlIds);
  2690. cmd.Parameters.Add("RejectMessagesFrom", ids);
  2691. cmd.Parameters.Add("RejectMessagesFromDLMembers", dlIds);
  2692. cmd.Parameters.Add("RequireSenderAuthenticationEnabled", requireSenderAuthentication);
  2693. ExecuteShellCommand(runSpace, cmd);
  2694. }
  2695. finally
  2696. {
  2697. CloseRunspace(runSpace);
  2698. }
  2699. ExchangeLog.LogEnd("SetContactMailFlowSettingsInternal");
  2700. }
  2701. #endregion
  2702. #region Distribution groups
  2703. /// <summary>
  2704. /// Creates Security Distribution Group
  2705. /// </summary>
  2706. /// <param name="runSpace"></param>
  2707. /// <param name="ouName"></param>
  2708. /// <param name="groupName"></param>
  2709. /// <returns>LDAP path</returns>
  2710. private string CreateSecurityDistributionGroup(Runspace runSpace, string ouName, string groupName)
  2711. {
  2712. ExchangeLog.LogStart("CreateSecurityDistributionGroup");
  2713. Command cmd = new Command("New-DistributionGroup");
  2714. cmd.Parameters.Add("Name", groupName);
  2715. cmd.Parameters.Add("Type", "Security");
  2716. cmd.Parameters.Add("OrganizationalUnit", ouName);
  2717. cmd.Parameters.Add("SamAccountName", groupName);
  2718. cmd.Parameters.Add("Alias", groupName);
  2719. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  2720. string id = CheckResultObjectDN(result);
  2721. ExchangeLog.LogEnd("CreateSecurityDistributionGroup");
  2722. return id;
  2723. }
  2724. internal string EnableMailSecurityDistributionGroup(Runspace runSpace, string distName, string groupName)
  2725. {
  2726. ExchangeLog.LogStart("EnableMailSecurityDistributionGroup");
  2727. ExchangeLog.DebugInfo("Group Distinguished Name: {0}", distName);
  2728. ExchangeLog.DebugInfo("Group Name: {0}", groupName);
  2729. int attempts = 0;
  2730. string securityGroupId = null;
  2731. while (true)
  2732. {
  2733. try
  2734. {
  2735. Command cmd = new Command("Enable-DistributionGroup");
  2736. cmd.Parameters.Add("Identity", distName);
  2737. cmd.Parameters.Add("Alias", groupName);
  2738. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  2739. securityGroupId = CheckResultObjectDN(result);
  2740. ExchangeLog.DebugInfo("Result: {0}", securityGroupId);
  2741. }
  2742. catch (Exception ex)
  2743. {
  2744. Log.WriteError(ex);
  2745. }
  2746. if (securityGroupId != null)
  2747. break;
  2748. if (attempts > 3)
  2749. throw new Exception(
  2750. string.Format("Could not enable mail Security Distribution Group '{0}' ", groupName));
  2751. attempts++;
  2752. ExchangeLog.LogWarning("Attempt #{0} to enable mail Security Distribution Group failed!", attempts);
  2753. // wait 5 sec
  2754. System.Threading.Thread.Sleep(5000);
  2755. }
  2756. ExchangeLog.LogEnd("EnableMailSecurityDistributionGroup");
  2757. return securityGroupId;
  2758. }
  2759. internal void DisableMailSecurityDistributionGroup(Runspace runSpace, string id)
  2760. {
  2761. ExchangeLog.LogStart("DisableMailSecurityDistributionGroup");
  2762. ExchangeLog.DebugInfo("Group Id: {0}", id);
  2763. Command cmd = new Command("Disable-DistributionGroup");
  2764. cmd.Parameters.Add("Identity", id);
  2765. cmd.Parameters.Add("Confirm", false);
  2766. ExecuteShellCommand(runSpace, cmd);
  2767. ExchangeLog.LogEnd("DisableMailSecurityDistributionGroup");
  2768. }
  2769. internal void UpdateSecurityDistributionGroup(Runspace runSpace, string id, string groupName, bool isConsumer)
  2770. {
  2771. ExchangeLog.LogStart("UpdateSecurityDistributionGroup");
  2772. Command cmd = new Command("Set-DistributionGroup");
  2773. cmd.Parameters.Add("Identity", id);
  2774. cmd.Parameters.Add("EmailAddressPolicyEnabled", false);
  2775. cmd.Parameters.Add("CustomAttribute1", groupName);
  2776. cmd.Parameters.Add("HiddenFromAddressListsEnabled", !isConsumer);
  2777. ExecuteShellCommand(runSpace, cmd);
  2778. ExchangeLog.LogEnd("UpdateSecurityDistributionGroup");
  2779. }
  2780. private void CreateDistributionListInternal(
  2781. string organizationId,
  2782. string organizationDistinguishedName,
  2783. string displayName,
  2784. string accountName,
  2785. string name,
  2786. string domain,
  2787. string managedBy,
  2788. string[] addressLists)
  2789. {
  2790. ExchangeLog.LogStart("CreateDistributionListInternal");
  2791. ExchangeLog.DebugInfo("Organization Id: {0}", organizationId);
  2792. ExchangeLog.DebugInfo("Name: {0}", name);
  2793. ExchangeLog.DebugInfo("Domain: {0}", domain);
  2794. ExchangeTransaction transaction = StartTransaction();
  2795. Runspace runSpace = null;
  2796. try
  2797. {
  2798. runSpace = OpenRunspace();
  2799. string email = string.Format("{0}@{1}", name, domain);
  2800. string ouName = ConvertADPathToCanonicalName(organizationDistinguishedName);
  2801. Command cmd = new Command("New-DistributionGroup");
  2802. cmd.Parameters.Add("Name", accountName);
  2803. cmd.Parameters.Add("DisplayName", displayName);
  2804. cmd.Parameters.Add("Type", "Security");
  2805. cmd.Parameters.Add("OrganizationalUnit", ouName);
  2806. cmd.Parameters.Add("SamAccountName", accountName);
  2807. cmd.Parameters.Add("Alias", accountName);
  2808. cmd.Parameters.Add("ManagedBy", managedBy);
  2809. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  2810. string id = GetResultObjectDN(result);
  2811. transaction.RegisterNewDistributionGroup(id);
  2812. //add manager permissions
  2813. if (!string.IsNullOrEmpty(managedBy))
  2814. {
  2815. AddADPermission(runSpace, accountName, managedBy, "WriteProperty", null, "Member");
  2816. }
  2817. string windowsEmailAddress = ObjToString(GetPSObjectProperty(result[0], "WindowsEmailAddress"));
  2818. //update
  2819. cmd = new Command("Set-DistributionGroup");
  2820. cmd.Parameters.Add("Identity", id);
  2821. cmd.Parameters.Add("EmailAddressPolicyEnabled", false);
  2822. cmd.Parameters.Add("CustomAttribute1", organizationId);
  2823. cmd.Parameters.Add("CustomAttribute3", windowsEmailAddress);
  2824. cmd.Parameters.Add("PrimarySmtpAddress", email);
  2825. cmd.Parameters.Add("WindowsEmailAddress", email);
  2826. cmd.Parameters.Add("RequireSenderAuthenticationEnabled", false);
  2827. ExecuteShellCommand(runSpace, cmd);
  2828. //fix showInAddressBook Attribute
  2829. if (addressLists.Length > 0)
  2830. FixShowInAddressBook(runSpace, email, addressLists, false);
  2831. }
  2832. catch (Exception ex)
  2833. {
  2834. ExchangeLog.LogError("CreateDistributionListInternal", ex);
  2835. RollbackTransaction(transaction);
  2836. throw;
  2837. }
  2838. finally
  2839. {
  2840. CloseRunspace(runSpace);
  2841. }
  2842. ExchangeLog.LogEnd("CreateDistributionListInternal");
  2843. }
  2844. private void FixShowInAddressBook(Runspace runSpace, string accountName, string[] addressLists, bool HideFromAddressList)
  2845. {
  2846. Command cmd = new Command("Get-DistributionGroup");
  2847. cmd.Parameters.Add("Identity", accountName);
  2848. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  2849. string id = GetResultObjectDN(result);
  2850. DirectoryEntry dlDEEntry = GetADObject(AddADPrefix(id));
  2851. dlDEEntry.Properties["showInAddressBook"].Clear();
  2852. if (!HideFromAddressList)
  2853. {
  2854. foreach (string addressList in addressLists)
  2855. {
  2856. dlDEEntry.Properties["showInAddressBook"].Add(addressList);
  2857. }
  2858. }
  2859. dlDEEntry.CommitChanges();
  2860. }
  2861. private void DeleteDistributionListInternal(string accountName)
  2862. {
  2863. ExchangeLog.LogStart("DeleteDistributionListInternal");
  2864. ExchangeLog.DebugInfo("Account Name: {0}", accountName);
  2865. Runspace runSpace = null;
  2866. try
  2867. {
  2868. runSpace = OpenRunspace();
  2869. RemoveDistributionGroup(runSpace, accountName);
  2870. }
  2871. finally
  2872. {
  2873. CloseRunspace(runSpace);
  2874. }
  2875. ExchangeLog.LogEnd("DeleteDistributionListInternal");
  2876. }
  2877. internal virtual void RemoveDistributionGroup(Runspace runSpace, string id)
  2878. {
  2879. ExchangeLog.LogStart("RemoveDistributionGroup");
  2880. Command cmd = new Command("Remove-DistributionGroup");
  2881. cmd.Parameters.Add("Identity", id);
  2882. cmd.Parameters.Add("Confirm", false);
  2883. ExecuteShellCommand(runSpace, cmd);
  2884. ExchangeLog.LogEnd("RemoveDistributionGroup");
  2885. }
  2886. private ExchangeDistributionList GetDistributionListGeneralSettingsInternal(string accountName)
  2887. {
  2888. ExchangeLog.LogStart("GetDistributionListGeneralSettingsInternal");
  2889. ExchangeLog.DebugInfo("Account: {0}", accountName);
  2890. ExchangeDistributionList info = new ExchangeDistributionList();
  2891. info.AccountName = accountName;
  2892. Runspace runSpace = null;
  2893. try
  2894. {
  2895. runSpace = OpenRunspace();
  2896. Command cmd = new Command("Get-DistributionGroup");
  2897. cmd.Parameters.Add("Identity", accountName);
  2898. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  2899. PSObject distributionGroup = result[0];
  2900. info.DisplayName = (string)GetPSObjectProperty(distributionGroup, "DisplayName");
  2901. info.HideFromAddressBook =
  2902. (bool)GetPSObjectProperty(distributionGroup, "HiddenFromAddressListsEnabled");
  2903. info.SAMAccountName = string.Format("{0}\\{1}", GetNETBIOSDomainName(), (string)GetPSObjectProperty(distributionGroup, "SamAccountName"));
  2904. cmd = new Command("Get-Group");
  2905. cmd.Parameters.Add("Identity", accountName);
  2906. result = ExecuteShellCommand(runSpace, cmd);
  2907. PSObject group = result[0];
  2908. info.ManagerAccount = GetGroupManagerAccount(runSpace, group);
  2909. info.MembersAccounts = GetGroupMembers(runSpace, accountName);
  2910. info.Notes = (string)GetPSObjectProperty(group, "Notes");
  2911. }
  2912. finally
  2913. {
  2914. CloseRunspace(runSpace);
  2915. }
  2916. ExchangeLog.LogEnd("GetDistributionListGeneralSettingsInternal");
  2917. return info;
  2918. }
  2919. internal virtual ExchangeAccount GetGroupManagerAccount(Runspace runSpace, PSObject group)
  2920. {
  2921. return GetExchangeAccount(runSpace, GetGroupManager(group));
  2922. }
  2923. internal virtual string GetGroupManager(PSObject group)
  2924. {
  2925. return ObjToString(GetPSObjectProperty(group, "ManagedBy"));
  2926. }
  2927. private void SetDistributionListGeneralSettingsInternal(string accountName, string displayName,
  2928. bool hideFromAddressBook, string managedBy, string[] memberAccounts, string notes, string[] addressLists)
  2929. {
  2930. ExchangeLog.LogStart("SetDistributionListGeneralSettingsInternal");
  2931. ExchangeLog.DebugInfo("Account: {0}", accountName);
  2932. Runspace runSpace = null;
  2933. try
  2934. {
  2935. runSpace = OpenRunspace();
  2936. SetDistributionGroup(runSpace, accountName, displayName, hideFromAddressBook);
  2937. //get old values
  2938. Command cmd = new Command("Get-Group");
  2939. cmd.Parameters.Add("Identity", accountName);
  2940. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  2941. PSObject group = result[0];
  2942. string manager = GetGroupManager(group);
  2943. //set members
  2944. ExchangeAccount[] accounts = GetGroupMembers(runSpace, accountName);
  2945. Dictionary<string, string> existingMembers = new Dictionary<string, string>();
  2946. Dictionary<string, string> newMembers = new Dictionary<string, string>();
  2947. List<string> membersToDelete = new List<string>();
  2948. List<string> membersToAdd = new List<string>();
  2949. foreach (ExchangeAccount account in accounts)
  2950. {
  2951. existingMembers.Add(account.AccountName.ToLower(), account.AccountName);
  2952. }
  2953. foreach (string member in memberAccounts)
  2954. {
  2955. newMembers.Add(member.ToLower(), member);
  2956. if (!existingMembers.ContainsKey(member.ToLower()))
  2957. {
  2958. membersToAdd.Add(member);
  2959. }
  2960. }
  2961. foreach (string delAccount in existingMembers.Keys)
  2962. {
  2963. if (!newMembers.ContainsKey(delAccount))
  2964. {
  2965. membersToDelete.Add(existingMembers[delAccount]);
  2966. }
  2967. }
  2968. foreach (string member in membersToAdd)
  2969. {
  2970. AddDistributionGroupMember(runSpace, accountName, member);
  2971. }
  2972. foreach (string member in membersToDelete)
  2973. {
  2974. RemoveDistributionGroupMember(runSpace, accountName, member);
  2975. }
  2976. //remove old manager rights
  2977. if (!string.IsNullOrEmpty(manager))
  2978. {
  2979. RemoveADPermission(runSpace, accountName, manager, "WriteProperty", null, "Member");
  2980. }
  2981. SetGroup(runSpace, accountName, managedBy, notes);
  2982. if (!string.IsNullOrEmpty(managedBy))
  2983. {
  2984. AddADPermission(runSpace, accountName, managedBy, "WriteProperty", null, "Member");
  2985. }
  2986. if (addressLists.Length > 0)
  2987. FixShowInAddressBook(runSpace, accountName, addressLists, hideFromAddressBook);
  2988. }
  2989. finally
  2990. {
  2991. CloseRunspace(runSpace);
  2992. }
  2993. ExchangeLog.LogEnd("SetDistributionListGeneralSettingsInternal");
  2994. }
  2995. internal virtual void RemoveDistributionGroupMember(Runspace runSpace, string group, string member)
  2996. {
  2997. Command cmd = new Command("Remove-DistributionGroupMember");
  2998. cmd.Parameters.Add("Identity", group);
  2999. cmd.Parameters.Add("Member", member);
  3000. cmd.Parameters.Add("Confirm", false);
  3001. ExecuteShellCommand(runSpace, cmd);
  3002. }
  3003. internal virtual void AddDistributionGroupMember(Runspace runSpace, string group, string member)
  3004. {
  3005. Command cmd = new Command("Add-DistributionGroupMember");
  3006. cmd.Parameters.Add("Identity", group);
  3007. cmd.Parameters.Add("Member", member);
  3008. ExecuteShellCommand(runSpace, cmd);
  3009. }
  3010. internal virtual void SetGroup(Runspace runSpace, string id, string managedBy, string notes)
  3011. {
  3012. Command cmd = new Command("Set-Group");
  3013. cmd.Parameters.Add("Identity", id);
  3014. cmd.Parameters.Add("ManagedBy", managedBy);
  3015. cmd.Parameters.Add("Notes", notes);
  3016. ExecuteShellCommand(runSpace, cmd);
  3017. }
  3018. internal virtual void SetDistributionGroup(Runspace runSpace, string id, string displayName, bool hideFromAddressBook)
  3019. {
  3020. Command cmd = new Command("Set-DistributionGroup");
  3021. cmd.Parameters.Add("Identity", id);
  3022. cmd.Parameters.Add("DisplayName", displayName);
  3023. cmd.Parameters.Add("HiddenFromAddressListsEnabled", hideFromAddressBook);
  3024. ExecuteShellCommand(runSpace, cmd);
  3025. }
  3026. private void AddDistributionListMembersInternal(string accountName, string[] memberAccounts, string[] addressLists)
  3027. {
  3028. ExchangeLog.LogStart("AddDistributionListMembersInternal");
  3029. ExchangeLog.DebugInfo("Account: {0}", accountName);
  3030. if (memberAccounts != null && memberAccounts.Length > 0)
  3031. {
  3032. Runspace runSpace = null;
  3033. try
  3034. {
  3035. runSpace = OpenRunspace();
  3036. Command cmd = null;
  3037. foreach (string member in memberAccounts)
  3038. {
  3039. cmd = new Command("Add-DistributionGroupMember");
  3040. cmd.Parameters.Add("Identity", accountName);
  3041. cmd.Parameters.Add("Member", member);
  3042. cmd.Parameters.Add("BypassSecurityGroupManagerCheck", true);
  3043. ExecuteShellCommand(runSpace, cmd);
  3044. }
  3045. if (addressLists.Length > 0)
  3046. {
  3047. cmd = new Command("Get-DistributionGroup");
  3048. cmd.Parameters.Add("Identity", accountName);
  3049. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  3050. PSObject distributionGroup = result[0];
  3051. FixShowInAddressBook(runSpace, accountName, addressLists, (bool)GetPSObjectProperty(distributionGroup, "HiddenFromAddressListsEnabled"));
  3052. }
  3053. }
  3054. finally
  3055. {
  3056. CloseRunspace(runSpace);
  3057. }
  3058. }
  3059. ExchangeLog.LogEnd("AddDistributionListMembersInternal");
  3060. }
  3061. private void RemoveDistributionListMembersInternal(string accountName, string[] memberAccounts, string[] addressLists)
  3062. {
  3063. ExchangeLog.LogStart("RemoveDistributionListMembersInternal");
  3064. ExchangeLog.DebugInfo("Account: {0}", accountName);
  3065. if (memberAccounts != null && memberAccounts.Length > 0)
  3066. {
  3067. Runspace runSpace = null;
  3068. try
  3069. {
  3070. runSpace = OpenRunspace();
  3071. Command cmd = null;
  3072. foreach (string member in memberAccounts)
  3073. {
  3074. cmd = new Command("Remove-DistributionGroupMember");
  3075. cmd.Parameters.Add("Identity", accountName);
  3076. cmd.Parameters.Add("Member", member);
  3077. cmd.Parameters.Add("Confirm", false);
  3078. ExecuteShellCommand(runSpace, cmd);
  3079. }
  3080. if (addressLists.Length > 0)
  3081. {
  3082. cmd = new Command("Get-DistributionGroup");
  3083. cmd.Parameters.Add("Identity", accountName);
  3084. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  3085. PSObject distributionGroup = result[0];
  3086. FixShowInAddressBook(runSpace, accountName, addressLists, (bool)GetPSObjectProperty(distributionGroup, "HiddenFromAddressListsEnabled"));
  3087. }
  3088. }
  3089. finally
  3090. {
  3091. CloseRunspace(runSpace);
  3092. }
  3093. }
  3094. ExchangeLog.LogEnd("RemoveDistributionListMembersInternal");
  3095. }
  3096. private ExchangeDistributionList GetDistributionListMailFlowSettingsInternal(string accountName)
  3097. {
  3098. ExchangeLog.LogStart("GetDistributionListMailFlowSettingsInternal");
  3099. ExchangeLog.DebugInfo("Account: {0}", accountName);
  3100. ExchangeDistributionList info = new ExchangeDistributionList();
  3101. info.AccountName = accountName;
  3102. Runspace runSpace = null;
  3103. try
  3104. {
  3105. runSpace = OpenRunspace();
  3106. Command cmd = new Command("Get-DistributionGroup");
  3107. cmd.Parameters.Add("Identity", accountName);
  3108. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  3109. PSObject group = result[0];
  3110. info.AcceptAccounts = GetAcceptedAccounts(runSpace, group);
  3111. info.RejectAccounts = GetRejectedAccounts(runSpace, group);
  3112. info.RequireSenderAuthentication = (bool)GetPSObjectProperty(group, "RequireSenderAuthenticationEnabled");
  3113. }
  3114. finally
  3115. {
  3116. CloseRunspace(runSpace);
  3117. }
  3118. ExchangeLog.LogEnd("GetDistributionListMailFlowSettingsInternal");
  3119. return info;
  3120. }
  3121. private void SetDistributionListMailFlowSettingsInternal(string accountName,
  3122. string[] acceptAccounts, string[] rejectAccounts, bool requireSenderAuthentication, string[] addressLists)
  3123. {
  3124. ExchangeLog.LogStart("SetDistributionListMailFlowSettingsInternal");
  3125. ExchangeLog.DebugInfo("Account: {0}", accountName);
  3126. Runspace runSpace = null;
  3127. try
  3128. {
  3129. runSpace = OpenRunspace();
  3130. Command cmd = new Command("Set-DistributionGroup");
  3131. cmd.Parameters.Add("Identity", accountName);
  3132. MultiValuedProperty<ADObjectId> ids = null;
  3133. MultiValuedProperty<ADObjectId> dlIds = null;
  3134. SetAccountIds(runSpace, acceptAccounts, out ids, out dlIds);
  3135. cmd.Parameters.Add("AcceptMessagesOnlyFrom", ids);
  3136. cmd.Parameters.Add("AcceptMessagesOnlyFromDLMembers", dlIds);
  3137. SetAccountIds(runSpace, rejectAccounts, out ids, out dlIds);
  3138. cmd.Parameters.Add("RejectMessagesFrom", ids);
  3139. cmd.Parameters.Add("RejectMessagesFromDLMembers", dlIds);
  3140. cmd.Parameters.Add("RequireSenderAuthenticationEnabled", requireSenderAuthentication);
  3141. ExecuteShellCommand(runSpace, cmd);
  3142. if (addressLists.Length > 0)
  3143. {
  3144. cmd = new Command("Get-DistributionGroup");
  3145. cmd.Parameters.Add("Identity", accountName);
  3146. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  3147. PSObject distributionGroup = result[0];
  3148. FixShowInAddressBook(runSpace, accountName, addressLists, (bool)GetPSObjectProperty(distributionGroup, "HiddenFromAddressListsEnabled"));
  3149. }
  3150. }
  3151. finally
  3152. {
  3153. CloseRunspace(runSpace);
  3154. }
  3155. ExchangeLog.LogEnd("SetDistributionListMailFlowSettingsInternal");
  3156. }
  3157. private ExchangeAccount[] GetGroupMembers(Runspace runSpace, string groupId)
  3158. {
  3159. ExchangeLog.LogStart("GetGroupMembers");
  3160. List<ExchangeAccount> list = new List<ExchangeAccount>();
  3161. Command cmd = new Command("Get-DistributionGroupMember");
  3162. cmd.Parameters.Add("Identity", groupId);
  3163. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  3164. ExchangeAccount account = null;
  3165. string id = null;
  3166. foreach (PSObject obj in result)
  3167. {
  3168. id = GetPSObjectIdentity(obj);
  3169. account = GetExchangeAccount(runSpace, id);
  3170. if (account != null)
  3171. {
  3172. list.Add(account);
  3173. }
  3174. else
  3175. {
  3176. string distinguishedName = (string)GetPSObjectProperty(obj, "DistinguishedName");
  3177. string path = ActiveDirectoryUtils.AddADPrefix(distinguishedName, PrimaryDomainController);
  3178. if (ActiveDirectoryUtils.AdObjectExists(path))
  3179. {
  3180. DirectoryEntry entry = ActiveDirectoryUtils.GetADObject(path);
  3181. list.Add(new ExchangeAccount
  3182. {
  3183. AccountName = ActiveDirectoryUtils.GetADObjectStringProperty(entry, ADAttributes.SAMAccountName),
  3184. AccountType = ExchangeAccountType.SecurityGroup
  3185. });
  3186. }
  3187. }
  3188. }
  3189. ExchangeLog.LogEnd("GetGroupMembers");
  3190. return list.ToArray();
  3191. }
  3192. private ExchangeEmailAddress[] GetDistributionListEmailAddressesInternal(string accountName)
  3193. {
  3194. ExchangeLog.LogStart("GetDistributionListEmailAddressesInternal");
  3195. ExchangeLog.DebugInfo("Account: {0}", accountName);
  3196. List<ExchangeEmailAddress> list = new List<ExchangeEmailAddress>();
  3197. Runspace runSpace = null;
  3198. try
  3199. {
  3200. runSpace = OpenRunspace();
  3201. Command cmd = new Command("Get-DistributionGroup");
  3202. cmd.Parameters.Add("Identity", accountName);
  3203. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  3204. PSObject group = result[0];
  3205. string primaryEmail = null;
  3206. string windowsEmail = null;
  3207. SmtpAddress smtpAddress = (SmtpAddress)GetPSObjectProperty(group, "PrimarySmtpAddress");
  3208. if (smtpAddress != null)
  3209. primaryEmail = smtpAddress.ToString();
  3210. //SmtpAddress winAddress = (SmtpAddress)GetPSObjectProperty(group, "WindowsEmailAddress");
  3211. //if (winAddress != null)
  3212. // windowsEmail = winAddress.ToString();
  3213. windowsEmail = ObjToString(GetPSObjectProperty(group, "CustomAttribute3"));
  3214. ProxyAddressCollection emails = (ProxyAddressCollection)GetPSObjectProperty(group, "EmailAddresses");
  3215. foreach (ProxyAddress email in emails)
  3216. {
  3217. //skip windows email
  3218. if (string.Equals(email.AddressString, windowsEmail, StringComparison.OrdinalIgnoreCase))
  3219. continue;
  3220. ExchangeEmailAddress item = new ExchangeEmailAddress();
  3221. item.Email = email.AddressString;
  3222. item.Primary = string.Equals(item.Email, primaryEmail, StringComparison.OrdinalIgnoreCase);
  3223. list.Add(item);
  3224. }
  3225. }
  3226. finally
  3227. {
  3228. CloseRunspace(runSpace);
  3229. }
  3230. ExchangeLog.LogEnd("GetDistributionListEmailAddressesInternal");
  3231. return list.ToArray();
  3232. }
  3233. private void SetDistributionListEmailAddressesInternal(string accountName, string[] emailAddresses, string[] addressLists)
  3234. {
  3235. ExchangeLog.LogStart("SetDistributionListEmailAddressesInternal");
  3236. ExchangeLog.DebugInfo("Account: {0}", accountName);
  3237. Runspace runSpace = null;
  3238. try
  3239. {
  3240. runSpace = OpenRunspace();
  3241. Command cmd = new Command("Get-DistributionGroup");
  3242. cmd.Parameters.Add("Identity", accountName);
  3243. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  3244. PSObject group = result[0];
  3245. //SmtpAddress winAddress = (SmtpAddress)GetPSObjectProperty(group, "WindowsEmailAddress");
  3246. //string windowsEmail = ObjToString(winAddress);
  3247. string windowsEmail = ObjToString(GetPSObjectProperty(group, "CustomAttribute3"));
  3248. ProxyAddressCollection emails = new ProxyAddressCollection();
  3249. ProxyAddress proxy = null;
  3250. string primaryEmail = null;
  3251. if (emailAddresses != null)
  3252. {
  3253. foreach (string email in emailAddresses)
  3254. {
  3255. proxy = ProxyAddress.Parse(email);
  3256. emails.Add(proxy);
  3257. if (proxy.IsPrimaryAddress)
  3258. {
  3259. primaryEmail = proxy.AddressString;
  3260. }
  3261. }
  3262. }
  3263. //add system windows email
  3264. if (!string.IsNullOrEmpty(windowsEmail))
  3265. {
  3266. emails.Add(ProxyAddress.Parse(windowsEmail));
  3267. }
  3268. cmd = new Command("Set-DistributionGroup");
  3269. cmd.Parameters.Add("Identity", accountName);
  3270. cmd.Parameters.Add("EmailAddresses", emails);
  3271. if (!string.IsNullOrEmpty(primaryEmail))
  3272. {
  3273. cmd.Parameters.Add("WindowsEmailAddress", primaryEmail);
  3274. }
  3275. ExecuteShellCommand(runSpace, cmd);
  3276. if (addressLists.Length > 0)
  3277. {
  3278. cmd = new Command("Get-DistributionGroup");
  3279. cmd.Parameters.Add("Identity", accountName);
  3280. Collection<PSObject> r = ExecuteShellCommand(runSpace, cmd);
  3281. PSObject distributionGroup = r[0];
  3282. FixShowInAddressBook(runSpace, accountName, addressLists, (bool)GetPSObjectProperty(distributionGroup, "HiddenFromAddressListsEnabled"));
  3283. }
  3284. }
  3285. finally
  3286. {
  3287. CloseRunspace(runSpace);
  3288. }
  3289. ExchangeLog.LogEnd("SetDistributionListEmailAddressesInternal");
  3290. }
  3291. private void SetDistributionListPrimaryEmailAddressInternal(string accountName, string emailAddress, string[] addressLists)
  3292. {
  3293. ExchangeLog.LogStart("SetDistributionListPrimaryEmailAddressInternal");
  3294. ExchangeLog.DebugInfo("Account: {0}", accountName);
  3295. Runspace runSpace = null;
  3296. try
  3297. {
  3298. runSpace = OpenRunspace();
  3299. SmtpAddress primaryEmail = new SmtpAddress(emailAddress);
  3300. Command cmd = new Command("Set-DistributionGroup");
  3301. cmd.Parameters.Add("Identity", accountName);
  3302. cmd.Parameters.Add("PrimarySmtpAddress", primaryEmail);
  3303. cmd.Parameters.Add("WindowsEmailAddress", primaryEmail);
  3304. ExecuteShellCommand(runSpace, cmd);
  3305. }
  3306. finally
  3307. {
  3308. CloseRunspace(runSpace);
  3309. }
  3310. ExchangeLog.LogEnd("SetDistributionListPrimaryEmailAddressInternal");
  3311. }
  3312. private ExchangeDistributionList GetDistributionListPermissionsInternal(string organizationId, string accountName, Runspace runspace)
  3313. {
  3314. ExchangeLog.LogStart("GetDistributionListPermissionsInternal");
  3315. if (string.IsNullOrEmpty(accountName))
  3316. throw new ArgumentNullException("accountName");
  3317. ExchangeDistributionList exchangeDistributionList = null;
  3318. bool closeRunspace = false;
  3319. try
  3320. {
  3321. if (runspace == null)
  3322. {
  3323. runspace = OpenRunspace();
  3324. closeRunspace = true;
  3325. }
  3326. Command cmd = new Command("Get-DistributionGroup");
  3327. cmd.Parameters.Add("Identity", accountName);
  3328. Collection<PSObject> result = ExecuteShellCommand(runspace, cmd);
  3329. PSObject distributionGroup = result[0];
  3330. string cn = GetPSObjectProperty(distributionGroup, "Name") as string;
  3331. exchangeDistributionList = new ExchangeDistributionList();
  3332. exchangeDistributionList.AccountName = accountName;
  3333. exchangeDistributionList.SendOnBehalfAccounts = GetSendOnBehalfAccounts(runspace, distributionGroup);
  3334. exchangeDistributionList.SendAsAccounts = GetSendAsAccounts(runspace, organizationId, cn);
  3335. }
  3336. catch (Exception ex)
  3337. {
  3338. ExchangeLog.LogError(ex);
  3339. throw ex;
  3340. }
  3341. finally
  3342. {
  3343. if (closeRunspace)
  3344. CloseRunspace(runspace);
  3345. }
  3346. ExchangeLog.LogEnd("GetDistributionListPermissionsInternal");
  3347. return exchangeDistributionList;
  3348. }
  3349. private void SetDistributionListPermissionsInternal(string organizationId, string accountName, string[] sendAsAccounts, string[] sendOnBehalfAccounts, string[] addressLists)
  3350. {
  3351. ExchangeLog.LogStart("SetDistributionListPermissionsInternal");
  3352. if (string.IsNullOrEmpty(accountName))
  3353. throw new ArgumentNullException("accountName");
  3354. if (sendAsAccounts == null)
  3355. throw new ArgumentNullException("sendAsAccounts");
  3356. if (sendOnBehalfAccounts == null)
  3357. throw new ArgumentNullException("sendOnBehalfAccounts");
  3358. Runspace runSpace = null;
  3359. try
  3360. {
  3361. runSpace = OpenRunspace();
  3362. string cn = GetDistributionListCommonName(runSpace, accountName);
  3363. ExchangeDistributionList distributionList = GetDistributionListPermissionsInternal(organizationId, accountName, runSpace);
  3364. SetSendAsPermissions(runSpace, distributionList.SendAsAccounts, cn, sendAsAccounts);
  3365. SetDistributionListSendOnBehalfAccounts(runSpace, accountName, sendOnBehalfAccounts);
  3366. if (addressLists.Length > 0)
  3367. {
  3368. Command cmd = new Command("Get-DistributionGroup");
  3369. cmd.Parameters.Add("Identity", accountName);
  3370. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  3371. PSObject distributionGroup = result[0];
  3372. FixShowInAddressBook(runSpace, accountName, addressLists, (bool)GetPSObjectProperty(distributionGroup, "HiddenFromAddressListsEnabled"));
  3373. }
  3374. }
  3375. catch (Exception ex)
  3376. {
  3377. ExchangeLog.LogError(ex);
  3378. throw;
  3379. }
  3380. finally
  3381. {
  3382. CloseRunspace(runSpace);
  3383. }
  3384. ExchangeLog.LogEnd("SetDistributionListPermissionsInternal");
  3385. }
  3386. internal virtual void SetDistributionListSendOnBehalfAccounts(Runspace runspace, string accountName, string[] sendOnBehalfAccounts)
  3387. {
  3388. ExchangeLog.LogStart("SetDistributionListSendOnBehalfAccounts");
  3389. Command cmd = new Command("Set-DistributionGroup");
  3390. cmd.Parameters.Add("Identity", accountName);
  3391. cmd.Parameters.Add("GrantSendOnBehalfTo", SetSendOnBehalfAccounts(runspace, sendOnBehalfAccounts));
  3392. ExecuteShellCommand(runspace, cmd);
  3393. ExchangeLog.LogEnd("SetDistributionListSendOnBehalfAccounts");
  3394. }
  3395. private string GetDistributionListCommonName(Runspace runSpace, string accountName)
  3396. {
  3397. ExchangeLog.LogStart("GetDistributionListCommonName");
  3398. Command cmd = new Command("Get-DistributionGroup");
  3399. cmd.Parameters.Add("Identity", accountName);
  3400. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  3401. PSObject obj = result[0];
  3402. string cn = GetPSObjectProperty(obj, "Name") as string;
  3403. ExchangeLog.LogEnd("GeDistributionListCommonName");
  3404. return cn;
  3405. }
  3406. #endregion
  3407. #region Public folders
  3408. private void CreatePublicFolderInternal(string organizationId, string securityGroup, string parentFolder,
  3409. string folderName, bool mailEnabled, string accountName, string name, string domain)
  3410. {
  3411. ExchangeLog.LogStart("CreatePublicFolderInternal");
  3412. ExchangeLog.DebugInfo("Organization Id: {0}", organizationId);
  3413. ExchangeLog.DebugInfo("Parent: {0}", parentFolder);
  3414. ExchangeLog.DebugInfo("Name: {0}", folderName);
  3415. ExchangeTransaction transaction = StartTransaction();
  3416. Runspace runSpace = null;
  3417. try
  3418. {
  3419. runSpace = OpenRunspace();
  3420. //create organization root folder if required
  3421. CheckOrganizationRootFolder(runSpace, organizationId, securityGroup);
  3422. string id = AddPublicFolder(runSpace, folderName, parentFolder);
  3423. transaction.RegisterNewPublicFolder(string.Empty, id);
  3424. SetPublicFolderPermissions(runSpace, id, securityGroup);
  3425. if (mailEnabled)
  3426. {
  3427. EnableMailPublicFolderInternal(organizationId, id, accountName, name, domain);
  3428. }
  3429. }
  3430. catch (Exception ex)
  3431. {
  3432. ExchangeLog.LogError("CreatePublicFolderInternal", ex);
  3433. RollbackTransaction(transaction);
  3434. throw;
  3435. }
  3436. finally
  3437. {
  3438. CloseRunspace(runSpace);
  3439. }
  3440. ExchangeLog.LogEnd("CreatePublicFolderInternal");
  3441. }
  3442. private void CheckOrganizationRootFolder(Runspace runSpace, string folder, string user)
  3443. {
  3444. ExchangeLog.LogStart("CheckOrganizationRootFolder");
  3445. Collection<PSObject> result = GetPublicFolderObject(runSpace, "\\" + folder);
  3446. if (result == null || result.Count == 0)
  3447. {
  3448. ExchangeTransaction transaction = StartTransaction();
  3449. try
  3450. {
  3451. string rootId = AddPublicFolder(runSpace, folder, "\\");
  3452. transaction.RegisterNewPublicFolder(string.Empty, rootId);
  3453. SetPublicFolderPermissions(runSpace, rootId, user);
  3454. }
  3455. catch
  3456. {
  3457. RollbackTransaction(transaction);
  3458. throw;
  3459. }
  3460. }
  3461. ExchangeLog.LogEnd("CheckOrganizationRootFolder");
  3462. }
  3463. private string AddPublicFolder(Runspace runSpace, string name, string path)
  3464. {
  3465. ExchangeLog.LogStart("CreatePublicFolder");
  3466. Command cmd = new Command("New-PublicFolder");
  3467. cmd.Parameters.Add("Name", name);
  3468. cmd.Parameters.Add("Path", path);
  3469. if (!string.IsNullOrEmpty(PublicFolderServer))
  3470. cmd.Parameters.Add("Server", PublicFolderServer);
  3471. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  3472. string id = GetResultObjectIdentity(result);
  3473. ExchangeLog.LogEnd("CreatePublicFolder");
  3474. return id;
  3475. }
  3476. private void DeletePublicFolderInternal(string folder)
  3477. {
  3478. ExchangeLog.LogStart("DeletePublicFolderInternal");
  3479. ExchangeLog.DebugInfo("Folder: {0}", folder);
  3480. Runspace runSpace = null;
  3481. try
  3482. {
  3483. runSpace = OpenRunspace();
  3484. RemovePublicFolder(runSpace, folder);
  3485. }
  3486. finally
  3487. {
  3488. CloseRunspace(runSpace);
  3489. }
  3490. ExchangeLog.LogEnd("DeletePublicFolderInternal");
  3491. }
  3492. private Collection<PSObject> GetPublicFolderObject(Runspace runSpace, string id)
  3493. {
  3494. Command cmd = new Command("Get-PublicFolder");
  3495. cmd.Parameters.Add("Identity", id);
  3496. if (!string.IsNullOrEmpty(PublicFolderServer))
  3497. cmd.Parameters.Add("Server", PublicFolderServer);
  3498. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  3499. return result;
  3500. }
  3501. private bool PublicFolderExists(Runspace runSpace, string id)
  3502. {
  3503. ExchangeLog.LogStart("PublicFolderExists");
  3504. Collection<PSObject> result = GetPublicFolderObject(runSpace, id);
  3505. bool ret = (result != null && result.Count == 1);
  3506. ExchangeLog.LogEnd("PublicFolderExists");
  3507. return ret;
  3508. }
  3509. private void RemovePublicFolder(Runspace runSpace, string id)
  3510. {
  3511. ExchangeLog.LogStart("RemovePublicFolder");
  3512. Command cmd = new Command("Remove-PublicFolder");
  3513. cmd.Parameters.Add("Identity", id);
  3514. cmd.Parameters.Add("Recurse", new SwitchParameter(true));
  3515. cmd.Parameters.Add("Confirm", false);
  3516. if (!string.IsNullOrEmpty(PublicFolderServer))
  3517. cmd.Parameters.Add("Server", PublicFolderServer);
  3518. ExecuteShellCommand(runSpace, cmd);
  3519. ExchangeLog.LogEnd("RemovePublicFolder");
  3520. }
  3521. private void SetPublicFolderPermissions(Runspace runSpace, string folder, string securityGroup)
  3522. {
  3523. //set the default Permission to 'Reviewer'
  3524. RemovePublicFolderClientPermission(runSpace, folder, "Default", "Author");
  3525. AddPublicFolderClientPermission(runSpace, folder, securityGroup, "Reviewer");
  3526. }
  3527. private void RemovePublicFolderClientPermission(Runspace runSpace, string id, string user,
  3528. string permission)
  3529. {
  3530. ExchangeLog.LogStart("RemovePublicFolderClientPermission");
  3531. Command cmd = new Command("Remove-PublicFolderClientPermission");
  3532. cmd.Parameters.Add("Identity", id);
  3533. cmd.Parameters.Add("User", user);
  3534. cmd.Parameters.Add("AccessRights", permission);
  3535. cmd.Parameters.Add("Confirm", false);
  3536. if (!string.IsNullOrEmpty(PublicFolderServer))
  3537. cmd.Parameters.Add("Server", PublicFolderServer);
  3538. ExecuteShellCommand(runSpace, cmd);
  3539. ExchangeLog.LogEnd("RemovePublicFolderClientPermission");
  3540. }
  3541. private void AddPublicFolderClientPermission(Runspace runSpace, string id, string user, string permission)
  3542. {
  3543. ExchangeLog.LogStart("AddPublicFolderClientPermission");
  3544. Command cmd = new Command("Add-PublicFolderClientPermission");
  3545. cmd.Parameters.Add("Identity", id);
  3546. cmd.Parameters.Add("User", user);
  3547. cmd.Parameters.Add("AccessRights", permission);
  3548. if (!string.IsNullOrEmpty(PublicFolderServer))
  3549. cmd.Parameters.Add("Server", PublicFolderServer);
  3550. ExecuteShellCommand(runSpace, cmd);
  3551. ExchangeLog.LogEnd("AddPublicFolderClientPermission");
  3552. }
  3553. private void GetPublicFolderClientPermission(Runspace runSpace, string id)
  3554. {
  3555. Command cmd = new Command("Get-PublicFolderClientPermission");
  3556. cmd.Parameters.Add("Identity", id);
  3557. if (!string.IsNullOrEmpty(PublicFolderServer))
  3558. cmd.Parameters.Add("Server", PublicFolderServer);
  3559. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  3560. PSObject obj = result[0];
  3561. }
  3562. private void EnableMailPublicFolderInternal(string organizationId, string folder, string accountName,
  3563. string name, string domain)
  3564. {
  3565. ExchangeLog.LogStart("EnableMailPublicFolderInternal");
  3566. ExchangeLog.DebugInfo("Folder: {0}", folder);
  3567. Runspace runSpace = null;
  3568. try
  3569. {
  3570. runSpace = OpenRunspace();
  3571. Command cmd = new Command("Enable-MailPublicFolder");
  3572. cmd.Parameters.Add("Identity", folder);
  3573. if (!string.IsNullOrEmpty(PublicFolderServer))
  3574. cmd.Parameters.Add("Server", PublicFolderServer);
  3575. ExecuteShellCommand(runSpace, cmd);
  3576. string id = null;
  3577. //try to avoid message: "The Active Directory proxy object for the public folder 'XXX'
  3578. // is being generated. Please try again later."
  3579. int attempts = 0;
  3580. string windowsEmailAddress = null;
  3581. while (true)
  3582. {
  3583. cmd = new Command("Get-MailPublicFolder");
  3584. cmd.Parameters.Add("Identity", folder);
  3585. if (!string.IsNullOrEmpty(PublicFolderServer))
  3586. cmd.Parameters.Add("Server", PublicFolderServer);
  3587. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  3588. if (result != null && result.Count > 0)
  3589. {
  3590. id = GetResultObjectIdentity(result);
  3591. windowsEmailAddress = ObjToString(GetPSObjectProperty(result[0], "WindowsEmailAddress"));
  3592. break;
  3593. }
  3594. if (attempts > 9)
  3595. {
  3596. string error = string.Format("Active Directory proxy object for the public folder '{0}' was not found or not generated yet.", folder);
  3597. throw new Exception(error);
  3598. }
  3599. attempts++;
  3600. ExchangeLog.LogWarning("Attemp {0} to create mail public folder {1}", attempts, folder);
  3601. System.Threading.Thread.Sleep(5000);
  3602. }
  3603. string email = string.Format("{0}@{1}", name, domain);
  3604. // fix issue with 2 DC
  3605. attempts = 0;
  3606. bool success = false;
  3607. object[] errors;
  3608. while (true)
  3609. {
  3610. try
  3611. {
  3612. cmd = new Command("Set-MailPublicFolder");
  3613. cmd.Parameters.Add("Identity", id);
  3614. cmd.Parameters.Add("Alias", accountName);
  3615. cmd.Parameters.Add("EmailAddressPolicyEnabled", false);
  3616. cmd.Parameters.Add("CustomAttribute1", organizationId);
  3617. cmd.Parameters.Add("CustomAttribute3", windowsEmailAddress);
  3618. cmd.Parameters.Add("PrimarySmtpAddress", email);
  3619. ExecuteShellCommand(runSpace, cmd, out errors);
  3620. if (errors.Length == 0)
  3621. success = true;
  3622. }
  3623. catch (Exception ex)
  3624. {
  3625. ExchangeLog.LogError(ex);
  3626. }
  3627. if (success)
  3628. break;
  3629. if (attempts > 9)
  3630. {
  3631. string error = string.Format("Mail public folder '{0}' was not found or not generated yet.", id);
  3632. throw new Exception(error);
  3633. }
  3634. attempts++;
  3635. ExchangeLog.LogWarning("Attemp {0} to update mail public folder {1}", attempts, folder);
  3636. System.Threading.Thread.Sleep(5000);
  3637. }
  3638. }
  3639. finally
  3640. {
  3641. CloseRunspace(runSpace);
  3642. }
  3643. ExchangeLog.LogEnd("EnableMailPublicFolderInternal");
  3644. }
  3645. private void DisableMailPublicFolderInternal(string folder)
  3646. {
  3647. ExchangeLog.LogStart("DisableMailPublicFolderInternal");
  3648. ExchangeLog.DebugInfo("Folder: {0}", folder);
  3649. Runspace runSpace = null;
  3650. try
  3651. {
  3652. runSpace = OpenRunspace();
  3653. Command cmd = new Command("Disable-MailPublicFolder");
  3654. cmd.Parameters.Add("Identity", folder);
  3655. cmd.Parameters.Add("Confirm", false);
  3656. if (!string.IsNullOrEmpty(PublicFolderServer))
  3657. cmd.Parameters.Add("Server", PublicFolderServer);
  3658. ExecuteShellCommand(runSpace, cmd);
  3659. }
  3660. finally
  3661. {
  3662. CloseRunspace(runSpace);
  3663. }
  3664. ExchangeLog.LogEnd("DisableMailPublicFolderInternal");
  3665. }
  3666. private ExchangePublicFolder GetPublicFolderGeneralSettingsInternal(string folder)
  3667. {
  3668. ExchangeLog.LogStart("GetPublicFolderGeneralSettingsInternal");
  3669. ExchangeLog.DebugInfo("Folder: {0}", folder);
  3670. ExchangePublicFolder info = new ExchangePublicFolder();
  3671. Runspace runSpace = null;
  3672. try
  3673. {
  3674. runSpace = OpenRunspace();
  3675. Collection<PSObject> result = GetPublicFolderObject(runSpace, folder);
  3676. PSObject publicFolder = result[0];
  3677. info.Name = (string)GetPSObjectProperty(publicFolder, "Name");
  3678. info.MailEnabled = (bool)GetPSObjectProperty(publicFolder, "MailEnabled");
  3679. info.HideFromAddressBook = (bool)GetPSObjectProperty(publicFolder, "HiddenFromAddressListsEnabled");
  3680. info.NETBIOS = GetNETBIOSDomainName();
  3681. info.Accounts = GetPublicFolderAccounts(runSpace, folder);
  3682. if (info.MailEnabled)
  3683. {
  3684. Command cmd = new Command("Get-MailPublicFolder");
  3685. cmd.Parameters.Add("Identity", folder);
  3686. if (!string.IsNullOrEmpty(PublicFolderServer))
  3687. cmd.Parameters.Add("Server", PublicFolderServer);
  3688. result = ExecuteShellCommand(runSpace, cmd);
  3689. if (result.Count > 0)
  3690. {
  3691. publicFolder = result[0];
  3692. info.SAMAccountName = string.Format("{0}\\{1}", GetNETBIOSDomainName(), (string)GetPSObjectProperty(publicFolder, "Alias"));
  3693. }
  3694. }
  3695. }
  3696. finally
  3697. {
  3698. CloseRunspace(runSpace);
  3699. }
  3700. ExchangeLog.LogEnd("GetPublicFolderGeneralSettingsInternal");
  3701. return info;
  3702. }
  3703. private ExchangeAccount[] GetPublicFolderAccounts(Runspace runSpace, string folder)
  3704. {
  3705. ExchangeLog.LogStart("GetPublicFolderAccounts");
  3706. ExchangeLog.DebugInfo("Folder: {0}", folder);
  3707. List<ExchangeAccount> list = new List<ExchangeAccount>();
  3708. ExchangeAccount account = null;
  3709. Command cmd = new Command("Get-PublicFolderClientPermission");
  3710. cmd.Parameters.Add("Identity", folder);
  3711. if (!string.IsNullOrEmpty(PublicFolderServer))
  3712. cmd.Parameters.Add("Server", PublicFolderServer);
  3713. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  3714. foreach (PSObject obj in result)
  3715. {
  3716. string userId = ObjToString(GetPSObjectProperty(obj, "User"));
  3717. if (userId == "Default" || userId == "Anonymous" || userId.StartsWith("NT User:") == true)
  3718. continue;
  3719. object rights = GetPSObjectProperty(obj, "AccessRights");
  3720. int count = (int)GetObjectPropertyValue(rights, "Count");
  3721. for (int i = 0; i < count; i++)
  3722. {
  3723. account = GetExchangeAccount(runSpace, userId);
  3724. string permission = ObjToString(GetObjectIndexerValue(rights, i));
  3725. if (account != null)
  3726. account.PublicFolderPermission = permission;
  3727. list.Add(account);
  3728. break;
  3729. }
  3730. }
  3731. ExchangeLog.LogEnd("GetPublicFolderAccounts");
  3732. return list.ToArray();
  3733. }
  3734. private void SetPublicFolderGeneralSettingsInternal(string folder, string newFolderName,
  3735. bool hideFromAddressBook, ExchangeAccount[] accounts)
  3736. {
  3737. ExchangeLog.LogStart("SetPublicFolderGeneralSettingsInternal");
  3738. ExchangeLog.DebugInfo("Folder: {0}", folder);
  3739. ExchangePublicFolder info = new ExchangePublicFolder();
  3740. Runspace runSpace = null;
  3741. try
  3742. {
  3743. runSpace = OpenRunspace();
  3744. Collection<PSObject> result = GetPublicFolderObject(runSpace, folder);
  3745. PSObject publicFolder = result[0];
  3746. string folderName = (string)GetPSObjectProperty(publicFolder, "Name");
  3747. ExchangeAccount[] allAccounts = GetPublicFolderAccounts(runSpace, folder);
  3748. //Remove all accounts and re-apply
  3749. List<ExchangeAccount> accountsToDelete = new List<ExchangeAccount>();
  3750. List<ExchangeAccount> accountsToAdd = new List<ExchangeAccount>();
  3751. foreach (ExchangeAccount existingAccount in allAccounts)
  3752. {
  3753. try
  3754. {
  3755. RemovePublicFolderClientPermission(runSpace,
  3756. folder,
  3757. existingAccount.AccountName.Contains("@") ? existingAccount.AccountName : @"\" + existingAccount.AccountName,
  3758. existingAccount.PublicFolderPermission);
  3759. }
  3760. catch (Exception)
  3761. {
  3762. throw;
  3763. }
  3764. }
  3765. foreach (ExchangeAccount newAccount in accounts)
  3766. {
  3767. try
  3768. {
  3769. AddPublicFolderClientPermission(runSpace,
  3770. folder,
  3771. newAccount.AccountName.Contains("@") ? newAccount.AccountName : @"\" + newAccount.AccountName,
  3772. newAccount.PublicFolderPermission);
  3773. }
  3774. catch (Exception)
  3775. {
  3776. throw;
  3777. }
  3778. }
  3779. //general settings
  3780. Command cmd = new Command("Set-PublicFolder");
  3781. cmd.Parameters.Add("Identity", folder);
  3782. if (!string.IsNullOrEmpty(PublicFolderServer))
  3783. cmd.Parameters.Add("Server", PublicFolderServer);
  3784. if (!folderName.Equals(newFolderName, StringComparison.OrdinalIgnoreCase))
  3785. {
  3786. cmd.Parameters.Add("Name", newFolderName);
  3787. }
  3788. cmd.Parameters.Add("HiddenFromAddressListsEnabled", hideFromAddressBook);
  3789. ExecuteShellCommand(runSpace, cmd);
  3790. }
  3791. finally
  3792. {
  3793. CloseRunspace(runSpace);
  3794. }
  3795. ExchangeLog.LogEnd("SetPublicFolderGeneralSettingsInternal");
  3796. }
  3797. private ExchangePublicFolder GetPublicFolderMailFlowSettingsInternal(string folder)
  3798. {
  3799. ExchangeLog.LogStart("GetPublicFolderMailFlowSettingsInternal");
  3800. ExchangeLog.DebugInfo("Folder: {0}", folder);
  3801. ExchangePublicFolder info = new ExchangePublicFolder();
  3802. Runspace runSpace = null;
  3803. try
  3804. {
  3805. runSpace = OpenRunspace();
  3806. Command cmd = new Command("Get-MailPublicFolder");
  3807. cmd.Parameters.Add("Identity", folder);
  3808. if (!string.IsNullOrEmpty(PublicFolderServer))
  3809. cmd.Parameters.Add("Server", PublicFolderServer);
  3810. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  3811. PSObject publicFolder = result[0];
  3812. info.AcceptAccounts = GetAcceptedAccounts(runSpace, publicFolder);
  3813. info.RejectAccounts = GetRejectedAccounts(runSpace, publicFolder);
  3814. info.RequireSenderAuthentication = (bool)GetPSObjectProperty(publicFolder, "RequireSenderAuthenticationEnabled");
  3815. }
  3816. finally
  3817. {
  3818. CloseRunspace(runSpace);
  3819. }
  3820. ExchangeLog.LogEnd("GetPublicFolderMailFlowSettingsInternal");
  3821. return info;
  3822. }
  3823. private void SetPublicFolderMailFlowSettingsInternal(string folder,
  3824. string[] acceptAccounts, string[] rejectAccounts, bool requireSenderAuthentication)
  3825. {
  3826. ExchangeLog.LogStart("SetPublicFolderMailFlowSettingsInternal");
  3827. ExchangeLog.DebugInfo("Folder: {0}", folder);
  3828. Runspace runSpace = null;
  3829. try
  3830. {
  3831. runSpace = OpenRunspace();
  3832. Command cmd = new Command("Set-MailPublicFolder");
  3833. cmd.Parameters.Add("Identity", folder);
  3834. MultiValuedProperty<ADObjectId> ids = null;
  3835. MultiValuedProperty<ADObjectId> dlIds = null;
  3836. SetAccountIds(runSpace, acceptAccounts, out ids, out dlIds);
  3837. cmd.Parameters.Add("AcceptMessagesOnlyFrom", ids);
  3838. cmd.Parameters.Add("AcceptMessagesOnlyFromDLMembers", dlIds);
  3839. SetAccountIds(runSpace, rejectAccounts, out ids, out dlIds);
  3840. cmd.Parameters.Add("RejectMessagesFrom", ids);
  3841. cmd.Parameters.Add("RejectMessagesFromDLMembers", dlIds);
  3842. cmd.Parameters.Add("RequireSenderAuthenticationEnabled", requireSenderAuthentication);
  3843. ExecuteShellCommand(runSpace, cmd);
  3844. }
  3845. finally
  3846. {
  3847. CloseRunspace(runSpace);
  3848. }
  3849. ExchangeLog.LogEnd("SetPublicFolderMailFlowSettingsInternal");
  3850. }
  3851. private ExchangeEmailAddress[] GetPublicFolderEmailAddressesInternal(string folder)
  3852. {
  3853. ExchangeLog.LogStart("GetPublicFolderEmailAddressesInternal");
  3854. ExchangeLog.DebugInfo("Folder: {0}", folder);
  3855. List<ExchangeEmailAddress> list = new List<ExchangeEmailAddress>();
  3856. Runspace runSpace = null;
  3857. try
  3858. {
  3859. runSpace = OpenRunspace();
  3860. Command cmd = new Command("Get-MailPublicFolder");
  3861. cmd.Parameters.Add("Identity", folder);
  3862. if (!string.IsNullOrEmpty(PublicFolderServer))
  3863. cmd.Parameters.Add("Server", PublicFolderServer);
  3864. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  3865. PSObject publicFolder = result[0];
  3866. string primaryEmail = null;
  3867. string windowsEmail = null;
  3868. SmtpAddress smtpAddress = (SmtpAddress)GetPSObjectProperty(publicFolder, "PrimarySmtpAddress");
  3869. if (smtpAddress != null)
  3870. primaryEmail = smtpAddress.ToString();
  3871. //SmtpAddress winAddress = (SmtpAddress)GetPSObjectProperty(publicFolder, "WindowsEmailAddress");
  3872. //if (winAddress != null)
  3873. // windowsEmail = winAddress.ToString();
  3874. windowsEmail = ObjToString(GetPSObjectProperty(publicFolder, "CustomAttribute3"));
  3875. ProxyAddressCollection emails = (ProxyAddressCollection)GetPSObjectProperty(publicFolder, "EmailAddresses");
  3876. foreach (ProxyAddress email in emails)
  3877. {
  3878. //skip windows email
  3879. if (string.Equals(email.AddressString, windowsEmail, StringComparison.OrdinalIgnoreCase))
  3880. continue;
  3881. ExchangeEmailAddress item = new ExchangeEmailAddress();
  3882. item.Email = email.AddressString;
  3883. item.Primary = string.Equals(item.Email, primaryEmail, StringComparison.OrdinalIgnoreCase);
  3884. list.Add(item);
  3885. }
  3886. }
  3887. finally
  3888. {
  3889. CloseRunspace(runSpace);
  3890. }
  3891. ExchangeLog.LogEnd("GetPublicFolderEmailAddressesInternal");
  3892. return list.ToArray();
  3893. }
  3894. private void SetPublicFolderEmailAddressesInternal(string folder, string[] emailAddresses)
  3895. {
  3896. ExchangeLog.LogStart("SetDistributionListEmailAddressesInternal");
  3897. ExchangeLog.DebugInfo("Folder: {0}", folder);
  3898. Runspace runSpace = null;
  3899. try
  3900. {
  3901. runSpace = OpenRunspace();
  3902. Command cmd = new Command("Get-MailPublicFolder");
  3903. cmd.Parameters.Add("Identity", folder);
  3904. if (!string.IsNullOrEmpty(PublicFolderServer))
  3905. cmd.Parameters.Add("Server", PublicFolderServer);
  3906. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  3907. PSObject publicFolder = result[0];
  3908. //SmtpAddress winAddress = (SmtpAddress)GetPSObjectProperty(publicFolder, "WindowsEmailAddress");
  3909. string windowsEmail = ObjToString(GetPSObjectProperty(publicFolder, "CustomAttribute3"));
  3910. //string windowsEmail = ObjToString(winAddress);
  3911. ProxyAddressCollection emails = new ProxyAddressCollection();
  3912. ProxyAddress proxy = null;
  3913. if (emailAddresses != null)
  3914. {
  3915. foreach (string email in emailAddresses)
  3916. {
  3917. proxy = ProxyAddress.Parse(email);
  3918. emails.Add(proxy);
  3919. }
  3920. }
  3921. //add system windows email
  3922. if (!string.IsNullOrEmpty(windowsEmail))
  3923. {
  3924. emails.Add(ProxyAddress.Parse(windowsEmail));
  3925. }
  3926. cmd = new Command("Set-MailPublicFolder");
  3927. cmd.Parameters.Add("Identity", folder);
  3928. cmd.Parameters.Add("EmailAddresses", emails);
  3929. ExecuteShellCommand(runSpace, cmd);
  3930. }
  3931. finally
  3932. {
  3933. CloseRunspace(runSpace);
  3934. }
  3935. ExchangeLog.LogEnd("SetPublicFolderEmailAddressesInternal");
  3936. }
  3937. private void SetPublicFolderPrimaryEmailAddressInternal(string folder, string emailAddress)
  3938. {
  3939. ExchangeLog.LogStart("SetPublicFolderPrimaryEmailAddressInternal");
  3940. ExchangeLog.DebugInfo("Folder: {0}", folder);
  3941. ExchangeLog.DebugInfo("Email: {0}", emailAddress);
  3942. Runspace runSpace = null;
  3943. try
  3944. {
  3945. runSpace = OpenRunspace();
  3946. SmtpAddress primaryEmail = new SmtpAddress(emailAddress);
  3947. Command cmd = new Command("Set-MailPublicFolder");
  3948. cmd.Parameters.Add("Identity", folder);
  3949. cmd.Parameters.Add("PrimarySmtpAddress", primaryEmail);
  3950. ExecuteShellCommand(runSpace, cmd);
  3951. }
  3952. finally
  3953. {
  3954. CloseRunspace(runSpace);
  3955. }
  3956. ExchangeLog.LogEnd("SetPublicFolderPrimaryEmailAddressInternal");
  3957. }
  3958. private ExchangeItemStatistics[] GetPublicFoldersStatisticsInternal(string[] folders)
  3959. {
  3960. ExchangeLog.LogStart("GetPublicFoldersStatisticsInternal");
  3961. Runspace runSpace = null;
  3962. List<ExchangeItemStatistics> ret = new List<ExchangeItemStatistics>();
  3963. try
  3964. {
  3965. runSpace = OpenRunspace();
  3966. PSObject obj = null;
  3967. foreach (string folder in folders)
  3968. {
  3969. Command cmd = new Command("Get-PublicFolderStatistics");
  3970. cmd.Parameters.Add("Identity", folder);
  3971. if (!string.IsNullOrEmpty(PublicFolderServer))
  3972. cmd.Parameters.Add("Server", PublicFolderServer);
  3973. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  3974. if (result != null && result.Count > 0)
  3975. {
  3976. obj = result[0];
  3977. ExchangeItemStatistics info = new ExchangeItemStatistics();
  3978. info.ItemName = (string)GetPSObjectProperty(obj, "FolderPath");
  3979. Unlimited<ByteQuantifiedSize> totalItemSize =
  3980. (Unlimited<ByteQuantifiedSize>)GetPSObjectProperty(obj, "TotalItemSize");
  3981. info.TotalSizeMB = ConvertUnlimitedToMB(totalItemSize);
  3982. uint? itemCount = (uint?)GetPSObjectProperty(obj, "ItemCount");
  3983. info.TotalItems = ConvertNullableToInt32(itemCount);
  3984. DateTime? lastAccessTime = (DateTime?)GetPSObjectProperty(obj, "LastAccessTime"); ;
  3985. DateTime? lastModificationTime = (DateTime?)GetPSObjectProperty(obj, "LastModificationTime"); ;
  3986. info.LastAccessTime = ConvertNullableToDateTime(lastAccessTime);
  3987. info.LastModificationTime = ConvertNullableToDateTime(lastModificationTime);
  3988. ret.Add(info);
  3989. }
  3990. }
  3991. }
  3992. finally
  3993. {
  3994. CloseRunspace(runSpace);
  3995. }
  3996. ExchangeLog.LogEnd("GetPublicFoldersStatisticsInternal");
  3997. return ret.ToArray();
  3998. }
  3999. private string[] GetPublicFoldersRecursiveInternal(string parent)
  4000. {
  4001. ExchangeLog.LogStart("GetPublicFoldersRecursiveInternal");
  4002. Runspace runSpace = null;
  4003. List<string> ret = new List<string>();
  4004. try
  4005. {
  4006. runSpace = OpenRunspace();
  4007. Command cmd = new Command("Get-PublicFolder");
  4008. cmd.Parameters.Add("Identity", parent);
  4009. cmd.Parameters.Add("Recurse", true);
  4010. if (!string.IsNullOrEmpty(PublicFolderServer))
  4011. cmd.Parameters.Add("Server", PublicFolderServer);
  4012. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  4013. if (result != null)
  4014. {
  4015. foreach (PSObject obj in result)
  4016. {
  4017. ret.Add(GetPSObjectIdentity(obj));
  4018. }
  4019. }
  4020. }
  4021. finally
  4022. {
  4023. CloseRunspace(runSpace);
  4024. }
  4025. ExchangeLog.LogEnd("GetPublicFoldersRecursiveInternal");
  4026. return ret.ToArray();
  4027. }
  4028. private long GetPublicFolderSizeInternal(string folder)
  4029. {
  4030. ExchangeLog.LogStart("GetPublicFolderSizeInternal");
  4031. long size = 0;
  4032. Runspace runSpace = null;
  4033. try
  4034. {
  4035. runSpace = OpenRunspace();
  4036. size += CalculatePublicFolderDiskSpace(runSpace, folder);
  4037. }
  4038. finally
  4039. {
  4040. CloseRunspace(runSpace);
  4041. }
  4042. ExchangeLog.LogEnd("GetPublicFolderSizeInternal");
  4043. return size;
  4044. }
  4045. public string CreateOrganizationRootPublicFolder(string organizationId, string organizationDistinguishedName, string securityGroup, string organizationDomain)
  4046. {
  4047. // not implemented
  4048. return null;
  4049. }
  4050. public string[] SetDefaultPublicFolderMailbox(string id, string organizationId, string organizationDistinguishedName)
  4051. {
  4052. // not implemented
  4053. return null;
  4054. }
  4055. #endregion
  4056. #region Address Lists (GAL, AL, RAL, OAB, ABP)
  4057. private string GetAddressListDN(Runspace runSpace, string id)
  4058. {
  4059. ExchangeLog.LogStart("GetAddressListDN");
  4060. string resultObjectDN = null;
  4061. Command cmd = new Command("Get-AddressList");
  4062. cmd.Parameters.Add("Identity", id);
  4063. Collection<PSObject> result = this.ExecuteShellCommand(runSpace, cmd);
  4064. if ((result != null) && (result.Count > 0))
  4065. {
  4066. resultObjectDN = this.GetResultObjectDN(result);
  4067. ExchangeLog.DebugInfo("AL DN: {0}", new object[] { resultObjectDN });
  4068. }
  4069. ExchangeLog.LogEnd("GetAddressListDN");
  4070. return resultObjectDN;
  4071. }
  4072. internal string CreateAddressList(Runspace runSpace, string organizationId)
  4073. {
  4074. ExchangeLog.LogStart("CreateAddressList");
  4075. string addressListName = this.GetAddressListName(organizationId);
  4076. string addressListDN = this.GetAddressListDN(runSpace, addressListName);
  4077. if (!string.IsNullOrEmpty(addressListDN))
  4078. {
  4079. //address list already exists - we will use it
  4080. ExchangeLog.LogWarning("Address List '{0}' already exists", new object[] { addressListName });
  4081. }
  4082. else
  4083. {
  4084. //try to create a new address list (10 attempts)
  4085. int attempts = 0;
  4086. Command cmd = null;
  4087. Collection<PSObject> result = null;
  4088. while (true)
  4089. {
  4090. try
  4091. {
  4092. //try to create address list
  4093. cmd = new Command("New-AddressList");
  4094. cmd.Parameters.Add("Name", addressListName);
  4095. cmd.Parameters.Add("IncludedRecipients", "AllRecipients");
  4096. cmd.Parameters.Add("ConditionalCustomAttribute1", organizationId);
  4097. result = ExecuteShellCommand(runSpace, cmd);
  4098. addressListDN = CheckResultObjectDN(result);
  4099. }
  4100. catch (Exception ex)
  4101. {
  4102. ExchangeLog.LogError(ex);
  4103. }
  4104. if (addressListDN != null)
  4105. break;
  4106. if (attempts > 9)
  4107. throw new Exception(
  4108. string.Format("Could not create Address List '{0}' ", addressListName));
  4109. attempts++;
  4110. ExchangeLog.LogWarning("Attempt #{0} to create address list failed!", attempts);
  4111. // wait 1 sec
  4112. System.Threading.Thread.Sleep(1000);
  4113. }
  4114. }
  4115. ExchangeLog.LogEnd("CreateAddressList");
  4116. return addressListDN;
  4117. }
  4118. internal string CreateRoomsAddressList(Runspace runSpace, string organizationId)
  4119. {
  4120. ExchangeLog.LogStart("CreateRoomList");
  4121. string addressListName = this.GetRoomsAddressListName(organizationId);
  4122. string addressListDN = this.GetAddressListDN(runSpace, addressListName);
  4123. if (!string.IsNullOrEmpty(addressListDN))
  4124. {
  4125. //address list already exists - we will use it
  4126. ExchangeLog.LogWarning("Room List '{0}' already exists", new object[] { addressListName });
  4127. }
  4128. else
  4129. {
  4130. //try to create a new address list (10 attempts)
  4131. int attempts = 0;
  4132. Command cmd = null;
  4133. Collection<PSObject> result = null;
  4134. while (true)
  4135. {
  4136. try
  4137. {
  4138. //try to create address list
  4139. cmd = new Command("New-AddressList");
  4140. cmd.Parameters.Add("Name", addressListName);
  4141. cmd.Parameters.Add("IncludedRecipients", "Resources");
  4142. cmd.Parameters.Add("ConditionalCustomAttribute1", organizationId);
  4143. result = ExecuteShellCommand(runSpace, cmd);
  4144. addressListDN = CheckResultObjectDN(result);
  4145. }
  4146. catch (Exception ex)
  4147. {
  4148. ExchangeLog.LogError(ex);
  4149. }
  4150. if (addressListDN != null)
  4151. break;
  4152. if (attempts > 9)
  4153. throw new Exception(
  4154. string.Format("Could not create Room List '{0}' ", addressListName));
  4155. attempts++;
  4156. ExchangeLog.LogWarning("Attempt #{0} to create room list failed!", attempts);
  4157. // wait 1 sec
  4158. System.Threading.Thread.Sleep(1000);
  4159. }
  4160. }
  4161. ExchangeLog.LogEnd("CreateRoomList");
  4162. return addressListDN;
  4163. }
  4164. internal void UpdateAddressList(Runspace runSpace, string id, string securityGroup)
  4165. {
  4166. ExchangeLog.LogStart("UpdateAddressList");
  4167. string path = AddADPrefix(id);
  4168. Command cmd = new Command("Update-AddressList");
  4169. cmd.Parameters.Add("Identity", id);
  4170. ExecuteShellCommand(runSpace, cmd);
  4171. AdjustADSecurity(path, securityGroup, false);
  4172. ExchangeLog.LogEnd("UpdateAddressList");
  4173. }
  4174. internal void DeleteAddressList(Runspace runSpace, string id)
  4175. {
  4176. ExchangeLog.LogStart("DeleteAddressList");
  4177. Command cmd = new Command("Remove-AddressList");
  4178. cmd.Parameters.Add("Identity", id);
  4179. cmd.Parameters.Add("Confirm", false);
  4180. ExecuteShellCommand(runSpace, cmd);
  4181. ExchangeLog.LogEnd("DeleteAddressList");
  4182. }
  4183. internal virtual void DeleteAddressBookPolicy(Runspace runSpace, string id)
  4184. {
  4185. ExchangeLog.LogStart("DeleteAddressBookPolicy");
  4186. ExchangeLog.LogEnd("DeleteAddressBookPolicy");
  4187. }
  4188. internal string GetGlobalAddressListDN(Runspace runSpace, string id)
  4189. {
  4190. ExchangeLog.LogStart("GetGlobalAddressListDN");
  4191. string resultObjectDN = null;
  4192. Command cmd = new Command("Get-GlobalAddressList");
  4193. cmd.Parameters.Add("Identity", id);
  4194. Collection<PSObject> result = this.ExecuteShellCommand(runSpace, cmd);
  4195. if ((result != null) && (result.Count > 0))
  4196. {
  4197. resultObjectDN = this.GetResultObjectDN(result);
  4198. ExchangeLog.DebugInfo("GAL DN: {0}", new object[] { resultObjectDN });
  4199. }
  4200. ExchangeLog.LogEnd("GetGlobalAddressListDN");
  4201. return resultObjectDN;
  4202. }
  4203. internal string CreateGlobalAddressList(Runspace runSpace, string organizationId)
  4204. {
  4205. ExchangeLog.LogStart("CreateGlobalAddressList");
  4206. string name = GetGlobalAddressListName(organizationId);
  4207. Command cmd = new Command("New-GlobalAddressList");
  4208. cmd.Parameters.Add("Name", name);
  4209. cmd.Parameters.Add("RecipientFilter", string.Format("(Alias -ne $null -and CustomAttribute1 -eq '{0}')", organizationId));
  4210. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  4211. string id = GetResultObjectDN(result);
  4212. ExchangeLog.LogEnd("CreateGlobalAddressList");
  4213. return id;
  4214. }
  4215. internal void UpdateGlobalAddressList(Runspace runSpace, string id, string securityGroup)
  4216. {
  4217. ExchangeLog.LogStart("UpdateGlobalAddressList");
  4218. Command cmd = new Command("Update-GlobalAddressList");
  4219. cmd.Parameters.Add("Identity", id);
  4220. ExecuteShellCommand(runSpace, cmd);
  4221. string path = AddADPrefix(id);
  4222. AdjustADSecurity(path, securityGroup, false);
  4223. ExchangeLog.LogEnd("UpdateGlobalAddressList");
  4224. }
  4225. internal void DeleteGlobalAddressList(Runspace runSpace, string id)
  4226. {
  4227. ExchangeLog.LogStart("DeleteGlobalAddressList");
  4228. Command cmd = new Command("Remove-GlobalAddressList");
  4229. cmd.Parameters.Add("Identity", id);
  4230. cmd.Parameters.Add("Confirm", false);
  4231. ExecuteShellCommand(runSpace, cmd);
  4232. ExchangeLog.LogEnd("DeleteGlobalAddressList");
  4233. }
  4234. private string CreateOfflineAddressBook(Runspace runSpace, string organizationId, string server, string oabVirtualDirs)
  4235. {
  4236. ExchangeLog.LogStart("CreateOfflineAddressBook");
  4237. string oabName = GetOfflineAddressBookName(organizationId);
  4238. string addressListName = GetAddressListName(organizationId);
  4239. Command cmd = new Command("New-OfflineAddressBook");
  4240. cmd.Parameters.Add("Name", oabName);
  4241. cmd.Parameters.Add("Server", server);
  4242. cmd.Parameters.Add("AddressLists", addressListName);
  4243. cmd.Parameters.Add("PublicFolderDistributionEnabled", PublicFolderDistributionEnabled);
  4244. cmd.Parameters.Add("IsDefault", false);
  4245. //TODO: fix web distribution
  4246. if (!string.IsNullOrEmpty(oabVirtualDirs))
  4247. {
  4248. ArrayList virtualDirs = new ArrayList();
  4249. string[] strTmp = oabVirtualDirs.Split(',');
  4250. foreach (string s in strTmp)
  4251. {
  4252. virtualDirs.Add(s);
  4253. }
  4254. cmd.Parameters.Add("VirtualDirectories", (String[])virtualDirs.ToArray(typeof(string)));
  4255. }
  4256. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  4257. string id = GetResultObjectDN(result);
  4258. ExchangeLog.LogEnd("CreateOfflineAddressBook");
  4259. return id;
  4260. }
  4261. private void UpdateOfflineAddressBook(Runspace runSpace, string id, string securityGroup)
  4262. {
  4263. ExchangeLog.LogStart("UpdateOfflineAddressBook");
  4264. string path = AddADPrefix(id);
  4265. //Command cmd = new Command("Update-OfflineAddressBook");
  4266. //cmd.Parameters.Add("Identity", id);
  4267. //ExecuteShellCommand(runSpace, cmd);
  4268. AdjustADSecurity(path, securityGroup, true);
  4269. ExchangeLog.LogEnd("UpdateOfflineAddressBook");
  4270. }
  4271. internal void DeleteOfflineAddressBook(Runspace runSpace, string id)
  4272. {
  4273. ExchangeLog.LogStart("DeleteOfflineAddressBook");
  4274. Command cmd = new Command("Remove-OfflineAddressBook");
  4275. cmd.Parameters.Add("Identity", id);
  4276. cmd.Parameters.Add("Confirm", false);
  4277. ExecuteShellCommand(runSpace, cmd);
  4278. ExchangeLog.LogEnd("DeleteOfflineAddressBook");
  4279. }
  4280. private void DeleteAddressPolicy(Runspace runSpace, string id)
  4281. {
  4282. ExchangeLog.LogStart("DeleteAddressPolicy");
  4283. Command cmd = new Command("Remove-AddressBookPolicy");
  4284. cmd.Parameters.Add("Identity", id);
  4285. cmd.Parameters.Add("Confirm", false);
  4286. ExecuteShellCommand(runSpace, cmd);
  4287. ExchangeLog.LogEnd("DeleteAddressPolicy");
  4288. }
  4289. private string GetAddressListName(string orgName)
  4290. {
  4291. return orgName + " Address List";
  4292. }
  4293. internal string GetGlobalAddressListName(string orgName)
  4294. {
  4295. return orgName + " Global Address List";
  4296. }
  4297. private string GetOfflineAddressBookName(string orgName)
  4298. {
  4299. return orgName + " Offline Address Book";
  4300. }
  4301. internal string GetAddressBookPolicyName(string orgName)
  4302. {
  4303. return orgName + " Address Policy";
  4304. }
  4305. private string GetRoomsAddressListName(string orgName)
  4306. {
  4307. return orgName + " Rooms";
  4308. }
  4309. #endregion
  4310. #region Active Directory
  4311. private string CreateOrganizationalUnit(string name)
  4312. {
  4313. ExchangeLog.LogStart("CreateOrganizationalUnit");
  4314. string ret = null;
  4315. DirectoryEntry ou = null;
  4316. DirectoryEntry rootOU = null;
  4317. try
  4318. {
  4319. rootOU = GetRootOU();
  4320. ou = rootOU.Children.Add(
  4321. string.Format("OU={0}", name),
  4322. rootOU.SchemaClassName);
  4323. ret = ou.Path;
  4324. ou.CommitChanges();
  4325. }
  4326. finally
  4327. {
  4328. if (ou != null)
  4329. ou.Close();
  4330. if (rootOU != null)
  4331. rootOU.Close();
  4332. }
  4333. ExchangeLog.LogEnd("CreateOrganizationalUnit");
  4334. return ret;
  4335. }
  4336. private void DeleteADObject(string id)
  4337. {
  4338. ExchangeLog.LogStart("DeleteADObject");
  4339. string path = AddADPrefix(id);
  4340. DirectoryEntry ou = GetADObject(path);
  4341. DirectoryEntry parent = ou.Parent;
  4342. if (parent != null)
  4343. {
  4344. parent.Children.Remove(ou);
  4345. parent.CommitChanges();
  4346. }
  4347. ExchangeLog.LogEnd("DeleteADObject");
  4348. }
  4349. private DirectoryEntry GetRootOU()
  4350. {
  4351. ExchangeLog.LogStart("GetRootOU");
  4352. StringBuilder sb = new StringBuilder();
  4353. // append provider
  4354. AppendProtocol(sb);
  4355. AppendDomainController(sb);
  4356. AppendOUPath(sb, RootOU);
  4357. AppendDomainPath(sb, RootDomain);
  4358. DirectoryEntry de = GetADObject(sb.ToString());
  4359. ExchangeLog.LogEnd("GetRootOU");
  4360. return de;
  4361. }
  4362. private void SetADObjectProperty(DirectoryEntry oDE, string name, string value)
  4363. {
  4364. if (!string.IsNullOrEmpty(value))
  4365. {
  4366. if (oDE.Properties.Contains(name))
  4367. {
  4368. oDE.Properties[name][0] = value;
  4369. }
  4370. else
  4371. {
  4372. oDE.Properties[name].Add(value);
  4373. }
  4374. }
  4375. }
  4376. internal void SetADObjectPropertyValue(DirectoryEntry oDE, string name, string value)
  4377. {
  4378. PropertyValueCollection collection = oDE.Properties[name];
  4379. collection.Value = value;
  4380. }
  4381. internal void AddADObjectProperty(DirectoryEntry oDE, string name, string value)
  4382. {
  4383. if (!string.IsNullOrEmpty(value))
  4384. {
  4385. oDE.Properties[name].Add(value);
  4386. }
  4387. }
  4388. internal DirectoryEntry GetADObject(string path)
  4389. {
  4390. DirectoryEntry de = null;
  4391. if (path.StartsWith("LDAP://" + PrimaryDomainController + "/", true, CultureInfo.InvariantCulture))
  4392. {
  4393. ExchangeLog.LogInfo("Get Active Directory Object {0} from {1}", path, PrimaryDomainController);
  4394. de = new DirectoryEntry(path, null, null, AuthenticationTypes.ServerBind);
  4395. }
  4396. else
  4397. {
  4398. ExchangeLog.LogInfo("Get Active Directory Object {0}", path);
  4399. de = new DirectoryEntry(path);
  4400. }
  4401. if (de != null)
  4402. de.RefreshCache();
  4403. return de;
  4404. }
  4405. internal object GetADObjectProperty(DirectoryEntry entry, string name)
  4406. {
  4407. if (entry.Properties.Contains(name))
  4408. return entry.Properties[name][0];
  4409. else
  4410. return String.Empty;
  4411. }
  4412. private string GetOrganizationPath(string organizationId)
  4413. {
  4414. StringBuilder sb = new StringBuilder();
  4415. // append provider
  4416. AppendOUPath(sb, organizationId);
  4417. AppendOUPath(sb, RootOU);
  4418. AppendDomainPath(sb, RootDomain);
  4419. return sb.ToString();
  4420. }
  4421. private void AppendProtocol(StringBuilder sb)
  4422. {
  4423. sb.Append("LDAP://");
  4424. }
  4425. private void AppendDomainController(StringBuilder sb)
  4426. {
  4427. sb.Append(PrimaryDomainController + "/");
  4428. }
  4429. private void AppendOUPath(StringBuilder sb, string ou)
  4430. {
  4431. if (string.IsNullOrEmpty(ou))
  4432. return;
  4433. string path = ou.Replace("/", "\\");
  4434. string[] parts = path.Split('\\');
  4435. for (int i = parts.Length - 1; i != -1; i--)
  4436. sb.Append("OU=").Append(parts[i]).Append(",");
  4437. }
  4438. private void AppendDomainPath(StringBuilder sb, string domain)
  4439. {
  4440. if (string.IsNullOrEmpty(domain))
  4441. return;
  4442. string[] parts = domain.Split('.');
  4443. for (int i = 0; i < parts.Length; i++)
  4444. {
  4445. sb.Append("DC=").Append(parts[i]);
  4446. if (i < (parts.Length - 1))
  4447. sb.Append(",");
  4448. }
  4449. }
  4450. internal string AddADPrefix(string path)
  4451. {
  4452. string dn = path;
  4453. if (!dn.ToUpper().StartsWith("LDAP://"))
  4454. {
  4455. dn = string.Format("LDAP://{0}/{1}", PrimaryDomainController, dn);
  4456. }
  4457. return dn;
  4458. }
  4459. private string RemoveADPrefix(string path)
  4460. {
  4461. string dn = path;
  4462. if (dn.ToUpper().StartsWith("LDAP://"))
  4463. {
  4464. dn = dn.Substring(7);
  4465. }
  4466. int index = dn.IndexOf("/");
  4467. if (index != -1)
  4468. {
  4469. dn = dn.Substring(index + 1);
  4470. }
  4471. return dn;
  4472. }
  4473. internal string ConvertADPathToCanonicalName(string name)
  4474. {
  4475. if (string.IsNullOrEmpty(name))
  4476. return null;
  4477. StringBuilder ret = new StringBuilder();
  4478. List<string> cn = new List<string>();
  4479. List<string> dc = new List<string>();
  4480. name = RemoveADPrefix(name);
  4481. string[] parts = name.Split(',');
  4482. for (int i = 0; i < parts.Length; i++)
  4483. {
  4484. if (parts[i].StartsWith("DC="))
  4485. {
  4486. dc.Add(parts[i].Substring(3));
  4487. }
  4488. else if (parts[i].StartsWith("OU=") || parts[i].StartsWith("CN="))
  4489. {
  4490. cn.Add(parts[i].Substring(3));
  4491. }
  4492. }
  4493. for (int i = 0; i < dc.Count; i++)
  4494. {
  4495. ret.Append(dc[i]);
  4496. if (i < dc.Count - 1)
  4497. ret.Append(".");
  4498. }
  4499. for (int i = cn.Count - 1; i != -1; i--)
  4500. {
  4501. ret.Append("/");
  4502. ret.Append(cn[i]);
  4503. }
  4504. return ret.ToString();
  4505. }
  4506. private string ConvertDomainName(string name)
  4507. {
  4508. if (string.IsNullOrEmpty(name))
  4509. return null;
  4510. StringBuilder ret = new StringBuilder("LDAP://");
  4511. string[] parts = name.Split('.');
  4512. for (int i = 0; i < parts.Length; i++)
  4513. {
  4514. ret.Append("DC=");
  4515. ret.Append(parts[i]);
  4516. if (i < parts.Length - 1)
  4517. ret.Append(",");
  4518. }
  4519. return ret.ToString();
  4520. }
  4521. internal virtual void AdjustADSecurity(string objPath, string securityGroupPath, bool isAddressBook)
  4522. {
  4523. ExchangeLog.LogStart("AdjustADSecurity");
  4524. ExchangeLog.DebugInfo(" Active Direcory object: {0}", objPath);
  4525. ExchangeLog.DebugInfo(" Security Group: {0}", securityGroupPath);
  4526. //"Open Address Book" security permission for address lists or
  4527. //"Download Address Book" security permission for offline address book
  4528. Guid openAddressBookGuid = new Guid("{a1990816-4298-11d1-ade2-00c04fd8d5cd}");
  4529. if (isAddressBook)
  4530. openAddressBookGuid = new Guid("{bd919c7c-2d79-4950-bc9c-e16fd99285e8}");
  4531. DirectoryEntry groupEntry = GetADObject(securityGroupPath);
  4532. byte[] byteSid = (byte[])GetADObjectProperty(groupEntry, "objectSid");
  4533. DirectoryEntry objEntry = GetADObject(objPath);
  4534. ActiveDirectorySecurity security = objEntry.ObjectSecurity;
  4535. // Create a SecurityIdentifier object for "AuthenticatedUsers".
  4536. SecurityIdentifier auSid = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null);
  4537. // Create a SecurityIdentifier object for security group.
  4538. SecurityIdentifier groupSid = new SecurityIdentifier(byteSid, 0);
  4539. // Create an access rule to allow AuthenticatedUsers to open address book.
  4540. // This is used to remove any existing access rules.
  4541. ActiveDirectoryAccessRule allowOpenAddressBook =
  4542. new ActiveDirectoryAccessRule(
  4543. auSid,
  4544. ActiveDirectoryRights.ExtendedRight,
  4545. AccessControlType.Allow,
  4546. openAddressBookGuid);
  4547. // Create an access rule to allow AuthenticatedUsers to read object.
  4548. // This is used to remove any existing access rules.
  4549. ActiveDirectoryAccessRule allowRead =
  4550. new ActiveDirectoryAccessRule(
  4551. auSid,
  4552. ActiveDirectoryRights.GenericRead,
  4553. AccessControlType.Allow);
  4554. // Remove any existing rule that gives "AuthenticatedUsers" the right to open address book.
  4555. security.RemoveAccessRuleSpecific(allowOpenAddressBook);
  4556. // Remove any existing rule that gives "AuthenticatedUsers" the right to read object.
  4557. security.RemoveAccessRuleSpecific(allowRead);
  4558. // Create an access rule to allow users in Security Group to open address book.
  4559. allowOpenAddressBook =
  4560. new ActiveDirectoryAccessRule(
  4561. groupSid,
  4562. ActiveDirectoryRights.ExtendedRight,
  4563. AccessControlType.Allow,
  4564. openAddressBookGuid);
  4565. // Create an access rule to allow users in Security Group to read object.
  4566. allowRead =
  4567. new ActiveDirectoryAccessRule(
  4568. groupSid,
  4569. ActiveDirectoryRights.GenericRead,
  4570. AccessControlType.Allow);
  4571. // Remove existing rules if exist
  4572. security.RemoveAccessRuleSpecific(allowOpenAddressBook);
  4573. security.RemoveAccessRuleSpecific(allowRead);
  4574. // Add a new access rule to allow users in Security Group to open address book.
  4575. security.AddAccessRule(allowOpenAddressBook);
  4576. // Add a new access rule to allow users in Security Group to read object.
  4577. security.AddAccessRule(allowRead);
  4578. // Commit the changes.
  4579. objEntry.CommitChanges();
  4580. ExchangeLog.LogEnd("AdjustADSecurity");
  4581. }
  4582. private void AddUPNSuffix(string ouPath, string suffix)
  4583. {
  4584. ExchangeLog.LogStart("AddUPNSuffix");
  4585. //Add UPN Suffix to the OU
  4586. DirectoryEntry ou = GetADObject(ouPath);
  4587. AddADObjectProperty(ou, "uPNSuffixes", suffix);
  4588. ou.CommitChanges();
  4589. ou.Close();
  4590. ExchangeLog.LogEnd("AddUPNSuffix");
  4591. }
  4592. private void RemoveUPNSuffix(string ouPath, string suffix)
  4593. {
  4594. ExchangeLog.LogStart("RemoveUPNSuffix");
  4595. if (DirectoryEntry.Exists(ouPath))
  4596. {
  4597. DirectoryEntry ou = GetADObject(ouPath);
  4598. PropertyValueCollection prop = null;
  4599. try
  4600. {
  4601. prop = ou.Properties["uPNSuffixes"];
  4602. }
  4603. catch (Exception ex)
  4604. {
  4605. ExchangeLog.LogWarning("AD object or property not found: {0}", ex);
  4606. }
  4607. if (prop != null)
  4608. {
  4609. if (ou.Properties["uPNSuffixes"].Contains(suffix))
  4610. {
  4611. ou.Properties["uPNSuffixes"].Remove(suffix);
  4612. ou.CommitChanges();
  4613. }
  4614. ou.Close();
  4615. }
  4616. }
  4617. ExchangeLog.LogEnd("RemoveUPNSuffix");
  4618. }
  4619. /*private void AddGlobalUPNSuffix(string name)
  4620. {
  4621. ExchangeLog.LogStart("AddGlobalUPNSuffix");
  4622. string path = string.Format("LDAP://{0}/RootDSE", RootDomain);
  4623. DirectoryEntry rootDSE = GetADObject(path);
  4624. string contextPath = GetADObjectProperty(rootDSE, "ConfigurationNamingContext").ToString();
  4625. DirectoryEntry partitions = GetADObject("LDAP://cn=Partitions," + contextPath);
  4626. partitions.Properties["uPNSuffixes"].Add(name);
  4627. partitions.CommitChanges();
  4628. partitions.Close();
  4629. rootDSE.Close();
  4630. ExchangeLog.LogEnd("AddGlobalUPNSuffix");
  4631. }*/
  4632. internal string GetNETBIOSDomainName()
  4633. {
  4634. ExchangeLog.LogStart("GetNETBIOSDomainName");
  4635. string ret = string.Empty;
  4636. string path = string.Format("LDAP://{0}/RootDSE", RootDomain);
  4637. DirectoryEntry rootDSE = GetADObject(path);
  4638. string contextPath = GetADObjectProperty(rootDSE, "ConfigurationNamingContext").ToString();
  4639. string defaultContext = GetADObjectProperty(rootDSE, "defaultNamingContext").ToString();
  4640. DirectoryEntry partitions = GetADObject("LDAP://cn=Partitions," + contextPath);
  4641. DirectorySearcher searcher = new DirectorySearcher();
  4642. searcher.SearchRoot = partitions;
  4643. searcher.Filter = string.Format("(&(objectCategory=crossRef)(nCName={0}))", defaultContext);
  4644. searcher.SearchScope = SearchScope.OneLevel;
  4645. //find the first instance
  4646. SearchResult result = searcher.FindOne();
  4647. if (result != null)
  4648. {
  4649. DirectoryEntry partition = GetADObject(result.Path);
  4650. ret = GetADObjectProperty(partition, "nETBIOSName").ToString();
  4651. partition.Close();
  4652. }
  4653. partitions.Close();
  4654. rootDSE.Close();
  4655. ExchangeLog.LogEnd("GetNETBIOSDomainName");
  4656. return ret;
  4657. }
  4658. /*private void RemoveGlobalUPNSuffix(string name)
  4659. {
  4660. ExchangeLog.LogStart("RemoveGlobalUPNSuffix");
  4661. string path = string.Format("LDAP://{0}/RootDSE", RootDomain);
  4662. DirectoryEntry rootDSE = GetADObject(path);
  4663. string contextPath = GetADObjectProperty(rootDSE, "ConfigurationNamingContext").ToString();
  4664. DirectoryEntry partitions = GetADObject("LDAP://cn=Partitions," + contextPath);
  4665. if (partitions.Properties["uPNSuffixes"].Contains(name))
  4666. {
  4667. partitions.Properties["uPNSuffixes"].Remove(name);
  4668. partitions.CommitChanges();
  4669. }
  4670. partitions.Close();
  4671. rootDSE.Close();
  4672. ExchangeLog.LogEnd("RemoveGlobalUPNSuffix");
  4673. }*/
  4674. #endregion
  4675. #region PowerShell integration
  4676. /*private Collection<PSObject> ExecuteShellCommand2(Runspace runSpace, string cmd)
  4677. {
  4678. ExchangeLog.LogStart("ExecuteShellCommand");
  4679. RunspaceInvoke invoker = new RunspaceInvoke(runSpace);
  4680. System.Collections.IList errors = null;
  4681. Collection<PSObject> results = invoker.Invoke(cmd, null, out errors);
  4682. if (errors != null && errors.Count > 0)
  4683. {
  4684. foreach (PSObject err in errors)
  4685. {
  4686. string errorMessage = string.Format("Invoke error: {0}", err.ToString());
  4687. ExchangeLog.LogError(errorMessage, null);
  4688. }
  4689. }
  4690. invoker = null;
  4691. ExchangeLog.LogEnd("ExecuteShellCommand");
  4692. return results;
  4693. }*/
  4694. private static RunspaceConfiguration runspaceConfiguration = null;
  4695. private static string ExchangePath = null;
  4696. internal static string GetExchangePath()
  4697. {
  4698. if (string.IsNullOrEmpty(ExchangePath))
  4699. {
  4700. RegistryKey root = Registry.LocalMachine;
  4701. RegistryKey rk = root.OpenSubKey(ExchangeRegistryPath);
  4702. if (rk != null)
  4703. {
  4704. string value = (string)rk.GetValue("MsiInstallPath", null);
  4705. rk.Close();
  4706. if (!string.IsNullOrEmpty(value))
  4707. ExchangePath = Path.Combine(value, "bin");
  4708. }
  4709. }
  4710. return ExchangePath;
  4711. }
  4712. private static Assembly ResolveExchangeAssembly(object p, ResolveEventArgs args)
  4713. {
  4714. //Add path for the Exchange 2007 DLLs
  4715. if (args.Name.Contains("Microsoft.Exchange"))
  4716. {
  4717. string exchangePath = GetExchangePath();
  4718. if (string.IsNullOrEmpty(exchangePath))
  4719. return null;
  4720. string path = Path.Combine(exchangePath, args.Name.Split(',')[0] + ".dll");
  4721. if (!File.Exists(path))
  4722. return null;
  4723. ExchangeLog.DebugInfo("Resolved assembly: {0}", path);
  4724. return Assembly.LoadFrom(path);
  4725. }
  4726. else
  4727. {
  4728. return null;
  4729. }
  4730. }
  4731. internal virtual Runspace OpenRunspace()
  4732. {
  4733. ExchangeLog.LogStart("OpenRunspace");
  4734. if (runspaceConfiguration == null)
  4735. {
  4736. runspaceConfiguration = RunspaceConfiguration.Create();
  4737. PSSnapInException exception = null;
  4738. PSSnapInInfo info = runspaceConfiguration.AddPSSnapIn(ExchangeSnapInName, out exception);
  4739. if (exception != null)
  4740. {
  4741. ExchangeLog.LogWarning("SnapIn error", exception);
  4742. }
  4743. }
  4744. Runspace runSpace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
  4745. //
  4746. runSpace.Open();
  4747. //
  4748. runSpace.SessionStateProxy.SetVariable("ConfirmPreference", "none");
  4749. ExchangeLog.LogEnd("OpenRunspace");
  4750. return runSpace;
  4751. }
  4752. internal void CloseRunspace(Runspace runspace)
  4753. {
  4754. try
  4755. {
  4756. if (runspace != null && runspace.RunspaceStateInfo.State == RunspaceState.Opened)
  4757. {
  4758. runspace.Close();
  4759. }
  4760. }
  4761. catch (Exception ex)
  4762. {
  4763. ExchangeLog.LogError("Runspace error", ex);
  4764. }
  4765. }
  4766. internal Collection<PSObject> ExecuteShellCommand(Runspace runSpace, Command cmd)
  4767. {
  4768. return ExecuteShellCommand(runSpace, cmd, false);
  4769. }
  4770. internal Collection<PSObject> ExecuteShellCommand(Runspace runSpace, Command cmd, bool useDomainController)
  4771. {
  4772. object[] errors;
  4773. return ExecuteShellCommand(runSpace, cmd, useDomainController, out errors);
  4774. }
  4775. internal Collection<PSObject> ExecuteShellCommand(Runspace runSpace, Command cmd, out object[] errors)
  4776. {
  4777. return ExecuteShellCommand(runSpace, cmd, true, out errors);
  4778. }
  4779. internal Collection<PSObject> ExecuteShellCommand(Runspace runSpace, Command cmd, bool useDomainController, out object[] errors)
  4780. {
  4781. ExchangeLog.LogStart("ExecuteShellCommand");
  4782. List<object> errorList = new List<object>();
  4783. if (useDomainController)
  4784. {
  4785. CommandParameter dc = new CommandParameter("DomainController", PrimaryDomainController);
  4786. if (!cmd.Parameters.Contains(dc))
  4787. {
  4788. cmd.Parameters.Add(dc);
  4789. }
  4790. }
  4791. ExchangeLog.DebugCommand(cmd);
  4792. Collection<PSObject> results = null;
  4793. // Create a pipeline
  4794. Pipeline pipeLine = runSpace.CreatePipeline();
  4795. using (pipeLine)
  4796. {
  4797. // Add the command
  4798. pipeLine.Commands.Add(cmd);
  4799. // Execute the pipeline and save the objects returned.
  4800. results = pipeLine.Invoke();
  4801. // Log out any errors in the pipeline execution
  4802. // NOTE: These errors are NOT thrown as exceptions!
  4803. // Be sure to check this to ensure that no errors
  4804. // happened while executing the command.
  4805. if (pipeLine.Error != null && pipeLine.Error.Count > 0)
  4806. {
  4807. foreach (object item in pipeLine.Error.ReadToEnd())
  4808. {
  4809. errorList.Add(item);
  4810. string errorMessage = string.Format("Invoke error: {0}", item);
  4811. ExchangeLog.LogWarning(errorMessage);
  4812. }
  4813. }
  4814. }
  4815. pipeLine = null;
  4816. errors = errorList.ToArray();
  4817. ExchangeLog.LogEnd("ExecuteShellCommand");
  4818. return results;
  4819. }
  4820. /// <summary>
  4821. /// Returns the distinguished name of the object from the shell execution result
  4822. /// </summary>
  4823. /// <param name="result"></param>
  4824. /// <returns></returns>
  4825. internal string GetResultObjectDN(Collection<PSObject> result)
  4826. {
  4827. ExchangeLog.LogStart("GetResultObjectDN");
  4828. if (result == null)
  4829. throw new ArgumentNullException("result", "Execution result is not specified");
  4830. if (result.Count < 1)
  4831. throw new ArgumentException("Execution result does not contain any object");
  4832. if (result.Count > 1)
  4833. throw new ArgumentException("Execution result contains more than one object");
  4834. PSMemberInfo info = result[0].Members["DistinguishedName"];
  4835. if (info == null)
  4836. throw new ArgumentException("Execution result does not contain DistinguishedName property", "result");
  4837. string ret = info.Value.ToString();
  4838. ExchangeLog.LogEnd("GetResultObjectDN");
  4839. return ret;
  4840. }
  4841. /// <summary>
  4842. /// Checks the object from the shell execution result.
  4843. /// </summary>
  4844. /// <param name="result"></param>
  4845. /// <returns>Distinguished name of the object if object exists or null otherwise.</returns>
  4846. internal string CheckResultObjectDN(Collection<PSObject> result)
  4847. {
  4848. ExchangeLog.LogStart("CheckResultObjectDN");
  4849. if (result == null)
  4850. return null;
  4851. if (result.Count < 1)
  4852. return null;
  4853. PSMemberInfo info = result[0].Members["DistinguishedName"];
  4854. if (info == null)
  4855. throw new ArgumentException("Execution result does not contain DistinguishedName property", "result");
  4856. string ret = info.Value.ToString();
  4857. ExchangeLog.LogEnd("CheckResultObjectDN");
  4858. return ret;
  4859. }
  4860. /// <summary>
  4861. /// Returns the identity of the object from the shell execution result
  4862. /// </summary>
  4863. /// <param name="result"></param>
  4864. /// <returns></returns>
  4865. internal string GetResultObjectIdentity(Collection<PSObject> result)
  4866. {
  4867. ExchangeLog.LogStart("GetResultObjectIdentity");
  4868. if (result == null)
  4869. throw new ArgumentNullException("result", "Execution result is not specified");
  4870. if (result.Count < 1)
  4871. throw new ArgumentException("Execution result is empty", "result");
  4872. if (result.Count > 1)
  4873. throw new ArgumentException("Execution result contains more than one object", "result");
  4874. PSMemberInfo info = result[0].Members["Identity"];
  4875. if (info == null)
  4876. throw new ArgumentException("Execution result does not contain Identity property", "result");
  4877. string ret = info.Value.ToString();
  4878. ExchangeLog.LogEnd("GetResultObjectIdentity");
  4879. return ret;
  4880. }
  4881. /// <summary>
  4882. /// Returns the identity of the PS object
  4883. /// </summary>
  4884. /// <param name="obj"></param>
  4885. /// <returns></returns>
  4886. internal string GetPSObjectIdentity(PSObject obj)
  4887. {
  4888. ExchangeLog.LogStart("GetPSObjectIdentity");
  4889. if (obj == null)
  4890. throw new ArgumentNullException("obj", "PSObject is not specified");
  4891. PSMemberInfo info = obj.Members["Identity"];
  4892. if (info == null)
  4893. throw new ArgumentException("PSObject does not contain Identity property", "obj");
  4894. string ret = info.Value.ToString();
  4895. ExchangeLog.LogEnd("GetPSObjectIdentity");
  4896. return ret;
  4897. }
  4898. internal object GetPSObjectProperty(PSObject obj, string name)
  4899. {
  4900. return obj.Members[name].Value;
  4901. }
  4902. #endregion
  4903. #region Storage
  4904. internal virtual string CreateStorageGroup(Runspace runSpace, string name, string server)
  4905. {
  4906. ExchangeLog.LogStart("CreateStorageGroup");
  4907. if (name.StartsWith(server + "\\"))
  4908. name = name.Substring(server.Length + 1);
  4909. string id = string.Format("{0}\\{1}", server, name);
  4910. Command cmd = new Command("Get-StorageGroup");
  4911. cmd.Parameters.Add("Identity", id);
  4912. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  4913. if (result != null && result.Count > 0)
  4914. {
  4915. id = GetResultObjectIdentity(result);
  4916. }
  4917. else
  4918. {
  4919. cmd = new Command("New-StorageGroup");
  4920. cmd.Parameters.Add("Name", name);
  4921. cmd.Parameters.Add("Server", server);
  4922. result = ExecuteShellCommand(runSpace, cmd);
  4923. id = GetResultObjectIdentity(result);
  4924. }
  4925. ExchangeLog.LogEnd("CreateStorageGroup");
  4926. return id;
  4927. }
  4928. internal virtual string CreateMailboxDatabase(Runspace runSpace, string name, string storageGroup)
  4929. {
  4930. ExchangeLog.LogStart("CreateMailboxDatabase");
  4931. string id = string.Format("{0}\\{1}", storageGroup, name);
  4932. Command cmd = new Command("Get-MailboxDatabase");
  4933. cmd.Parameters.Add("Identity", id);
  4934. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  4935. if (result != null && result.Count > 0)
  4936. {
  4937. id = GetResultObjectIdentity(result);
  4938. }
  4939. else
  4940. {
  4941. cmd = new Command("New-MailboxDatabase");
  4942. cmd.Parameters.Add("Name", name);
  4943. cmd.Parameters.Add("StorageGroup", storageGroup);
  4944. result = ExecuteShellCommand(runSpace, cmd);
  4945. id = GetResultObjectIdentity(result);
  4946. cmd = new Command("Set-MailboxDatabase");
  4947. cmd.Parameters.Add("Identity", id);
  4948. cmd.Parameters.Add("IssueWarningQuota", Unlimited<ByteQuantifiedSize>.UnlimitedValue);
  4949. cmd.Parameters.Add("ProhibitSendQuota", Unlimited<ByteQuantifiedSize>.UnlimitedValue);
  4950. cmd.Parameters.Add("ProhibitSendReceiveQuota", Unlimited<ByteQuantifiedSize>.UnlimitedValue);
  4951. cmd.Parameters.Add("DeletedItemRetention", KeepDeletedItemsDays);
  4952. cmd.Parameters.Add("MailboxRetention", KeepDeletedMailboxesDays);
  4953. ExecuteShellCommand(runSpace, cmd);
  4954. cmd = new Command("Mount-Database");
  4955. cmd.Parameters.Add("Identity", id);
  4956. ExecuteShellCommand(runSpace, cmd);
  4957. }
  4958. ExchangeLog.LogEnd("CreateMailboxDatabase");
  4959. return id;
  4960. }
  4961. #endregion
  4962. #region Domains
  4963. private string[] GetAuthoritativeDomainsInternal()
  4964. {
  4965. ExchangeLog.LogStart("GetAuthoritativeDomainsInternal");
  4966. Runspace runSpace = null;
  4967. List<string> domains = new List<string>();
  4968. try
  4969. {
  4970. runSpace = OpenRunspace();
  4971. Command cmd = new Command("Get-AcceptedDomain");
  4972. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  4973. foreach (PSObject current in result)
  4974. {
  4975. domains.Add(GetPSObjectProperty(current, "DomainName").ToString());
  4976. }
  4977. }
  4978. catch (Exception ex)
  4979. {
  4980. ExchangeLog.LogError("GetAuthoritativeDomainsInternal", ex);
  4981. throw;
  4982. }
  4983. finally
  4984. {
  4985. CloseRunspace(runSpace);
  4986. }
  4987. ExchangeLog.LogEnd("GetAuthoritativeDomainsInternal");
  4988. return domains.ToArray();
  4989. }
  4990. /// <summary>
  4991. /// Creates Authoritative Domain on Hub Transport Server
  4992. /// </summary>
  4993. /// <param name="domain"></param>
  4994. /// <returns></returns>
  4995. private void CreateAuthoritativeDomainInternal(string domain)
  4996. {
  4997. ExchangeLog.LogStart("CreateAuthoritativeDomainInternal");
  4998. Runspace runSpace = null;
  4999. try
  5000. {
  5001. runSpace = OpenRunspace();
  5002. CreateAcceptedDomain(runSpace, domain);
  5003. }
  5004. catch (Exception ex)
  5005. {
  5006. ExchangeLog.LogError("CreateAuthoritativeDomainInternal", ex);
  5007. throw;
  5008. }
  5009. finally
  5010. {
  5011. CloseRunspace(runSpace);
  5012. }
  5013. ExchangeLog.LogEnd("CreateAuthoritativeDomainInternal");
  5014. }
  5015. private void ChangeAcceptedDomainTypeInternal(string domainName, ExchangeAcceptedDomainType domainType)
  5016. {
  5017. ExchangeLog.LogStart("ChangeAcceptedDomainType");
  5018. Runspace runSpace = null;
  5019. try
  5020. {
  5021. runSpace = OpenRunspace();
  5022. SetAcceptedDomainType(runSpace, domainName, domainType);
  5023. }
  5024. catch (Exception ex)
  5025. {
  5026. ExchangeLog.LogError("ChangeAcceptedDomainType", ex);
  5027. throw;
  5028. }
  5029. finally
  5030. {
  5031. CloseRunspace(runSpace);
  5032. }
  5033. ExchangeLog.LogEnd("ChangeAcceptedDomainType");
  5034. }
  5035. private void DeleteAcceptedDomain(Runspace runSpace, string domainName)
  5036. {
  5037. ExchangeLog.LogStart("DeleteAcceptedDomain");
  5038. bool bCloseRunSpace = false;
  5039. try
  5040. {
  5041. if (runSpace == null)
  5042. {
  5043. bCloseRunSpace = true;
  5044. runSpace = OpenRunspace();
  5045. }
  5046. RemoveAcceptedDomain(runSpace, domainName);
  5047. }
  5048. catch (Exception ex)
  5049. {
  5050. ExchangeLog.LogError("DeleteAcceptedDomain", ex);
  5051. throw;
  5052. }
  5053. finally
  5054. {
  5055. if (bCloseRunSpace) CloseRunspace(runSpace);
  5056. }
  5057. ExchangeLog.LogEnd("DeleteAcceptedDomain");
  5058. }
  5059. /// <summary>
  5060. /// Deletes Authoritative Domain on Hub Transport Server
  5061. /// </summary>
  5062. /// <param name="domain"></param>
  5063. private void DeleteAuthoritativeDomainInternal(string domain)
  5064. {
  5065. ExchangeLog.LogStart("DeleteDomainInternal");
  5066. //Delete accepted domain
  5067. DeleteAcceptedDomain(null, domain);
  5068. ExchangeLog.LogEnd("DeleteDomainInternal");
  5069. }
  5070. private string CreateAcceptedDomain(Runspace runSpace, string name)
  5071. {
  5072. ExchangeLog.LogStart("CreateAcceptedDomain");
  5073. Command cmd = new Command("New-AcceptedDomain");
  5074. cmd.Parameters.Add("Name", name);
  5075. cmd.Parameters.Add("DomainName", name);
  5076. cmd.Parameters.Add("DomainType", "Authoritative");
  5077. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  5078. string id = GetResultObjectDN(result);
  5079. ExchangeLog.LogEnd("CreateAcceptedDomain");
  5080. return id;
  5081. }
  5082. private void RemoveAcceptedDomain(Runspace runSpace, string id)
  5083. {
  5084. ExchangeLog.LogStart("RemoveAcceptedDomain");
  5085. Command cmd = new Command("Remove-AcceptedDomain");
  5086. cmd.Parameters.Add("Identity", id);
  5087. cmd.Parameters.Add("Confirm", false);
  5088. ExecuteShellCommand(runSpace, cmd);
  5089. ExchangeLog.LogEnd("RemoveAcceptedDomain");
  5090. }
  5091. private void SetAcceptedDomainType(Runspace runSpace, string id, ExchangeAcceptedDomainType domainType)
  5092. {
  5093. ExchangeLog.LogStart("SetAcceptedDomainType");
  5094. Command cmd = new Command("Set-AcceptedDomain");
  5095. cmd.Parameters.Add("Identity", id);
  5096. cmd.Parameters.Add("DomainType", domainType.ToString());
  5097. cmd.Parameters.Add("AddressBookEnabled", !(domainType == ExchangeAcceptedDomainType.InternalRelay));
  5098. cmd.Parameters.Add("Confirm", false);
  5099. ExecuteShellCommand(runSpace, cmd);
  5100. ExchangeLog.LogEnd("SetAcceptedDomainType");
  5101. }
  5102. #endregion
  5103. #region ActiveSync
  5104. private void CreateOrganizationActiveSyncPolicyInternal(string organizationId)
  5105. {
  5106. ExchangeLog.LogStart("CreateOrganizationActiveSyncPolicyInternal");
  5107. ExchangeLog.DebugInfo(" Organization Id: {0}", organizationId);
  5108. Runspace runSpace = null;
  5109. try
  5110. {
  5111. runSpace = OpenRunspace();
  5112. //create ActiveSync policy
  5113. CreateActiveSyncPolicy(runSpace, organizationId);
  5114. }
  5115. finally
  5116. {
  5117. CloseRunspace(runSpace);
  5118. }
  5119. ExchangeLog.LogEnd("CreateOrganizationActiveSyncPolicyInternal");
  5120. }
  5121. internal string CreateActiveSyncPolicy(Runspace runSpace, string organizationId)
  5122. {
  5123. ExchangeLog.LogStart("CreateActiveSyncPolicy");
  5124. Command cmd = new Command("New-ActiveSyncMailboxPolicy");
  5125. cmd.Parameters.Add("Name", organizationId);
  5126. cmd.Parameters.Add("AllowNonProvisionableDevices", true);
  5127. cmd.Parameters.Add("Confirm", false);
  5128. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  5129. string id = GetResultObjectIdentity(result);
  5130. ExchangeLog.LogEnd("CreateActiveSyncPolicy");
  5131. return id;
  5132. }
  5133. internal void DeleteActiveSyncPolicy(Runspace runSpace, string id)
  5134. {
  5135. ExchangeLog.LogStart("DeleteActiveSyncPolicy");
  5136. Command cmd = new Command("Remove-ActiveSyncMailboxPolicy");
  5137. cmd.Parameters.Add("Identity", id);
  5138. cmd.Parameters.Add("Confirm", false);
  5139. ExecuteShellCommand(runSpace, cmd);
  5140. ExchangeLog.LogEnd("DeleteActiveSyncPolicy");
  5141. }
  5142. private ExchangeActiveSyncPolicy GetActiveSyncPolicyInternal(string id)
  5143. {
  5144. ExchangeLog.LogStart("GetActiveSyncPolicyInternal");
  5145. ExchangeLog.DebugInfo("Id: {0}", id);
  5146. ExchangeActiveSyncPolicy info = null;
  5147. Runspace runSpace = null;
  5148. try
  5149. {
  5150. runSpace = OpenRunspace();
  5151. Command cmd = new Command("Get-ActiveSyncMailboxPolicy");
  5152. cmd.Parameters.Add("Identity", id);
  5153. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  5154. if (result != null && result.Count > 0)
  5155. {
  5156. PSObject policy = result[0];
  5157. info = new ExchangeActiveSyncPolicy();
  5158. info.AllowNonProvisionableDevices = (bool)GetPSObjectProperty(policy, "AllowNonProvisionableDevices");
  5159. info.AttachmentsEnabled = (bool)GetPSObjectProperty(policy, "AttachmentsEnabled");
  5160. info.MaxAttachmentSizeKB =
  5161. ConvertUnlimitedToKB((Unlimited<ByteQuantifiedSize>)GetPSObjectProperty(policy, "MaxAttachmentSize"));
  5162. info.UNCAccessEnabled = (bool)GetPSObjectProperty(policy, "UNCAccessEnabled");
  5163. info.WSSAccessEnabled = (bool)GetPSObjectProperty(policy, "WSSAccessEnabled");
  5164. info.DevicePasswordEnabled = (bool)GetPSObjectProperty(policy, "DevicePasswordEnabled");
  5165. info.AlphanumericPasswordRequired = (bool)GetPSObjectProperty(policy, "AlphanumericDevicePasswordRequired");
  5166. info.PasswordRecoveryEnabled = (bool)GetPSObjectProperty(policy, "PasswordRecoveryEnabled");
  5167. info.DeviceEncryptionEnabled = (bool)GetPSObjectProperty(policy, "DeviceEncryptionEnabled");
  5168. info.AllowSimplePassword = (bool)GetPSObjectProperty(policy, "AllowSimpleDevicePassword");
  5169. info.MaxPasswordFailedAttempts =
  5170. ConvertUnlimitedToInt32((Unlimited<int>)GetPSObjectProperty(policy, "MaxDevicePasswordFailedAttempts"));
  5171. int? passwordLength = (int?)GetPSObjectProperty(policy, "MinDevicePasswordLength");
  5172. info.MinPasswordLength = ConvertNullableToInt32(passwordLength);
  5173. info.InactivityLockMin = ConvertUnlimitedToMinutes((Unlimited<EnhancedTimeSpan>)GetPSObjectProperty(policy, "MaxInactivityTimeDeviceLock"));
  5174. info.PasswordExpirationDays = ConvertUnlimitedTimeSpanToDays((Unlimited<EnhancedTimeSpan>)GetPSObjectProperty(policy, "DevicePasswordExpiration"));
  5175. info.PasswordHistory = (int)GetPSObjectProperty(policy, "DevicePasswordHistory");
  5176. info.RefreshInterval = ConvertUnlimitedToHours((Unlimited<EnhancedTimeSpan>)GetPSObjectProperty(policy, "DevicePolicyRefreshInterval"));
  5177. }
  5178. }
  5179. finally
  5180. {
  5181. CloseRunspace(runSpace);
  5182. }
  5183. ExchangeLog.LogEnd("GetActiveSyncPolicyInternal");
  5184. return info;
  5185. }
  5186. private void SetActiveSyncPolicyInternal(
  5187. string id,
  5188. bool allowNonProvisionableDevices,
  5189. bool attachmentsEnabled,
  5190. int maxAttachmentSizeKB,
  5191. bool uncAccessEnabled,
  5192. bool wssAccessEnabled,
  5193. bool devicePasswordEnabled,
  5194. bool alphanumericPasswordRequired,
  5195. bool passwordRecoveryEnabled,
  5196. bool deviceEncryptionEnabled,
  5197. bool allowSimplePassword,
  5198. int maxPasswordFailedAttempts,
  5199. int minPasswordLength,
  5200. int inactivityLockMin,
  5201. int passwordExpirationDays,
  5202. int passwordHistory,
  5203. int refreshInterval)
  5204. {
  5205. ExchangeLog.LogStart("SetActiveSyncPolicyInternal");
  5206. ExchangeLog.DebugInfo("Id: {0}", id);
  5207. Runspace runSpace = null;
  5208. try
  5209. {
  5210. runSpace = OpenRunspace();
  5211. Command cmd = new Command("Set-ActiveSyncMailboxPolicy");
  5212. cmd.Parameters.Add("Identity", id);
  5213. cmd.Parameters.Add("AllowNonProvisionableDevices", allowNonProvisionableDevices);
  5214. cmd.Parameters.Add("AttachmentsEnabled", attachmentsEnabled);
  5215. cmd.Parameters.Add("MaxAttachmentSize", ConvertKBToUnlimited(maxAttachmentSizeKB));
  5216. cmd.Parameters.Add("UNCAccessEnabled", uncAccessEnabled);
  5217. cmd.Parameters.Add("WSSAccessEnabled", wssAccessEnabled);
  5218. cmd.Parameters.Add("DevicePasswordEnabled", devicePasswordEnabled);
  5219. cmd.Parameters.Add("AlphanumericDevicePasswordRequired", alphanumericPasswordRequired);
  5220. cmd.Parameters.Add("PasswordRecoveryEnabled", passwordRecoveryEnabled);
  5221. cmd.Parameters.Add("DeviceEncryptionEnabled", deviceEncryptionEnabled);
  5222. cmd.Parameters.Add("AllowSimpleDevicePassword", allowSimplePassword);
  5223. Unlimited<int> attempts = ConvertInt32ToUnlimited(maxPasswordFailedAttempts);
  5224. cmd.Parameters.Add("MaxDevicePasswordFailedAttempts", attempts);
  5225. int? passwordLength = ConvertInt32ToNullable(minPasswordLength);
  5226. cmd.Parameters.Add("MinDevicePasswordLength", passwordLength);
  5227. Unlimited<EnhancedTimeSpan> inactivityLock = ConvertMinutesToUnlimitedTimeSpan(inactivityLockMin);
  5228. cmd.Parameters.Add("MaxInactivityTimeDeviceLock", inactivityLock);
  5229. Unlimited<EnhancedTimeSpan> passwordExpiration = ConvertDaysToUnlimitedTimeSpan(passwordExpirationDays);
  5230. cmd.Parameters.Add("DevicePasswordExpiration", passwordExpiration);
  5231. cmd.Parameters.Add("DevicePasswordHistory", passwordHistory);
  5232. Unlimited<EnhancedTimeSpan> refInter = ConvertHoursToUnlimitedTimeSpan(refreshInterval);
  5233. cmd.Parameters.Add("DevicePolicyRefreshInterval", refInter);
  5234. ExecuteShellCommand(runSpace, cmd);
  5235. }
  5236. finally
  5237. {
  5238. CloseRunspace(runSpace);
  5239. }
  5240. ExchangeLog.LogEnd("SetActiveSyncPolicyInternal");
  5241. }
  5242. #endregion
  5243. #region Mobile devices
  5244. private ExchangeMobileDevice[] GetMobileDevicesInternal(string accountName)
  5245. {
  5246. ExchangeLog.LogStart("GetMobileDevicesInternal");
  5247. ExchangeLog.DebugInfo("Account name: {0}", accountName);
  5248. List<ExchangeMobileDevice> devices = new List<ExchangeMobileDevice>();
  5249. ExchangeMobileDevice device = null;
  5250. Runspace runSpace = null;
  5251. try
  5252. {
  5253. runSpace = OpenRunspace();
  5254. Command cmd = new Command("Get-ActiveSyncDeviceStatistics");
  5255. cmd.Parameters.Add("Mailbox", accountName);
  5256. Collection<PSObject> result = null;
  5257. try
  5258. {
  5259. result = ExecuteShellCommand(runSpace, cmd);
  5260. }
  5261. catch (Exception)
  5262. {
  5263. }
  5264. if (result != null)
  5265. {
  5266. foreach (PSObject obj in result)
  5267. {
  5268. device = GetMobileDeviceObject(obj);
  5269. devices.Add(device);
  5270. }
  5271. }
  5272. }
  5273. finally
  5274. {
  5275. CloseRunspace(runSpace);
  5276. }
  5277. ExchangeLog.LogEnd("GetMobileDevicesInternal");
  5278. return devices.ToArray();
  5279. }
  5280. private ExchangeMobileDevice GetMobileDeviceObject(PSObject obj)
  5281. {
  5282. ExchangeMobileDevice device = new ExchangeMobileDevice();
  5283. device.Id = GetPSObjectIdentity(obj);
  5284. device.FirstSyncTime = ConvertNullableToDateTime((DateTime?)GetPSObjectProperty(obj, "FirstSyncTime"));
  5285. device.LastPolicyUpdateTime = ConvertNullableToDateTime((DateTime?)GetPSObjectProperty(obj, "LastPolicyUpdateTime"));
  5286. device.LastSyncAttemptTime = ConvertNullableToDateTime((DateTime?)GetPSObjectProperty(obj, "LastSyncAttemptTime"));
  5287. device.LastSuccessSync = ConvertNullableToDateTime((DateTime?)GetPSObjectProperty(obj, "LastSuccessSync"));
  5288. device.DeviceType = (string)GetPSObjectProperty(obj, "DeviceType");
  5289. device.DeviceID = (string)GetPSObjectProperty(obj, "DeviceID");
  5290. device.DeviceUserAgent = (string)GetPSObjectProperty(obj, "DeviceUserAgent");
  5291. DateTime? wipeSentTime = (DateTime?)GetPSObjectProperty(obj, "DeviceWipeSentTime");
  5292. device.DeviceWipeSentTime = ConvertNullableToDateTime(wipeSentTime);
  5293. DateTime? wipeRequestTime = (DateTime?)GetPSObjectProperty(obj, "DeviceWipeRequestTime");
  5294. device.DeviceWipeRequestTime = ConvertNullableToDateTime(wipeRequestTime);
  5295. DateTime? wipeAckTime = (DateTime?)GetPSObjectProperty(obj, "DeviceWipeAckTime");
  5296. device.DeviceWipeAckTime = ConvertNullableToDateTime(wipeAckTime);
  5297. device.LastPingHeartbeat = ConvertNullableToInt32((UInt32?)GetPSObjectProperty(obj, "LastPingHeartbeat"));
  5298. device.RecoveryPassword = (string)GetPSObjectProperty(obj, "RecoveryPassword");
  5299. device.DeviceModel = (string)GetPSObjectProperty(obj, "DeviceModel");
  5300. device.DeviceIMEI = (string)GetPSObjectProperty(obj, "DeviceIMEI");
  5301. device.DeviceFriendlyName = (string)GetPSObjectProperty(obj, "DeviceFriendlyName");
  5302. device.DeviceOS = (string)GetPSObjectProperty(obj, "DeviceOS");
  5303. device.DeviceOSLanguage = (string)GetPSObjectProperty(obj, "DeviceOSLanguage");
  5304. device.DevicePhoneNumber = (string)GetPSObjectProperty(obj, "DevicePhoneNumber");
  5305. //status
  5306. if (wipeAckTime.HasValue)
  5307. {
  5308. //green
  5309. device.Status = MobileDeviceStatus.WipeSuccessful;
  5310. }
  5311. else
  5312. {
  5313. if (wipeRequestTime.HasValue || wipeSentTime.HasValue)
  5314. {
  5315. //red
  5316. device.Status = MobileDeviceStatus.PendingWipe;
  5317. }
  5318. else
  5319. {
  5320. //black
  5321. device.Status = MobileDeviceStatus.OK;
  5322. }
  5323. }
  5324. return device;
  5325. }
  5326. private ExchangeMobileDevice GetMobileDeviceInternal(string id)
  5327. {
  5328. ExchangeLog.LogStart("GetMobileDeviceInternal");
  5329. ExchangeMobileDevice device = null;
  5330. Runspace runSpace = null;
  5331. try
  5332. {
  5333. runSpace = OpenRunspace();
  5334. Command cmd = new Command("Get-ActiveSyncDeviceStatistics");
  5335. cmd.Parameters.Add("Identity", id);
  5336. cmd.Parameters.Add("ShowRecoveryPassword", true);
  5337. Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
  5338. if (result != null && result.Count > 0)
  5339. {
  5340. device = GetMobileDeviceObject(result[0]);
  5341. }
  5342. }
  5343. finally
  5344. {
  5345. CloseRunspace(runSpace);
  5346. }
  5347. ExchangeLog.LogEnd("GetMobileDeviceInternal");
  5348. return device;
  5349. }
  5350. private void WipeDataFromDeviceInternal(string id)
  5351. {
  5352. ExchangeLog.LogStart("WipeDataFromDeviceInternal");
  5353. Runspace runSpace = null;
  5354. try
  5355. {
  5356. runSpace = OpenRunspace();
  5357. Command cmd = new Command("Clear-ActiveSyncDevice");
  5358. cmd.Parameters.Add("Identity", id);
  5359. cmd.Parameters.Add("Confirm", false);
  5360. ExecuteShellCommand(runSpace, cmd);
  5361. }
  5362. finally
  5363. {
  5364. CloseRunspace(runSpace);
  5365. }
  5366. ExchangeLog.LogEnd("WipeDataFromDeviceInternal");
  5367. }
  5368. private void CancelRemoteWipeRequestInternal(string id)
  5369. {
  5370. ExchangeLog.LogStart("CancelRemoteWipeRequestInternal");
  5371. Runspace runSpace = null;
  5372. try
  5373. {
  5374. runSpace = OpenRunspace();
  5375. Command cmd = new Command("Clear-ActiveSyncDevice");
  5376. cmd.Parameters.Add("Identity", id);
  5377. cmd.Parameters.Add("Cancel", true);
  5378. cmd.Parameters.Add("Confirm", false);
  5379. ExecuteShellCommand(runSpace, cmd);
  5380. }
  5381. finally
  5382. {
  5383. CloseRunspace(runSpace);
  5384. }
  5385. ExchangeLog.LogEnd("CancelRemoteWipeRequestInternal");
  5386. }
  5387. internal void RemoveDevicesInternal(Runspace runSpace, string accountName)
  5388. {
  5389. ExchangeLog.LogStart("RemoveDevicesInternal");
  5390. ExchangeLog.DebugInfo("Account name: {0}", accountName);
  5391. try
  5392. {
  5393. runSpace = OpenRunspace();
  5394. Command cmd = new Command("Get-ActiveSyncDeviceStatistics");
  5395. cmd.Parameters.Add("Mailbox", accountName);
  5396. Collection<PSObject> result = null;
  5397. try
  5398. {
  5399. result = ExecuteShellCommand(runSpace, cmd);
  5400. }
  5401. catch (Exception)
  5402. {
  5403. }
  5404. if (result != null)
  5405. {
  5406. foreach (PSObject obj in result)
  5407. {
  5408. ExchangeMobileDevice device = GetMobileDeviceObject(obj);
  5409. cmd = new Command("Remove-ActiveSyncDevice");
  5410. cmd.Parameters.Add("Identity", device.DeviceID);
  5411. cmd.Parameters.Add("Confirm", false);
  5412. ExecuteShellCommand(runSpace, cmd);
  5413. }
  5414. }
  5415. }
  5416. finally
  5417. {
  5418. }
  5419. ExchangeLog.LogEnd("RemoveDevicesInternal");
  5420. }
  5421. private void RemoveDeviceInternal(string id)
  5422. {
  5423. ExchangeLog.LogStart("RemoveDeviceInternal");
  5424. Runspace runSpace = null;
  5425. try
  5426. {
  5427. runSpace = OpenRunspace();
  5428. Command cmd = new Command("Remove-ActiveSyncDevice");
  5429. cmd.Parameters.Add("Identity", id);
  5430. cmd.Parameters.Add("Confirm", false);
  5431. ExecuteShellCommand(runSpace, cmd);
  5432. }
  5433. finally
  5434. {
  5435. CloseRunspace(runSpace);
  5436. }
  5437. ExchangeLog.LogEnd("RemoveDeviceInternal");
  5438. }
  5439. #endregion
  5440. #region Convert Utils
  5441. internal int ConvertUnlimitedToInt32(Unlimited<int> value)
  5442. {
  5443. int ret = 0;
  5444. if (value.IsUnlimited)
  5445. {
  5446. ret = -1;
  5447. }
  5448. else
  5449. {
  5450. ret = value.Value;
  5451. }
  5452. return ret;
  5453. }
  5454. internal Unlimited<int> ConvertInt32ToUnlimited(int value)
  5455. {
  5456. if (value == -1)
  5457. return Unlimited<int>.UnlimitedValue;
  5458. else
  5459. {
  5460. Unlimited<int> ret = new Unlimited<int>();
  5461. ret.Value = value;
  5462. return ret;
  5463. }
  5464. }
  5465. internal long ConvertUnlimitedToBytes(Unlimited<ByteQuantifiedSize> value)
  5466. {
  5467. long ret = 0;
  5468. if (value.IsUnlimited)
  5469. {
  5470. ret = -1;
  5471. }
  5472. else
  5473. {
  5474. ret = Convert.ToInt64(value.Value.ToBytes());
  5475. }
  5476. return ret;
  5477. }
  5478. internal int ConvertUnlimitedToKB(Unlimited<ByteQuantifiedSize> value)
  5479. {
  5480. int ret = 0;
  5481. if (value.IsUnlimited)
  5482. {
  5483. ret = -1;
  5484. }
  5485. else
  5486. {
  5487. ret = Convert.ToInt32(value.Value.ToKB());
  5488. }
  5489. return ret;
  5490. }
  5491. internal int ConvertUnlimitedToMB(Unlimited<ByteQuantifiedSize> value)
  5492. {
  5493. int ret = 0;
  5494. if (value.IsUnlimited)
  5495. {
  5496. ret = -1;
  5497. }
  5498. else
  5499. {
  5500. ret = Convert.ToInt32(value.Value.ToMB());
  5501. }
  5502. return ret;
  5503. }
  5504. internal int ConvertUnlimitedToHours(Unlimited<EnhancedTimeSpan> value)
  5505. {
  5506. int ret = 0;
  5507. if (value.IsUnlimited)
  5508. {
  5509. ret = -1;
  5510. }
  5511. else
  5512. {
  5513. ret = Convert.ToInt32(value.Value.TotalHours);
  5514. }
  5515. return ret;
  5516. }
  5517. internal int ConvertUnlimitedToMinutes(Unlimited<EnhancedTimeSpan> value)
  5518. {
  5519. int ret = 0;
  5520. if (value.IsUnlimited)
  5521. {
  5522. ret = -1;
  5523. }
  5524. else
  5525. {
  5526. ret = Convert.ToInt32(value.Value.TotalMinutes);
  5527. }
  5528. return ret;
  5529. }
  5530. internal Unlimited<EnhancedTimeSpan> ConvertHoursToUnlimitedTimeSpan(int value)
  5531. {
  5532. if (value == -1)
  5533. return Unlimited<EnhancedTimeSpan>.UnlimitedValue;
  5534. else
  5535. {
  5536. Unlimited<EnhancedTimeSpan> ret = new Unlimited<EnhancedTimeSpan>();
  5537. ret.Value = EnhancedTimeSpan.FromHours(Convert.ToDouble(value));
  5538. return ret;
  5539. }
  5540. }
  5541. internal Unlimited<EnhancedTimeSpan> ConvertMinutesToUnlimitedTimeSpan(int value)
  5542. {
  5543. if (value == -1)
  5544. return Unlimited<EnhancedTimeSpan>.UnlimitedValue;
  5545. else
  5546. {
  5547. Unlimited<EnhancedTimeSpan> ret = new Unlimited<EnhancedTimeSpan>();
  5548. ret.Value = EnhancedTimeSpan.FromMinutes(Convert.ToDouble(value));
  5549. return ret;
  5550. }
  5551. }
  5552. internal Unlimited<EnhancedTimeSpan> ConvertDaysToUnlimitedTimeSpan(int value)
  5553. {
  5554. if (value == -1)
  5555. return Unlimited<EnhancedTimeSpan>.UnlimitedValue;
  5556. else
  5557. {
  5558. Unlimited<EnhancedTimeSpan> ret = new Unlimited<EnhancedTimeSpan>();
  5559. ret.Value = EnhancedTimeSpan.FromDays(Convert.ToDouble(value));
  5560. return ret;
  5561. }
  5562. }
  5563. internal int ConvertUnlimitedTimeSpanToDays(Unlimited<EnhancedTimeSpan> value)
  5564. {
  5565. int ret = 0;
  5566. if (value.IsUnlimited)
  5567. {
  5568. ret = -1;
  5569. }
  5570. else
  5571. {
  5572. ret = value.Value.Days;
  5573. }
  5574. return ret;
  5575. }
  5576. internal int ConvertNullableToInt32<T>(Nullable<T> value) where T : struct
  5577. {
  5578. int ret = 0;
  5579. if (value.HasValue)
  5580. {
  5581. ret = Convert.ToInt32(value.Value);
  5582. }
  5583. return ret;
  5584. }
  5585. internal int? ConvertInt32ToNullable(int value)
  5586. {
  5587. int? ret = null;
  5588. if (value != 0)
  5589. {
  5590. ret = new int?(value);
  5591. }
  5592. return ret;
  5593. }
  5594. internal DateTime ConvertNullableToDateTime(DateTime? value)
  5595. {
  5596. DateTime ret = DateTime.MinValue;
  5597. if (value.HasValue)
  5598. {
  5599. ret = value.Value;
  5600. }
  5601. return ret;
  5602. }
  5603. internal bool ConvertNullableToBoolean(bool? value)
  5604. {
  5605. bool ret = false;
  5606. if (value.HasValue)
  5607. {
  5608. ret = value.Value;
  5609. }
  5610. return ret;
  5611. }
  5612. internal int ConvertEnhancedTimeSpanToDays(EnhancedTimeSpan value)
  5613. {
  5614. return value.Days;
  5615. }
  5616. internal EnhancedTimeSpan ConvertDaysToEnhancedTimeSpan(int days)
  5617. {
  5618. return EnhancedTimeSpan.FromDays(Convert.ToDouble(days));
  5619. }
  5620. internal Unlimited<ByteQuantifiedSize> ConvertKBToUnlimited(int kb)
  5621. {
  5622. if (kb == -1)
  5623. return Unlimited<ByteQuantifiedSize>.UnlimitedValue;
  5624. else
  5625. {
  5626. Unlimited<ByteQuantifiedSize> ret = new Unlimited<ByteQuantifiedSize>();
  5627. ret.Value = ByteQuantifiedSize.FromKB(Convert.ToUInt64(kb));
  5628. return ret;
  5629. }
  5630. }
  5631. internal Unlimited<ByteQuantifiedSize> ConvertKBToUnlimited(long kb)
  5632. {
  5633. if (kb == -1)
  5634. return Unlimited<ByteQuantifiedSize>.UnlimitedValue;
  5635. else
  5636. {
  5637. Unlimited<ByteQuantifiedSize> ret = new Unlimited<ByteQuantifiedSize>();
  5638. ret.Value = ByteQuantifiedSize.FromKB(Convert.ToUInt64(kb));
  5639. return ret;
  5640. }
  5641. }
  5642. internal string ProxyAddressToString(ProxyAddress proxyAddress)
  5643. {
  5644. string ret = null;
  5645. if (proxyAddress != null)
  5646. ret = proxyAddress.AddressString;
  5647. return ret;
  5648. }
  5649. internal string SmtpAddressToString(SmtpAddress smtpAddress)
  5650. {
  5651. string ret = null;
  5652. if (smtpAddress != null)
  5653. ret = smtpAddress.ToString();
  5654. return ret;
  5655. }
  5656. internal string CountryInfoToString(CountryInfo countryInfo)
  5657. {
  5658. string ret = null;
  5659. if (countryInfo != null)
  5660. ret = countryInfo.Name;
  5661. return ret;
  5662. }
  5663. internal CountryInfo ParseCountryInfo(string country)
  5664. {
  5665. CountryInfo ret = null;
  5666. if (!string.IsNullOrEmpty(country))
  5667. {
  5668. ret = CountryInfo.Parse(country);
  5669. }
  5670. return ret;
  5671. }
  5672. internal string ObjToString(object obj)
  5673. {
  5674. string ret = null;
  5675. if (obj != null)
  5676. ret = obj.ToString();
  5677. return ret;
  5678. }
  5679. #endregion
  5680. #region Utils
  5681. private object GetObjectPropertyValue(object obj, string property)
  5682. {
  5683. PropertyInfo pinfo = obj.GetType().GetProperty(property);
  5684. return pinfo.GetValue(obj, null);
  5685. }
  5686. private object GetObjectIndexerValue(object obj, object index)
  5687. {
  5688. Type t = obj.GetType();
  5689. object ret = t.InvokeMember("Item", BindingFlags.GetProperty, null, obj, new object[] { index });
  5690. return ret;
  5691. }
  5692. internal string GetServerName()
  5693. {
  5694. string ret = null;
  5695. if (!string.IsNullOrEmpty(MailboxCluster))
  5696. ret = MailboxCluster;
  5697. else
  5698. ret = System.Environment.MachineName;
  5699. return ret;
  5700. }
  5701. public override bool IsInstalled()
  5702. {
  5703. int value = 0;
  5704. RegistryKey root = Registry.LocalMachine;
  5705. RegistryKey rk = root.OpenSubKey(ExchangeRegistryPath);
  5706. if (rk != null)
  5707. {
  5708. value = (int)rk.GetValue("MsiProductMajor", null);
  5709. rk.Close();
  5710. }
  5711. return value == 8;
  5712. }
  5713. public Version GetExchangeVersion()
  5714. {
  5715. int major = 0;
  5716. int minor = 0;
  5717. RegistryKey root = Registry.LocalMachine;
  5718. RegistryKey rk = root.OpenSubKey(ExchangeRegistryPath);
  5719. if (rk != null)
  5720. {
  5721. major = (int)rk.GetValue("MsiProductMajor", 0);
  5722. minor = (int)rk.GetValue("MsiProductMinor", 0);
  5723. rk.Close();
  5724. }
  5725. return new Version(major, minor);
  5726. }
  5727. #endregion
  5728. #region Transactions
  5729. internal ExchangeTransaction StartTransaction()
  5730. {
  5731. return new ExchangeTransaction();
  5732. }
  5733. internal void RollbackTransaction(ExchangeTransaction transaction)
  5734. {
  5735. ExchangeLog.LogStart("RollbackTransaction");
  5736. Runspace runSpace = null;
  5737. try
  5738. {
  5739. runSpace = OpenRunspace();
  5740. for (int i = transaction.Actions.Count - 1; i > -1; i--)
  5741. {
  5742. //reverse order
  5743. try
  5744. {
  5745. RollbackAction(transaction.Actions[i], runSpace);
  5746. }
  5747. catch (Exception ex)
  5748. {
  5749. ExchangeLog.LogError("Rollback error", ex);
  5750. }
  5751. }
  5752. }
  5753. catch (Exception ex)
  5754. {
  5755. ExchangeLog.LogError("Rollback error", ex);
  5756. }
  5757. finally
  5758. {
  5759. CloseRunspace(runSpace);
  5760. }
  5761. ExchangeLog.LogEnd("RollbackTransaction");
  5762. }
  5763. private void RollbackAction(TransactionAction action, Runspace runspace)
  5764. {
  5765. ExchangeLog.LogInfo("Rollback action: {0}", action.ActionType);
  5766. switch (action.ActionType)
  5767. {
  5768. case TransactionAction.TransactionActionTypes.CreateOrganizationUnit:
  5769. DeleteADObject(action.Id);
  5770. break;
  5771. case TransactionAction.TransactionActionTypes.CreateDistributionGroup:
  5772. RemoveDistributionGroup(runspace, action.Id);
  5773. break;
  5774. case TransactionAction.TransactionActionTypes.EnableDistributionGroup:
  5775. DisableMailSecurityDistributionGroup(runspace, action.Id);
  5776. break;
  5777. case TransactionAction.TransactionActionTypes.CreateGlobalAddressList:
  5778. DeleteGlobalAddressList(runspace, action.Id);
  5779. break;
  5780. case TransactionAction.TransactionActionTypes.CreateAddressList:
  5781. DeleteAddressList(runspace, action.Id);
  5782. break;
  5783. case TransactionAction.TransactionActionTypes.CreateAddressBookPolicy:
  5784. DeleteAddressBookPolicy(runspace, action.Id);
  5785. break;
  5786. case TransactionAction.TransactionActionTypes.CreateOfflineAddressBook:
  5787. DeleteOfflineAddressBook(runspace, action.Id);
  5788. break;
  5789. case TransactionAction.TransactionActionTypes.CreateActiveSyncPolicy:
  5790. DeleteActiveSyncPolicy(runspace, action.Id);
  5791. break;
  5792. case TransactionAction.TransactionActionTypes.CreateAcceptedDomain:
  5793. RemoveAcceptedDomain(runspace, action.Id);
  5794. break;
  5795. case TransactionAction.TransactionActionTypes.AddUPNSuffix:
  5796. RemoveUPNSuffix(action.Id, action.Suffix);
  5797. break;
  5798. case TransactionAction.TransactionActionTypes.CreateMailbox:
  5799. RemoveMailbox(runspace, action.Id);
  5800. break;
  5801. case TransactionAction.TransactionActionTypes.EnableMailbox:
  5802. DisableMailbox(runspace, action.Id);
  5803. break;
  5804. case TransactionAction.TransactionActionTypes.CreateContact:
  5805. RemoveContact(runspace, action.Id);
  5806. break;
  5807. case TransactionAction.TransactionActionTypes.CreatePublicFolder:
  5808. RemovePublicFolder(runspace, action.Id);
  5809. break;
  5810. case TransactionAction.TransactionActionTypes.AddMailboxFullAccessPermission:
  5811. RemoveMailboxAccessPermission(runspace, action.Account, action.Id, "FullAccess");
  5812. break;
  5813. case TransactionAction.TransactionActionTypes.AddSendAsPermission:
  5814. RemoveADPermission(runspace, action.Account, action.Id, null, "Send-as", null);
  5815. break;
  5816. case TransactionAction.TransactionActionTypes.RemoveMailboxFullAccessPermission:
  5817. SetMailboxPermission(runspace, action.Account, action.Id, "FullAccess");
  5818. break;
  5819. case TransactionAction.TransactionActionTypes.RemoveSendAsPermission:
  5820. SetExtendedRights(runspace, action.Account, action.Id, "Send-as");
  5821. break;
  5822. }
  5823. }
  5824. #endregion
  5825. #region Disclaimers
  5826. private const string disclamerMemberPostfix = "_members";
  5827. public int SetDisclaimer(string name, string text)
  5828. {
  5829. ExchangeLog.LogStart("SetDisclaimer");
  5830. Runspace runSpace = null;
  5831. try
  5832. {
  5833. runSpace = OpenRunspace();
  5834. Command cmd;
  5835. bool distributionGroupExist = false;
  5836. bool transportRuleExist = false;
  5837. cmd = new Command("Get-DistributionGroup");
  5838. cmd.Parameters.Add("Identity", name + disclamerMemberPostfix);
  5839. Collection<PSObject> res = ExecuteShellCommand(runSpace, cmd);
  5840. distributionGroupExist = (res.Count > 0);
  5841. cmd = new Command("Get-TransportRule");
  5842. cmd.Parameters.Add("Identity", name);
  5843. res = ExecuteShellCommand(runSpace, cmd);
  5844. transportRuleExist = (res.Count > 0);
  5845. if (!distributionGroupExist)
  5846. {
  5847. cmd = new Command("New-DistributionGroup");
  5848. cmd.Parameters.Add("Name", name + disclamerMemberPostfix);
  5849. ExecuteShellCommand(runSpace, cmd);
  5850. }
  5851. if (transportRuleExist)
  5852. {
  5853. cmd = new Command("Set-TransportRule");
  5854. cmd.Parameters.Add("Identity", name);
  5855. }
  5856. else
  5857. {
  5858. cmd = new Command("New-TransportRule");
  5859. cmd.Parameters.Add("Name", name);
  5860. }
  5861. cmd.Parameters.Add("FromMemberOf", name + disclamerMemberPostfix);
  5862. cmd.Parameters.Add("Enabled", true);
  5863. cmd.Parameters.Add("ApplyHtmlDisclaimerLocation", "Append");
  5864. cmd.Parameters.Add("ApplyHtmlDisclaimerText", text);
  5865. cmd.Parameters.Add("ApplyHtmlDisclaimerFallbackAction", "Wrap");
  5866. ExecuteShellCommand(runSpace, cmd);
  5867. }
  5868. catch (Exception exc)
  5869. {
  5870. ExchangeLog.LogError(exc);
  5871. return -1;
  5872. }
  5873. finally
  5874. {
  5875. CloseRunspace(runSpace);
  5876. }
  5877. ExchangeLog.LogEnd("SetDisclaimer");
  5878. return 0;
  5879. }
  5880. public int RemoveDisclaimer(string name)
  5881. {
  5882. ExchangeLog.LogStart("RemoveDisclaimer");
  5883. Runspace runSpace = null;
  5884. try
  5885. {
  5886. runSpace = OpenRunspace();
  5887. Command cmd = new Command("Get-DistributionGroupMember");
  5888. cmd.Parameters.Add("Identity", name + disclamerMemberPostfix);
  5889. Collection<PSObject> res = ExecuteShellCommand(runSpace, cmd);
  5890. if (res.Count > 0)
  5891. return -1;
  5892. cmd = new Command("Remove-TransportRule");
  5893. cmd.Parameters.Add("Identity", name);
  5894. cmd.Parameters.Add("Confirm", new SwitchParameter(false));
  5895. ExecuteShellCommand(runSpace, cmd);
  5896. cmd = new Command("Remove-DistributionGroup");
  5897. cmd.Parameters.Add("Identity", name + disclamerMemberPostfix);
  5898. cmd.Parameters.Add("Confirm", new SwitchParameter(false));
  5899. ExecuteShellCommand(runSpace, cmd);
  5900. }
  5901. catch (Exception exc)
  5902. {
  5903. ExchangeLog.LogError(exc);
  5904. return -1;
  5905. }
  5906. finally
  5907. {
  5908. CloseRunspace(runSpace);
  5909. }
  5910. ExchangeLog.LogEnd("RemoveDisclaimer");
  5911. return 0;
  5912. }
  5913. public int AddDisclamerMember(string name, string member)
  5914. {
  5915. ExchangeLog.LogStart("SetDisclamerMember");
  5916. Runspace runSpace = null;
  5917. try
  5918. {
  5919. runSpace = OpenRunspace();
  5920. Command cmd = new Command("Add-DistributionGroupMember");
  5921. cmd.Parameters.Add("Identity", name + disclamerMemberPostfix);
  5922. cmd.Parameters.Add("Member", member);
  5923. ExecuteShellCommand(runSpace, cmd);
  5924. }
  5925. catch (Exception exc)
  5926. {
  5927. ExchangeLog.LogError(exc);
  5928. return -1;
  5929. }
  5930. finally
  5931. {
  5932. CloseRunspace(runSpace);
  5933. }
  5934. ExchangeLog.LogEnd("SetDisclamerMember");
  5935. return 0;
  5936. }
  5937. public int RemoveDisclamerMember(string name, string member)
  5938. {
  5939. ExchangeLog.LogStart("RemoveDisclamerMember");
  5940. Runspace runSpace = null;
  5941. try
  5942. {
  5943. runSpace = OpenRunspace();
  5944. Command cmd = new Command("Remove-DistributionGroupMember");
  5945. cmd.Parameters.Add("Identity", name + disclamerMemberPostfix);
  5946. cmd.Parameters.Add("Member", member);
  5947. ExecuteShellCommand(runSpace, cmd);
  5948. }
  5949. catch (Exception exc)
  5950. {
  5951. ExchangeLog.LogError(exc);
  5952. return -1;
  5953. }
  5954. finally
  5955. {
  5956. CloseRunspace(runSpace);
  5957. }
  5958. ExchangeLog.LogEnd("RemoveDisclamerMember");
  5959. return 0;
  5960. }
  5961. #endregion
  5962. #region Archiving
  5963. public virtual ResultObject ExportMailBox(string organizationId, string accountName, string storagePath)
  5964. {
  5965. // not implemented
  5966. return null;
  5967. }
  5968. public virtual ResultObject SetMailBoxArchiving(string organizationId, string accountName, bool archive, long archiveQuotaKB, long archiveWarningQuotaKB, string RetentionPolicy)
  5969. {
  5970. // not implemented
  5971. return null;
  5972. }
  5973. #endregion
  5974. #region Retention policy
  5975. public virtual ResultObject SetRetentionPolicyTag(string Identity, ExchangeRetentionPolicyTagType Type, int AgeLimitForRetention, ExchangeRetentionPolicyTagAction RetentionAction)
  5976. {
  5977. // not implemented
  5978. return null;
  5979. }
  5980. public virtual ResultObject RemoveRetentionPolicyTag(string Identity)
  5981. {
  5982. // not implemented
  5983. return null;
  5984. }
  5985. public virtual ResultObject SetRetentionPolicy(string Identity, string[] RetentionPolicyTagLinks)
  5986. {
  5987. // not implemented
  5988. return null;
  5989. }
  5990. public virtual ResultObject RemoveRetentionPolicy(string Identity)
  5991. {
  5992. // not implemented
  5993. return null;
  5994. }
  5995. #endregion
  5996. #region Picture
  5997. public virtual ResultObject SetPicture(string accountName, byte[] picture)
  5998. {
  5999. // not implemented
  6000. return null;
  6001. }
  6002. public virtual BytesResult GetPicture(string accountName)
  6003. {
  6004. // not implemented
  6005. return null;
  6006. }
  6007. #endregion
  6008. }
  6009. }