How to Retrieve Contact ID and Update Contact Details in Microsoft CRM 2013 Contact Entity Using C#

Editor’s note: The following post was written by Visual C# MVP  Ming Man Chan  

In order to connect and manipulate the data in Microsoft CRM 2013, the developer can download the MS CRM 2013 SDK (https://www.microsoft.com/en-my/download/details.aspx?id=40321). The CRM SDK uses different patterns to do the CRUD (Create, Read, Update, and Delete) operations. The simplest pattern for me is using the LINQ expression.  In my experience, not all the update operation can use the LINQ expression but you can definitely do the Read operation using LINQ easily.

This article divided into 3 subsections to accomplish the retrieve and update contact details in MS CRM 2013 Contact Entity.

  • Connect to CRM 2013 using C#.
  • Retrieve all the contacts using LIQN statement.
  • Update the contact information LINQ statement.

Connect to CRM 2013 using C#

Once you have downloaded the SDK then you will have a file name MicrosoftDynamicsCRM2013SDK.exe. The installer will ask you for a location to unzip the files when you run the exe execution file. Choose a location for example, C:\MSCRMSDK.

Open the folder that you unzipped the SDK then you will see a folder named SDK and a file named mscrmeula.txt. The code that we want to look at is located in SDK\Walkthroughs\Portal\ConsoleAppWalkthrough.

Double click the ConsoleAppWalkthrough.csproj file, provided you have either Visual Studio 2012 or Visual Studio 2013 installed. The default sample does not have do the contact update.

You will now see the following project structure in Visual Studio under the Solution Explorer.

 

Double click to open the App.config then you will see the file in the following XML format.

<?xml version="1.0"?>

<configuration>

  <configSections>

    <section name="microsoft.xrm.client" type="Microsoft.Xrm.Client.Configuration.CrmSection, Microsoft.Xrm.Client"/>

  </configSections>

  <connectionStrings>

    <!--<add name="Xrm" connectionString="Server=https://crm/contoso; Domain=CONTOSO; Username=Administrator; Password=pass@word1"/>-->

    <add name="Xrm" connectionString="Url=https://WIN-70BO4R8PVDT:5555/CRM2013MM; Domain=LOCALCRM; Username=mmchan; Password=Password;"/>

  

  </connectionStrings>

  <microsoft.xrm.client>

    <contexts default="Xrm">

      <add name="Xrm" type="Xrm.XrmServiceContext, Xrm" connectionStringName="Xrm"/>

    </contexts>

  </microsoft.xrm.client>

  <startup>

    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>

  </startup>

</configuration>

Pay attention to the entry:

< addname = " Xrm " connectionString = " Url=https://WIN-70BO4R8PVDT:5555/CRM2013MM; Domain=LOCALCRM; Username=mmchan; Password=Password; " />

This is the key connection string for you to connection to the MS CRM 2013 server.

 

Retrieve all the contacts using LIQN statement

I could not use the below code that comes with the SDK for the first time.

private static void WriteExampleContacts(XrmServiceContext xrm)

{

       var exampleContacts = xrm.ContactSet

              .Where(c => c.EMailAddress1.EndsWith("@example.com"));

 

       //write the example Contacts

       foreach (var contact in exampleContacts)           

       {

              Console.WriteLine(contact.FullName);

       }

}

It has given me Access is denied error. For that reason, I have created another set of similar code.

private static void GetContact(XrmServiceContext xrm)

{

    var result = from r in xrm.ContactSet where r.EMailAddress1.EndsWith("@example.com") select r;

 

    foreach (Contact contact in result)

    {

        Console.WriteLine(contact.EMailAddress1);

    }

}

The above method is to extract the contacts in MS CRM 2013. The line:

var result = from r in xrm.ContactSet where r.EMailAddress1.EndsWith("@example.com") select r;

It is used to filter all the contact with the email address that ended with “@example.com”. You will see the listing as below.

 

In order to see the return you must either type in some contacts the email address ends with @example.com or install the sample data for Dymanics CRM 2013. To install sample data for Dymanics CRM 2013 refer to https://community.dynamics.com/crm/b/crmpowerobjects/archive/2013/11/01/adding-and-removing-sample-data-in-dynamics-crm-2013.aspx.

Update the contact information LINQ statement

The sample code has a section to insert the contact record as follow.

var allisonBrown = new Xrm.Contact

{

       FirstName = "Allison",

       LastName = "Brown",

       Address1_Line1 = "23 Market St.",

       Address1_City = "Sammamish",

       Address1_StateOrProvince = "MT",

       Address1_PostalCode = "99999",

       Telephone1 = "12345678",

       EMailAddress1 = "allison.brown@example.com"

};

This article has added a method to update the record that the above code added.

private static void UpdateContact(XrmServiceContext xrm)

{

    var result = from r in xrm.ContactSet where r.EMailAddress1 == "allison.brown@example.com" select r;

 

    result.FirstOrDefault().EMailAddress1 = "allisonb@example.com";

    xrm.UpdateObject(result.FirstOrDefault());   

    xrm.SaveChanges();

}

The line below is to retrieve the added record using the email address (let us assume the email address is unique in this article).

var result = from r in xrm.ContactSet where r.EMailAddress1 == "allison.brown@example.com" select r;

We then change the email address.

result.FirstOrDefault().EMailAddress1 = "allisonb@example.com";

 

Finally, we save all the changes by using the SaveChanges() method.

xrm.UpdateObject(result.FirstOrDefault());

xrm.SaveChanges();

If you call the GetContact method now then you should see the listing as follow.

 

You can use the same way to update all the MS Dymanics CRM 2013 entities except for those entities that have dependencies to other entities.

 

About the author

 

Ming Man is Microsoft MVP since year 2006. He is a software development manager for a multinational company. With 25 years of experience in the IT field, he has developed system using Clipper, COBOL, VB5, VB6, VB.NET, Java and C #. He has been using Visual Studio (.NET) since the Beta back in year 2000.  He and the team have developed many projects using .NET platform such as SCM, and HR based applications. He is familiar with the N-Tier design of business application and is also an expert with database experience in MS SQL, Oracle and AS 400.  Additionally you can read Ming’s Channingham’s blog

 

About MVP Mondays

The MVP Monday Series is created by Melissa Travers. In this series we work to provide readers with a guest post from an MVP every Monday. Melissa is a Community Program Manager, formerly known as MVP Lead, for Messaging and Collaboration (Exchange, Lync, Office 365 and SharePoint) and Microsoft Dynamics in the US. She began her career at Microsoft as an Exchange Support Engineer and has been working with the technical community in some capacity for almost a decade. In her spare time she enjoys going to the gym, shopping for handbags, watching period and fantasy dramas, and spending time with her children and miniature Dachshund. Melissa lives in North Carolina and works out of the Microsoft Charlotte office.