Connecting ASP.NET MVC Application to Dynamics CRM

The ASP.NET MVC is a web application framework developed by Microsoft, which implements the Model View Controller (MVC) design pattern.

In this tutorial, we will learn how to connect an ASP.Net MVC application to Dynamic CRM and perform CRUD (Create, Update, Retrieve, and Delete) operations.

1. Create a new MVC project

MVC Project

2. 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=Your_Organization_Url/;Username=Your_User_id_of_Online_Org;Password=Your_Password"/>
</ connectionStrings>

Connection string for Microsoft on Premise:


<connectionStrings>
<add name="MyConnectionString" connectionString="Server=you_server_Url; Domain=Your_domain; Username=administrator; Password=password;"/>
</ connectionStrings>

Name: used to access the connection string

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.

3. 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

4. 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; }
 }

 

5. 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.

callRetriveFromController

6. 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. The output would look like this:

retriveResult

7. Add additional features e.g.  Add, Edit and Delete

First of all, add a controller for Add New as shown below:


public ActionResult AddNew(string id)

{

DAL_AccountEntity objDAL = new DAL_AccountEntity();

List<Microsoft.Xrm.Sdk.EntityReference> refUsers = objDAL.GetEntityReference();

AccountEntityModels objAccountModel = new AccountEntityModels();

Guid accountId=Guid.Empty;

if (id != null)

{

accountId = Guid.Parse(id);

}

if (accountId != Guid.Empty)

{

objAccountModel = objDAL.getCurrentRecord(accountId);

}

&nbsp;

if (refUsers.Count > 0)

{

ViewBag.EntityReferenceUsers = new SelectList(refUsers, "Id", "Name");

}

return View(objAccountModel);

}

And the http post method is shown bellow


[HttpPost]

public ActionResult AddNew(AccountEntityModels accountdmodel)

{

DAL_AccountEntity objDAL = new DAL_AccountEntity();

Guid id = accountdmodel.AccountID;

objDAL.SaveAccount(accountdmodel);

return Redirect("~/Home");

return View(accountdmodel);

}

 

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" />
 
 </td>

 @Html.ActionLink("Back to List", "Index")
 </tr>

 </table>

 </td>

 </tr>

 </table>

}

The output will be like this

AddNewRecord

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");
}
}

 



9 Comments

Leave a Reply

Request a Free Demo
Enter Your Information below and we will get back to you within few hours