Microsoft Dynamics CRM 2016 SDK & UII Download Links

Download Microsoft Dynamics CRM 2016 SDK and UII from the below links,

Name Size Download Link Description
MicrosoftDynamicsCRM2016SDK.exe 84.5 MB Click Here

 

Microsoft Dynamics CRM Software Development Kit (SDK) for CRM Online and on-premises CRM 2016
MicrosoftDynamicsCRM2016UII.exe 57.4 MB Click Here User Interface Integration (UII) solution framework, which includes a deployment guide, development guide and api reference for Unified Service Desk.

Error: The type or namespace name ‘Xrm’ does not exist in the namespace ‘Microsoft’ using CRM 2015 SDK

Have a look by clicking the below link to resolve this Error,

http://www.syntaxwarriors.com/2015/using-crm-2015-sdk-gives-error-that-xrm-does-not-exist-in-the-namespace/

Create Email using CRM SDK and C#

Follow the below steps to create a simple Email record in Console application,

Step 1: Open Visual Studio and Create Console Application Project.

Step 2: First we have to establish connection to CRM. Please follow my earlier post Connect to CRM Online or On-premise using C# SDK.

Step 3: Generate Early bound class using Crmsvcutil.exe. Please follow my earlier post Generate Early bound Class using CrmSvcUtil.Exe in CRM.

Step 4: Add EarlyBound.cs to the project.

Step 5: Include the namespace using EarlyBound.cs.

Step 6: Below method will create Email record,

Create Email - Parameter Description

public static void SendEmail(Guid From, Guid To, string ToEntitySchemaName, string Subject, string Description)
{
try
{
// Create 'From' activity party for the email

ActivityParty fromParty = new ActivityParty
{
PartyId = new EntityReference(SystemUser.EntityLogicalName, From)
};

// Create 'To' activity party for the email

ActivityParty toParty = new ActivityParty
{
PartyId = new EntityReference(ToEntitySchemaName, To)
};

// Create an e-mail message

Email email = new Email
{
To = new ActivityParty[] { toParty },
From = new ActivityParty[] { fromParty },
Subject = Subject,
Description = Description,
DirectionCode = true
};

Guid _emailId = _service.Create(email);

SendEmailRequest sendEmailreq = new SendEmailRequest
{
EmailId = _emailId,
TrackingToken = "",
IssueSend = true
};

SendEmailResponse sendEmailresp = (SendEmailResponse)_service.Execute(sendEmailreq);

if (sendEmailresp != null)
{
Console.WriteLine("Email record created successfully");
Console.ReadKey();
}
}
catch(Exception ex)
{
Console.Write("Error " + ex.Message);
Console.ReadKey();
}
}

Step 7: Final Code will be like below,

using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Description;
using System.Text;
using System.Threading.Tasks;
using EarlyBound;

namespace LinqToCRM
{
class Program
{
static IOrganizationService _service;
static void Main(string[] args)
{
ConnectToMSCRM("arunpotti@XYZOrg.onmicrosoft.com", "password", "https://XYZOrg.api.crm5.dynamics.com/XRMServices/2011/Organization.svc");

Guid userid = ((WhoAmIResponse)_service.Execute(new WhoAmIRequest())).UserId;

if (userid == Guid.Empty) return;

Contact c = new Contact() //Create Contact Record
{
FirstName = "Arvind Kumar",
LastName = "Shah",
MobilePhone = "9876543210",
EMailAddress1 = "arvindshah@crm2015trial.com"
};

Guid contactGuid = _service.Create(c);

if (contactGuid != Guid.Empty)
{
SendEmail(userid, contactGuid, "contact", "Test Subject", "Test Description");
}
}

public static void ConnectToMSCRM(string UserName, string Password, string SoapOrgServiceUri)
{
try
{
ClientCredentials credentials = new ClientCredentials();
credentials.UserName.UserName = UserName;
credentials.UserName.Password = Password;
Uri serviceUri = new Uri(SoapOrgServiceUri);
OrganizationServiceProxy proxy = new OrganizationServiceProxy(serviceUri, null, credentials, null);
proxy.EnableProxyTypes();
_service = (IOrganizationService)proxy;
}
catch (Exception ex)
{
Console.WriteLine("Error while connecting to CRM " + ex.Message);
Console.ReadKey();
}
}

public static void SendEmail(Guid From, Guid To, string ToEntitySchemaName, string Subject, string Description)
{
try
{
// Create 'From' activity party for the email

ActivityParty fromParty = new ActivityParty
{
PartyId = new EntityReference(SystemUser.EntityLogicalName, From)
};

// Create 'To' activity party for the email

ActivityParty toParty = new ActivityParty
{
PartyId = new EntityReference(ToEntitySchemaName, To)
};

// Create an e-mail message

Email email = new Email
{
To = new ActivityParty[] { toParty },
From = new ActivityParty[] { fromParty },
Subject = Subject,
Description = Description,
DirectionCode = true
};

Guid _emailId = _service.Create(email);

SendEmailRequest sendEmailreq = new SendEmailRequest
{
EmailId = _emailId,
TrackingToken = "",
IssueSend = true
};

SendEmailResponse sendEmailresp = (SendEmailResponse)_service.Execute(sendEmailreq);

if (sendEmailresp != null)
{
Console.WriteLine("Email record created successfully");
Console.ReadKey();
}
}

catch(Exception ex)
{
Console.Write("Error " + ex.Message);
Console.ReadKey();
}
}
}
}

Step 8: Execute the project for the below output, Open CRM and check for the email record

Create Email - Output

Please provide your valuable comments on this article.

Delete Contact record using Early Bound and LINQ in CRM

Task: Delete Contact record where Full Name = “Arun Potti”

Solution: Follow the below steps,

Step 1: Open Visual Studio and Create Console Application Project.

Step 2: First we have to establish connection to CRM. Please follow my earlier post Connect to CRM Online or On-premise using C# SDK.

Step 3: Generate Early bound class using Crmsvcutil.exe. Please follow my earlier post Generate Early bound Class using CrmSvcUtil.Exe in CRM.

Step 4: Add EarlyBound.cs to the project.

Step 5: Include the namespace using EarlyBound.cs.

Step 6: Below method will delete Contact record,

deleteContactRecord("Arun Potti");
public static void deleteContactRecord(string fullname)
       {
           using (var context = new ServiceContext(_service))
           {
               Contact conRecord = context.ContactSet.FirstOrDefault(c => c.FullName == fullName);
               if (conRecord != null)
               {
                   context.DeleteObject(conRecord);
                   if (context.SaveChanges().Count > 0)
                  {
                       Console.WriteLine("Record deleted Successfully");
                       Console.ReadKey();
                   }
               }
           }
       }

Step 7: Final Code will be like below,

using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Description;
using System.Text;
using System.Threading.Tasks;
using EarlyBound;
namespace LinqToCRM
{
class Program
{
static IOrganizationService _service;
static void Main(string[] args)
{
ConnectToMSCRM("arunpotti@MyOrg.onmicrosoft.com", "Password", "https://MyOrg.api.crm5.dynamics.com/XRMServices/2011/Organization.svc");
Guid userid = ((WhoAmIResponse)_service.Execute(new WhoAmIRequest())).UserId;
if (userid == Guid.Empty) return;
deleteContactRecord("Arun Potti");
}
public static void ConnectToMSCRM(string UserName, string Password, string SoapOrgServiceUri)
{
try
{
ClientCredentials credentials = new ClientCredentials();
credentials.UserName.UserName = UserName;
credentials.UserName.Password = Password;
Uri serviceUri = new Uri(SoapOrgServiceUri);
OrganizationServiceProxy proxy = new OrganizationServiceProxy(serviceUri, null, credentials, null);
proxy.EnableProxyTypes();
_service = (IOrganizationService)proxy;
}
catch (Exception ex)
{
Console.WriteLine("Error while connecting to CRM " + ex.Message);
Console.ReadKey();
}
}
public static void deleteContactRecord(string fullName)
{
using (var context = new ServiceContext(_service))
{
Contact conRecord = context.ContactSet.FirstOrDefault(c => c.FullName == fullName);
if (conRecord != null)
{
context.DeleteObject(conRecord);
if (context.SaveChanges().Count > 0)
{
Console.WriteLine("Record deleted Successfully");
Console.ReadKey();
}
}
}
}
}
}

Step 8: Execute the project for the below output,

LinqToCrm Delete Output

Please provide your valuable comments on this article.

Retrieve records using Early Bound and LINQ in CRM

Task: Display all Contact records Full Name from Contact entity where Status = Active and Order by Full Name

Solution: Follow the below steps,

Step 1: Open Visual Studio and Create Console Application Project.

Step 2: First we have to establish connection to CRM. Please follow my earlier post Connect to CRM Online or On-premise using C# SDK.

Step 3: Generate Early bound class using Crmsvcutil.exe. Please follow my earlier post Generate Early bound Class using CrmSvcUtil.Exe in CRM.

Step 4: Add EarlyBound.cs to the project.

Step 5: Include the namespace using EarlyBound.cs.

Step 6: Below code will retrieve records from Contact entity,

public static void retrieveContactRecords()
{
using (var context = new ServiceContext(_service))
{
var getContactRecords = from conSet in context.ContactSet
where conSet.StateCode == 0   //Check for Status == Active
orderby conSet.FullName
select conSet;

if (getContactRecords != null)
{
StringBuilder fullNameString = new StringBuilder();
Console.WriteLine("Full Name\n--------------------------");
foreach (var item in getContactRecords)
{
if (item.FullName != null)
fullNameString.AppendLine(item.FullName);
}

Console.Write(fullNameString);
Console.ReadKey();
}
}
}

Step 7: Final Code will be like below,

using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Description;
using System.Text;
using System.Threading.Tasks;
using EarlyBound;

namespace LinqToCRM
{
class Program
{
static IOrganizationService _service;
static void Main(string[] args)
{
ConnectToMSCRM("arunpotti@MyOrg.onmicrosoft.com", "Password", "https://MyOrg.api.crm5.dynamics.com/XRMServices/2011/Organization.svc");
Guid userid = ((WhoAmIResponse)_service.Execute(new WhoAmIRequest())).UserId;

if (userid == Guid.Empty) return; // Check whether connection established or not

retrieveContactRecords();
}

public static void ConnectToMSCRM(string UserName, string Password, string SoapOrgServiceUri)
{
try
{
ClientCredentials credentials = new ClientCredentials();
credentials.UserName.UserName = UserName;
credentials.UserName.Password = Password;
Uri serviceUri = new Uri(SoapOrgServiceUri);
OrganizationServiceProxy proxy = new OrganizationServiceProxy(serviceUri, null, credentials, null);
proxy.EnableProxyTypes();
_service = (IOrganizationService)proxy;
}
catch (Exception ex)
{
Console.WriteLine("Error while connecting to CRM " + ex.Message);
Console.ReadKey();
}
}

public static void retrieveContactRecords()
{
using (var context = new ServiceContext(_service))
{
var getContactRecords = from conSet in context.ContactSet
where conSet.StateCode == 0   //Check for Status == Active
orderby conSet.FullName
select conSet;

if (getContactRecords != null)
{
StringBuilder fullNameString = new StringBuilder();
Console.WriteLine("Full Name\n--------------------------");
foreach (var item in getContactRecords)
{
if (item.FullName != null)
fullNameString.AppendLine(item.FullName);
}

Console.Write(fullNameString);
Console.ReadKey();
}
}
}
}
}

Step 8: Execute the project for the below output,

Linq Retrieve Output

Please provide your valuable comments on this article.

Generate Early bound Class using CrmSvcUtil.Exe in CRM

CrmSvcUtil.exe is a command-line code generation tool for use with Microsoft Dynamics CRM. This tool generates Early bound class in C# with Custom entities and attributes. Provides Intellisense Support.

Follow the below steps to create early bound class,

Step 1: Download Latest CRM SDK.

Step 2: Open Run and type cmd.

Step 3: In SDK\bin, we can see crmsvcutil.exe. Now provide the path “CRM\SDK\bin” in command prompt.

Example: I have downloaded the CRM SDK on my desktop. So, path in command prompt will be like below,

Crmsvcutil - CMD

Step 4: Now we have to execute crmsvcutil.exe from command prompt with the following command,

CrmSvcUtil.exe
/url:<Organization Service>
out:<Class Name>.cs
/username:"<User Id>"
/password:"<Password>"
/namespace:<Namespace>
/serviceContextName:<Context Name>
Parameter Description
Organization Service Provide Organization Service. Goto Microsoft Dynamics CRM ->Settings -> Customizations -> Organization Service.
Class Name Provide Output Class Name. Ex: D:\OutputFile.cs
User Id Provide Online 365 User Id or On-Premise domain\userid .
Password Provide Password.
Namespace Provide Namespace name.
Context Name Provide Context Name.

Example:

CrmSvcUtil.exe /url:https://OrgName.api.crm5.dynamics.com/XRMServices/2011/Organization.svc /out:C:\Users\arunpotti\Desktop\EarlyBound.cs /username:"arunpotti@OrgName.onmicrosoft.com" /password:"password" /namespace:earlybound /serviceContextName:ServiceContext

Step 5: Paste the command line in command prompt and click on enter to generate class file.

Crmsvcutil - CMD line

Please provide your valuable comments on this article.

Read XML Web resource using C# & SDK in CRM

Let us see a simple example to read XML Web resource using Query Expression in Console Application,

Task: Read books.xml webresource and get all book titles.

books.xml

Solution:

Step 1: Create one Sample XML Webresource and name it as “new_books” in CRM. Click here to get XML.

Step 2: Include the below References in your visual Studio project, you can get the same from Latest SDK.

Goto the path, SDK -> Bin for the dlls

Microsoft.Crm.Sdk.Proxy
Microsoft.Xrm.Sdk

Step 3: Include the below Framework Assemblies in your project,

Reference Manager - ConnectToCRM

Step 4: Add the below namespaces in your class file,

using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using System.ServiceModel.Description;
using Microsoft.Xrm.Sdk.Query;

Step 5: First we have to connect to CRM, for details Click Here

Step 6: Next we have to use GetEntityCollection method to retrieve records, To Know more about this Click Here

private static EntityCollection GetEntityCollection(IOrganizationService service, string entityName, string attributeName, string attributeValue, ColumnSet cols)
{
QueryExpression query = new QueryExpression
{
EntityName = entityName,
ColumnSet = cols,
Criteria = new FilterExpression
{
Conditions =
{
new ConditionExpression
{
AttributeName = attributeName,
Operator = ConditionOperator.Equal,
Values = { attributeValue }
}
}
}
};
return service.RetrieveMultiple(query);
}

Step 7: We are going to use GetEntityCollection method as follows,

We are going to retrieve content from webresource entity. If we write the same in SQL it will be like this,

Select name, content from FilteredWebResource where name = ‘new_books’
EntityCollection ec = GetEntityCollection(_service, "webresource", "name", "new_books", new ColumnSet("name", "content"));

Step 8: Below method is useful for converting content binary data to string. Content will be encrypted in database, so we have to convert it into String format.

Note: Include MyOrganizationCrmSdkTypes.cs file in your project for WebResource Class.

You can get the same from the path SDK\SampleCode\CS\HelperCode.

private static string ConvertContentToXMLString(EntityCollection entCol)
{
WebResource webResource = null;
string webResourceContent = string.Empty;
webResource = (WebResource)entCol.Entities[0];
if (webResource.Attributes.Contains("content"))
{
byte[] binary = Convert.FromBase64String(webResource.Attributes["content"].ToString());
webResourceContent = UnicodeEncoding.UTF8.GetString(binary);
}
return webResourceContent;
}

Step 9: Below Method is useful for converting string to XMLDocument and pointing to correct node to get the result.

Note: nodeString parameter is for pointing to XML node. For our Example, we have to get title. So, nodestring will be /catalog/book/title

private static void DisplayXmlNodes(string webResourceContent, string nodeString)
{
XmlDocument xml = new XmlDocument();
xml.LoadXml(webResourceContent);
XmlNodeList xnList = xml.SelectNodes(nodeString);
string value = string.Empty;

if (xnList.Count > 0)
{
value += "Book Title\n--------------------------------------\n";
foreach (XmlNode xn in xnList)
{
value += xn.InnerText + "\n";
}
Console.WriteLine(value);
Console.ReadKey();
}
}

Step 10: So the final code is as follows,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using System.ServiceModel.Description;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;
using System.Xml;

namespace Read_Webresource
{
class Program
{
static IOrganizationService _service;
static void Main(string[] args)
{
ConnectToMSCRM("arunpotti@XXXXXX.onmicrosoft.com","XXXXXX","https://XXXXXX.api.crm5.dynamics.com/XRMServices/2011/Organization.svc");
Guid userid = ((WhoAmIResponse)_service.Execute(new WhoAmIRequest())).UserId;
string content = string.Empty;

if (userid == Guid.Empty) return;//check for CRM Connection Establishe or not, if not return otherwise proceed to next step

EntityCollection ec = GetEntityCollection(_service, "webresource", "name", "new_sampleXMLfile", new ColumnSet("name", "content"));

if (ec.Entities[0].Attributes.Count > 0)
{
content = ConvertContentToXMLString(ec);
if (!string.IsNullOrEmpty(content))
DisplayXmlNodes(content, "/catalog/book/title");
}
}

private static void ConnectToMSCRM(string UserName, string Password, string SoapOrgServiceUri)
{
try
{
ClientCredentials credentials = new ClientCredentials();
credentials.UserName.UserName = UserName;
credentials.UserName.Password = Password;
Uri serviceUri = new Uri(SoapOrgServiceUri);
OrganizationServiceProxy proxy = new OrganizationServiceProxy(serviceUri, null, credentials, null);
proxy.EnableProxyTypes();
_service = (IOrganizationService)proxy;
}
catch (Exception ex)
{
Console.WriteLine("Error while connecting to CRM " + ex.Message);
Console.ReadKey();
}
}

private static EntityCollection GetEntityCollection(IOrganizationService service, string entityName, string attributeName, string attributeValue, ColumnSet cols)
{
QueryExpression query = new QueryExpression
{
EntityName = entityName,
ColumnSet = cols,
Criteria = new FilterExpression
{
Conditions =
{
new ConditionExpression
{
AttributeName = attributeName,
Operator = ConditionOperator.Equal,
Values = { attributeValue }
}
}
}
};
return service.RetrieveMultiple(query);
}

private static string ConvertContentToXMLString(EntityCollection entCol)
{
WebResource webResource = null;
string webResourceContent = string.Empty;
webResource = (WebResource)entCol.Entities[0];
if (webResource.Attributes.Contains("content"))
{
byte[] binary = Convert.FromBase64String(webResource.Attributes["content"].ToString());
webResourceContent = UnicodeEncoding.UTF8.GetString(binary);
}
return webResourceContent;
}

private static void DisplayXmlNodes(string webResourceContent, string nodeString)
{
XmlDocument xml = new XmlDocument();
xml.LoadXml(webResourceContent);
XmlNodeList xnList = xml.SelectNodes(nodeString);
string value = string.Empty;

if (xnList.Count > 0)
{
value += "Book Title\n--------------------------------------\n";
foreach (XmlNode xn in xnList)
{
value += xn.InnerText + "\n";
}
Console.WriteLine(value);
Console.ReadKey();
}
}
}
}

Step 11: Final Output is,

Read XML Web resource-Output

Please provide your valuable feedback.