Connecting ASP.NET MVC Application to Dynamic CRM
Contents
- 1 Nuget Package
- 2 Create a new MVC project
- 3 Add a connection string in the Web.config file
- 4 Add the following assemblies from CRM SDK to your MVC project
- 5 Add new model to your project and add some properties
- 6 Make Data Access Layer(DAL)
- 7 Update Index View
- 8 Add additional features e.g. Add, Edit and Delete
Nuget Package
Install-Package Microsoft.CrmSdk.CoreTools -Version 8.0.2.1
Create a new MVC project
new MVC app
Add a connection string in the Web.config file
Microsoft Dynamics CRM uses the concept of connection string to connect to the Microsoft Dynamics CRM server. This is similar to the concept of connection strings used with Microsoft SQL Server. Connection string for Online using Office 365:
<connectionStrings> <add name="MyConnectionString" connectionString="Server=you_server_Url; Domain=Your_domain; Username=administrator; Password=password;"/> </ connectionStrings>
Connection string for Microsoft on Premise:
<connectionStrings> <add name="MyConnectionString" connectionString="Url=http://myserver/AdventureWorksCycle; Domain=mydomain; Username=administrator; Password=password;"/> </ connectionStrings>
Alternatively
<connectionStrings>
<add name="Xrm" connectionString="ServiceUri=https://dev-crm.rochdale.local/RochdaleDev/; Username=ROCHDALE_MBC\s-CRMIntegrationServ; Password=F3c9HFypwgfrD6;"/>
</connectionStrings>
- URL: Specifies the URL to the Microsoft Dynamics CRM organization.
- Username: User id of the Microsoft Dynamics CRM organization
- Password: Password of the Microsoft Dynamics CRM organization
- Domain: Specifies the domain that will verify user credentials.
Add the following assemblies from CRM SDK to your MVC project
- microsoft.crm.sdk.proxy.dll
- microsoft.xrm.sdk.dll
- microsoft.xrm.client.dll
Also add references to these assemblies from Visual Studio Assemblies.
- System.Runtime.Serialization
- System.ServiceModel
Add new model to your project and add some properties
public class AccountEntityModels
{
public Guid AccountID { get; set; }
public string AccountName { get; set; }
public int NumberOfEmployees { get; set; }
public Money Revenue { get; set; }
public EntityReference PrimaryContact { get; set; }
public string PrimaryContactName { get; set; }
public decimal RevenueValue { get; set; }
}
Make Data Access Layer(DAL)
Make a DAL Folder and add a new class “DAL_AccountEntity”. The purpose of this class is to handle all the data access to avoid complexity from controller class. Next, create “RetriveRecords” function in “DAL_AccountEntity” class. This function will retrieve all accounts and return the List as shown below. Make sure to add references to the following assemblies first:
using Microsoft.Xrm.Sdk;
using TestAppMVCAndCRM.Models;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Client.Services;
public List<AccountEntityModels> RetriveRecords()
{
using (OrganizationService service = new OrganizationService("MyConnectionString"))
{
QueryExpression query = new QueryExpression
{
EntityName = "account",
ColumnSet = new ColumnSet("accountid","name", "revenue", "numberofemployees", "primarycontactid")
};
List<AccountEntityModels> info = new List<AccountEntityModels>();
EntityCollection accountRecord = service.RetrieveMultiple(query);
if (accountRecord != null && accountRecord.Entities.Count > 0)
{
AccountEntityModels accountModel;
for (int i = 0; i < accountRecord.Entities.Count; i++)
{
accountModel = new AccountEntityModels();
if (accountRecord[i].Contains("accountid") && accountRecord[i]["accountid"] != null)
accountModel.AccountID = (Guid)accountRecord[i]["accountid"];
if (accountRecord[i].Contains("name") && accountRecord[i]["name"] != null)
accountModel.AccountName = accountRecord[i]["name"].ToString();
if (accountRecord[i].Contains("revenue") && accountRecord[i]["revenue"] != null)
accountModel.RevenueValue = ((Money)accountRecord[i]["revenue"]).Value;
if (accountRecord[i].Contains("numberofemployees") && accountRecord[i]["numberofemployees"] != null)
accountModel.NumberOfEmployees = (int)accountRecord[i]["numberofemployees"];
if (accountRecord[i].Contains("primarycontactid") && accountRecord[i]["primarycontactid"] != null)
accountModel.PrimaryContactName = ((EntityReference)accountRecord[i]["primarycontactid"]).Name;
info.Add(accountModel);
}
}
return info;
}
}
Then, call the function we just created from Controller.
public ActionResult Index()
{
DAL_AccountEntity objDAL = new DAL_AccountEntity();
List<AccountEntityModel> accountInfo = objDAL.RetriveRecords();
ViewBag.accountInfo = accountInfo;
return View();
}
Update Index View
Now, to show the accounts retrieved from CRM, index view needs to be updated like given below:
@model TestAppMVCAndCRM.Models.AccountEntityModels
@{
ViewBag.Title = "Home Page";
}
<table>
<tr>
<a href="~/Home/AddNew">Add New </a>
</tr>
<tr>
<td>
<table border="0" cellpadding="4" cellspacing="1" bgcolor="#D8D8D8" class="main_txt">
<tr>
<td width="100" align="center" class="header_bg">
<a href=""> Account name </a>
</td>
<td width="80" align="center">
<a href=""> Number of Employees </a>
</td>
<td width="80" align="center">
<a href=""> Revenue </a>
</td>
<td width="70" align="center">
<a href=""> Primary Contact </a>
</td>
<td width="120" align="center" class="header_bg">Action</td>
</tr>
@{
string COLOR1 = "#ffffff";
string COLOR2 = "#f1f1f1";
string bgcolor = "#ffffff";
}
@foreach (var x in ViewBag.accountinfo)
{
bgcolor = bgcolor == COLOR1 ? COLOR2 : COLOR1;
<tr bgcolor="@bgcolor">
<td>
@x.AccountName
</td>
<td>
@x.NumberOfEmployees
</td>
<td>
@x.RevenueValue
</td>
<td>
@x.PrimaryContactName
</td>
<td>
<a href="~/Home/Delete/@x.AccountID">Delete Account </a>
<a href="~/Home/AddNew/@x.AccountID">Edit Account </a>
</td>
</tr>
}
</table>
</td>
</tr>
</table>
Make sure you are using .NET Framework 4.5.2 and run the project.
Add additional features e.g. Add, Edit and Delete
First of all, add a controller for Add New as shown below:
public ActionResult AddNew()
{
DAL_AccountEntity objDAL = new DAL_AccountEntity();
List<Microsoft.XRM.Sdk.EntityReference> refUsers = = objDAL.GetEntityReference();
if(refUsers.Count > 0)
{
ViewBag.EntityReferenceUsers = new SelectList(refUsers, "id", "Name");
}
return View();
}
For the ‘Primary Contact’ lookup field we will retrieve contacts and display them in Drop down list. To do that, we will create GetEntityReference function as shown below:
public List<Microsoft.Xrm.Sdk.EntityReference> GetEntityReference()
{
try
{
List<Microsoft.Xrm.Sdk.EntityReference> info = new List<Microsoft.Xrm.Sdk.EntityReference>();
using (OrganizationService service = new OrganizationService("MyConnectionString"))
{
QueryExpression query = new QueryExpression
{
EntityName = "contact",
ColumnSet = new ColumnSet("contactid", "fullname")
};
EntityCollection PrimaryContact = service.RetrieveMultiple(query);
if (PrimaryContact != null && PrimaryContact.Entities.Count > 0)
{
Microsoft.Xrm.Sdk.EntityReference itm;
for (int i = 0; i < PrimaryContact.Entities.Count; i++)
{
itm = new EntityReference();
if (PrimaryContact[i].Id != null)
itm.Id = PrimaryContact[i].Id;
if (PrimaryContact[i].Contains("fullname") && PrimaryContact[i]["fullname"] != null)
itm.Name = PrimaryContact[i]["fullname"].ToString();
itm.LogicalName = "contact";
info.Add(itm); }
}
}
return info;
}
catch (Exception ex)
{
return null;
}
}
The View would look like this:
@model TestAppMVCAndCRM.Models.AccountEntityModels
@{
ViewBag.Title = "AddNew";
}
@using (Html.BeginForm())
{
<table>
<tr>
<td>
<table>
<tr>
<td width="150px">Account Name</td>
<td>
@Html.HiddenFor(m => m.AccountID)
@Html.EditorFor(m => m.AccountName)
</td>
</tr>
<tr>
<td>Number of Employees</td>
<td>
@Html.EditorFor(m => m.NumberOfEmployees)
</td>
</tr>
<tr>
<td width="150px">Revenue</td>
<td>
@Html.EditorFor(m => m.Revenue)
</td>
</tr>
<tr>
<td>Primary Contact</td>
<td>
@Html.DropDownListFor(model => model.PrimaryContact.Id, (SelectList)ViewBag.EntityReferenceUsers)
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="Save" />
<br />
</td>
@Html.ActionLink("Back to List", "Index")
</tr>
</table>
</td>
</tr>
</table>
}
In case of edit, we will pass the Guid of the record to be edited. The following function will do the job:
public AccountEntityModels getCurrentRecord(Guid accountId)
{
AccountEntityModels accountModel = new AccountEntityModels();
using (OrganizationService service = new OrganizationService("MyConnectionString"))
{
ColumnSet cols = new ColumnSet(new String[] { "name", "revenue", "numberofemployees", "primarycontactid" });
Entity account = service.Retrieve("account", accountId, cols);
accountModel.AccountID = accountId;
accountModel.AccountName = account.Attributes["name"].ToString();
accountModel.NumberOfEmployees = (int)account.Attributes["numberofemployees"];
accountModel.RevenueValue = ((Money)account.Attributes["revenue"]).Value;
accountModel.PrimaryContact = (EntityReference)account.Attributes["primarycontactid"];
}
return accountModel;
}
The code behind on save is given below:
public void SaveAccount(AccountEntityModels objAccountModel)
{
using (OrganizationService service = new OrganizationService("MyConnectionString"))
{
Entity AccountEntity = new Entity("account");
if (objAccountModel.AccountID != Guid.Empty)
{
AccountEntity["accountid"] = objAccountModel.AccountID;
}
AccountEntity["name"] = objAccountModel.AccountName;
AccountEntity["numberofemployees"] = objAccountModel.NumberOfEmployees;
AccountEntity["revenue"] = objAccountModel.Revenue;
AccountEntity["primarycontactid"] = new Microsoft.Xrm.Sdk.EntityReference { Id = objAccountModel.PrimaryContact.Id, LogicalName = "account" };
if (objAccountModel.AccountID == Guid.Empty)
{
objAccountModel.AccountID = service.Create(AccountEntity);
}
else
{
service.Update(AccountEntity);
}
}
}
And in last the Delete functionality can be achieved like below
public ActionResult Delete(Guid id)
{
using (OrganizationService service = new OrganizationService("MyConnectionString"))
{
service.Delete("account", id);
return Redirect("~/Home");
}
}