time 
设为首页】【收藏本站
当前位置: 主页 > ERP > CRM > 【Microsoft Dynamics CRM 2011教程】46、从外部连接CRM(二)

【Microsoft Dynamics CRM 2011教程】46、从外部连接CRM(二)

时间:2013-03-01 00:03 点击:4514次 字体:[ ]




 我在以前的文章中介绍过如何使用OrganizationService类来连接CRM的Web Service,在本文中我将介绍如何使用OrganizationServiceProxy类来连接CRM的Web Service。

 

Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy类与 Microsoft.Xrm.Client.Services.OrganizationService类的区别在于,前者既然叫做Proxy,通常是在CRM的Context之外使用,而后者是在CRM的Context中使用的。另外一个区别是如果你想impersonate为其他人的话,就只能使用OrganizationServiceProxy(CallerId )。

 

我在本文中创建一个console程序,通过OrganizationServiceProxy来使用CRM的Web Service,并通过设置OrganizationServiceProxy的CallerId 来代表别人创建一个 lead。顺便说一下,想要Impersonate别人的用户必须在CRM中具有Act on Behalf of Aonther User的权限,或者在Active Directory中加入PrivUserGroup。

【Microsoft Dynamics CRM 2011教程】46、从外部连接CRM(二)_www.fengfly.com

  1. using System;  
  2. using Microsoft.Xrm.Sdk.Discovery;  
  3. using Microsoft.Xrm.Sdk.Client;  
  4. using System.Configuration;  
  5. using Microsoft.Xrm.Sdk;  
  6. using Microsoft.Crm.Sdk.Messages; 
  7.  
  8. namespace ConsoleApplication3  
  9. {  
  10.     class Program  
  11.     {  
  12.         static void Main(string[] args)  
  13.         {  
  14.             string _discoveryServiceAddress = ConfigurationManager.AppSettings["DiscoveryServiceAddress"];  
  15.             IServiceManagement<IDiscoveryService> serviceManagement = ServiceConfigurationFactory.CreateManagement<IDiscoveryService>(new Uri(_discoveryServiceAddress));  
  16.             AuthenticationProviderType endpointType = serviceManagement.AuthenticationType; 
  17.  
  18.             AuthenticationCredentials authCredentials = GetCredentials(endpointType); 
  19.  
  20.             //String organizationUri = String.Empty;  
  21.             //string organizationUniqueName = ConfigurationManager.AppSettings["OrganizationUniqueName"];  
  22.             //// Get the discovery service proxy.  
  23.             //using (DiscoveryServiceProxy discoveryProxy = GetProxy<IDiscoveryService, DiscoveryServiceProxy>(serviceManagement, authCredentials))  
  24.             //{  
  25.             //    // Obtain organization information from the Discovery service.  
  26.             //    if (discoveryProxy != null)  
  27.             //    {  
  28.             //        // Obtain information about the organizations that the system user belongs to.  
  29.             //        OrganizationDetailCollection orgs = DiscoverOrganizations(discoveryProxy);  
  30.             //        // Obtains the Web address (Uri) of the target organization.  
  31.             //        organizationUri = FindOrganization(organizationUniqueName, orgs.ToArray()).Endpoints[EndpointType.OrganizationService];  
  32.             //    }  
  33.             //} 
  34.  
  35.             String organizationUri = ConfigurationManager.AppSettings["OrganizationServiceAddress"];  
  36.             if (!String.IsNullOrWhiteSpace(organizationUri))  
  37.             {  
  38.                 IServiceManagement<IOrganizationService> orgServiceManagement = ServiceConfigurationFactory.CreateManagement<IOrganizationService>(new Uri(organizationUri)); 
  39.  
  40.                 // Set the credentials.  
  41.                 AuthenticationCredentials credentials = GetCredentials(endpointType); 
  42.  
  43.                 // Get the organization service proxy.  
  44.                 using (OrganizationServiceProxy organizationProxy = GetProxy<IOrganizationService, OrganizationServiceProxy>(orgServiceManagement, credentials))  
  45.                 {  
  46.                     // This statement is required to enable early-bound type support.  
  47.                     organizationProxy.EnableProxyTypes();  
  48.                     organizationProxy.CallerId = new Guid("D63C171E-F47C-E211-A79A-00155DA83B36"); 
  49.  
  50.                     // Now make an SDK call with the organization service proxy.  
  51.                     // Display information about the logged on user.  
  52.                     Guid userid = ((WhoAmIResponse)organizationProxy.Execute(new WhoAmIRequest())).UserId;  
  53.                     Entity systemUser = organizationProxy.Retrieve("systemuser", userid, new Microsoft.Xrm.Sdk.Query.ColumnSet(new string[] { "firstname""lastname" })); 
  54.  
  55.                     Entity newEntity = new Entity("lead");  
  56.                      
  57.                     newEntity["salutation"] = "test";  
  58.                     newEntity["middlename"] = "test"; ;  
  59.                     newEntity["lastname"] = "test"; ;  
  60.                     newEntity["jobtitle"] = "test"; ; 
  61.  
  62.                     organizationProxy.Create(newEntity);         
  63.                 }  
  64.             } 
  65.  
  66.         } 
  67.  
  68.         private static AuthenticationCredentials GetCredentials(AuthenticationProviderType endpointType)  
  69.         {  
  70.             string _userName = ConfigurationManager.AppSettings["UserName"];  
  71.             string _password = ConfigurationManager.AppSettings["Password"];  
  72.             string _domain = ConfigurationManager.AppSettings["Domain"]; 
  73.  
  74.             AuthenticationCredentials authCredentials = new AuthenticationCredentials();  
  75.             switch (endpointType)  
  76.             {  
  77.                 case AuthenticationProviderType.ActiveDirectory:  
  78.                     authCredentials.ClientCredentials.Windows.ClientCredential = new System.Net.NetworkCredential(_userName, _password, _domain);  
  79.                     break;  
  80.                 case AuthenticationProviderType.Federation:  
  81.                 case AuthenticationProviderType.OnlineFederation:  
  82.                     authCredentials.ClientCredentials.UserName.UserName = _userName;  
  83.                     authCredentials.ClientCredentials.UserName.Password = _password;  
  84.                     break;  
  85.                 default:                      
  86.                     break;  
  87.             } 
  88.  
  89.             return authCredentials;  
  90.         } 
  91.  
  92.         private static TProxy GetProxy<TService, TProxy>(IServiceManagement<TService> serviceManagement, AuthenticationCredentials authCredentials)  
  93.             where TService : class  
  94.             where TProxy : ServiceProxy<TService>  
  95.         {  
  96.             Type classType = typeof(TProxy); 
  97.  
  98.             if (serviceManagement.AuthenticationType != AuthenticationProviderType.ActiveDirectory)  
  99.             {  
  100.                 AuthenticationCredentials tokenCredentials = serviceManagement.Authenticate(authCredentials);  
  101.                 // Obtain discovery/organization service proxy for Federated, LiveId and OnlineFederated environments.  
  102.                 // Instantiate a new class of type using the 2 parameter constructor of type IServiceManagement and SecurityTokenResponse.  
  103.                 return (TProxy)classType  
  104.                     .GetConstructor(new Type[] { typeof(IServiceManagement<TService>), typeof(SecurityTokenResponse) })  
  105.                     .Invoke(new object[] { serviceManagement, tokenCredentials.SecurityTokenResponse });  
  106.             } 
  107.  
  108.             // Obtain discovery/organization service proxy for ActiveDirectory environment.  
  109.             // Instantiate a new class of type using the 2 parameter constructor of type IServiceManagement and ClientCredentials.  
  110.             return (TProxy)classType  
  111.                 .GetConstructor(new Type[] { typeof(IServiceManagement<TService>), typeof(System.ServiceModel.Description.ClientCredentials) })  
  112.                 .Invoke(new object[] { serviceManagement, authCredentials.ClientCredentials });  
  113.         } 
  114.  
  115.         private static OrganizationDetailCollection DiscoverOrganizations(IDiscoveryService service)  
  116.         {  
  117.             if (service == null)  
  118.                 throw new ArgumentNullException("service");  
  119.             RetrieveOrganizationsRequest orgRequest = new RetrieveOrganizationsRequest();  
  120.             RetrieveOrganizationsResponse orgResponse = (RetrieveOrganizationsResponse)service.Execute(orgRequest); 
  121.  
  122.             return orgResponse.Details;  
  123.         } 
  124.  
  125.         private static OrganizationDetail FindOrganization(string orgUniqueName, OrganizationDetail[] orgDetails)  
  126.         {  
  127.             if (String.IsNullOrWhiteSpace(orgUniqueName))  
  128.                 throw new ArgumentNullException("orgUniqueName");  
  129.             if (orgDetails == null)  
  130.                 throw new ArgumentNullException("orgDetails");  
  131.             OrganizationDetail orgDetail = null
  132.  
  133.             foreach (OrganizationDetail detail in orgDetails)  
  134.             {  
  135.                 if (String.Compare(detail.UniqueName, orgUniqueName,  
  136.                     StringComparison.InvariantCultureIgnoreCase) == 0)  
  137.                 {  
  138.                     orgDetail = detail;  
  139.                     break;  
  140.                 }  
  141.             }  
  142.             return orgDetail;  
  143.         }  
  144.     }  



本文地址 : http://www.fengfly.com/plus/view-211915-1.html
标签: CRM Microsoft Dynamics
------分隔线----------------------------
最新评论 查看所有评论
发表评论 查看所有评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
评价:
表情:
验证码: