diff --git a/WebsitePanel/Database/update_db.sql b/WebsitePanel/Database/update_db.sql index a35668b3..275630c2 100644 --- a/WebsitePanel/Database/update_db.sql +++ b/WebsitePanel/Database/update_db.sql @@ -12,1225 +12,19 @@ BEGIN END GO --- Windows Server 2012 - -IF NOT EXISTS (SELECT * FROM [dbo].[Providers] WHERE [DisplayName] = 'Windows Server 2012') +-- Version 2.1 section +IF NOT EXISTS (SELECT * FROM [dbo].[Providers] WHERE [DisplayName] = 'Hosted Microsoft Exchange Server 2013') BEGIN -INSERT [dbo].[Providers] ([ProviderID], [GroupID], [ProviderName], [DisplayName], [ProviderType], [EditorControl], [DisableAutoDiscovery]) VALUES (104, 1, N'Windows2012', N'Windows Server 2012', N'WebsitePanel.Providers.OS.Windows2012, WebsitePanel.Providers.OS.Windows2012', N'Windows2008', NULL) -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[ServiceDefaultProperties] WHERE [ProviderID] = 104 AND [PropertyName] = N'UsersHome') -BEGIN - INSERT [dbo].[ServiceDefaultProperties] ([ProviderID], [PropertyName], [PropertyValue]) VALUES (104, N'UsersHome', N'%SYSTEMDRIVE%\HostingSpaces') -END -GO - --- IIS 8.0 -IF NOT EXISTS (SELECT * FROM [dbo].[Providers] WHERE [DisplayName] = 'Internet Information Services 8.0') -BEGIN -INSERT [dbo].[Providers] ([ProviderID], [GroupID], [ProviderName], [DisplayName], [ProviderType], [EditorControl], [DisableAutoDiscovery]) VALUES (105, 2, N'IIS80', N'Internet Information Services 8.0', N'WebsitePanel.Providers.Web.IIs80, WebsitePanel.Providers.Web.IIs80', N'IIS70', NULL) -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[ServiceDefaultProperties] WHERE [ProviderID] = 105 AND [PropertyName] = N'AspNet11Pool') -BEGIN - INSERT [dbo].[ServiceDefaultProperties] ([ProviderID], [PropertyName], [PropertyValue]) VALUES (105, N'AspNet11Pool', N'ASP.NET 1.1') -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[ServiceDefaultProperties] WHERE [ProviderID] = 105 AND [PropertyName] = N'AspNet40Path') -BEGIN - INSERT [dbo].[ServiceDefaultProperties] ([ProviderID], [PropertyName], [PropertyValue]) VALUES (105, N'AspNet40Path', N'%WINDIR%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll') -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[ServiceDefaultProperties] WHERE [ProviderID] = 105 AND [PropertyName] = N'AspNet40x64Path') -BEGIN - INSERT [dbo].[ServiceDefaultProperties] ([ProviderID], [PropertyName], [PropertyValue]) VALUES (105, N'AspNet40x64Path', N'%WINDIR%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll') -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[ServiceDefaultProperties] WHERE [ProviderID] = 105 AND [PropertyName] = N'AspNetBitnessMode') -BEGIN - INSERT [dbo].[ServiceDefaultProperties] ([ProviderID], [PropertyName], [PropertyValue]) VALUES (105, N'AspNetBitnessMode', N'32') -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[ServiceDefaultProperties] WHERE [ProviderID] = 105 AND [PropertyName] = N'CFFlashRemotingDirectory') -BEGIN - INSERT [dbo].[ServiceDefaultProperties] ([ProviderID], [PropertyName], [PropertyValue]) VALUES (105, N'CFFlashRemotingDirectory', N'C:\ColdFusion9\runtime\lib\wsconfig\1') -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[ServiceDefaultProperties] WHERE [ProviderID] = 105 AND [PropertyName] = N'CFScriptsDirectory') -BEGIN - INSERT [dbo].[ServiceDefaultProperties] ([ProviderID], [PropertyName], [PropertyValue]) VALUES (105, N'CFScriptsDirectory', N'C:\Inetpub\wwwroot\CFIDE') -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[ServiceDefaultProperties] WHERE [ProviderID] = 105 AND [PropertyName] = N'ClassicAspNet20Pool') -BEGIN - INSERT [dbo].[ServiceDefaultProperties] ([ProviderID], [PropertyName], [PropertyValue]) VALUES (105, N'ClassicAspNet20Pool', N'ASP.NET 2.0 (Classic)') -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[ServiceDefaultProperties] WHERE [ProviderID] = 105 AND [PropertyName] = N'ClassicAspNet40Pool') -BEGIN - INSERT [dbo].[ServiceDefaultProperties] ([ProviderID], [PropertyName], [PropertyValue]) VALUES (105, N'ClassicAspNet40Pool', N'ASP.NET 4.0 (Classic)') -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[ServiceDefaultProperties] WHERE [ProviderID] = 105 AND [PropertyName] = N'ColdFusionPath') -BEGIN - INSERT [dbo].[ServiceDefaultProperties] ([ProviderID], [PropertyName], [PropertyValue]) VALUES (105, N'ColdFusionPath', N'C:\ColdFusion9\runtime\lib\wsconfig\jrun_iis6.dll') -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[ServiceDefaultProperties] WHERE [ProviderID] = 105 AND [PropertyName] = N'GalleryXmlFeedUrl') -BEGIN - INSERT [dbo].[ServiceDefaultProperties] ([ProviderID], [PropertyName], [PropertyValue]) VALUES (105, N'GalleryXmlFeedUrl', N'') -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[ServiceDefaultProperties] WHERE [ProviderID] = 105 AND [PropertyName] = N'IntegratedAspNet20Pool') -BEGIN - INSERT [dbo].[ServiceDefaultProperties] ([ProviderID], [PropertyName], [PropertyValue]) VALUES (105, N'IntegratedAspNet20Pool', N'ASP.NET 2.0 (Integrated)') -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[ServiceDefaultProperties] WHERE [ProviderID] = 105 AND [PropertyName] = N'IntegratedAspNet40Pool') -BEGIN - INSERT [dbo].[ServiceDefaultProperties] ([ProviderID], [PropertyName], [PropertyValue]) VALUES (105, N'IntegratedAspNet40Pool', N'ASP.NET 4.0 (Integrated)') -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[ServiceDefaultProperties] WHERE [ProviderID] = 105 AND [PropertyName] = N'PerlPath') -BEGIN - INSERT [dbo].[ServiceDefaultProperties] ([ProviderID], [PropertyName], [PropertyValue]) VALUES (105, N'PerlPath', N'%SYSTEMDRIVE%\Perl\bin\PerlEx30.dll') -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[ServiceDefaultProperties] WHERE [ProviderID] = 105 AND [PropertyName] = N'Php4Path') -BEGIN - INSERT [dbo].[ServiceDefaultProperties] ([ProviderID], [PropertyName], [PropertyValue]) VALUES (105, N'Php4Path', N'%PROGRAMFILES%\PHP\php.exe') -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[ServiceDefaultProperties] WHERE [ProviderID] = 105 AND [PropertyName] = N'PhpMode') -BEGIN - INSERT [dbo].[ServiceDefaultProperties] ([ProviderID], [PropertyName], [PropertyValue]) VALUES (105, N'PhpMode', N'FastCGI') -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[ServiceDefaultProperties] WHERE [ProviderID] = 105 AND [PropertyName] = N'PhpPath') -BEGIN - INSERT [dbo].[ServiceDefaultProperties] ([ProviderID], [PropertyName], [PropertyValue]) VALUES (105, N'PhpPath', N'%PROGRAMFILES%\PHP\php-cgi.exe') -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[ServiceDefaultProperties] WHERE [ProviderID] = 105 AND [PropertyName] = N'ProtectedGroupsFile') -BEGIN - INSERT [dbo].[ServiceDefaultProperties] ([ProviderID], [PropertyName], [PropertyValue]) VALUES (105, N'ProtectedGroupsFile', N'.htgroup') -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[ServiceDefaultProperties] WHERE [ProviderID] = 105 AND [PropertyName] = N'ProtectedUsersFile') -BEGIN - INSERT [dbo].[ServiceDefaultProperties] ([ProviderID], [PropertyName], [PropertyValue]) VALUES (105, N'ProtectedUsersFile', N'.htpasswd') -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[ServiceDefaultProperties] WHERE [ProviderID] = 105 AND [PropertyName] = N'SecureFoldersModuleAssembly') -BEGIN - INSERT [dbo].[ServiceDefaultProperties] ([ProviderID], [PropertyName], [PropertyValue]) VALUES (105, N'SecureFoldersModuleAssembly', N'WebsitePanel.IIsModules.SecureFolders, WebsitePanel.IIsModules, Version=1.0.0.0, Culture=Neutral, PublicKeyToken=37f9c58a0aa32ff0') -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[ServiceDefaultProperties] WHERE [ProviderID] = 105 AND [PropertyName] = N'WebGroupName') -BEGIN - INSERT [dbo].[ServiceDefaultProperties] ([ProviderID], [PropertyName], [PropertyValue]) VALUES (105, N'WebGroupName', N'WSP_IUSRS') -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[ServiceDefaultProperties] WHERE [ProviderID] = 105 AND [PropertyName] = N'WmSvc.CredentialsMode') -BEGIN - INSERT [dbo].[ServiceDefaultProperties] ([ProviderID], [PropertyName], [PropertyValue]) VALUES (105, N'WmSvc.CredentialsMode', N'WINDOWS') -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[ServiceDefaultProperties] WHERE [ProviderID] = 105 AND [PropertyName] = N'WmSvc.Port') -BEGIN - INSERT [dbo].[ServiceDefaultProperties] ([ProviderID], [PropertyName], [PropertyValue]) VALUES (105, N'WmSvc.Port', N'8172') -END -GO - --- MS FTP 8.0 -IF NOT EXISTS (SELECT * FROM [dbo].[Providers] WHERE [DisplayName] = 'Microsoft FTP Server 8.0') -BEGIN -INSERT [dbo].[Providers] ([ProviderID], [GroupID], [ProviderName], [DisplayName], [ProviderType], [EditorControl], [DisableAutoDiscovery]) VALUES (106, 3, N'MSFTP80', N'Microsoft FTP Server 8.0', N'WebsitePanel.Providers.FTP.MsFTP80, WebsitePanel.Providers.FTP.IIs80', N'MSFTP70', NULL) -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[ServiceDefaultProperties] WHERE [ProviderID] = 106 AND [PropertyName] = N'FtpGroupName') -BEGIN - INSERT [dbo].[ServiceDefaultProperties] ([ProviderID], [PropertyName], [PropertyValue]) VALUES (106, N'FtpGroupName', N'WSPFtpUsers') -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[ServiceDefaultProperties] WHERE [ProviderID] = 106 AND [PropertyName] = N'SiteId') -BEGIN - INSERT [dbo].[ServiceDefaultProperties] ([ProviderID], [PropertyName], [PropertyValue]) VALUES (106, N'SiteId', N'Default FTP Site') -END -GO - --- end of MS FTP 8.0, IIS 8.0 and Windows 2012 - --- new user settings -IF NOT EXISTS (SELECT * FROM [dbo].[UserSettings] WHERE ([UserID] = 1) AND ([SettingsName] = 'WebPolicy') AND ([PropertyName] = 'EnableParkingPageTokens')) -BEGIN - INSERT [dbo].[UserSettings] ([UserID], [SettingsName], [PropertyName], [PropertyValue]) VALUES (1, N'WebPolicy', N'EnableParkingPageTokens', N'False') -END - -IF NOT EXISTS (SELECT * FROM [dbo].[ResourceGroups] WHERE [GroupName] = 'MsSQL2012') -BEGIN - INSERT [dbo].[ResourceGroups] ([GroupID], [GroupName], [GroupOrder], [GroupController]) VALUES (23, N'MsSQL2012', 10, N'WebsitePanel.EnterpriseServer.DatabaseServerController') -END -GO - -UPDATE [dbo].[ResourceGroups] SET [GroupOrder] = 1 WHERE [GroupName] = N'OS' -GO -UPDATE [dbo].[ResourceGroups] SET [GroupOrder] = 2 WHERE [GroupName] = N'Web' -GO -UPDATE [dbo].[ResourceGroups] SET [GroupOrder] = 3 WHERE [GroupName] = N'FTP' -GO -UPDATE [dbo].[ResourceGroups] SET [GroupOrder] = 4 WHERE [GroupName] = N'Mail' -GO -UPDATE [dbo].[ResourceGroups] SET [GroupOrder] = 5 WHERE [GroupName] = N'Exchange' -GO -UPDATE [dbo].[ResourceGroups] SET [GroupOrder] = 6 WHERE [GroupName] = N'Hosted Organizations' -GO -UPDATE [dbo].[ResourceGroups] SET [GroupOrder] = 7 WHERE [GroupName] = N'MsSQL2000' -GO -UPDATE [dbo].[ResourceGroups] SET [GroupOrder] = 8 WHERE [GroupName] = N'MsSQL2005' -GO -UPDATE [dbo].[ResourceGroups] SET [GroupOrder] = 9 WHERE [GroupName] = N'MsSQL2008' -GO -UPDATE [dbo].[ResourceGroups] SET [GroupOrder] = 10 WHERE [GroupName] = N'MsSQL2012' -GO -UPDATE [dbo].[ResourceGroups] SET [GroupOrder] = 11 WHERE [GroupName] = N'MySQL4' -GO -UPDATE [dbo].[ResourceGroups] SET [GroupOrder] = 12 WHERE [GroupName] = N'MySQL5' -GO -UPDATE [dbo].[ResourceGroups] SET [GroupOrder] = 13 WHERE [GroupName] = N'SharePoint' -GO -UPDATE [dbo].[ResourceGroups] SET [GroupOrder] = 14 WHERE [GroupName] = N'Hosted SharePoint' -GO -UPDATE [dbo].[ResourceGroups] SET [GroupOrder] = 15 WHERE [GroupName] = N'Hosted CRM' -GO -UPDATE [dbo].[ResourceGroups] SET [GroupOrder] = 16 WHERE [GroupName] = N'DNS' -GO -UPDATE [dbo].[ResourceGroups] SET [GroupOrder] = 17 WHERE [GroupName] = N'Statistics' -GO -UPDATE [dbo].[ResourceGroups] SET [GroupOrder] = 18 WHERE [GroupName] = N'VPS' -GO -UPDATE [dbo].[ResourceGroups] SET [GroupOrder] = 19 WHERE [GroupName] = N'VPSForPC' -GO -UPDATE [dbo].[ResourceGroups] SET [GroupOrder] = 20 WHERE [GroupName] = N'BlackBerry' -GO -UPDATE [dbo].[ResourceGroups] SET [GroupOrder] = 21 WHERE [GroupName] = N'OCS' -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[ResourceGroups] WHERE [GroupName] = 'Lync') -BEGIN -INSERT [dbo].[ResourceGroups] ([GroupID], [GroupName], [GroupOrder], [GroupController]) VALUES (41, N'Lync',22, NULL) -END -GO - - - -IF NOT EXISTS (SELECT * FROM [dbo].[ServiceItemTypes] WHERE [DisplayName] = 'MsSQL2012Database') -BEGIN - INSERT [dbo].[ServiceItemTypes] ([ItemTypeID], [GroupID], [DisplayName], [TypeName], [TypeOrder], [CalculateDiskspace], [CalculateBandwidth], [Suspendable], [Disposable], [Searchable], [Importable], [Backupable]) VALUES (37, 23, N'MsSQL2012Database', N'WebsitePanel.Providers.Database.SqlDatabase, WebsitePanel.Providers.Base', 1, 1, 0, 0, 1, 1, 1, 1) -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[ServiceItemTypes] WHERE [DisplayName] = 'MsSQL2012User') -BEGIN - INSERT [dbo].[ServiceItemTypes] ([ItemTypeID], [GroupID], [DisplayName], [TypeName], [TypeOrder], [CalculateDiskspace], [CalculateBandwidth], [Suspendable], [Disposable], [Searchable], [Importable], [Backupable]) VALUES (38, 23, N'MsSQL2012User', N'WebsitePanel.Providers.Database.SqlUser, WebsitePanel.Providers.Base', 1, 0, 0, 0, 1, 1, 1, 1) -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[Providers] WHERE [DisplayName] = 'Microsoft SQL Server 2012') -BEGIN - -- provider - INSERT [dbo].[Providers] ([ProviderID], [GroupID], [ProviderName], [DisplayName], [ProviderType], [EditorControl], [DisableAutoDiscovery]) VALUES (209, 23, N'MsSQL', N'Microsoft SQL Server 2012', N'WebsitePanel.Providers.Database.MsSqlServer2012, WebsitePanel.Providers.Database.SqlServer', N'MSSQL', NULL) -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[Quotas] WHERE [QuotaName] = 'MsSQL2012.Databases') -BEGIN - INSERT [dbo].[Quotas] ([QuotaID], [GroupID], [QuotaOrder], [QuotaName], [QuotaDescription], [QuotaTypeID], [ServiceQuota], [ItemTypeID]) VALUES (218, 23, 1, N'MsSQL2012.Databases', N'Databases', 2, 0, 37) -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[Quotas] WHERE [QuotaName] = 'MsSQL2012.Users') -BEGIN - INSERT [dbo].[Quotas] ([QuotaID], [GroupID], [QuotaOrder], [QuotaName], [QuotaDescription], [QuotaTypeID], [ServiceQuota], [ItemTypeID]) VALUES (219, 23, 2, N'MsSQL2012.Users', N'Users', 2, 0, 38) -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[Quotas] WHERE [QuotaName] = 'MsSQL2012.MaxDatabaseSize') -BEGIN - INSERT [dbo].[Quotas] ([QuotaID], [GroupID], [QuotaOrder], [QuotaName], [QuotaDescription], [QuotaTypeID], [ServiceQuota], [ItemTypeID]) VALUES (221, 23, 3, N'MsSQL2012.MaxDatabaseSize', N'Max Database Size', 3, 0, NULL) -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[Quotas] WHERE [QuotaName] = 'MsSQL2012.Backup') -BEGIN - INSERT [dbo].[Quotas] ([QuotaID], [GroupID], [QuotaOrder], [QuotaName], [QuotaDescription], [QuotaTypeID], [ServiceQuota], [ItemTypeID]) VALUES (222, 23, 5, N'MsSQL2012.Backup', N'Database Backups', 1, 0, NULL) -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[Quotas] WHERE [QuotaName] = 'MsSQL2012.Restore') -BEGIN - INSERT [dbo].[Quotas] ([QuotaID], [GroupID], [QuotaOrder], [QuotaName], [QuotaDescription], [QuotaTypeID], [ServiceQuota], [ItemTypeID]) VALUES (223, 23, 6, N'MsSQL2012.Restore', N'Database Restores', 1, 0, NULL) -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[Quotas] WHERE [QuotaName] = 'MsSQL2012.Truncate') -BEGIN -INSERT [dbo].[Quotas] ([QuotaID], [GroupID], [QuotaOrder], [QuotaName], [QuotaDescription], [QuotaTypeID], [ServiceQuota], [ItemTypeID]) VALUES (224, 23, 7, N'MsSQL2012.Truncate', N'Database Truncate', 1, 0, NULL) -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[Quotas] WHERE [QuotaName] = 'MsSQL2012.MaxLogSize') -BEGIN -INSERT [dbo].[Quotas] ([QuotaID], [GroupID], [QuotaOrder], [QuotaName], [QuotaDescription], [QuotaTypeID], [ServiceQuota], [ItemTypeID]) VALUES (225, 23, 4, N'MsSQL2012.MaxLogSize', N'Max Log Size', 3, 0, NULL) -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[Quotas] WHERE [QuotaName] = 'HostedSharePoint.UseSharedSSL') -BEGIN -INSERT [dbo].[Quotas] ([QuotaID], [GroupID], [QuotaOrder], [QuotaName], [QuotaDescription], [QuotaTypeID], [ServiceQuota], [ItemTypeID]) VALUES (400, 20, 3, N'HostedSharePoint.UseSharedSSL', N'Use shared SSL Root', 1, 0, NULL) -END -GO - - -IF NOT EXISTS (SELECT * FROM [dbo].[Quotas] WHERE [QuotaName] = 'Exchange2007.KeepDeletedItemsDays') -BEGIN -INSERT [dbo].[Quotas] ([QuotaID], [GroupID], [QuotaOrder], [QuotaName], [QuotaDescription], [QuotaTypeID], [ServiceQuota], [ItemTypeID]) VALUES (364, 12, 19, N'Exchange2007.KeepDeletedItemsDays', N'Keep Deleted Items (days)', 3, 0, NULL) -END -GO - -UPDATE [dbo].[Quotas] SET [QuotaTypeID] = 3 WHERE [QuotaID] = 364 -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[Quotas] WHERE [QuotaName] = 'Exchange2007.MaxRecipients') -BEGIN -INSERT [dbo].[Quotas] ([QuotaID], [GroupID], [QuotaOrder], [QuotaName], [QuotaDescription], [QuotaTypeID], [ServiceQuota], [ItemTypeID]) VALUES (365, 12, 20, N'Exchange2007.MaxRecipients', N'Maximum Recipients', 3, 0, NULL) -END -GO - -UPDATE [dbo].[Quotas] SET [QuotaTypeID] = 3 WHERE [QuotaID] = 365 -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[Quotas] WHERE [QuotaName] = 'Exchange2007.MaxSendMessageSizeKB') -BEGIN -INSERT [dbo].[Quotas] ([QuotaID], [GroupID], [QuotaOrder], [QuotaName], [QuotaDescription], [QuotaTypeID], [ServiceQuota], [ItemTypeID]) VALUES (366, 12, 21, N'Exchange2007.MaxSendMessageSizeKB', N'Maximum Send Message Size (Kb)', 3, 0, NULL) -END -GO - -UPDATE [dbo].[Quotas] SET [QuotaTypeID] = 3 WHERE [QuotaID] = 366 -GO - - -IF NOT EXISTS (SELECT * FROM [dbo].[Quotas] WHERE [QuotaName] = 'Exchange2007.MaxReceiveMessageSizeKB') -BEGIN -INSERT [dbo].[Quotas] ([QuotaID], [GroupID], [QuotaOrder], [QuotaName], [QuotaDescription], [QuotaTypeID], [ServiceQuota], [ItemTypeID]) VALUES (367, 12, 22, N'Exchange2007.MaxReceiveMessageSizeKB', N'Maximum Receive Message Size (Kb)', 3, 0, NULL) -END -GO - -UPDATE [dbo].[Quotas] SET [QuotaTypeID] = 3 WHERE [QuotaID] = 367 -GO - - -IF NOT EXISTS (SELECT * FROM [dbo].[Quotas] WHERE [QuotaName] = 'Exchange2007.IsConsumer') -BEGIN -INSERT [dbo].[Quotas] ([QuotaID], [GroupID], [QuotaOrder], [QuotaName], [QuotaDescription], [QuotaTypeID], [ServiceQuota], [ItemTypeID]) VALUES (368, 12, 1, N'Exchange2007.IsConsumer',N'Is Consumer Organization', 1, 0, NULL) -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[Quotas] WHERE [QuotaName] = 'Exchange2007.EnablePlansEditing') -BEGIN -INSERT [dbo].[Quotas] ([QuotaID], [GroupID],[QuotaOrder], [QuotaName], [QuotaDescription], [QuotaTypeID], [ServiceQuota], [ItemTypeID]) VALUES (369, 12, 23,N'Exchange2007.EnablePlansEditing',N'Enable Plans Editing',1, 0 , NULL) -END -GO - - - -IF NOT EXISTS (SELECT * FROM [dbo].[Quotas] WHERE [QuotaName] = 'Lync.Users') -BEGIN -INSERT [dbo].[Quotas] ([QuotaID], [GroupID], [QuotaOrder], [QuotaName], [QuotaDescription], [QuotaTypeID], [ServiceQuota], [ItemTypeID]) VALUES (370, 41, 1, N'Lync.Users', N'Users',2 ,0 , NULL) -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[Quotas] WHERE [QuotaName] = 'Lync.Federation') -BEGIN -INSERT [dbo].[Quotas] ([QuotaID], [GroupID], [QuotaOrder], [QuotaName], [QuotaDescription], [QuotaTypeID], [ServiceQuota], [ItemTypeID]) VALUES (371, 41, 2, N'Lync.Federation' , N'Allow Federation', 1, 0, NULL) -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[Quotas] WHERE [QuotaName] = 'Lync.Conferencing') -BEGIN -INSERT [dbo].[Quotas] ([QuotaID], [GroupID], [QuotaOrder], [QuotaName], [QuotaDescription], [QuotaTypeID], [ServiceQuota], [ItemTypeID]) VALUES (372, 41, 3, N'Lync.Conferencing', N'Allow Conferencing', 1, 0, NULL) -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[Quotas] WHERE [QuotaName] = 'Lync.MaxParticipants') -BEGIN -INSERT [dbo].[Quotas] ([QuotaID], [GroupID], [QuotaOrder], [QuotaName], [QuotaDescription], [QuotaTypeID], [ServiceQuota], [ItemTypeID]) VALUES (373, 41, 4, N'Lync.MaxParticipants', N'Maximum Conference Particiapants', 3, 0, NULL) -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[Quotas] WHERE [QuotaName] = 'Lync.AllowVideo') -BEGIN -INSERT [dbo].[Quotas] ([QuotaID], [GroupID], [QuotaOrder], [QuotaName], [QuotaDescription], [QuotaTypeID], [ServiceQuota], [ItemTypeID]) VALUES (374, 41, 5, N'Lync.AllowVideo', N'Allow Video in Conference', 1, 0, NULL) -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[Quotas] WHERE [QuotaName] = 'Lync.EnterpriseVoice') -BEGIN -INSERT [dbo].[Quotas] ([QuotaID], [GroupID], [QuotaOrder], [QuotaName], [QuotaDescription], [QuotaTypeID], [ServiceQuota], [ItemTypeID]) VALUES (375, 41, 6, N'Lync.EnterpriseVoice', N'Allow EnterpriseVoice', 1, 0, NULL) -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[Quotas] WHERE [QuotaName] = 'Lync.EVUsers') -BEGIN -INSERT [dbo].[Quotas] ([QuotaID], [GroupID], [QuotaOrder], [QuotaName], [QuotaDescription], [QuotaTypeID], [ServiceQuota], [ItemTypeID]) VALUES (376, 41, 7, N'Lync.EVUsers', N'Number of Enterprise Voice Users', 2, 0, NULL) -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[Quotas] WHERE [QuotaName] = 'Lync.EVNational') -BEGIN -INSERT [dbo].[Quotas] ([QuotaID], [GroupID], [QuotaOrder], [QuotaName], [QuotaDescription], [QuotaTypeID], [ServiceQuota], [ItemTypeID]) VALUES (377, 41, 8, N'Lync.EVNational', N'Allow National Calls', 1, 0, NULL) -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[Quotas] WHERE [QuotaName] = 'Lync.EVMobile') -BEGIN -INSERT [dbo].[Quotas] ([QuotaID], [GroupID], [QuotaOrder], [QuotaName], [QuotaDescription], [QuotaTypeID], [ServiceQuota], [ItemTypeID]) VALUES (378, 41, 9, N'Lync.EVMobile', N'Allow Mobile Calls', 1, 0, NULL) -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[Quotas] WHERE [QuotaName] = 'Lync.EVInternational') -BEGIN -INSERT [dbo].[Quotas] ([QuotaID], [GroupID], [QuotaOrder], [QuotaName], [QuotaDescription], [QuotaTypeID], [ServiceQuota], [ItemTypeID]) VALUES (379, 41, 10, N'Lync.EVInternational', N'Allow International Calls', 1, 0, NULL) -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[Quotas] WHERE [QuotaName] = 'HostedSharePoint.UseSharedSSL') -BEGIN -INSERT [dbo].[Quotas] ([QuotaID], [GroupID], [QuotaOrder], [QuotaName], [QuotaDescription], [QuotaTypeID], [ServiceQuota], [ItemTypeID]) VALUES (400, 20, 3, N'HostedSharePoint.UseSharedSSL', N'Use shared SSL Root', 1, 0, NULL) -END -GO - - - -IF NOT EXISTS (SELECT * FROM [dbo].[Quotas] WHERE [QuotaName] = 'Lync.EnablePlansEditing') -BEGIN -INSERT [dbo].[Quotas] ([QuotaID], [GroupID], [QuotaOrder], [QuotaName], [QuotaDescription], [QuotaTypeID], [ServiceQuota], [ItemTypeID]) VALUES (380, 41, 11, N'Lync.EnablePlansEditing', N'Enable Plans Editing', 1, 0, NULL) -END -GO - - - -IF NOT EXISTS (SELECT * FROM [dbo].[Providers] WHERE [DisplayName] = 'Hosted Microsoft Exchange Server 2010 SP2') -BEGIN -INSERT [dbo].[Providers] ([ProviderId], [GroupId], [ProviderName], [DisplayName], [ProviderType], [EditorControl], [DisableAutoDiscovery]) VALUES(90, 12, N'Exchange2010SP2', N'Hosted Microsoft Exchange Server 2010 SP2', N'WebsitePanel.Providers.HostedSolution.Exchange2010SP2, WebsitePanel.Providers.HostedSolution', N'Exchange', 1) +INSERT [dbo].[Providers] ([ProviderId], [GroupId], [ProviderName], [DisplayName], [ProviderType], [EditorControl], [DisableAutoDiscovery]) VALUES(91, 12, N'Exchange2013', N'Hosted Microsoft Exchange Server 2013', N'WebsitePanel.Providers.HostedSolution.Exchange2013, WebsitePanel.Providers.HostedSolution.Exchange2013', N'Exchange', 1) END ELSE BEGIN -UPDATE [dbo].[Providers] SET [DisableAutoDiscovery] = NULL WHERE [DisplayName] = 'Hosted Microsoft Exchange Server 2010 SP2' +UPDATE [dbo].[Providers] SET [DisableAutoDiscovery] = NULL WHERE [DisplayName] = 'Hosted Microsoft Exchange Server 2013' END GO -IF NOT EXISTS (SELECT * FROM [dbo].[Providers] WHERE [DisplayName] = 'Microsoft Lync Server 2010 Multitenant Hosting Pack') -BEGIN -INSERT [dbo].[Providers] ([ProviderID], [GroupID], [ProviderName], [DisplayName], [ProviderType], [EditorControl], [DisableAutoDiscovery]) VALUES (250, 41, N'Lync2010', N'Microsoft Lync Server 2010 Multitenant Hosting Pack', 'WebsitePanel.Providers.HostedSolution.Lync2010, WebsitePanel.Providers.HostedSolution', 'Lync', NULL) -END -ELSE -BEGIN -UPDATE [dbo].[Providers] SET [DisableAutoDiscovery] = NULL WHERE [DisplayName] = 'Microsoft Lync Server 2010 Multitenant Hosting Pack' -END -GO - - -IF NOT EXISTS (SELECT * FROM [dbo].[Quotas] WHERE [QuotaName] = 'OS.AllowTenantCreateDomains') -BEGIN -INSERT [dbo].[Quotas] ([QuotaID], [GroupID], [QuotaOrder], [QuotaName], [QuotaDescription], [QuotaTypeID], [ServiceQuota], [ItemTypeID]) VALUES (410, 1, 12, N'OS.AllowTenantCreateDomains', N'Allow Tenants to Create Top Level Domains', 1, 0, NULL) -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[Quotas] WHERE [QuotaName] = 'Web.AllowIPAddressModeSwitch') -BEGIN - INSERT [dbo].[Quotas] ([QuotaID], [GroupID], [QuotaOrder], [QuotaName], [QuotaDescription], [QuotaTypeID], [ServiceQuota], [ItemTypeID]) VALUES (333, 2, 22, N'Web.AllowIPAddressModeSwitch', N'Allow IP Address Mode Switch', 1, 0, NULL) -END -GO - - - -DELETE FROM [dbo].[PackageQuotas] WHERE [QuotaID] IN (SELECT [QuotaID] FROM [dbo].[Quotas] WHERE [QuotaName] = N'Exchange2007.POP3Enabled') -DELETE FROM [dbo].[HostingPlanQuotas] WHERE [QuotaID] IN (SELECT [QuotaID] FROM [dbo].[Quotas] WHERE [QuotaName] = N'Exchange2007.POP3Enabled') -DELETE FROM [dbo].[Quotas] WHERE [QuotaName] = N'Exchange2007.POP3Enabled' - -DELETE FROM [dbo].[PackageQuotas] WHERE [QuotaID] IN (SELECT [QuotaID] FROM [dbo].[Quotas] WHERE [QuotaName] = N'Exchange2007.IMAPEnabled') -DELETE FROM [dbo].[HostingPlanQuotas] WHERE [QuotaID] IN (SELECT [QuotaID] FROM [dbo].[Quotas] WHERE [QuotaName] = N'Exchange2007.IMAPEnabled') -DELETE FROM [dbo].[Quotas] WHERE [QuotaName] = N'Exchange2007.IMAPEnabled' - -DELETE FROM [dbo].[PackageQuotas] WHERE [QuotaID] IN (SELECT [QuotaID] FROM [dbo].[Quotas] WHERE [QuotaName] = N'Exchange2007.OWAEnabled') -DELETE FROM [dbo].[HostingPlanQuotas] WHERE [QuotaID] IN (SELECT [QuotaID] FROM [dbo].[Quotas] WHERE [QuotaName] = N'Exchange2007.OWAEnabled') -DELETE FROM [dbo].[Quotas] WHERE [QuotaName] = N'Exchange2007.OWAEnabled' - -DELETE FROM [dbo].[PackageQuotas] WHERE [QuotaID] IN (SELECT [QuotaID] FROM [dbo].[Quotas] WHERE [QuotaName] = N'Exchange2007.MAPIEnabled') -DELETE FROM [dbo].[HostingPlanQuotas] WHERE [QuotaID] IN (SELECT [QuotaID] FROM [dbo].[Quotas] WHERE [QuotaName] = N'Exchange2007.MAPIEnabled') -DELETE FROM [dbo].[Quotas] WHERE [QuotaName] = N'Exchange2007.MAPIEnabled' - -DELETE FROM [dbo].[PackageQuotas] WHERE [QuotaID] IN (SELECT [QuotaID] FROM [dbo].[Quotas] WHERE [QuotaName] = N'Exchange2007.ActiveSyncEnabled') -DELETE FROM [dbo].[HostingPlanQuotas] WHERE [QuotaID] IN (SELECT [QuotaID] FROM [dbo].[Quotas] WHERE [QuotaName] = N'Exchange2007.ActiveSyncEnabled') -DELETE FROM [dbo].[Quotas] WHERE [QuotaName] = N'Exchange2007.ActiveSyncEnabled' - -UPDATE [dbo].[ScheduleTaskParameters] SET DefaultValue = N'MsSQL2000=SQL Server 2000;MsSQL2005=SQL Server 2005;MsSQL2008=SQL Server 2008;MsSQL2012=SQL Server 2012;MySQL4=MySQL 4.0;MySQL5=MySQL 5.0' WHERE [ParameterID] = N'DATABASE_GROUP' -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[Providers] WHERE [DisplayName] = 'Microsoft SQL Server 2012') -BEGIN - INSERT [dbo].[Providers] ([ProviderID], [GroupID], [ProviderName], [DisplayName], [ProviderType], [EditorControl], [DisableAutoDiscovery]) VALUES (209, 23, N'MsSQL', N'Microsoft SQL Server 2012', N'WebsitePanel.Providers.Database.MsSqlServer2012, WebsitePanel.Providers.Database.SqlServer', N'MSSQL', NULL) -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[ServiceDefaultProperties] WHERE [ProviderID] = 12 AND [PropertyName] = 'LogsFolder') -BEGIN - INSERT [dbo].[ServiceDefaultProperties] ([ProviderID], [PropertyName], [PropertyValue]) VALUES (12, N'LogsFolder', N'%PROGRAMFILES%\Gene6 FTP Server\Log') -END -GO -UPDATE [dbo].[Providers] SET [EditorControl] = N'hMailServer5' WHERE [ProviderID] = 63 -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[ServiceDefaultProperties] WHERE [ProviderID] = 63 AND [PropertyName] = N'AdminUsername') -BEGIN - INSERT [dbo].[ServiceDefaultProperties] ([ProviderID], [PropertyName], [PropertyValue]) VALUES (63, N'AdminUsername', N'Administrator') -END -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[ServiceDefaultProperties] WHERE [ProviderID] = 63 AND [PropertyName] = N'AdminPassword') -BEGIN - INSERT [dbo].[ServiceDefaultProperties] ([ProviderID], [PropertyName], [PropertyValue]) VALUES (63, N'AdminPassword', N'') -END -GO - - -IF NOT EXISTS(select 1 from sys.columns COLS INNER JOIN sys.objects OBJS ON OBJS.object_id=COLS.object_id and OBJS.type='U' AND OBJS.name='Users' AND COLS.name='LoginStatusId') -BEGIN -ALTER TABLE [dbo].[Users] ADD - [LoginStatusId] [int] NULL, - [FailedLogins] [int] NULL -END -GO - - -IF NOT EXISTS(select 1 from sys.columns COLS INNER JOIN sys.objects OBJS ON OBJS.object_id=COLS.object_id and OBJS.type='U' AND OBJS.name='GlobalDnsRecords' AND COLS.name='SrvPriority') -BEGIN -ALTER TABLE [dbo].[GlobalDnsRecords] ADD - [SrvPriority] [int] NULL, - [SrvWeight] [int] NULL, - [SrvPort] [int] NULL -END -GO - -IF NOT EXISTS(select 1 from sys.columns COLS INNER JOIN sys.objects OBJS ON OBJS.object_id=COLS.object_id and OBJS.type='U' AND OBJS.name='ResourceGroups' AND COLS.name='ShowGroup') -BEGIN -ALTER TABLE [dbo].[ResourceGroups] ADD [ShowGroup] [bit] NULL -END -GO - - -UPDATE [dbo].[ResourceGroups] SET ShowGroup=1 -GO - -IF NOT EXISTS(select 1 from sys.columns COLS INNER JOIN sys.objects OBJS ON OBJS.object_id=COLS.object_id and OBJS.type='U' AND OBJS.name='Quotas' AND COLS.name='HideQuota') -BEGIN -ALTER TABLE [dbo].[Quotas] ADD [HideQuota] [bit] NULL -END -GO - -UPDATE [dbo].[Quotas] SET [HideQuota] = 1 WHERE [QuotaName] = N'OS.DomainPointers' -GO - - -/****** Object: Table [dbo].[ExchangeAccounts] Extend Exchange Accounts with UserPrincipalName ******/ -IF NOT EXISTS(select 1 from sys.columns COLS INNER JOIN sys.objects OBJS ON OBJS.object_id=COLS.object_id and OBJS.type='U' AND OBJS.name='ExchangeAccounts' AND COLS.name='UserPrincipalName') -BEGIN -ALTER TABLE [dbo].[ExchangeAccounts] ADD - [UserPrincipalName] [nvarchar] (300) COLLATE Latin1_General_CI_AS NULL -END -GO - -IF NOT EXISTS(SELECT 1 FROM [dbo].[ExchangeAccounts] WHERE UserPrincipalName IS NOT NULL) -BEGIN - UPDATE [dbo].[ExchangeAccounts] SET [UserPrincipalName] = PrimaryEmailAddress WHERE AccountType IN (1,7) -END -GO - - -/****** Object: Table [dbo].[ExchangeAccounts] Extend Exchange Accounts with SubscriberNumber ******/ -IF NOT EXISTS(select 1 from sys.columns COLS INNER JOIN sys.objects OBJS ON OBJS.object_id=COLS.object_id and OBJS.type='U' AND OBJS.name='Users' AND COLS.name='SubscriberNumber') -BEGIN -ALTER TABLE [dbo].[Users] ADD [SubscriberNumber] [nvarchar] (32) COLLATE Latin1_General_CI_AS NULL -END -GO - - - - -ALTER PROCEDURE [dbo].[AddDnsRecord] -( - @ActorID int, - @ServiceID int, - @ServerID int, - @PackageID int, - @RecordType nvarchar(10), - @RecordName nvarchar(50), - @RecordData nvarchar(500), - @MXPriority int, - @SrvPriority int, - @SrvWeight int, - @SrvPort int, - @IPAddressID int -) -AS - -IF (@ServiceID > 0 OR @ServerID > 0) AND dbo.CheckIsUserAdmin(@ActorID) = 0 -RAISERROR('You should have administrator role to perform such operation', 16, 1) - -IF (@PackageID > 0) AND dbo.CheckActorPackageRights(@ActorID, @PackageID) = 0 -RAISERROR('You are not allowed to access this package', 16, 1) - -IF @ServiceID = 0 SET @ServiceID = NULL -IF @ServerID = 0 SET @ServerID = NULL -IF @PackageID = 0 SET @PackageID = NULL -IF @IPAddressID = 0 SET @IPAddressID = NULL - -IF EXISTS -( - SELECT RecordID FROM GlobalDnsRecords WHERE - ServiceID = @ServiceID AND ServerID = @ServerID AND PackageID = @PackageID - AND RecordName = @RecordName AND RecordType = @RecordType -) - - UPDATE GlobalDnsRecords - SET - RecordData = RecordData, - MXPriority = MXPriority, - SrvPriority = SrvPriority, - SrvWeight = SrvWeight, - SrvPort = SrvPort, - - IPAddressID = @IPAddressID - WHERE - ServiceID = @ServiceID AND ServerID = @ServerID AND PackageID = @PackageID -ELSE - INSERT INTO GlobalDnsRecords - ( - ServiceID, - ServerID, - PackageID, - RecordType, - RecordName, - RecordData, - MXPriority, - SrvPriority, - SrvWeight, - SrvPort, - IPAddressID - ) - VALUES - ( - @ServiceID, - @ServerID, - @PackageID, - @RecordType, - @RecordName, - @RecordData, - @MXPriority, - @SrvPriority, - @SrvWeight, - @SrvPort, - @IPAddressID - ) - -RETURN - -GO - - - - - - - - -ALTER PROCEDURE [dbo].[CheckDomain] -( - @PackageID int, - @DomainName nvarchar(100), - @IsDomainPointer bit, - @Result int OUTPUT -) -AS - -/* -@Result values: - 0 - OK - -1 - already exists - -2 - sub-domain of prohibited domain -*/ - -SET @Result = 0 -- OK - --- check if the domain already exists -IF EXISTS( -SELECT DomainID FROM Domains -WHERE DomainName = @DomainName AND IsDomainPointer = @IsDomainPointer -) -BEGIN - SET @Result = -1 - RETURN -END - --- check if this is a sub-domain of other domain --- that is not allowed for 3rd level hosting - -DECLARE @UserID int -SELECT @UserID = UserID FROM Packages -WHERE PackageID = @PackageID - --- find sub-domains -DECLARE @DomainUserID int, @HostingAllowed bit -SELECT - @DomainUserID = P.UserID, - @HostingAllowed = D.HostingAllowed -FROM Domains AS D -INNER JOIN Packages AS P ON D.PackageID = P.PackageID -WHERE CHARINDEX('.' + DomainName, @DomainName) > 0 -AND (CHARINDEX('.' + DomainName, @DomainName) + LEN('.' + DomainName)) = LEN(@DomainName) + 1 -AND IsDomainPointer = 0 - --- this is a domain of other user -IF @UserID <> @DomainUserID AND @HostingAllowed = 0 -BEGIN - SET @Result = -2 - RETURN -END - -RETURN - -GO - - - - - - - - -ALTER PROCEDURE [dbo].[GetDnsRecord] -( - @ActorID int, - @RecordID int -) -AS - --- check rights -DECLARE @ServiceID int, @ServerID int, @PackageID int -SELECT - @ServiceID = ServiceID, - @ServerID = ServerID, - @PackageID = PackageID -FROM GlobalDnsRecords -WHERE - RecordID = @RecordID - -IF (@ServiceID > 0 OR @ServerID > 0) AND dbo.CheckIsUserAdmin(@ActorID) = 0 -RAISERROR('You are not allowed to perform this operation', 16, 1) - -IF (@PackageID > 0) AND dbo.CheckActorPackageRights(@ActorID, @PackageID) = 0 -RAISERROR('You are not allowed to access this package', 16, 1) - -SELECT - NR.RecordID, - NR.ServiceID, - NR.ServerID, - NR.PackageID, - NR.RecordType, - NR.RecordName, - NR.RecordData, - NR.MXPriority, - NR.SrvPriority, - NR.SrvWeight, - NR.SrvPort, - NR.IPAddressID -FROM - GlobalDnsRecords AS NR -WHERE NR.RecordID = @RecordID -RETURN - -GO - - - - - - - - -ALTER PROCEDURE [dbo].[GetDnsRecordsByPackage] -( - @ActorID int, - @PackageID int -) -AS - --- check rights -IF dbo.CheckActorPackageRights(@ActorID, @PackageID) = 0 -RAISERROR('You are not allowed to access this package', 16, 1) - -SELECT - NR.RecordID, - NR.ServiceID, - NR.ServerID, - NR.PackageID, - NR.RecordType, - NR.RecordName, - NR.RecordData, - NR.MXPriority, - NR.SrvPriority, - NR.SrvWeight, - NR.SrvPort, - NR.IPAddressID, - CASE - WHEN NR.RecordType = 'A' AND NR.RecordData = '' THEN dbo.GetFullIPAddress(IP.ExternalIP, IP.InternalIP) - WHEN NR.RecordType = 'MX' THEN CONVERT(varchar(3), NR.MXPriority) + ', ' + NR.RecordData - WHEN NR.RecordType = 'SRV' THEN CONVERT(varchar(3), NR.SrvPort) + ', ' + NR.RecordData - ELSE NR.RecordData - END AS FullRecordData, - dbo.GetFullIPAddress(IP.ExternalIP, IP.InternalIP) AS IPAddress, - IP.ExternalIP, - IP.InternalIP -FROM - GlobalDnsRecords AS NR -LEFT OUTER JOIN IPAddresses AS IP ON NR.IPAddressID = IP.AddressID -WHERE NR.PackageID = @PackageID -RETURN - -GO - - - - - - - - - - -ALTER PROCEDURE [dbo].[GetDnsRecordsByServer] -( - @ActorID int, - @ServerID int -) -AS - -SELECT - NR.RecordID, - NR.ServiceID, - NR.ServerID, - NR.PackageID, - NR.RecordType, - NR.RecordName, - NR.RecordData, - CASE - WHEN NR.RecordType = 'A' AND NR.RecordData = '' THEN dbo.GetFullIPAddress(IP.ExternalIP, IP.InternalIP) - WHEN NR.RecordType = 'MX' THEN CONVERT(varchar(3), NR.MXPriority) + ', ' + NR.RecordData - WHEN NR.RecordType = 'SRV' THEN CONVERT(varchar(3), NR.SrvPort) + ', ' + NR.RecordData - ELSE NR.RecordData - END AS FullRecordData, - NR.MXPriority, - NR.SrvPriority, - NR.SrvWeight, - NR.SrvPort, - NR.IPAddressID, - dbo.GetFullIPAddress(IP.ExternalIP, IP.InternalIP) AS IPAddress, - IP.ExternalIP, - IP.InternalIP -FROM - GlobalDnsRecords AS NR -LEFT OUTER JOIN IPAddresses AS IP ON NR.IPAddressID = IP.AddressID -WHERE - NR.ServerID = @ServerID -RETURN - -GO - - - - - - - - - -ALTER PROCEDURE [dbo].[GetDnsRecordsByService] -( - @ActorID int, - @ServiceID int -) -AS - -SELECT - NR.RecordID, - NR.ServiceID, - NR.ServerID, - NR.PackageID, - NR.RecordType, - NR.RecordName, - CASE - WHEN NR.RecordType = 'A' AND NR.RecordData = '' THEN dbo.GetFullIPAddress(IP.ExternalIP, IP.InternalIP) - WHEN NR.RecordType = 'MX' THEN CONVERT(varchar(3), NR.MXPriority) + ', ' + NR.RecordData - WHEN NR.RecordType = 'SRV' THEN CONVERT(varchar(3), NR.SrvPort) + ', ' + NR.RecordData - ELSE NR.RecordData - END AS FullRecordData, - NR.RecordData, - NR.MXPriority, - NR.SrvPriority, - NR.SrvWeight, - NR.SrvPort, - NR.IPAddressID, - dbo.GetFullIPAddress(IP.ExternalIP, IP.InternalIP) AS IPAddress, - IP.ExternalIP, - IP.InternalIP -FROM - GlobalDnsRecords AS NR -LEFT OUTER JOIN IPAddresses AS IP ON NR.IPAddressID = IP.AddressID -WHERE - NR.ServiceID = @ServiceID -RETURN - -GO - - - - - - - - - -ALTER PROCEDURE [dbo].[GetDnsRecordsTotal] -( - @ActorID int, - @PackageID int -) -AS - --- check rights -IF dbo.CheckActorPackageRights(@ActorID, @PackageID) = 0 -RAISERROR('You are not allowed to access this package', 16, 1) - --- create temp table for DNS records -DECLARE @Records TABLE -( - RecordID int, - RecordType nvarchar(10) COLLATE Latin1_General_CI_AS, - RecordName nvarchar(50) COLLATE Latin1_General_CI_AS -) - --- select PACKAGES DNS records -DECLARE @ParentPackageID int, @TmpPackageID int -SET @TmpPackageID = @PackageID - -WHILE 10 = 10 -BEGIN - - -- get DNS records for the current package - INSERT INTO @Records (RecordID, RecordType, RecordName) - SELECT - GR.RecordID, - GR.RecordType, - GR.RecordName - FROM GlobalDNSRecords AS GR - WHERE GR.PackageID = @TmpPackageID - AND GR.RecordType + GR.RecordName NOT IN (SELECT RecordType + RecordName FROM @Records) - - SET @ParentPackageID = NULL - - -- get parent package - SELECT - @ParentPackageID = ParentPackageID - FROM Packages - WHERE PackageID = @TmpPackageID - - IF @ParentPackageID IS NULL -- the last parent - BREAK - - SET @TmpPackageID = @ParentPackageID -END - --- select SERVER DNS records -DECLARE @ServerID int -SELECT @ServerID = ServerID FROM Packages -WHERE PackageID = @PackageID - -INSERT INTO @Records (RecordID, RecordType, RecordName) -SELECT - GR.RecordID, - GR.RecordType, - GR.RecordName -FROM GlobalDNSRecords AS GR -WHERE GR.ServerID = @ServerID -AND GR.RecordType + GR.RecordName NOT IN (SELECT RecordType + RecordName FROM @Records) - - --- select SERVICES DNS records --- re-distribute package services -EXEC DistributePackageServices @ActorID, @PackageID - -INSERT INTO @Records (RecordID, RecordType, RecordName) -SELECT - GR.RecordID, - GR.RecordType, - GR.RecordName -FROM GlobalDNSRecords AS GR -WHERE GR.ServiceID IN (SELECT ServiceID FROM PackageServices WHERE PackageID = @PackageID) -AND GR.RecordType + GR.RecordName NOT IN (SELECT RecordType + RecordName FROM @Records) - - -SELECT - NR.RecordID, - NR.ServiceID, - NR.ServerID, - NR.PackageID, - NR.RecordType, - NR.RecordName, - NR.RecordData, - NR.MXPriority, - NR.SrvPriority, - NR.SrvWeight, - NR.SrvPort, - NR.IPAddressID, - ISNULL(IP.ExternalIP, '') AS ExternalIP, - ISNULL(IP.InternalIP, '') AS InternalIP, - CASE - WHEN NR.RecordType = 'A' AND NR.RecordData = '' THEN dbo.GetFullIPAddress(IP.ExternalIP, IP.InternalIP) - WHEN NR.RecordType = 'MX' THEN CONVERT(varchar(3), NR.MXPriority) + ', ' + NR.RecordData - WHEN NR.RecordType = 'SRV' THEN CONVERT(varchar(3), NR.SrvPort) + ', ' + NR.RecordData - ELSE NR.RecordData - END AS FullRecordData, - dbo.GetFullIPAddress(IP.ExternalIP, IP.InternalIP) AS IPAddress -FROM @Records AS TR -INNER JOIN GlobalDnsRecords AS NR ON TR.RecordID = NR.RecordID -LEFT OUTER JOIN IPAddresses AS IP ON NR.IPAddressID = IP.AddressID - -RETURN - -GO - - - - - - - - - -ALTER PROCEDURE [dbo].[GetDomainsPaged] -( - @ActorID int, - @PackageID int, - @ServerID int, - @Recursive bit, - @FilterColumn nvarchar(50) = '', - @FilterValue nvarchar(50) = '', - @SortColumn nvarchar(50), - @StartRow int, - @MaximumRows int -) -AS -SET NOCOUNT ON - --- check rights -IF dbo.CheckActorPackageRights(@ActorID, @PackageID) = 0 -RAISERROR('You are not allowed to access this package', 16, 1) - --- build query and run it to the temporary table -DECLARE @sql nvarchar(2000) - -IF @SortColumn = '' OR @SortColumn IS NULL -SET @SortColumn = 'DomainName' - -SET @sql = ' -DECLARE @Domains TABLE -( - ItemPosition int IDENTITY(1,1), - DomainID int -) -INSERT INTO @Domains (DomainID) -SELECT - D.DomainID -FROM Domains AS D -INNER JOIN Packages AS P ON D.PackageID = P.PackageID -INNER JOIN UsersDetailed AS U ON P.UserID = U.UserID -LEFT OUTER JOIN ServiceItems AS Z ON D.ZoneItemID = Z.ItemID -LEFT OUTER JOIN Services AS S ON Z.ServiceID = S.ServiceID -LEFT OUTER JOIN Servers AS SRV ON S.ServerID = SRV.ServerID -WHERE D.IsInstantAlias = 0 AND - ((@Recursive = 0 AND D.PackageID = @PackageID) - OR (@Recursive = 1 AND dbo.CheckPackageParent(@PackageID, D.PackageID) = 1)) -AND (@ServerID = 0 OR (@ServerID > 0 AND S.ServerID = @ServerID)) -' - -IF @FilterColumn <> '' AND @FilterValue <> '' -SET @sql = @sql + ' AND ' + @FilterColumn + ' LIKE @FilterValue ' - -IF @SortColumn <> '' AND @SortColumn IS NOT NULL -SET @sql = @sql + ' ORDER BY ' + @SortColumn + ' ' - -SET @sql = @sql + ' SELECT COUNT(DomainID) FROM @Domains;SELECT - D.DomainID, - D.PackageID, - D.ZoneItemID, - D.DomainName, - D.HostingAllowed, - ISNULL(WS.ItemID, 0) AS WebSiteID, - WS.ItemName AS WebSiteName, - ISNULL(MD.ItemID, 0) AS MailDomainID, - MD.ItemName AS MailDomainName, - D.IsSubDomain, - D.IsInstantAlias, - D.IsDomainPointer, - - -- packages - P.PackageName, - - -- server - ISNULL(SRV.ServerID, 0) AS ServerID, - ISNULL(SRV.ServerName, '''') AS ServerName, - ISNULL(SRV.Comments, '''') AS ServerComments, - ISNULL(SRV.VirtualServer, 0) AS VirtualServer, - - -- user - P.UserID, - U.Username, - U.FirstName, - U.LastName, - U.FullName, - U.RoleID, - U.Email -FROM @Domains AS SD -INNER JOIN Domains AS D ON SD.DomainID = D.DomainID -INNER JOIN Packages AS P ON D.PackageID = P.PackageID -INNER JOIN UsersDetailed AS U ON P.UserID = U.UserID -LEFT OUTER JOIN ServiceItems AS WS ON D.WebSiteID = WS.ItemID -LEFT OUTER JOIN ServiceItems AS MD ON D.MailDomainID = MD.ItemID -LEFT OUTER JOIN ServiceItems AS Z ON D.ZoneItemID = Z.ItemID -LEFT OUTER JOIN Services AS S ON Z.ServiceID = S.ServiceID -LEFT OUTER JOIN Servers AS SRV ON S.ServerID = SRV.ServerID -WHERE SD.ItemPosition BETWEEN @StartRow + 1 AND @StartRow + @MaximumRows' - -exec sp_executesql @sql, N'@StartRow int, @MaximumRows int, @PackageID int, @FilterValue nvarchar(50), @ServerID int, @Recursive bit', -@StartRow, @MaximumRows, @PackageID, @FilterValue, @ServerID, @Recursive - - -RETURN - -GO - - - - - - - - - - -ALTER PROCEDURE [dbo].[UpdateDnsRecord] -( - @ActorID int, - @RecordID int, - @RecordType nvarchar(10), - @RecordName nvarchar(50), - @RecordData nvarchar(500), - @MXPriority int, - @SrvPriority int, - @SrvWeight int, - @SrvPort int, - @IPAddressID int -) -AS - -IF @IPAddressID = 0 SET @IPAddressID = NULL - --- check rights -DECLARE @ServiceID int, @ServerID int, @PackageID int -SELECT - @ServiceID = ServiceID, - @ServerID = ServerID, - @PackageID = PackageID -FROM GlobalDnsRecords -WHERE - RecordID = @RecordID - -IF (@ServiceID > 0 OR @ServerID > 0) AND dbo.CheckIsUserAdmin(@ActorID) = 0 -RAISERROR('You are not allowed to perform this operation', 16, 1) - -IF (@PackageID > 0) AND dbo.CheckActorPackageRights(@ActorID, @PackageID) = 0 -RAISERROR('You are not allowed to access this package', 16, 1) - - --- update record -UPDATE GlobalDnsRecords -SET - RecordType = @RecordType, - RecordName = @RecordName, - RecordData = @RecordData, - MXPriority = @MXPriority, - SrvPriority = @SrvPriority, - SrvWeight = @SrvWeight, - SrvPort = @SrvPort, - IPAddressID = @IPAddressID -WHERE - RecordID = @RecordID -RETURN - -GO - - - - -UPDATE dbo.Quotas SET QuotaTypeID = 2 WHERE QuotaName = 'HostedSharePoint.Sites' -GO -UPDATE dbo.Quotas SET QuotaTypeID = 2 WHERE QuotaName = 'HostedSolution.Users' -GO -UPDATE dbo.Quotas SET QuotaTypeID = 2 WHERE QuotaName = 'Exchange2007.Mailboxes' -GO -UPDATE dbo.Quotas SET QuotaTypeID = 2 WHERE QuotaName = 'Exchange2007.DiskSpace' -GO - - - --- Remove ExchangeHostedEdition Quotas +IF NOT EXISTS (SELECT * FROM [dbo].[Quotas] WHERE [QuotaName] = 'Exchange2007.AllowLitigationHold') DELETE FROM HostingPlanQuotas WHERE QuotaID = 340 GO DELETE FROM HostingPlanQuotas WHERE QuotaID = 341 @@ -1239,378 +33,31 @@ DELETE FROM HostingPlanQuotas WHERE QuotaID = 342 GO DELETE FROM HostingPlanQuotas WHERE QuotaID = 343 GO - - --- Remove ExchangeHostedEdition Quotas -DELETE FROM Quotas WHERE QuotaID = 340 -GO -DELETE FROM Quotas WHERE QuotaID = 341 -GO -DELETE FROM Quotas WHERE QuotaID = 342 -GO -DELETE FROM Quotas WHERE QuotaID = 343 -GO - DELETE FROM HostingPlanResources WHERE GroupID = 33 GO - --- Remove ExchangeHostedEdition ServiceItemType -DELETE FROM ServiceItemTypes WHERE ItemTypeID = 40 -GO - - --- Remove ExchangeHostedEdition ServiceDefaultProperties -DELETE FROM ServiceDefaultProperties WHERE ProviderID = 207 -GO - - - --- Remove ExchangeHostedEdition Provider -DELETE FROM Providers WHERE ProviderID = 207 -GO - - - --- Remove ExchangeHostedEdition VirtualGroups -DELETE FROM VirtualGroups WHERE GroupID = 33 -GO - - - --- Remove ExchangeHostedEdition ResourceGroups -DELETE FROM ResourceGroups WHERE GRoupID = 33 -GO - - --- Create Exchange Mailbox Plans -IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ExchangeMailboxPlans]') AND type in (N'U')) BEGIN -CREATE TABLE [dbo].[ExchangeMailboxPlans]( - [MailboxPlanId] [int] IDENTITY(1,1) NOT NULL, - [ItemID] [int] NOT NULL, - [MailboxPlan] [nvarchar](300) COLLATE Latin1_General_CI_AS NOT NULL, - [MailboxPlanType] [int] NULL, - [EnableActiveSync] [bit] NOT NULL, - [EnableIMAP] [bit] NOT NULL, - [EnableMAPI] [bit] NOT NULL, - [EnableOWA] [bit] NOT NULL, - [EnablePOP] [bit] NOT NULL, - [IsDefault] [bit] NOT NULL, - [IssueWarningPct] [int] NOT NULL, - [KeepDeletedItemsDays] [int] NOT NULL, - [MailboxSizeMB] [int] NOT NULL, - [MaxReceiveMessageSizeKB] [int] NOT NULL, - [MaxRecipients] [int] NOT NULL, - [MaxSendMessageSizeKB] [int] NOT NULL, - [ProhibitSendPct] [int] NOT NULL, - [ProhibitSendReceivePct] [int] NOT NULL, - [HideFromAddressBook] [bit] NOT NULL, - CONSTRAINT [PK_ExchangeMailboxPlans] PRIMARY KEY CLUSTERED -( - [MailboxPlanId] ASC -)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] -) ON [PRIMARY] - -/****** Object: Table [dbo].[ExchangeAccounts] ******/ -ALTER TABLE [dbo].[ExchangeAccounts] ALTER COLUMN [AccountName] [nvarchar](300) COLLATE Latin1_General_CI_AS NOT NULL - -/****** Object: Table [dbo].[ExchangeAccounts] ******/ -ALTER TABLE [dbo].[ExchangeAccounts] ADD [MailboxPlanId] int NULL - -/****** Object: Table [dbo].[ExchangeAccounts] ******/ -ALTER TABLE [dbo].[ExchangeAccounts] WITH CHECK ADD CONSTRAINT [FK_ExchangeAccounts_ExchangeMailboxPlans] FOREIGN KEY([MailboxPlanId]) -REFERENCES [dbo].[ExchangeMailboxPlans] ([MailboxPlanId]) - -ALTER TABLE [dbo].[ExchangeAccounts] CHECK CONSTRAINT [FK_ExchangeAccounts_ExchangeMailboxPlans] - -/****** Object: Table [dbo].[ExchangeAccounts] ******/ -ALTER TABLE [dbo].[ExchangeMailboxPlans] WITH CHECK ADD CONSTRAINT [FK_ExchangeMailboxPlans_ExchangeOrganizations] FOREIGN KEY([ItemID]) -REFERENCES [dbo].[ExchangeOrganizations] ([ItemID]) -ON DELETE CASCADE - -/****** Object: Table [dbo].[ExchangeAccounts] ******/ -ALTER TABLE dbo.ExchangeMailboxPlans ADD CONSTRAINT - IX_ExchangeMailboxPlans UNIQUE NONCLUSTERED - ( - MailboxPlanId - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -END -GO - -/****** Object: Table [dbo].[ExchangeAccounts] Extend Exchange Accounts with MailboxplanID ******/ -IF NOT EXISTS(select 1 from sys.columns COLS INNER JOIN sys.objects OBJS ON OBJS.object_id=COLS.object_id and OBJS.type='U' AND OBJS.name='ExchangeAccounts' AND COLS.name='MailboxPlanId') -BEGIN -ALTER TABLE [dbo].[ExchangeAccounts] ADD [MailboxPlanId] [int] NULL -END -GO - -/****** Object: Table [dbo].[ExchangeAccounts] Extend Exchange Accounts with SubscriberNumber ******/ -IF NOT EXISTS(select 1 from sys.columns COLS INNER JOIN sys.objects OBJS ON OBJS.object_id=COLS.object_id and OBJS.type='U' AND OBJS.name='ExchangeAccounts' AND COLS.name='SubscriberNumber') -BEGIN -ALTER TABLE [dbo].[ExchangeAccounts] ADD [SubscriberNumber] [nvarchar] (32) COLLATE Latin1_General_CI_AS NULL +INSERT [dbo].[Quotas] ([QuotaID], [GroupID],[QuotaOrder], [QuotaName], [QuotaDescription], [QuotaTypeID], [ServiceQuota], [ItemTypeID]) VALUES (420, 12, 24,N'Exchange2007.AllowLitigationHold',N'Allow Litigation Hold',1, 0 , NULL) END GO -ALTER VIEW [dbo].[UsersDetailed] -AS -SELECT U.UserID, U.RoleID, U.StatusID, U.LoginStatusId, U.SubscriberNumber, U.FailedLogins, U.OwnerID, U.Created, U.Changed, U.IsDemo, U.Comments, U.IsPeer, U.Username, U.FirstName, U.LastName, U.Email, - U.CompanyName, U.FirstName + ' ' + U.LastName AS FullName, UP.Username AS OwnerUsername, UP.FirstName AS OwnerFirstName, - UP.LastName AS OwnerLastName, UP.RoleID AS OwnerRoleID, UP.FirstName + ' ' + UP.LastName AS OwnerFullName, UP.Email AS OwnerEmail, UP.RoleID AS Expr1, - (SELECT COUNT(PackageID) AS Expr1 - FROM dbo.Packages AS P - WHERE (UserID = U.UserID)) AS PackagesNumber, U.EcommerceEnabled -FROM dbo.Users AS U LEFT OUTER JOIN - dbo.Users AS UP ON U.OwnerID = UP.UserID +IF NOT EXISTS (SELECT * FROM [dbo].[Quotas] WHERE [QuotaName] = 'Exchange2007.RecoverableItemsSpace') +BEGIN +INSERT [dbo].[Quotas] ([QuotaID], [GroupID],[QuotaOrder], [QuotaName], [QuotaDescription], [QuotaTypeID], [ServiceQuota], [ItemTypeID]) VALUES (421, 12, 25,N'Exchange2007.RecoverableItemsSpace',N'Recoverable Items Space',2, 0 , NULL) +END GO -/****** Object: Table [dbo].[ExchangeOrganizations] ******/ -ALTER TABLE [dbo].[ExchangeOrganizations] ALTER COLUMN [OrganizationID] [nvarchar](128) COLLATE Latin1_General_CI_AS NOT NULL -GO -IF NOT EXISTS(select 1 from sys.columns COLS INNER JOIN sys.objects OBJS ON OBJS.object_id=COLS.object_id and OBJS.type='U' AND OBJS.name='ExchangeMailboxPlans' AND COLS.name='MailboxPlanType') +IF NOT EXISTS(select 1 from sys.columns COLS INNER JOIN sys.objects OBJS ON OBJS.object_id=COLS.object_id and OBJS.type='U' AND OBJS.name='ExchangeMailboxPlans' AND COLS.name='AllowLitigationHold') BEGIN ALTER TABLE [dbo].[ExchangeMailboxPlans] ADD - [MailboxPlanType] [int] NULL + [AllowLitigationHold] [bit] NULL, + [RecoverableItemsWarningPct] [int] NULL, + [RecoverableItemsSpace] [int] NULL END GO --- LyncUsers -IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[LyncUsers]') AND type in (N'U')) -BEGIN -CREATE TABLE [dbo].[LyncUsers]( - [LyncUserID] [int] IDENTITY(1,1) NOT NULL, - [AccountID] [int] NOT NULL, - [LyncUserPlanID] [int] NOT NULL, - [CreatedDate] [datetime] NOT NULL, - [ModifiedDate] [datetime] NOT NULL, - CONSTRAINT [PK_LyncUsers] PRIMARY KEY CLUSTERED -( - [LyncUserID] ASC -)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] -) ON [PRIMARY] - - -ALTER TABLE [dbo].[LyncUsers] ADD CONSTRAINT [DF_LyncUsers_CreatedDate] DEFAULT (getdate()) FOR [CreatedDate] - -ALTER TABLE [dbo].[LyncUsers] ADD CONSTRAINT [DF_LyncUsers_ChangedDate] DEFAULT (getdate()) FOR [ModifiedDate] - -END -GO - - - - --- LyncUserPlans -IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[LyncUserPlans]') AND type in (N'U')) -BEGIN -CREATE TABLE [dbo].[LyncUserPlans]( - [LyncUserPlanId] [int] IDENTITY(1,1) NOT NULL, - [ItemID] [int] NOT NULL, - [LyncUserPlanName] [nvarchar](300) NOT NULL, - [LyncUserPlanType] [int] NULL, - [IM] [bit] NOT NULL, - [Mobility] [bit] NOT NULL, - [MobilityEnableOutsideVoice] [bit] NOT NULL, - [Federation] [bit] NOT NULL, - [Conferencing] [bit] NOT NULL, - [EnterpriseVoice] [bit] NOT NULL, - [VoicePolicy] [int] NOT NULL, - [IsDefault] [bit] NOT NULL, - CONSTRAINT [PK_LyncUserPlans] PRIMARY KEY CLUSTERED -( - [LyncUserPlanId] ASC -)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] -) ON [PRIMARY] - -ALTER TABLE dbo.LyncUserPlans ADD CONSTRAINT - IX_LyncUserPlans UNIQUE NONCLUSTERED - ( - LyncUserPlanId - ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - -ALTER TABLE dbo.LyncUserPlans ADD CONSTRAINT - FK_LyncUserPlans_ExchangeOrganizations FOREIGN KEY - ( - ItemID - ) REFERENCES dbo.ExchangeOrganizations - ( - ItemID - ) ON UPDATE NO ACTION - ON DELETE CASCADE - -ALTER TABLE [dbo].[LyncUsers] WITH CHECK ADD CONSTRAINT [FK_LyncUsers_LyncUserPlans] FOREIGN KEY([LyncUserPlanId]) -REFERENCES [dbo].[LyncUserPlans] ([LyncUserPlanId]) - -ALTER TABLE [dbo].[LyncUsers] CHECK CONSTRAINT [FK_LyncUsers_LyncUserPlans] - -END -GO - - - -IF NOT EXISTS(select 1 from sys.columns COLS INNER JOIN sys.objects OBJS ON OBJS.object_id=COLS.object_id and OBJS.type='U' AND OBJS.name='LyncUserPlans' AND COLS.name='LyncUserPlanType') -BEGIN -ALTER TABLE [dbo].[LyncUserPlans] ADD - [LyncUserPlanType] [int] NULL -END -GO - - - - -/****** Object: Table [dbo].[AddExchangeAccount] ******/ -ALTER PROCEDURE [dbo].[AddExchangeAccount] -( - @AccountID int OUTPUT, - @ItemID int, - @AccountType int, - @AccountName nvarchar(300), - @DisplayName nvarchar(300), - @PrimaryEmailAddress nvarchar(300), - @MailEnabledPublicFolder bit, - @MailboxManagerActions varchar(200), - @SamAccountName nvarchar(100), - @AccountPassword nvarchar(200), - @MailboxPlanId int, - @SubscriberNumber nvarchar(32) -) -AS - -INSERT INTO ExchangeAccounts -( - ItemID, - AccountType, - AccountName, - DisplayName, - PrimaryEmailAddress, - MailEnabledPublicFolder, - MailboxManagerActions, - SamAccountName, - AccountPassword, - MailboxPlanId, - SubscriberNumber, - UserPrincipalName -) -VALUES -( - @ItemID, - @AccountType, - @AccountName, - @DisplayName, - @PrimaryEmailAddress, - @MailEnabledPublicFolder, - @MailboxManagerActions, - @SamAccountName, - @AccountPassword, - @MailboxPlanId, - @SubscriberNumber, - @PrimaryEmailAddress -) - -SET @AccountID = SCOPE_IDENTITY() - -RETURN -GO - - - - - - - -IF NOT EXISTS (SELECT * FROM sys.objects WHERE type_desc = N'SQL_STORED_PROCEDURE' AND name = N'AddExchangeMailboxPlan') -BEGIN -EXEC sp_executesql N' -CREATE PROCEDURE [dbo].[AddExchangeMailboxPlan] -( - @MailboxPlanId int OUTPUT, - @ItemID int, - @MailboxPlan nvarchar(300), - @EnableActiveSync bit, - @EnableIMAP bit, - @EnableMAPI bit, - @EnableOWA bit, - @EnablePOP bit, - @IsDefault bit, - @IssueWarningPct int, - @KeepDeletedItemsDays int, - @MailboxSizeMB int, - @MaxReceiveMessageSizeKB int, - @MaxRecipients int, - @MaxSendMessageSizeKB int, - @ProhibitSendPct int, - @ProhibitSendReceivePct int , - @HideFromAddressBook bit, - @MailboxPlanType int -) -AS - -IF (((SELECT Count(*) FROM ExchangeMailboxPlans WHERE ItemId = @ItemID) = 0) AND (@MailboxPlanType=0)) -BEGIN - SET @IsDefault = 1 -END -ELSE -BEGIN - IF ((@IsDefault = 1) AND (@MailboxPlanType=0)) - BEGIN - UPDATE ExchangeMailboxPlans SET IsDefault = 0 WHERE ItemID = @ItemID - END -END - - -INSERT INTO ExchangeMailboxPlans -( - ItemID, - MailboxPlan, - EnableActiveSync, - EnableIMAP, - EnableMAPI, - EnableOWA, - EnablePOP, - IsDefault, - IssueWarningPct, - KeepDeletedItemsDays, - MailboxSizeMB, - MaxReceiveMessageSizeKB, - MaxRecipients, - MaxSendMessageSizeKB, - ProhibitSendPct, - ProhibitSendReceivePct, - HideFromAddressBook, - MailboxPlanType -) -VALUES -( - @ItemID, - @MailboxPlan, - @EnableActiveSync, - @EnableIMAP, - @EnableMAPI, - @EnableOWA, - @EnablePOP, - @IsDefault, - @IssueWarningPct, - @KeepDeletedItemsDays, - @MailboxSizeMB, - @MaxReceiveMessageSizeKB, - @MaxRecipients, - @MaxSendMessageSizeKB, - @ProhibitSendPct, - @ProhibitSendReceivePct, - @HideFromAddressBook, - @MailboxPlanType -) - -SET @MailboxPlanId = SCOPE_IDENTITY() - -RETURN' -END -GO - - @@ -1635,7 +82,10 @@ ALTER PROCEDURE [dbo].[AddExchangeMailboxPlan] @ProhibitSendPct int, @ProhibitSendReceivePct int , @HideFromAddressBook bit, - @MailboxPlanType int + @MailboxPlanType int, + @AllowLitigationHold bit, + @RecoverableItemsWarningPct int, + @RecoverableItemsSpace int ) AS @@ -1670,7 +120,10 @@ INSERT INTO ExchangeMailboxPlans ProhibitSendPct, ProhibitSendReceivePct, HideFromAddressBook, - MailboxPlanType + MailboxPlanType, + AllowLitigationHold, + RecoverableItemsWarningPct, + RecoverableItemsSpace ) VALUES ( @@ -1691,7 +144,10 @@ VALUES @ProhibitSendPct, @ProhibitSendReceivePct, @HideFromAddressBook, - @MailboxPlanType + @MailboxPlanType, + @AllowLitigationHold, + @RecoverableItemsWarningPct, + @RecoverableItemsSpace ) SET @MailboxPlanId = SCOPE_IDENTITY() @@ -1707,228 +163,7 @@ GO - - - - - - - -ALTER PROCEDURE [dbo].[AddExchangeOrganization] -( - @ItemID int, - @OrganizationID nvarchar(128) -) -AS - -IF NOT EXISTS(SELECT * FROM ExchangeOrganizations WHERE OrganizationID = @OrganizationID) -BEGIN - INSERT INTO ExchangeOrganizations - (ItemID, OrganizationID) - VALUES - (@ItemID, @OrganizationID) -END - -RETURN -GO - - - - - - - - - - - - - -ALTER FUNCTION [dbo].[CalculateQuotaUsage] -( - @PackageID int, - @QuotaID int -) -RETURNS int -AS - BEGIN - - DECLARE @QuotaTypeID int - SELECT @QuotaTypeID = QuotaTypeID FROM Quotas - WHERE QuotaID = @QuotaID - - IF @QuotaTypeID <> 2 - RETURN 0 - - DECLARE @Result int - - IF @QuotaID = 52 -- diskspace - SET @Result = dbo.CalculatePackageDiskspace(@PackageID) - ELSE IF @QuotaID = 51 -- bandwidth - SET @Result = dbo.CalculatePackageBandwidth(@PackageID) - ELSE IF @QuotaID = 53 -- domains - SET @Result = (SELECT COUNT(D.DomainID) FROM PackagesTreeCache AS PT - INNER JOIN Domains AS D ON D.PackageID = PT.PackageID - WHERE IsSubDomain = 0 AND IsInstantAlias = 0 AND IsDomainPointer = 0 AND PT.ParentPackageID = @PackageID) - ELSE IF @QuotaID = 54 -- sub-domains - SET @Result = (SELECT COUNT(D.DomainID) FROM PackagesTreeCache AS PT - INNER JOIN Domains AS D ON D.PackageID = PT.PackageID - WHERE IsSubDomain = 1 AND IsInstantAlias = 0 AND IsDomainPointer = 0 AND PT.ParentPackageID = @PackageID) - ELSE IF @QuotaID = 220 -- domain pointers - SET @Result = (SELECT COUNT(D.DomainID) FROM PackagesTreeCache AS PT - INNER JOIN Domains AS D ON D.PackageID = PT.PackageID - WHERE IsDomainPointer = 1 AND PT.ParentPackageID = @PackageID) - ELSE IF @QuotaID = 71 -- scheduled tasks - SET @Result = (SELECT COUNT(S.ScheduleID) FROM PackagesTreeCache AS PT - INNER JOIN Schedule AS S ON S.PackageID = PT.PackageID - WHERE PT.ParentPackageID = @PackageID) - ELSE IF @QuotaID = 305 -- RAM of VPS - SET @Result = (SELECT SUM(CAST(SIP.PropertyValue AS int)) FROM ServiceItemProperties AS SIP - INNER JOIN ServiceItems AS SI ON SIP.ItemID = SI.ItemID - INNER JOIN PackagesTreeCache AS PT ON SI.PackageID = PT.PackageID - WHERE SIP.PropertyName = 'RamSize' AND PT.ParentPackageID = @PackageID) - ELSE IF @QuotaID = 306 -- HDD of VPS - SET @Result = (SELECT SUM(CAST(SIP.PropertyValue AS int)) FROM ServiceItemProperties AS SIP - INNER JOIN ServiceItems AS SI ON SIP.ItemID = SI.ItemID - INNER JOIN PackagesTreeCache AS PT ON SI.PackageID = PT.PackageID - WHERE SIP.PropertyName = 'HddSize' AND PT.ParentPackageID = @PackageID) - ELSE IF @QuotaID = 309 -- External IP addresses of VPS - SET @Result = (SELECT COUNT(PIP.PackageAddressID) FROM PackageIPAddresses AS PIP - INNER JOIN IPAddresses AS IP ON PIP.AddressID = IP.AddressID - INNER JOIN PackagesTreeCache AS PT ON PIP.PackageID = PT.PackageID - WHERE PT.ParentPackageID = @PackageID AND IP.PoolID = 3) - ELSE IF @QuotaID = 100 -- Dedicated Web IP addresses - SET @Result = (SELECT COUNT(PIP.PackageAddressID) FROM PackageIPAddresses AS PIP - INNER JOIN IPAddresses AS IP ON PIP.AddressID = IP.AddressID - INNER JOIN PackagesTreeCache AS PT ON PIP.PackageID = PT.PackageID - WHERE PT.ParentPackageID = @PackageID AND IP.PoolID = 2) - ELSE IF @QuotaID = 350 -- RAM of VPSforPc - SET @Result = (SELECT SUM(CAST(SIP.PropertyValue AS int)) FROM ServiceItemProperties AS SIP - INNER JOIN ServiceItems AS SI ON SIP.ItemID = SI.ItemID - INNER JOIN PackagesTreeCache AS PT ON SI.PackageID = PT.PackageID - WHERE SIP.PropertyName = 'Memory' AND PT.ParentPackageID = @PackageID) - ELSE IF @QuotaID = 351 -- HDD of VPSforPc - SET @Result = (SELECT SUM(CAST(SIP.PropertyValue AS int)) FROM ServiceItemProperties AS SIP - INNER JOIN ServiceItems AS SI ON SIP.ItemID = SI.ItemID - INNER JOIN PackagesTreeCache AS PT ON SI.PackageID = PT.PackageID - WHERE SIP.PropertyName = 'HddSize' AND PT.ParentPackageID = @PackageID) - ELSE IF @QuotaID = 354 -- External IP addresses of VPSforPc - SET @Result = (SELECT COUNT(PIP.PackageAddressID) FROM PackageIPAddresses AS PIP - INNER JOIN IPAddresses AS IP ON PIP.AddressID = IP.AddressID - INNER JOIN PackagesTreeCache AS PT ON PIP.PackageID = PT.PackageID - WHERE PT.ParentPackageID = @PackageID AND IP.PoolID = 3) - ELSE IF @QuotaID = 319 -- BB Users - SET @Result = (SELECT COUNT(ea.AccountID) FROM ExchangeAccounts ea - INNER JOIN BlackBerryUsers bu ON ea.AccountID = bu.AccountID - INNER JOIN ServiceItems si ON ea.ItemID = si.ItemID - INNER JOIN PackagesTreeCache pt ON si.PackageID = pt.PackageID - WHERE pt.ParentPackageID = @PackageID) - ELSE IF @QuotaID = 320 -- OCS Users - SET @Result = (SELECT COUNT(ea.AccountID) FROM ExchangeAccounts ea - INNER JOIN OCSUsers ocs ON ea.AccountID = ocs.AccountID - INNER JOIN ServiceItems si ON ea.ItemID = si.ItemID - INNER JOIN PackagesTreeCache pt ON si.PackageID = pt.PackageID - WHERE pt.ParentPackageID = @PackageID) - ELSE IF @QuotaID = 206 -- HostedSolution.Users - SET @Result = (SELECT COUNT(ea.AccountID) FROM ExchangeAccounts AS ea - INNER JOIN ServiceItems si ON ea.ItemID = si.ItemID - INNER JOIN PackagesTreeCache pt ON si.PackageID = pt.PackageID - WHERE pt.ParentPackageID = @PackageID AND ea.AccountType IN (1,5,6,7)) - ELSE IF @QuotaID = 78 -- Exchange2007.Mailboxes - SET @Result = (SELECT COUNT(ea.AccountID) FROM ExchangeAccounts AS ea - INNER JOIN ServiceItems si ON ea.ItemID = si.ItemID - INNER JOIN PackagesTreeCache pt ON si.PackageID = pt.PackageID - WHERE pt.ParentPackageID = @PackageID - AND ea.AccountType IN (1) - AND ea.MailboxPlanId IS NOT NULL) - ELSE IF @QuotaID = 77 -- Exchange2007.DiskSpace - SET @Result = (SELECT SUM(B.MailboxSizeMB) FROM ExchangeAccounts AS ea - INNER JOIN ExchangeMailboxPlans AS B ON ea.MailboxPlanId = B.MailboxPlanId - INNER JOIN ServiceItems si ON ea.ItemID = si.ItemID - INNER JOIN PackagesTreeCache pt ON si.PackageID = pt.PackageID - WHERE pt.ParentPackageID = @PackageID) - ELSE IF @QuotaID = 370 -- Lync.Users - SET @Result = (SELECT COUNT(ea.AccountID) FROM ExchangeAccounts AS ea - INNER JOIN LyncUsers lu ON ea.AccountID = lu.AccountID - INNER JOIN ServiceItems si ON ea.ItemID = si.ItemID - INNER JOIN PackagesTreeCache pt ON si.PackageID = pt.PackageID - WHERE pt.ParentPackageID = @PackageID) - ELSE IF @QuotaID = 376 -- Lync.EVUsers - SET @Result = (SELECT COUNT(ea.AccountID) FROM ExchangeAccounts AS ea - INNER JOIN LyncUsers lu ON ea.AccountID = lu.AccountID - INNER JOIN LyncUserPlans lp ON lu.LyncUserPlanId = lp.LyncUserPlanId - INNER JOIN ServiceItems si ON ea.ItemID = si.ItemID - INNER JOIN PackagesTreeCache pt ON si.PackageID = pt.PackageID - WHERE pt.ParentPackageID = @PackageID AND lp.EnterpriseVoice = 1) - ELSE - SET @Result = (SELECT COUNT(SI.ItemID) FROM Quotas AS Q - INNER JOIN ServiceItems AS SI ON SI.ItemTypeID = Q.ItemTypeID - INNER JOIN PackagesTreeCache AS PT ON SI.PackageID = PT.PackageID AND PT.ParentPackageID = @PackageID - WHERE Q.QuotaID = @QuotaID) - - RETURN @Result - END -GO - - - - - - - - - - -IF NOT EXISTS (SELECT * FROM sys.objects WHERE type_desc = N'SQL_STORED_PROCEDURE' AND name = N'DeleteExchangeMailboxPlan') -BEGIN -EXEC sp_executesql N' -CREATE PROCEDURE [dbo].[DeleteExchangeMailboxPlan] -( - @MailboxPlanId int -) -AS - --- delete mailboxplan -DELETE FROM ExchangeMailboxPlans -WHERE MailboxPlanId = @MailboxPlanId - -RETURN' -END -GO - - - - - - - - - - - - - - -ALTER PROCEDURE [dbo].[DeleteExchangeOrganization] -( - @ItemID int -) -AS -BEGIN TRAN - DELETE FROM ExchangeMailboxPlans WHERE ItemID = @ItemID - DELETE FROM ExchangeOrganizations WHERE ItemID = @ItemID -COMMIT TRAN -RETURN -GO - - - - - -IF NOT EXISTS (SELECT * FROM sys.objects WHERE type_desc = N'SQL_STORED_PROCEDURE' AND name = N'UpdateExchangeMailboxPlan') -BEGIN -EXEC sp_executesql N' -CREATE PROCEDURE [dbo].[UpdateExchangeMailboxPlan] +ALTER PROCEDURE [dbo].[UpdateExchangeMailboxPlan] ( @MailboxPlanId int, @MailboxPlan nvarchar(300), @@ -1947,7 +182,10 @@ CREATE PROCEDURE [dbo].[UpdateExchangeMailboxPlan] @ProhibitSendPct int, @ProhibitSendReceivePct int , @HideFromAddressBook bit, - @MailboxPlanType int + @MailboxPlanType int, + @AllowLitigationHold bit, + @RecoverableItemsWarningPct int, + @RecoverableItemsSpace int ) AS @@ -1968,5039 +206,13 @@ UPDATE ExchangeMailboxPlans SET ProhibitSendPct= @ProhibitSendPct, ProhibitSendReceivePct = @ProhibitSendReceivePct, HideFromAddressBook = @HideFromAddressBook, - MailboxPlanType = @MailboxPlanType + MailboxPlanType = @MailboxPlanType, + AllowLitigationHold = @AllowLitigationHold, + RecoverableItemsWarningPct = @RecoverableItemsWarningPct, + RecoverableItemsSpace = @RecoverableItemsSpace WHERE MailboxPlanId = @MailboxPlanId -RETURN' -END -GO - - - - - - - -IF NOT EXISTS (SELECT * FROM sys.objects WHERE type_desc = N'SQL_STORED_PROCEDURE' AND name = N'GetUserByExchangeOrganizationIdInternally') -BEGIN -EXEC sp_executesql N' -CREATE PROCEDURE [dbo].[GetUserByExchangeOrganizationIdInternally] -( - @ItemID int -) -AS - SELECT - U.UserID, - U.RoleID, - U.StatusID, - U.SubscriberNumber, - U.LoginStatusId, - U.FailedLogins, - U.OwnerID, - U.Created, - U.Changed, - U.IsDemo, - U.Comments, - U.IsPeer, - U.Username, - U.Password, - U.FirstName, - U.LastName, - U.Email, - U.SecondaryEmail, - U.Address, - U.City, - U.State, - U.Country, - U.Zip, - U.PrimaryPhone, - U.SecondaryPhone, - U.Fax, - U.InstantMessenger, - U.HtmlMail, - U.CompanyName, - U.EcommerceEnabled, - U.[AdditionalParams] - FROM Users AS U - WHERE U.UserID IN (SELECT UserID FROM Packages WHERE PackageID IN ( - SELECT PackageID FROM ServiceItems WHERE ItemID = @ItemID)) - -RETURN' -END -GO - - - - - - - - - - -ALTER PROCEDURE [dbo].[GetUserByExchangeOrganizationIdInternally] -( - @ItemID int -) -AS - SELECT - U.UserID, - U.RoleID, - U.StatusID, - U.SubscriberNumber, - U.LoginStatusId, - U.FailedLogins, - U.OwnerID, - U.Created, - U.Changed, - U.IsDemo, - U.Comments, - U.IsPeer, - U.Username, - U.Password, - U.FirstName, - U.LastName, - U.Email, - U.SecondaryEmail, - U.Address, - U.City, - U.State, - U.Country, - U.Zip, - U.PrimaryPhone, - U.SecondaryPhone, - U.Fax, - U.InstantMessenger, - U.HtmlMail, - U.CompanyName, - U.EcommerceEnabled, - U.[AdditionalParams] - FROM Users AS U - WHERE U.UserID IN (SELECT UserID FROM Packages WHERE PackageID IN ( - SELECT PackageID FROM ServiceItems WHERE ItemID = @ItemID)) - RETURN - -GO - - - - - - -ALTER PROCEDURE [dbo].[GetUserByExchangeOrganizationIdInternally] -( - @ItemID int -) -AS - SELECT - U.UserID, - U.RoleID, - U.StatusID, - U.SubscriberNumber, - U.LoginStatusId, - U.FailedLogins, - U.OwnerID, - U.Created, - U.Changed, - U.IsDemo, - U.Comments, - U.IsPeer, - U.Username, - U.Password, - U.FirstName, - U.LastName, - U.Email, - U.SecondaryEmail, - U.Address, - U.City, - U.State, - U.Country, - U.Zip, - U.PrimaryPhone, - U.SecondaryPhone, - U.Fax, - U.InstantMessenger, - U.HtmlMail, - U.CompanyName, - U.EcommerceEnabled, - U.[AdditionalParams] - FROM Users AS U - WHERE U.UserID IN (SELECT UserID FROM Packages WHERE PackageID IN ( - SELECT PackageID FROM ServiceItems WHERE ItemID = @ItemID)) - -RETURN -GO - - - - - - - - -ALTER PROCEDURE [dbo].[ExchangeAccountExists] -( - @AccountName nvarchar(20), - @Exists bit OUTPUT -) -AS -SET @Exists = 0 -IF EXISTS(SELECT * FROM ExchangeAccounts WHERE sAMAccountName LIKE '%\'+@AccountName) -BEGIN - SET @Exists = 1 -END - -RETURN - -GO - - - - - - - - - - - - -ALTER PROCEDURE [dbo].[GetExchangeAccounts] -( - @ItemID int, - @AccountType int -) -AS -SELECT - E.AccountID, - E.ItemID, - E.AccountType, - E.AccountName, - E.DisplayName, - E.PrimaryEmailAddress, - E.MailEnabledPublicFolder, - E.MailboxPlanId, - P.MailboxPlan, - E.SubscriberNumber, - E.UserPrincipalName -FROM - ExchangeAccounts AS E -LEFT OUTER JOIN ExchangeMailboxPlans AS P ON E.MailboxPlanId = P.MailboxPlanId -WHERE - E.ItemID = @ItemID AND - (E.AccountType = @AccountType OR @AccountType IS NULL) -ORDER BY DisplayName -RETURN - -GO - - - - - - - - - - -ALTER PROCEDURE [dbo].[GetExchangeAccountsPaged] -( - @ActorID int, - @ItemID int, - @AccountTypes nvarchar(30), - @FilterColumn nvarchar(50) = '', - @FilterValue nvarchar(50) = '', - @SortColumn nvarchar(50), - @StartRow int, - @MaximumRows int -) -AS - -DECLARE @PackageID int -SELECT @PackageID = PackageID FROM ServiceItems -WHERE ItemID = @ItemID - --- check rights -IF dbo.CheckActorPackageRights(@ActorID, @PackageID) = 0 -RAISERROR('You are not allowed to access this package', 16, 1) - --- start -DECLARE @condition nvarchar(700) -SET @condition = ' -EA.AccountType IN (' + @AccountTypes + ') -AND EA.ItemID = @ItemID -' - -IF @FilterColumn <> '' AND @FilterColumn IS NOT NULL -AND @FilterValue <> '' AND @FilterValue IS NOT NULL -BEGIN - IF @FilterColumn = 'PrimaryEmailAddress' AND @AccountTypes <> '2' - BEGIN - SET @condition = @condition + ' AND EA.AccountID IN (SELECT EAEA.AccountID FROM ExchangeAccountEmailAddresses EAEA WHERE EAEA.EmailAddress LIKE ''' + @FilterValue + ''')' - END - ELSE - BEGIN - SET @condition = @condition + ' AND ' + @FilterColumn + ' LIKE ''' + @FilterValue + '''' - END -END - -IF @SortColumn IS NULL OR @SortColumn = '' -SET @SortColumn = 'EA.DisplayName ASC' - -DECLARE @joincondition nvarchar(700) - SET @joincondition = ',P.MailboxPlan FROM ExchangeAccounts AS EA - LEFT OUTER JOIN ExchangeMailboxPlans AS P ON EA.MailboxPlanId = P.MailboxPlanId' - -DECLARE @sql nvarchar(3500) - -set @sql = ' -SELECT COUNT(EA.AccountID) FROM ExchangeAccounts AS EA -WHERE ' + @condition + '; - -WITH Accounts AS ( - SELECT ROW_NUMBER() OVER (ORDER BY ' + @SortColumn + ') as Row, - EA.AccountID, - EA.ItemID, - EA.AccountType, - EA.AccountName, - EA.DisplayName, - EA.PrimaryEmailAddress, - EA.MailEnabledPublicFolder, - EA.MailboxPlanId, - EA.SubscriberNumber, - EA.UserPrincipalName ' + @joincondition + - ' WHERE ' + @condition + ' -) - -SELECT * FROM Accounts -WHERE Row BETWEEN @StartRow + 1 and @StartRow + @MaximumRows -' - -print @sql - -exec sp_executesql @sql, N'@ItemID int, @StartRow int, @MaximumRows int', -@ItemID, @StartRow, @MaximumRows - -RETURN - - - - -GO - - - - - - - - - -IF NOT EXISTS (SELECT * FROM sys.objects WHERE type_desc = N'SQL_STORED_PROCEDURE' AND name = N'GetExchangeAccountByAccountName') -BEGIN -EXEC sp_executesql N'CREATE PROCEDURE [dbo].[GetExchangeAccountByAccountName] -( - @ItemID int, - @AccountName nvarchar(300) -) -AS -SELECT - E.AccountID, - E.ItemID, - E.AccountType, - E.AccountName, - E.DisplayName, - E.PrimaryEmailAddress, - E.MailEnabledPublicFolder, - E.MailboxManagerActions, - E.SamAccountName, - E.AccountPassword, - E.MailboxPlanId, - P.MailboxPlan, - E.SubscriberNumber, - E.UserPrincipalName -FROM - ExchangeAccounts AS E -LEFT OUTER JOIN ExchangeMailboxPlans AS P ON E.MailboxPlanId = P.MailboxPlanId -WHERE - E.ItemID = @ItemID AND - E.AccountName = @AccountName -RETURN' -END -GO - - - -ALTER PROCEDURE [dbo].[GetExchangeAccountByAccountName] -( - @ItemID int, - @AccountName nvarchar(300) -) -AS -SELECT - E.AccountID, - E.ItemID, - E.AccountType, - E.AccountName, - E.DisplayName, - E.PrimaryEmailAddress, - E.MailEnabledPublicFolder, - E.MailboxManagerActions, - E.SamAccountName, - E.AccountPassword, - E.MailboxPlanId, - P.MailboxPlan, - E.SubscriberNumber, - E.UserPrincipalName -FROM - ExchangeAccounts AS E -LEFT OUTER JOIN ExchangeMailboxPlans AS P ON E.MailboxPlanId = P.MailboxPlanId -WHERE - E.ItemID = @ItemID AND - E.AccountName = @AccountName -RETURN -GO - - - - -IF NOT EXISTS (SELECT * FROM sys.objects WHERE type_desc = N'SQL_STORED_PROCEDURE' AND name = N'GetExchangeAccountByMailboxPlanId') -BEGIN -EXEC sp_executesql N'CREATE PROCEDURE [dbo].[GetExchangeAccountByMailboxPlanId] -( - @ItemID int, - @MailboxPlanId int -) -AS - -IF (@MailboxPlanId < 0) -BEGIN -SELECT - E.AccountID, - E.ItemID, - E.AccountType, - E.AccountName, - E.DisplayName, - E.PrimaryEmailAddress, - E.MailEnabledPublicFolder, - E.MailboxManagerActions, - E.SamAccountName, - E.AccountPassword, - E.MailboxPlanId, - P.MailboxPlan, - E.SubscriberNumber, - E.UserPrincipalName -FROM - ExchangeAccounts AS E -LEFT OUTER JOIN ExchangeMailboxPlans AS P ON E.MailboxPlanId = P.MailboxPlanId -WHERE - E.ItemID = @ItemID AND - E.MailboxPlanId IS NULL AND - E.AccountType IN (1,5) -RETURN - -END -ELSE -IF (@ItemId = 0) -BEGIN -SELECT - E.AccountID, - E.ItemID, - E.AccountType, - E.AccountName, - E.DisplayName, - E.PrimaryEmailAddress, - E.MailEnabledPublicFolder, - E.MailboxManagerActions, - E.SamAccountName, - E.AccountPassword, - E.MailboxPlanId, - P.MailboxPlan, - E.SubscriberNumber, - E.UserPrincipalName -FROM - ExchangeAccounts AS E -LEFT OUTER JOIN ExchangeMailboxPlans AS P ON E.MailboxPlanId = P.MailboxPlanId -WHERE - E.MailboxPlanId = @MailboxPlanId AND - E.AccountType IN (1,5) -END -ELSE -BEGIN -SELECT - E.AccountID, - E.ItemID, - E.AccountType, - E.AccountName, - E.DisplayName, - E.PrimaryEmailAddress, - E.MailEnabledPublicFolder, - E.MailboxManagerActions, - E.SamAccountName, - E.AccountPassword, - E.MailboxPlanId, - P.MailboxPlan, - E.SubscriberNumber, - E.UserPrincipalName -FROM - ExchangeAccounts AS E -LEFT OUTER JOIN ExchangeMailboxPlans AS P ON E.MailboxPlanId = P.MailboxPlanId -WHERE - E.ItemID = @ItemID AND - E.MailboxPlanId = @MailboxPlanId AND - E.AccountType IN (1,5) -RETURN -END' -END -GO - - - - - - -ALTER PROCEDURE [dbo].[GetExchangeAccountByMailboxPlanId] -( - @ItemID int, - @MailboxPlanId int -) -AS - -IF (@MailboxPlanId < 0) -BEGIN -SELECT - E.AccountID, - E.ItemID, - E.AccountType, - E.AccountName, - E.DisplayName, - E.PrimaryEmailAddress, - E.MailEnabledPublicFolder, - E.MailboxManagerActions, - E.SamAccountName, - E.AccountPassword, - E.MailboxPlanId, - P.MailboxPlan, - E.SubscriberNumber, - E.UserPrincipalName -FROM - ExchangeAccounts AS E -LEFT OUTER JOIN ExchangeMailboxPlans AS P ON E.MailboxPlanId = P.MailboxPlanId -WHERE - E.ItemID = @ItemID AND - E.MailboxPlanId IS NULL AND - E.AccountType IN (1,5) -RETURN - -END -ELSE -IF (@ItemId = 0) -BEGIN -SELECT - E.AccountID, - E.ItemID, - E.AccountType, - E.AccountName, - E.DisplayName, - E.PrimaryEmailAddress, - E.MailEnabledPublicFolder, - E.MailboxManagerActions, - E.SamAccountName, - E.AccountPassword, - E.MailboxPlanId, - P.MailboxPlan, - E.SubscriberNumber, - E.UserPrincipalName -FROM - ExchangeAccounts AS E -LEFT OUTER JOIN ExchangeMailboxPlans AS P ON E.MailboxPlanId = P.MailboxPlanId -WHERE - E.MailboxPlanId = @MailboxPlanId AND - E.AccountType IN (1,5) -END -ELSE -BEGIN -SELECT - E.AccountID, - E.ItemID, - E.AccountType, - E.AccountName, - E.DisplayName, - E.PrimaryEmailAddress, - E.MailEnabledPublicFolder, - E.MailboxManagerActions, - E.SamAccountName, - E.AccountPassword, - E.MailboxPlanId, - P.MailboxPlan, - E.SubscriberNumber, - E.UserPrincipalName -FROM - ExchangeAccounts AS E -LEFT OUTER JOIN ExchangeMailboxPlans AS P ON E.MailboxPlanId = P.MailboxPlanId -WHERE - E.ItemID = @ItemID AND - E.MailboxPlanId = @MailboxPlanId AND - E.AccountType IN (1,5) -RETURN -END -GO - - - - - - -IF NOT EXISTS (SELECT * FROM sys.objects WHERE type_desc = N'SQL_STORED_PROCEDURE' AND name = N'GetExchangeMailboxPlan') -BEGIN -EXEC sp_executesql N'CREATE PROCEDURE [dbo].[GetExchangeMailboxPlan] -( - @MailboxPlanId int -) -AS -SELECT - MailboxPlanId, - ItemID, - MailboxPlan, - EnableActiveSync, - EnableIMAP, - EnableMAPI, - EnableOWA, - EnablePOP, - IsDefault, - IssueWarningPct, - KeepDeletedItemsDays, - MailboxSizeMB, - MaxReceiveMessageSizeKB, - MaxRecipients, - MaxSendMessageSizeKB, - ProhibitSendPct, - ProhibitSendReceivePct, - HideFromAddressBook, - MailboxPlanType -FROM - ExchangeMailboxPlans -WHERE - MailboxPlanId = @MailboxPlanId -RETURN' -END -GO - - - - - - -ALTER PROCEDURE [dbo].[GetExchangeMailboxPlan] -( - @MailboxPlanId int -) -AS -SELECT - MailboxPlanId, - ItemID, - MailboxPlan, - EnableActiveSync, - EnableIMAP, - EnableMAPI, - EnableOWA, - EnablePOP, - IsDefault, - IssueWarningPct, - KeepDeletedItemsDays, - MailboxSizeMB, - MaxReceiveMessageSizeKB, - MaxRecipients, - MaxSendMessageSizeKB, - ProhibitSendPct, - ProhibitSendReceivePct, - HideFromAddressBook, - MailboxPlanType -FROM - ExchangeMailboxPlans -WHERE - MailboxPlanId = @MailboxPlanId -RETURN -GO - - - - - - - - - - - - - - - - - - -IF NOT EXISTS (SELECT * FROM sys.objects WHERE type_desc = N'SQL_STORED_PROCEDURE' AND name = N'GetExchangeMailboxPlans') -BEGIN -EXEC sp_executesql N'CREATE PROCEDURE [dbo].[GetExchangeMailboxPlans] -( - @ItemID int -) -AS -SELECT - MailboxPlanId, - ItemID, - MailboxPlan, - EnableActiveSync, - EnableIMAP, - EnableMAPI, - EnableOWA, - EnablePOP, - IsDefault, - IssueWarningPct, - KeepDeletedItemsDays, - MailboxSizeMB, - MaxReceiveMessageSizeKB, - MaxRecipients, - MaxSendMessageSizeKB, - ProhibitSendPct, - ProhibitSendReceivePct, - HideFromAddressBook, - MailboxPlanType -FROM - ExchangeMailboxPlans -WHERE - ItemID = @ItemID -ORDER BY MailboxPlan -RETURN' -END -GO - - - - - - - - -ALTER PROCEDURE [dbo].[GetExchangeMailboxPlans] -( - @ItemID int -) -AS -SELECT - MailboxPlanId, - ItemID, - MailboxPlan, - EnableActiveSync, - EnableIMAP, - EnableMAPI, - EnableOWA, - EnablePOP, - IsDefault, - IssueWarningPct, - KeepDeletedItemsDays, - MailboxSizeMB, - MaxReceiveMessageSizeKB, - MaxRecipients, - MaxSendMessageSizeKB, - ProhibitSendPct, - ProhibitSendReceivePct, - HideFromAddressBook, - MailboxPlanType -FROM - ExchangeMailboxPlans -WHERE - ItemID = @ItemID -ORDER BY MailboxPlan -RETURN -GO - - - - - - - - - - - - - - - - - -ALTER PROCEDURE [dbo].[GetExchangeOrganizationStatistics] -( - @ItemID int -) -AS - -IF -1 IN (SELECT B.MailboxSizeMB FROM ExchangeAccounts AS A INNER JOIN ExchangeMailboxPlans AS B ON A.MailboxPlanId = B.MailboxPlanId WHERE A.ItemID=@ItemID) -BEGIN -SELECT - (SELECT COUNT(*) FROM ExchangeAccounts WHERE (AccountType = 1 OR AccountType = 5 OR AccountType = 6) AND ItemID = @ItemID) AS CreatedMailboxes, - (SELECT COUNT(*) FROM ExchangeAccounts WHERE AccountType = 2 AND ItemID = @ItemID) AS CreatedContacts, - (SELECT COUNT(*) FROM ExchangeAccounts WHERE AccountType = 3 AND ItemID = @ItemID) AS CreatedDistributionLists, - (SELECT COUNT(*) FROM ExchangeAccounts WHERE AccountType = 4 AND ItemID = @ItemID) AS CreatedPublicFolders, - (SELECT COUNT(*) FROM ExchangeOrganizationDomains WHERE ItemID = @ItemID) AS CreatedDomains, - (SELECT MIN(B.MailboxSizeMB) FROM ExchangeAccounts AS A INNER JOIN ExchangeMailboxPlans AS B ON A.MailboxPlanId = B.MailboxPlanId WHERE A.ItemID=@ItemID) AS UsedDiskSpace -END -ELSE -BEGIN -SELECT - (SELECT COUNT(*) FROM ExchangeAccounts WHERE (AccountType = 1 OR AccountType = 5 OR AccountType = 6) AND ItemID = @ItemID) AS CreatedMailboxes, - (SELECT COUNT(*) FROM ExchangeAccounts WHERE AccountType = 2 AND ItemID = @ItemID) AS CreatedContacts, - (SELECT COUNT(*) FROM ExchangeAccounts WHERE AccountType = 3 AND ItemID = @ItemID) AS CreatedDistributionLists, - (SELECT COUNT(*) FROM ExchangeAccounts WHERE AccountType = 4 AND ItemID = @ItemID) AS CreatedPublicFolders, - (SELECT COUNT(*) FROM ExchangeOrganizationDomains WHERE ItemID = @ItemID) AS CreatedDomains, - (SELECT SUM(B.MailboxSizeMB) FROM ExchangeAccounts AS A INNER JOIN ExchangeMailboxPlans AS B ON A.MailboxPlanId = B.MailboxPlanId WHERE A.ItemID=@ItemID) AS UsedDiskSpace -END - - -RETURN -GO - - - - - - - - - - - - - - - - - - - - -ALTER PROCEDURE [dbo].[GetPackages] -( - @ActorID int, - @UserID int -) -AS - -IF dbo.CheckActorUserRights(@ActorID, @UserID) = 0 -RAISERROR('You are not allowed to access this account', 16, 1) - -SELECT - P.PackageID, - P.ParentPackageID, - P.PackageName, - P.StatusID, - P.PurchaseDate, - - -- server - ISNULL(P.ServerID, 0) AS ServerID, - ISNULL(S.ServerName, 'None') AS ServerName, - ISNULL(S.Comments, '') AS ServerComments, - ISNULL(S.VirtualServer, 1) AS VirtualServer, - - -- hosting plan - P.PlanID, - HP.PlanName, - - -- user - P.UserID, - U.Username, - U.FirstName, - U.LastName, - U.RoleID, - U.Email -FROM Packages AS P -INNER JOIN Users AS U ON P.UserID = U.UserID -INNER JOIN Servers AS S ON P.ServerID = S.ServerID -INNER JOIN HostingPlans AS HP ON P.PlanID = HP.PlanID -WHERE - P.UserID = @UserID -RETURN - -GO - - - - - - - - - - -IF NOT EXISTS (SELECT * FROM sys.objects WHERE type_desc = N'SQL_STORED_PROCEDURE' AND name = N'SetExchangeAccountMailboxplan') -BEGIN -EXEC sp_executesql N'CREATE PROCEDURE [dbo].[SetExchangeAccountMailboxplan] -( - @AccountID int, - @MailboxPlanId int -) -AS - -UPDATE ExchangeAccounts SET - MailboxPlanId = @MailboxPlanId -WHERE - AccountID = @AccountID - -RETURN' -END -GO - - - - - - - - - - - - - -IF NOT EXISTS (SELECT * FROM sys.objects WHERE type_desc = N'SQL_STORED_PROCEDURE' AND name = N'SetOrganizationDefaultExchangeMailboxPlan') -BEGIN -EXEC sp_executesql N'CREATE PROCEDURE [dbo].[SetOrganizationDefaultExchangeMailboxPlan] -( - @ItemId int, - @MailboxPlanId int -) -AS - -UPDATE ExchangeMailboxPlans SET IsDefault=0 WHERE ItemId=@ItemId -UPDATE ExchangeMailboxPlans SET IsDefault=1 WHERE MailboxPlanId=@MailboxPlanId - -RETURN' -END -GO - - - - - - - - - - - - - - - - - - -ALTER PROCEDURE [dbo].[UpdateExchangeAccount] -( - @AccountID int, - @AccountName nvarchar(300), - @DisplayName nvarchar(300), - @PrimaryEmailAddress nvarchar(300), - @AccountType int, - @SamAccountName nvarchar(100), - @MailEnabledPublicFolder bit, - @MailboxManagerActions varchar(200), - @Password varchar(200), - @MailboxPlanId int, - @SubscriberNumber varchar(32) -) -AS - -BEGIN TRAN - -IF (@MailboxPlanId = -1) -BEGIN - SET @MailboxPlanId = NULL -END - -UPDATE ExchangeAccounts SET - AccountName = @AccountName, - DisplayName = @DisplayName, - PrimaryEmailAddress = @PrimaryEmailAddress, - MailEnabledPublicFolder = @MailEnabledPublicFolder, - MailboxManagerActions = @MailboxManagerActions, - AccountType =@AccountType, - SamAccountName = @SamAccountName, - MailboxPlanId = @MailboxPlanId, - SubscriberNumber = @SubscriberNumber - -WHERE - AccountID = @AccountID - -IF (@@ERROR <> 0 ) - BEGIN - ROLLBACK TRANSACTION - RETURN -1 - END - -UPDATE ExchangeAccounts SET - AccountPassword = @Password WHERE AccountID = @AccountID AND @Password IS NOT NULL - -IF (@@ERROR <> 0 ) - BEGIN - ROLLBACK TRANSACTION - RETURN -1 - END -COMMIT TRAN -RETURN -GO - - - - - - - - - - -ALTER PROCEDURE [dbo].[GetExchangeAccount] -( - @ItemID int, - @AccountID int -) -AS -SELECT - E.AccountID, - E.ItemID, - E.AccountType, - E.AccountName, - E.DisplayName, - E.PrimaryEmailAddress, - E.MailEnabledPublicFolder, - E.MailboxManagerActions, - E.SamAccountName, - E.AccountPassword, - E.MailboxPlanId, - P.MailboxPlan, - E.SubscriberNumber, - E.UserPrincipalName -FROM - ExchangeAccounts AS E -LEFT OUTER JOIN ExchangeMailboxPlans AS P ON E.MailboxPlanId = P.MailboxPlanId -WHERE - E.ItemID = @ItemID AND - E.AccountID = @AccountID -RETURN -GO - - - - - - - - - -ALTER PROCEDURE [dbo].[GetExchangeMailboxes] - @ItemID int -AS -BEGIN -SELECT - AccountID, - ItemID, - AccountType, - AccountName, - DisplayName, - PrimaryEmailAddress, - MailEnabledPublicFolder, - SubscriberNumber, - UserPrincipalName -FROM - ExchangeAccounts -WHERE - ItemID = @ItemID AND - (AccountType =1 OR AccountType=5 OR AccountType=6) -ORDER BY 1 - -END - -GO - - - - - - - - - - - - -ALTER PROCEDURE [dbo].[SearchExchangeAccount] -( - @ActorID int, - @AccountType int, - @PrimaryEmailAddress nvarchar(300) -) -AS - -DECLARE @PackageID int -DECLARE @ItemID int -DECLARE @AccountID int - -SELECT - @AccountID = AccountID, - @ItemID = ItemID -FROM ExchangeAccounts -WHERE PrimaryEmailAddress = @PrimaryEmailAddress -AND AccountType = @AccountType - - --- check space rights -SELECT @PackageID = PackageID FROM ServiceItems -WHERE ItemID = @ItemID - -IF dbo.CheckActorPackageRights(@ActorID, @PackageID) = 0 -RAISERROR('You are not allowed to access this package', 16, 1) - -SELECT - AccountID, - ItemID, - @PackageID AS PackageID, - AccountType, - AccountName, - DisplayName, - PrimaryEmailAddress, - MailEnabledPublicFolder, - MailboxManagerActions, - SamAccountName, - AccountPassword, - SubscriberNumber, - UserPrincipalName -FROM ExchangeAccounts -WHERE AccountID = @AccountID - -RETURN - -GO - - - - - - - - - - - -ALTER PROCEDURE [dbo].[SearchExchangeAccounts] -( - @ActorID int, - @ItemID int, - @IncludeMailboxes bit, - @IncludeContacts bit, - @IncludeDistributionLists bit, - @IncludeRooms bit, - @IncludeEquipment bit, - @FilterColumn nvarchar(50) = '', - @FilterValue nvarchar(50) = '', - @SortColumn nvarchar(50) -) -AS -DECLARE @PackageID int -SELECT @PackageID = PackageID FROM ServiceItems -WHERE ItemID = @ItemID - --- check rights -IF dbo.CheckActorPackageRights(@ActorID, @PackageID) = 0 -RAISERROR('You are not allowed to access this package', 16, 1) - --- start -DECLARE @condition nvarchar(700) -SET @condition = ' -((@IncludeMailboxes = 1 AND EA.AccountType = 1) -OR (@IncludeContacts = 1 AND EA.AccountType = 2) -OR (@IncludeDistributionLists = 1 AND EA.AccountType = 3) -OR (@IncludeRooms = 1 AND EA.AccountType = 5) -OR (@IncludeEquipment = 1 AND EA.AccountType = 6)) -AND EA.ItemID = @ItemID -' - -IF @FilterColumn <> '' AND @FilterColumn IS NOT NULL -AND @FilterValue <> '' AND @FilterValue IS NOT NULL -SET @condition = @condition + ' AND ' + @FilterColumn + ' LIKE ''' + @FilterValue + '''' - -IF @SortColumn IS NULL OR @SortColumn = '' -SET @SortColumn = 'EA.DisplayName ASC' - -DECLARE @sql nvarchar(3500) - -set @sql = ' -SELECT - EA.AccountID, - EA.ItemID, - EA.AccountType, - EA.AccountName, - EA.DisplayName, - EA.PrimaryEmailAddress, - EA.MailEnabledPublicFolder, - EA.SubscriberNumber, - EA.UserPrincipalName -FROM ExchangeAccounts AS EA -WHERE ' + @condition - -print @sql - -exec sp_executesql @sql, N'@ItemID int, @IncludeMailboxes int, @IncludeContacts int, - @IncludeDistributionLists int, @IncludeRooms bit, @IncludeEquipment bit', -@ItemID, @IncludeMailboxes, @IncludeContacts, @IncludeDistributionLists, @IncludeRooms, @IncludeEquipment - -RETURN - -GO - - - - - - - - - - - - - - - - - - -ALTER PROCEDURE [dbo].[SearchOrganizationAccounts] -( - @ActorID int, - @ItemID int, - @FilterColumn nvarchar(50) = '', - @FilterValue nvarchar(50) = '', - @SortColumn nvarchar(50), - @IncludeMailboxes bit -) -AS -DECLARE @PackageID int -SELECT @PackageID = PackageID FROM ServiceItems -WHERE ItemID = @ItemID - --- check rights -IF dbo.CheckActorPackageRights(@ActorID, @PackageID) = 0 -RAISERROR('You are not allowed to access this package', 16, 1) - --- start -DECLARE @condition nvarchar(700) -SET @condition = ' -(EA.AccountType = 7 OR (EA.AccountType = 1 AND @IncludeMailboxes = 1) ) -AND EA.ItemID = @ItemID -' - -IF @FilterColumn <> '' AND @FilterColumn IS NOT NULL -AND @FilterValue <> '' AND @FilterValue IS NOT NULL -SET @condition = @condition + ' AND ' + @FilterColumn + ' LIKE ''' + @FilterValue + '''' - -IF @SortColumn IS NULL OR @SortColumn = '' -SET @SortColumn = 'EA.DisplayName ASC' - -DECLARE @sql nvarchar(3500) - -set @sql = ' -SELECT - EA.AccountID, - EA.ItemID, - EA.AccountType, - EA.AccountName, - EA.DisplayName, - EA.PrimaryEmailAddress, - EA.SubscriberNumber, - EA.UserPrincipalName -FROM ExchangeAccounts AS EA -WHERE ' + @condition - -print @sql - -exec sp_executesql @sql, N'@ItemID int, @IncludeMailboxes bit', -@ItemID, @IncludeMailboxes - -RETURN - -GO - - - - - - - - - - -IF NOT EXISTS (SELECT * FROM sys.objects WHERE type_desc = N'SQL_STORED_PROCEDURE' AND name = N'AddLyncUser') -BEGIN -EXEC sp_executesql N'CREATE PROCEDURE [dbo].[AddLyncUser] - @AccountID int, - @LyncUserPlanID int -AS -INSERT INTO - dbo.LyncUsers - (AccountID, - LyncUserPlanID, - CreatedDate, - ModifiedDate) -VALUES -( - @AccountID, - @LyncUserPlanID, - getdate(), - getdate() -)' -END -GO - - - -IF NOT EXISTS (SELECT * FROM sys.objects WHERE type_desc = N'SQL_STORED_PROCEDURE' AND name = N'GetLyncUsersByPlanId') -BEGIN -EXEC sp_executesql N'CREATE PROCEDURE [dbo].[GetLyncUsersByPlanId] -( - @ItemID int, - @PlanId int -) -AS - - SELECT - ea.AccountID, - ea.ItemID, - ea.AccountName, - ea.DisplayName, - ea.UserPrincipalName, - ea.SamAccountName, - ou.LyncUserPlanId, - lp.LyncUserPlanName - FROM - ExchangeAccounts ea - INNER JOIN - LyncUsers ou - INNER JOIN - LyncUserPlans lp - ON - ou.LyncUserPlanId = lp.LyncUserPlanId - ON - ea.AccountID = ou.AccountID - WHERE - ea.ItemID = @ItemID AND - ou.LyncUserPlanId = @PlanId' -END -GO - - - - - - - -ALTER PROCEDURE [dbo].[GetLyncUsersByPlanId] -( - @ItemID int, - @PlanId int -) -AS - - SELECT - ea.AccountID, - ea.ItemID, - ea.AccountName, - ea.DisplayName, - ea.UserPrincipalName, - ea.SamAccountName, - ou.LyncUserPlanId, - lp.LyncUserPlanName - FROM - ExchangeAccounts ea - INNER JOIN - LyncUsers ou - INNER JOIN - LyncUserPlans lp - ON - ou.LyncUserPlanId = lp.LyncUserPlanId - ON - ea.AccountID = ou.AccountID - WHERE - ea.ItemID = @ItemID AND - ou.LyncUserPlanId = @PlanId -GO - - - - - - - -IF NOT EXISTS (SELECT * FROM sys.objects WHERE type_desc = N'SQL_STORED_PROCEDURE' AND name = N'AddLyncUserPlan') -BEGIN -EXEC sp_executesql N'CREATE PROCEDURE [dbo].[AddLyncUserPlan] -( - @LyncUserPlanId int OUTPUT, - @ItemID int, - @LyncUserPlanName nvarchar(300), - @LyncUserPlanType int, - @IM bit, - @Mobility bit, - @MobilityEnableOutsideVoice bit, - @Federation bit, - @Conferencing bit, - @EnterpriseVoice bit, - @VoicePolicy int, - @IsDefault bit -) -AS - - - -IF (((SELECT Count(*) FROM LyncUserPlans WHERE ItemId = @ItemID) = 0) AND (@LyncUserPlanType=0)) -BEGIN - SET @IsDefault = 1 -END -ELSE -BEGIN - IF ((@IsDefault = 1) AND (@LyncUserPlanType=0)) - BEGIN - UPDATE LyncUserPlans SET IsDefault = 0 WHERE ItemID = @ItemID - END -END - - -INSERT INTO LyncUserPlans -( - ItemID, - LyncUserPlanName, - LyncUserPlanType, - IM, - Mobility, - MobilityEnableOutsideVoice, - Federation, - Conferencing, - EnterpriseVoice, - VoicePolicy, - IsDefault -) -VALUES -( - @ItemID, - @LyncUserPlanName, - @LyncUserPlanType, - @IM, - @Mobility, - @MobilityEnableOutsideVoice, - @Federation, - @Conferencing, - @EnterpriseVoice, - @VoicePolicy, - @IsDefault -) - -SET @LyncUserPlanId = SCOPE_IDENTITY() - -RETURN' -END -GO - - - - - - - - - -ALTER PROCEDURE [dbo].[AddLyncUserPlan] -( - @LyncUserPlanId int OUTPUT, - @ItemID int, - @LyncUserPlanName nvarchar(300), - @LyncUserPlanType int, - @IM bit, - @Mobility bit, - @MobilityEnableOutsideVoice bit, - @Federation bit, - @Conferencing bit, - @EnterpriseVoice bit, - @VoicePolicy int, - @IsDefault bit -) -AS - -IF (((SELECT Count(*) FROM LyncUserPlans WHERE ItemId = @ItemID) = 0) AND (@LyncUserPlanType=0)) -BEGIN - SET @IsDefault = 1 -END -ELSE -BEGIN - IF ((@IsDefault = 1) AND (@LyncUserPlanType=0)) - BEGIN - UPDATE LyncUserPlans SET IsDefault = 0 WHERE ItemID = @ItemID - END -END - - -INSERT INTO LyncUserPlans -( - ItemID, - LyncUserPlanName, - LyncUserPlanType, - IM, - Mobility, - MobilityEnableOutsideVoice, - Federation, - Conferencing, - EnterpriseVoice, - VoicePolicy, - IsDefault -) -VALUES -( - @ItemID, - @LyncUserPlanName, - @LyncUserPlanType, - @IM, - @Mobility, - @MobilityEnableOutsideVoice, - @Federation, - @Conferencing, - @EnterpriseVoice, - @VoicePolicy, - @IsDefault -) - -SET @LyncUserPlanId = SCOPE_IDENTITY() - -RETURN -GO - - -IF NOT EXISTS (SELECT * FROM sys.objects WHERE type_desc = N'SQL_STORED_PROCEDURE' AND name = N'CheckLyncUserExists') -BEGIN -EXEC sp_executesql N'CREATE PROCEDURE [dbo].[CheckLyncUserExists] - @AccountID int -AS - SELECT - COUNT(AccountID) - FROM - dbo.LyncUsers - WHERE AccountID = @AccountID' -END -GO - - - -IF NOT EXISTS (SELECT * FROM sys.objects WHERE type_desc = N'SQL_STORED_PROCEDURE' AND name = N'CheckLyncUserExists') -BEGIN -EXEC sp_executesql N'CREATE PROCEDURE [dbo].[CheckLyncUserExists] - @AccountID int -AS -BEGIN - SELECT - COUNT(AccountID) - FROM - dbo.LyncUsers - WHERE AccountID = @AccountID' -END -GO - - -IF NOT EXISTS (SELECT * FROM sys.objects WHERE type_desc = N'SQL_STORED_PROCEDURE' AND name = N'DeleteLyncUser') -BEGIN -EXEC sp_executesql N'CREATE PROCEDURE [dbo].[DeleteLyncUser] -( - @AccountId int -) -AS - -DELETE FROM - LyncUsers -WHERE - AccountId = @AccountId - -RETURN' -END -GO - - - - - - - - -IF NOT EXISTS (SELECT * FROM sys.objects WHERE type_desc = N'SQL_STORED_PROCEDURE' AND name = N'DeleteLyncUserPlan') -BEGIN -EXEC sp_executesql N'CREATE PROCEDURE [dbo].[DeleteLyncUserPlan] -( - @LyncUserPlanId int -) -AS - --- delete lyncuserplan -DELETE FROM LyncUserPlans -WHERE LyncUserPlanId = @LyncUserPlanId - -RETURN' -END -GO - - - - - - - - - -IF NOT EXISTS (SELECT * FROM sys.objects WHERE type_desc = N'SQL_STORED_PROCEDURE' AND name = N'GetLyncUserPlan') -BEGIN -EXEC sp_executesql N'CREATE PROCEDURE [dbo].[GetLyncUserPlan] -( - @LyncUserPlanId int -) -AS -SELECT - LyncUserPlanId, - ItemID, - LyncUserPlanName, - LyncUserPlanType, - IM, - Mobility, - MobilityEnableOutsideVoice, - Federation, - Conferencing, - EnterpriseVoice, - VoicePolicy, - IsDefault -FROM - LyncUserPlans -WHERE - LyncUserPlanId = @LyncUserPlanId -RETURN' -END -GO - - - - - -ALTER PROCEDURE [dbo].[GetLyncUserPlan] -( - @LyncUserPlanId int -) -AS -SELECT - LyncUserPlanId, - ItemID, - LyncUserPlanName, - LyncUserPlanType, - IM, - Mobility, - MobilityEnableOutsideVoice, - Federation, - Conferencing, - EnterpriseVoice, - VoicePolicy, - IsDefault -FROM - LyncUserPlans -WHERE - LyncUserPlanId = @LyncUserPlanId -RETURN -GO - - - - - -IF NOT EXISTS (SELECT * FROM sys.objects WHERE type_desc = N'SQL_STORED_PROCEDURE' AND name = N'GetLyncUserPlanByAccountId') -BEGIN -EXEC sp_executesql N'CREATE PROCEDURE [dbo].[GetLyncUserPlanByAccountId] -( - @AccountID int -) -AS -SELECT - LyncUserPlanId, - ItemID, - LyncUserPlanName, - LyncUserPlanType, - IM, - Mobility, - MobilityEnableOutsideVoice, - Federation, - Conferencing, - EnterpriseVoice, - VoicePolicy, - IsDefault -FROM - LyncUserPlans -WHERE - LyncUserPlanId IN (SELECT LyncUserPlanId FROM LyncUsers WHERE AccountID = @AccountID) -RETURN' -END -GO - - - - - - - -ALTER PROCEDURE [dbo].[GetLyncUserPlanByAccountId] -( - @AccountID int -) -AS -SELECT - LyncUserPlanId, - ItemID, - LyncUserPlanName, - LyncUserPlanType, - IM, - Mobility, - MobilityEnableOutsideVoice, - Federation, - Conferencing, - EnterpriseVoice, - VoicePolicy, - IsDefault -FROM - LyncUserPlans -WHERE - LyncUserPlanId IN (SELECT LyncUserPlanId FROM LyncUsers WHERE AccountID = @AccountID) -RETURN -GO - - - - -IF NOT EXISTS (SELECT * FROM sys.objects WHERE type_desc = N'SQL_STORED_PROCEDURE' AND name = N'GetLyncUserPlans') -BEGIN -EXEC sp_executesql N'CREATE PROCEDURE [dbo].[GetLyncUserPlans] -( - @ItemID int -) -AS -SELECT - LyncUserPlanId, - ItemID, - LyncUserPlanName, - LyncUserPlanType, - IM, - Mobility, - MobilityEnableOutsideVoice, - Federation, - Conferencing, - EnterpriseVoice, - VoicePolicy, - IsDefault -FROM - LyncUserPlans -WHERE - ItemID = @ItemID -ORDER BY LyncUserPlanName -RETURN' -END -GO - - - - - - -ALTER PROCEDURE [dbo].[GetLyncUserPlans] -( - @ItemID int -) -AS -SELECT - LyncUserPlanId, - ItemID, - LyncUserPlanName, - LyncUserPlanType, - IM, - Mobility, - MobilityEnableOutsideVoice, - Federation, - Conferencing, - EnterpriseVoice, - VoicePolicy, - IsDefault -FROM - LyncUserPlans -WHERE - ItemID = @ItemID -ORDER BY LyncUserPlanName -RETURN -GO - - -IF NOT EXISTS(select 1 from sys.columns COLS INNER JOIN sys.objects OBJS ON OBJS.object_id=COLS.object_id and OBJS.type='U' AND OBJS.name='LyncUsers' AND COLS.name='SipAddress') -BEGIN -ALTER TABLE [dbo].[LyncUsers] ADD - [SipAddress] [nvarchar] (300) COLLATE Latin1_General_CI_AS NULL -END -GO - - - -IF NOT EXISTS (SELECT * FROM sys.objects WHERE type_desc = N'SQL_STORED_PROCEDURE' AND name = N'GetLyncUsers') -BEGIN -EXEC sp_executesql N'CREATE PROCEDURE [dbo].[GetLyncUsers] -( - @ItemID int, - @SortColumn nvarchar(40), - @SortDirection nvarchar(20), - @StartRow int, - @Count int -) -AS - -CREATE TABLE #TempLyncUsers -( - [ID] [int] IDENTITY(1,1) NOT NULL, - [AccountID] [int], - [ItemID] [int] NOT NULL, - [AccountName] [nvarchar](300) NOT NULL, - [DisplayName] [nvarchar](300) NOT NULL, - [UserPrincipalName] [nvarchar](300) NULL, - [SipAddress] [nvarchar](300) NULL, - [SamAccountName] [nvarchar](100) NULL, - [LyncUserPlanId] [int] NOT NULL, - [LyncUserPlanName] [nvarchar] (300) NOT NULL, -) - - -DECLARE @condition nvarchar(700) -SET @condition = '''' - -IF (@SortColumn = ''DisplayName'') -BEGIN - SET @condition = ''ORDER BY ea.DisplayName'' -END - -IF (@SortColumn = ''UserPrincipalName'') -BEGIN - SET @condition = ''ORDER BY ea.UserPrincipalName'' -END - -IF (@SortColumn = ''SipAddress'') -BEGIN - SET @condition = ''ORDER BY ou.SipAddress'' -END - - -IF (@SortColumn = ''LyncUserPlanName'') -BEGIN - SET @condition = ''ORDER BY lp.LyncUserPlanName'' -END - -DECLARE @sql nvarchar(3500) - -set @sql = '' - INSERT INTO - #TempLyncUsers - SELECT - ea.AccountID, - ea.ItemID, - ea.AccountName, - ea.DisplayName, - ea.UserPrincipalName, - ou.SipAddress, - ea.SamAccountName, - ou.LyncUserPlanId, - lp.LyncUserPlanName - FROM - ExchangeAccounts ea - INNER JOIN - LyncUsers ou - INNER JOIN - LyncUserPlans lp - ON - ou.LyncUserPlanId = lp.LyncUserPlanId - ON - ea.AccountID = ou.AccountID - WHERE - ea.ItemID = @ItemID '' + @condition - -exec sp_executesql @sql, N''@ItemID int'',@ItemID - -DECLARE @RetCount int -SELECT @RetCount = COUNT(ID) FROM #TempLyncUsers - -IF (@SortDirection = ''ASC'') -BEGIN - SELECT * FROM #TempLyncUsers - WHERE ID > @StartRow AND ID <= (@StartRow + @Count) -END -ELSE -BEGIN - IF @SortColumn <> '''' AND @SortColumn IS NOT NULL - BEGIN - IF (@SortColumn = ''DisplayName'') - BEGIN - SELECT * FROM #TempLyncUsers - WHERE ID >@RetCount - @Count - @StartRow AND ID <= @RetCount- @StartRow ORDER BY DisplayName DESC - END - IF (@SortColumn = ''UserPrincipalName'') - BEGIN - SELECT * FROM #TempLyncUsers - WHERE ID >@RetCount - @Count - @StartRow AND ID <= @RetCount- @StartRow ORDER BY UserPrincipalName DESC - END - IF (@SortColumn = ''SipAddress'') - BEGIN - SELECT * FROM #TempLyncUsers - WHERE ID >@RetCount - @Count - @StartRow AND ID <= @RetCount- @StartRow ORDER BY SipAddress DESC - END - - IF (@SortColumn = ''LyncUserPlanName'') - BEGIN - SELECT * FROM #TempLyncUsers - WHERE ID >@RetCount - @Count - @StartRow AND ID <= @RetCount- @StartRow ORDER BY LyncUserPlanName DESC - END - END - ELSE - BEGIN - SELECT * FROM #TempLyncUsers - WHERE ID >@RetCount - @Count - @StartRow AND ID <= @RetCount- @StartRow ORDER BY UserPrincipalName DESC - END - - -END - -DROP TABLE #TempLyncUsers' -END -GO - - - - -ALTER PROCEDURE [dbo].[GetLyncUsers] -( - @ItemID int, - @SortColumn nvarchar(40), - @SortDirection nvarchar(20), - @StartRow int, - @Count int -) -AS - -CREATE TABLE #TempLyncUsers -( - [ID] [int] IDENTITY(1,1) NOT NULL, - [AccountID] [int], - [ItemID] [int] NOT NULL, - [AccountName] [nvarchar](300) NOT NULL, - [DisplayName] [nvarchar](300) NOT NULL, - [UserPrincipalName] [nvarchar](300) NULL, - [SipAddress] [nvarchar](300) NULL, - [SamAccountName] [nvarchar](100) NULL, - [LyncUserPlanId] [int] NOT NULL, - [LyncUserPlanName] [nvarchar] (300) NOT NULL, -) - - -DECLARE @condition nvarchar(700) -SET @condition = '' - -IF (@SortColumn = 'DisplayName') -BEGIN - SET @condition = 'ORDER BY ea.DisplayName' -END - -IF (@SortColumn = 'UserPrincipalName') -BEGIN - SET @condition = 'ORDER BY ea.UserPrincipalName' -END - -IF (@SortColumn = 'SipAddress') -BEGIN - SET @condition = 'ORDER BY ou.SipAddress' -END - - -IF (@SortColumn = 'LyncUserPlanName') -BEGIN - SET @condition = 'ORDER BY lp.LyncUserPlanName' -END - -DECLARE @sql nvarchar(3500) - -set @sql = '' - INSERT INTO - #TempLyncUsers - SELECT - ea.AccountID, - ea.ItemID, - ea.AccountName, - ea.DisplayName, - ea.UserPrincipalName, - ou.SipAddress, - ea.SamAccountName, - ou.LyncUserPlanId, - lp.LyncUserPlanName - FROM - ExchangeAccounts ea - INNER JOIN - LyncUsers ou - INNER JOIN - LyncUserPlans lp - ON - ou.LyncUserPlanId = lp.LyncUserPlanId - ON - ea.AccountID = ou.AccountID - WHERE - ea.ItemID = @ItemID + @condition - -exec sp_executesql @sql, N'@ItemID int',@ItemID - -DECLARE @RetCount int -SELECT @RetCount = COUNT(ID) FROM #TempLyncUsers - -IF (@SortDirection = 'ASC') -BEGIN - SELECT * FROM #TempLyncUsers - WHERE ID > @StartRow AND ID <= (@StartRow + @Count) -END -ELSE -BEGIN - IF @SortColumn <> '' AND @SortColumn IS NOT NULL - BEGIN - IF (@SortColumn = 'DisplayName') - BEGIN - SELECT * FROM #TempLyncUsers - WHERE ID >@RetCount - @Count - @StartRow AND ID <= @RetCount- @StartRow ORDER BY DisplayName DESC - END - IF (@SortColumn = 'UserPrincipalName') - BEGIN - SELECT * FROM #TempLyncUsers - WHERE ID >@RetCount - @Count - @StartRow AND ID <= @RetCount- @StartRow ORDER BY UserPrincipalName DESC - END - - IF (@SortColumn = 'SipAddress') - BEGIN - SELECT * FROM #TempLyncUsers - WHERE ID >@RetCount - @Count - @StartRow AND ID <= @RetCount- @StartRow ORDER BY SipAddress DESC - END - - IF (@SortColumn = 'LyncUserPlanName') - BEGIN - SELECT * FROM #TempLyncUsers - WHERE ID >@RetCount - @Count - @StartRow AND ID <= @RetCount- @StartRow ORDER BY LyncUserPlanName DESC - END - END - ELSE - BEGIN - SELECT * FROM #TempLyncUsers - WHERE ID >@RetCount - @Count - @StartRow AND ID <= @RetCount- @StartRow ORDER BY UserPrincipalName DESC - END - - -END - -DROP TABLE #TempLyncUsers -GO - - - - - - - - - - - -IF NOT EXISTS (SELECT * FROM sys.objects WHERE type_desc = N'SQL_STORED_PROCEDURE' AND name = N'GetLyncUsersCount') -BEGIN -EXEC sp_executesql N'CREATE PROCEDURE [dbo].[GetLyncUsersCount] -( - @ItemID int -) -AS - -SELECT - COUNT(ea.AccountID) -FROM - ExchangeAccounts ea -INNER JOIN - LyncUsers ou -ON - ea.AccountID = ou.AccountID -WHERE - ea.ItemID = @ItemID' -END -GO - - - - - - - - -IF NOT EXISTS (SELECT * FROM sys.objects WHERE type_desc = N'SQL_STORED_PROCEDURE' AND name = N'SetLyncUserLyncUserPlan') -BEGIN -EXEC sp_executesql N'CREATE PROCEDURE [dbo].[SetLyncUserLyncUserPlan] -( - @AccountID int, - @LyncUserPlanId int -) -AS - -UPDATE LyncUsers SET - LyncUserPlanId = @LyncUserPlanId -WHERE - AccountID = @AccountID - -RETURN' -END -GO - - - - - - - - - - - - -IF NOT EXISTS (SELECT * FROM sys.objects WHERE type_desc = N'SQL_STORED_PROCEDURE' AND name = N'SetOrganizationDefaultLyncUserPlan') -BEGIN -EXEC sp_executesql N'CREATE PROCEDURE [dbo].[SetOrganizationDefaultLyncUserPlan] -( - @ItemId int, - @LyncUserPlanId int -) -AS - -UPDATE LyncUserPlans SET IsDefault=0 WHERE ItemId=@ItemId -UPDATE LyncUserPlans SET IsDefault=1 WHERE LyncUserPlanId=@LyncUserPlanId - -RETURN' -END -GO - - - - - - - - - - - - - - - -ALTER PROCEDURE [dbo].[GetHostingPlanQuotas] -( - @ActorID int, - @PlanID int, - @PackageID int, - @ServerID int -) -AS - --- check rights -IF dbo.CheckActorParentPackageRights(@ActorID, @PackageID) = 0 -RAISERROR('You are not allowed to access this package', 16, 1) - -DECLARE @IsAddon bit - -IF @ServerID = 0 -SELECT @ServerID = ServerID FROM Packages -WHERE PackageID = @PackageID - --- get resource groups -SELECT - RG.GroupID, - RG.GroupName, - CASE - WHEN HPR.CalculateDiskSpace IS NULL THEN CAST(0 as bit) - ELSE CAST(1 as bit) - END AS Enabled, - dbo.GetPackageAllocatedResource(@PackageID, RG.GroupID, @ServerID) AS ParentEnabled, - ISNULL(HPR.CalculateDiskSpace, 1) AS CalculateDiskSpace, - ISNULL(HPR.CalculateBandwidth, 1) AS CalculateBandwidth -FROM ResourceGroups AS RG -LEFT OUTER JOIN HostingPlanResources AS HPR ON RG.GroupID = HPR.GroupID AND HPR.PlanID = @PlanID -WHERE (RG.ShowGroup = 1) -ORDER BY RG.GroupOrder - --- get quotas by groups -SELECT - Q.QuotaID, - Q.GroupID, - Q.QuotaName, - Q.QuotaDescription, - Q.QuotaTypeID, - ISNULL(HPQ.QuotaValue, 0) AS QuotaValue, - dbo.GetPackageAllocatedQuota(@PackageID, Q.QuotaID) AS ParentQuotaValue -FROM Quotas AS Q -LEFT OUTER JOIN HostingPlanQuotas AS HPQ ON Q.QuotaID = HPQ.QuotaID AND HPQ.PlanID = @PlanID -WHERE Q.HideQuota IS NULL OR Q.HideQuota = 0 -ORDER BY Q.QuotaOrder -RETURN -GO - - - - - - - - - - - - - - -ALTER PROCEDURE [dbo].[GetRawServicesByServerID] -( - @ActorID int, - @ServerID int -) -AS - --- check rights -DECLARE @IsAdmin bit -SET @IsAdmin = dbo.CheckIsUserAdmin(@ActorID) - --- resource groups -SELECT - GroupID, - GroupName -FROM ResourceGroups -WHERE @IsAdmin = 1 AND (ShowGroup = 1) -ORDER BY GroupOrder - --- services -SELECT - S.ServiceID, - S.ServerID, - S.ServiceName, - S.Comments, - RG.GroupID, - PROV.DisplayName AS ProviderName -FROM Services AS S -INNER JOIN Providers AS PROV ON S.ProviderID = PROV.ProviderID -INNER JOIN ResourceGroups AS RG ON PROV.GroupID = RG.GroupID -WHERE - S.ServerID = @ServerID - AND @IsAdmin = 1 -ORDER BY RG.GroupOrder - -RETURN -GO - - - - - - - - - - - - - -ALTER PROCEDURE [dbo].[GetVirtualServices] -( - @ActorID int, - @ServerID int -) -AS - --- check rights -DECLARE @IsAdmin bit -SET @IsAdmin = dbo.CheckIsUserAdmin(@ActorID) - --- virtual groups -SELECT - VRG.VirtualGroupID, - RG.GroupID, - RG.GroupName, - ISNULL(VRG.DistributionType, 1) AS DistributionType, - ISNULL(VRG.BindDistributionToPrimary, 1) AS BindDistributionToPrimary -FROM ResourceGroups AS RG -LEFT OUTER JOIN VirtualGroups AS VRG ON RG.GroupID = VRG.GroupID AND VRG.ServerID = @ServerID -WHERE - @IsAdmin = 1 AND (ShowGroup = 1) -ORDER BY RG.GroupOrder - --- services -SELECT - VS.ServiceID, - S.ServiceName, - S.Comments, - P.GroupID, - P.DisplayName, - SRV.ServerName -FROM VirtualServices AS VS -INNER JOIN Services AS S ON VS.ServiceID = S.ServiceID -INNER JOIN Servers AS SRV ON S.ServerID = SRV.ServerID -INNER JOIN Providers AS P ON S.ProviderID = P.ProviderID -WHERE - VS.ServerID = @ServerID - AND @IsAdmin = 1 - -RETURN -GO - - - - - - - - -ALTER PROCEDURE [dbo].[AddUser] -( - @ActorID int, - @UserID int OUTPUT, - @OwnerID int, - @RoleID int, - @StatusID int, - @SubscriberNumber nvarchar(32), - @LoginStatusID int, - @IsDemo bit, - @IsPeer bit, - @Comments ntext, - @Username nvarchar(50), - @Password nvarchar(200), - @FirstName nvarchar(50), - @LastName nvarchar(50), - @Email nvarchar(255), - @SecondaryEmail nvarchar(255), - @Address nvarchar(200), - @City nvarchar(50), - @State nvarchar(50), - @Country nvarchar(50), - @Zip varchar(20), - @PrimaryPhone varchar(30), - @SecondaryPhone varchar(30), - @Fax varchar(30), - @InstantMessenger nvarchar(200), - @HtmlMail bit, - @CompanyName nvarchar(100), - @EcommerceEnabled bit -) -AS - --- check if the user already exists -IF EXISTS(SELECT UserID FROM Users WHERE Username = @Username) -BEGIN - SET @UserID = -1 - RETURN -END - --- check actor rights -IF dbo.CanCreateUser(@ActorID, @OwnerID) = 0 -BEGIN - SET @UserID = -2 - RETURN -END - -INSERT INTO Users -( - OwnerID, - RoleID, - StatusID, - SubscriberNumber, - LoginStatusID, - Created, - Changed, - IsDemo, - IsPeer, - Comments, - Username, - Password, - FirstName, - LastName, - Email, - SecondaryEmail, - Address, - City, - State, - Country, - Zip, - PrimaryPhone, - SecondaryPhone, - Fax, - InstantMessenger, - HtmlMail, - CompanyName, - EcommerceEnabled -) -VALUES -( - @OwnerID, - @RoleID, - @StatusID, - @SubscriberNumber, - @LoginStatusID, - GetDate(), - GetDate(), - @IsDemo, - @IsPeer, - @Comments, - @Username, - @Password, - @FirstName, - @LastName, - @Email, - @SecondaryEmail, - @Address, - @City, - @State, - @Country, - @Zip, - @PrimaryPhone, - @SecondaryPhone, - @Fax, - @InstantMessenger, - @HtmlMail, - @CompanyName, - @EcommerceEnabled -) - -SET @UserID = SCOPE_IDENTITY() - -RETURN -GO - - - - - - -ALTER PROCEDURE [dbo].[GetUserById] -( - @ActorID int, - @UserID int -) -AS - -- user can retrieve his own account, his users accounts - -- and his reseller account (without pasword) - SELECT - U.UserID, - U.RoleID, - U.StatusID, - U.SubscriberNumber, - U.LoginStatusId, - U.FailedLogins, - U.OwnerID, - U.Created, - U.Changed, - U.IsDemo, - U.Comments, - U.IsPeer, - U.Username, - CASE WHEN dbo.CanGetUserPassword(@ActorID, @UserID) = 1 THEN U.Password - ELSE '' END AS Password, - U.FirstName, - U.LastName, - U.Email, - U.SecondaryEmail, - U.Address, - U.City, - U.State, - U.Country, - U.Zip, - U.PrimaryPhone, - U.SecondaryPhone, - U.Fax, - U.InstantMessenger, - U.HtmlMail, - U.CompanyName, - U.EcommerceEnabled, - U.[AdditionalParams] - FROM Users AS U - WHERE U.UserID = @UserID - AND dbo.CanGetUserDetails(@ActorID, @UserID) = 1 -- actor user rights - - RETURN -GO - - - - - - - - - - - - - -ALTER PROCEDURE [dbo].[GetUserByIdInternally] -( - @UserID int -) -AS - SELECT - U.UserID, - U.RoleID, - U.StatusID, - U.SubscriberNumber, - U.LoginStatusId, - U.FailedLogins, - U.OwnerID, - U.Created, - U.Changed, - U.IsDemo, - U.Comments, - U.IsPeer, - U.Username, - U.Password, - U.FirstName, - U.LastName, - U.Email, - U.SecondaryEmail, - U.Address, - U.City, - U.State, - U.Country, - U.Zip, - U.PrimaryPhone, - U.SecondaryPhone, - U.Fax, - U.InstantMessenger, - U.HtmlMail, - U.CompanyName, - U.EcommerceEnabled, - U.[AdditionalParams] - FROM Users AS U - WHERE U.UserID = @UserID - - RETURN - -GO - - - - - - - - - - -ALTER PROCEDURE [dbo].[GetUserByUsername] -( - @ActorID int, - @Username nvarchar(50) -) -AS - - SELECT - U.UserID, - U.RoleID, - U.StatusID, - U.SubscriberNumber, - U.LoginStatusId, - U.FailedLogins, - U.OwnerID, - U.Created, - U.Changed, - U.IsDemo, - U.Comments, - U.IsPeer, - U.Username, - CASE WHEN dbo.CanGetUserPassword(@ActorID, UserID) = 1 THEN U.Password - ELSE '' END AS Password, - U.FirstName, - U.LastName, - U.Email, - U.SecondaryEmail, - U.Address, - U.City, - U.State, - U.Country, - U.Zip, - U.PrimaryPhone, - U.SecondaryPhone, - U.Fax, - U.InstantMessenger, - U.HtmlMail, - U.CompanyName, - U.EcommerceEnabled, - U.[AdditionalParams] - FROM Users AS U - WHERE U.Username = @Username - AND dbo.CanGetUserDetails(@ActorID, UserID) = 1 -- actor user rights - - RETURN -GO - - - - - - - - -ALTER PROCEDURE [dbo].[GetUserByUsernameInternally] -( - @Username nvarchar(50) -) -AS - SELECT - U.UserID, - U.RoleID, - U.StatusID, - U.SubscriberNumber, - U.LoginStatusId, - U.FailedLogins, - U.OwnerID, - U.Created, - U.Changed, - U.IsDemo, - U.Comments, - U.IsPeer, - U.Username, - U.Password, - U.FirstName, - U.LastName, - U.Email, - U.SecondaryEmail, - U.Address, - U.City, - U.State, - U.Country, - U.Zip, - U.PrimaryPhone, - U.SecondaryPhone, - U.Fax, - U.InstantMessenger, - U.HtmlMail, - U.CompanyName, - U.EcommerceEnabled, - U.[AdditionalParams] - FROM Users AS U - WHERE U.Username = @Username - - RETURN - -GO - - - - - - - - - - - - - -ALTER PROCEDURE [dbo].[GetUserDomainsPaged] -( - @ActorID int, - @UserID int, - @FilterColumn nvarchar(50) = '', - @FilterValue nvarchar(50) = '', - @SortColumn nvarchar(50), - @StartRow int, - @MaximumRows int -) -AS --- build query and run it to the temporary table -DECLARE @sql nvarchar(2000) - -SET @sql = ' -DECLARE @HasUserRights bit -SET @HasUserRights = dbo.CheckActorUserRights(@ActorID, @UserID) - -DECLARE @EndRow int -SET @EndRow = @StartRow + @MaximumRows -DECLARE @Users TABLE -( - ItemPosition int IDENTITY(1,1), - UserID int, - DomainID int -) -INSERT INTO @Users (UserID, DomainID) -SELECT - U.UserID, - D.DomainID -FROM Users AS U -INNER JOIN UsersTree(@UserID, 1) AS UT ON U.UserID = UT.UserID -LEFT OUTER JOIN Packages AS P ON U.UserID = P.UserID -LEFT OUTER JOIN Domains AS D ON P.PackageID = D.PackageID -WHERE - U.UserID <> @UserID AND U.IsPeer = 0 - AND @HasUserRights = 1 ' - -IF @FilterColumn <> '' AND @FilterValue <> '' -SET @sql = @sql + ' AND ' + @FilterColumn + ' LIKE @FilterValue ' - -IF @SortColumn <> '' AND @SortColumn IS NOT NULL -SET @sql = @sql + ' ORDER BY ' + @SortColumn + ' ' - -SET @sql = @sql + ' SELECT COUNT(UserID) FROM @Users; -SELECT - U.UserID, - U.RoleID, - U.StatusID, - U.SubscriberNumber, - U.LoginStatusId, - U.FailedLogins, - U.OwnerID, - U.Created, - U.Changed, - U.IsDemo, - U.Comments, - U.IsPeer, - U.Username, - U.FirstName, - U.LastName, - U.Email, - D.DomainName -FROM @Users AS TU -INNER JOIN Users AS U ON TU.UserID = U.UserID -LEFT OUTER JOIN Domains AS D ON TU.DomainID = D.DomainID -WHERE TU.ItemPosition BETWEEN @StartRow AND @EndRow' - -exec sp_executesql @sql, N'@StartRow int, @MaximumRows int, @UserID int, @FilterValue nvarchar(50), @ActorID int', -@StartRow, @MaximumRows, @UserID, @FilterValue, @ActorID - - -RETURN -GO - - - - - - - - - - - - -ALTER PROCEDURE [dbo].[GetUserParents] -( - @ActorID int, - @UserID int -) -AS - --- check rights -IF dbo.CheckActorUserRights(@ActorID, @UserID) = 0 -RAISERROR('You are not allowed to access this account', 16, 1) - -SELECT - U.UserID, - U.RoleID, - U.StatusID, - U.SubscriberNumber, - U.LoginStatusId, - U.FailedLogins, - U.OwnerID, - U.Created, - U.Changed, - U.IsDemo, - U.Comments, - U.IsPeer, - U.Username, - U.FirstName, - U.LastName, - U.Email, - U.CompanyName, - U.EcommerceEnabled -FROM UserParents(@ActorID, @UserID) AS UP -INNER JOIN Users AS U ON UP.UserID = U.UserID -ORDER BY UP.UserOrder DESC -RETURN -GO - - - - - - - - - - - - - -ALTER PROCEDURE [dbo].[GetUserPeers] -( - @ActorID int, - @UserID int -) -AS - -DECLARE @CanGetDetails bit -SET @CanGetDetails = dbo.CanGetUserDetails(@ActorID, @UserID) - -SELECT - U.UserID, - U.RoleID, - U.StatusID, - U.LoginStatusId, - U.FailedLogins, - U.OwnerID, - U.Created, - U.Changed, - U.IsDemo, - U.Comments, - U.IsPeer, - U.Username, - U.FirstName, - U.LastName, - U.Email, - U.FullName, - (U.FirstName + ' ' + U.LastName) AS FullName, - U.CompanyName, - U.EcommerceEnabled -FROM UsersDetailed AS U -WHERE U.OwnerID = @UserID AND IsPeer = 1 -AND @CanGetDetails = 1 -- actor rights - -RETURN -GO - - - - - - - - - - - - - - -ALTER PROCEDURE [dbo].[GetUsers] -( - @ActorID int, - @OwnerID int, - @Recursive bit = 0 -) -AS - -DECLARE @CanGetDetails bit -SET @CanGetDetails = dbo.CanGetUserDetails(@ActorID, @OwnerID) - -SELECT - U.UserID, - U.RoleID, - U.StatusID, - U.SubscriberNumber, - U.LoginStatusId, - U.FailedLogins, - U.OwnerID, - U.Created, - U.Changed, - U.IsDemo, - U.Comments, - U.IsPeer, - U.Username, - U.FirstName, - U.LastName, - U.Email, - U.FullName, - U.OwnerUsername, - U.OwnerFirstName, - U.OwnerLastName, - U.OwnerRoleID, - U.OwnerFullName, - U.PackagesNumber, - U.CompanyName, - U.EcommerceEnabled -FROM UsersDetailed AS U -WHERE U.UserID <> @OwnerID AND -((@Recursive = 1 AND dbo.CheckUserParent(@OwnerID, U.UserID) = 1) OR -(@Recursive = 0 AND U.OwnerID = @OwnerID)) -AND U.IsPeer = 0 -AND @CanGetDetails = 1 -- actor user rights - -RETURN -GO - - - - - - - - - - -ALTER PROCEDURE [dbo].[GetUsersPaged] -( - @ActorID int, - @UserID int, - @FilterColumn nvarchar(50) = '', - @FilterValue nvarchar(50) = '', - @StatusID int, - @RoleID int, - @SortColumn nvarchar(50), - @StartRow int, - @MaximumRows int, - @Recursive bit -) -AS --- build query and run it to the temporary table -DECLARE @sql nvarchar(2000) - -SET @sql = ' - -DECLARE @HasUserRights bit -SET @HasUserRights = dbo.CheckActorUserRights(@ActorID, @UserID) - -DECLARE @EndRow int -SET @EndRow = @StartRow + @MaximumRows -DECLARE @Users TABLE -( - ItemPosition int IDENTITY(0,1), - UserID int -) -INSERT INTO @Users (UserID) -SELECT - U.UserID -FROM UsersDetailed AS U -WHERE - U.UserID <> @UserID AND U.IsPeer = 0 AND - ( - (@Recursive = 0 AND OwnerID = @UserID) OR - (@Recursive = 1 AND dbo.CheckUserParent(@UserID, U.UserID) = 1) - ) - AND ((@StatusID = 0) OR (@StatusID > 0 AND U.StatusID = @StatusID)) - AND ((@RoleID = 0) OR (@RoleID > 0 AND U.RoleID = @RoleID)) - AND @HasUserRights = 1 ' - -IF @FilterColumn <> '' AND @FilterValue <> '' -SET @sql = @sql + ' AND ' + @FilterColumn + ' LIKE @FilterValue ' - -IF @SortColumn <> '' AND @SortColumn IS NOT NULL -SET @sql = @sql + ' ORDER BY ' + @SortColumn + ' ' - -SET @sql = @sql + ' SELECT COUNT(UserID) FROM @Users; -SELECT - U.UserID, - U.RoleID, - U.StatusID, - U.SubscriberNumber, - U.LoginStatusId, - U.FailedLogins, - U.OwnerID, - U.Created, - U.Changed, - U.IsDemo, - dbo.GetItemComments(U.UserID, ''USER'', @ActorID) AS Comments, - U.IsPeer, - U.Username, - U.FirstName, - U.LastName, - U.Email, - U.FullName, - U.OwnerUsername, - U.OwnerFirstName, - U.OwnerLastName, - U.OwnerRoleID, - U.OwnerFullName, - U.OwnerEmail, - U.PackagesNumber, - U.CompanyName, - U.EcommerceEnabled -FROM @Users AS TU -INNER JOIN UsersDetailed AS U ON TU.UserID = U.UserID -WHERE TU.ItemPosition BETWEEN @StartRow AND @EndRow' - -exec sp_executesql @sql, N'@StartRow int, @MaximumRows int, @UserID int, @FilterValue nvarchar(50), @ActorID int, @Recursive bit, @StatusID int, @RoleID int', -@StartRow, @MaximumRows, @UserID, @FilterValue, @ActorID, @Recursive, @StatusID, @RoleID - - -RETURN -GO - - - - - - - - -ALTER PROCEDURE [dbo].[UpdateUser] -( - @ActorID int, - @UserID int, - @RoleID int, - @StatusID int, - @SubscriberNumber nvarchar(32), - @LoginStatusId int, - @IsDemo bit, - @IsPeer bit, - @Comments ntext, - @FirstName nvarchar(50), - @LastName nvarchar(50), - @Email nvarchar(255), - @SecondaryEmail nvarchar(255), - @Address nvarchar(200), - @City nvarchar(50), - @State nvarchar(50), - @Country nvarchar(50), - @Zip varchar(20), - @PrimaryPhone varchar(30), - @SecondaryPhone varchar(30), - @Fax varchar(30), - @InstantMessenger nvarchar(200), - @HtmlMail bit, - @CompanyName nvarchar(100), - @EcommerceEnabled BIT, - @AdditionalParams NVARCHAR(max) -) -AS - - -- check actor rights - IF dbo.CanUpdateUserDetails(@ActorID, @UserID) = 0 - BEGIN - RETURN - END - - IF @LoginStatusId = 0 - BEGIN - UPDATE Users SET - FailedLogins = 0 - WHERE UserID = @UserID - END - - UPDATE Users SET - RoleID = @RoleID, - StatusID = @StatusID, - SubscriberNumber = @SubscriberNumber, - LoginStatusId = @LoginStatusId, - Changed = GetDate(), - IsDemo = @IsDemo, - IsPeer = @IsPeer, - Comments = @Comments, - FirstName = @FirstName, - LastName = @LastName, - Email = @Email, - SecondaryEmail = @SecondaryEmail, - Address = @Address, - City = @City, - State = @State, - Country = @Country, - Zip = @Zip, - PrimaryPhone = @PrimaryPhone, - SecondaryPhone = @SecondaryPhone, - Fax = @Fax, - InstantMessenger = @InstantMessenger, - HtmlMail = @HtmlMail, - CompanyName = @CompanyName, - EcommerceEnabled = @EcommerceEnabled, - [AdditionalParams] = @AdditionalParams - WHERE UserID = @UserID - - RETURN -GO - - - - - - - - -IF NOT EXISTS (SELECT * FROM sys.objects WHERE type_desc = N'SQL_STORED_PROCEDURE' AND name = N'UpdateUserFailedLoginAttempt') -BEGIN -EXEC sp_executesql N' CREATE PROCEDURE [dbo].[UpdateUserFailedLoginAttempt] -( - @UserID int, - @LockOut int, - @Reset int -) -AS - -IF (@Reset = 1) -BEGIN - UPDATE Users SET FailedLogins = 0 WHERE UserID = @UserID -END -ELSE -BEGIN - IF (@LockOut <= (SELECT FailedLogins FROM USERS WHERE UserID = @UserID)) - BEGIN - UPDATE Users SET LoginStatusId = 2 WHERE UserID = @UserID - END - ELSE - BEGIN - IF ((SELECT FailedLogins FROM Users WHERE UserID = @UserID) IS NULL) - BEGIN - UPDATE Users SET FailedLogins = 1 WHERE UserID = @UserID - END - ELSE - UPDATE Users SET FailedLogins = FailedLogins + 1 WHERE UserID = @UserID - END -END' -END -GO - - - -IF NOT EXISTS (SELECT * FROM sys.objects WHERE type_desc = N'SQL_STORED_PROCEDURE' AND name = N'UpdateLyncUserPlan') -BEGIN -EXEC sp_executesql N' CREATE PROCEDURE [dbo].[UpdateLyncUserPlan] -( - @LyncUserPlanId int, - @LyncUserPlanName nvarchar(300), - @LyncUserPlanType int, - @IM bit, - @Mobility bit, - @MobilityEnableOutsideVoice bit, - @Federation bit, - @Conferencing bit, - @EnterpriseVoice bit, - @VoicePolicy int, - @IsDefault bit -) -AS - -UPDATE LyncUserPlans SET - LyncUserPlanName = @LyncUserPlanName, - LyncUserPlanType = @LyncUserPlanType, - IM = @IM, - Mobility = @Mobility, - MobilityEnableOutsideVoice = @MobilityEnableOutsideVoice, - Federation = @Federation, - Conferencing =@Conferencing, - EnterpriseVoice = @EnterpriseVoice, - VoicePolicy = @VoicePolicy, - IsDefault = @IsDefault -WHERE LyncUserPlanId = @LyncUserPlanId - - -RETURN' -END -GO - -UPDATE [dbo].[Providers] SET [DisplayName] = 'MailEnable Server 1.x - 7.x' WHERE [DisplayName] = 'MailEnable Server 1.x - 4.x' -GO - -UPDATE [dbo].[Providers] SET [DisplayName] = 'SmarterMail 7.x - 8.x' WHERE [DisplayName] = 'SmarterMail 7.x' -GO -UPDATE [dbo].[Providers] SET [DisplayName] = 'SmarterMail 10.x +' WHERE [DisplayName] = 'SmarterMail 10.x' -GO -UPDATE [dbo].[Providers] SET [DisplayName] = 'SmarterStats 5.x +' WHERE [DisplayName] = 'SmarterStats 5.x-6.x' -GO - -IF NOT EXISTS (SELECT * FROM [dbo].[Providers] WHERE [DisplayName] = 'SmarterMail 10.x +') -BEGIN - INSERT [dbo].[Providers] ([ProviderID], [GroupID], [ProviderName], [DisplayName], [ProviderType], [EditorControl], [DisableAutoDiscovery]) VALUES (66, 4, N'SmarterMail', N'SmarterMail 10.x +', N'WebsitePanel.Providers.Mail.SmarterMail10, WebsitePanel.Providers.Mail.SmarterMail10', N'SmarterMail60', NULL) - INSERT [dbo].[ServiceDefaultProperties] ([ProviderID], [PropertyName], [PropertyValue]) VALUES (66, N'AdminPassword', N'') - INSERT [dbo].[ServiceDefaultProperties] ([ProviderID], [PropertyName], [PropertyValue]) VALUES (66, N'AdminUsername', N'admin') - INSERT [dbo].[ServiceDefaultProperties] ([ProviderID], [PropertyName], [PropertyValue]) VALUES (66, N'DomainsPath', N'%SYSTEMDRIVE%\SmarterMail') - INSERT [dbo].[ServiceDefaultProperties] ([ProviderID], [PropertyName], [PropertyValue]) VALUES (66, N'ServerIPAddress', N'127.0.0.1;127.0.0.1') - INSERT [dbo].[ServiceDefaultProperties] ([ProviderID], [PropertyName], [PropertyValue]) VALUES (66, N'ServiceUrl', N'http://localhost:9998/services/') -END -GO - - -ALTER PROCEDURE [dbo].[AddServiceItem] -( - @ActorID int, - @PackageID int, - @ServiceID int, - @ItemName nvarchar(500), - @ItemTypeName nvarchar(200), - @ItemID int OUTPUT, - @XmlProperties ntext, - @CreatedDate datetime -) -AS -BEGIN TRAN - --- check rights -IF dbo.CheckActorPackageRights(@ActorID, @PackageID) = 0 -RAISERROR('You are not allowed to access this package', 16, 1) - --- get GroupID -DECLARE @GroupID int -SELECT - @GroupID = PROV.GroupID -FROM Services AS S -INNER JOIN Providers AS PROV ON S.ProviderID = PROV.ProviderID -WHERE S.ServiceID = @ServiceID - -DECLARE @ItemTypeID int -SELECT @ItemTypeID = ItemTypeID FROM ServiceItemTypes -WHERE TypeName = @ItemTypeName -AND ((@GroupID IS NULL) OR (@GroupID IS NOT NULL AND GroupID = @GroupID)) - --- Fix to allow plans assigned to serveradmin -IF (@ItemTypeName = 'WebsitePanel.Providers.HostedSolution.Organization, WebsitePanel.Providers.Base') -BEGIN - IF NOT EXISTS (SELECT * FROM ServiceItems WHERE PackageID = 1) - BEGIN - INSERT INTO ServiceItems (PackageID, ItemTypeID,ServiceID,ItemName,CreatedDate) - VALUES(1, @ItemTypeID, @ServiceID, 'System', @CreatedDate) - - DECLARE @TempItemID int - - SET @TempItemID = SCOPE_IDENTITY() - INSERT INTO ExchangeOrganizations (ItemID, OrganizationID) - VALUES(@TempItemID, 'System') - END -END - - --- add item -INSERT INTO ServiceItems -( - PackageID, - ServiceID, - ItemName, - ItemTypeID, - CreatedDate -) -VALUES -( - @PackageID, - @ServiceID, - @ItemName, - @ItemTypeID, - @CreatedDate -) - -SET @ItemID = SCOPE_IDENTITY() - -DECLARE @idoc int ---Create an internal representation of the XML document. -EXEC sp_xml_preparedocument @idoc OUTPUT, @XmlProperties - --- Execute a SELECT statement that uses the OPENXML rowset provider. -DELETE FROM ServiceItemProperties -WHERE ItemID = @ItemID - -INSERT INTO ServiceItemProperties -( - ItemID, - PropertyName, - PropertyValue -) -SELECT - @ItemID, - PropertyName, - PropertyValue -FROM OPENXML(@idoc, '/properties/property',1) WITH -( - PropertyName nvarchar(50) '@name', - PropertyValue nvarchar(3000) '@value' -) as PV - --- remove document -exec sp_xml_removedocument @idoc - -COMMIT TRAN -RETURN - -GO - - - -IF NOT EXISTS (SELECT * FROM sys.objects WHERE type_desc = N'SQL_STORED_PROCEDURE' AND name = N'GetBlackBerryUsers') -BEGIN -EXEC sp_executesql N' -CREATE PROCEDURE [dbo].[GetBlackBerryUsers] -( - @ItemID int, - @SortColumn nvarchar(40), - @SortDirection nvarchar(20), - @Name nvarchar(400), - @Email nvarchar(400), - @StartRow int, - @Count int -) -AS - -IF (@Name IS NULL) -BEGIN - SET @Name = ''%'' -END - -IF (@Email IS NULL) -BEGIN - SET @Email = ''%'' -END - -CREATE TABLE #TempBlackBerryUsers -( - [ID] [int] IDENTITY(1,1) NOT NULL, - [AccountID] [int], - [ItemID] [int] NOT NULL, - [AccountName] [nvarchar](300) NOT NULL, - [DisplayName] [nvarchar](300) NOT NULL, - [PrimaryEmailAddress] [nvarchar](300) NULL, - [SamAccountName] [nvarchar](100) NULL -) - - -IF (@SortColumn = ''DisplayName'') -BEGIN - INSERT INTO - #TempBlackBerryUsers - SELECT - ea.AccountID, - ea.ItemID, - ea.AccountName, - ea.DisplayName, - ea.PrimaryEmailAddress, - ea.SamAccountName - FROM - ExchangeAccounts ea - INNER JOIN - BlackBerryUsers bu - ON - ea.AccountID = bu.AccountID - WHERE - ea.ItemID = @ItemID AND ea.DisplayName LIKE @Name AND ea.PrimaryEmailAddress LIKE @Email - ORDER BY - ea.DisplayName -END -ELSE -BEGIN - INSERT INTO - #TempBlackBerryUsers - SELECT - ea.AccountID, - ea.ItemID, - ea.AccountName, - ea.DisplayName, - ea.PrimaryEmailAddress, - ea.SamAccountName - FROM - ExchangeAccounts ea - INNER JOIN - BlackBerryUsers bu - ON - ea.AccountID = bu.AccountID - WHERE - ea.ItemID = @ItemID AND ea.DisplayName LIKE @Name AND ea.PrimaryEmailAddress LIKE @Email - ORDER BY - ea.PrimaryEmailAddress -END - -DECLARE @RetCount int -SELECT @RetCount = COUNT(ID) FROM #TempBlackBerryUsers - -IF (@SortDirection = ''ASC'') -BEGIN - SELECT * FROM #TempBlackBerryUsers - WHERE ID > @StartRow AND ID <= (@StartRow + @Count) -END -ELSE -BEGIN - IF (@SortColumn = ''DisplayName'') - BEGIN - SELECT * FROM #TempBlackBerryUsers - WHERE ID >@RetCount - @Count - @StartRow AND ID <= @RetCount- @StartRow ORDER BY DisplayName DESC - END - ELSE - BEGIN - SELECT * FROM #TempBlackBerryUsers - WHERE ID >@RetCount - @Count - @StartRow AND ID <= @RetCount- @StartRow ORDER BY PrimaryEmailAddress DESC - END - -END - - -DROP TABLE #TempBlackBerryUsers' -END -GO - - - - - - - - - - -ALTER PROCEDURE [dbo].[GetBlackBerryUsers] -( - @ItemID int, - @SortColumn nvarchar(40), - @SortDirection nvarchar(20), - @Name nvarchar(400), - @Email nvarchar(400), - @StartRow int, - @Count int -) -AS - -IF (@Name IS NULL) -BEGIN - SET @Name = '%' -END - -IF (@Email IS NULL) -BEGIN - SET @Email = '%' -END - -CREATE TABLE #TempBlackBerryUsers -( - [ID] [int] IDENTITY(1,1) NOT NULL, - [AccountID] [int], - [ItemID] [int] NOT NULL, - [AccountName] [nvarchar](300) NOT NULL, - [DisplayName] [nvarchar](300) NOT NULL, - [PrimaryEmailAddress] [nvarchar](300) NULL, - [SamAccountName] [nvarchar](100) NULL -) - - -IF (@SortColumn = 'DisplayName') -BEGIN - INSERT INTO - #TempBlackBerryUsers - SELECT - ea.AccountID, - ea.ItemID, - ea.AccountName, - ea.DisplayName, - ea.PrimaryEmailAddress, - ea.SamAccountName - FROM - ExchangeAccounts ea - INNER JOIN - BlackBerryUsers bu - ON - ea.AccountID = bu.AccountID - WHERE - ea.ItemID = @ItemID AND ea.DisplayName LIKE @Name AND ea.PrimaryEmailAddress LIKE @Email - ORDER BY - ea.DisplayName -END -ELSE -BEGIN - INSERT INTO - #TempBlackBerryUsers - SELECT - ea.AccountID, - ea.ItemID, - ea.AccountName, - ea.DisplayName, - ea.PrimaryEmailAddress, - ea.SamAccountName - FROM - ExchangeAccounts ea - INNER JOIN - BlackBerryUsers bu - ON - ea.AccountID = bu.AccountID - WHERE - ea.ItemID = @ItemID AND ea.DisplayName LIKE @Name AND ea.PrimaryEmailAddress LIKE @Email - ORDER BY - ea.PrimaryEmailAddress -END - -DECLARE @RetCount int -SELECT @RetCount = COUNT(ID) FROM #TempBlackBerryUsers - -IF (@SortDirection = 'ASC') -BEGIN - SELECT * FROM #TempBlackBerryUsers - WHERE ID > @StartRow AND ID <= (@StartRow + @Count) -END -ELSE -BEGIN - IF (@SortColumn = 'DisplayName') - BEGIN - SELECT * FROM #TempBlackBerryUsers - WHERE ID >@RetCount - @Count - @StartRow AND ID <= @RetCount- @StartRow ORDER BY DisplayName DESC - END - ELSE - BEGIN - SELECT * FROM #TempBlackBerryUsers - WHERE ID >@RetCount - @Count - @StartRow AND ID <= @RetCount- @StartRow ORDER BY PrimaryEmailAddress DESC - END - -END - - -DROP TABLE #TempBlackBerryUsers -GO - - - - - - - - -IF NOT EXISTS(select 1 from sys.columns COLS INNER JOIN sys.objects OBJS ON OBJS.object_id=COLS.object_id and OBJS.type='U' AND OBJS.name='ExchangeOrganizationDomains' AND COLS.name='DomainTypeID') -BEGIN -ALTER TABLE [dbo].[ExchangeOrganizationDomains] ADD - [DomainTypeID] [int] NOT NULL CONSTRAINT DF_ExchangeOrganizationDomains_DomainTypeID DEFAULT 0 -END -GO - - - - -ALTER PROCEDURE [dbo].[GetExchangeOrganizationDomains] -( - @ItemID int -) -AS -SELECT - ED.DomainID, - D.DomainName, - ED.IsHost, - ED.DomainTypeID -FROM - ExchangeOrganizationDomains AS ED -INNER JOIN Domains AS D ON ED.DomainID = D.DomainID -WHERE ED.ItemID = @ItemID -RETURN - -GO - - - - - - - -IF NOT EXISTS (SELECT * FROM sys.objects WHERE type_desc = N'SQL_STORED_PROCEDURE' AND name = N'ChangeExchangeAcceptedDomainType') -BEGIN -EXEC sp_executesql N' -CREATE PROCEDURE [dbo].ChangeExchangeAcceptedDomainType -( - @ItemID int, - @DomainID int, - @DomainTypeID int -) -AS -UPDATE ExchangeOrganizationDomains -SET DomainTypeID=@DomainTypeID -WHERE ItemID=ItemID AND DomainID=@DomainID -RETURN' -END -GO - - - - - - - - - - -ALTER PROCEDURE [dbo].[GetPackages] -( - @ActorID int, - @UserID int -) -AS - -SELECT - P.PackageID, - P.ParentPackageID, - P.PackageName, - P.StatusID, - P.PurchaseDate, - - -- server - ISNULL(P.ServerID, 0) AS ServerID, - ISNULL(S.ServerName, 'None') AS ServerName, - ISNULL(S.Comments, '') AS ServerComments, - ISNULL(S.VirtualServer, 1) AS VirtualServer, - - -- hosting plan - P.PlanID, - HP.PlanName, - - -- user - P.UserID, - U.Username, - U.FirstName, - U.LastName, - U.RoleID, - U.Email -FROM Packages AS P -INNER JOIN Users AS U ON P.UserID = U.UserID -INNER JOIN Servers AS S ON P.ServerID = S.ServerID -INNER JOIN HostingPlans AS HP ON P.PlanID = HP.PlanID -WHERE - P.UserID = @UserID -RETURN -GO - - - - - - - -ALTER PROCEDURE [dbo].[GetDomainsPaged] -( - @ActorID int, - @PackageID int, - @ServerID int, - @Recursive bit, - @FilterColumn nvarchar(50) = '', - @FilterValue nvarchar(50) = '', - @SortColumn nvarchar(50), - @StartRow int, - @MaximumRows int -) -AS -SET NOCOUNT ON - --- check rights -IF dbo.CheckActorPackageRights(@ActorID, @PackageID) = 0 -RAISERROR('You are not allowed to access this package', 16, 1) - --- build query and run it to the temporary table -DECLARE @sql nvarchar(2000) - -IF @SortColumn = '' OR @SortColumn IS NULL -SET @SortColumn = 'DomainName' - -SET @sql = ' -DECLARE @Domains TABLE -( - ItemPosition int IDENTITY(1,1), - DomainID int -) -INSERT INTO @Domains (DomainID) -SELECT - D.DomainID -FROM Domains AS D -INNER JOIN Packages AS P ON D.PackageID = P.PackageID -INNER JOIN UsersDetailed AS U ON P.UserID = U.UserID -LEFT OUTER JOIN ServiceItems AS Z ON D.ZoneItemID = Z.ItemID -LEFT OUTER JOIN Services AS S ON Z.ServiceID = S.ServiceID -LEFT OUTER JOIN Servers AS SRV ON S.ServerID = SRV.ServerID -WHERE (D.IsInstantAlias = 0 AND D.IsDomainPointer = 0) AND - ((@Recursive = 0 AND D.PackageID = @PackageID) - OR (@Recursive = 1 AND dbo.CheckPackageParent(@PackageID, D.PackageID) = 1)) -AND (@ServerID = 0 OR (@ServerID > 0 AND S.ServerID = @ServerID)) -' - -IF @FilterColumn <> '' AND @FilterValue <> '' -SET @sql = @sql + ' AND ' + @FilterColumn + ' LIKE @FilterValue ' - -IF @SortColumn <> '' AND @SortColumn IS NOT NULL -SET @sql = @sql + ' ORDER BY ' + @SortColumn + ' ' - -SET @sql = @sql + ' SELECT COUNT(DomainID) FROM @Domains;SELECT - D.DomainID, - D.PackageID, - D.ZoneItemID, - D.DomainName, - D.HostingAllowed, - ISNULL(WS.ItemID, 0) AS WebSiteID, - WS.ItemName AS WebSiteName, - ISNULL(MD.ItemID, 0) AS MailDomainID, - MD.ItemName AS MailDomainName, - D.IsSubDomain, - D.IsInstantAlias, - D.IsDomainPointer, - - -- packages - P.PackageName, - - -- server - ISNULL(SRV.ServerID, 0) AS ServerID, - ISNULL(SRV.ServerName, '''') AS ServerName, - ISNULL(SRV.Comments, '''') AS ServerComments, - ISNULL(SRV.VirtualServer, 0) AS VirtualServer, - - -- user - P.UserID, - U.Username, - U.FirstName, - U.LastName, - U.FullName, - U.RoleID, - U.Email -FROM @Domains AS SD -INNER JOIN Domains AS D ON SD.DomainID = D.DomainID -INNER JOIN Packages AS P ON D.PackageID = P.PackageID -INNER JOIN UsersDetailed AS U ON P.UserID = U.UserID -LEFT OUTER JOIN ServiceItems AS WS ON D.WebSiteID = WS.ItemID -LEFT OUTER JOIN ServiceItems AS MD ON D.MailDomainID = MD.ItemID -LEFT OUTER JOIN ServiceItems AS Z ON D.ZoneItemID = Z.ItemID -LEFT OUTER JOIN Services AS S ON Z.ServiceID = S.ServiceID -LEFT OUTER JOIN Servers AS SRV ON S.ServerID = SRV.ServerID -WHERE SD.ItemPosition BETWEEN @StartRow + 1 AND @StartRow + @MaximumRows' - -exec sp_executesql @sql, N'@StartRow int, @MaximumRows int, @PackageID int, @FilterValue nvarchar(50), @ServerID int, @Recursive bit', -@StartRow, @MaximumRows, @PackageID, @FilterValue, @ServerID, @Recursive - - -RETURN -GO - - - - - - -ALTER PROCEDURE [dbo].[DeleteServiceItem] -( - @ActorID int, - @ItemID int -) -AS - --- check rights -DECLARE @PackageID int -SELECT PackageID = @PackageID FROM ServiceItems -WHERE ItemID = @ItemID - -IF dbo.CheckActorPackageRights(@ActorID, @PackageID) = 0 -RAISERROR('You are not allowed to access this package', 16, 1) - -BEGIN TRAN - -UPDATE Domains -SET ZoneItemID = NULL -WHERE ZoneItemID = @ItemID - -DELETE FROM Domains -WHERE WebSiteID = @ItemID AND IsDomainPointer = 1 - -UPDATE Domains -SET WebSiteID = NULL -WHERE WebSiteID = @ItemID - -UPDATE Domains -SET MailDomainID = NULL -WHERE MailDomainID = @ItemID - --- delete item comments -DELETE FROM Comments -WHERE ItemID = @ItemID AND ItemTypeID = 'SERVICE_ITEM' - --- delete item properties -DELETE FROM ServiceItemProperties -WHERE ItemID = @ItemID - --- delete external IP addresses -EXEC dbo.DeleteItemIPAddresses @ActorID, @ItemID - --- delete item -DELETE FROM ServiceItems -WHERE ItemID = @ItemID - -COMMIT TRAN - -RETURN - -GO - - - - - - - - - - -ALTER PROCEDURE [dbo].[GetOCSUsers] -( - @ItemID int, - @SortColumn nvarchar(40), - @SortDirection nvarchar(20), - @Name nvarchar(400), - @Email nvarchar(400), - @StartRow int, - @Count int -) -AS - -IF (@Name IS NULL) -BEGIN - SET @Name = '%' -END - -IF (@Email IS NULL) -BEGIN - SET @Email = '%' -END - -CREATE TABLE #TempOCSUsers -( - [ID] [int] IDENTITY(1,1) NOT NULL, - [AccountID] [int], - [ItemID] [int] NOT NULL, - [AccountName] [nvarchar](300) NOT NULL, - [DisplayName] [nvarchar](300) NOT NULL, - [InstanceID] [nvarchar](50) NOT NULL, - [PrimaryEmailAddress] [nvarchar](300) NULL, - [SamAccountName] [nvarchar](100) NULL -) - - -IF (@SortColumn = 'DisplayName') -BEGIN - INSERT INTO - #TempOCSUsers - SELECT - ea.AccountID, - ea.ItemID, - ea.AccountName, - ea.DisplayName, - ou.InstanceID, - ea.PrimaryEmailAddress, - ea.SamAccountName - FROM - ExchangeAccounts ea - INNER JOIN - OCSUsers ou - ON - ea.AccountID = ou.AccountID - WHERE - ea.ItemID = @ItemID AND ea.DisplayName LIKE @Name AND ea.PrimaryEmailAddress LIKE @Email - ORDER BY - ea.DisplayName -END -ELSE -BEGIN - INSERT INTO - #TempOCSUsers - SELECT - ea.AccountID, - ea.ItemID, - ea.AccountName, - ea.DisplayName, - ou.InstanceID, - ea.PrimaryEmailAddress, - ea.SamAccountName - FROM - ExchangeAccounts ea - INNER JOIN - OCSUsers ou - ON - ea.AccountID = ou.AccountID - WHERE - ea.ItemID = @ItemID AND ea.DisplayName LIKE @Name AND ea.PrimaryEmailAddress LIKE @Email - ORDER BY - ea.PrimaryEmailAddress -END - -DECLARE @RetCount int -SELECT @RetCount = COUNT(ID) FROM #TempOCSUsers - -IF (@SortDirection = 'ASC') -BEGIN - SELECT * FROM #TempOCSUsers - WHERE ID > @StartRow AND ID <= (@StartRow + @Count) -END -ELSE -BEGIN - IF (@SortColumn = 'DisplayName') - BEGIN - SELECT * FROM #TempOCSUsers - WHERE ID >@RetCount - @Count - @StartRow AND ID <= @RetCount- @StartRow ORDER BY DisplayName DESC - END - ELSE - BEGIN - SELECT * FROM #TempOCSUsers - WHERE ID >@RetCount - @Count - @StartRow AND ID <= @RetCount- @StartRow ORDER BY PrimaryEmailAddress DESC - END - -END - - -DROP TABLE #TempOCSUsers - -GO - - - - - - -ALTER PROCEDURE [dbo].[GetCRMUsers] -( - @ItemID int, - @SortColumn nvarchar(40), - @SortDirection nvarchar(20), - @Name nvarchar(400), - @Email nvarchar(400), - @StartRow int, - @Count int -) -AS - -IF (@Name IS NULL) -BEGIN - SET @Name = '%' -END - -IF (@Email IS NULL) -BEGIN - SET @Email = '%' -END - -CREATE TABLE #TempCRMUsers -( - [ID] [int] IDENTITY(1,1) NOT NULL, - [AccountID] [int], - [ItemID] [int] NOT NULL, - [AccountName] [nvarchar](300) NOT NULL, - [DisplayName] [nvarchar](300) NOT NULL, - [PrimaryEmailAddress] [nvarchar](300) NULL, - [SamAccountName] [nvarchar](100) NULL -) - - -IF (@SortColumn = 'DisplayName') -BEGIN - INSERT INTO - #TempCRMUsers - SELECT - ea.AccountID, - ea.ItemID, - ea.AccountName, - ea.DisplayName, - ea.PrimaryEmailAddress, - ea.SamAccountName - FROM - ExchangeAccounts ea - INNER JOIN - CRMUsers cu - ON - ea.AccountID = cu.AccountID - WHERE - ea.ItemID = @ItemID AND ea.DisplayName LIKE @Name AND ea.PrimaryEmailAddress LIKE @Email - ORDER BY - ea.DisplayName -END -ELSE -BEGIN - INSERT INTO - #TempCRMUsers - SELECT - ea.AccountID, - ea.ItemID, - ea.AccountName, - ea.DisplayName, - ea.PrimaryEmailAddress, - ea.SamAccountName - FROM - ExchangeAccounts ea - INNER JOIN - CRMUsers cu - ON - ea.AccountID = cu.AccountID - WHERE - ea.ItemID = @ItemID AND ea.DisplayName LIKE @Name AND ea.PrimaryEmailAddress LIKE @Email - ORDER BY - ea.PrimaryEmailAddress -END - -DECLARE @RetCount int -SELECT @RetCount = COUNT(ID) FROM #TempCRMUsers - -IF (@SortDirection = 'ASC') -BEGIN - SELECT * FROM #TempCRMUsers - WHERE ID > @StartRow AND ID <= (@StartRow + @Count) -END -ELSE -BEGIN - IF (@SortColumn = 'DisplayName') - BEGIN - SELECT * FROM #TempCRMUsers - WHERE ID >@RetCount - @Count - @StartRow AND ID <= @RetCount- @StartRow ORDER BY DisplayName DESC - END - ELSE - BEGIN - SELECT * FROM #TempCRMUsers - WHERE ID >@RetCount - @Count - @StartRow AND ID <= @RetCount- @StartRow ORDER BY PrimaryEmailAddress DESC - END - -END - - - -DROP TABLE #TempCRMUsers -GO - - -IF NOT EXISTS (SELECT * FROM sys.objects WHERE type_desc = N'SQL_STORED_PROCEDURE' AND name = N'GetDomainsByZoneID') -BEGIN -EXEC sp_executesql N'CREATE PROCEDURE [dbo].[GetDomainsByZoneID] -( - @ActorID int, - @ZoneID int -) -AS - -SELECT - D.DomainID, - D.PackageID, - D.ZoneItemID, - D.DomainName, - D.HostingAllowed, - ISNULL(D.WebSiteID, 0) AS WebSiteID, - WS.ItemName AS WebSiteName, - ISNULL(D.MailDomainID, 0) AS MailDomainID, - MD.ItemName AS MailDomainName, - Z.ItemName AS ZoneName, - D.IsSubDomain, - D.IsInstantAlias, - D.IsDomainPointer -FROM Domains AS D -INNER JOIN Packages AS P ON D.PackageID = P.PackageID -LEFT OUTER JOIN ServiceItems AS WS ON D.WebSiteID = WS.ItemID -LEFT OUTER JOIN ServiceItems AS MD ON D.MailDomainID = MD.ItemID -LEFT OUTER JOIN ServiceItems AS Z ON D.ZoneItemID = Z.ItemID -WHERE - D.ZoneItemID = @ZoneID - AND dbo.CheckActorPackageRights(@ActorID, P.PackageID) = 1 -RETURN' -END -GO - - - - - - - - - - - - - - - - -/****** Object: Table [dbo].[ExchangeOrganizations] Extend Exchange Accounts with ExchangeMailboxPlanID ******/ -IF NOT EXISTS(select 1 from sys.columns COLS INNER JOIN sys.objects OBJS ON OBJS.object_id=COLS.object_id and OBJS.type='U' AND OBJS.name='ExchangeOrganizations' AND COLS.name='ExchangeMailboxPlanID') -BEGIN -ALTER TABLE [dbo].[ExchangeOrganizations] ADD [ExchangeMailboxPlanID] [int] -END -GO - - - - - -/****** Object: Table [dbo].[ExchangeOrganizations] Extend Exchange Accounts with LyncUserPlanID ******/ -IF NOT EXISTS(select 1 from sys.columns COLS INNER JOIN sys.objects OBJS ON OBJS.object_id=COLS.object_id and OBJS.type='U' AND OBJS.name='ExchangeOrganizations' AND COLS.name='LyncUserPlanID') -BEGIN -ALTER TABLE [dbo].[ExchangeOrganizations] ADD [LyncUserPlanID] [int] -END -GO - - - - - - - - -ALTER PROCEDURE [dbo].[SetOrganizationDefaultLyncUserPlan] -( - @ItemID int, - @LyncUserPlanId int -) -AS - -UPDATE ExchangeOrganizations SET - LyncUserPlanID = @LyncUserPlanId -WHERE - ItemID = @ItemID - -RETURN -GO - - - -ALTER PROCEDURE [dbo].[SetOrganizationDefaultExchangeMailboxPlan] -( - @ItemID int, - @MailboxPlanId int -) -AS - -UPDATE ExchangeOrganizations SET - ExchangeMailboxPlanID = @MailboxPlanId -WHERE - ItemID = @ItemID - -RETURN -GO - - - - -IF NOT EXISTS (SELECT * FROM sys.objects WHERE type_desc = N'SQL_STORED_PROCEDURE' AND name = N'GetExchangeOrganization') -BEGIN -EXEC sp_executesql N'CREATE PROCEDURE [dbo].[GetExchangeOrganization] -( - @ItemID int -) -AS -SELECT - ItemID, - ExchangeMailboxPlanID, - LyncUserPlanID -FROM - ExchangeOrganizations -WHERE - ItemID = @ItemID -RETURN' -END -GO - - - - -IF NOT EXISTS(select 1 from sys.columns COLS INNER JOIN sys.objects OBJS ON OBJS.object_id=COLS.object_id and OBJS.type='U' AND OBJS.name='Domains' AND COLS.name='DomainItemId') -BEGIN -ALTER TABLE [dbo].[Domains] ADD [DomainItemId] [int] NULL - -END -GO - -IF (SELECT Count(*) FROM Domains WHERE DomainItemId IS NOT NULL) = 0 -BEGIN - CREATE TABLE #TempDomains - ( - [PackageID] [int] NOT NULL, - [ZoneItemID] [int] NULL, - [DomainName] [nvarchar](100) COLLATE Latin1_General_CI_AS NOT NULL, - [HostingAllowed] [bit] NOT NULL, - [WebSiteID] [int] NULL, - [IsSubDomain] [bit] NOT NULL, - [IsInstantAlias] [bit] NOT NULL, - [IsDomainPointer] [bit] NOT NULL, - [DomainItemID] [int] NULL, - ) - - UPDATE Domains SET DomainItemID = DomainID - - INSERT INTO #TempDomains SELECT PackageID, - ZoneItemID, - DomainName, - HostingAllowed, - WebSiteID, - IsSubDomain, - IsInstantAlias, - IsDomainPointer, - DomainItemID FROM Domains WHERE WebSiteID IS NOT NULL - - UPDATE Domains SET IsDomainPointer=0,WebSiteID=NULL, DomainItemID=NULL WHERE WebSiteID IS NOT NULL - UPDATE Domains SET IsDomainPointer=0, DomainItemID=NULL WHERE MailDomainID IS NOT NULL AND isDomainPointer=1 - INSERT INTO Domains SELECT PackageID, - ZoneItemID, - DomainName, - HostingAllowed, - WebSiteID, - NULL, - 0, - IsInstantAlias, - 1, - DomainItemID - FROM #TempDomains - - - DROP TABLE #TempDomains -END GO - - - -IF NOT EXISTS (SELECT * FROM [dbo].[Quotas] WHERE [QuotaName] = 'Web.EnableHostNameSupport') -BEGIN - INSERT [dbo].[Quotas] ([QuotaID], [GroupID], [QuotaOrder], [QuotaName], [QuotaDescription], [QuotaTypeID], [ServiceQuota], [ItemTypeID]) VALUES (334, 2, 23, N'Web.EnableHostNameSupport', N'Enable Hostname Support', 1, 0, NULL) -END -GO - - - - - - - - - -IF NOT EXISTS (SELECT * FROM sys.objects WHERE type_desc = N'SQL_STORED_PROCEDURE' AND name = N'GetDomainsByDomainItemID') -BEGIN -EXEC sp_executesql N'CREATE PROCEDURE [dbo].[GetDomainsByDomainItemID] -( - @ActorID int, - @DomainID int -) -AS - -SELECT - D.DomainID, - D.PackageID, - D.ZoneItemID, - D.DomainItemID, - D.DomainName, - D.HostingAllowed, - ISNULL(D.WebSiteID, 0) AS WebSiteID, - WS.ItemName AS WebSiteName, - ISNULL(D.MailDomainID, 0) AS MailDomainID, - MD.ItemName AS MailDomainName, - Z.ItemName AS ZoneName, - D.IsSubDomain, - D.IsInstantAlias, - D.IsDomainPointer -FROM Domains AS D -INNER JOIN Packages AS P ON D.PackageID = P.PackageID -LEFT OUTER JOIN ServiceItems AS WS ON D.WebSiteID = WS.ItemID -LEFT OUTER JOIN ServiceItems AS MD ON D.MailDomainID = MD.ItemID -LEFT OUTER JOIN ServiceItems AS Z ON D.ZoneItemID = Z.ItemID -WHERE - D.DomainItemID = @DomainID - AND dbo.CheckActorPackageRights(@ActorID, P.PackageID) = 1 -RETURN' -END -GO - - - - - -ALTER PROCEDURE [dbo].[UpdateDomain] -( - @DomainID int, - @ActorID int, - @ZoneItemID int, - @HostingAllowed bit, - @WebSiteID int, - @MailDomainID int, - @DomainItemID int -) -AS - --- check rights -DECLARE @PackageID int -SELECT @PackageID = PackageID FROM Domains -WHERE DomainID = @DomainID - -IF dbo.CheckActorPackageRights(@ActorID, @PackageID) = 0 -RAISERROR('You are not allowed to access this package', 16, 1) - -IF @ZoneItemID = 0 SET @ZoneItemID = NULL -IF @WebSiteID = 0 SET @WebSiteID = NULL -IF @MailDomainID = 0 SET @MailDomainID = NULL - --- update record -UPDATE Domains -SET - ZoneItemID = @ZoneItemID, - HostingAllowed = @HostingAllowed, - WebSiteID = @WebSiteID, - MailDomainID = @MailDomainID, - DomainItemID = @DomainItemID -WHERE - DomainID = @DomainID - RETURN -GO - - - - - -ALTER PROCEDURE [dbo].[GetDnsRecordsTotal] -( - @ActorID int, - @PackageID int -) -AS - --- check rights -IF dbo.CheckActorPackageRights(@ActorID, @PackageID) = 0 -RAISERROR('You are not allowed to access this package', 16, 1) - --- create temp table for DNS records -DECLARE @Records TABLE -( - RecordID int, - RecordType nvarchar(10) COLLATE Latin1_General_CI_AS, - RecordName nvarchar(50) COLLATE Latin1_General_CI_AS -) - --- select PACKAGES DNS records -DECLARE @ParentPackageID int, @TmpPackageID int -SET @TmpPackageID = @PackageID - -WHILE 10 = 10 -BEGIN - - -- get DNS records for the current package - INSERT INTO @Records (RecordID, RecordType, RecordName) - SELECT - GR.RecordID, - GR.RecordType, - GR.RecordName - FROM GlobalDNSRecords AS GR - WHERE GR.PackageID = @TmpPackageID - AND GR.RecordType + GR.RecordName NOT IN (SELECT RecordType + RecordName FROM @Records) - - SET @ParentPackageID = NULL - - -- get parent package - SELECT - @ParentPackageID = ParentPackageID - FROM Packages - WHERE PackageID = @TmpPackageID - - IF @ParentPackageID IS NULL -- the last parent - BREAK - - SET @TmpPackageID = @ParentPackageID -END - --- select VIRTUAL SERVER DNS records -DECLARE @ServerID int -SELECT @ServerID = ServerID FROM Packages -WHERE PackageID = @PackageID - -INSERT INTO @Records (RecordID, RecordType, RecordName) -SELECT - GR.RecordID, - GR.RecordType, - GR.RecordName -FROM GlobalDNSRecords AS GR -WHERE GR.ServerID = @ServerID -AND GR.RecordType + GR.RecordName NOT IN (SELECT RecordType + RecordName FROM @Records) - --- select SERVER DNS records -INSERT INTO @Records (RecordID, RecordType, RecordName) -SELECT - GR.RecordID, - GR.RecordType, - GR.RecordName -FROM GlobalDNSRecords AS GR -WHERE GR.ServerID IN (SELECT - SRV.ServerID -FROM VirtualServices AS VS -INNER JOIN Services AS S ON VS.ServiceID = S.ServiceID -INNER JOIN Servers AS SRV ON S.ServerID = SRV.ServerID -WHERE VS.ServerID = @ServerID) -AND GR.RecordType + GR.RecordName NOT IN (SELECT RecordType + RecordName FROM @Records) - - - - - --- select SERVICES DNS records --- re-distribute package services -EXEC DistributePackageServices @ActorID, @PackageID - ---INSERT INTO @Records (RecordID, RecordType, RecordName) ---SELECT --- GR.RecordID, --- GR.RecordType, - -- GR.RecordName --- FROM GlobalDNSRecords AS GR --- WHERE GR.ServiceID IN (SELECT ServiceID FROM PackageServices WHERE PackageID = @PackageID) --- AND GR.RecordType + GR.RecordName NOT IN (SELECT RecordType + RecordName FROM @Records) - - -SELECT - NR.RecordID, - NR.ServiceID, - NR.ServerID, - NR.PackageID, - NR.RecordType, - NR.RecordName, - NR.RecordData, - NR.MXPriority, - NR.SrvPriority, - NR.SrvWeight, - NR.SrvPort, - NR.IPAddressID, - ISNULL(IP.ExternalIP, '') AS ExternalIP, - ISNULL(IP.InternalIP, '') AS InternalIP, - CASE - WHEN NR.RecordType = 'A' AND NR.RecordData = '' THEN dbo.GetFullIPAddress(IP.ExternalIP, IP.InternalIP) - WHEN NR.RecordType = 'MX' THEN CONVERT(varchar(3), NR.MXPriority) + ', ' + NR.RecordData - WHEN NR.RecordType = 'SRV' THEN CONVERT(varchar(3), NR.SrvPort) + ', ' + NR.RecordData - ELSE NR.RecordData - END AS FullRecordData, - dbo.GetFullIPAddress(IP.ExternalIP, IP.InternalIP) AS IPAddress -FROM @Records AS TR -INNER JOIN GlobalDnsRecords AS NR ON TR.RecordID = NR.RecordID -LEFT OUTER JOIN IPAddresses AS IP ON NR.IPAddressID = IP.AddressID - -RETURN -GO - - - - -ALTER PROCEDURE [dbo].[GetDomainByName] -( - @ActorID int, - @DomainName nvarchar(100), - @SearchOnDomainPointer bit, - @IsDomainPointer bit -) -AS - -IF (@SearchOnDomainPointer = 1) -BEGIN - SELECT - D.DomainID, - D.PackageID, - D.ZoneItemID, - D.DomainItemID, - D.DomainName, - D.HostingAllowed, - ISNULL(D.WebSiteID, 0) AS WebSiteID, - WS.ItemName AS WebSiteName, - ISNULL(D.MailDomainID, 0) AS MailDomainID, - MD.ItemName AS MailDomainName, - Z.ItemName AS ZoneName, - D.IsSubDomain, - D.IsInstantAlias, - D.IsDomainPointer - FROM Domains AS D - INNER JOIN Packages AS P ON D.PackageID = P.PackageID - LEFT OUTER JOIN ServiceItems AS WS ON D.WebSiteID = WS.ItemID - LEFT OUTER JOIN ServiceItems AS MD ON D.MailDomainID = MD.ItemID - LEFT OUTER JOIN ServiceItems AS Z ON D.ZoneItemID = Z.ItemID - WHERE - D.DomainName = @DomainName - AND D.IsDomainPointer = @IsDomainPointer - AND dbo.CheckActorPackageRights(@ActorID, P.PackageID) = 1 - RETURN -END -ELSE -BEGIN - SELECT - D.DomainID, - D.PackageID, - D.ZoneItemID, - D.DomainItemID, - D.DomainName, - D.HostingAllowed, - ISNULL(D.WebSiteID, 0) AS WebSiteID, - WS.ItemName AS WebSiteName, - ISNULL(D.MailDomainID, 0) AS MailDomainID, - MD.ItemName AS MailDomainName, - Z.ItemName AS ZoneName, - D.IsSubDomain, - D.IsInstantAlias, - D.IsDomainPointer - FROM Domains AS D - INNER JOIN Packages AS P ON D.PackageID = P.PackageID - LEFT OUTER JOIN ServiceItems AS WS ON D.WebSiteID = WS.ItemID - LEFT OUTER JOIN ServiceItems AS MD ON D.MailDomainID = MD.ItemID - LEFT OUTER JOIN ServiceItems AS Z ON D.ZoneItemID = Z.ItemID - WHERE - D.DomainName = @DomainName - AND dbo.CheckActorPackageRights(@ActorID, P.PackageID) = 1 - RETURN -END -GO - - - -ALTER PROCEDURE [dbo].[GetDomain] -( - @ActorID int, - @DomainID int -) -AS - -SELECT - D.DomainID, - D.PackageID, - D.ZoneItemID, - D.DomainItemID, - D.DomainName, - D.HostingAllowed, - ISNULL(WS.ItemID, 0) AS WebSiteID, - WS.ItemName AS WebSiteName, - ISNULL(MD.ItemID, 0) AS MailDomainID, - MD.ItemName AS MailDomainName, - Z.ItemName AS ZoneName, - D.IsSubDomain, - D.IsInstantAlias, - D.IsDomainPointer -FROM Domains AS D -INNER JOIN Packages AS P ON D.PackageID = P.PackageID -LEFT OUTER JOIN ServiceItems AS WS ON D.WebSiteID = WS.ItemID -LEFT OUTER JOIN ServiceItems AS MD ON D.MailDomainID = MD.ItemID -LEFT OUTER JOIN ServiceItems AS Z ON D.ZoneItemID = Z.ItemID -WHERE - D.DomainID = @DomainID - AND dbo.CheckActorPackageRights(@ActorID, P.PackageID) = 1 -RETURN -GO - - - - -ALTER PROCEDURE [dbo].[GetDomains] -( - @ActorID int, - @PackageID int, - @Recursive bit = 1 -) -AS - --- check rights -IF dbo.CheckActorPackageRights(@ActorID, @PackageID) = 0 -RAISERROR('You are not allowed to access this package', 16, 1) - -SELECT - D.DomainID, - D.PackageID, - D.ZoneItemID, - D.DomainItemID, - D.DomainName, - D.HostingAllowed, - ISNULL(WS.ItemID, 0) AS WebSiteID, - WS.ItemName AS WebSiteName, - ISNULL(MD.ItemID, 0) AS MailDomainID, - MD.ItemName AS MailDomainName, - Z.ItemName AS ZoneName, - D.IsSubDomain, - D.IsInstantAlias, - D.IsDomainPointer -FROM Domains AS D -INNER JOIN PackagesTree(@PackageID, @Recursive) AS PT ON D.PackageID = PT.PackageID -LEFT OUTER JOIN ServiceItems AS WS ON D.WebSiteID = WS.ItemID -LEFT OUTER JOIN ServiceItems AS MD ON D.MailDomainID = MD.ItemID -LEFT OUTER JOIN ServiceItems AS Z ON D.ZoneItemID = Z.ItemID -RETURN -GO - - - - -ALTER PROCEDURE [dbo].[GetDomainsByZoneID] -( - @ActorID int, - @ZoneID int -) -AS - -SELECT - D.DomainID, - D.PackageID, - D.ZoneItemID, - D.DomainItemID, - D.DomainName, - D.HostingAllowed, - ISNULL(D.WebSiteID, 0) AS WebSiteID, - WS.ItemName AS WebSiteName, - ISNULL(D.MailDomainID, 0) AS MailDomainID, - MD.ItemName AS MailDomainName, - Z.ItemName AS ZoneName, - D.IsSubDomain, - D.IsInstantAlias, - D.IsDomainPointer -FROM Domains AS D -INNER JOIN Packages AS P ON D.PackageID = P.PackageID -LEFT OUTER JOIN ServiceItems AS WS ON D.WebSiteID = WS.ItemID -LEFT OUTER JOIN ServiceItems AS MD ON D.MailDomainID = MD.ItemID -LEFT OUTER JOIN ServiceItems AS Z ON D.ZoneItemID = Z.ItemID -WHERE - D.ZoneItemID = @ZoneID - AND dbo.CheckActorPackageRights(@ActorID, P.PackageID) = 1 -RETURN -GO - - - - -ALTER PROCEDURE [dbo].[GetDomainsPaged] -( - @ActorID int, - @PackageID int, - @ServerID int, - @Recursive bit, - @FilterColumn nvarchar(50) = '', - @FilterValue nvarchar(50) = '', - @SortColumn nvarchar(50), - @StartRow int, - @MaximumRows int -) -AS -SET NOCOUNT ON - --- check rights -IF dbo.CheckActorPackageRights(@ActorID, @PackageID) = 0 -RAISERROR('You are not allowed to access this package', 16, 1) - --- build query and run it to the temporary table -DECLARE @sql nvarchar(2000) - -IF @SortColumn = '' OR @SortColumn IS NULL -SET @SortColumn = 'DomainName' - -SET @sql = ' -DECLARE @Domains TABLE -( - ItemPosition int IDENTITY(1,1), - DomainID int -) -INSERT INTO @Domains (DomainID) -SELECT - D.DomainID -FROM Domains AS D -INNER JOIN Packages AS P ON D.PackageID = P.PackageID -INNER JOIN UsersDetailed AS U ON P.UserID = U.UserID -LEFT OUTER JOIN ServiceItems AS Z ON D.ZoneItemID = Z.ItemID -LEFT OUTER JOIN Services AS S ON Z.ServiceID = S.ServiceID -LEFT OUTER JOIN Servers AS SRV ON S.ServerID = SRV.ServerID -WHERE (D.IsInstantAlias = 0 AND D.IsDomainPointer = 0) AND - ((@Recursive = 0 AND D.PackageID = @PackageID) - OR (@Recursive = 1 AND dbo.CheckPackageParent(@PackageID, D.PackageID) = 1)) -AND (@ServerID = 0 OR (@ServerID > 0 AND S.ServerID = @ServerID)) -' - -IF @FilterColumn <> '' AND @FilterValue <> '' -SET @sql = @sql + ' AND ' + @FilterColumn + ' LIKE @FilterValue ' - -IF @SortColumn <> '' AND @SortColumn IS NOT NULL -SET @sql = @sql + ' ORDER BY ' + @SortColumn + ' ' - -SET @sql = @sql + ' SELECT COUNT(DomainID) FROM @Domains;SELECT - D.DomainID, - D.PackageID, - D.ZoneItemID, - D.DomainItemID, - D.DomainName, - D.HostingAllowed, - ISNULL(WS.ItemID, 0) AS WebSiteID, - WS.ItemName AS WebSiteName, - ISNULL(MD.ItemID, 0) AS MailDomainID, - MD.ItemName AS MailDomainName, - D.IsSubDomain, - D.IsInstantAlias, - D.IsDomainPointer, - - -- packages - P.PackageName, - - -- server - ISNULL(SRV.ServerID, 0) AS ServerID, - ISNULL(SRV.ServerName, '''') AS ServerName, - ISNULL(SRV.Comments, '''') AS ServerComments, - ISNULL(SRV.VirtualServer, 0) AS VirtualServer, - - -- user - P.UserID, - U.Username, - U.FirstName, - U.LastName, - U.FullName, - U.RoleID, - U.Email -FROM @Domains AS SD -INNER JOIN Domains AS D ON SD.DomainID = D.DomainID -INNER JOIN Packages AS P ON D.PackageID = P.PackageID -INNER JOIN UsersDetailed AS U ON P.UserID = U.UserID -LEFT OUTER JOIN ServiceItems AS WS ON D.WebSiteID = WS.ItemID -LEFT OUTER JOIN ServiceItems AS MD ON D.MailDomainID = MD.ItemID -LEFT OUTER JOIN ServiceItems AS Z ON D.ZoneItemID = Z.ItemID -LEFT OUTER JOIN Services AS S ON Z.ServiceID = S.ServiceID -LEFT OUTER JOIN Servers AS SRV ON S.ServerID = SRV.ServerID -WHERE SD.ItemPosition BETWEEN @StartRow + 1 AND @StartRow + @MaximumRows' - -exec sp_executesql @sql, N'@StartRow int, @MaximumRows int, @PackageID int, @FilterValue nvarchar(50), @ServerID int, @Recursive bit', -@StartRow, @MaximumRows, @PackageID, @FilterValue, @ServerID, @Recursive - - -RETURN -GO - - - -IF NOT EXISTS (SELECT * FROM [dbo].[ScheduleTaskParameters] WHERE [ParameterID] = 'LYNC_REPORT') -BEGIN -INSERT [dbo].[ScheduleTaskParameters] ([TaskID], [ParameterID], [DataTypeID], [DefaultValue], [ParameterOrder]) VALUES (N'SCHEDULE_TASK_HOSTED_SOLUTION_REPORT', N'LYNC_REPORT', N'Boolean', N'true', 5) -END -GO - - - -ALTER PROCEDURE [dbo].[GetItemIdByOrganizationId] - @OrganizationId nvarchar(128) -AS -BEGIN - SET NOCOUNT ON; - - SELECT - ItemID - FROM - dbo.ExchangeOrganizations - WHERE - OrganizationId = @OrganizationId -END -GO - - - - - - -ALTER PROCEDURE [dbo].[SearchServiceItemsPaged] -( - @ActorID int, - @UserID int, - @ItemTypeID int, - @FilterValue nvarchar(50) = '', - @SortColumn nvarchar(50), - @StartRow int, - @MaximumRows int -) -AS - - --- check rights -IF dbo.CheckActorUserRights(@ActorID, @UserID) = 0 -RAISERROR('You are not allowed to access this account', 16, 1) - --- build query and run it to the temporary table -DECLARE @sql nvarchar(2000) - -IF @ItemTypeID <> 13 -BEGIN - SET @sql = ' - DECLARE @EndRow int - SET @EndRow = @StartRow + @MaximumRows - DECLARE @Items TABLE - ( - ItemPosition int IDENTITY(1,1), - ItemID int - ) - INSERT INTO @Items (ItemID) - SELECT - SI.ItemID - FROM ServiceItems AS SI - INNER JOIN Packages AS P ON P.PackageID = SI.PackageID - INNER JOIN UsersDetailed AS U ON P.UserID = U.UserID - WHERE - dbo.CheckUserParent(@UserID, P.UserID) = 1 - AND SI.ItemTypeID = @ItemTypeID - ' - - IF @FilterValue <> '' - SET @sql = @sql + ' AND SI.ItemName LIKE @FilterValue ' - - IF @SortColumn = '' OR @SortColumn IS NULL - SET @SortColumn = 'ItemName' - - SET @sql = @sql + ' ORDER BY ' + @SortColumn + ' ' - - SET @sql = @sql + ' SELECT COUNT(ItemID) FROM @Items; - SELECT - - SI.ItemID, - SI.ItemName, - - P.PackageID, - P.PackageName, - P.StatusID, - P.PurchaseDate, - - -- user - P.UserID, - U.Username, - U.FirstName, - U.LastName, - U.FullName, - U.RoleID, - U.Email - FROM @Items AS I - INNER JOIN ServiceItems AS SI ON I.ItemID = SI.ItemID - INNER JOIN Packages AS P ON SI.PackageID = P.PackageID - INNER JOIN UsersDetailed AS U ON P.UserID = U.UserID - WHERE I.ItemPosition BETWEEN @StartRow AND @EndRow' -END -ELSE -BEGIN - - SET @SortColumn = REPLACE(@SortColumn, 'ItemName', 'DomainName') - - SET @sql = ' - DECLARE @EndRow int - SET @EndRow = @StartRow + @MaximumRows - DECLARE @Items TABLE - ( - ItemPosition int IDENTITY(1,1), - ItemID int - ) - INSERT INTO @Items (ItemID) - SELECT - D.DomainID - FROM Domains AS D - INNER JOIN Packages AS P ON P.PackageID = D.PackageID - INNER JOIN UsersDetailed AS U ON P.UserID = U.UserID - WHERE - dbo.CheckUserParent(@UserID, P.UserID) = 1 - ' - - IF @FilterValue <> '' - SET @sql = @sql + ' AND D.DomainName LIKE @FilterValue ' - - IF @SortColumn = '' OR @SortColumn IS NULL - SET @SortColumn = 'DomainName' - - SET @sql = @sql + ' ORDER BY ' + @SortColumn + ' ' - - SET @sql = @sql + ' SELECT COUNT(ItemID) FROM @Items; - SELECT - - D.DomainID AS ItemID, - D.DomainName AS ItemName, - - P.PackageID, - P.PackageName, - P.StatusID, - P.PurchaseDate, - - -- user - P.UserID, - U.Username, - U.FirstName, - U.LastName, - U.FullName, - U.RoleID, - U.Email - FROM @Items AS I - INNER JOIN Domains AS D ON I.ItemID = D.DomainID - INNER JOIN Packages AS P ON D.PackageID = P.PackageID - INNER JOIN UsersDetailed AS U ON P.UserID = U.UserID - WHERE I.ItemPosition BETWEEN @StartRow AND @EndRow AND D.IsDomainPointer=0' -END - -exec sp_executesql @sql, N'@StartRow int, @MaximumRows int, @UserID int, @FilterValue nvarchar(50), @ItemTypeID int, @ActorID int', -@StartRow, @MaximumRows, @UserID, @FilterValue, @ItemTypeID, @ActorID - -RETURN -GO - - - - -IF NOT EXISTS (SELECT * FROM sys.objects WHERE type_desc = N'SQL_STORED_PROCEDURE' AND name = N'LyncUserExists') -BEGIN -EXEC sp_executesql N' -CREATE PROCEDURE [dbo].[LyncUserExists] -( - @AccountID int, - @SipAddress nvarchar(300), - @Exists bit OUTPUT -) -AS - - SET @Exists = 0 - IF EXISTS(SELECT * FROM [dbo].[ExchangeAccountEmailAddresses] WHERE [EmailAddress] = @SipAddress AND [AccountID] <> @AccountID) - BEGIN - SET @Exists = 1 - END - ELSE IF EXISTS(SELECT * FROM [dbo].[ExchangeAccounts] WHERE [PrimaryEmailAddress] = @SipAddress AND [AccountID] <> @AccountID) - BEGIN - SET @Exists = 1 - END - ELSE IF EXISTS(SELECT * FROM [dbo].[ExchangeAccounts] WHERE [UserPrincipalName] = @SipAddress AND [AccountID] <> @AccountID) - BEGIN - SET @Exists = 1 - END - ELSE IF EXISTS(SELECT * FROM [dbo].[ExchangeAccounts] WHERE [AccountName] = @SipAddress AND [AccountID] <> @AccountID) - BEGIN - SET @Exists = 1 - END - ELSE IF EXISTS(SELECT * FROM [dbo].[LyncUsers] WHERE [SipAddress] = @SipAddress) - BEGIN - SET @Exists = 1 - END - - - RETURN' -END -GO - - - - -ALTER PROCEDURE [dbo].[LyncUserExists] -( - @AccountID int, - @SipAddress nvarchar(300), - @Exists bit OUTPUT -) -AS - - SET @Exists = 0 - IF EXISTS(SELECT * FROM [dbo].[ExchangeAccountEmailAddresses] WHERE [EmailAddress] = @SipAddress AND [AccountID] <> @AccountID) - BEGIN - SET @Exists = 1 - END - ELSE IF EXISTS(SELECT * FROM [dbo].[ExchangeAccounts] WHERE [PrimaryEmailAddress] = @SipAddress AND [AccountID] <> @AccountID) - BEGIN - SET @Exists = 1 - END - ELSE IF EXISTS(SELECT * FROM [dbo].[ExchangeAccounts] WHERE [UserPrincipalName] = @SipAddress AND [AccountID] <> @AccountID) - BEGIN - SET @Exists = 1 - END - ELSE IF EXISTS(SELECT * FROM [dbo].[ExchangeAccounts] WHERE [AccountName] = @SipAddress AND [AccountID] <> @AccountID) - BEGIN - SET @Exists = 1 - END - ELSE IF EXISTS(SELECT * FROM [dbo].[LyncUsers] WHERE [SipAddress] = @SipAddress) - BEGIN - SET @Exists = 1 - END - - - RETURN -GO - - - - - -ALTER PROCEDURE [dbo].[AddLyncUser] - @AccountID int, - @LyncUserPlanID int, - @SipAddress nvarchar(300) -AS -INSERT INTO - dbo.LyncUsers - (AccountID, - LyncUserPlanID, - CreatedDate, - ModifiedDate, - SipAddress) -VALUES -( - @AccountID, - @LyncUserPlanID, - getdate(), - getdate(), - @SipAddress -) -GO - - -IF NOT EXISTS (SELECT * FROM sys.objects WHERE type_desc = N'SQL_STORED_PROCEDURE' AND name = N'UpdateLyncUser') -BEGIN -EXEC sp_executesql N'CREATE PROCEDURE [dbo].[UpdateLyncUser] -( - @AccountID int, - @SipAddress nvarchar(300) -) -AS - -UPDATE LyncUsers SET - SipAddress = @SipAddress -WHERE - AccountID = @AccountID - -RETURN' -END -GO - - - -IF NOT EXISTS (SELECT * FROM sys.objects WHERE type_desc = N'SQL_STORED_PROCEDURE' AND name = N'CheckDomainUsedByHostedOrganization') -BEGIN -EXEC sp_executesql N'CREATE PROCEDURE [dbo].[CheckDomainUsedByHostedOrganization] - @DomainName nvarchar(100), - @Result int OUTPUT -AS - SET @Result = 0 - IF EXISTS(SELECT 1 FROM ExchangeAccounts WHERE UserPrincipalName LIKE ''%@''+ @DomainName) - BEGIN - SET @Result = 1 - END - ELSE - IF EXISTS(SELECT 1 FROM ExchangeAccountEmailAddresses WHERE EmailAddress LIKE ''%@''+ @DomainName) - BEGIN - SET @Result = 1 - END - ELSE - IF EXISTS(SELECT 1 FROM LyncUsers WHERE SipAddress LIKE ''%@''+ @DomainName) - BEGIN - SET @Result = 1 - END - - RETURN @Result' -END -GO - - -IF NOT EXISTS (SELECT * FROM [dbo].[Quotas] WHERE [QuotaName] = 'HostedSolution.AllowChangeUPN') -BEGIN -INSERT [dbo].[Quotas] ([QuotaID], [GroupID], [QuotaOrder], [QuotaName], [QuotaDescription], [QuotaTypeID], [ServiceQuota], [ItemTypeID]) VALUES (230, 13, 4, N'HostedSolution.AllowChangeUPN', N'Allow to Change UserPrincipalName', 1, 0, NULL) -END -GO - - - - -IF NOT EXISTS (SELECT * FROM sys.objects WHERE type_desc = N'SQL_STORED_PROCEDURE' AND name = N'UpdateExchangeAccountUserPrincipalName') -BEGIN -EXEC sp_executesql N' CREATE PROCEDURE [dbo].[UpdateExchangeAccountUserPrincipalName] -( - @AccountID int, - @UserPrincipalName nvarchar(300) -) -AS - -UPDATE ExchangeAccounts SET - UserPrincipalName = @UserPrincipalName -WHERE - AccountID = @AccountID - -RETURN' -END -GO - - -IF NOT EXISTS (SELECT 1 FROM LyncUsers WHERE SipAddress IS NOT NULL) -BEGIN - UPDATE LyncUsers SET SipAddress=EA.PrimaryEmailAddress FROM ExchangeAccounts AS EA WHERE LyncUsers.SipAddress IS NULL AND LyncUsers.AccountID = EA.AccountID -END -GO \ No newline at end of file diff --git a/WebsitePanel/Lib/References/Microsoft/Exchange2013/Microsoft.Exchange.Common.dll b/WebsitePanel/Lib/References/Microsoft/Exchange2013/Microsoft.Exchange.Common.dll new file mode 100644 index 00000000..c6a7e6fe Binary files /dev/null and b/WebsitePanel/Lib/References/Microsoft/Exchange2013/Microsoft.Exchange.Common.dll differ diff --git a/WebsitePanel/Lib/References/Microsoft/Exchange2013/Microsoft.Exchange.Data.Directory.dll b/WebsitePanel/Lib/References/Microsoft/Exchange2013/Microsoft.Exchange.Data.Directory.dll new file mode 100644 index 00000000..9eb46c79 Binary files /dev/null and b/WebsitePanel/Lib/References/Microsoft/Exchange2013/Microsoft.Exchange.Data.Directory.dll differ diff --git a/WebsitePanel/Lib/References/Microsoft/Exchange2013/Microsoft.Exchange.Data.Storage.dll b/WebsitePanel/Lib/References/Microsoft/Exchange2013/Microsoft.Exchange.Data.Storage.dll new file mode 100644 index 00000000..fc67917c Binary files /dev/null and b/WebsitePanel/Lib/References/Microsoft/Exchange2013/Microsoft.Exchange.Data.Storage.dll differ diff --git a/WebsitePanel/Lib/References/Microsoft/Exchange2013/Microsoft.Exchange.Data.dll b/WebsitePanel/Lib/References/Microsoft/Exchange2013/Microsoft.Exchange.Data.dll new file mode 100644 index 00000000..b1ca6048 Binary files /dev/null and b/WebsitePanel/Lib/References/Microsoft/Exchange2013/Microsoft.Exchange.Data.dll differ diff --git a/WebsitePanel/Lib/References/Microsoft/Exchange2013/Microsoft.Exchange.Diagnostics.dll b/WebsitePanel/Lib/References/Microsoft/Exchange2013/Microsoft.Exchange.Diagnostics.dll new file mode 100644 index 00000000..6f654162 Binary files /dev/null and b/WebsitePanel/Lib/References/Microsoft/Exchange2013/Microsoft.Exchange.Diagnostics.dll differ diff --git a/WebsitePanel/Lib/References/Microsoft/Exchange2013/Microsoft.Exchange.Extensibility.Internal.dll b/WebsitePanel/Lib/References/Microsoft/Exchange2013/Microsoft.Exchange.Extensibility.Internal.dll new file mode 100644 index 00000000..f986790a Binary files /dev/null and b/WebsitePanel/Lib/References/Microsoft/Exchange2013/Microsoft.Exchange.Extensibility.Internal.dll differ diff --git a/WebsitePanel/Lib/References/Microsoft/Exchange2013/Microsoft.Exchange.Net.dll b/WebsitePanel/Lib/References/Microsoft/Exchange2013/Microsoft.Exchange.Net.dll new file mode 100644 index 00000000..15e67c9b Binary files /dev/null and b/WebsitePanel/Lib/References/Microsoft/Exchange2013/Microsoft.Exchange.Net.dll differ diff --git a/WebsitePanel/Lib/References/Microsoft/Windows2012/System.Management.Automation.dll b/WebsitePanel/Lib/References/Microsoft/Windows2012/System.Management.Automation.dll new file mode 100644 index 00000000..e77aa930 Binary files /dev/null and b/WebsitePanel/Lib/References/Microsoft/Windows2012/System.Management.Automation.dll differ diff --git a/WebsitePanel/Sources/VersionInfo.vb b/WebsitePanel/Sources/VersionInfo.vb index 1e9ef7fe..420d8cce 100644 --- a/WebsitePanel/Sources/VersionInfo.vb +++ b/WebsitePanel/Sources/VersionInfo.vb @@ -15,9 +15,9 @@ Imports System Imports System.Reflection Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices - diff --git a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer.Base/Packages/Quotas.cs b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer.Base/Packages/Quotas.cs index 7541d383..6444c610 100644 --- a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer.Base/Packages/Quotas.cs +++ b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer.Base/Packages/Quotas.cs @@ -114,6 +114,8 @@ order by rg.groupOrder public const string EXCHANGE2007_MAXRECEIVEMESSAGESIZEKB = "Exchange2007.MaxReceiveMessageSizeKB"; // Max Receive Message Size public const string EXCHANGE2007_ISCONSUMER = "Exchange2007.IsConsumer"; // Is Consumer Organization public const string EXCHANGE2007_ENABLEDPLANSEDITING = "Exchange2007.EnablePlansEditing"; // Enabled plans editing + public const string EXCHANGE2007_ALLOWLITIGATIONHOLD = "Exchange2007.AllowLitigationHold"; + public const string EXCHANGE2007_RECOVERABLEITEMSSPACE = "Exchange2007.RecoverableItemsSpace"; public const string MSSQL2000_DATABASES = "MsSQL2000.Databases"; // Databases public const string MSSQL2000_USERS = "MsSQL2000.Users"; // Users public const string MSSQL2000_MAXDATABASESIZE = "MsSQL2000.MaxDatabaseSize"; // Max Database Size diff --git a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer.Client/FilesProxy.cs b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer.Client/FilesProxy.cs index 9018d66a..984321d9 100644 --- a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer.Client/FilesProxy.cs +++ b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer.Client/FilesProxy.cs @@ -1238,6 +1238,17 @@ namespace WebsitePanel.EnterpriseServer { this.ExecuteSyncActionsCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } + + //CO Changes + /// + [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/ApplyEnableHardQuotaFeature", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] + public int ApplyEnableHardQuotaFeature(int packageId) + { + object[] results = this.Invoke("ApplyEnableHardQuotaFeature", new object[] { + packageId }); + return ((int)(results[0])); + } + //END /// public new void CancelAsync(object userState) { diff --git a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer.Client/OperatingSystemsProxy.cs b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer.Client/OperatingSystemsProxy.cs index f64b1da1..1d23ee54 100644 --- a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer.Client/OperatingSystemsProxy.cs +++ b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer.Client/OperatingSystemsProxy.cs @@ -463,6 +463,17 @@ namespace WebsitePanel.EnterpriseServer } } + //CO Changes + /// + [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/CheckFileServicesInstallation", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] + public bool CheckFileServicesInstallation(int serviceId) + { + object[] results = this.Invoke("CheckFileServicesInstallation", new object[] { + serviceId}); + return ((bool)(results[0])); + } + //END + /// public new void CancelAsync(object userState) { diff --git a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer.Client/WebServersProxy.cs b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer.Client/WebServersProxy.cs index f65d5497..d6a5c7f7 100644 --- a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer.Client/WebServersProxy.cs +++ b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer.Client/WebServersProxy.cs @@ -1208,9 +1208,11 @@ namespace WebsitePanel.EnterpriseServer { /// [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/DeleteWebSite", RequestNamespace="http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace="http://smbsaas/websitepanel/enterpriseserver", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] - public int DeleteWebSite(int siteItemId) { + public int DeleteWebSite(int siteItemId, bool deleteWebsiteDirectory) + { object[] results = this.Invoke("DeleteWebSite", new object[] { - siteItemId}); + siteItemId, + deleteWebsiteDirectory}); return ((int)(results[0])); } diff --git a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/Code/Common/CryptoUtils.cs b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/Code/Common/CryptoUtils.cs index 49fb4ab4..a126dfb4 100644 --- a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/Code/Common/CryptoUtils.cs +++ b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/Code/Common/CryptoUtils.cs @@ -31,6 +31,7 @@ using System.IO; using System.Text; using System.Security.Cryptography; using System.Configuration; +using Microsoft.Win32; namespace WebsitePanel.EnterpriseServer { @@ -39,9 +40,32 @@ namespace WebsitePanel.EnterpriseServer /// public class CryptoUtils { + static string EnterpriseServerRegistryPath = "SOFTWARE\\WebsitePanel\\EnterpriseServer"; + public static string CryptoKey { - get { return ConfigurationManager.AppSettings["WebsitePanel.CryptoKey"]; } + get + { + string Key = ConfigurationManager.AppSettings["WebsitePanel.AltCryptoKey"]; + string value = string.Empty; + + if (!string.IsNullOrEmpty(Key)) + { + RegistryKey root = Registry.LocalMachine; + RegistryKey rk = root.OpenSubKey(EnterpriseServerRegistryPath); + if (rk != null) + { + value = (string)rk.GetValue(Key, null); + rk.Close(); + } + } + + if (!string.IsNullOrEmpty(value)) + return value; + else + return ConfigurationManager.AppSettings["WebsitePanel.CryptoKey"]; + + } } public static bool EncryptionEnabled diff --git a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/Code/Data/DataProvider.cs b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/Code/Data/DataProvider.cs index a92f6776..d9eca5a3 100644 --- a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/Code/Data/DataProvider.cs +++ b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/Code/Data/DataProvider.cs @@ -34,6 +34,7 @@ using System.Text.RegularExpressions; using WebsitePanel.Providers.HostedSolution; using Microsoft.ApplicationBlocks.Data; using System.Collections.Generic; +using Microsoft.Win32; namespace WebsitePanel.EnterpriseServer { @@ -42,11 +43,31 @@ namespace WebsitePanel.EnterpriseServer /// public static class DataProvider { + + static string EnterpriseServerRegistryPath = "SOFTWARE\\WebsitePanel\\EnterpriseServer"; + private static string ConnectionString { get { - return ConfigurationManager.ConnectionStrings["EnterpriseServer"].ConnectionString; + string ConnectionKey = ConfigurationManager.AppSettings["WebsitePanel.AltConnectionString"]; + string value = string.Empty; + + if (!string.IsNullOrEmpty(ConnectionKey)) + { + RegistryKey root = Registry.LocalMachine; + RegistryKey rk = root.OpenSubKey(EnterpriseServerRegistryPath); + if (rk != null) + { + value = (string)rk.GetValue(ConnectionKey, null); + rk.Close(); + } + } + + if (!string.IsNullOrEmpty(value)) + return value; + else + return ConfigurationManager.ConnectionStrings["EnterpriseServer"].ConnectionString; } } @@ -2512,7 +2533,8 @@ namespace WebsitePanel.EnterpriseServer #region Exchange Mailbox Plans public static int AddExchangeMailboxPlan(int itemID, string mailboxPlan, bool enableActiveSync, bool enableIMAP, bool enableMAPI, bool enableOWA, bool enablePOP, bool isDefault, int issueWarningPct, int keepDeletedItemsDays, int mailboxSizeMB, int maxReceiveMessageSizeKB, int maxRecipients, - int maxSendMessageSizeKB, int prohibitSendPct, int prohibitSendReceivePct, bool hideFromAddressBook, int mailboxPlanType) + int maxSendMessageSizeKB, int prohibitSendPct, int prohibitSendReceivePct, bool hideFromAddressBook, int mailboxPlanType, + bool enabledLitigationHold, long recoverabelItemsSpace, long recoverabelItemsWarning) { SqlParameter outParam = new SqlParameter("@MailboxPlanId", SqlDbType.Int); outParam.Direction = ParameterDirection.Output; @@ -2539,7 +2561,10 @@ namespace WebsitePanel.EnterpriseServer new SqlParameter("@ProhibitSendPct", prohibitSendPct), new SqlParameter("@ProhibitSendReceivePct", prohibitSendReceivePct), new SqlParameter("@HideFromAddressBook", hideFromAddressBook), - new SqlParameter("@MailboxPlanType", mailboxPlanType) + new SqlParameter("@MailboxPlanType", mailboxPlanType), + new SqlParameter("@AllowLitigationHold",enabledLitigationHold), + new SqlParameter("@RecoverableItemsWarningPct", recoverabelItemsSpace), + new SqlParameter("@RecoverableItemsSpace",recoverabelItemsWarning) ); return Convert.ToInt32(outParam.Value); @@ -2549,7 +2574,8 @@ namespace WebsitePanel.EnterpriseServer public static void UpdateExchangeMailboxPlan(int mailboxPlanID, string mailboxPlan, bool enableActiveSync, bool enableIMAP, bool enableMAPI, bool enableOWA, bool enablePOP, bool isDefault, int issueWarningPct, int keepDeletedItemsDays, int mailboxSizeMB, int maxReceiveMessageSizeKB, int maxRecipients, - int maxSendMessageSizeKB, int prohibitSendPct, int prohibitSendReceivePct, bool hideFromAddressBook, int mailboxPlanType) + int maxSendMessageSizeKB, int prohibitSendPct, int prohibitSendReceivePct, bool hideFromAddressBook, int mailboxPlanType, + bool enabledLitigationHold, long recoverabelItemsSpace, long recoverabelItemsWarning) { SqlHelper.ExecuteNonQuery( ConnectionString, @@ -2572,7 +2598,10 @@ namespace WebsitePanel.EnterpriseServer new SqlParameter("@ProhibitSendPct", prohibitSendPct), new SqlParameter("@ProhibitSendReceivePct", prohibitSendReceivePct), new SqlParameter("@HideFromAddressBook", hideFromAddressBook), - new SqlParameter("@MailboxPlanType", mailboxPlanType) + new SqlParameter("@MailboxPlanType", mailboxPlanType), + new SqlParameter("@AllowLitigationHold", enabledLitigationHold), + new SqlParameter("@RecoverableItemsWarningPct", recoverabelItemsSpace), + new SqlParameter("@RecoverableItemsSpace", recoverabelItemsWarning) ); } diff --git a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/Code/ExchangeServer/ExchangeServerController.cs b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/Code/ExchangeServer/ExchangeServerController.cs index 9e8665bb..58c99fff 100644 --- a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/Code/ExchangeServer/ExchangeServerController.cs +++ b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/Code/ExchangeServer/ExchangeServerController.cs @@ -1709,6 +1709,25 @@ namespace WebsitePanel.EnterpriseServer return BusinessErrorCodes.ERROR_EXCHANGE_STORAGE_QUOTAS_EXCEED_HOST_VALUES; } + int maxRecoverableItemsSpace = -1; + int quotaRecoverableItemsUsed = 0; + if (cntx.Quotas.ContainsKey(Quotas.EXCHANGE2007_RECOVERABLEITEMSSPACE) + && cntx.Quotas[Quotas.EXCHANGE2007_RECOVERABLEITEMSSPACE].QuotaAllocatedValue > 0) + { + maxRecoverableItemsSpace = cntx.Quotas[Quotas.EXCHANGE2007_RECOVERABLEITEMSSPACE].QuotaAllocatedValue; + quotaRecoverableItemsUsed = cntx.Quotas[Quotas.EXCHANGE2007_RECOVERABLEITEMSSPACE].QuotaUsedValue; + } + + if (maxRecoverableItemsSpace != -1) + { + if (plan.RecoverableItemsSpace == -1) + return BusinessErrorCodes.ERROR_EXCHANGE_STORAGE_QUOTAS_EXCEED_HOST_VALUES; + + if ((quotaRecoverableItemsUsed + plan.RecoverableItemsSpace) > (maxRecoverableItemsSpace)) + return BusinessErrorCodes.ERROR_EXCHANGE_STORAGE_QUOTAS_EXCEED_HOST_VALUES; + } + + //GetServiceSettings StringDictionary primSettings = ServerController.GetServiceSettings(exchangeServiceId); @@ -1729,7 +1748,10 @@ namespace WebsitePanel.EnterpriseServer plan.MaxSendMessageSizeKB, plan.MaxReceiveMessageSizeKB, plan.HideFromAddressBook, - Convert.ToBoolean(cntx.Quotas[Quotas.EXCHANGE2007_ISCONSUMER].QuotaAllocatedValue)); + Convert.ToBoolean(cntx.Quotas[Quotas.EXCHANGE2007_ISCONSUMER].QuotaAllocatedValue), + plan.AllowLitigationHold, + plan.RecoverableItemsSpace != -1 ? (plan.RecoverableItemsSpace * 1024) : -1, + plan.RecoverableItemsSpace != -1 ? (((long)plan.RecoverableItemsWarningPct * (long)plan.RecoverableItemsSpace * 1024) / 100) : -1); MailboxManagerActions pmmActions = MailboxManagerActions.GeneralSettings | MailboxManagerActions.MailFlowSettings @@ -2653,6 +2675,24 @@ namespace WebsitePanel.EnterpriseServer } } + int maxRecoverableItemsSpace = -1; + int quotaRecoverableItemsUsed = 0; + if (cntx.Quotas.ContainsKey(Quotas.EXCHANGE2007_RECOVERABLEITEMSSPACE) + && cntx.Quotas[Quotas.EXCHANGE2007_RECOVERABLEITEMSSPACE].QuotaAllocatedValue > 0) + { + maxRecoverableItemsSpace = cntx.Quotas[Quotas.EXCHANGE2007_RECOVERABLEITEMSSPACE].QuotaAllocatedValue; + quotaRecoverableItemsUsed = cntx.Quotas[Quotas.EXCHANGE2007_RECOVERABLEITEMSSPACE].QuotaUsedValue; + } + + if (maxRecoverableItemsSpace != -1) + { + if (plan.RecoverableItemsSpace == -1) + return BusinessErrorCodes.ERROR_EXCHANGE_STORAGE_QUOTAS_EXCEED_HOST_VALUES; + + if ((quotaRecoverableItemsUsed + plan.RecoverableItemsSpace) > (maxRecoverableItemsSpace)) + return BusinessErrorCodes.ERROR_EXCHANGE_STORAGE_QUOTAS_EXCEED_HOST_VALUES; + } + // get mailbox settings int exchangeServiceId = GetExchangeServiceID(org.PackageId); ExchangeServer exchange = GetExchangeServer(exchangeServiceId, org.ServiceId); @@ -2671,7 +2711,10 @@ namespace WebsitePanel.EnterpriseServer plan.KeepDeletedItemsDays, plan.MaxRecipients, plan.MaxSendMessageSizeKB, - plan.MaxReceiveMessageSizeKB); + plan.MaxReceiveMessageSizeKB, + plan.AllowLitigationHold, + plan.RecoverableItemsSpace != -1 ? (plan.RecoverableItemsSpace * 1024) : -1, + plan.RecoverableItemsSpace != -1 ? (((long)plan.RecoverableItemsWarningPct * (long)plan.RecoverableItemsSpace * 1024) / 100) : -1); DataProvider.SetExchangeAccountMailboxPlan(accountId, mailboxPlanId); @@ -2835,11 +2878,18 @@ namespace WebsitePanel.EnterpriseServer mailboxPlan.MaxRecipients = cntx.Quotas[Quotas.EXCHANGE2007_MAXRECIPIENTS].QuotaAllocatedValue; if (Convert.ToBoolean(cntx.Quotas[Quotas.EXCHANGE2007_ISCONSUMER].QuotaAllocatedValue)) mailboxPlan.HideFromAddressBook = true; + + mailboxPlan.AllowLitigationHold = mailboxPlan.AllowLitigationHold & Convert.ToBoolean(cntx.Quotas[Quotas.EXCHANGE2007_ALLOWLITIGATIONHOLD].QuotaAllocatedValue); + + if (cntx.Quotas[Quotas.EXCHANGE2007_RECOVERABLEITEMSSPACE].QuotaAllocatedValue != -1) + if (mailboxPlan.RecoverableItemsSpace > cntx.Quotas[Quotas.EXCHANGE2007_RECOVERABLEITEMSSPACE].QuotaAllocatedValue) + mailboxPlan.RecoverableItemsSpace = cntx.Quotas[Quotas.EXCHANGE2007_RECOVERABLEITEMSSPACE].QuotaAllocatedValue; } return DataProvider.AddExchangeMailboxPlan(itemID, mailboxPlan.MailboxPlan, mailboxPlan.EnableActiveSync, mailboxPlan.EnableIMAP, mailboxPlan.EnableMAPI, mailboxPlan.EnableOWA, mailboxPlan.EnablePOP, mailboxPlan.IsDefault, mailboxPlan.IssueWarningPct, mailboxPlan.KeepDeletedItemsDays, mailboxPlan.MailboxSizeMB, mailboxPlan.MaxReceiveMessageSizeKB, mailboxPlan.MaxRecipients, - mailboxPlan.MaxSendMessageSizeKB, mailboxPlan.ProhibitSendPct, mailboxPlan.ProhibitSendReceivePct, mailboxPlan.HideFromAddressBook, mailboxPlan.MailboxPlanType); + mailboxPlan.MaxSendMessageSizeKB, mailboxPlan.ProhibitSendPct, mailboxPlan.ProhibitSendReceivePct, mailboxPlan.HideFromAddressBook, mailboxPlan.MailboxPlanType, + mailboxPlan.AllowLitigationHold, mailboxPlan.RecoverableItemsSpace, mailboxPlan.RecoverableItemsWarningPct); } catch (Exception ex) { @@ -2897,11 +2947,19 @@ namespace WebsitePanel.EnterpriseServer mailboxPlan.MaxRecipients = cntx.Quotas[Quotas.EXCHANGE2007_MAXRECIPIENTS].QuotaAllocatedValue; if (Convert.ToBoolean(cntx.Quotas[Quotas.EXCHANGE2007_ISCONSUMER].QuotaAllocatedValue)) mailboxPlan.HideFromAddressBook = true; + + mailboxPlan.AllowLitigationHold = mailboxPlan.AllowLitigationHold & Convert.ToBoolean(cntx.Quotas[Quotas.EXCHANGE2007_ALLOWLITIGATIONHOLD].QuotaAllocatedValue); + + if (cntx.Quotas[Quotas.EXCHANGE2007_RECOVERABLEITEMSSPACE].QuotaAllocatedValue != -1) + if (mailboxPlan.RecoverableItemsSpace > cntx.Quotas[Quotas.EXCHANGE2007_RECOVERABLEITEMSSPACE].QuotaAllocatedValue) + mailboxPlan.RecoverableItemsSpace = cntx.Quotas[Quotas.EXCHANGE2007_RECOVERABLEITEMSSPACE].QuotaAllocatedValue; + } DataProvider.UpdateExchangeMailboxPlan(mailboxPlan.MailboxPlanId, mailboxPlan.MailboxPlan, mailboxPlan.EnableActiveSync, mailboxPlan.EnableIMAP, mailboxPlan.EnableMAPI, mailboxPlan.EnableOWA, mailboxPlan.EnablePOP, mailboxPlan.IsDefault, mailboxPlan.IssueWarningPct, mailboxPlan.KeepDeletedItemsDays, mailboxPlan.MailboxSizeMB, mailboxPlan.MaxReceiveMessageSizeKB, mailboxPlan.MaxRecipients, - mailboxPlan.MaxSendMessageSizeKB, mailboxPlan.ProhibitSendPct, mailboxPlan.ProhibitSendReceivePct, mailboxPlan.HideFromAddressBook, mailboxPlan.MailboxPlanType); + mailboxPlan.MaxSendMessageSizeKB, mailboxPlan.ProhibitSendPct, mailboxPlan.ProhibitSendReceivePct, mailboxPlan.HideFromAddressBook, mailboxPlan.MailboxPlanType, + mailboxPlan.AllowLitigationHold, mailboxPlan.RecoverableItemsSpace, mailboxPlan.RecoverableItemsWarningPct); } catch (Exception ex) { diff --git a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/Code/Files/FilesController.cs b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/Code/Files/FilesController.cs index 7784cad8..e9dc8e48 100644 --- a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/Code/Files/FilesController.cs +++ b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/Code/Files/FilesController.cs @@ -912,5 +912,163 @@ namespace WebsitePanel.EnterpriseServer return users.ToArray(); } + + public static int SetFolderQuota(int packageId, string path, string driveName) + { + + // check account + int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive); + if (accountCheck < 0) return accountCheck; + + // check package + int packageCheck = SecurityContext.CheckPackage(packageId, DemandPackage.IsActive); + if (packageCheck < 0) return packageCheck; + + // place log record + TaskManager.StartTask("FILES", "SET_QUOTA_ON_FOLDER", path); + TaskManager.ItemId = packageId; + + try + { + + // disk space quota + // This gets all the disk space allocated for a specific customer + // It includes the package Add Ons * Quatity + Hosting Plan System disk space value. + QuotaValueInfo diskSpaceQuota = PackageController.GetPackageQuota(packageId, Quotas.OS_DISKSPACE); + + + #region figure Quota Unit + + // Quota Unit + string unit = String.Empty; + if (diskSpaceQuota.QuotaDescription.ToLower().Contains("gb")) + unit = "GB"; + else if (diskSpaceQuota.QuotaDescription.ToLower().Contains("mb")) + unit = "MB"; + else + unit = "KB"; + + #endregion + + OS.OperatingSystem os = GetOS(packageId); + + os.SetQuotaLimitOnFolder(path, driveName, diskSpaceQuota.QuotaAllocatedValue.ToString() + unit, 0, String.Empty, String.Empty); + + return 0; + } + catch (Exception ex) + { + //Log and return a generic error rather than throwing an exception + TaskManager.WriteError(ex); + return BusinessErrorCodes.ERROR_FILE_GENERIC_LOGGED; + } + finally + { + TaskManager.CompleteTask(); + } + + + } + + public static int ApplyEnableHardQuotaFeature(int packageId) + { + if (SecurityContext.CheckAccount(DemandAccount.IsActive | DemandAccount.IsAdmin | DemandAccount.NotDemo) != 0) + throw new Exception("This method could be called by serveradmin only."); + + // place log record + TaskManager.StartTask("FILES", "APPLY_ENABLEHARDQUOTAFEATURE"); + + try + { + + // request OS service + //int osId = PackageController.GetPackageServiceId(packageId, ResourceGroups.Os); + //if (osId == 0) + // return -1; + + //OS.OperatingSystem os = new OS.OperatingSystem(); + //ServiceProviderProxy.Init(os, osId); + + ////Get operating system settings + // StringDictionary osSesstings = ServerController.GetServiceSettings(osId); + // bool diskQuotaEnabled = (osSesstings["EnableHardQuota"] != null) ? bool.Parse(osSesstings["EnableHardQuota"]) : false; + //string driveName = osSesstings["LocationDrive"]; + + //if (!diskQuotaEnabled) + // return -1; + + + List allPackages = PackageController.GetPackagePackages(packageId, true); + + foreach (PackageInfo childPackage in allPackages) + { + // request OS service + int osId = PackageController.GetPackageServiceId(childPackage.PackageId, ResourceGroups.Os); + if (osId == 0) + continue; + + OS.OperatingSystem os = new OS.OperatingSystem(); + ServiceProviderProxy.Init(os, osId); + + //Get operating system settings + StringDictionary osSesstings = ServerController.GetServiceSettings(osId); + string driveName = osSesstings["LocationDrive"]; + + if (String.IsNullOrEmpty(driveName)) + continue; + + string homeFolder = FilesController.GetHomeFolder(childPackage.PackageId); + FilesController.SetFolderQuota(childPackage.PackageId, homeFolder, driveName); + } + } + catch (Exception ex) + { + throw TaskManager.WriteError(ex); + } + finally + { + TaskManager.CompleteTask(); + } + + return 0; + + } + + public static int DeleteDirectoryRecursive(int packageId, string rootPath) + { + + // check account + int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive); + if (accountCheck < 0) return accountCheck; + + // check package + int packageCheck = SecurityContext.CheckPackage(packageId, DemandPackage.IsActive); + if (packageCheck < 0) return packageCheck; + + // place log record + TaskManager.StartTask("FILES", "DELETE_DIRECTORY_RECURSIVE", rootPath); + TaskManager.ItemId = packageId; + + try + { + + OS.OperatingSystem os = GetOS(packageId); + os.DeleteDirectoryRecursive(rootPath); + + return 0; + } + catch (Exception ex) + { + //Log and return a generic error rather than throwing an exception + TaskManager.WriteError(ex); + return BusinessErrorCodes.ERROR_FILE_GENERIC_LOGGED; + } + finally + { + TaskManager.CompleteTask(); + } + + + } } } diff --git a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/Code/OperatingSystems/OperatingSystemController.cs b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/Code/OperatingSystems/OperatingSystemController.cs index 2e6bc7bb..238ec360 100644 --- a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/Code/OperatingSystems/OperatingSystemController.cs +++ b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/Code/OperatingSystems/OperatingSystemController.cs @@ -406,6 +406,15 @@ namespace WebsitePanel.EnterpriseServer TaskManager.CompleteTask(); } } + + // Check If FSRM Role services were installed + public static bool CheckFileServicesInstallation(int serviceId) + { + OS.OperatingSystem os = GetOS(serviceId); + return os.CheckFileServicesInstallation(); + + } + #endregion #region Web Platform Installer diff --git a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/Code/Packages/PackageController.cs b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/Code/Packages/PackageController.cs index fd61926f..3363a13f 100644 --- a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/Code/Packages/PackageController.cs +++ b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/Code/Packages/PackageController.cs @@ -770,6 +770,9 @@ namespace WebsitePanel.EnterpriseServer if (result.ExceedingQuotas.Tables[0].Rows.Count > 0) result.Result = BusinessErrorCodes.ERROR_PACKAGE_QUOTA_EXCEED; + + // Update the Hard quota on home folder in case it was enabled and in case there was a change in disk space + UpdatePackageHardQuota(package.PackageId); } finally { @@ -963,6 +966,9 @@ namespace WebsitePanel.EnterpriseServer homeFolder.PackageId = packageId; homeFolder.Name = path; + // Added By Haya + UpdatePackageHardQuota(packageId); + // save package item return AddPackageItem(homeFolder); } @@ -976,6 +982,30 @@ namespace WebsitePanel.EnterpriseServer { DataProvider.UpdatePackageBandwidthUpdate(packageId, updateDate); } + + // This gets the system quota and updates the home folder with the value + public static void UpdatePackageHardQuota(int packageId) + { + // request OS service + int osId = GetPackageServiceId(packageId, ResourceGroups.Os); + if (osId == 0) + return; + + OS.OperatingSystem os = new OS.OperatingSystem(); + ServiceProviderProxy.Init(os, osId); + + //Get operating system settings + StringDictionary osSesstings = ServerController.GetServiceSettings(osId); + bool diskQuotaEnabled = (osSesstings["EnableHardQuota"] != null) ? bool.Parse(osSesstings["EnableHardQuota"]) : false; + string driveName = osSesstings["LocationDrive"]; + + if (!diskQuotaEnabled) + return; + + string homeFolder = FilesController.GetHomeFolder(packageId); + FilesController.SetFolderQuota(packageId, homeFolder, driveName); + + } #endregion @@ -1035,6 +1065,8 @@ namespace WebsitePanel.EnterpriseServer result.Result = addonId; + // Update the Hard quota on home folder in case it was enabled and in case there was a change in disk space + UpdatePackageHardQuota(addon.PackageId); return result; } @@ -1062,6 +1094,9 @@ namespace WebsitePanel.EnterpriseServer if (result.ExceedingQuotas.Tables[0].Rows.Count > 0) result.Result = BusinessErrorCodes.ERROR_PACKAGE_QUOTA_EXCEED; + // Update the Hard quota on home folder in case it was enabled and in case there was a change in disk space + UpdatePackageHardQuota(addon.PackageId); + return result; } @@ -1072,6 +1107,10 @@ namespace WebsitePanel.EnterpriseServer | DemandAccount.IsReseller); if (accountCheck < 0) return accountCheck; + + // Update the Hard quota on home folder in case it was enabled and in case there was a change in disk space + UpdatePackageHardQuota(GetPackageAddon(packageAddonId).PackageId); + DataProvider.DeletePackageAddon(SecurityContext.User.UserId, packageAddonId); return 0; diff --git a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/Code/WebServers/WebServerController.cs b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/Code/WebServers/WebServerController.cs index a0b96690..ae8a13bd 100644 --- a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/Code/WebServers/WebServerController.cs +++ b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/Code/WebServers/WebServerController.cs @@ -583,7 +583,7 @@ namespace WebsitePanel.EnterpriseServer } } - public static int DeleteWebSite(int siteItemId) + public static int DeleteWebSite(int siteItemId, bool deleteWebsiteDirectory) { // check account int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive); @@ -655,6 +655,16 @@ namespace WebsitePanel.EnterpriseServer // web.DeleteSite(siteItem.SiteId); + // Delete WebManagementAccess Account + WebServerController.RevokeWebManagementAccess(siteItemId); + + if (deleteWebsiteDirectory) + { + // Delete website directory from file server + // This will remove the hard quota as well + FilesController.DeleteDirectoryRecursive(siteItem.PackageId, new DirectoryInfo(siteItem.DataPath).Parent.FullName); + + } // delete service item PackageController.DeletePackageItem(siteItemId); diff --git a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/Web.config b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/Web.config index 3766094f..99362901 100644 --- a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/Web.config +++ b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/Web.config @@ -18,6 +18,9 @@ + + + diff --git a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/WebsitePanel.EnterpriseServer.csproj b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/WebsitePanel.EnterpriseServer.csproj index 8ba3e5cb..8dba7817 100644 --- a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/WebsitePanel.EnterpriseServer.csproj +++ b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/WebsitePanel.EnterpriseServer.csproj @@ -20,6 +20,10 @@ v4.0 false + + + + true @@ -411,9 +415,6 @@ - - Designer - diff --git a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/esFiles.asmx.cs b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/esFiles.asmx.cs index 15a64d0d..14b2b455 100644 --- a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/esFiles.asmx.cs +++ b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/esFiles.asmx.cs @@ -193,5 +193,13 @@ namespace WebsitePanel.EnterpriseServer { FilesController.ExecuteSyncActions(packageId, actions); } + + //CO Changes + [WebMethod] + public int ApplyEnableHardQuotaFeature(int packageId) + { + return FilesController.ApplyEnableHardQuotaFeature(packageId); + } + //END } } diff --git a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/esOperatingSystems.asmx.cs b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/esOperatingSystems.asmx.cs index e8b01891..807901a9 100644 --- a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/esOperatingSystems.asmx.cs +++ b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/esOperatingSystems.asmx.cs @@ -93,5 +93,13 @@ namespace WebsitePanel.EnterpriseServer { return OperatingSystemController.DeleteOdbcSource(itemId); } + + //CO Changes + [WebMethod] + public bool CheckFileServicesInstallation(int serviceId) + { + return OperatingSystemController.CheckFileServicesInstallation(serviceId); + } + //END } } diff --git a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/esWebServers.asmx.cs b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/esWebServers.asmx.cs index 3c1a6034..b1c1bfce 100644 --- a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/esWebServers.asmx.cs +++ b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/esWebServers.asmx.cs @@ -152,9 +152,9 @@ namespace WebsitePanel.EnterpriseServer } [WebMethod] - public int DeleteWebSite(int siteItemId) + public int DeleteWebSite(int siteItemId, bool deleteWebsiteDirectory) { - return WebServerController.DeleteWebSite(siteItemId); + return WebServerController.DeleteWebSite(siteItemId, deleteWebsiteDirectory); } [WebMethod] diff --git a/WebsitePanel/Sources/WebsitePanel.Providers.Base/HostedSolution/ExchangeMailbox.cs b/WebsitePanel/Sources/WebsitePanel.Providers.Base/HostedSolution/ExchangeMailbox.cs index e8bbee84..69c8bb69 100644 --- a/WebsitePanel/Sources/WebsitePanel.Providers.Base/HostedSolution/ExchangeMailbox.cs +++ b/WebsitePanel/Sources/WebsitePanel.Providers.Base/HostedSolution/ExchangeMailbox.cs @@ -98,6 +98,10 @@ namespace WebsitePanel.Providers.HostedSolution DateTime lastLogon; DateTime lastLogoff; + bool enableLitigationHold; + long recoverabelItemsSpace; + long recoverabelItemsWarning; + public string DisplayName @@ -399,5 +403,26 @@ namespace WebsitePanel.Providers.HostedSolution get { return fullAccessAccounts; } set { fullAccessAccounts = value; } } + + + public bool EnableLitigationHold + { + get { return enableLitigationHold; } + set { enableLitigationHold = value; } + } + + + public long RecoverabelItemsSpace + { + get { return this.recoverabelItemsSpace; } + set { this.recoverabelItemsSpace = value; } + } + + public long RecoverabelItemsWarning + { + get { return this.recoverabelItemsWarning; } + set { this.recoverabelItemsWarning = value; } + } + } } diff --git a/WebsitePanel/Sources/WebsitePanel.Providers.Base/HostedSolution/ExchangeMailboxPlan.cs b/WebsitePanel/Sources/WebsitePanel.Providers.Base/HostedSolution/ExchangeMailboxPlan.cs index 8b249c6e..34125367 100644 --- a/WebsitePanel/Sources/WebsitePanel.Providers.Base/HostedSolution/ExchangeMailboxPlan.cs +++ b/WebsitePanel/Sources/WebsitePanel.Providers.Base/HostedSolution/ExchangeMailboxPlan.cs @@ -56,6 +56,10 @@ namespace WebsitePanel.Providers.HostedSolution bool hideFromAddressBook; int mailboxPlanType; + bool allowLitigationHold; + int recoverableItemsWarningPct; + int recoverableItemsSpace; + public int ItemId { @@ -173,5 +177,24 @@ namespace WebsitePanel.Providers.HostedSolution set { this.hideFromAddressBook = value; } } + + public bool AllowLitigationHold + { + get { return this.allowLitigationHold; } + set { this.allowLitigationHold = value; } + } + + public int RecoverableItemsWarningPct + { + get { return this.recoverableItemsWarningPct; } + set { this.recoverableItemsWarningPct = value; } + } + + public int RecoverableItemsSpace + { + get { return this.recoverableItemsSpace; } + set { this.recoverableItemsSpace = value; } + } + } } diff --git a/WebsitePanel/Sources/WebsitePanel.Providers.Base/HostedSolution/ExchangeMailboxStatistics.cs b/WebsitePanel/Sources/WebsitePanel.Providers.Base/HostedSolution/ExchangeMailboxStatistics.cs index 7b408e10..040d55ca 100644 --- a/WebsitePanel/Sources/WebsitePanel.Providers.Base/HostedSolution/ExchangeMailboxStatistics.cs +++ b/WebsitePanel/Sources/WebsitePanel.Providers.Base/HostedSolution/ExchangeMailboxStatistics.cs @@ -37,6 +37,7 @@ namespace WebsitePanel.Providers.HostedSolution public string DisplayName{ get; set; } public DateTime AccountCreated { get; set; } public string PrimaryEmailAddress { get; set; } + public bool LitigationHoldEnabled { get; set; } public bool POPEnabled { get; set; } public bool IMAPEnabled { get; set; } public bool OWAEnabled { get; set; } @@ -45,6 +46,9 @@ namespace WebsitePanel.Providers.HostedSolution public int TotalItems { get; set; } public long TotalSize { get; set; } public long MaxSize { get; set; } + public long LitigationHoldTotalSize { get; set; } + public long LitigationHoldTotalItems { get; set; } + public long LitigationHoldMaxSize { get; set; } public DateTime LastLogon { get; set; } public DateTime LastLogoff { get; set; } public bool Enabled { get; set; } diff --git a/WebsitePanel/Sources/WebsitePanel.Providers.Base/HostedSolution/IExchangeServer.cs b/WebsitePanel/Sources/WebsitePanel.Providers.Base/HostedSolution/IExchangeServer.cs index dbbefc58..66173f60 100644 --- a/WebsitePanel/Sources/WebsitePanel.Providers.Base/HostedSolution/IExchangeServer.cs +++ b/WebsitePanel/Sources/WebsitePanel.Providers.Base/HostedSolution/IExchangeServer.cs @@ -39,7 +39,7 @@ namespace WebsitePanel.Providers.HostedSolution string accountName, bool enablePOP, bool enableIMAP, bool enableOWA, bool enableMAPI, bool enableActiveSync, long issueWarningKB, long prohibitSendKB, long prohibitSendReceiveKB, - int keepDeletedItemsDays, int maxRecipients, int maxSendMessageSizeKB, int maxReceiveMessageSizeKB, bool hideFromAddressBook, bool isConsumer); + int keepDeletedItemsDays, int maxRecipients, int maxSendMessageSizeKB, int maxReceiveMessageSizeKB, bool hideFromAddressBook, bool isConsumer, bool enabledLitigationHold, long recoverabelItemsSpace, long recoverabelItemsWarning); Organization ExtendToExchangeOrganization(string organizationId, string securityGroup, bool IsConsumer); string GetOABVirtualDirectory(); @@ -57,8 +57,6 @@ namespace WebsitePanel.Providers.HostedSolution string[] GetAuthoritativeDomains(); // Mailboxes - //string CreateMailbox(string organizationId, string organizationDistinguishedName, string mailboxDatabase, string securityGroup, string offlineAddressBook, string addressBookPolicy, ExchangeAccountType accountType, string displayName, string accountName, string name, string domain, string password, bool enablePOP, bool enableIMAP, bool enableOWA, bool enableMAPI, bool enableActiveSync, - // int issueWarningKB, int prohibitSendKB, int prohibitSendReceiveKB, int keepDeletedItemsDays, int maxRecipients, int maxSendMessageSizeKB, int maxReceiveMessageSizeKB,bool hideFromAddressBook); void DeleteMailbox(string accountName); void DisableMailbox(string id); ExchangeMailbox GetMailboxGeneralSettings(string accountName); @@ -66,7 +64,7 @@ namespace WebsitePanel.Providers.HostedSolution ExchangeMailbox GetMailboxMailFlowSettings(string accountName); void SetMailboxMailFlowSettings(string accountName, bool enableForwarding, string forwardingAccountName, bool forwardToBoth, string[] sendOnBehalfAccounts, string[] acceptAccounts, string[] rejectAccounts, bool requireSenderAuthentication); ExchangeMailbox GetMailboxAdvancedSettings(string accountName); - void SetMailboxAdvancedSettings(string organizationId, string accountName, bool enablePOP, bool enableIMAP, bool enableOWA, bool enableMAPI, bool enableActiveSync, long issueWarningKB, long prohibitSendKB, long prohibitSendReceiveKB, int keepDeletedItemsDays, int maxRecipients, int maxSendMessageSizeKB, int maxReceiveMessageSizeKB); + void SetMailboxAdvancedSettings(string organizationId, string accountName, bool enablePOP, bool enableIMAP, bool enableOWA, bool enableMAPI, bool enableActiveSync, long issueWarningKB, long prohibitSendKB, long prohibitSendReceiveKB, int keepDeletedItemsDays, int maxRecipients, int maxSendMessageSizeKB, int maxReceiveMessageSizeKB, bool enabledLitigationHold, long recoverabelItemsSpace, long recoverabelItemsWarning); ExchangeEmailAddress[] GetMailboxEmailAddresses(string accountName); void SetMailboxEmailAddresses(string accountName, string[] emailAddresses); void SetMailboxPrimaryEmailAddress(string accountName, string emailAddress); diff --git a/WebsitePanel/Sources/WebsitePanel.Providers.Base/HostedSolution/IOrganization.cs b/WebsitePanel/Sources/WebsitePanel.Providers.Base/HostedSolution/IOrganization.cs index e3ce875d..09e1a3de 100644 --- a/WebsitePanel/Sources/WebsitePanel.Providers.Base/HostedSolution/IOrganization.cs +++ b/WebsitePanel/Sources/WebsitePanel.Providers.Base/HostedSolution/IOrganization.cs @@ -54,7 +54,7 @@ namespace WebsitePanel.Providers.HostedSolution void SetUserPassword(string organizationId, string accountName, string password); void SetUserPrincipalName(string organizationId, string accountName, string userPrincipalName); - + bool OrganizationExists(string organizationId); void DeleteOrganizationDomain(string organizationDistinguishedName, string domain); diff --git a/WebsitePanel/Sources/WebsitePanel.Providers.Base/OS/IOperatingSystem.cs b/WebsitePanel/Sources/WebsitePanel.Providers.Base/OS/IOperatingSystem.cs index fc9f3076..0877a008 100644 --- a/WebsitePanel/Sources/WebsitePanel.Providers.Base/OS/IOperatingSystem.cs +++ b/WebsitePanel/Sources/WebsitePanel.Providers.Base/OS/IOperatingSystem.cs @@ -81,5 +81,11 @@ namespace WebsitePanel.Providers.OS // Synchronizing FolderGraph GetFolderGraph(string path); void ExecuteSyncActions(FileSyncAction[] actions); + + void SetQuotaLimitOnFolder(string folderPath, string shareNameDrive, string quotaLimit, int mode, string wmiUserName, string wmiPassword); + void DeleteDirectoryRecursive(string rootPath); + + // File Services + bool CheckFileServicesInstallation(); } } diff --git a/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution.Exchange2013/Exchange2013.cs b/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution.Exchange2013/Exchange2013.cs new file mode 100644 index 00000000..a84b9d18 --- /dev/null +++ b/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution.Exchange2013/Exchange2013.cs @@ -0,0 +1,6905 @@ +// Copyright (c) 2012, Outercurve Foundation. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// - Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// +// - Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// - Neither the name of the Outercurve Foundation nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +using System; +using System.IO; +using System.Configuration; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Text; +using System.Reflection; +using System.Globalization; +using System.Collections; + +using System.DirectoryServices; +using System.Security; +using System.Security.Principal; +using System.Security.AccessControl; + +using System.Management.Automation; +using System.Management.Automation.Runspaces; + +using WebsitePanel.Providers; +using WebsitePanel.Providers.HostedSolution; +using WebsitePanel.Providers.Utils; +using WebsitePanel.Server.Utils; +using Microsoft.Exchange.Data.Directory.Recipient; +using Microsoft.Win32; + +using Microsoft.Exchange.Data; +using Microsoft.Exchange.Data.Directory; +using Microsoft.Exchange.Data.Storage; + +namespace WebsitePanel.Providers.HostedSolution +{ + public class Exchange2013 : HostingServiceProviderBase, IExchangeServer + { + + static private Hashtable htBbalancer = new Hashtable(); + + static Exchange2013() + { + AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(ResolveExchangeAssembly); + ExchangeRegistryPath = "SOFTWARE\\Microsoft\\ExchangeServer\\v15\\Setup"; + } + + #region Constants + private const string CONFIG_CLEAR_QUERYBASEDN = "WebsitePanel.Exchange.ClearQueryBaseDN"; + #endregion + + #region Properties + + internal string RootOU + { + get { return ProviderSettings["RootOU"]; } + } + + internal string StorageGroup + { + get { return ProviderSettings["StorageGroup"]; } + } + + internal string MailboxDatabase + { + get { return ProviderSettings["MailboxDatabase"]; } + } + + internal bool PublicFolderDistributionEnabled + { + get { return ProviderSettings.GetBool("PublicFolderDistributionEnabled"); } + } + + internal int KeepDeletedItemsDays + { + get { return Int32.Parse(ProviderSettings["KeepDeletedItemsDays"]); } + } + + internal int KeepDeletedMailboxesDays + { + get { return Int32.Parse(ProviderSettings["KeepDeletedMailboxesDays"]); } + } + + internal string RootDomain + { + get { return ServerSettings.ADRootDomain; } + } + + internal string MailboxCluster + { + get { return ProviderSettings["MailboxCluster"]; } + } + + internal string PrimaryDomainController + { + get { return ProviderSettings["PrimaryDomainController"]; } + } + + internal string PublicFolderServer + { + get { return ProviderSettings["PublicFolderServer"]; } + } + + internal string OABGenerationServer + { + get { return ProviderSettings["OABServer"]; } + } + + internal static string ExchangeRegistryPath + { + get; + set; + } + + internal virtual string ExchangeSnapInName + { + get { return "Microsoft.Exchange.Management.PowerShell.E2010"; } + } + + #endregion + + #region IExchangeServer Members + + #region Common + public bool CheckAccountCredentials(string username, string password) + { + return CheckAccountCredentialsInternal(username, password); + } + #endregion + + #region Organizations + + /// + /// Extend existing organization with exchange functionality + /// + /// + /// + /// + public Organization ExtendToExchangeOrganization(string organizationId, string securityGroup, bool IsConsumer) + { + return ExtendToExchangeOrganizationInternal(organizationId, securityGroup, IsConsumer); + } + + /// + /// Creates organization OAB on the Client Access Server + /// + /// + /// + /// + public Organization CreateOrganizationOfflineAddressBook(string organizationId, string securityGroup, string oabVirtualDir) + { + return CreateOrganizationOfflineAddressBookInternal(organizationId, securityGroup, oabVirtualDir); + } + + /// + /// Updates organization OAB + /// + /// + public void UpdateOrganizationOfflineAddressBook(string oabId) + { + UpdateOrganizationOfflineAddressBookInternal(oabId); + } + + + public string GetOABVirtualDirectory() + { + return GetOABVirtualDirectoryInternal(); + } + + public Organization CreateOrganizationAddressBookPolicy(string organizationId, string gal, string addressBook, string roomList, string oab) + { + return CreateOrganizationAddressBookPolicyInternal(organizationId, gal, addressBook, roomList, oab); + } + + public bool DeleteOrganization(string organizationId, string distinguishedName, + string globalAddressList, string addressList, string roomList, string offlineAddressBook, + string securityGroup, string addressBookPolicy) + { + return DeleteOrganizationInternal(organizationId, distinguishedName, globalAddressList, + addressList, roomList, offlineAddressBook, securityGroup, addressBookPolicy); + } + + public void SetOrganizationStorageLimits(string organizationDistinguishedName, long issueWarningKB, long prohibitSendKB, + long prohibitSendReceiveKB, int keepDeletedItemsDays) + { + SetOrganizationStorageLimitsInternal(organizationDistinguishedName, issueWarningKB, prohibitSendKB, + prohibitSendReceiveKB, keepDeletedItemsDays); + } + + public ExchangeItemStatistics[] GetMailboxesStatistics(string organizationDistinguishedName) + { + return GetMailboxesStatisticsInternal(organizationDistinguishedName); + } + #endregion + + #region Domains + + public string[] GetAuthoritativeDomains() + { + return GetAuthoritativeDomainsInternal(); + } + + public void AddAuthoritativeDomain(string domain) + { + CreateAuthoritativeDomainInternal(domain); + } + + public void DeleteAuthoritativeDomain(string domain) + { + DeleteAuthoritativeDomainInternal(domain); + } + + public void ChangeAcceptedDomainType(string domainName, ExchangeAcceptedDomainType domainType) + { + ChangeAcceptedDomainTypeInternal(domainName, domainType); + } + #endregion + + #region Mailboxes + + public ExchangeMailbox GetMailboxPermissions(string organizationId, string accountName) + { + return GetMailboxPermissionsInternal(organizationId, accountName, null); + } + + public void SetMailboxPermissions(string organizationId, string accountName, string[] sendAsAccounts, string[] fullAccessAccounts) + { + SetMailboxPermissionsInternal(organizationId, accountName, sendAsAccounts, fullAccessAccounts); + } + + public void DeleteMailbox(string accountName) + { + DeleteMailboxInternal(accountName); + } + + public ExchangeMailbox GetMailboxGeneralSettings(string accountName) + { + return GetMailboxGeneralSettingsInternal(accountName); + } + + public void SetMailboxGeneralSettings(string accountName, bool hideFromAddressBook, bool disabled) + { + SetMailboxGeneralSettingsInternal(accountName, hideFromAddressBook, disabled); + } + + public ExchangeMailbox GetMailboxMailFlowSettings(string accountName) + { + return GetMailboxMailFlowSettingsInternal(accountName); + } + + public void SetMailboxMailFlowSettings(string accountName, bool enableForwarding, + string forwardingAccountName, bool forwardToBoth, string[] sendOnBehalfAccounts, + string[] acceptAccounts, string[] rejectAccounts, bool requireSenderAuthentication) + { + SetMailboxMailFlowSettingsInternal(accountName, enableForwarding, forwardingAccountName, + forwardToBoth, sendOnBehalfAccounts, acceptAccounts, rejectAccounts, requireSenderAuthentication); + } + + public ExchangeMailbox GetMailboxAdvancedSettings(string accountName) + { + return GetMailboxAdvancedSettingsInternal(accountName); + } + + public void SetMailboxAdvancedSettings(string organizationId, string accountName, bool enablePOP, + bool enableIMAP, bool enableOWA, bool enableMAPI, bool enableActiveSync, + long issueWarningKB, long prohibitSendKB, long prohibitSendReceiveKB, int keepDeletedItemsDays, int maxRecipients, int maxSendMessageSizeKB, + int maxReceiveMessageSizeKB, bool enabledLitigationHold, long recoverabelItemsSpace, long recoverabelItemsWarning) + { + SetMailboxAdvancedSettingsInternal(organizationId, accountName, enablePOP, enableIMAP, enableOWA, + enableMAPI, enableActiveSync, issueWarningKB, + prohibitSendKB, prohibitSendReceiveKB, keepDeletedItemsDays, maxRecipients, maxSendMessageSizeKB, maxReceiveMessageSizeKB, + enabledLitigationHold, recoverabelItemsSpace, recoverabelItemsWarning); + } + + public ExchangeEmailAddress[] GetMailboxEmailAddresses(string accountName) + { + return GetMailboxEmailAddressesInternal(accountName); + } + + public void SetMailboxEmailAddresses(string accountName, string[] emailAddresses) + { + SetMailboxEmailAddressesInternal(accountName, emailAddresses); + } + + public void SetMailboxPrimaryEmailAddress(string accountName, string emailAddress) + { + SetMailboxPrimaryEmailAddressInternal(accountName, emailAddress); + } + + public ExchangeMailboxStatistics GetMailboxStatistics(string id) + { + return GetMailboxStatisticsInternal(id); + } + #endregion + + #region Contacts + public void CreateContact(string organizationId, string organizationDistinguishedName, + string contactDisplayName, string contactAccountName, string contactEmail, string defaultOrganizationDomain) + { + CreateContactInternal(organizationId, organizationDistinguishedName, contactDisplayName, + contactAccountName, contactEmail, defaultOrganizationDomain); + } + + public void DeleteContact(string accountName) + { + DeleteContactInternal(accountName); + } + + public ExchangeContact GetContactGeneralSettings(string accountName) + { + return GetContactGeneralSettingsInternal(accountName); + } + + public void SetContactGeneralSettings(string accountName, string displayName, string email, + bool hideFromAddressBook, string firstName, string initials, string lastName, string address, + string city, string state, string zip, string country, string jobTitle, string company, + string department, string office, string managerAccountName, string businessPhone, string fax, + string homePhone, string mobilePhone, string pager, string webPage, string notes, int useMapiRichTextFormat, string defaultOrganizationDomain) + { + SetContactGeneralSettingsInternal(accountName, displayName, email, hideFromAddressBook, + firstName, initials, lastName, address, city, state, zip, country, jobTitle, + company, department, office, managerAccountName, businessPhone, fax, homePhone, + mobilePhone, pager, webPage, notes, useMapiRichTextFormat, defaultOrganizationDomain); + } + + public ExchangeContact GetContactMailFlowSettings(string accountName) + { + return GetContactMailFlowSettingsInternal(accountName); + } + + public void SetContactMailFlowSettings(string accountName, string[] acceptAccounts, string[] rejectAccounts, bool requireSenderAuthentication) + { + SetContactMailFlowSettingsInternal(accountName, acceptAccounts, rejectAccounts, requireSenderAuthentication); + } + #endregion + + #region Distribution lists + public void CreateDistributionList(string organizationId, string organizationDistinguishedName, + string displayName, string accountName, string name, string domain, string managedBy, string[] addressLists) + { + CreateDistributionListInternal(organizationId, organizationDistinguishedName, displayName, + accountName, name, domain, managedBy, addressLists); + } + + public void DeleteDistributionList(string accountName) + { + DeleteDistributionListInternal(accountName); + } + + public ExchangeDistributionList GetDistributionListGeneralSettings(string accountName) + { + return GetDistributionListGeneralSettingsInternal(accountName); + } + + public void SetDistributionListGeneralSettings(string accountName, string displayName, + bool hideFromAddressBook, string managedBy, string[] members, string notes, string[] addressLists) + { + SetDistributionListGeneralSettingsInternal(accountName, displayName, hideFromAddressBook, + managedBy, members, notes, addressLists); + } + + public void AddDistributionListMembers(string accountName, string[] memberAccounts, string[] addressLists) + { + AddDistributionListMembersInternal(accountName, memberAccounts, addressLists); + } + + + public void RemoveDistributionListMembers(string accountName, string[] memberAccounts, string[] addressLists) + { + RemoveDistributionListMembersInternal(accountName, memberAccounts, addressLists); + } + + public ExchangeDistributionList GetDistributionListMailFlowSettings(string accountName) + { + return GetDistributionListMailFlowSettingsInternal(accountName); + } + + public void SetDistributionListMailFlowSettings(string accountName, string[] acceptAccounts, + string[] rejectAccounts, bool requireSenderAuthentication, string[] addressLists) + { + SetDistributionListMailFlowSettingsInternal(accountName, acceptAccounts, rejectAccounts, requireSenderAuthentication, addressLists); + } + + public ExchangeEmailAddress[] GetDistributionListEmailAddresses(string accountName) + { + return GetDistributionListEmailAddressesInternal(accountName); + } + + public void SetDistributionListEmailAddresses(string accountName, string[] emailAddresses, string[] addressLists) + { + SetDistributionListEmailAddressesInternal(accountName, emailAddresses, addressLists); + } + + public void SetDistributionListPrimaryEmailAddress(string accountName, string emailAddress, string[] addressLists) + { + SetDistributionListPrimaryEmailAddressInternal(accountName, emailAddress, addressLists); + } + + public ExchangeDistributionList GetDistributionListPermissions(string organizationId, string accountName) + { + return GetDistributionListPermissionsInternal(organizationId, accountName, null); + } + + public void SetDistributionListPermissions(string organizationId, string accountName, string[] sendAsAccounts, string[] sendOnBehalfAccounts, string[] addressLists) + { + SetDistributionListPermissionsInternal(organizationId, accountName, sendAsAccounts, sendOnBehalfAccounts, addressLists); + } + #endregion + + #region Public folders + public void CreatePublicFolder(string organizationId, string securityGroup, string parentFolder, + string folderName, bool mailEnabled, string accountName, string name, string domain) + { + CreatePublicFolderInternal(organizationId, securityGroup, parentFolder, folderName, + mailEnabled, accountName, name, domain); + } + + public void DeletePublicFolder(string folder) + { + DeletePublicFolderInternal(folder); + } + + public void EnableMailPublicFolder(string organizationId, string folder, string accountName, + string name, string domain) + { + EnableMailPublicFolderInternal(organizationId, folder, accountName, name, domain); + } + + public void DisableMailbox(string id) + { + DisableMailboxInternal(id); + } + + internal virtual void DisableMailboxInternal(string id) + { + ExchangeLog.LogStart("DisableMailboxInternal"); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + Command cmd = new Command("Get-Mailbox"); + cmd.Parameters.Add("Identity", id); + Collection result = ExecuteShellCommand(runSpace, cmd); + + if (result != null && result.Count > 0) + { + string upn = ObjToString(GetPSObjectProperty(result[0], "UserPrincipalName")); + + string addressbookPolicy = ObjToString(GetPSObjectProperty(result[0], "AddressBookPolicy")); + + RemoveDevicesInternal(runSpace, id); + + cmd = new Command("Disable-Mailbox"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("Confirm", false); + ExecuteShellCommand(runSpace, cmd); + + + if (addressbookPolicy == (upn + " AP")) + { + try + { + DeleteAddressBookPolicy(runSpace, upn + " AP"); + } + catch (Exception) + { + } + + try + { + DeleteGlobalAddressList(runSpace, upn + " GAL"); + } + catch (Exception) + { + } + + try + { + DeleteAddressList(runSpace, upn + " AL"); + } + catch (Exception) + { + } + } + + + } + + } + + finally + { + + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("DisableMailboxInternal"); + } + + + public void DisableMailPublicFolder(string folder) + { + DisableMailPublicFolderInternal(folder); + } + + public ExchangePublicFolder GetPublicFolderGeneralSettings(string folder) + { + return GetPublicFolderGeneralSettingsInternal(folder); + } + + public void SetPublicFolderGeneralSettings(string folder, string newFolderName, + bool hideFromAddressBook, ExchangeAccount[] accounts) + { + SetPublicFolderGeneralSettingsInternal(folder, newFolderName, hideFromAddressBook, accounts); + } + public ExchangePublicFolder GetPublicFolderMailFlowSettings(string folder) + { + return GetPublicFolderMailFlowSettingsInternal(folder); + } + + public void SetPublicFolderMailFlowSettings(string folder, + string[] acceptAccounts, string[] rejectAccounts, bool requireSenderAuthentication) + { + SetPublicFolderMailFlowSettingsInternal(folder, acceptAccounts, rejectAccounts, requireSenderAuthentication); + } + + public ExchangeEmailAddress[] GetPublicFolderEmailAddresses(string folder) + { + return GetPublicFolderEmailAddressesInternal(folder); + } + + public void SetPublicFolderEmailAddresses(string folder, string[] emailAddresses) + { + SetPublicFolderEmailAddressesInternal(folder, emailAddresses); + } + + public void SetPublicFolderPrimaryEmailAddress(string folder, string emailAddress) + { + SetPublicFolderPrimaryEmailAddressInternal(folder, emailAddress); + } + + public ExchangeItemStatistics[] GetPublicFoldersStatistics(string[] folders) + { + return GetPublicFoldersStatisticsInternal(folders); + } + + public string[] GetPublicFoldersRecursive(string parent) + { + return GetPublicFoldersRecursiveInternal(parent); + } + + public long GetPublicFolderSize(string folder) + { + return GetPublicFolderSizeInternal(folder); + } + #endregion + + #region ActiveSync + public void CreateOrganizationActiveSyncPolicy(string organizationId) + { + CreateOrganizationActiveSyncPolicyInternal(organizationId); + } + + + public ExchangeActiveSyncPolicy GetActiveSyncPolicy(string organizationId) + { + return GetActiveSyncPolicyInternal(organizationId); + } + + public void SetActiveSyncPolicy(string id, bool allowNonProvisionableDevices, bool attachmentsEnabled, + int maxAttachmentSizeKB, bool uncAccessEnabled, bool wssAccessEnabled, bool devicePasswordEnabled, + bool alphanumericPasswordRequired, bool passwordRecoveryEnabled, bool deviceEncryptionEnabled, + bool allowSimplePassword, int maxPasswordFailedAttempts, int minPasswordLength, int inactivityLockMin, + int passwordExpirationDays, int passwordHistory, int refreshInterval) + { + SetActiveSyncPolicyInternal(id, allowNonProvisionableDevices, attachmentsEnabled, + maxAttachmentSizeKB, uncAccessEnabled, wssAccessEnabled, + devicePasswordEnabled, alphanumericPasswordRequired, passwordRecoveryEnabled, + deviceEncryptionEnabled, allowSimplePassword, maxPasswordFailedAttempts, + minPasswordLength, inactivityLockMin, passwordExpirationDays, passwordHistory, refreshInterval); + } + #endregion + + #region Mobile devices + public ExchangeMobileDevice[] GetMobileDevices(string accountName) + { + return GetMobileDevicesInternal(accountName); + } + public ExchangeMobileDevice GetMobileDevice(string id) + { + return GetMobileDeviceInternal(id); + } + public void WipeDataFromDevice(string id) + { + WipeDataFromDeviceInternal(id); + } + public void CancelRemoteWipeRequest(string id) + { + CancelRemoteWipeRequestInternal(id); + } + public void RemoveDevice(string id) + { + RemoveDeviceInternal(id); + } + #endregion + + #endregion + + #region IHostingServiceProvider Members + + public virtual void ChangeServiceItemsState(ServiceProviderItem[] items, bool enabled) + { + foreach (ServiceProviderItem item in items) + { + if (item is Organization) + { + try + { + // make E2K7 mailboxes disabled + Organization org = item as Organization; + ChangeOrganizationState(org.DistinguishedName, enabled); + } + catch (Exception ex) + { + Log.WriteError(String.Format("Error switching '{0}' {1}", item.Name, item.GetType().Name), ex); + } + } + } + } + + public virtual void DeleteServiceItems(ServiceProviderItem[] items) + { + foreach (ServiceProviderItem item in items) + { + try + { + if (item is Organization) + { + Organization org = item as Organization; + DeleteOrganization(org.OrganizationId, org.DistinguishedName, org.GlobalAddressList, + org.AddressList, org.RoomsAddressList, org.OfflineAddressBook, org.SecurityGroup, org.AddressBookPolicy); + } + else if (item is ExchangeDomain) + { + DeleteAcceptedDomain(item.Name); + } + } + catch (Exception ex) + { + Log.WriteError(String.Format("Error deleting '{0}' {1}", item.Name, item.GetType().Name), ex); + } + } + } + + public virtual ServiceProviderItemDiskSpace[] GetServiceItemsDiskSpace(ServiceProviderItem[] items) + { + List itemsDiskspace = new List(); + + // update items with diskspace + foreach (ServiceProviderItem item in items) + { + if (item is Organization) + { + try + { + Log.WriteStart(String.Format("Calculating '{0}' disk space", item.Name)); + Organization org = item as Organization; + // calculate disk space + ServiceProviderItemDiskSpace diskspace = new ServiceProviderItemDiskSpace(); + diskspace.ItemId = item.Id; + diskspace.DiskSpace = CalculateOrganizationDiskSpace(org.OrganizationId, org.DistinguishedName); + itemsDiskspace.Add(diskspace); + + Log.WriteEnd(String.Format("Calculating '{0}' disk space", item.Name)); + } + catch (Exception ex) + { + Log.WriteError(String.Format("Error calculating '{0}' Exchange organization disk space", item.Name), ex); + } + } + } + + return itemsDiskspace.ToArray(); + } + + #endregion + + #region Common + private bool CheckAccountCredentialsInternal(string username, string password) + { + try + { + string path = ConvertDomainName(RootDomain); + DirectoryEntry entry = new DirectoryEntry(path, username, password); + //Bind to the native AdsObject to force authentication. + object obj = entry.NativeObject; + + DirectorySearcher search = new DirectorySearcher(entry); + + search.Filter = string.Format("(userPrincipalName={0})", username); + search.PropertiesToLoad.Add("cn"); + SearchResult result = search.FindOne(); + + if (result == null) + { + return false; + } + + //Update the new path to the user in the directory. + path = result.Path; + string filterAttribute = (string)result.Properties["cn"][0]; + } + catch (Exception) + { + return false; + //throw new Exception("Error authenticating user. " + ex.Message); + } + return true; + } + #endregion + + #region Organizations + + /// + /// Creates organization on Mail Server + /// + /// + /// + internal virtual Organization ExtendToExchangeOrganizationInternal(string organizationId, string securityGroup, bool IsConsumer) + { + ExchangeLog.LogStart("CreateOrganizationInternal"); + ExchangeLog.DebugInfo(" Organization Id: {0}", organizationId); + + ExchangeTransaction transaction = StartTransaction(); + Organization info = new Organization(); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + string server = GetServerName(); + string securityGroupPath = AddADPrefix(securityGroup); + + //Create mail enabled organization security group + EnableMailSecurityDistributionGroup(runSpace, securityGroup, organizationId); + transaction.RegisterMailEnabledDistributionGroup(securityGroup); + UpdateSecurityDistributionGroup(runSpace, securityGroup, organizationId, IsConsumer); + + //create GAL + string galId = CreateGlobalAddressList(runSpace, organizationId); + transaction.RegisterNewGlobalAddressList(galId); + ExchangeLog.LogInfo(" Global Address List: {0}", galId); + UpdateGlobalAddressList(runSpace, galId, securityGroupPath); + + //create AL + string alId = CreateAddressList(runSpace, organizationId); + transaction.RegisterNewAddressList(alId); + ExchangeLog.LogInfo(" Address List: {0}", alId); + UpdateAddressList(runSpace, alId, securityGroupPath); + + //create RAL + string ralId = CreateRoomsAddressList(runSpace, organizationId); + transaction.RegisterNewRoomsAddressList(ralId); + ExchangeLog.LogInfo(" Rooms Address List: {0}", ralId); + UpdateAddressList(runSpace, ralId, securityGroupPath); + + //create ActiveSync policy + string asId = CreateActiveSyncPolicy(runSpace, organizationId); + transaction.RegisterNewActiveSyncPolicy(asId); + ExchangeLog.LogInfo(" ActiveSync Policy: {0}", asId); + + info.AddressList = alId; + info.GlobalAddressList = galId; + info.RoomsAddressList = ralId; + info.OrganizationId = organizationId; + } + catch (Exception ex) + { + ExchangeLog.LogError("CreateOrganizationInternal", ex); + RollbackTransaction(transaction); + throw; + } + finally + { + + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("CreateOrganizationInternal"); + return info; + } + + private void CheckServiceSettings() + { + if (!ServerSettings.ADEnabled) + throw new Exception("Active Directory is not enabled. Check server settings."); + if (string.IsNullOrEmpty(RootDomain)) + throw new Exception("Active Directory root domain is not specified. Check server settings."); + if (string.IsNullOrEmpty(RootOU)) + throw new Exception("Active Directory root organizational unit is not specified. Check provider settings."); + if (string.IsNullOrEmpty(PrimaryDomainController)) + throw new Exception("Primary Domain Controller is not specified. Check provider settings."); + } + + private string GetOABVirtualDirectoryInternal() + { + ExchangeLog.LogStart("GetOABVirtualDirectoryInternal"); + Runspace runSpace = null; + string virtualDir = null; + try + { + runSpace = OpenRunspace(); + + + string server = GetServerName(); + Command cmd = new Command("Get-OabVirtualDirectory"); + cmd.Parameters.Add("Server", server); + + Collection result = ExecuteShellCommand(runSpace, cmd); + + if (result.Count > 0) + { + virtualDir = ObjToString(GetPSObjectProperty(result[0], "Identity")); + } + } + finally + { + + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("GetOABVirtualDirectoryInternal"); + return virtualDir; + } + + private Organization CreateOrganizationOfflineAddressBookInternal(string organizationId, string securityGroup, string oabVirtualDir) + { + ExchangeLog.LogStart("CreateOrganizationOfflineAddressBookInternal"); + ExchangeLog.LogInfo(" Organization Id: {0}", organizationId); + ExchangeLog.LogInfo(" Security Group: {0}", securityGroup); + ExchangeLog.LogInfo(" OAB Virtual Dir: {0}", oabVirtualDir); + + ExchangeTransaction transaction = StartTransaction(); + + Organization info = new Organization(); + + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + + string server = GetOABGenerationServerName(); + + string securityGroupId = AddADPrefix(securityGroup); + + //create OAB + string oabId = CreateOfflineAddressBook(runSpace, organizationId, server, oabVirtualDir); + transaction.RegisterNewOfflineAddressBook(oabId); + UpdateOfflineAddressBook(runSpace, oabId, securityGroupId); + info.OfflineAddressBook = oabId; + } + catch (Exception ex) + { + ExchangeLog.LogError("CreateOrganizationOfflineAddressBookInternal", ex); + RollbackTransaction(transaction); + throw; + } + finally + { + + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("CreateOrganizationOfflineAddressBookInternal"); + + + return info; + } + + private string GetOABGenerationServerName() + { + string ret = null; + if (!string.IsNullOrEmpty(OABGenerationServer)) + ret = OABGenerationServer; + else + ret = GetServerName(); + return ret; + } + + private void UpdateOrganizationOfflineAddressBookInternal(string oabId) + { + ExchangeLog.LogStart("UpdateOrganizationOfflineAddressBookInternal"); + ExchangeLog.LogInfo(" Id: {0}", oabId); + + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + Command cmd = new Command("Update-OfflineAddressBook"); + cmd.Parameters.Add("Identity", oabId); + ExecuteShellCommand(runSpace, cmd); + } + finally + { + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("UpdateOrganizationOfflineAddressBookInternal"); + } + + internal virtual Organization CreateOrganizationAddressBookPolicyInternal(string organizationId, string gal, string addressBook, string roomList, string oab) + { + ExchangeLog.LogStart("CreateOrganizationAddressBookPolicyInternal"); + ExchangeLog.LogInfo(" Organization Id: {0}", organizationId); + ExchangeLog.LogInfo(" GAL: {0}", gal); + ExchangeLog.LogInfo(" AddressBook: {0}", addressBook); + ExchangeLog.LogInfo(" RoomList: {0}", roomList); + ExchangeLog.LogInfo(" OAB: {0}", oab); + + ExchangeTransaction transaction = StartTransaction(); + + Organization info = new Organization(); + string policyName = GetAddressBookPolicyName(organizationId); + + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + Command cmd = new Command("New-AddressBookPolicy"); + cmd.Parameters.Add("Name", policyName); + cmd.Parameters.Add("AddressLists", addressBook); + cmd.Parameters.Add("RoomList", roomList); + cmd.Parameters.Add("GlobalAddressList", gal); + cmd.Parameters.Add("OfflineAddressBook", oab); + + Collection result = ExecuteShellCommand(runSpace, cmd); + info.AddressBookPolicy = GetResultObjectDN(result); + + } + catch (Exception ex) + { + ExchangeLog.LogError("CreateOrganizationAddressBookPolicyInternal", ex); + RollbackTransaction(transaction); + throw; + } + finally + { + + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("CreateOrganizationAddressBookPolicyInternal"); + return info; + } + + + internal virtual bool DeleteOrganizationInternal(string organizationId, string distinguishedName, + string globalAddressList, string addressList, string roomList, string offlineAddressBook, string securityGroup, string addressBookPolicy) + { + ExchangeLog.LogStart("DeleteOrganizationInternal"); + bool ret = true; + + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + + string ou = ConvertADPathToCanonicalName(distinguishedName); + + if (!DeleteOrganizationMailboxes(runSpace, ou)) + ret = false; + + if (!DeleteOrganizationContacts(runSpace, ou)) + ret = false; + + if (!DeleteOrganizationDistributionLists(runSpace, ou)) + ret = false; + + //delete AddressBookPolicy + try + { + if (!string.IsNullOrEmpty(addressBookPolicy)) + DeleteAddressBookPolicy(runSpace, addressBookPolicy); + } + catch (Exception ex) + { + ret = false; + ExchangeLog.LogError("Could not delete AddressBook Policy " + addressBookPolicy, ex); + } + + //delete OAB + try + { + if (!string.IsNullOrEmpty(offlineAddressBook)) + DeleteOfflineAddressBook(runSpace, offlineAddressBook); + } + catch (Exception ex) + { + ret = false; + ExchangeLog.LogError("Could not delete Offline Address Book " + offlineAddressBook, ex); + } + + //delete AL + try + { + if (!string.IsNullOrEmpty(addressList)) + DeleteAddressList(runSpace, addressList); + } + catch (Exception ex) + { + ret = false; + ExchangeLog.LogError("Could not delete Address List " + addressList, ex); + } + + //delete RL + try + { + if (!string.IsNullOrEmpty(roomList)) + DeleteAddressList(runSpace, roomList); + } + catch (Exception ex) + { + ret = false; + ExchangeLog.LogError("Could not delete Address List " + roomList, ex); + } + + + //delete GAL + try + { + if (!string.IsNullOrEmpty(globalAddressList)) + DeleteGlobalAddressList(runSpace, globalAddressList); + } + catch (Exception ex) + { + ret = false; + ExchangeLog.LogError("Could not delete Global Address List " + globalAddressList, ex); + } + + //delete ActiveSync policy + try + { + DeleteActiveSyncPolicy(runSpace, organizationId); + } + catch (Exception ex) + { + ret = false; + ExchangeLog.LogError("Could not delete ActiveSyncPolicy " + organizationId, ex); + } + + //disable mail security distribution group + try + { + DisableMailSecurityDistributionGroup(runSpace, securityGroup); + } + catch (Exception ex) + { + ret = false; + ExchangeLog.LogError("Could not disable mail security distribution group " + securityGroup, ex); + } + } + catch (Exception ex) + { + ret = false; + ExchangeLog.LogError("DeleteOrganizationInternal", ex); + throw; + } + finally + { + + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("DeleteOrganizationInternal"); + return ret; + } + + private bool CanDeleteOrganization(Runspace runSpace, string organizationId, string ou) + { + ExchangeLog.LogStart("CanDeleteOrganization"); + bool ret = true; + + Command cmd = new Command("Get-Mailbox"); + cmd.Parameters.Add("OrganizationalUnit", ou); + Collection result = ExecuteShellCommand(runSpace, cmd); + if (result != null && result.Count > 0) + ret = false; + + if (ret) + { + cmd = new Command("Get-MailContact"); + cmd.Parameters.Add("OrganizationalUnit", ou); + result = ExecuteShellCommand(runSpace, cmd); + if (result != null && result.Count > 0) + ret = false; + } + + if (ret) + { + cmd = new Command("Get-DistributionGroup"); + cmd.Parameters.Add("OrganizationalUnit", ou); + cmd.Parameters.Add("RecipientTypeDetails", "MailUniversalDistributionGroup"); + result = ExecuteShellCommand(runSpace, cmd); + if (result != null && result.Count > 0) + ret = false; + } + + if (ret) + { + cmd = new Command("Get-PublicFolder"); + cmd.Parameters.Add("Identity", "\\" + organizationId); + cmd.Parameters.Add("GetChildren", new SwitchParameter(true)); + if (!string.IsNullOrEmpty(PublicFolderServer)) + cmd.Parameters.Add("Server", PublicFolderServer); + + result = ExecuteShellCommand(runSpace, cmd); + if (result != null && result.Count > 0) + ret = false; + } + + ExchangeLog.LogEnd("CanDeleteOrganization"); + return ret; + } + + internal bool DeleteOrganizationMailboxes(Runspace runSpace, string ou) + { + ExchangeLog.LogStart("DeleteOrganizationMailboxes"); + bool ret = true; + + Command cmd = new Command("Get-Mailbox"); + cmd.Parameters.Add("OrganizationalUnit", ou); + Collection result = ExecuteShellCommand(runSpace, cmd); + if (result != null && result.Count > 0) + { + foreach (PSObject obj in result) + { + string id = null; + try + { + id = ObjToString(GetPSObjectProperty(obj, "Identity")); + RemoveDevicesInternal(runSpace, id); + + RemoveMailbox(runSpace, id); + } + catch (Exception ex) + { + ret = false; + ExchangeLog.LogError(string.Format("Can't delete mailbox {0}", id), ex); + } + } + } + + ExchangeLog.LogEnd("DeleteOrganizationMailboxes"); + return ret; + } + + internal bool DeleteOrganizationContacts(Runspace runSpace, string ou) + { + ExchangeLog.LogStart("DeleteOrganizationContacts"); + bool ret = true; + + Command cmd = new Command("Get-MailContact"); + cmd.Parameters.Add("OrganizationalUnit", ou); + Collection result = ExecuteShellCommand(runSpace, cmd); + if (result != null && result.Count > 0) + { + foreach (PSObject obj in result) + { + string id = null; + try + { + id = ObjToString(GetPSObjectProperty(obj, "Identity")); + RemoveContact(runSpace, id); + } + catch (Exception ex) + { + ret = false; + ExchangeLog.LogError(string.Format("Can't delete contact {0}", id), ex); + } + } + } + + ExchangeLog.LogEnd("DeleteOrganizationContacts"); + return ret; + } + + internal bool DeleteOrganizationDistributionLists(Runspace runSpace, string ou) + { + ExchangeLog.LogStart("DeleteOrganizationDistributionLists"); + bool ret = true; + + Command cmd = new Command("Get-DistributionGroup"); + cmd.Parameters.Add("OrganizationalUnit", ou); + cmd.Parameters.Add("RecipientTypeDetails", "MailUniversalDistributionGroup"); + Collection result = ExecuteShellCommand(runSpace, cmd); + if (result != null && result.Count > 0) + { + foreach (PSObject obj in result) + { + string id = null; + try + { + id = ObjToString(GetPSObjectProperty(obj, "Identity")); + RemoveDistributionGroup(runSpace, id); + } + catch (Exception ex) + { + ret = false; + ExchangeLog.LogError(string.Format("Can't delete distribution list {0}", id), ex); + } + } + } + + ExchangeLog.LogEnd("DeleteOrganizationDistributionLists"); + return ret; + } + + private bool DeleteOrganizationPublicFolders(Runspace runSpace, string organizationId) + { + ExchangeLog.LogStart("DeleteOrganizationPublicFolders"); + bool ret = true; + + //Delete public folders. + string publicFolder = "\\" + organizationId; + try + { + RemovePublicFolder(runSpace, publicFolder); + } + catch (Exception ex) + { + ret = false; + ExchangeLog.LogError(string.Format("Can't delete public folder {0}", publicFolder), ex); + } + ExchangeLog.LogEnd("DeleteOrganizationPublicFolders"); + return ret; + } + + private void SetOrganizationStorageLimitsInternal(string organizationDistinguishedName, long issueWarningKB, + long prohibitSendKB, long prohibitSendReceiveKB, int keepDeletedItemsDays) + { + ExchangeLog.LogStart("SetOrganizationStorageLimitsInternal"); + ExchangeLog.DebugInfo("Organization Id: {0}", organizationDistinguishedName); + + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + + string org = ConvertADPathToCanonicalName(organizationDistinguishedName); + + Unlimited issueWarningQuota = ConvertKBToUnlimited(issueWarningKB); + Unlimited prohibitSendQuota = ConvertKBToUnlimited(prohibitSendKB); + Unlimited prohibitSendReceiveQuota = ConvertKBToUnlimited(prohibitSendReceiveKB); + EnhancedTimeSpan retainDeletedItemsFor = ConvertDaysToEnhancedTimeSpan(keepDeletedItemsDays); + + Command cmd = new Command("Get-Mailbox"); + cmd.Parameters.Add("OrganizationalUnit", org); + Collection result = ExecuteShellCommand(runSpace, cmd); + + foreach (PSObject obj in result) + { + string id = ObjToString(GetPSObjectProperty(obj, "Identity")); + cmd = new Command("Set-Mailbox"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("IssueWarningQuota", issueWarningQuota); + cmd.Parameters.Add("ProhibitSendQuota", prohibitSendQuota); + cmd.Parameters.Add("ProhibitSendReceiveQuota", prohibitSendReceiveQuota); + cmd.Parameters.Add("RetainDeletedItemsFor", retainDeletedItemsFor); + ExecuteShellCommand(runSpace, cmd); + } + } + finally + { + + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("SetOrganizationStorageLimitsInternal"); + } + + private ExchangeItemStatistics[] GetMailboxesStatisticsInternal(string organizationDistinguishedName) + { + ExchangeLog.LogStart("GetMailboxesStatisticsInternal"); + ExchangeLog.DebugInfo("Organization Id: {0}", organizationDistinguishedName); + + List ret = new List(); + + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + + string org = ConvertADPathToCanonicalName(organizationDistinguishedName); + + Command cmd = new Command("Get-Mailbox"); + cmd.Parameters.Add("OrganizationalUnit", org); + Collection result = ExecuteShellCommand(runSpace, cmd); + + foreach (PSObject obj in result) + { + string id = ObjToString(GetPSObjectProperty(obj, "Identity")); + + cmd = new Command("Get-MailboxStatistics"); + cmd.Parameters.Add("Identity", id); + result = ExecuteShellCommand(runSpace, cmd); + if (result != null && result.Count > 0) + { + PSObject mailbox = result[0]; + ExchangeItemStatistics info = new ExchangeItemStatistics(); + info.ItemName = (string)GetPSObjectProperty(mailbox, "DisplayName"); + Unlimited totalItemSize = + (Unlimited)GetPSObjectProperty(mailbox, "TotalItemSize"); + info.TotalSizeMB = ConvertUnlimitedToMB(totalItemSize); + uint? itemCount = (uint?)GetPSObjectProperty(mailbox, "ItemCount"); + info.TotalItems = ConvertNullableToInt32(itemCount); + DateTime? lastLogoffTime = (DateTime?)GetPSObjectProperty(mailbox, "LastLogoffTime"); + DateTime? lastLogonTime = (DateTime?)GetPSObjectProperty(mailbox, "LastLogonTime"); + info.LastLogoff = ConvertNullableToDateTime(lastLogoffTime); + info.LastLogon = ConvertNullableToDateTime(lastLogonTime); + ret.Add(info); + } + } + } + finally + { + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("GetMailboxesStatisticsInternal"); + return ret.ToArray(); + } + + private void ChangeOrganizationState(string organizationDistinguishedName, bool enabled) + { + ExchangeLog.LogStart("ChangeOrganizationState"); + ExchangeLog.DebugInfo("Organization: {0}", organizationDistinguishedName); + + Runspace runSpace = null; + try + { + string ouName = ConvertADPathToCanonicalName(organizationDistinguishedName); + runSpace = OpenRunspace(); + + + Command cmd = new Command("Get-Mailbox"); + cmd.Parameters.Add("OrganizationalUnit", ouName); + cmd.Parameters.Add("Filter", "CustomAttribute2 -ne 'disabled'"); + Collection result = ExecuteShellCommand(runSpace, cmd); + foreach (PSObject obj in result) + { + string id = (string)GetPSObjectProperty(obj, "DistinguishedName"); + ChangeMailboxState(id, enabled); + } + } + finally + { + + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("ChangeOrganizationState"); + } + + + private long CalculateOrganizationDiskSpace(string organizationId, string organizationDistinguishedName) + { + ExchangeLog.LogStart("CalculateOrganizationDiskSpace"); + ExchangeLog.DebugInfo("Organization Id: {0}", organizationId); + + long size = 0; + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + + size += CalculateMailboxDiskSpace(runSpace, organizationDistinguishedName); + size += CalculatePublicFolderDiskSpace(runSpace, "\\" + organizationId); + } + finally + { + + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("CalculateOrganizationDiskSpace"); + return size; + } + + private long CalculateMailboxDiskSpace(Runspace runSpace, string organizationDistinguishedName) + { + ExchangeLog.LogStart("CalculateMailboxDiskSpace"); + ExchangeLog.DebugInfo("Organization DN: {0}", organizationDistinguishedName); + + long size = 0; + + string org = ConvertADPathToCanonicalName(organizationDistinguishedName); + + Command cmd = new Command("Get-Mailbox"); + cmd.Parameters.Add("OrganizationalUnit", org); + Collection result = ExecuteShellCommand(runSpace, cmd); + + foreach (PSObject obj in result) + { + string id = ObjToString(GetPSObjectProperty(obj, "Identity")); + cmd = new Command("Get-MailboxStatistics"); + cmd.Parameters.Add("Identity", id); + result = ExecuteShellCommand(runSpace, cmd); + if (result != null && result.Count > 0) + { + Unlimited totalItemSize = + (Unlimited)GetPSObjectProperty(result[0], "TotalItemSize"); + size += ConvertUnlimitedToBytes(totalItemSize); + } + } + ExchangeLog.LogEnd("CalculateMailboxDiskSpace"); + return size; + } + + internal virtual long CalculatePublicFolderDiskSpace(Runspace runSpace, string folder) + { + ExchangeLog.LogStart("CalculatePublicFolderDiskSpace"); + ExchangeLog.DebugInfo("Folder: {0}", folder); + + long size = 0; + + Command cmd = new Command("Get-PublicFolderDatabase"); + Collection result = ExecuteShellCommand(runSpace, cmd); + if (result != null && result.Count > 0) + { + cmd = new Command("Get-PublicFolderStatistics"); + cmd.Parameters.Add("Identity", folder); + if (!string.IsNullOrEmpty(PublicFolderServer)) + cmd.Parameters.Add("Server", PublicFolderServer); + result = ExecuteShellCommand(runSpace, cmd); + if (result != null && result.Count > 0) + { + PSObject obj = result[0]; + Unlimited totalItemSize = + (Unlimited)GetPSObjectProperty(obj, "TotalItemSize"); + size += ConvertUnlimitedToBytes(totalItemSize); + } + + cmd = new Command("Get-PublicFolder"); + cmd.Parameters.Add("Identity", folder); + cmd.Parameters.Add("GetChildren", new SwitchParameter(true)); + if (!string.IsNullOrEmpty(PublicFolderServer)) + cmd.Parameters.Add("Server", PublicFolderServer); + result = ExecuteShellCommand(runSpace, cmd); + foreach (PSObject obj in result) + { + string id = ObjToString(GetPSObjectProperty(obj, "Identity")); + size += CalculatePublicFolderDiskSpace(runSpace, id); + } + } + else + size = 0; + ExchangeLog.LogEnd("CalculatePublicFolderDiskSpace"); + return size; + } + + #endregion + + #region Mailboxes + + + private void SetExtendedRights(Runspace runSpace, string identity, string user, string rights) + { + ExchangeLog.LogStart("SetExtendedRights"); + + Command cmd = new Command("Add-ADPermission"); + cmd.Parameters.Add("Identity", identity); + cmd.Parameters.Add("User", user); + + cmd.Parameters.Add("ExtendedRights", rights); + ExecuteShellCommand(runSpace, cmd); + + ExchangeLog.LogEnd("SetExtendedRights"); + } + + private void SetMailboxPermission(Runspace runSpace, string accountName, string user, string accessRights) + { + ExchangeLog.LogStart("SetMailboxPermission"); + + Command cmd = new Command("Add-MailboxPermission"); + cmd.Parameters.Add("Identity", accountName); + cmd.Parameters.Add("User", user); + cmd.Parameters.Add("AccessRights", accessRights); + ExecuteShellCommand(runSpace, cmd); + + ExchangeLog.LogEnd("SetMailboxPermission"); + } + + private ExchangeAccount[] GetMailboxSendAsAccounts(Runspace runSpace, string organizationId, string accountName) + { + ExchangeLog.LogStart("GetMailboxSendAsAccounts"); + + string cn = GetMailboxCommonName(runSpace, accountName); + ExchangeAccount[] ret = GetSendAsAccounts(runSpace, organizationId, cn); + + ExchangeLog.LogEnd("GetMailboxSendAsAccounts"); + return ret; + } + + private ExchangeAccount[] GetSendAsAccounts(Runspace runSpace, string organizationId, string accountId) + { + ExchangeLog.LogStart("GetSendAsAccounts"); + + Command cmd = new Command("Get-ADPermission"); + cmd.Parameters.Add("Identity", accountId); + Collection results = ExecuteShellCommand(runSpace, cmd); + List accounts = new List(); + foreach (PSObject current in results) + { + string user = GetPSObjectProperty(current, "User").ToString(); + + Array extendedRights = GetPSObjectProperty(current, "ExtendedRights") as Array; + + if (extendedRights != null) + { + foreach (object obj in extendedRights) + { + string strRightName = obj.ToString(); + if (string.Compare(strRightName, "Send-as", true) == 0) + { + ExchangeAccount account = GetOrganizationAccount(runSpace, organizationId, user); + if (account != null) + accounts.Add(account); + } + } + } + } + + ExchangeLog.LogEnd("GetSendAsAccounts"); + return accounts.ToArray(); + } + + + private ExchangeAccount[] GetMailBoxFullAccessAcounts(Runspace runSpace, string organizationId, string accountName) + { + ExchangeLog.LogStart("GetMailBoxFullAccessAcounts"); + + Command cmd = new Command("Get-MailboxPermission"); + cmd.Parameters.Add("Identity", accountName); + Collection results = ExecuteShellCommand(runSpace, cmd); + + + List accounts = new List(); + foreach (PSObject current in results) + { + string user = GetPSObjectProperty(current, "User").ToString(); + + Array accessRights = GetPSObjectProperty(current, "AccessRights") as Array; + + if (accessRights != null) + { + foreach (object obj in accessRights) + { + string strRightName = obj.ToString(); + if (string.Compare(strRightName, "FullAccess", true) == 0) + { + ExchangeAccount account = GetOrganizationAccount(runSpace, organizationId, user); + if (account != null) + accounts.Add(account); + } + } + } + } + + ExchangeLog.LogEnd("GetMailBoxFullAccessAcounts"); + return accounts.ToArray(); + } + + private ExchangeMailbox GetMailboxPermissionsInternal(string organizationId, string accountName, Runspace runspace) + { + ExchangeLog.LogStart("GetMailboxPermissionsInternal"); + + if (string.IsNullOrEmpty(accountName)) + throw new ArgumentNullException("accountName"); + + ExchangeMailbox exchangeMailbox = null; + bool closeRunspace = false; + + try + { + if (runspace == null) + { + runspace = OpenRunspace(); + closeRunspace = true; + } + + exchangeMailbox = new ExchangeMailbox(); + exchangeMailbox.FullAccessAccounts = GetMailBoxFullAccessAcounts(runspace, organizationId, accountName); + exchangeMailbox.SendAsAccounts = GetMailboxSendAsAccounts(runspace, organizationId, accountName); + } + catch (Exception ex) + { + ExchangeLog.LogError(ex); + throw ex; + } + finally + { + if (closeRunspace) + CloseRunspace(runspace); + } + + ExchangeLog.LogEnd("GetMailboxPermissionsInternal"); + return exchangeMailbox; + } + + + private void SetSendAsPermissions(Runspace runSpace, ExchangeAccount[] existingAccounts, string accountId, string[] accounts) + { + ExchangeLog.LogStart("SetSendAsPermissions"); + + if (string.IsNullOrEmpty(accountId)) + throw new ArgumentNullException("accountId"); + + if (accounts == null) + throw new ArgumentNullException("accounts"); + + ExchangeTransaction transaction = null; + try + { + transaction = StartTransaction(); + + string[] resAccounts = MergeADPermission(runSpace, existingAccounts, accountId, accounts, transaction); + foreach (string id in resAccounts) + { + SetExtendedRights(runSpace, accountId, id, "Send-as"); + transaction.AddSendAsPermission(accountId, id); + } + + } + catch (Exception) + { + RollbackTransaction(transaction); + throw; + } + ExchangeLog.LogEnd("SetSendAsPermissions"); + } + + + private void SetMailboxPermissionsInternal(string organizationId, string accountName, string[] sendAsAccounts, string[] fullAccessAccounts) + { + ExchangeLog.LogStart("SetMailboxPermissionsInternal"); + + if (string.IsNullOrEmpty(accountName)) + throw new ArgumentNullException("accountName"); + + if (sendAsAccounts == null) + throw new ArgumentNullException("sendAsAccounts"); + + + if (fullAccessAccounts == null) + throw new ArgumentNullException("fullAccessAccounts"); + + Runspace runSpace = null; + try + { + + runSpace = OpenRunspace(); + string cn = GetMailboxCommonName(runSpace, accountName); + ExchangeMailbox mailbox = GetMailboxPermissionsInternal(organizationId, accountName, runSpace); + SetSendAsPermissions(runSpace, mailbox.SendAsAccounts, cn, sendAsAccounts); + SetMailboxFullAccessPermissions(runSpace, mailbox.FullAccessAccounts, accountName, fullAccessAccounts); + + } + catch (Exception ex) + { + ExchangeLog.LogError(ex); + + throw; + } + finally + { + CloseRunspace(runSpace); + } + + ExchangeLog.LogEnd("SetMailboxPermissionsInternal"); + } + + + internal void RemoveMailboxAccessPermission(Runspace runSpace, string accountName, string account, string accessRights) + { + ExchangeLog.LogStart("RemoveMailboxFullAccessPermission"); + + Command cmd = new Command("Remove-MailboxPermission"); + cmd.Parameters.Add("Identity", accountName); + cmd.Parameters.Add("User", account); + cmd.Parameters.Add("AccessRights", accessRights); + cmd.Parameters.Add("Confirm", false); + ExecuteShellCommand(runSpace, cmd); + + ExchangeLog.LogEnd("RemoveMailboxFullAccessPermission"); + } + + + private string[] MergeMailboxFullAccessPermissions(Runspace runSpace, ExchangeAccount[] existingAccounts, string accountName, string[] newAccounts, ExchangeTransaction transaction) + { + ExchangeLog.LogStart("MergeMailboxFullAccessPermissions"); + List temp = new List(newAccounts); + + Array.Sort(newAccounts); + foreach (ExchangeAccount exist in existingAccounts) + { + if (Array.BinarySearch(newAccounts, exist.AccountName, StringComparer.Create(CultureInfo.InvariantCulture, true)) >= 0) + { + temp.Remove(exist.AccountName); + continue; + } + + RemoveMailboxAccessPermission(runSpace, accountName, exist.AccountName, "FullAccess"); + transaction.RemoveMailboxFullAccessPermission(accountName, exist.AccountName); + } + + ExchangeLog.LogEnd("MergeMailboxFullAccessPermissions"); + return temp.ToArray(); + } + + + private void SetMailboxFullAccessPermissions(Runspace runSpace, ExchangeAccount[] existingAccounts, string accountName, string[] accounts) + { + ExchangeLog.LogStart("SetMailboxFullAccessPermissions"); + + if (string.IsNullOrEmpty(accountName)) + throw new ArgumentNullException("accountName"); + + if (accounts == null) + throw new ArgumentNullException("accounts"); + + ExchangeTransaction transaction = StartTransaction(); + + try + { + + string[] resAccounts = MergeMailboxFullAccessPermissions(runSpace, existingAccounts, accountName, accounts, transaction); + foreach (string id in resAccounts) + { + SetMailboxPermission(runSpace, accountName, id, "FullAccess"); + transaction.AddMailBoxFullAccessPermission(accountName, id); + } + } + catch (Exception) + { + RollbackTransaction(transaction); + throw; + } + ExchangeLog.LogEnd("SetMailboxFullAccessPermissions"); + + } + + + private void RemoveADPermission(Runspace runSpace, string identity, string account, string accessRights, string extendedRights, string properties) + { + ExchangeLog.LogStart("RemoveADPermission"); + + Command cmd = new Command("Remove-ADPermission"); + cmd.Parameters.Add("Identity", identity); + cmd.Parameters.Add("User", account); + cmd.Parameters.Add("InheritanceType", "All"); + cmd.Parameters.Add("AccessRights", accessRights); + cmd.Parameters.Add("ExtendedRights", extendedRights); + cmd.Parameters.Add("ChildObjectTypes", null); + cmd.Parameters.Add("InheritedObjectType", null); + cmd.Parameters.Add("Properties", properties); + cmd.Parameters.Add("Confirm", false); + ExecuteShellCommand(runSpace, cmd); + + ExchangeLog.LogEnd("RemoveADPermission"); + } + + private void AddADPermission(Runspace runSpace, string identity, string user, string accessRights, string extendedRights, string properties) + { + ExchangeLog.LogStart("AddADPermission"); + + Command cmd = new Command("Add-ADPermission"); + cmd.Parameters.Add("Identity", identity); + cmd.Parameters.Add("User", user); + cmd.Parameters.Add("AccessRights", accessRights); + cmd.Parameters.Add("ExtendedRights", extendedRights); + cmd.Parameters.Add("Properties", properties); + //cmd.Parameters.Add("Confirm", false); + ExecuteShellCommand(runSpace, cmd); + + ExchangeLog.LogEnd("AddADPermission"); + } + + + private string[] MergeADPermission(Runspace runSpace, ExchangeAccount[] existingAccounts, string identity, string[] newAccounts, ExchangeTransaction transaction) + { + ExchangeLog.LogStart("MergeADPermission"); + + List temp = new List(newAccounts); + + Array.Sort(newAccounts); + foreach (ExchangeAccount current in existingAccounts) + { + if (Array.BinarySearch(newAccounts, current.AccountName, StringComparer.Create(CultureInfo.InvariantCulture, true)) >= 0) + { + temp.Remove(current.AccountName); + continue; + } + RemoveADPermission(runSpace, identity, current.AccountName, null, "Send-as", null); + transaction.RemoveSendAsPermission(identity, current.AccountName); + } + + ExchangeLog.LogEnd("MergeADPermission"); + return temp.ToArray(); + } + + + public string CreateMailEnableUser(string upn, string organizationId, string organizationDistinguishedName, ExchangeAccountType accountType, + string mailboxDatabase, string offlineAddressBook, string addressBookPolicy, + string accountName, bool enablePOP, bool enableIMAP, + bool enableOWA, bool enableMAPI, bool enableActiveSync, + long issueWarningKB, long prohibitSendKB, long prohibitSendReceiveKB, int keepDeletedItemsDays, + int maxRecipients, int maxSendMessageSizeKB, int maxReceiveMessageSizeKB, bool hideFromAddressBook, bool IsConsumer, bool enabledLitigationHold, long recoverabelItemsSpace, long recoverabelItemsWarning) + { + return CreateMailEnableUserInternal(upn, organizationId, organizationDistinguishedName, accountType, + mailboxDatabase, offlineAddressBook, addressBookPolicy, + accountName, enablePOP, enableIMAP, + enableOWA, enableMAPI, enableActiveSync, + issueWarningKB, prohibitSendKB, prohibitSendReceiveKB, + keepDeletedItemsDays, maxRecipients, maxSendMessageSizeKB, maxReceiveMessageSizeKB, hideFromAddressBook, IsConsumer, enabledLitigationHold, recoverabelItemsSpace, recoverabelItemsWarning); + } + + internal virtual string CreateMailEnableUserInternal(string upn, string organizationId, string organizationDistinguishedName, ExchangeAccountType accountType, + string mailboxDatabase, string offlineAddressBook, string addressBookPolicy, + string accountName, bool enablePOP, bool enableIMAP, + bool enableOWA, bool enableMAPI, bool enableActiveSync, + long issueWarningKB, long prohibitSendKB, long prohibitSendReceiveKB, int keepDeletedItemsDays, + int maxRecipients, int maxSendMessageSizeKB, int maxReceiveMessageSizeKB, bool hideFromAddressBook, bool IsConsumer, bool enabledLitigationHold, long recoverabelItemsSpace, long recoverabelItemsWarning) + { + + ExchangeLog.LogStart("CreateMailEnableUserInternal"); + ExchangeLog.DebugInfo("Organization Id: {0}", organizationId); + + string ret = null; + ExchangeTransaction transaction = StartTransaction(); + Runspace runSpace = null; + + int attempts = 0; + string id = null; + + try + { + runSpace = OpenRunspace(); + Command cmd = null; + Collection result = null; + + //try to enable mail user for 10 times + while (true) + { + try + { + //create mailbox + cmd = new Command("Enable-Mailbox"); + cmd.Parameters.Add("Identity", upn); + cmd.Parameters.Add("Alias", accountName); + string database = GetDatabase(runSpace, PrimaryDomainController, mailboxDatabase); + ExchangeLog.DebugInfo("database: " + database); + if (database != string.Empty) + { + cmd.Parameters.Add("Database", database); + } + if (accountType == ExchangeAccountType.Equipment) + cmd.Parameters.Add("Equipment"); + else if (accountType == ExchangeAccountType.Room) + cmd.Parameters.Add("Room"); + + result = ExecuteShellCommand(runSpace, cmd); + + id = CheckResultObjectDN(result); + } + catch (Exception ex) + { + ExchangeLog.LogError(ex); + } + if (id != null) + break; + + if (attempts > 9) + throw new Exception( + string.Format("Could not enable mail user '{0}' ", upn)); + + attempts++; + ExchangeLog.LogWarning("Attempt #{0} to enable mail user failed!", attempts); + // wait 5 sec + System.Threading.Thread.Sleep(1000); + } + + transaction.RegisterEnableMailbox(id); + + string windowsEmailAddress = ObjToString(GetPSObjectProperty(result[0], "WindowsEmailAddress")); + + //update mailbox + cmd = new Command("Set-Mailbox"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("OfflineAddressBook", offlineAddressBook); + cmd.Parameters.Add("EmailAddressPolicyEnabled", false); + cmd.Parameters.Add("CustomAttribute1", organizationId); + cmd.Parameters.Add("CustomAttribute3", windowsEmailAddress); + cmd.Parameters.Add("PrimarySmtpAddress", upn); + cmd.Parameters.Add("WindowsEmailAddress", upn); + + cmd.Parameters.Add("UseDatabaseQuotaDefaults", new bool?(false)); + cmd.Parameters.Add("UseDatabaseRetentionDefaults", false); + cmd.Parameters.Add("IssueWarningQuota", ConvertKBToUnlimited(issueWarningKB)); + cmd.Parameters.Add("ProhibitSendQuota", ConvertKBToUnlimited(prohibitSendKB)); + cmd.Parameters.Add("ProhibitSendReceiveQuota", ConvertKBToUnlimited(prohibitSendReceiveKB)); + cmd.Parameters.Add("RetainDeletedItemsFor", ConvertDaysToEnhancedTimeSpan(keepDeletedItemsDays)); + cmd.Parameters.Add("RecipientLimits", ConvertInt32ToUnlimited(maxRecipients)); + cmd.Parameters.Add("MaxSendSize", ConvertKBToUnlimited(maxSendMessageSizeKB)); + cmd.Parameters.Add("MaxReceiveSize", ConvertKBToUnlimited(maxReceiveMessageSizeKB)); + if (IsConsumer) cmd.Parameters.Add("HiddenFromAddressListsEnabled", true); + else + cmd.Parameters.Add("HiddenFromAddressListsEnabled", hideFromAddressBook); + cmd.Parameters.Add("AddressBookPolicy", addressBookPolicy); + + if (enabledLitigationHold) + { + cmd.Parameters.Add("LitigationHoldEnabled", true); + cmd.Parameters.Add("RecoverableItemsQuota", ConvertKBToUnlimited(recoverabelItemsSpace)); + cmd.Parameters.Add("RecoverableItemsWarningQuota", ConvertKBToUnlimited(recoverabelItemsWarning)); + } + + ExecuteShellCommand(runSpace, cmd); + + //Client Access + cmd = new Command("Set-CASMailbox"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("ActiveSyncEnabled", enableActiveSync); + if (enableActiveSync) + { + cmd.Parameters.Add("ActiveSyncMailboxPolicy", organizationId); + } + cmd.Parameters.Add("OWAEnabled", enableOWA); + cmd.Parameters.Add("MAPIEnabled", enableMAPI); + cmd.Parameters.Add("PopEnabled", enablePOP); + cmd.Parameters.Add("ImapEnabled", enableIMAP); + ExecuteShellCommand(runSpace, cmd); + + //add to the security group + cmd = new Command("Add-DistributionGroupMember"); + cmd.Parameters.Add("Identity", organizationId); + cmd.Parameters.Add("Member", id); + cmd.Parameters.Add("BypassSecurityGroupManagerCheck", true); + ExecuteShellCommand(runSpace, cmd); + + if (!IsConsumer) + { + //Set-MailboxFolderPermission for calendar + cmd = new Command("Add-MailboxFolderPermission"); + cmd.Parameters.Add("Identity", id + ":\\calendar"); + cmd.Parameters.Add("AccessRights", "Reviewer"); + cmd.Parameters.Add("User", organizationId); + ExecuteShellCommand(runSpace, cmd); + } + cmd = new Command("Set-MailboxFolderPermission"); + cmd.Parameters.Add("Identity", id + ":\\calendar"); + cmd.Parameters.Add("AccessRights", "None"); + cmd.Parameters.Add("User", "Default"); + ExecuteShellCommand(runSpace, cmd); + + ret = string.Format("{0}\\{1}", GetNETBIOSDomainName(), accountName); + ExchangeLog.LogEnd("CreateMailEnableUserInternal"); + return ret; + } + catch (Exception ex) + { + ExchangeLog.LogError("CreateMailEnableUserInternal", ex); + RollbackTransaction(transaction); + throw; + } + finally + { + CloseRunspace(runSpace); + } + } + + internal virtual void SetCalendarSettings(Runspace runspace, string id) + { + ExchangeLog.LogStart("SetCalendarSettings"); + Command cmd = new Command("Set-CalendarProcessing"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("AutomateProcessing", CalendarProcessingFlags.AutoAccept); + ExecuteShellCommand(runspace, cmd); + ExchangeLog.LogEnd("SetCalendarSettings"); + } + + internal virtual void DeleteMailboxInternal(string accountName) + { + ExchangeLog.LogStart("DeleteMailboxInternal"); + ExchangeLog.DebugInfo("Account Name: {0}", accountName); + + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + Command cmd = new Command("Get-Mailbox"); + cmd.Parameters.Add("Identity", accountName); + Collection result = ExecuteShellCommand(runSpace, cmd); + + if (result != null && result.Count > 0) + { + string upn = ObjToString(GetPSObjectProperty(result[0], "UserPrincipalName")); + string addressbookPolicy = ObjToString(GetPSObjectProperty(result[0], "AddressBookPolicy")); + + RemoveDevicesInternal(runSpace, accountName); + + RemoveMailbox(runSpace, accountName); + + if (addressbookPolicy == (upn + " AP")) + { + try + { + DeleteAddressBookPolicy(runSpace, upn + " AP"); + } + catch (Exception) + { + } + + try + { + DeleteGlobalAddressList(runSpace, upn + " GAL"); + } + catch (Exception) + { + } + + try + { + DeleteAddressList(runSpace, upn + " AL"); + } + catch (Exception) + { + } + } + } + + + } + finally + { + + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("DeleteMailboxInternal"); + } + + + internal string GetDatabase(Runspace runSpace, string primaryDomainController, string dagName) + { + string database = string.Empty; + + if (string.IsNullOrEmpty(dagName)) return string.Empty; + + ExchangeLog.LogStart("GetDatabase"); + ExchangeLog.LogInfo("DAG: " + dagName); + + //Get Dag Servers + Collection dags = null; + Command cmd = new Command("Get-DatabaseAvailabilityGroup"); + cmd.Parameters.Add("Identity", dagName); + dags = ExecuteShellCommand(runSpace, cmd); + + if (htBbalancer == null) + htBbalancer = new Hashtable(); + + if (htBbalancer[dagName] == null) + htBbalancer.Add(dagName, 0); + + if (dags != null && dags.Count > 0) + { + + ADMultiValuedProperty servers = (ADMultiValuedProperty)GetPSObjectProperty(dags[0], "Servers"); + + if (servers != null) + { + System.Collections.Generic.List lstDatabase = new System.Collections.Generic.List(); + + foreach (object objServer in servers) + { + Collection databases = null; + cmd = new Command("Get-MailboxDatabase"); + cmd.Parameters.Add("Server", ObjToString(objServer)); + databases = ExecuteShellCommand(runSpace, cmd); + + foreach (PSObject objDatabase in databases) + { + if (((bool)GetPSObjectProperty(objDatabase, "IsExcludedFromProvisioning") == false) && + ((bool)GetPSObjectProperty(objDatabase, "IsSuspendedFromProvisioning") == false)) + { + string db = ObjToString(GetPSObjectProperty(objDatabase, "Identity")); + + bool bAdd = true; + foreach (string s in lstDatabase) + { + if (s.ToLower() == db.ToLower()) + { + bAdd = false; + break; + } + } + + if (bAdd) + { + lstDatabase.Add(db); + ExchangeLog.LogInfo("AddDatabase: " + db); + } + } + } + } + + int balancer = (int)htBbalancer[dagName]; + balancer++; + if (balancer >= lstDatabase.Count) balancer = 0; + htBbalancer[dagName] = balancer; + if (lstDatabase.Count != 0) database = lstDatabase[balancer]; + + } + } + + ExchangeLog.LogEnd("GetDatabase"); + return database; + } + + internal void RemoveMailbox(Runspace runSpace, string id) + { + ExchangeLog.LogStart("RemoveMailbox"); + Command cmd = new Command("Remove-Mailbox"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("Permanent", false); + cmd.Parameters.Add("Confirm", false); + ExecuteShellCommand(runSpace, cmd); + ExchangeLog.LogEnd("RemoveMailbox"); + } + + private void DisableMailbox(Runspace runSpace, string id) + { + ExchangeLog.LogStart("DisableMailbox"); + Command cmd = new Command("Disable-Mailbox"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("Confirm", false); + ExecuteShellCommand(runSpace, cmd); + ExchangeLog.LogEnd("DisableMailbox"); + } + + private string GetMailboxCommonName(Runspace runSpace, string accountName) + { + ExchangeLog.LogStart("GetMailboxCommonName"); + Collection result = GetMailboxObject(runSpace, accountName); + PSObject mailbox = result[0]; + string cn = GetPSObjectProperty(mailbox, "Name") as string; + ExchangeLog.LogEnd("GetMailboxCommonName"); + return cn; + } + + private ExchangeAccount GetManager(DirectoryEntry entry) + { + ExchangeAccount retUser = null; + string path = ActiveDirectoryUtils.GetADObjectStringProperty(entry, ADAttributes.Manager); + if (!string.IsNullOrEmpty(path)) + { + path = ActiveDirectoryUtils.AddADPrefix(path, PrimaryDomainController); + if (ActiveDirectoryUtils.AdObjectExists(path)) + { + DirectoryEntry user = ActiveDirectoryUtils.GetADObject(path); + retUser = new ExchangeAccount(); + retUser.DisplayName = ActiveDirectoryUtils.GetADObjectStringProperty(user, ADAttributes.DisplayName); + retUser.AccountName = ActiveDirectoryUtils.GetADObjectStringProperty(user, ADAttributes.Name); + } + } + + return retUser; + } + + private ExchangeMailbox GetMailboxGeneralSettingsInternal(string accountName) + { + ExchangeLog.LogStart("GetMailboxGeneralSettingsInternal"); + ExchangeLog.DebugInfo("Account: {0}", accountName); + + ExchangeMailbox info = new ExchangeMailbox(); + info.AccountName = accountName; + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + Collection result = GetMailboxObject(runSpace, accountName); + PSObject mailbox = result[0]; + + string id = GetResultObjectDN(result); + string path = AddADPrefix(id); + DirectoryEntry entry = GetADObject(path); + + + //ADAccountOptions userFlags = (ADAccountOptions)entry.Properties["userAccountControl"].Value; + //info.Disabled = ((userFlags & ADAccountOptions.UF_ACCOUNTDISABLE) != 0); + info.Disabled = (bool)entry.InvokeGet("AccountDisabled"); + + info.DisplayName = (string)GetPSObjectProperty(mailbox, "DisplayName"); + info.HideFromAddressBook = (bool)GetPSObjectProperty(mailbox, "HiddenFromAddressListsEnabled"); + + Command cmd = new Command("Get-User"); + cmd.Parameters.Add("Identity", accountName); + result = ExecuteShellCommand(runSpace, cmd); + PSObject user = result[0]; + + info.FirstName = (string)GetPSObjectProperty(user, "FirstName"); + info.Initials = (string)GetPSObjectProperty(user, "Initials"); + info.LastName = (string)GetPSObjectProperty(user, "LastName"); + + info.Address = (string)GetPSObjectProperty(user, "StreetAddress"); + info.City = (string)GetPSObjectProperty(user, "City"); + info.State = (string)GetPSObjectProperty(user, "StateOrProvince"); + info.Zip = (string)GetPSObjectProperty(user, "PostalCode"); + info.Country = CountryInfoToString((CountryInfo)GetPSObjectProperty(user, "CountryOrRegion")); + info.JobTitle = (string)GetPSObjectProperty(user, "Title"); + info.Company = (string)GetPSObjectProperty(user, "Company"); + info.Department = (string)GetPSObjectProperty(user, "Department"); + info.Office = (string)GetPSObjectProperty(user, "Office"); + + + info.ManagerAccount = GetManager(entry); //GetExchangeAccount(runSpace, ObjToString(GetPSObjectProperty(user, "Manager"))); + info.BusinessPhone = (string)GetPSObjectProperty(user, "Phone"); + info.Fax = (string)GetPSObjectProperty(user, "Fax"); + info.HomePhone = (string)GetPSObjectProperty(user, "HomePhone"); + info.MobilePhone = (string)GetPSObjectProperty(user, "MobilePhone"); + info.Pager = (string)GetPSObjectProperty(user, "Pager"); + info.WebPage = (string)GetPSObjectProperty(user, "WebPage"); + info.Notes = (string)GetPSObjectProperty(user, "Notes"); + + } + finally + { + + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("GetMailboxGeneralSettingsInternal"); + return info; + } + + + private void SetMailboxGeneralSettingsInternal(string accountName, bool hideFromAddressBook, bool disabled) + { + ExchangeLog.LogStart("SetMailboxGeneralSettingsInternal"); + ExchangeLog.DebugInfo("Account: {0}", accountName); + + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + Collection result = GetMailboxObject(runSpace, accountName); + PSObject mailbox = result[0]; + + string id = GetResultObjectDN(result); + string path = AddADPrefix(id); + DirectoryEntry entry = GetADObject(path); + entry.InvokeSet("AccountDisabled", disabled); + entry.CommitChanges(); + + Command cmd = new Command("Set-Mailbox"); + cmd.Parameters.Add("Identity", accountName); + cmd.Parameters.Add("HiddenFromAddressListsEnabled", hideFromAddressBook); + cmd.Parameters.Add("CustomAttribute2", (disabled ? "disabled" : null)); + + + ExecuteShellCommand(runSpace, cmd); + + } + finally + { + + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("SetMailboxGeneralSettingsInternal"); + } + + private void ChangeMailboxState(string id, bool enabled) + { + string path = AddADPrefix(id); + DirectoryEntry entry = GetADObject(path); + entry.InvokeSet("AccountDisabled", !enabled); + entry.CommitChanges(); + } + + private ExchangeMailbox GetMailboxMailFlowSettingsInternal(string accountName) + { + ExchangeLog.LogStart("GetMailboxMailFlowSettings"); + ExchangeLog.DebugInfo("Account: {0}", accountName); + + ExchangeMailbox info = new ExchangeMailbox(); + info.AccountName = accountName; + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + Collection result = GetMailboxObject(runSpace, accountName); + PSObject mailbox = result[0]; + + string forwardingAddress = ObjToString(GetPSObjectProperty(mailbox, "ForwardingAddress")); + if (string.IsNullOrEmpty(forwardingAddress)) + { + info.EnableForwarding = false; + info.ForwardingAccount = null; + info.DoNotDeleteOnForward = false; + } + else + { + info.EnableForwarding = true; + info.ForwardingAccount = GetExchangeAccount(runSpace, forwardingAddress); + info.DoNotDeleteOnForward = (bool)GetPSObjectProperty(mailbox, "DeliverToMailboxAndForward"); + } + + info.SendOnBehalfAccounts = GetSendOnBehalfAccounts(runSpace, mailbox); + info.AcceptAccounts = GetAcceptedAccounts(runSpace, mailbox); + info.RejectAccounts = GetRejectedAccounts(runSpace, mailbox); + info.MaxRecipients = + ConvertUnlimitedToInt32((Unlimited)GetPSObjectProperty(mailbox, "RecipientLimits")); + info.MaxSendMessageSizeKB = + ConvertUnlimitedToKB((Unlimited)GetPSObjectProperty(mailbox, "MaxSendSize")); + info.MaxReceiveMessageSizeKB = + ConvertUnlimitedToKB((Unlimited)GetPSObjectProperty(mailbox, "MaxReceiveSize")); + info.RequireSenderAuthentication = (bool)GetPSObjectProperty(mailbox, "RequireSenderAuthenticationEnabled"); + } + finally + { + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("GetMailboxMailFlowSettings"); + return info; + } + + private void SetMailboxMailFlowSettingsInternal(string accountName, bool enableForwarding, + string forwardingAccountName, bool forwardToBoth, string[] sendOnBehalfAccounts, + string[] acceptAccounts, string[] rejectAccounts, bool requireSenderAuthentication) + { + ExchangeLog.LogStart("SetMailboxMailFlowSettingsInternal"); + ExchangeLog.DebugInfo("Account: {0}", accountName); + + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + + Command cmd = new Command("Set-Mailbox"); + cmd.Parameters.Add("Identity", accountName); + + if (enableForwarding) + { + cmd.Parameters.Add("ForwardingAddress", forwardingAccountName); + cmd.Parameters.Add("DeliverToMailboxAndForward", forwardToBoth); + } + else + { + cmd.Parameters.Add("ForwardingAddress", null); + cmd.Parameters.Add("DeliverToMailboxAndForward", false); + } + + cmd.Parameters.Add("GrantSendOnBehalfTo", SetSendOnBehalfAccounts(runSpace, sendOnBehalfAccounts)); + + MultiValuedProperty ids = null; + MultiValuedProperty dlIds = null; + + SetAccountIds(runSpace, acceptAccounts, out ids, out dlIds); + cmd.Parameters.Add("AcceptMessagesOnlyFrom", ids); + cmd.Parameters.Add("AcceptMessagesOnlyFromDLMembers", dlIds); + + SetAccountIds(runSpace, rejectAccounts, out ids, out dlIds); + cmd.Parameters.Add("RejectMessagesFrom", ids); + cmd.Parameters.Add("RejectMessagesFromDLMembers", dlIds); + + cmd.Parameters.Add("RequireSenderAuthenticationEnabled", requireSenderAuthentication); + + ExecuteShellCommand(runSpace, cmd); + + } + finally + { + + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("SetMailboxMailFlowSettingsInternal"); + } + + private ExchangeMailbox GetMailboxAdvancedSettingsInternal(string accountName) + { + ExchangeLog.LogStart("GetMailboxAdvancedSettingsInternal"); + ExchangeLog.DebugInfo("Account: {0}", accountName); + + ExchangeMailbox info = new ExchangeMailbox(); + info.AccountName = accountName; + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + Collection result = GetMailboxObject(runSpace, accountName); + PSObject mailbox = result[0]; + + info.IssueWarningKB = + ConvertUnlimitedToKB((Unlimited)GetPSObjectProperty(mailbox, "IssueWarningQuota")); + info.ProhibitSendKB = + ConvertUnlimitedToKB((Unlimited)GetPSObjectProperty(mailbox, "ProhibitSendQuota")); + info.ProhibitSendReceiveKB = + ConvertUnlimitedToKB((Unlimited)GetPSObjectProperty(mailbox, "ProhibitSendReceiveQuota")); + info.KeepDeletedItemsDays = + ConvertEnhancedTimeSpanToDays((EnhancedTimeSpan)GetPSObjectProperty(mailbox, "RetainDeletedItemsFor")); + + info.EnableLitigationHold = (bool)GetPSObjectProperty(mailbox, "LitigationHoldEnabled"); + + info.RecoverabelItemsSpace = + ConvertUnlimitedToKB((Unlimited)GetPSObjectProperty(mailbox, "RecoverableItemsQuota")); + info.RecoverabelItemsWarning = + ConvertUnlimitedToKB((Unlimited)GetPSObjectProperty(mailbox, "RecoverableItemsWarningQuota")); + + //Client Access + Command cmd = new Command("Get-CASMailbox"); + cmd.Parameters.Add("Identity", accountName); + result = ExecuteShellCommand(runSpace, cmd); + mailbox = result[0]; + + info.EnableActiveSync = (bool)GetPSObjectProperty(mailbox, "ActiveSyncEnabled"); + info.EnableOWA = (bool)GetPSObjectProperty(mailbox, "OWAEnabled"); + info.EnableMAPI = (bool)GetPSObjectProperty(mailbox, "MAPIEnabled"); + info.EnablePOP = (bool)GetPSObjectProperty(mailbox, "PopEnabled"); + info.EnableIMAP = (bool)GetPSObjectProperty(mailbox, "ImapEnabled"); + + //Statistics + cmd = new Command("Get-MailboxStatistics"); + cmd.Parameters.Add("Identity", accountName); + result = ExecuteShellCommand(runSpace, cmd); + if (result.Count > 0) + { + PSObject statistics = result[0]; + Unlimited totalItemSize = + (Unlimited)GetPSObjectProperty(statistics, "TotalItemSize"); + info.TotalSizeMB = ConvertUnlimitedToMB(totalItemSize); + uint? itemCount = (uint?)GetPSObjectProperty(statistics, "ItemCount"); + info.TotalItems = ConvertNullableToInt32(itemCount); + DateTime? lastLogoffTime = (DateTime?)GetPSObjectProperty(statistics, "LastLogoffTime"); ; + DateTime? lastLogonTime = (DateTime?)GetPSObjectProperty(statistics, "LastLogonTime"); ; + info.LastLogoff = ConvertNullableToDateTime(lastLogoffTime); + info.LastLogon = ConvertNullableToDateTime(lastLogonTime); + } + else + { + info.TotalSizeMB = 0; + info.TotalItems = 0; + info.LastLogoff = DateTime.MinValue; + info.LastLogon = DateTime.MinValue; + } + + //domain + info.Domain = GetNETBIOSDomainName(); + } + finally + { + + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("GetMailboxAdvancedSettingsInternal"); + return info; + } + + private void SetMailboxAdvancedSettingsInternal(string organizationId, string accountName, bool enablePOP, bool enableIMAP, + bool enableOWA, bool enableMAPI, bool enableActiveSync, long issueWarningKB, long prohibitSendKB, + long prohibitSendReceiveKB, int keepDeletedItemsDays, int maxRecipients, int maxSendMessageSizeKB, + int maxReceiveMessageSizeKB, bool enabledLitigationHold, long recoverabelItemsSpace, long recoverabelItemsWarning) + { + ExchangeLog.LogStart("SetMailboxAdvancedSettingsInternal"); + ExchangeLog.DebugInfo("Account: {0}", accountName); + + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + + Command cmd = new Command("Set-Mailbox"); + cmd.Parameters.Add("Identity", accountName); + cmd.Parameters.Add("IssueWarningQuota", ConvertKBToUnlimited(issueWarningKB)); + cmd.Parameters.Add("ProhibitSendQuota", ConvertKBToUnlimited(prohibitSendKB)); + cmd.Parameters.Add("ProhibitSendReceiveQuota", ConvertKBToUnlimited(prohibitSendReceiveKB)); + cmd.Parameters.Add("RetainDeletedItemsFor", ConvertDaysToEnhancedTimeSpan(keepDeletedItemsDays)); + cmd.Parameters.Add("RecipientLimits", ConvertInt32ToUnlimited(maxRecipients)); + cmd.Parameters.Add("MaxSendSize", ConvertKBToUnlimited(maxSendMessageSizeKB)); + cmd.Parameters.Add("MaxReceiveSize", ConvertKBToUnlimited(maxReceiveMessageSizeKB)); + + if (enabledLitigationHold) + { + cmd.Parameters.Add("LitigationHoldEnabled", true); + cmd.Parameters.Add("RecoverableItemsQuota", ConvertKBToUnlimited(recoverabelItemsSpace)); + cmd.Parameters.Add("RecoverableItemsWarningQuota", ConvertKBToUnlimited(recoverabelItemsWarning)); + } + + ExecuteShellCommand(runSpace, cmd); + + //Client Access + cmd = new Command("Set-CASMailbox"); + cmd.Parameters.Add("Identity", accountName); + cmd.Parameters.Add("ActiveSyncEnabled", enableActiveSync); + if (enableActiveSync) + { + cmd.Parameters.Add("ActiveSyncMailboxPolicy", organizationId); + } + cmd.Parameters.Add("OWAEnabled", enableOWA); + cmd.Parameters.Add("MAPIEnabled", enableMAPI); + cmd.Parameters.Add("PopEnabled", enablePOP); + cmd.Parameters.Add("ImapEnabled", enableIMAP); + ExecuteShellCommand(runSpace, cmd); + } + finally + { + + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("SetMailboxAdvancedSettingsInternal"); + } + + private ExchangeEmailAddress[] GetMailboxEmailAddressesInternal(string accountName) + { + ExchangeLog.LogStart("GetMailboxEmailAddressesInternal"); + ExchangeLog.DebugInfo("Account: {0}", accountName); + + List list = new List(); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + Collection result = GetMailboxObject(runSpace, accountName); + PSObject mailbox = result[0]; + + string primaryEmail = null; + string windowsEmail = null; + + SmtpAddress smtpAddress = (SmtpAddress)GetPSObjectProperty(mailbox, "PrimarySmtpAddress"); + if (smtpAddress != null) + primaryEmail = smtpAddress.ToString(); + + //SmtpAddress winAddress = (SmtpAddress)GetPSObjectProperty(mailbox, "WindowsEmailAddress"); + windowsEmail = ObjToString(GetPSObjectProperty(mailbox, "CustomAttribute3")); + + ProxyAddressCollection emails = (ProxyAddressCollection)GetPSObjectProperty(mailbox, "EmailAddresses"); + foreach (ProxyAddress email in emails) + { + //skip windows email + if (string.Equals(email.AddressString, windowsEmail, StringComparison.OrdinalIgnoreCase)) + continue; + + ExchangeEmailAddress item = new ExchangeEmailAddress(); + item.Email = email.AddressString; + item.Primary = string.Equals(item.Email, primaryEmail, StringComparison.OrdinalIgnoreCase); + list.Add(item); + } + } + finally + { + + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("GetMailboxEmailAddressesInternal"); + return list.ToArray(); + } + + private void SetMailboxEmailAddressesInternal(string accountName, string[] emailAddresses) + { + ExchangeLog.LogStart("SetMailboxEmailAddressesInternal"); + ExchangeLog.DebugInfo("Account: {0}", accountName); + + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + Collection result = GetMailboxObject(runSpace, accountName); + PSObject mailbox = result[0]; + + //SmtpAddress winAddress = (SmtpAddress)GetPSObjectProperty(mailbox, "WindowsEmailAddress"); + //if (winAddress != null) + // windowsEmail = winAddress.ToString(); + + string windowsEmail = ObjToString(GetPSObjectProperty(mailbox, "CustomAttribute3")); + + ProxyAddressCollection emails = new ProxyAddressCollection(); + ProxyAddress proxy = null; + string upn = null; + if (emailAddresses != null) + { + foreach (string email in emailAddresses) + { + proxy = ProxyAddress.Parse(email); + emails.Add(proxy); + if (proxy.IsPrimaryAddress) + { + upn = proxy.AddressString; + } + } + } + //add system windows email + if (!string.IsNullOrEmpty(windowsEmail)) + { + emails.Add(ProxyAddress.Parse(windowsEmail)); + } + + Command cmd = new Command("Set-Mailbox"); + cmd.Parameters.Add("Identity", accountName); + cmd.Parameters.Add("EmailAddresses", emails); + if (!string.IsNullOrEmpty(upn)) + { + cmd.Parameters.Add("UserPrincipalName", upn); + cmd.Parameters.Add("WindowsEmailAddress", upn); + } + ExecuteShellCommand(runSpace, cmd); + } + finally + { + + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("SetMailboxEmailAddressesInternal"); + } + + private void SetMailboxPrimaryEmailAddressInternal(string accountName, string emailAddress) + { + ExchangeLog.LogStart("SetMailboxPrimaryEmailAddressInternal"); + ExchangeLog.DebugInfo("Account: {0}", accountName); + + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + + SmtpAddress primaryEmail = new SmtpAddress(emailAddress); + Command cmd = new Command("Set-Mailbox"); + cmd.Parameters.Add("Identity", accountName); + cmd.Parameters.Add("PrimarySmtpAddress", primaryEmail); + cmd.Parameters.Add("UserPrincipalName", primaryEmail); + cmd.Parameters.Add("WindowsEmailAddress", primaryEmail); + + ExecuteShellCommand(runSpace, cmd); + } + finally + { + + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("SetMailboxPrimaryEmailAddressInternal"); + } + + + private ExchangeAccount[] GetSendOnBehalfAccounts(Runspace runSpace, PSObject exchangeObject) + { + List list = new List(); + + IList ids = + (IList)GetPSObjectProperty(exchangeObject, "GrantSendOnBehalfTo"); + + foreach (ADObjectId id in ids) + { + ExchangeAccount account = GetExchangeAccount(runSpace, id.ToString()); + if (account != null) + list.Add(account); + } + return list.ToArray(); + } + + internal MultiValuedProperty SetSendOnBehalfAccounts(Runspace runspace, string[] accounts) + { + if (accounts == null || accounts.Length == 0) + return MultiValuedProperty.Empty; + else + { + MultiValuedProperty ids = new MultiValuedProperty(); + string dn = null; + foreach (string account in accounts) + { + dn = GetRecipientDistinguishedName(runspace, account); + ids.Add(new ADObjectId(dn)); + } + return ids; + } + } + + private ExchangeAccount[] GetAcceptedAccounts(Runspace runSpace, PSObject mailbox) + { + List list = new List(); + ExchangeAccount account = null; + IList ids = + (IList)GetPSObjectProperty(mailbox, "AcceptMessagesOnlyFrom"); + foreach (ADObjectId id in ids) + { + account = GetExchangeAccount(runSpace, id.ToString()); + if (account != null) + list.Add(account); + } + ids = (IList)GetPSObjectProperty(mailbox, "AcceptMessagesOnlyFromDLMembers"); + foreach (ADObjectId id in ids) + { + account = GetExchangeAccount(runSpace, id.ToString()); + if (account != null) + list.Add(account); + } + + return list.ToArray(); + } + + private void SetAccountIds(Runspace runspace, string[] accounts, + out MultiValuedProperty ids, out MultiValuedProperty dlIds) + { + ids = MultiValuedProperty.Empty; + dlIds = MultiValuedProperty.Empty; + + if (accounts == null || accounts.Length == 0) + return; + + ids = new MultiValuedProperty(); + dlIds = new MultiValuedProperty(); + + string dn = null; + string type = null; + foreach (string account in accounts) + { + type = GetRecipientType(runspace, account, out dn); + if (type == "MailUniversalDistributionGroup") + dlIds.Add(new ADObjectId(dn)); + else + ids.Add(new ADObjectId(dn)); + } + if (ids.Count == 0) + ids = MultiValuedProperty.Empty; + if (dlIds.Count == 0) + dlIds = MultiValuedProperty.Empty; + } + + + private ExchangeAccount[] GetRejectedAccounts(Runspace runSpace, PSObject mailbox) + { + List list = new List(); + ExchangeAccount account = null; + IList ids = + (IList)GetPSObjectProperty(mailbox, "RejectMessagesFrom"); + foreach (ADObjectId id in ids) + { + account = GetExchangeAccount(runSpace, id.ToString()); + if (account != null) + list.Add(account); + } + ids = (IList)GetPSObjectProperty(mailbox, "RejectMessagesFromDLMembers"); + foreach (ADObjectId id in ids) + { + account = GetExchangeAccount(runSpace, id.ToString()); + if (account != null) + list.Add(account); + } + return list.ToArray(); + } + + internal ExchangeAccount GetExchangeAccount(Runspace runSpace, string id) + { + return GetOrganizationAccount(runSpace, null, id); + } + + internal ExchangeAccount GetOrganizationAccount(Runspace runSpace, string organizationId, string id) + { + if (string.IsNullOrEmpty(id)) + return null; + + ExchangeAccount ret = null; + Command cmd = new Command("Get-Recipient"); + cmd.Parameters.Add("Identity", id); + Collection result = ExecuteShellCommand(runSpace, cmd); + if (result != null && result.Count > 0) + { + //check for organization + if (!string.IsNullOrEmpty(organizationId)) + { + string attr1 = (string)GetPSObjectProperty(result[0], "CustomAttribute1"); + if (!string.Equals(organizationId, attr1, StringComparison.InvariantCultureIgnoreCase)) + return ret; + } + ret = new ExchangeAccount(); + ret.AccountName = (string)GetPSObjectProperty(result[0], "Alias"); + ret.DisplayName = (string)GetPSObjectProperty(result[0], "DisplayName"); + ret.PrimaryEmailAddress = ObjToString(GetPSObjectProperty(result[0], "PrimarySmtpAddress")); + ret.AccountType = ParseAccountType(ObjToString(GetPSObjectProperty(result[0], "RecipientType"))); + if (ret.AccountType == ExchangeAccountType.Contact) + { + string email = ObjToString(GetPSObjectProperty(result[0], "ExternalEmailAddress")); + if (!string.IsNullOrEmpty(email) && email.StartsWith("SMTP:")) + ret.PrimaryEmailAddress = email.Substring(5); + } + } + return ret; + } + + + + private ExchangeAccountType ParseAccountType(string type) + { + ExchangeAccountType ret = ExchangeAccountType.Mailbox; + switch (type) + { + case "UserMailbox": + ret = ExchangeAccountType.Mailbox; + break; + case "MailContact": + ret = ExchangeAccountType.Contact; + break; + case "MailUniversalDistributionGroup": + ret = ExchangeAccountType.DistributionList; + break; + case "PublicFolder": + ret = ExchangeAccountType.PublicFolder; + break; + } + return ret; + } + + private string GetRecipientDistinguishedName(Runspace runSpace, string id) + { + if (string.IsNullOrEmpty(id)) + return null; + + string dn = null; + Command cmd = new Command("Get-Recipient"); + cmd.Parameters.Add("Identity", id); + Collection result = ExecuteShellCommand(runSpace, cmd); + if (result != null && result.Count > 0) + { + dn = (string)GetPSObjectProperty(result[0], "DistinguishedName"); + } + return dn; + } + + private string GetRecipientType(Runspace runSpace, string id, out string name) + { + name = null; + if (string.IsNullOrEmpty(id)) + return null; + + string type = null; + Command cmd = new Command("Get-Recipient"); + cmd.Parameters.Add("Identity", id); + Collection result = ExecuteShellCommand(runSpace, cmd); + if (result != null && result.Count > 0) + { + name = (string)GetPSObjectProperty(result[0], "DistinguishedName"); + type = GetPSObjectProperty(result[0], "RecipientType").ToString(); + } + return type; + } + + private ExchangeMailboxStatistics GetMailboxStatisticsInternal(string id) + { + ExchangeLog.LogStart("GetMailboxStatisticsInternal"); + ExchangeLog.DebugInfo("Account: {0}", id); + + ExchangeMailboxStatistics info = new ExchangeMailboxStatistics(); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + Collection result = GetMailboxObject(runSpace, id); + PSObject mailbox = result[0]; + + string dn = GetResultObjectDN(result); + string path = AddADPrefix(dn); + DirectoryEntry entry = GetADObject(path); + info.Enabled = !(bool)entry.InvokeGet("AccountDisabled"); + + info.DisplayName = (string)GetPSObjectProperty(mailbox, "DisplayName"); + SmtpAddress smtpAddress = (SmtpAddress)GetPSObjectProperty(mailbox, "PrimarySmtpAddress"); + if (smtpAddress != null) + info.PrimaryEmailAddress = smtpAddress.ToString(); + + info.MaxSize = ConvertUnlimitedToBytes((Unlimited)GetPSObjectProperty(mailbox, "ProhibitSendReceiveQuota")); + DateTime? whenCreated = (DateTime?)GetPSObjectProperty(mailbox, "WhenCreated"); + info.AccountCreated = ConvertNullableToDateTime(whenCreated); + //Client Access + Command cmd = new Command("Get-CASMailbox"); + cmd.Parameters.Add("Identity", id); + result = ExecuteShellCommand(runSpace, cmd); + mailbox = result[0]; + + info.ActiveSyncEnabled = (bool)GetPSObjectProperty(mailbox, "ActiveSyncEnabled"); + info.OWAEnabled = (bool)GetPSObjectProperty(mailbox, "OWAEnabled"); + info.MAPIEnabled = (bool)GetPSObjectProperty(mailbox, "MAPIEnabled"); + info.POPEnabled = (bool)GetPSObjectProperty(mailbox, "PopEnabled"); + info.IMAPEnabled = (bool)GetPSObjectProperty(mailbox, "ImapEnabled"); + + //Statistics + cmd = new Command("Get-MailboxStatistics"); + cmd.Parameters.Add("Identity", id); + result = ExecuteShellCommand(runSpace, cmd); + if (result.Count > 0) + { + PSObject statistics = result[0]; + Unlimited totalItemSize = + (Unlimited)GetPSObjectProperty(statistics, "TotalItemSize"); + info.TotalSize = ConvertUnlimitedToBytes(totalItemSize); + uint? itemCount = (uint?)GetPSObjectProperty(statistics, "ItemCount"); + info.TotalItems = ConvertNullableToInt32(itemCount); + DateTime? lastLogoffTime = (DateTime?)GetPSObjectProperty(statistics, "LastLogoffTime"); + DateTime? lastLogonTime = (DateTime?)GetPSObjectProperty(statistics, "LastLogonTime"); + info.LastLogoff = ConvertNullableToDateTime(lastLogoffTime); + info.LastLogon = ConvertNullableToDateTime(lastLogonTime); + } + else + { + info.TotalSize = 0; + info.TotalItems = 0; + info.LastLogoff = DateTime.MinValue; + info.LastLogon = DateTime.MinValue; + } + } + finally + { + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("GetMailboxStatisticsInternal"); + return info; + } + + private Collection GetMailboxObject(Runspace runSpace, string id) + { + Command cmd = new Command("Get-Mailbox"); + cmd.Parameters.Add("Identity", id); + Collection result = ExecuteShellCommand(runSpace, cmd); + return result; + } + + #endregion + + #region Contacts + private void CreateContactInternal( + string organizationId, + string organizationDistinguishedName, + string contactDisplayName, + string contactAccountName, + string contactEmail, + string defaultOrganizationDomain) + { + ExchangeLog.LogStart("CreateContactInternal"); + ExchangeLog.DebugInfo("Organization Id: {0}", organizationId); + ExchangeLog.DebugInfo("Name: {0}", contactDisplayName); + ExchangeLog.DebugInfo("Account: {0}", contactAccountName); + ExchangeLog.DebugInfo("Email: {0}", contactEmail); + + ExchangeTransaction transaction = StartTransaction(); + + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + + string ouName = ConvertADPathToCanonicalName(organizationDistinguishedName); + string tempEmail = string.Format("{0}@{1}", Guid.NewGuid().ToString("N"), defaultOrganizationDomain); + //create contact + Command cmd = new Command("New-MailContact"); + cmd.Parameters.Add("Name", contactAccountName); + cmd.Parameters.Add("DisplayName", contactDisplayName); + cmd.Parameters.Add("OrganizationalUnit", ouName); + cmd.Parameters.Add("Alias", contactAccountName); + cmd.Parameters.Add("ExternalEmailAddress", tempEmail); + Collection result = ExecuteShellCommand(runSpace, cmd); + string id = GetResultObjectDN(result); + + transaction.RegisterNewContact(id); + + //update contact + cmd = new Command("Set-MailContact"); + cmd.Parameters.Add("Identity", contactAccountName); + cmd.Parameters.Add("EmailAddressPolicyEnabled", false); + cmd.Parameters.Add("CustomAttribute1", organizationId); + cmd.Parameters.Add("WindowsEmailAddress", tempEmail); + ExecuteShellCommand(runSpace, cmd); + + SetContactEmail(id, contactEmail); + + } + catch (Exception ex) + { + ExchangeLog.LogError("CreateContactInternal", ex); + RollbackTransaction(transaction); + throw; + } + finally + { + + CloseRunspace(runSpace); + } + + ExchangeLog.LogEnd("CreateContactInternal"); + } + + private void DeleteContactInternal(string accountName) + { + ExchangeLog.LogStart("DeleteContactInternal"); + ExchangeLog.DebugInfo("Account Name: {0}", accountName); + + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + RemoveContact(runSpace, accountName); + } + finally + { + + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("DeleteContactInternal"); + } + + private void RemoveContact(Runspace runSpace, string id) + { + ExchangeLog.LogStart("RemoveContact"); + Command cmd = new Command("Remove-MailContact"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("Confirm", false); + ExecuteShellCommand(runSpace, cmd); + ExchangeLog.LogEnd("RemoveContact"); + } + + private ExchangeContact GetContactGeneralSettingsInternal(string accountName) + { + ExchangeLog.LogStart("GetContactGeneralSettingsInternal"); + ExchangeLog.DebugInfo("Account: {0}", accountName); + + ExchangeContact info = new ExchangeContact(); + info.AccountName = accountName; + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + + Command cmd = new Command("Get-MailContact"); + cmd.Parameters.Add("Identity", accountName); + Collection result = ExecuteShellCommand(runSpace, cmd); + PSObject contact = result[0]; + string id = GetResultObjectDN(result); + + info.DisplayName = (string)GetPSObjectProperty(contact, "DisplayName"); + info.HideFromAddressBook = (bool)GetPSObjectProperty(contact, "HiddenFromAddressListsEnabled"); + info.EmailAddress = GetContactEmail(id); + info.UseMapiRichTextFormat = (int)GetPSObjectProperty(contact, "UseMapiRichTextFormat"); + + cmd = new Command("Get-Contact"); + cmd.Parameters.Add("Identity", accountName); + result = ExecuteShellCommand(runSpace, cmd); + PSObject user = result[0]; + + info.FirstName = (string)GetPSObjectProperty(user, "FirstName"); + info.Initials = (string)GetPSObjectProperty(user, "Initials"); + info.LastName = (string)GetPSObjectProperty(user, "LastName"); + + info.Address = (string)GetPSObjectProperty(user, "StreetAddress"); + info.City = (string)GetPSObjectProperty(user, "City"); + info.State = (string)GetPSObjectProperty(user, "StateOrProvince"); + info.Zip = (string)GetPSObjectProperty(user, "PostalCode"); + info.Country = CountryInfoToString((CountryInfo)GetPSObjectProperty(user, "CountryOrRegion")); + info.JobTitle = (string)GetPSObjectProperty(user, "Title"); + info.Company = (string)GetPSObjectProperty(user, "Company"); + info.Department = (string)GetPSObjectProperty(user, "Department"); + info.Office = (string)GetPSObjectProperty(user, "Office"); + info.ManagerAccount = GetExchangeAccount(runSpace, ObjToString(GetPSObjectProperty(user, "Manager"))); + info.BusinessPhone = (string)GetPSObjectProperty(user, "Phone"); + info.Fax = (string)GetPSObjectProperty(user, "Fax"); + info.HomePhone = (string)GetPSObjectProperty(user, "HomePhone"); + info.MobilePhone = (string)GetPSObjectProperty(user, "MobilePhone"); + info.Pager = (string)GetPSObjectProperty(user, "Pager"); + info.WebPage = (string)GetPSObjectProperty(user, "WebPage"); + info.Notes = (string)GetPSObjectProperty(user, "Notes"); + + info.SAMAccountName = string.Format("{0}\\{1}", GetNETBIOSDomainName(), (string)GetPSObjectProperty(user, "Name")); + + } + finally + { + + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("GetContactGeneralSettingsInternal"); + return info; + } + + private void SetContactEmail(string id, string email) + { + string cn = ActiveDirectoryUtils.AddADPrefix(id, PrimaryDomainController); + DirectoryEntry de = ActiveDirectoryUtils.GetADObject(cn); + ActiveDirectoryUtils.SetADObjectPropertyValue(de, "targetAddress", "SMTP:" + email); + //ActiveDirectoryUtils.SetADObjectPropertyValue(de, "mail", email); + de.CommitChanges(); + + } + + private string GetContactEmail(string id) + { + string cn = ActiveDirectoryUtils.AddADPrefix(id, PrimaryDomainController); + DirectoryEntry de = ActiveDirectoryUtils.GetADObject(cn); + string email = ActiveDirectoryUtils.GetADObjectStringProperty(de, "targetAddress"); + if (email != null && email.ToLower().StartsWith("smtp:")) + email = email.Substring(5); + return email; + } + + private void SetContactGeneralSettingsInternal(string accountName, string displayName, string email, + bool hideFromAddressBook, string firstName, string initials, string lastName, string address, + string city, string state, string zip, string country, string jobTitle, string company, + string department, string office, string managerAccountName, string businessPhone, string fax, + string homePhone, string mobilePhone, string pager, string webPage, string notes, int useMapiRichTextFormat, string defaultDomain) + { + ExchangeLog.LogStart("SetContactGeneralSettingsInternal"); + ExchangeLog.DebugInfo("Account: {0}", accountName); + + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + Command cmd = new Command("Get-MailContact"); + cmd.Parameters.Add("Identity", accountName); + Collection result = ExecuteShellCommand(runSpace, cmd); + + string id = GetResultObjectDN(result); + string tempEmail = SmtpAddressToString((SmtpAddress)GetPSObjectProperty(result[0], "PrimarySmtpAddress")); + string[] parts = tempEmail.Split('@'); + if (parts != null && parts.Length > 0) + tempEmail = parts[0] + '@' + defaultDomain; + + cmd = new Command("Set-MailContact"); + cmd.Parameters.Add("Identity", accountName); + + cmd.Parameters.Add("DisplayName", displayName); + cmd.Parameters.Add("HiddenFromAddressListsEnabled", hideFromAddressBook); + cmd.Parameters.Add("ExternalEmailAddress", tempEmail); + cmd.Parameters.Add("UseMapiRichTextFormat", (UseMapiRichTextFormat)useMapiRichTextFormat); + cmd.Parameters.Add("WindowsEmailAddress", tempEmail); + ExecuteShellCommand(runSpace, cmd); + + + cmd = new Command("Set-Contact"); + cmd.Parameters.Add("Identity", accountName); + cmd.Parameters.Add("FirstName", firstName); + cmd.Parameters.Add("Initials", initials); + cmd.Parameters.Add("LastName", lastName); + cmd.Parameters.Add("StreetAddress", address); + cmd.Parameters.Add("City", city); + cmd.Parameters.Add("StateOrProvince", state); + cmd.Parameters.Add("PostalCode", zip); + cmd.Parameters.Add("CountryOrRegion", ParseCountryInfo(country)); + cmd.Parameters.Add("Title", jobTitle); + cmd.Parameters.Add("Company", company); + cmd.Parameters.Add("Department", department); + cmd.Parameters.Add("Office", office); + cmd.Parameters.Add("Manager", managerAccountName); + cmd.Parameters.Add("Phone", businessPhone); + cmd.Parameters.Add("Fax", fax); + cmd.Parameters.Add("HomePhone", homePhone); + cmd.Parameters.Add("MobilePhone", mobilePhone); + cmd.Parameters.Add("Pager", pager); + cmd.Parameters.Add("WebPage", webPage); + cmd.Parameters.Add("Notes", notes); + + ExecuteShellCommand(runSpace, cmd); + + SetContactEmail(id, email); + + } + finally + { + + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("SetContactGeneralSettingsInternal"); + } + + private ExchangeContact GetContactMailFlowSettingsInternal(string accountName) + { + ExchangeLog.LogStart("GetContactMailFlowSettingsInternal"); + ExchangeLog.DebugInfo("Account: {0}", accountName); + + ExchangeContact info = new ExchangeContact(); + info.AccountName = accountName; + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + + Command cmd = new Command("Get-MailContact"); + cmd.Parameters.Add("Identity", accountName); + Collection result = ExecuteShellCommand(runSpace, cmd); + PSObject contact = result[0]; + + info.AcceptAccounts = GetAcceptedAccounts(runSpace, contact); + info.RejectAccounts = GetRejectedAccounts(runSpace, contact); + info.RequireSenderAuthentication = (bool)GetPSObjectProperty(contact, "RequireSenderAuthenticationEnabled"); + } + finally + { + + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("GetContactMailFlowSettingsInternal"); + return info; + } + + private void SetContactMailFlowSettingsInternal(string accountName, string[] acceptAccounts, + string[] rejectAccounts, bool requireSenderAuthentication) + { + ExchangeLog.LogStart("SetContactMailFlowSettingsInternal"); + ExchangeLog.DebugInfo("Account: {0}", accountName); + + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + + Command cmd = new Command("Set-MailContact"); + cmd.Parameters.Add("Identity", accountName); + + MultiValuedProperty ids = null; + MultiValuedProperty dlIds = null; + + SetAccountIds(runSpace, acceptAccounts, out ids, out dlIds); + cmd.Parameters.Add("AcceptMessagesOnlyFrom", ids); + cmd.Parameters.Add("AcceptMessagesOnlyFromDLMembers", dlIds); + + SetAccountIds(runSpace, rejectAccounts, out ids, out dlIds); + cmd.Parameters.Add("RejectMessagesFrom", ids); + cmd.Parameters.Add("RejectMessagesFromDLMembers", dlIds); + cmd.Parameters.Add("RequireSenderAuthenticationEnabled", requireSenderAuthentication); + + ExecuteShellCommand(runSpace, cmd); + + } + finally + { + + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("SetContactMailFlowSettingsInternal"); + } + + #endregion + + #region Distribution groups + /// + /// Creates Security Distribution Group + /// + /// + /// + /// + /// LDAP path + private string CreateSecurityDistributionGroup(Runspace runSpace, string ouName, string groupName) + { + ExchangeLog.LogStart("CreateSecurityDistributionGroup"); + + Command cmd = new Command("New-DistributionGroup"); + cmd.Parameters.Add("Name", groupName); + cmd.Parameters.Add("Type", "Security"); + cmd.Parameters.Add("OrganizationalUnit", ouName); + cmd.Parameters.Add("SamAccountName", groupName); + cmd.Parameters.Add("Alias", groupName); + + Collection result = ExecuteShellCommand(runSpace, cmd); + string id = CheckResultObjectDN(result); + + ExchangeLog.LogEnd("CreateSecurityDistributionGroup"); + return id; + } + + internal string EnableMailSecurityDistributionGroup(Runspace runSpace, string distName, string groupName) + { + ExchangeLog.LogStart("EnableMailSecurityDistributionGroup"); + ExchangeLog.DebugInfo("Group Distinguished Name: {0}", distName); + ExchangeLog.DebugInfo("Group Name: {0}", groupName); + + int attempts = 0; + string securityGroupId = null; + + while (true) + { + try + { + Command cmd = new Command("Enable-DistributionGroup"); + cmd.Parameters.Add("Identity", distName); + cmd.Parameters.Add("Alias", groupName); + + Collection result = ExecuteShellCommand(runSpace, cmd); + + securityGroupId = CheckResultObjectDN(result); + ExchangeLog.DebugInfo("Result: {0}", securityGroupId); + } + catch (Exception ex) + { + Log.WriteError(ex); + } + + if (securityGroupId != null) + break; + + if (attempts > 3) + throw new Exception( + string.Format("Could not enable mail Security Distribution Group '{0}' ", groupName)); + + attempts++; + ExchangeLog.LogWarning("Attempt #{0} to enable mail Security Distribution Group failed!", attempts); + // wait 5 sec + System.Threading.Thread.Sleep(5000); + } + + + ExchangeLog.LogEnd("EnableMailSecurityDistributionGroup"); + return securityGroupId; + } + + internal void DisableMailSecurityDistributionGroup(Runspace runSpace, string id) + { + ExchangeLog.LogStart("DisableMailSecurityDistributionGroup"); + ExchangeLog.DebugInfo("Group Id: {0}", id); + Command cmd = new Command("Disable-DistributionGroup"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("Confirm", false); + ExecuteShellCommand(runSpace, cmd); + ExchangeLog.LogEnd("DisableMailSecurityDistributionGroup"); + } + + + internal void UpdateSecurityDistributionGroup(Runspace runSpace, string id, string groupName, bool isConsumer) + { + ExchangeLog.LogStart("UpdateSecurityDistributionGroup"); + + Command cmd = new Command("Set-DistributionGroup"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("EmailAddressPolicyEnabled", false); + cmd.Parameters.Add("CustomAttribute1", groupName); + cmd.Parameters.Add("HiddenFromAddressListsEnabled", !isConsumer); + ExecuteShellCommand(runSpace, cmd); + + ExchangeLog.LogEnd("UpdateSecurityDistributionGroup"); + } + + private void CreateDistributionListInternal( + string organizationId, + string organizationDistinguishedName, + string displayName, + string accountName, + string name, + string domain, + string managedBy, + string[] addressLists) + { + ExchangeLog.LogStart("CreateDistributionListInternal"); + ExchangeLog.DebugInfo("Organization Id: {0}", organizationId); + ExchangeLog.DebugInfo("Name: {0}", name); + ExchangeLog.DebugInfo("Domain: {0}", domain); + + ExchangeTransaction transaction = StartTransaction(); + + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + + string email = string.Format("{0}@{1}", name, domain); + string ouName = ConvertADPathToCanonicalName(organizationDistinguishedName); + + Command cmd = new Command("New-DistributionGroup"); + cmd.Parameters.Add("Name", accountName); + cmd.Parameters.Add("DisplayName", displayName); + cmd.Parameters.Add("Type", "Security"); + cmd.Parameters.Add("OrganizationalUnit", ouName); + cmd.Parameters.Add("SamAccountName", accountName); + cmd.Parameters.Add("Alias", accountName); + cmd.Parameters.Add("ManagedBy", managedBy); + + Collection result = ExecuteShellCommand(runSpace, cmd); + string id = GetResultObjectDN(result); + + transaction.RegisterNewDistributionGroup(id); + + //add manager permissions + if (!string.IsNullOrEmpty(managedBy)) + { + AddADPermission(runSpace, accountName, managedBy, "WriteProperty", null, "Member"); + } + + string windowsEmailAddress = ObjToString(GetPSObjectProperty(result[0], "WindowsEmailAddress")); + + //update + cmd = new Command("Set-DistributionGroup"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("EmailAddressPolicyEnabled", false); + cmd.Parameters.Add("CustomAttribute1", organizationId); + cmd.Parameters.Add("CustomAttribute3", windowsEmailAddress); + cmd.Parameters.Add("PrimarySmtpAddress", email); + cmd.Parameters.Add("WindowsEmailAddress", email); + cmd.Parameters.Add("RequireSenderAuthenticationEnabled", false); + ExecuteShellCommand(runSpace, cmd); + + //fix showInAddressBook Attribute + if (addressLists.Length > 0) + FixShowInAddressBook(runSpace, email, addressLists, false); + + } + catch (Exception ex) + { + ExchangeLog.LogError("CreateDistributionListInternal", ex); + RollbackTransaction(transaction); + throw; + } + finally + { + + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("CreateDistributionListInternal"); + } + + private void FixShowInAddressBook(Runspace runSpace, string accountName, string[] addressLists, bool HideFromAddressList) + { + Command cmd = new Command("Get-DistributionGroup"); + cmd.Parameters.Add("Identity", accountName); + + Collection result = ExecuteShellCommand(runSpace, cmd); + string id = GetResultObjectDN(result); + + DirectoryEntry dlDEEntry = GetADObject(AddADPrefix(id)); + dlDEEntry.Properties["showInAddressBook"].Clear(); + if (!HideFromAddressList) + { + foreach (string addressList in addressLists) + { + dlDEEntry.Properties["showInAddressBook"].Add(addressList); + } + } + dlDEEntry.CommitChanges(); + } + + private void DeleteDistributionListInternal(string accountName) + { + ExchangeLog.LogStart("DeleteDistributionListInternal"); + ExchangeLog.DebugInfo("Account Name: {0}", accountName); + + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + RemoveDistributionGroup(runSpace, accountName); + } + finally + { + + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("DeleteDistributionListInternal"); + } + + internal virtual void RemoveDistributionGroup(Runspace runSpace, string id) + { + ExchangeLog.LogStart("RemoveDistributionGroup"); + Command cmd = new Command("Remove-DistributionGroup"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("Confirm", false); + cmd.Parameters.Add("BypassSecurityGroupManagerCheck"); + ExecuteShellCommand(runSpace, cmd); + ExchangeLog.LogEnd("RemoveDistributionGroup"); + } + + private ExchangeDistributionList GetDistributionListGeneralSettingsInternal(string accountName) + { + ExchangeLog.LogStart("GetDistributionListGeneralSettingsInternal"); + ExchangeLog.DebugInfo("Account: {0}", accountName); + + ExchangeDistributionList info = new ExchangeDistributionList(); + info.AccountName = accountName; + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + + Command cmd = new Command("Get-DistributionGroup"); + cmd.Parameters.Add("Identity", accountName); + Collection result = ExecuteShellCommand(runSpace, cmd); + PSObject distributionGroup = result[0]; + + info.DisplayName = (string)GetPSObjectProperty(distributionGroup, "DisplayName"); + info.HideFromAddressBook = + (bool)GetPSObjectProperty(distributionGroup, "HiddenFromAddressListsEnabled"); + + info.SAMAccountName = string.Format("{0}\\{1}", GetNETBIOSDomainName(), (string)GetPSObjectProperty(distributionGroup, "SamAccountName")); + + cmd = new Command("Get-Group"); + cmd.Parameters.Add("Identity", accountName); + result = ExecuteShellCommand(runSpace, cmd); + PSObject group = result[0]; + + info.ManagerAccount = GetGroupManagerAccount(runSpace, group); + info.MembersAccounts = GetGroupMembers(runSpace, accountName); + info.Notes = (string)GetPSObjectProperty(group, "Notes"); + } + finally + { + + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("GetDistributionListGeneralSettingsInternal"); + return info; + } + + internal virtual ExchangeAccount GetGroupManagerAccount(Runspace runSpace, PSObject group) + { + return GetExchangeAccount(runSpace, GetGroupManager(group)); + } + + internal virtual string GetGroupManager(PSObject group) + { + string ret = null; + MultiValuedProperty ids = + (MultiValuedProperty)GetPSObjectProperty(group, "ManagedBy"); + if (ids.Count > 0) + ret = ObjToString(ids[0]); + return ret; + } + + private void SetDistributionListGeneralSettingsInternal(string accountName, string displayName, + bool hideFromAddressBook, string managedBy, string[] memberAccounts, string notes, string[] addressLists) + { + ExchangeLog.LogStart("SetDistributionListGeneralSettingsInternal"); + ExchangeLog.DebugInfo("Account: {0}", accountName); + + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + SetDistributionGroup(runSpace, accountName, displayName, hideFromAddressBook); + + //get old values + Command cmd = new Command("Get-Group"); + cmd.Parameters.Add("Identity", accountName); + Collection result = ExecuteShellCommand(runSpace, cmd); + PSObject group = result[0]; + string manager = GetGroupManager(group); + + //set members + ExchangeAccount[] accounts = GetGroupMembers(runSpace, accountName); + Dictionary existingMembers = new Dictionary(); + Dictionary newMembers = new Dictionary(); + List membersToDelete = new List(); + List membersToAdd = new List(); + + foreach (ExchangeAccount account in accounts) + { + existingMembers.Add(account.AccountName.ToLower(), account.AccountName); + } + + foreach (string member in memberAccounts) + { + newMembers.Add(member.ToLower(), member); + if (!existingMembers.ContainsKey(member.ToLower())) + { + membersToAdd.Add(member); + } + } + + foreach (string delAccount in existingMembers.Keys) + { + if (!newMembers.ContainsKey(delAccount)) + { + membersToDelete.Add(existingMembers[delAccount]); + } + } + + foreach (string member in membersToAdd) + { + AddDistributionGroupMember(runSpace, accountName, member); + } + + foreach (string member in membersToDelete) + { + RemoveDistributionGroupMember(runSpace, accountName, member); + } + + //remove old manager rights + if (!string.IsNullOrEmpty(manager)) + { + RemoveADPermission(runSpace, accountName, manager, "WriteProperty", null, "Member"); + } + + SetGroup(runSpace, accountName, managedBy, notes); + + if (!string.IsNullOrEmpty(managedBy)) + { + AddADPermission(runSpace, accountName, managedBy, "WriteProperty", null, "Member"); + } + + if (addressLists.Length > 0) + FixShowInAddressBook(runSpace, accountName, addressLists, hideFromAddressBook); + + } + finally + { + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("SetDistributionListGeneralSettingsInternal"); + } + + internal virtual void RemoveDistributionGroupMember(Runspace runSpace, string group, string member) + { + Command cmd = new Command("Remove-DistributionGroupMember"); + cmd.Parameters.Add("Identity", group); + cmd.Parameters.Add("Member", member); + cmd.Parameters.Add("Confirm", false); + cmd.Parameters.Add("BypassSecurityGroupManagerCheck"); + ExecuteShellCommand(runSpace, cmd); + } + + internal virtual void AddDistributionGroupMember(Runspace runSpace, string group, string member) + { + Command cmd = new Command("Add-DistributionGroupMember"); + cmd.Parameters.Add("Identity", group); + cmd.Parameters.Add("Member", member); + cmd.Parameters.Add("BypassSecurityGroupManagerCheck"); + ExecuteShellCommand(runSpace, cmd); + } + + + internal virtual void SetGroup(Runspace runSpace, string id, string managedBy, string notes) + { + Command cmd = new Command("Set-Group"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("ManagedBy", managedBy); + cmd.Parameters.Add("Notes", notes); + cmd.Parameters.Add("BypassSecurityGroupManagerCheck"); + ExecuteShellCommand(runSpace, cmd); + } + + internal virtual void SetDistributionGroup(Runspace runSpace, string id, string displayName, bool hideFromAddressBook) + { + Command cmd = new Command("Set-DistributionGroup"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("DisplayName", displayName); + cmd.Parameters.Add("HiddenFromAddressListsEnabled", hideFromAddressBook); + cmd.Parameters.Add("BypassSecurityGroupManagerCheck"); + ExecuteShellCommand(runSpace, cmd); + } + + + private void AddDistributionListMembersInternal(string accountName, string[] memberAccounts, string[] addressLists) + { + ExchangeLog.LogStart("AddDistributionListMembersInternal"); + ExchangeLog.DebugInfo("Account: {0}", accountName); + + if (memberAccounts != null && memberAccounts.Length > 0) + { + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + Command cmd = null; + + foreach (string member in memberAccounts) + { + cmd = new Command("Add-DistributionGroupMember"); + cmd.Parameters.Add("Identity", accountName); + cmd.Parameters.Add("Member", member); + cmd.Parameters.Add("BypassSecurityGroupManagerCheck", true); + ExecuteShellCommand(runSpace, cmd); + } + + if (addressLists.Length > 0) + { + cmd = new Command("Get-DistributionGroup"); + cmd.Parameters.Add("Identity", accountName); + Collection result = ExecuteShellCommand(runSpace, cmd); + PSObject distributionGroup = result[0]; + + FixShowInAddressBook(runSpace, accountName, addressLists, (bool)GetPSObjectProperty(distributionGroup, "HiddenFromAddressListsEnabled")); + } + + } + finally + { + + CloseRunspace(runSpace); + } + } + ExchangeLog.LogEnd("AddDistributionListMembersInternal"); + } + + private void RemoveDistributionListMembersInternal(string accountName, string[] memberAccounts, string[] addressLists) + { + ExchangeLog.LogStart("RemoveDistributionListMembersInternal"); + ExchangeLog.DebugInfo("Account: {0}", accountName); + + if (memberAccounts != null && memberAccounts.Length > 0) + { + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + Command cmd = null; + + foreach (string member in memberAccounts) + { + cmd = new Command("Remove-DistributionGroupMember"); + cmd.Parameters.Add("Identity", accountName); + cmd.Parameters.Add("Member", member); + cmd.Parameters.Add("Confirm", false); + ExecuteShellCommand(runSpace, cmd); + } + + if (addressLists.Length > 0) + { + cmd = new Command("Get-DistributionGroup"); + cmd.Parameters.Add("Identity", accountName); + Collection result = ExecuteShellCommand(runSpace, cmd); + PSObject distributionGroup = result[0]; + + FixShowInAddressBook(runSpace, accountName, addressLists, (bool)GetPSObjectProperty(distributionGroup, "HiddenFromAddressListsEnabled")); + } + + } + finally + { + + CloseRunspace(runSpace); + } + } + ExchangeLog.LogEnd("RemoveDistributionListMembersInternal"); + } + + private ExchangeDistributionList GetDistributionListMailFlowSettingsInternal(string accountName) + { + ExchangeLog.LogStart("GetDistributionListMailFlowSettingsInternal"); + ExchangeLog.DebugInfo("Account: {0}", accountName); + + ExchangeDistributionList info = new ExchangeDistributionList(); + info.AccountName = accountName; + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + + Command cmd = new Command("Get-DistributionGroup"); + cmd.Parameters.Add("Identity", accountName); + Collection result = ExecuteShellCommand(runSpace, cmd); + PSObject group = result[0]; + + info.AcceptAccounts = GetAcceptedAccounts(runSpace, group); + info.RejectAccounts = GetRejectedAccounts(runSpace, group); + info.RequireSenderAuthentication = (bool)GetPSObjectProperty(group, "RequireSenderAuthenticationEnabled"); + } + finally + { + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("GetDistributionListMailFlowSettingsInternal"); + return info; + } + + private void SetDistributionListMailFlowSettingsInternal(string accountName, + string[] acceptAccounts, string[] rejectAccounts, bool requireSenderAuthentication, string[] addressLists) + { + ExchangeLog.LogStart("SetDistributionListMailFlowSettingsInternal"); + ExchangeLog.DebugInfo("Account: {0}", accountName); + + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + + Command cmd = new Command("Set-DistributionGroup"); + cmd.Parameters.Add("Identity", accountName); + + MultiValuedProperty ids = null; + MultiValuedProperty dlIds = null; + + SetAccountIds(runSpace, acceptAccounts, out ids, out dlIds); + cmd.Parameters.Add("AcceptMessagesOnlyFrom", ids); + cmd.Parameters.Add("AcceptMessagesOnlyFromDLMembers", dlIds); + + SetAccountIds(runSpace, rejectAccounts, out ids, out dlIds); + cmd.Parameters.Add("RejectMessagesFrom", ids); + cmd.Parameters.Add("RejectMessagesFromDLMembers", dlIds); + cmd.Parameters.Add("RequireSenderAuthenticationEnabled", requireSenderAuthentication); + + ExecuteShellCommand(runSpace, cmd); + + if (addressLists.Length > 0) + { + cmd = new Command("Get-DistributionGroup"); + cmd.Parameters.Add("Identity", accountName); + Collection result = ExecuteShellCommand(runSpace, cmd); + PSObject distributionGroup = result[0]; + + FixShowInAddressBook(runSpace, accountName, addressLists, (bool)GetPSObjectProperty(distributionGroup, "HiddenFromAddressListsEnabled")); + } + + } + finally + { + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("SetDistributionListMailFlowSettingsInternal"); + } + + private ExchangeAccount[] GetGroupMembers(Runspace runSpace, string groupId) + { + ExchangeLog.LogStart("GetGroupMembers"); + List list = new List(); + Command cmd = new Command("Get-DistributionGroupMember"); + cmd.Parameters.Add("Identity", groupId); + Collection result = ExecuteShellCommand(runSpace, cmd); + + ExchangeAccount account = null; + string id = null; + + foreach (PSObject obj in result) + { + id = GetPSObjectIdentity(obj); + account = GetExchangeAccount(runSpace, id); + if (account != null) + list.Add(account); + } + ExchangeLog.LogEnd("GetGroupMembers"); + return list.ToArray(); + } + + private ExchangeEmailAddress[] GetDistributionListEmailAddressesInternal(string accountName) + { + ExchangeLog.LogStart("GetDistributionListEmailAddressesInternal"); + ExchangeLog.DebugInfo("Account: {0}", accountName); + + List list = new List(); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + + Command cmd = new Command("Get-DistributionGroup"); + cmd.Parameters.Add("Identity", accountName); + Collection result = ExecuteShellCommand(runSpace, cmd); + PSObject group = result[0]; + + string primaryEmail = null; + string windowsEmail = null; + + SmtpAddress smtpAddress = (SmtpAddress)GetPSObjectProperty(group, "PrimarySmtpAddress"); + if (smtpAddress != null) + primaryEmail = smtpAddress.ToString(); + + //SmtpAddress winAddress = (SmtpAddress)GetPSObjectProperty(group, "WindowsEmailAddress"); + //if (winAddress != null) + // windowsEmail = winAddress.ToString(); + windowsEmail = ObjToString(GetPSObjectProperty(group, "CustomAttribute3")); + + + ProxyAddressCollection emails = (ProxyAddressCollection)GetPSObjectProperty(group, "EmailAddresses"); + foreach (ProxyAddress email in emails) + { + //skip windows email + if (string.Equals(email.AddressString, windowsEmail, StringComparison.OrdinalIgnoreCase)) + continue; + + ExchangeEmailAddress item = new ExchangeEmailAddress(); + item.Email = email.AddressString; + item.Primary = string.Equals(item.Email, primaryEmail, StringComparison.OrdinalIgnoreCase); + list.Add(item); + } + } + finally + { + + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("GetDistributionListEmailAddressesInternal"); + return list.ToArray(); + } + + private void SetDistributionListEmailAddressesInternal(string accountName, string[] emailAddresses, string[] addressLists) + { + ExchangeLog.LogStart("SetDistributionListEmailAddressesInternal"); + ExchangeLog.DebugInfo("Account: {0}", accountName); + + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + + Command cmd = new Command("Get-DistributionGroup"); + cmd.Parameters.Add("Identity", accountName); + Collection result = ExecuteShellCommand(runSpace, cmd); + PSObject group = result[0]; + + //SmtpAddress winAddress = (SmtpAddress)GetPSObjectProperty(group, "WindowsEmailAddress"); + //string windowsEmail = ObjToString(winAddress); + string windowsEmail = ObjToString(GetPSObjectProperty(group, "CustomAttribute3")); + + ProxyAddressCollection emails = new ProxyAddressCollection(); + ProxyAddress proxy = null; + string primaryEmail = null; + + if (emailAddresses != null) + { + foreach (string email in emailAddresses) + { + proxy = ProxyAddress.Parse(email); + emails.Add(proxy); + if (proxy.IsPrimaryAddress) + { + primaryEmail = proxy.AddressString; + } + } + } + //add system windows email + if (!string.IsNullOrEmpty(windowsEmail)) + { + emails.Add(ProxyAddress.Parse(windowsEmail)); + } + + cmd = new Command("Set-DistributionGroup"); + cmd.Parameters.Add("Identity", accountName); + cmd.Parameters.Add("EmailAddresses", emails); + if (!string.IsNullOrEmpty(primaryEmail)) + { + cmd.Parameters.Add("WindowsEmailAddress", primaryEmail); + } + ExecuteShellCommand(runSpace, cmd); + + if (addressLists.Length > 0) + { + cmd = new Command("Get-DistributionGroup"); + cmd.Parameters.Add("Identity", accountName); + Collection r = ExecuteShellCommand(runSpace, cmd); + PSObject distributionGroup = r[0]; + + FixShowInAddressBook(runSpace, accountName, addressLists, (bool)GetPSObjectProperty(distributionGroup, "HiddenFromAddressListsEnabled")); + } + } + finally + { + + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("SetDistributionListEmailAddressesInternal"); + } + + private void SetDistributionListPrimaryEmailAddressInternal(string accountName, string emailAddress, string[] addressLists) + { + ExchangeLog.LogStart("SetDistributionListPrimaryEmailAddressInternal"); + ExchangeLog.DebugInfo("Account: {0}", accountName); + + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + + SmtpAddress primaryEmail = new SmtpAddress(emailAddress); + Command cmd = new Command("Set-DistributionGroup"); + cmd.Parameters.Add("Identity", accountName); + cmd.Parameters.Add("PrimarySmtpAddress", primaryEmail); + cmd.Parameters.Add("WindowsEmailAddress", primaryEmail); + + ExecuteShellCommand(runSpace, cmd); + + + } + finally + { + + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("SetDistributionListPrimaryEmailAddressInternal"); + } + + private ExchangeDistributionList GetDistributionListPermissionsInternal(string organizationId, string accountName, Runspace runspace) + { + ExchangeLog.LogStart("GetDistributionListPermissionsInternal"); + + if (string.IsNullOrEmpty(accountName)) + throw new ArgumentNullException("accountName"); + + ExchangeDistributionList exchangeDistributionList = null; + bool closeRunspace = false; + + try + { + if (runspace == null) + { + runspace = OpenRunspace(); + closeRunspace = true; + } + + Command cmd = new Command("Get-DistributionGroup"); + + cmd.Parameters.Add("Identity", accountName); + Collection result = ExecuteShellCommand(runspace, cmd); + PSObject distributionGroup = result[0]; + string cn = GetPSObjectProperty(distributionGroup, "Name") as string; + + + exchangeDistributionList = new ExchangeDistributionList(); + exchangeDistributionList.AccountName = accountName; + exchangeDistributionList.SendOnBehalfAccounts = GetSendOnBehalfAccounts(runspace, distributionGroup); + exchangeDistributionList.SendAsAccounts = GetSendAsAccounts(runspace, organizationId, cn); + } + catch (Exception ex) + { + ExchangeLog.LogError(ex); + throw ex; + } + finally + { + if (closeRunspace) + CloseRunspace(runspace); + } + + ExchangeLog.LogEnd("GetDistributionListPermissionsInternal"); + return exchangeDistributionList; + } + + private void SetDistributionListPermissionsInternal(string organizationId, string accountName, string[] sendAsAccounts, string[] sendOnBehalfAccounts, string[] addressLists) + { + ExchangeLog.LogStart("SetDistributionListPermissionsInternal"); + + if (string.IsNullOrEmpty(accountName)) + throw new ArgumentNullException("accountName"); + + if (sendAsAccounts == null) + throw new ArgumentNullException("sendAsAccounts"); + + + if (sendOnBehalfAccounts == null) + throw new ArgumentNullException("sendOnBehalfAccounts"); + + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + string cn = GetDistributionListCommonName(runSpace, accountName); + ExchangeDistributionList distributionList = GetDistributionListPermissionsInternal(organizationId, accountName, runSpace); + SetSendAsPermissions(runSpace, distributionList.SendAsAccounts, cn, sendAsAccounts); + SetDistributionListSendOnBehalfAccounts(runSpace, accountName, sendOnBehalfAccounts); + + if (addressLists.Length > 0) + { + Command cmd = new Command("Get-DistributionGroup"); + cmd.Parameters.Add("Identity", accountName); + Collection result = ExecuteShellCommand(runSpace, cmd); + PSObject distributionGroup = result[0]; + + FixShowInAddressBook(runSpace, accountName, addressLists, (bool)GetPSObjectProperty(distributionGroup, "HiddenFromAddressListsEnabled")); + } + + } + catch (Exception ex) + { + ExchangeLog.LogError(ex); + throw; + } + finally + { + CloseRunspace(runSpace); + } + + ExchangeLog.LogEnd("SetDistributionListPermissionsInternal"); + } + + internal virtual void SetDistributionListSendOnBehalfAccounts(Runspace runspace, string accountName, string[] sendOnBehalfAccounts) + { + ExchangeLog.LogStart("SetDistributionListSendOnBehalfAccounts"); + Command cmd = new Command("Set-DistributionGroup"); + cmd.Parameters.Add("Identity", accountName); + cmd.Parameters.Add("GrantSendOnBehalfTo", SetSendOnBehalfAccounts(runspace, sendOnBehalfAccounts)); + cmd.Parameters.Add("BypassSecurityGroupManagerCheck"); + ExecuteShellCommand(runspace, cmd); + ExchangeLog.LogEnd("SetDistributionListSendOnBehalfAccounts"); + } + + private string GetDistributionListCommonName(Runspace runSpace, string accountName) + { + ExchangeLog.LogStart("GetDistributionListCommonName"); + Command cmd = new Command("Get-DistributionGroup"); + cmd.Parameters.Add("Identity", accountName); + Collection result = ExecuteShellCommand(runSpace, cmd); + PSObject obj = result[0]; + string cn = GetPSObjectProperty(obj, "Name") as string; + ExchangeLog.LogEnd("GeDistributionListCommonName"); + return cn; + } + + #endregion + + #region Public folders + + private void CreatePublicFolderInternal(string organizationId, string securityGroup, string parentFolder, + string folderName, bool mailEnabled, string accountName, string name, string domain) + { + ExchangeLog.LogStart("CreatePublicFolderInternal"); + ExchangeLog.DebugInfo("Organization Id: {0}", organizationId); + ExchangeLog.DebugInfo("Parent: {0}", parentFolder); + ExchangeLog.DebugInfo("Name: {0}", folderName); + + ExchangeTransaction transaction = StartTransaction(); + + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + + //create organization root folder if required + CheckOrganizationRootFolder(runSpace, organizationId, securityGroup); + + string id = AddPublicFolder(runSpace, folderName, parentFolder); + transaction.RegisterNewPublicFolder(id); + + SetPublicFolderPermissions(runSpace, id, securityGroup); + + if (mailEnabled) + { + EnableMailPublicFolderInternal(organizationId, id, accountName, name, domain); + } + + } + catch (Exception ex) + { + ExchangeLog.LogError("CreatePublicFolderInternal", ex); + RollbackTransaction(transaction); + throw; + } + finally + { + + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("CreatePublicFolderInternal"); + } + + private void CheckOrganizationRootFolder(Runspace runSpace, string folder, string user) + { + ExchangeLog.LogStart("CheckOrganizationRootFolder"); + + Collection result = GetPublicFolderObject(runSpace, "\\" + folder); + if (result == null || result.Count == 0) + { + ExchangeTransaction transaction = StartTransaction(); + try + { + string rootId = AddPublicFolder(runSpace, folder, "\\"); + transaction.RegisterNewPublicFolder(rootId); + SetPublicFolderPermissions(runSpace, rootId, user); + } + catch + { + RollbackTransaction(transaction); + throw; + } + } + ExchangeLog.LogEnd("CheckOrganizationRootFolder"); + } + + private string AddPublicFolder(Runspace runSpace, string name, string path) + { + ExchangeLog.LogStart("CreatePublicFolder"); + Command cmd = new Command("New-PublicFolder"); + cmd.Parameters.Add("Name", name); + cmd.Parameters.Add("Path", path); + if (!string.IsNullOrEmpty(PublicFolderServer)) + cmd.Parameters.Add("Server", PublicFolderServer); + Collection result = ExecuteShellCommand(runSpace, cmd); + string id = GetResultObjectIdentity(result); + ExchangeLog.LogEnd("CreatePublicFolder"); + return id; + } + + private void DeletePublicFolderInternal(string folder) + { + ExchangeLog.LogStart("DeletePublicFolderInternal"); + ExchangeLog.DebugInfo("Folder: {0}", folder); + + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + RemovePublicFolder(runSpace, folder); + } + finally + { + + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("DeletePublicFolderInternal"); + } + + private Collection GetPublicFolderObject(Runspace runSpace, string id) + { + Command cmd = new Command("Get-PublicFolder"); + cmd.Parameters.Add("Identity", id); + if (!string.IsNullOrEmpty(PublicFolderServer)) + cmd.Parameters.Add("Server", PublicFolderServer); + Collection result = ExecuteShellCommand(runSpace, cmd); + return result; + } + + private bool PublicFolderExists(Runspace runSpace, string id) + { + ExchangeLog.LogStart("PublicFolderExists"); + + Collection result = GetPublicFolderObject(runSpace, id); + bool ret = (result != null && result.Count == 1); + ExchangeLog.LogEnd("PublicFolderExists"); + return ret; + } + + private void RemovePublicFolder(Runspace runSpace, string id) + { + ExchangeLog.LogStart("RemovePublicFolder"); + + Command cmd = new Command("Remove-PublicFolder"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("Recurse", new SwitchParameter(true)); + cmd.Parameters.Add("Confirm", false); + if (!string.IsNullOrEmpty(PublicFolderServer)) + cmd.Parameters.Add("Server", PublicFolderServer); + ExecuteShellCommand(runSpace, cmd); + + ExchangeLog.LogEnd("RemovePublicFolder"); + } + + private void SetPublicFolderPermissions(Runspace runSpace, string folder, string securityGroup) + { + //set the default Permission to 'Reviewer' + RemovePublicFolderClientPermission(runSpace, folder, "Default", "Author"); + AddPublicFolderClientPermission(runSpace, folder, securityGroup, "Reviewer"); + } + + private void RemovePublicFolderClientPermission(Runspace runSpace, string id, string user, + string permission) + { + ExchangeLog.LogStart("RemovePublicFolderClientPermission"); + + Command cmd = new Command("Remove-PublicFolderClientPermission"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("User", user); + cmd.Parameters.Add("AccessRights", permission); + cmd.Parameters.Add("Confirm", false); + if (!string.IsNullOrEmpty(PublicFolderServer)) + cmd.Parameters.Add("Server", PublicFolderServer); + ExecuteShellCommand(runSpace, cmd); + ExchangeLog.LogEnd("RemovePublicFolderClientPermission"); + } + + private void AddPublicFolderClientPermission(Runspace runSpace, string id, string user, string permission) + { + ExchangeLog.LogStart("AddPublicFolderClientPermission"); + + Command cmd = new Command("Add-PublicFolderClientPermission"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("User", user); + cmd.Parameters.Add("AccessRights", permission); + if (!string.IsNullOrEmpty(PublicFolderServer)) + cmd.Parameters.Add("Server", PublicFolderServer); + ExecuteShellCommand(runSpace, cmd); + ExchangeLog.LogEnd("AddPublicFolderClientPermission"); + } + + private void GetPublicFolderClientPermission(Runspace runSpace, string id) + { + Command cmd = new Command("Get-PublicFolderClientPermission"); + cmd.Parameters.Add("Identity", id); + if (!string.IsNullOrEmpty(PublicFolderServer)) + cmd.Parameters.Add("Server", PublicFolderServer); + Collection result = ExecuteShellCommand(runSpace, cmd); + PSObject obj = result[0]; + } + + + private void EnableMailPublicFolderInternal(string organizationId, string folder, string accountName, + string name, string domain) + { + ExchangeLog.LogStart("EnableMailPublicFolderInternal"); + ExchangeLog.DebugInfo("Folder: {0}", folder); + + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + + Command cmd = new Command("Enable-MailPublicFolder"); + cmd.Parameters.Add("Identity", folder); + if (!string.IsNullOrEmpty(PublicFolderServer)) + cmd.Parameters.Add("Server", PublicFolderServer); + ExecuteShellCommand(runSpace, cmd); + string id = null; + + //try to avoid message: "The Active Directory proxy object for the public folder 'XXX' + // is being generated. Please try again later." + int attempts = 0; + string windowsEmailAddress = null; + while (true) + { + cmd = new Command("Get-MailPublicFolder"); + cmd.Parameters.Add("Identity", folder); + if (!string.IsNullOrEmpty(PublicFolderServer)) + cmd.Parameters.Add("Server", PublicFolderServer); + Collection result = ExecuteShellCommand(runSpace, cmd); + if (result != null && result.Count > 0) + { + id = GetResultObjectIdentity(result); + windowsEmailAddress = ObjToString(GetPSObjectProperty(result[0], "WindowsEmailAddress")); + break; + } + + if (attempts > 9) + { + string error = string.Format("Active Directory proxy object for the public folder '{0}' was not found or not generated yet.", folder); + throw new Exception(error); + } + + attempts++; + ExchangeLog.LogWarning("Attemp {0} to create mail public folder {1}", attempts, folder); + System.Threading.Thread.Sleep(5000); + } + + string email = string.Format("{0}@{1}", name, domain); + // fix issue with 2 DC + attempts = 0; + bool success = false; + object[] errors; + while (true) + { + try + { + cmd = new Command("Set-MailPublicFolder"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("Alias", accountName); + cmd.Parameters.Add("EmailAddressPolicyEnabled", false); + cmd.Parameters.Add("CustomAttribute1", organizationId); + cmd.Parameters.Add("CustomAttribute3", windowsEmailAddress); + cmd.Parameters.Add("PrimarySmtpAddress", email); + ExecuteShellCommand(runSpace, cmd, out errors); + + if (errors.Length == 0) + success = true; + } + catch (Exception ex) + { + ExchangeLog.LogError(ex); + } + + if (success) + break; + + if (attempts > 9) + { + string error = string.Format("Mail public folder '{0}' was not found or not generated yet.", id); + throw new Exception(error); + } + + attempts++; + ExchangeLog.LogWarning("Attemp {0} to update mail public folder {1}", attempts, folder); + System.Threading.Thread.Sleep(5000); + } + } + finally + { + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("EnableMailPublicFolderInternal"); + } + + private void DisableMailPublicFolderInternal(string folder) + { + ExchangeLog.LogStart("DisableMailPublicFolderInternal"); + ExchangeLog.DebugInfo("Folder: {0}", folder); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + + Command cmd = new Command("Disable-MailPublicFolder"); + cmd.Parameters.Add("Identity", folder); + cmd.Parameters.Add("Confirm", false); + if (!string.IsNullOrEmpty(PublicFolderServer)) + cmd.Parameters.Add("Server", PublicFolderServer); + ExecuteShellCommand(runSpace, cmd); + } + finally + { + + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("DisableMailPublicFolderInternal"); + } + + private ExchangePublicFolder GetPublicFolderGeneralSettingsInternal(string folder) + { + ExchangeLog.LogStart("GetPublicFolderGeneralSettingsInternal"); + ExchangeLog.DebugInfo("Folder: {0}", folder); + + ExchangePublicFolder info = new ExchangePublicFolder(); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + Collection result = GetPublicFolderObject(runSpace, folder); + PSObject publicFolder = result[0]; + + info.Name = (string)GetPSObjectProperty(publicFolder, "Name"); + info.MailEnabled = (bool)GetPSObjectProperty(publicFolder, "MailEnabled"); + info.HideFromAddressBook = (bool)GetPSObjectProperty(publicFolder, "HiddenFromAddressListsEnabled"); + info.NETBIOS = GetNETBIOSDomainName(); + info.Accounts = GetPublicFolderAccounts(runSpace, folder); + + if (info.MailEnabled) + { + Command cmd = new Command("Get-MailPublicFolder"); + cmd.Parameters.Add("Identity", folder); + if (!string.IsNullOrEmpty(PublicFolderServer)) + cmd.Parameters.Add("Server", PublicFolderServer); + result = ExecuteShellCommand(runSpace, cmd); + if (result.Count > 0) + { + publicFolder = result[0]; + info.SAMAccountName = string.Format("{0}\\{1}", GetNETBIOSDomainName(), (string)GetPSObjectProperty(publicFolder, "Alias")); + } + } + } + finally + { + + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("GetPublicFolderGeneralSettingsInternal"); + return info; + } + + private ExchangeAccount[] GetPublicFolderAccounts(Runspace runSpace, string folder) + { + ExchangeLog.LogStart("GetPublicFolderAccounts"); + ExchangeLog.DebugInfo("Folder: {0}", folder); + + List list = new List(); + ExchangeAccount account = null; + + Command cmd = new Command("Get-PublicFolderClientPermission"); + cmd.Parameters.Add("Identity", folder); + if (!string.IsNullOrEmpty(PublicFolderServer)) + cmd.Parameters.Add("Server", PublicFolderServer); + Collection result = ExecuteShellCommand(runSpace, cmd); + + foreach (PSObject obj in result) + { + string userId = ObjToString(GetPSObjectProperty(obj, "User")); + if (userId == "Default" || userId == "Anonymous" || userId.StartsWith("NT User:") == true) + continue; + + object rights = GetPSObjectProperty(obj, "AccessRights"); + int count = (int)GetObjectPropertyValue(rights, "Count"); + for (int i = 0; i < count; i++) + { + account = GetExchangeAccount(runSpace, userId); + string permission = ObjToString(GetObjectIndexerValue(rights, i)); + if (account != null) + account.PublicFolderPermission = permission; + list.Add(account); + break; + } + } + ExchangeLog.LogEnd("GetPublicFolderAccounts"); + return list.ToArray(); + } + + private void SetPublicFolderGeneralSettingsInternal(string folder, string newFolderName, + bool hideFromAddressBook, ExchangeAccount[] accounts) + { + ExchangeLog.LogStart("SetPublicFolderGeneralSettingsInternal"); + ExchangeLog.DebugInfo("Folder: {0}", folder); + + ExchangePublicFolder info = new ExchangePublicFolder(); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + Collection result = GetPublicFolderObject(runSpace, folder); + PSObject publicFolder = result[0]; + string folderName = (string)GetPSObjectProperty(publicFolder, "Name"); + ExchangeAccount[] allAccounts = GetPublicFolderAccounts(runSpace, folder); + + //Remove all accounts and re-apply + List accountsToDelete = new List(); + List accountsToAdd = new List(); + + foreach (ExchangeAccount existingAccount in allAccounts) + { + try + { + RemovePublicFolderClientPermission(runSpace, + folder, + existingAccount.AccountName.Contains("@") ? existingAccount.AccountName : @"\" + existingAccount.AccountName, + existingAccount.PublicFolderPermission); + } + catch (Exception) + { + throw; + } + + } + + foreach (ExchangeAccount newAccount in accounts) + { + try + { + AddPublicFolderClientPermission(runSpace, + folder, + newAccount.AccountName.Contains("@") ? newAccount.AccountName : @"\" + newAccount.AccountName, + newAccount.PublicFolderPermission); + } + catch (Exception) + { + throw; + } + + } + + //general settings + Command cmd = new Command("Set-PublicFolder"); + cmd.Parameters.Add("Identity", folder); + if (!string.IsNullOrEmpty(PublicFolderServer)) + cmd.Parameters.Add("Server", PublicFolderServer); + if (!folderName.Equals(newFolderName, StringComparison.OrdinalIgnoreCase)) + { + cmd.Parameters.Add("Name", newFolderName); + } + cmd.Parameters.Add("HiddenFromAddressListsEnabled", hideFromAddressBook); + ExecuteShellCommand(runSpace, cmd); + } + finally + { + + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("SetPublicFolderGeneralSettingsInternal"); + } + + private ExchangePublicFolder GetPublicFolderMailFlowSettingsInternal(string folder) + { + ExchangeLog.LogStart("GetPublicFolderMailFlowSettingsInternal"); + ExchangeLog.DebugInfo("Folder: {0}", folder); + + ExchangePublicFolder info = new ExchangePublicFolder(); + + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + + Command cmd = new Command("Get-MailPublicFolder"); + cmd.Parameters.Add("Identity", folder); + if (!string.IsNullOrEmpty(PublicFolderServer)) + cmd.Parameters.Add("Server", PublicFolderServer); + Collection result = ExecuteShellCommand(runSpace, cmd); + PSObject publicFolder = result[0]; + + info.AcceptAccounts = GetAcceptedAccounts(runSpace, publicFolder); + info.RejectAccounts = GetRejectedAccounts(runSpace, publicFolder); + info.RequireSenderAuthentication = (bool)GetPSObjectProperty(publicFolder, "RequireSenderAuthenticationEnabled"); + } + finally + { + + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("GetPublicFolderMailFlowSettingsInternal"); + return info; + } + + private void SetPublicFolderMailFlowSettingsInternal(string folder, + string[] acceptAccounts, string[] rejectAccounts, bool requireSenderAuthentication) + { + ExchangeLog.LogStart("SetPublicFolderMailFlowSettingsInternal"); + ExchangeLog.DebugInfo("Folder: {0}", folder); + + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + + Command cmd = new Command("Set-MailPublicFolder"); + cmd.Parameters.Add("Identity", folder); + + MultiValuedProperty ids = null; + MultiValuedProperty dlIds = null; + + SetAccountIds(runSpace, acceptAccounts, out ids, out dlIds); + cmd.Parameters.Add("AcceptMessagesOnlyFrom", ids); + cmd.Parameters.Add("AcceptMessagesOnlyFromDLMembers", dlIds); + + SetAccountIds(runSpace, rejectAccounts, out ids, out dlIds); + cmd.Parameters.Add("RejectMessagesFrom", ids); + cmd.Parameters.Add("RejectMessagesFromDLMembers", dlIds); + cmd.Parameters.Add("RequireSenderAuthenticationEnabled", requireSenderAuthentication); + + ExecuteShellCommand(runSpace, cmd); + } + finally + { + + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("SetPublicFolderMailFlowSettingsInternal"); + + } + + + private ExchangeEmailAddress[] GetPublicFolderEmailAddressesInternal(string folder) + { + ExchangeLog.LogStart("GetPublicFolderEmailAddressesInternal"); + ExchangeLog.DebugInfo("Folder: {0}", folder); + + List list = new List(); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + + Command cmd = new Command("Get-MailPublicFolder"); + cmd.Parameters.Add("Identity", folder); + if (!string.IsNullOrEmpty(PublicFolderServer)) + cmd.Parameters.Add("Server", PublicFolderServer); + Collection result = ExecuteShellCommand(runSpace, cmd); + PSObject publicFolder = result[0]; + + string primaryEmail = null; + string windowsEmail = null; + + SmtpAddress smtpAddress = (SmtpAddress)GetPSObjectProperty(publicFolder, "PrimarySmtpAddress"); + if (smtpAddress != null) + primaryEmail = smtpAddress.ToString(); + + //SmtpAddress winAddress = (SmtpAddress)GetPSObjectProperty(publicFolder, "WindowsEmailAddress"); + //if (winAddress != null) + // windowsEmail = winAddress.ToString(); + windowsEmail = ObjToString(GetPSObjectProperty(publicFolder, "CustomAttribute3")); + + + ProxyAddressCollection emails = (ProxyAddressCollection)GetPSObjectProperty(publicFolder, "EmailAddresses"); + foreach (ProxyAddress email in emails) + { + //skip windows email + if (string.Equals(email.AddressString, windowsEmail, StringComparison.OrdinalIgnoreCase)) + continue; + + ExchangeEmailAddress item = new ExchangeEmailAddress(); + item.Email = email.AddressString; + item.Primary = string.Equals(item.Email, primaryEmail, StringComparison.OrdinalIgnoreCase); + list.Add(item); + } + } + finally + { + + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("GetPublicFolderEmailAddressesInternal"); + return list.ToArray(); + } + + private void SetPublicFolderEmailAddressesInternal(string folder, string[] emailAddresses) + { + ExchangeLog.LogStart("SetDistributionListEmailAddressesInternal"); + ExchangeLog.DebugInfo("Folder: {0}", folder); + + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + + Command cmd = new Command("Get-MailPublicFolder"); + cmd.Parameters.Add("Identity", folder); + if (!string.IsNullOrEmpty(PublicFolderServer)) + cmd.Parameters.Add("Server", PublicFolderServer); + Collection result = ExecuteShellCommand(runSpace, cmd); + PSObject publicFolder = result[0]; + + //SmtpAddress winAddress = (SmtpAddress)GetPSObjectProperty(publicFolder, "WindowsEmailAddress"); + string windowsEmail = ObjToString(GetPSObjectProperty(publicFolder, "CustomAttribute3")); + //string windowsEmail = ObjToString(winAddress); + + ProxyAddressCollection emails = new ProxyAddressCollection(); + ProxyAddress proxy = null; + if (emailAddresses != null) + { + foreach (string email in emailAddresses) + { + proxy = ProxyAddress.Parse(email); + emails.Add(proxy); + } + } + //add system windows email + if (!string.IsNullOrEmpty(windowsEmail)) + { + emails.Add(ProxyAddress.Parse(windowsEmail)); + } + + cmd = new Command("Set-MailPublicFolder"); + cmd.Parameters.Add("Identity", folder); + cmd.Parameters.Add("EmailAddresses", emails); + ExecuteShellCommand(runSpace, cmd); + } + finally + { + + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("SetPublicFolderEmailAddressesInternal"); + } + + private void SetPublicFolderPrimaryEmailAddressInternal(string folder, string emailAddress) + { + ExchangeLog.LogStart("SetPublicFolderPrimaryEmailAddressInternal"); + ExchangeLog.DebugInfo("Folder: {0}", folder); + ExchangeLog.DebugInfo("Email: {0}", emailAddress); + + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + + SmtpAddress primaryEmail = new SmtpAddress(emailAddress); + Command cmd = new Command("Set-MailPublicFolder"); + cmd.Parameters.Add("Identity", folder); + cmd.Parameters.Add("PrimarySmtpAddress", primaryEmail); + + ExecuteShellCommand(runSpace, cmd); + } + finally + { + + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("SetPublicFolderPrimaryEmailAddressInternal"); + } + + private ExchangeItemStatistics[] GetPublicFoldersStatisticsInternal(string[] folders) + { + ExchangeLog.LogStart("GetPublicFoldersStatisticsInternal"); + + Runspace runSpace = null; + List ret = new List(); + try + { + runSpace = OpenRunspace(); + + PSObject obj = null; + foreach (string folder in folders) + { + Command cmd = new Command("Get-PublicFolderStatistics"); + cmd.Parameters.Add("Identity", folder); + if (!string.IsNullOrEmpty(PublicFolderServer)) + cmd.Parameters.Add("Server", PublicFolderServer); + Collection result = ExecuteShellCommand(runSpace, cmd); + if (result != null && result.Count > 0) + { + obj = result[0]; + ExchangeItemStatistics info = new ExchangeItemStatistics(); + info.ItemName = (string)GetPSObjectProperty(obj, "FolderPath"); + Unlimited totalItemSize = + (Unlimited)GetPSObjectProperty(obj, "TotalItemSize"); + info.TotalSizeMB = ConvertUnlimitedToMB(totalItemSize); + uint? itemCount = (uint?)GetPSObjectProperty(obj, "ItemCount"); + info.TotalItems = ConvertNullableToInt32(itemCount); + + DateTime? lastAccessTime = (DateTime?)GetPSObjectProperty(obj, "LastAccessTime"); ; + DateTime? lastModificationTime = (DateTime?)GetPSObjectProperty(obj, "LastModificationTime"); ; + info.LastAccessTime = ConvertNullableToDateTime(lastAccessTime); + info.LastModificationTime = ConvertNullableToDateTime(lastModificationTime); + ret.Add(info); + } + } + } + finally + { + + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("GetPublicFoldersStatisticsInternal"); + return ret.ToArray(); + } + + private string[] GetPublicFoldersRecursiveInternal(string parent) + { + ExchangeLog.LogStart("GetPublicFoldersRecursiveInternal"); + + Runspace runSpace = null; + List ret = new List(); + try + { + runSpace = OpenRunspace(); + Command cmd = new Command("Get-PublicFolder"); + cmd.Parameters.Add("Identity", parent); + cmd.Parameters.Add("Recurse", true); + if (!string.IsNullOrEmpty(PublicFolderServer)) + cmd.Parameters.Add("Server", PublicFolderServer); + + Collection result = ExecuteShellCommand(runSpace, cmd); + if (result != null) + { + foreach (PSObject obj in result) + { + ret.Add(GetPSObjectIdentity(obj)); + } + } + } + finally + { + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("GetPublicFoldersRecursiveInternal"); + return ret.ToArray(); + } + + private long GetPublicFolderSizeInternal(string folder) + { + ExchangeLog.LogStart("GetPublicFolderSizeInternal"); + long size = 0; + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + size += CalculatePublicFolderDiskSpace(runSpace, folder); + } + finally + { + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("GetPublicFolderSizeInternal"); + return size; + } + + #endregion + + #region Address Lists (GAL, AL, RAL, OAB, ABP) + + private string GetAddressListDN(Runspace runSpace, string id) + { + ExchangeLog.LogStart("GetAddressListDN"); + string resultObjectDN = null; + Command cmd = new Command("Get-AddressList"); + cmd.Parameters.Add("Identity", id); + Collection result = this.ExecuteShellCommand(runSpace, cmd); + if ((result != null) && (result.Count > 0)) + { + resultObjectDN = this.GetResultObjectDN(result); + ExchangeLog.DebugInfo("AL DN: {0}", new object[] { resultObjectDN }); + } + ExchangeLog.LogEnd("GetAddressListDN"); + return resultObjectDN; + } + + internal string CreateAddressList(Runspace runSpace, string organizationId) + { + ExchangeLog.LogStart("CreateAddressList"); + string addressListName = this.GetAddressListName(organizationId); + string addressListDN = this.GetAddressListDN(runSpace, addressListName); + if (!string.IsNullOrEmpty(addressListDN)) + { + //address list already exists - we will use it + ExchangeLog.LogWarning("Address List '{0}' already exists", new object[] { addressListName }); + } + else + { + //try to create a new address list (10 attempts) + int attempts = 0; + Command cmd = null; + Collection result = null; + + while (true) + { + try + { + //try to create address list + cmd = new Command("New-AddressList"); + cmd.Parameters.Add("Name", addressListName); + cmd.Parameters.Add("IncludedRecipients", "AllRecipients"); + cmd.Parameters.Add("ConditionalCustomAttribute1", organizationId); + + result = ExecuteShellCommand(runSpace, cmd); + addressListDN = CheckResultObjectDN(result); + } + catch (Exception ex) + { + ExchangeLog.LogError(ex); + } + if (addressListDN != null) + break; + + if (attempts > 9) + throw new Exception( + string.Format("Could not create Address List '{0}' ", addressListName)); + + attempts++; + ExchangeLog.LogWarning("Attempt #{0} to create address list failed!", attempts); + // wait 1 sec + System.Threading.Thread.Sleep(1000); + } + } + + ExchangeLog.LogEnd("CreateAddressList"); + return addressListDN; + } + + internal string CreateRoomsAddressList(Runspace runSpace, string organizationId) + { + ExchangeLog.LogStart("CreateRoomList"); + string addressListName = this.GetRoomsAddressListName(organizationId); + string addressListDN = this.GetAddressListDN(runSpace, addressListName); + if (!string.IsNullOrEmpty(addressListDN)) + { + //address list already exists - we will use it + ExchangeLog.LogWarning("Room List '{0}' already exists", new object[] { addressListName }); + } + else + { + //try to create a new address list (10 attempts) + int attempts = 0; + Command cmd = null; + Collection result = null; + + while (true) + { + try + { + //try to create address list + cmd = new Command("New-AddressList"); + cmd.Parameters.Add("Name", addressListName); + cmd.Parameters.Add("IncludedRecipients", "Resources"); + cmd.Parameters.Add("ConditionalCustomAttribute1", organizationId); + + result = ExecuteShellCommand(runSpace, cmd); + addressListDN = CheckResultObjectDN(result); + } + catch (Exception ex) + { + ExchangeLog.LogError(ex); + } + if (addressListDN != null) + break; + + if (attempts > 9) + throw new Exception( + string.Format("Could not create Room List '{0}' ", addressListName)); + + attempts++; + ExchangeLog.LogWarning("Attempt #{0} to create room list failed!", attempts); + // wait 1 sec + System.Threading.Thread.Sleep(1000); + } + } + + ExchangeLog.LogEnd("CreateRoomList"); + return addressListDN; + } + + + internal void UpdateAddressList(Runspace runSpace, string id, string securityGroup) + { + ExchangeLog.LogStart("UpdateAddressList"); + + string path = AddADPrefix(id); + Command cmd = new Command("Update-AddressList"); + cmd.Parameters.Add("Identity", id); + ExecuteShellCommand(runSpace, cmd); + + AdjustADSecurity(path, securityGroup, false); + + ExchangeLog.LogEnd("UpdateAddressList"); + } + + internal void DeleteAddressList(Runspace runSpace, string id) + { + ExchangeLog.LogStart("DeleteAddressList"); + Command cmd = new Command("Remove-AddressList"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("Confirm", false); + ExecuteShellCommand(runSpace, cmd); + ExchangeLog.LogEnd("DeleteAddressList"); + } + + + internal virtual void DeleteAddressBookPolicy(Runspace runSpace, string id) + { + ExchangeLog.LogStart("DeleteAddressBookPolicy"); + //if (id != "IsConsumer") + //{ + Command cmd = new Command("Remove-AddressBookPolicy"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("Confirm", false); + ExecuteShellCommand(runSpace, cmd); + //} + ExchangeLog.LogEnd("DeleteAddressBookPolicy"); + } + + + + internal string GetGlobalAddressListDN(Runspace runSpace, string id) + { + ExchangeLog.LogStart("GetGlobalAddressListDN"); + string resultObjectDN = null; + Command cmd = new Command("Get-GlobalAddressList"); + cmd.Parameters.Add("Identity", id); + Collection result = this.ExecuteShellCommand(runSpace, cmd); + if ((result != null) && (result.Count > 0)) + { + resultObjectDN = this.GetResultObjectDN(result); + ExchangeLog.DebugInfo("GAL DN: {0}", new object[] { resultObjectDN }); + } + ExchangeLog.LogEnd("GetGlobalAddressListDN"); + return resultObjectDN; + } + + + internal string CreateGlobalAddressList(Runspace runSpace, string organizationId) + { + ExchangeLog.LogStart("CreateGlobalAddressList"); + + string name = GetGlobalAddressListName(organizationId); + + Command cmd = new Command("New-GlobalAddressList"); + cmd.Parameters.Add("Name", name); + cmd.Parameters.Add("RecipientFilter", string.Format("(Alias -ne $null -and CustomAttribute1 -eq '{0}')", organizationId)); + + Collection result = ExecuteShellCommand(runSpace, cmd); + string id = GetResultObjectDN(result); + + ExchangeLog.LogEnd("CreateGlobalAddressList"); + return id; + } + + internal void UpdateGlobalAddressList(Runspace runSpace, string id, string securityGroup) + { + ExchangeLog.LogStart("UpdateGlobalAddressList"); + + + Command cmd = new Command("Update-GlobalAddressList"); + cmd.Parameters.Add("Identity", id); + ExecuteShellCommand(runSpace, cmd); + + string path = AddADPrefix(id); + AdjustADSecurity(path, securityGroup, false); + + ExchangeLog.LogEnd("UpdateGlobalAddressList"); + } + + internal void DeleteGlobalAddressList(Runspace runSpace, string id) + { + ExchangeLog.LogStart("DeleteGlobalAddressList"); + Command cmd = new Command("Remove-GlobalAddressList"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("Confirm", false); + ExecuteShellCommand(runSpace, cmd); + ExchangeLog.LogEnd("DeleteGlobalAddressList"); + } + + private string CreateOfflineAddressBook(Runspace runSpace, string organizationId, string server, string oabVirtualDirs) + { + ExchangeLog.LogStart("CreateOfflineAddressBook"); + + string oabName = GetOfflineAddressBookName(organizationId); + string addressListName = GetAddressListName(organizationId); + + Command cmd = new Command("New-OfflineAddressBook"); + cmd.Parameters.Add("Name", oabName); + cmd.Parameters.Add("AddressLists", addressListName); + cmd.Parameters.Add("PublicFolderDistributionEnabled", PublicFolderDistributionEnabled); + cmd.Parameters.Add("IsDefault", false); + cmd.Parameters.Add("GlobalWebDistributionEnabled", false); + + + //TODO: fix web distribution + if (!string.IsNullOrEmpty(oabVirtualDirs)) + { + ArrayList virtualDirs = new ArrayList(); + string[] strTmp = oabVirtualDirs.Split(','); + foreach (string s in strTmp) + { + virtualDirs.Add(s); + } + + cmd.Parameters.Add("VirtualDirectories", (String[])virtualDirs.ToArray(typeof(string))); + } + + Collection result = ExecuteShellCommand(runSpace, cmd); + string id = GetResultObjectDN(result); + + ExchangeLog.LogEnd("CreateOfflineAddressBook"); + + return id; + } + + private void UpdateOfflineAddressBook(Runspace runSpace, string id, string securityGroup) + { + ExchangeLog.LogStart("UpdateOfflineAddressBook"); + + string path = AddADPrefix(id); + + Command cmd = new Command("Update-OfflineAddressBook"); + cmd.Parameters.Add("Identity", id); + ExecuteShellCommand(runSpace, cmd); + + AdjustADSecurity(path, securityGroup, true); + + ExchangeLog.LogEnd("UpdateOfflineAddressBook"); + } + + + internal void DeleteOfflineAddressBook(Runspace runSpace, string id) + { + ExchangeLog.LogStart("DeleteOfflineAddressBook"); + Command cmd = new Command("Remove-OfflineAddressBook"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("Confirm", false); + ExecuteShellCommand(runSpace, cmd); + ExchangeLog.LogEnd("DeleteOfflineAddressBook"); + } + + private void DeleteAddressPolicy(Runspace runSpace, string id) + { + ExchangeLog.LogStart("DeleteAddressPolicy"); + Command cmd = new Command("Remove-AddressBookPolicy"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("Confirm", false); + ExecuteShellCommand(runSpace, cmd); + ExchangeLog.LogEnd("DeleteAddressPolicy"); + } + + private string GetAddressListName(string orgName) + { + return orgName + " Address List"; + } + + internal string GetGlobalAddressListName(string orgName) + { + return orgName + " Global Address List"; + } + + private string GetOfflineAddressBookName(string orgName) + { + return orgName + " Offline Address Book"; + } + + internal string GetAddressBookPolicyName(string orgName) + { + return orgName + " Address Policy"; + } + + private string GetRoomsAddressListName(string orgName) + { + return orgName + " Rooms"; + } + + #endregion + + #region Active Directory + private string CreateOrganizationalUnit(string name) + { + ExchangeLog.LogStart("CreateOrganizationalUnit"); + + string ret = null; + DirectoryEntry ou = null; + DirectoryEntry rootOU = null; + try + { + rootOU = GetRootOU(); + ou = rootOU.Children.Add( + string.Format("OU={0}", name), + rootOU.SchemaClassName); + + ret = ou.Path; + ou.CommitChanges(); + } + finally + { + if (ou != null) + ou.Close(); + if (rootOU != null) + rootOU.Close(); + } + + ExchangeLog.LogEnd("CreateOrganizationalUnit"); + return ret; + } + + private void DeleteADObject(string id) + { + ExchangeLog.LogStart("DeleteADObject"); + + string path = AddADPrefix(id); + + DirectoryEntry ou = GetADObject(path); + DirectoryEntry parent = ou.Parent; + if (parent != null) + { + parent.Children.Remove(ou); + parent.CommitChanges(); + } + + ExchangeLog.LogEnd("DeleteADObject"); + } + + private DirectoryEntry GetRootOU() + { + ExchangeLog.LogStart("GetRootOU"); + StringBuilder sb = new StringBuilder(); + // append provider + AppendProtocol(sb); + AppendDomainController(sb); + AppendOUPath(sb, RootOU); + AppendDomainPath(sb, RootDomain); + + DirectoryEntry de = GetADObject(sb.ToString()); + ExchangeLog.LogEnd("GetRootOU"); + return de; + } + + private void SetADObjectProperty(DirectoryEntry oDE, string name, string value) + { + if (!string.IsNullOrEmpty(value)) + { + if (oDE.Properties.Contains(name)) + { + oDE.Properties[name][0] = value; + } + else + { + oDE.Properties[name].Add(value); + } + } + } + + internal void SetADObjectPropertyValue(DirectoryEntry oDE, string name, string value) + { + PropertyValueCollection collection = oDE.Properties[name]; + collection.Value = value; + } + + + internal void AddADObjectProperty(DirectoryEntry oDE, string name, string value) + { + if (!string.IsNullOrEmpty(value)) + { + oDE.Properties[name].Add(value); + + } + } + + internal DirectoryEntry GetADObject(string path) + { + DirectoryEntry de = null; + if (path.StartsWith("LDAP://" + PrimaryDomainController + "/", true, CultureInfo.InvariantCulture)) + { + ExchangeLog.LogInfo("Get Active Directory Object {0} from {1}", path, PrimaryDomainController); + de = new DirectoryEntry(path, null, null, AuthenticationTypes.ServerBind); + } + else + { + ExchangeLog.LogInfo("Get Active Directory Object {0}", path); + de = new DirectoryEntry(path); + } + if (de != null) + de.RefreshCache(); + return de; + } + + internal object GetADObjectProperty(DirectoryEntry entry, string name) + { + if (entry.Properties.Contains(name)) + return entry.Properties[name][0]; + else + return String.Empty; + } + + + private string GetOrganizationPath(string organizationId) + { + StringBuilder sb = new StringBuilder(); + // append provider + AppendOUPath(sb, organizationId); + AppendOUPath(sb, RootOU); + AppendDomainPath(sb, RootDomain); + + return sb.ToString(); + } + + private void AppendProtocol(StringBuilder sb) + { + sb.Append("LDAP://"); + } + + private void AppendDomainController(StringBuilder sb) + { + sb.Append(PrimaryDomainController + "/"); + } + + private void AppendOUPath(StringBuilder sb, string ou) + { + if (string.IsNullOrEmpty(ou)) + return; + + string path = ou.Replace("/", "\\"); + string[] parts = path.Split('\\'); + for (int i = parts.Length - 1; i != -1; i--) + sb.Append("OU=").Append(parts[i]).Append(","); + } + + private void AppendDomainPath(StringBuilder sb, string domain) + { + if (string.IsNullOrEmpty(domain)) + return; + + string[] parts = domain.Split('.'); + for (int i = 0; i < parts.Length; i++) + { + sb.Append("DC=").Append(parts[i]); + + if (i < (parts.Length - 1)) + sb.Append(","); + } + } + + internal string AddADPrefix(string path) + { + string dn = path; + if (!dn.ToUpper().StartsWith("LDAP://")) + { + dn = string.Format("LDAP://{0}/{1}", PrimaryDomainController, dn); + } + return dn; + } + + private string RemoveADPrefix(string path) + { + string dn = path; + if (dn.ToUpper().StartsWith("LDAP://")) + { + dn = dn.Substring(7); + } + int index = dn.IndexOf("/"); + + if (index != -1) + { + dn = dn.Substring(index + 1); + } + return dn; + } + + internal string ConvertADPathToCanonicalName(string name) + { + + if (string.IsNullOrEmpty(name)) + return null; + + StringBuilder ret = new StringBuilder(); + List cn = new List(); + List dc = new List(); + + name = RemoveADPrefix(name); + + string[] parts = name.Split(','); + for (int i = 0; i < parts.Length; i++) + { + if (parts[i].StartsWith("DC=")) + { + dc.Add(parts[i].Substring(3)); + } + else if (parts[i].StartsWith("OU=") || parts[i].StartsWith("CN=")) + { + cn.Add(parts[i].Substring(3)); + } + } + + for (int i = 0; i < dc.Count; i++) + { + ret.Append(dc[i]); + if (i < dc.Count - 1) + ret.Append("."); + } + for (int i = cn.Count - 1; i != -1; i--) + { + ret.Append("/"); + ret.Append(cn[i]); + } + return ret.ToString(); + } + + private string ConvertDomainName(string name) + { + + if (string.IsNullOrEmpty(name)) + return null; + + StringBuilder ret = new StringBuilder("LDAP://"); + + string[] parts = name.Split('.'); + for (int i = 0; i < parts.Length; i++) + { + ret.Append("DC="); + ret.Append(parts[i]); + if (i < parts.Length - 1) + ret.Append(","); + } + return ret.ToString(); + } + + + internal virtual void AdjustADSecurity(string objPath, string securityGroupPath, bool isAddressBook) + { + ExchangeLog.LogStart("AdjustADSecurity"); + ExchangeLog.DebugInfo(" Active Direcory object: {0}", objPath); + ExchangeLog.DebugInfo(" Security Group: {0}", securityGroupPath); + + if (isAddressBook) + { + ExchangeLog.DebugInfo(" Updating Security"); + //"Download Address Book" security permission for offline address book + Guid openAddressBookGuid = new Guid("{bd919c7c-2d79-4950-bc9c-e16fd99285e8}"); + + DirectoryEntry groupEntry = GetADObject(securityGroupPath); + byte[] byteSid = (byte[])GetADObjectProperty(groupEntry, "objectSid"); + + DirectoryEntry objEntry = GetADObject(objPath); + ActiveDirectorySecurity security = objEntry.ObjectSecurity; + + // Create a SecurityIdentifier object for security group. + SecurityIdentifier groupSid = new SecurityIdentifier(byteSid, 0); + + // Create an access rule to allow users in Security Group to open address book. + ActiveDirectoryAccessRule allowOpenAddressBook = + new ActiveDirectoryAccessRule( + groupSid, + ActiveDirectoryRights.ExtendedRight, + AccessControlType.Allow, + openAddressBookGuid); + + // Create an access rule to allow users in Security Group to read object. + ActiveDirectoryAccessRule allowRead = + new ActiveDirectoryAccessRule( + groupSid, + ActiveDirectoryRights.GenericRead, + AccessControlType.Allow); + + // Remove existing rules if exist + security.RemoveAccessRuleSpecific(allowOpenAddressBook); + security.RemoveAccessRuleSpecific(allowRead); + + // Add a new access rule to allow users in Security Group to open address book. + security.AddAccessRule(allowOpenAddressBook); + // Add a new access rule to allow users in Security Group to read object. + security.AddAccessRule(allowRead); + + // Commit the changes. + objEntry.CommitChanges(); + } + + ExchangeLog.LogEnd("AdjustADSecurity"); + } + + private void AddUPNSuffix(string ouPath, string suffix) + { + ExchangeLog.LogStart("AddUPNSuffix"); + //Add UPN Suffix to the OU + DirectoryEntry ou = GetADObject(ouPath); + AddADObjectProperty(ou, "uPNSuffixes", suffix); + ou.CommitChanges(); + ou.Close(); + ExchangeLog.LogEnd("AddUPNSuffix"); + } + + private void RemoveUPNSuffix(string ouPath, string suffix) + { + ExchangeLog.LogStart("RemoveUPNSuffix"); + + if (DirectoryEntry.Exists(ouPath)) + { + DirectoryEntry ou = GetADObject(ouPath); + PropertyValueCollection prop = null; + try + { + prop = ou.Properties["uPNSuffixes"]; + } + catch (Exception ex) + { + ExchangeLog.LogWarning("AD object or property not found: {0}", ex); + } + + if (prop != null) + { + if (ou.Properties["uPNSuffixes"].Contains(suffix)) + { + ou.Properties["uPNSuffixes"].Remove(suffix); + ou.CommitChanges(); + } + ou.Close(); + } + } + ExchangeLog.LogEnd("RemoveUPNSuffix"); + } + + /*private void AddGlobalUPNSuffix(string name) + { + ExchangeLog.LogStart("AddGlobalUPNSuffix"); + string path = string.Format("LDAP://{0}/RootDSE", RootDomain); + DirectoryEntry rootDSE = GetADObject(path); + string contextPath = GetADObjectProperty(rootDSE, "ConfigurationNamingContext").ToString(); + DirectoryEntry partitions = GetADObject("LDAP://cn=Partitions," + contextPath); + partitions.Properties["uPNSuffixes"].Add(name); + partitions.CommitChanges(); + partitions.Close(); + rootDSE.Close(); + ExchangeLog.LogEnd("AddGlobalUPNSuffix"); + }*/ + + internal string GetNETBIOSDomainName() + { + ExchangeLog.LogStart("GetNETBIOSDomainName"); + string ret = string.Empty; + + string path = string.Format("LDAP://{0}/RootDSE", RootDomain); + DirectoryEntry rootDSE = GetADObject(path); + string contextPath = GetADObjectProperty(rootDSE, "ConfigurationNamingContext").ToString(); + string defaultContext = GetADObjectProperty(rootDSE, "defaultNamingContext").ToString(); + DirectoryEntry partitions = GetADObject("LDAP://cn=Partitions," + contextPath); + + DirectorySearcher searcher = new DirectorySearcher(); + searcher.SearchRoot = partitions; + searcher.Filter = string.Format("(&(objectCategory=crossRef)(nCName={0}))", defaultContext); + searcher.SearchScope = SearchScope.OneLevel; + + //find the first instance + SearchResult result = searcher.FindOne(); + if (result != null) + { + DirectoryEntry partition = GetADObject(result.Path); + ret = GetADObjectProperty(partition, "nETBIOSName").ToString(); + partition.Close(); + } + partitions.Close(); + rootDSE.Close(); + ExchangeLog.LogEnd("GetNETBIOSDomainName"); + return ret; + } + + /*private void RemoveGlobalUPNSuffix(string name) + { + ExchangeLog.LogStart("RemoveGlobalUPNSuffix"); + string path = string.Format("LDAP://{0}/RootDSE", RootDomain); + DirectoryEntry rootDSE = GetADObject(path); + string contextPath = GetADObjectProperty(rootDSE, "ConfigurationNamingContext").ToString(); + DirectoryEntry partitions = GetADObject("LDAP://cn=Partitions," + contextPath); + if (partitions.Properties["uPNSuffixes"].Contains(name)) + { + partitions.Properties["uPNSuffixes"].Remove(name); + partitions.CommitChanges(); + } + partitions.Close(); + rootDSE.Close(); + ExchangeLog.LogEnd("RemoveGlobalUPNSuffix"); + }*/ + + + #endregion + + #region PowerShell integration + /*private Collection ExecuteShellCommand2(Runspace runSpace, string cmd) + { + ExchangeLog.LogStart("ExecuteShellCommand"); + RunspaceInvoke invoker = new RunspaceInvoke(runSpace); + System.Collections.IList errors = null; + Collection results = invoker.Invoke(cmd, null, out errors); + if (errors != null && errors.Count > 0) + { + foreach (PSObject err in errors) + { + string errorMessage = string.Format("Invoke error: {0}", err.ToString()); + ExchangeLog.LogError(errorMessage, null); + } + } + invoker = null; + ExchangeLog.LogEnd("ExecuteShellCommand"); + return results; + }*/ + + private static RunspaceConfiguration runspaceConfiguration = null; + private static string ExchangePath = null; + + internal static string GetExchangePath() + { + if (string.IsNullOrEmpty(ExchangePath)) + { + RegistryKey root = Registry.LocalMachine; + RegistryKey rk = root.OpenSubKey(ExchangeRegistryPath); + if (rk != null) + { + string value = (string)rk.GetValue("MsiInstallPath", null); + rk.Close(); + if (!string.IsNullOrEmpty(value)) + ExchangePath = Path.Combine(value, "bin"); + } + } + return ExchangePath; + } + + internal static Assembly ResolveExchangeAssembly(object p, ResolveEventArgs args) + { + //Add path for the Exchange 2007 DLLs + if (args.Name.Contains("Microsoft.Exchange")) + { + string exchangePath = GetExchangePath(); + if (string.IsNullOrEmpty(exchangePath)) + return null; + + string path = Path.Combine(exchangePath, args.Name.Split(',')[0] + ".dll"); + if (!File.Exists(path)) + return null; + + ExchangeLog.DebugInfo("Resolved assembly: {0}", path); + + return Assembly.LoadFrom(path); + } + else + { + return null; + } + } + + internal virtual Runspace OpenRunspace() + { + ExchangeLog.LogStart("OpenRunspace"); + + if (runspaceConfiguration == null) + { + runspaceConfiguration = RunspaceConfiguration.Create(); + PSSnapInException exception = null; + + PSSnapInInfo info = runspaceConfiguration.AddPSSnapIn(ExchangeSnapInName, out exception); + + if (exception != null) + { + ExchangeLog.LogWarning("SnapIn error", exception); + } + } + Runspace runSpace = RunspaceFactory.CreateRunspace(runspaceConfiguration); + // + runSpace.Open(); + // + runSpace.SessionStateProxy.SetVariable("ConfirmPreference", "none"); + ExchangeLog.LogEnd("OpenRunspace"); + + Command cmd = new Command("Set-ADServerSettings"); + cmd.Parameters.Add("PreferredServer", PrimaryDomainController); + ExecuteShellCommand(runSpace, cmd, false); + return runSpace; + } + + internal void CloseRunspace(Runspace runspace) + { + try + { + if (runspace != null && runspace.RunspaceStateInfo.State == RunspaceState.Opened) + { + runspace.Close(); + } + } + catch (Exception ex) + { + ExchangeLog.LogError("Runspace error", ex); + } + } + + internal Collection ExecuteShellCommand(Runspace runSpace, Command cmd) + { + return ExecuteShellCommand(runSpace, cmd, true); + } + + internal Collection ExecuteShellCommand(Runspace runSpace, Command cmd, bool useDomainController) + { + object[] errors; + return ExecuteShellCommand(runSpace, cmd, useDomainController, out errors); + } + + internal Collection ExecuteShellCommand(Runspace runSpace, Command cmd, out object[] errors) + { + return ExecuteShellCommand(runSpace, cmd, true, out errors); + } + + internal Collection ExecuteShellCommand(Runspace runSpace, Command cmd, bool useDomainController, out object[] errors) + { + ExchangeLog.LogStart("ExecuteShellCommand"); + List errorList = new List(); + + if (useDomainController) + { + CommandParameter dc = new CommandParameter("DomainController", PrimaryDomainController); + if (!cmd.Parameters.Contains(dc)) + { + cmd.Parameters.Add(dc); + } + } + + ExchangeLog.DebugCommand(cmd); + Collection results = null; + // Create a pipeline + Pipeline pipeLine = runSpace.CreatePipeline(); + using (pipeLine) + { + // Add the command + pipeLine.Commands.Add(cmd); + // Execute the pipeline and save the objects returned. + results = pipeLine.Invoke(); + + // Log out any errors in the pipeline execution + // NOTE: These errors are NOT thrown as exceptions! + // Be sure to check this to ensure that no errors + // happened while executing the command. + if (pipeLine.Error != null && pipeLine.Error.Count > 0) + { + foreach (object item in pipeLine.Error.ReadToEnd()) + { + errorList.Add(item); + string errorMessage = string.Format("Invoke error: {0}", item); + ExchangeLog.LogWarning(errorMessage); + } + } + } + pipeLine = null; + errors = errorList.ToArray(); + ExchangeLog.LogEnd("ExecuteShellCommand"); + return results; + } + + /// + /// Returns the distinguished name of the object from the shell execution result + /// + /// + /// + internal string GetResultObjectDN(Collection result) + { + ExchangeLog.LogStart("GetResultObjectDN"); + if (result == null) + throw new ArgumentNullException("result", "Execution result is not specified"); + + if (result.Count < 1) + throw new ArgumentException("Execution result does not contain any object"); + + if (result.Count > 1) + throw new ArgumentException("Execution result contains more than one object"); + + PSMemberInfo info = result[0].Members["DistinguishedName"]; + if (info == null) + throw new ArgumentException("Execution result does not contain DistinguishedName property", "result"); + + string ret = info.Value.ToString(); + ExchangeLog.LogEnd("GetResultObjectDN"); + return ret; + } + + /// + /// Checks the object from the shell execution result. + /// + /// + /// Distinguished name of the object if object exists or null otherwise. + internal string CheckResultObjectDN(Collection result) + { + ExchangeLog.LogStart("CheckResultObjectDN"); + + if (result == null) + return null; + + if (result.Count < 1) + return null; + + PSMemberInfo info = result[0].Members["DistinguishedName"]; + if (info == null) + throw new ArgumentException("Execution result does not contain DistinguishedName property", "result"); + + string ret = info.Value.ToString(); + ExchangeLog.LogEnd("CheckResultObjectDN"); + return ret; + } + + /// + /// Returns the identity of the object from the shell execution result + /// + /// + /// + internal string GetResultObjectIdentity(Collection result) + { + ExchangeLog.LogStart("GetResultObjectIdentity"); + if (result == null) + throw new ArgumentNullException("result", "Execution result is not specified"); + + if (result.Count < 1) + throw new ArgumentException("Execution result is empty", "result"); + + if (result.Count > 1) + throw new ArgumentException("Execution result contains more than one object", "result"); + + PSMemberInfo info = result[0].Members["Identity"]; + if (info == null) + throw new ArgumentException("Execution result does not contain Identity property", "result"); + + string ret = info.Value.ToString(); + ExchangeLog.LogEnd("GetResultObjectIdentity"); + return ret; + } + + /// + /// Returns the identity of the PS object + /// + /// + /// + internal string GetPSObjectIdentity(PSObject obj) + { + ExchangeLog.LogStart("GetPSObjectIdentity"); + if (obj == null) + throw new ArgumentNullException("obj", "PSObject is not specified"); + + + PSMemberInfo info = obj.Members["Identity"]; + if (info == null) + throw new ArgumentException("PSObject does not contain Identity property", "obj"); + + string ret = info.Value.ToString(); + ExchangeLog.LogEnd("GetPSObjectIdentity"); + return ret; + } + + internal object GetPSObjectProperty(PSObject obj, string name) + { + return obj.Members[name].Value; + } + + #endregion + + #region Storage + internal virtual string CreateStorageGroup(Runspace runSpace, string name, string server) + { + return string.Empty; + } + + internal virtual string CreateMailboxDatabase(Runspace runSpace, string name, string storageGroup) + { + ExchangeLog.LogStart("CreateMailboxDatabase"); + string id; + if (name != "*") + { + Command cmd = new Command("Get-MailboxDatabase"); + cmd.Parameters.Add("Identity", name); + Collection result = ExecuteShellCommand(runSpace, cmd); + if (result != null && result.Count > 0) + { + id = GetResultObjectIdentity(result); + } + else + { + throw new Exception(string.Format("Mailbox database {0} not found", name)); + } + } + else + { + id = "*"; + } + ExchangeLog.LogEnd("CreateMailboxDatabase"); + return id; + } + #endregion + + #region Domains + + + private string[] GetAuthoritativeDomainsInternal() + { + ExchangeLog.LogStart("GetAuthoritativeDomainsInternal"); + + Runspace runSpace = null; + List domains = new List(); + try + { + runSpace = OpenRunspace(); + Command cmd = new Command("Get-AcceptedDomain"); + + Collection result = ExecuteShellCommand(runSpace, cmd); + foreach (PSObject current in result) + { + domains.Add(GetPSObjectProperty(current, "DomainName").ToString()); + } + + } + catch (Exception ex) + { + ExchangeLog.LogError("GetAuthoritativeDomainsInternal", ex); + throw; + } + finally + { + CloseRunspace(runSpace); + } + + ExchangeLog.LogEnd("GetAuthoritativeDomainsInternal"); + return domains.ToArray(); + + } + + + + /// + /// Creates Authoritative Domain on Hub Transport Server + /// + /// + /// + private void CreateAuthoritativeDomainInternal(string domain) + { + ExchangeLog.LogStart("CreateAuthoritativeDomainInternal"); + + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + CreateAcceptedDomain(runSpace, domain); + } + catch (Exception ex) + { + ExchangeLog.LogError("CreateAuthoritativeDomainInternal", ex); + throw; + } + finally + { + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("CreateAuthoritativeDomainInternal"); + } + + private void ChangeAcceptedDomainTypeInternal(string domainName, ExchangeAcceptedDomainType domainType) + { + ExchangeLog.LogStart("ChangeAcceptedDomainType"); + + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + SetAcceptedDomainType(runSpace, domainName, domainType); + } + catch (Exception ex) + { + ExchangeLog.LogError("ChangeAcceptedDomainType", ex); + throw; + } + finally + { + + CloseRunspace(runSpace); + } + + ExchangeLog.LogEnd("ChangeAcceptedDomainType"); + } + + private void DeleteAcceptedDomain(string domainName) + { + ExchangeLog.LogStart("DeleteAcceptedDomain"); + + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + RemoveAcceptedDomain(runSpace, domainName); + } + catch (Exception ex) + { + ExchangeLog.LogError("DeleteAcceptedDomain", ex); + throw; + } + finally + { + + CloseRunspace(runSpace); + } + + ExchangeLog.LogEnd("DeleteAcceptedDomain"); + } + + /// + /// Deletes Authoritative Domain on Hub Transport Server + /// + /// + private void DeleteAuthoritativeDomainInternal(string domain) + { + ExchangeLog.LogStart("DeleteDomainInternal"); + //Delete accepted domain + DeleteAcceptedDomain(domain); + ExchangeLog.LogEnd("DeleteDomainInternal"); + } + + private string CreateAcceptedDomain(Runspace runSpace, string name) + { + ExchangeLog.LogStart("CreateAcceptedDomain"); + + Command cmd = new Command("New-AcceptedDomain"); + cmd.Parameters.Add("Name", name); + cmd.Parameters.Add("DomainName", name); + cmd.Parameters.Add("DomainType", "Authoritative"); + + Collection result = ExecuteShellCommand(runSpace, cmd); + string id = GetResultObjectDN(result); + + ExchangeLog.LogEnd("CreateAcceptedDomain"); + + return id; + } + + private void RemoveAcceptedDomain(Runspace runSpace, string id) + { + ExchangeLog.LogStart("RemoveAcceptedDomain"); + Command cmd = new Command("Remove-AcceptedDomain"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("Confirm", false); + ExecuteShellCommand(runSpace, cmd); + ExchangeLog.LogEnd("RemoveAcceptedDomain"); + } + + private void SetAcceptedDomainType(Runspace runSpace, string id, ExchangeAcceptedDomainType domainType) + { + ExchangeLog.LogStart("SetAcceptedDomainType"); + Command cmd = new Command("Set-AcceptedDomain"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("DomainType", domainType.ToString()); + cmd.Parameters.Add("Confirm", false); + ExecuteShellCommand(runSpace, cmd); + ExchangeLog.LogEnd("SetAcceptedDomainType"); + } + + #endregion + + #region ActiveSync + private void CreateOrganizationActiveSyncPolicyInternal(string organizationId) + { + ExchangeLog.LogStart("CreateOrganizationActiveSyncPolicyInternal"); + ExchangeLog.DebugInfo(" Organization Id: {0}", organizationId); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + //create ActiveSync policy + CreateActiveSyncPolicy(runSpace, organizationId); + } + finally + { + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("CreateOrganizationActiveSyncPolicyInternal"); + } + + internal string CreateActiveSyncPolicy(Runspace runSpace, string organizationId) + { + ExchangeLog.LogStart("CreateActiveSyncPolicy"); + Command cmd = new Command("New-ActiveSyncMailboxPolicy"); + cmd.Parameters.Add("Name", organizationId); + cmd.Parameters.Add("AllowNonProvisionableDevices", true); + cmd.Parameters.Add("Confirm", false); + Collection result = ExecuteShellCommand(runSpace, cmd); + string id = GetResultObjectIdentity(result); + ExchangeLog.LogEnd("CreateActiveSyncPolicy"); + return id; + } + + internal void DeleteActiveSyncPolicy(Runspace runSpace, string id) + { + ExchangeLog.LogStart("DeleteActiveSyncPolicy"); + Command cmd = new Command("Remove-ActiveSyncMailboxPolicy"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("Confirm", false); + ExecuteShellCommand(runSpace, cmd); + ExchangeLog.LogEnd("DeleteActiveSyncPolicy"); + } + + private ExchangeActiveSyncPolicy GetActiveSyncPolicyInternal(string id) + { + ExchangeLog.LogStart("GetActiveSyncPolicyInternal"); + ExchangeLog.DebugInfo("Id: {0}", id); + ExchangeActiveSyncPolicy info = null; + + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + Command cmd = new Command("Get-ActiveSyncMailboxPolicy"); + cmd.Parameters.Add("Identity", id); + Collection result = ExecuteShellCommand(runSpace, cmd); + + if (result != null && result.Count > 0) + { + PSObject policy = result[0]; + info = new ExchangeActiveSyncPolicy(); + info.AllowNonProvisionableDevices = (bool)GetPSObjectProperty(policy, "AllowNonProvisionableDevices"); + info.AttachmentsEnabled = (bool)GetPSObjectProperty(policy, "AttachmentsEnabled"); + info.MaxAttachmentSizeKB = + ConvertUnlimitedToKB((Unlimited)GetPSObjectProperty(policy, "MaxAttachmentSize")); + info.UNCAccessEnabled = (bool)GetPSObjectProperty(policy, "UNCAccessEnabled"); + info.WSSAccessEnabled = (bool)GetPSObjectProperty(policy, "WSSAccessEnabled"); + + info.DevicePasswordEnabled = (bool)GetPSObjectProperty(policy, "DevicePasswordEnabled"); + info.AlphanumericPasswordRequired = (bool)GetPSObjectProperty(policy, "AlphanumericDevicePasswordRequired"); + info.PasswordRecoveryEnabled = (bool)GetPSObjectProperty(policy, "PasswordRecoveryEnabled"); + info.DeviceEncryptionEnabled = (bool)GetPSObjectProperty(policy, "DeviceEncryptionEnabled"); + info.AllowSimplePassword = (bool)GetPSObjectProperty(policy, "AllowSimpleDevicePassword"); + + info.MaxPasswordFailedAttempts = + ConvertUnlimitedToInt32((Unlimited)GetPSObjectProperty(policy, "MaxDevicePasswordFailedAttempts")); + int? passwordLength = (int?)GetPSObjectProperty(policy, "MinDevicePasswordLength"); + info.MinPasswordLength = ConvertNullableToInt32(passwordLength); + + info.InactivityLockMin = ConvertUnlimitedToMinutes((Unlimited)GetPSObjectProperty(policy, "MaxInactivityTimeDeviceLock")); + info.PasswordExpirationDays = ConvertUnlimitedTimeSpanToDays((Unlimited)GetPSObjectProperty(policy, "DevicePasswordExpiration")); + info.PasswordHistory = (int)GetPSObjectProperty(policy, "DevicePasswordHistory"); + + + info.RefreshInterval = ConvertUnlimitedToHours((Unlimited)GetPSObjectProperty(policy, "DevicePolicyRefreshInterval")); + } + } + finally + { + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("GetActiveSyncPolicyInternal"); + return info; + } + + private void SetActiveSyncPolicyInternal( + string id, + bool allowNonProvisionableDevices, + bool attachmentsEnabled, + int maxAttachmentSizeKB, + bool uncAccessEnabled, + bool wssAccessEnabled, + bool devicePasswordEnabled, + bool alphanumericPasswordRequired, + bool passwordRecoveryEnabled, + bool deviceEncryptionEnabled, + bool allowSimplePassword, + int maxPasswordFailedAttempts, + int minPasswordLength, + int inactivityLockMin, + int passwordExpirationDays, + int passwordHistory, + int refreshInterval) + { + ExchangeLog.LogStart("SetActiveSyncPolicyInternal"); + ExchangeLog.DebugInfo("Id: {0}", id); + + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + Command cmd = new Command("Set-ActiveSyncMailboxPolicy"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("AllowNonProvisionableDevices", allowNonProvisionableDevices); + cmd.Parameters.Add("AttachmentsEnabled", attachmentsEnabled); + cmd.Parameters.Add("MaxAttachmentSize", ConvertKBToUnlimited(maxAttachmentSizeKB)); + cmd.Parameters.Add("UNCAccessEnabled", uncAccessEnabled); + cmd.Parameters.Add("WSSAccessEnabled", wssAccessEnabled); + + cmd.Parameters.Add("DevicePasswordEnabled", devicePasswordEnabled); + cmd.Parameters.Add("AlphanumericDevicePasswordRequired", alphanumericPasswordRequired); + cmd.Parameters.Add("PasswordRecoveryEnabled", passwordRecoveryEnabled); + cmd.Parameters.Add("DeviceEncryptionEnabled", deviceEncryptionEnabled); + cmd.Parameters.Add("AllowSimpleDevicePassword", allowSimplePassword); + + Unlimited attempts = ConvertInt32ToUnlimited(maxPasswordFailedAttempts); + cmd.Parameters.Add("MaxDevicePasswordFailedAttempts", attempts); + + int? passwordLength = ConvertInt32ToNullable(minPasswordLength); + cmd.Parameters.Add("MinDevicePasswordLength", passwordLength); + + + Unlimited inactivityLock = ConvertMinutesToUnlimitedTimeSpan(inactivityLockMin); + cmd.Parameters.Add("MaxInactivityTimeDeviceLock", inactivityLock); + + Unlimited passwordExpiration = ConvertDaysToUnlimitedTimeSpan(passwordExpirationDays); + cmd.Parameters.Add("DevicePasswordExpiration", passwordExpiration); + + cmd.Parameters.Add("DevicePasswordHistory", passwordHistory); + + Unlimited refInter = ConvertHoursToUnlimitedTimeSpan(refreshInterval); + cmd.Parameters.Add("DevicePolicyRefreshInterval", refInter); + + ExecuteShellCommand(runSpace, cmd); + } + finally + { + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("SetActiveSyncPolicyInternal"); + } + #endregion + + #region Mobile devices + + private ExchangeMobileDevice[] GetMobileDevicesInternal(string accountName) + { + ExchangeLog.LogStart("GetMobileDevicesInternal"); + ExchangeLog.DebugInfo("Account name: {0}", accountName); + + List devices = new List(); + ExchangeMobileDevice device = null; + + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + Command cmd = new Command("Get-ActiveSyncDeviceStatistics"); + cmd.Parameters.Add("Mailbox", accountName); + + Collection result = null; + try + { + result = ExecuteShellCommand(runSpace, cmd); + } + catch (Exception) + { + } + + if (result != null) + { + foreach (PSObject obj in result) + { + device = GetMobileDeviceObject(obj); + devices.Add(device); + } + } + } + finally + { + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("GetMobileDevicesInternal"); + return devices.ToArray(); + } + + private ExchangeMobileDevice GetMobileDeviceObject(PSObject obj) + { + ExchangeMobileDevice device = new ExchangeMobileDevice(); + device.Id = GetPSObjectIdentity(obj); + device.FirstSyncTime = ConvertNullableToDateTime((DateTime?)GetPSObjectProperty(obj, "FirstSyncTime")); + device.LastPolicyUpdateTime = ConvertNullableToDateTime((DateTime?)GetPSObjectProperty(obj, "LastPolicyUpdateTime")); + device.LastSyncAttemptTime = ConvertNullableToDateTime((DateTime?)GetPSObjectProperty(obj, "LastSyncAttemptTime")); + device.LastSuccessSync = ConvertNullableToDateTime((DateTime?)GetPSObjectProperty(obj, "LastSuccessSync")); + device.DeviceType = (string)GetPSObjectProperty(obj, "DeviceType"); + device.DeviceID = (string)GetPSObjectProperty(obj, "DeviceID"); + device.DeviceUserAgent = (string)GetPSObjectProperty(obj, "DeviceUserAgent"); + DateTime? wipeSentTime = (DateTime?)GetPSObjectProperty(obj, "DeviceWipeSentTime"); + device.DeviceWipeSentTime = ConvertNullableToDateTime(wipeSentTime); + DateTime? wipeRequestTime = (DateTime?)GetPSObjectProperty(obj, "DeviceWipeRequestTime"); + device.DeviceWipeRequestTime = ConvertNullableToDateTime(wipeRequestTime); + DateTime? wipeAckTime = (DateTime?)GetPSObjectProperty(obj, "DeviceWipeAckTime"); + device.DeviceWipeAckTime = ConvertNullableToDateTime(wipeAckTime); + device.LastPingHeartbeat = ConvertNullableToInt32((UInt32?)GetPSObjectProperty(obj, "LastPingHeartbeat")); + device.RecoveryPassword = (string)GetPSObjectProperty(obj, "RecoveryPassword"); + device.DeviceModel = (string)GetPSObjectProperty(obj, "DeviceModel"); + device.DeviceIMEI = (string)GetPSObjectProperty(obj, "DeviceIMEI"); + device.DeviceFriendlyName = (string)GetPSObjectProperty(obj, "DeviceFriendlyName"); + device.DeviceOS = (string)GetPSObjectProperty(obj, "DeviceOS"); + device.DeviceOSLanguage = (string)GetPSObjectProperty(obj, "DeviceOSLanguage"); + device.DevicePhoneNumber = (string)GetPSObjectProperty(obj, "DevicePhoneNumber"); + //status + if (wipeAckTime.HasValue) + { + //green + device.Status = MobileDeviceStatus.WipeSuccessful; + } + else + { + if (wipeRequestTime.HasValue || wipeSentTime.HasValue) + { + //red + device.Status = MobileDeviceStatus.PendingWipe; + } + else + { + //black + device.Status = MobileDeviceStatus.OK; + } + } + + return device; + } + + private ExchangeMobileDevice GetMobileDeviceInternal(string id) + { + ExchangeLog.LogStart("GetMobileDeviceInternal"); + ExchangeMobileDevice device = null; + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + Command cmd = new Command("Get-ActiveSyncDeviceStatistics"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("ShowRecoveryPassword", true); + Collection result = ExecuteShellCommand(runSpace, cmd); + if (result != null && result.Count > 0) + { + device = GetMobileDeviceObject(result[0]); + } + } + finally + { + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("GetMobileDeviceInternal"); + return device; + } + + private void WipeDataFromDeviceInternal(string id) + { + ExchangeLog.LogStart("WipeDataFromDeviceInternal"); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + Command cmd = new Command("Clear-ActiveSyncDevice"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("Confirm", false); + ExecuteShellCommand(runSpace, cmd); + } + finally + { + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("WipeDataFromDeviceInternal"); + } + + private void CancelRemoteWipeRequestInternal(string id) + { + ExchangeLog.LogStart("CancelRemoteWipeRequestInternal"); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + Command cmd = new Command("Clear-ActiveSyncDevice"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("Cancel", true); + cmd.Parameters.Add("Confirm", false); + ExecuteShellCommand(runSpace, cmd); + } + finally + { + CloseRunspace(runSpace); + } + + ExchangeLog.LogEnd("CancelRemoteWipeRequestInternal"); + } + + + internal void RemoveDevicesInternal(Runspace runSpace, string accountName) + { + ExchangeLog.LogStart("RemoveDevicesInternal"); + ExchangeLog.DebugInfo("Account name: {0}", accountName); + + try + { + runSpace = OpenRunspace(); + Command cmd = new Command("Get-ActiveSyncDeviceStatistics"); + cmd.Parameters.Add("Mailbox", accountName); + + Collection result = null; + try + { + result = ExecuteShellCommand(runSpace, cmd); + } + catch (Exception) + { + } + + if (result != null) + { + foreach (PSObject obj in result) + { + ExchangeMobileDevice device = GetMobileDeviceObject(obj); + + cmd = new Command("Remove-ActiveSyncDevice"); + cmd.Parameters.Add("Identity", device.DeviceID); + cmd.Parameters.Add("Confirm", false); + ExecuteShellCommand(runSpace, cmd); + } + } + } + finally + { + + } + ExchangeLog.LogEnd("RemoveDevicesInternal"); + } + + + private void RemoveDeviceInternal(string id) + { + ExchangeLog.LogStart("RemoveDeviceInternal"); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + Command cmd = new Command("Remove-ActiveSyncDevice"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("Confirm", false); + ExecuteShellCommand(runSpace, cmd); + } + finally + { + CloseRunspace(runSpace); + } + + ExchangeLog.LogEnd("RemoveDeviceInternal"); + } + #endregion + + #region Convert Utils + internal int ConvertUnlimitedToInt32(Unlimited value) + { + int ret = 0; + if (value.IsUnlimited) + { + ret = -1; + } + else + { + ret = value.Value; + } + return ret; + } + + internal Unlimited ConvertInt32ToUnlimited(int value) + { + if (value == -1) + return Unlimited.UnlimitedValue; + else + { + Unlimited ret = new Unlimited(); + ret.Value = value; + return ret; + } + } + + internal long ConvertUnlimitedToBytes(Unlimited value) + { + long ret = 0; + if (value.IsUnlimited) + { + ret = -1; + } + else + { + ret = Convert.ToInt64(value.Value.ToBytes()); + } + return ret; + } + + internal int ConvertUnlimitedToKB(Unlimited value) + { + int ret = 0; + if (value.IsUnlimited) + { + ret = -1; + } + else + { + ret = Convert.ToInt32(value.Value.ToKB()); + } + return ret; + } + + internal int ConvertUnlimitedToMB(Unlimited value) + { + int ret = 0; + if (value.IsUnlimited) + { + ret = -1; + } + else + { + ret = Convert.ToInt32(value.Value.ToMB()); + } + return ret; + } + + + internal int ConvertUnlimitedToHours(Unlimited value) + { + int ret = 0; + if (value.IsUnlimited) + { + ret = -1; + } + else + { + ret = Convert.ToInt32(value.Value.TotalHours); + } + return ret; + } + + internal int ConvertUnlimitedToMinutes(Unlimited value) + { + int ret = 0; + if (value.IsUnlimited) + { + ret = -1; + } + else + { + ret = Convert.ToInt32(value.Value.TotalMinutes); + } + return ret; + } + + internal Unlimited ConvertHoursToUnlimitedTimeSpan(int value) + { + if (value == -1) + return Unlimited.UnlimitedValue; + else + { + Unlimited ret = new Unlimited(); + ret.Value = EnhancedTimeSpan.FromHours(Convert.ToDouble(value)); + return ret; + } + + } + + internal Unlimited ConvertMinutesToUnlimitedTimeSpan(int value) + { + if (value == -1) + return Unlimited.UnlimitedValue; + else + { + Unlimited ret = new Unlimited(); + ret.Value = EnhancedTimeSpan.FromMinutes(Convert.ToDouble(value)); + return ret; + } + } + + internal Unlimited ConvertDaysToUnlimitedTimeSpan(int value) + { + if (value == -1) + return Unlimited.UnlimitedValue; + else + { + Unlimited ret = new Unlimited(); + ret.Value = EnhancedTimeSpan.FromDays(Convert.ToDouble(value)); + return ret; + } + } + + + internal int ConvertUnlimitedTimeSpanToDays(Unlimited value) + { + int ret = 0; + if (value.IsUnlimited) + { + ret = -1; + } + else + { + ret = value.Value.Days; + } + return ret; + } + + + internal int ConvertNullableToInt32(Nullable value) where T : struct + { + int ret = 0; + if (value.HasValue) + { + ret = Convert.ToInt32(value.Value); + } + return ret; + } + + + internal int? ConvertInt32ToNullable(int value) + { + int? ret = null; + if (value != 0) + { + ret = new int?(value); + } + return ret; + } + + + + internal DateTime ConvertNullableToDateTime(DateTime? value) + { + DateTime ret = DateTime.MinValue; + if (value.HasValue) + { + ret = value.Value; + } + return ret; + } + + internal bool ConvertNullableToBoolean(bool? value) + { + bool ret = false; + if (value.HasValue) + { + ret = value.Value; + } + return ret; + } + + internal int ConvertEnhancedTimeSpanToDays(EnhancedTimeSpan value) + { + return value.Days; + } + + internal EnhancedTimeSpan ConvertDaysToEnhancedTimeSpan(int days) + { + return EnhancedTimeSpan.FromDays(Convert.ToDouble(days)); + } + + internal Unlimited ConvertKBToUnlimited(int kb) + { + if (kb == -1) + return Unlimited.UnlimitedValue; + else + { + Unlimited ret = new Unlimited(); + ret.Value = ByteQuantifiedSize.FromKB(Convert.ToUInt64(kb)); + return ret; + } + } + + internal Unlimited ConvertKBToUnlimited(long kb) + { + if (kb == -1) + return Unlimited.UnlimitedValue; + else + { + Unlimited ret = new Unlimited(); + ret.Value = ByteQuantifiedSize.FromKB(Convert.ToUInt64(kb)); + return ret; + } + } + + + internal string ProxyAddressToString(ProxyAddress proxyAddress) + { + string ret = null; + if (proxyAddress != null) + ret = proxyAddress.AddressString; + return ret; + } + + internal string SmtpAddressToString(SmtpAddress smtpAddress) + { + string ret = null; + if (smtpAddress != null) + ret = smtpAddress.ToString(); + return ret; + } + + internal string CountryInfoToString(CountryInfo countryInfo) + { + string ret = null; + if (countryInfo != null) + ret = countryInfo.Name; + return ret; + } + + internal CountryInfo ParseCountryInfo(string country) + { + CountryInfo ret = null; + if (!string.IsNullOrEmpty(country)) + { + ret = CountryInfo.Parse(country); + } + return ret; + } + + + internal string ObjToString(object obj) + { + string ret = null; + if (obj != null) + ret = obj.ToString(); + return ret; + } + + + #endregion + + #region Utils + private object GetObjectPropertyValue(object obj, string property) + { + PropertyInfo pinfo = obj.GetType().GetProperty(property); + return pinfo.GetValue(obj, null); + } + + private object GetObjectIndexerValue(object obj, object index) + { + Type t = obj.GetType(); + object ret = t.InvokeMember("Item", BindingFlags.GetProperty, null, obj, new object[] { index }); + return ret; + } + + internal string GetServerName() + { + return System.Environment.MachineName; + } + #endregion + + #region Transactions + + internal ExchangeTransaction StartTransaction() + { + return new ExchangeTransaction(); + } + + internal void RollbackTransaction(ExchangeTransaction transaction) + { + ExchangeLog.LogStart("RollbackTransaction"); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + + for (int i = transaction.Actions.Count - 1; i > -1; i--) + { + //reverse order + try + { + RollbackAction(transaction.Actions[i], runSpace); + } + catch (Exception ex) + { + ExchangeLog.LogError("Rollback error", ex); + } + } + } + catch (Exception ex) + { + ExchangeLog.LogError("Rollback error", ex); + } + finally + { + + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("RollbackTransaction"); + } + + private void RollbackAction(TransactionAction action, Runspace runspace) + { + ExchangeLog.LogInfo("Rollback action: {0}", action.ActionType); + switch (action.ActionType) + { + case TransactionAction.TransactionActionTypes.CreateOrganizationUnit: + DeleteADObject(action.Id); + break; + case TransactionAction.TransactionActionTypes.CreateDistributionGroup: + RemoveDistributionGroup(runspace, action.Id); + break; + case TransactionAction.TransactionActionTypes.EnableDistributionGroup: + DisableMailSecurityDistributionGroup(runspace, action.Id); + break; + case TransactionAction.TransactionActionTypes.CreateGlobalAddressList: + DeleteGlobalAddressList(runspace, action.Id); + break; + case TransactionAction.TransactionActionTypes.CreateAddressList: + DeleteAddressList(runspace, action.Id); + break; + case TransactionAction.TransactionActionTypes.CreateAddressBookPolicy: + DeleteAddressBookPolicy(runspace, action.Id); + break; + case TransactionAction.TransactionActionTypes.CreateOfflineAddressBook: + DeleteOfflineAddressBook(runspace, action.Id); + break; + case TransactionAction.TransactionActionTypes.CreateActiveSyncPolicy: + DeleteActiveSyncPolicy(runspace, action.Id); + break; + case TransactionAction.TransactionActionTypes.CreateAcceptedDomain: + RemoveAcceptedDomain(runspace, action.Id); + break; + case TransactionAction.TransactionActionTypes.AddUPNSuffix: + RemoveUPNSuffix(action.Id, action.Suffix); + break; + case TransactionAction.TransactionActionTypes.CreateMailbox: + RemoveMailbox(runspace, action.Id); + break; + case TransactionAction.TransactionActionTypes.EnableMailbox: + DisableMailbox(runspace, action.Id); + break; + case TransactionAction.TransactionActionTypes.CreateContact: + RemoveContact(runspace, action.Id); + break; + case TransactionAction.TransactionActionTypes.CreatePublicFolder: + RemovePublicFolder(runspace, action.Id); + break; + case TransactionAction.TransactionActionTypes.AddMailboxFullAccessPermission: + RemoveMailboxAccessPermission(runspace, action.Account, action.Id, "FullAccess"); + break; + case TransactionAction.TransactionActionTypes.AddSendAsPermission: + RemoveADPermission(runspace, action.Account, action.Id, null, "Send-as", null); + break; + case TransactionAction.TransactionActionTypes.RemoveMailboxFullAccessPermission: + SetMailboxPermission(runspace, action.Account, action.Id, "FullAccess"); + break; + case TransactionAction.TransactionActionTypes.RemoveSendAsPermission: + SetExtendedRights(runspace, action.Account, action.Id, "Send-as"); + break; + } + } + #endregion + + public override bool IsInstalled() + { + + int value = 0; + bool bResult = false; + RegistryKey root = Registry.LocalMachine; + RegistryKey rk = root.OpenSubKey(ExchangeRegistryPath); + if (rk != null) + { + value = (int)rk.GetValue("MsiProductMajor", null); + if (value == 15) + { + value = (int)rk.GetValue("MsiProductMinor", null); + if (value == 0) bResult = true; + } + rk.Close(); + } + return bResult; + } + } +} + diff --git a/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution.Exchange2013/Properties/AssemblyInfo.cs b/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution.Exchange2013/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..201cf4ac --- /dev/null +++ b/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution.Exchange2013/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("WebsitePanel.Providers.HostedSolution.Exchange2013")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("WebsitePanel.Providers.HostedSolution.Exchange2013")] +[assembly: AssemblyCopyright("Copyright © 2012")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("d30b5e58-a80d-411b-ab69-30bdc4e2ec15")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution.Exchange2013/WebsitePanel.Providers.HostedSolution.Exchange2013.csproj b/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution.Exchange2013/WebsitePanel.Providers.HostedSolution.Exchange2013.csproj new file mode 100644 index 00000000..eb6f427f --- /dev/null +++ b/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution.Exchange2013/WebsitePanel.Providers.HostedSolution.Exchange2013.csproj @@ -0,0 +1,90 @@ + + + + + Debug + AnyCPU + {BC094166-B6A1-4D42-B53C-FF956FC7A4A1} + Library + Properties + WebsitePanel.Providers.HostedSolution.Exchange2013 + WebsitePanel.Providers.HostedSolution.Exchange2013 + v4.0 + 512 + + + + true + full + false + ..\WebsitePanel.Server\bin\ + DEBUG;TRACE + prompt + 4 + AllRules.ruleset + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\..\Lib\References\Microsoft\Exchange2013\Microsoft.Exchange.Common.dll + + + ..\..\Lib\References\Microsoft\Exchange2013\Microsoft.Exchange.Data.dll + + + ..\..\Lib\References\Microsoft\Exchange2013\Microsoft.Exchange.Data.Directory.dll + + + ..\..\Lib\References\Microsoft\Exchange2013\Microsoft.Exchange.Data.Storage.dll + + + ..\..\Lib\References\Microsoft\Exchange2013\Microsoft.Exchange.Diagnostics.dll + + + ..\..\Lib\References\Microsoft\Exchange2013\Microsoft.Exchange.Extensibility.Internal.dll + + + ..\..\Lib\References\Microsoft\Exchange2013\Microsoft.Exchange.Net.dll + + + + + + False + ..\..\Lib\References\Microsoft\Windows2012\System.Management.Automation.dll + + + + + + + + ..\..\Bin\WebsitePanel.Providers.Base.dll + + + ..\WebsitePanel.Server\bin\WebsitePanel.Providers.HostedSolution.dll + + + ..\WebsitePanel.Server.Utils\bin\Debug\WebsitePanel.Server.Utils.dll + + + + + + + + + \ No newline at end of file diff --git a/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution/Exchange2007.cs b/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution/Exchange2007.cs index f972983b..a23552fa 100644 --- a/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution/Exchange2007.cs +++ b/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution/Exchange2007.cs @@ -56,36 +56,36 @@ using Microsoft.Exchange.Data.Storage; namespace WebsitePanel.Providers.HostedSolution { - public class Exchange2007 : HostingServiceProviderBase, IExchangeServer - { - #region Static constructor - static Exchange2007() - { - AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(ResolveExchangeAssembly); - ExchangeRegistryPath = "SOFTWARE\\Microsoft\\Exchange\\Setup"; - } - #endregion + public class Exchange2007 : HostingServiceProviderBase, IExchangeServer + { + #region Static constructor + static Exchange2007() + { + AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(ResolveExchangeAssembly); + ExchangeRegistryPath = "SOFTWARE\\Microsoft\\Exchange\\Setup"; + } + #endregion - #region Constants - private const string CONFIG_CLEAR_QUERYBASEDN = "WebsitePanel.Exchange.ClearQueryBaseDN"; - #endregion + #region Constants + private const string CONFIG_CLEAR_QUERYBASEDN = "WebsitePanel.Exchange.ClearQueryBaseDN"; + #endregion - #region Properties + #region Properties - internal string RootOU - { - get { return ProviderSettings["RootOU"]; } - } + internal string RootOU + { + get { return ProviderSettings["RootOU"]; } + } - internal string StorageGroup - { - get { return ProviderSettings["StorageGroup"]; } - } + internal string StorageGroup + { + get { return ProviderSettings["StorageGroup"]; } + } - internal string MailboxDatabase - { - get { return ProviderSettings["MailboxDatabase"]; } - } + internal string MailboxDatabase + { + get { return ProviderSettings["MailboxDatabase"]; } + } internal bool PublicFolderDistributionEnabled { @@ -93,100 +93,100 @@ namespace WebsitePanel.Providers.HostedSolution } internal int KeepDeletedItemsDays - { - get { return Int32.Parse(ProviderSettings["KeepDeletedItemsDays"]); } - } + { + get { return Int32.Parse(ProviderSettings["KeepDeletedItemsDays"]); } + } - internal int KeepDeletedMailboxesDays - { - get { return Int32.Parse(ProviderSettings["KeepDeletedMailboxesDays"]); } - } + internal int KeepDeletedMailboxesDays + { + get { return Int32.Parse(ProviderSettings["KeepDeletedMailboxesDays"]); } + } - internal string RootDomain - { - get { return ServerSettings.ADRootDomain; } - } + internal string RootDomain + { + get { return ServerSettings.ADRootDomain; } + } - internal string MailboxCluster - { - get { return ProviderSettings["MailboxCluster"]; } - } + internal string MailboxCluster + { + get { return ProviderSettings["MailboxCluster"]; } + } - internal string PrimaryDomainController - { - get { return ProviderSettings["PrimaryDomainController"]; } - } + internal string PrimaryDomainController + { + get { return ProviderSettings["PrimaryDomainController"]; } + } - internal string PublicFolderServer - { - get { return ProviderSettings["PublicFolderServer"]; } - } + internal string PublicFolderServer + { + get { return ProviderSettings["PublicFolderServer"]; } + } - internal string OABGenerationServer - { - get { return ProviderSettings["OABServer"]; } - } + internal string OABGenerationServer + { + get { return ProviderSettings["OABServer"]; } + } - internal static string ExchangeRegistryPath - { - get; - set; - } + internal static string ExchangeRegistryPath + { + get; + set; + } - internal virtual string ExchangeSnapInName - { - get { return "Microsoft.Exchange.Management.PowerShell.Admin"; } - } + internal virtual string ExchangeSnapInName + { + get { return "Microsoft.Exchange.Management.PowerShell.Admin"; } + } - #endregion + #endregion - #region IExchangeServer Members + #region IExchangeServer Members - #region Common - public bool CheckAccountCredentials(string username, string password) - { - return CheckAccountCredentialsInternal(username, password); - } - #endregion + #region Common + public bool CheckAccountCredentials(string username, string password) + { + return CheckAccountCredentialsInternal(username, password); + } + #endregion - #region Organizations + #region Organizations - /// - /// Extend existing organization with exchange functionality - /// - /// - /// - /// + /// + /// Extend existing organization with exchange functionality + /// + /// + /// + /// public Organization ExtendToExchangeOrganization(string organizationId, string securityGroup, bool IsConsumer) { return ExtendToExchangeOrganizationInternal(organizationId, securityGroup, IsConsumer); } - /// - /// Creates organization OAB on the Client Access Server - /// - /// - /// - /// - public Organization CreateOrganizationOfflineAddressBook(string organizationId, string securityGroup, string oabVirtualDir) - { - return CreateOrganizationOfflineAddressBookInternal(organizationId, securityGroup, oabVirtualDir); - } + /// + /// Creates organization OAB on the Client Access Server + /// + /// + /// + /// + public Organization CreateOrganizationOfflineAddressBook(string organizationId, string securityGroup, string oabVirtualDir) + { + return CreateOrganizationOfflineAddressBookInternal(organizationId, securityGroup, oabVirtualDir); + } - /// - /// Updates organization OAB - /// - /// - public void UpdateOrganizationOfflineAddressBook(string oabId) - { - UpdateOrganizationOfflineAddressBookInternal(oabId); - } + /// + /// Updates organization OAB + /// + /// + public void UpdateOrganizationOfflineAddressBook(string oabId) + { + UpdateOrganizationOfflineAddressBookInternal(oabId); + } - public string GetOABVirtualDirectory() - { - return GetOABVirtualDirectoryInternal(); - } + public string GetOABVirtualDirectory() + { + return GetOABVirtualDirectoryInternal(); + } public Organization CreateOrganizationAddressBookPolicy(string organizationId, string gal, string addressBook, string roomList, string oab) { @@ -201,87 +201,73 @@ namespace WebsitePanel.Providers.HostedSolution addressList, roomList, offlineAddressBook, securityGroup, addressBookPolicy); } - public void SetOrganizationStorageLimits(string organizationDistinguishedName, long issueWarningKB, long prohibitSendKB, - long prohibitSendReceiveKB, int keepDeletedItemsDays) - { - SetOrganizationStorageLimitsInternal(organizationDistinguishedName, issueWarningKB, prohibitSendKB, - prohibitSendReceiveKB, keepDeletedItemsDays); - } + public void SetOrganizationStorageLimits(string organizationDistinguishedName, long issueWarningKB, long prohibitSendKB, + long prohibitSendReceiveKB, int keepDeletedItemsDays) + { + SetOrganizationStorageLimitsInternal(organizationDistinguishedName, issueWarningKB, prohibitSendKB, + prohibitSendReceiveKB, keepDeletedItemsDays); + } - public ExchangeItemStatistics[] GetMailboxesStatistics(string organizationDistinguishedName) - { - return GetMailboxesStatisticsInternal(organizationDistinguishedName); - } - #endregion + public ExchangeItemStatistics[] GetMailboxesStatistics(string organizationDistinguishedName) + { + return GetMailboxesStatisticsInternal(organizationDistinguishedName); + } + #endregion - #region Domains + #region Domains - public string[] GetAuthoritativeDomains() - { - return GetAuthoritativeDomainsInternal(); - } + public string[] GetAuthoritativeDomains() + { + return GetAuthoritativeDomainsInternal(); + } - public void AddAuthoritativeDomain(string domain) - { - CreateAuthoritativeDomainInternal(domain); - } + public void AddAuthoritativeDomain(string domain) + { + CreateAuthoritativeDomainInternal(domain); + } - public void DeleteAuthoritativeDomain(string domain) - { - DeleteAuthoritativeDomainInternal(domain); - } + public void DeleteAuthoritativeDomain(string domain) + { + DeleteAuthoritativeDomainInternal(domain); + } public void ChangeAcceptedDomainType(string domainName, ExchangeAcceptedDomainType domainType) { ChangeAcceptedDomainTypeInternal(domainName, domainType); } - #endregion + #endregion - #region Mailboxes + #region Mailboxes - public ExchangeMailbox GetMailboxPermissions(string organizationId, string accountName) - { - return GetMailboxPermissionsInternal(organizationId, accountName, null); - } + public ExchangeMailbox GetMailboxPermissions(string organizationId, string accountName) + { + return GetMailboxPermissionsInternal(organizationId, accountName, null); + } - public void SetMailboxPermissions(string organizationId, string accountName, string[] sendAsAccounts, string[] fullAccessAccounts) - { - SetMailboxPermissionsInternal(organizationId, accountName, sendAsAccounts, fullAccessAccounts); - } + public void SetMailboxPermissions(string organizationId, string accountName, string[] sendAsAccounts, string[] fullAccessAccounts) + { + SetMailboxPermissionsInternal(organizationId, accountName, sendAsAccounts, fullAccessAccounts); + } -/* - public string CreateMailbox(string organizationId, string organizationDistinguishedName, - string mailboxDatabase, string securityGroup, string offlineAddressBook, ExchangeAccountType accountType, - string displayName, - string accountName, string name, string domain, string password, bool enablePOP, bool enableIMAP, - bool enableOWA, bool enableMAPI, bool enableActiveSync, - int issueWarningKB, int prohibitSendKB, int prohibitSendReceiveKB, int keepDeletedItemsDays) - { - return CreateMailboxInternal(organizationId, organizationDistinguishedName, mailboxDatabase, securityGroup, - offlineAddressBook, accountType, displayName, accountName, name, domain, password, enablePOP, enableIMAP, - enableOWA, enableMAPI, enableActiveSync, - issueWarningKB, prohibitSendKB, prohibitSendReceiveKB, keepDeletedItemsDays); - } -*/ - public void DeleteMailbox(string accountName) - { - DeleteMailboxInternal(accountName); - } + public void DeleteMailbox(string accountName) + { + DeleteMailboxInternal(accountName); + } - public ExchangeMailbox GetMailboxGeneralSettings(string accountName) - { - return GetMailboxGeneralSettingsInternal(accountName); - } + public ExchangeMailbox GetMailboxGeneralSettings(string accountName) + { + return GetMailboxGeneralSettingsInternal(accountName); + } - public void SetMailboxGeneralSettings(string accountName, bool hideFromAddressBook, bool disabled) - { - SetMailboxGeneralSettingsInternal(accountName, hideFromAddressBook, disabled); - } + public void SetMailboxGeneralSettings(string accountName, bool hideFromAddressBook, bool disabled) + { + SetMailboxGeneralSettingsInternal(accountName, hideFromAddressBook, disabled); + } - public ExchangeMailbox GetMailboxMailFlowSettings(string accountName) - { - return GetMailboxMailFlowSettingsInternal(accountName); - } + public ExchangeMailbox GetMailboxMailFlowSettings(string accountName) + { + return GetMailboxMailFlowSettingsInternal(accountName); + } public void SetMailboxMailFlowSettings(string accountName, bool enableForwarding, string forwardingAccountName, bool forwardToBoth, string[] sendOnBehalfAccounts, @@ -291,84 +277,85 @@ namespace WebsitePanel.Providers.HostedSolution forwardToBoth, sendOnBehalfAccounts, acceptAccounts, rejectAccounts, requireSenderAuthentication); } - public ExchangeMailbox GetMailboxAdvancedSettings(string accountName) - { - return GetMailboxAdvancedSettingsInternal(accountName); - } + public ExchangeMailbox GetMailboxAdvancedSettings(string accountName) + { + return GetMailboxAdvancedSettingsInternal(accountName); + } public void SetMailboxAdvancedSettings(string organizationId, string accountName, bool enablePOP, bool enableIMAP, bool enableOWA, bool enableMAPI, bool enableActiveSync, long issueWarningKB, long prohibitSendKB, long prohibitSendReceiveKB, int keepDeletedItemsDays, int maxRecipients, int maxSendMessageSizeKB, - int maxReceiveMessageSizeKB) + int maxReceiveMessageSizeKB, bool enabledLitigationHold, long recoverabelItemsSpace, long recoverabelItemsWarning) { SetMailboxAdvancedSettingsInternal(organizationId, accountName, enablePOP, enableIMAP, enableOWA, enableMAPI, enableActiveSync, issueWarningKB, - prohibitSendKB, prohibitSendReceiveKB, keepDeletedItemsDays, maxRecipients, maxSendMessageSizeKB, maxReceiveMessageSizeKB); + prohibitSendKB, prohibitSendReceiveKB, keepDeletedItemsDays, maxRecipients, maxSendMessageSizeKB, maxReceiveMessageSizeKB, + enabledLitigationHold, recoverabelItemsSpace, recoverabelItemsWarning); } - public ExchangeEmailAddress[] GetMailboxEmailAddresses(string accountName) - { - return GetMailboxEmailAddressesInternal(accountName); - } + public ExchangeEmailAddress[] GetMailboxEmailAddresses(string accountName) + { + return GetMailboxEmailAddressesInternal(accountName); + } - public void SetMailboxEmailAddresses(string accountName, string[] emailAddresses) - { - SetMailboxEmailAddressesInternal(accountName, emailAddresses); - } + public void SetMailboxEmailAddresses(string accountName, string[] emailAddresses) + { + SetMailboxEmailAddressesInternal(accountName, emailAddresses); + } - public void SetMailboxPrimaryEmailAddress(string accountName, string emailAddress) - { - SetMailboxPrimaryEmailAddressInternal(accountName, emailAddress); - } + public void SetMailboxPrimaryEmailAddress(string accountName, string emailAddress) + { + SetMailboxPrimaryEmailAddressInternal(accountName, emailAddress); + } - public ExchangeMailboxStatistics GetMailboxStatistics(string id) - { - return GetMailboxStatisticsInternal(id); - } - #endregion + public ExchangeMailboxStatistics GetMailboxStatistics(string id) + { + return GetMailboxStatisticsInternal(id); + } + #endregion - #region Contacts - public void CreateContact(string organizationId, string organizationDistinguishedName, - string contactDisplayName, string contactAccountName, string contactEmail, string defaultOrganizationDomain) - { - CreateContactInternal(organizationId, organizationDistinguishedName, contactDisplayName, - contactAccountName, contactEmail, defaultOrganizationDomain); - } + #region Contacts + public void CreateContact(string organizationId, string organizationDistinguishedName, + string contactDisplayName, string contactAccountName, string contactEmail, string defaultOrganizationDomain) + { + CreateContactInternal(organizationId, organizationDistinguishedName, contactDisplayName, + contactAccountName, contactEmail, defaultOrganizationDomain); + } - public void DeleteContact(string accountName) - { - DeleteContactInternal(accountName); - } + public void DeleteContact(string accountName) + { + DeleteContactInternal(accountName); + } - public ExchangeContact GetContactGeneralSettings(string accountName) - { - return GetContactGeneralSettingsInternal(accountName); - } + public ExchangeContact GetContactGeneralSettings(string accountName) + { + return GetContactGeneralSettingsInternal(accountName); + } - public void SetContactGeneralSettings(string accountName, string displayName, string email, - bool hideFromAddressBook, string firstName, string initials, string lastName, string address, - string city, string state, string zip, string country, string jobTitle, string company, - string department, string office, string managerAccountName, string businessPhone, string fax, - string homePhone, string mobilePhone, string pager, string webPage, string notes, int useMapiRichTextFormat, string defaultOrganizationDomain) - { - SetContactGeneralSettingsInternal(accountName, displayName, email, hideFromAddressBook, - firstName, initials, lastName, address, city, state, zip, country, jobTitle, - company, department, office, managerAccountName, businessPhone, fax, homePhone, - mobilePhone, pager, webPage, notes, useMapiRichTextFormat, defaultOrganizationDomain); - } + public void SetContactGeneralSettings(string accountName, string displayName, string email, + bool hideFromAddressBook, string firstName, string initials, string lastName, string address, + string city, string state, string zip, string country, string jobTitle, string company, + string department, string office, string managerAccountName, string businessPhone, string fax, + string homePhone, string mobilePhone, string pager, string webPage, string notes, int useMapiRichTextFormat, string defaultOrganizationDomain) + { + SetContactGeneralSettingsInternal(accountName, displayName, email, hideFromAddressBook, + firstName, initials, lastName, address, city, state, zip, country, jobTitle, + company, department, office, managerAccountName, businessPhone, fax, homePhone, + mobilePhone, pager, webPage, notes, useMapiRichTextFormat, defaultOrganizationDomain); + } - public ExchangeContact GetContactMailFlowSettings(string accountName) - { - return GetContactMailFlowSettingsInternal(accountName); - } + public ExchangeContact GetContactMailFlowSettings(string accountName) + { + return GetContactMailFlowSettingsInternal(accountName); + } - public void SetContactMailFlowSettings(string accountName, string[] acceptAccounts, string[] rejectAccounts, bool requireSenderAuthentication) - { - SetContactMailFlowSettingsInternal(accountName, acceptAccounts, rejectAccounts, requireSenderAuthentication); - } - #endregion + public void SetContactMailFlowSettings(string accountName, string[] acceptAccounts, string[] rejectAccounts, bool requireSenderAuthentication) + { + SetContactMailFlowSettingsInternal(accountName, acceptAccounts, rejectAccounts, requireSenderAuthentication); + } + #endregion - #region Distribution lists + #region Distribution lists public void CreateDistributionList(string organizationId, string organizationDistinguishedName, string displayName, string accountName, string name, string domain, string managedBy, string[] addressLists) { @@ -376,15 +363,15 @@ namespace WebsitePanel.Providers.HostedSolution accountName, name, domain, managedBy, addressLists); } - public void DeleteDistributionList(string accountName) - { - DeleteDistributionListInternal(accountName); - } + public void DeleteDistributionList(string accountName) + { + DeleteDistributionListInternal(accountName); + } - public ExchangeDistributionList GetDistributionListGeneralSettings(string accountName) - { - return GetDistributionListGeneralSettingsInternal(accountName); - } + public ExchangeDistributionList GetDistributionListGeneralSettings(string accountName) + { + return GetDistributionListGeneralSettingsInternal(accountName); + } public void SetDistributionListGeneralSettings(string accountName, string displayName, bool hideFromAddressBook, string managedBy, string[] members, string notes, string[] addressLists) @@ -404,10 +391,10 @@ namespace WebsitePanel.Providers.HostedSolution RemoveDistributionListMembersInternal(accountName, memberAccounts, addressLists); } - public ExchangeDistributionList GetDistributionListMailFlowSettings(string accountName) - { - return GetDistributionListMailFlowSettingsInternal(accountName); - } + public ExchangeDistributionList GetDistributionListMailFlowSettings(string accountName) + { + return GetDistributionListMailFlowSettingsInternal(accountName); + } public void SetDistributionListMailFlowSettings(string accountName, string[] acceptAccounts, string[] rejectAccounts, bool requireSenderAuthentication, string[] addressLists) @@ -415,10 +402,10 @@ namespace WebsitePanel.Providers.HostedSolution SetDistributionListMailFlowSettingsInternal(accountName, acceptAccounts, rejectAccounts, requireSenderAuthentication, addressLists); } - public ExchangeEmailAddress[] GetDistributionListEmailAddresses(string accountName) - { - return GetDistributionListEmailAddressesInternal(accountName); - } + public ExchangeEmailAddress[] GetDistributionListEmailAddresses(string accountName) + { + return GetDistributionListEmailAddressesInternal(accountName); + } public void SetDistributionListEmailAddresses(string accountName, string[] emailAddresses, string[] addressLists) { @@ -430,323 +417,323 @@ namespace WebsitePanel.Providers.HostedSolution SetDistributionListPrimaryEmailAddressInternal(accountName, emailAddress, addressLists); } - public ExchangeDistributionList GetDistributionListPermissions(string organizationId, string accountName) - { - return GetDistributionListPermissionsInternal(organizationId, accountName, null); - } + public ExchangeDistributionList GetDistributionListPermissions(string organizationId, string accountName) + { + return GetDistributionListPermissionsInternal(organizationId, accountName, null); + } public void SetDistributionListPermissions(string organizationId, string accountName, string[] sendAsAccounts, string[] sendOnBehalfAccounts, string[] addressLists) { SetDistributionListPermissionsInternal(organizationId, accountName, sendAsAccounts, sendOnBehalfAccounts, addressLists); } - #endregion + #endregion - #region Public folders - public void CreatePublicFolder(string organizationId, string securityGroup, string parentFolder, - string folderName, bool mailEnabled, string accountName, string name, string domain) - { - CreatePublicFolderInternal(organizationId, securityGroup, parentFolder, folderName, - mailEnabled, accountName, name, domain); - } + #region Public folders + public void CreatePublicFolder(string organizationId, string securityGroup, string parentFolder, + string folderName, bool mailEnabled, string accountName, string name, string domain) + { + CreatePublicFolderInternal(organizationId, securityGroup, parentFolder, folderName, + mailEnabled, accountName, name, domain); + } - public void DeletePublicFolder(string folder) - { - DeletePublicFolderInternal(folder); - } + public void DeletePublicFolder(string folder) + { + DeletePublicFolderInternal(folder); + } - public void EnableMailPublicFolder(string organizationId, string folder, string accountName, - string name, string domain) - { - EnableMailPublicFolderInternal(organizationId, folder, accountName, name, domain); - } + public void EnableMailPublicFolder(string organizationId, string folder, string accountName, + string name, string domain) + { + EnableMailPublicFolderInternal(organizationId, folder, accountName, name, domain); + } - public void DisableMailbox(string id) - { - DisableMailboxInternal(id); - } + public void DisableMailbox(string id) + { + DisableMailboxInternal(id); + } internal virtual void DisableMailboxInternal(string id) - { - ExchangeLog.LogStart("DisableMailboxIntenal"); - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + { + ExchangeLog.LogStart("DisableMailboxIntenal"); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); RemoveDevicesInternal(runSpace, id); - Command cmd = new Command("Disable-Mailbox"); - cmd.Parameters.Add("Identity", id); - cmd.Parameters.Add("Confirm", false); - ExecuteShellCommand(runSpace, cmd); - } + Command cmd = new Command("Disable-Mailbox"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("Confirm", false); + ExecuteShellCommand(runSpace, cmd); + } - finally - { + finally + { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("DisableMailboxIntenal"); - } - public void DisableMailPublicFolder(string folder) - { - DisableMailPublicFolderInternal(folder); - } + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("DisableMailboxIntenal"); + } + public void DisableMailPublicFolder(string folder) + { + DisableMailPublicFolderInternal(folder); + } - public ExchangePublicFolder GetPublicFolderGeneralSettings(string folder) - { - return GetPublicFolderGeneralSettingsInternal(folder); - } + public ExchangePublicFolder GetPublicFolderGeneralSettings(string folder) + { + return GetPublicFolderGeneralSettingsInternal(folder); + } - public void SetPublicFolderGeneralSettings(string folder, string newFolderName, - bool hideFromAddressBook, ExchangeAccount[] accounts) - { - SetPublicFolderGeneralSettingsInternal(folder, newFolderName, hideFromAddressBook, accounts); - } - public ExchangePublicFolder GetPublicFolderMailFlowSettings(string folder) - { - return GetPublicFolderMailFlowSettingsInternal(folder); - } + public void SetPublicFolderGeneralSettings(string folder, string newFolderName, + bool hideFromAddressBook, ExchangeAccount[] accounts) + { + SetPublicFolderGeneralSettingsInternal(folder, newFolderName, hideFromAddressBook, accounts); + } + public ExchangePublicFolder GetPublicFolderMailFlowSettings(string folder) + { + return GetPublicFolderMailFlowSettingsInternal(folder); + } - public void SetPublicFolderMailFlowSettings(string folder, - string[] acceptAccounts, string[] rejectAccounts, bool requireSenderAuthentication) - { - SetPublicFolderMailFlowSettingsInternal(folder, acceptAccounts, rejectAccounts, requireSenderAuthentication); - } + public void SetPublicFolderMailFlowSettings(string folder, + string[] acceptAccounts, string[] rejectAccounts, bool requireSenderAuthentication) + { + SetPublicFolderMailFlowSettingsInternal(folder, acceptAccounts, rejectAccounts, requireSenderAuthentication); + } - public ExchangeEmailAddress[] GetPublicFolderEmailAddresses(string folder) - { - return GetPublicFolderEmailAddressesInternal(folder); - } + public ExchangeEmailAddress[] GetPublicFolderEmailAddresses(string folder) + { + return GetPublicFolderEmailAddressesInternal(folder); + } - public void SetPublicFolderEmailAddresses(string folder, string[] emailAddresses) - { - SetPublicFolderEmailAddressesInternal(folder, emailAddresses); - } + public void SetPublicFolderEmailAddresses(string folder, string[] emailAddresses) + { + SetPublicFolderEmailAddressesInternal(folder, emailAddresses); + } - public void SetPublicFolderPrimaryEmailAddress(string folder, string emailAddress) - { - SetPublicFolderPrimaryEmailAddressInternal(folder, emailAddress); - } + public void SetPublicFolderPrimaryEmailAddress(string folder, string emailAddress) + { + SetPublicFolderPrimaryEmailAddressInternal(folder, emailAddress); + } - public ExchangeItemStatistics[] GetPublicFoldersStatistics(string[] folders) - { - return GetPublicFoldersStatisticsInternal(folders); - } + public ExchangeItemStatistics[] GetPublicFoldersStatistics(string[] folders) + { + return GetPublicFoldersStatisticsInternal(folders); + } - public string[] GetPublicFoldersRecursive(string parent) - { - return GetPublicFoldersRecursiveInternal(parent); - } + public string[] GetPublicFoldersRecursive(string parent) + { + return GetPublicFoldersRecursiveInternal(parent); + } - public long GetPublicFolderSize(string folder) - { - return GetPublicFolderSizeInternal(folder); - } - #endregion + public long GetPublicFolderSize(string folder) + { + return GetPublicFolderSizeInternal(folder); + } + #endregion - #region ActiveSync - public void CreateOrganizationActiveSyncPolicy(string organizationId) - { - CreateOrganizationActiveSyncPolicyInternal(organizationId); - } + #region ActiveSync + public void CreateOrganizationActiveSyncPolicy(string organizationId) + { + CreateOrganizationActiveSyncPolicyInternal(organizationId); + } - public ExchangeActiveSyncPolicy GetActiveSyncPolicy(string organizationId) - { - return GetActiveSyncPolicyInternal(organizationId); - } + public ExchangeActiveSyncPolicy GetActiveSyncPolicy(string organizationId) + { + return GetActiveSyncPolicyInternal(organizationId); + } - public void SetActiveSyncPolicy(string id, bool allowNonProvisionableDevices, bool attachmentsEnabled, - int maxAttachmentSizeKB, bool uncAccessEnabled, bool wssAccessEnabled, bool devicePasswordEnabled, - bool alphanumericPasswordRequired, bool passwordRecoveryEnabled, bool deviceEncryptionEnabled, - bool allowSimplePassword, int maxPasswordFailedAttempts, int minPasswordLength, int inactivityLockMin, - int passwordExpirationDays, int passwordHistory, int refreshInterval) - { - SetActiveSyncPolicyInternal(id, allowNonProvisionableDevices, attachmentsEnabled, - maxAttachmentSizeKB, uncAccessEnabled, wssAccessEnabled, - devicePasswordEnabled, alphanumericPasswordRequired, passwordRecoveryEnabled, - deviceEncryptionEnabled, allowSimplePassword, maxPasswordFailedAttempts, - minPasswordLength, inactivityLockMin, passwordExpirationDays, passwordHistory, refreshInterval); - } - #endregion + public void SetActiveSyncPolicy(string id, bool allowNonProvisionableDevices, bool attachmentsEnabled, + int maxAttachmentSizeKB, bool uncAccessEnabled, bool wssAccessEnabled, bool devicePasswordEnabled, + bool alphanumericPasswordRequired, bool passwordRecoveryEnabled, bool deviceEncryptionEnabled, + bool allowSimplePassword, int maxPasswordFailedAttempts, int minPasswordLength, int inactivityLockMin, + int passwordExpirationDays, int passwordHistory, int refreshInterval) + { + SetActiveSyncPolicyInternal(id, allowNonProvisionableDevices, attachmentsEnabled, + maxAttachmentSizeKB, uncAccessEnabled, wssAccessEnabled, + devicePasswordEnabled, alphanumericPasswordRequired, passwordRecoveryEnabled, + deviceEncryptionEnabled, allowSimplePassword, maxPasswordFailedAttempts, + minPasswordLength, inactivityLockMin, passwordExpirationDays, passwordHistory, refreshInterval); + } + #endregion - #region Mobile devices - public ExchangeMobileDevice[] GetMobileDevices(string accountName) - { - return GetMobileDevicesInternal(accountName); - } - public ExchangeMobileDevice GetMobileDevice(string id) - { - return GetMobileDeviceInternal(id); - } - public void WipeDataFromDevice(string id) - { - WipeDataFromDeviceInternal(id); - } - public void CancelRemoteWipeRequest(string id) - { - CancelRemoteWipeRequestInternal(id); - } - public void RemoveDevice(string id) - { - RemoveDeviceInternal(id); - } - #endregion + #region Mobile devices + public ExchangeMobileDevice[] GetMobileDevices(string accountName) + { + return GetMobileDevicesInternal(accountName); + } + public ExchangeMobileDevice GetMobileDevice(string id) + { + return GetMobileDeviceInternal(id); + } + public void WipeDataFromDevice(string id) + { + WipeDataFromDeviceInternal(id); + } + public void CancelRemoteWipeRequest(string id) + { + CancelRemoteWipeRequestInternal(id); + } + public void RemoveDevice(string id) + { + RemoveDeviceInternal(id); + } + #endregion - #endregion + #endregion - #region IHostingServiceProvider Members + #region IHostingServiceProvider Members - public override void ChangeServiceItemsState(ServiceProviderItem[] items, bool enabled) - { - foreach (ServiceProviderItem item in items) - { - if (item is Organization) - { - try - { - // make E2K7 mailboxes disabled - Organization org = item as Organization; - ChangeOrganizationState(org.DistinguishedName, enabled); - } - catch (Exception ex) - { - Log.WriteError(String.Format("Error switching '{0}' {1}", item.Name, item.GetType().Name), ex); - } - } - } - } + public override void ChangeServiceItemsState(ServiceProviderItem[] items, bool enabled) + { + foreach (ServiceProviderItem item in items) + { + if (item is Organization) + { + try + { + // make E2K7 mailboxes disabled + Organization org = item as Organization; + ChangeOrganizationState(org.DistinguishedName, enabled); + } + catch (Exception ex) + { + Log.WriteError(String.Format("Error switching '{0}' {1}", item.Name, item.GetType().Name), ex); + } + } + } + } - public override void DeleteServiceItems(ServiceProviderItem[] items) - { - foreach (ServiceProviderItem item in items) - { - try - { - if (item is Organization) - { - Organization org = item as Organization; + public override void DeleteServiceItems(ServiceProviderItem[] items) + { + foreach (ServiceProviderItem item in items) + { + try + { + if (item is Organization) + { + Organization org = item as Organization; DeleteOrganization(org.OrganizationId, org.DistinguishedName, org.GlobalAddressList, org.AddressList, org.RoomsAddressList, org.OfflineAddressBook, org.SecurityGroup, org.AddressBookPolicy); } - else if (item is ExchangeDomain) - { - DeleteAcceptedDomain(item.Name); - } - } - catch (Exception ex) - { - Log.WriteError(String.Format("Error deleting '{0}' {1}", item.Name, item.GetType().Name), ex); - } - } - } + else if (item is ExchangeDomain) + { + DeleteAcceptedDomain(item.Name); + } + } + catch (Exception ex) + { + Log.WriteError(String.Format("Error deleting '{0}' {1}", item.Name, item.GetType().Name), ex); + } + } + } - public override ServiceProviderItemDiskSpace[] GetServiceItemsDiskSpace(ServiceProviderItem[] items) - { - List itemsDiskspace = new List(); + public override ServiceProviderItemDiskSpace[] GetServiceItemsDiskSpace(ServiceProviderItem[] items) + { + List itemsDiskspace = new List(); - // update items with diskspace - foreach (ServiceProviderItem item in items) - { - if (item is Organization) - { - try - { - Log.WriteStart(String.Format("Calculating '{0}' disk space", item.Name)); - Organization org = item as Organization; - // calculate disk space - ServiceProviderItemDiskSpace diskspace = new ServiceProviderItemDiskSpace(); - diskspace.ItemId = item.Id; - diskspace.DiskSpace = CalculateOrganizationDiskSpace(org.OrganizationId, org.DistinguishedName); - itemsDiskspace.Add(diskspace); + // update items with diskspace + foreach (ServiceProviderItem item in items) + { + if (item is Organization) + { + try + { + Log.WriteStart(String.Format("Calculating '{0}' disk space", item.Name)); + Organization org = item as Organization; + // calculate disk space + ServiceProviderItemDiskSpace diskspace = new ServiceProviderItemDiskSpace(); + diskspace.ItemId = item.Id; + diskspace.DiskSpace = CalculateOrganizationDiskSpace(org.OrganizationId, org.DistinguishedName); + itemsDiskspace.Add(diskspace); - Log.WriteEnd(String.Format("Calculating '{0}' disk space", item.Name)); - } - catch (Exception ex) - { - Log.WriteError(String.Format("Error calculating '{0}' Exchange organization disk space", item.Name), ex); - } - } - } + Log.WriteEnd(String.Format("Calculating '{0}' disk space", item.Name)); + } + catch (Exception ex) + { + Log.WriteError(String.Format("Error calculating '{0}' Exchange organization disk space", item.Name), ex); + } + } + } - return itemsDiskspace.ToArray(); - } + return itemsDiskspace.ToArray(); + } - #endregion + #endregion - #region Common - private bool CheckAccountCredentialsInternal(string username, string password) - { - try - { - string path = ConvertDomainName(RootDomain); - DirectoryEntry entry = new DirectoryEntry(path, username, password); - //Bind to the native AdsObject to force authentication. - object obj = entry.NativeObject; + #region Common + private bool CheckAccountCredentialsInternal(string username, string password) + { + try + { + string path = ConvertDomainName(RootDomain); + DirectoryEntry entry = new DirectoryEntry(path, username, password); + //Bind to the native AdsObject to force authentication. + object obj = entry.NativeObject; - DirectorySearcher search = new DirectorySearcher(entry); + DirectorySearcher search = new DirectorySearcher(entry); - search.Filter = string.Format("(userPrincipalName={0})", username); - search.PropertiesToLoad.Add("cn"); - SearchResult result = search.FindOne(); + search.Filter = string.Format("(userPrincipalName={0})", username); + search.PropertiesToLoad.Add("cn"); + SearchResult result = search.FindOne(); - if (result == null) - { - return false; - } + if (result == null) + { + return false; + } - //Update the new path to the user in the directory. - path = result.Path; - string filterAttribute = (string)result.Properties["cn"][0]; - } - catch (Exception) - { - return false; - //throw new Exception("Error authenticating user. " + ex.Message); - } - return true; - } - #endregion + //Update the new path to the user in the directory. + path = result.Path; + string filterAttribute = (string)result.Properties["cn"][0]; + } + catch (Exception) + { + return false; + //throw new Exception("Error authenticating user. " + ex.Message); + } + return true; + } + #endregion - #region Organizations + #region Organizations - /// - /// Creates organization on Mail Server - /// - /// - /// + /// + /// Creates organization on Mail Server + /// + /// + /// internal virtual Organization ExtendToExchangeOrganizationInternal(string organizationId, string securityGroup, bool IsConsumer) { ExchangeLog.LogStart("CreateOrganizationInternal"); - ExchangeLog.DebugInfo(" Organization Id: {0}", organizationId); + ExchangeLog.DebugInfo(" Organization Id: {0}", organizationId); - ExchangeTransaction transaction = StartTransaction(); - Organization info = new Organization(); - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + ExchangeTransaction transaction = StartTransaction(); + Organization info = new Organization(); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); - string server = GetServerName(); - string securityGroupPath = AddADPrefix(securityGroup); + string server = GetServerName(); + string securityGroupPath = AddADPrefix(securityGroup); - //Create mail enabled organization security group - EnableMailSecurityDistributionGroup(runSpace, securityGroup, organizationId); - transaction.RegisterMailEnabledDistributionGroup(securityGroup); + //Create mail enabled organization security group + EnableMailSecurityDistributionGroup(runSpace, securityGroup, organizationId); + transaction.RegisterMailEnabledDistributionGroup(securityGroup); UpdateSecurityDistributionGroup(runSpace, securityGroup, organizationId, IsConsumer); - //create GAL - string galId = CreateGlobalAddressList(runSpace, organizationId); - transaction.RegisterNewGlobalAddressList(galId); - ExchangeLog.LogInfo(" Global Address List: {0}", galId); - UpdateGlobalAddressList(runSpace, galId, securityGroupPath); + //create GAL + string galId = CreateGlobalAddressList(runSpace, organizationId); + transaction.RegisterNewGlobalAddressList(galId); + ExchangeLog.LogInfo(" Global Address List: {0}", galId); + UpdateGlobalAddressList(runSpace, galId, securityGroupPath); - //create AL - string alId = CreateAddressList(runSpace, organizationId); - transaction.RegisterNewAddressList(alId); - ExchangeLog.LogInfo(" Address List: {0}", alId); - UpdateAddressList(runSpace, alId, securityGroupPath); + //create AL + string alId = CreateAddressList(runSpace, organizationId); + transaction.RegisterNewAddressList(alId); + ExchangeLog.LogInfo(" Address List: {0}", alId); + UpdateAddressList(runSpace, alId, securityGroupPath); //create RAL string ralId = CreateRoomsAddressList(runSpace, organizationId); @@ -754,157 +741,157 @@ namespace WebsitePanel.Providers.HostedSolution ExchangeLog.LogInfo(" Rooms Address List: {0}", ralId); UpdateAddressList(runSpace, ralId, securityGroupPath); - //create ActiveSync policy - string asId = CreateActiveSyncPolicy(runSpace, organizationId); - transaction.RegisterNewActiveSyncPolicy(asId); - ExchangeLog.LogInfo(" ActiveSync Policy: {0}", asId); + //create ActiveSync policy + string asId = CreateActiveSyncPolicy(runSpace, organizationId); + transaction.RegisterNewActiveSyncPolicy(asId); + ExchangeLog.LogInfo(" ActiveSync Policy: {0}", asId); - //storage group - string storageGroupId = CreateStorageGroup(runSpace, StorageGroup, server); - ExchangeLog.LogInfo(" Storage Group: {0}", storageGroupId); + //storage group + string storageGroupId = CreateStorageGroup(runSpace, StorageGroup, server); + ExchangeLog.LogInfo(" Storage Group: {0}", storageGroupId); - //mailbox database - string databaseId = CreateMailboxDatabase(runSpace, MailboxDatabase, storageGroupId); - ExchangeLog.LogInfo(" Database: {0}", databaseId); + //mailbox database + string databaseId = CreateMailboxDatabase(runSpace, MailboxDatabase, storageGroupId); + ExchangeLog.LogInfo(" Database: {0}", databaseId); - info.AddressList = alId; - info.GlobalAddressList = galId; + info.AddressList = alId; + info.GlobalAddressList = galId; info.RoomsAddressList = ralId; - info.OrganizationId = organizationId; - info.Database = databaseId; + info.OrganizationId = organizationId; + info.Database = databaseId; - } - catch (Exception ex) - { - ExchangeLog.LogError("CreateOrganizationInternal", ex); - RollbackTransaction(transaction); - throw; - } - finally - { - - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("CreateOrganizationInternal"); - return info; - } - - private void CheckServiceSettings() - { - if (!ServerSettings.ADEnabled) - throw new Exception("Active Directory is not enabled. Check server settings."); - if (string.IsNullOrEmpty(RootDomain)) - throw new Exception("Active Directory root domain is not specified. Check server settings."); - if (string.IsNullOrEmpty(RootOU)) - throw new Exception("Active Directory root organizational unit is not specified. Check provider settings."); - if (string.IsNullOrEmpty(PrimaryDomainController)) - throw new Exception("Primary Domain Controller is not specified. Check provider settings."); - } - - private string GetOABVirtualDirectoryInternal() - { - ExchangeLog.LogStart("GetOABVirtualDirectoryInternal"); - Runspace runSpace = null; - string virtualDir = null; - try - { - runSpace = OpenRunspace(); - - - string server = GetServerName(); - Command cmd = new Command("Get-OabVirtualDirectory"); - cmd.Parameters.Add("Server", server); - - Collection result = ExecuteShellCommand(runSpace, cmd); - - if (result.Count > 0) - { - virtualDir = ObjToString(GetPSObjectProperty(result[0], "Identity")); - } - } - finally - { - - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("GetOABVirtualDirectoryInternal"); - return virtualDir; - } - - private Organization CreateOrganizationOfflineAddressBookInternal(string organizationId, string securityGroup, string oabVirtualDir) - { - ExchangeLog.LogStart("CreateOrganizationOfflineAddressBookInternal"); - ExchangeLog.LogInfo(" Organization Id: {0}", organizationId); - ExchangeLog.LogInfo(" Security Group: {0}", securityGroup); - ExchangeLog.LogInfo(" OAB Virtual Dir: {0}", oabVirtualDir); - - ExchangeTransaction transaction = StartTransaction(); - - Organization info = new Organization(); - - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); - - - string server = GetOABGenerationServerName(); - - string securityGroupId = AddADPrefix(securityGroup); - - //create OAB - string oabId = CreateOfflineAddressBook(runSpace, organizationId, server, oabVirtualDir); - transaction.RegisterNewOfflineAddressBook(oabId); - UpdateOfflineAddressBook(runSpace, oabId, securityGroupId); - info.OfflineAddressBook = oabId; } - catch (Exception ex) - { - ExchangeLog.LogError("CreateOrganizationOfflineAddressBookInternal", ex); - RollbackTransaction(transaction); - throw; - } - finally - { + catch (Exception ex) + { + ExchangeLog.LogError("CreateOrganizationInternal", ex); + RollbackTransaction(transaction); + throw; + } + finally + { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("CreateOrganizationOfflineAddressBookInternal"); - + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("CreateOrganizationInternal"); + return info; + } - return info; - } + private void CheckServiceSettings() + { + if (!ServerSettings.ADEnabled) + throw new Exception("Active Directory is not enabled. Check server settings."); + if (string.IsNullOrEmpty(RootDomain)) + throw new Exception("Active Directory root domain is not specified. Check server settings."); + if (string.IsNullOrEmpty(RootOU)) + throw new Exception("Active Directory root organizational unit is not specified. Check provider settings."); + if (string.IsNullOrEmpty(PrimaryDomainController)) + throw new Exception("Primary Domain Controller is not specified. Check provider settings."); + } - private string GetOABGenerationServerName() - { - string ret = null; - if (!string.IsNullOrEmpty(OABGenerationServer)) - ret = OABGenerationServer; - else - ret = GetServerName(); - return ret; - } + private string GetOABVirtualDirectoryInternal() + { + ExchangeLog.LogStart("GetOABVirtualDirectoryInternal"); + Runspace runSpace = null; + string virtualDir = null; + try + { + runSpace = OpenRunspace(); - private void UpdateOrganizationOfflineAddressBookInternal(string oabId) - { - ExchangeLog.LogStart("UpdateOrganizationOfflineAddressBookInternal"); - ExchangeLog.LogInfo(" Id: {0}", oabId); - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); - Command cmd = new Command("Update-OfflineAddressBook"); - cmd.Parameters.Add("Identity", oabId); - ExecuteShellCommand(runSpace, cmd); - } - finally - { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("UpdateOrganizationOfflineAddressBookInternal"); - } - + string server = GetServerName(); + Command cmd = new Command("Get-OabVirtualDirectory"); + cmd.Parameters.Add("Server", server); + + Collection result = ExecuteShellCommand(runSpace, cmd); + + if (result.Count > 0) + { + virtualDir = ObjToString(GetPSObjectProperty(result[0], "Identity")); + } + } + finally + { + + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("GetOABVirtualDirectoryInternal"); + return virtualDir; + } + + private Organization CreateOrganizationOfflineAddressBookInternal(string organizationId, string securityGroup, string oabVirtualDir) + { + ExchangeLog.LogStart("CreateOrganizationOfflineAddressBookInternal"); + ExchangeLog.LogInfo(" Organization Id: {0}", organizationId); + ExchangeLog.LogInfo(" Security Group: {0}", securityGroup); + ExchangeLog.LogInfo(" OAB Virtual Dir: {0}", oabVirtualDir); + + ExchangeTransaction transaction = StartTransaction(); + + Organization info = new Organization(); + + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + + string server = GetOABGenerationServerName(); + + string securityGroupId = AddADPrefix(securityGroup); + + //create OAB + string oabId = CreateOfflineAddressBook(runSpace, organizationId, server, oabVirtualDir); + transaction.RegisterNewOfflineAddressBook(oabId); + UpdateOfflineAddressBook(runSpace, oabId, securityGroupId); + info.OfflineAddressBook = oabId; + } + catch (Exception ex) + { + ExchangeLog.LogError("CreateOrganizationOfflineAddressBookInternal", ex); + RollbackTransaction(transaction); + throw; + } + finally + { + + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("CreateOrganizationOfflineAddressBookInternal"); + + + return info; + } + + private string GetOABGenerationServerName() + { + string ret = null; + if (!string.IsNullOrEmpty(OABGenerationServer)) + ret = OABGenerationServer; + else + ret = GetServerName(); + return ret; + } + + private void UpdateOrganizationOfflineAddressBookInternal(string oabId) + { + ExchangeLog.LogStart("UpdateOrganizationOfflineAddressBookInternal"); + ExchangeLog.LogInfo(" Id: {0}", oabId); + + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + Command cmd = new Command("Update-OfflineAddressBook"); + cmd.Parameters.Add("Identity", oabId); + ExecuteShellCommand(runSpace, cmd); + } + finally + { + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("UpdateOrganizationOfflineAddressBookInternal"); + } + internal virtual Organization CreateOrganizationAddressBookPolicyInternal(string organizationId, string gal, string addressBook, string roomList, string oab) { Organization info = new Organization(); @@ -915,61 +902,61 @@ namespace WebsitePanel.Providers.HostedSolution internal virtual bool DeleteOrganizationInternal(string organizationId, string distinguishedName, string globalAddressList, string addressList, string roomsAddressList, string offlineAddressBook, string securityGroup, string addressBookPolicy) { - ExchangeLog.LogStart("DeleteOrganizationInternal"); - bool ret = true; + ExchangeLog.LogStart("DeleteOrganizationInternal"); + bool ret = true; - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); - string ou = ConvertADPathToCanonicalName(distinguishedName); + string ou = ConvertADPathToCanonicalName(distinguishedName); - //organization cannot be deleted when mailboxes, contacts or distribution groups exist - /*bool canDelete = CanDeleteOrganization(runSpace, organizationId, ou); - if (!canDelete) - { - throw new Exception("Organization cannot be deleted as it contains mailboxes, " + - "contacts, distribution lists or public folders.\nDelete organization items first."); - }*/ + //organization cannot be deleted when mailboxes, contacts or distribution groups exist + /*bool canDelete = CanDeleteOrganization(runSpace, organizationId, ou); + if (!canDelete) + { + throw new Exception("Organization cannot be deleted as it contains mailboxes, " + + "contacts, distribution lists or public folders.\nDelete organization items first."); + }*/ - if (!DeleteOrganizationMailboxes(runSpace, ou)) - ret = false; + if (!DeleteOrganizationMailboxes(runSpace, ou)) + ret = false; - if (!DeleteOrganizationContacts(runSpace, ou)) - ret = false; + if (!DeleteOrganizationContacts(runSpace, ou)) + ret = false; - if (!DeleteOrganizationDistributionLists(runSpace, ou)) - ret = false; + if (!DeleteOrganizationDistributionLists(runSpace, ou)) + ret = false; - if (!DeleteOrganizationPublicFolders(runSpace, organizationId)) - ret = false; + if (!DeleteOrganizationPublicFolders(runSpace, organizationId)) + ret = false; - //delete OAB - try - { - if (!string.IsNullOrEmpty(offlineAddressBook)) - DeleteOfflineAddressBook(runSpace, offlineAddressBook); - } - catch (Exception ex) - { - ret = false; - ExchangeLog.LogError("Could not delete Offline Address Book " + offlineAddressBook, ex); - } + //delete OAB + try + { + if (!string.IsNullOrEmpty(offlineAddressBook)) + DeleteOfflineAddressBook(runSpace, offlineAddressBook); + } + catch (Exception ex) + { + ret = false; + ExchangeLog.LogError("Could not delete Offline Address Book " + offlineAddressBook, ex); + } - //delete AL - try - { - if (!string.IsNullOrEmpty(addressList)) - DeleteAddressList(runSpace, addressList); - } - catch (Exception ex) - { - ret = false; - ExchangeLog.LogError("Could not delete Address List " + addressList, ex); - } + //delete AL + try + { + if (!string.IsNullOrEmpty(addressList)) + DeleteAddressList(runSpace, addressList); + } + catch (Exception ex) + { + ret = false; + ExchangeLog.LogError("Could not delete Address List " + addressList, ex); + } //delete RAL (Rooms Address List) try @@ -983,404 +970,404 @@ namespace WebsitePanel.Providers.HostedSolution ExchangeLog.LogError("Could not delete Rooms Address List " + roomsAddressList, ex); } - //delete GAL - try - { - if (!string.IsNullOrEmpty(globalAddressList)) - DeleteGlobalAddressList(runSpace, globalAddressList); - } - catch (Exception ex) - { - ret = false; - ExchangeLog.LogError("Could not delete Global Address List " + globalAddressList, ex); - } + //delete GAL + try + { + if (!string.IsNullOrEmpty(globalAddressList)) + DeleteGlobalAddressList(runSpace, globalAddressList); + } + catch (Exception ex) + { + ret = false; + ExchangeLog.LogError("Could not delete Global Address List " + globalAddressList, ex); + } - //delete ActiveSync policy - try - { - DeleteActiveSyncPolicy(runSpace, organizationId); - } - catch (Exception ex) - { - ret = false; - ExchangeLog.LogError("Could not delete ActiveSyncPolicy " + organizationId, ex); - } + //delete ActiveSync policy + try + { + DeleteActiveSyncPolicy(runSpace, organizationId); + } + catch (Exception ex) + { + ret = false; + ExchangeLog.LogError("Could not delete ActiveSyncPolicy " + organizationId, ex); + } - //disable mail security distribution group - try - { - DisableMailSecurityDistributionGroup(runSpace, securityGroup); - } - catch (Exception ex) - { - ret = false; - ExchangeLog.LogError("Could not disable mail security distribution group " + securityGroup, ex); - } - } - catch (Exception ex) - { - ret = false; - ExchangeLog.LogError("DeleteOrganizationInternal", ex); - throw; - } - finally - { + //disable mail security distribution group + try + { + DisableMailSecurityDistributionGroup(runSpace, securityGroup); + } + catch (Exception ex) + { + ret = false; + ExchangeLog.LogError("Could not disable mail security distribution group " + securityGroup, ex); + } + } + catch (Exception ex) + { + ret = false; + ExchangeLog.LogError("DeleteOrganizationInternal", ex); + throw; + } + finally + { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("DeleteOrganizationInternal"); - return ret; - } + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("DeleteOrganizationInternal"); + return ret; + } - private bool CanDeleteOrganization(Runspace runSpace, string organizationId, string ou) - { - ExchangeLog.LogStart("CanDeleteOrganization"); - bool ret = true; + private bool CanDeleteOrganization(Runspace runSpace, string organizationId, string ou) + { + ExchangeLog.LogStart("CanDeleteOrganization"); + bool ret = true; - Command cmd = new Command("Get-Mailbox"); - cmd.Parameters.Add("OrganizationalUnit", ou); - Collection result = ExecuteShellCommand(runSpace, cmd); - if (result != null && result.Count > 0) - ret = false; + Command cmd = new Command("Get-Mailbox"); + cmd.Parameters.Add("OrganizationalUnit", ou); + Collection result = ExecuteShellCommand(runSpace, cmd); + if (result != null && result.Count > 0) + ret = false; - if (ret) - { - cmd = new Command("Get-MailContact"); - cmd.Parameters.Add("OrganizationalUnit", ou); - result = ExecuteShellCommand(runSpace, cmd); - if (result != null && result.Count > 0) - ret = false; - } + if (ret) + { + cmd = new Command("Get-MailContact"); + cmd.Parameters.Add("OrganizationalUnit", ou); + result = ExecuteShellCommand(runSpace, cmd); + if (result != null && result.Count > 0) + ret = false; + } - if (ret) - { - cmd = new Command("Get-DistributionGroup"); - cmd.Parameters.Add("OrganizationalUnit", ou); - cmd.Parameters.Add("RecipientTypeDetails", "MailUniversalDistributionGroup"); - result = ExecuteShellCommand(runSpace, cmd); - if (result != null && result.Count > 0) - ret = false; - } + if (ret) + { + cmd = new Command("Get-DistributionGroup"); + cmd.Parameters.Add("OrganizationalUnit", ou); + cmd.Parameters.Add("RecipientTypeDetails", "MailUniversalDistributionGroup"); + result = ExecuteShellCommand(runSpace, cmd); + if (result != null && result.Count > 0) + ret = false; + } - if (ret) - { - cmd = new Command("Get-PublicFolder"); - cmd.Parameters.Add("Identity", "\\" + organizationId); - cmd.Parameters.Add("GetChildren", new SwitchParameter(true)); - if (!string.IsNullOrEmpty(PublicFolderServer)) - cmd.Parameters.Add("Server", PublicFolderServer); + if (ret) + { + cmd = new Command("Get-PublicFolder"); + cmd.Parameters.Add("Identity", "\\" + organizationId); + cmd.Parameters.Add("GetChildren", new SwitchParameter(true)); + if (!string.IsNullOrEmpty(PublicFolderServer)) + cmd.Parameters.Add("Server", PublicFolderServer); - result = ExecuteShellCommand(runSpace, cmd); - if (result != null && result.Count > 0) - ret = false; - } + result = ExecuteShellCommand(runSpace, cmd); + if (result != null && result.Count > 0) + ret = false; + } - ExchangeLog.LogEnd("CanDeleteOrganization"); - return ret; - } + ExchangeLog.LogEnd("CanDeleteOrganization"); + return ret; + } - internal bool DeleteOrganizationMailboxes(Runspace runSpace, string ou) - { - ExchangeLog.LogStart("DeleteOrganizationMailboxes"); - bool ret = true; + internal bool DeleteOrganizationMailboxes(Runspace runSpace, string ou) + { + ExchangeLog.LogStart("DeleteOrganizationMailboxes"); + bool ret = true; - Command cmd = new Command("Get-Mailbox"); - cmd.Parameters.Add("OrganizationalUnit", ou); - Collection result = ExecuteShellCommand(runSpace, cmd); - if (result != null && result.Count > 0) - { - foreach (PSObject obj in result) - { - string id = null; - try - { - id = ObjToString(GetPSObjectProperty(obj, "Identity")); + Command cmd = new Command("Get-Mailbox"); + cmd.Parameters.Add("OrganizationalUnit", ou); + Collection result = ExecuteShellCommand(runSpace, cmd); + if (result != null && result.Count > 0) + { + foreach (PSObject obj in result) + { + string id = null; + try + { + id = ObjToString(GetPSObjectProperty(obj, "Identity")); RemoveDevicesInternal(runSpace, id); - RemoveMailbox(runSpace, id); - } - catch (Exception ex) - { - ret = false; - ExchangeLog.LogError(string.Format("Can't delete mailbox {0}", id), ex); - } - } - } + RemoveMailbox(runSpace, id); + } + catch (Exception ex) + { + ret = false; + ExchangeLog.LogError(string.Format("Can't delete mailbox {0}", id), ex); + } + } + } - ExchangeLog.LogEnd("DeleteOrganizationMailboxes"); - return ret; - } + ExchangeLog.LogEnd("DeleteOrganizationMailboxes"); + return ret; + } - internal bool DeleteOrganizationContacts(Runspace runSpace, string ou) - { - ExchangeLog.LogStart("DeleteOrganizationContacts"); - bool ret = true; + internal bool DeleteOrganizationContacts(Runspace runSpace, string ou) + { + ExchangeLog.LogStart("DeleteOrganizationContacts"); + bool ret = true; - Command cmd = new Command("Get-MailContact"); - cmd.Parameters.Add("OrganizationalUnit", ou); - Collection result = ExecuteShellCommand(runSpace, cmd); - if (result != null && result.Count > 0) - { - foreach (PSObject obj in result) - { - string id = null; - try - { - id = ObjToString(GetPSObjectProperty(obj, "Identity")); - RemoveContact(runSpace, id); - } - catch (Exception ex) - { - ret = false; - ExchangeLog.LogError(string.Format("Can't delete contact {0}", id), ex); - } - } - } + Command cmd = new Command("Get-MailContact"); + cmd.Parameters.Add("OrganizationalUnit", ou); + Collection result = ExecuteShellCommand(runSpace, cmd); + if (result != null && result.Count > 0) + { + foreach (PSObject obj in result) + { + string id = null; + try + { + id = ObjToString(GetPSObjectProperty(obj, "Identity")); + RemoveContact(runSpace, id); + } + catch (Exception ex) + { + ret = false; + ExchangeLog.LogError(string.Format("Can't delete contact {0}", id), ex); + } + } + } - ExchangeLog.LogEnd("DeleteOrganizationContacts"); - return ret; - } + ExchangeLog.LogEnd("DeleteOrganizationContacts"); + return ret; + } - internal bool DeleteOrganizationDistributionLists(Runspace runSpace, string ou) - { - ExchangeLog.LogStart("DeleteOrganizationDistributionLists"); - bool ret = true; + internal bool DeleteOrganizationDistributionLists(Runspace runSpace, string ou) + { + ExchangeLog.LogStart("DeleteOrganizationDistributionLists"); + bool ret = true; - Command cmd = new Command("Get-DistributionGroup"); - cmd.Parameters.Add("OrganizationalUnit", ou); - cmd.Parameters.Add("RecipientTypeDetails", "MailUniversalDistributionGroup"); - Collection result = ExecuteShellCommand(runSpace, cmd); - if (result != null && result.Count > 0) - { - foreach (PSObject obj in result) - { - string id = null; - try - { - id = ObjToString(GetPSObjectProperty(obj, "Identity")); - RemoveDistributionGroup(runSpace, id); - } - catch (Exception ex) - { - ret = false; - ExchangeLog.LogError(string.Format("Can't delete distribution list {0}", id), ex); - } - } - } + Command cmd = new Command("Get-DistributionGroup"); + cmd.Parameters.Add("OrganizationalUnit", ou); + cmd.Parameters.Add("RecipientTypeDetails", "MailUniversalDistributionGroup"); + Collection result = ExecuteShellCommand(runSpace, cmd); + if (result != null && result.Count > 0) + { + foreach (PSObject obj in result) + { + string id = null; + try + { + id = ObjToString(GetPSObjectProperty(obj, "Identity")); + RemoveDistributionGroup(runSpace, id); + } + catch (Exception ex) + { + ret = false; + ExchangeLog.LogError(string.Format("Can't delete distribution list {0}", id), ex); + } + } + } - ExchangeLog.LogEnd("DeleteOrganizationDistributionLists"); - return ret; - } + ExchangeLog.LogEnd("DeleteOrganizationDistributionLists"); + return ret; + } - private bool DeleteOrganizationPublicFolders(Runspace runSpace, string organizationId) - { - ExchangeLog.LogStart("DeleteOrganizationPublicFolders"); - bool ret = true; + private bool DeleteOrganizationPublicFolders(Runspace runSpace, string organizationId) + { + ExchangeLog.LogStart("DeleteOrganizationPublicFolders"); + bool ret = true; - //Delete public folders. - string publicFolder = "\\" + organizationId; - try - { - RemovePublicFolder(runSpace, publicFolder); - } - catch (Exception ex) - { - ret = false; - ExchangeLog.LogError(string.Format("Can't delete public folder {0}", publicFolder), ex); - } - ExchangeLog.LogEnd("DeleteOrganizationPublicFolders"); - return ret; - } + //Delete public folders. + string publicFolder = "\\" + organizationId; + try + { + RemovePublicFolder(runSpace, publicFolder); + } + catch (Exception ex) + { + ret = false; + ExchangeLog.LogError(string.Format("Can't delete public folder {0}", publicFolder), ex); + } + ExchangeLog.LogEnd("DeleteOrganizationPublicFolders"); + return ret; + } - private void SetOrganizationStorageLimitsInternal(string organizationDistinguishedName, long issueWarningKB, - long prohibitSendKB, long prohibitSendReceiveKB, int keepDeletedItemsDays) - { - ExchangeLog.LogStart("SetOrganizationStorageLimitsInternal"); - ExchangeLog.DebugInfo("Organization Id: {0}", organizationDistinguishedName); + private void SetOrganizationStorageLimitsInternal(string organizationDistinguishedName, long issueWarningKB, + long prohibitSendKB, long prohibitSendReceiveKB, int keepDeletedItemsDays) + { + ExchangeLog.LogStart("SetOrganizationStorageLimitsInternal"); + ExchangeLog.DebugInfo("Organization Id: {0}", organizationDistinguishedName); - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); - string org = ConvertADPathToCanonicalName(organizationDistinguishedName); + string org = ConvertADPathToCanonicalName(organizationDistinguishedName); - Unlimited issueWarningQuota = ConvertKBToUnlimited(issueWarningKB); - Unlimited prohibitSendQuota = ConvertKBToUnlimited(prohibitSendKB); - Unlimited prohibitSendReceiveQuota = ConvertKBToUnlimited(prohibitSendReceiveKB); - EnhancedTimeSpan retainDeletedItemsFor = ConvertDaysToEnhancedTimeSpan(keepDeletedItemsDays); + Unlimited issueWarningQuota = ConvertKBToUnlimited(issueWarningKB); + Unlimited prohibitSendQuota = ConvertKBToUnlimited(prohibitSendKB); + Unlimited prohibitSendReceiveQuota = ConvertKBToUnlimited(prohibitSendReceiveKB); + EnhancedTimeSpan retainDeletedItemsFor = ConvertDaysToEnhancedTimeSpan(keepDeletedItemsDays); - Command cmd = new Command("Get-Mailbox"); - cmd.Parameters.Add("OrganizationalUnit", org); - Collection result = ExecuteShellCommand(runSpace, cmd); + Command cmd = new Command("Get-Mailbox"); + cmd.Parameters.Add("OrganizationalUnit", org); + Collection result = ExecuteShellCommand(runSpace, cmd); - foreach (PSObject obj in result) - { - string id = ObjToString(GetPSObjectProperty(obj, "Identity")); - cmd = new Command("Set-Mailbox"); - cmd.Parameters.Add("Identity", id); - cmd.Parameters.Add("IssueWarningQuota", issueWarningQuota); - cmd.Parameters.Add("ProhibitSendQuota", prohibitSendQuota); - cmd.Parameters.Add("ProhibitSendReceiveQuota", prohibitSendReceiveQuota); - cmd.Parameters.Add("RetainDeletedItemsFor", retainDeletedItemsFor); - ExecuteShellCommand(runSpace, cmd); - } - } - finally - { + foreach (PSObject obj in result) + { + string id = ObjToString(GetPSObjectProperty(obj, "Identity")); + cmd = new Command("Set-Mailbox"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("IssueWarningQuota", issueWarningQuota); + cmd.Parameters.Add("ProhibitSendQuota", prohibitSendQuota); + cmd.Parameters.Add("ProhibitSendReceiveQuota", prohibitSendReceiveQuota); + cmd.Parameters.Add("RetainDeletedItemsFor", retainDeletedItemsFor); + ExecuteShellCommand(runSpace, cmd); + } + } + finally + { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("SetOrganizationStorageLimitsInternal"); - } + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("SetOrganizationStorageLimitsInternal"); + } - private ExchangeItemStatistics[] GetMailboxesStatisticsInternal(string organizationDistinguishedName) - { - ExchangeLog.LogStart("GetMailboxesStatisticsInternal"); - ExchangeLog.DebugInfo("Organization Id: {0}", organizationDistinguishedName); + private ExchangeItemStatistics[] GetMailboxesStatisticsInternal(string organizationDistinguishedName) + { + ExchangeLog.LogStart("GetMailboxesStatisticsInternal"); + ExchangeLog.DebugInfo("Organization Id: {0}", organizationDistinguishedName); - List ret = new List(); + List ret = new List(); - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); - string org = ConvertADPathToCanonicalName(organizationDistinguishedName); + string org = ConvertADPathToCanonicalName(organizationDistinguishedName); - Command cmd = new Command("Get-Mailbox"); - cmd.Parameters.Add("OrganizationalUnit", org); - Collection result = ExecuteShellCommand(runSpace, cmd); + Command cmd = new Command("Get-Mailbox"); + cmd.Parameters.Add("OrganizationalUnit", org); + Collection result = ExecuteShellCommand(runSpace, cmd); - foreach (PSObject obj in result) - { - string id = ObjToString(GetPSObjectProperty(obj, "Identity")); + foreach (PSObject obj in result) + { + string id = ObjToString(GetPSObjectProperty(obj, "Identity")); - cmd = new Command("Get-MailboxStatistics"); - cmd.Parameters.Add("Identity", id); - result = ExecuteShellCommand(runSpace, cmd); - if (result != null && result.Count > 0) - { - PSObject mailbox = result[0]; - ExchangeItemStatistics info = new ExchangeItemStatistics(); - info.ItemName = (string)GetPSObjectProperty(mailbox, "DisplayName"); - Unlimited totalItemSize = - (Unlimited)GetPSObjectProperty(mailbox, "TotalItemSize"); - info.TotalSizeMB = ConvertUnlimitedToMB(totalItemSize); - uint? itemCount = (uint?)GetPSObjectProperty(mailbox, "ItemCount"); - info.TotalItems = ConvertNullableToInt32(itemCount); - DateTime? lastLogoffTime = (DateTime?)GetPSObjectProperty(mailbox, "LastLogoffTime"); - DateTime? lastLogonTime = (DateTime?)GetPSObjectProperty(mailbox, "LastLogonTime"); - info.LastLogoff = ConvertNullableToDateTime(lastLogoffTime); - info.LastLogon = ConvertNullableToDateTime(lastLogonTime); - ret.Add(info); - } - } - } - finally - { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("GetMailboxesStatisticsInternal"); - return ret.ToArray(); - } + cmd = new Command("Get-MailboxStatistics"); + cmd.Parameters.Add("Identity", id); + result = ExecuteShellCommand(runSpace, cmd); + if (result != null && result.Count > 0) + { + PSObject mailbox = result[0]; + ExchangeItemStatistics info = new ExchangeItemStatistics(); + info.ItemName = (string)GetPSObjectProperty(mailbox, "DisplayName"); + Unlimited totalItemSize = + (Unlimited)GetPSObjectProperty(mailbox, "TotalItemSize"); + info.TotalSizeMB = ConvertUnlimitedToMB(totalItemSize); + uint? itemCount = (uint?)GetPSObjectProperty(mailbox, "ItemCount"); + info.TotalItems = ConvertNullableToInt32(itemCount); + DateTime? lastLogoffTime = (DateTime?)GetPSObjectProperty(mailbox, "LastLogoffTime"); + DateTime? lastLogonTime = (DateTime?)GetPSObjectProperty(mailbox, "LastLogonTime"); + info.LastLogoff = ConvertNullableToDateTime(lastLogoffTime); + info.LastLogon = ConvertNullableToDateTime(lastLogonTime); + ret.Add(info); + } + } + } + finally + { + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("GetMailboxesStatisticsInternal"); + return ret.ToArray(); + } - private void ChangeOrganizationState(string organizationDistinguishedName, bool enabled) - { - ExchangeLog.LogStart("ChangeOrganizationState"); - ExchangeLog.DebugInfo("Organization: {0}", organizationDistinguishedName); + private void ChangeOrganizationState(string organizationDistinguishedName, bool enabled) + { + ExchangeLog.LogStart("ChangeOrganizationState"); + ExchangeLog.DebugInfo("Organization: {0}", organizationDistinguishedName); - Runspace runSpace = null; - try - { - string ouName = ConvertADPathToCanonicalName(organizationDistinguishedName); - runSpace = OpenRunspace(); + Runspace runSpace = null; + try + { + string ouName = ConvertADPathToCanonicalName(organizationDistinguishedName); + runSpace = OpenRunspace(); - Command cmd = new Command("Get-Mailbox"); - cmd.Parameters.Add("OrganizationalUnit", ouName); - cmd.Parameters.Add("Filter", "CustomAttribute2 -ne 'disabled'"); - Collection result = ExecuteShellCommand(runSpace, cmd); - foreach (PSObject obj in result) - { - string id = (string)GetPSObjectProperty(obj, "DistinguishedName"); - ChangeMailboxState(id, enabled); - } - } - finally - { + Command cmd = new Command("Get-Mailbox"); + cmd.Parameters.Add("OrganizationalUnit", ouName); + cmd.Parameters.Add("Filter", "CustomAttribute2 -ne 'disabled'"); + Collection result = ExecuteShellCommand(runSpace, cmd); + foreach (PSObject obj in result) + { + string id = (string)GetPSObjectProperty(obj, "DistinguishedName"); + ChangeMailboxState(id, enabled); + } + } + finally + { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("ChangeOrganizationState"); - } + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("ChangeOrganizationState"); + } - private long CalculateOrganizationDiskSpace(string organizationId, string organizationDistinguishedName) - { - ExchangeLog.LogStart("CalculateOrganizationDiskSpace"); - ExchangeLog.DebugInfo("Organization Id: {0}", organizationId); + private long CalculateOrganizationDiskSpace(string organizationId, string organizationDistinguishedName) + { + ExchangeLog.LogStart("CalculateOrganizationDiskSpace"); + ExchangeLog.DebugInfo("Organization Id: {0}", organizationId); - long size = 0; - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + long size = 0; + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); - size += CalculateMailboxDiskSpace(runSpace, organizationDistinguishedName); - size += CalculatePublicFolderDiskSpace(runSpace, "\\" + organizationId); - } - finally - { + size += CalculateMailboxDiskSpace(runSpace, organizationDistinguishedName); + size += CalculatePublicFolderDiskSpace(runSpace, "\\" + organizationId); + } + finally + { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("CalculateOrganizationDiskSpace"); - return size; - } + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("CalculateOrganizationDiskSpace"); + return size; + } - private long CalculateMailboxDiskSpace(Runspace runSpace, string organizationDistinguishedName) - { - ExchangeLog.LogStart("CalculateMailboxDiskSpace"); - ExchangeLog.DebugInfo("Organization DN: {0}", organizationDistinguishedName); + private long CalculateMailboxDiskSpace(Runspace runSpace, string organizationDistinguishedName) + { + ExchangeLog.LogStart("CalculateMailboxDiskSpace"); + ExchangeLog.DebugInfo("Organization DN: {0}", organizationDistinguishedName); - long size = 0; + long size = 0; - string org = ConvertADPathToCanonicalName(organizationDistinguishedName); + string org = ConvertADPathToCanonicalName(organizationDistinguishedName); - Command cmd = new Command("Get-Mailbox"); - cmd.Parameters.Add("OrganizationalUnit", org); - Collection result = ExecuteShellCommand(runSpace, cmd); + Command cmd = new Command("Get-Mailbox"); + cmd.Parameters.Add("OrganizationalUnit", org); + Collection result = ExecuteShellCommand(runSpace, cmd); - foreach (PSObject obj in result) - { - string id = ObjToString(GetPSObjectProperty(obj, "Identity")); - cmd = new Command("Get-MailboxStatistics"); - cmd.Parameters.Add("Identity", id); - result = ExecuteShellCommand(runSpace, cmd); - if (result != null && result.Count > 0) - { - Unlimited totalItemSize = - (Unlimited)GetPSObjectProperty(result[0], "TotalItemSize"); - size += ConvertUnlimitedToBytes(totalItemSize); - } - } - ExchangeLog.LogEnd("CalculateMailboxDiskSpace"); - return size; - } + foreach (PSObject obj in result) + { + string id = ObjToString(GetPSObjectProperty(obj, "Identity")); + cmd = new Command("Get-MailboxStatistics"); + cmd.Parameters.Add("Identity", id); + result = ExecuteShellCommand(runSpace, cmd); + if (result != null && result.Count > 0) + { + Unlimited totalItemSize = + (Unlimited)GetPSObjectProperty(result[0], "TotalItemSize"); + size += ConvertUnlimitedToBytes(totalItemSize); + } + } + ExchangeLog.LogEnd("CalculateMailboxDiskSpace"); + return size; + } - internal virtual long CalculatePublicFolderDiskSpace(Runspace runSpace, string folder) - { - ExchangeLog.LogStart("CalculatePublicFolderDiskSpace"); - ExchangeLog.DebugInfo("Folder: {0}", folder); + internal virtual long CalculatePublicFolderDiskSpace(Runspace runSpace, string folder) + { + ExchangeLog.LogStart("CalculatePublicFolderDiskSpace"); + ExchangeLog.DebugInfo("Folder: {0}", folder); - long size = 0; + long size = 0; Command cmd = new Command("Get-PublicFolderDatabase"); - Collection result = ExecuteShellCommand(runSpace, cmd); + Collection result = ExecuteShellCommand(runSpace, cmd); if (result != null && result.Count > 0) { cmd = new Command("Get-PublicFolderStatistics"); @@ -1410,382 +1397,382 @@ namespace WebsitePanel.Providers.HostedSolution } else size = 0; - ExchangeLog.LogEnd("CalculatePublicFolderDiskSpace"); - return size; - } - - #endregion - - #region Mailboxes - - - private void SetExtendedRights(Runspace runSpace, string identity, string user, string rights) - { - ExchangeLog.LogStart("SetExtendedRights"); - - Command cmd = new Command("Add-ADPermission"); - cmd.Parameters.Add("Identity", identity); - cmd.Parameters.Add("User", user); - - cmd.Parameters.Add("ExtendedRights", rights); - ExecuteShellCommand(runSpace, cmd); - - ExchangeLog.LogEnd("SetExtendedRights"); - } - - private void SetMailboxPermission(Runspace runSpace, string accountName, string user, string accessRights) - { - ExchangeLog.LogStart("SetMailboxPermission"); - - Command cmd = new Command("Add-MailboxPermission"); - cmd.Parameters.Add("Identity", accountName); - cmd.Parameters.Add("User", user); - cmd.Parameters.Add("AccessRights", accessRights); - ExecuteShellCommand(runSpace, cmd); - - ExchangeLog.LogEnd("SetMailboxPermission"); - } - - private ExchangeAccount[] GetMailboxSendAsAccounts(Runspace runSpace, string organizationId, string accountName) - { - ExchangeLog.LogStart("GetMailboxSendAsAccounts"); - - string cn = GetMailboxCommonName(runSpace, accountName); - ExchangeAccount[] ret = GetSendAsAccounts(runSpace, organizationId, cn); - - ExchangeLog.LogEnd("GetMailboxSendAsAccounts"); - return ret; - } - - private ExchangeAccount[] GetSendAsAccounts(Runspace runSpace, string organizationId, string accountId) - { - ExchangeLog.LogStart("GetSendAsAccounts"); - - Command cmd = new Command("Get-ADPermission"); - cmd.Parameters.Add("Identity", accountId); - Collection results = ExecuteShellCommand(runSpace, cmd); - List accounts = new List(); - foreach (PSObject current in results) - { - string user = GetPSObjectProperty(current, "User").ToString(); - - Array extendedRights = GetPSObjectProperty(current, "ExtendedRights") as Array; - - if (extendedRights != null) - { - foreach (object obj in extendedRights) - { - string strRightName = obj.ToString(); - if (string.Compare(strRightName, "Send-as", true) == 0) - { - ExchangeAccount account = GetOrganizationAccount(runSpace, organizationId, user); - if (account != null) - accounts.Add(account); - } - } - } - } - - ExchangeLog.LogEnd("GetSendAsAccounts"); - return accounts.ToArray(); - } - - - private ExchangeAccount[] GetMailBoxFullAccessAcounts(Runspace runSpace, string organizationId, string accountName) - { - ExchangeLog.LogStart("GetMailBoxFullAccessAcounts"); - - Command cmd = new Command("Get-MailboxPermission"); - cmd.Parameters.Add("Identity", accountName); - Collection results = ExecuteShellCommand(runSpace, cmd); - - - List accounts = new List(); - foreach (PSObject current in results) - { - string user = GetPSObjectProperty(current, "User").ToString(); - - Array accessRights = GetPSObjectProperty(current, "AccessRights") as Array; - - if (accessRights != null) - { - foreach (object obj in accessRights) - { - string strRightName = obj.ToString(); - if (string.Compare(strRightName, "FullAccess", true) == 0) - { - ExchangeAccount account = GetOrganizationAccount(runSpace, organizationId, user); - if (account != null) - accounts.Add(account); - } - } - } - } - - ExchangeLog.LogEnd("GetMailBoxFullAccessAcounts"); - return accounts.ToArray(); - } - - private ExchangeMailbox GetMailboxPermissionsInternal(string organizationId, string accountName, Runspace runspace) - { - ExchangeLog.LogStart("GetMailboxPermissionsInternal"); - - if (string.IsNullOrEmpty(accountName)) - throw new ArgumentNullException("accountName"); - - ExchangeMailbox exchangeMailbox = null; - bool closeRunspace = false; - - try - { - if (runspace == null) - { - runspace = OpenRunspace(); - closeRunspace = true; - } - - exchangeMailbox = new ExchangeMailbox(); - exchangeMailbox.FullAccessAccounts = GetMailBoxFullAccessAcounts(runspace, organizationId, accountName); - exchangeMailbox.SendAsAccounts = GetMailboxSendAsAccounts(runspace, organizationId, accountName); - } - catch (Exception ex) - { - ExchangeLog.LogError(ex); - throw ex; - } - finally - { - if (closeRunspace) - CloseRunspace(runspace); - } - - ExchangeLog.LogEnd("GetMailboxPermissionsInternal"); - return exchangeMailbox; - } - - - private void SetSendAsPermissions(Runspace runSpace, ExchangeAccount[] existingAccounts, string accountId, string[] accounts) - { - ExchangeLog.LogStart("SetSendAsPermissions"); - - if (string.IsNullOrEmpty(accountId)) - throw new ArgumentNullException("accountId"); - - if (accounts == null) - throw new ArgumentNullException("accounts"); - - ExchangeTransaction transaction = null; - try - { - transaction = StartTransaction(); - - string[] resAccounts = MergeADPermission(runSpace, existingAccounts, accountId, accounts, transaction); - foreach (string id in resAccounts) - { - SetExtendedRights(runSpace, accountId, id, "Send-as"); - transaction.AddSendAsPermission(accountId, id); - } - - } - catch (Exception) - { - RollbackTransaction(transaction); - throw; - } - ExchangeLog.LogEnd("SetSendAsPermissions"); - } - - - private void SetMailboxPermissionsInternal(string organizationId, string accountName, string[] sendAsAccounts, string[] fullAccessAccounts) - { - ExchangeLog.LogStart("SetMailboxPermissionsInternal"); - - if (string.IsNullOrEmpty(accountName)) - throw new ArgumentNullException("accountName"); - - if (sendAsAccounts == null) - throw new ArgumentNullException("sendAsAccounts"); - - - if (fullAccessAccounts == null) - throw new ArgumentNullException("fullAccessAccounts"); - - Runspace runSpace = null; - try - { - - runSpace = OpenRunspace(); - string cn = GetMailboxCommonName(runSpace, accountName); - ExchangeMailbox mailbox = GetMailboxPermissionsInternal(organizationId, accountName, runSpace); - SetSendAsPermissions(runSpace, mailbox.SendAsAccounts, cn, sendAsAccounts); - SetMailboxFullAccessPermissions(runSpace, mailbox.FullAccessAccounts, accountName, fullAccessAccounts); - - } - catch (Exception ex) - { - ExchangeLog.LogError(ex); - - throw; - } - finally - { - CloseRunspace(runSpace); - } - - ExchangeLog.LogEnd("SetMailboxPermissionsInternal"); - } - - - internal void RemoveMailboxAccessPermission(Runspace runSpace, string accountName, string account, string accessRights) - { - ExchangeLog.LogStart("RemoveMailboxFullAccessPermission"); - - Command cmd = new Command("Remove-MailboxPermission"); - cmd.Parameters.Add("Identity", accountName); - cmd.Parameters.Add("User", account); - cmd.Parameters.Add("AccessRights", accessRights); - cmd.Parameters.Add("Confirm", false); - ExecuteShellCommand(runSpace, cmd); - - ExchangeLog.LogEnd("RemoveMailboxFullAccessPermission"); - } - - - private string[] MergeMailboxFullAccessPermissions(Runspace runSpace, ExchangeAccount[] existingAccounts, string accountName, string[] newAccounts, ExchangeTransaction transaction) - { - ExchangeLog.LogStart("MergeMailboxFullAccessPermissions"); - List temp = new List(newAccounts); - - Array.Sort(newAccounts); - foreach (ExchangeAccount exist in existingAccounts) - { - if (Array.BinarySearch(newAccounts, exist.AccountName, StringComparer.Create(CultureInfo.InvariantCulture, true)) >= 0) - { - temp.Remove(exist.AccountName); - continue; - } - - RemoveMailboxAccessPermission(runSpace, accountName, exist.AccountName, "FullAccess"); - transaction.RemoveMailboxFullAccessPermission(accountName, exist.AccountName); - } - - ExchangeLog.LogEnd("MergeMailboxFullAccessPermissions"); - return temp.ToArray(); - } - - - private void SetMailboxFullAccessPermissions(Runspace runSpace, ExchangeAccount[] existingAccounts, string accountName, string[] accounts) - { - ExchangeLog.LogStart("SetMailboxFullAccessPermissions"); - - if (string.IsNullOrEmpty(accountName)) - throw new ArgumentNullException("accountName"); - - if (accounts == null) - throw new ArgumentNullException("accounts"); - - ExchangeTransaction transaction = StartTransaction(); - - try - { - - string[] resAccounts = MergeMailboxFullAccessPermissions(runSpace, existingAccounts, accountName, accounts, transaction); - foreach (string id in resAccounts) - { - SetMailboxPermission(runSpace, accountName, id, "FullAccess"); - transaction.AddMailBoxFullAccessPermission(accountName, id); - } - } - catch (Exception) - { - RollbackTransaction(transaction); - throw; - } - ExchangeLog.LogEnd("SetMailboxFullAccessPermissions"); - - } - - - private void RemoveADPermission(Runspace runSpace, string identity, string account, string accessRights, string extendedRights, string properties) - { - ExchangeLog.LogStart("RemoveADPermission"); - - Command cmd = new Command("Remove-ADPermission"); - cmd.Parameters.Add("Identity", identity); - cmd.Parameters.Add("User", account); - cmd.Parameters.Add("InheritanceType", "All"); - cmd.Parameters.Add("AccessRights", accessRights); - cmd.Parameters.Add("ExtendedRights", extendedRights); - cmd.Parameters.Add("ChildObjectTypes", null); - cmd.Parameters.Add("InheritedObjectType", null); - cmd.Parameters.Add("Properties", properties); - cmd.Parameters.Add("Confirm", false); - ExecuteShellCommand(runSpace, cmd); - - ExchangeLog.LogEnd("RemoveADPermission"); - } - - private void AddADPermission(Runspace runSpace, string identity, string user, string accessRights, string extendedRights, string properties) - { - ExchangeLog.LogStart("AddADPermission"); - - Command cmd = new Command("Add-ADPermission"); - cmd.Parameters.Add("Identity", identity); - cmd.Parameters.Add("User", user); - cmd.Parameters.Add("AccessRights", accessRights); - cmd.Parameters.Add("ExtendedRights", extendedRights); - cmd.Parameters.Add("Properties", properties); - //cmd.Parameters.Add("Confirm", false); - ExecuteShellCommand(runSpace, cmd); - - ExchangeLog.LogEnd("AddADPermission"); - } - - - private string[] MergeADPermission(Runspace runSpace, ExchangeAccount[] existingAccounts, string identity, string[] newAccounts, ExchangeTransaction transaction) - { - ExchangeLog.LogStart("MergeADPermission"); - - List temp = new List(newAccounts); - - Array.Sort(newAccounts); - foreach (ExchangeAccount current in existingAccounts) - { - if (Array.BinarySearch(newAccounts, current.AccountName, StringComparer.Create(CultureInfo.InvariantCulture, true)) >= 0) - { - temp.Remove(current.AccountName); - continue; - } - RemoveADPermission(runSpace, identity, current.AccountName, null, "Send-as", null); - transaction.RemoveSendAsPermission(identity, current.AccountName); - } - - ExchangeLog.LogEnd("MergeADPermission"); - return temp.ToArray(); - } - - - public string CreateMailEnableUser(string upn, string organizationId, string organizationDistinguishedName, ExchangeAccountType accountType, - string mailboxDatabase, string offlineAddressBook,string addressBookPolicy, - string accountName, bool enablePOP, bool enableIMAP, - bool enableOWA, bool enableMAPI, bool enableActiveSync, - long issueWarningKB, long prohibitSendKB, long prohibitSendReceiveKB, int keepDeletedItemsDays, - int maxRecipients, int maxSendMessageSizeKB, int maxReceiveMessageSizeKB, bool hideFromAddressBook, bool IsConsumer) - { - return CreateMailEnableUserInternal(upn, organizationId, organizationDistinguishedName, accountType, - mailboxDatabase, offlineAddressBook,addressBookPolicy, - accountName, enablePOP, enableIMAP, - enableOWA, enableMAPI, enableActiveSync, - issueWarningKB, prohibitSendKB, prohibitSendReceiveKB, - keepDeletedItemsDays, maxRecipients, maxSendMessageSizeKB, maxReceiveMessageSizeKB, hideFromAddressBook, IsConsumer); - } + ExchangeLog.LogEnd("CalculatePublicFolderDiskSpace"); + return size; + } + + #endregion + + #region Mailboxes + + + private void SetExtendedRights(Runspace runSpace, string identity, string user, string rights) + { + ExchangeLog.LogStart("SetExtendedRights"); + + Command cmd = new Command("Add-ADPermission"); + cmd.Parameters.Add("Identity", identity); + cmd.Parameters.Add("User", user); + + cmd.Parameters.Add("ExtendedRights", rights); + ExecuteShellCommand(runSpace, cmd); + + ExchangeLog.LogEnd("SetExtendedRights"); + } + + private void SetMailboxPermission(Runspace runSpace, string accountName, string user, string accessRights) + { + ExchangeLog.LogStart("SetMailboxPermission"); + + Command cmd = new Command("Add-MailboxPermission"); + cmd.Parameters.Add("Identity", accountName); + cmd.Parameters.Add("User", user); + cmd.Parameters.Add("AccessRights", accessRights); + ExecuteShellCommand(runSpace, cmd); + + ExchangeLog.LogEnd("SetMailboxPermission"); + } + + private ExchangeAccount[] GetMailboxSendAsAccounts(Runspace runSpace, string organizationId, string accountName) + { + ExchangeLog.LogStart("GetMailboxSendAsAccounts"); + + string cn = GetMailboxCommonName(runSpace, accountName); + ExchangeAccount[] ret = GetSendAsAccounts(runSpace, organizationId, cn); + + ExchangeLog.LogEnd("GetMailboxSendAsAccounts"); + return ret; + } + + private ExchangeAccount[] GetSendAsAccounts(Runspace runSpace, string organizationId, string accountId) + { + ExchangeLog.LogStart("GetSendAsAccounts"); + + Command cmd = new Command("Get-ADPermission"); + cmd.Parameters.Add("Identity", accountId); + Collection results = ExecuteShellCommand(runSpace, cmd); + List accounts = new List(); + foreach (PSObject current in results) + { + string user = GetPSObjectProperty(current, "User").ToString(); + + Array extendedRights = GetPSObjectProperty(current, "ExtendedRights") as Array; + + if (extendedRights != null) + { + foreach (object obj in extendedRights) + { + string strRightName = obj.ToString(); + if (string.Compare(strRightName, "Send-as", true) == 0) + { + ExchangeAccount account = GetOrganizationAccount(runSpace, organizationId, user); + if (account != null) + accounts.Add(account); + } + } + } + } + + ExchangeLog.LogEnd("GetSendAsAccounts"); + return accounts.ToArray(); + } + + + private ExchangeAccount[] GetMailBoxFullAccessAcounts(Runspace runSpace, string organizationId, string accountName) + { + ExchangeLog.LogStart("GetMailBoxFullAccessAcounts"); + + Command cmd = new Command("Get-MailboxPermission"); + cmd.Parameters.Add("Identity", accountName); + Collection results = ExecuteShellCommand(runSpace, cmd); + + + List accounts = new List(); + foreach (PSObject current in results) + { + string user = GetPSObjectProperty(current, "User").ToString(); + + Array accessRights = GetPSObjectProperty(current, "AccessRights") as Array; + + if (accessRights != null) + { + foreach (object obj in accessRights) + { + string strRightName = obj.ToString(); + if (string.Compare(strRightName, "FullAccess", true) == 0) + { + ExchangeAccount account = GetOrganizationAccount(runSpace, organizationId, user); + if (account != null) + accounts.Add(account); + } + } + } + } + + ExchangeLog.LogEnd("GetMailBoxFullAccessAcounts"); + return accounts.ToArray(); + } + + private ExchangeMailbox GetMailboxPermissionsInternal(string organizationId, string accountName, Runspace runspace) + { + ExchangeLog.LogStart("GetMailboxPermissionsInternal"); + + if (string.IsNullOrEmpty(accountName)) + throw new ArgumentNullException("accountName"); + + ExchangeMailbox exchangeMailbox = null; + bool closeRunspace = false; + + try + { + if (runspace == null) + { + runspace = OpenRunspace(); + closeRunspace = true; + } + + exchangeMailbox = new ExchangeMailbox(); + exchangeMailbox.FullAccessAccounts = GetMailBoxFullAccessAcounts(runspace, organizationId, accountName); + exchangeMailbox.SendAsAccounts = GetMailboxSendAsAccounts(runspace, organizationId, accountName); + } + catch (Exception ex) + { + ExchangeLog.LogError(ex); + throw ex; + } + finally + { + if (closeRunspace) + CloseRunspace(runspace); + } + + ExchangeLog.LogEnd("GetMailboxPermissionsInternal"); + return exchangeMailbox; + } + + + private void SetSendAsPermissions(Runspace runSpace, ExchangeAccount[] existingAccounts, string accountId, string[] accounts) + { + ExchangeLog.LogStart("SetSendAsPermissions"); + + if (string.IsNullOrEmpty(accountId)) + throw new ArgumentNullException("accountId"); + + if (accounts == null) + throw new ArgumentNullException("accounts"); + + ExchangeTransaction transaction = null; + try + { + transaction = StartTransaction(); + + string[] resAccounts = MergeADPermission(runSpace, existingAccounts, accountId, accounts, transaction); + foreach (string id in resAccounts) + { + SetExtendedRights(runSpace, accountId, id, "Send-as"); + transaction.AddSendAsPermission(accountId, id); + } + + } + catch (Exception) + { + RollbackTransaction(transaction); + throw; + } + ExchangeLog.LogEnd("SetSendAsPermissions"); + } + + + private void SetMailboxPermissionsInternal(string organizationId, string accountName, string[] sendAsAccounts, string[] fullAccessAccounts) + { + ExchangeLog.LogStart("SetMailboxPermissionsInternal"); + + if (string.IsNullOrEmpty(accountName)) + throw new ArgumentNullException("accountName"); + + if (sendAsAccounts == null) + throw new ArgumentNullException("sendAsAccounts"); + + + if (fullAccessAccounts == null) + throw new ArgumentNullException("fullAccessAccounts"); + + Runspace runSpace = null; + try + { + + runSpace = OpenRunspace(); + string cn = GetMailboxCommonName(runSpace, accountName); + ExchangeMailbox mailbox = GetMailboxPermissionsInternal(organizationId, accountName, runSpace); + SetSendAsPermissions(runSpace, mailbox.SendAsAccounts, cn, sendAsAccounts); + SetMailboxFullAccessPermissions(runSpace, mailbox.FullAccessAccounts, accountName, fullAccessAccounts); + + } + catch (Exception ex) + { + ExchangeLog.LogError(ex); + + throw; + } + finally + { + CloseRunspace(runSpace); + } + + ExchangeLog.LogEnd("SetMailboxPermissionsInternal"); + } + + + internal void RemoveMailboxAccessPermission(Runspace runSpace, string accountName, string account, string accessRights) + { + ExchangeLog.LogStart("RemoveMailboxFullAccessPermission"); + + Command cmd = new Command("Remove-MailboxPermission"); + cmd.Parameters.Add("Identity", accountName); + cmd.Parameters.Add("User", account); + cmd.Parameters.Add("AccessRights", accessRights); + cmd.Parameters.Add("Confirm", false); + ExecuteShellCommand(runSpace, cmd); + + ExchangeLog.LogEnd("RemoveMailboxFullAccessPermission"); + } + + + private string[] MergeMailboxFullAccessPermissions(Runspace runSpace, ExchangeAccount[] existingAccounts, string accountName, string[] newAccounts, ExchangeTransaction transaction) + { + ExchangeLog.LogStart("MergeMailboxFullAccessPermissions"); + List temp = new List(newAccounts); + + Array.Sort(newAccounts); + foreach (ExchangeAccount exist in existingAccounts) + { + if (Array.BinarySearch(newAccounts, exist.AccountName, StringComparer.Create(CultureInfo.InvariantCulture, true)) >= 0) + { + temp.Remove(exist.AccountName); + continue; + } + + RemoveMailboxAccessPermission(runSpace, accountName, exist.AccountName, "FullAccess"); + transaction.RemoveMailboxFullAccessPermission(accountName, exist.AccountName); + } + + ExchangeLog.LogEnd("MergeMailboxFullAccessPermissions"); + return temp.ToArray(); + } + + + private void SetMailboxFullAccessPermissions(Runspace runSpace, ExchangeAccount[] existingAccounts, string accountName, string[] accounts) + { + ExchangeLog.LogStart("SetMailboxFullAccessPermissions"); + + if (string.IsNullOrEmpty(accountName)) + throw new ArgumentNullException("accountName"); + + if (accounts == null) + throw new ArgumentNullException("accounts"); + + ExchangeTransaction transaction = StartTransaction(); + + try + { + + string[] resAccounts = MergeMailboxFullAccessPermissions(runSpace, existingAccounts, accountName, accounts, transaction); + foreach (string id in resAccounts) + { + SetMailboxPermission(runSpace, accountName, id, "FullAccess"); + transaction.AddMailBoxFullAccessPermission(accountName, id); + } + } + catch (Exception) + { + RollbackTransaction(transaction); + throw; + } + ExchangeLog.LogEnd("SetMailboxFullAccessPermissions"); + + } + + + private void RemoveADPermission(Runspace runSpace, string identity, string account, string accessRights, string extendedRights, string properties) + { + ExchangeLog.LogStart("RemoveADPermission"); + + Command cmd = new Command("Remove-ADPermission"); + cmd.Parameters.Add("Identity", identity); + cmd.Parameters.Add("User", account); + cmd.Parameters.Add("InheritanceType", "All"); + cmd.Parameters.Add("AccessRights", accessRights); + cmd.Parameters.Add("ExtendedRights", extendedRights); + cmd.Parameters.Add("ChildObjectTypes", null); + cmd.Parameters.Add("InheritedObjectType", null); + cmd.Parameters.Add("Properties", properties); + cmd.Parameters.Add("Confirm", false); + ExecuteShellCommand(runSpace, cmd); + + ExchangeLog.LogEnd("RemoveADPermission"); + } + + private void AddADPermission(Runspace runSpace, string identity, string user, string accessRights, string extendedRights, string properties) + { + ExchangeLog.LogStart("AddADPermission"); + + Command cmd = new Command("Add-ADPermission"); + cmd.Parameters.Add("Identity", identity); + cmd.Parameters.Add("User", user); + cmd.Parameters.Add("AccessRights", accessRights); + cmd.Parameters.Add("ExtendedRights", extendedRights); + cmd.Parameters.Add("Properties", properties); + //cmd.Parameters.Add("Confirm", false); + ExecuteShellCommand(runSpace, cmd); + + ExchangeLog.LogEnd("AddADPermission"); + } + + + private string[] MergeADPermission(Runspace runSpace, ExchangeAccount[] existingAccounts, string identity, string[] newAccounts, ExchangeTransaction transaction) + { + ExchangeLog.LogStart("MergeADPermission"); + + List temp = new List(newAccounts); + + Array.Sort(newAccounts); + foreach (ExchangeAccount current in existingAccounts) + { + if (Array.BinarySearch(newAccounts, current.AccountName, StringComparer.Create(CultureInfo.InvariantCulture, true)) >= 0) + { + temp.Remove(current.AccountName); + continue; + } + RemoveADPermission(runSpace, identity, current.AccountName, null, "Send-as", null); + transaction.RemoveSendAsPermission(identity, current.AccountName); + } + + ExchangeLog.LogEnd("MergeADPermission"); + return temp.ToArray(); + } + + + public string CreateMailEnableUser(string upn, string organizationId, string organizationDistinguishedName, ExchangeAccountType accountType, + string mailboxDatabase, string offlineAddressBook, string addressBookPolicy, + string accountName, bool enablePOP, bool enableIMAP, + bool enableOWA, bool enableMAPI, bool enableActiveSync, + long issueWarningKB, long prohibitSendKB, long prohibitSendReceiveKB, int keepDeletedItemsDays, + int maxRecipients, int maxSendMessageSizeKB, int maxReceiveMessageSizeKB, bool hideFromAddressBook, bool IsConsumer, bool enabledLitigationHold, long recoverabelItemsSpace, long recoverabelItemsWarning) + { + return CreateMailEnableUserInternal(upn, organizationId, organizationDistinguishedName, accountType, + mailboxDatabase, offlineAddressBook, addressBookPolicy, + accountName, enablePOP, enableIMAP, + enableOWA, enableMAPI, enableActiveSync, + issueWarningKB, prohibitSendKB, prohibitSendReceiveKB, + keepDeletedItemsDays, maxRecipients, maxSendMessageSizeKB, maxReceiveMessageSizeKB, hideFromAddressBook, IsConsumer, enabledLitigationHold, recoverabelItemsSpace, recoverabelItemsWarning); + } internal virtual string CreateMailEnableUserInternal(string upn, string organizationId, string organizationDistinguishedName, ExchangeAccountType accountType, string mailboxDatabase, string offlineAddressBook, string addressBookPolicy, string accountName, bool enablePOP, bool enableIMAP, bool enableOWA, bool enableMAPI, bool enableActiveSync, long issueWarningKB, long prohibitSendKB, long prohibitSendReceiveKB, int keepDeletedItemsDays, - int maxRecipients, int maxSendMessageSizeKB, int maxReceiveMessageSizeKB, bool hideFromAddressBook, bool IsConsumer) + int maxRecipients, int maxSendMessageSizeKB, int maxReceiveMessageSizeKB, bool hideFromAddressBook, bool IsConsumer,bool enabledLitigationHold, long recoverabelItemsSpace, long recoverabelItemsWarning) { ExchangeLog.LogStart("CreateMailEnableUserInternal"); @@ -1799,7 +1786,7 @@ namespace WebsitePanel.Providers.HostedSolution string id = null; Version exchangeVersion = GetExchangeVersion(); - + try { runSpace = OpenRunspace(); @@ -2060,48 +2047,48 @@ namespace WebsitePanel.Providers.HostedSolution } } */ - internal virtual void SetCalendarSettings(Runspace runspace, string id) - { - ExchangeLog.LogStart("SetCalendarSettings"); - Command cmd = new Command("Set-MailboxCalendarSettings"); - cmd.Parameters.Add("Identity", id); - cmd.Parameters.Add("AutomateProcessing", CalendarProcessingFlags.AutoAccept); - ExecuteShellCommand(runspace, cmd); - ExchangeLog.LogEnd("SetCalendarSettings"); - } + internal virtual void SetCalendarSettings(Runspace runspace, string id) + { + ExchangeLog.LogStart("SetCalendarSettings"); + Command cmd = new Command("Set-MailboxCalendarSettings"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("AutomateProcessing", CalendarProcessingFlags.AutoAccept); + ExecuteShellCommand(runspace, cmd); + ExchangeLog.LogEnd("SetCalendarSettings"); + } - internal virtual void DeleteMailboxInternal(string accountName) - { - ExchangeLog.LogStart("DeleteMailboxInternal"); - ExchangeLog.DebugInfo("Account Name: {0}", accountName); + internal virtual void DeleteMailboxInternal(string accountName) + { + ExchangeLog.LogStart("DeleteMailboxInternal"); + ExchangeLog.DebugInfo("Account Name: {0}", accountName); - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); RemoveDevicesInternal(runSpace, accountName); - RemoveMailbox(runSpace, accountName); - } - finally - { + RemoveMailbox(runSpace, accountName); + } + finally + { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("DeleteMailboxInternal"); - } + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("DeleteMailboxInternal"); + } - internal void RemoveMailbox(Runspace runSpace, string id) - { - ExchangeLog.LogStart("RemoveMailbox"); - Command cmd = new Command("Remove-Mailbox"); - cmd.Parameters.Add("Identity", id); - cmd.Parameters.Add("Permanent", false); - cmd.Parameters.Add("Confirm", false); - ExecuteShellCommand(runSpace, cmd); - ExchangeLog.LogEnd("RemoveMailbox"); - } + internal void RemoveMailbox(Runspace runSpace, string id) + { + ExchangeLog.LogStart("RemoveMailbox"); + Command cmd = new Command("Remove-Mailbox"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("Permanent", false); + cmd.Parameters.Add("Confirm", false); + ExecuteShellCommand(runSpace, cmd); + ExchangeLog.LogEnd("RemoveMailbox"); + } private void DisableMailbox(Runspace runSpace, string id) { @@ -2113,100 +2100,100 @@ namespace WebsitePanel.Providers.HostedSolution ExchangeLog.LogEnd("DisableMailbox"); } - private string GetMailboxCommonName(Runspace runSpace, string accountName) - { - ExchangeLog.LogStart("GetMailboxCommonName"); - Collection result = GetMailboxObject(runSpace, accountName); - PSObject mailbox = result[0]; - string cn = GetPSObjectProperty(mailbox, "Name") as string; - ExchangeLog.LogEnd("GetMailboxCommonName"); - return cn; - } + private string GetMailboxCommonName(Runspace runSpace, string accountName) + { + ExchangeLog.LogStart("GetMailboxCommonName"); + Collection result = GetMailboxObject(runSpace, accountName); + PSObject mailbox = result[0]; + string cn = GetPSObjectProperty(mailbox, "Name") as string; + ExchangeLog.LogEnd("GetMailboxCommonName"); + return cn; + } - private ExchangeAccount GetManager(DirectoryEntry entry) - { - ExchangeAccount retUser = null; - string path = ActiveDirectoryUtils.GetADObjectStringProperty(entry, ADAttributes.Manager); - if (!string.IsNullOrEmpty(path)) - { - path = ActiveDirectoryUtils.AddADPrefix(path, PrimaryDomainController); - if (ActiveDirectoryUtils.AdObjectExists(path)) - { - DirectoryEntry user = ActiveDirectoryUtils.GetADObject(path); - retUser = new ExchangeAccount(); - retUser.DisplayName = ActiveDirectoryUtils.GetADObjectStringProperty(user, ADAttributes.DisplayName); - retUser.AccountName = ActiveDirectoryUtils.GetADObjectStringProperty(user, ADAttributes.Name); - } - } + private ExchangeAccount GetManager(DirectoryEntry entry) + { + ExchangeAccount retUser = null; + string path = ActiveDirectoryUtils.GetADObjectStringProperty(entry, ADAttributes.Manager); + if (!string.IsNullOrEmpty(path)) + { + path = ActiveDirectoryUtils.AddADPrefix(path, PrimaryDomainController); + if (ActiveDirectoryUtils.AdObjectExists(path)) + { + DirectoryEntry user = ActiveDirectoryUtils.GetADObject(path); + retUser = new ExchangeAccount(); + retUser.DisplayName = ActiveDirectoryUtils.GetADObjectStringProperty(user, ADAttributes.DisplayName); + retUser.AccountName = ActiveDirectoryUtils.GetADObjectStringProperty(user, ADAttributes.Name); + } + } - return retUser; - } + return retUser; + } - private ExchangeMailbox GetMailboxGeneralSettingsInternal(string accountName) - { - ExchangeLog.LogStart("GetMailboxGeneralSettingsInternal"); - ExchangeLog.DebugInfo("Account: {0}", accountName); + private ExchangeMailbox GetMailboxGeneralSettingsInternal(string accountName) + { + ExchangeLog.LogStart("GetMailboxGeneralSettingsInternal"); + ExchangeLog.DebugInfo("Account: {0}", accountName); - ExchangeMailbox info = new ExchangeMailbox(); - info.AccountName = accountName; - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + ExchangeMailbox info = new ExchangeMailbox(); + info.AccountName = accountName; + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); - Collection result = GetMailboxObject(runSpace, accountName); - PSObject mailbox = result[0]; + Collection result = GetMailboxObject(runSpace, accountName); + PSObject mailbox = result[0]; - string id = GetResultObjectDN(result); - string path = AddADPrefix(id); - DirectoryEntry entry = GetADObject(path); + string id = GetResultObjectDN(result); + string path = AddADPrefix(id); + DirectoryEntry entry = GetADObject(path); - //ADAccountOptions userFlags = (ADAccountOptions)entry.Properties["userAccountControl"].Value; - //info.Disabled = ((userFlags & ADAccountOptions.UF_ACCOUNTDISABLE) != 0); - info.Disabled = (bool)entry.InvokeGet("AccountDisabled"); + //ADAccountOptions userFlags = (ADAccountOptions)entry.Properties["userAccountControl"].Value; + //info.Disabled = ((userFlags & ADAccountOptions.UF_ACCOUNTDISABLE) != 0); + info.Disabled = (bool)entry.InvokeGet("AccountDisabled"); - info.DisplayName = (string)GetPSObjectProperty(mailbox, "DisplayName"); - info.HideFromAddressBook = (bool)GetPSObjectProperty(mailbox, "HiddenFromAddressListsEnabled"); + info.DisplayName = (string)GetPSObjectProperty(mailbox, "DisplayName"); + info.HideFromAddressBook = (bool)GetPSObjectProperty(mailbox, "HiddenFromAddressListsEnabled"); - Command cmd = new Command("Get-User"); - cmd.Parameters.Add("Identity", accountName); - result = ExecuteShellCommand(runSpace, cmd); - PSObject user = result[0]; + Command cmd = new Command("Get-User"); + cmd.Parameters.Add("Identity", accountName); + result = ExecuteShellCommand(runSpace, cmd); + PSObject user = result[0]; - info.FirstName = (string)GetPSObjectProperty(user, "FirstName"); - info.Initials = (string)GetPSObjectProperty(user, "Initials"); - info.LastName = (string)GetPSObjectProperty(user, "LastName"); + info.FirstName = (string)GetPSObjectProperty(user, "FirstName"); + info.Initials = (string)GetPSObjectProperty(user, "Initials"); + info.LastName = (string)GetPSObjectProperty(user, "LastName"); - info.Address = (string)GetPSObjectProperty(user, "StreetAddress"); - info.City = (string)GetPSObjectProperty(user, "City"); - info.State = (string)GetPSObjectProperty(user, "StateOrProvince"); - info.Zip = (string)GetPSObjectProperty(user, "PostalCode"); - info.Country = CountryInfoToString((CountryInfo)GetPSObjectProperty(user, "CountryOrRegion")); - info.JobTitle = (string)GetPSObjectProperty(user, "Title"); - info.Company = (string)GetPSObjectProperty(user, "Company"); - info.Department = (string)GetPSObjectProperty(user, "Department"); - info.Office = (string)GetPSObjectProperty(user, "Office"); + info.Address = (string)GetPSObjectProperty(user, "StreetAddress"); + info.City = (string)GetPSObjectProperty(user, "City"); + info.State = (string)GetPSObjectProperty(user, "StateOrProvince"); + info.Zip = (string)GetPSObjectProperty(user, "PostalCode"); + info.Country = CountryInfoToString((CountryInfo)GetPSObjectProperty(user, "CountryOrRegion")); + info.JobTitle = (string)GetPSObjectProperty(user, "Title"); + info.Company = (string)GetPSObjectProperty(user, "Company"); + info.Department = (string)GetPSObjectProperty(user, "Department"); + info.Office = (string)GetPSObjectProperty(user, "Office"); - info.ManagerAccount = GetManager(entry); //GetExchangeAccount(runSpace, ObjToString(GetPSObjectProperty(user, "Manager"))); - info.BusinessPhone = (string)GetPSObjectProperty(user, "Phone"); - info.Fax = (string)GetPSObjectProperty(user, "Fax"); - info.HomePhone = (string)GetPSObjectProperty(user, "HomePhone"); - info.MobilePhone = (string)GetPSObjectProperty(user, "MobilePhone"); - info.Pager = (string)GetPSObjectProperty(user, "Pager"); - info.WebPage = (string)GetPSObjectProperty(user, "WebPage"); - info.Notes = (string)GetPSObjectProperty(user, "Notes"); + info.ManagerAccount = GetManager(entry); //GetExchangeAccount(runSpace, ObjToString(GetPSObjectProperty(user, "Manager"))); + info.BusinessPhone = (string)GetPSObjectProperty(user, "Phone"); + info.Fax = (string)GetPSObjectProperty(user, "Fax"); + info.HomePhone = (string)GetPSObjectProperty(user, "HomePhone"); + info.MobilePhone = (string)GetPSObjectProperty(user, "MobilePhone"); + info.Pager = (string)GetPSObjectProperty(user, "Pager"); + info.WebPage = (string)GetPSObjectProperty(user, "WebPage"); + info.Notes = (string)GetPSObjectProperty(user, "Notes"); - } - finally - { + } + finally + { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("GetMailboxGeneralSettingsInternal"); - return info; - } + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("GetMailboxGeneralSettingsInternal"); + return info; + } private void SetMailboxGeneralSettingsInternal(string accountName, bool hideFromAddressBook, bool disabled) @@ -2243,61 +2230,61 @@ namespace WebsitePanel.Providers.HostedSolution ExchangeLog.LogEnd("SetMailboxGeneralSettingsInternal"); } - private void ChangeMailboxState(string id, bool enabled) - { - string path = AddADPrefix(id); - DirectoryEntry entry = GetADObject(path); - entry.InvokeSet("AccountDisabled", !enabled); - entry.CommitChanges(); - } + private void ChangeMailboxState(string id, bool enabled) + { + string path = AddADPrefix(id); + DirectoryEntry entry = GetADObject(path); + entry.InvokeSet("AccountDisabled", !enabled); + entry.CommitChanges(); + } - private ExchangeMailbox GetMailboxMailFlowSettingsInternal(string accountName) - { - ExchangeLog.LogStart("GetMailboxMailFlowSettings"); - ExchangeLog.DebugInfo("Account: {0}", accountName); + private ExchangeMailbox GetMailboxMailFlowSettingsInternal(string accountName) + { + ExchangeLog.LogStart("GetMailboxMailFlowSettings"); + ExchangeLog.DebugInfo("Account: {0}", accountName); - ExchangeMailbox info = new ExchangeMailbox(); - info.AccountName = accountName; - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + ExchangeMailbox info = new ExchangeMailbox(); + info.AccountName = accountName; + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); - Collection result = GetMailboxObject(runSpace, accountName); - PSObject mailbox = result[0]; + Collection result = GetMailboxObject(runSpace, accountName); + PSObject mailbox = result[0]; - string forwardingAddress = ObjToString(GetPSObjectProperty(mailbox, "ForwardingAddress")); - if (string.IsNullOrEmpty(forwardingAddress)) - { - info.EnableForwarding = false; - info.ForwardingAccount = null; - info.DoNotDeleteOnForward = false; - } - else - { - info.EnableForwarding = true; - info.ForwardingAccount = GetExchangeAccount(runSpace, forwardingAddress); - info.DoNotDeleteOnForward = (bool)GetPSObjectProperty(mailbox, "DeliverToMailboxAndForward"); - } + string forwardingAddress = ObjToString(GetPSObjectProperty(mailbox, "ForwardingAddress")); + if (string.IsNullOrEmpty(forwardingAddress)) + { + info.EnableForwarding = false; + info.ForwardingAccount = null; + info.DoNotDeleteOnForward = false; + } + else + { + info.EnableForwarding = true; + info.ForwardingAccount = GetExchangeAccount(runSpace, forwardingAddress); + info.DoNotDeleteOnForward = (bool)GetPSObjectProperty(mailbox, "DeliverToMailboxAndForward"); + } - info.SendOnBehalfAccounts = GetSendOnBehalfAccounts(runSpace, mailbox); - info.AcceptAccounts = GetAcceptedAccounts(runSpace, mailbox); - info.RejectAccounts = GetRejectedAccounts(runSpace, mailbox); - info.MaxRecipients = - ConvertUnlimitedToInt32((Unlimited)GetPSObjectProperty(mailbox, "RecipientLimits")); - info.MaxSendMessageSizeKB = - ConvertUnlimitedToKB((Unlimited)GetPSObjectProperty(mailbox, "MaxSendSize")); - info.MaxReceiveMessageSizeKB = - ConvertUnlimitedToKB((Unlimited)GetPSObjectProperty(mailbox, "MaxReceiveSize")); - info.RequireSenderAuthentication = (bool)GetPSObjectProperty(mailbox, "RequireSenderAuthenticationEnabled"); - } - finally - { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("GetMailboxMailFlowSettings"); - return info; - } + info.SendOnBehalfAccounts = GetSendOnBehalfAccounts(runSpace, mailbox); + info.AcceptAccounts = GetAcceptedAccounts(runSpace, mailbox); + info.RejectAccounts = GetRejectedAccounts(runSpace, mailbox); + info.MaxRecipients = + ConvertUnlimitedToInt32((Unlimited)GetPSObjectProperty(mailbox, "RecipientLimits")); + info.MaxSendMessageSizeKB = + ConvertUnlimitedToKB((Unlimited)GetPSObjectProperty(mailbox, "MaxSendSize")); + info.MaxReceiveMessageSizeKB = + ConvertUnlimitedToKB((Unlimited)GetPSObjectProperty(mailbox, "MaxReceiveSize")); + info.RequireSenderAuthentication = (bool)GetPSObjectProperty(mailbox, "RequireSenderAuthenticationEnabled"); + } + finally + { + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("GetMailboxMailFlowSettings"); + return info; + } private void SetMailboxMailFlowSettingsInternal(string accountName, bool enableForwarding, string forwardingAccountName, bool forwardToBoth, string[] sendOnBehalfAccounts, @@ -2352,83 +2339,83 @@ namespace WebsitePanel.Providers.HostedSolution ExchangeLog.LogEnd("SetMailboxMailFlowSettingsInternal"); } - private ExchangeMailbox GetMailboxAdvancedSettingsInternal(string accountName) - { - ExchangeLog.LogStart("GetMailboxAdvancedSettingsInternal"); - ExchangeLog.DebugInfo("Account: {0}", accountName); + internal virtual ExchangeMailbox GetMailboxAdvancedSettingsInternal(string accountName) + { + ExchangeLog.LogStart("GetMailboxAdvancedSettingsInternal"); + ExchangeLog.DebugInfo("Account: {0}", accountName); - ExchangeMailbox info = new ExchangeMailbox(); - info.AccountName = accountName; - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + ExchangeMailbox info = new ExchangeMailbox(); + info.AccountName = accountName; + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); - Collection result = GetMailboxObject(runSpace, accountName); - PSObject mailbox = result[0]; + Collection result = GetMailboxObject(runSpace, accountName); + PSObject mailbox = result[0]; - info.IssueWarningKB = - ConvertUnlimitedToKB((Unlimited)GetPSObjectProperty(mailbox, "IssueWarningQuota")); - info.ProhibitSendKB = - ConvertUnlimitedToKB((Unlimited)GetPSObjectProperty(mailbox, "ProhibitSendQuota")); - info.ProhibitSendReceiveKB = - ConvertUnlimitedToKB((Unlimited)GetPSObjectProperty(mailbox, "ProhibitSendReceiveQuota")); - info.KeepDeletedItemsDays = - ConvertEnhancedTimeSpanToDays((EnhancedTimeSpan)GetPSObjectProperty(mailbox, "RetainDeletedItemsFor")); + info.IssueWarningKB = + ConvertUnlimitedToKB((Unlimited)GetPSObjectProperty(mailbox, "IssueWarningQuota")); + info.ProhibitSendKB = + ConvertUnlimitedToKB((Unlimited)GetPSObjectProperty(mailbox, "ProhibitSendQuota")); + info.ProhibitSendReceiveKB = + ConvertUnlimitedToKB((Unlimited)GetPSObjectProperty(mailbox, "ProhibitSendReceiveQuota")); + info.KeepDeletedItemsDays = + ConvertEnhancedTimeSpanToDays((EnhancedTimeSpan)GetPSObjectProperty(mailbox, "RetainDeletedItemsFor")); - //Client Access - Command cmd = new Command("Get-CASMailbox"); - cmd.Parameters.Add("Identity", accountName); - result = ExecuteShellCommand(runSpace, cmd); - mailbox = result[0]; + //Client Access + Command cmd = new Command("Get-CASMailbox"); + cmd.Parameters.Add("Identity", accountName); + result = ExecuteShellCommand(runSpace, cmd); + mailbox = result[0]; - info.EnableActiveSync = (bool)GetPSObjectProperty(mailbox, "ActiveSyncEnabled"); - info.EnableOWA = (bool)GetPSObjectProperty(mailbox, "OWAEnabled"); - info.EnableMAPI = (bool)GetPSObjectProperty(mailbox, "MAPIEnabled"); - info.EnablePOP = (bool)GetPSObjectProperty(mailbox, "PopEnabled"); - info.EnableIMAP = (bool)GetPSObjectProperty(mailbox, "ImapEnabled"); + info.EnableActiveSync = (bool)GetPSObjectProperty(mailbox, "ActiveSyncEnabled"); + info.EnableOWA = (bool)GetPSObjectProperty(mailbox, "OWAEnabled"); + info.EnableMAPI = (bool)GetPSObjectProperty(mailbox, "MAPIEnabled"); + info.EnablePOP = (bool)GetPSObjectProperty(mailbox, "PopEnabled"); + info.EnableIMAP = (bool)GetPSObjectProperty(mailbox, "ImapEnabled"); - //Statistics - cmd = new Command("Get-MailboxStatistics"); - cmd.Parameters.Add("Identity", accountName); - result = ExecuteShellCommand(runSpace, cmd); - if (result.Count > 0) - { - PSObject statistics = result[0]; - Unlimited totalItemSize = - (Unlimited)GetPSObjectProperty(statistics, "TotalItemSize"); - info.TotalSizeMB = ConvertUnlimitedToMB(totalItemSize); - uint? itemCount = (uint?)GetPSObjectProperty(statistics, "ItemCount"); - info.TotalItems = ConvertNullableToInt32(itemCount); - DateTime? lastLogoffTime = (DateTime?)GetPSObjectProperty(statistics, "LastLogoffTime"); ; - DateTime? lastLogonTime = (DateTime?)GetPSObjectProperty(statistics, "LastLogonTime"); ; - info.LastLogoff = ConvertNullableToDateTime(lastLogoffTime); - info.LastLogon = ConvertNullableToDateTime(lastLogonTime); - } - else - { - info.TotalSizeMB = 0; - info.TotalItems = 0; - info.LastLogoff = DateTime.MinValue; - info.LastLogon = DateTime.MinValue; - } + //Statistics + cmd = new Command("Get-MailboxStatistics"); + cmd.Parameters.Add("Identity", accountName); + result = ExecuteShellCommand(runSpace, cmd); + if (result.Count > 0) + { + PSObject statistics = result[0]; + Unlimited totalItemSize = + (Unlimited)GetPSObjectProperty(statistics, "TotalItemSize"); + info.TotalSizeMB = ConvertUnlimitedToMB(totalItemSize); + uint? itemCount = (uint?)GetPSObjectProperty(statistics, "ItemCount"); + info.TotalItems = ConvertNullableToInt32(itemCount); + DateTime? lastLogoffTime = (DateTime?)GetPSObjectProperty(statistics, "LastLogoffTime"); ; + DateTime? lastLogonTime = (DateTime?)GetPSObjectProperty(statistics, "LastLogonTime"); ; + info.LastLogoff = ConvertNullableToDateTime(lastLogoffTime); + info.LastLogon = ConvertNullableToDateTime(lastLogonTime); + } + else + { + info.TotalSizeMB = 0; + info.TotalItems = 0; + info.LastLogoff = DateTime.MinValue; + info.LastLogon = DateTime.MinValue; + } - //domain - info.Domain = GetNETBIOSDomainName(); - } - finally - { + //domain + info.Domain = GetNETBIOSDomainName(); + } + finally + { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("GetMailboxAdvancedSettingsInternal"); - return info; - } + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("GetMailboxAdvancedSettingsInternal"); + return info; + } - private void SetMailboxAdvancedSettingsInternal(string organizationId, string accountName, bool enablePOP, bool enableIMAP, + internal virtual void SetMailboxAdvancedSettingsInternal(string organizationId, string accountName, bool enablePOP, bool enableIMAP, bool enableOWA, bool enableMAPI, bool enableActiveSync, long issueWarningKB, long prohibitSendKB, long prohibitSendReceiveKB, int keepDeletedItemsDays, int maxRecipients, int maxSendMessageSizeKB, - int maxReceiveMessageSizeKB) + int maxReceiveMessageSizeKB, bool enabledLitigationHold, long recoverabelItemsSpace, long recoverabelItemsWarning) { ExchangeLog.LogStart("SetMailboxAdvancedSettingsInternal"); ExchangeLog.DebugInfo("Account: {0}", accountName); @@ -2448,6 +2435,7 @@ namespace WebsitePanel.Providers.HostedSolution cmd.Parameters.Add("RecipientLimits", ConvertInt32ToUnlimited(maxRecipients)); cmd.Parameters.Add("MaxSendSize", ConvertKBToUnlimited(maxSendMessageSizeKB)); cmd.Parameters.Add("MaxReceiveSize", ConvertKBToUnlimited(maxReceiveMessageSizeKB)); + ExecuteShellCommand(runSpace, cmd); //Client Access @@ -2472,837 +2460,837 @@ namespace WebsitePanel.Providers.HostedSolution ExchangeLog.LogEnd("SetMailboxAdvancedSettingsInternal"); } - private ExchangeEmailAddress[] GetMailboxEmailAddressesInternal(string accountName) - { - ExchangeLog.LogStart("GetMailboxEmailAddressesInternal"); - ExchangeLog.DebugInfo("Account: {0}", accountName); + private ExchangeEmailAddress[] GetMailboxEmailAddressesInternal(string accountName) + { + ExchangeLog.LogStart("GetMailboxEmailAddressesInternal"); + ExchangeLog.DebugInfo("Account: {0}", accountName); - List list = new List(); - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + List list = new List(); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); - Collection result = GetMailboxObject(runSpace, accountName); - PSObject mailbox = result[0]; + Collection result = GetMailboxObject(runSpace, accountName); + PSObject mailbox = result[0]; - string primaryEmail = null; - string windowsEmail = null; + string primaryEmail = null; + string windowsEmail = null; - SmtpAddress smtpAddress = (SmtpAddress)GetPSObjectProperty(mailbox, "PrimarySmtpAddress"); - if (smtpAddress != null) - primaryEmail = smtpAddress.ToString(); + SmtpAddress smtpAddress = (SmtpAddress)GetPSObjectProperty(mailbox, "PrimarySmtpAddress"); + if (smtpAddress != null) + primaryEmail = smtpAddress.ToString(); - //SmtpAddress winAddress = (SmtpAddress)GetPSObjectProperty(mailbox, "WindowsEmailAddress"); - windowsEmail = ObjToString(GetPSObjectProperty(mailbox, "CustomAttribute3")); + //SmtpAddress winAddress = (SmtpAddress)GetPSObjectProperty(mailbox, "WindowsEmailAddress"); + windowsEmail = ObjToString(GetPSObjectProperty(mailbox, "CustomAttribute3")); - ProxyAddressCollection emails = (ProxyAddressCollection)GetPSObjectProperty(mailbox, "EmailAddresses"); - foreach (ProxyAddress email in emails) - { - //skip windows email - if (string.Equals(email.AddressString, windowsEmail, StringComparison.OrdinalIgnoreCase)) - continue; + ProxyAddressCollection emails = (ProxyAddressCollection)GetPSObjectProperty(mailbox, "EmailAddresses"); + foreach (ProxyAddress email in emails) + { + //skip windows email + if (string.Equals(email.AddressString, windowsEmail, StringComparison.OrdinalIgnoreCase)) + continue; - ExchangeEmailAddress item = new ExchangeEmailAddress(); - item.Email = email.AddressString; - item.Primary = string.Equals(item.Email, primaryEmail, StringComparison.OrdinalIgnoreCase); - list.Add(item); - } - } - finally - { + ExchangeEmailAddress item = new ExchangeEmailAddress(); + item.Email = email.AddressString; + item.Primary = string.Equals(item.Email, primaryEmail, StringComparison.OrdinalIgnoreCase); + list.Add(item); + } + } + finally + { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("GetMailboxEmailAddressesInternal"); - return list.ToArray(); - } + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("GetMailboxEmailAddressesInternal"); + return list.ToArray(); + } - private void SetMailboxEmailAddressesInternal(string accountName, string[] emailAddresses) - { - ExchangeLog.LogStart("SetMailboxEmailAddressesInternal"); - ExchangeLog.DebugInfo("Account: {0}", accountName); + private void SetMailboxEmailAddressesInternal(string accountName, string[] emailAddresses) + { + ExchangeLog.LogStart("SetMailboxEmailAddressesInternal"); + ExchangeLog.DebugInfo("Account: {0}", accountName); - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); - Collection result = GetMailboxObject(runSpace, accountName); - PSObject mailbox = result[0]; + Collection result = GetMailboxObject(runSpace, accountName); + PSObject mailbox = result[0]; - //SmtpAddress winAddress = (SmtpAddress)GetPSObjectProperty(mailbox, "WindowsEmailAddress"); - //if (winAddress != null) - // windowsEmail = winAddress.ToString(); + //SmtpAddress winAddress = (SmtpAddress)GetPSObjectProperty(mailbox, "WindowsEmailAddress"); + //if (winAddress != null) + // windowsEmail = winAddress.ToString(); - string windowsEmail = ObjToString(GetPSObjectProperty(mailbox, "CustomAttribute3")); + string windowsEmail = ObjToString(GetPSObjectProperty(mailbox, "CustomAttribute3")); - ProxyAddressCollection emails = new ProxyAddressCollection(); - ProxyAddress proxy = null; - string upn = null; - if (emailAddresses != null) - { - foreach (string email in emailAddresses) - { - proxy = ProxyAddress.Parse(email); - emails.Add(proxy); - if (proxy.IsPrimaryAddress) - { - upn = proxy.AddressString; - } - } - } - //add system windows email - if (!string.IsNullOrEmpty(windowsEmail)) - { - emails.Add(ProxyAddress.Parse(windowsEmail)); - } + ProxyAddressCollection emails = new ProxyAddressCollection(); + ProxyAddress proxy = null; + string upn = null; + if (emailAddresses != null) + { + foreach (string email in emailAddresses) + { + proxy = ProxyAddress.Parse(email); + emails.Add(proxy); + if (proxy.IsPrimaryAddress) + { + upn = proxy.AddressString; + } + } + } + //add system windows email + if (!string.IsNullOrEmpty(windowsEmail)) + { + emails.Add(ProxyAddress.Parse(windowsEmail)); + } - Command cmd = new Command("Set-Mailbox"); - cmd.Parameters.Add("Identity", accountName); - cmd.Parameters.Add("EmailAddresses", emails); - if (!string.IsNullOrEmpty(upn)) - { - cmd.Parameters.Add("UserPrincipalName", upn); - cmd.Parameters.Add("WindowsEmailAddress", upn); - } - ExecuteShellCommand(runSpace, cmd); - } - finally - { + Command cmd = new Command("Set-Mailbox"); + cmd.Parameters.Add("Identity", accountName); + cmd.Parameters.Add("EmailAddresses", emails); + if (!string.IsNullOrEmpty(upn)) + { + cmd.Parameters.Add("UserPrincipalName", upn); + cmd.Parameters.Add("WindowsEmailAddress", upn); + } + ExecuteShellCommand(runSpace, cmd); + } + finally + { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("SetMailboxEmailAddressesInternal"); - } + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("SetMailboxEmailAddressesInternal"); + } - private void SetMailboxPrimaryEmailAddressInternal(string accountName, string emailAddress) - { - ExchangeLog.LogStart("SetMailboxPrimaryEmailAddressInternal"); - ExchangeLog.DebugInfo("Account: {0}", accountName); + private void SetMailboxPrimaryEmailAddressInternal(string accountName, string emailAddress) + { + ExchangeLog.LogStart("SetMailboxPrimaryEmailAddressInternal"); + ExchangeLog.DebugInfo("Account: {0}", accountName); - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); - SmtpAddress primaryEmail = new SmtpAddress(emailAddress); - Command cmd = new Command("Set-Mailbox"); - cmd.Parameters.Add("Identity", accountName); - cmd.Parameters.Add("PrimarySmtpAddress", primaryEmail); + SmtpAddress primaryEmail = new SmtpAddress(emailAddress); + Command cmd = new Command("Set-Mailbox"); + cmd.Parameters.Add("Identity", accountName); + cmd.Parameters.Add("PrimarySmtpAddress", primaryEmail); //cmd.Parameters.Add("UserPrincipalName", primaryEmail); //cmd.Parameters.Add("WindowsEmailAddress", primaryEmail); - ExecuteShellCommand(runSpace, cmd); - } - finally - { + ExecuteShellCommand(runSpace, cmd); + } + finally + { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("SetMailboxPrimaryEmailAddressInternal"); - } + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("SetMailboxPrimaryEmailAddressInternal"); + } - private ExchangeAccount[] GetSendOnBehalfAccounts(Runspace runSpace, PSObject exchangeObject) - { - List list = new List(); + private ExchangeAccount[] GetSendOnBehalfAccounts(Runspace runSpace, PSObject exchangeObject) + { + List list = new List(); - IList ids = - (IList)GetPSObjectProperty(exchangeObject, "GrantSendOnBehalfTo"); + IList ids = + (IList)GetPSObjectProperty(exchangeObject, "GrantSendOnBehalfTo"); - foreach (ADObjectId id in ids) - { - ExchangeAccount account = GetExchangeAccount(runSpace, id.ToString()); - if (account != null) - list.Add(account); - } - return list.ToArray(); - } + foreach (ADObjectId id in ids) + { + ExchangeAccount account = GetExchangeAccount(runSpace, id.ToString()); + if (account != null) + list.Add(account); + } + return list.ToArray(); + } - internal MultiValuedProperty SetSendOnBehalfAccounts(Runspace runspace, string[] accounts) - { - if (accounts == null || accounts.Length == 0) - return MultiValuedProperty.Empty; - else - { - MultiValuedProperty ids = new MultiValuedProperty(); - string dn = null; - foreach (string account in accounts) - { - dn = GetRecipientDistinguishedName(runspace, account); - ids.Add(new ADObjectId(dn)); - } - return ids; - } - } + internal MultiValuedProperty SetSendOnBehalfAccounts(Runspace runspace, string[] accounts) + { + if (accounts == null || accounts.Length == 0) + return MultiValuedProperty.Empty; + else + { + MultiValuedProperty ids = new MultiValuedProperty(); + string dn = null; + foreach (string account in accounts) + { + dn = GetRecipientDistinguishedName(runspace, account); + ids.Add(new ADObjectId(dn)); + } + return ids; + } + } - private ExchangeAccount[] GetAcceptedAccounts(Runspace runSpace, PSObject mailbox) - { - List list = new List(); - ExchangeAccount account = null; - IList ids = - (IList)GetPSObjectProperty(mailbox, "AcceptMessagesOnlyFrom"); - foreach (ADObjectId id in ids) - { - account = GetExchangeAccount(runSpace, id.ToString()); - if (account != null) - list.Add(account); - } - ids = (IList)GetPSObjectProperty(mailbox, "AcceptMessagesOnlyFromDLMembers"); - foreach (ADObjectId id in ids) - { - account = GetExchangeAccount(runSpace, id.ToString()); - if (account != null) - list.Add(account); - } + private ExchangeAccount[] GetAcceptedAccounts(Runspace runSpace, PSObject mailbox) + { + List list = new List(); + ExchangeAccount account = null; + IList ids = + (IList)GetPSObjectProperty(mailbox, "AcceptMessagesOnlyFrom"); + foreach (ADObjectId id in ids) + { + account = GetExchangeAccount(runSpace, id.ToString()); + if (account != null) + list.Add(account); + } + ids = (IList)GetPSObjectProperty(mailbox, "AcceptMessagesOnlyFromDLMembers"); + foreach (ADObjectId id in ids) + { + account = GetExchangeAccount(runSpace, id.ToString()); + if (account != null) + list.Add(account); + } - return list.ToArray(); - } + return list.ToArray(); + } - private void SetAccountIds(Runspace runspace, string[] accounts, - out MultiValuedProperty ids, out MultiValuedProperty dlIds) - { - ids = MultiValuedProperty.Empty; - dlIds = MultiValuedProperty.Empty; + private void SetAccountIds(Runspace runspace, string[] accounts, + out MultiValuedProperty ids, out MultiValuedProperty dlIds) + { + ids = MultiValuedProperty.Empty; + dlIds = MultiValuedProperty.Empty; - if (accounts == null || accounts.Length == 0) - return; + if (accounts == null || accounts.Length == 0) + return; - ids = new MultiValuedProperty(); - dlIds = new MultiValuedProperty(); + ids = new MultiValuedProperty(); + dlIds = new MultiValuedProperty(); - string dn = null; - string type = null; - foreach (string account in accounts) - { - type = GetRecipientType(runspace, account, out dn); - if (type == "MailUniversalDistributionGroup") - dlIds.Add(new ADObjectId(dn)); - else - ids.Add(new ADObjectId(dn)); - } - if (ids.Count == 0) - ids = MultiValuedProperty.Empty; - if (dlIds.Count == 0) - dlIds = MultiValuedProperty.Empty; - } + string dn = null; + string type = null; + foreach (string account in accounts) + { + type = GetRecipientType(runspace, account, out dn); + if (type == "MailUniversalDistributionGroup") + dlIds.Add(new ADObjectId(dn)); + else + ids.Add(new ADObjectId(dn)); + } + if (ids.Count == 0) + ids = MultiValuedProperty.Empty; + if (dlIds.Count == 0) + dlIds = MultiValuedProperty.Empty; + } - private ExchangeAccount[] GetRejectedAccounts(Runspace runSpace, PSObject mailbox) - { - List list = new List(); - ExchangeAccount account = null; - IList ids = - (IList)GetPSObjectProperty(mailbox, "RejectMessagesFrom"); - foreach (ADObjectId id in ids) - { - account = GetExchangeAccount(runSpace, id.ToString()); - if (account != null) - list.Add(account); - } - ids = (IList)GetPSObjectProperty(mailbox, "RejectMessagesFromDLMembers"); - foreach (ADObjectId id in ids) - { - account = GetExchangeAccount(runSpace, id.ToString()); - if (account != null) - list.Add(account); - } - return list.ToArray(); - } + private ExchangeAccount[] GetRejectedAccounts(Runspace runSpace, PSObject mailbox) + { + List list = new List(); + ExchangeAccount account = null; + IList ids = + (IList)GetPSObjectProperty(mailbox, "RejectMessagesFrom"); + foreach (ADObjectId id in ids) + { + account = GetExchangeAccount(runSpace, id.ToString()); + if (account != null) + list.Add(account); + } + ids = (IList)GetPSObjectProperty(mailbox, "RejectMessagesFromDLMembers"); + foreach (ADObjectId id in ids) + { + account = GetExchangeAccount(runSpace, id.ToString()); + if (account != null) + list.Add(account); + } + return list.ToArray(); + } - internal ExchangeAccount GetExchangeAccount(Runspace runSpace, string id) - { - return GetOrganizationAccount(runSpace, null, id); - } + internal ExchangeAccount GetExchangeAccount(Runspace runSpace, string id) + { + return GetOrganizationAccount(runSpace, null, id); + } - internal ExchangeAccount GetOrganizationAccount(Runspace runSpace, string organizationId, string id) - { - if (string.IsNullOrEmpty(id)) - return null; + internal ExchangeAccount GetOrganizationAccount(Runspace runSpace, string organizationId, string id) + { + if (string.IsNullOrEmpty(id)) + return null; - ExchangeAccount ret = null; - Command cmd = new Command("Get-Recipient"); - cmd.Parameters.Add("Identity", id); - Collection result = ExecuteShellCommand(runSpace, cmd); - if (result != null && result.Count > 0) - { - //check for organization - if (!string.IsNullOrEmpty(organizationId)) - { - string attr1 = (string)GetPSObjectProperty(result[0], "CustomAttribute1"); - if (!string.Equals(organizationId, attr1, StringComparison.InvariantCultureIgnoreCase)) - return ret; - } - ret = new ExchangeAccount(); - ret.AccountName = (string)GetPSObjectProperty(result[0], "Alias"); - ret.DisplayName = (string)GetPSObjectProperty(result[0], "DisplayName"); - ret.PrimaryEmailAddress = ObjToString(GetPSObjectProperty(result[0], "PrimarySmtpAddress")); - ret.AccountType = ParseAccountType(ObjToString(GetPSObjectProperty(result[0], "RecipientType"))); - if (ret.AccountType == ExchangeAccountType.Contact) - { - string email = ObjToString(GetPSObjectProperty(result[0], "ExternalEmailAddress")); - if (!string.IsNullOrEmpty(email) && email.StartsWith("SMTP:")) - ret.PrimaryEmailAddress = email.Substring(5); - } - } - return ret; - } + ExchangeAccount ret = null; + Command cmd = new Command("Get-Recipient"); + cmd.Parameters.Add("Identity", id); + Collection result = ExecuteShellCommand(runSpace, cmd); + if (result != null && result.Count > 0) + { + //check for organization + if (!string.IsNullOrEmpty(organizationId)) + { + string attr1 = (string)GetPSObjectProperty(result[0], "CustomAttribute1"); + if (!string.Equals(organizationId, attr1, StringComparison.InvariantCultureIgnoreCase)) + return ret; + } + ret = new ExchangeAccount(); + ret.AccountName = (string)GetPSObjectProperty(result[0], "Alias"); + ret.DisplayName = (string)GetPSObjectProperty(result[0], "DisplayName"); + ret.PrimaryEmailAddress = ObjToString(GetPSObjectProperty(result[0], "PrimarySmtpAddress")); + ret.AccountType = ParseAccountType(ObjToString(GetPSObjectProperty(result[0], "RecipientType"))); + if (ret.AccountType == ExchangeAccountType.Contact) + { + string email = ObjToString(GetPSObjectProperty(result[0], "ExternalEmailAddress")); + if (!string.IsNullOrEmpty(email) && email.StartsWith("SMTP:")) + ret.PrimaryEmailAddress = email.Substring(5); + } + } + return ret; + } - private ExchangeAccountType ParseAccountType(string type) - { - ExchangeAccountType ret = ExchangeAccountType.Mailbox; - switch (type) - { - case "UserMailbox": - ret = ExchangeAccountType.Mailbox; - break; - case "MailContact": - ret = ExchangeAccountType.Contact; - break; - case "MailUniversalDistributionGroup": - ret = ExchangeAccountType.DistributionList; - break; - case "PublicFolder": - ret = ExchangeAccountType.PublicFolder; - break; - } - return ret; - } + private ExchangeAccountType ParseAccountType(string type) + { + ExchangeAccountType ret = ExchangeAccountType.Mailbox; + switch (type) + { + case "UserMailbox": + ret = ExchangeAccountType.Mailbox; + break; + case "MailContact": + ret = ExchangeAccountType.Contact; + break; + case "MailUniversalDistributionGroup": + ret = ExchangeAccountType.DistributionList; + break; + case "PublicFolder": + ret = ExchangeAccountType.PublicFolder; + break; + } + return ret; + } - private string GetRecipientDistinguishedName(Runspace runSpace, string id) - { - if (string.IsNullOrEmpty(id)) - return null; + private string GetRecipientDistinguishedName(Runspace runSpace, string id) + { + if (string.IsNullOrEmpty(id)) + return null; - string dn = null; - Command cmd = new Command("Get-Recipient"); - cmd.Parameters.Add("Identity", id); - Collection result = ExecuteShellCommand(runSpace, cmd); - if (result != null && result.Count > 0) - { - dn = (string)GetPSObjectProperty(result[0], "DistinguishedName"); - } - return dn; - } + string dn = null; + Command cmd = new Command("Get-Recipient"); + cmd.Parameters.Add("Identity", id); + Collection result = ExecuteShellCommand(runSpace, cmd); + if (result != null && result.Count > 0) + { + dn = (string)GetPSObjectProperty(result[0], "DistinguishedName"); + } + return dn; + } - private string GetRecipientType(Runspace runSpace, string id, out string name) - { - name = null; - if (string.IsNullOrEmpty(id)) - return null; + private string GetRecipientType(Runspace runSpace, string id, out string name) + { + name = null; + if (string.IsNullOrEmpty(id)) + return null; - string type = null; - Command cmd = new Command("Get-Recipient"); - cmd.Parameters.Add("Identity", id); - Collection result = ExecuteShellCommand(runSpace, cmd); - if (result != null && result.Count > 0) - { - name = (string)GetPSObjectProperty(result[0], "DistinguishedName"); - type = GetPSObjectProperty(result[0], "RecipientType").ToString(); - } - return type; - } + string type = null; + Command cmd = new Command("Get-Recipient"); + cmd.Parameters.Add("Identity", id); + Collection result = ExecuteShellCommand(runSpace, cmd); + if (result != null && result.Count > 0) + { + name = (string)GetPSObjectProperty(result[0], "DistinguishedName"); + type = GetPSObjectProperty(result[0], "RecipientType").ToString(); + } + return type; + } - private ExchangeMailboxStatistics GetMailboxStatisticsInternal(string id) - { - ExchangeLog.LogStart("GetMailboxStatisticsInternal"); - ExchangeLog.DebugInfo("Account: {0}", id); + virtual internal ExchangeMailboxStatistics GetMailboxStatisticsInternal(string id) + { + ExchangeLog.LogStart("GetMailboxStatisticsInternal"); + ExchangeLog.DebugInfo("Account: {0}", id); - ExchangeMailboxStatistics info = new ExchangeMailboxStatistics(); - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + ExchangeMailboxStatistics info = new ExchangeMailboxStatistics(); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); - Collection result = GetMailboxObject(runSpace, id); - PSObject mailbox = result[0]; + Collection result = GetMailboxObject(runSpace, id); + PSObject mailbox = result[0]; - string dn = GetResultObjectDN(result); - string path = AddADPrefix(dn); - DirectoryEntry entry = GetADObject(path); - info.Enabled = !(bool)entry.InvokeGet("AccountDisabled"); + string dn = GetResultObjectDN(result); + string path = AddADPrefix(dn); + DirectoryEntry entry = GetADObject(path); + info.Enabled = !(bool)entry.InvokeGet("AccountDisabled"); - info.DisplayName = (string)GetPSObjectProperty(mailbox, "DisplayName"); - SmtpAddress smtpAddress = (SmtpAddress)GetPSObjectProperty(mailbox, "PrimarySmtpAddress"); - if (smtpAddress != null) - info.PrimaryEmailAddress = smtpAddress.ToString(); + info.DisplayName = (string)GetPSObjectProperty(mailbox, "DisplayName"); + SmtpAddress smtpAddress = (SmtpAddress)GetPSObjectProperty(mailbox, "PrimarySmtpAddress"); + if (smtpAddress != null) + info.PrimaryEmailAddress = smtpAddress.ToString(); - info.MaxSize = ConvertUnlimitedToBytes((Unlimited)GetPSObjectProperty(mailbox, "ProhibitSendReceiveQuota")); - DateTime? whenCreated = (DateTime?)GetPSObjectProperty(mailbox, "WhenCreated"); - info.AccountCreated = ConvertNullableToDateTime(whenCreated); - //Client Access - Command cmd = new Command("Get-CASMailbox"); - cmd.Parameters.Add("Identity", id); - result = ExecuteShellCommand(runSpace, cmd); - mailbox = result[0]; + info.MaxSize = ConvertUnlimitedToBytes((Unlimited)GetPSObjectProperty(mailbox, "ProhibitSendReceiveQuota")); + DateTime? whenCreated = (DateTime?)GetPSObjectProperty(mailbox, "WhenCreated"); + info.AccountCreated = ConvertNullableToDateTime(whenCreated); + //Client Access + Command cmd = new Command("Get-CASMailbox"); + cmd.Parameters.Add("Identity", id); + result = ExecuteShellCommand(runSpace, cmd); + mailbox = result[0]; - info.ActiveSyncEnabled = (bool)GetPSObjectProperty(mailbox, "ActiveSyncEnabled"); - info.OWAEnabled = (bool)GetPSObjectProperty(mailbox, "OWAEnabled"); - info.MAPIEnabled = (bool)GetPSObjectProperty(mailbox, "MAPIEnabled"); - info.POPEnabled = (bool)GetPSObjectProperty(mailbox, "PopEnabled"); - info.IMAPEnabled = (bool)GetPSObjectProperty(mailbox, "ImapEnabled"); + info.ActiveSyncEnabled = (bool)GetPSObjectProperty(mailbox, "ActiveSyncEnabled"); + info.OWAEnabled = (bool)GetPSObjectProperty(mailbox, "OWAEnabled"); + info.MAPIEnabled = (bool)GetPSObjectProperty(mailbox, "MAPIEnabled"); + info.POPEnabled = (bool)GetPSObjectProperty(mailbox, "PopEnabled"); + info.IMAPEnabled = (bool)GetPSObjectProperty(mailbox, "ImapEnabled"); - //Statistics - cmd = new Command("Get-MailboxStatistics"); - cmd.Parameters.Add("Identity", id); - result = ExecuteShellCommand(runSpace, cmd); - if (result.Count > 0) - { - PSObject statistics = result[0]; - Unlimited totalItemSize = - (Unlimited)GetPSObjectProperty(statistics, "TotalItemSize"); - info.TotalSize = ConvertUnlimitedToBytes(totalItemSize); - uint? itemCount = (uint?)GetPSObjectProperty(statistics, "ItemCount"); - info.TotalItems = ConvertNullableToInt32(itemCount); - DateTime? lastLogoffTime = (DateTime?)GetPSObjectProperty(statistics, "LastLogoffTime"); - DateTime? lastLogonTime = (DateTime?)GetPSObjectProperty(statistics, "LastLogonTime"); - info.LastLogoff = ConvertNullableToDateTime(lastLogoffTime); - info.LastLogon = ConvertNullableToDateTime(lastLogonTime); - } - else - { - info.TotalSize = 0; - info.TotalItems = 0; - info.LastLogoff = DateTime.MinValue; - info.LastLogon = DateTime.MinValue; - } - } - finally - { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("GetMailboxStatisticsInternal"); - return info; - } + //Statistics + cmd = new Command("Get-MailboxStatistics"); + cmd.Parameters.Add("Identity", id); + result = ExecuteShellCommand(runSpace, cmd); + if (result.Count > 0) + { + PSObject statistics = result[0]; + Unlimited totalItemSize = + (Unlimited)GetPSObjectProperty(statistics, "TotalItemSize"); + info.TotalSize = ConvertUnlimitedToBytes(totalItemSize); + uint? itemCount = (uint?)GetPSObjectProperty(statistics, "ItemCount"); + info.TotalItems = ConvertNullableToInt32(itemCount); + DateTime? lastLogoffTime = (DateTime?)GetPSObjectProperty(statistics, "LastLogoffTime"); + DateTime? lastLogonTime = (DateTime?)GetPSObjectProperty(statistics, "LastLogonTime"); + info.LastLogoff = ConvertNullableToDateTime(lastLogoffTime); + info.LastLogon = ConvertNullableToDateTime(lastLogonTime); + } + else + { + info.TotalSize = 0; + info.TotalItems = 0; + info.LastLogoff = DateTime.MinValue; + info.LastLogon = DateTime.MinValue; + } + } + finally + { + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("GetMailboxStatisticsInternal"); + return info; + } - private Collection GetMailboxObject(Runspace runSpace, string id) - { - Command cmd = new Command("Get-Mailbox"); - cmd.Parameters.Add("Identity", id); - Collection result = ExecuteShellCommand(runSpace, cmd); - return result; - } + virtual internal Collection GetMailboxObject(Runspace runSpace, string id) + { + Command cmd = new Command("Get-Mailbox"); + cmd.Parameters.Add("Identity", id); + Collection result = ExecuteShellCommand(runSpace, cmd); + return result; + } - #endregion + #endregion - #region Contacts - private void CreateContactInternal( - string organizationId, - string organizationDistinguishedName, - string contactDisplayName, - string contactAccountName, - string contactEmail, - string defaultOrganizationDomain) - { - ExchangeLog.LogStart("CreateContactInternal"); - ExchangeLog.DebugInfo("Organization Id: {0}", organizationId); - ExchangeLog.DebugInfo("Name: {0}", contactDisplayName); - ExchangeLog.DebugInfo("Account: {0}", contactAccountName); - ExchangeLog.DebugInfo("Email: {0}", contactEmail); + #region Contacts + private void CreateContactInternal( + string organizationId, + string organizationDistinguishedName, + string contactDisplayName, + string contactAccountName, + string contactEmail, + string defaultOrganizationDomain) + { + ExchangeLog.LogStart("CreateContactInternal"); + ExchangeLog.DebugInfo("Organization Id: {0}", organizationId); + ExchangeLog.DebugInfo("Name: {0}", contactDisplayName); + ExchangeLog.DebugInfo("Account: {0}", contactAccountName); + ExchangeLog.DebugInfo("Email: {0}", contactEmail); - ExchangeTransaction transaction = StartTransaction(); + ExchangeTransaction transaction = StartTransaction(); - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); - string ouName = ConvertADPathToCanonicalName(organizationDistinguishedName); - string tempEmail = string.Format("{0}@{1}", Guid.NewGuid().ToString("N"), defaultOrganizationDomain); - //create contact - Command cmd = new Command("New-MailContact"); - cmd.Parameters.Add("Name", contactAccountName); - cmd.Parameters.Add("DisplayName", contactDisplayName); - cmd.Parameters.Add("OrganizationalUnit", ouName); - cmd.Parameters.Add("Alias", contactAccountName); - cmd.Parameters.Add("ExternalEmailAddress", tempEmail); - Collection result = ExecuteShellCommand(runSpace, cmd); - string id = GetResultObjectDN(result); + string ouName = ConvertADPathToCanonicalName(organizationDistinguishedName); + string tempEmail = string.Format("{0}@{1}", Guid.NewGuid().ToString("N"), defaultOrganizationDomain); + //create contact + Command cmd = new Command("New-MailContact"); + cmd.Parameters.Add("Name", contactAccountName); + cmd.Parameters.Add("DisplayName", contactDisplayName); + cmd.Parameters.Add("OrganizationalUnit", ouName); + cmd.Parameters.Add("Alias", contactAccountName); + cmd.Parameters.Add("ExternalEmailAddress", tempEmail); + Collection result = ExecuteShellCommand(runSpace, cmd); + string id = GetResultObjectDN(result); - transaction.RegisterNewContact(id); + transaction.RegisterNewContact(id); - //update contact - cmd = new Command("Set-MailContact"); - cmd.Parameters.Add("Identity", contactAccountName); - cmd.Parameters.Add("EmailAddressPolicyEnabled", false); - cmd.Parameters.Add("CustomAttribute1", organizationId); - cmd.Parameters.Add("WindowsEmailAddress", tempEmail); - ExecuteShellCommand(runSpace, cmd); + //update contact + cmd = new Command("Set-MailContact"); + cmd.Parameters.Add("Identity", contactAccountName); + cmd.Parameters.Add("EmailAddressPolicyEnabled", false); + cmd.Parameters.Add("CustomAttribute1", organizationId); + cmd.Parameters.Add("WindowsEmailAddress", tempEmail); + ExecuteShellCommand(runSpace, cmd); - SetContactEmail(id, contactEmail); + SetContactEmail(id, contactEmail); - } - catch (Exception ex) - { - ExchangeLog.LogError("CreateContactInternal", ex); - RollbackTransaction(transaction); - throw; - } - finally - { + } + catch (Exception ex) + { + ExchangeLog.LogError("CreateContactInternal", ex); + RollbackTransaction(transaction); + throw; + } + finally + { - CloseRunspace(runSpace); - } + CloseRunspace(runSpace); + } - ExchangeLog.LogEnd("CreateContactInternal"); - } + ExchangeLog.LogEnd("CreateContactInternal"); + } - private void DeleteContactInternal(string accountName) - { - ExchangeLog.LogStart("DeleteContactInternal"); - ExchangeLog.DebugInfo("Account Name: {0}", accountName); + private void DeleteContactInternal(string accountName) + { + ExchangeLog.LogStart("DeleteContactInternal"); + ExchangeLog.DebugInfo("Account Name: {0}", accountName); - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); - RemoveContact(runSpace, accountName); - } - finally - { + RemoveContact(runSpace, accountName); + } + finally + { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("DeleteContactInternal"); - } + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("DeleteContactInternal"); + } - private void RemoveContact(Runspace runSpace, string id) - { - ExchangeLog.LogStart("RemoveContact"); - Command cmd = new Command("Remove-MailContact"); - cmd.Parameters.Add("Identity", id); - cmd.Parameters.Add("Confirm", false); - ExecuteShellCommand(runSpace, cmd); - ExchangeLog.LogEnd("RemoveContact"); - } + private void RemoveContact(Runspace runSpace, string id) + { + ExchangeLog.LogStart("RemoveContact"); + Command cmd = new Command("Remove-MailContact"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("Confirm", false); + ExecuteShellCommand(runSpace, cmd); + ExchangeLog.LogEnd("RemoveContact"); + } - private ExchangeContact GetContactGeneralSettingsInternal(string accountName) - { - ExchangeLog.LogStart("GetContactGeneralSettingsInternal"); - ExchangeLog.DebugInfo("Account: {0}", accountName); + private ExchangeContact GetContactGeneralSettingsInternal(string accountName) + { + ExchangeLog.LogStart("GetContactGeneralSettingsInternal"); + ExchangeLog.DebugInfo("Account: {0}", accountName); - ExchangeContact info = new ExchangeContact(); - info.AccountName = accountName; - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + ExchangeContact info = new ExchangeContact(); + info.AccountName = accountName; + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); - Command cmd = new Command("Get-MailContact"); - cmd.Parameters.Add("Identity", accountName); - Collection result = ExecuteShellCommand(runSpace, cmd); - PSObject contact = result[0]; - string id = GetResultObjectDN(result); + Command cmd = new Command("Get-MailContact"); + cmd.Parameters.Add("Identity", accountName); + Collection result = ExecuteShellCommand(runSpace, cmd); + PSObject contact = result[0]; + string id = GetResultObjectDN(result); - info.DisplayName = (string)GetPSObjectProperty(contact, "DisplayName"); - info.HideFromAddressBook = (bool)GetPSObjectProperty(contact, "HiddenFromAddressListsEnabled"); - info.EmailAddress = GetContactEmail(id); - info.UseMapiRichTextFormat = (int)GetPSObjectProperty(contact, "UseMapiRichTextFormat"); + info.DisplayName = (string)GetPSObjectProperty(contact, "DisplayName"); + info.HideFromAddressBook = (bool)GetPSObjectProperty(contact, "HiddenFromAddressListsEnabled"); + info.EmailAddress = GetContactEmail(id); + info.UseMapiRichTextFormat = (int)GetPSObjectProperty(contact, "UseMapiRichTextFormat"); - cmd = new Command("Get-Contact"); - cmd.Parameters.Add("Identity", accountName); - result = ExecuteShellCommand(runSpace, cmd); - PSObject user = result[0]; + cmd = new Command("Get-Contact"); + cmd.Parameters.Add("Identity", accountName); + result = ExecuteShellCommand(runSpace, cmd); + PSObject user = result[0]; - info.FirstName = (string)GetPSObjectProperty(user, "FirstName"); - info.Initials = (string)GetPSObjectProperty(user, "Initials"); - info.LastName = (string)GetPSObjectProperty(user, "LastName"); + info.FirstName = (string)GetPSObjectProperty(user, "FirstName"); + info.Initials = (string)GetPSObjectProperty(user, "Initials"); + info.LastName = (string)GetPSObjectProperty(user, "LastName"); - info.Address = (string)GetPSObjectProperty(user, "StreetAddress"); - info.City = (string)GetPSObjectProperty(user, "City"); - info.State = (string)GetPSObjectProperty(user, "StateOrProvince"); - info.Zip = (string)GetPSObjectProperty(user, "PostalCode"); - info.Country = CountryInfoToString((CountryInfo)GetPSObjectProperty(user, "CountryOrRegion")); - info.JobTitle = (string)GetPSObjectProperty(user, "Title"); - info.Company = (string)GetPSObjectProperty(user, "Company"); - info.Department = (string)GetPSObjectProperty(user, "Department"); - info.Office = (string)GetPSObjectProperty(user, "Office"); - info.ManagerAccount = GetExchangeAccount(runSpace, ObjToString(GetPSObjectProperty(user, "Manager"))); - info.BusinessPhone = (string)GetPSObjectProperty(user, "Phone"); - info.Fax = (string)GetPSObjectProperty(user, "Fax"); - info.HomePhone = (string)GetPSObjectProperty(user, "HomePhone"); - info.MobilePhone = (string)GetPSObjectProperty(user, "MobilePhone"); - info.Pager = (string)GetPSObjectProperty(user, "Pager"); - info.WebPage = (string)GetPSObjectProperty(user, "WebPage"); - info.Notes = (string)GetPSObjectProperty(user, "Notes"); + info.Address = (string)GetPSObjectProperty(user, "StreetAddress"); + info.City = (string)GetPSObjectProperty(user, "City"); + info.State = (string)GetPSObjectProperty(user, "StateOrProvince"); + info.Zip = (string)GetPSObjectProperty(user, "PostalCode"); + info.Country = CountryInfoToString((CountryInfo)GetPSObjectProperty(user, "CountryOrRegion")); + info.JobTitle = (string)GetPSObjectProperty(user, "Title"); + info.Company = (string)GetPSObjectProperty(user, "Company"); + info.Department = (string)GetPSObjectProperty(user, "Department"); + info.Office = (string)GetPSObjectProperty(user, "Office"); + info.ManagerAccount = GetExchangeAccount(runSpace, ObjToString(GetPSObjectProperty(user, "Manager"))); + info.BusinessPhone = (string)GetPSObjectProperty(user, "Phone"); + info.Fax = (string)GetPSObjectProperty(user, "Fax"); + info.HomePhone = (string)GetPSObjectProperty(user, "HomePhone"); + info.MobilePhone = (string)GetPSObjectProperty(user, "MobilePhone"); + info.Pager = (string)GetPSObjectProperty(user, "Pager"); + info.WebPage = (string)GetPSObjectProperty(user, "WebPage"); + info.Notes = (string)GetPSObjectProperty(user, "Notes"); info.SAMAccountName = string.Format("{0}\\{1}", GetNETBIOSDomainName(), (string)GetPSObjectProperty(user, "Name")); - } - finally - { + } + finally + { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("GetContactGeneralSettingsInternal"); - return info; - } + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("GetContactGeneralSettingsInternal"); + return info; + } - private void SetContactEmail(string id, string email) - { - string cn = ActiveDirectoryUtils.AddADPrefix(id, PrimaryDomainController); - DirectoryEntry de = ActiveDirectoryUtils.GetADObject(cn); - ActiveDirectoryUtils.SetADObjectPropertyValue(de, "targetAddress", "SMTP:" + email); - //ActiveDirectoryUtils.SetADObjectPropertyValue(de, "mail", email); - de.CommitChanges(); + private void SetContactEmail(string id, string email) + { + string cn = ActiveDirectoryUtils.AddADPrefix(id, PrimaryDomainController); + DirectoryEntry de = ActiveDirectoryUtils.GetADObject(cn); + ActiveDirectoryUtils.SetADObjectPropertyValue(de, "targetAddress", "SMTP:" + email); + //ActiveDirectoryUtils.SetADObjectPropertyValue(de, "mail", email); + de.CommitChanges(); - } + } - private string GetContactEmail(string id) - { - string cn = ActiveDirectoryUtils.AddADPrefix(id, PrimaryDomainController); - DirectoryEntry de = ActiveDirectoryUtils.GetADObject(cn); - string email = ActiveDirectoryUtils.GetADObjectStringProperty(de, "targetAddress"); - if (email != null && email.ToLower().StartsWith("smtp:")) - email = email.Substring(5); - return email; - } + private string GetContactEmail(string id) + { + string cn = ActiveDirectoryUtils.AddADPrefix(id, PrimaryDomainController); + DirectoryEntry de = ActiveDirectoryUtils.GetADObject(cn); + string email = ActiveDirectoryUtils.GetADObjectStringProperty(de, "targetAddress"); + if (email != null && email.ToLower().StartsWith("smtp:")) + email = email.Substring(5); + return email; + } - private void SetContactGeneralSettingsInternal(string accountName, string displayName, string email, - bool hideFromAddressBook, string firstName, string initials, string lastName, string address, - string city, string state, string zip, string country, string jobTitle, string company, - string department, string office, string managerAccountName, string businessPhone, string fax, - string homePhone, string mobilePhone, string pager, string webPage, string notes, int useMapiRichTextFormat, string defaultDomain) - { - ExchangeLog.LogStart("SetContactGeneralSettingsInternal"); - ExchangeLog.DebugInfo("Account: {0}", accountName); + private void SetContactGeneralSettingsInternal(string accountName, string displayName, string email, + bool hideFromAddressBook, string firstName, string initials, string lastName, string address, + string city, string state, string zip, string country, string jobTitle, string company, + string department, string office, string managerAccountName, string businessPhone, string fax, + string homePhone, string mobilePhone, string pager, string webPage, string notes, int useMapiRichTextFormat, string defaultDomain) + { + ExchangeLog.LogStart("SetContactGeneralSettingsInternal"); + ExchangeLog.DebugInfo("Account: {0}", accountName); - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); - Command cmd = new Command("Get-MailContact"); - cmd.Parameters.Add("Identity", accountName); - Collection result = ExecuteShellCommand(runSpace, cmd); + Command cmd = new Command("Get-MailContact"); + cmd.Parameters.Add("Identity", accountName); + Collection result = ExecuteShellCommand(runSpace, cmd); - string id = GetResultObjectDN(result); - string tempEmail = SmtpAddressToString((SmtpAddress)GetPSObjectProperty(result[0], "PrimarySmtpAddress")); - string[] parts = tempEmail.Split('@'); - if (parts != null && parts.Length > 0) - tempEmail = parts[0] + '@' + defaultDomain; + string id = GetResultObjectDN(result); + string tempEmail = SmtpAddressToString((SmtpAddress)GetPSObjectProperty(result[0], "PrimarySmtpAddress")); + string[] parts = tempEmail.Split('@'); + if (parts != null && parts.Length > 0) + tempEmail = parts[0] + '@' + defaultDomain; - cmd = new Command("Set-MailContact"); - cmd.Parameters.Add("Identity", accountName); + cmd = new Command("Set-MailContact"); + cmd.Parameters.Add("Identity", accountName); - cmd.Parameters.Add("DisplayName", displayName); - cmd.Parameters.Add("HiddenFromAddressListsEnabled", hideFromAddressBook); - cmd.Parameters.Add("ExternalEmailAddress", tempEmail); - cmd.Parameters.Add("UseMapiRichTextFormat", (UseMapiRichTextFormat)useMapiRichTextFormat); - cmd.Parameters.Add("WindowsEmailAddress", tempEmail); - ExecuteShellCommand(runSpace, cmd); + cmd.Parameters.Add("DisplayName", displayName); + cmd.Parameters.Add("HiddenFromAddressListsEnabled", hideFromAddressBook); + cmd.Parameters.Add("ExternalEmailAddress", tempEmail); + cmd.Parameters.Add("UseMapiRichTextFormat", (UseMapiRichTextFormat)useMapiRichTextFormat); + cmd.Parameters.Add("WindowsEmailAddress", tempEmail); + ExecuteShellCommand(runSpace, cmd); - cmd = new Command("Set-Contact"); - cmd.Parameters.Add("Identity", accountName); - cmd.Parameters.Add("FirstName", firstName); - cmd.Parameters.Add("Initials", initials); - cmd.Parameters.Add("LastName", lastName); - cmd.Parameters.Add("StreetAddress", address); - cmd.Parameters.Add("City", city); - cmd.Parameters.Add("StateOrProvince", state); - cmd.Parameters.Add("PostalCode", zip); - cmd.Parameters.Add("CountryOrRegion", ParseCountryInfo(country)); - cmd.Parameters.Add("Title", jobTitle); - cmd.Parameters.Add("Company", company); - cmd.Parameters.Add("Department", department); - cmd.Parameters.Add("Office", office); - cmd.Parameters.Add("Manager", managerAccountName); - cmd.Parameters.Add("Phone", businessPhone); - cmd.Parameters.Add("Fax", fax); - cmd.Parameters.Add("HomePhone", homePhone); - cmd.Parameters.Add("MobilePhone", mobilePhone); - cmd.Parameters.Add("Pager", pager); - cmd.Parameters.Add("WebPage", webPage); - cmd.Parameters.Add("Notes", notes); + cmd = new Command("Set-Contact"); + cmd.Parameters.Add("Identity", accountName); + cmd.Parameters.Add("FirstName", firstName); + cmd.Parameters.Add("Initials", initials); + cmd.Parameters.Add("LastName", lastName); + cmd.Parameters.Add("StreetAddress", address); + cmd.Parameters.Add("City", city); + cmd.Parameters.Add("StateOrProvince", state); + cmd.Parameters.Add("PostalCode", zip); + cmd.Parameters.Add("CountryOrRegion", ParseCountryInfo(country)); + cmd.Parameters.Add("Title", jobTitle); + cmd.Parameters.Add("Company", company); + cmd.Parameters.Add("Department", department); + cmd.Parameters.Add("Office", office); + cmd.Parameters.Add("Manager", managerAccountName); + cmd.Parameters.Add("Phone", businessPhone); + cmd.Parameters.Add("Fax", fax); + cmd.Parameters.Add("HomePhone", homePhone); + cmd.Parameters.Add("MobilePhone", mobilePhone); + cmd.Parameters.Add("Pager", pager); + cmd.Parameters.Add("WebPage", webPage); + cmd.Parameters.Add("Notes", notes); - ExecuteShellCommand(runSpace, cmd); + ExecuteShellCommand(runSpace, cmd); - SetContactEmail(id, email); + SetContactEmail(id, email); - } - finally - { + } + finally + { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("SetContactGeneralSettingsInternal"); - } + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("SetContactGeneralSettingsInternal"); + } - private ExchangeContact GetContactMailFlowSettingsInternal(string accountName) - { - ExchangeLog.LogStart("GetContactMailFlowSettingsInternal"); - ExchangeLog.DebugInfo("Account: {0}", accountName); + private ExchangeContact GetContactMailFlowSettingsInternal(string accountName) + { + ExchangeLog.LogStart("GetContactMailFlowSettingsInternal"); + ExchangeLog.DebugInfo("Account: {0}", accountName); - ExchangeContact info = new ExchangeContact(); - info.AccountName = accountName; - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + ExchangeContact info = new ExchangeContact(); + info.AccountName = accountName; + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); - Command cmd = new Command("Get-MailContact"); - cmd.Parameters.Add("Identity", accountName); - Collection result = ExecuteShellCommand(runSpace, cmd); - PSObject contact = result[0]; + Command cmd = new Command("Get-MailContact"); + cmd.Parameters.Add("Identity", accountName); + Collection result = ExecuteShellCommand(runSpace, cmd); + PSObject contact = result[0]; - info.AcceptAccounts = GetAcceptedAccounts(runSpace, contact); - info.RejectAccounts = GetRejectedAccounts(runSpace, contact); - info.RequireSenderAuthentication = (bool)GetPSObjectProperty(contact, "RequireSenderAuthenticationEnabled"); - } - finally - { + info.AcceptAccounts = GetAcceptedAccounts(runSpace, contact); + info.RejectAccounts = GetRejectedAccounts(runSpace, contact); + info.RequireSenderAuthentication = (bool)GetPSObjectProperty(contact, "RequireSenderAuthenticationEnabled"); + } + finally + { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("GetContactMailFlowSettingsInternal"); - return info; - } + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("GetContactMailFlowSettingsInternal"); + return info; + } - private void SetContactMailFlowSettingsInternal(string accountName, string[] acceptAccounts, - string[] rejectAccounts, bool requireSenderAuthentication) - { - ExchangeLog.LogStart("SetContactMailFlowSettingsInternal"); - ExchangeLog.DebugInfo("Account: {0}", accountName); + private void SetContactMailFlowSettingsInternal(string accountName, string[] acceptAccounts, + string[] rejectAccounts, bool requireSenderAuthentication) + { + ExchangeLog.LogStart("SetContactMailFlowSettingsInternal"); + ExchangeLog.DebugInfo("Account: {0}", accountName); - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); - Command cmd = new Command("Set-MailContact"); - cmd.Parameters.Add("Identity", accountName); + Command cmd = new Command("Set-MailContact"); + cmd.Parameters.Add("Identity", accountName); - MultiValuedProperty ids = null; - MultiValuedProperty dlIds = null; + MultiValuedProperty ids = null; + MultiValuedProperty dlIds = null; - SetAccountIds(runSpace, acceptAccounts, out ids, out dlIds); - cmd.Parameters.Add("AcceptMessagesOnlyFrom", ids); - cmd.Parameters.Add("AcceptMessagesOnlyFromDLMembers", dlIds); + SetAccountIds(runSpace, acceptAccounts, out ids, out dlIds); + cmd.Parameters.Add("AcceptMessagesOnlyFrom", ids); + cmd.Parameters.Add("AcceptMessagesOnlyFromDLMembers", dlIds); - SetAccountIds(runSpace, rejectAccounts, out ids, out dlIds); - cmd.Parameters.Add("RejectMessagesFrom", ids); - cmd.Parameters.Add("RejectMessagesFromDLMembers", dlIds); - cmd.Parameters.Add("RequireSenderAuthenticationEnabled", requireSenderAuthentication); + SetAccountIds(runSpace, rejectAccounts, out ids, out dlIds); + cmd.Parameters.Add("RejectMessagesFrom", ids); + cmd.Parameters.Add("RejectMessagesFromDLMembers", dlIds); + cmd.Parameters.Add("RequireSenderAuthenticationEnabled", requireSenderAuthentication); - ExecuteShellCommand(runSpace, cmd); + ExecuteShellCommand(runSpace, cmd); - } - finally - { + } + finally + { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("SetContactMailFlowSettingsInternal"); - } + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("SetContactMailFlowSettingsInternal"); + } - #endregion + #endregion - #region Distribution groups - /// - /// Creates Security Distribution Group - /// - /// - /// - /// - /// LDAP path - private string CreateSecurityDistributionGroup(Runspace runSpace, string ouName, string groupName) - { - ExchangeLog.LogStart("CreateSecurityDistributionGroup"); + #region Distribution groups + /// + /// Creates Security Distribution Group + /// + /// + /// + /// + /// LDAP path + private string CreateSecurityDistributionGroup(Runspace runSpace, string ouName, string groupName) + { + ExchangeLog.LogStart("CreateSecurityDistributionGroup"); - Command cmd = new Command("New-DistributionGroup"); - cmd.Parameters.Add("Name", groupName); - cmd.Parameters.Add("Type", "Security"); - cmd.Parameters.Add("OrganizationalUnit", ouName); - cmd.Parameters.Add("SamAccountName", groupName); - cmd.Parameters.Add("Alias", groupName); + Command cmd = new Command("New-DistributionGroup"); + cmd.Parameters.Add("Name", groupName); + cmd.Parameters.Add("Type", "Security"); + cmd.Parameters.Add("OrganizationalUnit", ouName); + cmd.Parameters.Add("SamAccountName", groupName); + cmd.Parameters.Add("Alias", groupName); - Collection result = ExecuteShellCommand(runSpace, cmd); - string id = CheckResultObjectDN(result); + Collection result = ExecuteShellCommand(runSpace, cmd); + string id = CheckResultObjectDN(result); - ExchangeLog.LogEnd("CreateSecurityDistributionGroup"); - return id; - } + ExchangeLog.LogEnd("CreateSecurityDistributionGroup"); + return id; + } internal string EnableMailSecurityDistributionGroup(Runspace runSpace, string distName, string groupName) - { - ExchangeLog.LogStart("EnableMailSecurityDistributionGroup"); - ExchangeLog.DebugInfo("Group Distinguished Name: {0}", distName); - ExchangeLog.DebugInfo("Group Name: {0}", groupName); + { + ExchangeLog.LogStart("EnableMailSecurityDistributionGroup"); + ExchangeLog.DebugInfo("Group Distinguished Name: {0}", distName); + ExchangeLog.DebugInfo("Group Name: {0}", groupName); - int attempts = 0; - string securityGroupId = null; + int attempts = 0; + string securityGroupId = null; - while (true) - { - try - { - Command cmd = new Command("Enable-DistributionGroup"); - cmd.Parameters.Add("Identity", distName); - cmd.Parameters.Add("Alias", groupName); + while (true) + { + try + { + Command cmd = new Command("Enable-DistributionGroup"); + cmd.Parameters.Add("Identity", distName); + cmd.Parameters.Add("Alias", groupName); - Collection result = ExecuteShellCommand(runSpace, cmd); + Collection result = ExecuteShellCommand(runSpace, cmd); - securityGroupId = CheckResultObjectDN(result); - ExchangeLog.DebugInfo("Result: {0}", securityGroupId); - } - catch (Exception ex) - { - Log.WriteError(ex); - } + securityGroupId = CheckResultObjectDN(result); + ExchangeLog.DebugInfo("Result: {0}", securityGroupId); + } + catch (Exception ex) + { + Log.WriteError(ex); + } - if (securityGroupId != null) - break; + if (securityGroupId != null) + break; - if (attempts > 3) - throw new Exception( - string.Format("Could not enable mail Security Distribution Group '{0}' ", groupName)); + if (attempts > 3) + throw new Exception( + string.Format("Could not enable mail Security Distribution Group '{0}' ", groupName)); - attempts++; - ExchangeLog.LogWarning("Attempt #{0} to enable mail Security Distribution Group failed!", attempts); - // wait 5 sec - System.Threading.Thread.Sleep(5000); - } + attempts++; + ExchangeLog.LogWarning("Attempt #{0} to enable mail Security Distribution Group failed!", attempts); + // wait 5 sec + System.Threading.Thread.Sleep(5000); + } - ExchangeLog.LogEnd("EnableMailSecurityDistributionGroup"); - return securityGroupId; - } + ExchangeLog.LogEnd("EnableMailSecurityDistributionGroup"); + return securityGroupId; + } internal void DisableMailSecurityDistributionGroup(Runspace runSpace, string id) - { - ExchangeLog.LogStart("DisableMailSecurityDistributionGroup"); - ExchangeLog.DebugInfo("Group Id: {0}", id); - Command cmd = new Command("Disable-DistributionGroup"); - cmd.Parameters.Add("Identity", id); - cmd.Parameters.Add("Confirm", false); - ExecuteShellCommand(runSpace, cmd); - ExchangeLog.LogEnd("DisableMailSecurityDistributionGroup"); - } + { + ExchangeLog.LogStart("DisableMailSecurityDistributionGroup"); + ExchangeLog.DebugInfo("Group Id: {0}", id); + Command cmd = new Command("Disable-DistributionGroup"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("Confirm", false); + ExecuteShellCommand(runSpace, cmd); + ExchangeLog.LogEnd("DisableMailSecurityDistributionGroup"); + } internal void UpdateSecurityDistributionGroup(Runspace runSpace, string id, string groupName, bool isConsumer) - { - ExchangeLog.LogStart("UpdateSecurityDistributionGroup"); + { + ExchangeLog.LogStart("UpdateSecurityDistributionGroup"); - Command cmd = new Command("Set-DistributionGroup"); - cmd.Parameters.Add("Identity", id); - cmd.Parameters.Add("EmailAddressPolicyEnabled", false); - cmd.Parameters.Add("CustomAttribute1", groupName); + Command cmd = new Command("Set-DistributionGroup"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("EmailAddressPolicyEnabled", false); + cmd.Parameters.Add("CustomAttribute1", groupName); cmd.Parameters.Add("HiddenFromAddressListsEnabled", !isConsumer); - ExecuteShellCommand(runSpace, cmd); + ExecuteShellCommand(runSpace, cmd); - ExchangeLog.LogEnd("UpdateSecurityDistributionGroup"); - } + ExchangeLog.LogEnd("UpdateSecurityDistributionGroup"); + } private void CreateDistributionListInternal( string organizationId, @@ -3314,73 +3302,73 @@ namespace WebsitePanel.Providers.HostedSolution string managedBy, string[] addressLists) { - ExchangeLog.LogStart("CreateDistributionListInternal"); - ExchangeLog.DebugInfo("Organization Id: {0}", organizationId); - ExchangeLog.DebugInfo("Name: {0}", name); - ExchangeLog.DebugInfo("Domain: {0}", domain); + ExchangeLog.LogStart("CreateDistributionListInternal"); + ExchangeLog.DebugInfo("Organization Id: {0}", organizationId); + ExchangeLog.DebugInfo("Name: {0}", name); + ExchangeLog.DebugInfo("Domain: {0}", domain); - ExchangeTransaction transaction = StartTransaction(); + ExchangeTransaction transaction = StartTransaction(); - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); - string email = string.Format("{0}@{1}", name, domain); - string ouName = ConvertADPathToCanonicalName(organizationDistinguishedName); + string email = string.Format("{0}@{1}", name, domain); + string ouName = ConvertADPathToCanonicalName(organizationDistinguishedName); - Command cmd = new Command("New-DistributionGroup"); - cmd.Parameters.Add("Name", accountName); - cmd.Parameters.Add("DisplayName", displayName); - cmd.Parameters.Add("Type", "Security"); - cmd.Parameters.Add("OrganizationalUnit", ouName); - cmd.Parameters.Add("SamAccountName", accountName); - cmd.Parameters.Add("Alias", accountName); - cmd.Parameters.Add("ManagedBy", managedBy); + Command cmd = new Command("New-DistributionGroup"); + cmd.Parameters.Add("Name", accountName); + cmd.Parameters.Add("DisplayName", displayName); + cmd.Parameters.Add("Type", "Security"); + cmd.Parameters.Add("OrganizationalUnit", ouName); + cmd.Parameters.Add("SamAccountName", accountName); + cmd.Parameters.Add("Alias", accountName); + cmd.Parameters.Add("ManagedBy", managedBy); - Collection result = ExecuteShellCommand(runSpace, cmd); - string id = GetResultObjectDN(result); + Collection result = ExecuteShellCommand(runSpace, cmd); + string id = GetResultObjectDN(result); - transaction.RegisterNewDistributionGroup(id); + transaction.RegisterNewDistributionGroup(id); - //add manager permissions - if (!string.IsNullOrEmpty(managedBy)) - { - AddADPermission(runSpace, accountName, managedBy, "WriteProperty", null, "Member"); - } + //add manager permissions + if (!string.IsNullOrEmpty(managedBy)) + { + AddADPermission(runSpace, accountName, managedBy, "WriteProperty", null, "Member"); + } - string windowsEmailAddress = ObjToString(GetPSObjectProperty(result[0], "WindowsEmailAddress")); + string windowsEmailAddress = ObjToString(GetPSObjectProperty(result[0], "WindowsEmailAddress")); - //update - cmd = new Command("Set-DistributionGroup"); - cmd.Parameters.Add("Identity", id); - cmd.Parameters.Add("EmailAddressPolicyEnabled", false); - cmd.Parameters.Add("CustomAttribute1", organizationId); - cmd.Parameters.Add("CustomAttribute3", windowsEmailAddress); - cmd.Parameters.Add("PrimarySmtpAddress", email); - cmd.Parameters.Add("WindowsEmailAddress", email); - cmd.Parameters.Add("RequireSenderAuthenticationEnabled", false); - ExecuteShellCommand(runSpace, cmd); + //update + cmd = new Command("Set-DistributionGroup"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("EmailAddressPolicyEnabled", false); + cmd.Parameters.Add("CustomAttribute1", organizationId); + cmd.Parameters.Add("CustomAttribute3", windowsEmailAddress); + cmd.Parameters.Add("PrimarySmtpAddress", email); + cmd.Parameters.Add("WindowsEmailAddress", email); + cmd.Parameters.Add("RequireSenderAuthenticationEnabled", false); + ExecuteShellCommand(runSpace, cmd); //fix showInAddressBook Attribute if (addressLists.Length > 0) FixShowInAddressBook(runSpace, email, addressLists, false); - } - catch (Exception ex) - { - ExchangeLog.LogError("CreateDistributionListInternal", ex); - RollbackTransaction(transaction); - throw; - } - finally - { + } + catch (Exception ex) + { + ExchangeLog.LogError("CreateDistributionListInternal", ex); + RollbackTransaction(transaction); + throw; + } + finally + { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("CreateDistributionListInternal"); - } + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("CreateDistributionListInternal"); + } private void FixShowInAddressBook(Runspace runSpace, string accountName, string[] addressLists, bool HideFromAddressList) { @@ -3402,46 +3390,46 @@ namespace WebsitePanel.Providers.HostedSolution dlDEEntry.CommitChanges(); } - private void DeleteDistributionListInternal(string accountName) - { - ExchangeLog.LogStart("DeleteDistributionListInternal"); - ExchangeLog.DebugInfo("Account Name: {0}", accountName); + private void DeleteDistributionListInternal(string accountName) + { + ExchangeLog.LogStart("DeleteDistributionListInternal"); + ExchangeLog.DebugInfo("Account Name: {0}", accountName); - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); - RemoveDistributionGroup(runSpace, accountName); - } - finally - { + RemoveDistributionGroup(runSpace, accountName); + } + finally + { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("DeleteDistributionListInternal"); - } + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("DeleteDistributionListInternal"); + } - internal virtual void RemoveDistributionGroup(Runspace runSpace, string id) - { - ExchangeLog.LogStart("RemoveDistributionGroup"); - Command cmd = new Command("Remove-DistributionGroup"); - cmd.Parameters.Add("Identity", id); - cmd.Parameters.Add("Confirm", false); - ExecuteShellCommand(runSpace, cmd); - ExchangeLog.LogEnd("RemoveDistributionGroup"); - } + internal virtual void RemoveDistributionGroup(Runspace runSpace, string id) + { + ExchangeLog.LogStart("RemoveDistributionGroup"); + Command cmd = new Command("Remove-DistributionGroup"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("Confirm", false); + ExecuteShellCommand(runSpace, cmd); + ExchangeLog.LogEnd("RemoveDistributionGroup"); + } - private ExchangeDistributionList GetDistributionListGeneralSettingsInternal(string accountName) - { - ExchangeLog.LogStart("GetDistributionListGeneralSettingsInternal"); - ExchangeLog.DebugInfo("Account: {0}", accountName); + private ExchangeDistributionList GetDistributionListGeneralSettingsInternal(string accountName) + { + ExchangeLog.LogStart("GetDistributionListGeneralSettingsInternal"); + ExchangeLog.DebugInfo("Account: {0}", accountName); - ExchangeDistributionList info = new ExchangeDistributionList(); - info.AccountName = accountName; - Runspace runSpace = null; - try - { + ExchangeDistributionList info = new ExchangeDistributionList(); + info.AccountName = accountName; + Runspace runSpace = null; + try + { runSpace = OpenRunspace(); @@ -3465,166 +3453,166 @@ namespace WebsitePanel.Providers.HostedSolution info.MembersAccounts = GetGroupMembers(runSpace, accountName); info.Notes = (string)GetPSObjectProperty(group, "Notes"); } - finally - { + finally + { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("GetDistributionListGeneralSettingsInternal"); - return info; - } + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("GetDistributionListGeneralSettingsInternal"); + return info; + } - internal virtual ExchangeAccount GetGroupManagerAccount(Runspace runSpace, PSObject group) - { - return GetExchangeAccount(runSpace, GetGroupManager(group)); - } + internal virtual ExchangeAccount GetGroupManagerAccount(Runspace runSpace, PSObject group) + { + return GetExchangeAccount(runSpace, GetGroupManager(group)); + } - internal virtual string GetGroupManager(PSObject group) - { - return ObjToString(GetPSObjectProperty(group, "ManagedBy")); - } + internal virtual string GetGroupManager(PSObject group) + { + return ObjToString(GetPSObjectProperty(group, "ManagedBy")); + } private void SetDistributionListGeneralSettingsInternal(string accountName, string displayName, bool hideFromAddressBook, string managedBy, string[] memberAccounts, string notes, string[] addressLists) { - ExchangeLog.LogStart("SetDistributionListGeneralSettingsInternal"); - ExchangeLog.DebugInfo("Account: {0}", accountName); + ExchangeLog.LogStart("SetDistributionListGeneralSettingsInternal"); + ExchangeLog.DebugInfo("Account: {0}", accountName); - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); - SetDistributionGroup(runSpace, accountName, displayName, hideFromAddressBook); + SetDistributionGroup(runSpace, accountName, displayName, hideFromAddressBook); - //get old values - Command cmd = new Command("Get-Group"); - cmd.Parameters.Add("Identity", accountName); - Collection result = ExecuteShellCommand(runSpace, cmd); - PSObject group = result[0]; - string manager = GetGroupManager(group); + //get old values + Command cmd = new Command("Get-Group"); + cmd.Parameters.Add("Identity", accountName); + Collection result = ExecuteShellCommand(runSpace, cmd); + PSObject group = result[0]; + string manager = GetGroupManager(group); - //set members - ExchangeAccount[] accounts = GetGroupMembers(runSpace, accountName); - Dictionary existingMembers = new Dictionary(); - Dictionary newMembers = new Dictionary(); - List membersToDelete = new List(); - List membersToAdd = new List(); + //set members + ExchangeAccount[] accounts = GetGroupMembers(runSpace, accountName); + Dictionary existingMembers = new Dictionary(); + Dictionary newMembers = new Dictionary(); + List membersToDelete = new List(); + List membersToAdd = new List(); - foreach (ExchangeAccount account in accounts) - { - existingMembers.Add(account.AccountName.ToLower(), account.AccountName); - } + foreach (ExchangeAccount account in accounts) + { + existingMembers.Add(account.AccountName.ToLower(), account.AccountName); + } - foreach (string member in memberAccounts) - { - newMembers.Add(member.ToLower(), member); - if (!existingMembers.ContainsKey(member.ToLower())) - { - membersToAdd.Add(member); - } - } + foreach (string member in memberAccounts) + { + newMembers.Add(member.ToLower(), member); + if (!existingMembers.ContainsKey(member.ToLower())) + { + membersToAdd.Add(member); + } + } - foreach (string delAccount in existingMembers.Keys) - { - if (!newMembers.ContainsKey(delAccount)) - { - membersToDelete.Add(existingMembers[delAccount]); - } - } + foreach (string delAccount in existingMembers.Keys) + { + if (!newMembers.ContainsKey(delAccount)) + { + membersToDelete.Add(existingMembers[delAccount]); + } + } - foreach (string member in membersToAdd) - { - AddDistributionGroupMember(runSpace, accountName, member); - } + foreach (string member in membersToAdd) + { + AddDistributionGroupMember(runSpace, accountName, member); + } - foreach (string member in membersToDelete) - { - RemoveDistributionGroupMember(runSpace, accountName, member); - } + foreach (string member in membersToDelete) + { + RemoveDistributionGroupMember(runSpace, accountName, member); + } - //remove old manager rights - if (!string.IsNullOrEmpty(manager)) - { - RemoveADPermission(runSpace, accountName, manager, "WriteProperty", null, "Member"); - } + //remove old manager rights + if (!string.IsNullOrEmpty(manager)) + { + RemoveADPermission(runSpace, accountName, manager, "WriteProperty", null, "Member"); + } - SetGroup(runSpace, accountName, managedBy, notes); + SetGroup(runSpace, accountName, managedBy, notes); - if (!string.IsNullOrEmpty(managedBy)) - { - AddADPermission(runSpace, accountName, managedBy, "WriteProperty", null, "Member"); - } + if (!string.IsNullOrEmpty(managedBy)) + { + AddADPermission(runSpace, accountName, managedBy, "WriteProperty", null, "Member"); + } if (addressLists.Length > 0) FixShowInAddressBook(runSpace, accountName, addressLists, hideFromAddressBook); - } - finally - { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("SetDistributionListGeneralSettingsInternal"); - } + } + finally + { + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("SetDistributionListGeneralSettingsInternal"); + } - internal virtual void RemoveDistributionGroupMember(Runspace runSpace, string group, string member) - { - Command cmd = new Command("Remove-DistributionGroupMember"); - cmd.Parameters.Add("Identity", group); - cmd.Parameters.Add("Member", member); - cmd.Parameters.Add("Confirm", false); - ExecuteShellCommand(runSpace, cmd); - } + internal virtual void RemoveDistributionGroupMember(Runspace runSpace, string group, string member) + { + Command cmd = new Command("Remove-DistributionGroupMember"); + cmd.Parameters.Add("Identity", group); + cmd.Parameters.Add("Member", member); + cmd.Parameters.Add("Confirm", false); + ExecuteShellCommand(runSpace, cmd); + } - internal virtual void AddDistributionGroupMember(Runspace runSpace, string group, string member) - { - Command cmd = new Command("Add-DistributionGroupMember"); - cmd.Parameters.Add("Identity", group); - cmd.Parameters.Add("Member", member); - ExecuteShellCommand(runSpace, cmd); - } + internal virtual void AddDistributionGroupMember(Runspace runSpace, string group, string member) + { + Command cmd = new Command("Add-DistributionGroupMember"); + cmd.Parameters.Add("Identity", group); + cmd.Parameters.Add("Member", member); + ExecuteShellCommand(runSpace, cmd); + } - internal virtual void SetGroup(Runspace runSpace, string id, string managedBy, string notes) - { - Command cmd = new Command("Set-Group"); - cmd.Parameters.Add("Identity", id); - cmd.Parameters.Add("ManagedBy", managedBy); - cmd.Parameters.Add("Notes", notes); - ExecuteShellCommand(runSpace, cmd); - } + internal virtual void SetGroup(Runspace runSpace, string id, string managedBy, string notes) + { + Command cmd = new Command("Set-Group"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("ManagedBy", managedBy); + cmd.Parameters.Add("Notes", notes); + ExecuteShellCommand(runSpace, cmd); + } - internal virtual void SetDistributionGroup(Runspace runSpace, string id, string displayName, bool hideFromAddressBook) - { - Command cmd = new Command("Set-DistributionGroup"); - cmd.Parameters.Add("Identity", id); - cmd.Parameters.Add("DisplayName", displayName); - cmd.Parameters.Add("HiddenFromAddressListsEnabled", hideFromAddressBook); - ExecuteShellCommand(runSpace, cmd); - } + internal virtual void SetDistributionGroup(Runspace runSpace, string id, string displayName, bool hideFromAddressBook) + { + Command cmd = new Command("Set-DistributionGroup"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("DisplayName", displayName); + cmd.Parameters.Add("HiddenFromAddressListsEnabled", hideFromAddressBook); + ExecuteShellCommand(runSpace, cmd); + } private void AddDistributionListMembersInternal(string accountName, string[] memberAccounts, string[] addressLists) - { - ExchangeLog.LogStart("AddDistributionListMembersInternal"); - ExchangeLog.DebugInfo("Account: {0}", accountName); + { + ExchangeLog.LogStart("AddDistributionListMembersInternal"); + ExchangeLog.DebugInfo("Account: {0}", accountName); - if (memberAccounts != null && memberAccounts.Length > 0) - { - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + if (memberAccounts != null && memberAccounts.Length > 0) + { + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); - Command cmd = null; + Command cmd = null; - foreach (string member in memberAccounts) - { - cmd = new Command("Add-DistributionGroupMember"); - cmd.Parameters.Add("Identity", accountName); - cmd.Parameters.Add("Member", member); + foreach (string member in memberAccounts) + { + cmd = new Command("Add-DistributionGroupMember"); + cmd.Parameters.Add("Identity", accountName); + cmd.Parameters.Add("Member", member); cmd.Parameters.Add("BypassSecurityGroupManagerCheck", true); - ExecuteShellCommand(runSpace, cmd); - } + ExecuteShellCommand(runSpace, cmd); + } if (addressLists.Length > 0) { @@ -3636,38 +3624,38 @@ namespace WebsitePanel.Providers.HostedSolution FixShowInAddressBook(runSpace, accountName, addressLists, (bool)GetPSObjectProperty(distributionGroup, "HiddenFromAddressListsEnabled")); } - } - finally - { + } + finally + { - CloseRunspace(runSpace); - } - } - ExchangeLog.LogEnd("AddDistributionListMembersInternal"); - } + CloseRunspace(runSpace); + } + } + ExchangeLog.LogEnd("AddDistributionListMembersInternal"); + } private void RemoveDistributionListMembersInternal(string accountName, string[] memberAccounts, string[] addressLists) - { - ExchangeLog.LogStart("RemoveDistributionListMembersInternal"); - ExchangeLog.DebugInfo("Account: {0}", accountName); + { + ExchangeLog.LogStart("RemoveDistributionListMembersInternal"); + ExchangeLog.DebugInfo("Account: {0}", accountName); - if (memberAccounts != null && memberAccounts.Length > 0) - { - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + if (memberAccounts != null && memberAccounts.Length > 0) + { + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); - Command cmd = null; + Command cmd = null; - foreach (string member in memberAccounts) - { - cmd = new Command("Remove-DistributionGroupMember"); - cmd.Parameters.Add("Identity", accountName); - cmd.Parameters.Add("Member", member); - cmd.Parameters.Add("Confirm", false); - ExecuteShellCommand(runSpace, cmd); - } + foreach (string member in memberAccounts) + { + cmd = new Command("Remove-DistributionGroupMember"); + cmd.Parameters.Add("Identity", accountName); + cmd.Parameters.Add("Member", member); + cmd.Parameters.Add("Confirm", false); + ExecuteShellCommand(runSpace, cmd); + } if (addressLists.Length > 0) { @@ -3679,74 +3667,74 @@ namespace WebsitePanel.Providers.HostedSolution FixShowInAddressBook(runSpace, accountName, addressLists, (bool)GetPSObjectProperty(distributionGroup, "HiddenFromAddressListsEnabled")); } - } - finally - { + } + finally + { - CloseRunspace(runSpace); - } - } - ExchangeLog.LogEnd("RemoveDistributionListMembersInternal"); - } + CloseRunspace(runSpace); + } + } + ExchangeLog.LogEnd("RemoveDistributionListMembersInternal"); + } - private ExchangeDistributionList GetDistributionListMailFlowSettingsInternal(string accountName) - { - ExchangeLog.LogStart("GetDistributionListMailFlowSettingsInternal"); - ExchangeLog.DebugInfo("Account: {0}", accountName); + private ExchangeDistributionList GetDistributionListMailFlowSettingsInternal(string accountName) + { + ExchangeLog.LogStart("GetDistributionListMailFlowSettingsInternal"); + ExchangeLog.DebugInfo("Account: {0}", accountName); - ExchangeDistributionList info = new ExchangeDistributionList(); - info.AccountName = accountName; - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + ExchangeDistributionList info = new ExchangeDistributionList(); + info.AccountName = accountName; + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); - Command cmd = new Command("Get-DistributionGroup"); - cmd.Parameters.Add("Identity", accountName); - Collection result = ExecuteShellCommand(runSpace, cmd); - PSObject group = result[0]; + Command cmd = new Command("Get-DistributionGroup"); + cmd.Parameters.Add("Identity", accountName); + Collection result = ExecuteShellCommand(runSpace, cmd); + PSObject group = result[0]; - info.AcceptAccounts = GetAcceptedAccounts(runSpace, group); - info.RejectAccounts = GetRejectedAccounts(runSpace, group); - info.RequireSenderAuthentication = (bool)GetPSObjectProperty(group, "RequireSenderAuthenticationEnabled"); - } - finally - { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("GetDistributionListMailFlowSettingsInternal"); - return info; - } + info.AcceptAccounts = GetAcceptedAccounts(runSpace, group); + info.RejectAccounts = GetRejectedAccounts(runSpace, group); + info.RequireSenderAuthentication = (bool)GetPSObjectProperty(group, "RequireSenderAuthenticationEnabled"); + } + finally + { + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("GetDistributionListMailFlowSettingsInternal"); + return info; + } private void SetDistributionListMailFlowSettingsInternal(string accountName, string[] acceptAccounts, string[] rejectAccounts, bool requireSenderAuthentication, string[] addressLists) { - ExchangeLog.LogStart("SetDistributionListMailFlowSettingsInternal"); - ExchangeLog.DebugInfo("Account: {0}", accountName); + ExchangeLog.LogStart("SetDistributionListMailFlowSettingsInternal"); + ExchangeLog.DebugInfo("Account: {0}", accountName); - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); - Command cmd = new Command("Set-DistributionGroup"); - cmd.Parameters.Add("Identity", accountName); + Command cmd = new Command("Set-DistributionGroup"); + cmd.Parameters.Add("Identity", accountName); - MultiValuedProperty ids = null; - MultiValuedProperty dlIds = null; + MultiValuedProperty ids = null; + MultiValuedProperty dlIds = null; - SetAccountIds(runSpace, acceptAccounts, out ids, out dlIds); - cmd.Parameters.Add("AcceptMessagesOnlyFrom", ids); - cmd.Parameters.Add("AcceptMessagesOnlyFromDLMembers", dlIds); + SetAccountIds(runSpace, acceptAccounts, out ids, out dlIds); + cmd.Parameters.Add("AcceptMessagesOnlyFrom", ids); + cmd.Parameters.Add("AcceptMessagesOnlyFromDLMembers", dlIds); - SetAccountIds(runSpace, rejectAccounts, out ids, out dlIds); - cmd.Parameters.Add("RejectMessagesFrom", ids); - cmd.Parameters.Add("RejectMessagesFromDLMembers", dlIds); - cmd.Parameters.Add("RequireSenderAuthenticationEnabled", requireSenderAuthentication); + SetAccountIds(runSpace, rejectAccounts, out ids, out dlIds); + cmd.Parameters.Add("RejectMessagesFrom", ids); + cmd.Parameters.Add("RejectMessagesFromDLMembers", dlIds); + cmd.Parameters.Add("RequireSenderAuthenticationEnabled", requireSenderAuthentication); - ExecuteShellCommand(runSpace, cmd); + ExecuteShellCommand(runSpace, cmd); if (addressLists.Length > 0) { @@ -3758,138 +3746,138 @@ namespace WebsitePanel.Providers.HostedSolution FixShowInAddressBook(runSpace, accountName, addressLists, (bool)GetPSObjectProperty(distributionGroup, "HiddenFromAddressListsEnabled")); } - } - finally - { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("SetDistributionListMailFlowSettingsInternal"); - } + } + finally + { + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("SetDistributionListMailFlowSettingsInternal"); + } - private ExchangeAccount[] GetGroupMembers(Runspace runSpace, string groupId) - { - ExchangeLog.LogStart("GetGroupMembers"); - List list = new List(); - Command cmd = new Command("Get-DistributionGroupMember"); - cmd.Parameters.Add("Identity", groupId); - Collection result = ExecuteShellCommand(runSpace, cmd); + private ExchangeAccount[] GetGroupMembers(Runspace runSpace, string groupId) + { + ExchangeLog.LogStart("GetGroupMembers"); + List list = new List(); + Command cmd = new Command("Get-DistributionGroupMember"); + cmd.Parameters.Add("Identity", groupId); + Collection result = ExecuteShellCommand(runSpace, cmd); - ExchangeAccount account = null; - string id = null; + ExchangeAccount account = null; + string id = null; - foreach (PSObject obj in result) - { - id = GetPSObjectIdentity(obj); - account = GetExchangeAccount(runSpace, id); - if (account != null) - list.Add(account); - } - ExchangeLog.LogEnd("GetGroupMembers"); - return list.ToArray(); - } + foreach (PSObject obj in result) + { + id = GetPSObjectIdentity(obj); + account = GetExchangeAccount(runSpace, id); + if (account != null) + list.Add(account); + } + ExchangeLog.LogEnd("GetGroupMembers"); + return list.ToArray(); + } - private ExchangeEmailAddress[] GetDistributionListEmailAddressesInternal(string accountName) - { - ExchangeLog.LogStart("GetDistributionListEmailAddressesInternal"); - ExchangeLog.DebugInfo("Account: {0}", accountName); + private ExchangeEmailAddress[] GetDistributionListEmailAddressesInternal(string accountName) + { + ExchangeLog.LogStart("GetDistributionListEmailAddressesInternal"); + ExchangeLog.DebugInfo("Account: {0}", accountName); - List list = new List(); - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + List list = new List(); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); - Command cmd = new Command("Get-DistributionGroup"); - cmd.Parameters.Add("Identity", accountName); - Collection result = ExecuteShellCommand(runSpace, cmd); - PSObject group = result[0]; + Command cmd = new Command("Get-DistributionGroup"); + cmd.Parameters.Add("Identity", accountName); + Collection result = ExecuteShellCommand(runSpace, cmd); + PSObject group = result[0]; - string primaryEmail = null; - string windowsEmail = null; + string primaryEmail = null; + string windowsEmail = null; - SmtpAddress smtpAddress = (SmtpAddress)GetPSObjectProperty(group, "PrimarySmtpAddress"); - if (smtpAddress != null) - primaryEmail = smtpAddress.ToString(); + SmtpAddress smtpAddress = (SmtpAddress)GetPSObjectProperty(group, "PrimarySmtpAddress"); + if (smtpAddress != null) + primaryEmail = smtpAddress.ToString(); - //SmtpAddress winAddress = (SmtpAddress)GetPSObjectProperty(group, "WindowsEmailAddress"); - //if (winAddress != null) - // windowsEmail = winAddress.ToString(); - windowsEmail = ObjToString(GetPSObjectProperty(group, "CustomAttribute3")); + //SmtpAddress winAddress = (SmtpAddress)GetPSObjectProperty(group, "WindowsEmailAddress"); + //if (winAddress != null) + // windowsEmail = winAddress.ToString(); + windowsEmail = ObjToString(GetPSObjectProperty(group, "CustomAttribute3")); - ProxyAddressCollection emails = (ProxyAddressCollection)GetPSObjectProperty(group, "EmailAddresses"); - foreach (ProxyAddress email in emails) - { - //skip windows email - if (string.Equals(email.AddressString, windowsEmail, StringComparison.OrdinalIgnoreCase)) - continue; + ProxyAddressCollection emails = (ProxyAddressCollection)GetPSObjectProperty(group, "EmailAddresses"); + foreach (ProxyAddress email in emails) + { + //skip windows email + if (string.Equals(email.AddressString, windowsEmail, StringComparison.OrdinalIgnoreCase)) + continue; - ExchangeEmailAddress item = new ExchangeEmailAddress(); - item.Email = email.AddressString; - item.Primary = string.Equals(item.Email, primaryEmail, StringComparison.OrdinalIgnoreCase); - list.Add(item); - } - } - finally - { + ExchangeEmailAddress item = new ExchangeEmailAddress(); + item.Email = email.AddressString; + item.Primary = string.Equals(item.Email, primaryEmail, StringComparison.OrdinalIgnoreCase); + list.Add(item); + } + } + finally + { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("GetDistributionListEmailAddressesInternal"); - return list.ToArray(); - } + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("GetDistributionListEmailAddressesInternal"); + return list.ToArray(); + } private void SetDistributionListEmailAddressesInternal(string accountName, string[] emailAddresses, string[] addressLists) - { - ExchangeLog.LogStart("SetDistributionListEmailAddressesInternal"); - ExchangeLog.DebugInfo("Account: {0}", accountName); + { + ExchangeLog.LogStart("SetDistributionListEmailAddressesInternal"); + ExchangeLog.DebugInfo("Account: {0}", accountName); - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); - Command cmd = new Command("Get-DistributionGroup"); - cmd.Parameters.Add("Identity", accountName); - Collection result = ExecuteShellCommand(runSpace, cmd); - PSObject group = result[0]; + Command cmd = new Command("Get-DistributionGroup"); + cmd.Parameters.Add("Identity", accountName); + Collection result = ExecuteShellCommand(runSpace, cmd); + PSObject group = result[0]; - //SmtpAddress winAddress = (SmtpAddress)GetPSObjectProperty(group, "WindowsEmailAddress"); - //string windowsEmail = ObjToString(winAddress); - string windowsEmail = ObjToString(GetPSObjectProperty(group, "CustomAttribute3")); + //SmtpAddress winAddress = (SmtpAddress)GetPSObjectProperty(group, "WindowsEmailAddress"); + //string windowsEmail = ObjToString(winAddress); + string windowsEmail = ObjToString(GetPSObjectProperty(group, "CustomAttribute3")); - ProxyAddressCollection emails = new ProxyAddressCollection(); - ProxyAddress proxy = null; - string primaryEmail = null; + ProxyAddressCollection emails = new ProxyAddressCollection(); + ProxyAddress proxy = null; + string primaryEmail = null; - if (emailAddresses != null) - { - foreach (string email in emailAddresses) - { - proxy = ProxyAddress.Parse(email); - emails.Add(proxy); - if (proxy.IsPrimaryAddress) - { - primaryEmail = proxy.AddressString; - } - } - } - //add system windows email - if (!string.IsNullOrEmpty(windowsEmail)) - { - emails.Add(ProxyAddress.Parse(windowsEmail)); - } + if (emailAddresses != null) + { + foreach (string email in emailAddresses) + { + proxy = ProxyAddress.Parse(email); + emails.Add(proxy); + if (proxy.IsPrimaryAddress) + { + primaryEmail = proxy.AddressString; + } + } + } + //add system windows email + if (!string.IsNullOrEmpty(windowsEmail)) + { + emails.Add(ProxyAddress.Parse(windowsEmail)); + } - cmd = new Command("Set-DistributionGroup"); - cmd.Parameters.Add("Identity", accountName); - cmd.Parameters.Add("EmailAddresses", emails); - if (!string.IsNullOrEmpty(primaryEmail)) - { - cmd.Parameters.Add("WindowsEmailAddress", primaryEmail); - } - ExecuteShellCommand(runSpace, cmd); + cmd = new Command("Set-DistributionGroup"); + cmd.Parameters.Add("Identity", accountName); + cmd.Parameters.Add("EmailAddresses", emails); + if (!string.IsNullOrEmpty(primaryEmail)) + { + cmd.Parameters.Add("WindowsEmailAddress", primaryEmail); + } + ExecuteShellCommand(runSpace, cmd); if (addressLists.Length > 0) { @@ -3900,112 +3888,112 @@ namespace WebsitePanel.Providers.HostedSolution FixShowInAddressBook(runSpace, accountName, addressLists, (bool)GetPSObjectProperty(distributionGroup, "HiddenFromAddressListsEnabled")); } - } - finally - { + } + finally + { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("SetDistributionListEmailAddressesInternal"); - } + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("SetDistributionListEmailAddressesInternal"); + } private void SetDistributionListPrimaryEmailAddressInternal(string accountName, string emailAddress, string[] addressLists) - { - ExchangeLog.LogStart("SetDistributionListPrimaryEmailAddressInternal"); - ExchangeLog.DebugInfo("Account: {0}", accountName); + { + ExchangeLog.LogStart("SetDistributionListPrimaryEmailAddressInternal"); + ExchangeLog.DebugInfo("Account: {0}", accountName); - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); - SmtpAddress primaryEmail = new SmtpAddress(emailAddress); - Command cmd = new Command("Set-DistributionGroup"); - cmd.Parameters.Add("Identity", accountName); - cmd.Parameters.Add("PrimarySmtpAddress", primaryEmail); - cmd.Parameters.Add("WindowsEmailAddress", primaryEmail); + SmtpAddress primaryEmail = new SmtpAddress(emailAddress); + Command cmd = new Command("Set-DistributionGroup"); + cmd.Parameters.Add("Identity", accountName); + cmd.Parameters.Add("PrimarySmtpAddress", primaryEmail); + cmd.Parameters.Add("WindowsEmailAddress", primaryEmail); - ExecuteShellCommand(runSpace, cmd); + ExecuteShellCommand(runSpace, cmd); - } - finally - { + } + finally + { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("SetDistributionListPrimaryEmailAddressInternal"); - } + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("SetDistributionListPrimaryEmailAddressInternal"); + } - private ExchangeDistributionList GetDistributionListPermissionsInternal(string organizationId, string accountName, Runspace runspace) - { - ExchangeLog.LogStart("GetDistributionListPermissionsInternal"); + private ExchangeDistributionList GetDistributionListPermissionsInternal(string organizationId, string accountName, Runspace runspace) + { + ExchangeLog.LogStart("GetDistributionListPermissionsInternal"); - if (string.IsNullOrEmpty(accountName)) - throw new ArgumentNullException("accountName"); + if (string.IsNullOrEmpty(accountName)) + throw new ArgumentNullException("accountName"); - ExchangeDistributionList exchangeDistributionList = null; - bool closeRunspace = false; + ExchangeDistributionList exchangeDistributionList = null; + bool closeRunspace = false; - try - { - if (runspace == null) - { - runspace = OpenRunspace(); - closeRunspace = true; - } + try + { + if (runspace == null) + { + runspace = OpenRunspace(); + closeRunspace = true; + } - Command cmd = new Command("Get-DistributionGroup"); + Command cmd = new Command("Get-DistributionGroup"); - cmd.Parameters.Add("Identity", accountName); - Collection result = ExecuteShellCommand(runspace, cmd); - PSObject distributionGroup = result[0]; - string cn = GetPSObjectProperty(distributionGroup, "Name") as string; + cmd.Parameters.Add("Identity", accountName); + Collection result = ExecuteShellCommand(runspace, cmd); + PSObject distributionGroup = result[0]; + string cn = GetPSObjectProperty(distributionGroup, "Name") as string; - exchangeDistributionList = new ExchangeDistributionList(); - exchangeDistributionList.AccountName = accountName; - exchangeDistributionList.SendOnBehalfAccounts = GetSendOnBehalfAccounts(runspace, distributionGroup); - exchangeDistributionList.SendAsAccounts = GetSendAsAccounts(runspace, organizationId, cn); - } - catch (Exception ex) - { - ExchangeLog.LogError(ex); - throw ex; - } - finally - { - if (closeRunspace) - CloseRunspace(runspace); - } + exchangeDistributionList = new ExchangeDistributionList(); + exchangeDistributionList.AccountName = accountName; + exchangeDistributionList.SendOnBehalfAccounts = GetSendOnBehalfAccounts(runspace, distributionGroup); + exchangeDistributionList.SendAsAccounts = GetSendAsAccounts(runspace, organizationId, cn); + } + catch (Exception ex) + { + ExchangeLog.LogError(ex); + throw ex; + } + finally + { + if (closeRunspace) + CloseRunspace(runspace); + } - ExchangeLog.LogEnd("GetDistributionListPermissionsInternal"); - return exchangeDistributionList; - } + ExchangeLog.LogEnd("GetDistributionListPermissionsInternal"); + return exchangeDistributionList; + } private void SetDistributionListPermissionsInternal(string organizationId, string accountName, string[] sendAsAccounts, string[] sendOnBehalfAccounts, string[] addressLists) - { - ExchangeLog.LogStart("SetDistributionListPermissionsInternal"); + { + ExchangeLog.LogStart("SetDistributionListPermissionsInternal"); - if (string.IsNullOrEmpty(accountName)) - throw new ArgumentNullException("accountName"); + if (string.IsNullOrEmpty(accountName)) + throw new ArgumentNullException("accountName"); - if (sendAsAccounts == null) - throw new ArgumentNullException("sendAsAccounts"); + if (sendAsAccounts == null) + throw new ArgumentNullException("sendAsAccounts"); - if (sendOnBehalfAccounts == null) - throw new ArgumentNullException("sendOnBehalfAccounts"); + if (sendOnBehalfAccounts == null) + throw new ArgumentNullException("sendOnBehalfAccounts"); - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); - string cn = GetDistributionListCommonName(runSpace, accountName); - ExchangeDistributionList distributionList = GetDistributionListPermissionsInternal(organizationId, accountName, runSpace); - SetSendAsPermissions(runSpace, distributionList.SendAsAccounts, cn, sendAsAccounts); - SetDistributionListSendOnBehalfAccounts(runSpace, accountName, sendOnBehalfAccounts); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + string cn = GetDistributionListCommonName(runSpace, accountName); + ExchangeDistributionList distributionList = GetDistributionListPermissionsInternal(organizationId, accountName, runSpace); + SetSendAsPermissions(runSpace, distributionList.SendAsAccounts, cn, sendAsAccounts); + SetDistributionListSendOnBehalfAccounts(runSpace, accountName, sendOnBehalfAccounts); if (addressLists.Length > 0) { @@ -4017,369 +4005,369 @@ namespace WebsitePanel.Providers.HostedSolution FixShowInAddressBook(runSpace, accountName, addressLists, (bool)GetPSObjectProperty(distributionGroup, "HiddenFromAddressListsEnabled")); } - } - catch (Exception ex) - { - ExchangeLog.LogError(ex); - throw; - } - finally - { - CloseRunspace(runSpace); - } + } + catch (Exception ex) + { + ExchangeLog.LogError(ex); + throw; + } + finally + { + CloseRunspace(runSpace); + } - ExchangeLog.LogEnd("SetDistributionListPermissionsInternal"); - } + ExchangeLog.LogEnd("SetDistributionListPermissionsInternal"); + } - internal virtual void SetDistributionListSendOnBehalfAccounts(Runspace runspace, string accountName, string[] sendOnBehalfAccounts) - { - ExchangeLog.LogStart("SetDistributionListSendOnBehalfAccounts"); - Command cmd = new Command("Set-DistributionGroup"); - cmd.Parameters.Add("Identity", accountName); - cmd.Parameters.Add("GrantSendOnBehalfTo", SetSendOnBehalfAccounts(runspace, sendOnBehalfAccounts)); - ExecuteShellCommand(runspace, cmd); - ExchangeLog.LogEnd("SetDistributionListSendOnBehalfAccounts"); - } + internal virtual void SetDistributionListSendOnBehalfAccounts(Runspace runspace, string accountName, string[] sendOnBehalfAccounts) + { + ExchangeLog.LogStart("SetDistributionListSendOnBehalfAccounts"); + Command cmd = new Command("Set-DistributionGroup"); + cmd.Parameters.Add("Identity", accountName); + cmd.Parameters.Add("GrantSendOnBehalfTo", SetSendOnBehalfAccounts(runspace, sendOnBehalfAccounts)); + ExecuteShellCommand(runspace, cmd); + ExchangeLog.LogEnd("SetDistributionListSendOnBehalfAccounts"); + } - private string GetDistributionListCommonName(Runspace runSpace, string accountName) - { - ExchangeLog.LogStart("GetDistributionListCommonName"); - Command cmd = new Command("Get-DistributionGroup"); - cmd.Parameters.Add("Identity", accountName); - Collection result = ExecuteShellCommand(runSpace, cmd); - PSObject obj = result[0]; - string cn = GetPSObjectProperty(obj, "Name") as string; - ExchangeLog.LogEnd("GeDistributionListCommonName"); - return cn; - } + private string GetDistributionListCommonName(Runspace runSpace, string accountName) + { + ExchangeLog.LogStart("GetDistributionListCommonName"); + Command cmd = new Command("Get-DistributionGroup"); + cmd.Parameters.Add("Identity", accountName); + Collection result = ExecuteShellCommand(runSpace, cmd); + PSObject obj = result[0]; + string cn = GetPSObjectProperty(obj, "Name") as string; + ExchangeLog.LogEnd("GeDistributionListCommonName"); + return cn; + } - #endregion + #endregion - #region Public folders + #region Public folders - private void CreatePublicFolderInternal(string organizationId, string securityGroup, string parentFolder, - string folderName, bool mailEnabled, string accountName, string name, string domain) - { - ExchangeLog.LogStart("CreatePublicFolderInternal"); - ExchangeLog.DebugInfo("Organization Id: {0}", organizationId); - ExchangeLog.DebugInfo("Parent: {0}", parentFolder); - ExchangeLog.DebugInfo("Name: {0}", folderName); + private void CreatePublicFolderInternal(string organizationId, string securityGroup, string parentFolder, + string folderName, bool mailEnabled, string accountName, string name, string domain) + { + ExchangeLog.LogStart("CreatePublicFolderInternal"); + ExchangeLog.DebugInfo("Organization Id: {0}", organizationId); + ExchangeLog.DebugInfo("Parent: {0}", parentFolder); + ExchangeLog.DebugInfo("Name: {0}", folderName); - ExchangeTransaction transaction = StartTransaction(); + ExchangeTransaction transaction = StartTransaction(); - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); - //create organization root folder if required - CheckOrganizationRootFolder(runSpace, organizationId, securityGroup); + //create organization root folder if required + CheckOrganizationRootFolder(runSpace, organizationId, securityGroup); - string id = AddPublicFolder(runSpace, folderName, parentFolder); - transaction.RegisterNewPublicFolder(id); + string id = AddPublicFolder(runSpace, folderName, parentFolder); + transaction.RegisterNewPublicFolder(id); - SetPublicFolderPermissions(runSpace, id, securityGroup); + SetPublicFolderPermissions(runSpace, id, securityGroup); - if (mailEnabled) - { - EnableMailPublicFolderInternal(organizationId, id, accountName, name, domain); - } + if (mailEnabled) + { + EnableMailPublicFolderInternal(organizationId, id, accountName, name, domain); + } - } - catch (Exception ex) - { - ExchangeLog.LogError("CreatePublicFolderInternal", ex); - RollbackTransaction(transaction); - throw; - } - finally - { + } + catch (Exception ex) + { + ExchangeLog.LogError("CreatePublicFolderInternal", ex); + RollbackTransaction(transaction); + throw; + } + finally + { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("CreatePublicFolderInternal"); - } + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("CreatePublicFolderInternal"); + } - private void CheckOrganizationRootFolder(Runspace runSpace, string folder, string user) - { - ExchangeLog.LogStart("CheckOrganizationRootFolder"); + private void CheckOrganizationRootFolder(Runspace runSpace, string folder, string user) + { + ExchangeLog.LogStart("CheckOrganizationRootFolder"); - Collection result = GetPublicFolderObject(runSpace, "\\" + folder); - if (result == null || result.Count == 0) - { - ExchangeTransaction transaction = StartTransaction(); - try - { - string rootId = AddPublicFolder(runSpace, folder, "\\"); - transaction.RegisterNewPublicFolder(rootId); - SetPublicFolderPermissions(runSpace, rootId, user); - } - catch - { - RollbackTransaction(transaction); - throw; - } - } - ExchangeLog.LogEnd("CheckOrganizationRootFolder"); - } + Collection result = GetPublicFolderObject(runSpace, "\\" + folder); + if (result == null || result.Count == 0) + { + ExchangeTransaction transaction = StartTransaction(); + try + { + string rootId = AddPublicFolder(runSpace, folder, "\\"); + transaction.RegisterNewPublicFolder(rootId); + SetPublicFolderPermissions(runSpace, rootId, user); + } + catch + { + RollbackTransaction(transaction); + throw; + } + } + ExchangeLog.LogEnd("CheckOrganizationRootFolder"); + } - private string AddPublicFolder(Runspace runSpace, string name, string path) - { - ExchangeLog.LogStart("CreatePublicFolder"); - Command cmd = new Command("New-PublicFolder"); - cmd.Parameters.Add("Name", name); - cmd.Parameters.Add("Path", path); - if (!string.IsNullOrEmpty(PublicFolderServer)) - cmd.Parameters.Add("Server", PublicFolderServer); - Collection result = ExecuteShellCommand(runSpace, cmd); - string id = GetResultObjectIdentity(result); - ExchangeLog.LogEnd("CreatePublicFolder"); - return id; - } + private string AddPublicFolder(Runspace runSpace, string name, string path) + { + ExchangeLog.LogStart("CreatePublicFolder"); + Command cmd = new Command("New-PublicFolder"); + cmd.Parameters.Add("Name", name); + cmd.Parameters.Add("Path", path); + if (!string.IsNullOrEmpty(PublicFolderServer)) + cmd.Parameters.Add("Server", PublicFolderServer); + Collection result = ExecuteShellCommand(runSpace, cmd); + string id = GetResultObjectIdentity(result); + ExchangeLog.LogEnd("CreatePublicFolder"); + return id; + } - private void DeletePublicFolderInternal(string folder) - { - ExchangeLog.LogStart("DeletePublicFolderInternal"); - ExchangeLog.DebugInfo("Folder: {0}", folder); + private void DeletePublicFolderInternal(string folder) + { + ExchangeLog.LogStart("DeletePublicFolderInternal"); + ExchangeLog.DebugInfo("Folder: {0}", folder); - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); - RemovePublicFolder(runSpace, folder); - } - finally - { + RemovePublicFolder(runSpace, folder); + } + finally + { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("DeletePublicFolderInternal"); - } + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("DeletePublicFolderInternal"); + } - private Collection GetPublicFolderObject(Runspace runSpace, string id) - { - Command cmd = new Command("Get-PublicFolder"); - cmd.Parameters.Add("Identity", id); - if (!string.IsNullOrEmpty(PublicFolderServer)) - cmd.Parameters.Add("Server", PublicFolderServer); - Collection result = ExecuteShellCommand(runSpace, cmd); - return result; - } + private Collection GetPublicFolderObject(Runspace runSpace, string id) + { + Command cmd = new Command("Get-PublicFolder"); + cmd.Parameters.Add("Identity", id); + if (!string.IsNullOrEmpty(PublicFolderServer)) + cmd.Parameters.Add("Server", PublicFolderServer); + Collection result = ExecuteShellCommand(runSpace, cmd); + return result; + } - private bool PublicFolderExists(Runspace runSpace, string id) - { - ExchangeLog.LogStart("PublicFolderExists"); + private bool PublicFolderExists(Runspace runSpace, string id) + { + ExchangeLog.LogStart("PublicFolderExists"); - Collection result = GetPublicFolderObject(runSpace, id); - bool ret = (result != null && result.Count == 1); - ExchangeLog.LogEnd("PublicFolderExists"); - return ret; - } + Collection result = GetPublicFolderObject(runSpace, id); + bool ret = (result != null && result.Count == 1); + ExchangeLog.LogEnd("PublicFolderExists"); + return ret; + } - private void RemovePublicFolder(Runspace runSpace, string id) - { - ExchangeLog.LogStart("RemovePublicFolder"); + private void RemovePublicFolder(Runspace runSpace, string id) + { + ExchangeLog.LogStart("RemovePublicFolder"); - Command cmd = new Command("Remove-PublicFolder"); - cmd.Parameters.Add("Identity", id); - cmd.Parameters.Add("Recurse", new SwitchParameter(true)); - cmd.Parameters.Add("Confirm", false); - if (!string.IsNullOrEmpty(PublicFolderServer)) - cmd.Parameters.Add("Server", PublicFolderServer); - ExecuteShellCommand(runSpace, cmd); + Command cmd = new Command("Remove-PublicFolder"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("Recurse", new SwitchParameter(true)); + cmd.Parameters.Add("Confirm", false); + if (!string.IsNullOrEmpty(PublicFolderServer)) + cmd.Parameters.Add("Server", PublicFolderServer); + ExecuteShellCommand(runSpace, cmd); - ExchangeLog.LogEnd("RemovePublicFolder"); - } + ExchangeLog.LogEnd("RemovePublicFolder"); + } - private void SetPublicFolderPermissions(Runspace runSpace, string folder, string securityGroup) - { - //set the default Permission to 'Reviewer' + private void SetPublicFolderPermissions(Runspace runSpace, string folder, string securityGroup) + { + //set the default Permission to 'Reviewer' RemovePublicFolderClientPermission(runSpace, folder, "Default", "Author"); - AddPublicFolderClientPermission(runSpace, folder, securityGroup, "Reviewer"); - } + AddPublicFolderClientPermission(runSpace, folder, securityGroup, "Reviewer"); + } - private void RemovePublicFolderClientPermission(Runspace runSpace, string id, string user, - string permission) - { - ExchangeLog.LogStart("RemovePublicFolderClientPermission"); + private void RemovePublicFolderClientPermission(Runspace runSpace, string id, string user, + string permission) + { + ExchangeLog.LogStart("RemovePublicFolderClientPermission"); - Command cmd = new Command("Remove-PublicFolderClientPermission"); - cmd.Parameters.Add("Identity", id); - cmd.Parameters.Add("User", user); - cmd.Parameters.Add("AccessRights", permission); - cmd.Parameters.Add("Confirm", false); - if (!string.IsNullOrEmpty(PublicFolderServer)) - cmd.Parameters.Add("Server", PublicFolderServer); - ExecuteShellCommand(runSpace, cmd); - ExchangeLog.LogEnd("RemovePublicFolderClientPermission"); - } + Command cmd = new Command("Remove-PublicFolderClientPermission"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("User", user); + cmd.Parameters.Add("AccessRights", permission); + cmd.Parameters.Add("Confirm", false); + if (!string.IsNullOrEmpty(PublicFolderServer)) + cmd.Parameters.Add("Server", PublicFolderServer); + ExecuteShellCommand(runSpace, cmd); + ExchangeLog.LogEnd("RemovePublicFolderClientPermission"); + } - private void AddPublicFolderClientPermission(Runspace runSpace, string id, string user, string permission) - { - ExchangeLog.LogStart("AddPublicFolderClientPermission"); + private void AddPublicFolderClientPermission(Runspace runSpace, string id, string user, string permission) + { + ExchangeLog.LogStart("AddPublicFolderClientPermission"); - Command cmd = new Command("Add-PublicFolderClientPermission"); - cmd.Parameters.Add("Identity", id); - cmd.Parameters.Add("User", user); - cmd.Parameters.Add("AccessRights", permission); - if (!string.IsNullOrEmpty(PublicFolderServer)) - cmd.Parameters.Add("Server", PublicFolderServer); - ExecuteShellCommand(runSpace, cmd); - ExchangeLog.LogEnd("AddPublicFolderClientPermission"); - } + Command cmd = new Command("Add-PublicFolderClientPermission"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("User", user); + cmd.Parameters.Add("AccessRights", permission); + if (!string.IsNullOrEmpty(PublicFolderServer)) + cmd.Parameters.Add("Server", PublicFolderServer); + ExecuteShellCommand(runSpace, cmd); + ExchangeLog.LogEnd("AddPublicFolderClientPermission"); + } - private void GetPublicFolderClientPermission(Runspace runSpace, string id) - { - Command cmd = new Command("Get-PublicFolderClientPermission"); - cmd.Parameters.Add("Identity", id); - if (!string.IsNullOrEmpty(PublicFolderServer)) - cmd.Parameters.Add("Server", PublicFolderServer); - Collection result = ExecuteShellCommand(runSpace, cmd); - PSObject obj = result[0]; - } + private void GetPublicFolderClientPermission(Runspace runSpace, string id) + { + Command cmd = new Command("Get-PublicFolderClientPermission"); + cmd.Parameters.Add("Identity", id); + if (!string.IsNullOrEmpty(PublicFolderServer)) + cmd.Parameters.Add("Server", PublicFolderServer); + Collection result = ExecuteShellCommand(runSpace, cmd); + PSObject obj = result[0]; + } - private void EnableMailPublicFolderInternal(string organizationId, string folder, string accountName, - string name, string domain) - { - ExchangeLog.LogStart("EnableMailPublicFolderInternal"); - ExchangeLog.DebugInfo("Folder: {0}", folder); + private void EnableMailPublicFolderInternal(string organizationId, string folder, string accountName, + string name, string domain) + { + ExchangeLog.LogStart("EnableMailPublicFolderInternal"); + ExchangeLog.DebugInfo("Folder: {0}", folder); - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); - Command cmd = new Command("Enable-MailPublicFolder"); - cmd.Parameters.Add("Identity", folder); - if (!string.IsNullOrEmpty(PublicFolderServer)) - cmd.Parameters.Add("Server", PublicFolderServer); - ExecuteShellCommand(runSpace, cmd); - string id = null; + Command cmd = new Command("Enable-MailPublicFolder"); + cmd.Parameters.Add("Identity", folder); + if (!string.IsNullOrEmpty(PublicFolderServer)) + cmd.Parameters.Add("Server", PublicFolderServer); + ExecuteShellCommand(runSpace, cmd); + string id = null; - //try to avoid message: "The Active Directory proxy object for the public folder 'XXX' - // is being generated. Please try again later." - int attempts = 0; - string windowsEmailAddress = null; - while (true) - { - cmd = new Command("Get-MailPublicFolder"); - cmd.Parameters.Add("Identity", folder); - if (!string.IsNullOrEmpty(PublicFolderServer)) - cmd.Parameters.Add("Server", PublicFolderServer); - Collection result = ExecuteShellCommand(runSpace, cmd); - if (result != null && result.Count > 0) - { - id = GetResultObjectIdentity(result); - windowsEmailAddress = ObjToString(GetPSObjectProperty(result[0], "WindowsEmailAddress")); - break; - } + //try to avoid message: "The Active Directory proxy object for the public folder 'XXX' + // is being generated. Please try again later." + int attempts = 0; + string windowsEmailAddress = null; + while (true) + { + cmd = new Command("Get-MailPublicFolder"); + cmd.Parameters.Add("Identity", folder); + if (!string.IsNullOrEmpty(PublicFolderServer)) + cmd.Parameters.Add("Server", PublicFolderServer); + Collection result = ExecuteShellCommand(runSpace, cmd); + if (result != null && result.Count > 0) + { + id = GetResultObjectIdentity(result); + windowsEmailAddress = ObjToString(GetPSObjectProperty(result[0], "WindowsEmailAddress")); + break; + } - if (attempts > 9) - { - string error = string.Format("Active Directory proxy object for the public folder '{0}' was not found or not generated yet.", folder); - throw new Exception(error); - } + if (attempts > 9) + { + string error = string.Format("Active Directory proxy object for the public folder '{0}' was not found or not generated yet.", folder); + throw new Exception(error); + } - attempts++; - ExchangeLog.LogWarning("Attemp {0} to create mail public folder {1}", attempts, folder); - System.Threading.Thread.Sleep(5000); - } + attempts++; + ExchangeLog.LogWarning("Attemp {0} to create mail public folder {1}", attempts, folder); + System.Threading.Thread.Sleep(5000); + } - string email = string.Format("{0}@{1}", name, domain); - // fix issue with 2 DC - attempts = 0; - bool success = false; - object[] errors; - while (true) - { - try - { - cmd = new Command("Set-MailPublicFolder"); - cmd.Parameters.Add("Identity", id); - cmd.Parameters.Add("Alias", accountName); - cmd.Parameters.Add("EmailAddressPolicyEnabled", false); - cmd.Parameters.Add("CustomAttribute1", organizationId); - cmd.Parameters.Add("CustomAttribute3", windowsEmailAddress); - cmd.Parameters.Add("PrimarySmtpAddress", email); - ExecuteShellCommand(runSpace, cmd, out errors); + string email = string.Format("{0}@{1}", name, domain); + // fix issue with 2 DC + attempts = 0; + bool success = false; + object[] errors; + while (true) + { + try + { + cmd = new Command("Set-MailPublicFolder"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("Alias", accountName); + cmd.Parameters.Add("EmailAddressPolicyEnabled", false); + cmd.Parameters.Add("CustomAttribute1", organizationId); + cmd.Parameters.Add("CustomAttribute3", windowsEmailAddress); + cmd.Parameters.Add("PrimarySmtpAddress", email); + ExecuteShellCommand(runSpace, cmd, out errors); - if (errors.Length == 0) - success = true; - } - catch (Exception ex) - { - ExchangeLog.LogError(ex); - } + if (errors.Length == 0) + success = true; + } + catch (Exception ex) + { + ExchangeLog.LogError(ex); + } - if (success) - break; + if (success) + break; - if (attempts > 9) - { - string error = string.Format("Mail public folder '{0}' was not found or not generated yet.", id); - throw new Exception(error); - } + if (attempts > 9) + { + string error = string.Format("Mail public folder '{0}' was not found or not generated yet.", id); + throw new Exception(error); + } - attempts++; - ExchangeLog.LogWarning("Attemp {0} to update mail public folder {1}", attempts, folder); - System.Threading.Thread.Sleep(5000); - } - } - finally - { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("EnableMailPublicFolderInternal"); - } + attempts++; + ExchangeLog.LogWarning("Attemp {0} to update mail public folder {1}", attempts, folder); + System.Threading.Thread.Sleep(5000); + } + } + finally + { + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("EnableMailPublicFolderInternal"); + } - private void DisableMailPublicFolderInternal(string folder) - { - ExchangeLog.LogStart("DisableMailPublicFolderInternal"); - ExchangeLog.DebugInfo("Folder: {0}", folder); - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + private void DisableMailPublicFolderInternal(string folder) + { + ExchangeLog.LogStart("DisableMailPublicFolderInternal"); + ExchangeLog.DebugInfo("Folder: {0}", folder); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); - Command cmd = new Command("Disable-MailPublicFolder"); - cmd.Parameters.Add("Identity", folder); - cmd.Parameters.Add("Confirm", false); - if (!string.IsNullOrEmpty(PublicFolderServer)) - cmd.Parameters.Add("Server", PublicFolderServer); - ExecuteShellCommand(runSpace, cmd); - } - finally - { + Command cmd = new Command("Disable-MailPublicFolder"); + cmd.Parameters.Add("Identity", folder); + cmd.Parameters.Add("Confirm", false); + if (!string.IsNullOrEmpty(PublicFolderServer)) + cmd.Parameters.Add("Server", PublicFolderServer); + ExecuteShellCommand(runSpace, cmd); + } + finally + { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("DisableMailPublicFolderInternal"); - } + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("DisableMailPublicFolderInternal"); + } - private ExchangePublicFolder GetPublicFolderGeneralSettingsInternal(string folder) - { - ExchangeLog.LogStart("GetPublicFolderGeneralSettingsInternal"); - ExchangeLog.DebugInfo("Folder: {0}", folder); + private ExchangePublicFolder GetPublicFolderGeneralSettingsInternal(string folder) + { + ExchangeLog.LogStart("GetPublicFolderGeneralSettingsInternal"); + ExchangeLog.DebugInfo("Folder: {0}", folder); - ExchangePublicFolder info = new ExchangePublicFolder(); - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + ExchangePublicFolder info = new ExchangePublicFolder(); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); - Collection result = GetPublicFolderObject(runSpace, folder); - PSObject publicFolder = result[0]; + Collection result = GetPublicFolderObject(runSpace, folder); + PSObject publicFolder = result[0]; - info.Name = (string)GetPSObjectProperty(publicFolder, "Name"); - info.MailEnabled = (bool)GetPSObjectProperty(publicFolder, "MailEnabled"); - info.HideFromAddressBook = (bool)GetPSObjectProperty(publicFolder, "HiddenFromAddressListsEnabled"); + info.Name = (string)GetPSObjectProperty(publicFolder, "Name"); + info.MailEnabled = (bool)GetPSObjectProperty(publicFolder, "MailEnabled"); + info.HideFromAddressBook = (bool)GetPSObjectProperty(publicFolder, "HiddenFromAddressListsEnabled"); info.NETBIOS = GetNETBIOSDomainName(); - info.Accounts = GetPublicFolderAccounts(runSpace, folder); + info.Accounts = GetPublicFolderAccounts(runSpace, folder); if (info.MailEnabled) { @@ -4394,16 +4382,16 @@ namespace WebsitePanel.Providers.HostedSolution info.SAMAccountName = string.Format("{0}\\{1}", GetNETBIOSDomainName(), (string)GetPSObjectProperty(publicFolder, "Alias")); } } - } - finally - { + } + finally + { + + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("GetPublicFolderGeneralSettingsInternal"); + return info; + } - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("GetPublicFolderGeneralSettingsInternal"); - return info; - } - private ExchangeAccount[] GetPublicFolderAccounts(Runspace runSpace, string folder) { ExchangeLog.LogStart("GetPublicFolderAccounts"); @@ -4432,458 +4420,458 @@ namespace WebsitePanel.Providers.HostedSolution string permission = ObjToString(GetObjectIndexerValue(rights, i)); if (account != null) account.PublicFolderPermission = permission; - list.Add(account); - break; + list.Add(account); + break; } } ExchangeLog.LogEnd("GetPublicFolderAccounts"); return list.ToArray(); } - private void SetPublicFolderGeneralSettingsInternal(string folder, string newFolderName, - bool hideFromAddressBook, ExchangeAccount[] accounts) - { - ExchangeLog.LogStart("SetPublicFolderGeneralSettingsInternal"); - ExchangeLog.DebugInfo("Folder: {0}", folder); + private void SetPublicFolderGeneralSettingsInternal(string folder, string newFolderName, + bool hideFromAddressBook, ExchangeAccount[] accounts) + { + ExchangeLog.LogStart("SetPublicFolderGeneralSettingsInternal"); + ExchangeLog.DebugInfo("Folder: {0}", folder); - ExchangePublicFolder info = new ExchangePublicFolder(); - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + ExchangePublicFolder info = new ExchangePublicFolder(); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + Collection result = GetPublicFolderObject(runSpace, folder); + PSObject publicFolder = result[0]; + string folderName = (string)GetPSObjectProperty(publicFolder, "Name"); + ExchangeAccount[] allAccounts = GetPublicFolderAccounts(runSpace, folder); - Collection result = GetPublicFolderObject(runSpace, folder); - PSObject publicFolder = result[0]; - string folderName = (string)GetPSObjectProperty(publicFolder, "Name"); - ExchangeAccount[] allAccounts = GetPublicFolderAccounts(runSpace, folder); - //Remove all accounts and re-apply List accountsToDelete = new List(); List accountsToAdd = new List(); - + foreach (ExchangeAccount existingAccount in allAccounts) { try { - RemovePublicFolderClientPermission( runSpace, + RemovePublicFolderClientPermission(runSpace, folder, - existingAccount.AccountName.Contains("@") ? existingAccount.AccountName : @"\" + existingAccount.AccountName, + existingAccount.AccountName.Contains("@") ? existingAccount.AccountName : @"\" + existingAccount.AccountName, existingAccount.PublicFolderPermission); } catch (Exception) { throw; } - + } foreach (ExchangeAccount newAccount in accounts) { try { - AddPublicFolderClientPermission(runSpace, + AddPublicFolderClientPermission(runSpace, folder, - newAccount.AccountName.Contains("@") ? newAccount.AccountName : @"\" + newAccount.AccountName, + newAccount.AccountName.Contains("@") ? newAccount.AccountName : @"\" + newAccount.AccountName, newAccount.PublicFolderPermission); } catch (Exception) - { + { throw; } - + } - - //general settings - Command cmd = new Command("Set-PublicFolder"); - cmd.Parameters.Add("Identity", folder); - if (!string.IsNullOrEmpty(PublicFolderServer)) - cmd.Parameters.Add("Server", PublicFolderServer); - if (!folderName.Equals(newFolderName, StringComparison.OrdinalIgnoreCase)) - { - cmd.Parameters.Add("Name", newFolderName); - } - cmd.Parameters.Add("HiddenFromAddressListsEnabled", hideFromAddressBook); - ExecuteShellCommand(runSpace, cmd); - } - finally - { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("SetPublicFolderGeneralSettingsInternal"); - } + //general settings + Command cmd = new Command("Set-PublicFolder"); + cmd.Parameters.Add("Identity", folder); + if (!string.IsNullOrEmpty(PublicFolderServer)) + cmd.Parameters.Add("Server", PublicFolderServer); + if (!folderName.Equals(newFolderName, StringComparison.OrdinalIgnoreCase)) + { + cmd.Parameters.Add("Name", newFolderName); + } + cmd.Parameters.Add("HiddenFromAddressListsEnabled", hideFromAddressBook); + ExecuteShellCommand(runSpace, cmd); + } + finally + { - private ExchangePublicFolder GetPublicFolderMailFlowSettingsInternal(string folder) - { - ExchangeLog.LogStart("GetPublicFolderMailFlowSettingsInternal"); - ExchangeLog.DebugInfo("Folder: {0}", folder); + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("SetPublicFolderGeneralSettingsInternal"); + } - ExchangePublicFolder info = new ExchangePublicFolder(); + private ExchangePublicFolder GetPublicFolderMailFlowSettingsInternal(string folder) + { + ExchangeLog.LogStart("GetPublicFolderMailFlowSettingsInternal"); + ExchangeLog.DebugInfo("Folder: {0}", folder); - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + ExchangePublicFolder info = new ExchangePublicFolder(); + + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); - Command cmd = new Command("Get-MailPublicFolder"); - cmd.Parameters.Add("Identity", folder); - if (!string.IsNullOrEmpty(PublicFolderServer)) - cmd.Parameters.Add("Server", PublicFolderServer); - Collection result = ExecuteShellCommand(runSpace, cmd); - PSObject publicFolder = result[0]; + Command cmd = new Command("Get-MailPublicFolder"); + cmd.Parameters.Add("Identity", folder); + if (!string.IsNullOrEmpty(PublicFolderServer)) + cmd.Parameters.Add("Server", PublicFolderServer); + Collection result = ExecuteShellCommand(runSpace, cmd); + PSObject publicFolder = result[0]; - info.AcceptAccounts = GetAcceptedAccounts(runSpace, publicFolder); - info.RejectAccounts = GetRejectedAccounts(runSpace, publicFolder); - info.RequireSenderAuthentication = (bool)GetPSObjectProperty(publicFolder, "RequireSenderAuthenticationEnabled"); - } - finally - { + info.AcceptAccounts = GetAcceptedAccounts(runSpace, publicFolder); + info.RejectAccounts = GetRejectedAccounts(runSpace, publicFolder); + info.RequireSenderAuthentication = (bool)GetPSObjectProperty(publicFolder, "RequireSenderAuthenticationEnabled"); + } + finally + { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("GetPublicFolderMailFlowSettingsInternal"); - return info; - } + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("GetPublicFolderMailFlowSettingsInternal"); + return info; + } - private void SetPublicFolderMailFlowSettingsInternal(string folder, - string[] acceptAccounts, string[] rejectAccounts, bool requireSenderAuthentication) - { - ExchangeLog.LogStart("SetPublicFolderMailFlowSettingsInternal"); - ExchangeLog.DebugInfo("Folder: {0}", folder); + private void SetPublicFolderMailFlowSettingsInternal(string folder, + string[] acceptAccounts, string[] rejectAccounts, bool requireSenderAuthentication) + { + ExchangeLog.LogStart("SetPublicFolderMailFlowSettingsInternal"); + ExchangeLog.DebugInfo("Folder: {0}", folder); - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); - Command cmd = new Command("Set-MailPublicFolder"); - cmd.Parameters.Add("Identity", folder); + Command cmd = new Command("Set-MailPublicFolder"); + cmd.Parameters.Add("Identity", folder); - MultiValuedProperty ids = null; - MultiValuedProperty dlIds = null; + MultiValuedProperty ids = null; + MultiValuedProperty dlIds = null; - SetAccountIds(runSpace, acceptAccounts, out ids, out dlIds); - cmd.Parameters.Add("AcceptMessagesOnlyFrom", ids); - cmd.Parameters.Add("AcceptMessagesOnlyFromDLMembers", dlIds); + SetAccountIds(runSpace, acceptAccounts, out ids, out dlIds); + cmd.Parameters.Add("AcceptMessagesOnlyFrom", ids); + cmd.Parameters.Add("AcceptMessagesOnlyFromDLMembers", dlIds); - SetAccountIds(runSpace, rejectAccounts, out ids, out dlIds); - cmd.Parameters.Add("RejectMessagesFrom", ids); - cmd.Parameters.Add("RejectMessagesFromDLMembers", dlIds); - cmd.Parameters.Add("RequireSenderAuthenticationEnabled", requireSenderAuthentication); + SetAccountIds(runSpace, rejectAccounts, out ids, out dlIds); + cmd.Parameters.Add("RejectMessagesFrom", ids); + cmd.Parameters.Add("RejectMessagesFromDLMembers", dlIds); + cmd.Parameters.Add("RequireSenderAuthenticationEnabled", requireSenderAuthentication); - ExecuteShellCommand(runSpace, cmd); - } - finally - { + ExecuteShellCommand(runSpace, cmd); + } + finally + { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("SetPublicFolderMailFlowSettingsInternal"); + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("SetPublicFolderMailFlowSettingsInternal"); - } + } - private ExchangeEmailAddress[] GetPublicFolderEmailAddressesInternal(string folder) - { - ExchangeLog.LogStart("GetPublicFolderEmailAddressesInternal"); - ExchangeLog.DebugInfo("Folder: {0}", folder); + private ExchangeEmailAddress[] GetPublicFolderEmailAddressesInternal(string folder) + { + ExchangeLog.LogStart("GetPublicFolderEmailAddressesInternal"); + ExchangeLog.DebugInfo("Folder: {0}", folder); - List list = new List(); - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + List list = new List(); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); - Command cmd = new Command("Get-MailPublicFolder"); - cmd.Parameters.Add("Identity", folder); - if (!string.IsNullOrEmpty(PublicFolderServer)) - cmd.Parameters.Add("Server", PublicFolderServer); - Collection result = ExecuteShellCommand(runSpace, cmd); - PSObject publicFolder = result[0]; + Command cmd = new Command("Get-MailPublicFolder"); + cmd.Parameters.Add("Identity", folder); + if (!string.IsNullOrEmpty(PublicFolderServer)) + cmd.Parameters.Add("Server", PublicFolderServer); + Collection result = ExecuteShellCommand(runSpace, cmd); + PSObject publicFolder = result[0]; - string primaryEmail = null; - string windowsEmail = null; + string primaryEmail = null; + string windowsEmail = null; - SmtpAddress smtpAddress = (SmtpAddress)GetPSObjectProperty(publicFolder, "PrimarySmtpAddress"); - if (smtpAddress != null) - primaryEmail = smtpAddress.ToString(); + SmtpAddress smtpAddress = (SmtpAddress)GetPSObjectProperty(publicFolder, "PrimarySmtpAddress"); + if (smtpAddress != null) + primaryEmail = smtpAddress.ToString(); - //SmtpAddress winAddress = (SmtpAddress)GetPSObjectProperty(publicFolder, "WindowsEmailAddress"); - //if (winAddress != null) - // windowsEmail = winAddress.ToString(); - windowsEmail = ObjToString(GetPSObjectProperty(publicFolder, "CustomAttribute3")); + //SmtpAddress winAddress = (SmtpAddress)GetPSObjectProperty(publicFolder, "WindowsEmailAddress"); + //if (winAddress != null) + // windowsEmail = winAddress.ToString(); + windowsEmail = ObjToString(GetPSObjectProperty(publicFolder, "CustomAttribute3")); - ProxyAddressCollection emails = (ProxyAddressCollection)GetPSObjectProperty(publicFolder, "EmailAddresses"); - foreach (ProxyAddress email in emails) - { - //skip windows email - if (string.Equals(email.AddressString, windowsEmail, StringComparison.OrdinalIgnoreCase)) - continue; + ProxyAddressCollection emails = (ProxyAddressCollection)GetPSObjectProperty(publicFolder, "EmailAddresses"); + foreach (ProxyAddress email in emails) + { + //skip windows email + if (string.Equals(email.AddressString, windowsEmail, StringComparison.OrdinalIgnoreCase)) + continue; - ExchangeEmailAddress item = new ExchangeEmailAddress(); - item.Email = email.AddressString; - item.Primary = string.Equals(item.Email, primaryEmail, StringComparison.OrdinalIgnoreCase); - list.Add(item); - } - } - finally - { + ExchangeEmailAddress item = new ExchangeEmailAddress(); + item.Email = email.AddressString; + item.Primary = string.Equals(item.Email, primaryEmail, StringComparison.OrdinalIgnoreCase); + list.Add(item); + } + } + finally + { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("GetPublicFolderEmailAddressesInternal"); - return list.ToArray(); - } + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("GetPublicFolderEmailAddressesInternal"); + return list.ToArray(); + } - private void SetPublicFolderEmailAddressesInternal(string folder, string[] emailAddresses) - { - ExchangeLog.LogStart("SetDistributionListEmailAddressesInternal"); - ExchangeLog.DebugInfo("Folder: {0}", folder); + private void SetPublicFolderEmailAddressesInternal(string folder, string[] emailAddresses) + { + ExchangeLog.LogStart("SetDistributionListEmailAddressesInternal"); + ExchangeLog.DebugInfo("Folder: {0}", folder); - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); - Command cmd = new Command("Get-MailPublicFolder"); - cmd.Parameters.Add("Identity", folder); - if (!string.IsNullOrEmpty(PublicFolderServer)) - cmd.Parameters.Add("Server", PublicFolderServer); - Collection result = ExecuteShellCommand(runSpace, cmd); - PSObject publicFolder = result[0]; + Command cmd = new Command("Get-MailPublicFolder"); + cmd.Parameters.Add("Identity", folder); + if (!string.IsNullOrEmpty(PublicFolderServer)) + cmd.Parameters.Add("Server", PublicFolderServer); + Collection result = ExecuteShellCommand(runSpace, cmd); + PSObject publicFolder = result[0]; - //SmtpAddress winAddress = (SmtpAddress)GetPSObjectProperty(publicFolder, "WindowsEmailAddress"); - string windowsEmail = ObjToString(GetPSObjectProperty(publicFolder, "CustomAttribute3")); - //string windowsEmail = ObjToString(winAddress); + //SmtpAddress winAddress = (SmtpAddress)GetPSObjectProperty(publicFolder, "WindowsEmailAddress"); + string windowsEmail = ObjToString(GetPSObjectProperty(publicFolder, "CustomAttribute3")); + //string windowsEmail = ObjToString(winAddress); - ProxyAddressCollection emails = new ProxyAddressCollection(); - ProxyAddress proxy = null; - if (emailAddresses != null) - { - foreach (string email in emailAddresses) - { - proxy = ProxyAddress.Parse(email); - emails.Add(proxy); - } - } - //add system windows email - if (!string.IsNullOrEmpty(windowsEmail)) - { - emails.Add(ProxyAddress.Parse(windowsEmail)); - } + ProxyAddressCollection emails = new ProxyAddressCollection(); + ProxyAddress proxy = null; + if (emailAddresses != null) + { + foreach (string email in emailAddresses) + { + proxy = ProxyAddress.Parse(email); + emails.Add(proxy); + } + } + //add system windows email + if (!string.IsNullOrEmpty(windowsEmail)) + { + emails.Add(ProxyAddress.Parse(windowsEmail)); + } - cmd = new Command("Set-MailPublicFolder"); - cmd.Parameters.Add("Identity", folder); - cmd.Parameters.Add("EmailAddresses", emails); - ExecuteShellCommand(runSpace, cmd); - } - finally - { + cmd = new Command("Set-MailPublicFolder"); + cmd.Parameters.Add("Identity", folder); + cmd.Parameters.Add("EmailAddresses", emails); + ExecuteShellCommand(runSpace, cmd); + } + finally + { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("SetPublicFolderEmailAddressesInternal"); - } + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("SetPublicFolderEmailAddressesInternal"); + } - private void SetPublicFolderPrimaryEmailAddressInternal(string folder, string emailAddress) - { - ExchangeLog.LogStart("SetPublicFolderPrimaryEmailAddressInternal"); - ExchangeLog.DebugInfo("Folder: {0}", folder); - ExchangeLog.DebugInfo("Email: {0}", emailAddress); + private void SetPublicFolderPrimaryEmailAddressInternal(string folder, string emailAddress) + { + ExchangeLog.LogStart("SetPublicFolderPrimaryEmailAddressInternal"); + ExchangeLog.DebugInfo("Folder: {0}", folder); + ExchangeLog.DebugInfo("Email: {0}", emailAddress); - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); - SmtpAddress primaryEmail = new SmtpAddress(emailAddress); - Command cmd = new Command("Set-MailPublicFolder"); - cmd.Parameters.Add("Identity", folder); - cmd.Parameters.Add("PrimarySmtpAddress", primaryEmail); + SmtpAddress primaryEmail = new SmtpAddress(emailAddress); + Command cmd = new Command("Set-MailPublicFolder"); + cmd.Parameters.Add("Identity", folder); + cmd.Parameters.Add("PrimarySmtpAddress", primaryEmail); - ExecuteShellCommand(runSpace, cmd); - } - finally - { + ExecuteShellCommand(runSpace, cmd); + } + finally + { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("SetPublicFolderPrimaryEmailAddressInternal"); - } + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("SetPublicFolderPrimaryEmailAddressInternal"); + } - private ExchangeItemStatistics[] GetPublicFoldersStatisticsInternal(string[] folders) - { - ExchangeLog.LogStart("GetPublicFoldersStatisticsInternal"); + private ExchangeItemStatistics[] GetPublicFoldersStatisticsInternal(string[] folders) + { + ExchangeLog.LogStart("GetPublicFoldersStatisticsInternal"); - Runspace runSpace = null; - List ret = new List(); - try - { - runSpace = OpenRunspace(); + Runspace runSpace = null; + List ret = new List(); + try + { + runSpace = OpenRunspace(); - PSObject obj = null; - foreach (string folder in folders) - { - Command cmd = new Command("Get-PublicFolderStatistics"); - cmd.Parameters.Add("Identity", folder); - if (!string.IsNullOrEmpty(PublicFolderServer)) - cmd.Parameters.Add("Server", PublicFolderServer); - Collection result = ExecuteShellCommand(runSpace, cmd); - if (result != null && result.Count > 0) - { - obj = result[0]; - ExchangeItemStatistics info = new ExchangeItemStatistics(); - info.ItemName = (string)GetPSObjectProperty(obj, "FolderPath"); - Unlimited totalItemSize = - (Unlimited)GetPSObjectProperty(obj, "TotalItemSize"); - info.TotalSizeMB = ConvertUnlimitedToMB(totalItemSize); - uint? itemCount = (uint?)GetPSObjectProperty(obj, "ItemCount"); - info.TotalItems = ConvertNullableToInt32(itemCount); + PSObject obj = null; + foreach (string folder in folders) + { + Command cmd = new Command("Get-PublicFolderStatistics"); + cmd.Parameters.Add("Identity", folder); + if (!string.IsNullOrEmpty(PublicFolderServer)) + cmd.Parameters.Add("Server", PublicFolderServer); + Collection result = ExecuteShellCommand(runSpace, cmd); + if (result != null && result.Count > 0) + { + obj = result[0]; + ExchangeItemStatistics info = new ExchangeItemStatistics(); + info.ItemName = (string)GetPSObjectProperty(obj, "FolderPath"); + Unlimited totalItemSize = + (Unlimited)GetPSObjectProperty(obj, "TotalItemSize"); + info.TotalSizeMB = ConvertUnlimitedToMB(totalItemSize); + uint? itemCount = (uint?)GetPSObjectProperty(obj, "ItemCount"); + info.TotalItems = ConvertNullableToInt32(itemCount); - DateTime? lastAccessTime = (DateTime?)GetPSObjectProperty(obj, "LastAccessTime"); ; - DateTime? lastModificationTime = (DateTime?)GetPSObjectProperty(obj, "LastModificationTime"); ; - info.LastAccessTime = ConvertNullableToDateTime(lastAccessTime); - info.LastModificationTime = ConvertNullableToDateTime(lastModificationTime); - ret.Add(info); - } - } - } - finally - { + DateTime? lastAccessTime = (DateTime?)GetPSObjectProperty(obj, "LastAccessTime"); ; + DateTime? lastModificationTime = (DateTime?)GetPSObjectProperty(obj, "LastModificationTime"); ; + info.LastAccessTime = ConvertNullableToDateTime(lastAccessTime); + info.LastModificationTime = ConvertNullableToDateTime(lastModificationTime); + ret.Add(info); + } + } + } + finally + { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("GetPublicFoldersStatisticsInternal"); - return ret.ToArray(); - } + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("GetPublicFoldersStatisticsInternal"); + return ret.ToArray(); + } - private string[] GetPublicFoldersRecursiveInternal(string parent) - { - ExchangeLog.LogStart("GetPublicFoldersRecursiveInternal"); + private string[] GetPublicFoldersRecursiveInternal(string parent) + { + ExchangeLog.LogStart("GetPublicFoldersRecursiveInternal"); - Runspace runSpace = null; - List ret = new List(); - try - { - runSpace = OpenRunspace(); - Command cmd = new Command("Get-PublicFolder"); - cmd.Parameters.Add("Identity", parent); - cmd.Parameters.Add("Recurse", true); - if (!string.IsNullOrEmpty(PublicFolderServer)) - cmd.Parameters.Add("Server", PublicFolderServer); + Runspace runSpace = null; + List ret = new List(); + try + { + runSpace = OpenRunspace(); + Command cmd = new Command("Get-PublicFolder"); + cmd.Parameters.Add("Identity", parent); + cmd.Parameters.Add("Recurse", true); + if (!string.IsNullOrEmpty(PublicFolderServer)) + cmd.Parameters.Add("Server", PublicFolderServer); - Collection result = ExecuteShellCommand(runSpace, cmd); - if (result != null) - { - foreach (PSObject obj in result) - { - ret.Add(GetPSObjectIdentity(obj)); - } - } - } - finally - { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("GetPublicFoldersRecursiveInternal"); - return ret.ToArray(); - } + Collection result = ExecuteShellCommand(runSpace, cmd); + if (result != null) + { + foreach (PSObject obj in result) + { + ret.Add(GetPSObjectIdentity(obj)); + } + } + } + finally + { + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("GetPublicFoldersRecursiveInternal"); + return ret.ToArray(); + } - private long GetPublicFolderSizeInternal(string folder) - { - ExchangeLog.LogStart("GetPublicFolderSizeInternal"); - long size = 0; - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); - size += CalculatePublicFolderDiskSpace(runSpace, folder); - } - finally - { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("GetPublicFolderSizeInternal"); - return size; - } + private long GetPublicFolderSizeInternal(string folder) + { + ExchangeLog.LogStart("GetPublicFolderSizeInternal"); + long size = 0; + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + size += CalculatePublicFolderDiskSpace(runSpace, folder); + } + finally + { + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("GetPublicFolderSizeInternal"); + return size; + } - #endregion + #endregion - #region Address Lists (GAL, AL, RAL, OAB, ABP) + #region Address Lists (GAL, AL, RAL, OAB, ABP) - private string GetAddressListDN(Runspace runSpace, string id) - { - ExchangeLog.LogStart("GetAddressListDN"); - string resultObjectDN = null; - Command cmd = new Command("Get-AddressList"); - cmd.Parameters.Add("Identity", id); - Collection result = this.ExecuteShellCommand(runSpace, cmd); - if ((result != null) && (result.Count > 0)) - { - resultObjectDN = this.GetResultObjectDN(result); - ExchangeLog.DebugInfo("AL DN: {0}", new object[] { resultObjectDN }); - } + private string GetAddressListDN(Runspace runSpace, string id) + { + ExchangeLog.LogStart("GetAddressListDN"); + string resultObjectDN = null; + Command cmd = new Command("Get-AddressList"); + cmd.Parameters.Add("Identity", id); + Collection result = this.ExecuteShellCommand(runSpace, cmd); + if ((result != null) && (result.Count > 0)) + { + resultObjectDN = this.GetResultObjectDN(result); + ExchangeLog.DebugInfo("AL DN: {0}", new object[] { resultObjectDN }); + } ExchangeLog.LogEnd("GetAddressListDN"); - return resultObjectDN; - } + return resultObjectDN; + } internal string CreateAddressList(Runspace runSpace, string organizationId) - { - ExchangeLog.LogStart("CreateAddressList"); - string addressListName = this.GetAddressListName(organizationId); - string addressListDN = this.GetAddressListDN(runSpace, addressListName); - if (!string.IsNullOrEmpty(addressListDN)) - { - //address list already exists - we will use it - ExchangeLog.LogWarning("Address List '{0}' already exists", new object[] { addressListName }); - } - else - { - //try to create a new address list (10 attempts) - int attempts = 0; - Command cmd = null; - Collection result = null; + { + ExchangeLog.LogStart("CreateAddressList"); + string addressListName = this.GetAddressListName(organizationId); + string addressListDN = this.GetAddressListDN(runSpace, addressListName); + if (!string.IsNullOrEmpty(addressListDN)) + { + //address list already exists - we will use it + ExchangeLog.LogWarning("Address List '{0}' already exists", new object[] { addressListName }); + } + else + { + //try to create a new address list (10 attempts) + int attempts = 0; + Command cmd = null; + Collection result = null; - while (true) - { - try - { - //try to create address list - cmd = new Command("New-AddressList"); - cmd.Parameters.Add("Name", addressListName); - cmd.Parameters.Add("IncludedRecipients", "AllRecipients"); - cmd.Parameters.Add("ConditionalCustomAttribute1", organizationId); + while (true) + { + try + { + //try to create address list + cmd = new Command("New-AddressList"); + cmd.Parameters.Add("Name", addressListName); + cmd.Parameters.Add("IncludedRecipients", "AllRecipients"); + cmd.Parameters.Add("ConditionalCustomAttribute1", organizationId); - result = ExecuteShellCommand(runSpace, cmd); - addressListDN = CheckResultObjectDN(result); - } - catch (Exception ex) - { - ExchangeLog.LogError(ex); - } - if (addressListDN != null) - break; + result = ExecuteShellCommand(runSpace, cmd); + addressListDN = CheckResultObjectDN(result); + } + catch (Exception ex) + { + ExchangeLog.LogError(ex); + } + if (addressListDN != null) + break; - if (attempts > 9) - throw new Exception( - string.Format("Could not create Address List '{0}' ", addressListName)); + if (attempts > 9) + throw new Exception( + string.Format("Could not create Address List '{0}' ", addressListName)); - attempts++; - ExchangeLog.LogWarning("Attempt #{0} to create address list failed!", attempts); - // wait 1 sec - System.Threading.Thread.Sleep(1000); - } - } + attempts++; + ExchangeLog.LogWarning("Attempt #{0} to create address list failed!", attempts); + // wait 1 sec + System.Threading.Thread.Sleep(1000); + } + } - ExchangeLog.LogEnd("CreateAddressList"); - return addressListDN; - } + ExchangeLog.LogEnd("CreateAddressList"); + return addressListDN; + } internal string CreateRoomsAddressList(Runspace runSpace, string organizationId) { @@ -4939,28 +4927,28 @@ namespace WebsitePanel.Providers.HostedSolution internal void UpdateAddressList(Runspace runSpace, string id, string securityGroup) - { - ExchangeLog.LogStart("UpdateAddressList"); + { + ExchangeLog.LogStart("UpdateAddressList"); - string path = AddADPrefix(id); - Command cmd = new Command("Update-AddressList"); - cmd.Parameters.Add("Identity", id); - ExecuteShellCommand(runSpace, cmd); + string path = AddADPrefix(id); + Command cmd = new Command("Update-AddressList"); + cmd.Parameters.Add("Identity", id); + ExecuteShellCommand(runSpace, cmd); - AdjustADSecurity(path, securityGroup, false); + AdjustADSecurity(path, securityGroup, false); - ExchangeLog.LogEnd("UpdateAddressList"); - } + ExchangeLog.LogEnd("UpdateAddressList"); + } internal void DeleteAddressList(Runspace runSpace, string id) - { - ExchangeLog.LogStart("DeleteAddressList"); - Command cmd = new Command("Remove-AddressList"); - cmd.Parameters.Add("Identity", id); - cmd.Parameters.Add("Confirm", false); - ExecuteShellCommand(runSpace, cmd); - ExchangeLog.LogEnd("DeleteAddressList"); - } + { + ExchangeLog.LogStart("DeleteAddressList"); + Command cmd = new Command("Remove-AddressList"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("Confirm", false); + ExecuteShellCommand(runSpace, cmd); + ExchangeLog.LogEnd("DeleteAddressList"); + } internal virtual void DeleteAddressBookPolicy(Runspace runSpace, string id) @@ -4988,50 +4976,50 @@ namespace WebsitePanel.Providers.HostedSolution } - internal string CreateGlobalAddressList(Runspace runSpace, string organizationId) - { - ExchangeLog.LogStart("CreateGlobalAddressList"); + internal string CreateGlobalAddressList(Runspace runSpace, string organizationId) + { + ExchangeLog.LogStart("CreateGlobalAddressList"); - string name = GetGlobalAddressListName(organizationId); + string name = GetGlobalAddressListName(organizationId); - Command cmd = new Command("New-GlobalAddressList"); - cmd.Parameters.Add("Name", name); - cmd.Parameters.Add("RecipientFilter", string.Format("(Alias -ne $null -and CustomAttribute1 -eq '{0}')", organizationId)); + Command cmd = new Command("New-GlobalAddressList"); + cmd.Parameters.Add("Name", name); + cmd.Parameters.Add("RecipientFilter", string.Format("(Alias -ne $null -and CustomAttribute1 -eq '{0}')", organizationId)); - Collection result = ExecuteShellCommand(runSpace, cmd); - string id = GetResultObjectDN(result); + Collection result = ExecuteShellCommand(runSpace, cmd); + string id = GetResultObjectDN(result); - ExchangeLog.LogEnd("CreateGlobalAddressList"); - return id; - } + ExchangeLog.LogEnd("CreateGlobalAddressList"); + return id; + } - internal void UpdateGlobalAddressList(Runspace runSpace, string id, string securityGroup) - { - ExchangeLog.LogStart("UpdateGlobalAddressList"); + internal void UpdateGlobalAddressList(Runspace runSpace, string id, string securityGroup) + { + ExchangeLog.LogStart("UpdateGlobalAddressList"); - Command cmd = new Command("Update-GlobalAddressList"); - cmd.Parameters.Add("Identity", id); - ExecuteShellCommand(runSpace, cmd); + Command cmd = new Command("Update-GlobalAddressList"); + cmd.Parameters.Add("Identity", id); + ExecuteShellCommand(runSpace, cmd); - string path = AddADPrefix(id); - AdjustADSecurity(path, securityGroup, false); + string path = AddADPrefix(id); + AdjustADSecurity(path, securityGroup, false); - ExchangeLog.LogEnd("UpdateGlobalAddressList"); - } + ExchangeLog.LogEnd("UpdateGlobalAddressList"); + } - internal void DeleteGlobalAddressList(Runspace runSpace, string id) - { - ExchangeLog.LogStart("DeleteGlobalAddressList"); - Command cmd = new Command("Remove-GlobalAddressList"); - cmd.Parameters.Add("Identity", id); - cmd.Parameters.Add("Confirm", false); - ExecuteShellCommand(runSpace, cmd); - ExchangeLog.LogEnd("DeleteGlobalAddressList"); - } + internal void DeleteGlobalAddressList(Runspace runSpace, string id) + { + ExchangeLog.LogStart("DeleteGlobalAddressList"); + Command cmd = new Command("Remove-GlobalAddressList"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("Confirm", false); + ExecuteShellCommand(runSpace, cmd); + ExchangeLog.LogEnd("DeleteGlobalAddressList"); + } - private string CreateOfflineAddressBook(Runspace runSpace, string organizationId, string server, string oabVirtualDirs) - { + private string CreateOfflineAddressBook(Runspace runSpace, string organizationId, string server, string oabVirtualDirs) + { ExchangeLog.LogStart("CreateOfflineAddressBook"); string oabName = GetOfflineAddressBookName(organizationId); @@ -5066,31 +5054,31 @@ namespace WebsitePanel.Providers.HostedSolution return id; } - private void UpdateOfflineAddressBook(Runspace runSpace, string id, string securityGroup) - { - ExchangeLog.LogStart("UpdateOfflineAddressBook"); + private void UpdateOfflineAddressBook(Runspace runSpace, string id, string securityGroup) + { + ExchangeLog.LogStart("UpdateOfflineAddressBook"); - string path = AddADPrefix(id); + string path = AddADPrefix(id); - Command cmd = new Command("Update-OfflineAddressBook"); - cmd.Parameters.Add("Identity", id); - ExecuteShellCommand(runSpace, cmd); + Command cmd = new Command("Update-OfflineAddressBook"); + cmd.Parameters.Add("Identity", id); + ExecuteShellCommand(runSpace, cmd); - AdjustADSecurity(path, securityGroup, true); + AdjustADSecurity(path, securityGroup, true); - ExchangeLog.LogEnd("UpdateOfflineAddressBook"); - } + ExchangeLog.LogEnd("UpdateOfflineAddressBook"); + } - internal void DeleteOfflineAddressBook(Runspace runSpace, string id) - { - ExchangeLog.LogStart("DeleteOfflineAddressBook"); - Command cmd = new Command("Remove-OfflineAddressBook"); - cmd.Parameters.Add("Identity", id); - cmd.Parameters.Add("Confirm", false); - ExecuteShellCommand(runSpace, cmd); - ExchangeLog.LogEnd("DeleteOfflineAddressBook"); - } + internal void DeleteOfflineAddressBook(Runspace runSpace, string id) + { + ExchangeLog.LogStart("DeleteOfflineAddressBook"); + Command cmd = new Command("Remove-OfflineAddressBook"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("Confirm", false); + ExecuteShellCommand(runSpace, cmd); + ExchangeLog.LogEnd("DeleteOfflineAddressBook"); + } private void DeleteAddressPolicy(Runspace runSpace, string id) { @@ -5102,20 +5090,20 @@ namespace WebsitePanel.Providers.HostedSolution ExchangeLog.LogEnd("DeleteAddressPolicy"); } - private string GetAddressListName(string orgName) - { - return orgName + " Address List"; - } + private string GetAddressListName(string orgName) + { + return orgName + " Address List"; + } - internal string GetGlobalAddressListName(string orgName) - { - return orgName + " Global Address List"; - } + internal string GetGlobalAddressListName(string orgName) + { + return orgName + " Global Address List"; + } - private string GetOfflineAddressBookName(string orgName) - { - return orgName + " Offline Address Book"; - } + private string GetOfflineAddressBookName(string orgName) + { + return orgName + " Offline Address Book"; + } internal string GetAddressBookPolicyName(string orgName) { @@ -5127,126 +5115,126 @@ namespace WebsitePanel.Providers.HostedSolution return orgName + " Rooms"; } - #endregion + #endregion - #region Active Directory - private string CreateOrganizationalUnit(string name) - { - ExchangeLog.LogStart("CreateOrganizationalUnit"); + #region Active Directory + private string CreateOrganizationalUnit(string name) + { + ExchangeLog.LogStart("CreateOrganizationalUnit"); - string ret = null; - DirectoryEntry ou = null; - DirectoryEntry rootOU = null; - try - { - rootOU = GetRootOU(); - ou = rootOU.Children.Add( - string.Format("OU={0}", name), - rootOU.SchemaClassName); + string ret = null; + DirectoryEntry ou = null; + DirectoryEntry rootOU = null; + try + { + rootOU = GetRootOU(); + ou = rootOU.Children.Add( + string.Format("OU={0}", name), + rootOU.SchemaClassName); - ret = ou.Path; - ou.CommitChanges(); - } - finally - { - if (ou != null) - ou.Close(); - if (rootOU != null) - rootOU.Close(); - } + ret = ou.Path; + ou.CommitChanges(); + } + finally + { + if (ou != null) + ou.Close(); + if (rootOU != null) + rootOU.Close(); + } - ExchangeLog.LogEnd("CreateOrganizationalUnit"); - return ret; - } + ExchangeLog.LogEnd("CreateOrganizationalUnit"); + return ret; + } - private void DeleteADObject(string id) - { - ExchangeLog.LogStart("DeleteADObject"); + private void DeleteADObject(string id) + { + ExchangeLog.LogStart("DeleteADObject"); - string path = AddADPrefix(id); + string path = AddADPrefix(id); - DirectoryEntry ou = GetADObject(path); - DirectoryEntry parent = ou.Parent; - if (parent != null) - { - parent.Children.Remove(ou); - parent.CommitChanges(); - } + DirectoryEntry ou = GetADObject(path); + DirectoryEntry parent = ou.Parent; + if (parent != null) + { + parent.Children.Remove(ou); + parent.CommitChanges(); + } - ExchangeLog.LogEnd("DeleteADObject"); - } + ExchangeLog.LogEnd("DeleteADObject"); + } private DirectoryEntry GetRootOU() - { - ExchangeLog.LogStart("GetRootOU"); - StringBuilder sb = new StringBuilder(); - // append provider - AppendProtocol(sb); - AppendDomainController(sb); - AppendOUPath(sb, RootOU); - AppendDomainPath(sb, RootDomain); + { + ExchangeLog.LogStart("GetRootOU"); + StringBuilder sb = new StringBuilder(); + // append provider + AppendProtocol(sb); + AppendDomainController(sb); + AppendOUPath(sb, RootOU); + AppendDomainPath(sb, RootDomain); - DirectoryEntry de = GetADObject(sb.ToString()); - ExchangeLog.LogEnd("GetRootOU"); - return de; - } + DirectoryEntry de = GetADObject(sb.ToString()); + ExchangeLog.LogEnd("GetRootOU"); + return de; + } private void SetADObjectProperty(DirectoryEntry oDE, string name, string value) - { - if (!string.IsNullOrEmpty(value)) - { - if (oDE.Properties.Contains(name)) - { - oDE.Properties[name][0] = value; - } - else - { - oDE.Properties[name].Add(value); - } - } - } + { + if (!string.IsNullOrEmpty(value)) + { + if (oDE.Properties.Contains(name)) + { + oDE.Properties[name][0] = value; + } + else + { + oDE.Properties[name].Add(value); + } + } + } internal void SetADObjectPropertyValue(DirectoryEntry oDE, string name, string value) - { - PropertyValueCollection collection = oDE.Properties[name]; - collection.Value = value; - } + { + PropertyValueCollection collection = oDE.Properties[name]; + collection.Value = value; + } internal void AddADObjectProperty(DirectoryEntry oDE, string name, string value) - { - if (!string.IsNullOrEmpty(value)) - { - oDE.Properties[name].Add(value); + { + if (!string.IsNullOrEmpty(value)) + { + oDE.Properties[name].Add(value); - } - } + } + } - internal DirectoryEntry GetADObject(string path) - { - DirectoryEntry de = null; - if (path.StartsWith("LDAP://" + PrimaryDomainController + "/", true, CultureInfo.InvariantCulture)) - { - ExchangeLog.LogInfo("Get Active Directory Object {0} from {1}", path, PrimaryDomainController); - de = new DirectoryEntry(path, null, null, AuthenticationTypes.ServerBind); - } - else - { - ExchangeLog.LogInfo("Get Active Directory Object {0}", path); - de = new DirectoryEntry(path); - } - if (de != null) - de.RefreshCache(); - return de; - } + internal DirectoryEntry GetADObject(string path) + { + DirectoryEntry de = null; + if (path.StartsWith("LDAP://" + PrimaryDomainController + "/", true, CultureInfo.InvariantCulture)) + { + ExchangeLog.LogInfo("Get Active Directory Object {0} from {1}", path, PrimaryDomainController); + de = new DirectoryEntry(path, null, null, AuthenticationTypes.ServerBind); + } + else + { + ExchangeLog.LogInfo("Get Active Directory Object {0}", path); + de = new DirectoryEntry(path); + } + if (de != null) + de.RefreshCache(); + return de; + } internal object GetADObjectProperty(DirectoryEntry entry, string name) - { - if (entry.Properties.Contains(name)) - return entry.Properties[name][0]; - else - return String.Empty; - } + { + if (entry.Properties.Contains(name)) + return entry.Properties[name][0]; + else + return String.Empty; + } private string GetOrganizationPath(string organizationId) @@ -5260,311 +5248,311 @@ namespace WebsitePanel.Providers.HostedSolution return sb.ToString(); } - private void AppendProtocol(StringBuilder sb) - { - sb.Append("LDAP://"); - } + private void AppendProtocol(StringBuilder sb) + { + sb.Append("LDAP://"); + } - private void AppendDomainController(StringBuilder sb) - { - sb.Append(PrimaryDomainController + "/"); - } + private void AppendDomainController(StringBuilder sb) + { + sb.Append(PrimaryDomainController + "/"); + } - private void AppendOUPath(StringBuilder sb, string ou) - { - if (string.IsNullOrEmpty(ou)) - return; + private void AppendOUPath(StringBuilder sb, string ou) + { + if (string.IsNullOrEmpty(ou)) + return; - string path = ou.Replace("/", "\\"); - string[] parts = path.Split('\\'); - for (int i = parts.Length - 1; i != -1; i--) - sb.Append("OU=").Append(parts[i]).Append(","); - } + string path = ou.Replace("/", "\\"); + string[] parts = path.Split('\\'); + for (int i = parts.Length - 1; i != -1; i--) + sb.Append("OU=").Append(parts[i]).Append(","); + } - private void AppendDomainPath(StringBuilder sb, string domain) - { - if (string.IsNullOrEmpty(domain)) - return; + private void AppendDomainPath(StringBuilder sb, string domain) + { + if (string.IsNullOrEmpty(domain)) + return; - string[] parts = domain.Split('.'); - for (int i = 0; i < parts.Length; i++) - { - sb.Append("DC=").Append(parts[i]); + string[] parts = domain.Split('.'); + for (int i = 0; i < parts.Length; i++) + { + sb.Append("DC=").Append(parts[i]); - if (i < (parts.Length - 1)) - sb.Append(","); - } - } + if (i < (parts.Length - 1)) + sb.Append(","); + } + } - internal string AddADPrefix(string path) - { - string dn = path; - if (!dn.ToUpper().StartsWith("LDAP://")) - { - dn = string.Format("LDAP://{0}/{1}", PrimaryDomainController, dn); - } - return dn; - } + internal string AddADPrefix(string path) + { + string dn = path; + if (!dn.ToUpper().StartsWith("LDAP://")) + { + dn = string.Format("LDAP://{0}/{1}", PrimaryDomainController, dn); + } + return dn; + } - private string RemoveADPrefix(string path) - { - string dn = path; - if (dn.ToUpper().StartsWith("LDAP://")) - { - dn = dn.Substring(7); - } - int index = dn.IndexOf("/"); + private string RemoveADPrefix(string path) + { + string dn = path; + if (dn.ToUpper().StartsWith("LDAP://")) + { + dn = dn.Substring(7); + } + int index = dn.IndexOf("/"); - if (index != -1) - { - dn = dn.Substring(index + 1); - } - return dn; - } + if (index != -1) + { + dn = dn.Substring(index + 1); + } + return dn; + } - internal string ConvertADPathToCanonicalName(string name) - { + internal string ConvertADPathToCanonicalName(string name) + { - if (string.IsNullOrEmpty(name)) - return null; + if (string.IsNullOrEmpty(name)) + return null; - StringBuilder ret = new StringBuilder(); - List cn = new List(); - List dc = new List(); + StringBuilder ret = new StringBuilder(); + List cn = new List(); + List dc = new List(); - name = RemoveADPrefix(name); + name = RemoveADPrefix(name); - string[] parts = name.Split(','); - for (int i = 0; i < parts.Length; i++) - { - if (parts[i].StartsWith("DC=")) - { - dc.Add(parts[i].Substring(3)); - } - else if (parts[i].StartsWith("OU=") || parts[i].StartsWith("CN=")) - { - cn.Add(parts[i].Substring(3)); - } - } + string[] parts = name.Split(','); + for (int i = 0; i < parts.Length; i++) + { + if (parts[i].StartsWith("DC=")) + { + dc.Add(parts[i].Substring(3)); + } + else if (parts[i].StartsWith("OU=") || parts[i].StartsWith("CN=")) + { + cn.Add(parts[i].Substring(3)); + } + } - for (int i = 0; i < dc.Count; i++) - { - ret.Append(dc[i]); - if (i < dc.Count - 1) - ret.Append("."); - } - for (int i = cn.Count - 1; i != -1; i--) - { - ret.Append("/"); - ret.Append(cn[i]); - } - return ret.ToString(); - } + for (int i = 0; i < dc.Count; i++) + { + ret.Append(dc[i]); + if (i < dc.Count - 1) + ret.Append("."); + } + for (int i = cn.Count - 1; i != -1; i--) + { + ret.Append("/"); + ret.Append(cn[i]); + } + return ret.ToString(); + } - private string ConvertDomainName(string name) - { + private string ConvertDomainName(string name) + { - if (string.IsNullOrEmpty(name)) - return null; + if (string.IsNullOrEmpty(name)) + return null; - StringBuilder ret = new StringBuilder("LDAP://"); + StringBuilder ret = new StringBuilder("LDAP://"); - string[] parts = name.Split('.'); - for (int i = 0; i < parts.Length; i++) - { - ret.Append("DC="); - ret.Append(parts[i]); - if (i < parts.Length - 1) - ret.Append(","); - } - return ret.ToString(); - } + string[] parts = name.Split('.'); + for (int i = 0; i < parts.Length; i++) + { + ret.Append("DC="); + ret.Append(parts[i]); + if (i < parts.Length - 1) + ret.Append(","); + } + return ret.ToString(); + } - internal virtual void AdjustADSecurity(string objPath, string securityGroupPath, bool isAddressBook) - { - ExchangeLog.LogStart("AdjustADSecurity"); - ExchangeLog.DebugInfo(" Active Direcory object: {0}", objPath); - ExchangeLog.DebugInfo(" Security Group: {0}", securityGroupPath); + internal virtual void AdjustADSecurity(string objPath, string securityGroupPath, bool isAddressBook) + { + ExchangeLog.LogStart("AdjustADSecurity"); + ExchangeLog.DebugInfo(" Active Direcory object: {0}", objPath); + ExchangeLog.DebugInfo(" Security Group: {0}", securityGroupPath); - //"Open Address Book" security permission for address lists or - //"Download Address Book" security permission for offline address book - Guid openAddressBookGuid = new Guid("{a1990816-4298-11d1-ade2-00c04fd8d5cd}"); - if (isAddressBook) - openAddressBookGuid = new Guid("{bd919c7c-2d79-4950-bc9c-e16fd99285e8}"); + //"Open Address Book" security permission for address lists or + //"Download Address Book" security permission for offline address book + Guid openAddressBookGuid = new Guid("{a1990816-4298-11d1-ade2-00c04fd8d5cd}"); + if (isAddressBook) + openAddressBookGuid = new Guid("{bd919c7c-2d79-4950-bc9c-e16fd99285e8}"); - DirectoryEntry groupEntry = GetADObject(securityGroupPath); - byte[] byteSid = (byte[])GetADObjectProperty(groupEntry, "objectSid"); + DirectoryEntry groupEntry = GetADObject(securityGroupPath); + byte[] byteSid = (byte[])GetADObjectProperty(groupEntry, "objectSid"); - DirectoryEntry objEntry = GetADObject(objPath); - ActiveDirectorySecurity security = objEntry.ObjectSecurity; + DirectoryEntry objEntry = GetADObject(objPath); + ActiveDirectorySecurity security = objEntry.ObjectSecurity; - // Create a SecurityIdentifier object for "AuthenticatedUsers". - SecurityIdentifier auSid = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null); - // Create a SecurityIdentifier object for security group. - SecurityIdentifier groupSid = new SecurityIdentifier(byteSid, 0); + // Create a SecurityIdentifier object for "AuthenticatedUsers". + SecurityIdentifier auSid = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null); + // Create a SecurityIdentifier object for security group. + SecurityIdentifier groupSid = new SecurityIdentifier(byteSid, 0); - // Create an access rule to allow AuthenticatedUsers to open address book. - // This is used to remove any existing access rules. - ActiveDirectoryAccessRule allowOpenAddressBook = - new ActiveDirectoryAccessRule( - auSid, - ActiveDirectoryRights.ExtendedRight, - AccessControlType.Allow, - openAddressBookGuid); + // Create an access rule to allow AuthenticatedUsers to open address book. + // This is used to remove any existing access rules. + ActiveDirectoryAccessRule allowOpenAddressBook = + new ActiveDirectoryAccessRule( + auSid, + ActiveDirectoryRights.ExtendedRight, + AccessControlType.Allow, + openAddressBookGuid); - // Create an access rule to allow AuthenticatedUsers to read object. - // This is used to remove any existing access rules. - ActiveDirectoryAccessRule allowRead = - new ActiveDirectoryAccessRule( - auSid, - ActiveDirectoryRights.GenericRead, - AccessControlType.Allow); + // Create an access rule to allow AuthenticatedUsers to read object. + // This is used to remove any existing access rules. + ActiveDirectoryAccessRule allowRead = + new ActiveDirectoryAccessRule( + auSid, + ActiveDirectoryRights.GenericRead, + AccessControlType.Allow); - // Remove any existing rule that gives "AuthenticatedUsers" the right to open address book. - security.RemoveAccessRuleSpecific(allowOpenAddressBook); - // Remove any existing rule that gives "AuthenticatedUsers" the right to read object. - security.RemoveAccessRuleSpecific(allowRead); + // Remove any existing rule that gives "AuthenticatedUsers" the right to open address book. + security.RemoveAccessRuleSpecific(allowOpenAddressBook); + // Remove any existing rule that gives "AuthenticatedUsers" the right to read object. + security.RemoveAccessRuleSpecific(allowRead); - // Create an access rule to allow users in Security Group to open address book. - allowOpenAddressBook = - new ActiveDirectoryAccessRule( - groupSid, - ActiveDirectoryRights.ExtendedRight, - AccessControlType.Allow, - openAddressBookGuid); + // Create an access rule to allow users in Security Group to open address book. + allowOpenAddressBook = + new ActiveDirectoryAccessRule( + groupSid, + ActiveDirectoryRights.ExtendedRight, + AccessControlType.Allow, + openAddressBookGuid); - // Create an access rule to allow users in Security Group to read object. - allowRead = - new ActiveDirectoryAccessRule( - groupSid, - ActiveDirectoryRights.GenericRead, - AccessControlType.Allow); + // Create an access rule to allow users in Security Group to read object. + allowRead = + new ActiveDirectoryAccessRule( + groupSid, + ActiveDirectoryRights.GenericRead, + AccessControlType.Allow); - // Remove existing rules if exist - security.RemoveAccessRuleSpecific(allowOpenAddressBook); - security.RemoveAccessRuleSpecific(allowRead); + // Remove existing rules if exist + security.RemoveAccessRuleSpecific(allowOpenAddressBook); + security.RemoveAccessRuleSpecific(allowRead); - // Add a new access rule to allow users in Security Group to open address book. - security.AddAccessRule(allowOpenAddressBook); - // Add a new access rule to allow users in Security Group to read object. - security.AddAccessRule(allowRead); + // Add a new access rule to allow users in Security Group to open address book. + security.AddAccessRule(allowOpenAddressBook); + // Add a new access rule to allow users in Security Group to read object. + security.AddAccessRule(allowRead); - // Commit the changes. - objEntry.CommitChanges(); - ExchangeLog.LogEnd("AdjustADSecurity"); - } + // Commit the changes. + objEntry.CommitChanges(); + ExchangeLog.LogEnd("AdjustADSecurity"); + } - private void AddUPNSuffix(string ouPath, string suffix) - { - ExchangeLog.LogStart("AddUPNSuffix"); - //Add UPN Suffix to the OU - DirectoryEntry ou = GetADObject(ouPath); - AddADObjectProperty(ou, "uPNSuffixes", suffix); - ou.CommitChanges(); - ou.Close(); - ExchangeLog.LogEnd("AddUPNSuffix"); - } + private void AddUPNSuffix(string ouPath, string suffix) + { + ExchangeLog.LogStart("AddUPNSuffix"); + //Add UPN Suffix to the OU + DirectoryEntry ou = GetADObject(ouPath); + AddADObjectProperty(ou, "uPNSuffixes", suffix); + ou.CommitChanges(); + ou.Close(); + ExchangeLog.LogEnd("AddUPNSuffix"); + } - private void RemoveUPNSuffix(string ouPath, string suffix) - { - ExchangeLog.LogStart("RemoveUPNSuffix"); + private void RemoveUPNSuffix(string ouPath, string suffix) + { + ExchangeLog.LogStart("RemoveUPNSuffix"); - if (DirectoryEntry.Exists(ouPath)) - { - DirectoryEntry ou = GetADObject(ouPath); - PropertyValueCollection prop = null; - try - { - prop = ou.Properties["uPNSuffixes"]; - } - catch (Exception ex) - { - ExchangeLog.LogWarning("AD object or property not found: {0}", ex); - } + if (DirectoryEntry.Exists(ouPath)) + { + DirectoryEntry ou = GetADObject(ouPath); + PropertyValueCollection prop = null; + try + { + prop = ou.Properties["uPNSuffixes"]; + } + catch (Exception ex) + { + ExchangeLog.LogWarning("AD object or property not found: {0}", ex); + } - if (prop != null) - { - if (ou.Properties["uPNSuffixes"].Contains(suffix)) - { - ou.Properties["uPNSuffixes"].Remove(suffix); - ou.CommitChanges(); - } - ou.Close(); - } - } - ExchangeLog.LogEnd("RemoveUPNSuffix"); - } + if (prop != null) + { + if (ou.Properties["uPNSuffixes"].Contains(suffix)) + { + ou.Properties["uPNSuffixes"].Remove(suffix); + ou.CommitChanges(); + } + ou.Close(); + } + } + ExchangeLog.LogEnd("RemoveUPNSuffix"); + } - /*private void AddGlobalUPNSuffix(string name) - { - ExchangeLog.LogStart("AddGlobalUPNSuffix"); - string path = string.Format("LDAP://{0}/RootDSE", RootDomain); - DirectoryEntry rootDSE = GetADObject(path); - string contextPath = GetADObjectProperty(rootDSE, "ConfigurationNamingContext").ToString(); - DirectoryEntry partitions = GetADObject("LDAP://cn=Partitions," + contextPath); - partitions.Properties["uPNSuffixes"].Add(name); - partitions.CommitChanges(); - partitions.Close(); - rootDSE.Close(); - ExchangeLog.LogEnd("AddGlobalUPNSuffix"); - }*/ + /*private void AddGlobalUPNSuffix(string name) + { + ExchangeLog.LogStart("AddGlobalUPNSuffix"); + string path = string.Format("LDAP://{0}/RootDSE", RootDomain); + DirectoryEntry rootDSE = GetADObject(path); + string contextPath = GetADObjectProperty(rootDSE, "ConfigurationNamingContext").ToString(); + DirectoryEntry partitions = GetADObject("LDAP://cn=Partitions," + contextPath); + partitions.Properties["uPNSuffixes"].Add(name); + partitions.CommitChanges(); + partitions.Close(); + rootDSE.Close(); + ExchangeLog.LogEnd("AddGlobalUPNSuffix"); + }*/ - internal string GetNETBIOSDomainName() - { - ExchangeLog.LogStart("GetNETBIOSDomainName"); - string ret = string.Empty; + internal string GetNETBIOSDomainName() + { + ExchangeLog.LogStart("GetNETBIOSDomainName"); + string ret = string.Empty; - string path = string.Format("LDAP://{0}/RootDSE", RootDomain); - DirectoryEntry rootDSE = GetADObject(path); - string contextPath = GetADObjectProperty(rootDSE, "ConfigurationNamingContext").ToString(); - string defaultContext = GetADObjectProperty(rootDSE, "defaultNamingContext").ToString(); - DirectoryEntry partitions = GetADObject("LDAP://cn=Partitions," + contextPath); + string path = string.Format("LDAP://{0}/RootDSE", RootDomain); + DirectoryEntry rootDSE = GetADObject(path); + string contextPath = GetADObjectProperty(rootDSE, "ConfigurationNamingContext").ToString(); + string defaultContext = GetADObjectProperty(rootDSE, "defaultNamingContext").ToString(); + DirectoryEntry partitions = GetADObject("LDAP://cn=Partitions," + contextPath); - DirectorySearcher searcher = new DirectorySearcher(); - searcher.SearchRoot = partitions; - searcher.Filter = string.Format("(&(objectCategory=crossRef)(nCName={0}))", defaultContext); - searcher.SearchScope = SearchScope.OneLevel; + DirectorySearcher searcher = new DirectorySearcher(); + searcher.SearchRoot = partitions; + searcher.Filter = string.Format("(&(objectCategory=crossRef)(nCName={0}))", defaultContext); + searcher.SearchScope = SearchScope.OneLevel; - //find the first instance - SearchResult result = searcher.FindOne(); - if (result != null) - { - DirectoryEntry partition = GetADObject(result.Path); - ret = GetADObjectProperty(partition, "nETBIOSName").ToString(); - partition.Close(); - } - partitions.Close(); - rootDSE.Close(); - ExchangeLog.LogEnd("GetNETBIOSDomainName"); - return ret; - } + //find the first instance + SearchResult result = searcher.FindOne(); + if (result != null) + { + DirectoryEntry partition = GetADObject(result.Path); + ret = GetADObjectProperty(partition, "nETBIOSName").ToString(); + partition.Close(); + } + partitions.Close(); + rootDSE.Close(); + ExchangeLog.LogEnd("GetNETBIOSDomainName"); + return ret; + } - /*private void RemoveGlobalUPNSuffix(string name) - { - ExchangeLog.LogStart("RemoveGlobalUPNSuffix"); - string path = string.Format("LDAP://{0}/RootDSE", RootDomain); - DirectoryEntry rootDSE = GetADObject(path); - string contextPath = GetADObjectProperty(rootDSE, "ConfigurationNamingContext").ToString(); - DirectoryEntry partitions = GetADObject("LDAP://cn=Partitions," + contextPath); - if (partitions.Properties["uPNSuffixes"].Contains(name)) - { - partitions.Properties["uPNSuffixes"].Remove(name); - partitions.CommitChanges(); - } - partitions.Close(); - rootDSE.Close(); - ExchangeLog.LogEnd("RemoveGlobalUPNSuffix"); - }*/ + /*private void RemoveGlobalUPNSuffix(string name) + { + ExchangeLog.LogStart("RemoveGlobalUPNSuffix"); + string path = string.Format("LDAP://{0}/RootDSE", RootDomain); + DirectoryEntry rootDSE = GetADObject(path); + string contextPath = GetADObjectProperty(rootDSE, "ConfigurationNamingContext").ToString(); + DirectoryEntry partitions = GetADObject("LDAP://cn=Partitions," + contextPath); + if (partitions.Properties["uPNSuffixes"].Contains(name)) + { + partitions.Properties["uPNSuffixes"].Remove(name); + partitions.CommitChanges(); + } + partitions.Close(); + rootDSE.Close(); + ExchangeLog.LogEnd("RemoveGlobalUPNSuffix"); + }*/ - #endregion + #endregion - #region PowerShell integration - /*private Collection ExecuteShellCommand2(Runspace runSpace, string cmd) + #region PowerShell integration + /*private Collection ExecuteShellCommand2(Runspace runSpace, string cmd) { ExchangeLog.LogStart("ExecuteShellCommand"); RunspaceInvoke invoker = new RunspaceInvoke(runSpace); @@ -5583,388 +5571,388 @@ namespace WebsitePanel.Providers.HostedSolution return results; }*/ - private static RunspaceConfiguration runspaceConfiguration = null; - private static string ExchangePath = null; + private static RunspaceConfiguration runspaceConfiguration = null; + private static string ExchangePath = null; - internal static string GetExchangePath() - { - if (string.IsNullOrEmpty(ExchangePath)) - { - RegistryKey root = Registry.LocalMachine; - RegistryKey rk = root.OpenSubKey(ExchangeRegistryPath); - if (rk != null) - { - string value = (string)rk.GetValue("MsiInstallPath", null); - rk.Close(); - if (!string.IsNullOrEmpty(value)) - ExchangePath = Path.Combine(value, "bin"); - } - } - return ExchangePath; - } + internal static string GetExchangePath() + { + if (string.IsNullOrEmpty(ExchangePath)) + { + RegistryKey root = Registry.LocalMachine; + RegistryKey rk = root.OpenSubKey(ExchangeRegistryPath); + if (rk != null) + { + string value = (string)rk.GetValue("MsiInstallPath", null); + rk.Close(); + if (!string.IsNullOrEmpty(value)) + ExchangePath = Path.Combine(value, "bin"); + } + } + return ExchangePath; + } - private static Assembly ResolveExchangeAssembly(object p, ResolveEventArgs args) - { - //Add path for the Exchange 2007 DLLs - if (args.Name.Contains("Microsoft.Exchange")) - { - string exchangePath = GetExchangePath(); - if (string.IsNullOrEmpty(exchangePath)) - return null; + private static Assembly ResolveExchangeAssembly(object p, ResolveEventArgs args) + { + //Add path for the Exchange 2007 DLLs + if (args.Name.Contains("Microsoft.Exchange")) + { + string exchangePath = GetExchangePath(); + if (string.IsNullOrEmpty(exchangePath)) + return null; - string path = Path.Combine(exchangePath, args.Name.Split(',')[0] + ".dll"); - if (!File.Exists(path)) - return null; + string path = Path.Combine(exchangePath, args.Name.Split(',')[0] + ".dll"); + if (!File.Exists(path)) + return null; - ExchangeLog.DebugInfo("Resolved assembly: {0}", path); - return Assembly.LoadFrom(path); - } - else - { - return null; - } - } + ExchangeLog.DebugInfo("Resolved assembly: {0}", path); + return Assembly.LoadFrom(path); + } + else + { + return null; + } + } - internal virtual Runspace OpenRunspace() - { - ExchangeLog.LogStart("OpenRunspace"); + internal virtual Runspace OpenRunspace() + { + ExchangeLog.LogStart("OpenRunspace"); - if (runspaceConfiguration == null) - { - runspaceConfiguration = RunspaceConfiguration.Create(); - PSSnapInException exception = null; + if (runspaceConfiguration == null) + { + runspaceConfiguration = RunspaceConfiguration.Create(); + PSSnapInException exception = null; - PSSnapInInfo info = runspaceConfiguration.AddPSSnapIn(ExchangeSnapInName, out exception); + PSSnapInInfo info = runspaceConfiguration.AddPSSnapIn(ExchangeSnapInName, out exception); - if (exception != null) - { - ExchangeLog.LogWarning("SnapIn error", exception); - } - } - Runspace runSpace = RunspaceFactory.CreateRunspace(runspaceConfiguration); - // - runSpace.Open(); - // - runSpace.SessionStateProxy.SetVariable("ConfirmPreference", "none"); - ExchangeLog.LogEnd("OpenRunspace"); - return runSpace; - } + if (exception != null) + { + ExchangeLog.LogWarning("SnapIn error", exception); + } + } + Runspace runSpace = RunspaceFactory.CreateRunspace(runspaceConfiguration); + // + runSpace.Open(); + // + runSpace.SessionStateProxy.SetVariable("ConfirmPreference", "none"); + ExchangeLog.LogEnd("OpenRunspace"); + return runSpace; + } - internal void CloseRunspace(Runspace runspace) - { - try - { - if (runspace != null && runspace.RunspaceStateInfo.State == RunspaceState.Opened) - { - runspace.Close(); - } - } - catch (Exception ex) - { - ExchangeLog.LogError("Runspace error", ex); - } - } + internal void CloseRunspace(Runspace runspace) + { + try + { + if (runspace != null && runspace.RunspaceStateInfo.State == RunspaceState.Opened) + { + runspace.Close(); + } + } + catch (Exception ex) + { + ExchangeLog.LogError("Runspace error", ex); + } + } - internal Collection ExecuteShellCommand(Runspace runSpace, Command cmd) - { - return ExecuteShellCommand(runSpace, cmd, true); - } + internal Collection ExecuteShellCommand(Runspace runSpace, Command cmd) + { + return ExecuteShellCommand(runSpace, cmd, true); + } - internal Collection ExecuteShellCommand(Runspace runSpace, Command cmd, bool useDomainController) - { - object[] errors; - return ExecuteShellCommand(runSpace, cmd, useDomainController, out errors); - } + internal Collection ExecuteShellCommand(Runspace runSpace, Command cmd, bool useDomainController) + { + object[] errors; + return ExecuteShellCommand(runSpace, cmd, useDomainController, out errors); + } - internal Collection ExecuteShellCommand(Runspace runSpace, Command cmd, out object[] errors) - { - return ExecuteShellCommand(runSpace, cmd, true, out errors); - } + internal Collection ExecuteShellCommand(Runspace runSpace, Command cmd, out object[] errors) + { + return ExecuteShellCommand(runSpace, cmd, true, out errors); + } - internal Collection ExecuteShellCommand(Runspace runSpace, Command cmd, bool useDomainController, out object[] errors) - { - ExchangeLog.LogStart("ExecuteShellCommand"); - List errorList = new List(); + internal Collection ExecuteShellCommand(Runspace runSpace, Command cmd, bool useDomainController, out object[] errors) + { + ExchangeLog.LogStart("ExecuteShellCommand"); + List errorList = new List(); - if (useDomainController) - { - CommandParameter dc = new CommandParameter("DomainController", PrimaryDomainController); - if (!cmd.Parameters.Contains(dc)) - { - cmd.Parameters.Add(dc); - } - } + if (useDomainController) + { + CommandParameter dc = new CommandParameter("DomainController", PrimaryDomainController); + if (!cmd.Parameters.Contains(dc)) + { + cmd.Parameters.Add(dc); + } + } - ExchangeLog.DebugCommand(cmd); - Collection results = null; - // Create a pipeline - Pipeline pipeLine = runSpace.CreatePipeline(); - using (pipeLine) - { - // Add the command - pipeLine.Commands.Add(cmd); - // Execute the pipeline and save the objects returned. - results = pipeLine.Invoke(); + ExchangeLog.DebugCommand(cmd); + Collection results = null; + // Create a pipeline + Pipeline pipeLine = runSpace.CreatePipeline(); + using (pipeLine) + { + // Add the command + pipeLine.Commands.Add(cmd); + // Execute the pipeline and save the objects returned. + results = pipeLine.Invoke(); - // Log out any errors in the pipeline execution - // NOTE: These errors are NOT thrown as exceptions! - // Be sure to check this to ensure that no errors - // happened while executing the command. - if (pipeLine.Error != null && pipeLine.Error.Count > 0) - { - foreach (object item in pipeLine.Error.ReadToEnd()) - { - errorList.Add(item); - string errorMessage = string.Format("Invoke error: {0}", item); - ExchangeLog.LogWarning(errorMessage); - } - } - } - pipeLine = null; - errors = errorList.ToArray(); - ExchangeLog.LogEnd("ExecuteShellCommand"); - return results; - } + // Log out any errors in the pipeline execution + // NOTE: These errors are NOT thrown as exceptions! + // Be sure to check this to ensure that no errors + // happened while executing the command. + if (pipeLine.Error != null && pipeLine.Error.Count > 0) + { + foreach (object item in pipeLine.Error.ReadToEnd()) + { + errorList.Add(item); + string errorMessage = string.Format("Invoke error: {0}", item); + ExchangeLog.LogWarning(errorMessage); + } + } + } + pipeLine = null; + errors = errorList.ToArray(); + ExchangeLog.LogEnd("ExecuteShellCommand"); + return results; + } - /// - /// Returns the distinguished name of the object from the shell execution result - /// - /// - /// - internal string GetResultObjectDN(Collection result) - { - ExchangeLog.LogStart("GetResultObjectDN"); - if (result == null) - throw new ArgumentNullException("result", "Execution result is not specified"); + /// + /// Returns the distinguished name of the object from the shell execution result + /// + /// + /// + internal string GetResultObjectDN(Collection result) + { + ExchangeLog.LogStart("GetResultObjectDN"); + if (result == null) + throw new ArgumentNullException("result", "Execution result is not specified"); - if (result.Count < 1) - throw new ArgumentException("Execution result does not contain any object"); + if (result.Count < 1) + throw new ArgumentException("Execution result does not contain any object"); - if (result.Count > 1) - throw new ArgumentException("Execution result contains more than one object"); + if (result.Count > 1) + throw new ArgumentException("Execution result contains more than one object"); - PSMemberInfo info = result[0].Members["DistinguishedName"]; - if (info == null) - throw new ArgumentException("Execution result does not contain DistinguishedName property", "result"); + PSMemberInfo info = result[0].Members["DistinguishedName"]; + if (info == null) + throw new ArgumentException("Execution result does not contain DistinguishedName property", "result"); - string ret = info.Value.ToString(); - ExchangeLog.LogEnd("GetResultObjectDN"); - return ret; - } + string ret = info.Value.ToString(); + ExchangeLog.LogEnd("GetResultObjectDN"); + return ret; + } - /// - /// Checks the object from the shell execution result. - /// - /// - /// Distinguished name of the object if object exists or null otherwise. - internal string CheckResultObjectDN(Collection result) - { - ExchangeLog.LogStart("CheckResultObjectDN"); + /// + /// Checks the object from the shell execution result. + /// + /// + /// Distinguished name of the object if object exists or null otherwise. + internal string CheckResultObjectDN(Collection result) + { + ExchangeLog.LogStart("CheckResultObjectDN"); - if (result == null) - return null; + if (result == null) + return null; - if (result.Count < 1) - return null; + if (result.Count < 1) + return null; - PSMemberInfo info = result[0].Members["DistinguishedName"]; - if (info == null) - throw new ArgumentException("Execution result does not contain DistinguishedName property", "result"); + PSMemberInfo info = result[0].Members["DistinguishedName"]; + if (info == null) + throw new ArgumentException("Execution result does not contain DistinguishedName property", "result"); - string ret = info.Value.ToString(); - ExchangeLog.LogEnd("CheckResultObjectDN"); - return ret; - } + string ret = info.Value.ToString(); + ExchangeLog.LogEnd("CheckResultObjectDN"); + return ret; + } - /// - /// Returns the identity of the object from the shell execution result - /// - /// - /// - internal string GetResultObjectIdentity(Collection result) - { - ExchangeLog.LogStart("GetResultObjectIdentity"); - if (result == null) - throw new ArgumentNullException("result", "Execution result is not specified"); + /// + /// Returns the identity of the object from the shell execution result + /// + /// + /// + internal string GetResultObjectIdentity(Collection result) + { + ExchangeLog.LogStart("GetResultObjectIdentity"); + if (result == null) + throw new ArgumentNullException("result", "Execution result is not specified"); - if (result.Count < 1) - throw new ArgumentException("Execution result is empty", "result"); + if (result.Count < 1) + throw new ArgumentException("Execution result is empty", "result"); - if (result.Count > 1) - throw new ArgumentException("Execution result contains more than one object", "result"); + if (result.Count > 1) + throw new ArgumentException("Execution result contains more than one object", "result"); - PSMemberInfo info = result[0].Members["Identity"]; - if (info == null) - throw new ArgumentException("Execution result does not contain Identity property", "result"); + PSMemberInfo info = result[0].Members["Identity"]; + if (info == null) + throw new ArgumentException("Execution result does not contain Identity property", "result"); - string ret = info.Value.ToString(); - ExchangeLog.LogEnd("GetResultObjectIdentity"); - return ret; - } + string ret = info.Value.ToString(); + ExchangeLog.LogEnd("GetResultObjectIdentity"); + return ret; + } - /// - /// Returns the identity of the PS object - /// - /// - /// - internal string GetPSObjectIdentity(PSObject obj) - { - ExchangeLog.LogStart("GetPSObjectIdentity"); - if (obj == null) - throw new ArgumentNullException("obj", "PSObject is not specified"); + /// + /// Returns the identity of the PS object + /// + /// + /// + internal string GetPSObjectIdentity(PSObject obj) + { + ExchangeLog.LogStart("GetPSObjectIdentity"); + if (obj == null) + throw new ArgumentNullException("obj", "PSObject is not specified"); - PSMemberInfo info = obj.Members["Identity"]; - if (info == null) - throw new ArgumentException("PSObject does not contain Identity property", "obj"); + PSMemberInfo info = obj.Members["Identity"]; + if (info == null) + throw new ArgumentException("PSObject does not contain Identity property", "obj"); - string ret = info.Value.ToString(); - ExchangeLog.LogEnd("GetPSObjectIdentity"); - return ret; - } + string ret = info.Value.ToString(); + ExchangeLog.LogEnd("GetPSObjectIdentity"); + return ret; + } - internal object GetPSObjectProperty(PSObject obj, string name) - { - return obj.Members[name].Value; - } + internal object GetPSObjectProperty(PSObject obj, string name) + { + return obj.Members[name].Value; + } - #endregion + #endregion - #region Storage - internal virtual string CreateStorageGroup(Runspace runSpace, string name, string server) - { - ExchangeLog.LogStart("CreateStorageGroup"); + #region Storage + internal virtual string CreateStorageGroup(Runspace runSpace, string name, string server) + { + ExchangeLog.LogStart("CreateStorageGroup"); - if (name.StartsWith(server + "\\")) - name = name.Substring(server.Length + 1); + if (name.StartsWith(server + "\\")) + name = name.Substring(server.Length + 1); - string id = string.Format("{0}\\{1}", server, name); + string id = string.Format("{0}\\{1}", server, name); - Command cmd = new Command("Get-StorageGroup"); - cmd.Parameters.Add("Identity", id); - Collection result = ExecuteShellCommand(runSpace, cmd); - if (result != null && result.Count > 0) - { - id = GetResultObjectIdentity(result); - } - else - { - cmd = new Command("New-StorageGroup"); - cmd.Parameters.Add("Name", name); - cmd.Parameters.Add("Server", server); + Command cmd = new Command("Get-StorageGroup"); + cmd.Parameters.Add("Identity", id); + Collection result = ExecuteShellCommand(runSpace, cmd); + if (result != null && result.Count > 0) + { + id = GetResultObjectIdentity(result); + } + else + { + cmd = new Command("New-StorageGroup"); + cmd.Parameters.Add("Name", name); + cmd.Parameters.Add("Server", server); - result = ExecuteShellCommand(runSpace, cmd); - id = GetResultObjectIdentity(result); - } - ExchangeLog.LogEnd("CreateStorageGroup"); - return id; - } + result = ExecuteShellCommand(runSpace, cmd); + id = GetResultObjectIdentity(result); + } + ExchangeLog.LogEnd("CreateStorageGroup"); + return id; + } - internal virtual string CreateMailboxDatabase(Runspace runSpace, string name, string storageGroup) - { - ExchangeLog.LogStart("CreateMailboxDatabase"); + internal virtual string CreateMailboxDatabase(Runspace runSpace, string name, string storageGroup) + { + ExchangeLog.LogStart("CreateMailboxDatabase"); - string id = string.Format("{0}\\{1}", storageGroup, name); - Command cmd = new Command("Get-MailboxDatabase"); - cmd.Parameters.Add("Identity", id); - Collection result = ExecuteShellCommand(runSpace, cmd); - if (result != null && result.Count > 0) - { - id = GetResultObjectIdentity(result); - } - else - { - cmd = new Command("New-MailboxDatabase"); - cmd.Parameters.Add("Name", name); - cmd.Parameters.Add("StorageGroup", storageGroup); + string id = string.Format("{0}\\{1}", storageGroup, name); + Command cmd = new Command("Get-MailboxDatabase"); + cmd.Parameters.Add("Identity", id); + Collection result = ExecuteShellCommand(runSpace, cmd); + if (result != null && result.Count > 0) + { + id = GetResultObjectIdentity(result); + } + else + { + cmd = new Command("New-MailboxDatabase"); + cmd.Parameters.Add("Name", name); + cmd.Parameters.Add("StorageGroup", storageGroup); - result = ExecuteShellCommand(runSpace, cmd); - id = GetResultObjectIdentity(result); + result = ExecuteShellCommand(runSpace, cmd); + id = GetResultObjectIdentity(result); - cmd = new Command("Set-MailboxDatabase"); - cmd.Parameters.Add("Identity", id); - cmd.Parameters.Add("IssueWarningQuota", Unlimited.UnlimitedValue); - cmd.Parameters.Add("ProhibitSendQuota", Unlimited.UnlimitedValue); - cmd.Parameters.Add("ProhibitSendReceiveQuota", Unlimited.UnlimitedValue); - cmd.Parameters.Add("DeletedItemRetention", KeepDeletedItemsDays); - cmd.Parameters.Add("MailboxRetention", KeepDeletedMailboxesDays); - ExecuteShellCommand(runSpace, cmd); + cmd = new Command("Set-MailboxDatabase"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("IssueWarningQuota", Unlimited.UnlimitedValue); + cmd.Parameters.Add("ProhibitSendQuota", Unlimited.UnlimitedValue); + cmd.Parameters.Add("ProhibitSendReceiveQuota", Unlimited.UnlimitedValue); + cmd.Parameters.Add("DeletedItemRetention", KeepDeletedItemsDays); + cmd.Parameters.Add("MailboxRetention", KeepDeletedMailboxesDays); + ExecuteShellCommand(runSpace, cmd); - cmd = new Command("Mount-Database"); - cmd.Parameters.Add("Identity", id); - ExecuteShellCommand(runSpace, cmd); - } + cmd = new Command("Mount-Database"); + cmd.Parameters.Add("Identity", id); + ExecuteShellCommand(runSpace, cmd); + } - ExchangeLog.LogEnd("CreateMailboxDatabase"); + ExchangeLog.LogEnd("CreateMailboxDatabase"); - return id; - } - #endregion + return id; + } + #endregion - #region Domains + #region Domains - private string[] GetAuthoritativeDomainsInternal() - { - ExchangeLog.LogStart("GetAuthoritativeDomainsInternal"); + private string[] GetAuthoritativeDomainsInternal() + { + ExchangeLog.LogStart("GetAuthoritativeDomainsInternal"); - Runspace runSpace = null; - List domains = new List(); - try - { - runSpace = OpenRunspace(); - Command cmd = new Command("Get-AcceptedDomain"); + Runspace runSpace = null; + List domains = new List(); + try + { + runSpace = OpenRunspace(); + Command cmd = new Command("Get-AcceptedDomain"); - Collection result = ExecuteShellCommand(runSpace, cmd); - foreach (PSObject current in result) - { - domains.Add(GetPSObjectProperty(current, "DomainName").ToString()); - } + Collection result = ExecuteShellCommand(runSpace, cmd); + foreach (PSObject current in result) + { + domains.Add(GetPSObjectProperty(current, "DomainName").ToString()); + } - } - catch (Exception ex) - { - ExchangeLog.LogError("GetAuthoritativeDomainsInternal", ex); - throw; - } - finally - { - CloseRunspace(runSpace); - } + } + catch (Exception ex) + { + ExchangeLog.LogError("GetAuthoritativeDomainsInternal", ex); + throw; + } + finally + { + CloseRunspace(runSpace); + } - ExchangeLog.LogEnd("GetAuthoritativeDomainsInternal"); - return domains.ToArray(); + ExchangeLog.LogEnd("GetAuthoritativeDomainsInternal"); + return domains.ToArray(); - } + } - /// - /// Creates Authoritative Domain on Hub Transport Server - /// - /// - /// - private void CreateAuthoritativeDomainInternal(string domain) - { - ExchangeLog.LogStart("CreateAuthoritativeDomainInternal"); + /// + /// Creates Authoritative Domain on Hub Transport Server + /// + /// + /// + private void CreateAuthoritativeDomainInternal(string domain) + { + ExchangeLog.LogStart("CreateAuthoritativeDomainInternal"); - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); - CreateAcceptedDomain(runSpace, domain); - } - catch (Exception ex) - { - ExchangeLog.LogError("CreateAuthoritativeDomainInternal", ex); - throw; - } - finally - { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("CreateAuthoritativeDomainInternal"); - } + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + CreateAcceptedDomain(runSpace, domain); + } + catch (Exception ex) + { + ExchangeLog.LogError("CreateAuthoritativeDomainInternal", ex); + throw; + } + finally + { + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("CreateAuthoritativeDomainInternal"); + } private void ChangeAcceptedDomainTypeInternal(string domainName, ExchangeAcceptedDomainType domainType) { @@ -5975,7 +5963,7 @@ namespace WebsitePanel.Providers.HostedSolution { runSpace = OpenRunspace(); - SetAcceptedDomainType(runSpace, domainName,domainType); + SetAcceptedDomainType(runSpace, domainName, domainType); } catch (Exception ex) { @@ -5991,69 +5979,69 @@ namespace WebsitePanel.Providers.HostedSolution ExchangeLog.LogEnd("ChangeAcceptedDomainType"); } - private void DeleteAcceptedDomain(string domainName) - { - ExchangeLog.LogStart("DeleteAcceptedDomain"); + private void DeleteAcceptedDomain(string domainName) + { + ExchangeLog.LogStart("DeleteAcceptedDomain"); - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); - RemoveAcceptedDomain(runSpace, domainName); - } - catch (Exception ex) - { - ExchangeLog.LogError("DeleteAcceptedDomain", ex); - throw; - } - finally - { + RemoveAcceptedDomain(runSpace, domainName); + } + catch (Exception ex) + { + ExchangeLog.LogError("DeleteAcceptedDomain", ex); + throw; + } + finally + { - CloseRunspace(runSpace); - } + CloseRunspace(runSpace); + } - ExchangeLog.LogEnd("DeleteAcceptedDomain"); - } + ExchangeLog.LogEnd("DeleteAcceptedDomain"); + } - /// - /// Deletes Authoritative Domain on Hub Transport Server - /// - /// - private void DeleteAuthoritativeDomainInternal(string domain) - { - ExchangeLog.LogStart("DeleteDomainInternal"); - //Delete accepted domain - DeleteAcceptedDomain(domain); - ExchangeLog.LogEnd("DeleteDomainInternal"); - } + /// + /// Deletes Authoritative Domain on Hub Transport Server + /// + /// + private void DeleteAuthoritativeDomainInternal(string domain) + { + ExchangeLog.LogStart("DeleteDomainInternal"); + //Delete accepted domain + DeleteAcceptedDomain(domain); + ExchangeLog.LogEnd("DeleteDomainInternal"); + } - private string CreateAcceptedDomain(Runspace runSpace, string name) - { - ExchangeLog.LogStart("CreateAcceptedDomain"); + private string CreateAcceptedDomain(Runspace runSpace, string name) + { + ExchangeLog.LogStart("CreateAcceptedDomain"); - Command cmd = new Command("New-AcceptedDomain"); - cmd.Parameters.Add("Name", name); - cmd.Parameters.Add("DomainName", name); - cmd.Parameters.Add("DomainType", "Authoritative"); + Command cmd = new Command("New-AcceptedDomain"); + cmd.Parameters.Add("Name", name); + cmd.Parameters.Add("DomainName", name); + cmd.Parameters.Add("DomainType", "Authoritative"); - Collection result = ExecuteShellCommand(runSpace, cmd); - string id = GetResultObjectDN(result); + Collection result = ExecuteShellCommand(runSpace, cmd); + string id = GetResultObjectDN(result); - ExchangeLog.LogEnd("CreateAcceptedDomain"); + ExchangeLog.LogEnd("CreateAcceptedDomain"); - return id; - } + return id; + } - private void RemoveAcceptedDomain(Runspace runSpace, string id) - { - ExchangeLog.LogStart("RemoveAcceptedDomain"); - Command cmd = new Command("Remove-AcceptedDomain"); - cmd.Parameters.Add("Identity", id); - cmd.Parameters.Add("Confirm", false); - ExecuteShellCommand(runSpace, cmd); - ExchangeLog.LogEnd("RemoveAcceptedDomain"); - } + private void RemoveAcceptedDomain(Runspace runSpace, string id) + { + ExchangeLog.LogStart("RemoveAcceptedDomain"); + Command cmd = new Command("Remove-AcceptedDomain"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("Confirm", false); + ExecuteShellCommand(runSpace, cmd); + ExchangeLog.LogEnd("RemoveAcceptedDomain"); + } private void SetAcceptedDomainType(Runspace runSpace, string id, ExchangeAcceptedDomainType domainType) { @@ -6066,177 +6054,177 @@ namespace WebsitePanel.Providers.HostedSolution ExchangeLog.LogEnd("SetAcceptedDomainType"); } - #endregion + #endregion - #region ActiveSync - private void CreateOrganizationActiveSyncPolicyInternal(string organizationId) - { - ExchangeLog.LogStart("CreateOrganizationActiveSyncPolicyInternal"); - ExchangeLog.DebugInfo(" Organization Id: {0}", organizationId); - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + #region ActiveSync + private void CreateOrganizationActiveSyncPolicyInternal(string organizationId) + { + ExchangeLog.LogStart("CreateOrganizationActiveSyncPolicyInternal"); + ExchangeLog.DebugInfo(" Organization Id: {0}", organizationId); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); - //create ActiveSync policy - CreateActiveSyncPolicy(runSpace, organizationId); - } - finally - { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("CreateOrganizationActiveSyncPolicyInternal"); - } + //create ActiveSync policy + CreateActiveSyncPolicy(runSpace, organizationId); + } + finally + { + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("CreateOrganizationActiveSyncPolicyInternal"); + } - internal string CreateActiveSyncPolicy(Runspace runSpace, string organizationId) - { - ExchangeLog.LogStart("CreateActiveSyncPolicy"); - Command cmd = new Command("New-ActiveSyncMailboxPolicy"); - cmd.Parameters.Add("Name", organizationId); - cmd.Parameters.Add("AllowNonProvisionableDevices", true); - cmd.Parameters.Add("Confirm", false); - Collection result = ExecuteShellCommand(runSpace, cmd); - string id = GetResultObjectIdentity(result); - ExchangeLog.LogEnd("CreateActiveSyncPolicy"); - return id; - } + internal string CreateActiveSyncPolicy(Runspace runSpace, string organizationId) + { + ExchangeLog.LogStart("CreateActiveSyncPolicy"); + Command cmd = new Command("New-ActiveSyncMailboxPolicy"); + cmd.Parameters.Add("Name", organizationId); + cmd.Parameters.Add("AllowNonProvisionableDevices", true); + cmd.Parameters.Add("Confirm", false); + Collection result = ExecuteShellCommand(runSpace, cmd); + string id = GetResultObjectIdentity(result); + ExchangeLog.LogEnd("CreateActiveSyncPolicy"); + return id; + } - internal void DeleteActiveSyncPolicy(Runspace runSpace, string id) - { - ExchangeLog.LogStart("DeleteActiveSyncPolicy"); - Command cmd = new Command("Remove-ActiveSyncMailboxPolicy"); - cmd.Parameters.Add("Identity", id); - cmd.Parameters.Add("Confirm", false); - ExecuteShellCommand(runSpace, cmd); - ExchangeLog.LogEnd("DeleteActiveSyncPolicy"); - } + internal void DeleteActiveSyncPolicy(Runspace runSpace, string id) + { + ExchangeLog.LogStart("DeleteActiveSyncPolicy"); + Command cmd = new Command("Remove-ActiveSyncMailboxPolicy"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("Confirm", false); + ExecuteShellCommand(runSpace, cmd); + ExchangeLog.LogEnd("DeleteActiveSyncPolicy"); + } - private ExchangeActiveSyncPolicy GetActiveSyncPolicyInternal(string id) - { - ExchangeLog.LogStart("GetActiveSyncPolicyInternal"); - ExchangeLog.DebugInfo("Id: {0}", id); - ExchangeActiveSyncPolicy info = null; + private ExchangeActiveSyncPolicy GetActiveSyncPolicyInternal(string id) + { + ExchangeLog.LogStart("GetActiveSyncPolicyInternal"); + ExchangeLog.DebugInfo("Id: {0}", id); + ExchangeActiveSyncPolicy info = null; - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); - Command cmd = new Command("Get-ActiveSyncMailboxPolicy"); - cmd.Parameters.Add("Identity", id); - Collection result = ExecuteShellCommand(runSpace, cmd); + Command cmd = new Command("Get-ActiveSyncMailboxPolicy"); + cmd.Parameters.Add("Identity", id); + Collection result = ExecuteShellCommand(runSpace, cmd); - if (result != null && result.Count > 0) - { - PSObject policy = result[0]; - info = new ExchangeActiveSyncPolicy(); - info.AllowNonProvisionableDevices = (bool)GetPSObjectProperty(policy, "AllowNonProvisionableDevices"); - info.AttachmentsEnabled = (bool)GetPSObjectProperty(policy, "AttachmentsEnabled"); - info.MaxAttachmentSizeKB = - ConvertUnlimitedToKB((Unlimited)GetPSObjectProperty(policy, "MaxAttachmentSize")); - info.UNCAccessEnabled = (bool)GetPSObjectProperty(policy, "UNCAccessEnabled"); - info.WSSAccessEnabled = (bool)GetPSObjectProperty(policy, "WSSAccessEnabled"); + if (result != null && result.Count > 0) + { + PSObject policy = result[0]; + info = new ExchangeActiveSyncPolicy(); + info.AllowNonProvisionableDevices = (bool)GetPSObjectProperty(policy, "AllowNonProvisionableDevices"); + info.AttachmentsEnabled = (bool)GetPSObjectProperty(policy, "AttachmentsEnabled"); + info.MaxAttachmentSizeKB = + ConvertUnlimitedToKB((Unlimited)GetPSObjectProperty(policy, "MaxAttachmentSize")); + info.UNCAccessEnabled = (bool)GetPSObjectProperty(policy, "UNCAccessEnabled"); + info.WSSAccessEnabled = (bool)GetPSObjectProperty(policy, "WSSAccessEnabled"); - info.DevicePasswordEnabled = (bool)GetPSObjectProperty(policy, "DevicePasswordEnabled"); - info.AlphanumericPasswordRequired = (bool)GetPSObjectProperty(policy, "AlphanumericDevicePasswordRequired"); - info.PasswordRecoveryEnabled = (bool)GetPSObjectProperty(policy, "PasswordRecoveryEnabled"); - info.DeviceEncryptionEnabled = (bool)GetPSObjectProperty(policy, "DeviceEncryptionEnabled"); - info.AllowSimplePassword = (bool)GetPSObjectProperty(policy, "AllowSimpleDevicePassword"); + info.DevicePasswordEnabled = (bool)GetPSObjectProperty(policy, "DevicePasswordEnabled"); + info.AlphanumericPasswordRequired = (bool)GetPSObjectProperty(policy, "AlphanumericDevicePasswordRequired"); + info.PasswordRecoveryEnabled = (bool)GetPSObjectProperty(policy, "PasswordRecoveryEnabled"); + info.DeviceEncryptionEnabled = (bool)GetPSObjectProperty(policy, "DeviceEncryptionEnabled"); + info.AllowSimplePassword = (bool)GetPSObjectProperty(policy, "AllowSimpleDevicePassword"); - info.MaxPasswordFailedAttempts = - ConvertUnlimitedToInt32((Unlimited)GetPSObjectProperty(policy, "MaxDevicePasswordFailedAttempts")); - int? passwordLength = (int?)GetPSObjectProperty(policy, "MinDevicePasswordLength"); - info.MinPasswordLength = ConvertNullableToInt32(passwordLength); + info.MaxPasswordFailedAttempts = + ConvertUnlimitedToInt32((Unlimited)GetPSObjectProperty(policy, "MaxDevicePasswordFailedAttempts")); + int? passwordLength = (int?)GetPSObjectProperty(policy, "MinDevicePasswordLength"); + info.MinPasswordLength = ConvertNullableToInt32(passwordLength); - info.InactivityLockMin = ConvertUnlimitedToMinutes((Unlimited)GetPSObjectProperty(policy, "MaxInactivityTimeDeviceLock")); - info.PasswordExpirationDays = ConvertUnlimitedTimeSpanToDays((Unlimited)GetPSObjectProperty(policy, "DevicePasswordExpiration")); - info.PasswordHistory = (int)GetPSObjectProperty(policy, "DevicePasswordHistory"); + info.InactivityLockMin = ConvertUnlimitedToMinutes((Unlimited)GetPSObjectProperty(policy, "MaxInactivityTimeDeviceLock")); + info.PasswordExpirationDays = ConvertUnlimitedTimeSpanToDays((Unlimited)GetPSObjectProperty(policy, "DevicePasswordExpiration")); + info.PasswordHistory = (int)GetPSObjectProperty(policy, "DevicePasswordHistory"); - info.RefreshInterval = ConvertUnlimitedToHours((Unlimited)GetPSObjectProperty(policy, "DevicePolicyRefreshInterval")); - } - } - finally - { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("GetActiveSyncPolicyInternal"); - return info; - } + info.RefreshInterval = ConvertUnlimitedToHours((Unlimited)GetPSObjectProperty(policy, "DevicePolicyRefreshInterval")); + } + } + finally + { + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("GetActiveSyncPolicyInternal"); + return info; + } - private void SetActiveSyncPolicyInternal( - string id, - bool allowNonProvisionableDevices, - bool attachmentsEnabled, - int maxAttachmentSizeKB, - bool uncAccessEnabled, - bool wssAccessEnabled, - bool devicePasswordEnabled, - bool alphanumericPasswordRequired, - bool passwordRecoveryEnabled, - bool deviceEncryptionEnabled, - bool allowSimplePassword, - int maxPasswordFailedAttempts, - int minPasswordLength, - int inactivityLockMin, - int passwordExpirationDays, - int passwordHistory, - int refreshInterval) - { - ExchangeLog.LogStart("SetActiveSyncPolicyInternal"); - ExchangeLog.DebugInfo("Id: {0}", id); + private void SetActiveSyncPolicyInternal( + string id, + bool allowNonProvisionableDevices, + bool attachmentsEnabled, + int maxAttachmentSizeKB, + bool uncAccessEnabled, + bool wssAccessEnabled, + bool devicePasswordEnabled, + bool alphanumericPasswordRequired, + bool passwordRecoveryEnabled, + bool deviceEncryptionEnabled, + bool allowSimplePassword, + int maxPasswordFailedAttempts, + int minPasswordLength, + int inactivityLockMin, + int passwordExpirationDays, + int passwordHistory, + int refreshInterval) + { + ExchangeLog.LogStart("SetActiveSyncPolicyInternal"); + ExchangeLog.DebugInfo("Id: {0}", id); - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); - Command cmd = new Command("Set-ActiveSyncMailboxPolicy"); - cmd.Parameters.Add("Identity", id); - cmd.Parameters.Add("AllowNonProvisionableDevices", allowNonProvisionableDevices); - cmd.Parameters.Add("AttachmentsEnabled", attachmentsEnabled); - cmd.Parameters.Add("MaxAttachmentSize", ConvertKBToUnlimited(maxAttachmentSizeKB)); - cmd.Parameters.Add("UNCAccessEnabled", uncAccessEnabled); - cmd.Parameters.Add("WSSAccessEnabled", wssAccessEnabled); + Command cmd = new Command("Set-ActiveSyncMailboxPolicy"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("AllowNonProvisionableDevices", allowNonProvisionableDevices); + cmd.Parameters.Add("AttachmentsEnabled", attachmentsEnabled); + cmd.Parameters.Add("MaxAttachmentSize", ConvertKBToUnlimited(maxAttachmentSizeKB)); + cmd.Parameters.Add("UNCAccessEnabled", uncAccessEnabled); + cmd.Parameters.Add("WSSAccessEnabled", wssAccessEnabled); - cmd.Parameters.Add("DevicePasswordEnabled", devicePasswordEnabled); - cmd.Parameters.Add("AlphanumericDevicePasswordRequired", alphanumericPasswordRequired); - cmd.Parameters.Add("PasswordRecoveryEnabled", passwordRecoveryEnabled); - cmd.Parameters.Add("DeviceEncryptionEnabled", deviceEncryptionEnabled); - cmd.Parameters.Add("AllowSimpleDevicePassword", allowSimplePassword); + cmd.Parameters.Add("DevicePasswordEnabled", devicePasswordEnabled); + cmd.Parameters.Add("AlphanumericDevicePasswordRequired", alphanumericPasswordRequired); + cmd.Parameters.Add("PasswordRecoveryEnabled", passwordRecoveryEnabled); + cmd.Parameters.Add("DeviceEncryptionEnabled", deviceEncryptionEnabled); + cmd.Parameters.Add("AllowSimpleDevicePassword", allowSimplePassword); - Unlimited attempts = ConvertInt32ToUnlimited(maxPasswordFailedAttempts); - cmd.Parameters.Add("MaxDevicePasswordFailedAttempts", attempts); + Unlimited attempts = ConvertInt32ToUnlimited(maxPasswordFailedAttempts); + cmd.Parameters.Add("MaxDevicePasswordFailedAttempts", attempts); - int? passwordLength = ConvertInt32ToNullable(minPasswordLength); - cmd.Parameters.Add("MinDevicePasswordLength", passwordLength); + int? passwordLength = ConvertInt32ToNullable(minPasswordLength); + cmd.Parameters.Add("MinDevicePasswordLength", passwordLength); - Unlimited inactivityLock = ConvertMinutesToUnlimitedTimeSpan(inactivityLockMin); - cmd.Parameters.Add("MaxInactivityTimeDeviceLock", inactivityLock); + Unlimited inactivityLock = ConvertMinutesToUnlimitedTimeSpan(inactivityLockMin); + cmd.Parameters.Add("MaxInactivityTimeDeviceLock", inactivityLock); - Unlimited passwordExpiration = ConvertDaysToUnlimitedTimeSpan(passwordExpirationDays); - cmd.Parameters.Add("DevicePasswordExpiration", passwordExpiration); + Unlimited passwordExpiration = ConvertDaysToUnlimitedTimeSpan(passwordExpirationDays); + cmd.Parameters.Add("DevicePasswordExpiration", passwordExpiration); - cmd.Parameters.Add("DevicePasswordHistory", passwordHistory); + cmd.Parameters.Add("DevicePasswordHistory", passwordHistory); - Unlimited refInter = ConvertHoursToUnlimitedTimeSpan(refreshInterval); - cmd.Parameters.Add("DevicePolicyRefreshInterval", refInter); + Unlimited refInter = ConvertHoursToUnlimitedTimeSpan(refreshInterval); + cmd.Parameters.Add("DevicePolicyRefreshInterval", refInter); - ExecuteShellCommand(runSpace, cmd); - } - finally - { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("SetActiveSyncPolicyInternal"); - } - #endregion + ExecuteShellCommand(runSpace, cmd); + } + finally + { + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("SetActiveSyncPolicyInternal"); + } + #endregion - #region Mobile devices + #region Mobile devices - private ExchangeMobileDevice[] GetMobileDevicesInternal(string accountName) - { + private ExchangeMobileDevice[] GetMobileDevicesInternal(string accountName) + { ExchangeLog.LogStart("GetMobileDevicesInternal"); ExchangeLog.DebugInfo("Account name: {0}", accountName); @@ -6274,120 +6262,120 @@ namespace WebsitePanel.Providers.HostedSolution } ExchangeLog.LogEnd("GetMobileDevicesInternal"); return devices.ToArray(); - } + } - private ExchangeMobileDevice GetMobileDeviceObject(PSObject obj) - { - ExchangeMobileDevice device = new ExchangeMobileDevice(); - device.Id = GetPSObjectIdentity(obj); - device.FirstSyncTime = ConvertNullableToDateTime((DateTime?)GetPSObjectProperty(obj, "FirstSyncTime")); - device.LastPolicyUpdateTime = ConvertNullableToDateTime((DateTime?)GetPSObjectProperty(obj, "LastPolicyUpdateTime")); - device.LastSyncAttemptTime = ConvertNullableToDateTime((DateTime?)GetPSObjectProperty(obj, "LastSyncAttemptTime")); - device.LastSuccessSync = ConvertNullableToDateTime((DateTime?)GetPSObjectProperty(obj, "LastSuccessSync")); - device.DeviceType = (string)GetPSObjectProperty(obj, "DeviceType"); - device.DeviceID = (string)GetPSObjectProperty(obj, "DeviceID"); - device.DeviceUserAgent = (string)GetPSObjectProperty(obj, "DeviceUserAgent"); - DateTime? wipeSentTime = (DateTime?)GetPSObjectProperty(obj, "DeviceWipeSentTime"); - device.DeviceWipeSentTime = ConvertNullableToDateTime(wipeSentTime); - DateTime? wipeRequestTime = (DateTime?)GetPSObjectProperty(obj, "DeviceWipeRequestTime"); - device.DeviceWipeRequestTime = ConvertNullableToDateTime(wipeRequestTime); - DateTime? wipeAckTime = (DateTime?)GetPSObjectProperty(obj, "DeviceWipeAckTime"); - device.DeviceWipeAckTime = ConvertNullableToDateTime(wipeAckTime); - device.LastPingHeartbeat = ConvertNullableToInt32((UInt32?)GetPSObjectProperty(obj, "LastPingHeartbeat")); - device.RecoveryPassword = (string)GetPSObjectProperty(obj, "RecoveryPassword"); - device.DeviceModel = (string)GetPSObjectProperty(obj, "DeviceModel"); - device.DeviceIMEI = (string)GetPSObjectProperty(obj, "DeviceIMEI"); - device.DeviceFriendlyName = (string)GetPSObjectProperty(obj, "DeviceFriendlyName"); - device.DeviceOS = (string)GetPSObjectProperty(obj, "DeviceOS"); - device.DeviceOSLanguage = (string)GetPSObjectProperty(obj, "DeviceOSLanguage"); - device.DevicePhoneNumber = (string)GetPSObjectProperty(obj, "DevicePhoneNumber"); - //status - if (wipeAckTime.HasValue) - { - //green - device.Status = MobileDeviceStatus.WipeSuccessful; - } - else - { - if (wipeRequestTime.HasValue || wipeSentTime.HasValue) - { - //red - device.Status = MobileDeviceStatus.PendingWipe; - } - else - { - //black - device.Status = MobileDeviceStatus.OK; - } - } + private ExchangeMobileDevice GetMobileDeviceObject(PSObject obj) + { + ExchangeMobileDevice device = new ExchangeMobileDevice(); + device.Id = GetPSObjectIdentity(obj); + device.FirstSyncTime = ConvertNullableToDateTime((DateTime?)GetPSObjectProperty(obj, "FirstSyncTime")); + device.LastPolicyUpdateTime = ConvertNullableToDateTime((DateTime?)GetPSObjectProperty(obj, "LastPolicyUpdateTime")); + device.LastSyncAttemptTime = ConvertNullableToDateTime((DateTime?)GetPSObjectProperty(obj, "LastSyncAttemptTime")); + device.LastSuccessSync = ConvertNullableToDateTime((DateTime?)GetPSObjectProperty(obj, "LastSuccessSync")); + device.DeviceType = (string)GetPSObjectProperty(obj, "DeviceType"); + device.DeviceID = (string)GetPSObjectProperty(obj, "DeviceID"); + device.DeviceUserAgent = (string)GetPSObjectProperty(obj, "DeviceUserAgent"); + DateTime? wipeSentTime = (DateTime?)GetPSObjectProperty(obj, "DeviceWipeSentTime"); + device.DeviceWipeSentTime = ConvertNullableToDateTime(wipeSentTime); + DateTime? wipeRequestTime = (DateTime?)GetPSObjectProperty(obj, "DeviceWipeRequestTime"); + device.DeviceWipeRequestTime = ConvertNullableToDateTime(wipeRequestTime); + DateTime? wipeAckTime = (DateTime?)GetPSObjectProperty(obj, "DeviceWipeAckTime"); + device.DeviceWipeAckTime = ConvertNullableToDateTime(wipeAckTime); + device.LastPingHeartbeat = ConvertNullableToInt32((UInt32?)GetPSObjectProperty(obj, "LastPingHeartbeat")); + device.RecoveryPassword = (string)GetPSObjectProperty(obj, "RecoveryPassword"); + device.DeviceModel = (string)GetPSObjectProperty(obj, "DeviceModel"); + device.DeviceIMEI = (string)GetPSObjectProperty(obj, "DeviceIMEI"); + device.DeviceFriendlyName = (string)GetPSObjectProperty(obj, "DeviceFriendlyName"); + device.DeviceOS = (string)GetPSObjectProperty(obj, "DeviceOS"); + device.DeviceOSLanguage = (string)GetPSObjectProperty(obj, "DeviceOSLanguage"); + device.DevicePhoneNumber = (string)GetPSObjectProperty(obj, "DevicePhoneNumber"); + //status + if (wipeAckTime.HasValue) + { + //green + device.Status = MobileDeviceStatus.WipeSuccessful; + } + else + { + if (wipeRequestTime.HasValue || wipeSentTime.HasValue) + { + //red + device.Status = MobileDeviceStatus.PendingWipe; + } + else + { + //black + device.Status = MobileDeviceStatus.OK; + } + } - return device; - } + return device; + } - private ExchangeMobileDevice GetMobileDeviceInternal(string id) - { - ExchangeLog.LogStart("GetMobileDeviceInternal"); - ExchangeMobileDevice device = null; - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); - Command cmd = new Command("Get-ActiveSyncDeviceStatistics"); - cmd.Parameters.Add("Identity", id); - cmd.Parameters.Add("ShowRecoveryPassword", true); - Collection result = ExecuteShellCommand(runSpace, cmd); - if (result != null && result.Count > 0) - { - device = GetMobileDeviceObject(result[0]); - } - } - finally - { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("GetMobileDeviceInternal"); - return device; - } + private ExchangeMobileDevice GetMobileDeviceInternal(string id) + { + ExchangeLog.LogStart("GetMobileDeviceInternal"); + ExchangeMobileDevice device = null; + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + Command cmd = new Command("Get-ActiveSyncDeviceStatistics"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("ShowRecoveryPassword", true); + Collection result = ExecuteShellCommand(runSpace, cmd); + if (result != null && result.Count > 0) + { + device = GetMobileDeviceObject(result[0]); + } + } + finally + { + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("GetMobileDeviceInternal"); + return device; + } - private void WipeDataFromDeviceInternal(string id) - { - ExchangeLog.LogStart("WipeDataFromDeviceInternal"); - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); - Command cmd = new Command("Clear-ActiveSyncDevice"); - cmd.Parameters.Add("Identity", id); - cmd.Parameters.Add("Confirm", false); - ExecuteShellCommand(runSpace, cmd); - } - finally - { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("WipeDataFromDeviceInternal"); - } + private void WipeDataFromDeviceInternal(string id) + { + ExchangeLog.LogStart("WipeDataFromDeviceInternal"); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + Command cmd = new Command("Clear-ActiveSyncDevice"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("Confirm", false); + ExecuteShellCommand(runSpace, cmd); + } + finally + { + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("WipeDataFromDeviceInternal"); + } - private void CancelRemoteWipeRequestInternal(string id) - { - ExchangeLog.LogStart("CancelRemoteWipeRequestInternal"); - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); - Command cmd = new Command("Clear-ActiveSyncDevice"); - cmd.Parameters.Add("Identity", id); - cmd.Parameters.Add("Cancel", true); - cmd.Parameters.Add("Confirm", false); - ExecuteShellCommand(runSpace, cmd); - } - finally - { - CloseRunspace(runSpace); - } + private void CancelRemoteWipeRequestInternal(string id) + { + ExchangeLog.LogStart("CancelRemoteWipeRequestInternal"); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + Command cmd = new Command("Clear-ActiveSyncDevice"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("Cancel", true); + cmd.Parameters.Add("Confirm", false); + ExecuteShellCommand(runSpace, cmd); + } + finally + { + CloseRunspace(runSpace); + } - ExchangeLog.LogEnd("CancelRemoteWipeRequestInternal"); - } + ExchangeLog.LogEnd("CancelRemoteWipeRequestInternal"); + } internal void RemoveDevicesInternal(Runspace runSpace, string accountName) @@ -6431,242 +6419,242 @@ namespace WebsitePanel.Providers.HostedSolution } - private void RemoveDeviceInternal(string id) - { - ExchangeLog.LogStart("RemoveDeviceInternal"); - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); - Command cmd = new Command("Remove-ActiveSyncDevice"); - cmd.Parameters.Add("Identity", id); - cmd.Parameters.Add("Confirm", false); - ExecuteShellCommand(runSpace, cmd); - } - finally - { - CloseRunspace(runSpace); - } + private void RemoveDeviceInternal(string id) + { + ExchangeLog.LogStart("RemoveDeviceInternal"); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + Command cmd = new Command("Remove-ActiveSyncDevice"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("Confirm", false); + ExecuteShellCommand(runSpace, cmd); + } + finally + { + CloseRunspace(runSpace); + } - ExchangeLog.LogEnd("RemoveDeviceInternal"); - } - #endregion + ExchangeLog.LogEnd("RemoveDeviceInternal"); + } + #endregion - #region Convert Utils - internal int ConvertUnlimitedToInt32(Unlimited value) - { - int ret = 0; - if (value.IsUnlimited) - { - ret = -1; - } - else - { - ret = value.Value; - } - return ret; - } + #region Convert Utils + internal int ConvertUnlimitedToInt32(Unlimited value) + { + int ret = 0; + if (value.IsUnlimited) + { + ret = -1; + } + else + { + ret = value.Value; + } + return ret; + } - internal Unlimited ConvertInt32ToUnlimited(int value) - { - if (value == -1) - return Unlimited.UnlimitedValue; - else - { - Unlimited ret = new Unlimited(); - ret.Value = value; - return ret; - } - } + internal Unlimited ConvertInt32ToUnlimited(int value) + { + if (value == -1) + return Unlimited.UnlimitedValue; + else + { + Unlimited ret = new Unlimited(); + ret.Value = value; + return ret; + } + } - internal long ConvertUnlimitedToBytes(Unlimited value) - { - long ret = 0; - if (value.IsUnlimited) - { - ret = -1; - } - else - { - ret = Convert.ToInt64(value.Value.ToBytes()); - } - return ret; - } + internal long ConvertUnlimitedToBytes(Unlimited value) + { + long ret = 0; + if (value.IsUnlimited) + { + ret = -1; + } + else + { + ret = Convert.ToInt64(value.Value.ToBytes()); + } + return ret; + } - internal int ConvertUnlimitedToKB(Unlimited value) - { - int ret = 0; - if (value.IsUnlimited) - { - ret = -1; - } - else - { - ret = Convert.ToInt32(value.Value.ToKB()); - } - return ret; - } + internal int ConvertUnlimitedToKB(Unlimited value) + { + int ret = 0; + if (value.IsUnlimited) + { + ret = -1; + } + else + { + ret = Convert.ToInt32(value.Value.ToKB()); + } + return ret; + } - internal int ConvertUnlimitedToMB(Unlimited value) - { - int ret = 0; - if (value.IsUnlimited) - { - ret = -1; - } - else - { - ret = Convert.ToInt32(value.Value.ToMB()); - } - return ret; - } + internal int ConvertUnlimitedToMB(Unlimited value) + { + int ret = 0; + if (value.IsUnlimited) + { + ret = -1; + } + else + { + ret = Convert.ToInt32(value.Value.ToMB()); + } + return ret; + } - internal int ConvertUnlimitedToHours(Unlimited value) - { - int ret = 0; - if (value.IsUnlimited) - { - ret = -1; - } - else - { - ret = Convert.ToInt32(value.Value.TotalHours); - } - return ret; - } + internal int ConvertUnlimitedToHours(Unlimited value) + { + int ret = 0; + if (value.IsUnlimited) + { + ret = -1; + } + else + { + ret = Convert.ToInt32(value.Value.TotalHours); + } + return ret; + } - internal int ConvertUnlimitedToMinutes(Unlimited value) - { - int ret = 0; - if (value.IsUnlimited) - { - ret = -1; - } - else - { - ret = Convert.ToInt32(value.Value.TotalMinutes); - } - return ret; - } + internal int ConvertUnlimitedToMinutes(Unlimited value) + { + int ret = 0; + if (value.IsUnlimited) + { + ret = -1; + } + else + { + ret = Convert.ToInt32(value.Value.TotalMinutes); + } + return ret; + } - internal Unlimited ConvertHoursToUnlimitedTimeSpan(int value) - { - if (value == -1) - return Unlimited.UnlimitedValue; - else - { - Unlimited ret = new Unlimited(); - ret.Value = EnhancedTimeSpan.FromHours(Convert.ToDouble(value)); - return ret; - } + internal Unlimited ConvertHoursToUnlimitedTimeSpan(int value) + { + if (value == -1) + return Unlimited.UnlimitedValue; + else + { + Unlimited ret = new Unlimited(); + ret.Value = EnhancedTimeSpan.FromHours(Convert.ToDouble(value)); + return ret; + } - } + } - internal Unlimited ConvertMinutesToUnlimitedTimeSpan(int value) - { - if (value == -1) - return Unlimited.UnlimitedValue; - else - { - Unlimited ret = new Unlimited(); - ret.Value = EnhancedTimeSpan.FromMinutes(Convert.ToDouble(value)); - return ret; - } - } + internal Unlimited ConvertMinutesToUnlimitedTimeSpan(int value) + { + if (value == -1) + return Unlimited.UnlimitedValue; + else + { + Unlimited ret = new Unlimited(); + ret.Value = EnhancedTimeSpan.FromMinutes(Convert.ToDouble(value)); + return ret; + } + } - internal Unlimited ConvertDaysToUnlimitedTimeSpan(int value) - { - if (value == -1) - return Unlimited.UnlimitedValue; - else - { - Unlimited ret = new Unlimited(); - ret.Value = EnhancedTimeSpan.FromDays(Convert.ToDouble(value)); - return ret; - } - } + internal Unlimited ConvertDaysToUnlimitedTimeSpan(int value) + { + if (value == -1) + return Unlimited.UnlimitedValue; + else + { + Unlimited ret = new Unlimited(); + ret.Value = EnhancedTimeSpan.FromDays(Convert.ToDouble(value)); + return ret; + } + } - internal int ConvertUnlimitedTimeSpanToDays(Unlimited value) - { - int ret = 0; - if (value.IsUnlimited) - { - ret = -1; - } - else - { - ret = value.Value.Days; - } - return ret; - } + internal int ConvertUnlimitedTimeSpanToDays(Unlimited value) + { + int ret = 0; + if (value.IsUnlimited) + { + ret = -1; + } + else + { + ret = value.Value.Days; + } + return ret; + } - internal int ConvertNullableToInt32(Nullable value) where T : struct - { - int ret = 0; - if (value.HasValue) - { - ret = Convert.ToInt32(value.Value); - } - return ret; - } + internal int ConvertNullableToInt32(Nullable value) where T : struct + { + int ret = 0; + if (value.HasValue) + { + ret = Convert.ToInt32(value.Value); + } + return ret; + } - internal int? ConvertInt32ToNullable(int value) - { - int? ret = null; - if (value != 0) - { - ret = new int?(value); - } - return ret; - } + internal int? ConvertInt32ToNullable(int value) + { + int? ret = null; + if (value != 0) + { + ret = new int?(value); + } + return ret; + } - internal DateTime ConvertNullableToDateTime(DateTime? value) - { - DateTime ret = DateTime.MinValue; - if (value.HasValue) - { - ret = value.Value; - } - return ret; - } + internal DateTime ConvertNullableToDateTime(DateTime? value) + { + DateTime ret = DateTime.MinValue; + if (value.HasValue) + { + ret = value.Value; + } + return ret; + } - internal bool ConvertNullableToBoolean(bool? value) - { - bool ret = false; - if (value.HasValue) - { - ret = value.Value; - } - return ret; - } + internal bool ConvertNullableToBoolean(bool? value) + { + bool ret = false; + if (value.HasValue) + { + ret = value.Value; + } + return ret; + } - internal int ConvertEnhancedTimeSpanToDays(EnhancedTimeSpan value) - { - return value.Days; - } + internal int ConvertEnhancedTimeSpanToDays(EnhancedTimeSpan value) + { + return value.Days; + } - internal EnhancedTimeSpan ConvertDaysToEnhancedTimeSpan(int days) - { - return EnhancedTimeSpan.FromDays(Convert.ToDouble(days)); - } + internal EnhancedTimeSpan ConvertDaysToEnhancedTimeSpan(int days) + { + return EnhancedTimeSpan.FromDays(Convert.ToDouble(days)); + } - internal Unlimited ConvertKBToUnlimited(int kb) - { - if (kb == -1) - return Unlimited.UnlimitedValue; - else - { - Unlimited ret = new Unlimited(); - ret.Value = ByteQuantifiedSize.FromKB(Convert.ToUInt64(kb)); - return ret; - } - } + internal Unlimited ConvertKBToUnlimited(int kb) + { + if (kb == -1) + return Unlimited.UnlimitedValue; + else + { + Unlimited ret = new Unlimited(); + ret.Value = ByteQuantifiedSize.FromKB(Convert.ToUInt64(kb)); + return ret; + } + } internal Unlimited ConvertKBToUnlimited(long kb) { @@ -6681,153 +6669,153 @@ namespace WebsitePanel.Providers.HostedSolution } - internal string ProxyAddressToString(ProxyAddress proxyAddress) - { - string ret = null; - if (proxyAddress != null) - ret = proxyAddress.AddressString; - return ret; - } + internal string ProxyAddressToString(ProxyAddress proxyAddress) + { + string ret = null; + if (proxyAddress != null) + ret = proxyAddress.AddressString; + return ret; + } - internal string SmtpAddressToString(SmtpAddress smtpAddress) - { - string ret = null; - if (smtpAddress != null) - ret = smtpAddress.ToString(); - return ret; - } + internal string SmtpAddressToString(SmtpAddress smtpAddress) + { + string ret = null; + if (smtpAddress != null) + ret = smtpAddress.ToString(); + return ret; + } - internal string CountryInfoToString(CountryInfo countryInfo) - { - string ret = null; - if (countryInfo != null) - ret = countryInfo.Name; - return ret; - } + internal string CountryInfoToString(CountryInfo countryInfo) + { + string ret = null; + if (countryInfo != null) + ret = countryInfo.Name; + return ret; + } - internal CountryInfo ParseCountryInfo(string country) - { - CountryInfo ret = null; - if (!string.IsNullOrEmpty(country)) - { - ret = CountryInfo.Parse(country); - } - return ret; - } + internal CountryInfo ParseCountryInfo(string country) + { + CountryInfo ret = null; + if (!string.IsNullOrEmpty(country)) + { + ret = CountryInfo.Parse(country); + } + return ret; + } - internal string ObjToString(object obj) - { - string ret = null; - if (obj != null) - ret = obj.ToString(); - return ret; - } + internal string ObjToString(object obj) + { + string ret = null; + if (obj != null) + ret = obj.ToString(); + return ret; + } - #endregion + #endregion - #region Utils - private object GetObjectPropertyValue(object obj, string property) - { - PropertyInfo pinfo = obj.GetType().GetProperty(property); - return pinfo.GetValue(obj, null); - } + #region Utils + private object GetObjectPropertyValue(object obj, string property) + { + PropertyInfo pinfo = obj.GetType().GetProperty(property); + return pinfo.GetValue(obj, null); + } - private object GetObjectIndexerValue(object obj, object index) - { - Type t = obj.GetType(); - object ret = t.InvokeMember("Item", BindingFlags.GetProperty, null, obj, new object[] { index }); - return ret; - } + private object GetObjectIndexerValue(object obj, object index) + { + Type t = obj.GetType(); + object ret = t.InvokeMember("Item", BindingFlags.GetProperty, null, obj, new object[] { index }); + return ret; + } - internal string GetServerName() - { - string ret = null; - if (!string.IsNullOrEmpty(MailboxCluster)) - ret = MailboxCluster; - else - ret = System.Environment.MachineName; - return ret; - } + internal string GetServerName() + { + string ret = null; + if (!string.IsNullOrEmpty(MailboxCluster)) + ret = MailboxCluster; + else + ret = System.Environment.MachineName; + return ret; + } - public override bool IsInstalled() - { - int value = 0; - RegistryKey root = Registry.LocalMachine; - RegistryKey rk = root.OpenSubKey(ExchangeRegistryPath); - if (rk != null) - { - value = (int)rk.GetValue("MsiProductMajor", null); - rk.Close(); - } + public override bool IsInstalled() + { + int value = 0; + RegistryKey root = Registry.LocalMachine; + RegistryKey rk = root.OpenSubKey(ExchangeRegistryPath); + if (rk != null) + { + value = (int)rk.GetValue("MsiProductMajor", null); + rk.Close(); + } - return value == 8; - } + return value == 8; + } - public Version GetExchangeVersion() - { - int major = 0; - int minor = 0; - RegistryKey root = Registry.LocalMachine; - RegistryKey rk = root.OpenSubKey(ExchangeRegistryPath); - if (rk != null) - { - major = (int)rk.GetValue("MsiProductMajor", 0); - minor = (int)rk.GetValue("MsiProductMinor", 0); - rk.Close(); - } + public Version GetExchangeVersion() + { + int major = 0; + int minor = 0; + RegistryKey root = Registry.LocalMachine; + RegistryKey rk = root.OpenSubKey(ExchangeRegistryPath); + if (rk != null) + { + major = (int)rk.GetValue("MsiProductMajor", 0); + minor = (int)rk.GetValue("MsiProductMinor", 0); + rk.Close(); + } - return new Version(major, minor); - } - #endregion + return new Version(major, minor); + } + #endregion - #region Transactions + #region Transactions - internal ExchangeTransaction StartTransaction() - { - return new ExchangeTransaction(); - } + internal ExchangeTransaction StartTransaction() + { + return new ExchangeTransaction(); + } - internal void RollbackTransaction(ExchangeTransaction transaction) - { - ExchangeLog.LogStart("RollbackTransaction"); - Runspace runSpace = null; - try - { - runSpace = OpenRunspace(); + internal void RollbackTransaction(ExchangeTransaction transaction) + { + ExchangeLog.LogStart("RollbackTransaction"); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); - for (int i = transaction.Actions.Count - 1; i > -1; i--) - { - //reverse order - try - { - RollbackAction(transaction.Actions[i], runSpace); - } - catch (Exception ex) - { - ExchangeLog.LogError("Rollback error", ex); - } - } - } - catch (Exception ex) - { - ExchangeLog.LogError("Rollback error", ex); - } - finally - { + for (int i = transaction.Actions.Count - 1; i > -1; i--) + { + //reverse order + try + { + RollbackAction(transaction.Actions[i], runSpace); + } + catch (Exception ex) + { + ExchangeLog.LogError("Rollback error", ex); + } + } + } + catch (Exception ex) + { + ExchangeLog.LogError("Rollback error", ex); + } + finally + { - CloseRunspace(runSpace); - } - ExchangeLog.LogEnd("RollbackTransaction"); - } + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("RollbackTransaction"); + } - private void RollbackAction(TransactionAction action, Runspace runspace) - { - ExchangeLog.LogInfo("Rollback action: {0}", action.ActionType); - switch (action.ActionType) - { + private void RollbackAction(TransactionAction action, Runspace runspace) + { + ExchangeLog.LogInfo("Rollback action: {0}", action.ActionType); + switch (action.ActionType) + { case TransactionAction.TransactionActionTypes.CreateOrganizationUnit: DeleteADObject(action.Id); break; @@ -6883,7 +6871,7 @@ namespace WebsitePanel.Providers.HostedSolution SetExtendedRights(runspace, action.Account, action.Id, "Send-as"); break; } - } - #endregion - } + } + #endregion + } } \ No newline at end of file diff --git a/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution/Exchange2010.cs b/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution/Exchange2010.cs index 78970a28..d4a8b7ec 100644 --- a/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution/Exchange2010.cs +++ b/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution/Exchange2010.cs @@ -55,153 +55,374 @@ using Microsoft.Exchange.Data.Storage; namespace WebsitePanel.Providers.HostedSolution { - public class Exchange2010 : Exchange2007 - { - #region Static constructor - static Exchange2010() - { - AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(ResolveExchangeAssembly); - ExchangeRegistryPath = "SOFTWARE\\Microsoft\\ExchangeServer\\v14\\Setup"; - } - #endregion + public class Exchange2010 : Exchange2007 + { + #region Static constructor + static Exchange2010() + { + AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(ResolveExchangeAssembly); + ExchangeRegistryPath = "SOFTWARE\\Microsoft\\ExchangeServer\\v14\\Setup"; + } + #endregion - #region Mailboxes + #region Mailboxes - internal override void SetCalendarSettings(Runspace runspace, string id) - { - ExchangeLog.LogStart("SetCalendarSettings"); - Command cmd = new Command("Set-CalendarProcessing"); - cmd.Parameters.Add("Identity", id); - cmd.Parameters.Add("AutomateProcessing", CalendarProcessingFlags.AutoAccept); - ExecuteShellCommand(runspace, cmd); - ExchangeLog.LogEnd("SetCalendarSettings"); - } + internal override void SetCalendarSettings(Runspace runspace, string id) + { + ExchangeLog.LogStart("SetCalendarSettings"); + Command cmd = new Command("Set-CalendarProcessing"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("AutomateProcessing", CalendarProcessingFlags.AutoAccept); + ExecuteShellCommand(runspace, cmd); + ExchangeLog.LogEnd("SetCalendarSettings"); + } - #endregion - #region Distribution Lists - internal override string GetGroupManager(PSObject group) - { - string ret = null; - MultiValuedProperty ids = - (MultiValuedProperty)GetPSObjectProperty(group, "ManagedBy"); - if ( ids.Count > 0 ) - ret = ObjToString(ids[0]); - return ret; - } + internal override ExchangeMailbox GetMailboxAdvancedSettingsInternal(string accountName) + { + ExchangeLog.LogStart("GetMailboxAdvancedSettingsInternal"); + ExchangeLog.DebugInfo("Account: {0}", accountName); - internal override void RemoveDistributionGroup(Runspace runSpace, string id) - { - ExchangeLog.LogStart("RemoveDistributionGroup"); - Command cmd = new Command("Remove-DistributionGroup"); - cmd.Parameters.Add("Identity", id); - cmd.Parameters.Add("Confirm", false); - cmd.Parameters.Add("BypassSecurityGroupManagerCheck"); - ExecuteShellCommand(runSpace, cmd); - ExchangeLog.LogEnd("RemoveDistributionGroup"); - } + ExchangeMailbox info = new ExchangeMailbox(); + info.AccountName = accountName; + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); - internal override void SetDistributionGroup(Runspace runSpace, string id, string displayName, bool hideFromAddressBook) - { - Command cmd = new Command("Set-DistributionGroup"); - cmd.Parameters.Add("Identity", id); - cmd.Parameters.Add("DisplayName", displayName); - cmd.Parameters.Add("HiddenFromAddressListsEnabled", hideFromAddressBook); - cmd.Parameters.Add("BypassSecurityGroupManagerCheck"); - ExecuteShellCommand(runSpace, cmd); - } + Collection result = GetMailboxObject(runSpace, accountName); + PSObject mailbox = result[0]; - internal override void SetGroup(Runspace runSpace, string id, string managedBy, string notes) - { - Command cmd = new Command("Set-Group"); - cmd.Parameters.Add("Identity", id); - cmd.Parameters.Add("ManagedBy", managedBy); - cmd.Parameters.Add("Notes", notes); - cmd.Parameters.Add("BypassSecurityGroupManagerCheck"); - ExecuteShellCommand(runSpace, cmd); - } + info.IssueWarningKB = + ConvertUnlimitedToKB((Unlimited)GetPSObjectProperty(mailbox, "IssueWarningQuota")); + info.ProhibitSendKB = + ConvertUnlimitedToKB((Unlimited)GetPSObjectProperty(mailbox, "ProhibitSendQuota")); + info.ProhibitSendReceiveKB = + ConvertUnlimitedToKB((Unlimited)GetPSObjectProperty(mailbox, "ProhibitSendReceiveQuota")); + info.KeepDeletedItemsDays = + ConvertEnhancedTimeSpanToDays((EnhancedTimeSpan)GetPSObjectProperty(mailbox, "RetainDeletedItemsFor")); - internal override void RemoveDistributionGroupMember(Runspace runSpace, string group, string member) - { - Command cmd = new Command("Remove-DistributionGroupMember"); - cmd.Parameters.Add("Identity", group); - cmd.Parameters.Add("Member", member); - cmd.Parameters.Add("Confirm", false); - cmd.Parameters.Add("BypassSecurityGroupManagerCheck"); - ExecuteShellCommand(runSpace, cmd); - } + info.EnableLitigationHold = (bool)GetPSObjectProperty(mailbox, "LitigationHoldEnabled"); - internal override void AddDistributionGroupMember(Runspace runSpace, string group, string member) - { - Command cmd = new Command("Add-DistributionGroupMember"); - cmd.Parameters.Add("Identity", group); - cmd.Parameters.Add("Member", member); - cmd.Parameters.Add("BypassSecurityGroupManagerCheck"); - ExecuteShellCommand(runSpace, cmd); - } + info.RecoverabelItemsSpace = + ConvertUnlimitedToKB((Unlimited)GetPSObjectProperty(mailbox, "RecoverableItemsQuota")); + info.RecoverabelItemsWarning = + ConvertUnlimitedToKB((Unlimited)GetPSObjectProperty(mailbox, "RecoverableItemsWarningQuota")); - internal override void SetDistributionListSendOnBehalfAccounts(Runspace runspace, string accountName, string[] sendOnBehalfAccounts) - { - ExchangeLog.LogStart("SetDistributionListSendOnBehalfAccounts"); - Command cmd = new Command("Set-DistributionGroup"); - cmd.Parameters.Add("Identity", accountName); - cmd.Parameters.Add("GrantSendOnBehalfTo", SetSendOnBehalfAccounts(runspace, sendOnBehalfAccounts)); - cmd.Parameters.Add("BypassSecurityGroupManagerCheck"); - ExecuteShellCommand(runspace, cmd); - ExchangeLog.LogEnd("SetDistributionListSendOnBehalfAccounts"); - } - #endregion - #region PowerShell integration - internal override string ExchangeSnapInName - { - get { return "Microsoft.Exchange.Management.PowerShell.E2010"; } - } + //Client Access + Command cmd = new Command("Get-CASMailbox"); + cmd.Parameters.Add("Identity", accountName); + result = ExecuteShellCommand(runSpace, cmd); + mailbox = result[0]; - internal override Runspace OpenRunspace() - { - Runspace runspace = base.OpenRunspace(); - Command cmd = new Command("Set-ADServerSettings"); - cmd.Parameters.Add("PreferredServer", PrimaryDomainController); - ExecuteShellCommand(runspace, cmd, false); - return runspace; - } + info.EnableActiveSync = (bool)GetPSObjectProperty(mailbox, "ActiveSyncEnabled"); + info.EnableOWA = (bool)GetPSObjectProperty(mailbox, "OWAEnabled"); + info.EnableMAPI = (bool)GetPSObjectProperty(mailbox, "MAPIEnabled"); + info.EnablePOP = (bool)GetPSObjectProperty(mailbox, "PopEnabled"); + info.EnableIMAP = (bool)GetPSObjectProperty(mailbox, "ImapEnabled"); - internal static Assembly ResolveExchangeAssembly(object p, ResolveEventArgs args) - { - //Add path for the Exchange 2007 DLLs - if (args.Name.Contains("Microsoft.Exchange")) - { - string exchangePath = GetExchangePath(); - if (string.IsNullOrEmpty(exchangePath)) - return null; + //Statistics + cmd = new Command("Get-MailboxStatistics"); + cmd.Parameters.Add("Identity", accountName); + result = ExecuteShellCommand(runSpace, cmd); + if (result.Count > 0) + { + PSObject statistics = result[0]; + Unlimited totalItemSize = + (Unlimited)GetPSObjectProperty(statistics, "TotalItemSize"); + info.TotalSizeMB = ConvertUnlimitedToMB(totalItemSize); + uint? itemCount = (uint?)GetPSObjectProperty(statistics, "ItemCount"); + info.TotalItems = ConvertNullableToInt32(itemCount); + DateTime? lastLogoffTime = (DateTime?)GetPSObjectProperty(statistics, "LastLogoffTime"); ; + DateTime? lastLogonTime = (DateTime?)GetPSObjectProperty(statistics, "LastLogonTime"); ; + info.LastLogoff = ConvertNullableToDateTime(lastLogoffTime); + info.LastLogon = ConvertNullableToDateTime(lastLogonTime); + } + else + { + info.TotalSizeMB = 0; + info.TotalItems = 0; + info.LastLogoff = DateTime.MinValue; + info.LastLogon = DateTime.MinValue; + } - string path = Path.Combine(exchangePath, args.Name.Split(',')[0] + ".dll"); - if (!File.Exists(path)) - return null; - - ExchangeLog.DebugInfo("Resolved assembly: {0}", path); + //domain + info.Domain = GetNETBIOSDomainName(); + } + finally + { - return Assembly.LoadFrom(path); - } - else - { - return null; - } - } + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("GetMailboxAdvancedSettingsInternal"); + return info; + } - #endregion - #region Storage - internal override string CreateStorageGroup(Runspace runSpace, string name, string server) - { - return string.Empty; - } + internal override ExchangeMailboxStatistics GetMailboxStatisticsInternal(string id) + { + ExchangeLog.LogStart("GetMailboxStatisticsInternal"); + ExchangeLog.DebugInfo("Account: {0}", id); - internal override string CreateMailboxDatabase(Runspace runSpace, string name, string storageGroup) - { - ExchangeLog.LogStart("CreateMailboxDatabase"); - string id; + ExchangeMailboxStatistics info = new ExchangeMailboxStatistics(); + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + Collection result = GetMailboxObject(runSpace, id); + PSObject mailbox = result[0]; + + string dn = GetResultObjectDN(result); + string path = AddADPrefix(dn); + DirectoryEntry entry = GetADObject(path); + info.Enabled = !(bool)entry.InvokeGet("AccountDisabled"); + info.LitigationHoldEnabled = (bool)GetPSObjectProperty(mailbox, "LitigationHoldEnabled"); + + info.DisplayName = (string)GetPSObjectProperty(mailbox, "DisplayName"); + SmtpAddress smtpAddress = (SmtpAddress)GetPSObjectProperty(mailbox, "PrimarySmtpAddress"); + if (smtpAddress != null) + info.PrimaryEmailAddress = smtpAddress.ToString(); + + info.MaxSize = ConvertUnlimitedToBytes((Unlimited)GetPSObjectProperty(mailbox, "ProhibitSendReceiveQuota")); + info.LitigationHoldMaxSize = ConvertUnlimitedToBytes((Unlimited)GetPSObjectProperty(mailbox, "RecoverableItemsQuota")); + + DateTime? whenCreated = (DateTime?)GetPSObjectProperty(mailbox, "WhenCreated"); + info.AccountCreated = ConvertNullableToDateTime(whenCreated); + //Client Access + Command cmd = new Command("Get-CASMailbox"); + cmd.Parameters.Add("Identity", id); + result = ExecuteShellCommand(runSpace, cmd); + mailbox = result[0]; + + info.ActiveSyncEnabled = (bool)GetPSObjectProperty(mailbox, "ActiveSyncEnabled"); + info.OWAEnabled = (bool)GetPSObjectProperty(mailbox, "OWAEnabled"); + info.MAPIEnabled = (bool)GetPSObjectProperty(mailbox, "MAPIEnabled"); + info.POPEnabled = (bool)GetPSObjectProperty(mailbox, "PopEnabled"); + info.IMAPEnabled = (bool)GetPSObjectProperty(mailbox, "ImapEnabled"); + + //Statistics + cmd = new Command("Get-MailboxStatistics"); + cmd.Parameters.Add("Identity", id); + result = ExecuteShellCommand(runSpace, cmd); + if (result.Count > 0) + { + PSObject statistics = result[0]; + Unlimited totalItemSize = (Unlimited)GetPSObjectProperty(statistics, "TotalItemSize"); + info.TotalSize = ConvertUnlimitedToBytes(totalItemSize); + + uint? itemCount = (uint?)GetPSObjectProperty(statistics, "ItemCount"); + info.TotalItems = ConvertNullableToInt32(itemCount); + + totalItemSize = (Unlimited)GetPSObjectProperty(statistics, "FolderAndSubfolderSize"); + info.LitigationHoldTotalSize = ConvertUnlimitedToBytes(totalItemSize); + + itemCount = (uint?)GetPSObjectProperty(statistics, "ItemsInFolder"); + info.LitigationHoldTotalItems = ConvertNullableToInt32(itemCount); + + DateTime? lastLogoffTime = (DateTime?)GetPSObjectProperty(statistics, "LastLogoffTime"); + DateTime? lastLogonTime = (DateTime?)GetPSObjectProperty(statistics, "LastLogonTime"); + info.LastLogoff = ConvertNullableToDateTime(lastLogoffTime); + info.LastLogon = ConvertNullableToDateTime(lastLogonTime); + } + else + { + info.TotalSize = 0; + info.TotalItems = 0; + info.LastLogoff = DateTime.MinValue; + info.LastLogon = DateTime.MinValue; + } + } + finally + { + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("GetMailboxStatisticsInternal"); + return info; + } + + + + internal override void SetMailboxAdvancedSettingsInternal(string organizationId, string accountName, bool enablePOP, bool enableIMAP, + bool enableOWA, bool enableMAPI, bool enableActiveSync, long issueWarningKB, long prohibitSendKB, + long prohibitSendReceiveKB, int keepDeletedItemsDays, int maxRecipients, int maxSendMessageSizeKB, + int maxReceiveMessageSizeKB, bool enabledLitigationHold, long recoverabelItemsSpace, long recoverabelItemsWarning) + { + ExchangeLog.LogStart("SetMailboxAdvancedSettingsInternal"); + ExchangeLog.DebugInfo("Account: {0}", accountName); + + Runspace runSpace = null; + try + { + runSpace = OpenRunspace(); + + + Command cmd = new Command("Set-Mailbox"); + cmd.Parameters.Add("Identity", accountName); + cmd.Parameters.Add("IssueWarningQuota", ConvertKBToUnlimited(issueWarningKB)); + cmd.Parameters.Add("ProhibitSendQuota", ConvertKBToUnlimited(prohibitSendKB)); + cmd.Parameters.Add("ProhibitSendReceiveQuota", ConvertKBToUnlimited(prohibitSendReceiveKB)); + cmd.Parameters.Add("RetainDeletedItemsFor", ConvertDaysToEnhancedTimeSpan(keepDeletedItemsDays)); + cmd.Parameters.Add("RecipientLimits", ConvertInt32ToUnlimited(maxRecipients)); + cmd.Parameters.Add("MaxSendSize", ConvertKBToUnlimited(maxSendMessageSizeKB)); + cmd.Parameters.Add("MaxReceiveSize", ConvertKBToUnlimited(maxReceiveMessageSizeKB)); + + cmd.Parameters.Add("LitigationHoldEnabled", enabledLitigationHold); + cmd.Parameters.Add("RecoverableItemsQuota", ConvertKBToUnlimited(recoverabelItemsSpace)); + cmd.Parameters.Add("RecoverableItemsWarningQuota", ConvertKBToUnlimited(recoverabelItemsWarning)); + + ExecuteShellCommand(runSpace, cmd); + + //Client Access + cmd = new Command("Set-CASMailbox"); + cmd.Parameters.Add("Identity", accountName); + cmd.Parameters.Add("ActiveSyncEnabled", enableActiveSync); + if (enableActiveSync) + { + cmd.Parameters.Add("ActiveSyncMailboxPolicy", organizationId); + } + cmd.Parameters.Add("OWAEnabled", enableOWA); + cmd.Parameters.Add("MAPIEnabled", enableMAPI); + cmd.Parameters.Add("PopEnabled", enablePOP); + cmd.Parameters.Add("ImapEnabled", enableIMAP); + ExecuteShellCommand(runSpace, cmd); + } + finally + { + + CloseRunspace(runSpace); + } + ExchangeLog.LogEnd("SetMailboxAdvancedSettingsInternal"); + } + + + + #endregion + + #region Distribution Lists + internal override string GetGroupManager(PSObject group) + { + string ret = null; + MultiValuedProperty ids = + (MultiValuedProperty)GetPSObjectProperty(group, "ManagedBy"); + if (ids.Count > 0) + ret = ObjToString(ids[0]); + return ret; + } + + internal override void RemoveDistributionGroup(Runspace runSpace, string id) + { + ExchangeLog.LogStart("RemoveDistributionGroup"); + Command cmd = new Command("Remove-DistributionGroup"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("Confirm", false); + cmd.Parameters.Add("BypassSecurityGroupManagerCheck"); + ExecuteShellCommand(runSpace, cmd); + ExchangeLog.LogEnd("RemoveDistributionGroup"); + } + + internal override void SetDistributionGroup(Runspace runSpace, string id, string displayName, bool hideFromAddressBook) + { + Command cmd = new Command("Set-DistributionGroup"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("DisplayName", displayName); + cmd.Parameters.Add("HiddenFromAddressListsEnabled", hideFromAddressBook); + cmd.Parameters.Add("BypassSecurityGroupManagerCheck"); + ExecuteShellCommand(runSpace, cmd); + } + + internal override void SetGroup(Runspace runSpace, string id, string managedBy, string notes) + { + Command cmd = new Command("Set-Group"); + cmd.Parameters.Add("Identity", id); + cmd.Parameters.Add("ManagedBy", managedBy); + cmd.Parameters.Add("Notes", notes); + cmd.Parameters.Add("BypassSecurityGroupManagerCheck"); + ExecuteShellCommand(runSpace, cmd); + } + + internal override void RemoveDistributionGroupMember(Runspace runSpace, string group, string member) + { + Command cmd = new Command("Remove-DistributionGroupMember"); + cmd.Parameters.Add("Identity", group); + cmd.Parameters.Add("Member", member); + cmd.Parameters.Add("Confirm", false); + cmd.Parameters.Add("BypassSecurityGroupManagerCheck"); + ExecuteShellCommand(runSpace, cmd); + } + + internal override void AddDistributionGroupMember(Runspace runSpace, string group, string member) + { + Command cmd = new Command("Add-DistributionGroupMember"); + cmd.Parameters.Add("Identity", group); + cmd.Parameters.Add("Member", member); + cmd.Parameters.Add("BypassSecurityGroupManagerCheck"); + ExecuteShellCommand(runSpace, cmd); + } + + internal override void SetDistributionListSendOnBehalfAccounts(Runspace runspace, string accountName, string[] sendOnBehalfAccounts) + { + ExchangeLog.LogStart("SetDistributionListSendOnBehalfAccounts"); + Command cmd = new Command("Set-DistributionGroup"); + cmd.Parameters.Add("Identity", accountName); + cmd.Parameters.Add("GrantSendOnBehalfTo", SetSendOnBehalfAccounts(runspace, sendOnBehalfAccounts)); + cmd.Parameters.Add("BypassSecurityGroupManagerCheck"); + ExecuteShellCommand(runspace, cmd); + ExchangeLog.LogEnd("SetDistributionListSendOnBehalfAccounts"); + } + #endregion + + #region PowerShell integration + internal override string ExchangeSnapInName + { + get { return "Microsoft.Exchange.Management.PowerShell.E2010"; } + } + + internal override Runspace OpenRunspace() + { + Runspace runspace = base.OpenRunspace(); + Command cmd = new Command("Set-ADServerSettings"); + cmd.Parameters.Add("PreferredServer", PrimaryDomainController); + ExecuteShellCommand(runspace, cmd, false); + return runspace; + } + + internal static Assembly ResolveExchangeAssembly(object p, ResolveEventArgs args) + { + //Add path for the Exchange 2007 DLLs + if (args.Name.Contains("Microsoft.Exchange")) + { + string exchangePath = GetExchangePath(); + if (string.IsNullOrEmpty(exchangePath)) + return null; + + string path = Path.Combine(exchangePath, args.Name.Split(',')[0] + ".dll"); + if (!File.Exists(path)) + return null; + + ExchangeLog.DebugInfo("Resolved assembly: {0}", path); + + return Assembly.LoadFrom(path); + } + else + { + return null; + } + } + + #endregion + + #region Storage + internal override string CreateStorageGroup(Runspace runSpace, string name, string server) + { + return string.Empty; + } + + internal override string CreateMailboxDatabase(Runspace runSpace, string name, string storageGroup) + { + ExchangeLog.LogStart("CreateMailboxDatabase"); + string id; if (name != "*") { Command cmd = new Command("Get-MailboxDatabase"); @@ -220,31 +441,31 @@ namespace WebsitePanel.Providers.HostedSolution { id = "*"; } - ExchangeLog.LogEnd("CreateMailboxDatabase"); - return id; - } - #endregion + ExchangeLog.LogEnd("CreateMailboxDatabase"); + return id; + } + #endregion + - public override bool IsInstalled() { - int value = 0; + int value = 0; bool bResult = false; - RegistryKey root = Registry.LocalMachine; - RegistryKey rk = root.OpenSubKey(ExchangeRegistryPath); - if (rk != null) - { - value = (int)rk.GetValue("MsiProductMajor", null); + RegistryKey root = Registry.LocalMachine; + RegistryKey rk = root.OpenSubKey(ExchangeRegistryPath); + if (rk != null) + { + value = (int)rk.GetValue("MsiProductMajor", null); if (value == 14) { value = (int)rk.GetValue("MsiProductMinor", null); - if ((value == 0) | (value == 1)) bResult = true; + if ((value == 0) | (value == 1)) bResult = true; } - rk.Close(); - } + rk.Close(); + } return bResult; } - } + } } diff --git a/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution/Exchange2010SP2.cs b/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution/Exchange2010SP2.cs index 230ac187..e6a5f908 100644 --- a/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution/Exchange2010SP2.cs +++ b/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution/Exchange2010SP2.cs @@ -327,7 +327,7 @@ namespace WebsitePanel.Providers.HostedSolution string accountName, bool enablePOP, bool enableIMAP, bool enableOWA, bool enableMAPI, bool enableActiveSync, long issueWarningKB, long prohibitSendKB, long prohibitSendReceiveKB, int keepDeletedItemsDays, - int maxRecipients, int maxSendMessageSizeKB, int maxReceiveMessageSizeKB, bool hideFromAddressBook, bool IsConsumer) + int maxRecipients, int maxSendMessageSizeKB, int maxReceiveMessageSizeKB, bool hideFromAddressBook, bool IsConsumer, bool enabledLitigationHold, long recoverabelItemsSpace, long recoverabelItemsWarning) { ExchangeLog.LogStart("CreateMailEnableUserInternal"); @@ -414,6 +414,14 @@ namespace WebsitePanel.Providers.HostedSolution else cmd.Parameters.Add("HiddenFromAddressListsEnabled", hideFromAddressBook); cmd.Parameters.Add("AddressBookPolicy", addressBookPolicy); + + if (enabledLitigationHold) + { + cmd.Parameters.Add("LitigationHoldEnabled", true); + cmd.Parameters.Add("RecoverableItemsQuota", ConvertKBToUnlimited(recoverabelItemsSpace)); + cmd.Parameters.Add("RecoverableItemsWarningQuota", ConvertKBToUnlimited(recoverabelItemsWarning)); + } + ExecuteShellCommand(runSpace, cmd); //Client Access @@ -493,7 +501,7 @@ namespace WebsitePanel.Providers.HostedSolution cmd.Parameters.Add("Identity", id); cmd.Parameters.Add("Confirm", false); ExecuteShellCommand(runSpace, cmd); - + if (addressbookPolicy == (upn + " AP")) { diff --git a/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution/ExchangeLog.cs b/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution/ExchangeLog.cs index aa965e8f..752514f0 100644 --- a/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution/ExchangeLog.cs +++ b/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution/ExchangeLog.cs @@ -36,52 +36,52 @@ namespace WebsitePanel.Providers.HostedSolution /// /// Exchange Log Helper Methods /// - internal class ExchangeLog + public static class ExchangeLog { - internal static string LogPrefix = "Exchange"; + public static string LogPrefix = "Exchange"; - internal static void LogStart(string message, params object[] args) + public static void LogStart(string message, params object[] args) { string text = String.Format(message, args); Log.WriteStart("{0} {1}", LogPrefix, text); } - internal static void LogEnd(string message, params object[] args) + public static void LogEnd(string message, params object[] args) { string text = String.Format(message, args); Log.WriteEnd("{0} {1}", LogPrefix, text); } - internal static void LogInfo(string message, params object[] args) + public static void LogInfo(string message, params object[] args) { string text = String.Format(message, args); Log.WriteInfo("{0} {1}", LogPrefix, text); } - internal static void LogWarning(string message, params object[] args) + public static void LogWarning(string message, params object[] args) { string text = String.Format(message, args); Log.WriteWarning("{0} {1}", LogPrefix, text); } - internal static void LogError(Exception ex) + public static void LogError(Exception ex) { Log.WriteError(LogPrefix, ex); } - internal static void LogError(string message, Exception ex) + public static void LogError(string message, Exception ex) { string text = String.Format("{0} {1}", LogPrefix, message); Log.WriteError(text, ex); } - internal static void DebugInfo(string message, params object[] args) + public static void DebugInfo(string message, params object[] args) { string text = String.Format(message, args); Log.WriteInfo("{0} {1}", LogPrefix, text); } - internal static void DebugCommand(Command cmd) + public static void DebugCommand(Command cmd) { StringBuilder sb = new StringBuilder(cmd.CommandText); foreach (CommandParameter parameter in cmd.Parameters) diff --git a/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution/ExchangeTransaction.cs b/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution/ExchangeTransaction.cs index 1d6e0eba..be3e4773 100644 --- a/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution/ExchangeTransaction.cs +++ b/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution/ExchangeTransaction.cs @@ -30,7 +30,7 @@ using System.Collections.Generic; namespace WebsitePanel.Providers.HostedSolution { - internal class ExchangeTransaction + public class ExchangeTransaction { List actions = null; @@ -39,12 +39,12 @@ namespace WebsitePanel.Providers.HostedSolution actions = new List(); } - internal List Actions + public List Actions { get { return actions; } } - internal void RegisterNewOrganizationUnit(string id) + public void RegisterNewOrganizationUnit(string id) { TransactionAction action = new TransactionAction(); action.ActionType = TransactionAction.TransactionActionTypes.CreateOrganizationUnit; @@ -69,7 +69,7 @@ namespace WebsitePanel.Providers.HostedSolution Actions.Add(action); } - internal void RegisterNewGlobalAddressList(string id) + public void RegisterNewGlobalAddressList(string id) { TransactionAction action = new TransactionAction(); action.ActionType = TransactionAction.TransactionActionTypes.CreateGlobalAddressList; @@ -77,7 +77,7 @@ namespace WebsitePanel.Providers.HostedSolution Actions.Add(action); } - internal void RegisterNewAddressList(string id) + public void RegisterNewAddressList(string id) { TransactionAction action = new TransactionAction(); action.ActionType = TransactionAction.TransactionActionTypes.CreateAddressList; @@ -85,7 +85,7 @@ namespace WebsitePanel.Providers.HostedSolution Actions.Add(action); } - internal void RegisterNewAddressBookPolicy(string id) + public void RegisterNewAddressBookPolicy(string id) { TransactionAction action = new TransactionAction(); action.ActionType = TransactionAction.TransactionActionTypes.CreateAddressBookPolicy; @@ -94,7 +94,7 @@ namespace WebsitePanel.Providers.HostedSolution } - internal void RegisterNewRoomsAddressList(string id) + public void RegisterNewRoomsAddressList(string id) { TransactionAction action = new TransactionAction(); action.ActionType = TransactionAction.TransactionActionTypes.CreateAddressList; @@ -103,7 +103,7 @@ namespace WebsitePanel.Providers.HostedSolution } - internal void RegisterNewOfflineAddressBook(string id) + public void RegisterNewOfflineAddressBook(string id) { TransactionAction action = new TransactionAction(); action.ActionType = TransactionAction.TransactionActionTypes.CreateOfflineAddressBook; @@ -111,7 +111,7 @@ namespace WebsitePanel.Providers.HostedSolution Actions.Add(action); } - internal void RegisterNewActiveSyncPolicy(string id) + public void RegisterNewActiveSyncPolicy(string id) { TransactionAction action = new TransactionAction(); action.ActionType = TransactionAction.TransactionActionTypes.CreateActiveSyncPolicy; @@ -120,7 +120,7 @@ namespace WebsitePanel.Providers.HostedSolution } - internal void RegisterNewAcceptedDomain(string id) + public void RegisterNewAcceptedDomain(string id) { TransactionAction action = new TransactionAction(); action.ActionType = TransactionAction.TransactionActionTypes.CreateAcceptedDomain; @@ -128,7 +128,7 @@ namespace WebsitePanel.Providers.HostedSolution Actions.Add(action); } - internal void RegisterNewUPNSuffix(string id, string suffix) + public void RegisterNewUPNSuffix(string id, string suffix) { TransactionAction action = new TransactionAction(); action.ActionType = TransactionAction.TransactionActionTypes.AddUPNSuffix; @@ -137,7 +137,7 @@ namespace WebsitePanel.Providers.HostedSolution Actions.Add(action); } - internal void RegisterNewMailbox(string id) + public void RegisterNewMailbox(string id) { TransactionAction action = new TransactionAction(); action.ActionType = TransactionAction.TransactionActionTypes.CreateMailbox; @@ -145,7 +145,7 @@ namespace WebsitePanel.Providers.HostedSolution Actions.Add(action); } - internal void RegisterEnableMailbox(string id) + public void RegisterEnableMailbox(string id) { TransactionAction action = new TransactionAction(); action.ActionType = TransactionAction.TransactionActionTypes.EnableMailbox; @@ -154,7 +154,7 @@ namespace WebsitePanel.Providers.HostedSolution } - internal void RegisterNewContact(string id) + public void RegisterNewContact(string id) { TransactionAction action = new TransactionAction(); action.ActionType = TransactionAction.TransactionActionTypes.CreateContact; @@ -162,7 +162,7 @@ namespace WebsitePanel.Providers.HostedSolution Actions.Add(action); } - internal void RegisterNewPublicFolder(string id) + public void RegisterNewPublicFolder(string id) { TransactionAction action = new TransactionAction(); action.ActionType = TransactionAction.TransactionActionTypes.CreatePublicFolder; @@ -170,7 +170,7 @@ namespace WebsitePanel.Providers.HostedSolution Actions.Add(action); } - internal void AddMailBoxFullAccessPermission(string accountName, string id) + public void AddMailBoxFullAccessPermission(string accountName, string id) { TransactionAction action = new TransactionAction(); action.ActionType = TransactionAction.TransactionActionTypes.AddMailboxFullAccessPermission; @@ -179,7 +179,7 @@ namespace WebsitePanel.Providers.HostedSolution Actions.Add(action); } - internal void AddSendAsPermission(string accountName, string id) + public void AddSendAsPermission(string accountName, string id) { TransactionAction action = new TransactionAction(); action.ActionType = TransactionAction.TransactionActionTypes.AddSendAsPermission; @@ -188,7 +188,7 @@ namespace WebsitePanel.Providers.HostedSolution Actions.Add(action); } - internal void RemoveMailboxFullAccessPermission(string accountName, string id) + public void RemoveMailboxFullAccessPermission(string accountName, string id) { TransactionAction action = new TransactionAction(); action.ActionType = TransactionAction.TransactionActionTypes.RemoveMailboxFullAccessPermission; @@ -197,7 +197,7 @@ namespace WebsitePanel.Providers.HostedSolution Actions.Add(action); } - internal void RemoveSendAsPermission(string accountName, string id) + public void RemoveSendAsPermission(string accountName, string id) { TransactionAction action = new TransactionAction(); action.ActionType = TransactionAction.TransactionActionTypes.RemoveSendAsPermission; diff --git a/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution/OrganizationProvider.cs b/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution/OrganizationProvider.cs index cd7e60b0..9dee569f 100644 --- a/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution/OrganizationProvider.cs +++ b/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution/OrganizationProvider.cs @@ -645,7 +645,7 @@ namespace WebsitePanel.Providers.HostedSolution { string path = GetUserPath(organizationId, accountName); DirectoryEntry entry = ActiveDirectoryUtils.GetADObject(path); - + if (!string.IsNullOrEmpty(password)) entry.Invoke(ADAttributes.SetPassword, password); diff --git a/WebsitePanel/Sources/WebsitePanel.Providers.Mail.SmarterMail7/WebsitePanel.Providers.Mail.SmarterMail7.csproj b/WebsitePanel/Sources/WebsitePanel.Providers.Mail.SmarterMail7/WebsitePanel.Providers.Mail.SmarterMail7.csproj index 5714a35a..daef889b 100644 --- a/WebsitePanel/Sources/WebsitePanel.Providers.Mail.SmarterMail7/WebsitePanel.Providers.Mail.SmarterMail7.csproj +++ b/WebsitePanel/Sources/WebsitePanel.Providers.Mail.SmarterMail7/WebsitePanel.Providers.Mail.SmarterMail7.csproj @@ -32,6 +32,7 @@ prompt 4 618 + AllRules.ruleset diff --git a/WebsitePanel/Sources/WebsitePanel.Providers.OS.Windows2003/Windows2003.cs b/WebsitePanel/Sources/WebsitePanel.Providers.OS.Windows2003/Windows2003.cs index f251bd66..f9c8026b 100644 --- a/WebsitePanel/Sources/WebsitePanel.Providers.OS.Windows2003/Windows2003.cs +++ b/WebsitePanel/Sources/WebsitePanel.Providers.OS.Windows2003/Windows2003.cs @@ -209,6 +209,16 @@ namespace WebsitePanel.Providers.OS SecurityUtils.GrantGroupNtfsPermissions(path, users, resetChildPermissions, ServerSettings, usersOU, null); } + + public virtual void SetQuotaLimitOnFolder(string folderPath, string shareNameDrive, string quotaLimit, int mode, string wmiUserName, string wmiPassword) + { + FileUtils.SetQuotaLimitOnFolder(folderPath, shareNameDrive, quotaLimit, mode, wmiUserName, wmiPassword); + } + + public virtual void DeleteDirectoryRecursive(string rootPath) + { + FileUtils.DeleteDirectoryRecursive(rootPath); + } #endregion #region ODBC DSNs @@ -729,5 +739,11 @@ namespace WebsitePanel.Providers.OS { return WebsitePanel.Server.Utils.OS.GetVersion() == WebsitePanel.Server.Utils.OS.WindowsVersion.WindowsServer2003; } + + public virtual bool CheckFileServicesInstallation() + { + return WebsitePanel.Server.Utils.OS.CheckFileServicesInstallation(); + + } } } diff --git a/WebsitePanel/Sources/WebsitePanel.Server.Client/ExchangeServerProxy.cs b/WebsitePanel/Sources/WebsitePanel.Server.Client/ExchangeServerProxy.cs index 64a9509c..0ddc067f 100644 --- a/WebsitePanel/Sources/WebsitePanel.Server.Client/ExchangeServerProxy.cs +++ b/WebsitePanel/Sources/WebsitePanel.Server.Client/ExchangeServerProxy.cs @@ -29,7 +29,7 @@ //------------------------------------------------------------------------------ // // This code was generated by a tool. -// Runtime Version:2.0.50727.5456 +// Runtime Version:2.0.50727.6400 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. @@ -37,19 +37,18 @@ //------------------------------------------------------------------------------ // -// This source code was auto-generated by wsdl, Version=2.0.50727.42. +// This source code was auto-generated by wsdl, Version=2.0.50727.3038. // using WebsitePanel.Providers.HostedSolution; -namespace WebsitePanel.Providers.Exchange -{ +namespace WebsitePanel.Providers.Exchange { using System.Xml.Serialization; using System.Web.Services; using System.ComponentModel; using System.Web.Services.Protocols; using System; - using System.Diagnostics; + using System.Diagnostics; /// @@ -85,6 +84,8 @@ namespace WebsitePanel.Providers.Exchange private System.Threading.SendOrPostCallback AddAuthoritativeDomainOperationCompleted; + private System.Threading.SendOrPostCallback ChangeAcceptedDomainTypeOperationCompleted; + private System.Threading.SendOrPostCallback GetAuthoritativeDomainsOperationCompleted; private System.Threading.SendOrPostCallback DeleteAuthoritativeDomainOperationCompleted; @@ -233,6 +234,9 @@ namespace WebsitePanel.Providers.Exchange /// public event AddAuthoritativeDomainCompletedEventHandler AddAuthoritativeDomainCompleted; + /// + public event ChangeAcceptedDomainTypeCompletedEventHandler ChangeAcceptedDomainTypeCompleted; + /// public event GetAuthoritativeDomainsCompletedEventHandler GetAuthoritativeDomainsCompleted; @@ -516,7 +520,10 @@ namespace WebsitePanel.Providers.Exchange int maxSendMessageSizeKB, int maxReceiveMessageSizeKB, bool hideFromAddressBook, - bool isConsumer) { + bool isConsumer, + bool enabledLitigationHold, + long recoverabelItemsSpace, + long recoverabelItemsWarning) { object[] results = this.Invoke("CreateMailEnableUser", new object[] { upn, organizationId, @@ -539,7 +546,10 @@ namespace WebsitePanel.Providers.Exchange maxSendMessageSizeKB, maxReceiveMessageSizeKB, hideFromAddressBook, - isConsumer}); + isConsumer, + enabledLitigationHold, + recoverabelItemsSpace, + recoverabelItemsWarning}); return ((string)(results[0])); } @@ -567,6 +577,9 @@ namespace WebsitePanel.Providers.Exchange int maxReceiveMessageSizeKB, bool hideFromAddressBook, bool isConsumer, + bool enabledLitigationHold, + long recoverabelItemsSpace, + long recoverabelItemsWarning, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("CreateMailEnableUser", new object[] { @@ -591,7 +604,10 @@ namespace WebsitePanel.Providers.Exchange maxSendMessageSizeKB, maxReceiveMessageSizeKB, hideFromAddressBook, - isConsumer}, callback, asyncState); + isConsumer, + enabledLitigationHold, + recoverabelItemsSpace, + recoverabelItemsWarning}, callback, asyncState); } /// @@ -623,8 +639,11 @@ namespace WebsitePanel.Providers.Exchange int maxSendMessageSizeKB, int maxReceiveMessageSizeKB, bool hideFromAddressBook, - bool isConsumer) { - this.CreateMailEnableUserAsync(upn, organizationId, organizationDistinguishedName, accountType, mailboxDatabase, offlineAddressBook, addressBookPolicy, accountName, enablePOP, enableIMAP, enableOWA, enableMAPI, enableActiveSync, issueWarningKB, prohibitSendKB, prohibitSendReceiveKB, keepDeletedItemsDays, maxRecipients, maxSendMessageSizeKB, maxReceiveMessageSizeKB, hideFromAddressBook, isConsumer, null); + bool isConsumer, + bool enabledLitigationHold, + long recoverabelItemsSpace, + long recoverabelItemsWarning) { + this.CreateMailEnableUserAsync(upn, organizationId, organizationDistinguishedName, accountType, mailboxDatabase, offlineAddressBook, addressBookPolicy, accountName, enablePOP, enableIMAP, enableOWA, enableMAPI, enableActiveSync, issueWarningKB, prohibitSendKB, prohibitSendReceiveKB, keepDeletedItemsDays, maxRecipients, maxSendMessageSizeKB, maxReceiveMessageSizeKB, hideFromAddressBook, isConsumer, enabledLitigationHold, recoverabelItemsSpace, recoverabelItemsWarning, null); } /// @@ -651,6 +670,9 @@ namespace WebsitePanel.Providers.Exchange int maxReceiveMessageSizeKB, bool hideFromAddressBook, bool isConsumer, + bool enabledLitigationHold, + long recoverabelItemsSpace, + long recoverabelItemsWarning, object userState) { if ((this.CreateMailEnableUserOperationCompleted == null)) { this.CreateMailEnableUserOperationCompleted = new System.Threading.SendOrPostCallback(this.OnCreateMailEnableUserOperationCompleted); @@ -677,7 +699,10 @@ namespace WebsitePanel.Providers.Exchange maxSendMessageSizeKB, maxReceiveMessageSizeKB, hideFromAddressBook, - isConsumer}, this.CreateMailEnableUserOperationCompleted, userState); + isConsumer, + enabledLitigationHold, + recoverabelItemsSpace, + recoverabelItemsWarning}, this.CreateMailEnableUserOperationCompleted, userState); } private void OnCreateMailEnableUserOperationCompleted(object arg) { @@ -1032,17 +1057,7 @@ namespace WebsitePanel.Providers.Exchange this.Invoke("AddAuthoritativeDomain", new object[] { domain}); } - - /// - [System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")] - [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/ChangeAcceptedDomainType", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] - public void ChangeAcceptedDomainType(string domain, ExchangeAcceptedDomainType domainType) - { - this.Invoke("ChangeAcceptedDomainType", new object[] { - domain, - domainType}); - } - + /// public System.IAsyncResult BeginAddAuthoritativeDomain(string domain, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("AddAuthoritativeDomain", new object[] { @@ -1075,6 +1090,49 @@ namespace WebsitePanel.Providers.Exchange } } + /// + [System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")] + [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/ChangeAcceptedDomainType", RequestNamespace="http://smbsaas/websitepanel/server/", ResponseNamespace="http://smbsaas/websitepanel/server/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] + public void ChangeAcceptedDomainType(string domain, ExchangeAcceptedDomainType domainType) { + this.Invoke("ChangeAcceptedDomainType", new object[] { + domain, + domainType}); + } + + /// + public System.IAsyncResult BeginChangeAcceptedDomainType(string domain, ExchangeAcceptedDomainType domainType, System.AsyncCallback callback, object asyncState) { + return this.BeginInvoke("ChangeAcceptedDomainType", new object[] { + domain, + domainType}, callback, asyncState); + } + + /// + public void EndChangeAcceptedDomainType(System.IAsyncResult asyncResult) { + this.EndInvoke(asyncResult); + } + + /// + public void ChangeAcceptedDomainTypeAsync(string domain, ExchangeAcceptedDomainType domainType) { + this.ChangeAcceptedDomainTypeAsync(domain, domainType, null); + } + + /// + public void ChangeAcceptedDomainTypeAsync(string domain, ExchangeAcceptedDomainType domainType, object userState) { + if ((this.ChangeAcceptedDomainTypeOperationCompleted == null)) { + this.ChangeAcceptedDomainTypeOperationCompleted = new System.Threading.SendOrPostCallback(this.OnChangeAcceptedDomainTypeOperationCompleted); + } + this.InvokeAsync("ChangeAcceptedDomainType", new object[] { + domain, + domainType}, this.ChangeAcceptedDomainTypeOperationCompleted, userState); + } + + private void OnChangeAcceptedDomainTypeOperationCompleted(object arg) { + if ((this.ChangeAcceptedDomainTypeCompleted != null)) { + System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); + this.ChangeAcceptedDomainTypeCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); + } + } + /// [System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")] [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/GetAuthoritativeDomains", RequestNamespace="http://smbsaas/websitepanel/server/", ResponseNamespace="http://smbsaas/websitepanel/server/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] @@ -1470,7 +1528,24 @@ namespace WebsitePanel.Providers.Exchange /// [System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")] [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/SetMailboxAdvancedSettings", RequestNamespace="http://smbsaas/websitepanel/server/", ResponseNamespace="http://smbsaas/websitepanel/server/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] - public void SetMailboxAdvancedSettings(string organizationId, string accountName, bool enablePOP, bool enableIMAP, bool enableOWA, bool enableMAPI, bool enableActiveSync, long issueWarningKB, long prohibitSendKB, long prohibitSendReceiveKB, int keepDeletedItemsDays, int maxRecipients, int maxSendMessageSizeKB, int maxReceiveMessageSizeKB) { + public void SetMailboxAdvancedSettings( + string organizationId, + string accountName, + bool enablePOP, + bool enableIMAP, + bool enableOWA, + bool enableMAPI, + bool enableActiveSync, + long issueWarningKB, + long prohibitSendKB, + long prohibitSendReceiveKB, + int keepDeletedItemsDays, + int maxRecipients, + int maxSendMessageSizeKB, + int maxReceiveMessageSizeKB, + bool enabledLitigationHold, + long recoverabelItemsSpace, + long recoverabelItemsWarning) { this.Invoke("SetMailboxAdvancedSettings", new object[] { organizationId, accountName, @@ -1485,7 +1560,10 @@ namespace WebsitePanel.Providers.Exchange keepDeletedItemsDays, maxRecipients, maxSendMessageSizeKB, - maxReceiveMessageSizeKB}); + maxReceiveMessageSizeKB, + enabledLitigationHold, + recoverabelItemsSpace, + recoverabelItemsWarning}); } /// @@ -1504,6 +1582,9 @@ namespace WebsitePanel.Providers.Exchange int maxRecipients, int maxSendMessageSizeKB, int maxReceiveMessageSizeKB, + bool enabledLitigationHold, + long recoverabelItemsSpace, + long recoverabelItemsWarning, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("SetMailboxAdvancedSettings", new object[] { @@ -1520,7 +1601,10 @@ namespace WebsitePanel.Providers.Exchange keepDeletedItemsDays, maxRecipients, maxSendMessageSizeKB, - maxReceiveMessageSizeKB}, callback, asyncState); + maxReceiveMessageSizeKB, + enabledLitigationHold, + recoverabelItemsSpace, + recoverabelItemsWarning}, callback, asyncState); } /// @@ -1529,12 +1613,47 @@ namespace WebsitePanel.Providers.Exchange } /// - public void SetMailboxAdvancedSettingsAsync(string organizationId, string accountName, bool enablePOP, bool enableIMAP, bool enableOWA, bool enableMAPI, bool enableActiveSync, long issueWarningKB, long prohibitSendKB, long prohibitSendReceiveKB, int keepDeletedItemsDays, int maxRecipients, int maxSendMessageSizeKB, int maxReceiveMessageSizeKB) { - this.SetMailboxAdvancedSettingsAsync(organizationId, accountName, enablePOP, enableIMAP, enableOWA, enableMAPI, enableActiveSync, issueWarningKB, prohibitSendKB, prohibitSendReceiveKB, keepDeletedItemsDays, maxRecipients, maxSendMessageSizeKB, maxReceiveMessageSizeKB, null); + public void SetMailboxAdvancedSettingsAsync( + string organizationId, + string accountName, + bool enablePOP, + bool enableIMAP, + bool enableOWA, + bool enableMAPI, + bool enableActiveSync, + long issueWarningKB, + long prohibitSendKB, + long prohibitSendReceiveKB, + int keepDeletedItemsDays, + int maxRecipients, + int maxSendMessageSizeKB, + int maxReceiveMessageSizeKB, + bool enabledLitigationHold, + long recoverabelItemsSpace, + long recoverabelItemsWarning) { + this.SetMailboxAdvancedSettingsAsync(organizationId, accountName, enablePOP, enableIMAP, enableOWA, enableMAPI, enableActiveSync, issueWarningKB, prohibitSendKB, prohibitSendReceiveKB, keepDeletedItemsDays, maxRecipients, maxSendMessageSizeKB, maxReceiveMessageSizeKB, enabledLitigationHold, recoverabelItemsSpace, recoverabelItemsWarning, null); } /// - public void SetMailboxAdvancedSettingsAsync(string organizationId, string accountName, bool enablePOP, bool enableIMAP, bool enableOWA, bool enableMAPI, bool enableActiveSync, long issueWarningKB, long prohibitSendKB, long prohibitSendReceiveKB, int keepDeletedItemsDays, int maxRecipients, int maxSendMessageSizeKB, int maxReceiveMessageSizeKB, object userState) { + public void SetMailboxAdvancedSettingsAsync( + string organizationId, + string accountName, + bool enablePOP, + bool enableIMAP, + bool enableOWA, + bool enableMAPI, + bool enableActiveSync, + long issueWarningKB, + long prohibitSendKB, + long prohibitSendReceiveKB, + int keepDeletedItemsDays, + int maxRecipients, + int maxSendMessageSizeKB, + int maxReceiveMessageSizeKB, + bool enabledLitigationHold, + long recoverabelItemsSpace, + long recoverabelItemsWarning, + object userState) { if ((this.SetMailboxAdvancedSettingsOperationCompleted == null)) { this.SetMailboxAdvancedSettingsOperationCompleted = new System.Threading.SendOrPostCallback(this.OnSetMailboxAdvancedSettingsOperationCompleted); } @@ -1552,7 +1671,10 @@ namespace WebsitePanel.Providers.Exchange keepDeletedItemsDays, maxRecipients, maxSendMessageSizeKB, - maxReceiveMessageSizeKB}, this.SetMailboxAdvancedSettingsOperationCompleted, userState); + maxReceiveMessageSizeKB, + enabledLitigationHold, + recoverabelItemsSpace, + recoverabelItemsWarning}, this.SetMailboxAdvancedSettingsOperationCompleted, userState); } private void OnSetMailboxAdvancedSettingsOperationCompleted(object arg) { @@ -4102,6 +4224,10 @@ namespace WebsitePanel.Providers.Exchange [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void AddAuthoritativeDomainCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e); + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] + public delegate void ChangeAcceptedDomainTypeCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e); + /// [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void GetAuthoritativeDomainsCompletedEventHandler(object sender, GetAuthoritativeDomainsCompletedEventArgs e); diff --git a/WebsitePanel/Sources/WebsitePanel.Server.Client/OperatingSystemProxy.cs b/WebsitePanel/Sources/WebsitePanel.Server.Client/OperatingSystemProxy.cs index f40b6d59..b6675706 100644 --- a/WebsitePanel/Sources/WebsitePanel.Server.Client/OperatingSystemProxy.cs +++ b/WebsitePanel/Sources/WebsitePanel.Server.Client/OperatingSystemProxy.cs @@ -131,6 +131,12 @@ namespace WebsitePanel.Providers.OS { private System.Threading.SendOrPostCallback UpdateDSNOperationCompleted; private System.Threading.SendOrPostCallback DeleteDSNOperationCompleted; + + private System.Threading.SendOrPostCallback SetQuotaLimitOnFolderOperationCompleted; + + private System.Threading.SendOrPostCallback DeleteDirectoryRecursiveOperationCompleted; + + private System.Threading.SendOrPostCallback CheckFileServicesInstallationOperationCompleted; /// public OperatingSystem() { @@ -247,6 +253,16 @@ namespace WebsitePanel.Providers.OS { /// public event DeleteDSNCompletedEventHandler DeleteDSNCompleted; + + /// + public event SetQuotaLimitOnFolderCompletedEventHandler SetQuotaLimitOnFolderCompleted; + + /// + public event DeleteDirectoryRecursiveCompletedEventHandler DeleteDirectoryRecursiveCompleted; + + /// + public event CheckFileServicesInstallationCompletedEventHandler CheckFileServicesInstallationCompleted; + /// [System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")] @@ -1592,7 +1608,154 @@ namespace WebsitePanel.Providers.OS { this.ExecuteSyncActionsCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } - + + /// + [System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")] + [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/SetQuotaLimitOnFolder", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] + public bool SetQuotaLimitOnFolder(string folderPath, string shareNameDrive, string quotaLimit, int mode, string wmiUserName, string wmiPassword) + { + object[] results = this.Invoke("SetQuotaLimitOnFolder", new object[] { + folderPath, shareNameDrive, quotaLimit, mode, wmiUserName, wmiPassword}); + return ((bool)(results[0])); + } + + /// + public System.IAsyncResult BeginSetQuotaLimitOnFolder(string folderPath, string shareNameDrive, string quotaLimit, int mode, string wmiUserName, string wmiPassword, System.AsyncCallback callback, object asyncState) + { + return this.BeginInvoke("SetQuotaLimitOnFolder", new object[] { + folderPath, shareNameDrive, quotaLimit, mode, wmiUserName, wmiPassword}, callback, asyncState); + } + + /// + public bool EndSetQuotaLimitOnFolder(System.IAsyncResult asyncResult) + { + object[] results = this.EndInvoke(asyncResult); + return ((bool)(results[0])); + } + + /// + public void SetQuotaLimitOnFolderAsync(string folderPath, string shareNameDrive, string quotaLimit, int mode, string wmiUserName, string wmiPassword) + { + this.SetQuotaLimitOnFolderAsync(folderPath, shareNameDrive, quotaLimit, mode, wmiUserName, wmiPassword, null); + } + + /// + public void SetQuotaLimitOnFolderAsync(string folderPath, string shareNameDrive, string quotaLimit, int mode, string wmiUserName, string wmiPassword, object userState) + { + if ((this.SetQuotaLimitOnFolderOperationCompleted == null)) + { + this.SetQuotaLimitOnFolderOperationCompleted = new System.Threading.SendOrPostCallback(this.OnSetQuotaLimitOnFolderOperationCompleted); + } + this.InvokeAsync("SetQuotaLimitOnFolder", new object[] { + folderPath, shareNameDrive, quotaLimit, mode, wmiUserName, wmiPassword}, this.SetQuotaLimitOnFolderOperationCompleted, userState); + } + + private void OnSetQuotaLimitOnFolderOperationCompleted(object arg) + { + if ((this.SetQuotaLimitOnFolderCompleted != null)) + { + System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); + this.SetQuotaLimitOnFolderCompleted(this, new SetQuotaLimitOnFolderCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); + } + } + + /// + [System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")] + [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/DeleteDirectoryRecursive", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] + public bool DeleteDirectoryRecursive(string rootPath) + { + object[] results = this.Invoke("DeleteDirectoryRecursive", new object[] { + rootPath }); + return ((bool)(results[0])); + } + + /// + public System.IAsyncResult BeginDeleteDirectoryRecursive(string rootPath, System.AsyncCallback callback, object asyncState) + { + return this.BeginInvoke("DeleteDirectoryRecursive", new object[] { + rootPath}, callback, asyncState); + } + + /// + public bool EndDeleteDirectoryRecursive(System.IAsyncResult asyncResult) + { + object[] results = this.EndInvoke(asyncResult); + return ((bool)(results[0])); + } + + /// + public void DeleteDirectoryRecursiveAsync(string rootPath) + { + this.DeleteDirectoryRecursiveAsync(rootPath, null); + } + + /// + public void DeleteDirectoryRecursiveAsync(string rootPath, object userState) + { + if ((this.DeleteDirectoryRecursiveOperationCompleted == null)) + { + this.DeleteDirectoryRecursiveOperationCompleted = new System.Threading.SendOrPostCallback(this.OnDeleteDirectoryRecursiveOperationCompleted); + } + this.InvokeAsync("DeleteDirectoryRecursive", new object[] { + rootPath}, this.DeleteDirectoryRecursiveOperationCompleted, userState); + } + + private void OnDeleteDirectoryRecursiveOperationCompleted(object arg) + { + if ((this.DeleteDirectoryRecursiveCompleted != null)) + { + System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); + this.DeleteDirectoryRecursiveCompleted(this, new DeleteDirectoryRecursiveCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); + } + } + + /// + [System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")] + [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/CheckFileServicesInstallation", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] + public bool CheckFileServicesInstallation() + { + object[] results = this.Invoke("CheckFileServicesInstallation", new object[0]); + return ((bool)(results[0])); + } + + /// + public System.IAsyncResult BeginCheckFileServicesInstallation(System.AsyncCallback callback, object asyncState) + { + return this.BeginInvoke("CheckFileServicesInstallation", new object[0], callback, asyncState); + } + + /// + public bool EndCheckFileServicesInstallation(System.IAsyncResult asyncResult) + { + object[] results = this.EndInvoke(asyncResult); + return ((bool)(results[0])); + } + + /// + public void CheckFileServicesInstallationAsync() + { + this.CheckFileServicesInstallationAsync(null); + } + + /// + public void CheckFileServicesInstallationAsync(object userState) + { + if ((this.CheckFileServicesInstallationOperationCompleted == null)) + { + this.CheckFileServicesInstallationOperationCompleted = new System.Threading.SendOrPostCallback(this.OnCheckFileServicesInstallationOperationCompleted); + } + this.InvokeAsync("CheckFileServicesInstallation", new object[0], this.CheckFileServicesInstallationOperationCompleted, userState); + } + + private void OnCheckFileServicesInstallationOperationCompleted(object arg) + { + if ((this.CheckFileServicesInstallationCompleted != null)) + { + System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); + this.CheckFileServicesInstallationCompleted(this, new CheckFileServicesInstallationCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); + } + } + /// [System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")] [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/GetInstalledOdbcDrivers", RequestNamespace="http://smbsaas/websitepanel/server/", ResponseNamespace="http://smbsaas/websitepanel/server/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] @@ -2391,4 +2554,95 @@ namespace WebsitePanel.Providers.OS { /// [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void DeleteDSNCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e); + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] + public delegate void SetQuotaLimitOnFolderCompletedEventHandler(object sender, SetQuotaLimitOnFolderCompletedEventArgs e); + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.ComponentModel.DesignerCategoryAttribute("code")] + public partial class SetQuotaLimitOnFolderCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs + { + + private object[] results; + + internal SetQuotaLimitOnFolderCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) + { + this.results = results; + } + + /// + public bool Result + { + get + { + this.RaiseExceptionIfNecessary(); + return ((bool)(this.results[0])); + } + } + } + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] + public delegate void CheckFileServicesInstallationCompletedEventHandler(object sender, CheckFileServicesInstallationCompletedEventArgs e); + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.ComponentModel.DesignerCategoryAttribute("code")] + public partial class CheckFileServicesInstallationCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs + { + + private object[] results; + + internal CheckFileServicesInstallationCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) + { + this.results = results; + } + + /// + public bool Result + { + get + { + this.RaiseExceptionIfNecessary(); + return ((bool)(this.results[0])); + } + } + } + + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] + public delegate void DeleteDirectoryRecursiveCompletedEventHandler(object sender, DeleteDirectoryRecursiveCompletedEventArgs e); + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.ComponentModel.DesignerCategoryAttribute("code")] + public partial class DeleteDirectoryRecursiveCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs + { + + private object[] results; + + internal DeleteDirectoryRecursiveCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) + { + this.results = results; + } + + /// + public bool Result + { + get + { + this.RaiseExceptionIfNecessary(); + return ((bool)(this.results[0])); + } + } + } } diff --git a/WebsitePanel/Sources/WebsitePanel.Server.Utils/FileUtils.cs b/WebsitePanel/Sources/WebsitePanel.Server.Utils/FileUtils.cs index f30354a5..cdc199d3 100644 --- a/WebsitePanel/Sources/WebsitePanel.Server.Utils/FileUtils.cs +++ b/WebsitePanel/Sources/WebsitePanel.Server.Utils/FileUtils.cs @@ -37,6 +37,7 @@ using System.Collections.Generic; using System.Reflection; using Ionic.Zip; using WebsitePanel.Providers.OS; +using System.Management; namespace WebsitePanel.Providers.Utils { @@ -844,6 +845,126 @@ namespace WebsitePanel.Providers.Utils conn, null); cat = null; } + + public static void DeleteDirectoryRecursive(string rootPath) + { + // This code is done this way to force folder deletion + // even if the folder was opened + + DirectoryInfo treeRoot = new DirectoryInfo(rootPath); + if (treeRoot.Exists) + { + + DirectoryInfo[] dirs = treeRoot.GetDirectories(); + while (dirs.Length > 0) + { + foreach (DirectoryInfo dir in dirs) + DeleteDirectoryRecursive(dir.FullName); + + dirs = treeRoot.GetDirectories(); + } + + // DELETE THE FILES UNDER THE CURRENT ROOT + string[] files = Directory.GetFiles(treeRoot.FullName); + foreach (string file in files) + { + File.SetAttributes(file, FileAttributes.Normal); + File.Delete(file); + } + + Directory.Delete(treeRoot.FullName, true); + } + + + } + + public static void SetQuotaLimitOnFolder(string folderPath, string shareNameDrive, string quotaLimit, int mode, string wmiUserName, string wmiPassword) + { + + try + { + string[] splits = folderPath.Split('\\'); + if (splits.Length > 0) + { + // bat file pat + string cmdFilePath = @"\\" + splits[2] + @"\" + splits[3] + @"\" + "Process.bat"; + + // Creating the BAT file + FileStream fs = File.Create(cmdFilePath); + if (fs != null) + { + fs.Close(); + fs.Dispose(); + } + + StreamWriter swr = new StreamWriter(cmdFilePath); + + if (swr != null) + { + swr.WriteLine(@"cd c:\windows\system32"); + + string sharePath = String.Empty; + + if (splits.Length > 4) + { + // Form the share physicalPath + sharePath = shareNameDrive + @":\" + splits[3]; + + if (splits.Length == 5 && !quotaLimit.Equals(String.Empty)) + { + + switch (mode) + { + // Set + case 0: + // Delete the quota in case one exists + swr.WriteLine(@"dirquota quota delete /path:" + sharePath + @"\" + splits[4] + @" /remote:" + splits[2] + @" /quiet"); + swr.WriteLine(@"dirquota quota add /path:" + sharePath + @"\" + splits[4] + @" /limit:" + quotaLimit + @" /remote:" + splits[2]); + break; + + // Modify + case 1: swr.WriteLine(@"dirquota quota modify /path:" + sharePath + @"\" + splits[4] + @" /limit:" + quotaLimit + @" /remote:" + splits[2]); + break; + } + } + + + } + swr.Flush(); + swr.Close(); + swr.Dispose(); + } + + ConnectionOptions connOptions = new ConnectionOptions(); + + if (wmiUserName.Length > 0) + { + connOptions.Username = wmiUserName; + connOptions.Password = wmiPassword; + } + + connOptions.Impersonation = ImpersonationLevel.Impersonate; + + connOptions.EnablePrivileges = true; + + ManagementScope manScope = + new ManagementScope(String.Format(@"\\{0}\ROOT\CIMV2", splits[2]), connOptions); + manScope.Connect(); + + ObjectGetOptions objectGetOptions = new ObjectGetOptions(); + ManagementPath managementPath = new ManagementPath("Win32_Process"); + ManagementClass processClass = new ManagementClass(manScope, managementPath, objectGetOptions); + + ManagementBaseObject inParams = processClass.GetMethodParameters("Create"); + inParams["CommandLine"] = cmdFilePath; + ManagementBaseObject outParams = processClass.InvokeMethod("Create", inParams, null); + + } + } + catch + { } + } + #region Advanced Delete /// /// Deletes the specified file. diff --git a/WebsitePanel/Sources/WebsitePanel.Server.Utils/OS.cs b/WebsitePanel/Sources/WebsitePanel.Server.Utils/OS.cs index accc9d27..03f07a5b 100644 --- a/WebsitePanel/Sources/WebsitePanel.Server.Utils/OS.cs +++ b/WebsitePanel/Sources/WebsitePanel.Server.Utils/OS.cs @@ -30,6 +30,8 @@ using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; +using System.Management; + namespace WebsitePanel.Server.Utils { @@ -402,6 +404,22 @@ namespace WebsitePanel.Server.Utils { return Environment.GetEnvironmentVariable("windir"); } + /// + /// Checks Whether the FSRM role services are installed + /// + /// + public static bool CheckFileServicesInstallation() + { + + ManagementClass objMC = new ManagementClass("Win32_ServerFeature"); + ManagementObjectCollection objMOC = objMC.GetInstances(); + foreach (ManagementObject objMO in objMOC) + if (objMO.Properties["Name"].Value.ToString().ToLower().Contains("file server resource manager")) + return true; + + return false; + + } } } diff --git a/WebsitePanel/Sources/WebsitePanel.Server.sln b/WebsitePanel/Sources/WebsitePanel.Server.sln index 138b2957..5ae70b5f 100644 --- a/WebsitePanel/Sources/WebsitePanel.Server.sln +++ b/WebsitePanel/Sources/WebsitePanel.Server.sln @@ -90,6 +90,9 @@ EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebsitePanel.Providers.Mail.SmarterMail6", "WebsitePanel.Providers.Mail.SmarterMail6\WebsitePanel.Providers.Mail.SmarterMail6.csproj", "{88E9734F-2066-4674-AA5B-F1A772436F04}" EndProject Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "WebsitePanel.Providers.Mail.Merak10", "WebsitePanel.Providers.Mail.Merak10\WebsitePanel.Providers.Mail.Merak10.vbproj", "{7105A714-FF61-46B2-A16E-F4CBAD71BF02}" + ProjectSection(ProjectDependencies) = postProject + {E91E52F3-9555-4D00-B577-2B1DBDD87CA7} = {E91E52F3-9555-4D00-B577-2B1DBDD87CA7} + EndProjectSection EndProject Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "WebsitePanel.Providers.Mail.hMailServer5", "WebsitePanel.Providers.Mail.hMail5\WebsitePanel.Providers.Mail.hMailServer5.vbproj", "{8F644D50-D602-4AD3-8EB0-CA3C3676B18D}" EndProject @@ -111,6 +114,13 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebsitePanel.Providers.Web. EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebsitePanel.Providers.FTP.IIs80", "WebsitePanel.Providers.FTP.IIs80\WebsitePanel.Providers.FTP.IIs80.csproj", "{D73CCF4C-9CFF-4D61-9030-34DCAF0C50D6}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebsitePanel.Providers.HostedSolution.Exchange2013", "WebsitePanel.Providers.HostedSolution.Exchange2013\WebsitePanel.Providers.HostedSolution.Exchange2013.csproj", "{BC094166-B6A1-4D42-B53C-FF956FC7A4A1}" + ProjectSection(ProjectDependencies) = postProject + {684C932A-6C75-46AC-A327-F3689D89EB42} = {684C932A-6C75-46AC-A327-F3689D89EB42} + {A06DE5E4-4331-47E1-8F46-7B846146B559} = {A06DE5E4-4331-47E1-8F46-7B846146B559} + {E91E52F3-9555-4D00-B577-2B1DBDD87CA7} = {E91E52F3-9555-4D00-B577-2B1DBDD87CA7} + EndProjectSection +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -611,6 +621,16 @@ Global {D73CCF4C-9CFF-4D61-9030-34DCAF0C50D6}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {D73CCF4C-9CFF-4D61-9030-34DCAF0C50D6}.Release|Mixed Platforms.Build.0 = Release|Any CPU {D73CCF4C-9CFF-4D61-9030-34DCAF0C50D6}.Release|x86.ActiveCfg = Release|Any CPU + {BC094166-B6A1-4D42-B53C-FF956FC7A4A1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {BC094166-B6A1-4D42-B53C-FF956FC7A4A1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {BC094166-B6A1-4D42-B53C-FF956FC7A4A1}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {BC094166-B6A1-4D42-B53C-FF956FC7A4A1}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {BC094166-B6A1-4D42-B53C-FF956FC7A4A1}.Debug|x86.ActiveCfg = Debug|Any CPU + {BC094166-B6A1-4D42-B53C-FF956FC7A4A1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {BC094166-B6A1-4D42-B53C-FF956FC7A4A1}.Release|Any CPU.Build.0 = Release|Any CPU + {BC094166-B6A1-4D42-B53C-FF956FC7A4A1}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {BC094166-B6A1-4D42-B53C-FF956FC7A4A1}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {BC094166-B6A1-4D42-B53C-FF956FC7A4A1}.Release|x86.ActiveCfg = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/WebsitePanel/Sources/WebsitePanel.Server/ExchangeServer.asmx.cs b/WebsitePanel/Sources/WebsitePanel.Server/ExchangeServer.asmx.cs index 8553b61f..855f87a0 100644 --- a/WebsitePanel/Sources/WebsitePanel.Server/ExchangeServer.asmx.cs +++ b/WebsitePanel/Sources/WebsitePanel.Server/ExchangeServer.asmx.cs @@ -93,7 +93,7 @@ namespace WebsitePanel.Server string accountName, bool enablePOP, bool enableIMAP, bool enableOWA, bool enableMAPI, bool enableActiveSync, long issueWarningKB, long prohibitSendKB, long prohibitSendReceiveKB, int keepDeletedItemsDays, - int maxRecipients, int maxSendMessageSizeKB, int maxReceiveMessageSizeKB, bool hideFromAddressBook, bool isConsumer) + int maxRecipients, int maxSendMessageSizeKB, int maxReceiveMessageSizeKB, bool hideFromAddressBook, bool isConsumer, bool enabledLitigationHold, long recoverabelItemsSpace, long recoverabelItemsWarning) { try { @@ -104,7 +104,7 @@ namespace WebsitePanel.Server enableOWA, enableMAPI, enableActiveSync, issueWarningKB, prohibitSendKB, prohibitSendReceiveKB, keepDeletedItemsDays, - maxRecipients, maxSendMessageSizeKB, maxReceiveMessageSizeKB, hideFromAddressBook, isConsumer); + maxRecipients, maxSendMessageSizeKB, maxReceiveMessageSizeKB, hideFromAddressBook, isConsumer, enabledLitigationHold, recoverabelItemsSpace, recoverabelItemsWarning); LogEnd("CreateMailEnableUser"); return ret; } @@ -316,33 +316,6 @@ namespace WebsitePanel.Server #endregion #region Mailboxes - /* - [WebMethod, SoapHeader("settings")] - public string CreateMailbox(string organizationId, string organizationDistinguishedName, string mailboxDatabase, - string securityGroup, string offlineAddressBook, string addressBookPolicy, ExchangeAccountType accountType, - string displayName, string accountName, string name, - string domain, string password, bool enablePOP, bool enableIMAP, bool enableOWA, bool enableMAPI, bool enableActiveSync, - int issueWarningKB, int prohibitSendKB, int prohibitSendReceiveKB, int keepDeletedItemsDays, int maxRecipients, int maxSendMessageSizeKB, int maxReceiveMessageSizeKB, bool hideFromAddressBook) - { - try - { - LogStart("CreateMailbox"); - string ret = ES.CreateMailbox(organizationId, organizationDistinguishedName, mailboxDatabase, securityGroup, - offlineAddressBook, addressBookPolicy, accountType, - displayName, accountName, name, domain, password, enablePOP, enableIMAP, - enableOWA, enableMAPI, enableActiveSync, - issueWarningKB, prohibitSendKB, prohibitSendReceiveKB, keepDeletedItemsDays, - maxRecipients, maxSendMessageSizeKB, maxReceiveMessageSizeKB, hideFromAddressBook); - LogEnd("CreateMailbox"); - return ret; - } - catch (Exception ex) - { - LogError("CreateMailbox", ex); - throw; - } - } -*/ [WebMethod, SoapHeader("settings")] public void DeleteMailbox(string accountName) { @@ -461,13 +434,15 @@ namespace WebsitePanel.Server [WebMethod, SoapHeader("settings")] public void SetMailboxAdvancedSettings(string organizationId, string accountName, bool enablePOP, bool enableIMAP, bool enableOWA, bool enableMAPI, bool enableActiveSync, - long issueWarningKB, long prohibitSendKB, long prohibitSendReceiveKB, int keepDeletedItemsDays, int maxRecipients, int maxSendMessageSizeKB, int maxReceiveMessageSizeKB) + long issueWarningKB, long prohibitSendKB, long prohibitSendReceiveKB, int keepDeletedItemsDays, int maxRecipients, int maxSendMessageSizeKB, int maxReceiveMessageSizeKB + , bool enabledLitigationHold, long recoverabelItemsSpace, long recoverabelItemsWarning) { try { LogStart("SetMailboxAdvancedSettings"); ES.SetMailboxAdvancedSettings(organizationId, accountName, enablePOP, enableIMAP, enableOWA, enableMAPI, enableActiveSync, - issueWarningKB, prohibitSendKB, prohibitSendReceiveKB, keepDeletedItemsDays, maxRecipients, maxSendMessageSizeKB, maxReceiveMessageSizeKB); + issueWarningKB, prohibitSendKB, prohibitSendReceiveKB, keepDeletedItemsDays, maxRecipients, maxSendMessageSizeKB, maxReceiveMessageSizeKB, + enabledLitigationHold, recoverabelItemsSpace, recoverabelItemsWarning); LogEnd("SetMailboxAdvancedSettings"); } catch (Exception ex) diff --git a/WebsitePanel/Sources/WebsitePanel.Server/OperatingSystem.asmx.cs b/WebsitePanel/Sources/WebsitePanel.Server/OperatingSystem.asmx.cs index e258900a..235fb03d 100644 --- a/WebsitePanel/Sources/WebsitePanel.Server/OperatingSystem.asmx.cs +++ b/WebsitePanel/Sources/WebsitePanel.Server/OperatingSystem.asmx.cs @@ -533,6 +533,55 @@ namespace WebsitePanel.Server throw; } } + + + [WebMethod, SoapHeader("settings")] + public void SetQuotaLimitOnFolder(string folderPath, string shareNameDrive, string quotaLimit, int mode, string wmiUserName, string wmiPassword) + { + try + { + Log.WriteStart("'{0}' SetQuotaLimitOnFolder", ProviderSettings.ProviderName); + OsProvider.SetQuotaLimitOnFolder(folderPath, shareNameDrive, quotaLimit, mode, wmiUserName, wmiPassword); + Log.WriteEnd("'{0}' SetQuotaLimitOnFolder", ProviderSettings.ProviderName); + } + catch (Exception ex) + { + Log.WriteError(String.Format("'{0}' SetQuotaLimitOnFolder", ProviderSettings.ProviderName), ex); + throw; + } + } + + [WebMethod, SoapHeader("settings")] + public void DeleteDirectoryRecursive(string rootPath) + { + try + { + Log.WriteStart("'{0}' DeleteDirectoryRecursive", ProviderSettings.ProviderName); + OsProvider.DeleteDirectoryRecursive(rootPath); + Log.WriteEnd("'{0}' DeleteDirectoryRecursive", ProviderSettings.ProviderName); + } + catch (Exception ex) + { + Log.WriteError(String.Format("'{0}' DeleteDirectoryRecursive", ProviderSettings.ProviderName), ex); + throw; + } + } + + [WebMethod, SoapHeader("settings")] + public bool CheckFileServicesInstallation() + { + try + { + Log.WriteStart("'{0}' CheckFileServicesInstallation", ProviderSettings.ProviderName); + return OsProvider.CheckFileServicesInstallation(); + Log.WriteEnd("'{0}' CheckFileServicesInstallation", ProviderSettings.ProviderName); + } + catch (Exception ex) + { + Log.WriteError(String.Format("'{0}' CheckFileServicesInstallation", ProviderSettings.ProviderName), ex); + throw; + } + } #endregion #region Synchronizing diff --git a/WebsitePanel/Sources/WebsitePanel.WebPortal/App_Data/ModulesData.config b/WebsitePanel/Sources/WebsitePanel.WebPortal/App_Data/ModulesData.config index efd04273..b2602ecb 100644 --- a/WebsitePanel/Sources/WebsitePanel.WebPortal/App_Data/ModulesData.config +++ b/WebsitePanel/Sources/WebsitePanel.WebPortal/App_Data/ModulesData.config @@ -76,6 +76,9 @@ + + + diff --git a/WebsitePanel/Sources/WebsitePanel.WebPortal/App_Data/WebsitePanel_Modules.config b/WebsitePanel/Sources/WebsitePanel.WebPortal/App_Data/WebsitePanel_Modules.config index 73475696..496315ef 100644 --- a/WebsitePanel/Sources/WebsitePanel.WebPortal/App_Data/WebsitePanel_Modules.config +++ b/WebsitePanel/Sources/WebsitePanel.WebPortal/App_Data/WebsitePanel_Modules.config @@ -594,4 +594,12 @@ + + + + + + + + \ No newline at end of file diff --git a/WebsitePanel/Sources/WebsitePanel.WebPortal/App_Data/WebsitePanel_Pages.config b/WebsitePanel/Sources/WebsitePanel.WebPortal/App_Data/WebsitePanel_Pages.config index 9143f106..e6277aa7 100644 --- a/WebsitePanel/Sources/WebsitePanel.WebPortal/App_Data/WebsitePanel_Pages.config +++ b/WebsitePanel/Sources/WebsitePanel.WebPortal/App_Data/WebsitePanel_Pages.config @@ -566,4 +566,17 @@ + + + + diff --git a/WebsitePanel/Sources/WebsitePanel.WebPortal/App_GlobalResources/WebsitePanel_Modules.ascx.resx b/WebsitePanel/Sources/WebsitePanel.WebPortal/App_GlobalResources/WebsitePanel_Modules.ascx.resx index 3ecef0a5..fef0f5c7 100644 --- a/WebsitePanel/Sources/WebsitePanel.WebPortal/App_GlobalResources/WebsitePanel_Modules.ascx.resx +++ b/WebsitePanel/Sources/WebsitePanel.WebPortal/App_GlobalResources/WebsitePanel_Modules.ascx.resx @@ -762,10 +762,13 @@ System Center Server Addresses - + Add VLan to user Setup WebsitePanel Accounts + + System Hard Quota + \ No newline at end of file diff --git a/WebsitePanel/Sources/WebsitePanel.WebPortal/App_GlobalResources/WebsitePanel_Pages.ascx.resx b/WebsitePanel/Sources/WebsitePanel.WebPortal/App_GlobalResources/WebsitePanel_Pages.ascx.resx index d4b134f6..6b30cf6d 100644 --- a/WebsitePanel/Sources/WebsitePanel.WebPortal/App_GlobalResources/WebsitePanel_Pages.ascx.resx +++ b/WebsitePanel/Sources/WebsitePanel.WebPortal/App_GlobalResources/WebsitePanel_Pages.ascx.resx @@ -459,4 +459,7 @@ {user} - {space} - Virtual Private Servers for Private Cloud + + System Hard Quota + \ No newline at end of file diff --git a/WebsitePanel/Sources/WebsitePanel.WebPortal/App_GlobalResources/WebsitePanel_SharedResources.ascx.resx b/WebsitePanel/Sources/WebsitePanel.WebPortal/App_GlobalResources/WebsitePanel_SharedResources.ascx.resx index c676ac95..f2ee2cef 100644 --- a/WebsitePanel/Sources/WebsitePanel.WebPortal/App_GlobalResources/WebsitePanel_SharedResources.ascx.resx +++ b/WebsitePanel/Sources/WebsitePanel.WebPortal/App_GlobalResources/WebsitePanel_SharedResources.ascx.resx @@ -2124,7 +2124,6 @@ Web Site Host Header - Applications Installer @@ -5269,4 +5268,10 @@ Web site has been updated to shared IP + + Apply Enable Hard Quota Feature + + + By clicking on the button 'Apply', you will apply the respective hard quota on each provisioned home folder. Note that this may take some time. + \ No newline at end of file diff --git a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/App_LocalResources/SettingsExchangeMailboxPlansPolicy.ascx.resx b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/App_LocalResources/SettingsExchangeMailboxPlansPolicy.ascx.resx index 020ef5fe..2dc7d064 100644 --- a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/App_LocalResources/SettingsExchangeMailboxPlansPolicy.ascx.resx +++ b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/App_LocalResources/SettingsExchangeMailboxPlansPolicy.ascx.resx @@ -228,4 +228,16 @@ Update Mailbox Plan + + Enable Litigation Hold + + + Recoverable Items Space (Mb): + + + Warning at: + + + Litigation Hold + \ No newline at end of file diff --git a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/App_LocalResources/WebSitesEditSite.ascx.resx b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/App_LocalResources/WebSitesEditSite.ascx.resx index f82d2d99..78df331e 100644 --- a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/App_LocalResources/WebSitesEditSite.ascx.resx +++ b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/App_LocalResources/WebSitesEditSite.ascx.resx @@ -486,4 +486,7 @@ To connect to web site management service please use username and password provi IP address: Shared + + Force delete website directory? + \ No newline at end of file diff --git a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ApplyEnableHardQuotaFeature.ascx b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ApplyEnableHardQuotaFeature.ascx new file mode 100644 index 00000000..38488387 --- /dev/null +++ b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ApplyEnableHardQuotaFeature.ascx @@ -0,0 +1,19 @@ +<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ApplyEnableHardQuotaFeature.ascx.cs" Inherits="WebsitePanel.Portal.ApplyEnableHardQuotaFeature" %> +<%@ Register Src="UserControls/SimpleMessageBox.ascx" TagName="messageBox" TagPrefix="uc4" %> + +
+ + + + + +
+ + +
+ +
+
+ + +
diff --git a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ApplyEnableHardQuotaFeature.ascx.cs b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ApplyEnableHardQuotaFeature.ascx.cs new file mode 100644 index 00000000..c96f2e87 --- /dev/null +++ b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ApplyEnableHardQuotaFeature.ascx.cs @@ -0,0 +1,74 @@ +// Copyright (c) 2012, Outercurve Foundation. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// - Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// +// - Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// - Neither the name of the Outercurve Foundation nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +using System; +using System.Collections.Generic; +using System.Web; +using System.Web.UI; +using System.Web.UI.WebControls; +using WebsitePanel.EnterpriseServer; +using WebsitePanel.EnterpriseServer.Base.Scheduling; +using WebsitePanel.Portal.Code.Framework; + +namespace WebsitePanel.Portal +{ + public partial class ApplyEnableHardQuotaFeature : WebsitePanelModuleBase + { + + public int PackageId + { + get { return PanelSecurity.PackageId; } + } + + protected void Page_Load(object sender, EventArgs e) + { + messageBox.ShowWarningMessage("ApplyEnableHardQuotaFeature"); + } + + private void Update() + { + try + { + ES.Services.Files.ApplyEnableHardQuotaFeature(PackageId); + // redirect + Response.Redirect(NavigatePageURL("SpaceHome", "SpaceID", PackageId.ToString())); + } + catch (Exception ex) + { + messageBox.ShowErrorMessage("APPLY_QUOTA", ex); + } + } + + + protected void btnUpdate_Click(object sender, EventArgs e) + { + Update(); + } + + } +} \ No newline at end of file diff --git a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ApplyEnableHardQuotaFeature.ascx.designer.cs b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ApplyEnableHardQuotaFeature.ascx.designer.cs new file mode 100644 index 00000000..0573c5af --- /dev/null +++ b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ApplyEnableHardQuotaFeature.ascx.designer.cs @@ -0,0 +1,61 @@ +// Copyright (c) 2012, Outercurve Foundation. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// - Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// +// - Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// - Neither the name of the Outercurve Foundation nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace WebsitePanel.Portal { + + + public partial class ApplyEnableHardQuotaFeature { + + /// + /// messageBox control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::WebsitePanel.Portal.UserControls.SimpleMessageBox messageBox; + + /// + /// btnUpdate control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.Button btnUpdate; + } +} diff --git a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ExchangeServer/App_LocalResources/ExchangeAddMailboxPlan.ascx.resx b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ExchangeServer/App_LocalResources/ExchangeAddMailboxPlan.ascx.resx index 5de71b1e..1fbc750c 100644 --- a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ExchangeServer/App_LocalResources/ExchangeAddMailboxPlan.ascx.resx +++ b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ExchangeServer/App_LocalResources/ExchangeAddMailboxPlan.ascx.resx @@ -198,4 +198,16 @@ * + + Enable Litigation Hold + + + Recoverable Items Space (Mb): + + + Warning at: + + + Litigation Hold + \ No newline at end of file diff --git a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ExchangeServer/App_LocalResources/ExchangeMailboxGeneralSettings.ascx.resx b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ExchangeServer/App_LocalResources/ExchangeMailboxGeneralSettings.ascx.resx index cb0a8c7b..eac7ac03 100644 --- a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ExchangeServer/App_LocalResources/ExchangeMailboxGeneralSettings.ascx.resx +++ b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ExchangeServer/App_LocalResources/ExchangeMailboxGeneralSettings.ascx.resx @@ -159,4 +159,13 @@ * + + Enable Litigation Hold + + + Litigation Hold Space: + + + Litigation Hold Settings + \ No newline at end of file diff --git a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ExchangeServer/ExchangeAddMailboxPlan.ascx b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ExchangeServer/ExchangeAddMailboxPlan.ascx index 2cfe8c89..78d3d3b6 100644 --- a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ExchangeServer/ExchangeAddMailboxPlan.ascx +++ b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ExchangeServer/ExchangeAddMailboxPlan.ascx @@ -91,7 +91,6 @@ -
-
-
-
-
-
-
-
-
- + + + @@ -170,7 +163,6 @@ -
@@ -186,9 +178,39 @@ -
+ + + + + + + + + + + + + + + + +
+ +
+ + +
+ +
+
+ +
diff --git a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ExchangeServer/ExchangeAddMailboxPlan.ascx.cs b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ExchangeServer/ExchangeAddMailboxPlan.ascx.cs index a421859b..816c764c 100644 --- a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ExchangeServer/ExchangeAddMailboxPlan.ascx.cs +++ b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ExchangeServer/ExchangeAddMailboxPlan.ascx.cs @@ -60,6 +60,11 @@ namespace WebsitePanel.Portal.ExchangeServer sizeProhibitSendReceive.ValueKB = plan.ProhibitSendReceivePct; daysKeepDeletedItems.ValueDays = plan.KeepDeletedItemsDays; chkHideFromAddressBook.Checked = plan.HideFromAddressBook; + chkEnableLitigationHold.Checked = plan.AllowLitigationHold; + recoverableItemsSpace.QuotaValue = plan.RecoverableItemsSpace; + recoverableItemsWarning.ValueKB = plan.RecoverableItemsWarningPct; + + /* txtMailboxPlan.Enabled = false; @@ -138,11 +143,17 @@ namespace WebsitePanel.Portal.ExchangeServer daysKeepDeletedItems.ValueDays = quota.QuotaAllocatedValue; daysKeepDeletedItems.RequireValidatorEnabled = true; break; + case 420: + chkEnableLitigationHold.Checked = Convert.ToBoolean(quota.QuotaAllocatedValue); + chkEnableLitigationHold.Enabled = Convert.ToBoolean(quota.QuotaAllocatedValue); + break; + } - sizeIssueWarning.ValueKB = 100; + sizeIssueWarning.ValueKB = 95; sizeProhibitSend.ValueKB = 100; sizeProhibitSendReceive.ValueKB = 100; + recoverableItemsWarning.ValueKB = 95; } } else @@ -183,6 +194,10 @@ namespace WebsitePanel.Portal.ExchangeServer if ((plan.ProhibitSendReceivePct == 0)) plan.ProhibitSendReceivePct = 100; plan.KeepDeletedItemsDays = daysKeepDeletedItems.ValueDays; plan.HideFromAddressBook = chkHideFromAddressBook.Checked; + plan.AllowLitigationHold = chkEnableLitigationHold.Checked; + plan.RecoverableItemsSpace = recoverableItemsSpace.QuotaValue; + plan.RecoverableItemsWarningPct = recoverableItemsWarning.ValueKB; + if ((plan.RecoverableItemsWarningPct == 0)) plan.RecoverableItemsWarningPct = 100; int result = ES.Services.ExchangeServer.AddExchangeMailboxPlan(PanelRequest.ItemID, plan); diff --git a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ExchangeServer/ExchangeAddMailboxPlan.ascx.designer.cs b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ExchangeServer/ExchangeAddMailboxPlan.ascx.designer.cs index a9b442a6..2a9825d3 100644 --- a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ExchangeServer/ExchangeAddMailboxPlan.ascx.designer.cs +++ b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ExchangeServer/ExchangeAddMailboxPlan.ascx.designer.cs @@ -1,4 +1,31 @@ -//------------------------------------------------------------------------------ +// Copyright (c) 2012, Outercurve Foundation. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// - Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// +// - Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// - Neither the name of the Outercurve Foundation nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +//------------------------------------------------------------------------------ // // This code was generated by a tool. // @@ -381,6 +408,69 @@ namespace WebsitePanel.Portal.ExchangeServer { /// protected global::WebsitePanel.Portal.ExchangeServer.UserControls.DaysBox daysKeepDeletedItems; + /// + /// secLitigationHold control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::WebsitePanel.Portal.CollapsiblePanel secLitigationHold; + + /// + /// LitigationHold control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.Panel LitigationHold; + + /// + /// chkEnableLitigationHold control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.CheckBox chkEnableLitigationHold; + + /// + /// locRecoverableItemsSpace control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.Localize locRecoverableItemsSpace; + + /// + /// recoverableItemsSpace control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::WebsitePanel.Portal.QuotaEditor recoverableItemsSpace; + + /// + /// locRecoverableItemsWarning control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.Localize locRecoverableItemsWarning; + + /// + /// recoverableItemsWarning control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::WebsitePanel.Portal.ExchangeServer.UserControls.SizeBox recoverableItemsWarning; + /// /// btnAdd control. /// diff --git a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ExchangeServer/ExchangeMailboxGeneralSettings.ascx b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ExchangeServer/ExchangeMailboxGeneralSettings.ascx index 848f1310..184d86bc 100644 --- a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ExchangeServer/ExchangeMailboxGeneralSettings.ascx +++ b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ExchangeServer/ExchangeMailboxGeneralSettings.ascx @@ -32,9 +32,7 @@ - - + @@ -71,14 +69,35 @@ - - + + + + + + + + + + + + + +
+ +
+
+
+ MB +
+
+
+
+ + -
diff --git a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ExchangeServer/ExchangeMailboxGeneralSettings.ascx.cs b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ExchangeServer/ExchangeMailboxGeneralSettings.ascx.cs index f2ea7f15..8a8430a4 100644 --- a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ExchangeServer/ExchangeMailboxGeneralSettings.ascx.cs +++ b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ExchangeServer/ExchangeMailboxGeneralSettings.ascx.cs @@ -50,8 +50,9 @@ namespace WebsitePanel.Portal.ExchangeServer chkHideAddressBook.Visible = false; chkDisable.Visible = false; } - } + secLitigationHoldSettings.Visible = (Utils.CheckQouta(Quotas.EXCHANGE2007_ALLOWLITIGATIONHOLD, cntx)); + } } } @@ -99,10 +100,13 @@ namespace WebsitePanel.Portal.ExchangeServer mailboxSize.QuotaUsedValue = Convert.ToInt32(stats.TotalSize / 1024 / 1024); mailboxSize.QuotaValue = (stats.MaxSize == -1) ? -1: (int)Math.Round((double)(stats.MaxSize / 1024 / 1024)); - if ((account.AccountType == ExchangeAccountType.Equipment) | (account.AccountType == ExchangeAccountType.Room)) - secCalendarSettings.Visible = true; - else - secCalendarSettings.Visible = false; + secCalendarSettings.Visible = ((account.AccountType == ExchangeAccountType.Equipment) | (account.AccountType == ExchangeAccountType.Room)); + + chkEnableLitigationHold.Checked = mailbox.EnableLitigationHold; + + litigationHoldSpace.QuotaUsedValue = Convert.ToInt32(stats.LitigationHoldTotalSize / 1024 / 1024); + litigationHoldSpace.QuotaValue = (stats.LitigationHoldMaxSize == -1) ? -1 : (int)Math.Round((double)(stats.LitigationHoldMaxSize / 1024 / 1024)); + } diff --git a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ExchangeServer/ExchangeMailboxGeneralSettings.ascx.designer.cs b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ExchangeServer/ExchangeMailboxGeneralSettings.ascx.designer.cs index d1dc4f60..9592c1b9 100644 --- a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ExchangeServer/ExchangeMailboxGeneralSettings.ascx.designer.cs +++ b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ExchangeServer/ExchangeMailboxGeneralSettings.ascx.designer.cs @@ -1,3 +1,30 @@ +// Copyright (c) 2012, Outercurve Foundation. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// - Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// +// - Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// - Neither the name of the Outercurve Foundation nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //------------------------------------------------------------------------------ // // This code was generated by a tool. @@ -165,6 +192,60 @@ namespace WebsitePanel.Portal.ExchangeServer { /// protected global::WebsitePanel.Portal.QuotaViewer mailboxSize; + /// + /// secLitigationHoldSettings control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::WebsitePanel.Portal.CollapsiblePanel secLitigationHoldSettings; + + /// + /// LitigationHoldSettings control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.Panel LitigationHoldSettings; + + /// + /// LitigationHoldUpdatePanel control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.UpdatePanel LitigationHoldUpdatePanel; + + /// + /// chkEnableLitigationHold control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.CheckBox chkEnableLitigationHold; + + /// + /// locLitigationHoldSpace control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.Localize locLitigationHoldSpace; + + /// + /// litigationHoldSpace control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::WebsitePanel.Portal.QuotaViewer litigationHoldSpace; + /// /// secCalendarSettings control. /// @@ -218,14 +299,5 @@ namespace WebsitePanel.Portal.ExchangeServer { /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.ValidationSummary ValidationSummary1; - - /// - /// FormComments control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.Localize FormComments; } } diff --git a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ProviderControls/App_LocalResources/Windows2008_Settings.ascx.resx b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ProviderControls/App_LocalResources/Windows2008_Settings.ascx.resx index 8f21e2f8..d2f4439d 100644 --- a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ProviderControls/App_LocalResources/Windows2008_Settings.ascx.resx +++ b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ProviderControls/App_LocalResources/Windows2008_Settings.ascx.resx @@ -112,11 +112,17 @@ 2.0 - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + Enable Hard Quota: + + + Location Drive: + Hosting Spaces Folder: diff --git a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ProviderControls/Exchange_Settings.ascx.cs b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ProviderControls/Exchange_Settings.ascx.cs index 7da1698d..944b4d94 100644 --- a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ProviderControls/Exchange_Settings.ascx.cs +++ b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ProviderControls/Exchange_Settings.ascx.cs @@ -43,6 +43,7 @@ namespace WebsitePanel.Portal.ProviderControls public const int EXCHANGE2010_PROVIDER_ID = 32; public const int EXCHANGE2010SP2_PROVIDER_ID = 90; + public const int EXCHANGE2013_PROVIDER_ID = 91; public string HubTransports @@ -102,6 +103,16 @@ namespace WebsitePanel.Portal.ProviderControls locMailboxDatabase.Visible = false; break; + case EXCHANGE2013_PROVIDER_ID: + clusteredMailboxServer.Visible = false; + txtMailboxClusterName.Text = ""; + + storageGroup.Visible = false; + txtStorageGroup.Text = ""; + + locMailboxDatabase.Visible = false; + break; + default: storageGroup.Visible = true; txtStorageGroup.Text = settings["StorageGroup"]; diff --git a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ProviderControls/Windows2008_Settings.ascx b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ProviderControls/Windows2008_Settings.ascx index 972b403e..66819836 100644 --- a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ProviderControls/Windows2008_Settings.ascx +++ b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ProviderControls/Windows2008_Settings.ascx @@ -1,9 +1,36 @@ <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Windows2008_Settings.ascx.cs" Inherits="WebsitePanel.Portal.ProviderControls.Windows2008_Settings" %> - - - - + + + + + + + + + + + +
- -
+ + +
+ + + + + +
+ + + + + + + +
+
+
+
diff --git a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ProviderControls/Windows2008_Settings.ascx.cs b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ProviderControls/Windows2008_Settings.ascx.cs index 5d8ec8f1..822b3f93 100644 --- a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ProviderControls/Windows2008_Settings.ascx.cs +++ b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ProviderControls/Windows2008_Settings.ascx.cs @@ -44,16 +44,40 @@ namespace WebsitePanel.Portal.ProviderControls { protected void Page_Load(object sender, EventArgs e) { + //CO Changes + if (!IsPostBack) + { + try + { + chkEnableHardQuota.Enabled = ES.Services.OperatingSystems.CheckFileServicesInstallation(PanelRequest.ServiceId); + txtLocationDrive.Enabled = chkEnableHardQuota.Enabled; + valLocationDrive.Enabled = chkEnableHardQuota.Enabled; + if (!chkEnableHardQuota.Enabled) + lblFileServiceInfo.Visible = true; + } + catch + { + } + } + //END } public void BindSettings(StringDictionary settings) { txtFolder.Text = settings["UsersHome"]; + //CO Changes + txtLocationDrive.Text = settings["LocationDrive"]; + chkEnableHardQuota.Checked = settings["EnableHardQuota"] == "true" ? true : false; + //END } public void SaveSettings(StringDictionary settings) { settings["UsersHome"] = txtFolder.Text; + //CO Changes + settings["LocationDrive"] = txtLocationDrive.Text; + settings["EnableHardQuota"] = chkEnableHardQuota.Checked.ToString().ToLower(); + //END } } } \ No newline at end of file diff --git a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ProviderControls/Windows2008_Settings.ascx.designer.cs b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ProviderControls/Windows2008_Settings.ascx.designer.cs index 4250465f..14dda85b 100644 --- a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ProviderControls/Windows2008_Settings.ascx.designer.cs +++ b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ProviderControls/Windows2008_Settings.ascx.designer.cs @@ -1,22 +1,43 @@ +// Copyright (c) 2012, Outercurve Foundation. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// - Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// +// - Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// - Neither the name of the Outercurve Foundation nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + //------------------------------------------------------------------------------ // // This code was generated by a tool. -// Runtime Version:2.0.50727.312 // // Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. +// the code is regenerated. // //------------------------------------------------------------------------------ namespace WebsitePanel.Portal.ProviderControls { - /// - /// Windows2008_Settings class. - /// - /// - /// Auto-generated class. - /// public partial class Windows2008_Settings { /// @@ -36,5 +57,50 @@ namespace WebsitePanel.Portal.ProviderControls { /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.TextBox txtFolder; + + /// + /// lblLocationDrive control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.Label lblLocationDrive; + + /// + /// txtLocationDrive control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.TextBox txtLocationDrive; + + /// + /// valLocationDrive control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.RequiredFieldValidator valLocationDrive; + + /// + /// chkEnableHardQuota control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.CheckBox chkEnableHardQuota; + + /// + /// lblFileServiceInfo control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.Label lblFileServiceInfo; } } diff --git a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/Resources/Windows2008_Settings.ascx.resx b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/Resources/Windows2008_Settings.ascx.resx new file mode 100644 index 00000000..d2f4439d --- /dev/null +++ b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/Resources/Windows2008_Settings.ascx.resx @@ -0,0 +1,129 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Enable Hard Quota: + + + Location Drive: + + + Hosting Spaces Folder: + + \ No newline at end of file diff --git a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/SettingsExchangeMailboxPlansPolicy.ascx b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/SettingsExchangeMailboxPlansPolicy.ascx index f1a7dba9..04e493eb 100644 --- a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/SettingsExchangeMailboxPlansPolicy.ascx +++ b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/SettingsExchangeMailboxPlansPolicy.ascx @@ -215,6 +215,37 @@
+ + + + + + + + + + + + + + + + +
+ +
+ + +
+ +
+
+ + + +
diff --git a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/SettingsExchangeMailboxPlansPolicy.ascx.cs b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/SettingsExchangeMailboxPlansPolicy.ascx.cs index 2ed2f52f..075a243a 100644 --- a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/SettingsExchangeMailboxPlansPolicy.ascx.cs +++ b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/SettingsExchangeMailboxPlansPolicy.ascx.cs @@ -120,6 +120,10 @@ namespace WebsitePanel.Portal if ((plan.ProhibitSendReceivePct == 0)) plan.ProhibitSendReceivePct = 100; plan.KeepDeletedItemsDays = daysKeepDeletedItems.ValueDays; plan.HideFromAddressBook = chkHideFromAddressBook.Checked; + plan.AllowLitigationHold = chkEnableLitigationHold.Checked; + plan.RecoverableItemsSpace = recoverableItemsSpace.QuotaValue; + plan.RecoverableItemsWarningPct = recoverableItemsWarning.ValueKB; + if ((plan.RecoverableItemsWarningPct == 0)) plan.RecoverableItemsWarningPct = 100; if (PanelSecurity.SelectedUser.Role == UserRole.Administrator) plan.MailboxPlanType = (int)ExchangeMailboxPlanType.Administrator; @@ -218,6 +222,10 @@ namespace WebsitePanel.Portal sizeProhibitSendReceive.ValueKB = -1; daysKeepDeletedItems.ValueDays = -1; chkHideFromAddressBook.Checked = false; + chkEnableLitigationHold.Checked = false; + recoverableItemsSpace.QuotaValue = 0; + recoverableItemsWarning.ValueKB = -1; + btnUpdateMailboxPlan.Enabled = (string.IsNullOrEmpty(txtMailboxPlan.Text)) ? false : true; @@ -266,7 +274,9 @@ namespace WebsitePanel.Portal if (plan.KeepDeletedItemsDays != -1) daysKeepDeletedItems.ValueDays = plan.KeepDeletedItemsDays; chkHideFromAddressBook.Checked = plan.HideFromAddressBook; - + chkEnableLitigationHold.Checked = plan.AllowLitigationHold; + recoverableItemsSpace.QuotaValue = plan.RecoverableItemsSpace; + recoverableItemsWarning.ValueKB = plan.RecoverableItemsWarningPct; btnUpdateMailboxPlan.Enabled = (string.IsNullOrEmpty(txtMailboxPlan.Text)) ? false : true; @@ -369,6 +379,11 @@ namespace WebsitePanel.Portal if ((plan.ProhibitSendReceivePct == 0)) plan.ProhibitSendReceivePct = 100; plan.KeepDeletedItemsDays = daysKeepDeletedItems.ValueDays; plan.HideFromAddressBook = chkHideFromAddressBook.Checked; + plan.AllowLitigationHold = chkEnableLitigationHold.Checked; + plan.RecoverableItemsSpace = recoverableItemsSpace.QuotaValue; + plan.RecoverableItemsWarningPct = recoverableItemsWarning.ValueKB; + if ((plan.RecoverableItemsWarningPct == 0)) plan.RecoverableItemsWarningPct = 100; + if (PanelSecurity.SelectedUser.Role == UserRole.Administrator) plan.MailboxPlanType = (int)ExchangeMailboxPlanType.Administrator; diff --git a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/SettingsExchangeMailboxPlansPolicy.ascx.designer.cs b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/SettingsExchangeMailboxPlansPolicy.ascx.designer.cs index 14dabec4..2f52dedf 100644 --- a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/SettingsExchangeMailboxPlansPolicy.ascx.designer.cs +++ b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/SettingsExchangeMailboxPlansPolicy.ascx.designer.cs @@ -25,7 +25,6 @@ // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - //------------------------------------------------------------------------------ // // This code was generated by a tool. @@ -382,6 +381,69 @@ namespace WebsitePanel.Portal { /// protected global::WebsitePanel.Portal.ExchangeServer.UserControls.DaysBox daysKeepDeletedItems; + /// + /// secLitigationHold control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::WebsitePanel.Portal.CollapsiblePanel secLitigationHold; + + /// + /// LitigationHold control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.Panel LitigationHold; + + /// + /// chkEnableLitigationHold control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.CheckBox chkEnableLitigationHold; + + /// + /// locRecoverableItemsSpace control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.Localize locRecoverableItemsSpace; + + /// + /// recoverableItemsSpace control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::WebsitePanel.Portal.QuotaEditor recoverableItemsSpace; + + /// + /// locRecoverableItemsWarning control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.Localize locRecoverableItemsWarning; + + /// + /// recoverableItemsWarning control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::WebsitePanel.Portal.ExchangeServer.UserControls.SizeBox recoverableItemsWarning; + /// /// btnAddMailboxPlan control. /// diff --git a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/WebSitesEditSite.ascx b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/WebSitesEditSite.ascx index 3af4a279..0ae495ee 100644 --- a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/WebSitesEditSite.ascx +++ b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/WebSitesEditSite.ascx @@ -1,119 +1,119 @@ <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebSitesEditSite.ascx.cs" - Inherits="WebsitePanel.Portal.WebSitesEditSite" %> + Inherits="WebsitePanel.Portal.WebSitesEditSite" %> <%@ Import Namespace="WebsitePanel.Portal" %> -<%@ Register Src="WebSitesExtensionsControl.ascx" TagName="WebSitesExtensionsControl" TagPrefix="uc6" %> -<%@ Register Src="WebSitesCustomErrorsControl.ascx" TagName="WebSitesCustomErrorsControl" TagPrefix="uc4" %> -<%@ Register Src="WebSitesMimeTypesControl.ascx" TagName="WebSitesMimeTypesControl" TagPrefix="uc5" %> -<%@ Register Src="WebSitesHomeFolderControl.ascx" TagName="WebSitesHomeFolderControl" TagPrefix="uc1" %> -<%@ Register Src="WebSitesCustomHeadersControl.ascx" TagName="WebSitesCustomHeadersControl" TagPrefix="uc6" %> -<%@ Register Src="WebSitesSecuredFoldersControl.ascx" TagName="WebSitesSecuredFoldersControl" TagPrefix="wsp" %> -<%@ Register Src="WebSitesHeliconApeControl.ascx" TagName="WebSitesHeliconApeControl" TagPrefix="wsp" %> +<%@ Register Src="WebSitesExtensionsControl.ascx" TagName="WebSitesExtensionsControl" TagPrefix="uc6" %> +<%@ Register Src="WebSitesCustomErrorsControl.ascx" TagName="WebSitesCustomErrorsControl" TagPrefix="uc4" %> +<%@ Register Src="WebSitesMimeTypesControl.ascx" TagName="WebSitesMimeTypesControl" TagPrefix="uc5" %> +<%@ Register Src="WebSitesHomeFolderControl.ascx" TagName="WebSitesHomeFolderControl" TagPrefix="uc1" %> +<%@ Register Src="WebSitesCustomHeadersControl.ascx" TagName="WebSitesCustomHeadersControl" TagPrefix="uc6" %> +<%@ Register Src="WebSitesSecuredFoldersControl.ascx" TagName="WebSitesSecuredFoldersControl" TagPrefix="wsp" %> +<%@ Register Src="WebSitesHeliconApeControl.ascx" TagName="WebSitesHeliconApeControl" TagPrefix="wsp" %> <%@ Register Src="UserControls/PasswordControl.ascx" TagName="PasswordControl" TagPrefix="wsp" %> <%@ Register Src="UserControls/UsernameControl.ascx" TagName="UsernameControl" TagPrefix="wsp" %> -<%@ Register Src="UserControls/EnableAsyncTasksSupport.ascx" TagName="EnableAsyncTasksSupport" TagPrefix="wsp" %> -<%@ Register Src="UserControls/SimpleMessageBox.ascx" TagName="SimpleMessageBox" TagPrefix="wsp" %> +<%@ Register Src="UserControls/EnableAsyncTasksSupport.ascx" TagName="EnableAsyncTasksSupport" TagPrefix="wsp" %> +<%@ Register Src="UserControls/SimpleMessageBox.ascx" TagName="SimpleMessageBox" TagPrefix="wsp" %> <%@ Register Src="UserControls/PopupHeader.ascx" TagName="PopupHeader" TagPrefix="wsp" %> <%@ Register TagPrefix="wsp" Namespace="WebsitePanel.Portal" %> <%@ Register Src="WebsitesSSL.ascx" TagName="WebsitesSSL" TagPrefix="uc2" %> + TargetControlID="WDeployRebuildPubProfileLinkButton" PopupControlID="WDeployBuildPublishingProfileWizardPanel" + BackgroundCssClass="modalBackground" DropShadow="false" CancelControlID="PubProfileWizardCancelButton" />
- - - - - -
- - - + +
- domain.com -
+ + - - - - + + + + + +
+ + + - - - - -
+ domain.com + @@ -128,376 +128,386 @@ - +    
-
- -
- - - - - - <%# Eval("DomainName") %> - - - - - - -
-
- - - - - - - -
- -
- - - - -
-
- - - + + + +
-    +
+
+ +
+ + + + + + <%# Eval("DomainName") %> + + + + + +
+
+ + + + + + + +
+ +
+ + + + +
+
+ + + - -
   - - - + RepeatLayout="Flow" DataKeyField="ViewId"> + + + <%# Eval("Name") %> - - - - - + + + + + <%# Eval("Name") %> - - - -
-
- - - - - -
-
- -
- - - - - - + + + +
+
+ + + + + +
+
+ +
+ + + + + + <%# Eval("Name") %> - - - - - - - - -
-
- - - - - - - - - - - - -
- -
- - - - - - - - - - - - - - - - - - -
- - - -
- - - -
- - - -
- - - - -
-
-
- - - - - - - - - - -
- -
-
-
-
-
-
-
- -
-
-
-
-
-
-

-  / 

-
-
- - - - - - - - - - - - - - -
- - - - - -
- - - - -
- - - - - -
-
-
-   + + + + + + + + +
+ + + + + + + + + + + + + +
+ +
+ + + + + + + + + + + + + + + + + + +
+ + + +
+ + + +
+ + + +
+ + + +
+
+
+ + + + + + + + + + +
+ +
+ +
+
+
+ +
+
+
+ +
+ +
+
+
+ +
+
+

+  /  +

+
+
+ + + + + + + + + + + + + + +
+ + + + + +
+ + + + +
+ + + + + +
+
+
+     + CssClass="Button1" OnClick="WDeployChangePublishingPasswButton_Click" ValidationGroup="WDeployPublishingGroup" />  -
-
- Web Deploy + CssClass="Button1" OnClick="WDeployDisablePublishingButton_Click" OnClientClick="return confirmationWebDeployPublishing();" + ValidationGroup="WDeployPublishingGroup" CausesValidation="false" /> +
+
+ Web Deploy Remote Agent is not installed... -
-
- - - - - -

-

- - - - - - - - - -
- - - -
- - - -
-
- -
- -
-
-
-
-
-
-
- -
-
-
-
-
-
-
- - - - - - - - - - - - - - -
- - - - - -
- - - - -
- - - - - -
-
-
- -   +
+ + + + + + +

+

+ + + + + + + + + +
+ + + +
+ + + +
+
+ +
+ +
+ +
+
+
+ +
+
+
+ +
+ +
+
+
+ +
+
+
+ + + + + + + + + + + + + + +
+ + + + + +
+ + + + +
+ + + + + +
+
+
+ +   -
-
- -
-
-
-
-
- - - - -
-
+ CssClass="Button1" OnClick="btnWmSvcSiteDisable_Click" OnClientClick="return confirmationWMSVC();" + ValidationGroup="WmSvcGroup" CausesValidation="false" /> +
+ + +
+ +
+
+ + + + + + + +
- - - -
\ No newline at end of file + + + +
+ + +
diff --git a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/WebSitesEditSite.ascx.cs b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/WebSitesEditSite.ascx.cs index d3ac61b0..162d35ce 100644 --- a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/WebSitesEditSite.ascx.cs +++ b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/WebSitesEditSite.ascx.cs @@ -913,7 +913,7 @@ namespace WebsitePanel.Portal { try { - int result = ES.Services.WebServers.DeleteWebSite(PanelRequest.ItemID); + int result = ES.Services.WebServers.DeleteWebSite(PanelRequest.ItemID, chkDeleteWebsiteDirectory.Checked); if (result < 0) { ShowResultMessage(result); diff --git a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/WebSitesEditSite.ascx.designer.cs b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/WebSitesEditSite.ascx.designer.cs index 299d66d1..fe3cda42 100644 --- a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/WebSitesEditSite.ascx.designer.cs +++ b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/WebSitesEditSite.ascx.designer.cs @@ -1,3 +1,31 @@ +// Copyright (c) 2012, Outercurve Foundation. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// - Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// +// - Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// - Neither the name of the Outercurve Foundation nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + //------------------------------------------------------------------------------ // // This code was generated by a tool. @@ -1073,5 +1101,14 @@ namespace WebsitePanel.Portal { /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Button btnDelete; + + /// + /// chkDeleteWebsiteDirectory control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.CheckBox chkDeleteWebsiteDirectory; } } diff --git a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/WebsitePanel.Portal.Modules.csproj b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/WebsitePanel.Portal.Modules.csproj index bea7dc26..881b1ce1 100644 --- a/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/WebsitePanel.Portal.Modules.csproj +++ b/WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/WebsitePanel.Portal.Modules.csproj @@ -93,6 +93,13 @@ Code\VersionInfo.cs + + ApplyEnableHardQuotaFeature.ascx + ASPXCodeBehind + + + ApplyEnableHardQuotaFeature.ascx + AuditLog.ascx ASPXCodeBehind @@ -3811,6 +3818,7 @@ + @@ -4975,6 +4983,7 @@ Designer + Designer diff --git a/WebsitePanel/Sources/generate_server_proxies.bat b/WebsitePanel/Sources/generate_server_proxies.bat index d4811b50..2ef3d080 100644 --- a/WebsitePanel/Sources/generate_server_proxies.bat +++ b/WebsitePanel/Sources/generate_server_proxies.bat @@ -17,8 +17,8 @@ REM %WSE_CLEAN% .\WebsitePanel.Server.Client\DatabaseServerProxy.cs REM %WSDL% %SERVER_URL%/DNSServer.asmx /out:.\WebsitePanel.Server.Client\DnsServerProxy.cs /namespace:WebsitePanel.Providers.DNS /type:webClient /fields REM %WSE_CLEAN% .\WebsitePanel.Server.Client\DnsServerProxy.cs -REM %WSDL% %SERVER_URL%/ExchangeServer.asmx /out:.\WebsitePanel.Server.Client\ExchangeServerProxy.cs /namespace:WebsitePanel.Providers.Exchange /type:webClient /fields -REM %WSE_CLEAN% .\WebsitePanel.Server.Client\ExchangeServerProxy.cs +%WSDL% %SERVER_URL%/ExchangeServer.asmx /out:.\WebsitePanel.Server.Client\ExchangeServerProxy.cs /namespace:WebsitePanel.Providers.Exchange /type:webClient /fields +%WSE_CLEAN% .\WebsitePanel.Server.Client\ExchangeServerProxy.cs REM %WSDL% %SERVER_URL%/ExchangeServerHostedEdition.asmx /out:.\WebsitePanel.Server.Client\ExchangeServerHostedEditionProxy.cs /namespace:WebsitePanel.Providers.ExchangeHostedEdition /type:webClient /fields REM %WSE_CLEAN% .\WebsitePanel.Server.Client\ExchangeServerHostedEditionProxy.cs @@ -35,8 +35,8 @@ REM %WSE_CLEAN% .\WebsitePanel.Server.Client\OCSServerProxy.cs REM %WSDL% %SERVER_URL%/OperatingSystem.asmx /out:.\WebsitePanel.Server.Client\OperatingSystemProxy.cs /namespace:WebsitePanel.Providers.OS /type:webClient /fields REM %WSE_CLEAN% .\WebsitePanel.Server.Client\OperatingSystemProxy.cs -%WSDL% %SERVER_URL%/Organizations.asmx /out:.\WebsitePanel.Server.Client\OrganizationProxy.cs /namespace:WebsitePanel.Providers.HostedSolution /type:webClient /fields -%WSE_CLEAN% .\WebsitePanel.Server.Client\OrganizationProxy.cs +REM %WSDL% %SERVER_URL%/Organizations.asmx /out:.\WebsitePanel.Server.Client\OrganizationProxy.cs /namespace:WebsitePanel.Providers.HostedSolution /type:webClient /fields +REM %WSE_CLEAN% .\WebsitePanel.Server.Client\OrganizationProxy.cs REM %WSDL% %SERVER_URL%/ServiceProvider.asmx /out:.\WebsitePanel.Server.Client\ServiceProviderProxy.cs /namespace:WebsitePanel.Providers /type:webClient /fields REM %WSE_CLEAN% .\WebsitePanel.Server.Client\ServiceProviderProxy.cs diff --git a/WebsitePanel/build.xml b/WebsitePanel/build.xml index a821fa72..572c7b35 100644 --- a/WebsitePanel/build.xml +++ b/WebsitePanel/build.xml @@ -1,6 +1,6 @@  - 2.0.0 + 2.1.0 $(BUILD_NUMBER) $(BUILD_NUMBER) 2012-12-07