博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
MS CRM 2011 如何从外部连接CRM
阅读量:7056 次
发布时间:2019-06-28

本文共 9048 字,大约阅读时间需要 30 分钟。

本文要讲解,在CRM应用之外,不具有CRM context的情况下,如何连接到CRM,获得CRM的相关数据。如果你有耐心的话,也可以仔细研究一下SDK中Sample: Simplified Connection Quick Start using Microsoft Dynamics CRM 2011 and Microsoft Dynamics CRM Online。

 

CRM 2011提供了一个Assembly microsoft.xrm.client.dll,如果从客户端连接CRM的话,可以使用该Assembly中的OrganizationService类。我在本文中以一个控制台程序来演示如何连接到CRM 2011。首先程序需要使用到的引用如下图。有关CRM的引用都可以在sdk的bin文件夹中找到。

Program.cs的代码为:

using System;using Microsoft.Xrm.Client.Services;using Microsoft.Xrm.Client;using Microsoft.Crm.Sdk.Messages;using System.ServiceModel;using System.Configuration;using Microsoft.Xrm.Sdk;using Microsoft.Xrm.Sdk.Query;namespace ConsoleApplication3{    public class SimplifiedConnection    {        #region Class Level Members                private OrganizationService _orgService;        #endregion Class Level Members        public void Run(String connectionString, bool promptforDelete)        {            try            {                // Establish a connection to the organization web service using CrmConnection.                Microsoft.Xrm.Client.CrmConnection connection = CrmConnection.Parse(connectionString);                // Obtain an organization service proxy.                // The using statement assures that the service proxy will be properly disposed.                using (_orgService = new OrganizationService(connection))                {                    // Obtain information about the logged on user from the web service.                    Guid userid = ((WhoAmIResponse)_orgService.Execute(new WhoAmIRequest())).UserId;                    Entity systemUser = _orgService.Retrieve("systemuser", userid,                        new ColumnSet(new string[] { "firstname", "lastname" }));                    Console.WriteLine("Logged on user is {0} {1}.",                        systemUser["firstname"].ToString(), systemUser["lastname"].ToString());                                    }            }            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.            catch (FaultException
) { // You can handle an exception here or pass it back to the calling method. throw; } } #region Public Methods #endregion Public Methods #region Private Methods ///
/// Gets web service connection information from the app.config file. /// If there is more than one available, the user is prompted to select /// the desired connection configuration by name. /// ///
A string containing web service connection configuration information.
private static String GetServiceConfiguration() { var connection = ConfigurationManager.ConnectionStrings["CrmConnection"]; return connection.ConnectionString; } #endregion Private Methods #region Main method ///
/// Standard Main() method used by most SDK samples. /// ///
static public void Main(string[] args) { try { // Obtain connection configuration information for the Microsoft Dynamics // CRM organization web service. String connectionString = GetServiceConfiguration(); if (connectionString != null) { SimplifiedConnection app = new SimplifiedConnection(); app.Run(connectionString, true); } } catch (FaultException
ex) { Console.WriteLine("The application terminated with an error."); Console.WriteLine("Timestamp: {0}", ex.Detail.Timestamp); Console.WriteLine("Code: {0}", ex.Detail.ErrorCode); Console.WriteLine("Message: {0}", ex.Detail.Message); Console.WriteLine("Trace: {0}", ex.Detail.TraceText); Console.WriteLine("Inner Fault: {0}", null == ex.Detail.InnerFault ? "Has Inner Fault" : "No Inner Fault"); } catch (System.TimeoutException ex) { Console.WriteLine("The application terminated with an error."); Console.WriteLine("Message: {0}", ex.Message); Console.WriteLine("Stack Trace: {0}", ex.StackTrace); Console.WriteLine("Inner Fault: {0}", null == ex.InnerException.Message ? "Has Inner Fault" : "No Inner Fault"); } catch (System.Exception ex) { Console.WriteLine("The application terminated with an error."); Console.WriteLine(ex.Message); // Display the details of the inner exception. if (ex.InnerException != null) { Console.WriteLine(ex.InnerException.Message); FaultException
fe = ex.InnerException as FaultException
; if (fe != null) { Console.WriteLine("Timestamp: {0}", fe.Detail.Timestamp); Console.WriteLine("Code: {0}", fe.Detail.ErrorCode); Console.WriteLine("Message: {0}", fe.Detail.Message); Console.WriteLine("Trace: {0}", fe.Detail.TraceText); Console.WriteLine("Inner Fault: {0}", null == fe.Detail.InnerFault ? "Has Inner Fault" : "No Inner Fault"); } } } // Additional exceptions to catch: SecurityTokenValidationException, ExpiredSecurityTokenException, // SecurityAccessDeniedException, MessageSecurityException, and SecurityNegotiationException. finally { Console.WriteLine("Press
to exit."); Console.ReadLine(); } } #endregion Main method }}

上面的程序需要从配置文件读取ConnectionString。一个范例app.config文件如下所示。

这段代码完成的事情很简单,就是使用OrganizationService类来执行一个WhoAmIRequest。如果成功就表示控制台成功连接到了CRM。配置文件中一共有5个connection string 的样例。分别用来连接:

(1) 使用Office 365 ID 的 CRM Online;

(2) 使用Windows Live ID的 CRM Online;

(3) CRM On-Premises;

(4)CRM On-Premises,使用当前Windows integrated security来登录,所以不需要提供用户密码;

(5) 使用了IFD的CRM On-Premises。

上面除了(1)我没有进行测试,其他四种CRM都通过了该段代码的测试。在Connection String中,对于CRM Online和IFD On-Premises,URL需要使用Organization Service 的 URL。要查看CRM的Organization Service的URL,可以在Settings –> Customization –> Customizations –> Developer Resources中查看

连接CRM Online的时候,需要DeviceID和DevicePassword。很多人不懂DeviceID是干什么用的。DeviceID的目的就是注册一个设备,使这个设备可以使用Windows Live ID。当你注册了这个设备后,任何用户就都可以使用这个设备了。所以如果这个是一个从未注册过的设备,你首先要注册它。关于如何注册一个设备,可以使用sdk带的deviceregistration工具。具体的命令是DeviceRegistration.exe /operation:Register。命令运行成功后,你就可以拷贝生成的Device ID和Device Password了。

最后再说一下,因为在配置文件中,我们保存了用户登录信息,这样很容易泄露用户名和密码,所以我再说一下如何对配置文件的Connection string进行加密。对配置文件加密可以使用aspnet_regiis.exe工具,Visual Studio自带这个工具。如果没有Visual Studio,.Net中也包含了这个工具。可以在%windows root directory%\Microsoft.NET\%Framework\%version 中找到该工具。首先将app.config另存为文件名为web.config的文件,假如我将该文件保存到我的C:\temp目录中。文件的内容为:

运行命令 aspnet_regiis -pef "connectionStrings" "C:\temp",打开web.config文件,发现加密后的内容为:

 

Rsa Key
ll2Y+mC2QlqQ/xhj4jpTu4IQwYVoXjJ7ZVomJvWTtfo5f1o8N46lEPED5Z8k4RrSoJWlk2CKsmxIW8Y5soBlsckEe8ZAGfAHezynUXI1X3QNXLX7qm6F2A7NPuZxpEjKv1JEWOKpTxwo3MMXZwiKjuw3e/puOqKYsrfqT+wHK1E=
1+ugw1BnAfPhQW3AXtWnjn+KjYFdD4xz56ue8RFjATaNw0HbdyoYm4F+R1zKQP7iqWIebD/gNoYNARFiF7BwHtgOO+7nJsSzkH5i6FgkNaJtvIPUMK7dXF9kCbXEB1MGmnSnjgb8AHhvy68k+Ib1HuWeSvlRDzHuLAOWQ4iM6+Impdcoe27Rs02tRs3a/Jy0NPFhUS+Ps0tTsMJQO5uztcjPbmaNx/jOoxHWaUDWpSx7ucaOK1p/Ko4aN29W1y7iCvvi0wFAOXPi1oega5qSXFnyIADekuPRXxM1vNvKHXBuemxslqtNfazTeY/NxkJ/qRYUbPfdxJRk2MaBZtPOS57nqTWxiRGQJtsUliw4Y0x8sfj/wO0/aDD7T/zFVOj9Ayk15bTNQ2Kpu8qM+DpiUkg/I6l0HDDYz1BZlgItGEjykDjgE6QrB6Woq+svAukEt7bbCitdPPSbliE7d1lxw6VktjQ9/3A1

然后你可以将该内容拷贝到你的app.config文件中去。

 

解密的命令为aspnet_regiis -pef "connectionStrings" "C:\temp"。当然解密与加密必须是在同一电脑上进行的,如果某个恶意用户获取了你加密后的app.config文件,在他自己的电脑上运行该命令是无法解密该文件的。

 

总结:从CRM外部连接CRM,可以使用上面的CRM“万能”连接程序,基本上各种deployment方式的CRM,都可以使用它来连接。该程序使用了Assembly microsoft.xrm.client.dll中的OrganizationService类。你需要在app.config或web.config中配置connection string。最后基于安全性,要对配置文件的connectionStrings section进行加密。加密可以使用aspnet_regiis 工具。

本文转自JF Zhu博客园博客,原文链接:  http://www.cnblogs.com/jfzhu/archive/2012/11/02/2752006.html  ,如需转载请自行联系原作者

你可能感兴趣的文章
作者问答:解密硅谷
查看>>
linux系统高并发socket最大连接数优化
查看>>
Netflix发布Polly.JS,一个用于HTTP交互的开源库
查看>>
敏捷团队中测试人员的角色
查看>>
GitHub推出Scientist,帮助开发者重构关键路径代码
查看>>
40%创业公司用伪AI忽悠钱,欧洲被AI时代抛弃了吗?
查看>>
AT&T签署8位数合同,设备商恐无法从5G获利
查看>>
Netflix Play API:我们为什么构建了一个演进式架构?
查看>>
我不是仆人,是主人!敏捷中领导力的新比喻?
查看>>
Next.js 7.0正式发布:重新编译速度提高42%,支持WebAssembly
查看>>
Java API for RESTful Web Services 2.1发布
查看>>
Visual Studio 2017 15.8第一个预览版发布,支持ARM64
查看>>
Java日志性能那些事
查看>>
Invokedynamic:Java的秘密武器
查看>>
Raffi Krikorian 为“在运行中进行架构重写”提供了指南
查看>>
Plaid.com的监控系统如何实现与9600多家金融机构的集成
查看>>
Laravel学习笔记之PHP反射(Reflection) (上)
查看>>
Build Your Own Promise
查看>>
bootstrap - form
查看>>
业务安全通用解决方案——WAF数据风控
查看>>