Skip to main content

Getting Started with MS Dynamics API

This is mostly a "note to self" post following some research and prototyping into working with the Microsoft Dynamics API from ASP.Net but might also be useful for anyone else that stumbles across it trying to get things working on this front.

Accessing a Dynamics Instance

First step for me was to get access to an instance of MS Dynamics to work with by signing up for a free trial. This gives access to a fully featured set up of Dynamics that you can work with for 30 days.

You'll need to sign up with a user name and password and get assigned a sub-domain that will be of the form *.onmicrosoft.com. All of these will be needed for accessing via the API.

Working with the API

Starting with an empty ASP.Net MVC application, the first step is to install a NuGet package:

PM> Install-Package Microsoft.CrmSdk.Extensions

And then add references to the following assemblies:

  • System.IdentityModel.dll
  • System.Data.Services.dll
  • System.Data.Services.Client.dll
  • System.Runtime.Caching.dll
  • System.Runtime.Serialization.dll

Make sure you have .Net 4.5.2 installed and the project set up to target this version of the framework.

With that in place, the following code that creates a new Account record in Dynamics should run successfully:

 public ActionResult Index()
 {
  var crmConnection = CrmConnection.Parse("Url=https://mydomain.crm4.dynamics.com; Username=username; Password=password;");
  var service = new OrganizationService(crmConnection);

  var account = new Entity("account");
  account["name"] = "Test Account";

  var accountId = service.Create(account);

  var result = "Account created with Id: " + accountId;
  return Content(result);
 }

Using Strong Typing

Whilst the above is fine for simple integrations to work with Dynamics data in a more maintainable way it's likely we'd want to make use of strong typing.

To get this working I downloaded the CRM SDK (file: MicrosoftDynamicsCRM2016SDK.exe)

And then from a command prompt opened at C:\Program Files\MS Dynamics SDK\SDK\Bin:

CrmSvcUtil.exe /out:c:\temp\Xrm.cs /url:https://mydomain.crm4.dynamics.com/XRMServices/2011/Organization.svc /username:username /password:password /namespace:Xrm /serviceContextName:XrmServiceContext

This generated a file called Xrm.cs which can be copied into the project. And then code such as the following can be run:

 public ActionResult Index()
 {
  var crmConnection = CrmConnection.Parse("Url=https://mydomain.crm4.dynamics.com; Username=username; Password=password;");
  var service = new OrganizationService(crmConnection);

  var account = new Account
  {
   Name = "Test Account 2",
  };
  account.Id = service.Create(account);

  var result = "Account created with Id: " + account.Id;
  return Content(result);
 }

References

Comments