由于MSCRM的异构性和封闭性,许多其它的平台无法直接调用MSCRM提供的API接口,一般的处理方式是用.net编写webservice,通过中间这一层转换来使其它系统调用我们自己编写的webservice.下面演示如何开发可调用MSCRM2013 API的webservice。
主要步骤:
- 新建asp.net web项目
- 编写代码
- 验证服务
- 生成项目,并将相关文件拷贝到CRM的指定路径
一.新建项目
右键点击资源管理器项目,并添加一个web服务,此处名称为:MSCRMWebServiceDemo
引用相关的DLL文件
二.编写代码
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.ServiceModel.Description;
using System.Web;
using System.Web.Services;
namespace MSCRMWebServiceDemo
{
/// <summary>
/// MyMSCRMWebService 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。
// [System.Web.Script.Services.ScriptService]
public class MyMSCRMWebService : System.Web.Services.WebService
{
static private IOrganizationService GetOrganisationService()
{
ClientCredentials credentials = new ClientCredentials();
credentials.Windows.ClientCredential = new NetworkCredential("crmadmin", "password01!", "test");
OrganizationServiceProxy proxy = new OrganizationServiceProxy(new Uri("http://192.168.10.17/test/XRMServices/2011/Organization.svc"), null, credentials, null);
return proxy as IOrganizationService;
}
[WebMethod]
public string HelloWorld()
{
IOrganizationService service = GetOrganisationService();
//用FETCHXML的方式获取会员数据
string fetch2 = @"
<fetch mapping='logical'>
<entity name='account'>
<attribute name='name' />
<attribute name='address1_city' />
<attribute name='primarycontactid' />
<attribute name='telephone1' />
<attribute name='accountid' />
<order attribute='name' descending='false' />
<link-entity name='contact' from='contactid' to='primarycontactid' visible='false' link-type='outer' alias='accountprimarycontactidcontactcontactid'>
<attribute name='emailaddress1' />
</link-entity>
</entity>
</fetch>";
EntityCollection result = service.RetrieveMultiple(new FetchExpression(fetch2));
String name = "";
foreach (var c in result.Entities)
{
name += c.Attributes["name"];
}
return name;
}
}
}
三.点击VS的运行按钮,测试服务
四.部署相关项目至CRM指定路径
拷贝MSCRMWebServiceDemo.dll至CRM的以下路径:
X:\Program Files\Microsoft Dynamics CRM\CRMWeb\bin
拷贝MyMSCRMWebService.asmx至CRM的以下路径:
C:\Program Files\Microsoft Dynamics CRM\CRMWeb\ISV
最后验证一下webservice,打开如下地址,出现以下界面则部署成功