CRM and Azure Integration

Part 1:
Create sample WCF Service which connect to CRM and deploy in Azure

I will not go into detail that how to create WCF service for CRM. The purpose of this post is to deploy the WCF service Azure and get data from CRM.I created a sample “SampleWCFForAzure” project which will connect to CRM and retrieve contact based on the email id using GET method. Below is actual source code of Service and Contract.

CRMService.cs

using Microsoft.Xrm.Client;
using Microsoft.Xrm.Client.Services;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace SampleWCFForAzure
{
public class CRMService : ICRMService
{
private static IOrganizationService service = Service();
static CRMService()
{
if (service == null) { throw new Exception(“CRM Service not found”); }
}

public List<Contact> GetContact(string email)
{
List<Contact> contactList = new List<Contact>();
contactList = GetContactList(service, email);
return contactList;
}

public static List<Contact> GetContactList(IOrganizationService service, string emailId)
{
List<Contact> contactList = new List<Contact>();
string fetchContact = “<fetch version=’1.0′ output-format=’xml-platform’ mapping=’logical’ distinct=’false’>” +
” <entity name=’contact’>” +
”   <attribute name=’fullname’ />” +
”   <attribute name=’contactid’ />” +
”   <attribute name=’lastname’ />” +
”   <attribute name=’firstname’ />” +
”   <attribute name=’emailaddress1′ />” +
”   <order attribute=’fullname’ descending=’false’ />” +
”   <filter type=’and’>” +
”     <condition attribute=’emailaddress1′ operator=’eq’ value='” + emailId + “‘ />” +
”     <condition attribute=’statecode’ operator=’eq’ value=’0′ />” +
”   </filter>” +
” </entity>” +
“</fetch>”;

var fetchExpression = new FetchExpression(fetchContact);
EntityCollection contactCollection = service.RetrieveMultiple(fetchExpression);
if (contactCollection.Entities.Count > 0)
{
foreach (var record in contactCollection.Entities)
{
Contact contact = new Contact();
contact.ContactId = record.Contains(“contactid”) ? ((Guid)record.Attributes”contactid”]).ToString() : string.Empty;
contact.FirstName = record.Contains(“firstname”) ? record.Attributes[“firstname”].ToString() : string.Empty;
contact.LastName = record.Contains(“lastname”) ? record.Attributes[“lastname”].ToString() : string.Empty;
contact.Email = record.Contains(“emailaddress1”) ? record.Attributes[“emailaddress1”].ToString() : string.Empty;
contactList.Add(contact);
}
}
return contactList;
}

public static IOrganizationService Service()
{
String connectionString = ConfigurationManager.AppSettings[“CRMConnection”];
CrmConnection connection = CrmConnection.Parse(connectionString);
IOrganizationService service = new OrganizationService(connection);
return service;
}
}
}

Contract: ICRMService.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace SampleWCFForAzure
{
[ServiceContract]
public interface ICRMService
{
[OperationContract]
[WebInvoke(Method = “GET”,
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = “/contact?email={email}”)]
List<Contact> GetContact(string email);
}

[DataContract]
public class Contact
{
[DataMember]
public string ContactId { get; set; }
[DataMember]
public string Email { get; set; }
[DataMember]
public string FirstName { get; set; }
[DataMember]
public string LastName { get; set; }
}
}
Web.config

<?xml version=”1.0″?>
<configuration>
<appSettings>
<add key=”CRMConnection” value=”Url=https://xxxxxxxxxxx.crm5.dynamics.com; sername=abc@organizationname.org; Password=XXXXXXXXX;” />
</appSettings>
<system.web>
<compilation debug=”true” targetFramework=”4.5.2″ />
<customErrors mode=”Off” />
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name=”servicebehavior”>
<serviceMetadata httpGetEnabled=”true” />
<serviceDebug includeExceptionDetailInFaults=”false” />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name=”restbehavior”>
<webHttp helpEnabled=”true” />
</behavior>

</endpointBehaviors>
</behaviors>
<bindings>
<webHttpBinding>
<binding name=”TransportSecurity”>
<security mode=”None”>
<transport clientCredentialType=”None” />
</security>
</binding>
</webHttpBinding>
</bindings>
<services>
<service name=”SampleWCFForAzure.CRMService” behaviorConfiguration=”servicebehavior”>
<endpoint name=”RESTEndPoint” contract=”SampleWCFForAzure.ICRMService” binding=”webHttpBinding” bindingConfiguration=”TransportSecurity” address=”” behaviorConfiguration=”restbehavior” />
</service>
</services>
<serviceHostingEnvironment multipleSiteBindingsEnabled=”true” />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests=”true” />
<directoryBrowse enabled=”true” />
</system.webServer>
</configuration>

Now coding part is over, we have to deploy it in azure and for this you must have azure subscription to deploy in Azure or you can subscribe trial version.

Now right click on project and select PUBLISH

Select “Microsoft Azure App Service” and select your subscription like below and click “OK”

Verify your connection and if you multiple site under one site(virtual directory) then mention the correct site path. In my case I have multiple sites under one site.

I will not go into detail that how to create WCF service for CRM. The purpose of this post is to deploy the WCF service Azure and get data from CRM.I created a sample “SampleWCFForAzure” project which will connect to CRM and retrieve contact based on the email id using GET method. Below is actual source code of Service and Contract

Click “Next” and select the Configuration mode as “Release/Debug” as below.

Then Click “Publish” and it should be published successfully and it will open the root site. Verify the web service by browsing the correct URL based on URI in your Data Contract. In my case it is http://<servername>.azurewebsites.net/uat/crm/connect/CRMService.svc

Now we should test the service whether service working or not.
To test the service, I will use PostMan. Just enter the correct URL and “GET” method and then click “Send”.

Next tutorial, I will explain how to Debug GET/POST Restful service hosted on Azure.

Hope it helps.