Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Linq;
- using System.Net;
- using System.ServiceModel.Description;
- using Microsoft.Xrm.Sdk;
- using Microsoft.Xrm.Sdk.Client;
- using Microsoft.Xrm.Sdk.Discovery;
- namespace AGP.DataLayer.Xrm.Services
- {
- public class CrmConnectionService
- {
- private readonly CrmCredentials _credentials;
- public CrmConnectionService(CrmCredentials credentials)
- {
- _credentials = credentials;
- }
- public OrganizationServiceProxy GetOrganizationServiceProxy()
- {
- var serviceManagement =
- ServiceConfigurationFactory.CreateManagement<IDiscoveryService>(
- new Uri(_credentials.DiscoveryServiceAddress));
- var endpointType = serviceManagement.AuthenticationType;
- // Set the credentials.
- var authCredentials = GetCredentials(serviceManagement, endpointType);
- var organizationUri = string.Empty;
- // Get the discovery service proxy.
- using (var discoveryProxy =
- GetProxy<IDiscoveryService, DiscoveryServiceProxy>(serviceManagement, authCredentials))
- {
- // Obtain organization information from the Discovery service.
- if (discoveryProxy != null)
- {
- // Obtain information about the organizations that the system user belongs to.
- var orgs = DiscoverOrganizations(discoveryProxy);
- // Obtains the Web address (Uri) of the target organization.
- organizationUri = FindOrganization(_credentials.OrganizationUniqueName,
- orgs.ToArray()).Endpoints[EndpointType.OrganizationService];
- }
- }
- var orgServiceManagement =
- ServiceConfigurationFactory.CreateManagement<IOrganizationService>(
- new Uri(organizationUri));
- // Set the credentials.
- var credentials = GetCredentials(orgServiceManagement, endpointType);
- // Get the organization service proxy.
- var organizationProxy =
- GetProxy<IOrganizationService, OrganizationServiceProxy>(orgServiceManagement, credentials);
- // This statement is required to enable early-bound type support.
- organizationProxy.EnableProxyTypes();
- return organizationProxy;
- }
- private AuthenticationCredentials GetCredentials<TService>(IServiceManagement<TService> service, AuthenticationProviderType endpointType)
- {
- var authCredentials = new AuthenticationCredentials();
- switch (endpointType)
- {
- case AuthenticationProviderType.ActiveDirectory:
- authCredentials.ClientCredentials.Windows.ClientCredential =
- new NetworkCredential(_credentials.Username,
- _credentials.Password,
- _credentials.Domain);
- break;
- default: // For Federated and OnlineFederated environments.
- authCredentials.ClientCredentials.UserName.UserName = _credentials.Username;
- authCredentials.ClientCredentials.UserName.Password = _credentials.Password;
- break;
- }
- return authCredentials;
- }
- public OrganizationDetailCollection DiscoverOrganizations(
- IDiscoveryService service)
- {
- if (service == null) throw new ArgumentNullException(nameof(service));
- var orgRequest = new RetrieveOrganizationsRequest();
- var orgResponse =
- (RetrieveOrganizationsResponse)service.Execute(orgRequest);
- return orgResponse.Details;
- }
- /// <summary>
- /// Finds a specific organization detail in the array of organization details
- /// returned from the Discovery service.
- /// </summary>
- /// <param name="orgUniqueName">The unique name of the organization to find.</param>
- /// <param name="orgDetails">Array of organization detail object returned from the discovery service.</param>
- /// <returns>Organization details or null if the organization was not found.</returns>
- /// <seealso>
- /// <cref>DiscoveryOrganizations</cref>
- /// </seealso>
- public OrganizationDetail FindOrganization(string orgUniqueName,
- OrganizationDetail[] orgDetails)
- {
- if (string.IsNullOrWhiteSpace(orgUniqueName))
- throw new ArgumentNullException(nameof(orgUniqueName));
- if (orgDetails == null)
- throw new ArgumentNullException(nameof(orgDetails));
- return orgDetails.FirstOrDefault(detail => string.Compare(detail.UniqueName, orgUniqueName, StringComparison.InvariantCultureIgnoreCase) == 0);
- }
- private static TProxy GetProxy<TService, TProxy>(
- IServiceManagement<TService> serviceManagement,
- AuthenticationCredentials authCredentials)
- where TService : class
- where TProxy : ServiceProxy<TService>
- {
- var classType = typeof(TProxy);
- if (serviceManagement.AuthenticationType == AuthenticationProviderType.ActiveDirectory)
- // ReSharper disable once PossibleNullReferenceException
- return (TProxy) classType
- .GetConstructor(new[] {typeof (IServiceManagement<TService>), typeof (ClientCredentials)})
- .Invoke(new object[] {serviceManagement, authCredentials.ClientCredentials});
- var tokenCredentials =
- serviceManagement.Authenticate(authCredentials);
- // Obtain discovery/organization service proxy for Federated, LiveId and OnlineFederated environments.
- // Instantiate a new class of type using the 2 parameter constructor of type IServiceManagement and SecurityTokenResponse.
- // ReSharper disable once PossibleNullReferenceException
- return (TProxy)classType
- .GetConstructor(new[] { typeof(IServiceManagement<TService>), typeof(SecurityTokenResponse) })
- .Invoke(new object[] { serviceManagement, tokenCredentials.SecurityTokenResponse });
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement