diff --git a/WebsitePanel/Database/update_db.sql b/WebsitePanel/Database/update_db.sql
index bafb3077..9001eceb 100644
--- a/WebsitePanel/Database/update_db.sql
+++ b/WebsitePanel/Database/update_db.sql
@@ -2797,4 +2797,300 @@ WHERE
AND (@OrgID = 0 OR @OrgID <> 0 AND PA.OrgID = @OrgID)
END
+GO
+
+-- Enterprise Storage Quotas
+IF NOT EXISTS (SELECT * FROM [dbo].[Quotas] WHERE [QuotaName] = 'EnterpriseStorage.DiskStorageSpace')
+BEGIN
+INSERT [dbo].[Quotas] ([QuotaID], [GroupID],[QuotaOrder], [QuotaName], [QuotaDescription], [QuotaTypeID], [ServiceQuota], [ItemTypeID]) VALUES (430, 44, 1,N'EnterpriseStorage.DiskStorageSpace',N'Disk Storage Space (Gb)',2, 0 , NULL)
+END
+GO
+
+UPDATE [dbo].[Quotas] SET [QuotaDescription] = N'Disk Storage Space (Gb)' WHERE [QuotaName] = 'EnterpriseStorage.DiskStorageSpace'
+GO
+
+IF NOT EXISTS (SELECT * FROM SYS.TABLES WHERE name = 'EnterpriseFolders')
+
+CREATE TABLE [dbo].[EnterpriseFolders](
+ [EnterpriseFolderID] [int] IDENTITY(1,1) NOT NULL,
+ [ItemID] [int] NOT NULL,
+ [FolderName] [nvarchar](255) NOT NULL,
+ [FolderQuota] [int] NOT NULL DEFAULT 0,
+ CONSTRAINT [PK_EnterpriseFolders] PRIMARY KEY CLUSTERED
+(
+ [EnterpriseFolderId] ASC
+)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
+)
+
+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 IF @QuotaID = 381 -- Dedicated Lync Phone Numbers
+ 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 = 5)
+ ELSE IF @QuotaID = 430 -- Enterprise Storage
+ SET @Result = (SELECT SUM(ESF.FolderQuota) FROM EnterpriseFolders AS ESF
+ INNER JOIN ServiceItems SI ON ESF.ItemID = SI.ItemID
+ INNER JOIN PackagesTreeCache PT ON SI.PackageID = PT.PackageID
+ WHERE PT.ParentPackageID = @PackageID)
+ ELSE IF @QuotaID = 431 -- Enterprise Storage Folders
+ SET @Result = (SELECT COUNT(ESF.EnterpriseFolderID) FROM EnterpriseFolders AS ESF
+ INNER JOIN ServiceItems SI ON ESF.ItemID = SI.ItemID
+ INNER JOIN PackagesTreeCache PT ON SI.PackageID = PT.PackageID
+ WHERE PT.ParentPackageID = @PackageID)
+ 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 EXISTS (SELECT * FROM SYS.OBJECTS WHERE type = 'P' AND name = 'AddEnterpriseFolder')
+DROP PROCEDURE [dbo].[AddEnterpriseFolder]
+GO
+
+CREATE PROCEDURE [dbo].[AddEnterpriseFolder]
+(
+ @FolderID INT OUTPUT,
+ @ItemID INT,
+ @FolderName NVARCHAR(255)
+)
+AS
+
+INSERT INTO EnterpriseFolders
+(
+ ItemID,
+ FolderName
+)
+VALUES
+(
+ @ItemID,
+ @FolderName
+)
+
+SET @FolderID = SCOPE_IDENTITY()
+
+RETURN
+GO
+
+IF EXISTS (SELECT * FROM SYS.OBJECTS WHERE type = 'P' AND name = 'DeleteEnterpriseFolder')
+DROP PROCEDURE DeleteEnterpriseFolder
+GO
+
+CREATE PROCEDURE [dbo].[DeleteEnterpriseFolder]
+(
+ @ItemID INT,
+ @FolderName NVARCHAR(255)
+)
+AS
+
+DELETE FROM EnterpriseFolders
+WHERE ItemID = @ItemID AND FolderName = @FolderName
+GO
+
+IF EXISTS (SELECT * FROM SYS.OBJECTS WHERE type = 'P' AND name = 'UpdateEnterpriseFolder')
+DROP PROCEDURE UpdateEnterpriseFolder
+GO
+
+CREATE PROCEDURE [dbo].[UpdateEnterpriseFolder]
+(
+ @ItemID INT,
+ @FolderID NVARCHAR(255),
+ @FolderName NVARCHAR(255),
+ @FolderQuota INT
+)
+AS
+
+UPDATE EnterpriseFolders SET
+ FolderName = @FolderName,
+ FolderQuota = @FolderQuota
+WHERE ItemID = @ItemID AND FolderName = @FolderID
+GO
+
+-- Enterprise Storage Quotas
+IF NOT EXISTS (SELECT * FROM [dbo].[Quotas] WHERE [QuotaName] = 'EnterpriseStorage.DiskStorageSpace')
+BEGIN
+INSERT [dbo].[Quotas] ([QuotaID], [GroupID],[QuotaOrder], [QuotaName], [QuotaDescription], [QuotaTypeID], [ServiceQuota], [ItemTypeID]) VALUES (430, 44, 1,N'EnterpriseStorage.DiskStorageSpace',N'Disk Storage Space (Mb)',2, 0 , NULL)
+END
+GO
+
+UPDATE [dbo].[Quotas] SET [QuotaDescription] = N'Disk Storage Space (Mb)' WHERE [QuotaName] = 'EnterpriseStorage.DiskStorageSpace'
+GO
+
+
+-- CRM2013
+
+-- CRM2013 ResourceGroup
+
+IF NOT EXISTS (SELECT * FROM [dbo].[ResourceGroups] WHERE [GroupName] = 'Hosted CRM2013')
+BEGIN
+INSERT [dbo].[ResourceGroups] ([GroupID], [GroupName], [GroupOrder], [GroupController], [ShowGroup]) VALUES (24, N'Hosted CRM2013', 15, NULL, 1)
+END
+GO
+
+-- CRM2013 Provider
+
+IF NOT EXISTS (SELECT * FROM [dbo].[Providers] WHERE [DisplayName] = 'Hosted MS CRM 2013')
+BEGIN
+INSERT [dbo].[Providers] ([ProviderId], [GroupId], [ProviderName], [DisplayName], [ProviderType], [EditorControl], [DisableAutoDiscovery])
+VALUES(1202, 24, N'CRM', N'Hosted MS CRM 2013', N'WebsitePanel.Providers.HostedSolution.CRMProvider2013, WebsitePanel.Providers.HostedSolution.Crm2013', N'CRM2011', NULL)
+END
+GO
+
+-- CRM2013 Quotas
+
+IF NOT EXISTS (SELECT * FROM [dbo].[Quotas] WHERE [QuotaName] = 'HostedCRM2013.Organization')
+BEGIN
+INSERT [dbo].[Quotas] ([QuotaID], [GroupID], [QuotaOrder], [QuotaName], [QuotaDescription], [QuotaTypeID], [ServiceQuota], [ItemTypeID], [HideQuota])
+VALUES (463, 24, 1, N'HostedCRM2013.Organization', N'CRM Organization', 1, 0, NULL, NULL)
+END
+GO
+
+IF NOT EXISTS (SELECT * FROM [dbo].[Quotas] WHERE [QuotaName] = 'HostedCRM2013.MaxDatabaseSize')
+BEGIN
+INSERT [dbo].[Quotas] ([QuotaID], [GroupID],[QuotaOrder], [QuotaName], [QuotaDescription], [QuotaTypeID], [ServiceQuota], [ItemTypeID])
+VALUES (464, 24, 5, N'HostedCRM2013.MaxDatabaseSize', N'Max Database Size, MB',3, 0 , NULL)
+END
+GO
+
+IF NOT EXISTS (SELECT * FROM [dbo].[Quotas] WHERE [QuotaName] = 'HostedCRM2013.EssentialUsers')
+BEGIN
+INSERT [dbo].[Quotas] ([QuotaID], [GroupID], [QuotaOrder], [QuotaName], [QuotaDescription], [QuotaTypeID], [ServiceQuota], [ItemTypeID], [HideQuota])
+VALUES (465, 24, 2, N'HostedCRM2013.EssentialUsers', N'Essential licenses per organization', 3, 0, NULL, NULL)
+END
+GO
+
+IF NOT EXISTS (SELECT * FROM [dbo].[Quotas] WHERE [QuotaName] = 'HostedCRM2013.BasicUsers')
+BEGIN
+INSERT [dbo].[Quotas] ([QuotaID], [GroupID],[QuotaOrder], [QuotaName], [QuotaDescription], [QuotaTypeID], [ServiceQuota], [ItemTypeID])
+VALUES (466, 24, 3, N'HostedCRM2013.BasicUsers', N'Basic licenses per organization',3, 0 , NULL)
+END
+GO
+
+IF NOT EXISTS (SELECT * FROM [dbo].[Quotas] WHERE [QuotaName] = 'HostedCRM2013.ProfessionalUsers')
+BEGIN
+INSERT [dbo].[Quotas] ([QuotaID], [GroupID],[QuotaOrder], [QuotaName], [QuotaDescription], [QuotaTypeID], [ServiceQuota], [ItemTypeID])
+VALUES (467, 24, 4, N'HostedCRM2013.ProfessionalUsers', N'Professional licenses per organization',3, 0 , NULL)
+END
+GO
diff --git a/WebsitePanel/Lib/References/Microsoft/microsoft.crm.sdk.proxy.dll b/WebsitePanel/Lib/References/Microsoft/CRM2011/microsoft.crm.sdk.proxy.dll
similarity index 100%
rename from WebsitePanel/Lib/References/Microsoft/microsoft.crm.sdk.proxy.dll
rename to WebsitePanel/Lib/References/Microsoft/CRM2011/microsoft.crm.sdk.proxy.dll
diff --git a/WebsitePanel/Lib/References/Microsoft/microsoft.xrm.client.codegeneration.dll b/WebsitePanel/Lib/References/Microsoft/CRM2011/microsoft.xrm.client.codegeneration.dll
similarity index 100%
rename from WebsitePanel/Lib/References/Microsoft/microsoft.xrm.client.codegeneration.dll
rename to WebsitePanel/Lib/References/Microsoft/CRM2011/microsoft.xrm.client.codegeneration.dll
diff --git a/WebsitePanel/Lib/References/Microsoft/microsoft.xrm.client.dll b/WebsitePanel/Lib/References/Microsoft/CRM2011/microsoft.xrm.client.dll
similarity index 100%
rename from WebsitePanel/Lib/References/Microsoft/microsoft.xrm.client.dll
rename to WebsitePanel/Lib/References/Microsoft/CRM2011/microsoft.xrm.client.dll
diff --git a/WebsitePanel/Lib/References/Microsoft/microsoft.xrm.portal.dll b/WebsitePanel/Lib/References/Microsoft/CRM2011/microsoft.xrm.portal.dll
similarity index 100%
rename from WebsitePanel/Lib/References/Microsoft/microsoft.xrm.portal.dll
rename to WebsitePanel/Lib/References/Microsoft/CRM2011/microsoft.xrm.portal.dll
diff --git a/WebsitePanel/Lib/References/Microsoft/microsoft.xrm.portal.files.dll b/WebsitePanel/Lib/References/Microsoft/CRM2011/microsoft.xrm.portal.files.dll
similarity index 100%
rename from WebsitePanel/Lib/References/Microsoft/microsoft.xrm.portal.files.dll
rename to WebsitePanel/Lib/References/Microsoft/CRM2011/microsoft.xrm.portal.files.dll
diff --git a/WebsitePanel/Lib/References/Microsoft/microsoft.xrm.sdk.deployment.dll b/WebsitePanel/Lib/References/Microsoft/CRM2011/microsoft.xrm.sdk.deployment.dll
similarity index 100%
rename from WebsitePanel/Lib/References/Microsoft/microsoft.xrm.sdk.deployment.dll
rename to WebsitePanel/Lib/References/Microsoft/CRM2011/microsoft.xrm.sdk.deployment.dll
diff --git a/WebsitePanel/Lib/References/Microsoft/microsoft.xrm.sdk.dll b/WebsitePanel/Lib/References/Microsoft/CRM2011/microsoft.xrm.sdk.dll
similarity index 100%
rename from WebsitePanel/Lib/References/Microsoft/microsoft.xrm.sdk.dll
rename to WebsitePanel/Lib/References/Microsoft/CRM2011/microsoft.xrm.sdk.dll
diff --git a/WebsitePanel/Lib/References/Microsoft/microsoft.xrm.sdk.workflow.dll b/WebsitePanel/Lib/References/Microsoft/CRM2011/microsoft.xrm.sdk.workflow.dll
similarity index 100%
rename from WebsitePanel/Lib/References/Microsoft/microsoft.xrm.sdk.workflow.dll
rename to WebsitePanel/Lib/References/Microsoft/CRM2011/microsoft.xrm.sdk.workflow.dll
diff --git a/WebsitePanel/Lib/References/Microsoft/CRM2013/Microsoft.Crm.Sdk.Proxy.dll b/WebsitePanel/Lib/References/Microsoft/CRM2013/Microsoft.Crm.Sdk.Proxy.dll
new file mode 100644
index 00000000..cc98c301
Binary files /dev/null and b/WebsitePanel/Lib/References/Microsoft/CRM2013/Microsoft.Crm.Sdk.Proxy.dll differ
diff --git a/WebsitePanel/Lib/References/Microsoft/CRM2013/Microsoft.Xrm.Client.CodeGeneration.dll b/WebsitePanel/Lib/References/Microsoft/CRM2013/Microsoft.Xrm.Client.CodeGeneration.dll
new file mode 100644
index 00000000..758d4494
Binary files /dev/null and b/WebsitePanel/Lib/References/Microsoft/CRM2013/Microsoft.Xrm.Client.CodeGeneration.dll differ
diff --git a/WebsitePanel/Lib/References/Microsoft/CRM2013/Microsoft.Xrm.Client.dll b/WebsitePanel/Lib/References/Microsoft/CRM2013/Microsoft.Xrm.Client.dll
new file mode 100644
index 00000000..8f9629aa
Binary files /dev/null and b/WebsitePanel/Lib/References/Microsoft/CRM2013/Microsoft.Xrm.Client.dll differ
diff --git a/WebsitePanel/Lib/References/Microsoft/CRM2013/Microsoft.Xrm.Portal.Files.dll b/WebsitePanel/Lib/References/Microsoft/CRM2013/Microsoft.Xrm.Portal.Files.dll
new file mode 100644
index 00000000..b8d9278a
Binary files /dev/null and b/WebsitePanel/Lib/References/Microsoft/CRM2013/Microsoft.Xrm.Portal.Files.dll differ
diff --git a/WebsitePanel/Lib/References/Microsoft/CRM2013/Microsoft.Xrm.Portal.dll b/WebsitePanel/Lib/References/Microsoft/CRM2013/Microsoft.Xrm.Portal.dll
new file mode 100644
index 00000000..33eb2197
Binary files /dev/null and b/WebsitePanel/Lib/References/Microsoft/CRM2013/Microsoft.Xrm.Portal.dll differ
diff --git a/WebsitePanel/Lib/References/Microsoft/CRM2013/Microsoft.Xrm.Sdk.Deployment.dll b/WebsitePanel/Lib/References/Microsoft/CRM2013/Microsoft.Xrm.Sdk.Deployment.dll
new file mode 100644
index 00000000..05c065a5
Binary files /dev/null and b/WebsitePanel/Lib/References/Microsoft/CRM2013/Microsoft.Xrm.Sdk.Deployment.dll differ
diff --git a/WebsitePanel/Lib/References/Microsoft/CRM2013/Microsoft.Xrm.Sdk.Workflow.dll b/WebsitePanel/Lib/References/Microsoft/CRM2013/Microsoft.Xrm.Sdk.Workflow.dll
new file mode 100644
index 00000000..ef8b5116
Binary files /dev/null and b/WebsitePanel/Lib/References/Microsoft/CRM2013/Microsoft.Xrm.Sdk.Workflow.dll differ
diff --git a/WebsitePanel/Lib/References/Microsoft/CRM2013/Microsoft.Xrm.Sdk.dll b/WebsitePanel/Lib/References/Microsoft/CRM2013/Microsoft.Xrm.Sdk.dll
new file mode 100644
index 00000000..048a102b
Binary files /dev/null and b/WebsitePanel/Lib/References/Microsoft/CRM2013/Microsoft.Xrm.Sdk.dll differ
diff --git a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer.Base/HostedSolution/CRMLycenseTypes.cs b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer.Base/HostedSolution/CRMLycenseTypes.cs
new file mode 100644
index 00000000..a38a0c7c
--- /dev/null
+++ b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer.Base/HostedSolution/CRMLycenseTypes.cs
@@ -0,0 +1,50 @@
+// 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.Linq;
+using System.Text;
+using WebsitePanel.EnterpriseServer;
+
+namespace WebsitePanel.EnterpriseServer
+{
+ public class CRMUserLycenseTypes
+ {
+ // CRM 2011
+ public const int FULL = 0;
+ public const int LIMITED = 2;
+ public const int ESS = 22;
+
+ // CRM 2013
+ public const int PROFESSIONAL = 0;
+ public const int BASIC = 2;
+ public const int ESSENTIAL = 5;
+
+ }
+}
diff --git a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer.Base/Packages/Quotas.cs b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer.Base/Packages/Quotas.cs
index 35dc110f..03374d8e 100644
--- a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer.Base/Packages/Quotas.cs
+++ b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer.Base/Packages/Quotas.cs
@@ -163,6 +163,14 @@ order by rg.groupOrder
public const string CRM_ESSUSERS = "HostedCRM.ESSUsers";
public const string CRM_MAXDATABASESIZE = "HostedCRM.MaxDatabaseSize";
+ public const string CRM2013_ORGANIZATION = "HostedCRM2013.Organization";
+ public const string CRM2013_MAXDATABASESIZE = "HostedCRM2013.MaxDatabaseSize";
+
+ public const string CRM2013_ESSENTIALUSERS = "HostedCRM2013.EssentialUsers";
+ public const string CRM2013_BASICUSERS = "HostedCRM2013.BasicUsers";
+ public const string CRM2013_PROFESSIONALUSERS = "HostedCRM2013.ProfessionalUsers";
+
+
public const string VPS_SERVERS_NUMBER = "VPS.ServersNumber"; // Number of VPS
public const string VPS_MANAGING_ALLOWED = "VPS.ManagingAllowed"; // Allow user to create VPS
public const string VPS_CPU_NUMBER = "VPS.CpuNumber"; // Number of CPU cores
diff --git a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer.Base/Servers/ResourceGroups.cs b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer.Base/Servers/ResourceGroups.cs
index 43fb177f..da82621d 100644
--- a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer.Base/Servers/ResourceGroups.cs
+++ b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer.Base/Servers/ResourceGroups.cs
@@ -47,6 +47,7 @@ namespace WebsitePanel.EnterpriseServer
public const string Exchange = "Exchange";
public const string HostedOrganizations = "Hosted Organizations";
public const string HostedCRM = "Hosted CRM";
+ public const string HostedCRM2013 = "Hosted CRM2013";
public const string VPS = "VPS";
public const string BlackBerry = "BlackBerry";
public const string OCS = "OCS";
diff --git a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer.Base/WebsitePanel.EnterpriseServer.Base.csproj b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer.Base/WebsitePanel.EnterpriseServer.Base.csproj
index 082f5542..90172b0b 100644
--- a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer.Base/WebsitePanel.EnterpriseServer.Base.csproj
+++ b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer.Base/WebsitePanel.EnterpriseServer.Base.csproj
@@ -117,6 +117,7 @@
+
diff --git a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer.Client/CRMProxy.cs b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer.Client/CRMProxy.cs
index e77c153c..1bb230d9 100644
--- a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer.Client/CRMProxy.cs
+++ b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer.Client/CRMProxy.cs
@@ -26,23 +26,11 @@
// (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.5466
-//
-// Changes to this file may cause incorrect behavior and will be lost if
-// the code is regenerated.
-//
-//------------------------------------------------------------------------------
-
-//
-// This source code was auto-generated by wsdl, Version=2.0.50727.42.
-//
using WebsitePanel.Providers;
using WebsitePanel.Providers.Common;
using WebsitePanel.Providers.HostedSolution;
using WebsitePanel.Providers.ResultObjects;
+
//
// This source code was auto-generated by wsdl, Version=2.0.50727.42.
//
@@ -67,8 +55,12 @@ namespace WebsitePanel.EnterpriseServer {
private System.Threading.SendOrPostCallback GetCollationOperationCompleted;
+ private System.Threading.SendOrPostCallback GetCollationByServiceIdOperationCompleted;
+
private System.Threading.SendOrPostCallback GetCurrencyOperationCompleted;
+ private System.Threading.SendOrPostCallback GetCurrencyByServiceIdOperationCompleted;
+
private System.Threading.SendOrPostCallback DeleteCRMOrganizationOperationCompleted;
private System.Threading.SendOrPostCallback GetCRMUsersPagedOperationCompleted;
@@ -95,6 +87,10 @@ namespace WebsitePanel.EnterpriseServer {
private System.Threading.SendOrPostCallback GetMaxDBSizeOperationCompleted;
+ private System.Threading.SendOrPostCallback GetInstalledLanguagePacksOperationCompleted;
+
+ private System.Threading.SendOrPostCallback GetInstalledLanguagePacksByServiceIdOperationCompleted;
+
///
public esCRM() {
this.Url = "http://localhost:9002/esCRM.asmx";
@@ -106,9 +102,15 @@ namespace WebsitePanel.EnterpriseServer {
///
public event GetCollationCompletedEventHandler GetCollationCompleted;
+ ///
+ public event GetCollationByServiceIdCompletedEventHandler GetCollationByServiceIdCompleted;
+
///
public event GetCurrencyCompletedEventHandler GetCurrencyCompleted;
+ ///
+ public event GetCurrencyByServiceIdCompletedEventHandler GetCurrencyByServiceIdCompleted;
+
///
public event DeleteCRMOrganizationCompletedEventHandler DeleteCRMOrganizationCompleted;
@@ -148,9 +150,15 @@ namespace WebsitePanel.EnterpriseServer {
///
public event GetMaxDBSizeCompletedEventHandler GetMaxDBSizeCompleted;
+ ///
+ public event GetInstalledLanguagePacksCompletedEventHandler GetInstalledLanguagePacksCompleted;
+
+ ///
+ public event GetInstalledLanguagePacksByServiceIdCompletedEventHandler GetInstalledLanguagePacksByServiceIdCompleted;
+
///
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/CreateOrganization", 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 OrganizationResult CreateOrganization(int organizationId, string baseCurrencyCode, string baseCurrencyName, string baseCurrencySymbol, string regionName, int userId, string collation) {
+ public OrganizationResult CreateOrganization(int organizationId, string baseCurrencyCode, string baseCurrencyName, string baseCurrencySymbol, string regionName, int userId, string collation, int baseLanguageCode) {
object[] results = this.Invoke("CreateOrganization", new object[] {
organizationId,
baseCurrencyCode,
@@ -158,12 +166,13 @@ namespace WebsitePanel.EnterpriseServer {
baseCurrencySymbol,
regionName,
userId,
- collation});
+ collation,
+ baseLanguageCode});
return ((OrganizationResult)(results[0]));
}
///
- public System.IAsyncResult BeginCreateOrganization(int organizationId, string baseCurrencyCode, string baseCurrencyName, string baseCurrencySymbol, string regionName, int userId, string collation, System.AsyncCallback callback, object asyncState) {
+ public System.IAsyncResult BeginCreateOrganization(int organizationId, string baseCurrencyCode, string baseCurrencyName, string baseCurrencySymbol, string regionName, int userId, string collation, int baseLanguageCode, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("CreateOrganization", new object[] {
organizationId,
baseCurrencyCode,
@@ -171,7 +180,8 @@ namespace WebsitePanel.EnterpriseServer {
baseCurrencySymbol,
regionName,
userId,
- collation}, callback, asyncState);
+ collation,
+ baseLanguageCode}, callback, asyncState);
}
///
@@ -181,12 +191,12 @@ namespace WebsitePanel.EnterpriseServer {
}
///
- public void CreateOrganizationAsync(int organizationId, string baseCurrencyCode, string baseCurrencyName, string baseCurrencySymbol, string regionName, int userId, string collation) {
- this.CreateOrganizationAsync(organizationId, baseCurrencyCode, baseCurrencyName, baseCurrencySymbol, regionName, userId, collation, null);
+ public void CreateOrganizationAsync(int organizationId, string baseCurrencyCode, string baseCurrencyName, string baseCurrencySymbol, string regionName, int userId, string collation, int baseLanguageCode) {
+ this.CreateOrganizationAsync(organizationId, baseCurrencyCode, baseCurrencyName, baseCurrencySymbol, regionName, userId, collation, baseLanguageCode, null);
}
///
- public void CreateOrganizationAsync(int organizationId, string baseCurrencyCode, string baseCurrencyName, string baseCurrencySymbol, string regionName, int userId, string collation, object userState) {
+ public void CreateOrganizationAsync(int organizationId, string baseCurrencyCode, string baseCurrencyName, string baseCurrencySymbol, string regionName, int userId, string collation, int baseLanguageCode, object userState) {
if ((this.CreateOrganizationOperationCompleted == null)) {
this.CreateOrganizationOperationCompleted = new System.Threading.SendOrPostCallback(this.OnCreateOrganizationOperationCompleted);
}
@@ -197,7 +207,8 @@ namespace WebsitePanel.EnterpriseServer {
baseCurrencySymbol,
regionName,
userId,
- collation}, this.CreateOrganizationOperationCompleted, userState);
+ collation,
+ baseLanguageCode}, this.CreateOrganizationOperationCompleted, userState);
}
private void OnCreateOrganizationOperationCompleted(object arg) {
@@ -248,6 +259,47 @@ namespace WebsitePanel.EnterpriseServer {
}
}
+ ///
+ [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/GetCollationByServiceId", 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 StringArrayResultObject GetCollationByServiceId(int serviceId) {
+ object[] results = this.Invoke("GetCollationByServiceId", new object[] {
+ serviceId});
+ return ((StringArrayResultObject)(results[0]));
+ }
+
+ ///
+ public System.IAsyncResult BeginGetCollationByServiceId(int serviceId, System.AsyncCallback callback, object asyncState) {
+ return this.BeginInvoke("GetCollationByServiceId", new object[] {
+ serviceId}, callback, asyncState);
+ }
+
+ ///
+ public StringArrayResultObject EndGetCollationByServiceId(System.IAsyncResult asyncResult) {
+ object[] results = this.EndInvoke(asyncResult);
+ return ((StringArrayResultObject)(results[0]));
+ }
+
+ ///
+ public void GetCollationByServiceIdAsync(int serviceId) {
+ this.GetCollationByServiceIdAsync(serviceId, null);
+ }
+
+ ///
+ public void GetCollationByServiceIdAsync(int serviceId, object userState) {
+ if ((this.GetCollationByServiceIdOperationCompleted == null)) {
+ this.GetCollationByServiceIdOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetCollationByServiceIdOperationCompleted);
+ }
+ this.InvokeAsync("GetCollationByServiceId", new object[] {
+ serviceId}, this.GetCollationByServiceIdOperationCompleted, userState);
+ }
+
+ private void OnGetCollationByServiceIdOperationCompleted(object arg) {
+ if ((this.GetCollationByServiceIdCompleted != null)) {
+ System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
+ this.GetCollationByServiceIdCompleted(this, new GetCollationByServiceIdCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
+ }
+ }
+
///
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/GetCurrency", 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 CurrencyArrayResultObject GetCurrency(int packageId) {
@@ -289,6 +341,47 @@ namespace WebsitePanel.EnterpriseServer {
}
}
+ ///
+ [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/GetCurrencyByServiceId", 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 CurrencyArrayResultObject GetCurrencyByServiceId(int serviceId) {
+ object[] results = this.Invoke("GetCurrencyByServiceId", new object[] {
+ serviceId});
+ return ((CurrencyArrayResultObject)(results[0]));
+ }
+
+ ///
+ public System.IAsyncResult BeginGetCurrencyByServiceId(int serviceId, System.AsyncCallback callback, object asyncState) {
+ return this.BeginInvoke("GetCurrencyByServiceId", new object[] {
+ serviceId}, callback, asyncState);
+ }
+
+ ///
+ public CurrencyArrayResultObject EndGetCurrencyByServiceId(System.IAsyncResult asyncResult) {
+ object[] results = this.EndInvoke(asyncResult);
+ return ((CurrencyArrayResultObject)(results[0]));
+ }
+
+ ///
+ public void GetCurrencyByServiceIdAsync(int serviceId) {
+ this.GetCurrencyByServiceIdAsync(serviceId, null);
+ }
+
+ ///
+ public void GetCurrencyByServiceIdAsync(int serviceId, object userState) {
+ if ((this.GetCurrencyByServiceIdOperationCompleted == null)) {
+ this.GetCurrencyByServiceIdOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetCurrencyByServiceIdOperationCompleted);
+ }
+ this.InvokeAsync("GetCurrencyByServiceId", new object[] {
+ serviceId}, this.GetCurrencyByServiceIdOperationCompleted, userState);
+ }
+
+ private void OnGetCurrencyByServiceIdOperationCompleted(object arg) {
+ if ((this.GetCurrencyByServiceIdCompleted != null)) {
+ System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
+ this.GetCurrencyByServiceIdCompleted(this, new GetCurrencyByServiceIdCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
+ }
+ }
+
///
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/DeleteCRMOrganization", 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 ResultObject DeleteCRMOrganization(int organizationId) {
@@ -909,6 +1002,89 @@ namespace WebsitePanel.EnterpriseServer {
}
}
+ ///
+ [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/GetInstalledLanguagePacks", 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[] GetInstalledLanguagePacks(int packageId) {
+ object[] results = this.Invoke("GetInstalledLanguagePacks", new object[] {
+ packageId});
+ return ((int[])(results[0]));
+ }
+
+ ///
+ public System.IAsyncResult BeginGetInstalledLanguagePacks(int packageId, System.AsyncCallback callback, object asyncState) {
+ return this.BeginInvoke("GetInstalledLanguagePacks", new object[] {
+ packageId}, callback, asyncState);
+ }
+
+ ///
+ public int[] EndGetInstalledLanguagePacks(System.IAsyncResult asyncResult) {
+ object[] results = this.EndInvoke(asyncResult);
+ return ((int[])(results[0]));
+ }
+
+ ///
+ public void GetInstalledLanguagePacksAsync(int packageId) {
+ this.GetInstalledLanguagePacksAsync(packageId, null);
+ }
+
+ ///
+ public void GetInstalledLanguagePacksAsync(int packageId, object userState) {
+ if ((this.GetInstalledLanguagePacksOperationCompleted == null)) {
+ this.GetInstalledLanguagePacksOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetInstalledLanguagePacksOperationCompleted);
+ }
+ this.InvokeAsync("GetInstalledLanguagePacks", new object[] {
+ packageId}, this.GetInstalledLanguagePacksOperationCompleted, userState);
+ }
+
+ private void OnGetInstalledLanguagePacksOperationCompleted(object arg) {
+ if ((this.GetInstalledLanguagePacksCompleted != null)) {
+ System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
+ this.GetInstalledLanguagePacksCompleted(this, new GetInstalledLanguagePacksCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
+ }
+ }
+
+ ///
+ [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/GetInstalledLanguagePacksByServiceId" +
+ "", 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[] GetInstalledLanguagePacksByServiceId(int serviceId) {
+ object[] results = this.Invoke("GetInstalledLanguagePacksByServiceId", new object[] {
+ serviceId});
+ return ((int[])(results[0]));
+ }
+
+ ///
+ public System.IAsyncResult BeginGetInstalledLanguagePacksByServiceId(int serviceId, System.AsyncCallback callback, object asyncState) {
+ return this.BeginInvoke("GetInstalledLanguagePacksByServiceId", new object[] {
+ serviceId}, callback, asyncState);
+ }
+
+ ///
+ public int[] EndGetInstalledLanguagePacksByServiceId(System.IAsyncResult asyncResult) {
+ object[] results = this.EndInvoke(asyncResult);
+ return ((int[])(results[0]));
+ }
+
+ ///
+ public void GetInstalledLanguagePacksByServiceIdAsync(int serviceId) {
+ this.GetInstalledLanguagePacksByServiceIdAsync(serviceId, null);
+ }
+
+ ///
+ public void GetInstalledLanguagePacksByServiceIdAsync(int serviceId, object userState) {
+ if ((this.GetInstalledLanguagePacksByServiceIdOperationCompleted == null)) {
+ this.GetInstalledLanguagePacksByServiceIdOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetInstalledLanguagePacksByServiceIdOperationCompleted);
+ }
+ this.InvokeAsync("GetInstalledLanguagePacksByServiceId", new object[] {
+ serviceId}, this.GetInstalledLanguagePacksByServiceIdOperationCompleted, userState);
+ }
+
+ private void OnGetInstalledLanguagePacksByServiceIdOperationCompleted(object arg) {
+ if ((this.GetInstalledLanguagePacksByServiceIdCompleted != null)) {
+ System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
+ this.GetInstalledLanguagePacksByServiceIdCompleted(this, new GetInstalledLanguagePacksByServiceIdCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
+ }
+ }
+
///
public new void CancelAsync(object userState) {
base.CancelAsync(userState);
@@ -967,6 +1143,32 @@ namespace WebsitePanel.EnterpriseServer {
}
}
+ ///
+ [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
+ public delegate void GetCollationByServiceIdCompletedEventHandler(object sender, GetCollationByServiceIdCompletedEventArgs e);
+
+ ///
+ [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
+ [System.Diagnostics.DebuggerStepThroughAttribute()]
+ [System.ComponentModel.DesignerCategoryAttribute("code")]
+ public partial class GetCollationByServiceIdCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
+
+ private object[] results;
+
+ internal GetCollationByServiceIdCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
+ base(exception, cancelled, userState) {
+ this.results = results;
+ }
+
+ ///
+ public StringArrayResultObject Result {
+ get {
+ this.RaiseExceptionIfNecessary();
+ return ((StringArrayResultObject)(this.results[0]));
+ }
+ }
+ }
+
///
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void GetCurrencyCompletedEventHandler(object sender, GetCurrencyCompletedEventArgs e);
@@ -993,6 +1195,32 @@ namespace WebsitePanel.EnterpriseServer {
}
}
+ ///
+ [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
+ public delegate void GetCurrencyByServiceIdCompletedEventHandler(object sender, GetCurrencyByServiceIdCompletedEventArgs e);
+
+ ///
+ [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
+ [System.Diagnostics.DebuggerStepThroughAttribute()]
+ [System.ComponentModel.DesignerCategoryAttribute("code")]
+ public partial class GetCurrencyByServiceIdCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
+
+ private object[] results;
+
+ internal GetCurrencyByServiceIdCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
+ base(exception, cancelled, userState) {
+ this.results = results;
+ }
+
+ ///
+ public CurrencyArrayResultObject Result {
+ get {
+ this.RaiseExceptionIfNecessary();
+ return ((CurrencyArrayResultObject)(this.results[0]));
+ }
+ }
+ }
+
///
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void DeleteCRMOrganizationCompletedEventHandler(object sender, DeleteCRMOrganizationCompletedEventArgs e);
@@ -1330,4 +1558,56 @@ namespace WebsitePanel.EnterpriseServer {
}
}
}
+
+ ///
+ [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
+ public delegate void GetInstalledLanguagePacksCompletedEventHandler(object sender, GetInstalledLanguagePacksCompletedEventArgs e);
+
+ ///
+ [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
+ [System.Diagnostics.DebuggerStepThroughAttribute()]
+ [System.ComponentModel.DesignerCategoryAttribute("code")]
+ public partial class GetInstalledLanguagePacksCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
+
+ private object[] results;
+
+ internal GetInstalledLanguagePacksCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
+ base(exception, cancelled, userState) {
+ this.results = results;
+ }
+
+ ///
+ public int[] Result {
+ get {
+ this.RaiseExceptionIfNecessary();
+ return ((int[])(this.results[0]));
+ }
+ }
+ }
+
+ ///
+ [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
+ public delegate void GetInstalledLanguagePacksByServiceIdCompletedEventHandler(object sender, GetInstalledLanguagePacksByServiceIdCompletedEventArgs e);
+
+ ///
+ [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
+ [System.Diagnostics.DebuggerStepThroughAttribute()]
+ [System.ComponentModel.DesignerCategoryAttribute("code")]
+ public partial class GetInstalledLanguagePacksByServiceIdCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
+
+ private object[] results;
+
+ internal GetInstalledLanguagePacksByServiceIdCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
+ base(exception, cancelled, userState) {
+ this.results = results;
+ }
+
+ ///
+ public int[] Result {
+ get {
+ this.RaiseExceptionIfNecessary();
+ return ((int[])(this.results[0]));
+ }
+ }
+ }
}
diff --git a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer.Code/HostedSolution/CRMController.cs b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer.Code/HostedSolution/CRMController.cs
index 6ca779d3..9679be40 100644
--- a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer.Code/HostedSolution/CRMController.cs
+++ b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer.Code/HostedSolution/CRMController.cs
@@ -49,8 +49,19 @@ namespace WebsitePanel.EnterpriseServer
}
private static int GetCRMServiceId(int packageId)
- {
- int serviceId = PackageController.GetPackageServiceId(packageId, ResourceGroups.HostedCRM);
+ {
+ int serviceId = PackageController.GetPackageServiceId(packageId, ResourceGroups.HostedCRM2013);
+ if (serviceId == 0)
+ serviceId = PackageController.GetPackageServiceId(packageId, ResourceGroups.HostedCRM);
+ return serviceId;
+ }
+
+ private static int GetCRMServiceId(int packageId, ResultObject res)
+ {
+ int serviceId = GetCRMServiceId(packageId);
+ if (serviceId == 0)
+ CompleteTask(res, CrmErrorCodes.CRM_IS_NOT_SELECTED_IN_HOSTING_PLAN, null,
+ "CRM is not selected in hosting plan.");
return serviceId;
}
@@ -226,7 +237,7 @@ namespace WebsitePanel.EnterpriseServer
return value;
}
- public static OrganizationResult CreateOrganization(int organizationId, string baseCurrencyCode, string baseCurrencyName, string baseCurrencySymbol, string regionName, int userId, string collation)
+ public static OrganizationResult CreateOrganization(int organizationId, string baseCurrencyCode, string baseCurrencyName, string baseCurrencySymbol, string regionName, int userId, string collation, int baseLanguageCode)
{
OrganizationResult res = StartTask("CRM", "CREATE_ORGANIZATION");
@@ -269,7 +280,12 @@ namespace WebsitePanel.EnterpriseServer
string rootOU = GetProviderProperty(serviceid, "rootou");
PackageContext cntx = PackageController.GetPackageContext(org.PackageId);
- long maxDBSize = cntx.Quotas[Quotas.CRM_MAXDATABASESIZE].QuotaAllocatedValue;
+
+ string maxDBSizeQuotaName = "";
+ if (cntx.Groups.ContainsKey(ResourceGroups.HostedCRM2013)) maxDBSizeQuotaName = Quotas.CRM2013_MAXDATABASESIZE;
+ else if (cntx.Groups.ContainsKey(ResourceGroups.HostedCRM)) maxDBSizeQuotaName = Quotas.CRM_MAXDATABASESIZE;
+
+ long maxDBSize = cntx.Quotas[maxDBSizeQuotaName].QuotaAllocatedValue;
if (maxDBSize != -1) maxDBSize = maxDBSize * 1024 * 1024;
org.CrmAdministratorId = user.AccountId;
@@ -277,10 +293,12 @@ namespace WebsitePanel.EnterpriseServer
string.Join("|", new[] {baseCurrencyCode, baseCurrencyName, baseCurrencySymbol, regionName});
org.CrmCollation = collation;
org.CrmOrgState = (int) CrmOrganizationState.Enabled;
+ org.CrmLanguadgeCode = baseLanguageCode.ToString();
org.CrmOrganizationId = orgId;
OrganizationResult serverRes =
crm.CreateOrganization(orgId, org.OrganizationId, org.Name,
+ baseLanguageCode,
org.OrganizationId + "." + rootOU,
baseCurrencyCode, baseCurrencyName,
baseCurrencySymbol, user.SamAccountName, user.FirstName, user.LastName, user.PrimaryEmailAddress,
@@ -343,19 +361,35 @@ namespace WebsitePanel.EnterpriseServer
return res;
}
- public static StringArrayResultObject GetCollationNames(int packageId)
+ public static StringArrayResultObject GetCollationByServiceId(int serviceId)
+ {
+ StringArrayResultObject ret = StartTask("CRM", "GET_COLLATION_NAMES");
+ ret.IsSuccess = true;
+ try
+ {
+ CRM crm = new CRM();
+ ServiceProviderProxy.Init(crm, serviceId);
+ ret.Value = crm.GetSupportedCollationNames();
+ }
+ catch (Exception ex)
+ {
+ CompleteTask(ret, CrmErrorCodes.CANNOT_GET_COLLATION_NAMES, ex);
+ return ret;
+ }
+ CompleteTask();
+ return ret;
+ }
+
+ public static StringArrayResultObject GetCollation(int packageId)
{
StringArrayResultObject ret = StartTask("CRM", "GET_COLLATION_NAMES");
ret.IsSuccess = true;
try
{
- int serviceId = PackageController.GetPackageServiceId(packageId, ResourceGroups.HostedCRM);
+ int serviceId = GetCRMServiceId(packageId, ret);
if (serviceId == 0)
- {
- CompleteTask(ret, CrmErrorCodes.CRM_IS_NOT_SELECTED_IN_HOSTING_PLAN);
return ret;
- }
CRM crm = new CRM();
ServiceProviderProxy.Init(crm, serviceId);
@@ -372,18 +406,35 @@ namespace WebsitePanel.EnterpriseServer
return ret;
}
+ public static CurrencyArrayResultObject GetCurrencyByServiceId(int serviceId)
+ {
+ CurrencyArrayResultObject ret = StartTask("CRM", "GET_CURRENCY");
+ ret.IsSuccess = true;
+ try
+ {
+ CRM crm = new CRM();
+ ServiceProviderProxy.Init(crm, serviceId);
+ ret.Value = crm.GetCurrencyList();
+ }
+ catch (Exception ex)
+ {
+ CompleteTask(ret, CrmErrorCodes.CANNOT_GET_CURRENCY_LIST, ex);
+ return ret;
+ }
+ CompleteTask();
+
+ return ret;
+ }
+
public static CurrencyArrayResultObject GetCurrency(int packageId)
{
CurrencyArrayResultObject ret = StartTask("CRM", "GET_CURRENCY");
ret.IsSuccess = true;
try
{
- int serviceId = PackageController.GetPackageServiceId(packageId, ResourceGroups.HostedCRM);
+ int serviceId = GetCRMServiceId(packageId, ret);
if (serviceId == 0)
- {
- CompleteTask(ret, CrmErrorCodes.CRM_IS_NOT_SELECTED_IN_HOSTING_PLAN, null, "CRM is not selected in hosting plan.");
return ret;
- }
CRM crm = new CRM();
ServiceProviderProxy.Init(crm, serviceId);
@@ -550,9 +601,12 @@ namespace WebsitePanel.EnterpriseServer
PackageContext cntx = PackageController.GetPackageContext(packageId);
- return (cntx.Quotas[Quotas.CRM_ORGANIZATION] != null && !cntx.Quotas[Quotas.CRM_ORGANIZATION].QuotaExhausted);
-
-
+
+ string quotaName = "";
+ if (cntx.Groups.ContainsKey(ResourceGroups.HostedCRM2013)) quotaName = Quotas.CRM2013_ORGANIZATION;
+ else if (cntx.Groups.ContainsKey(ResourceGroups.HostedCRM)) quotaName = Quotas.CRM_ORGANIZATION;
+
+ return (cntx.Quotas[quotaName] != null && !cntx.Quotas[quotaName].QuotaExhausted);
}
catch(Exception ex)
@@ -676,19 +730,22 @@ namespace WebsitePanel.EnterpriseServer
if (!quotaRes.Value)
{
- CompleteTask(ret, CrmErrorCodes.USER_QUOTA_HAS_BEEN_REACHED + CALType.ToString(), null, "CRM user quota has been reached.");
+ string errorCode = CrmErrorCodes.USER_QUOTA_HAS_BEEN_REACHED;
+ PackageContext cntx = PackageController.GetPackageContext(packageId);
+ if (cntx.Groups.ContainsKey(ResourceGroups.HostedCRM2013))
+ errorCode += "2013_";
+ errorCode += CALType.ToString();
+
+ CompleteTask(ret, errorCode , null, "CRM user quota has been reached.");
return ret;
}
Guid crmId;
try
{
- int serviceId = PackageController.GetPackageServiceId(packageId, ResourceGroups.HostedCRM);
+ int serviceId = GetCRMServiceId(packageId, ret);
if (serviceId == 0)
- {
- CompleteTask(ret, CrmErrorCodes.CRM_IS_NOT_SELECTED_IN_HOSTING_PLAN, null, "CRM is not selected in hosting plan.");
return ret;
- }
Organization org = OrganizationController.GetOrganization(itemId);
@@ -735,12 +792,9 @@ namespace WebsitePanel.EnterpriseServer
CRMBusinessUnitsResult res = StartTask("CRM", "GET_CRM_BUSINESS_UNITS");
try
{
- int serviceId = PackageController.GetPackageServiceId(packageId, ResourceGroups.HostedCRM);
+ int serviceId = GetCRMServiceId(packageId, res);
if (serviceId == 0)
- {
- CompleteTask(res, CrmErrorCodes.CRM_IS_NOT_SELECTED_IN_HOSTING_PLAN, null, "CRM is not selected in hosting plan.");
return res;
- }
Organization org;
try
@@ -784,12 +838,9 @@ namespace WebsitePanel.EnterpriseServer
try
{
- int serviceId = PackageController.GetPackageServiceId(packageId, ResourceGroups.HostedCRM);
+ int serviceId = GetCRMServiceId(packageId, res);
if (serviceId == 0)
- {
- CompleteTask(res, CrmErrorCodes.CRM_IS_NOT_SELECTED_IN_HOSTING_PLAN, null, "CRM is not selected in hosting plan.");
return res;
- }
CRM crm = new CRM();
ServiceProviderProxy.Init(crm, serviceId);
@@ -874,13 +925,9 @@ namespace WebsitePanel.EnterpriseServer
}
- int serviceId = PackageController.GetPackageServiceId(org.PackageId, ResourceGroups.HostedCRM);
+ int serviceId = GetCRMServiceId(org.PackageId, res);
if (serviceId == 0)
- {
- CompleteTask(res, CrmErrorCodes.CRM_IS_NOT_SELECTED_IN_HOSTING_PLAN, null,
- "CRM is not selected in hosting plan.");
return res;
- }
try
{
@@ -919,13 +966,9 @@ namespace WebsitePanel.EnterpriseServer
try
{
- int serviceId = PackageController.GetPackageServiceId(packageId, ResourceGroups.HostedCRM);
+ int serviceId = GetCRMServiceId(packageId, res);
if (serviceId == 0)
- {
- CompleteTask(res, CrmErrorCodes.CRM_IS_NOT_SELECTED_IN_HOSTING_PLAN, null,
- "CRM is not selected in hosting plan.");
return res;
- }
CRM crm = new CRM();
ServiceProviderProxy.Init(crm, serviceId);
@@ -978,13 +1021,9 @@ namespace WebsitePanel.EnterpriseServer
return res;
}
- int serviceId = PackageController.GetPackageServiceId(packageId, ResourceGroups.HostedCRM);
+ int serviceId = GetCRMServiceId(packageId, res);
if (serviceId == 0)
- {
- CompleteTask(res, CrmErrorCodes.CRM_IS_NOT_SELECTED_IN_HOSTING_PLAN, null,
- "CRM is not selected in hosting plan.");
return res;
- }
CRM crm = new CRM();
ServiceProviderProxy.Init(crm, serviceId);
@@ -1012,7 +1051,13 @@ namespace WebsitePanel.EnterpriseServer
}
if (!quotaRes.Value)
{
- CompleteTask(res, CrmErrorCodes.USER_QUOTA_HAS_BEEN_REACHED + CALType.ToString(), null, "CRM user quota has been reached.");
+ string errorCode = CrmErrorCodes.USER_QUOTA_HAS_BEEN_REACHED;
+ PackageContext cntx = PackageController.GetPackageContext(packageId);
+ if (cntx.Groups.ContainsKey(ResourceGroups.HostedCRM2013))
+ errorCode += "2013_";
+ errorCode += CALType.ToString();
+
+ CompleteTask(res, errorCode, null, "CRM user quota has been reached.");
return res;
}
@@ -1058,13 +1103,9 @@ namespace WebsitePanel.EnterpriseServer
return res;
}
- int serviceId = PackageController.GetPackageServiceId(org.PackageId, ResourceGroups.HostedCRM);
+ int serviceId = GetCRMServiceId(org.PackageId, res);
if (serviceId == 0)
- {
- CompleteTask(res, CrmErrorCodes.CRM_IS_NOT_SELECTED_IN_HOSTING_PLAN, null,
- "CRM is not selected in hosting plan.");
return res;
- }
CRM crm = new CRM();
ServiceProviderProxy.Init(crm, serviceId);
@@ -1105,19 +1146,37 @@ namespace WebsitePanel.EnterpriseServer
return res;
}
- string quotaName = Quotas.CRM_USERS;
+ string quotaName = "";
- switch (CALType)
+ if (cntx.Groups.ContainsKey(ResourceGroups.HostedCRM2013))
{
- case 0:
- quotaName = Quotas.CRM_USERS;
- break;
- case 2:
- quotaName = Quotas.CRM_LIMITEDUSERS;
- break;
- case 22:
- quotaName = Quotas.CRM_ESSUSERS;
- break;
+ switch (CALType)
+ {
+ case CRMUserLycenseTypes.PROFESSIONAL:
+ quotaName = Quotas.CRM2013_PROFESSIONALUSERS;
+ break;
+ case CRMUserLycenseTypes.BASIC:
+ quotaName = Quotas.CRM2013_BASICUSERS;
+ break;
+ case CRMUserLycenseTypes.ESSENTIAL:
+ quotaName = Quotas.CRM2013_ESSENTIALUSERS;
+ break;
+ }
+ }
+ else if (cntx.Groups.ContainsKey(ResourceGroups.HostedCRM))
+ {
+ switch (CALType)
+ {
+ case CRMUserLycenseTypes.FULL:
+ quotaName = Quotas.CRM_USERS;
+ break;
+ case CRMUserLycenseTypes.LIMITED:
+ quotaName = Quotas.CRM_LIMITEDUSERS;
+ break;
+ case CRMUserLycenseTypes.ESS:
+ quotaName = Quotas.CRM_ESSUSERS;
+ break;
+ }
}
int allocatedCrmUsers = cntx.Quotas[quotaName].QuotaAllocatedValue;
@@ -1137,18 +1196,14 @@ namespace WebsitePanel.EnterpriseServer
public static ResultObject SetMaxDBSize(int itemId, int packageId, long maxSize)
{
- ResultObject res = StartTask("CRM", "SET_CRM_MAXDBSIZE");
+ ResultObject res = StartTask("CRM", "SET_CRM_MAXDBSIZE");
try
{
- int serviceId = PackageController.GetPackageServiceId(packageId, ResourceGroups.HostedCRM);
+ int serviceId = GetCRMServiceId(packageId, res);
if (serviceId == 0)
- {
- CompleteTask(res, CrmErrorCodes.CRM_IS_NOT_SELECTED_IN_HOSTING_PLAN, null,
- "CRM is not selected in hosting plan.");
return res;
- }
CRM crm = new CRM();
ServiceProviderProxy.Init(crm, serviceId);
@@ -1169,7 +1224,11 @@ namespace WebsitePanel.EnterpriseServer
PackageContext cntx = PackageController.GetPackageContext(packageId);
- long limitSize = cntx.Quotas[Quotas.CRM_MAXDATABASESIZE].QuotaAllocatedValue;
+ string quotaName = "";
+ if (cntx.Groups.ContainsKey(ResourceGroups.HostedCRM2013)) quotaName = Quotas.CRM2013_MAXDATABASESIZE;
+ else if (cntx.Groups.ContainsKey(ResourceGroups.HostedCRM)) quotaName = Quotas.CRM_MAXDATABASESIZE;
+
+ long limitSize = cntx.Quotas[quotaName].QuotaAllocatedValue;
if (limitSize != -1)
{
@@ -1199,19 +1258,15 @@ namespace WebsitePanel.EnterpriseServer
public static long GetDBSize(int itemId, int packageId)
{
- ResultObject res = StartTask("CRM", "GET_CRM_DBSIZE");
+ ResultObject res = StartTask("CRM", "GET_CRM_DBSIZE");
long size = -1;
try
{
- int serviceId = PackageController.GetPackageServiceId(packageId, ResourceGroups.HostedCRM);
+ int serviceId = GetCRMServiceId(packageId, res);
if (serviceId == 0)
- {
- CompleteTask(res, CrmErrorCodes.CRM_IS_NOT_SELECTED_IN_HOSTING_PLAN, null,
- "CRM is not selected in hosting plan.");
return -1;
- }
CRM crm = new CRM();
ServiceProviderProxy.Init(crm, serviceId);
@@ -1244,19 +1299,15 @@ namespace WebsitePanel.EnterpriseServer
public static long GetMaxDBSize(int itemId, int packageId)
{
- ResultObject res = StartTask("CRM", "GET_CRM_MAXDBSIZE");
+ ResultObject res = StartTask("CRM", "GET_CRM_MAXDBSIZE");
long size = -1;
try
{
- int serviceId = PackageController.GetPackageServiceId(packageId, ResourceGroups.HostedCRM);
+ int serviceId = GetCRMServiceId(packageId, res);
if (serviceId == 0)
- {
- CompleteTask(res, CrmErrorCodes.CRM_IS_NOT_SELECTED_IN_HOSTING_PLAN, null,
- "CRM is not selected in hosting plan.");
return -1;
- }
CRM crm = new CRM();
ServiceProviderProxy.Init(crm, serviceId);
@@ -1287,5 +1338,52 @@ namespace WebsitePanel.EnterpriseServer
return size;
}
+
+ public static int[] GetInstalledLanguagePacks(int packageId)
+ {
+ ResultObject res = StartTask("CRM", "GET_CRM_MAXDBSIZE");
+ int[] ret = null;
+
+ try
+ {
+ int serviceId = GetCRMServiceId(packageId, res);
+ if (serviceId == 0)
+ return null;
+
+ CRM crm = new CRM();
+ ServiceProviderProxy.Init(crm, serviceId);
+
+ ret = crm.GetInstalledLanguagePacks();
+ }
+ catch (Exception ex)
+ {
+ CompleteTask(res, CrmErrorCodes.CANNOT_CONFIGURE_CRM_ORGANIZATION, ex);
+ return null;
+ }
+ CompleteTask();
+ return ret;
+ }
+
+ public static int[] GetInstalledLanguagePacksByServiceId(int serviceId)
+ {
+ ResultObject res = StartTask("CRM", "GET_CRM_MAXDBSIZE");
+ int[] ret = null;
+
+ try
+ {
+ CRM crm = new CRM();
+ ServiceProviderProxy.Init(crm, serviceId);
+
+ ret = crm.GetInstalledLanguagePacks();
+ }
+ catch (Exception ex)
+ {
+ CompleteTask(res, CrmErrorCodes.CANNOT_CONFIGURE_CRM_ORGANIZATION, ex);
+ return null;
+ }
+ CompleteTask();
+ return ret;
+ }
+
}
}
diff --git a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer.Code/HostedSolution/OrganizationController.cs b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer.Code/HostedSolution/OrganizationController.cs
index 4239f90a..3a992ff8 100644
--- a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer.Code/HostedSolution/OrganizationController.cs
+++ b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer.Code/HostedSolution/OrganizationController.cs
@@ -932,12 +932,20 @@ namespace WebsitePanel.EnterpriseServer
if (cntxTmp.Groups.ContainsKey(ResourceGroups.HostedCRM))
{
- stats.CreatedCRMUsers = CRMController.GetCRMUsersCount(org.Id, string.Empty, string.Empty, 0).Value;
- stats.CreatedLimitedCRMUsers = CRMController.GetCRMUsersCount(org.Id, string.Empty, string.Empty, 2).Value;
- stats.CreatedESSCRMUsers = CRMController.GetCRMUsersCount(org.Id, string.Empty, string.Empty, 22).Value;
+ stats.CreatedCRMUsers = CRMController.GetCRMUsersCount(org.Id, string.Empty, string.Empty, CRMUserLycenseTypes.FULL).Value;
+ stats.CreatedLimitedCRMUsers = CRMController.GetCRMUsersCount(org.Id, string.Empty, string.Empty, CRMUserLycenseTypes.LIMITED).Value;
+ stats.CreatedESSCRMUsers = CRMController.GetCRMUsersCount(org.Id, string.Empty, string.Empty, CRMUserLycenseTypes.ESS).Value;
+ stats.UsedCRMDiskSpace = CRMController.GetDBSize(org.Id, org.PackageId);
+ stats.AllocatedCRMDiskSpace = CRMController.GetMaxDBSize(org.Id, org.PackageId);
+ }
+
+ if (cntxTmp.Groups.ContainsKey(ResourceGroups.HostedCRM2013))
+ {
+ stats.CreatedProfessionalCRMUsers = CRMController.GetCRMUsersCount(org.Id, string.Empty, string.Empty, CRMUserLycenseTypes.PROFESSIONAL).Value;
+ stats.CreatedBasicCRMUsers = CRMController.GetCRMUsersCount(org.Id, string.Empty, string.Empty, CRMUserLycenseTypes.BASIC).Value;
+ stats.CreatedEssentialCRMUsers = CRMController.GetCRMUsersCount(org.Id, string.Empty, string.Empty, CRMUserLycenseTypes.ESSENTIAL).Value;
stats.UsedCRMDiskSpace = CRMController.GetDBSize(org.Id, org.PackageId);
stats.AllocatedCRMDiskSpace = CRMController.GetMaxDBSize(org.Id, org.PackageId);
-
}
if (cntxTmp.Groups.ContainsKey(ResourceGroups.BlackBerry))
@@ -996,9 +1004,18 @@ namespace WebsitePanel.EnterpriseServer
if (cntxTmp.Groups.ContainsKey(ResourceGroups.HostedCRM))
{
- stats.CreatedCRMUsers += CRMController.GetCRMUsersCount(o.Id, string.Empty, string.Empty, 0 ).Value;
- stats.CreatedLimitedCRMUsers += CRMController.GetCRMUsersCount(o.Id, string.Empty, string.Empty, 2).Value;
- stats.CreatedESSCRMUsers += CRMController.GetCRMUsersCount(o.Id, string.Empty, string.Empty, 22).Value;
+ stats.CreatedCRMUsers += CRMController.GetCRMUsersCount(o.Id, string.Empty, string.Empty, CRMUserLycenseTypes.FULL ).Value;
+ stats.CreatedLimitedCRMUsers += CRMController.GetCRMUsersCount(o.Id, string.Empty, string.Empty, CRMUserLycenseTypes.LIMITED).Value;
+ stats.CreatedESSCRMUsers += CRMController.GetCRMUsersCount(o.Id, string.Empty, string.Empty, CRMUserLycenseTypes.ESS).Value;
+ stats.UsedCRMDiskSpace += CRMController.GetDBSize(o.Id, o.PackageId);
+ stats.AllocatedCRMDiskSpace += CRMController.GetMaxDBSize(o.Id, o.PackageId);
+ }
+
+ if (cntxTmp.Groups.ContainsKey(ResourceGroups.HostedCRM2013))
+ {
+ stats.CreatedProfessionalCRMUsers += CRMController.GetCRMUsersCount(o.Id, string.Empty, string.Empty, CRMUserLycenseTypes.PROFESSIONAL).Value;
+ stats.CreatedBasicCRMUsers += CRMController.GetCRMUsersCount(o.Id, string.Empty, string.Empty, CRMUserLycenseTypes.BASIC).Value;
+ stats.CreatedEssentialCRMUsers += CRMController.GetCRMUsersCount(o.Id, string.Empty, string.Empty, CRMUserLycenseTypes.ESSENTIAL).Value;
stats.UsedCRMDiskSpace += CRMController.GetDBSize(o.Id, o.PackageId);
stats.AllocatedCRMDiskSpace += CRMController.GetMaxDBSize(o.Id, o.PackageId);
}
@@ -1049,6 +1066,13 @@ namespace WebsitePanel.EnterpriseServer
stats.AllocatedESSCRMUsers = cntx.Quotas[Quotas.CRM_ESSUSERS].QuotaAllocatedValue;
}
+ if (cntx.Groups.ContainsKey(ResourceGroups.HostedCRM2013))
+ {
+ stats.AllocatedProfessionalCRMUsers = cntx.Quotas[Quotas.CRM2013_PROFESSIONALUSERS].QuotaAllocatedValue;
+ stats.AllocatedBasicCRMUsers = cntx.Quotas[Quotas.CRM2013_BASICUSERS].QuotaAllocatedValue;
+ stats.AllocatedEssentialCRMUsers = cntx.Quotas[Quotas.CRM2013_ESSENTIALUSERS].QuotaAllocatedValue;
+ }
+
if (cntx.Groups.ContainsKey(ResourceGroups.BlackBerry))
{
stats.AllocatedBlackBerryUsers = cntx.Quotas[Quotas.BLACKBERRY_USERS].QuotaAllocatedValue;
diff --git a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/esCRM.asmx.cs b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/esCRM.asmx.cs
index e7f3d8de..491875e6 100644
--- a/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/esCRM.asmx.cs
+++ b/WebsitePanel/Sources/WebsitePanel.EnterpriseServer/esCRM.asmx.cs
@@ -48,24 +48,34 @@ namespace WebsitePanel.EnterpriseServer
{
[WebMethod]
- public OrganizationResult CreateOrganization(int organizationId, string baseCurrencyCode, string baseCurrencyName, string baseCurrencySymbol, string regionName, int userId, string collation)
+ public OrganizationResult CreateOrganization(int organizationId, string baseCurrencyCode, string baseCurrencyName, string baseCurrencySymbol, string regionName, int userId, string collation, int baseLanguageCode)
{
- return CRMController.CreateOrganization(organizationId, baseCurrencyCode, baseCurrencyName, baseCurrencySymbol, regionName, userId, collation);
+ return CRMController.CreateOrganization(organizationId, baseCurrencyCode, baseCurrencyName, baseCurrencySymbol, regionName, userId, collation, baseLanguageCode);
}
-
[WebMethod]
public StringArrayResultObject GetCollation(int packageId)
{
- return CRMController.GetCollationNames(packageId);
+ return CRMController.GetCollation(packageId);
+ }
+
+ [WebMethod]
+ public StringArrayResultObject GetCollationByServiceId(int serviceId)
+ {
+ return CRMController.GetCollationByServiceId(serviceId);
}
[WebMethod]
public CurrencyArrayResultObject GetCurrency(int packageId)
{
-
return CRMController.GetCurrency(packageId);
}
+
+ [WebMethod]
+ public CurrencyArrayResultObject GetCurrencyByServiceId(int serviceId)
+ {
+ return CRMController.GetCurrencyByServiceId(serviceId);
+ }
[WebMethod]
public ResultObject DeleteCRMOrganization(int organizationId)
@@ -149,5 +159,17 @@ namespace WebsitePanel.EnterpriseServer
return CRMController.GetMaxDBSize(itemId, packageId);
}
+ [WebMethod]
+ public int[] GetInstalledLanguagePacks(int packageId)
+ {
+ return CRMController.GetInstalledLanguagePacks(packageId);
+ }
+
+ [WebMethod]
+ public int[] GetInstalledLanguagePacksByServiceId(int serviceId)
+ {
+ return CRMController.GetInstalledLanguagePacksByServiceId(serviceId);
+ }
+
}
}
diff --git a/WebsitePanel/Sources/WebsitePanel.Providers.Base/Common/Constants.cs b/WebsitePanel/Sources/WebsitePanel.Providers.Base/Common/Constants.cs
index d99847d0..165991a2 100644
--- a/WebsitePanel/Sources/WebsitePanel.Providers.Base/Common/Constants.cs
+++ b/WebsitePanel/Sources/WebsitePanel.Providers.Base/Common/Constants.cs
@@ -74,6 +74,11 @@ namespace WebsitePanel.Providers.Common
public const string UsersHome = "UsersHome";
-
+ public const string Collation = "Collation";
+
+ public const string Currency = "Currency";
+
+ public const string BaseLanguage = "BaseLanguage";
+
}
}
diff --git a/WebsitePanel/Sources/WebsitePanel.Providers.Base/HostedSolution/ICRM.cs b/WebsitePanel/Sources/WebsitePanel.Providers.Base/HostedSolution/ICRM.cs
index 0808f1b8..ef0f3e83 100644
--- a/WebsitePanel/Sources/WebsitePanel.Providers.Base/HostedSolution/ICRM.cs
+++ b/WebsitePanel/Sources/WebsitePanel.Providers.Base/HostedSolution/ICRM.cs
@@ -35,6 +35,7 @@ namespace WebsitePanel.Providers.HostedSolution
public interface ICRM
{
OrganizationResult CreateOrganization(Guid organizationId, string organizationUniqueName, string organizationFriendlyName,
+ int baseLanguageCode,
string ou,
string baseCurrencyCode, string baseCurrencyName, string baseCurrencySymbol,
string initialUserDomainName, string initialUserFirstName, string initialUserLastName, string initialUserPrimaryEmail,
@@ -44,6 +45,8 @@ namespace WebsitePanel.Providers.HostedSolution
string[] GetSupportedCollationNames();
Currency[] GetCurrencyList();
+
+ int[] GetInstalledLanguagePacks();
ResultObject DeleteOrganization(Guid orgId);
diff --git a/WebsitePanel/Sources/WebsitePanel.Providers.Base/HostedSolution/OrganizationStatistics.cs b/WebsitePanel/Sources/WebsitePanel.Providers.Base/HostedSolution/OrganizationStatistics.cs
index b107d59a..a68cb77a 100644
--- a/WebsitePanel/Sources/WebsitePanel.Providers.Base/HostedSolution/OrganizationStatistics.cs
+++ b/WebsitePanel/Sources/WebsitePanel.Providers.Base/HostedSolution/OrganizationStatistics.cs
@@ -75,7 +75,53 @@ namespace WebsitePanel.Providers.HostedSolution
private int allocatedEnterpriseStorageSpace;
private int usedEnterpriseStorageSpace;
-
+
+ private int createdProfessionalCRMUsers;
+ private int allocatedProfessionalCRMUsers;
+
+ public int CreatedProfessionalCRMUsers
+ {
+ get { return createdProfessionalCRMUsers; }
+ set { createdProfessionalCRMUsers = value; }
+ }
+
+ public int AllocatedProfessionalCRMUsers
+ {
+ get { return allocatedProfessionalCRMUsers; }
+ set { allocatedProfessionalCRMUsers = value; }
+ }
+
+
+ private int createdBasicCRMUsers;
+ private int allocatedBasicCRMUsers;
+
+ public int CreatedBasicCRMUsers
+ {
+ get { return createdBasicCRMUsers; }
+ set { createdBasicCRMUsers = value; }
+ }
+
+ public int AllocatedBasicCRMUsers
+ {
+ get { return allocatedBasicCRMUsers; }
+ set { allocatedBasicCRMUsers = value; }
+ }
+
+ private int createdEssentialCRMUsers;
+ private int allocatedEssentialCRMUsers;
+
+ public int CreatedEssentialCRMUsers
+ {
+ get { return createdEssentialCRMUsers; }
+ set { createdEssentialCRMUsers = value; }
+ }
+
+ public int AllocatedEssentialCRMUsers
+ {
+ get { return allocatedEssentialCRMUsers; }
+ set { allocatedEssentialCRMUsers = value; }
+ }
+
public int CreatedCRMUsers
{
diff --git a/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution.Crm2011/CRMBase.cs b/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution.Crm2011/CRMBase.cs
new file mode 100644
index 00000000..c07b7594
--- /dev/null
+++ b/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution.Crm2011/CRMBase.cs
@@ -0,0 +1,2096 @@
+// Copyright (c) 2012 - 2013, 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.Data;
+using System.Data.SqlClient;
+using System.Globalization;
+using System.IO;
+using System.Net;
+using System.Reflection;
+using System.Net.Security;
+using System.Security.Principal;
+using System.Security.Cryptography.X509Certificates;
+using System.Threading;
+using System.ServiceModel.Description;
+using System.Text.RegularExpressions;
+using Microsoft.Win32;
+using WebsitePanel.Providers.Common;
+using WebsitePanel.Providers.ResultObjects;
+using WebsitePanel.Server.Utils;
+using WebsitePanel.Providers.HostedSolution;
+using WebsitePanel.Providers;
+using WebsitePanel.Providers.Utils;
+using Microsoft.Xrm.Sdk;
+using Microsoft.Xrm.Sdk.Query;
+using Microsoft.Xrm.Sdk.Discovery;
+using Microsoft.Xrm.Sdk.Client;
+using Microsoft.Xrm.Sdk.Deployment;
+using Microsoft.Xrm.Sdk.Messages;
+
+namespace WebsitePanel.Providers.HostedSolution
+{
+ public class CRMBase : HostingServiceProviderBase, ICRM
+ {
+ #region Properties
+
+ protected virtual string UserName
+ {
+ get { return ProviderSettings[Constants.UserName]; }
+ }
+
+ protected virtual string Password
+ {
+ get { return ProviderSettings[Constants.Password]; }
+ }
+
+ protected virtual string SqlServer
+ {
+ get { return ProviderSettings[Constants.SqlServer]; }
+ }
+
+ protected virtual string ReportingServer
+ {
+ get { return ProviderSettings[Constants.ReportingServer]; }
+ }
+
+ protected virtual string UrlSchema
+ {
+ get { return ProviderSettings[Constants.UrlSchema] == "http" ? "http://" : "https://"; }
+ }
+
+ protected virtual string CRMDeploymentUrl
+ {
+ get
+ {
+ string uri = ProviderSettings[Constants.DeploymentWebService];
+ if (String.IsNullOrEmpty(uri)) uri = ProviderSettings[Constants.AppRootDomain];
+ string cRMServiceUrl = UrlSchema + uri + ":" + ProviderSettings[Constants.Port] + "/XRMDeployment/2011/Deployment.svc";
+ return cRMServiceUrl;
+ }
+ }
+
+ protected virtual string CRMDiscoveryUrl
+ {
+ get
+ {
+ string uri = ProviderSettings[Constants.DiscoveryWebService];
+ if (String.IsNullOrEmpty(uri)) uri = ProviderSettings[Constants.AppRootDomain];
+ string cRMDiscoveryUri = UrlSchema + uri + ":" + ProviderSettings[Constants.Port] + "/XRMServices/2011/Discovery.svc";
+ return cRMDiscoveryUri;
+ }
+ }
+
+ private static string crmPath = null;
+ protected static string CRMPath
+ {
+ get
+ {
+ if (string.IsNullOrEmpty(crmPath))
+ {
+ RegistryKey root = Registry.LocalMachine;
+ RegistryKey rk = root.OpenSubKey("SOFTWARE\\Microsoft\\MSCRM");
+ if (rk != null)
+ {
+ crmPath = (string)rk.GetValue("CRM_Server_InstallDir", string.Empty);
+ }
+ }
+ return crmPath;
+ }
+ }
+
+ protected static string CRMDatabaseName = "MSCRM_CONFIG";
+
+ #endregion
+
+ #region Service
+
+ protected virtual ClientCredentials GetUserLogonCredentials()
+ {
+ ClientCredentials credentials = new ClientCredentials();
+
+ if (String.IsNullOrEmpty(UserName))
+ {
+ credentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials;
+ }
+ else
+ {
+ credentials.UserName.UserName = UserName;
+ credentials.UserName.Password = Password;
+ }
+
+ return credentials;
+ }
+
+ protected virtual DeploymentServiceClient GetDeploymentProxy()
+ {
+ Uri serviceUrl = new Uri(CRMDeploymentUrl);
+
+ DeploymentServiceClient deploymentService = Microsoft.Xrm.Sdk.Deployment.Proxy.ProxyClientHelper.CreateClient(serviceUrl);
+ if (!String.IsNullOrEmpty(UserName))
+ deploymentService.ClientCredentials.Windows.ClientCredential = new NetworkCredential(UserName, Password);
+
+ return deploymentService;
+ }
+
+ protected virtual DiscoveryServiceProxy GetDiscoveryProxy()
+ {
+
+ IServiceManagement serviceManagement =
+ ServiceConfigurationFactory.CreateManagement(
+ new Uri(CRMDiscoveryUrl));
+
+ ClientCredentials Credentials = GetUserLogonCredentials();
+
+ DiscoveryServiceProxy r = new DiscoveryServiceProxy(serviceManagement, Credentials);
+
+ return r;
+ }
+
+ private OrganizationDetailCollection DiscoverOrganizations(IDiscoveryService service)
+ {
+ if (service == null) throw new ArgumentNullException("service");
+ RetrieveOrganizationsRequest orgRequest = new RetrieveOrganizationsRequest();
+ RetrieveOrganizationsResponse orgResponse =
+ (RetrieveOrganizationsResponse)service.Execute(orgRequest);
+
+ return orgResponse.Details;
+ }
+
+ protected virtual Uri GetCRMOrganizationUrl(string orgName)
+ {
+ //string url = "https://" + ProviderSettings[Constants.AppRootDomain] + ":" + ProviderSettings[Constants.Port] + "/" + orgName + "/XRMServices/2011/Organization.svc";
+
+ string url;
+
+ string organizationWebServiceUri = ProviderSettings[Constants.OrganizationWebService];
+
+ if (String.IsNullOrEmpty(orgName))
+ return null;
+
+ if (!String.IsNullOrEmpty(organizationWebServiceUri))
+ {
+ url = UrlSchema + organizationWebServiceUri + ":" + ProviderSettings[Constants.Port] + "/" + orgName + "/XRMServices/2011/Organization.svc";
+ }
+ else
+ {
+ url = UrlSchema + orgName + "." + ProviderSettings[Constants.IFDWebApplicationRootDomain] + ":" + ProviderSettings[Constants.Port] + "/XRMServices/2011/Organization.svc";
+ }
+
+ try
+ {
+
+ using (DiscoveryServiceProxy serviceProxy = GetDiscoveryProxy())
+ {
+ // Obtain organization information from the Discovery service.
+ if (serviceProxy != null)
+ {
+ // Obtain information about the organizations that the system user belongs to.
+ OrganizationDetailCollection orgs = DiscoverOrganizations(serviceProxy);
+
+ for (int n = 0; n < orgs.Count; n++)
+ {
+ if (orgs[n].UniqueName == orgName)
+ {
+ // Return the organization Uri.
+ return new System.Uri(orgs[n].Endpoints[EndpointType.OrganizationService]);
+ }
+ }
+
+ }
+ }
+ }
+ catch { }
+
+ return new Uri(url);
+ }
+
+ private int getOrganizationProxyTryCount = 10;
+ private int getOrganizationProxyTryTimeout = 30000;
+ protected virtual OrganizationServiceProxy GetOrganizationProxy(string orgName)
+ {
+ return GetOrganizationProxy(orgName, getOrganizationProxyTryCount, getOrganizationProxyTryTimeout);
+ }
+
+ protected virtual OrganizationServiceProxy GetOrganizationProxy(string orgName, int TryCount, int TryTimeout)
+ {
+
+ Uri OrganizationUri = GetCRMOrganizationUrl(orgName);
+
+ OrganizationServiceProxy r = null;
+
+ bool success = false;
+ int tryItem = 0;
+ Exception exception = null;
+
+ while (!success)
+ {
+
+ try
+ {
+ // Set IServiceManagement for the current organization.
+ IServiceManagement orgServiceManagement =
+ ServiceConfigurationFactory.CreateManagement(
+ OrganizationUri);
+
+ r = new OrganizationServiceProxy(
+ orgServiceManagement,
+ GetUserLogonCredentials());
+
+ success = true;
+
+ }
+ catch (Exception exc)
+ {
+ Thread.Sleep(TryTimeout);
+ tryItem++;
+ if (tryItem >= TryCount)
+ {
+ exception = exc;
+ success = true;
+ }
+ }
+
+ }
+
+ if (exception != null)
+ throw new ArgumentException(exception.ToString());
+
+ r.EnableProxyTypes();
+
+ return r;
+ }
+
+ #endregion
+
+ #region Static constructor
+
+ static CRMBase()
+ {
+ AppDomain.CurrentDomain.AssemblyResolve += ResolveCRMAssembly;
+ }
+
+ static Assembly ResolveCRMAssembly(object sender, ResolveEventArgs args)
+ {
+ // Ensure we load DLLs only.
+ if (args.Name.ToLower().Contains("microsoft.crm") || args.Name.ToLower().Contains("antixsslibrary") || args.Name.ToLower().Contains("microsoft.xrm"))
+ {
+ string dllName = args.Name.Split(',')[0] + ".dll";
+
+ List paths = new List();
+
+ // assembly location
+ paths.Add( Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().EscapedCodeBase).LocalPath) );
+ // crm tools path
+ paths.Add(CRMPath);
+
+ foreach(string path in paths)
+ {
+ string filename = Path.Combine(path, dllName);
+ if (File.Exists(filename))
+ return Assembly.LoadFrom(filename);
+ }
+ }
+
+ return default(Assembly);
+ }
+
+ #endregion
+
+ #region Check environment
+
+ protected virtual bool CheckCRMWebServicesAccess()
+ {
+ Log.WriteStart("CheckCRMWebServicesAccess");
+ bool ret = false;
+ HttpWebResponse response = null;
+ HttpWebRequest request;
+
+ try
+ {
+ WindowsIdentity.GetCurrent();
+
+ request = WebRequest.Create(CRMDeploymentUrl) as HttpWebRequest;
+
+ if (request != null)
+ {
+ request.UseDefaultCredentials = true;
+ request.Credentials = CredentialCache.DefaultCredentials;
+ response = request.GetResponse() as HttpWebResponse;
+
+ }
+ if (response != null)
+ ret = (response.StatusCode == HttpStatusCode.OK);
+ }
+ catch (Exception ex)
+ {
+ Log.WriteError(ex);
+ ret = false;
+ }
+
+ Log.WriteEnd("CheckCRMWebServicesAccess");
+ return ret;
+ }
+
+ protected virtual bool CheckPermissions()
+ {
+ Log.WriteStart("CheckPermissions");
+ bool res = false;
+ try
+ {
+ string group = "PrivUserGroup";
+ string user = WindowsIdentity.GetCurrent().Name.Split(new char[] { '\\' })[1];
+ res = ActiveDirectoryUtils.IsUserInGroup(user, group);
+ }
+ catch (Exception ex)
+ {
+ Log.WriteError(ex);
+ res = false;
+ }
+
+ Log.WriteEnd("CheckPermissions");
+ return res;
+ }
+
+ protected virtual bool CheckOrganizationUnique(string databaseName, string orgName)
+ {
+ Log.WriteStart("CheckOrganizationUnique");
+ bool res = false;
+
+ SqlConnection connection = null;
+ try
+ {
+ connection = new SqlConnection();
+ connection.ConnectionString =
+ string.Format("Server={1};Initial Catalog={0};Integrated Security=SSPI",
+ databaseName, SqlServer);
+
+ connection.Open();
+
+ string commandText = string.Format("SELECT COUNT(*) FROM dbo.Organization WHERE UniqueName = '{0}'", orgName);
+ SqlCommand command = new SqlCommand(commandText, connection);
+ int count = (int)command.ExecuteScalar();
+ res = count == 0;
+
+
+ }
+ catch (Exception ex)
+ {
+ res = false;
+ Log.WriteError(ex);
+ }
+ finally
+ {
+ if (connection != null)
+ connection.Dispose();
+
+ }
+
+ Log.WriteEnd("CheckOrganizationUnique");
+ return res;
+ }
+
+ protected virtual bool CheckSqlServerConnection()
+ {
+ Log.WriteStart("CheckSqlServerConnection");
+ bool res = false;
+ SqlConnection connection = null;
+ try
+ {
+ connection = new SqlConnection();
+ connection.ConnectionString =
+ string.Format("server={0}; Integrated Security=SSPI",
+ SqlServer);
+
+ connection.Open();
+ res = true;
+ }
+ catch (Exception ex)
+ {
+ Log.WriteError(ex);
+ res = false;
+ }
+ finally
+ {
+ if (connection != null)
+ connection.Dispose();
+ }
+
+ Log.WriteEnd("CheckSqlServerConnection");
+
+ return res;
+ }
+
+ protected virtual bool CheckReportServerConnection()
+ {
+ Log.WriteStart("CheckReportServerConnection");
+ bool ret = false;
+ HttpWebResponse response = null;
+ HttpWebRequest request;
+
+ try
+ {
+ WindowsIdentity.GetCurrent();
+
+ request = WebRequest.Create(ReportingServer) as HttpWebRequest;
+
+ if (request != null)
+ {
+ request.UseDefaultCredentials = true;
+ request.Credentials = CredentialCache.DefaultCredentials;
+ response = request.GetResponse() as HttpWebResponse;
+
+ }
+ if (response != null)
+ ret = (response.StatusCode == HttpStatusCode.OK);
+ }
+ catch (Exception ex)
+ {
+ Log.WriteError(ex);
+ ret = false;
+ }
+
+ Log.WriteEnd("CheckReportServerConnection");
+ return ret;
+ }
+
+ protected virtual OrganizationResult CheckCrmEnvironment(string strDataBaseName, string organizationUniqueName)
+ {
+ OrganizationResult retOrganization = StartLog("CheckCrmEnvironment");
+ bool res = CheckSqlServerConnection();
+
+ if (!res)
+ {
+ EndLog("CheckCrmEnvironment", retOrganization, CrmErrorCodes.CRM_SQL_SERVER_ERROR);
+ return retOrganization;
+ }
+
+ res = CheckOrganizationUnique(strDataBaseName, organizationUniqueName);
+ if (!res)
+ {
+ EndLog("CheckCrmEnvironment", retOrganization, CrmErrorCodes.CRM_ORGANIZATION_ALREADY_EXISTS);
+ return retOrganization;
+ }
+
+ res = CheckReportServerConnection();
+ if (!res)
+ {
+ EndLog("CheckCrmEnvironment", retOrganization, CrmErrorCodes.CRM_REPORT_SERVER_ERROR);
+ return retOrganization;
+ }
+
+ res = CheckPermissions();
+ if (!res)
+ {
+ EndLog("CheckCrmEnvironment", retOrganization, CrmErrorCodes.CRM_PERMISSIONS_ERROR);
+ return retOrganization;
+ }
+
+ res = CheckCRMWebServicesAccess();
+ if (!res)
+ {
+ EndLog("CheckCrmEnvironment", retOrganization, CrmErrorCodes.CRM_WEB_SERVICE_ERROR);
+ return retOrganization;
+ }
+
+ EndLog("CheckCrmEnvironment");
+ return retOrganization;
+ }
+
+ #endregion
+
+ #region DataBase
+
+ protected virtual string GetDataBaseName(Guid organizationId)
+ {
+ string databasename = null;
+
+ SqlConnection connection = null;
+ try
+ {
+ connection = new SqlConnection();
+ connection.ConnectionString =
+ string.Format("Server={1};Initial Catalog={0};Integrated Security=SSPI",
+ CRMDatabaseName, SqlServer);
+
+ connection.Open();
+
+ string commandText = string.Format("SELECT DatabaseName FROM dbo.Organization where id = '{0}'", organizationId);
+ SqlCommand command = new SqlCommand(commandText, connection);
+ object result = command.ExecuteScalar();
+ if (result!=null)
+ databasename = result.ToString();
+
+ }
+ catch (Exception ex)
+ {
+ Log.WriteError(ex);
+ }
+ finally
+ {
+ if (connection != null)
+ connection.Dispose();
+ }
+
+ return databasename;
+ }
+
+ public virtual long GetDBSize(Guid organizationId)
+ {
+ StartLog("GetDBSize");
+ long res = 0;
+
+ string databasename = GetDataBaseName(organizationId);
+ if (databasename == null) return 0;
+
+ if (databasename == null) return 0;
+
+ SqlConnection connection = null;
+ try
+ {
+ connection = new SqlConnection();
+ connection.ConnectionString =
+ string.Format("Server={1};Initial Catalog={0};Integrated Security=SSPI",
+ databasename, SqlServer);
+
+ connection.Open();
+
+ string commandText = "SELECT ((dbsize ) * 8192 ) size FROM " + // + logsize
+ "( " +
+ "SELECT SUM(CONVERT(BIGINT,CASE WHEN status & 64 = 0 THEN size ELSE 0 END)) dbsize " +
+ ", SUM(CONVERT(BIGINT,CASE WHEN status & 64 <> 0 THEN size ELSE 0 END)) logsize " +
+ "FROM dbo.sysfiles " +
+ ") big";
+
+ SqlCommand command = new SqlCommand(commandText, connection);
+ res = (long)command.ExecuteScalar();
+
+ }
+ catch (Exception ex)
+ {
+ EndLog("GetDBSize", null, null, ex);
+ }
+ finally
+ {
+ if (connection != null)
+ connection.Dispose();
+
+ }
+
+ EndLog("GetDBSize");
+ return res;
+
+ }
+
+ public virtual long GetMaxDBSize(Guid organizationId)
+ {
+ StartLog("GetMaxDBSize");
+ long res = 0;
+
+ string databasename = GetDataBaseName(organizationId);
+ if (databasename == null) return 0;
+
+ SqlConnection connection = null;
+ try
+ {
+ connection = new SqlConnection();
+ connection.ConnectionString =
+ string.Format("Server={1};Initial Catalog={0};Integrated Security=SSPI",
+ databasename, SqlServer);
+
+ connection.Open();
+
+ string commandText = "SELECT SUM(CONVERT(BIGINT,CASE WHEN status & 64 = 0 THEN maxsize ELSE 0 END)) dbsize FROM dbo.sysfiles";
+
+ SqlCommand command = new SqlCommand(commandText, connection);
+ res = (long)command.ExecuteScalar();
+ if (res > 0) res = res * 8192;
+
+ }
+ catch (Exception ex)
+ {
+ EndLog("GetMaxDBSize", null, null, ex);
+ }
+ finally
+ {
+ if (connection != null)
+ connection.Dispose();
+
+ }
+
+ EndLog("GetMaxDBSize");
+ return res;
+ }
+
+ public virtual ResultObject SetMaxDBSize(Guid organizationId, long maxSize)
+ {
+ ResultObject res = StartLog("SetMaxDBSize");
+
+ SqlConnection connection = null;
+ try
+ {
+ string databasename = GetDataBaseName(organizationId);
+ if (databasename == null) throw new Exception("Can not get database name");
+
+ connection = new SqlConnection();
+ connection.ConnectionString =
+ string.Format("Server={1};Initial Catalog={0};Integrated Security=SSPI",
+ databasename, SqlServer);
+
+ connection.Open();
+
+ string maxSizeStr = maxSize == -1 ? "UNLIMITED" : (maxSize / (1024 * 1024)).ToString() + " MB";
+
+ string commandText = "ALTER DATABASE [" + databasename + "] MODIFY FILE ( NAME = N'mscrm', MAXSIZE = " + maxSizeStr + " )";
+
+ SqlCommand command = new SqlCommand(commandText, connection);
+ command.ExecuteNonQuery();
+
+ res.IsSuccess = true;
+
+ }
+ catch (Exception ex)
+ {
+ EndLog("SetMaxDBSize", res, CrmErrorCodes.CANNOT_CHANGE_CRM_ORGANIZATION_STATE, ex);
+ }
+ finally
+ {
+ if (connection != null)
+ connection.Dispose();
+
+ }
+
+ EndLog("SetMaxDBSize");
+ return res;
+ }
+
+ #endregion
+
+ #region Organization
+
+ public virtual OrganizationResult CreateOrganization(Guid organizationId, string organizationUniqueName, string organizationFriendlyName,
+ int baseLanguageCode,
+ string ou,
+ string baseCurrencyCode, string baseCurrencyName, string baseCurrencySymbol,
+ string initialUserDomainName, string initialUserFirstName, string initialUserLastName, string initialUserPrimaryEmail,
+ string organizationCollation,
+ long maxSize)
+ {
+ return CreateOrganizationInternal(organizationId, organizationUniqueName, organizationFriendlyName,
+ baseLanguageCode,
+ ou , baseCurrencyCode, baseCurrencyName, baseCurrencySymbol,
+ initialUserDomainName, initialUserFirstName, initialUserLastName, initialUserPrimaryEmail,
+ organizationCollation,
+ maxSize);
+ }
+
+ protected const string CRMSysAdminRoleStr = "Системный администратор;System Administrator";
+
+ internal virtual OrganizationResult CreateOrganizationInternal(Guid organizationId, string organizationUniqueName, string organizationFriendlyName,
+ int baseLanguageCode,
+ string ou,
+ string baseCurrencyCode, string baseCurrencyName, string baseCurrencySymbol,
+ string initialUserDomainName, string initialUserFirstName, string initialUserLastName, string initialUserPrimaryEmail,
+ string organizationCollation,
+ long maxSize)
+ {
+
+ OrganizationResult ret = StartLog("CreateOrganizationInternal");
+
+ organizationUniqueName = Regex.Replace(organizationUniqueName, @"[^\dA-Za-z]", "-", RegexOptions.Compiled);
+
+ // calculate UserRootPath
+ string ldapstr = "";
+
+ string[] ouItems = ou.Split('.');
+ foreach (string ouItem in ouItems)
+ {
+ if (ldapstr.Length != 0) ldapstr += ",";
+ ldapstr += "OU=" + ouItem;
+ }
+
+ string rootDomain = ServerSettings.ADRootDomain;
+ string[] domainItems = rootDomain.Split('.');
+ foreach (string domainItem in domainItems)
+ ldapstr += ",DC=" + domainItem;
+
+ ldapstr = @"LDAP://" + rootDomain + "/" + ldapstr;
+
+
+
+ if (organizationId == Guid.Empty)
+ throw new ArgumentException("OrganizationId is Guid.Empty");
+
+ if (string.IsNullOrEmpty(organizationFriendlyName))
+ throw new ArgumentNullException("organizationFriendlyName");
+
+ if (string.IsNullOrEmpty(baseCurrencyCode))
+ throw new ArgumentNullException("baseCurrencyCode");
+
+ if (string.IsNullOrEmpty(baseCurrencySymbol))
+ throw new ArgumentNullException("baseCurrencySymbol");
+
+ if (string.IsNullOrEmpty(initialUserDomainName))
+ throw new ArgumentNullException("initialUserDomainName");
+
+ OrganizationResult retCheckEn = CheckCrmEnvironment(CRMDatabaseName, organizationUniqueName);
+
+ if (!retCheckEn.IsSuccess)
+ {
+ ret.ErrorCodes.AddRange(retCheckEn.ErrorCodes);
+ EndLog("CreateOrganizationInternal", ret, null, null);
+ return ret;
+ }
+
+ try
+ {
+
+ DeploymentServiceClient deploymentService = GetDeploymentProxy();
+
+ Microsoft.Xrm.Sdk.Deployment.Organization org = new Microsoft.Xrm.Sdk.Deployment.Organization
+ {
+ Id = organizationId,
+ UniqueName = organizationUniqueName,
+ FriendlyName = organizationFriendlyName,
+ SqlServerName = SqlServer,
+ SrsUrl = ReportingServer,
+ BaseCurrencyCode = baseCurrencyCode,
+ BaseCurrencyName = baseCurrencyName,
+ BaseCurrencySymbol = baseCurrencySymbol,
+ SqlCollation = organizationCollation,
+ State = Microsoft.Xrm.Sdk.Deployment.OrganizationState.Enabled
+ };
+
+ if (baseLanguageCode > 0)
+ org.BaseLanguageCode = baseLanguageCode;
+
+ BeginCreateOrganizationRequest req = new BeginCreateOrganizationRequest
+ {
+ Organization = org
+ };
+
+ if (!String.IsNullOrEmpty(UserName))
+ {
+ req.SysAdminName = UserName;
+ }
+
+ BeginCreateOrganizationResponse resp = deploymentService.Execute(req) as BeginCreateOrganizationResponse;
+
+ if (resp == null)
+ throw new ArgumentException("BeginCreateOrganizationResponse is Null");
+
+ EntityInstanceId id = new EntityInstanceId();
+ id.Name = org.UniqueName;
+
+ Microsoft.Xrm.Sdk.Deployment.OrganizationState OperationState = Microsoft.Xrm.Sdk.Deployment.OrganizationState.Pending;
+
+ int timeout = 30000;
+
+ do
+ {
+ Thread.Sleep(timeout);
+ try
+ {
+ Microsoft.Xrm.Sdk.Deployment.Organization getorg
+ = (Microsoft.Xrm.Sdk.Deployment.Organization)deploymentService.Retrieve(DeploymentEntityType.Organization, id);
+ OperationState = getorg.State;
+ }
+ catch { }
+ } while ((OperationState != Microsoft.Xrm.Sdk.Deployment.OrganizationState.Enabled) &&
+ (OperationState != Microsoft.Xrm.Sdk.Deployment.OrganizationState.Failed));
+
+ if (OperationState == Microsoft.Xrm.Sdk.Deployment.OrganizationState.Failed)
+ throw new ArgumentException("Create organization failed.");
+
+ // update UserRootPath setting
+ Microsoft.Xrm.Sdk.Deployment.ConfigurationEntity orgSettings = new Microsoft.Xrm.Sdk.Deployment.ConfigurationEntity
+ {
+ Id = org.Id,
+ LogicalName = "Organization"
+ };
+ orgSettings.Attributes = new Microsoft.Xrm.Sdk.Deployment.AttributeCollection();
+ orgSettings.Attributes.Add(new KeyValuePair("UserRootPath", ldapstr));
+ Microsoft.Xrm.Sdk.Deployment.UpdateAdvancedSettingsRequest reqUpdateSettings = new Microsoft.Xrm.Sdk.Deployment.UpdateAdvancedSettingsRequest
+ {
+ Entity = orgSettings
+ };
+ Microsoft.Xrm.Sdk.Deployment.UpdateAdvancedSettingsResponse respUpdateSettings = (Microsoft.Xrm.Sdk.Deployment.UpdateAdvancedSettingsResponse) deploymentService.Execute(reqUpdateSettings);
+
+ // DB size limit
+ if (maxSize!=-1)
+ SetMaxDBSize(organizationId, maxSize);
+
+ int tryTimeout = 30000;
+ int tryCount = 10;
+
+ bool success = false;
+ int tryItem = 0;
+
+ while (!success)
+ {
+
+ try
+ {
+ Thread.Sleep(tryTimeout);
+
+ OrganizationServiceProxy _serviceProxy = GetOrganizationProxy(organizationUniqueName, 0, 0);
+
+ string ldap = "";
+
+ Guid SysAdminGuid = RetrieveSystemUser(GetDomainName(initialUserDomainName), initialUserFirstName, initialUserLastName, CRMSysAdminRoleStr, _serviceProxy, ref ldap, 0);
+
+ success = true;
+
+ }
+ catch
+ {
+ tryItem++;
+ if (tryItem >= tryCount)
+ success = true;
+ }
+ }
+
+
+ }
+ catch (Exception ex)
+ {
+ EndLog("CheckCrmEnvironment", ret, CrmErrorCodes.CREATE_CRM_ORGANIZATION_GENERAL_ERROR, ex);
+ return ret;
+
+ }
+
+ EndLog("CheckCrmEnvironment");
+
+ return ret;
+ }
+
+ protected string GetDomainName(string username)
+ {
+ string domain = ActiveDirectoryUtils.GetNETBIOSDomainName(ServerSettings.ADRootDomain);
+ string ret = string.Format(@"{0}\{1}", domain, username);
+ return ret;
+ }
+
+ public virtual string[] GetSupportedCollationNames()
+ {
+ return GetSupportedCollationNamesInternal(SqlServer);
+ }
+
+ internal virtual string[] GetSupportedCollationNamesInternal(string SqlServer)
+ {
+ StartLog("GetSupportedCollationNamesInternal");
+
+ List ret = new List();
+
+ SqlConnection connection = null;
+ try
+ {
+ connection = new SqlConnection();
+ connection.ConnectionString =
+ string.Format("Server={1};Initial Catalog={0};Integrated Security=SSPI",
+ CRMDatabaseName, SqlServer);
+
+ connection.Open();
+
+ string commandText = "select * from fn_helpcollations() where " +
+ "(name not like '%_WS') AND (name not like '%_KS') AND (name not like '%_100_%') " +
+ " AND (name not like 'SQL_%') " +
+ " order by name";
+ SqlCommand command = new SqlCommand(commandText, connection);
+ SqlDataReader reader = command.ExecuteReader();
+
+ while (reader.Read())
+ {
+ string name = reader["name"] as string;
+ ret.Add(name);
+ }
+
+ }
+ catch (Exception ex)
+ {
+ Log.WriteError(ex);
+ }
+ finally
+ {
+ if (connection != null)
+ connection.Dispose();
+
+ }
+
+ EndLog("GetSupportedCollationNamesInternal");
+ return ret.ToArray();
+ }
+
+ public virtual Currency[] GetCurrencyList()
+ {
+ return GetCurrencyListInternal();
+ }
+
+ internal virtual Currency[] GetCurrencyListInternal()
+ {
+ StartLog("GetCurrencyListInternal");
+ List retList = new List();
+
+ CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.AllCultures & ~CultureTypes.NeutralCultures);
+
+ foreach (CultureInfo culture in cultures)
+ {
+ if (culture.IsNeutralCulture) continue;
+
+ try
+ {
+ RegionInfo Region = new RegionInfo(culture.LCID);
+
+ Currency currency = new Currency();
+ currency.RegionName = Region.NativeName;
+ currency.CurrencyName = Region.CurrencyNativeName;
+ currency.CurrencyCode = Region.ISOCurrencySymbol;
+ currency.CurrencySymbol = Region.CurrencySymbol;
+ retList.Add(currency);
+
+ }
+ catch
+ {
+ continue;
+ }
+ }
+
+ retList.Sort(delegate(Currency a, Currency b) { return a.RegionName.CompareTo(b.RegionName); });
+
+ EndLog("GetCurrencyListInternal");
+ return retList.ToArray();
+ }
+
+ public virtual int[] GetInstalledLanguagePacks()
+ {
+ return GetInstalledLanguagePacksInternal();
+ }
+
+ internal virtual int[] GetInstalledLanguagePacksInternal()
+ {
+ StartLog("GetInstalledLanguagePacks");
+ List res = new List();
+
+ try
+ {
+ RegistryKey root = Registry.LocalMachine;
+ RegistryKey rk = root.OpenSubKey("SOFTWARE\\Microsoft\\MSCRM");
+
+ if (rk == null)
+ rk = root.OpenSubKey("SOFTWARE\\Wow6432Node\\Microsoft\\MSCRM");
+
+ if (rk == null) throw new Exception("Can't open SOFTWARE\\Microsoft\\MSCRM");
+
+ RegistryKey langPacksKey = rk.OpenSubKey("LangPacks");
+ if (langPacksKey == null) throw new Exception("Can't open SOFTWARE\\Microsoft\\MSCRM\\LangPacks");
+
+ string[] langPacksId = langPacksKey.GetSubKeyNames();
+
+ foreach (string strLangId in langPacksId)
+ {
+ int langId = 0;
+ if (int.TryParse(strLangId, out langId))
+ res.Add(langId);
+ }
+
+ }
+ catch (Exception ex)
+ {
+ EndLog("GetInstalledLanguagePacks", null, null, ex);
+ return null;
+ }
+
+ EndLog("GetInstalledLanguagePacks");
+ return res.ToArray();
+ }
+
+ public virtual ResultObject DeleteOrganization(Guid orgId)
+ {
+ return DeleteOrganizationInternal(orgId);
+ }
+
+ internal virtual ResultObject DeleteOrganizationInternal(Guid orgId)
+ {
+ ResultObject res = StartLog("DeleteOrganizationInternal");
+
+
+ res.IsSuccess = true;
+ try
+ {
+ DeploymentServiceClient deploymentService = GetDeploymentProxy();
+
+ EntityInstanceId i = new EntityInstanceId();
+ i.Id = orgId; //Organisation Id
+
+ Microsoft.Xrm.Sdk.Deployment.Organization org = (Microsoft.Xrm.Sdk.Deployment.Organization)deploymentService.Retrieve(DeploymentEntityType.Organization, i);
+
+ org.State = Microsoft.Xrm.Sdk.Deployment.OrganizationState.Disabled;
+
+ Microsoft.Xrm.Sdk.Deployment.UpdateRequest updateRequest = new Microsoft.Xrm.Sdk.Deployment.UpdateRequest();
+ updateRequest.Entity = org;
+
+ deploymentService.Execute(updateRequest);
+
+ }
+ catch (Exception ex)
+ {
+ EndLog("DeleteOrganizationInternal", res, CrmErrorCodes.DELETE_CRM_ORGANIZATION_GENERAL_ERROR, ex);
+ return res;
+
+ }
+
+
+ EndLog("DeleteOrganizationInternal");
+ return res;
+ }
+
+ public override void DeleteServiceItems(ServiceProviderItem[] items)
+ {
+ foreach (ServiceProviderItem item in items)
+ {
+ try
+ {
+ if (item is Organization)
+ {
+ Organization org = item as Organization;
+ DeleteOrganization(org.CrmOrganizationId);
+ }
+
+ }
+ catch (Exception ex)
+ {
+ Log.WriteError(String.Format("Error deleting '{0}' {1}", item.Name, item.GetType().Name), ex);
+ }
+ }
+ base.DeleteServiceItems(items);
+
+ }
+
+ #endregion
+
+ #region Log
+
+ private static void EndLog(string message, ResultObject res, string errorCode, Exception ex)
+ {
+ if (res != null)
+ {
+ res.IsSuccess = false;
+
+ if (!string.IsNullOrEmpty(errorCode))
+ res.ErrorCodes.Add(errorCode);
+ }
+
+ if (ex != null)
+ HostedSolutionLog.LogError(ex);
+
+ HostedSolutionLog.LogEnd(message);
+ }
+
+ private static void EndLog(string message, ResultObject res, string errorCode)
+ {
+ EndLog(message, res, errorCode, null);
+ }
+
+ private static void EndLog(string message, ResultObject res)
+ {
+ EndLog(message, res, null);
+ }
+
+ private static void EndLog(string message)
+ {
+ EndLog(message, null);
+ }
+
+ private static T StartLog(string message) where T : ResultObject, new()
+ {
+ HostedSolutionLog.LogStart(message);
+ T res = new T();
+ res.IsSuccess = true;
+ return res;
+ }
+
+ private static void StartLog(string message)
+ {
+ HostedSolutionLog.LogStart(message);
+ }
+
+ #endregion
+
+ #region User
+
+ public virtual UserResult CreateCRMUser(OrganizationUser user, string orgName, Guid organizationId, Guid baseUnitId, int CALType)
+ {
+ return CreateCRMUserInternal(user, orgName, organizationId, baseUnitId, CALType);
+ }
+
+ internal virtual UserResult CreateCRMUserInternal(OrganizationUser user, string orgName, Guid organizationId, Guid businessUnitId, int CALType)
+ {
+ UserResult res = StartLog("CreateCRMUserInternal");
+
+ try
+ {
+ if (user == null)
+ throw new ArgumentNullException("user");
+
+ if (string.IsNullOrEmpty(orgName))
+ throw new ArgumentNullException("orgName");
+
+ if (organizationId == Guid.Empty)
+ throw new ArgumentException("organizationId");
+
+ if (businessUnitId == Guid.Empty)
+ throw new ArgumentException("businessUnitId");
+
+ try
+ {
+ OrganizationServiceProxy _serviceProxy = GetOrganizationProxy(orgName);
+
+
+ string ldap = "";
+ Guid guid = RetrieveSystemUser(user.DomainUserName, user.FirstName, user.LastName, CRMSysAdminRoleStr, _serviceProxy, ref ldap, CALType);
+
+ user.CrmUserId = guid;
+ res.Value = user;
+
+ }
+ catch (Exception ex)
+ {
+ EndLog("CreateCRMUserInternal", res, CrmErrorCodes.CANNOT_CREATE_CRM_USER, ex);
+ return res;
+ }
+ }
+ catch (Exception ex)
+ {
+ EndLog("CreateCRMUserInternal", res, CrmErrorCodes.CANNOT_CREATE_CRM_USER_GENERAL_ERROR, ex);
+ return res;
+
+ }
+
+ EndLog("CreateCRMUserInternal");
+ return res;
+ }
+
+ protected virtual Guid CreateSystemUser(String userName, String firstName,
+ String lastName, String domain, String roleStr,
+ OrganizationServiceProxy serviceProxy, ref String ldapPath, int CALType)
+ {
+
+ if (serviceProxy.ServiceConfiguration.AuthenticationType == AuthenticationProviderType.LiveId ||
+ serviceProxy.ServiceConfiguration.AuthenticationType == AuthenticationProviderType.OnlineFederation)
+ throw new Exception(String.Format("To run this sample, {0} {1} must be an active system user in your Microsoft Dynamics CRM Online organization.", firstName, lastName));
+
+ Guid userId = Guid.Empty;
+
+ Microsoft.Xrm.Sdk.Query.QueryExpression businessUnitQuery = new Microsoft.Xrm.Sdk.Query.QueryExpression
+ {
+ EntityName = BusinessUnit.EntityLogicalName,
+ ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet("businessunitid"),
+ Criteria =
+ {
+ Conditions =
+ {
+ new Microsoft.Xrm.Sdk.Query.ConditionExpression("parentbusinessunitid",
+ Microsoft.Xrm.Sdk.Query.ConditionOperator.Null)
+ }
+ }
+ };
+
+ BusinessUnit defaultBusinessUnit = serviceProxy.RetrieveMultiple(
+ businessUnitQuery).Entities[0].ToEntity();
+
+ // Retrieve the specified security role.
+ Role role = RetrieveRoleByName(serviceProxy, roleStr);
+
+ // CALType and AccessMode
+ int accessmode = CALType / 10;
+ int caltype = CALType % 10;
+
+ //Create a new system user.
+ SystemUser user = new SystemUser
+ {
+ DomainName = userName,
+ FirstName = firstName,
+ LastName = lastName,
+ BusinessUnitId = new EntityReference
+ {
+ LogicalName = BusinessUnit.EntityLogicalName,
+ Name = BusinessUnit.EntityLogicalName,
+ Id = defaultBusinessUnit.Id
+ },
+ CALType = new OptionSetValue(caltype),
+ AccessMode = new OptionSetValue(accessmode)
+ };
+ userId = serviceProxy.Create(user);
+
+ // Assign the security role to the newly created Microsoft Dynamics CRM user.
+ AssociateRequest associate = new AssociateRequest()
+ {
+ Target = new EntityReference(SystemUser.EntityLogicalName, userId),
+ RelatedEntities = new EntityReferenceCollection()
+ {
+ new EntityReference(Role.EntityLogicalName, role.Id),
+ },
+ Relationship = new Relationship("systemuserroles_association")
+ };
+ serviceProxy.Execute(associate);
+
+ return userId;
+ }
+
+
+ protected virtual Guid RetrieveSystemUser(String userName, String firstName,
+ String lastName, String roleStr, OrganizationServiceProxy serviceProxy,
+ ref String ldapPath,
+ int CALType)
+ {
+ String domain;
+ Guid userId = Guid.Empty;
+
+ if (serviceProxy == null)
+ throw new ArgumentNullException("serviceProxy");
+
+ if (String.IsNullOrWhiteSpace(userName))
+ throw new ArgumentNullException("UserName");
+
+ if (String.IsNullOrWhiteSpace(firstName))
+ throw new ArgumentNullException("FirstName");
+
+ if (String.IsNullOrWhiteSpace(lastName))
+ throw new ArgumentNullException("LastName");
+
+ if (String.IsNullOrWhiteSpace(roleStr))
+ throw new ArgumentNullException("Role");
+
+ // Obtain the current user's information.
+ Microsoft.Crm.Sdk.Messages.WhoAmIRequest who = new Microsoft.Crm.Sdk.Messages.WhoAmIRequest();
+ Microsoft.Crm.Sdk.Messages.WhoAmIResponse whoResp = (Microsoft.Crm.Sdk.Messages.WhoAmIResponse)serviceProxy.Execute(who);
+ Guid currentUserId = whoResp.UserId;
+
+ SystemUser currentUser =
+ serviceProxy.Retrieve(SystemUser.EntityLogicalName, currentUserId, new Microsoft.Xrm.Sdk.Query.ColumnSet("domainname")).ToEntity();
+
+ // Extract the domain and create the LDAP object.
+ String[] userPath = currentUser.DomainName.Split(new char[] { '\\' });
+ if (userPath.Length > 1)
+ domain = userPath[0] + "\\";
+ else
+ domain = String.Empty;
+
+ // Create the system user in Microsoft Dynamics CRM if the user doesn't
+ // already exist.
+ Microsoft.Xrm.Sdk.Query.QueryExpression userQuery = new Microsoft.Xrm.Sdk.Query.QueryExpression
+ {
+ EntityName = SystemUser.EntityLogicalName,
+ ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet("systemuserid"),
+ Criteria =
+ {
+ FilterOperator = Microsoft.Xrm.Sdk.Query.LogicalOperator.Or,
+ Filters =
+ {
+ new Microsoft.Xrm.Sdk.Query.FilterExpression
+ {
+ FilterOperator = Microsoft.Xrm.Sdk.Query.LogicalOperator.And,
+ Conditions =
+ {
+ new Microsoft.Xrm.Sdk.Query.ConditionExpression("domainname", Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal, domain + userName)
+ }
+ },
+ new Microsoft.Xrm.Sdk.Query.FilterExpression
+ {
+ FilterOperator = Microsoft.Xrm.Sdk.Query.LogicalOperator.And,
+ Conditions =
+ {
+ new Microsoft.Xrm.Sdk.Query.ConditionExpression("firstname", Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal, firstName),
+ new Microsoft.Xrm.Sdk.Query.ConditionExpression("lastname", Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal, lastName)
+ }
+ }
+ }
+
+ }
+ };
+
+ DataCollection existingUsers = (DataCollection)serviceProxy.RetrieveMultiple(userQuery).Entities;
+
+ SystemUser existingUser = null;
+ if (existingUsers.Count > 0)
+ existingUser = existingUsers[0].ToEntity();
+
+ if (existingUser != null)
+ {
+ userId = existingUser.SystemUserId.Value;
+
+ // Check to make sure the user is assigned the correct role.
+ Role role = RetrieveRoleByName(serviceProxy, roleStr);
+
+ // Associate the user with the role when needed.
+ if (!UserInRole(serviceProxy, userId, role.Id))
+ {
+ AssociateRequest associate = new AssociateRequest()
+ {
+ Target = new EntityReference(SystemUser.EntityLogicalName, userId),
+ RelatedEntities = new EntityReferenceCollection()
+ {
+ new EntityReference(Role.EntityLogicalName, role.Id)
+ },
+ Relationship = new Relationship("systemuserroles_association")
+ };
+ serviceProxy.Execute(associate);
+ }
+
+ }
+ else
+ {
+ userId = CreateSystemUser(userName, firstName, lastName, domain,
+ roleStr, serviceProxy, ref ldapPath, CALType);
+ }
+
+ return userId;
+ }
+
+ public virtual CrmUserResult GetCrmUserById(Guid crmUserId, string orgName)
+ {
+ return GetCrmUserByIdInternal(crmUserId, orgName);
+ }
+
+ internal virtual CrmUserResult GetCrmUserByIdInternal(Guid crmUserId, string orgName)
+ {
+ CrmUserResult ret = StartLog("GetCrmUserByIdInternal");
+
+ try
+ {
+ if (crmUserId == Guid.Empty)
+ throw new ArgumentNullException("crmUserId");
+
+ if (string.IsNullOrEmpty(orgName))
+ throw new ArgumentNullException("orgName");
+
+ OrganizationServiceProxy serviceProxy = GetOrganizationProxy(orgName);
+
+ SystemUser retruveUser =
+ serviceProxy.Retrieve(SystemUser.EntityLogicalName, crmUserId, new Microsoft.Xrm.Sdk.Query.ColumnSet("domainname", "businessunitid", "accessmode", "isdisabled", "caltype")).ToEntity();
+
+ CrmUser user = null;
+
+ if (retruveUser != null)
+ {
+ user = new CrmUser();
+ user.BusinessUnitId = retruveUser.BusinessUnitId.Id;
+ user.CRMUserId = retruveUser.SystemUserId.Value;
+ user.ClientAccessMode = (CRMUserAccessMode)retruveUser.AccessMode.Value;
+ user.IsDisabled = (bool)retruveUser.IsDisabled;
+ user.CALType = retruveUser.CALType.Value;
+
+ ret.Value = user;
+ }
+ }
+ catch (Exception ex)
+ {
+ EndLog("GetCrmUserByIdInternal", ret, CrmErrorCodes.CANONT_GET_CRM_USER_BY_ID, ex);
+ return ret;
+ }
+
+ EndLog("GetCrmUserByIdInternal");
+ return ret;
+ }
+
+ internal virtual CrmUserResult GetCrmUserByDomainNameInternal(string domainName, string orgName)
+ {
+ CrmUserResult ret = StartLog("GetCrmUserByDomainNameInternal");
+
+ try
+ {
+ if (string.IsNullOrEmpty(domainName))
+ throw new ArgumentNullException("domainName");
+
+ if (string.IsNullOrEmpty(orgName))
+ throw new ArgumentNullException("orgName");
+
+
+ OrganizationServiceProxy serviceProxy = GetOrganizationProxy(orgName);
+
+ Microsoft.Xrm.Sdk.Query.QueryExpression usereQuery = new Microsoft.Xrm.Sdk.Query.QueryExpression
+ {
+ EntityName = SystemUser.EntityLogicalName,
+ ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet("domainname", "businessunitid", "accessmode", "isdisabled", "systemuserid", "caltype"),
+ };
+
+ EntityCollection users = serviceProxy.RetrieveMultiple(usereQuery);
+
+ foreach (Entity entityuser in users.Entities)
+ {
+ SystemUser sysuser = entityuser.ToEntity();
+
+ if (sysuser == null) continue;
+ if (sysuser.DomainName != domainName) continue;
+
+ CrmUser user = new CrmUser();
+ user.BusinessUnitId = sysuser.BusinessUnitId.Id;
+ user.CRMUserId = sysuser.SystemUserId.Value;
+ user.ClientAccessMode = (CRMUserAccessMode)sysuser.AccessMode.Value;
+ user.IsDisabled = sysuser.IsDisabled.Value;
+ user.CALType = sysuser.CALType.Value;
+ ret.Value = user;
+ }
+ }
+ catch (Exception ex)
+ {
+ EndLog("GetCrmUserByDomainNameInternal", ret, CrmErrorCodes.CANONT_GET_CRM_USER_BY_DOMAIN_NAME, ex);
+ return ret;
+ }
+
+ EndLog("GetCrmUserByDomainNameInternal");
+ return ret;
+ }
+
+ public virtual CrmUserResult GetCrmUserByDomainName(string domainName, string orgName)
+ {
+ return GetCrmUserByDomainNameInternal(domainName, orgName);
+ }
+
+ public virtual ResultObject ChangeUserState(bool disable, string orgName, Guid crmUserId)
+ {
+ return ChangeUserStateInternal(disable, orgName, crmUserId);
+ }
+
+ internal virtual ResultObject ChangeUserStateInternal(bool disable, string orgName, Guid crmUserId)
+ {
+ ResultObject res = StartLog("ChangeUserStateInternal");
+
+ res.IsSuccess = true;
+ try
+ {
+ if (crmUserId == Guid.Empty)
+ throw new ArgumentNullException("crmUserId");
+
+ if (string.IsNullOrEmpty(orgName))
+ throw new ArgumentNullException("orgName");
+
+ OrganizationServiceProxy serviceProxy = GetOrganizationProxy(orgName);
+
+ // Retrieve a user.
+ SystemUser user = serviceProxy.Retrieve(SystemUser.EntityLogicalName,
+ crmUserId, new Microsoft.Xrm.Sdk.Query.ColumnSet(new String[] { "systemuserid", "firstname", "lastname" })).ToEntity();
+
+ if (user != null)
+ {
+ Microsoft.Crm.Sdk.Messages.SetStateRequest request = new Microsoft.Crm.Sdk.Messages.SetStateRequest()
+ {
+ EntityMoniker = user.ToEntityReference(),
+
+ // Required by request but always valued at -1 in this context.
+ Status = new OptionSetValue(-1),
+
+ // Sets the user to disabled.
+ State = disable ? new OptionSetValue(-1) : new OptionSetValue(0)
+ };
+
+ serviceProxy.Execute(request);
+
+ }
+ }
+ catch (Exception ex)
+ {
+ EndLog("ChangeUserStateInternal", res, CrmErrorCodes.CANNOT_CHANGE_USER_STATE, ex);
+ return res;
+ }
+
+
+ EndLog("ChangeUserStateInternal");
+ return res;
+ }
+
+ public virtual ResultObject SetUserCALType(string orgName, Guid userId, int CALType)
+ {
+ return SetUserCALTypeInternal(orgName, userId, CALType);
+ }
+
+ internal virtual ResultObject SetUserCALTypeInternal(string orgName, Guid userId, int CALType)
+ {
+ ResultObject ret = StartLog("SetUserCALTypeInternal");
+
+ try
+ {
+ if (userId == Guid.Empty)
+ throw new ArgumentNullException("crmUserId");
+
+ if (string.IsNullOrEmpty(orgName))
+ throw new ArgumentNullException("orgName");
+
+ OrganizationServiceProxy serviceProxy = GetOrganizationProxy(orgName);
+
+ SystemUser user =
+ serviceProxy.Retrieve(SystemUser.EntityLogicalName, userId, new Microsoft.Xrm.Sdk.Query.ColumnSet("domainname", "businessunitid", "accessmode", "isdisabled", "caltype")).ToEntity();
+
+ // CALType and AccessMode
+ int accessmode = CALType / 10;
+ int caltype = CALType % 10;
+
+ user.CALType = new OptionSetValue(caltype);
+ user.AccessMode = new OptionSetValue(accessmode);
+
+ serviceProxy.Update(user);
+
+ }
+ catch (Exception ex)
+ {
+ EndLog("SetUserCALTypeInternal", ret, CrmErrorCodes.CANONT_GET_CRM_USER_BY_ID, ex);
+ return ret;
+ }
+
+ EndLog("SetUserCALTypeInternal");
+ return ret;
+ }
+
+ #endregion
+
+ #region Role
+
+ protected virtual Role RetrieveRoleByName(OrganizationServiceProxy serviceProxy,
+ String roleSplitStr)
+ {
+ string[] RolesStr = roleSplitStr.Split(';');
+
+ foreach (string roleStr in RolesStr)
+ {
+
+ Microsoft.Xrm.Sdk.Query.QueryExpression roleQuery = new Microsoft.Xrm.Sdk.Query.QueryExpression
+ {
+ EntityName = Role.EntityLogicalName,
+ ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet("roleid"),
+ Criteria =
+ {
+ Conditions =
+ {
+ new Microsoft.Xrm.Sdk.Query.ConditionExpression("name", Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal, roleStr)
+ }
+ }
+ };
+
+ DataCollection roles = serviceProxy.RetrieveMultiple(roleQuery).Entities;
+
+ if (roles.Count > 0) return roles[0].ToEntity();
+ }
+
+ return null;
+ }
+
+ protected virtual bool UserInRole(OrganizationServiceProxy serviceProxy,
+ Guid userId, Guid roleId)
+ {
+ // Establish a SystemUser link for a query.
+ Microsoft.Xrm.Sdk.Query.LinkEntity systemUserLink = new Microsoft.Xrm.Sdk.Query.LinkEntity()
+ {
+ LinkFromEntityName = SystemUserRoles.EntityLogicalName,
+ LinkFromAttributeName = "systemuserid",
+ LinkToEntityName = SystemUser.EntityLogicalName,
+ LinkToAttributeName = "systemuserid",
+ LinkCriteria =
+ {
+ Conditions =
+ {
+ new Microsoft.Xrm.Sdk.Query.ConditionExpression(
+ "systemuserid", Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal, userId)
+ }
+ }
+ };
+
+ // Build the query.
+ Microsoft.Xrm.Sdk.Query.QueryExpression query = new Microsoft.Xrm.Sdk.Query.QueryExpression()
+ {
+ EntityName = Role.EntityLogicalName,
+ ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet("roleid"),
+ LinkEntities =
+ {
+ new Microsoft.Xrm.Sdk.Query.LinkEntity()
+ {
+ LinkFromEntityName = Role.EntityLogicalName,
+ LinkFromAttributeName = "roleid",
+ LinkToEntityName = SystemUserRoles.EntityLogicalName,
+ LinkToAttributeName = "roleid",
+ LinkEntities = {systemUserLink}
+ }
+ },
+ Criteria =
+ {
+ Conditions =
+ {
+ new Microsoft.Xrm.Sdk.Query.ConditionExpression("roleid", Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal, roleId)
+ }
+ }
+ };
+
+ // Retrieve matching roles.
+ EntityCollection ec = serviceProxy.RetrieveMultiple(query);
+
+ if (ec.Entities.Count > 0)
+ return true;
+
+ return false;
+ }
+
+ public virtual CrmRolesResult GetAllCrmRoles(string orgName, Guid businessUnitId)
+ {
+ return GetAllCrmRolesInternal(orgName, businessUnitId);
+ }
+
+ public virtual CrmRolesResult GetCrmUserRoles(string orgName, Guid userId)
+ {
+ return GetCrmUserRolesInternal(userId, orgName);
+ }
+
+ public virtual EntityCollection GetUserRoles(Guid userId, string orgName)
+ {
+ OrganizationServiceProxy serviceProxy = GetOrganizationProxy(orgName);
+
+ // Establish a SystemUser link for a query.
+ Microsoft.Xrm.Sdk.Query.LinkEntity systemUserLink = new Microsoft.Xrm.Sdk.Query.LinkEntity()
+ {
+ LinkFromEntityName = SystemUserRoles.EntityLogicalName,
+ LinkFromAttributeName = "systemuserid",
+ LinkToEntityName = SystemUser.EntityLogicalName,
+ LinkToAttributeName = "systemuserid",
+ LinkCriteria =
+ {
+ Conditions =
+ {
+ new Microsoft.Xrm.Sdk.Query.ConditionExpression(
+ "systemuserid", Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal, userId)
+ }
+ }
+ };
+
+ // Build the query.
+ Microsoft.Xrm.Sdk.Query.QueryExpression query = new Microsoft.Xrm.Sdk.Query.QueryExpression()
+ {
+ EntityName = Role.EntityLogicalName,
+ ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet("roleid"),
+ LinkEntities =
+ {
+ new Microsoft.Xrm.Sdk.Query.LinkEntity()
+ {
+ LinkFromEntityName = Role.EntityLogicalName,
+ LinkFromAttributeName = "roleid",
+ LinkToEntityName = SystemUserRoles.EntityLogicalName,
+ LinkToAttributeName = "roleid",
+ LinkEntities = {systemUserLink}
+ }
+ }
+ };
+
+ // Retrieve matching roles.
+ EntityCollection relations = serviceProxy.RetrieveMultiple(query);
+
+ return relations;
+ }
+
+ internal virtual CrmRolesResult GetCrmUserRolesInternal(Guid userId, string orgName)
+ {
+ CrmRolesResult res = StartLog("GetCrmUserRolesInternal");
+
+ try
+ {
+ EntityCollection relations;
+
+ if (userId == Guid.Empty)
+ throw new ArgumentException("userId");
+
+ if (string.IsNullOrEmpty(orgName))
+ throw new ArgumentNullException("orgName");
+
+ try
+ {
+ relations = GetUserRoles(userId, orgName);
+ }
+ catch (Exception ex)
+ {
+ EndLog("GetCrmUserRolesInternal", res, CrmErrorCodes.CANNOT_GET_CRM_USER_ROLES, ex);
+ return res;
+ }
+
+ try
+ {
+ res.Value = FillCrmRoles(relations, true, Guid.Empty);
+ }
+ catch (Exception ex)
+ {
+ EndLog("GetCrmUserRolesInternal", res, CrmErrorCodes.CANNOT_FILL_ROLES_COLLECTION, ex);
+ return res;
+ }
+ }
+ catch (Exception ex)
+ {
+ EndLog("GetCrmUserRolesInternal", res, CrmErrorCodes.GET_CRM_USER_ROLE_GENERAL_ERROR, ex);
+ return res;
+ }
+
+ EndLog("GetCrmUserRolesInternal");
+ return res;
+ }
+
+ protected static string excludedRolesStr = ";пользователь поддержки;support user;";
+
+ protected virtual List FillCrmRoles(EntityCollection entities, bool isUserRole, Guid businessUnitId)
+ {
+ List res = new List();
+
+ foreach (Entity current in entities.Entities)
+ {
+ Role role = current.ToEntity();
+
+ if (role == null) continue;
+
+ if (businessUnitId != Guid.Empty)
+ {
+ if (businessUnitId != role.BusinessUnitId.Id)
+ continue;
+ }
+
+ string roleName = role.Name;
+
+ if (roleName != null)
+ if (excludedRolesStr.IndexOf(";" + roleName.ToLower() + ";") != -1)
+ continue;
+
+ CrmRole crmRole = new CrmRole();
+ crmRole.IsCurrentUserRole = isUserRole;
+ crmRole.RoleId = (Guid)role.RoleId;
+ crmRole.RoleName = roleName;
+
+ res.Add(crmRole);
+ }
+
+ return res;
+ }
+
+ protected virtual List FillCrmRoles(EntityCollection entities, Guid businessUnitId)
+ {
+ return FillCrmRoles(entities, false, businessUnitId);
+ }
+
+ internal virtual CrmRolesResult GetAllCrmRolesInternal(string orgName, Guid businessUnitId)
+ {
+ CrmRolesResult res = StartLog("GetAllCrmRoles");
+
+ try
+ {
+ if (string.IsNullOrEmpty(orgName))
+ throw new ArgumentNullException("orgName");
+
+ EntityCollection roles;
+ try
+ {
+ OrganizationServiceProxy serviceProxy = GetOrganizationProxy(orgName);
+
+ Microsoft.Xrm.Sdk.Query.QueryExpression roleQuery = new Microsoft.Xrm.Sdk.Query.QueryExpression
+ {
+ EntityName = Role.EntityLogicalName,
+ ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet(new string[] { "roleid", "name", "businessunitid" }),
+ };
+
+ roles = serviceProxy.RetrieveMultiple(roleQuery);
+
+
+ }
+ catch (Exception ex)
+ {
+ EndLog("GetAllCrmRoles", res, CrmErrorCodes.CANNOT_GET_ALL_CRM_ROLES, ex);
+ return res;
+ }
+
+ try
+ {
+ List crmRoles = FillCrmRoles(roles, businessUnitId);
+ res.Value = crmRoles;
+ }
+ catch (Exception ex)
+ {
+ EndLog("GetAllCrmRoles", res, CrmErrorCodes.CANNOT_FILL_ROLES_COLLECTION, ex);
+ return res;
+ }
+ }
+ catch (Exception ex)
+ {
+ EndLog("GetAllCrmRoles", res, CrmErrorCodes.GET_ALL_CRM_ROLES_GENERAL_ERROR, ex);
+ return res;
+ }
+
+ EndLog("GetAllCrmRoles");
+ return res;
+ }
+
+ public virtual ResultObject SetUserRoles(string orgName, Guid userId, Guid[] roles)
+ {
+ return SetUserRolesInternal(orgName, userId, roles);
+ }
+
+ internal virtual ResultObject SetUserRolesInternal(string orgName, Guid userId, Guid[] roles)
+ {
+ CrmRolesResult res = StartLog("SetUserRolesInternal");
+
+ try
+ {
+ if (string.IsNullOrEmpty(orgName))
+ throw new ArgumentNullException("orgName");
+
+ if (userId == Guid.Empty)
+ throw new ArgumentException("userId");
+
+ if (roles == null)
+ throw new ArgumentNullException("roles");
+
+ OrganizationServiceProxy serviceProxy = GetOrganizationProxy(orgName);
+
+
+ CrmRolesResult tmpRoles = GetCrmUserRoles(orgName, userId);
+ res.ErrorCodes.AddRange(tmpRoles.ErrorCodes);
+
+ if (!tmpRoles.IsSuccess)
+ return res;
+
+ List remRoles = new List();
+
+ for (int i = 0; i < tmpRoles.Value.Count; i++)
+ {
+ if (Array.Find(roles, delegate(Guid current) { return current == tmpRoles.Value[i].RoleId; }) == Guid.Empty)
+ {
+ remRoles.Add(tmpRoles.Value[i].RoleId);
+ }
+ }
+
+ try
+ {
+ DisassociateRequest removeRole = new DisassociateRequest()
+ {
+ Target = new EntityReference(SystemUser.EntityLogicalName, userId),
+ RelatedEntities = new EntityReferenceCollection(),
+ Relationship = new Relationship("systemuserroles_association")
+ };
+
+ for (int i = 0; i < remRoles.Count; i++)
+ removeRole.RelatedEntities.Add(new EntityReference(Role.EntityLogicalName, remRoles[i]));
+
+ serviceProxy.Execute(removeRole);
+
+ }
+ catch (Exception ex)
+ {
+ EndLog("SetUserRolesInternal", res, CrmErrorCodes.CANNOT_REMOVE_CRM_USER_ROLES, ex);
+ return res;
+ }
+
+
+ try
+ {
+ // Assign the security role to the newly created Microsoft Dynamics CRM user.
+ AssociateRequest associate = new AssociateRequest()
+ {
+ Target = new EntityReference(SystemUser.EntityLogicalName, userId),
+ RelatedEntities = new EntityReferenceCollection(),
+ Relationship = new Relationship("systemuserroles_association")
+ };
+
+ for (int i = 0; i < roles.Length; i++)
+ {
+ bool find = false;
+ foreach (CrmRole current in tmpRoles.Value)
+ {
+ if (current.RoleId == roles[i])
+ find = true;
+ }
+ if (find) continue;
+
+ associate.RelatedEntities.Add(new EntityReference(Role.EntityLogicalName, roles[i]));
+ }
+
+ serviceProxy.Execute(associate);
+ }
+ catch (Exception ex)
+ {
+ EndLog("SetUserRolesInternal", res, CrmErrorCodes.CANNOT_ASSIGN_CRM_USER_ROLES, ex);
+ return res;
+ }
+
+ }
+ catch (Exception ex)
+ {
+ EndLog("SetUserRolesInternal", res, CrmErrorCodes.CANNOT_SET_CRM_USER_ROLES_GENERAL_ERROR, ex);
+ return res;
+ }
+
+
+ EndLog("SetUserRolesInternal");
+ return res;
+
+ }
+
+ #endregion
+
+ #region Business Units
+
+ internal virtual CRMBusinessUnitsResult GetOrganizationBusinessUnitsInternal(Guid organizationId, string orgName)
+ {
+ CRMBusinessUnitsResult res = StartLog("GetOrganizationBusinessUnitsInternal");
+
+ try
+ {
+ if (organizationId == Guid.Empty)
+ throw new ArgumentException("organizationId");
+
+ if (string.IsNullOrEmpty(orgName))
+ throw new ArgumentNullException("orgName");
+
+ OrganizationServiceProxy serviceProxy;
+
+ try
+ {
+ serviceProxy = GetOrganizationProxy(orgName);
+ }
+ catch (Exception ex)
+ {
+ EndLog("GetOrganizationBusinessUnitsInternal", res, CrmErrorCodes.CANNOT_GET_CRM_SERVICE, ex);
+ return res;
+ }
+
+ DataCollection BusinessUnits;
+
+ try
+ {
+
+ Microsoft.Xrm.Sdk.Query.QueryExpression businessUnitQuery = new Microsoft.Xrm.Sdk.Query.QueryExpression
+ {
+ EntityName = BusinessUnit.EntityLogicalName,
+ ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet(new string[] { "businessunitid", "name" }),
+ Criteria =
+ {
+ Conditions =
+ {
+ new Microsoft.Xrm.Sdk.Query.ConditionExpression("parentbusinessunitid",
+ Microsoft.Xrm.Sdk.Query.ConditionOperator.Null)
+ }
+ }
+ };
+
+ BusinessUnits = serviceProxy.RetrieveMultiple(
+ businessUnitQuery).Entities;
+
+ }
+ catch (Exception ex)
+ {
+ EndLog("GetOrganizationBusinessUnitsInternal", res, CrmErrorCodes.CANNOT_GET_CRM_BUSINESS_UNITS, ex);
+ return res;
+ }
+
+ List businessUnits = new List();
+
+ try
+ {
+ for (int i = 0; i < BusinessUnits.Count; i++)
+ {
+ BusinessUnit bu = BusinessUnits[i].ToEntity();
+
+ CRMBusinessUnit unit = new CRMBusinessUnit();
+ unit.BusinessUnitId = (Guid)bu.BusinessUnitId;
+ unit.BusinessUnitName = bu.Name;
+
+ if (unit.BusinessUnitName == null)
+ unit.BusinessUnitName = "default";
+
+ businessUnits.Add(unit);
+
+ }
+
+ res.Value = businessUnits;
+ }
+ catch (Exception ex)
+ {
+ EndLog("GetOrganizationBusinessUnitsInternal", res, CrmErrorCodes.CANNOT_FILL_BASE_UNITS_COLLECTION,
+ ex);
+ return res;
+ }
+ }
+ catch (Exception ex)
+ {
+ EndLog("GetOrganizationBusinessUnitsInternal", res, CrmErrorCodes.GET_ORGANIZATION_BUSINESS_UNITS_GENERAL_ERROR,
+ ex);
+ return res;
+
+ }
+
+ EndLog("GetOrganizationBusinessUnitsInternal");
+ return res;
+
+ }
+
+ public virtual CRMBusinessUnitsResult GetOrganizationBusinessUnits(Guid organizationId, string orgName)
+ {
+ return GetOrganizationBusinessUnitsInternal(organizationId, orgName);
+ }
+
+ #endregion
+
+ #region Version
+
+ public virtual string CRMServerVersion
+ {
+ get
+ {
+ string value = "";
+ try
+ {
+ RegistryKey root = Registry.LocalMachine;
+ RegistryKey rk = root.OpenSubKey("SOFTWARE\\Microsoft\\MSCRM");
+
+ if (rk == null)
+ rk = root.OpenSubKey("SOFTWARE\\Wow6432Node\\Microsoft\\MSCRM");
+
+ if (rk != null)
+ {
+ value = (string)rk.GetValue("CRM_Server_Version", null);
+ rk.Close();
+ }
+ }
+ catch (Exception ex)
+ {
+ Log.WriteError(ex);
+ }
+
+ return value;
+ }
+
+ }
+
+ public override bool IsInstalled()
+ {
+ return false;
+ }
+
+ #endregion
+
+ }
+}
diff --git a/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution.Crm2011/CRMProvider2011.cs b/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution.Crm2011/CRMProvider2011.cs
index 44d03f40..c787aaca 100644
--- a/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution.Crm2011/CRMProvider2011.cs
+++ b/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution.Crm2011/CRMProvider2011.cs
@@ -1,1961 +1,46 @@
-using System;
-using System.Collections.Generic;
-using System.Data;
-using System.Data.SqlClient;
-using System.Globalization;
-using System.IO;
-using System.Net;
-using System.Reflection;
-using System.Net.Security;
-using System.Security.Principal;
-using System.Security.Cryptography.X509Certificates;
-using System.Threading;
-using System.ServiceModel.Description;
-using System.Text.RegularExpressions;
-using Microsoft.Win32;
-using WebsitePanel.Providers.Common;
-using WebsitePanel.Providers.ResultObjects;
-using WebsitePanel.Server.Utils;
+// Copyright (c) 2012 - 2013, 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 WebsitePanel.Providers.HostedSolution;
-using WebsitePanel.Providers;
-using WebsitePanel.Providers.Utils;
-using Microsoft.Xrm.Sdk;
-using Microsoft.Xrm.Sdk.Query;
-using Microsoft.Xrm.Sdk.Discovery;
-using Microsoft.Xrm.Sdk.Client;
-using Microsoft.Xrm.Sdk.Deployment;
-using Microsoft.Xrm.Sdk.Messages;
namespace WebsitePanel.Providers.HostedSolution
{
- public class CRMProvider2011 : HostingServiceProviderBase, ICRM
+ public class CRMProvider2011 : CRMBase
{
- private static string crmPath = null;
-
- #region Properties
-
- private string UserName
- {
- get { return ProviderSettings[Constants.UserName]; }
- }
-
- private string Password
- {
- get { return ProviderSettings[Constants.Password]; }
- }
-
- private string SqlServer
- {
- get { return ProviderSettings[Constants.SqlServer]; }
- }
-
- private string ReportingServer
- {
- get { return ProviderSettings[Constants.ReportingServer]; }
- }
-
- private string CRMServiceUrl
- {
- get
- {
- string uri = ProviderSettings[Constants.DeploymentWebService];
- if (String.IsNullOrEmpty(uri)) uri = ProviderSettings[Constants.AppRootDomain];
- string cRMServiceUrl = "https://" + uri + ":" + ProviderSettings[Constants.Port] + "/XRMDeployment/2011/Deployment.svc";
- return cRMServiceUrl;
- }
- }
-
- private string CRMDiscoveryUri
- {
- get
- {
- string uri = ProviderSettings[Constants.DiscoveryWebService];
- if (String.IsNullOrEmpty(uri)) uri = ProviderSettings[Constants.AppRootDomain];
- string cRMDiscoveryUri = "https://" + uri + ":" + ProviderSettings[Constants.Port] + "/XRMServices/2011/Discovery.svc";
- return cRMDiscoveryUri;
- }
- }
-
- private static string CrmPath
- {
- get
- {
- if (string.IsNullOrEmpty(crmPath))
- {
- RegistryKey root = Registry.LocalMachine;
- RegistryKey rk = root.OpenSubKey("SOFTWARE\\Microsoft\\MSCRM");
- if (rk != null)
- {
- crmPath = (string)rk.GetValue("CRM_Server_InstallDir", string.Empty);
- }
- }
- return crmPath;
- }
- }
-
- #endregion
-
-
- #region Static constructor
-
- static CRMProvider2011()
- {
- AppDomain.CurrentDomain.AssemblyResolve += ResolveCRMAssembly;
- }
-
- #endregion
-
- static Assembly ResolveCRMAssembly(object sender, ResolveEventArgs args)
- {
- var loadedAssembly = default(Assembly);
- // Ensure we load DLLs only.
- if (args.Name.ToLower().Contains("microsoft.crm") || args.Name.ToLower().Contains("antixsslibrary"))
- {
- //
- string crmToolsPath = Path.Combine(CrmPath, "tools");
- //
- string path = Path.Combine(crmToolsPath, args.Name.Split(',')[0] + ".dll");
- // Call to load an assembly only if its existence is confirmed.
- if (File.Exists(path))
- {
- loadedAssembly = Assembly.LoadFrom(path);
- }
- }
- //
- return loadedAssembly;
- }
-
- private bool CheckCRMWebServicesAccess()
- {
- Log.WriteStart("CheckCRMWebServicesAccess");
- bool ret = false;
- HttpWebResponse response = null;
- HttpWebRequest request;
-
- try
- {
- WindowsIdentity.GetCurrent();
-
- request = WebRequest.Create(CRMServiceUrl) as HttpWebRequest;
-
- if (request != null)
- {
- request.UseDefaultCredentials = true;
- request.Credentials = CredentialCache.DefaultCredentials;
- response = request.GetResponse() as HttpWebResponse;
-
- }
- if (response != null)
- ret = (response.StatusCode == HttpStatusCode.OK);
- }
- catch (Exception ex)
- {
- Log.WriteError(ex);
- ret = false;
- }
-
- Log.WriteEnd("CheckCRMWebServicesAccess");
- return ret;
- }
-
- private static bool CheckPermissions()
- {
- Log.WriteStart("CheckPermissions");
- bool res = false;
- try
- {
- string group = "PrivUserGroup";
- string user = WindowsIdentity.GetCurrent().Name.Split(new char[] { '\\' })[1];
- res = ActiveDirectoryUtils.IsUserInGroup(user, group);
- }
- catch (Exception ex)
- {
- Log.WriteError(ex);
- res = false;
- }
-
- Log.WriteEnd("CheckPermissions");
- return res;
- }
-
- private string GetDataBaseName(Guid organizationId)
- {
- string crmDatabaseName = "MSCRM_CONFIG";
- string databasename = "";
-
- SqlConnection connection = null;
- try
- {
- connection = new SqlConnection();
- connection.ConnectionString =
- string.Format("Server={1};Initial Catalog={0};Integrated Security=SSPI",
- crmDatabaseName, SqlServer);
-
- connection.Open();
-
- string commandText = string.Format("SELECT DatabaseName FROM dbo.Organization where id = '{0}'", organizationId);
- SqlCommand command = new SqlCommand(commandText, connection);
- databasename = command.ExecuteScalar().ToString();
-
- }
- catch (Exception ex)
- {
- Log.WriteError(ex);
- }
- finally
- {
- if (connection != null)
- connection.Dispose();
- }
-
- return databasename;
- }
-
- public long GetDBSize(Guid organizationId)
- {
- Log.WriteStart("GetDBSize");
- long res = 0;
-
- string databasename = GetDataBaseName(organizationId);
-
- SqlConnection connection = null;
- try
- {
- connection = new SqlConnection();
- connection.ConnectionString =
- string.Format("Server={1};Initial Catalog={0};Integrated Security=SSPI",
- databasename, SqlServer);
-
- connection.Open();
-
- string commandText = "SELECT ((dbsize ) * 8192 ) size FROM " + // + logsize
- "( " +
- "SELECT SUM(CONVERT(BIGINT,CASE WHEN status & 64 = 0 THEN size ELSE 0 END)) dbsize " +
- ", SUM(CONVERT(BIGINT,CASE WHEN status & 64 <> 0 THEN size ELSE 0 END)) logsize " +
- "FROM dbo.sysfiles " +
- ") big";
-
- SqlCommand command = new SqlCommand(commandText, connection);
- res = (long)command.ExecuteScalar();
-
- }
- catch (Exception ex)
- {
- Log.WriteError(ex);
- }
- finally
- {
- if (connection != null)
- connection.Dispose();
-
- }
-
- Log.WriteEnd("GetDBSize");
- return res;
-
- }
-
- public long GetMaxDBSize(Guid organizationId)
- {
- Log.WriteStart("GetMaxDBSize");
- long res = 0;
-
- string databasename = GetDataBaseName(organizationId);
-
- SqlConnection connection = null;
- try
- {
- connection = new SqlConnection();
- connection.ConnectionString =
- string.Format("Server={1};Initial Catalog={0};Integrated Security=SSPI",
- databasename, SqlServer);
-
- connection.Open();
-
- string commandText = "SELECT SUM(CONVERT(BIGINT,CASE WHEN status & 64 = 0 THEN maxsize ELSE 0 END)) dbsize FROM dbo.sysfiles";
-
- SqlCommand command = new SqlCommand(commandText, connection);
- res = (long)command.ExecuteScalar();
- if (res > 0) res = res * 8192;
-
- }
- catch (Exception ex)
- {
- Log.WriteError(ex);
- }
- finally
- {
- if (connection != null)
- connection.Dispose();
-
- }
-
- Log.WriteEnd("GetMaxDBSize");
- return res;
-
- }
-
- public ResultObject SetMaxDBSize(Guid organizationId, long maxSize)
- {
- ResultObject res = StartLog("SetMaxDBSize");
-
- string databasename = GetDataBaseName(organizationId);
-
- SqlConnection connection = null;
- try
- {
- connection = new SqlConnection();
- connection.ConnectionString =
- string.Format("Server={1};Initial Catalog={0};Integrated Security=SSPI",
- databasename, SqlServer);
-
- connection.Open();
-
- string maxSizeStr = maxSize == -1 ? "UNLIMITED" : (maxSize/(1024*1024)).ToString() +" MB";
-
- string commandText = "ALTER DATABASE [" + databasename + "] MODIFY FILE ( NAME = N'mscrm', MAXSIZE = " + maxSizeStr + " )";
-
- SqlCommand command = new SqlCommand(commandText, connection);
- command.ExecuteNonQuery();
-
- res.IsSuccess = true;
-
- }
- catch (Exception ex)
- {
- EndLog("SetMaxDBSize", res, CrmErrorCodes.CANNOT_CHANGE_CRM_ORGANIZATION_STATE, ex);
- }
- finally
- {
- if (connection != null)
- connection.Dispose();
-
- }
-
-
- EndLog("SetMaxDBSize");
- return res;
- }
-
- private bool CheckOrganizationUnique(string databaseName, string orgName)
- {
- Log.WriteStart("CheckOrganizationUnique");
- bool res = false;
-
- SqlConnection connection = null;
- try
- {
- connection = new SqlConnection();
- connection.ConnectionString =
- string.Format("Server={1};Initial Catalog={0};Integrated Security=SSPI",
- databaseName, SqlServer);
-
- connection.Open();
-
- string commandText = string.Format("SELECT COUNT(*) FROM dbo.Organization WHERE UniqueName = '{0}'", orgName);
- SqlCommand command = new SqlCommand(commandText, connection);
- int count = (int)command.ExecuteScalar();
- res = count == 0;
-
-
- }
- catch (Exception ex)
- {
- res = false;
- Log.WriteError(ex);
- }
- finally
- {
- if (connection != null)
- connection.Dispose();
-
- }
-
- Log.WriteEnd("CheckOrganizationUnique");
- return res;
- }
-
- private bool CheckSqlServerConnection()
- {
- Log.WriteStart("CheckSqlServerConnection");
- bool res = false;
- SqlConnection connection = null;
- try
- {
- connection = new SqlConnection();
- connection.ConnectionString =
- string.Format("server={0}; Integrated Security=SSPI",
- SqlServer);
-
- connection.Open();
- res = true;
- }
- catch (Exception ex)
- {
- Log.WriteError(ex);
- res = false;
- }
- finally
- {
- if (connection != null)
- connection.Dispose();
- }
-
- Log.WriteEnd("CheckSqlServerConnection");
-
- return res;
- }
-
- private bool CheckReportServerConnection()
- {
- Log.WriteStart("CheckReportServerConnection");
- bool ret = false;
- HttpWebResponse response = null;
- HttpWebRequest request;
-
- try
- {
- WindowsIdentity.GetCurrent();
-
- request = WebRequest.Create(ReportingServer) as HttpWebRequest;
-
- if (request != null)
- {
- request.UseDefaultCredentials = true;
- request.Credentials = CredentialCache.DefaultCredentials;
- response = request.GetResponse() as HttpWebResponse;
-
- }
- if (response != null)
- ret = (response.StatusCode == HttpStatusCode.OK);
- }
- catch (Exception ex)
- {
- Log.WriteError(ex);
- ret = false;
- }
-
- Log.WriteEnd("CheckReportServerConnection");
- return ret;
- }
-
- private OrganizationResult CheckCrmEnvironment(string strDataBaseName, string organizationUniqueName)
- {
- OrganizationResult retOrganization = StartLog("CheckCrmEnvironment");
- bool res = CheckSqlServerConnection();
-
- if (!res)
- {
- EndLog("CheckCrmEnvironment", retOrganization, CrmErrorCodes.CRM_SQL_SERVER_ERROR);
- return retOrganization;
- }
-
- res = CheckOrganizationUnique(strDataBaseName, organizationUniqueName);
- if (!res)
- {
- EndLog("CheckCrmEnvironment", retOrganization, CrmErrorCodes.CRM_ORGANIZATION_ALREADY_EXISTS);
- return retOrganization;
- }
-
- res = CheckReportServerConnection();
- if (!res)
- {
- EndLog("CheckCrmEnvironment", retOrganization, CrmErrorCodes.CRM_REPORT_SERVER_ERROR);
- return retOrganization;
- }
-
- res = CheckPermissions();
- if (!res)
- {
- EndLog("CheckCrmEnvironment", retOrganization, CrmErrorCodes.CRM_PERMISSIONS_ERROR);
- return retOrganization;
- }
-
- res = CheckCRMWebServicesAccess();
- if (!res)
- {
- EndLog("CheckCrmEnvironment", retOrganization, CrmErrorCodes.CRM_WEB_SERVICE_ERROR);
- return retOrganization;
- }
-
- EndLog("CheckCrmEnvironment");
- return retOrganization;
- }
-
- public OrganizationResult CreateOrganization(Guid organizationId, string organizationUniqueName, string organizationFriendlyName, string ou, string baseCurrencyCode, string baseCurrencyName, string baseCurrencySymbol, string initialUserDomainName, string initialUserFirstName, string initialUserLastName, string initialUserPrimaryEmail, string organizationCollation, long maxSize)
- {
- return CreateOrganizationInternal(organizationId, organizationUniqueName, organizationFriendlyName, ou , baseCurrencyCode, baseCurrencyName, baseCurrencySymbol, initialUserDomainName, initialUserFirstName, initialUserLastName, initialUserPrimaryEmail, organizationCollation, maxSize);
- }
-
- const string CRMSysAdminRoleStr = "Системный администратор;System Administrator";
-
- internal OrganizationResult CreateOrganizationInternal(Guid organizationId, string organizationUniqueName, string organizationFriendlyName, string ou, string baseCurrencyCode, string baseCurrencyName, string baseCurrencySymbol, string initialUserDomainName, string initialUserFirstName, string initialUserLastName, string initialUserPrimaryEmail, string organizationCollation, long maxSize)
- {
-
- OrganizationResult ret = StartLog("CreateOrganizationInternal");
-
- organizationUniqueName = Regex.Replace(organizationUniqueName, @"[^\dA-Za-z]", "-", RegexOptions.Compiled);
-
- // calculate UserRootPath
- string ldapstr = "";
-
- string[] ouItems = ou.Split('.');
- foreach (string ouItem in ouItems)
- {
- if (ldapstr.Length != 0) ldapstr += ",";
- ldapstr += "OU=" + ouItem;
- }
-
- string rootDomain = ServerSettings.ADRootDomain;
- string[] domainItems = rootDomain.Split('.');
- foreach (string domainItem in domainItems)
- ldapstr += ",DC=" + domainItem;
-
- ldapstr = @"LDAP://" + rootDomain + "/" + ldapstr;
-
-
-
- if (organizationId == Guid.Empty)
- throw new ArgumentException("OrganizationId is Guid.Empty");
-
- if (string.IsNullOrEmpty(organizationFriendlyName))
- throw new ArgumentNullException("organizationFriendlyName");
-
- if (string.IsNullOrEmpty(baseCurrencyCode))
- throw new ArgumentNullException("baseCurrencyCode");
-
- if (string.IsNullOrEmpty(baseCurrencySymbol))
- throw new ArgumentNullException("baseCurrencySymbol");
-
- if (string.IsNullOrEmpty(initialUserDomainName))
- throw new ArgumentNullException("initialUserDomainName");
-
- string strDataBaseName = "MSCRM_CONFIG";
-
- OrganizationResult retCheckEn = CheckCrmEnvironment(strDataBaseName, organizationUniqueName);
-
- if (!retCheckEn.IsSuccess)
- {
- ret.ErrorCodes.AddRange(retCheckEn.ErrorCodes);
- EndLog("CreateOrganizationInternal", ret, null, null);
- return ret;
- }
-
- try
- {
-
- Uri serviceUrl = new Uri(CRMServiceUrl);
-
- DeploymentServiceClient deploymentService = Microsoft.Xrm.Sdk.Deployment.Proxy.ProxyClientHelper.CreateClient(serviceUrl);
- if (!String.IsNullOrEmpty(UserName))
- deploymentService.ClientCredentials.Windows.ClientCredential = new NetworkCredential(UserName, Password);
-
- Microsoft.Xrm.Sdk.Deployment.Organization org = new Microsoft.Xrm.Sdk.Deployment.Organization
- {
- Id = organizationId,
- UniqueName = organizationUniqueName,
- FriendlyName = organizationFriendlyName,
- SqlServerName = SqlServer,
- SrsUrl = ReportingServer,
- BaseCurrencyCode = baseCurrencyCode,
- BaseCurrencyName = baseCurrencyName,
- BaseCurrencySymbol = baseCurrencySymbol,
- SqlCollation = organizationCollation,
- State = Microsoft.Xrm.Sdk.Deployment.OrganizationState.Enabled
- };
-
- BeginCreateOrganizationRequest req = new BeginCreateOrganizationRequest
- {
- Organization = org
- };
-
- if (!String.IsNullOrEmpty(UserName))
- {
- req.SysAdminName = UserName;
- }
-
- BeginCreateOrganizationResponse resp = deploymentService.Execute(req) as BeginCreateOrganizationResponse;
-
- if (resp == null)
- throw new ArgumentException("BeginCreateOrganizationResponse is Null");
-
- EntityInstanceId id = new EntityInstanceId();
- id.Name = org.UniqueName;
-
- Microsoft.Xrm.Sdk.Deployment.OrganizationState OperationState = Microsoft.Xrm.Sdk.Deployment.OrganizationState.Pending;
-
- int timeout = 30000;
-
- do
- {
- Thread.Sleep(timeout);
- try
- {
- Microsoft.Xrm.Sdk.Deployment.Organization getorg
- = (Microsoft.Xrm.Sdk.Deployment.Organization)deploymentService.Retrieve(DeploymentEntityType.Organization, id);
- OperationState = getorg.State;
- }
- catch { }
- } while ((OperationState != Microsoft.Xrm.Sdk.Deployment.OrganizationState.Enabled) &&
- (OperationState != Microsoft.Xrm.Sdk.Deployment.OrganizationState.Failed));
-
- if (OperationState == Microsoft.Xrm.Sdk.Deployment.OrganizationState.Failed)
- throw new ArgumentException("Create organization failed.");
-
- // update UserRootPath setting
- Microsoft.Xrm.Sdk.Deployment.ConfigurationEntity orgSettings = new Microsoft.Xrm.Sdk.Deployment.ConfigurationEntity
- {
- Id = org.Id,
- LogicalName = "Organization"
- };
- orgSettings.Attributes = new Microsoft.Xrm.Sdk.Deployment.AttributeCollection();
- orgSettings.Attributes.Add(new KeyValuePair("UserRootPath", ldapstr));
- Microsoft.Xrm.Sdk.Deployment.UpdateAdvancedSettingsRequest reqUpdateSettings = new Microsoft.Xrm.Sdk.Deployment.UpdateAdvancedSettingsRequest
- {
- Entity = orgSettings
- };
- Microsoft.Xrm.Sdk.Deployment.UpdateAdvancedSettingsResponse respUpdateSettings = (Microsoft.Xrm.Sdk.Deployment.UpdateAdvancedSettingsResponse) deploymentService.Execute(reqUpdateSettings);
-
- // DB size limit
- if (maxSize!=-1)
- SetMaxDBSize(organizationId, maxSize);
-
- int tryTimeout = 30000;
- int tryCount = 10;
-
- bool success = false;
- int tryItem = 0;
-
- while (!success)
- {
-
- try
- {
- Thread.Sleep(tryTimeout);
-
- OrganizationServiceProxy _serviceProxy = GetOrganizationProxy(organizationUniqueName, 0, 0);
-
- string ldap = "";
-
- Guid SysAdminGuid = RetrieveSystemUser(GetDomainName(initialUserDomainName), initialUserFirstName, initialUserLastName, CRMSysAdminRoleStr, _serviceProxy, ref ldap, 0);
-
- success = true;
-
- }
- catch (Exception exc)
- {
- tryItem++;
- if (tryItem >= tryCount)
- success = true;
- }
- }
-
-
- }
- catch (Exception ex)
- {
- HostedSolutionLog.LogError(ex);
- EndLog("CheckCrmEnvironment", ret, CrmErrorCodes.CREATE_CRM_ORGANIZATION_GENERAL_ERROR, ex);
- return ret;
-
- }
-
- EndLog("CheckCrmEnvironment");
-
- return ret;
- }
-
- private string GetDomainName(string username)
- {
- string domain = ActiveDirectoryUtils.GetNETBIOSDomainName(ServerSettings.ADRootDomain);
- string ret = string.Format(@"{0}\{1}", domain, username);
- return ret;
- }
-
- public string[] GetSupportedCollationNames()
- {
- return GetSupportedCollationNamesInternal(SqlServer);
- }
-
- internal static string[] GetSupportedCollationNamesInternal(string SqlServer)
- {
- HostedSolutionLog.LogStart("GetSupportedCollationNamesInternal");
-
- List ret = new List();
-
- string databaseName = "MSCRM_CONFIG";
-
- SqlConnection connection = null;
- try
- {
- connection = new SqlConnection();
- connection.ConnectionString =
- string.Format("Server={1};Initial Catalog={0};Integrated Security=SSPI",
- databaseName, SqlServer);
-
- connection.Open();
-
- string commandText = "select * from fn_helpcollations() where " +
- "(name not like '%_WS') AND (name not like '%_KS') AND (name not like '%_100_%') " +
- " AND (name not like 'SQL_%') " +
- " order by name";
- SqlCommand command = new SqlCommand(commandText, connection);
- SqlDataReader reader = command.ExecuteReader();
-
- while (reader.Read())
- {
- string name = reader["name"] as string;
- ret.Add(name);
- }
-
- }
- catch (Exception)
- {
- }
- finally
- {
- if (connection != null)
- connection.Dispose();
-
- }
-
- HostedSolutionLog.LogEnd("GetSupportedCollationNamesInternal");
- return ret.ToArray();
- }
-
- public Currency[] GetCurrencyList()
- {
- return GetCurrencyListInternal();
- }
-
- private Currency[] GetCurrencyListInternal()
- {
- HostedSolutionLog.LogStart("GetCurrencyListInternal");
- List retList = new List();
-
- CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.AllCultures & ~CultureTypes.NeutralCultures);
-
- foreach (CultureInfo cultire in cultures)
- {
- try
- {
- RegionInfo Region = new RegionInfo(cultire.LCID);
-
- Console.WriteLine(cultire.NativeName + " " + Region.CurrencyNativeName);
-
- Currency currency = new Currency();
- currency.RegionName = Region.NativeName;
- currency.CurrencyName = Region.CurrencyNativeName;
- currency.CurrencyCode = Region.ISOCurrencySymbol;
- currency.CurrencySymbol = Region.CurrencySymbol;
- retList.Add(currency);
-
- }
- catch
- {
- continue;
- }
- }
-
- retList.Sort(delegate(Currency a, Currency b) { return a.RegionName.CompareTo(b.RegionName); });
-
- HostedSolutionLog.LogEnd("GetCurrencyListInternal");
- return retList.ToArray();
- }
-
-
- public ResultObject DeleteOrganization(Guid orgId)
- {
- return DeleteOrganizationInternal(orgId);
- }
-
- internal ResultObject DeleteOrganizationInternal(Guid orgId)
- {
- ResultObject res = StartLog("DeleteOrganizationInternal");
-
-
- res.IsSuccess = true;
- try
- {
- Uri serviceUrl = new Uri(CRMServiceUrl);
-
- DeploymentServiceClient deploymentService = Microsoft.Xrm.Sdk.Deployment.Proxy.ProxyClientHelper.CreateClient(serviceUrl);
-
- EntityInstanceId i = new EntityInstanceId();
- i.Id = orgId; //Organisation Id
-
- Microsoft.Xrm.Sdk.Deployment.Organization org = (Microsoft.Xrm.Sdk.Deployment.Organization)deploymentService.Retrieve(DeploymentEntityType.Organization, i);
-
- org.State = Microsoft.Xrm.Sdk.Deployment.OrganizationState.Disabled;
-
- Microsoft.Xrm.Sdk.Deployment.UpdateRequest updateRequest = new Microsoft.Xrm.Sdk.Deployment.UpdateRequest();
- updateRequest.Entity = org;
-
- deploymentService.Execute(updateRequest);
-
- }
- catch (Exception ex)
- {
- EndLog("DeleteOrganizationInternal", res, CrmErrorCodes.DELETE_CRM_ORGANIZATION_GENERAL_ERROR, ex);
- return res;
-
- }
-
-
- EndLog("DeleteOrganizationInternal");
- return res;
- }
-
- public override void DeleteServiceItems(ServiceProviderItem[] items)
- {
- foreach (ServiceProviderItem item in items)
- {
- try
- {
- if (item is Organization)
- {
- Organization org = item as Organization;
- DeleteOrganization(org.CrmOrganizationId);
- }
-
- }
- catch (Exception ex)
- {
- Log.WriteError(String.Format("Error deleting '{0}' {1}", item.Name, item.GetType().Name), ex);
- }
- }
- base.DeleteServiceItems(items);
-
- }
-
- private static void EndLog(string message, ResultObject res, string errorCode, Exception ex)
- {
- if (res != null)
- {
- res.IsSuccess = false;
-
- if (!string.IsNullOrEmpty(errorCode))
- res.ErrorCodes.Add(errorCode);
- }
-
- if (ex != null)
- HostedSolutionLog.LogError(ex);
-
- HostedSolutionLog.LogEnd(message);
- }
-
- private static void EndLog(string message, ResultObject res, string errorCode)
- {
- EndLog(message, res, errorCode, null);
- }
-
- private static void EndLog(string message, ResultObject res)
- {
- EndLog(message, res, null);
- }
-
- private static void EndLog(string message)
- {
- EndLog(message, null);
- }
-
- private static T StartLog(string message) where T : ResultObject, new()
- {
- HostedSolutionLog.LogStart(message);
- T res = new T();
- res.IsSuccess = true;
- return res;
- }
-
- public UserResult CreateCRMUser(OrganizationUser user, string orgName, Guid organizationId, Guid baseUnitId, int CALType)
- {
- return CreateCRMUserInternal(user, orgName, organizationId, baseUnitId, CALType);
- }
-
- internal UserResult CreateCRMUserInternal(OrganizationUser user, string orgName, Guid organizationId, Guid businessUnitId, int CALType)
- {
- UserResult res = StartLog("CreateCRMUserInternal");
-
- try
- {
- if (user == null)
- throw new ArgumentNullException("user");
-
- if (string.IsNullOrEmpty(orgName))
- throw new ArgumentNullException("orgName");
-
- if (organizationId == Guid.Empty)
- throw new ArgumentException("organizationId");
-
- if (businessUnitId == Guid.Empty)
- throw new ArgumentException("businessUnitId");
-
- try
- {
- OrganizationServiceProxy _serviceProxy = GetOrganizationProxy(orgName);
-
-
- string ldap = "";
- Guid guid = RetrieveSystemUser(user.DomainUserName, user.FirstName, user.LastName, CRMSysAdminRoleStr, _serviceProxy, ref ldap, CALType);
-
- user.CrmUserId = guid;
- res.Value = user;
-
- }
- catch (Exception ex)
- {
- EndLog("CreateCRMUserInternal", res, CrmErrorCodes.CANNOT_CREATE_CRM_USER, ex);
- return res;
- }
- }
- catch (Exception ex)
- {
- EndLog("CreateCRMUserInternal", res, CrmErrorCodes.CANNOT_CREATE_CRM_USER_GENERAL_ERROR, ex);
- return res;
-
- }
-
- EndLog("CreateCRMUserInternal");
- return res;
- }
-
- private static Guid CreateSystemUser(String userName, String firstName,
- String lastName, String domain, String roleStr,
- OrganizationServiceProxy serviceProxy, ref String ldapPath, int CALType)
- {
-
- if (serviceProxy.ServiceConfiguration.AuthenticationType == AuthenticationProviderType.LiveId ||
- serviceProxy.ServiceConfiguration.AuthenticationType == AuthenticationProviderType.OnlineFederation)
- throw new Exception(String.Format("To run this sample, {0} {1} must be an active system user in your Microsoft Dynamics CRM Online organization.", firstName, lastName));
-
- Guid userId = Guid.Empty;
-
- Microsoft.Xrm.Sdk.Query.QueryExpression businessUnitQuery = new Microsoft.Xrm.Sdk.Query.QueryExpression
- {
- EntityName = BusinessUnit.EntityLogicalName,
- ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet("businessunitid"),
- Criteria =
- {
- Conditions =
- {
- new Microsoft.Xrm.Sdk.Query.ConditionExpression("parentbusinessunitid",
- Microsoft.Xrm.Sdk.Query.ConditionOperator.Null)
- }
- }
- };
-
- BusinessUnit defaultBusinessUnit = serviceProxy.RetrieveMultiple(
- businessUnitQuery).Entities[0].ToEntity();
-
- // Retrieve the specified security role.
- Role role = RetrieveRoleByName(serviceProxy, roleStr);
-
- // CALType and AccessMode
- int accessmode = CALType / 10;
- int caltype = CALType % 10;
-
- //Create a new system user.
- SystemUser user = new SystemUser
- {
- DomainName = userName,
- FirstName = firstName,
- LastName = lastName,
- BusinessUnitId = new EntityReference
- {
- LogicalName = BusinessUnit.EntityLogicalName,
- Name = BusinessUnit.EntityLogicalName,
- Id = defaultBusinessUnit.Id
- },
- CALType = new OptionSetValue(caltype),
- AccessMode = new OptionSetValue(accessmode)
- };
- userId = serviceProxy.Create(user);
-
- // Assign the security role to the newly created Microsoft Dynamics CRM user.
- AssociateRequest associate = new AssociateRequest()
- {
- Target = new EntityReference(SystemUser.EntityLogicalName, userId),
- RelatedEntities = new EntityReferenceCollection()
- {
- new EntityReference(Role.EntityLogicalName, role.Id),
- },
- Relationship = new Relationship("systemuserroles_association")
- };
- serviceProxy.Execute(associate);
-
- return userId;
- }
-
-
- public static Guid RetrieveSystemUser(String userName, String firstName,
- String lastName, String roleStr, OrganizationServiceProxy serviceProxy,
- ref String ldapPath,
- int CALType)
- {
- String domain;
- Guid userId = Guid.Empty;
-
- if (serviceProxy == null)
- throw new ArgumentNullException("serviceProxy");
-
- if (String.IsNullOrWhiteSpace(userName))
- throw new ArgumentNullException("UserName");
-
- if (String.IsNullOrWhiteSpace(firstName))
- throw new ArgumentNullException("FirstName");
-
- if (String.IsNullOrWhiteSpace(lastName))
- throw new ArgumentNullException("LastName");
-
- if (String.IsNullOrWhiteSpace(roleStr))
- throw new ArgumentNullException("Role");
-
- // Obtain the current user's information.
- Microsoft.Crm.Sdk.Messages.WhoAmIRequest who = new Microsoft.Crm.Sdk.Messages.WhoAmIRequest();
- Microsoft.Crm.Sdk.Messages.WhoAmIResponse whoResp = (Microsoft.Crm.Sdk.Messages.WhoAmIResponse)serviceProxy.Execute(who);
- Guid currentUserId = whoResp.UserId;
-
- SystemUser currentUser =
- serviceProxy.Retrieve(SystemUser.EntityLogicalName, currentUserId, new Microsoft.Xrm.Sdk.Query.ColumnSet("domainname")).ToEntity();
-
- // Extract the domain and create the LDAP object.
- String[] userPath = currentUser.DomainName.Split(new char[] { '\\' });
- if (userPath.Length > 1)
- domain = userPath[0] + "\\";
- else
- domain = String.Empty;
-
- // Create the system user in Microsoft Dynamics CRM if the user doesn't
- // already exist.
- Microsoft.Xrm.Sdk.Query.QueryExpression userQuery = new Microsoft.Xrm.Sdk.Query.QueryExpression
- {
- EntityName = SystemUser.EntityLogicalName,
- ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet("systemuserid"),
- Criteria =
- {
- FilterOperator = Microsoft.Xrm.Sdk.Query.LogicalOperator.Or,
- Filters =
- {
- new Microsoft.Xrm.Sdk.Query.FilterExpression
- {
- FilterOperator = Microsoft.Xrm.Sdk.Query.LogicalOperator.And,
- Conditions =
- {
- new Microsoft.Xrm.Sdk.Query.ConditionExpression("domainname", Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal, domain + userName)
- }
- },
- new Microsoft.Xrm.Sdk.Query.FilterExpression
- {
- FilterOperator = Microsoft.Xrm.Sdk.Query.LogicalOperator.And,
- Conditions =
- {
- new Microsoft.Xrm.Sdk.Query.ConditionExpression("firstname", Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal, firstName),
- new Microsoft.Xrm.Sdk.Query.ConditionExpression("lastname", Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal, lastName)
- }
- }
- }
-
- }
- };
-
- DataCollection existingUsers = (DataCollection)serviceProxy.RetrieveMultiple(userQuery).Entities;
-
- SystemUser existingUser = null;
- if (existingUsers.Count > 0)
- existingUser = existingUsers[0].ToEntity();
-
- if (existingUser != null)
- {
- userId = existingUser.SystemUserId.Value;
-
- // Check to make sure the user is assigned the correct role.
- Role role = RetrieveRoleByName(serviceProxy, roleStr);
-
- // Associate the user with the role when needed.
- if (!UserInRole(serviceProxy, userId, role.Id))
- {
- AssociateRequest associate = new AssociateRequest()
- {
- Target = new EntityReference(SystemUser.EntityLogicalName, userId),
- RelatedEntities = new EntityReferenceCollection()
- {
- new EntityReference(Role.EntityLogicalName, role.Id)
- },
- Relationship = new Relationship("systemuserroles_association")
- };
- serviceProxy.Execute(associate);
- }
-
- }
- else
- {
- userId = CreateSystemUser(userName, firstName, lastName, domain,
- roleStr, serviceProxy, ref ldapPath, CALType);
- }
-
- return userId;
- }
-
- private static Role RetrieveRoleByName(OrganizationServiceProxy serviceProxy,
- String roleSplitStr)
- {
- string[] RolesStr = roleSplitStr.Split(';');
-
- foreach (string roleStr in RolesStr)
- {
-
- Microsoft.Xrm.Sdk.Query.QueryExpression roleQuery = new Microsoft.Xrm.Sdk.Query.QueryExpression
- {
- EntityName = Role.EntityLogicalName,
- ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet("roleid"),
- Criteria =
- {
- Conditions =
- {
- new Microsoft.Xrm.Sdk.Query.ConditionExpression("name", Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal, roleStr)
- }
- }
- };
-
- DataCollection roles = serviceProxy.RetrieveMultiple(roleQuery).Entities;
-
- if (roles.Count > 0) return roles[0].ToEntity();
- }
-
- return null;
- }
-
- private static bool UserInRole(OrganizationServiceProxy serviceProxy,
- Guid userId, Guid roleId)
- {
- // Establish a SystemUser link for a query.
- Microsoft.Xrm.Sdk.Query.LinkEntity systemUserLink = new Microsoft.Xrm.Sdk.Query.LinkEntity()
- {
- LinkFromEntityName = SystemUserRoles.EntityLogicalName,
- LinkFromAttributeName = "systemuserid",
- LinkToEntityName = SystemUser.EntityLogicalName,
- LinkToAttributeName = "systemuserid",
- LinkCriteria =
- {
- Conditions =
- {
- new Microsoft.Xrm.Sdk.Query.ConditionExpression(
- "systemuserid", Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal, userId)
- }
- }
- };
-
- // Build the query.
- Microsoft.Xrm.Sdk.Query.QueryExpression query = new Microsoft.Xrm.Sdk.Query.QueryExpression()
- {
- EntityName = Role.EntityLogicalName,
- ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet("roleid"),
- LinkEntities =
- {
- new Microsoft.Xrm.Sdk.Query.LinkEntity()
- {
- LinkFromEntityName = Role.EntityLogicalName,
- LinkFromAttributeName = "roleid",
- LinkToEntityName = SystemUserRoles.EntityLogicalName,
- LinkToAttributeName = "roleid",
- LinkEntities = {systemUserLink}
- }
- },
- Criteria =
- {
- Conditions =
- {
- new Microsoft.Xrm.Sdk.Query.ConditionExpression("roleid", Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal, roleId)
- }
- }
- };
-
- // Retrieve matching roles.
- EntityCollection ec = serviceProxy.RetrieveMultiple(query);
-
- if (ec.Entities.Count > 0)
- return true;
-
- return false;
- }
-
- int GetOrganizationProxyTryCount = 10;
- int GetOrganizationProxyTryTimeout = 30000;
-
- private OrganizationServiceProxy GetOrganizationProxy(string orgName)
- {
- return GetOrganizationProxy(orgName, GetOrganizationProxyTryCount, GetOrganizationProxyTryTimeout);
- }
-
- private OrganizationServiceProxy GetOrganizationProxy(string orgName, int TryCount, int TryTimeout)
- {
-
- Uri OrganizationUri = GetOrganizationAddress(orgName);
-
- OrganizationServiceProxy r = null;
-
- bool success = false;
- int tryItem = 0;
- Exception exception = null;
-
- while (!success)
- {
-
- try
- {
- // Set IServiceManagement for the current organization.
- IServiceManagement orgServiceManagement =
- ServiceConfigurationFactory.CreateManagement(
- OrganizationUri);
-
- r = new OrganizationServiceProxy(
- orgServiceManagement,
- GetUserLogonCredentials());
-
- success = true;
-
- }
- catch (Exception exc)
- {
- Thread.Sleep(TryTimeout);
- tryItem++;
- if (tryItem >= TryCount)
- {
- exception = exc;
- success = true;
- }
- }
-
- }
-
- if (exception != null)
- throw new ArgumentException(exception.ToString());
-
- r.EnableProxyTypes();
-
- return r;
- }
-
- protected virtual ClientCredentials GetUserLogonCredentials()
- {
- ClientCredentials credentials = new ClientCredentials();
-
- if (String.IsNullOrEmpty(UserName))
- {
- credentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials;
- }
- else
- {
- credentials.UserName.UserName = UserName;
- credentials.UserName.Password = Password;
- }
-
- return credentials;
- }
-
- private DiscoveryServiceProxy GetDiscoveryProxy()
- {
-
- IServiceManagement serviceManagement =
- ServiceConfigurationFactory.CreateManagement(
- new Uri(CRMDiscoveryUri));
-
- ClientCredentials Credentials = GetUserLogonCredentials();
-
- DiscoveryServiceProxy r = new DiscoveryServiceProxy(serviceManagement, Credentials);
-
- return r;
- }
-
-
- public OrganizationDetailCollection DiscoverOrganizations(IDiscoveryService service)
- {
- if (service == null) throw new ArgumentNullException("service");
- RetrieveOrganizationsRequest orgRequest = new RetrieveOrganizationsRequest();
- RetrieveOrganizationsResponse orgResponse =
- (RetrieveOrganizationsResponse)service.Execute(orgRequest);
-
- return orgResponse.Details;
- }
-
- protected virtual Uri GetOrganizationAddress(string orgName)
- {
- //string url = "https://" + ProviderSettings[Constants.AppRootDomain] + ":" + ProviderSettings[Constants.Port] + "/" + orgName + "/XRMServices/2011/Organization.svc";
-
- string url;
-
- string organizationWebServiceUri = ProviderSettings[Constants.OrganizationWebService];
-
- if (!String.IsNullOrEmpty(organizationWebServiceUri))
- {
- url = "https://" + organizationWebServiceUri + ":" + ProviderSettings[Constants.Port] + "/" + orgName + "/XRMServices/2011/Organization.svc";
- }
- else
- {
- url = "https://" + orgName + "." + ProviderSettings[Constants.IFDWebApplicationRootDomain] + ":" + ProviderSettings[Constants.Port] + "/XRMServices/2011/Organization.svc";
- }
-
- try
- {
-
- using (DiscoveryServiceProxy serviceProxy = GetDiscoveryProxy())
- {
- // Obtain organization information from the Discovery service.
- if (serviceProxy != null)
- {
- // Obtain information about the organizations that the system user belongs to.
- OrganizationDetailCollection orgs = DiscoverOrganizations(serviceProxy);
-
- for (int n = 0; n < orgs.Count; n++)
- {
- if (orgs[n].UniqueName == orgName)
- {
- // Return the organization Uri.
- return new System.Uri(orgs[n].Endpoints[EndpointType.OrganizationService]);
- }
- }
-
- }
- }
- }
- catch { }
-
- return new Uri(url);
-
- }
-
-
- internal CRMBusinessUnitsResult GetOrganizationBusinessUnitsInternal(Guid organizationId, string orgName)
- {
- CRMBusinessUnitsResult res = StartLog("GetOrganizationBusinessUnitsInternal");
-
- try
- {
- if (organizationId == Guid.Empty)
- throw new ArgumentException("organizationId");
-
- if (string.IsNullOrEmpty(orgName))
- throw new ArgumentNullException("orgName");
-
- OrganizationServiceProxy serviceProxy;
-
- try
- {
- serviceProxy = GetOrganizationProxy(orgName);
- }
- catch (Exception ex)
- {
- EndLog("GetOrganizationBusinessUnitsInternal", res, CrmErrorCodes.CANNOT_GET_CRM_SERVICE, ex);
- return res;
- }
-
- DataCollection BusinessUnits;
-
- try
- {
-
- Microsoft.Xrm.Sdk.Query.QueryExpression businessUnitQuery = new Microsoft.Xrm.Sdk.Query.QueryExpression
- {
- EntityName = BusinessUnit.EntityLogicalName,
- ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet(new string[] { "businessunitid", "name" }),
- Criteria =
- {
- Conditions =
- {
- new Microsoft.Xrm.Sdk.Query.ConditionExpression("parentbusinessunitid",
- Microsoft.Xrm.Sdk.Query.ConditionOperator.Null)
- }
- }
- };
-
- BusinessUnits = serviceProxy.RetrieveMultiple(
- businessUnitQuery).Entities;
-
- }
- catch (Exception ex)
- {
- EndLog("GetOrganizationBusinessUnitsInternal", res, CrmErrorCodes.CANNOT_GET_CRM_BUSINESS_UNITS, ex);
- return res;
- }
-
- List businessUnits = new List();
-
- try
- {
- for (int i = 0; i < BusinessUnits.Count; i++)
- {
- BusinessUnit bu = BusinessUnits[i].ToEntity();
-
- CRMBusinessUnit unit = new CRMBusinessUnit();
- unit.BusinessUnitId = (Guid)bu.BusinessUnitId;
- unit.BusinessUnitName = bu.Name;
-
- if (unit.BusinessUnitName == null)
- unit.BusinessUnitName = "default";
-
- businessUnits.Add(unit);
-
- }
-
- res.Value = businessUnits;
- }
- catch (Exception ex)
- {
- EndLog("GetOrganizationBusinessUnitsInternal", res, CrmErrorCodes.CANNOT_FILL_BASE_UNITS_COLLECTION,
- ex);
- return res;
- }
- }
- catch (Exception ex)
- {
- EndLog("GetOrganizationBusinessUnitsInternal", res, CrmErrorCodes.GET_ORGANIZATION_BUSINESS_UNITS_GENERAL_ERROR,
- ex);
- return res;
-
- }
-
- EndLog("GetOrganizationBusinessUnitsInternal");
- return res;
-
- }
-
- public CRMBusinessUnitsResult GetOrganizationBusinessUnits(Guid organizationId, string orgName)
- {
- return GetOrganizationBusinessUnitsInternal(organizationId, orgName);
- }
-
- public CrmRolesResult GetAllCrmRoles(string orgName, Guid businessUnitId)
- {
- return GetAllCrmRolesInternal(orgName, businessUnitId);
- }
-
- public CrmRolesResult GetCrmUserRoles(string orgName, Guid userId)
- {
- return GetCrmUserRolesInternal(userId, orgName);
- }
-
- public EntityCollection GetUserRoles(Guid userId, string orgName)
- {
- OrganizationServiceProxy serviceProxy = GetOrganizationProxy(orgName);
-
- // Establish a SystemUser link for a query.
- Microsoft.Xrm.Sdk.Query.LinkEntity systemUserLink = new Microsoft.Xrm.Sdk.Query.LinkEntity()
- {
- LinkFromEntityName = SystemUserRoles.EntityLogicalName,
- LinkFromAttributeName = "systemuserid",
- LinkToEntityName = SystemUser.EntityLogicalName,
- LinkToAttributeName = "systemuserid",
- LinkCriteria =
- {
- Conditions =
- {
- new Microsoft.Xrm.Sdk.Query.ConditionExpression(
- "systemuserid", Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal, userId)
- }
- }
- };
-
- // Build the query.
- Microsoft.Xrm.Sdk.Query.QueryExpression query = new Microsoft.Xrm.Sdk.Query.QueryExpression()
- {
- EntityName = Role.EntityLogicalName,
- ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet("roleid"),
- LinkEntities =
- {
- new Microsoft.Xrm.Sdk.Query.LinkEntity()
- {
- LinkFromEntityName = Role.EntityLogicalName,
- LinkFromAttributeName = "roleid",
- LinkToEntityName = SystemUserRoles.EntityLogicalName,
- LinkToAttributeName = "roleid",
- LinkEntities = {systemUserLink}
- }
- }
- };
-
- // Retrieve matching roles.
- EntityCollection relations = serviceProxy.RetrieveMultiple(query);
-
- return relations;
- }
-
- internal CrmRolesResult GetCrmUserRolesInternal(Guid userId, string orgName)
- {
- CrmRolesResult res = StartLog("GetCrmUserRolesInternal");
-
-
- try
- {
- EntityCollection relations;
-
- if (userId == Guid.Empty)
- throw new ArgumentException("userId");
-
- if (string.IsNullOrEmpty(orgName))
- throw new ArgumentNullException("orgName");
-
- try
- {
- relations = GetUserRoles(userId, orgName);
- }
- catch (Exception ex)
- {
- EndLog("GetCrmUserRolesInternal", res, CrmErrorCodes.CANNOT_GET_CRM_USER_ROLES, ex);
- return res;
- }
-
- try
- {
- res.Value = FillCrmRoles(relations, true, Guid.Empty);
- }
- catch (Exception ex)
- {
- EndLog("GetCrmUserRolesInternal", res, CrmErrorCodes.CANNOT_FILL_ROLES_COLLECTION, ex);
- return res;
- }
- }
- catch (Exception ex)
- {
- EndLog("GetCrmUserRolesInternal", res, CrmErrorCodes.GET_CRM_USER_ROLE_GENERAL_ERROR, ex);
- return res;
- }
-
- EndLog("GetCrmUserRolesInternal");
- return res;
- }
-
- static string excludedRolesStr = ";пользователь поддержки;support user;";
-
- private static List FillCrmRoles(EntityCollection entities, bool isUserRole, Guid businessUnitId)
- {
- List res = new List();
-
- foreach (Entity current in entities.Entities)
- {
- Role role = current.ToEntity();
-
- if (role == null) continue;
-
- if (businessUnitId != Guid.Empty)
- {
- if (businessUnitId != role.BusinessUnitId.Id)
- continue;
- }
-
- string roleName = role.Name;
-
- if (roleName!=null)
- if (excludedRolesStr.IndexOf(";" + roleName.ToLower() + ";") != -1)
- continue;
-
- CrmRole crmRole = new CrmRole();
- crmRole.IsCurrentUserRole = isUserRole;
- crmRole.RoleId = (Guid)role.RoleId;
- crmRole.RoleName = roleName;
-
- res.Add(crmRole);
- }
-
- return res;
- }
-
-
- private static List FillCrmRoles(EntityCollection entities, Guid businessUnitId)
- {
- return FillCrmRoles(entities, false, businessUnitId);
- }
-
- internal CrmRolesResult GetAllCrmRolesInternal(string orgName, Guid businessUnitId)
- {
- CrmRolesResult res = StartLog("GetAllCrmRoles");
-
- try
- {
- if (string.IsNullOrEmpty(orgName))
- throw new ArgumentNullException("orgName");
-
- EntityCollection roles;
- try
- {
- OrganizationServiceProxy serviceProxy = GetOrganizationProxy(orgName);
-
- Microsoft.Xrm.Sdk.Query.QueryExpression roleQuery = new Microsoft.Xrm.Sdk.Query.QueryExpression
- {
- EntityName = Role.EntityLogicalName,
- ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet(new string[] { "roleid", "name", "businessunitid" }),
- };
-
- roles = serviceProxy.RetrieveMultiple(roleQuery);
-
-
- }
- catch (Exception ex)
- {
- EndLog("GetAllCrmRoles", res, CrmErrorCodes.CANNOT_GET_ALL_CRM_ROLES, ex);
- return res;
- }
-
- try
- {
- List crmRoles = FillCrmRoles(roles, businessUnitId);
- res.Value = crmRoles;
- }
- catch (Exception ex)
- {
- EndLog("GetAllCrmRoles", res, CrmErrorCodes.CANNOT_FILL_ROLES_COLLECTION, ex);
- return res;
- }
- }
- catch (Exception ex)
- {
- EndLog("GetAllCrmRoles", res, CrmErrorCodes.GET_ALL_CRM_ROLES_GENERAL_ERROR, ex);
- return res;
- }
-
- EndLog("GetAllCrmRoles");
- return res;
- }
-
- public ResultObject SetUserRoles(string orgName, Guid userId, Guid[] roles)
- {
- return SetUserRolesInternal(orgName, userId, roles);
- }
-
- internal ResultObject SetUserRolesInternal(string orgName, Guid userId, Guid[] roles)
- {
- CrmRolesResult res = StartLog("SetUserRolesInternal");
-
- try
- {
- if (string.IsNullOrEmpty(orgName))
- throw new ArgumentNullException("orgName");
-
- if (userId == Guid.Empty)
- throw new ArgumentException("userId");
-
- if (roles == null)
- throw new ArgumentNullException("roles");
-
- OrganizationServiceProxy serviceProxy = GetOrganizationProxy(orgName);
-
-
- CrmRolesResult tmpRoles = GetCrmUserRoles(orgName, userId);
- res.ErrorCodes.AddRange(tmpRoles.ErrorCodes);
-
- if (!tmpRoles.IsSuccess)
- return res;
-
- List remRoles = new List();
-
- for (int i = 0; i < tmpRoles.Value.Count; i++)
- {
- if (Array.Find(roles, delegate(Guid current) { return current == tmpRoles.Value[i].RoleId; }) == Guid.Empty)
- {
- remRoles.Add(tmpRoles.Value[i].RoleId);
- }
- }
-
- try
- {
- DisassociateRequest removeRole = new DisassociateRequest()
- {
- Target = new EntityReference(SystemUser.EntityLogicalName, userId),
- RelatedEntities = new EntityReferenceCollection(),
- Relationship = new Relationship("systemuserroles_association")
- };
-
- for (int i = 0; i < remRoles.Count; i++)
- removeRole.RelatedEntities.Add(new EntityReference(Role.EntityLogicalName, remRoles[i]));
-
- serviceProxy.Execute(removeRole);
-
- }
- catch (Exception ex)
- {
- EndLog("SetUserRolesInternal", res, CrmErrorCodes.CANNOT_REMOVE_CRM_USER_ROLES, ex);
- return res;
- }
-
-
- try
- {
- // Assign the security role to the newly created Microsoft Dynamics CRM user.
- AssociateRequest associate = new AssociateRequest()
- {
- Target = new EntityReference(SystemUser.EntityLogicalName, userId),
- RelatedEntities = new EntityReferenceCollection(),
- Relationship = new Relationship("systemuserroles_association")
- };
-
- for (int i = 0; i < roles.Length; i++)
- {
- bool find = false;
- foreach (CrmRole current in tmpRoles.Value)
- {
- if (current.RoleId == roles[i])
- find = true;
- }
- if (find) continue;
-
- associate.RelatedEntities.Add(new EntityReference(Role.EntityLogicalName, roles[i]));
- }
-
- serviceProxy.Execute(associate);
- }
- catch (Exception ex)
- {
- EndLog("SetUserRolesInternal", res, CrmErrorCodes.CANNOT_ASSIGN_CRM_USER_ROLES, ex);
- return res;
- }
-
- }
- catch (Exception ex)
- {
- EndLog("SetUserRolesInternal", res, CrmErrorCodes.CANNOT_SET_CRM_USER_ROLES_GENERAL_ERROR, ex);
- return res;
- }
-
-
- EndLog("SetUserRolesInternal");
- return res;
-
- }
-
-
- public CrmUserResult GetCrmUserById(Guid crmUserId, string orgName)
- {
- return GetCrmUserByIdInternal(crmUserId, orgName);
- }
-
- internal CrmUserResult GetCrmUserByIdInternal(Guid crmUserId, string orgName)
- {
- CrmUserResult ret = StartLog("GetCrmUserByIdInternal");
-
- try
- {
- if (crmUserId == Guid.Empty)
- throw new ArgumentNullException("crmUserId");
-
- if (string.IsNullOrEmpty(orgName))
- throw new ArgumentNullException("orgName");
-
- OrganizationServiceProxy serviceProxy = GetOrganizationProxy(orgName);
-
- SystemUser retruveUser =
- serviceProxy.Retrieve(SystemUser.EntityLogicalName, crmUserId, new Microsoft.Xrm.Sdk.Query.ColumnSet("domainname", "businessunitid", "accessmode", "isdisabled", "caltype")).ToEntity();
-
- CrmUser user = null;
-
- if (retruveUser != null)
- {
- user = new CrmUser();
- user.BusinessUnitId = retruveUser.BusinessUnitId.Id;
- user.CRMUserId = retruveUser.SystemUserId.Value;
- user.ClientAccessMode = (CRMUserAccessMode)retruveUser.AccessMode.Value;
- user.IsDisabled = (bool)retruveUser.IsDisabled;
- user.CALType = retruveUser.CALType.Value;
-
- ret.Value = user;
- }
- }
- catch (Exception ex)
- {
- EndLog("GetCrmUserByIdInternal", ret, CrmErrorCodes.CANONT_GET_CRM_USER_BY_ID, ex);
- return ret;
- }
-
- EndLog("GetCrmUserByIdInternal");
- return ret;
- }
-
-
- internal CrmUserResult GetCrmUserByDomainNameInternal(string domainName, string orgName)
- {
- CrmUserResult ret = StartLog("GetCrmUserByDomainNameInternal");
-
- try
- {
- if (string.IsNullOrEmpty(domainName))
- throw new ArgumentNullException("domainName");
-
- if (string.IsNullOrEmpty(orgName))
- throw new ArgumentNullException("orgName");
-
-
- OrganizationServiceProxy serviceProxy = GetOrganizationProxy(orgName);
-
- Microsoft.Xrm.Sdk.Query.QueryExpression usereQuery = new Microsoft.Xrm.Sdk.Query.QueryExpression
- {
- EntityName = SystemUser.EntityLogicalName,
- ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet("domainname", "businessunitid", "accessmode", "isdisabled", "systemuserid", "caltype"),
- };
-
- EntityCollection users = serviceProxy.RetrieveMultiple(usereQuery);
-
- foreach (Entity entityuser in users.Entities)
- {
- SystemUser sysuser = entityuser.ToEntity();
-
- if (sysuser == null) continue;
- if (sysuser.DomainName != domainName) continue;
-
- CrmUser user = new CrmUser();
- user.BusinessUnitId = sysuser.BusinessUnitId.Id;
- user.CRMUserId = sysuser.SystemUserId.Value;
- user.ClientAccessMode = (CRMUserAccessMode)sysuser.AccessMode.Value;
- user.IsDisabled = sysuser.IsDisabled.Value;
- user.CALType = sysuser.CALType.Value;
- ret.Value = user;
- }
- }
- catch (Exception ex)
- {
- EndLog("GetCrmUserByDomainNameInternal", ret, CrmErrorCodes.CANONT_GET_CRM_USER_BY_DOMAIN_NAME, ex);
- return ret;
- }
-
- EndLog("GetCrmUserByDomainNameInternal");
- return ret;
- }
-
- public CrmUserResult GetCrmUserByDomainName(string domainName, string orgName)
- {
- return GetCrmUserByDomainNameInternal(domainName, orgName);
- }
-
-
- private static Guid GetFetureId(string name)
- {
- if (string.IsNullOrEmpty(name))
- throw new ArgumentNullException("name");
-
- return Guid.Empty;
- }
-
-
- public ResultObject ChangeUserState(bool disable, string orgName, Guid crmUserId)
- {
- return ChangeUserStateInternal(disable, orgName, crmUserId);
- }
-
-
- internal ResultObject ChangeUserStateInternal(bool disable, string orgName, Guid crmUserId)
- {
- ResultObject res = StartLog("ChangeUserStateInternal");
-
- res.IsSuccess = true;
- try
- {
- if (crmUserId == Guid.Empty)
- throw new ArgumentNullException("crmUserId");
-
- if (string.IsNullOrEmpty(orgName))
- throw new ArgumentNullException("orgName");
-
- OrganizationServiceProxy serviceProxy = GetOrganizationProxy(orgName);
-
- // Retrieve a user.
- SystemUser user = serviceProxy.Retrieve(SystemUser.EntityLogicalName,
- crmUserId, new Microsoft.Xrm.Sdk.Query.ColumnSet(new String[] { "systemuserid", "firstname", "lastname" })).ToEntity();
-
- if (user != null)
- {
- Microsoft.Crm.Sdk.Messages.SetStateRequest request = new Microsoft.Crm.Sdk.Messages.SetStateRequest()
- {
- EntityMoniker = user.ToEntityReference(),
-
- // Required by request but always valued at -1 in this context.
- Status = new OptionSetValue(-1),
-
- // Sets the user to disabled.
- State = disable ? new OptionSetValue(-1) : new OptionSetValue(0)
- };
-
- serviceProxy.Execute(request);
-
- }
- }
- catch (Exception ex)
- {
- EndLog("ChangeUserStateInternal", res, CrmErrorCodes.CANNOT_CHANGE_USER_STATE, ex);
- return res;
- }
-
-
- EndLog("ChangeUserStateInternal");
- return res;
- }
-
public override bool IsInstalled()
{
- string value = string.Empty;
- try
- {
- RegistryKey root = Registry.LocalMachine;
- RegistryKey rk = root.OpenSubKey("SOFTWARE\\Microsoft\\MSCRM");
- if (rk == null)
- rk = root.OpenSubKey("SOFTWARE\\Wow6432Node\\Microsoft\\MSCRM");
-
- if (rk != null)
- {
- value = (string)rk.GetValue("CRM_Server_Version", null);
- rk.Close();
- }
- }
- catch (Exception ex)
- {
- Log.WriteError(ex);
- }
-
- return value.StartsWith("5.");
+ return CRMServerVersion.StartsWith("5.");
}
- public ResultObject SetUserCALType(string orgName, Guid userId, int CALType)
- {
- return SetUserCALTypeInternal(orgName, userId, CALType);
- }
-
- internal ResultObject SetUserCALTypeInternal(string orgName, Guid userId, int CALType)
- {
- ResultObject ret = StartLog("SetUserCALTypeInternal");
-
- try
- {
- if (userId == Guid.Empty)
- throw new ArgumentNullException("crmUserId");
-
- if (string.IsNullOrEmpty(orgName))
- throw new ArgumentNullException("orgName");
-
- OrganizationServiceProxy serviceProxy = GetOrganizationProxy(orgName);
-
- SystemUser user =
- serviceProxy.Retrieve(SystemUser.EntityLogicalName, userId, new Microsoft.Xrm.Sdk.Query.ColumnSet("domainname", "businessunitid", "accessmode", "isdisabled", "caltype")).ToEntity();
-
- // CALType and AccessMode
- int accessmode = CALType / 10;
- int caltype = CALType % 10;
-
- user.CALType = new OptionSetValue(caltype);
- user.AccessMode = new OptionSetValue(accessmode);
-
- serviceProxy.Update(user);
-
- }
- catch (Exception ex)
- {
- EndLog("SetUserCALTypeInternal", ret, CrmErrorCodes.CANONT_GET_CRM_USER_BY_ID, ex);
- return ret;
- }
-
- EndLog("SetUserCALTypeInternal");
- return ret;
- }
-
-
}
}
diff --git a/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution.Crm2011/HostedSolutionLog.cs b/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution.Crm2011/HostedSolutionLog.cs
new file mode 100644
index 00000000..83257a78
--- /dev/null
+++ b/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution.Crm2011/HostedSolutionLog.cs
@@ -0,0 +1,152 @@
+// 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 WebsitePanel.Providers.Common;
+using WebsitePanel.Server.Utils;
+using System.Text;
+using System.Management.Automation.Runspaces;
+
+namespace WebsitePanel.Providers.HostedSolution
+{
+ public class HostedSolutionLog
+ {
+ public static string LogPrefix = "HostedSolution";
+
+ public static void LogStart(string message, params object[] args)
+ {
+ string text = String.Format(message, args);
+ Log.WriteStart("{0} {1}", LogPrefix, text);
+ }
+
+ public static void LogEnd(string message, params object[] args)
+ {
+ string text = String.Format(message, args);
+ Log.WriteEnd("{0} {1}", LogPrefix, text);
+ }
+
+ public static void LogInfo(string message)
+ {
+ Log.WriteInfo("{0} {1}", LogPrefix, message);
+ }
+
+ public static void LogInfo(string message, params object[] args)
+ {
+ string text = String.Format(message, args);
+ Log.WriteInfo("{0} {1}", LogPrefix, text);
+ }
+
+ public static void LogWarning(string message)
+ {
+ Log.WriteWarning("{0} {1}", LogPrefix, message);
+ }
+
+ public static void LogWarning(string message, params object[] args)
+ {
+ string text = String.Format(message, args);
+ Log.WriteWarning("{0} {1}", LogPrefix, text);
+ }
+
+ public static void LogError(Exception ex)
+ {
+ Log.WriteError(LogPrefix, ex);
+ }
+
+ public static void LogError(string message, Exception ex)
+ {
+ string text = String.Format("{0} {1}", LogPrefix, message);
+ Log.WriteError(text, ex);
+ }
+
+ public static void DebugInfo(string message, params object[] args)
+ {
+ string text = String.Format(message, args);
+ Log.WriteInfo("{0} {1}", LogPrefix, text);
+ }
+
+ public static void EndLog(string message, ResultObject res, string errorCode, Exception ex)
+ {
+ if (res != null)
+ {
+ res.IsSuccess = false;
+
+ if (!string.IsNullOrEmpty(errorCode))
+ res.ErrorCodes.Add(errorCode);
+ }
+
+ if (ex != null)
+ LogError(ex);
+
+
+ //LogRecord.
+ LogEnd(message);
+
+
+ }
+
+ public static void EndLog(string message, ResultObject res, string errorCode)
+ {
+ EndLog(message, res, errorCode, null);
+ }
+
+ public static void EndLog(string message, ResultObject res)
+ {
+ EndLog(message, res, null);
+ }
+
+ public static void EndLog(string message)
+ {
+ EndLog(message, null);
+ }
+
+ internal static T StartLog(string message) where T : ResultObject, new()
+ {
+ LogStart(message);
+ T res = new T();
+ res.IsSuccess = true;
+ return res;
+ }
+
+ public static void DebugCommand(Command cmd)
+ {
+ StringBuilder sb = new StringBuilder(cmd.CommandText);
+ foreach (CommandParameter parameter in cmd.Parameters)
+ {
+ string formatString = " -{0} {1}";
+ if (parameter.Value is string)
+ formatString = " -{0} '{1}'";
+ else if (parameter.Value is bool)
+ formatString = " -{0} ${1}";
+ sb.AppendFormat(formatString, parameter.Name, parameter.Value);
+ }
+ Log.WriteInfo("{0} {1}", LogPrefix, sb.ToString());
+ }
+
+
+ }
+}
diff --git a/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution.Crm2011/WebsitePanel.Providers.HostedSolution.Crm2011.csproj b/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution.Crm2011/WebsitePanel.Providers.HostedSolution.Crm2011.csproj
index 4ce83413..7a97058e 100644
--- a/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution.Crm2011/WebsitePanel.Providers.HostedSolution.Crm2011.csproj
+++ b/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution.Crm2011/WebsitePanel.Providers.HostedSolution.Crm2011.csproj
@@ -31,40 +31,44 @@
4
-
- ..\..\Lib\References\Microsoft\microsoft.crm.sdk.proxy.dll
- True
+
+ False
+ ..\..\Lib\References\Microsoft\CRM2011\microsoft.crm.sdk.proxy.dll
-
- ..\..\Lib\References\Microsoft\microsoft.xrm.client.dll
- True
+
+ False
+ ..\..\Lib\References\Microsoft\CRM2011\microsoft.xrm.client.dll
-
- ..\..\Lib\References\Microsoft\microsoft.xrm.client.codegeneration.dll
- True
+
+ False
+ ..\..\Lib\References\Microsoft\CRM2011\microsoft.xrm.client.codegeneration.dll
-
- ..\..\Lib\References\Microsoft\microsoft.xrm.portal.dll
- True
+
+ False
+ ..\..\Lib\References\Microsoft\CRM2011\microsoft.xrm.portal.dll
-
- ..\..\Lib\References\Microsoft\microsoft.xrm.portal.files.dll
- True
+
+ False
+ ..\..\Lib\References\Microsoft\CRM2011\microsoft.xrm.portal.files.dll
-
- ..\..\Lib\References\Microsoft\microsoft.xrm.sdk.dll
- True
+
+ False
+ ..\..\Lib\References\Microsoft\CRM2011\microsoft.xrm.sdk.dll
-
- ..\..\Lib\References\Microsoft\microsoft.xrm.sdk.deployment.dll
- True
+
+ False
+ ..\..\Lib\References\Microsoft\CRM2011\microsoft.xrm.sdk.deployment.dll
-
- ..\..\Lib\References\Microsoft\microsoft.xrm.sdk.workflow.dll
- True
+
+ False
+ ..\..\Lib\References\Microsoft\CRM2011\microsoft.xrm.sdk.workflow.dll
+
+ False
+ ..\..\Lib\System.Management.Automation.dll
+
@@ -74,7 +78,9 @@
+
+
@@ -84,11 +90,6 @@
WebsitePanel.Providers.Base
False
-
- {A06DE5E4-4331-47E1-8F46-7B846146B559}
- WebsitePanel.Providers.HostedSolution
- False
-
{E91E52F3-9555-4D00-B577-2B1DBDD87CA7}
WebsitePanel.Server.Utils
diff --git a/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution.Crm2011/myorganizationcrmsdktypes.cs b/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution.Crm2011/myorganizationcrmsdktypes.cs
index fe429976..ed6f0461 100644
--- a/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution.Crm2011/myorganizationcrmsdktypes.cs
+++ b/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution.Crm2011/myorganizationcrmsdktypes.cs
@@ -9,7 +9,9 @@
//------------------------------------------------------------------------------
[assembly: Microsoft.Xrm.Sdk.Client.ProxyTypesAssemblyAttribute()]
-/*
+
+
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum AccountState
@@ -20,7 +22,7 @@ public enum AccountState
[System.Runtime.Serialization.EnumMemberAttribute()]
Inactive = 1,
-}*/
+}
///
/// Business that represents a customer or potential customer. The company that is billed in business transactions.
@@ -4875,7 +4877,7 @@ public partial class ActivityParty : Microsoft.Xrm.Sdk.Entity, System.ComponentM
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum ActivityPointerState
@@ -4892,7 +4894,7 @@ public enum ActivityPointerState
[System.Runtime.Serialization.EnumMemberAttribute()]
Scheduled = 3,
-}*/
+}
///
/// Task performed, or to be performed, by a user. An activity is any action for which an entry can be made on a calendar.
@@ -8070,7 +8072,7 @@ public partial class AnnualFiscalCalendar : Microsoft.Xrm.Sdk.Entity, System.Com
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum AppointmentState
@@ -8087,7 +8089,7 @@ public enum AppointmentState
[System.Runtime.Serialization.EnumMemberAttribute()]
Scheduled = 3,
-}*/
+}
///
/// Commitment representing a time interval with start/end times and duration.
@@ -9622,7 +9624,7 @@ public partial class Appointment : Microsoft.Xrm.Sdk.Entity, System.ComponentMod
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum AsyncOperationState
@@ -9639,7 +9641,7 @@ public enum AsyncOperationState
[System.Runtime.Serialization.EnumMemberAttribute()]
Completed = 3,
-}*/
+}
///
/// Process whose execution can proceed independently or in the background.
@@ -14691,7 +14693,7 @@ public partial class BulkDeleteFailure : Microsoft.Xrm.Sdk.Entity, System.Compon
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum BulkDeleteOperationState
@@ -14708,7 +14710,7 @@ public enum BulkDeleteOperationState
[System.Runtime.Serialization.EnumMemberAttribute()]
Completed = 3,
-}*/
+}
///
/// User-submitted bulk deletion job.
@@ -15149,7 +15151,7 @@ public partial class BulkDeleteOperation : Microsoft.Xrm.Sdk.Entity, System.Comp
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum BulkOperationState
@@ -15163,7 +15165,7 @@ public enum BulkOperationState
[System.Runtime.Serialization.EnumMemberAttribute()]
Canceled = 2,
-}*/
+}
///
/// System operation used to perform lengthy and asynchronous operations on large data sets, such as distributing a campaign activity or quick campaign.
@@ -21108,7 +21110,7 @@ public partial class CalendarRule : Microsoft.Xrm.Sdk.Entity, System.ComponentMo
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum CampaignState
@@ -21119,7 +21121,7 @@ public enum CampaignState
[System.Runtime.Serialization.EnumMemberAttribute()]
Inactive = 1,
-}*/
+}
///
/// Container for campaign activities and responses, sales literature, products, and lists to create, plan, execute, and track the results of a specific marketing campaign through its life.
@@ -22556,7 +22558,7 @@ public partial class Campaign : Microsoft.Xrm.Sdk.Entity, System.ComponentModel.
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum CampaignActivityState
@@ -22570,7 +22572,7 @@ public enum CampaignActivityState
[System.Runtime.Serialization.EnumMemberAttribute()]
Canceled = 2,
-}*/
+}
///
/// Task performed, or to be performed, by a user for planning or running a campaign.
@@ -24497,7 +24499,7 @@ public partial class CampaignItem : Microsoft.Xrm.Sdk.Entity, System.ComponentMo
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum CampaignResponseState
@@ -24511,7 +24513,7 @@ public enum CampaignResponseState
[System.Runtime.Serialization.EnumMemberAttribute()]
Canceled = 2,
-}*/
+}
///
/// Response from an existing or a potential new customer for a campaign.
@@ -25993,7 +25995,7 @@ public partial class CampaignResponse : Microsoft.Xrm.Sdk.Entity, System.Compone
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum ColumnMappingState
@@ -26001,7 +26003,7 @@ public enum ColumnMappingState
[System.Runtime.Serialization.EnumMemberAttribute()]
Active = 0,
-}*/
+}
///
/// Mapping for columns in a data map.
@@ -31712,7 +31714,7 @@ public partial class ConstraintBasedGroup : Microsoft.Xrm.Sdk.Entity, System.Com
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum ContactState
@@ -31723,7 +31725,7 @@ public enum ContactState
[System.Runtime.Serialization.EnumMemberAttribute()]
Inactive = 1,
-}*/
+}
///
/// Person with whom a business unit has a relationship, such as customer, supplier, and colleague.
@@ -35945,7 +35947,7 @@ public partial class ContactQuotes : Microsoft.Xrm.Sdk.Entity, System.ComponentM
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum ContractState
@@ -35968,7 +35970,7 @@ public enum ContractState
[System.Runtime.Serialization.EnumMemberAttribute()]
Expired = 5,
-}*/
+}
///
/// Agreement to provide customer service during a specified amount of time or number of cases.
@@ -37502,7 +37504,7 @@ public partial class Contract : Microsoft.Xrm.Sdk.Entity, System.ComponentModel.
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum ContractDetailState
@@ -37519,7 +37521,7 @@ public enum ContractDetailState
[System.Runtime.Serialization.EnumMemberAttribute()]
Expired = 3,
-}*/
+}
///
/// Line item in a contract that specifies the type of service a customer is entitled to.
@@ -42271,7 +42273,7 @@ public partial class Discount : Microsoft.Xrm.Sdk.Entity, System.ComponentModel.
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum DiscountTypeState
@@ -42282,7 +42284,7 @@ public enum DiscountTypeState
[System.Runtime.Serialization.EnumMemberAttribute()]
Inactive = 1,
-}*/
+}
///
/// Type of discount specified as either a percentage or an amount.
@@ -44193,7 +44195,7 @@ public partial class DuplicateRecord : Microsoft.Xrm.Sdk.Entity, System.Componen
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum DuplicateRuleState
@@ -44204,7 +44206,7 @@ public enum DuplicateRuleState
[System.Runtime.Serialization.EnumMemberAttribute()]
Active = 1,
-}*/
+}
///
/// Rule used to identify potential duplicates.
@@ -45191,7 +45193,7 @@ public partial class DuplicateRuleCondition : Microsoft.Xrm.Sdk.Entity, System.C
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum EmailState
@@ -45205,7 +45207,7 @@ public enum EmailState
[System.Runtime.Serialization.EnumMemberAttribute()]
Canceled = 2,
-}*/
+}
///
/// Activity that is delivered using e-mail protocols.
@@ -48145,7 +48147,7 @@ public partial class Equipment : Microsoft.Xrm.Sdk.Entity, System.ComponentModel
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum FaxState
@@ -48159,7 +48161,7 @@ public enum FaxState
[System.Runtime.Serialization.EnumMemberAttribute()]
Canceled = 2,
-}*/
+}
///
/// Activity that tracks call outcome and number of pages for a fax and optionally stores an electronic copy of the document.
@@ -53690,7 +53692,7 @@ public partial class GoalRollupQuery : Microsoft.Xrm.Sdk.Entity, System.Componen
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum ImportState
@@ -53698,7 +53700,7 @@ public enum ImportState
[System.Runtime.Serialization.EnumMemberAttribute()]
Active = 0,
-}*/
+}
///
/// Status and ownership information for an import job.
@@ -54589,7 +54591,7 @@ public partial class ImportEntityMapping : Microsoft.Xrm.Sdk.Entity, System.Comp
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum ImportFileState
@@ -54597,7 +54599,7 @@ public enum ImportFileState
[System.Runtime.Serialization.EnumMemberAttribute()]
Active = 0,
-}*/
+}
///
/// File name of file used for import.
@@ -55948,7 +55950,7 @@ public partial class ImportJob : Microsoft.Xrm.Sdk.Entity, System.ComponentModel
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum ImportLogState
@@ -55956,7 +55958,7 @@ public enum ImportLogState
[System.Runtime.Serialization.EnumMemberAttribute()]
Active = 0,
-}*/
+}
///
/// Failure reason and other detailed information for a record that failed to import.
@@ -56540,7 +56542,7 @@ public partial class ImportLog : Microsoft.Xrm.Sdk.Entity, System.ComponentModel
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum ImportMapState
@@ -56551,7 +56553,7 @@ public enum ImportMapState
[System.Runtime.Serialization.EnumMemberAttribute()]
Inactive = 1,
-}*/
+}
///
/// Data map used in import.
@@ -57254,7 +57256,7 @@ public partial class ImportMap : Microsoft.Xrm.Sdk.Entity, System.ComponentModel
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum IncidentState
@@ -57268,7 +57270,7 @@ public enum IncidentState
[System.Runtime.Serialization.EnumMemberAttribute()]
Canceled = 2,
-}*/
+}
///
/// Service request case associated with a contract.
@@ -58724,7 +58726,7 @@ public partial class Incident : Microsoft.Xrm.Sdk.Entity, System.ComponentModel.
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum IncidentResolutionState
@@ -58738,7 +58740,7 @@ public enum IncidentResolutionState
[System.Runtime.Serialization.EnumMemberAttribute()]
Canceled = 2,
-}*/
+}
///
/// Special type of activity that includes description of the resolution, billing status, and the duration of the case.
@@ -59781,7 +59783,7 @@ public partial class InvalidDependency : Microsoft.Xrm.Sdk.Entity, System.Compon
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum InvoiceState
@@ -59798,7 +59800,7 @@ public enum InvoiceState
[System.Runtime.Serialization.EnumMemberAttribute()]
Canceled = 3,
-}*/
+}
///
/// Order that has been billed.
@@ -63179,7 +63181,7 @@ public partial class IsvConfig : Microsoft.Xrm.Sdk.Entity, System.ComponentModel
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum KbArticleState
@@ -63193,7 +63195,7 @@ public enum KbArticleState
[System.Runtime.Serialization.EnumMemberAttribute()]
Published = 3,
-}*/
+}
///
/// Structured content that is part of the knowledge base.
@@ -64891,7 +64893,7 @@ public partial class KbArticleTemplate : Microsoft.Xrm.Sdk.Entity, System.Compon
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum LeadState
@@ -64905,7 +64907,7 @@ public enum LeadState
[System.Runtime.Serialization.EnumMemberAttribute()]
Disqualified = 2,
-}*/
+}
///
/// Prospect or potential sales opportunity. Leads are converted into accounts, contacts, or opportunities when they are qualified. Otherwise, they are deleted or archived.
@@ -68688,7 +68690,7 @@ public partial class LeadProduct : Microsoft.Xrm.Sdk.Entity, System.ComponentMod
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum LetterState
@@ -68702,7 +68704,7 @@ public enum LetterState
[System.Runtime.Serialization.EnumMemberAttribute()]
Canceled = 2,
-}*/
+}
///
/// Activity that tracks the delivery of a letter. The activity can contain the electronic copy of the letter.
@@ -70364,7 +70366,7 @@ public partial class License : Microsoft.Xrm.Sdk.Entity, System.ComponentModel.I
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum ListState
@@ -70375,7 +70377,7 @@ public enum ListState
[System.Runtime.Serialization.EnumMemberAttribute()]
Inactive = 1,
-}*/
+}
///
/// Group of existing or potential customers created for a marketing campaign or other sales purposes.
@@ -71764,7 +71766,7 @@ public partial class ListMember : Microsoft.Xrm.Sdk.Entity, System.ComponentMode
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum LookUpMappingState
@@ -71772,7 +71774,7 @@ public enum LookUpMappingState
[System.Runtime.Serialization.EnumMemberAttribute()]
Active = 0,
-}*/
+}
///
/// In a data map, maps a lookup attribute in a source file to Microsoft Dynamics CRM.
@@ -72180,7 +72182,7 @@ public partial class LookUpMapping : Microsoft.Xrm.Sdk.Entity, System.ComponentM
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum MailMergeTemplateState
@@ -72191,7 +72193,7 @@ public enum MailMergeTemplateState
[System.Runtime.Serialization.EnumMemberAttribute()]
Inactive = 1,
-}*/
+}
///
/// Template for a mail merge document that contains the standard attributes of that document.
@@ -74280,7 +74282,7 @@ public partial class MonthlyFiscalCalendar : Microsoft.Xrm.Sdk.Entity, System.Co
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum OpportunityState
@@ -74294,7 +74296,7 @@ public enum OpportunityState
[System.Runtime.Serialization.EnumMemberAttribute()]
Lost = 2,
-}*/
+}
///
/// Potential revenue-generating event, or sale to an account, which needs to be tracked through a sales process to completion.
@@ -76011,7 +76013,7 @@ public partial class Opportunity : Microsoft.Xrm.Sdk.Entity, System.ComponentMod
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum OpportunityCloseState
@@ -76025,7 +76027,7 @@ public enum OpportunityCloseState
[System.Runtime.Serialization.EnumMemberAttribute()]
Canceled = 2,
-}*/
+}
///
/// Activity that is created automatically when an opportunity is closed, containing information such as the description of the closing and actual revenue.
@@ -77977,7 +77979,7 @@ public partial class OpportunityProduct : Microsoft.Xrm.Sdk.Entity, System.Compo
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum OrderCloseState
@@ -77991,7 +77993,7 @@ public enum OrderCloseState
[System.Runtime.Serialization.EnumMemberAttribute()]
Canceled = 2,
-}*/
+}
///
/// Activity generated automatically when an order is closed.
@@ -83464,7 +83466,7 @@ public partial class OrganizationUI : Microsoft.Xrm.Sdk.Entity, System.Component
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum OwnerMappingState
@@ -83472,7 +83474,7 @@ public enum OwnerMappingState
[System.Runtime.Serialization.EnumMemberAttribute()]
Active = 0,
-}*/
+}
///
/// In a data map, maps ownership data from the source file to Microsoft Dynamics CRM.
@@ -83898,7 +83900,7 @@ public partial class OwnerMapping : Microsoft.Xrm.Sdk.Entity, System.ComponentMo
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum PhoneCallState
@@ -83912,7 +83914,7 @@ public enum PhoneCallState
[System.Runtime.Serialization.EnumMemberAttribute()]
Canceled = 2,
-}*/
+}
///
/// Activity to track a telephone call.
@@ -85310,7 +85312,7 @@ public partial class PhoneCall : Microsoft.Xrm.Sdk.Entity, System.ComponentModel
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum PickListMappingState
@@ -85318,7 +85320,7 @@ public enum PickListMappingState
[System.Runtime.Serialization.EnumMemberAttribute()]
Active = 0,
-}*/
+}
///
/// In a data map, maps list values from the source file to Microsoft Dynamics CRM.
@@ -88719,7 +88721,7 @@ public partial class PostLike : Microsoft.Xrm.Sdk.Entity, System.ComponentModel.
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum PriceLevelState
@@ -88730,7 +88732,7 @@ public enum PriceLevelState
[System.Runtime.Serialization.EnumMemberAttribute()]
Inactive = 1,
-}*/
+}
///
/// Entity that defines pricing levels.
@@ -93295,7 +93297,7 @@ public partial class ProcessSession : Microsoft.Xrm.Sdk.Entity, System.Component
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum ProductState
@@ -93306,7 +93308,7 @@ public enum ProductState
[System.Runtime.Serialization.EnumMemberAttribute()]
Inactive = 1,
-}*/
+}
///
/// Information about products and their pricing information.
@@ -100282,7 +100284,7 @@ public partial class QueueItem : Microsoft.Xrm.Sdk.Entity, System.ComponentModel
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum QuoteState
@@ -100299,7 +100301,7 @@ public enum QuoteState
[System.Runtime.Serialization.EnumMemberAttribute()]
Closed = 3,
-}*/
+}
///
/// Formal offer for products and/or services, proposed at specific prices and related payment terms, which is sent to a prospective customer.
@@ -102328,7 +102330,7 @@ public partial class Quote : Microsoft.Xrm.Sdk.Entity, System.ComponentModel.INo
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum QuoteCloseState
@@ -102342,7 +102344,7 @@ public enum QuoteCloseState
[System.Runtime.Serialization.EnumMemberAttribute()]
Canceled = 2,
-}*/
+}
///
/// Activity generated when a quote is closed.
@@ -107004,7 +107006,7 @@ public partial class RecurringAppointmentMaster : Microsoft.Xrm.Sdk.Entity, Syst
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum RelationshipRoleState
@@ -107015,7 +107017,7 @@ public enum RelationshipRoleState
[System.Runtime.Serialization.EnumMemberAttribute()]
Inactive = 1,
-}*/
+}
///
/// Relationship between an account or contact and an opportunity.
@@ -115072,7 +115074,7 @@ public partial class SalesLiteratureItem : Microsoft.Xrm.Sdk.Entity, System.Comp
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum SalesOrderState
@@ -115092,7 +115094,7 @@ public enum SalesOrderState
[System.Runtime.Serialization.EnumMemberAttribute()]
Invoiced = 4,
-}*/
+}
///
/// Quote that has been accepted.
@@ -120852,7 +120854,7 @@ public partial class SdkMessagePair : Microsoft.Xrm.Sdk.Entity, System.Component
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum SdkMessageProcessingStepState
@@ -120863,7 +120865,7 @@ public enum SdkMessageProcessingStepState
[System.Runtime.Serialization.EnumMemberAttribute()]
Disabled = 1,
-}*/
+}
///
/// Stage in the execution pipeline that a plug-in is to execute.
@@ -125550,7 +125552,7 @@ public partial class Service : Microsoft.Xrm.Sdk.Entity, System.ComponentModel.I
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum ServiceAppointmentState
@@ -125567,7 +125569,7 @@ public enum ServiceAppointmentState
[System.Runtime.Serialization.EnumMemberAttribute()]
Scheduled = 3,
-}*/
+}
///
/// Activity offered by the organization to satisfy its customer's needs. Each service activity includes date, time, duration, and required resources.
@@ -132591,8 +132593,6 @@ public partial class SystemForm : Microsoft.Xrm.Sdk.Entity, System.ComponentMode
}
}
-
-
///
/// Person with access to the Microsoft CRM system and who owns objects in the Microsoft CRM database.
///
@@ -146900,7 +146900,6 @@ public partial class SystemUser : Microsoft.Xrm.Sdk.Entity, System.ComponentMode
}
}
-
///
///
///
@@ -147275,7 +147274,7 @@ public partial class SystemUserRoles : Microsoft.Xrm.Sdk.Entity, System.Componen
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum TaskState
@@ -147289,7 +147288,7 @@ public enum TaskState
[System.Runtime.Serialization.EnumMemberAttribute()]
Canceled = 2,
-}*/
+}
///
/// Generic activity representing work needed to be done.
@@ -153380,7 +153379,7 @@ public partial class TimeZoneRule : Microsoft.Xrm.Sdk.Entity, System.ComponentMo
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum TransactionCurrencyState
@@ -153391,7 +153390,7 @@ public enum TransactionCurrencyState
[System.Runtime.Serialization.EnumMemberAttribute()]
Inactive = 1,
-}*/
+}
///
/// Currency in which a financial transaction is carried out.
@@ -154896,7 +154895,7 @@ public partial class TransactionCurrency : Microsoft.Xrm.Sdk.Entity, System.Comp
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum TransformationMappingState
@@ -154904,7 +154903,7 @@ public enum TransformationMappingState
[System.Runtime.Serialization.EnumMemberAttribute()]
Active = 0,
-}*/
+}
///
/// In a data map, maps the transformation of source attributes to Microsoft Dynamics CRM attributes.
@@ -161202,7 +161201,7 @@ public partial class UserForm : Microsoft.Xrm.Sdk.Entity, System.ComponentModel.
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum UserQueryState
@@ -161213,7 +161212,7 @@ public enum UserQueryState
[System.Runtime.Serialization.EnumMemberAttribute()]
Inactive = 1,
-}*/
+}
///
/// Saved database query that is owned by a user.
@@ -164515,7 +164514,7 @@ public partial class WebResource : Microsoft.Xrm.Sdk.Entity, System.ComponentMod
}
}
}
-/*
+
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "5.0.9690.2153")]
public enum WorkflowState
@@ -164526,7 +164525,7 @@ public enum WorkflowState
[System.Runtime.Serialization.EnumMemberAttribute()]
Activated = 1,
-}*/
+}
///
/// Set of logical rules that define the steps necessary to automate a specific business process, task, or set of actions to be performed.
@@ -168684,4 +168683,3 @@ public partial class ServiceContext : Microsoft.Xrm.Sdk.Client.OrganizationServi
}
}
}
-
diff --git a/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution.Crm2013/CRMBase.cs b/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution.Crm2013/CRMBase.cs
new file mode 100644
index 00000000..3a52bdca
--- /dev/null
+++ b/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution.Crm2013/CRMBase.cs
@@ -0,0 +1,2096 @@
+// Copyright (c) 2012 - 2013, 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.Data;
+using System.Data.SqlClient;
+using System.Globalization;
+using System.IO;
+using System.Net;
+using System.Reflection;
+using System.Net.Security;
+using System.Security.Principal;
+using System.Security.Cryptography.X509Certificates;
+using System.Threading;
+using System.ServiceModel.Description;
+using System.Text.RegularExpressions;
+using Microsoft.Win32;
+using WebsitePanel.Providers.Common;
+using WebsitePanel.Providers.ResultObjects;
+using WebsitePanel.Server.Utils;
+using WebsitePanel.Providers.HostedSolution;
+using WebsitePanel.Providers;
+using WebsitePanel.Providers.Utils;
+using Microsoft.Xrm.Sdk;
+using Microsoft.Xrm.Sdk.Query;
+using Microsoft.Xrm.Sdk.Discovery;
+using Microsoft.Xrm.Sdk.Client;
+using Microsoft.Xrm.Sdk.Deployment;
+using Microsoft.Xrm.Sdk.Messages;
+
+namespace WebsitePanel.Providers.HostedSolution
+{
+ public class CRMBase : HostingServiceProviderBase, ICRM
+ {
+ #region Properties
+
+ protected virtual string UserName
+ {
+ get { return ProviderSettings[Constants.UserName]; }
+ }
+
+ protected virtual string Password
+ {
+ get { return ProviderSettings[Constants.Password]; }
+ }
+
+ protected virtual string SqlServer
+ {
+ get { return ProviderSettings[Constants.SqlServer]; }
+ }
+
+ protected virtual string ReportingServer
+ {
+ get { return ProviderSettings[Constants.ReportingServer]; }
+ }
+
+ protected virtual string UrlSchema
+ {
+ get { return ProviderSettings[Constants.UrlSchema] == "http" ? "http://" : "https://"; }
+ }
+
+ protected virtual string CRMDeploymentUrl
+ {
+ get
+ {
+ string uri = ProviderSettings[Constants.DeploymentWebService];
+ if (String.IsNullOrEmpty(uri)) uri = ProviderSettings[Constants.AppRootDomain];
+ string cRMServiceUrl = UrlSchema + uri + ":" + ProviderSettings[Constants.Port] + "/XRMDeployment/2011/Deployment.svc";
+ return cRMServiceUrl;
+ }
+ }
+
+ protected virtual string CRMDiscoveryUrl
+ {
+ get
+ {
+ string uri = ProviderSettings[Constants.DiscoveryWebService];
+ if (String.IsNullOrEmpty(uri)) uri = ProviderSettings[Constants.AppRootDomain];
+ string cRMDiscoveryUri = UrlSchema + uri + ":" + ProviderSettings[Constants.Port] + "/XRMServices/2011/Discovery.svc";
+ return cRMDiscoveryUri;
+ }
+ }
+
+ private static string crmPath = null;
+ protected static string CRMPath
+ {
+ get
+ {
+ if (string.IsNullOrEmpty(crmPath))
+ {
+ RegistryKey root = Registry.LocalMachine;
+ RegistryKey rk = root.OpenSubKey("SOFTWARE\\Microsoft\\MSCRM");
+ if (rk != null)
+ {
+ crmPath = (string)rk.GetValue("CRM_Server_InstallDir", string.Empty);
+ }
+ }
+ return crmPath;
+ }
+ }
+
+ protected static string CRMDatabaseName = "MSCRM_CONFIG";
+
+ #endregion
+
+ #region Service
+
+ protected virtual ClientCredentials GetUserLogonCredentials()
+ {
+ ClientCredentials credentials = new ClientCredentials();
+
+ if (String.IsNullOrEmpty(UserName))
+ {
+ credentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials;
+ }
+ else
+ {
+ credentials.UserName.UserName = UserName;
+ credentials.UserName.Password = Password;
+ }
+
+ return credentials;
+ }
+
+ protected virtual DeploymentServiceClient GetDeploymentProxy()
+ {
+ Uri serviceUrl = new Uri(CRMDeploymentUrl);
+
+ DeploymentServiceClient deploymentService = Microsoft.Xrm.Sdk.Deployment.Proxy.ProxyClientHelper.CreateClient(serviceUrl);
+ if (!String.IsNullOrEmpty(UserName))
+ deploymentService.ClientCredentials.Windows.ClientCredential = new NetworkCredential(UserName, Password);
+
+ return deploymentService;
+ }
+
+ protected virtual DiscoveryServiceProxy GetDiscoveryProxy()
+ {
+
+ IServiceManagement serviceManagement =
+ ServiceConfigurationFactory.CreateManagement(
+ new Uri(CRMDiscoveryUrl));
+
+ ClientCredentials Credentials = GetUserLogonCredentials();
+
+ DiscoveryServiceProxy r = new DiscoveryServiceProxy(serviceManagement, Credentials);
+
+ return r;
+ }
+
+ private OrganizationDetailCollection DiscoverOrganizations(IDiscoveryService service)
+ {
+ if (service == null) throw new ArgumentNullException("service");
+ RetrieveOrganizationsRequest orgRequest = new RetrieveOrganizationsRequest();
+ RetrieveOrganizationsResponse orgResponse =
+ (RetrieveOrganizationsResponse)service.Execute(orgRequest);
+
+ return orgResponse.Details;
+ }
+
+ protected virtual Uri GetCRMOrganizationUrl(string orgName)
+ {
+ //string url = "https://" + ProviderSettings[Constants.AppRootDomain] + ":" + ProviderSettings[Constants.Port] + "/" + orgName + "/XRMServices/2011/Organization.svc";
+
+ string url;
+
+ string organizationWebServiceUri = ProviderSettings[Constants.OrganizationWebService];
+
+ if (String.IsNullOrEmpty(orgName))
+ return null;
+
+ if (!String.IsNullOrEmpty(organizationWebServiceUri))
+ {
+ url = UrlSchema + organizationWebServiceUri + ":" + ProviderSettings[Constants.Port] + "/" + orgName + "/XRMServices/2011/Organization.svc";
+ }
+ else
+ {
+ url = UrlSchema + orgName + "." + ProviderSettings[Constants.IFDWebApplicationRootDomain] + ":" + ProviderSettings[Constants.Port] + "/XRMServices/2011/Organization.svc";
+ }
+
+ try
+ {
+
+ using (DiscoveryServiceProxy serviceProxy = GetDiscoveryProxy())
+ {
+ // Obtain organization information from the Discovery service.
+ if (serviceProxy != null)
+ {
+ // Obtain information about the organizations that the system user belongs to.
+ OrganizationDetailCollection orgs = DiscoverOrganizations(serviceProxy);
+
+ for (int n = 0; n < orgs.Count; n++)
+ {
+ if (orgs[n].UniqueName == orgName)
+ {
+ // Return the organization Uri.
+ return new System.Uri(orgs[n].Endpoints[EndpointType.OrganizationService]);
+ }
+ }
+
+ }
+ }
+ }
+ catch { }
+
+ return new Uri(url);
+ }
+
+ private int getOrganizationProxyTryCount = 10;
+ private int getOrganizationProxyTryTimeout = 30000;
+ protected virtual OrganizationServiceProxy GetOrganizationProxy(string orgName)
+ {
+ return GetOrganizationProxy(orgName, getOrganizationProxyTryCount, getOrganizationProxyTryTimeout);
+ }
+
+ protected virtual OrganizationServiceProxy GetOrganizationProxy(string orgName, int TryCount, int TryTimeout)
+ {
+
+ Uri OrganizationUri = GetCRMOrganizationUrl(orgName);
+
+ OrganizationServiceProxy r = null;
+
+ bool success = false;
+ int tryItem = 0;
+ Exception exception = null;
+
+ while (!success)
+ {
+
+ try
+ {
+ // Set IServiceManagement for the current organization.
+ IServiceManagement orgServiceManagement =
+ ServiceConfigurationFactory.CreateManagement(
+ OrganizationUri);
+
+ r = new OrganizationServiceProxy(
+ orgServiceManagement,
+ GetUserLogonCredentials());
+
+ success = true;
+
+ }
+ catch (Exception exc)
+ {
+ Thread.Sleep(TryTimeout);
+ tryItem++;
+ if (tryItem >= TryCount)
+ {
+ exception = exc;
+ success = true;
+ }
+ }
+
+ }
+
+ if (exception != null)
+ throw new ArgumentException(exception.ToString());
+
+ r.EnableProxyTypes();
+
+ return r;
+ }
+
+ #endregion
+
+ #region Static constructor
+
+ static CRMBase()
+ {
+ AppDomain.CurrentDomain.AssemblyResolve += ResolveCRMAssembly;
+ }
+
+ static Assembly ResolveCRMAssembly(object sender, ResolveEventArgs args)
+ {
+ // Ensure we load DLLs only.
+ if (args.Name.ToLower().Contains("microsoft.crm") || args.Name.ToLower().Contains("antixsslibrary") || args.Name.ToLower().Contains("microsoft.xrm"))
+ {
+ string dllName = args.Name.Split(',')[0] + ".dll";
+
+ List paths = new List();
+
+ // assembly location
+ paths.Add( Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().EscapedCodeBase).LocalPath) );
+ // crm tools path
+ paths.Add(CRMPath);
+
+ foreach(string path in paths)
+ {
+ string filename = Path.Combine(path, dllName);
+ if (File.Exists(filename))
+ return Assembly.LoadFrom(filename);
+ }
+ }
+
+ return default(Assembly);
+ }
+
+ #endregion
+
+ #region Check environment
+
+ protected virtual bool CheckCRMWebServicesAccess()
+ {
+ Log.WriteStart("CheckCRMWebServicesAccess");
+ bool ret = false;
+ HttpWebResponse response = null;
+ HttpWebRequest request;
+
+ try
+ {
+ WindowsIdentity.GetCurrent();
+
+ request = WebRequest.Create(CRMDeploymentUrl) as HttpWebRequest;
+
+ if (request != null)
+ {
+ request.UseDefaultCredentials = true;
+ request.Credentials = CredentialCache.DefaultCredentials;
+ response = request.GetResponse() as HttpWebResponse;
+
+ }
+ if (response != null)
+ ret = (response.StatusCode == HttpStatusCode.OK);
+ }
+ catch (Exception ex)
+ {
+ Log.WriteError(ex);
+ ret = false;
+ }
+
+ Log.WriteEnd("CheckCRMWebServicesAccess");
+ return ret;
+ }
+
+ protected virtual bool CheckPermissions()
+ {
+ Log.WriteStart("CheckPermissions");
+ bool res = false;
+ try
+ {
+ string group = "PrivUserGroup";
+ string user = WindowsIdentity.GetCurrent().Name.Split(new char[] { '\\' })[1];
+ res = ActiveDirectoryUtils.IsUserInGroup(user, group);
+ }
+ catch (Exception ex)
+ {
+ Log.WriteError(ex);
+ res = false;
+ }
+
+ Log.WriteEnd("CheckPermissions");
+ return res;
+ }
+
+ protected virtual bool CheckOrganizationUnique(string databaseName, string orgName)
+ {
+ Log.WriteStart("CheckOrganizationUnique");
+ bool res = false;
+
+ SqlConnection connection = null;
+ try
+ {
+ connection = new SqlConnection();
+ connection.ConnectionString =
+ string.Format("Server={1};Initial Catalog={0};Integrated Security=SSPI",
+ databaseName, SqlServer);
+
+ connection.Open();
+
+ string commandText = string.Format("SELECT COUNT(*) FROM dbo.Organization WHERE UniqueName = '{0}'", orgName);
+ SqlCommand command = new SqlCommand(commandText, connection);
+ int count = (int)command.ExecuteScalar();
+ res = count == 0;
+
+
+ }
+ catch (Exception ex)
+ {
+ res = false;
+ Log.WriteError(ex);
+ }
+ finally
+ {
+ if (connection != null)
+ connection.Close();
+
+ }
+
+ Log.WriteEnd("CheckOrganizationUnique");
+ return res;
+ }
+
+ protected virtual bool CheckSqlServerConnection()
+ {
+ Log.WriteStart("CheckSqlServerConnection");
+ bool res = false;
+ SqlConnection connection = null;
+ try
+ {
+ connection = new SqlConnection();
+ connection.ConnectionString =
+ string.Format("server={0}; Integrated Security=SSPI",
+ SqlServer);
+
+ connection.Open();
+ res = true;
+ }
+ catch (Exception ex)
+ {
+ Log.WriteError(ex);
+ res = false;
+ }
+ finally
+ {
+ if (connection != null)
+ connection.Close();
+ }
+
+ Log.WriteEnd("CheckSqlServerConnection");
+
+ return res;
+ }
+
+ protected virtual bool CheckReportServerConnection()
+ {
+ Log.WriteStart("CheckReportServerConnection");
+ bool ret = false;
+ HttpWebResponse response = null;
+ HttpWebRequest request;
+
+ try
+ {
+ WindowsIdentity.GetCurrent();
+
+ request = WebRequest.Create(ReportingServer) as HttpWebRequest;
+
+ if (request != null)
+ {
+ request.UseDefaultCredentials = true;
+ request.Credentials = CredentialCache.DefaultCredentials;
+ response = request.GetResponse() as HttpWebResponse;
+
+ }
+ if (response != null)
+ ret = (response.StatusCode == HttpStatusCode.OK);
+ }
+ catch (Exception ex)
+ {
+ Log.WriteError(ex);
+ ret = false;
+ }
+
+ Log.WriteEnd("CheckReportServerConnection");
+ return ret;
+ }
+
+ protected virtual OrganizationResult CheckCrmEnvironment(string strDataBaseName, string organizationUniqueName)
+ {
+ OrganizationResult retOrganization = StartLog("CheckCrmEnvironment");
+ bool res = CheckSqlServerConnection();
+
+ if (!res)
+ {
+ EndLog("CheckCrmEnvironment", retOrganization, CrmErrorCodes.CRM_SQL_SERVER_ERROR);
+ return retOrganization;
+ }
+
+ res = CheckOrganizationUnique(strDataBaseName, organizationUniqueName);
+ if (!res)
+ {
+ EndLog("CheckCrmEnvironment", retOrganization, CrmErrorCodes.CRM_ORGANIZATION_ALREADY_EXISTS);
+ return retOrganization;
+ }
+
+ res = CheckReportServerConnection();
+ if (!res)
+ {
+ EndLog("CheckCrmEnvironment", retOrganization, CrmErrorCodes.CRM_REPORT_SERVER_ERROR);
+ return retOrganization;
+ }
+
+ res = CheckPermissions();
+ if (!res)
+ {
+ EndLog("CheckCrmEnvironment", retOrganization, CrmErrorCodes.CRM_PERMISSIONS_ERROR);
+ return retOrganization;
+ }
+
+ res = CheckCRMWebServicesAccess();
+ if (!res)
+ {
+ EndLog("CheckCrmEnvironment", retOrganization, CrmErrorCodes.CRM_WEB_SERVICE_ERROR);
+ return retOrganization;
+ }
+
+ EndLog("CheckCrmEnvironment");
+ return retOrganization;
+ }
+
+ #endregion
+
+ #region DataBase
+
+ protected virtual string GetDataBaseName(Guid organizationId)
+ {
+ string databasename = null;
+
+ SqlConnection connection = null;
+ try
+ {
+ connection = new SqlConnection();
+ connection.ConnectionString =
+ string.Format("Server={1};Initial Catalog={0};Integrated Security=SSPI",
+ CRMDatabaseName, SqlServer);
+
+ connection.Open();
+
+ string commandText = string.Format("SELECT DatabaseName FROM dbo.Organization where id = '{0}'", organizationId);
+ SqlCommand command = new SqlCommand(commandText, connection);
+ object result = command.ExecuteScalar();
+ if (result!=null)
+ databasename = String.Concat(result.ToString());
+
+ }
+ catch (Exception ex)
+ {
+ Log.WriteError(ex);
+ }
+ finally
+ {
+ if (connection != null)
+ connection.Close();
+ }
+
+ return databasename;
+ }
+
+ public virtual long GetDBSize(Guid organizationId)
+ {
+ StartLog("GetDBSize");
+ long res = 0;
+
+ string databasename = GetDataBaseName(organizationId);
+ if (databasename == null) return 0;
+
+ if (databasename == null) return 0;
+
+ SqlConnection connection = null;
+ try
+ {
+ connection = new SqlConnection();
+ connection.ConnectionString =
+ string.Format("Server={1};Initial Catalog={0};Integrated Security=SSPI",
+ databasename, SqlServer);
+
+ connection.Open();
+
+ string commandText = "SELECT ((dbsize ) * 8192 ) size FROM " + // + logsize
+ "( " +
+ "SELECT SUM(CONVERT(BIGINT,CASE WHEN status & 64 = 0 THEN size ELSE 0 END)) dbsize " +
+ ", SUM(CONVERT(BIGINT,CASE WHEN status & 64 <> 0 THEN size ELSE 0 END)) logsize " +
+ "FROM dbo.sysfiles " +
+ ") big";
+
+ SqlCommand command = new SqlCommand(commandText, connection);
+ res = (long)command.ExecuteScalar();
+
+ }
+ catch (Exception ex)
+ {
+ EndLog("GetDBSize", null, null, ex);
+ }
+ finally
+ {
+ if (connection != null)
+ connection.Close();
+
+ }
+
+ EndLog("GetDBSize");
+ return res;
+
+ }
+
+ public virtual long GetMaxDBSize(Guid organizationId)
+ {
+ StartLog("GetMaxDBSize");
+ long res = 0;
+
+ string databasename = GetDataBaseName(organizationId);
+ if (databasename == null) return 0;
+
+ SqlConnection connection = null;
+ try
+ {
+ connection = new SqlConnection();
+ connection.ConnectionString =
+ string.Format("Server={1};Initial Catalog={0};Integrated Security=SSPI",
+ databasename, SqlServer);
+
+ connection.Open();
+
+ string commandText = "SELECT SUM(CONVERT(BIGINT,CASE WHEN status & 64 = 0 THEN maxsize ELSE 0 END)) dbsize FROM dbo.sysfiles";
+
+ SqlCommand command = new SqlCommand(commandText, connection);
+ res = (long)command.ExecuteScalar();
+ if (res > 0) res = res * 8192;
+
+ }
+ catch (Exception ex)
+ {
+ EndLog("GetMaxDBSize", null, null, ex);
+ }
+ finally
+ {
+ if (connection != null)
+ connection.Close();
+
+ }
+
+ EndLog("GetMaxDBSize");
+ return res;
+ }
+
+ public virtual ResultObject SetMaxDBSize(Guid organizationId, long maxSize)
+ {
+ ResultObject res = StartLog("SetMaxDBSize");
+
+ SqlConnection connection = null;
+ try
+ {
+ string databasename = GetDataBaseName(organizationId);
+ if (databasename == null) throw new Exception("Can not get database name");
+
+ connection = new SqlConnection();
+ connection.ConnectionString =
+ string.Format("Server={1};Initial Catalog={0};Integrated Security=SSPI",
+ databasename, SqlServer);
+
+ connection.Open();
+
+ string maxSizeStr = maxSize == -1 ? "UNLIMITED" : (maxSize / (1024 * 1024)).ToString() + " MB";
+
+ string commandText = "ALTER DATABASE [" + databasename + "] MODIFY FILE ( NAME = N'mscrm', MAXSIZE = " + maxSizeStr + " )";
+
+ SqlCommand command = new SqlCommand(commandText, connection);
+ command.ExecuteNonQuery();
+
+ res.IsSuccess = true;
+
+ }
+ catch (Exception ex)
+ {
+ EndLog("SetMaxDBSize", res, CrmErrorCodes.CANNOT_CHANGE_CRM_ORGANIZATION_STATE, ex);
+ }
+ finally
+ {
+ if (connection != null)
+ connection.Close();
+
+ }
+
+ EndLog("SetMaxDBSize");
+ return res;
+ }
+
+ #endregion
+
+ #region Organization
+
+ public virtual OrganizationResult CreateOrganization(Guid organizationId, string organizationUniqueName, string organizationFriendlyName,
+ int baseLanguageCode,
+ string ou,
+ string baseCurrencyCode, string baseCurrencyName, string baseCurrencySymbol,
+ string initialUserDomainName, string initialUserFirstName, string initialUserLastName, string initialUserPrimaryEmail,
+ string organizationCollation,
+ long maxSize)
+ {
+ return CreateOrganizationInternal(organizationId, organizationUniqueName, organizationFriendlyName,
+ baseLanguageCode,
+ ou , baseCurrencyCode, baseCurrencyName, baseCurrencySymbol,
+ initialUserDomainName, initialUserFirstName, initialUserLastName, initialUserPrimaryEmail,
+ organizationCollation,
+ maxSize);
+ }
+
+ protected const string CRMSysAdminRoleStr = "Системный администратор;System Administrator";
+
+ internal virtual OrganizationResult CreateOrganizationInternal(Guid organizationId, string organizationUniqueName, string organizationFriendlyName,
+ int baseLanguageCode,
+ string ou,
+ string baseCurrencyCode, string baseCurrencyName, string baseCurrencySymbol,
+ string initialUserDomainName, string initialUserFirstName, string initialUserLastName, string initialUserPrimaryEmail,
+ string organizationCollation,
+ long maxSize)
+ {
+
+ OrganizationResult ret = StartLog("CreateOrganizationInternal");
+
+ organizationUniqueName = Regex.Replace(organizationUniqueName, @"[^\dA-Za-z]", "-", RegexOptions.Compiled);
+
+ // calculate UserRootPath
+ string ldapstr = "";
+
+ string[] ouItems = ou.Split('.');
+ foreach (string ouItem in ouItems)
+ {
+ if (ldapstr.Length != 0) ldapstr += ",";
+ ldapstr += "OU=" + ouItem;
+ }
+
+ string rootDomain = ServerSettings.ADRootDomain;
+ string[] domainItems = rootDomain.Split('.');
+ foreach (string domainItem in domainItems)
+ ldapstr += ",DC=" + domainItem;
+
+ ldapstr = @"LDAP://" + rootDomain + "/" + ldapstr;
+
+
+
+ if (organizationId == Guid.Empty)
+ throw new ArgumentException("OrganizationId is Guid.Empty");
+
+ if (string.IsNullOrEmpty(organizationFriendlyName))
+ throw new ArgumentNullException("organizationFriendlyName");
+
+ if (string.IsNullOrEmpty(baseCurrencyCode))
+ throw new ArgumentNullException("baseCurrencyCode");
+
+ if (string.IsNullOrEmpty(baseCurrencySymbol))
+ throw new ArgumentNullException("baseCurrencySymbol");
+
+ if (string.IsNullOrEmpty(initialUserDomainName))
+ throw new ArgumentNullException("initialUserDomainName");
+
+ OrganizationResult retCheckEn = CheckCrmEnvironment(CRMDatabaseName, organizationUniqueName);
+
+ if (!retCheckEn.IsSuccess)
+ {
+ ret.ErrorCodes.AddRange(retCheckEn.ErrorCodes);
+ EndLog("CreateOrganizationInternal", ret, null, null);
+ return ret;
+ }
+
+ try
+ {
+
+ DeploymentServiceClient deploymentService = GetDeploymentProxy();
+
+ Microsoft.Xrm.Sdk.Deployment.Organization org = new Microsoft.Xrm.Sdk.Deployment.Organization
+ {
+ Id = organizationId,
+ UniqueName = organizationUniqueName,
+ FriendlyName = organizationFriendlyName,
+ SqlServerName = SqlServer,
+ SrsUrl = ReportingServer,
+ BaseCurrencyCode = baseCurrencyCode,
+ BaseCurrencyName = baseCurrencyName,
+ BaseCurrencySymbol = baseCurrencySymbol,
+ SqlCollation = organizationCollation,
+ State = Microsoft.Xrm.Sdk.Deployment.OrganizationState.Enabled
+ };
+
+ if (baseLanguageCode > 0)
+ org.BaseLanguageCode = baseLanguageCode;
+
+ BeginCreateOrganizationRequest req = new BeginCreateOrganizationRequest
+ {
+ Organization = org
+ };
+
+ if (!String.IsNullOrEmpty(UserName))
+ {
+ req.SysAdminName = UserName;
+ }
+
+ BeginCreateOrganizationResponse resp = deploymentService.Execute(req) as BeginCreateOrganizationResponse;
+
+ if (resp == null)
+ throw new ArgumentException("BeginCreateOrganizationResponse is Null");
+
+ EntityInstanceId id = new EntityInstanceId();
+ id.Name = org.UniqueName;
+
+ Microsoft.Xrm.Sdk.Deployment.OrganizationState OperationState = Microsoft.Xrm.Sdk.Deployment.OrganizationState.Pending;
+
+ int timeout = 30000;
+
+ do
+ {
+ Thread.Sleep(timeout);
+ try
+ {
+ Microsoft.Xrm.Sdk.Deployment.Organization getorg
+ = (Microsoft.Xrm.Sdk.Deployment.Organization)deploymentService.Retrieve(DeploymentEntityType.Organization, id);
+ OperationState = getorg.State;
+ }
+ catch { }
+ } while ((OperationState != Microsoft.Xrm.Sdk.Deployment.OrganizationState.Enabled) &&
+ (OperationState != Microsoft.Xrm.Sdk.Deployment.OrganizationState.Failed));
+
+ if (OperationState == Microsoft.Xrm.Sdk.Deployment.OrganizationState.Failed)
+ throw new ArgumentException("Create organization failed.");
+
+ // update UserRootPath setting
+ Microsoft.Xrm.Sdk.Deployment.ConfigurationEntity orgSettings = new Microsoft.Xrm.Sdk.Deployment.ConfigurationEntity
+ {
+ Id = org.Id,
+ LogicalName = "Organization"
+ };
+ orgSettings.Attributes = new Microsoft.Xrm.Sdk.Deployment.AttributeCollection();
+ orgSettings.Attributes.Add(new KeyValuePair("UserRootPath", ldapstr));
+ Microsoft.Xrm.Sdk.Deployment.UpdateAdvancedSettingsRequest reqUpdateSettings = new Microsoft.Xrm.Sdk.Deployment.UpdateAdvancedSettingsRequest
+ {
+ Entity = orgSettings
+ };
+ Microsoft.Xrm.Sdk.Deployment.UpdateAdvancedSettingsResponse respUpdateSettings = (Microsoft.Xrm.Sdk.Deployment.UpdateAdvancedSettingsResponse) deploymentService.Execute(reqUpdateSettings);
+
+ // DB size limit
+ if (maxSize!=-1)
+ SetMaxDBSize(organizationId, maxSize);
+
+ int tryTimeout = 30000;
+ int tryCount = 10;
+
+ bool success = false;
+ int tryItem = 0;
+
+ while (!success)
+ {
+
+ try
+ {
+ Thread.Sleep(tryTimeout);
+
+ OrganizationServiceProxy _serviceProxy = GetOrganizationProxy(organizationUniqueName, 0, 0);
+
+ string ldap = "";
+
+ Guid SysAdminGuid = RetrieveSystemUser(GetDomainName(initialUserDomainName), initialUserFirstName, initialUserLastName, CRMSysAdminRoleStr, _serviceProxy, ref ldap, 0);
+
+ success = true;
+
+ }
+ catch
+ {
+ tryItem++;
+ if (tryItem >= tryCount)
+ success = true;
+ }
+ }
+
+
+ }
+ catch (Exception ex)
+ {
+ EndLog("CheckCrmEnvironment", ret, CrmErrorCodes.CREATE_CRM_ORGANIZATION_GENERAL_ERROR, ex);
+ return ret;
+
+ }
+
+ EndLog("CheckCrmEnvironment");
+
+ return ret;
+ }
+
+ protected string GetDomainName(string username)
+ {
+ string domain = ActiveDirectoryUtils.GetNETBIOSDomainName(ServerSettings.ADRootDomain);
+ string ret = string.Format(@"{0}\{1}", domain, username);
+ return ret;
+ }
+
+ public virtual string[] GetSupportedCollationNames()
+ {
+ return GetSupportedCollationNamesInternal(SqlServer);
+ }
+
+ internal virtual string[] GetSupportedCollationNamesInternal(string SqlServer)
+ {
+ StartLog("GetSupportedCollationNamesInternal");
+
+ List ret = new List();
+
+ SqlConnection connection = null;
+ try
+ {
+ connection = new SqlConnection();
+ connection.ConnectionString =
+ string.Format("Server={1};Initial Catalog={0};Integrated Security=SSPI",
+ CRMDatabaseName, SqlServer);
+
+ connection.Open();
+
+ string commandText = "select * from fn_helpcollations() where " +
+ "(name not like '%_WS') AND (name not like '%_KS') AND (name not like '%_100_%') " +
+ " AND (name not like 'SQL_%') " +
+ " order by name";
+ SqlCommand command = new SqlCommand(commandText, connection);
+ SqlDataReader reader = command.ExecuteReader();
+
+ while (reader.Read())
+ {
+ string name = reader["name"] as string;
+ ret.Add(name);
+ }
+
+ }
+ catch (Exception ex)
+ {
+ Log.WriteError(ex);
+ }
+ finally
+ {
+ if (connection != null)
+ connection.Close();
+
+ }
+
+ EndLog("GetSupportedCollationNamesInternal");
+ return ret.ToArray();
+ }
+
+ public virtual Currency[] GetCurrencyList()
+ {
+ return GetCurrencyListInternal();
+ }
+
+ internal virtual Currency[] GetCurrencyListInternal()
+ {
+ StartLog("GetCurrencyListInternal");
+ List retList = new List();
+
+ CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.AllCultures & ~CultureTypes.NeutralCultures);
+
+ foreach (CultureInfo culture in cultures)
+ {
+ if (culture.IsNeutralCulture) continue;
+
+ try
+ {
+ RegionInfo Region = new RegionInfo(culture.LCID);
+
+ Currency currency = new Currency();
+ currency.RegionName = Region.NativeName;
+ currency.CurrencyName = Region.CurrencyNativeName;
+ currency.CurrencyCode = Region.ISOCurrencySymbol;
+ currency.CurrencySymbol = Region.CurrencySymbol;
+ retList.Add(currency);
+
+ }
+ catch
+ {
+ continue;
+ }
+ }
+
+ retList.Sort(delegate(Currency a, Currency b) { return a.RegionName.CompareTo(b.RegionName); });
+
+ EndLog("GetCurrencyListInternal");
+ return retList.ToArray();
+ }
+
+ public virtual int[] GetInstalledLanguagePacks()
+ {
+ return GetInstalledLanguagePacksInternal();
+ }
+
+ internal virtual int[] GetInstalledLanguagePacksInternal()
+ {
+ StartLog("GetInstalledLanguagePacks");
+ List res = new List();
+
+ try
+ {
+ RegistryKey root = Registry.LocalMachine;
+ RegistryKey rk = root.OpenSubKey("SOFTWARE\\Microsoft\\MSCRM");
+
+ if (rk == null)
+ rk = root.OpenSubKey("SOFTWARE\\Wow6432Node\\Microsoft\\MSCRM");
+
+ if (rk == null) throw new Exception("Can't open SOFTWARE\\Microsoft\\MSCRM");
+
+ RegistryKey langPacksKey = rk.OpenSubKey("LangPacks");
+ if (langPacksKey == null) throw new Exception("Can't open SOFTWARE\\Microsoft\\MSCRM\\LangPacks");
+
+ string[] langPacksId = langPacksKey.GetSubKeyNames();
+
+ foreach (string strLangId in langPacksId)
+ {
+ int langId = 0;
+ if (int.TryParse(strLangId, out langId))
+ res.Add(langId);
+ }
+
+ }
+ catch (Exception ex)
+ {
+ EndLog("GetInstalledLanguagePacks", null, null, ex);
+ return null;
+ }
+
+ EndLog("GetInstalledLanguagePacks");
+ return res.ToArray();
+ }
+
+ public virtual ResultObject DeleteOrganization(Guid orgId)
+ {
+ return DeleteOrganizationInternal(orgId);
+ }
+
+ internal virtual ResultObject DeleteOrganizationInternal(Guid orgId)
+ {
+ ResultObject res = StartLog("DeleteOrganizationInternal");
+
+
+ res.IsSuccess = true;
+ try
+ {
+ DeploymentServiceClient deploymentService = GetDeploymentProxy();
+
+ EntityInstanceId i = new EntityInstanceId();
+ i.Id = orgId; //Organisation Id
+
+ Microsoft.Xrm.Sdk.Deployment.Organization org = (Microsoft.Xrm.Sdk.Deployment.Organization)deploymentService.Retrieve(DeploymentEntityType.Organization, i);
+
+ org.State = Microsoft.Xrm.Sdk.Deployment.OrganizationState.Disabled;
+
+ Microsoft.Xrm.Sdk.Deployment.UpdateRequest updateRequest = new Microsoft.Xrm.Sdk.Deployment.UpdateRequest();
+ updateRequest.Entity = org;
+
+ deploymentService.Execute(updateRequest);
+
+ }
+ catch (Exception ex)
+ {
+ EndLog("DeleteOrganizationInternal", res, CrmErrorCodes.DELETE_CRM_ORGANIZATION_GENERAL_ERROR, ex);
+ return res;
+
+ }
+
+
+ EndLog("DeleteOrganizationInternal");
+ return res;
+ }
+
+ public override void DeleteServiceItems(ServiceProviderItem[] items)
+ {
+ foreach (ServiceProviderItem item in items)
+ {
+ try
+ {
+ if (item is Organization)
+ {
+ Organization org = item as Organization;
+ DeleteOrganization(org.CrmOrganizationId);
+ }
+
+ }
+ catch (Exception ex)
+ {
+ Log.WriteError(String.Format("Error deleting '{0}' {1}", item.Name, item.GetType().Name), ex);
+ }
+ }
+ base.DeleteServiceItems(items);
+
+ }
+
+ #endregion
+
+ #region Log
+
+ private static void EndLog(string message, ResultObject res, string errorCode, Exception ex)
+ {
+ if (res != null)
+ {
+ res.IsSuccess = false;
+
+ if (!string.IsNullOrEmpty(errorCode))
+ res.ErrorCodes.Add(errorCode);
+ }
+
+ if (ex != null)
+ HostedSolutionLog.LogError(ex);
+
+ HostedSolutionLog.LogEnd(message);
+ }
+
+ private static void EndLog(string message, ResultObject res, string errorCode)
+ {
+ EndLog(message, res, errorCode, null);
+ }
+
+ private static void EndLog(string message, ResultObject res)
+ {
+ EndLog(message, res, null);
+ }
+
+ private static void EndLog(string message)
+ {
+ EndLog(message, null);
+ }
+
+ private static T StartLog(string message) where T : ResultObject, new()
+ {
+ HostedSolutionLog.LogStart(message);
+ T res = new T();
+ res.IsSuccess = true;
+ return res;
+ }
+
+ private static void StartLog(string message)
+ {
+ HostedSolutionLog.LogStart(message);
+ }
+
+ #endregion
+
+ #region User
+
+ public virtual UserResult CreateCRMUser(OrganizationUser user, string orgName, Guid organizationId, Guid baseUnitId, int CALType)
+ {
+ return CreateCRMUserInternal(user, orgName, organizationId, baseUnitId, CALType);
+ }
+
+ internal virtual UserResult CreateCRMUserInternal(OrganizationUser user, string orgName, Guid organizationId, Guid businessUnitId, int CALType)
+ {
+ UserResult res = StartLog("CreateCRMUserInternal");
+
+ try
+ {
+ if (user == null)
+ throw new ArgumentNullException("user");
+
+ if (string.IsNullOrEmpty(orgName))
+ throw new ArgumentNullException("orgName");
+
+ if (organizationId == Guid.Empty)
+ throw new ArgumentException("organizationId");
+
+ if (businessUnitId == Guid.Empty)
+ throw new ArgumentException("businessUnitId");
+
+ try
+ {
+ OrganizationServiceProxy _serviceProxy = GetOrganizationProxy(orgName);
+
+
+ string ldap = "";
+ Guid guid = RetrieveSystemUser(user.DomainUserName, user.FirstName, user.LastName, CRMSysAdminRoleStr, _serviceProxy, ref ldap, CALType);
+
+ user.CrmUserId = guid;
+ res.Value = user;
+
+ }
+ catch (Exception ex)
+ {
+ EndLog("CreateCRMUserInternal", res, CrmErrorCodes.CANNOT_CREATE_CRM_USER, ex);
+ return res;
+ }
+ }
+ catch (Exception ex)
+ {
+ EndLog("CreateCRMUserInternal", res, CrmErrorCodes.CANNOT_CREATE_CRM_USER_GENERAL_ERROR, ex);
+ return res;
+
+ }
+
+ EndLog("CreateCRMUserInternal");
+ return res;
+ }
+
+ protected virtual Guid CreateSystemUser(String userName, String firstName,
+ String lastName, String domain, String roleStr,
+ OrganizationServiceProxy serviceProxy, ref String ldapPath, int CALType)
+ {
+
+ if (serviceProxy.ServiceConfiguration.AuthenticationType == AuthenticationProviderType.LiveId ||
+ serviceProxy.ServiceConfiguration.AuthenticationType == AuthenticationProviderType.OnlineFederation)
+ throw new Exception(String.Format("To run this sample, {0} {1} must be an active system user in your Microsoft Dynamics CRM Online organization.", firstName, lastName));
+
+ Guid userId = Guid.Empty;
+
+ Microsoft.Xrm.Sdk.Query.QueryExpression businessUnitQuery = new Microsoft.Xrm.Sdk.Query.QueryExpression
+ {
+ EntityName = BusinessUnit.EntityLogicalName,
+ ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet("businessunitid"),
+ Criteria =
+ {
+ Conditions =
+ {
+ new Microsoft.Xrm.Sdk.Query.ConditionExpression("parentbusinessunitid",
+ Microsoft.Xrm.Sdk.Query.ConditionOperator.Null)
+ }
+ }
+ };
+
+ BusinessUnit defaultBusinessUnit = serviceProxy.RetrieveMultiple(
+ businessUnitQuery).Entities[0].ToEntity();
+
+ // Retrieve the specified security role.
+ Role role = RetrieveRoleByName(serviceProxy, roleStr);
+
+ // CALType and AccessMode
+ int accessmode = CALType / 10;
+ int caltype = CALType % 10;
+
+ //Create a new system user.
+ SystemUser user = new SystemUser
+ {
+ DomainName = userName,
+ FirstName = firstName,
+ LastName = lastName,
+ BusinessUnitId = new EntityReference
+ {
+ LogicalName = BusinessUnit.EntityLogicalName,
+ Name = BusinessUnit.EntityLogicalName,
+ Id = defaultBusinessUnit.Id
+ },
+ CALType = new OptionSetValue(caltype),
+ AccessMode = new OptionSetValue(accessmode)
+ };
+ userId = serviceProxy.Create(user);
+
+ // Assign the security role to the newly created Microsoft Dynamics CRM user.
+ AssociateRequest associate = new AssociateRequest()
+ {
+ Target = new EntityReference(SystemUser.EntityLogicalName, userId),
+ RelatedEntities = new EntityReferenceCollection()
+ {
+ new EntityReference(Role.EntityLogicalName, role.Id),
+ },
+ Relationship = new Relationship("systemuserroles_association")
+ };
+ serviceProxy.Execute(associate);
+
+ return userId;
+ }
+
+
+ protected virtual Guid RetrieveSystemUser(String userName, String firstName,
+ String lastName, String roleStr, OrganizationServiceProxy serviceProxy,
+ ref String ldapPath,
+ int CALType)
+ {
+ String domain;
+ Guid userId = Guid.Empty;
+
+ if (serviceProxy == null)
+ throw new ArgumentNullException("serviceProxy");
+
+ if (String.IsNullOrWhiteSpace(userName))
+ throw new ArgumentNullException("UserName");
+
+ if (String.IsNullOrWhiteSpace(firstName))
+ throw new ArgumentNullException("FirstName");
+
+ if (String.IsNullOrWhiteSpace(lastName))
+ throw new ArgumentNullException("LastName");
+
+ if (String.IsNullOrWhiteSpace(roleStr))
+ throw new ArgumentNullException("Role");
+
+ // Obtain the current user's information.
+ Microsoft.Crm.Sdk.Messages.WhoAmIRequest who = new Microsoft.Crm.Sdk.Messages.WhoAmIRequest();
+ Microsoft.Crm.Sdk.Messages.WhoAmIResponse whoResp = (Microsoft.Crm.Sdk.Messages.WhoAmIResponse)serviceProxy.Execute(who);
+ Guid currentUserId = whoResp.UserId;
+
+ SystemUser currentUser =
+ serviceProxy.Retrieve(SystemUser.EntityLogicalName, currentUserId, new Microsoft.Xrm.Sdk.Query.ColumnSet("domainname")).ToEntity();
+
+ // Extract the domain and create the LDAP object.
+ String[] userPath = currentUser.DomainName.Split(new char[] { '\\' });
+ if (userPath.Length > 1)
+ domain = userPath[0] + "\\";
+ else
+ domain = String.Empty;
+
+ // Create the system user in Microsoft Dynamics CRM if the user doesn't
+ // already exist.
+ Microsoft.Xrm.Sdk.Query.QueryExpression userQuery = new Microsoft.Xrm.Sdk.Query.QueryExpression
+ {
+ EntityName = SystemUser.EntityLogicalName,
+ ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet("systemuserid"),
+ Criteria =
+ {
+ FilterOperator = Microsoft.Xrm.Sdk.Query.LogicalOperator.Or,
+ Filters =
+ {
+ new Microsoft.Xrm.Sdk.Query.FilterExpression
+ {
+ FilterOperator = Microsoft.Xrm.Sdk.Query.LogicalOperator.And,
+ Conditions =
+ {
+ new Microsoft.Xrm.Sdk.Query.ConditionExpression("domainname", Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal, domain + userName)
+ }
+ },
+ new Microsoft.Xrm.Sdk.Query.FilterExpression
+ {
+ FilterOperator = Microsoft.Xrm.Sdk.Query.LogicalOperator.And,
+ Conditions =
+ {
+ new Microsoft.Xrm.Sdk.Query.ConditionExpression("firstname", Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal, firstName),
+ new Microsoft.Xrm.Sdk.Query.ConditionExpression("lastname", Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal, lastName)
+ }
+ }
+ }
+
+ }
+ };
+
+ DataCollection existingUsers = (DataCollection)serviceProxy.RetrieveMultiple(userQuery).Entities;
+
+ SystemUser existingUser = null;
+ if (existingUsers.Count > 0)
+ existingUser = existingUsers[0].ToEntity();
+
+ if (existingUser != null)
+ {
+ userId = existingUser.SystemUserId.Value;
+
+ // Check to make sure the user is assigned the correct role.
+ Role role = RetrieveRoleByName(serviceProxy, roleStr);
+
+ // Associate the user with the role when needed.
+ if (!UserInRole(serviceProxy, userId, role.Id))
+ {
+ AssociateRequest associate = new AssociateRequest()
+ {
+ Target = new EntityReference(SystemUser.EntityLogicalName, userId),
+ RelatedEntities = new EntityReferenceCollection()
+ {
+ new EntityReference(Role.EntityLogicalName, role.Id)
+ },
+ Relationship = new Relationship("systemuserroles_association")
+ };
+ serviceProxy.Execute(associate);
+ }
+
+ }
+ else
+ {
+ userId = CreateSystemUser(userName, firstName, lastName, domain,
+ roleStr, serviceProxy, ref ldapPath, CALType);
+ }
+
+ return userId;
+ }
+
+ public virtual CrmUserResult GetCrmUserById(Guid crmUserId, string orgName)
+ {
+ return GetCrmUserByIdInternal(crmUserId, orgName);
+ }
+
+ internal virtual CrmUserResult GetCrmUserByIdInternal(Guid crmUserId, string orgName)
+ {
+ CrmUserResult ret = StartLog("GetCrmUserByIdInternal");
+
+ try
+ {
+ if (crmUserId == Guid.Empty)
+ throw new ArgumentNullException("crmUserId");
+
+ if (string.IsNullOrEmpty(orgName))
+ throw new ArgumentNullException("orgName");
+
+ OrganizationServiceProxy serviceProxy = GetOrganizationProxy(orgName);
+
+ SystemUser retruveUser =
+ serviceProxy.Retrieve(SystemUser.EntityLogicalName, crmUserId, new Microsoft.Xrm.Sdk.Query.ColumnSet("domainname", "businessunitid", "accessmode", "isdisabled", "caltype")).ToEntity();
+
+ CrmUser user = null;
+
+ if (retruveUser != null)
+ {
+ user = new CrmUser();
+ user.BusinessUnitId = retruveUser.BusinessUnitId.Id;
+ user.CRMUserId = retruveUser.SystemUserId.Value;
+ user.ClientAccessMode = (CRMUserAccessMode)retruveUser.AccessMode.Value;
+ user.IsDisabled = (bool)retruveUser.IsDisabled;
+ user.CALType = retruveUser.CALType.Value;
+
+ ret.Value = user;
+ }
+ }
+ catch (Exception ex)
+ {
+ EndLog("GetCrmUserByIdInternal", ret, CrmErrorCodes.CANONT_GET_CRM_USER_BY_ID, ex);
+ return ret;
+ }
+
+ EndLog("GetCrmUserByIdInternal");
+ return ret;
+ }
+
+ internal virtual CrmUserResult GetCrmUserByDomainNameInternal(string domainName, string orgName)
+ {
+ CrmUserResult ret = StartLog("GetCrmUserByDomainNameInternal");
+
+ try
+ {
+ if (string.IsNullOrEmpty(domainName))
+ throw new ArgumentNullException("domainName");
+
+ if (string.IsNullOrEmpty(orgName))
+ throw new ArgumentNullException("orgName");
+
+
+ OrganizationServiceProxy serviceProxy = GetOrganizationProxy(orgName);
+
+ Microsoft.Xrm.Sdk.Query.QueryExpression usereQuery = new Microsoft.Xrm.Sdk.Query.QueryExpression
+ {
+ EntityName = SystemUser.EntityLogicalName,
+ ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet("domainname", "businessunitid", "accessmode", "isdisabled", "systemuserid", "caltype"),
+ };
+
+ EntityCollection users = serviceProxy.RetrieveMultiple(usereQuery);
+
+ foreach (Entity entityuser in users.Entities)
+ {
+ SystemUser sysuser = entityuser.ToEntity();
+
+ if (sysuser == null) continue;
+ if (sysuser.DomainName != domainName) continue;
+
+ CrmUser user = new CrmUser();
+ user.BusinessUnitId = sysuser.BusinessUnitId.Id;
+ user.CRMUserId = sysuser.SystemUserId.Value;
+ user.ClientAccessMode = (CRMUserAccessMode)sysuser.AccessMode.Value;
+ user.IsDisabled = sysuser.IsDisabled.Value;
+ user.CALType = sysuser.CALType.Value;
+ ret.Value = user;
+ }
+ }
+ catch (Exception ex)
+ {
+ EndLog("GetCrmUserByDomainNameInternal", ret, CrmErrorCodes.CANONT_GET_CRM_USER_BY_DOMAIN_NAME, ex);
+ return ret;
+ }
+
+ EndLog("GetCrmUserByDomainNameInternal");
+ return ret;
+ }
+
+ public virtual CrmUserResult GetCrmUserByDomainName(string domainName, string orgName)
+ {
+ return GetCrmUserByDomainNameInternal(domainName, orgName);
+ }
+
+ public virtual ResultObject ChangeUserState(bool disable, string orgName, Guid crmUserId)
+ {
+ return ChangeUserStateInternal(disable, orgName, crmUserId);
+ }
+
+ internal virtual ResultObject ChangeUserStateInternal(bool disable, string orgName, Guid crmUserId)
+ {
+ ResultObject res = StartLog("ChangeUserStateInternal");
+
+ res.IsSuccess = true;
+ try
+ {
+ if (crmUserId == Guid.Empty)
+ throw new ArgumentNullException("crmUserId");
+
+ if (string.IsNullOrEmpty(orgName))
+ throw new ArgumentNullException("orgName");
+
+ OrganizationServiceProxy serviceProxy = GetOrganizationProxy(orgName);
+
+ // Retrieve a user.
+ SystemUser user = serviceProxy.Retrieve(SystemUser.EntityLogicalName,
+ crmUserId, new Microsoft.Xrm.Sdk.Query.ColumnSet(new String[] { "systemuserid", "firstname", "lastname" })).ToEntity();
+
+ if (user != null)
+ {
+ Microsoft.Crm.Sdk.Messages.SetStateRequest request = new Microsoft.Crm.Sdk.Messages.SetStateRequest()
+ {
+ EntityMoniker = user.ToEntityReference(),
+
+ // Required by request but always valued at -1 in this context.
+ Status = new OptionSetValue(-1),
+
+ // Sets the user to disabled.
+ State = disable ? new OptionSetValue(-1) : new OptionSetValue(0)
+ };
+
+ serviceProxy.Execute(request);
+
+ }
+ }
+ catch (Exception ex)
+ {
+ EndLog("ChangeUserStateInternal", res, CrmErrorCodes.CANNOT_CHANGE_USER_STATE, ex);
+ return res;
+ }
+
+
+ EndLog("ChangeUserStateInternal");
+ return res;
+ }
+
+ public virtual ResultObject SetUserCALType(string orgName, Guid userId, int CALType)
+ {
+ return SetUserCALTypeInternal(orgName, userId, CALType);
+ }
+
+ internal virtual ResultObject SetUserCALTypeInternal(string orgName, Guid userId, int CALType)
+ {
+ ResultObject ret = StartLog("SetUserCALTypeInternal");
+
+ try
+ {
+ if (userId == Guid.Empty)
+ throw new ArgumentNullException("crmUserId");
+
+ if (string.IsNullOrEmpty(orgName))
+ throw new ArgumentNullException("orgName");
+
+ OrganizationServiceProxy serviceProxy = GetOrganizationProxy(orgName);
+
+ SystemUser user =
+ serviceProxy.Retrieve(SystemUser.EntityLogicalName, userId, new Microsoft.Xrm.Sdk.Query.ColumnSet("domainname", "businessunitid", "accessmode", "isdisabled", "caltype")).ToEntity();
+
+ // CALType and AccessMode
+ int accessmode = CALType / 10;
+ int caltype = CALType % 10;
+
+ user.CALType = new OptionSetValue(caltype);
+ user.AccessMode = new OptionSetValue(accessmode);
+
+ serviceProxy.Update(user);
+
+ }
+ catch (Exception ex)
+ {
+ EndLog("SetUserCALTypeInternal", ret, CrmErrorCodes.CANONT_GET_CRM_USER_BY_ID, ex);
+ return ret;
+ }
+
+ EndLog("SetUserCALTypeInternal");
+ return ret;
+ }
+
+ #endregion
+
+ #region Role
+
+ protected virtual Role RetrieveRoleByName(OrganizationServiceProxy serviceProxy,
+ String roleSplitStr)
+ {
+ string[] RolesStr = roleSplitStr.Split(';');
+
+ foreach (string roleStr in RolesStr)
+ {
+
+ Microsoft.Xrm.Sdk.Query.QueryExpression roleQuery = new Microsoft.Xrm.Sdk.Query.QueryExpression
+ {
+ EntityName = Role.EntityLogicalName,
+ ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet("roleid"),
+ Criteria =
+ {
+ Conditions =
+ {
+ new Microsoft.Xrm.Sdk.Query.ConditionExpression("name", Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal, roleStr)
+ }
+ }
+ };
+
+ DataCollection roles = serviceProxy.RetrieveMultiple(roleQuery).Entities;
+
+ if (roles.Count > 0) return roles[0].ToEntity();
+ }
+
+ return null;
+ }
+
+ protected virtual bool UserInRole(OrganizationServiceProxy serviceProxy,
+ Guid userId, Guid roleId)
+ {
+ // Establish a SystemUser link for a query.
+ Microsoft.Xrm.Sdk.Query.LinkEntity systemUserLink = new Microsoft.Xrm.Sdk.Query.LinkEntity()
+ {
+ LinkFromEntityName = SystemUserRoles.EntityLogicalName,
+ LinkFromAttributeName = "systemuserid",
+ LinkToEntityName = SystemUser.EntityLogicalName,
+ LinkToAttributeName = "systemuserid",
+ LinkCriteria =
+ {
+ Conditions =
+ {
+ new Microsoft.Xrm.Sdk.Query.ConditionExpression(
+ "systemuserid", Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal, userId)
+ }
+ }
+ };
+
+ // Build the query.
+ Microsoft.Xrm.Sdk.Query.QueryExpression query = new Microsoft.Xrm.Sdk.Query.QueryExpression()
+ {
+ EntityName = Role.EntityLogicalName,
+ ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet("roleid"),
+ LinkEntities =
+ {
+ new Microsoft.Xrm.Sdk.Query.LinkEntity()
+ {
+ LinkFromEntityName = Role.EntityLogicalName,
+ LinkFromAttributeName = "roleid",
+ LinkToEntityName = SystemUserRoles.EntityLogicalName,
+ LinkToAttributeName = "roleid",
+ LinkEntities = {systemUserLink}
+ }
+ },
+ Criteria =
+ {
+ Conditions =
+ {
+ new Microsoft.Xrm.Sdk.Query.ConditionExpression("roleid", Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal, roleId)
+ }
+ }
+ };
+
+ // Retrieve matching roles.
+ EntityCollection ec = serviceProxy.RetrieveMultiple(query);
+
+ if (ec.Entities.Count > 0)
+ return true;
+
+ return false;
+ }
+
+ public virtual CrmRolesResult GetAllCrmRoles(string orgName, Guid businessUnitId)
+ {
+ return GetAllCrmRolesInternal(orgName, businessUnitId);
+ }
+
+ public virtual CrmRolesResult GetCrmUserRoles(string orgName, Guid userId)
+ {
+ return GetCrmUserRolesInternal(userId, orgName);
+ }
+
+ public virtual EntityCollection GetUserRoles(Guid userId, string orgName)
+ {
+ OrganizationServiceProxy serviceProxy = GetOrganizationProxy(orgName);
+
+ // Establish a SystemUser link for a query.
+ Microsoft.Xrm.Sdk.Query.LinkEntity systemUserLink = new Microsoft.Xrm.Sdk.Query.LinkEntity()
+ {
+ LinkFromEntityName = SystemUserRoles.EntityLogicalName,
+ LinkFromAttributeName = "systemuserid",
+ LinkToEntityName = SystemUser.EntityLogicalName,
+ LinkToAttributeName = "systemuserid",
+ LinkCriteria =
+ {
+ Conditions =
+ {
+ new Microsoft.Xrm.Sdk.Query.ConditionExpression(
+ "systemuserid", Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal, userId)
+ }
+ }
+ };
+
+ // Build the query.
+ Microsoft.Xrm.Sdk.Query.QueryExpression query = new Microsoft.Xrm.Sdk.Query.QueryExpression()
+ {
+ EntityName = Role.EntityLogicalName,
+ ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet("roleid"),
+ LinkEntities =
+ {
+ new Microsoft.Xrm.Sdk.Query.LinkEntity()
+ {
+ LinkFromEntityName = Role.EntityLogicalName,
+ LinkFromAttributeName = "roleid",
+ LinkToEntityName = SystemUserRoles.EntityLogicalName,
+ LinkToAttributeName = "roleid",
+ LinkEntities = {systemUserLink}
+ }
+ }
+ };
+
+ // Retrieve matching roles.
+ EntityCollection relations = serviceProxy.RetrieveMultiple(query);
+
+ return relations;
+ }
+
+ internal virtual CrmRolesResult GetCrmUserRolesInternal(Guid userId, string orgName)
+ {
+ CrmRolesResult res = StartLog("GetCrmUserRolesInternal");
+
+ try
+ {
+ EntityCollection relations;
+
+ if (userId == Guid.Empty)
+ throw new ArgumentException("userId");
+
+ if (string.IsNullOrEmpty(orgName))
+ throw new ArgumentNullException("orgName");
+
+ try
+ {
+ relations = GetUserRoles(userId, orgName);
+ }
+ catch (Exception ex)
+ {
+ EndLog("GetCrmUserRolesInternal", res, CrmErrorCodes.CANNOT_GET_CRM_USER_ROLES, ex);
+ return res;
+ }
+
+ try
+ {
+ res.Value = FillCrmRoles(relations, true, Guid.Empty);
+ }
+ catch (Exception ex)
+ {
+ EndLog("GetCrmUserRolesInternal", res, CrmErrorCodes.CANNOT_FILL_ROLES_COLLECTION, ex);
+ return res;
+ }
+ }
+ catch (Exception ex)
+ {
+ EndLog("GetCrmUserRolesInternal", res, CrmErrorCodes.GET_CRM_USER_ROLE_GENERAL_ERROR, ex);
+ return res;
+ }
+
+ EndLog("GetCrmUserRolesInternal");
+ return res;
+ }
+
+ protected static string excludedRolesStr = ";пользователь поддержки;support user;";
+
+ protected virtual List FillCrmRoles(EntityCollection entities, bool isUserRole, Guid businessUnitId)
+ {
+ List res = new List();
+
+ foreach (Entity current in entities.Entities)
+ {
+ Role role = current.ToEntity();
+
+ if (role == null) continue;
+
+ if (businessUnitId != Guid.Empty)
+ {
+ if (businessUnitId != role.BusinessUnitId.Id)
+ continue;
+ }
+
+ string roleName = role.Name;
+
+ if (roleName != null)
+ if (excludedRolesStr.IndexOf(";" + roleName.ToLower() + ";") != -1)
+ continue;
+
+ CrmRole crmRole = new CrmRole();
+ crmRole.IsCurrentUserRole = isUserRole;
+ crmRole.RoleId = (Guid)role.RoleId;
+ crmRole.RoleName = roleName;
+
+ res.Add(crmRole);
+ }
+
+ return res;
+ }
+
+ protected virtual List FillCrmRoles(EntityCollection entities, Guid businessUnitId)
+ {
+ return FillCrmRoles(entities, false, businessUnitId);
+ }
+
+ internal virtual CrmRolesResult GetAllCrmRolesInternal(string orgName, Guid businessUnitId)
+ {
+ CrmRolesResult res = StartLog("GetAllCrmRoles");
+
+ try
+ {
+ if (string.IsNullOrEmpty(orgName))
+ throw new ArgumentNullException("orgName");
+
+ EntityCollection roles;
+ try
+ {
+ OrganizationServiceProxy serviceProxy = GetOrganizationProxy(orgName);
+
+ Microsoft.Xrm.Sdk.Query.QueryExpression roleQuery = new Microsoft.Xrm.Sdk.Query.QueryExpression
+ {
+ EntityName = Role.EntityLogicalName,
+ ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet(new string[] { "roleid", "name", "businessunitid" }),
+ };
+
+ roles = serviceProxy.RetrieveMultiple(roleQuery);
+
+
+ }
+ catch (Exception ex)
+ {
+ EndLog("GetAllCrmRoles", res, CrmErrorCodes.CANNOT_GET_ALL_CRM_ROLES, ex);
+ return res;
+ }
+
+ try
+ {
+ List crmRoles = FillCrmRoles(roles, businessUnitId);
+ res.Value = crmRoles;
+ }
+ catch (Exception ex)
+ {
+ EndLog("GetAllCrmRoles", res, CrmErrorCodes.CANNOT_FILL_ROLES_COLLECTION, ex);
+ return res;
+ }
+ }
+ catch (Exception ex)
+ {
+ EndLog("GetAllCrmRoles", res, CrmErrorCodes.GET_ALL_CRM_ROLES_GENERAL_ERROR, ex);
+ return res;
+ }
+
+ EndLog("GetAllCrmRoles");
+ return res;
+ }
+
+ public virtual ResultObject SetUserRoles(string orgName, Guid userId, Guid[] roles)
+ {
+ return SetUserRolesInternal(orgName, userId, roles);
+ }
+
+ internal virtual ResultObject SetUserRolesInternal(string orgName, Guid userId, Guid[] roles)
+ {
+ CrmRolesResult res = StartLog("SetUserRolesInternal");
+
+ try
+ {
+ if (string.IsNullOrEmpty(orgName))
+ throw new ArgumentNullException("orgName");
+
+ if (userId == Guid.Empty)
+ throw new ArgumentException("userId");
+
+ if (roles == null)
+ throw new ArgumentNullException("roles");
+
+ OrganizationServiceProxy serviceProxy = GetOrganizationProxy(orgName);
+
+
+ CrmRolesResult tmpRoles = GetCrmUserRoles(orgName, userId);
+ res.ErrorCodes.AddRange(tmpRoles.ErrorCodes);
+
+ if (!tmpRoles.IsSuccess)
+ return res;
+
+ List remRoles = new List();
+
+ for (int i = 0; i < tmpRoles.Value.Count; i++)
+ {
+ if (Array.Find(roles, delegate(Guid current) { return current == tmpRoles.Value[i].RoleId; }) == Guid.Empty)
+ {
+ remRoles.Add(tmpRoles.Value[i].RoleId);
+ }
+ }
+
+ try
+ {
+ DisassociateRequest removeRole = new DisassociateRequest()
+ {
+ Target = new EntityReference(SystemUser.EntityLogicalName, userId),
+ RelatedEntities = new EntityReferenceCollection(),
+ Relationship = new Relationship("systemuserroles_association")
+ };
+
+ for (int i = 0; i < remRoles.Count; i++)
+ removeRole.RelatedEntities.Add(new EntityReference(Role.EntityLogicalName, remRoles[i]));
+
+ serviceProxy.Execute(removeRole);
+
+ }
+ catch (Exception ex)
+ {
+ EndLog("SetUserRolesInternal", res, CrmErrorCodes.CANNOT_REMOVE_CRM_USER_ROLES, ex);
+ return res;
+ }
+
+
+ try
+ {
+ // Assign the security role to the newly created Microsoft Dynamics CRM user.
+ AssociateRequest associate = new AssociateRequest()
+ {
+ Target = new EntityReference(SystemUser.EntityLogicalName, userId),
+ RelatedEntities = new EntityReferenceCollection(),
+ Relationship = new Relationship("systemuserroles_association")
+ };
+
+ for (int i = 0; i < roles.Length; i++)
+ {
+ bool find = false;
+ foreach (CrmRole current in tmpRoles.Value)
+ {
+ if (current.RoleId == roles[i])
+ find = true;
+ }
+ if (find) continue;
+
+ associate.RelatedEntities.Add(new EntityReference(Role.EntityLogicalName, roles[i]));
+ }
+
+ serviceProxy.Execute(associate);
+ }
+ catch (Exception ex)
+ {
+ EndLog("SetUserRolesInternal", res, CrmErrorCodes.CANNOT_ASSIGN_CRM_USER_ROLES, ex);
+ return res;
+ }
+
+ }
+ catch (Exception ex)
+ {
+ EndLog("SetUserRolesInternal", res, CrmErrorCodes.CANNOT_SET_CRM_USER_ROLES_GENERAL_ERROR, ex);
+ return res;
+ }
+
+
+ EndLog("SetUserRolesInternal");
+ return res;
+
+ }
+
+ #endregion
+
+ #region Business Units
+
+ internal virtual CRMBusinessUnitsResult GetOrganizationBusinessUnitsInternal(Guid organizationId, string orgName)
+ {
+ CRMBusinessUnitsResult res = StartLog("GetOrganizationBusinessUnitsInternal");
+
+ try
+ {
+ if (organizationId == Guid.Empty)
+ throw new ArgumentException("organizationId");
+
+ if (string.IsNullOrEmpty(orgName))
+ throw new ArgumentNullException("orgName");
+
+ OrganizationServiceProxy serviceProxy;
+
+ try
+ {
+ serviceProxy = GetOrganizationProxy(orgName);
+ }
+ catch (Exception ex)
+ {
+ EndLog("GetOrganizationBusinessUnitsInternal", res, CrmErrorCodes.CANNOT_GET_CRM_SERVICE, ex);
+ return res;
+ }
+
+ DataCollection BusinessUnits;
+
+ try
+ {
+
+ Microsoft.Xrm.Sdk.Query.QueryExpression businessUnitQuery = new Microsoft.Xrm.Sdk.Query.QueryExpression
+ {
+ EntityName = BusinessUnit.EntityLogicalName,
+ ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet(new string[] { "businessunitid", "name" }),
+ Criteria =
+ {
+ Conditions =
+ {
+ new Microsoft.Xrm.Sdk.Query.ConditionExpression("parentbusinessunitid",
+ Microsoft.Xrm.Sdk.Query.ConditionOperator.Null)
+ }
+ }
+ };
+
+ BusinessUnits = serviceProxy.RetrieveMultiple(
+ businessUnitQuery).Entities;
+
+ }
+ catch (Exception ex)
+ {
+ EndLog("GetOrganizationBusinessUnitsInternal", res, CrmErrorCodes.CANNOT_GET_CRM_BUSINESS_UNITS, ex);
+ return res;
+ }
+
+ List businessUnits = new List();
+
+ try
+ {
+ for (int i = 0; i < BusinessUnits.Count; i++)
+ {
+ BusinessUnit bu = BusinessUnits[i].ToEntity();
+
+ CRMBusinessUnit unit = new CRMBusinessUnit();
+ unit.BusinessUnitId = (Guid)bu.BusinessUnitId;
+ unit.BusinessUnitName = bu.Name;
+
+ if (unit.BusinessUnitName == null)
+ unit.BusinessUnitName = "default";
+
+ businessUnits.Add(unit);
+
+ }
+
+ res.Value = businessUnits;
+ }
+ catch (Exception ex)
+ {
+ EndLog("GetOrganizationBusinessUnitsInternal", res, CrmErrorCodes.CANNOT_FILL_BASE_UNITS_COLLECTION,
+ ex);
+ return res;
+ }
+ }
+ catch (Exception ex)
+ {
+ EndLog("GetOrganizationBusinessUnitsInternal", res, CrmErrorCodes.GET_ORGANIZATION_BUSINESS_UNITS_GENERAL_ERROR,
+ ex);
+ return res;
+
+ }
+
+ EndLog("GetOrganizationBusinessUnitsInternal");
+ return res;
+
+ }
+
+ public virtual CRMBusinessUnitsResult GetOrganizationBusinessUnits(Guid organizationId, string orgName)
+ {
+ return GetOrganizationBusinessUnitsInternal(organizationId, orgName);
+ }
+
+ #endregion
+
+ #region Version
+
+ public virtual string CRMServerVersion
+ {
+ get
+ {
+ string value = "";
+ try
+ {
+ RegistryKey root = Registry.LocalMachine;
+ RegistryKey rk = root.OpenSubKey("SOFTWARE\\Microsoft\\MSCRM");
+
+ if (rk == null)
+ rk = root.OpenSubKey("SOFTWARE\\Wow6432Node\\Microsoft\\MSCRM");
+
+ if (rk != null)
+ {
+ value = (string)rk.GetValue("CRM_Server_Version", null);
+ rk.Close();
+ }
+ }
+ catch (Exception ex)
+ {
+ Log.WriteError(ex);
+ }
+
+ return value;
+ }
+
+ }
+
+ public override bool IsInstalled()
+ {
+ return false;
+ }
+
+ #endregion
+
+ }
+}
diff --git a/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution.Crm2013/CRMProvider2013.cs b/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution.Crm2013/CRMProvider2013.cs
new file mode 100644
index 00000000..3b1b7dde
--- /dev/null
+++ b/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution.Crm2013/CRMProvider2013.cs
@@ -0,0 +1,46 @@
+// Copyright (c) 2012 - 2013, 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 WebsitePanel.Providers.HostedSolution;
+
+
+namespace WebsitePanel.Providers.HostedSolution
+{
+ public class CRMProvider2013 : CRMBase
+ {
+
+ public override bool IsInstalled()
+ {
+
+ return CRMServerVersion.StartsWith("6.");
+ }
+
+ }
+
+}
diff --git a/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution.Crm2013/HostedSolutionLog.cs b/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution.Crm2013/HostedSolutionLog.cs
new file mode 100644
index 00000000..83257a78
--- /dev/null
+++ b/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution.Crm2013/HostedSolutionLog.cs
@@ -0,0 +1,152 @@
+// 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 WebsitePanel.Providers.Common;
+using WebsitePanel.Server.Utils;
+using System.Text;
+using System.Management.Automation.Runspaces;
+
+namespace WebsitePanel.Providers.HostedSolution
+{
+ public class HostedSolutionLog
+ {
+ public static string LogPrefix = "HostedSolution";
+
+ public static void LogStart(string message, params object[] args)
+ {
+ string text = String.Format(message, args);
+ Log.WriteStart("{0} {1}", LogPrefix, text);
+ }
+
+ public static void LogEnd(string message, params object[] args)
+ {
+ string text = String.Format(message, args);
+ Log.WriteEnd("{0} {1}", LogPrefix, text);
+ }
+
+ public static void LogInfo(string message)
+ {
+ Log.WriteInfo("{0} {1}", LogPrefix, message);
+ }
+
+ public static void LogInfo(string message, params object[] args)
+ {
+ string text = String.Format(message, args);
+ Log.WriteInfo("{0} {1}", LogPrefix, text);
+ }
+
+ public static void LogWarning(string message)
+ {
+ Log.WriteWarning("{0} {1}", LogPrefix, message);
+ }
+
+ public static void LogWarning(string message, params object[] args)
+ {
+ string text = String.Format(message, args);
+ Log.WriteWarning("{0} {1}", LogPrefix, text);
+ }
+
+ public static void LogError(Exception ex)
+ {
+ Log.WriteError(LogPrefix, ex);
+ }
+
+ public static void LogError(string message, Exception ex)
+ {
+ string text = String.Format("{0} {1}", LogPrefix, message);
+ Log.WriteError(text, ex);
+ }
+
+ public static void DebugInfo(string message, params object[] args)
+ {
+ string text = String.Format(message, args);
+ Log.WriteInfo("{0} {1}", LogPrefix, text);
+ }
+
+ public static void EndLog(string message, ResultObject res, string errorCode, Exception ex)
+ {
+ if (res != null)
+ {
+ res.IsSuccess = false;
+
+ if (!string.IsNullOrEmpty(errorCode))
+ res.ErrorCodes.Add(errorCode);
+ }
+
+ if (ex != null)
+ LogError(ex);
+
+
+ //LogRecord.
+ LogEnd(message);
+
+
+ }
+
+ public static void EndLog(string message, ResultObject res, string errorCode)
+ {
+ EndLog(message, res, errorCode, null);
+ }
+
+ public static void EndLog(string message, ResultObject res)
+ {
+ EndLog(message, res, null);
+ }
+
+ public static void EndLog(string message)
+ {
+ EndLog(message, null);
+ }
+
+ internal static T StartLog(string message) where T : ResultObject, new()
+ {
+ LogStart(message);
+ T res = new T();
+ res.IsSuccess = true;
+ return res;
+ }
+
+ public static void DebugCommand(Command cmd)
+ {
+ StringBuilder sb = new StringBuilder(cmd.CommandText);
+ foreach (CommandParameter parameter in cmd.Parameters)
+ {
+ string formatString = " -{0} {1}";
+ if (parameter.Value is string)
+ formatString = " -{0} '{1}'";
+ else if (parameter.Value is bool)
+ formatString = " -{0} ${1}";
+ sb.AppendFormat(formatString, parameter.Name, parameter.Value);
+ }
+ Log.WriteInfo("{0} {1}", LogPrefix, sb.ToString());
+ }
+
+
+ }
+}
diff --git a/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution.Crm2013/MyOrganizationCrmSdkTypes.cs b/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution.Crm2013/MyOrganizationCrmSdkTypes.cs
new file mode 100644
index 00000000..01cbdb17
--- /dev/null
+++ b/WebsitePanel/Sources/WebsitePanel.Providers.HostedSolution.Crm2013/MyOrganizationCrmSdkTypes.cs
@@ -0,0 +1,185223 @@
+//------------------------------------------------------------------------------
+//
+// This code was generated by a tool.
+// Runtime Version:4.0.30319.34003
+//
+// Changes to this file may cause incorrect behavior and will be lost if
+// the code is regenerated.
+//
+//------------------------------------------------------------------------------
+
+[assembly: Microsoft.Xrm.Sdk.Client.ProxyTypesAssemblyAttribute()]
+
+
+
+[System.Runtime.Serialization.DataContractAttribute()]
+[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "6.0.0001.0059")]
+public enum AccountState
+{
+
+ [System.Runtime.Serialization.EnumMemberAttribute()]
+ Active = 0,
+
+ [System.Runtime.Serialization.EnumMemberAttribute()]
+ Inactive = 1,
+}
+
+///
+/// Business that represents a customer or potential customer. The company that is billed in business transactions.
+///
+[System.Runtime.Serialization.DataContractAttribute()]
+[Microsoft.Xrm.Sdk.Client.EntityLogicalNameAttribute("account")]
+[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "6.0.0001.0059")]
+public partial class Account : Microsoft.Xrm.Sdk.Entity, System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged
+{
+
+ ///
+ /// Default Constructor.
+ ///
+ public Account() :
+ base(EntityLogicalName)
+ {
+ }
+
+ public const string EntityLogicalName = "account";
+
+ public const int EntityTypeCode = 1;
+
+ public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
+
+ public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;
+
+ private void OnPropertyChanged(string propertyName)
+ {
+ if ((this.PropertyChanged != null))
+ {
+ this.PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
+ }
+ }
+
+ private void OnPropertyChanging(string propertyName)
+ {
+ if ((this.PropertyChanging != null))
+ {
+ this.PropertyChanging(this, new System.ComponentModel.PropertyChangingEventArgs(propertyName));
+ }
+ }
+
+ ///
+ /// Select a category to indicate whether the customer account is standard or preferred.
+ ///
+ [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("accountcategorycode")]
+ public Microsoft.Xrm.Sdk.OptionSetValue AccountCategoryCode
+ {
+ get
+ {
+ return this.GetAttributeValue("accountcategorycode");
+ }
+ set
+ {
+ this.OnPropertyChanging("AccountCategoryCode");
+ this.SetAttributeValue("accountcategorycode", value);
+ this.OnPropertyChanged("AccountCategoryCode");
+ }
+ }
+
+ ///
+ /// Select a classification code to indicate the potential value of the customer account based on the projected return on investment, cooperation level, sales cycle length or other criteria.
+ ///
+ [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("accountclassificationcode")]
+ public Microsoft.Xrm.Sdk.OptionSetValue AccountClassificationCode
+ {
+ get
+ {
+ return this.GetAttributeValue("accountclassificationcode");
+ }
+ set
+ {
+ this.OnPropertyChanging("AccountClassificationCode");
+ this.SetAttributeValue("accountclassificationcode", value);
+ this.OnPropertyChanged("AccountClassificationCode");
+ }
+ }
+
+ ///
+ /// Unique identifier of the account.
+ ///
+ [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("accountid")]
+ public System.Nullable AccountId
+ {
+ get
+ {
+ return this.GetAttributeValue>("accountid");
+ }
+ set
+ {
+ this.OnPropertyChanging("AccountId");
+ this.SetAttributeValue("accountid", value);
+ if (value.HasValue)
+ {
+ base.Id = value.Value;
+ }
+ else
+ {
+ base.Id = System.Guid.Empty;
+ }
+ this.OnPropertyChanged("AccountId");
+ }
+ }
+
+ [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("accountid")]
+ public override System.Guid Id
+ {
+ get
+ {
+ return base.Id;
+ }
+ set
+ {
+ this.AccountId = value;
+ }
+ }
+
+ ///
+ /// Type an ID number or code for the account to quickly search and identify the account in system views.
+ ///
+ [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("accountnumber")]
+ public string AccountNumber
+ {
+ get
+ {
+ return this.GetAttributeValue("accountnumber");
+ }
+ set
+ {
+ this.OnPropertyChanging("AccountNumber");
+ this.SetAttributeValue("accountnumber", value);
+ this.OnPropertyChanged("AccountNumber");
+ }
+ }
+
+ ///
+ /// Select a rating to indicate the value of the customer account.
+ ///
+ [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("accountratingcode")]
+ public Microsoft.Xrm.Sdk.OptionSetValue AccountRatingCode
+ {
+ get
+ {
+ return this.GetAttributeValue("accountratingcode");
+ }
+ set
+ {
+ this.OnPropertyChanging("AccountRatingCode");
+ this.SetAttributeValue("accountratingcode", value);
+ this.OnPropertyChanged("AccountRatingCode");
+ }
+ }
+
+ ///
+ /// Unique identifier for address 1.
+ ///
+ [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("address1_addressid")]
+ public System.Nullable Address1_AddressId
+ {
+ get
+ {
+ return this.GetAttributeValue>("address1_addressid");
+ }
+ set
+ {
+ this.OnPropertyChanging("Address1_AddressId");
+ this.SetAttributeValue("address1_addressid", value);
+ this.OnPropertyChanged("Address1_AddressId");
+ }
+ }
+
+ ///
+ /// Select the primary address type.
+ ///
+ [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("address1_addresstypecode")]
+ public Microsoft.Xrm.Sdk.OptionSetValue Address1_AddressTypeCode
+ {
+ get
+ {
+ return this.GetAttributeValue("address1_addresstypecode");
+ }
+ set
+ {
+ this.OnPropertyChanging("Address1_AddressTypeCode");
+ this.SetAttributeValue("address1_addresstypecode", value);
+ this.OnPropertyChanged("Address1_AddressTypeCode");
+ }
+ }
+
+ ///
+ /// Type the city for the primary address.
+ ///
+ [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("address1_city")]
+ public string Address1_City
+ {
+ get
+ {
+ return this.GetAttributeValue("address1_city");
+ }
+ set
+ {
+ this.OnPropertyChanging("Address1_City");
+ this.SetAttributeValue("address1_city", value);
+ this.OnPropertyChanged("Address1_City");
+ }
+ }
+
+ ///
+ /// Shows the complete primary address.
+ ///
+ [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("address1_composite")]
+ public string Address1_Composite
+ {
+ get
+ {
+ return this.GetAttributeValue("address1_composite");
+ }
+ }
+
+ ///
+ /// Type the country or region for the primary address.
+ ///
+ [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("address1_country")]
+ public string Address1_Country
+ {
+ get
+ {
+ return this.GetAttributeValue("address1_country");
+ }
+ set
+ {
+ this.OnPropertyChanging("Address1_Country");
+ this.SetAttributeValue("address1_country", value);
+ this.OnPropertyChanged("Address1_Country");
+ }
+ }
+
+ ///
+ /// Type the county for the primary address.
+ ///
+ [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("address1_county")]
+ public string Address1_County
+ {
+ get
+ {
+ return this.GetAttributeValue("address1_county");
+ }
+ set
+ {
+ this.OnPropertyChanging("Address1_County");
+ this.SetAttributeValue("address1_county", value);
+ this.OnPropertyChanged("Address1_County");
+ }
+ }
+
+ ///
+ /// Type the fax number associated with the primary address.
+ ///
+ [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("address1_fax")]
+ public string Address1_Fax
+ {
+ get
+ {
+ return this.GetAttributeValue("address1_fax");
+ }
+ set
+ {
+ this.OnPropertyChanging("Address1_Fax");
+ this.SetAttributeValue("address1_fax", value);
+ this.OnPropertyChanged("Address1_Fax");
+ }
+ }
+
+ ///
+ /// Select the freight terms for the primary address to make sure shipping orders are processed correctly.
+ ///
+ [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("address1_freighttermscode")]
+ public Microsoft.Xrm.Sdk.OptionSetValue Address1_FreightTermsCode
+ {
+ get
+ {
+ return this.GetAttributeValue("address1_freighttermscode");
+ }
+ set
+ {
+ this.OnPropertyChanging("Address1_FreightTermsCode");
+ this.SetAttributeValue("address1_freighttermscode", value);
+ this.OnPropertyChanged("Address1_FreightTermsCode");
+ }
+ }
+
+ ///
+ /// Type the latitude value for the primary address for use in mapping and other applications.
+ ///
+ [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("address1_latitude")]
+ public System.Nullable Address1_Latitude
+ {
+ get
+ {
+ return this.GetAttributeValue>("address1_latitude");
+ }
+ set
+ {
+ this.OnPropertyChanging("Address1_Latitude");
+ this.SetAttributeValue("address1_latitude", value);
+ this.OnPropertyChanged("Address1_Latitude");
+ }
+ }
+
+ ///
+ /// Type the first line of the primary address.
+ ///
+ [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("address1_line1")]
+ public string Address1_Line1
+ {
+ get
+ {
+ return this.GetAttributeValue("address1_line1");
+ }
+ set
+ {
+ this.OnPropertyChanging("Address1_Line1");
+ this.SetAttributeValue("address1_line1", value);
+ this.OnPropertyChanged("Address1_Line1");
+ }
+ }
+
+ ///
+ /// Type the second line of the primary address.
+ ///
+ [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("address1_line2")]
+ public string Address1_Line2
+ {
+ get
+ {
+ return this.GetAttributeValue("address1_line2");
+ }
+ set
+ {
+ this.OnPropertyChanging("Address1_Line2");
+ this.SetAttributeValue("address1_line2", value);
+ this.OnPropertyChanged("Address1_Line2");
+ }
+ }
+
+ ///
+ /// Type the third line of the primary address.
+ ///
+ [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("address1_line3")]
+ public string Address1_Line3
+ {
+ get
+ {
+ return this.GetAttributeValue("address1_line3");
+ }
+ set
+ {
+ this.OnPropertyChanging("Address1_Line3");
+ this.SetAttributeValue("address1_line3", value);
+ this.OnPropertyChanged("Address1_Line3");
+ }
+ }
+
+ ///
+ /// Type the longitude value for the primary address for use in mapping and other applications.
+ ///
+ [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("address1_longitude")]
+ public System.Nullable Address1_Longitude
+ {
+ get
+ {
+ return this.GetAttributeValue>("address1_longitude");
+ }
+ set
+ {
+ this.OnPropertyChanging("Address1_Longitude");
+ this.SetAttributeValue("address1_longitude", value);
+ this.OnPropertyChanged("Address1_Longitude");
+ }
+ }
+
+ ///
+ /// Type a descriptive name for the primary address, such as Corporate Headquarters.
+ ///
+ [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("address1_name")]
+ public string Address1_Name
+ {
+ get
+ {
+ return this.GetAttributeValue("address1_name");
+ }
+ set
+ {
+ this.OnPropertyChanging("Address1_Name");
+ this.SetAttributeValue("address1_name", value);
+ this.OnPropertyChanged("Address1_Name");
+ }
+ }
+
+ ///
+ /// Type the ZIP Code or postal code for the primary address.
+ ///
+ [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("address1_postalcode")]
+ public string Address1_PostalCode
+ {
+ get
+ {
+ return this.GetAttributeValue("address1_postalcode");
+ }
+ set
+ {
+ this.OnPropertyChanging("Address1_PostalCode");
+ this.SetAttributeValue("address1_postalcode", value);
+ this.OnPropertyChanged("Address1_PostalCode");
+ }
+ }
+
+ ///
+ /// Type the post office box number of the primary address.
+ ///
+ [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("address1_postofficebox")]
+ public string Address1_PostOfficeBox
+ {
+ get
+ {
+ return this.GetAttributeValue("address1_postofficebox");
+ }
+ set
+ {
+ this.OnPropertyChanging("Address1_PostOfficeBox");
+ this.SetAttributeValue("address1_postofficebox", value);
+ this.OnPropertyChanged("Address1_PostOfficeBox");
+ }
+ }
+
+ ///
+ /// Type the name of the main contact at the account's primary address.
+ ///
+ [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("address1_primarycontactname")]
+ public string Address1_PrimaryContactName
+ {
+ get
+ {
+ return this.GetAttributeValue("address1_primarycontactname");
+ }
+ set
+ {
+ this.OnPropertyChanging("Address1_PrimaryContactName");
+ this.SetAttributeValue("address1_primarycontactname", value);
+ this.OnPropertyChanged("Address1_PrimaryContactName");
+ }
+ }
+
+ ///
+ /// Select a shipping method for deliveries sent to this address.
+ ///
+ [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("address1_shippingmethodcode")]
+ public Microsoft.Xrm.Sdk.OptionSetValue Address1_ShippingMethodCode
+ {
+ get
+ {
+ return this.GetAttributeValue("address1_shippingmethodcode");
+ }
+ set
+ {
+ this.OnPropertyChanging("Address1_ShippingMethodCode");
+ this.SetAttributeValue("address1_shippingmethodcode", value);
+ this.OnPropertyChanged("Address1_ShippingMethodCode");
+ }
+ }
+
+ ///
+ /// Type the state or province of the primary address.
+ ///
+ [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("address1_stateorprovince")]
+ public string Address1_StateOrProvince
+ {
+ get
+ {
+ return this.GetAttributeValue("address1_stateorprovince");
+ }
+ set
+ {
+ this.OnPropertyChanging("Address1_StateOrProvince");
+ this.SetAttributeValue("address1_stateorprovince", value);
+ this.OnPropertyChanged("Address1_StateOrProvince");
+ }
+ }
+
+ ///
+ /// Type the main phone number associated with the primary address.
+ ///
+ [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("address1_telephone1")]
+ public string Address1_Telephone1
+ {
+ get
+ {
+ return this.GetAttributeValue("address1_telephone1");
+ }
+ set
+ {
+ this.OnPropertyChanging("Address1_Telephone1");
+ this.SetAttributeValue("address1_telephone1", value);
+ this.OnPropertyChanged("Address1_Telephone1");
+ }
+ }
+
+ ///
+ /// Type a second phone number associated with the primary address.
+ ///
+ [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("address1_telephone2")]
+ public string Address1_Telephone2
+ {
+ get
+ {
+ return this.GetAttributeValue("address1_telephone2");
+ }
+ set
+ {
+ this.OnPropertyChanging("Address1_Telephone2");
+ this.SetAttributeValue("address1_telephone2", value);
+ this.OnPropertyChanged("Address1_Telephone2");
+ }
+ }
+
+ ///
+ /// Type a third phone number associated with the primary address.
+ ///
+ [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("address1_telephone3")]
+ public string Address1_Telephone3
+ {
+ get
+ {
+ return this.GetAttributeValue("address1_telephone3");
+ }
+ set
+ {
+ this.OnPropertyChanging("Address1_Telephone3");
+ this.SetAttributeValue("address1_telephone3", value);
+ this.OnPropertyChanged("Address1_Telephone3");
+ }
+ }
+
+ ///
+ /// Type the UPS zone of the primary address to make sure shipping charges are calculated correctly and deliveries are made promptly, if shipped by UPS.
+ ///
+ [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("address1_upszone")]
+ public string Address1_UPSZone
+ {
+ get
+ {
+ return this.GetAttributeValue("address1_upszone");
+ }
+ set
+ {
+ this.OnPropertyChanging("Address1_UPSZone");
+ this.SetAttributeValue("address1_upszone", value);
+ this.OnPropertyChanged("Address1_UPSZone");
+ }
+ }
+
+ ///
+ /// Select the time zone, or UTC offset, for this address so that other people can reference it when they contact someone at this address.
+ ///
+ [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("address1_utcoffset")]
+ public System.Nullable Address1_UTCOffset
+ {
+ get
+ {
+ return this.GetAttributeValue>("address1_utcoffset");
+ }
+ set
+ {
+ this.OnPropertyChanging("Address1_UTCOffset");
+ this.SetAttributeValue("address1_utcoffset", value);
+ this.OnPropertyChanged("Address1_UTCOffset");
+ }
+ }
+
+ ///
+ /// Unique identifier for address 2.
+ ///
+ [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("address2_addressid")]
+ public System.Nullable Address2_AddressId
+ {
+ get
+ {
+ return this.GetAttributeValue>("address2_addressid");
+ }
+ set
+ {
+ this.OnPropertyChanging("Address2_AddressId");
+ this.SetAttributeValue("address2_addressid", value);
+ this.OnPropertyChanged("Address2_AddressId");
+ }
+ }
+
+ ///
+ /// Select the secondary address type.
+ ///
+ [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("address2_addresstypecode")]
+ public Microsoft.Xrm.Sdk.OptionSetValue Address2_AddressTypeCode
+ {
+ get
+ {
+ return this.GetAttributeValue("address2_addresstypecode");
+ }
+ set
+ {
+ this.OnPropertyChanging("Address2_AddressTypeCode");
+ this.SetAttributeValue("address2_addresstypecode", value);
+ this.OnPropertyChanged("Address2_AddressTypeCode");
+ }
+ }
+
+ ///
+ /// Type the city for the secondary address.
+ ///
+ [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("address2_city")]
+ public string Address2_City
+ {
+ get
+ {
+ return this.GetAttributeValue("address2_city");
+ }
+ set
+ {
+ this.OnPropertyChanging("Address2_City");
+ this.SetAttributeValue("address2_city", value);
+ this.OnPropertyChanged("Address2_City");
+ }
+ }
+
+ ///
+ /// Shows the complete secondary address.
+ ///
+ [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("address2_composite")]
+ public string Address2_Composite
+ {
+ get
+ {
+ return this.GetAttributeValue("address2_composite");
+ }
+ }
+
+ ///
+ /// Type the country or region for the secondary address.
+ ///
+ [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("address2_country")]
+ public string Address2_Country
+ {
+ get
+ {
+ return this.GetAttributeValue("address2_country");
+ }
+ set
+ {
+ this.OnPropertyChanging("Address2_Country");
+ this.SetAttributeValue("address2_country", value);
+ this.OnPropertyChanged("Address2_Country");
+ }
+ }
+
+ ///
+ /// Type the county for the secondary address.
+ ///
+ [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("address2_county")]
+ public string Address2_County
+ {
+ get
+ {
+ return this.GetAttributeValue("address2_county");
+ }
+ set
+ {
+ this.OnPropertyChanging("Address2_County");
+ this.SetAttributeValue("address2_county", value);
+ this.OnPropertyChanged("Address2_County");
+ }
+ }
+
+ ///
+ /// Type the fax number associated with the secondary address.
+ ///
+ [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("address2_fax")]
+ public string Address2_Fax
+ {
+ get
+ {
+ return this.GetAttributeValue("address2_fax");
+ }
+ set
+ {
+ this.OnPropertyChanging("Address2_Fax");
+ this.SetAttributeValue("address2_fax", value);
+ this.OnPropertyChanged("Address2_Fax");
+ }
+ }
+
+ ///