Advertisement
Guest User

?

a guest
May 9th, 2016
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 6.40 KB | None | 0 0
  1. using System;
  2. using System.Linq;
  3. using System.Net;
  4. using System.ServiceModel.Description;
  5. using Microsoft.Xrm.Sdk;
  6. using Microsoft.Xrm.Sdk.Client;
  7. using Microsoft.Xrm.Sdk.Discovery;
  8.  
  9. namespace AGP.DataLayer.Xrm.Services
  10. {
  11.     public class CrmConnectionService
  12.     {
  13.         private readonly CrmCredentials _credentials;
  14.  
  15.         public CrmConnectionService(CrmCredentials credentials)
  16.         {
  17.             _credentials = credentials;
  18.         }
  19.  
  20.  
  21.         public OrganizationServiceProxy GetOrganizationServiceProxy()
  22.         {
  23.             var serviceManagement =
  24.                         ServiceConfigurationFactory.CreateManagement<IDiscoveryService>(
  25.                         new Uri(_credentials.DiscoveryServiceAddress));
  26.             var endpointType = serviceManagement.AuthenticationType;
  27.  
  28.             // Set the credentials.
  29.             var authCredentials = GetCredentials(serviceManagement, endpointType);
  30.  
  31.  
  32.             var organizationUri = string.Empty;
  33.             // Get the discovery service proxy.
  34.             using (var discoveryProxy =
  35.                 GetProxy<IDiscoveryService, DiscoveryServiceProxy>(serviceManagement, authCredentials))
  36.             {
  37.                 // Obtain organization information from the Discovery service.
  38.                 if (discoveryProxy != null)
  39.                 {
  40.                     // Obtain information about the organizations that the system user belongs to.
  41.                     var orgs = DiscoverOrganizations(discoveryProxy);
  42.                     // Obtains the Web address (Uri) of the target organization.
  43.                     organizationUri = FindOrganization(_credentials.OrganizationUniqueName,
  44.                         orgs.ToArray()).Endpoints[EndpointType.OrganizationService];
  45.  
  46.                 }
  47.             }
  48.  
  49.             var orgServiceManagement =
  50.                 ServiceConfigurationFactory.CreateManagement<IOrganizationService>(
  51.                 new Uri(organizationUri));
  52.  
  53.             // Set the credentials.
  54.             var credentials = GetCredentials(orgServiceManagement, endpointType);
  55.  
  56.             // Get the organization service proxy.
  57.             var organizationProxy =
  58.                 GetProxy<IOrganizationService, OrganizationServiceProxy>(orgServiceManagement, credentials);
  59.  
  60.             // This statement is required to enable early-bound type support.
  61.             organizationProxy.EnableProxyTypes();
  62.            
  63.             return organizationProxy;
  64.         }
  65.  
  66.         private AuthenticationCredentials GetCredentials<TService>(IServiceManagement<TService> service, AuthenticationProviderType endpointType)
  67.         {
  68.             var authCredentials = new AuthenticationCredentials();
  69.  
  70.             switch (endpointType)
  71.             {
  72.                 case AuthenticationProviderType.ActiveDirectory:
  73.                     authCredentials.ClientCredentials.Windows.ClientCredential =
  74.                         new NetworkCredential(_credentials.Username,
  75.                             _credentials.Password,
  76.                             _credentials.Domain);
  77.                     break;
  78.  
  79.                 default: // For Federated and OnlineFederated environments.                    
  80.                     authCredentials.ClientCredentials.UserName.UserName = _credentials.Username;
  81.                     authCredentials.ClientCredentials.UserName.Password = _credentials.Password;
  82.                     break;
  83.             }
  84.  
  85.             return authCredentials;
  86.         }
  87.         public OrganizationDetailCollection DiscoverOrganizations(
  88.             IDiscoveryService service)
  89.         {
  90.             if (service == null) throw new ArgumentNullException(nameof(service));
  91.             var orgRequest = new RetrieveOrganizationsRequest();
  92.             var orgResponse =
  93.                 (RetrieveOrganizationsResponse)service.Execute(orgRequest);
  94.  
  95.             return orgResponse.Details;
  96.         }
  97.  
  98.         /// <summary>
  99.         /// Finds a specific organization detail in the array of organization details
  100.         /// returned from the Discovery service.
  101.         /// </summary>
  102.         /// <param name="orgUniqueName">The unique name of the organization to find.</param>
  103.         /// <param name="orgDetails">Array of organization detail object returned from the discovery service.</param>
  104.         /// <returns>Organization details or null if the organization was not found.</returns>
  105.         /// <seealso>
  106.         ///     <cref>DiscoveryOrganizations</cref>
  107.         /// </seealso>
  108.         public OrganizationDetail FindOrganization(string orgUniqueName,
  109.             OrganizationDetail[] orgDetails)
  110.         {
  111.             if (string.IsNullOrWhiteSpace(orgUniqueName))
  112.                 throw new ArgumentNullException(nameof(orgUniqueName));
  113.             if (orgDetails == null)
  114.                 throw new ArgumentNullException(nameof(orgDetails));
  115.  
  116.             return orgDetails.FirstOrDefault(detail => string.Compare(detail.UniqueName, orgUniqueName, StringComparison.InvariantCultureIgnoreCase) == 0);
  117.         }
  118.  
  119.         private static TProxy GetProxy<TService, TProxy>(
  120.            IServiceManagement<TService> serviceManagement,
  121.            AuthenticationCredentials authCredentials)
  122.            where TService : class
  123.            where TProxy : ServiceProxy<TService>
  124.         {
  125.             var classType = typeof(TProxy);
  126.  
  127.             if (serviceManagement.AuthenticationType == AuthenticationProviderType.ActiveDirectory)
  128.                 // ReSharper disable once PossibleNullReferenceException
  129.                 return (TProxy) classType
  130.                     .GetConstructor(new[] {typeof (IServiceManagement<TService>), typeof (ClientCredentials)})
  131.                     .Invoke(new object[] {serviceManagement, authCredentials.ClientCredentials});
  132.  
  133.             var tokenCredentials =
  134.                 serviceManagement.Authenticate(authCredentials);
  135.             // Obtain discovery/organization service proxy for Federated, LiveId and OnlineFederated environments.
  136.             // Instantiate a new class of type using the 2 parameter constructor of type IServiceManagement and SecurityTokenResponse.
  137.             // ReSharper disable once PossibleNullReferenceException
  138.             return (TProxy)classType
  139.                 .GetConstructor(new[] { typeof(IServiceManagement<TService>), typeof(SecurityTokenResponse) })
  140.                 .Invoke(new object[] { serviceManagement, tokenCredentials.SecurityTokenResponse });
  141.            
  142.         }
  143.     }
  144. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement