Learning to use the Microsoft Dynamics 365 SDK

Microsoft Dynamics 365 is an amazing platform with awesome potential, however, from personal experience, it is not a good fit for most businesses out of the box.

Whether you are on-premise or online, Dynamics 365 boasts an impressive level of out of the box customisation features to create almost unlimited entities, fields, forms workflows, business process flows and more. Sometimes though, you just need more control to make it work exactly how you need it to and it’s time like this that you might use the SDK.

The below article assumes you have a working knowledge of Visual Studio and c# or at least are comfortable setting up a basic console application or similar.

 

Installing the SDK

So, let’s get going! Start by getting the SDK . This can only be downloaded via NuGet right now as the executable installs are now deprecated. The package you want to find is Microsoft.CrmSdk.CoreTools. This gives you the core dlls for most general SDK use, but you may need to add additional references if you do something a bit more specific. The current version of the Dynamics SDK is v 9.1 at the time of writing.

The NuGet package downloads everything you need into a folder called ‘coretools’. You will then need to add references to these dlls in the project itself.

Connecting to Dynamics 365

 

The example below gives a method to explicitly log in as a user which is great for console applications where you want to log in as yourself to run various commands. Ideally you would collect this information from the user and populate the variables for the sign in method, but for now, I have just popped the values in a config file to save time.

 

var userName = ConfigurationManager.AppSettings[“userName”];

var password = ConfigurationManager.AppSettings[“password”];

 

ClientCredentials clientCredentials = new ClientCredentials();

clientCredentials.UserName.UserName = userName;

clientCredentials.UserName.Password = password;

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

// Get the URL from Dynamics, Navigate to Settings -> Customizations -> Developer Resources and Copy and Paste Organization Service Endpoint Address URL

var connectionstring =    ConfigurationManager.ConnectionStrings[“Dynamics”].ConnectionString;

_dynamics = new OrganizationServiceProxy(new Uri(connectionstring),

null, clientCredentials, null);

// Check that our Dynamics instance is not null before continuing

if (_dynamics != null)

{

// Do Code

}

Retrieve a Single Record

Working with data in Dynamics is super simple. If you know the GUID of the record you want, just use Dynamics to ‘retrieve’ it like below.

The example casts to a generic entity object so you will not have any kind of intellisense picking up a model.

The parameters of the Retrieve method are

  • The name of the table you are looking up in Dynamics (ie opportunity or incident).
  • The GUID of the record you want to return
  • What columns you want in the result set (true returns all).

Entity account = _dynamics.Retrieve(“account”, new Guid(d.Value), new ColumnSet(true));

//You can also pass in a column set

ColumnSet columns = new ColumnSet(new string[] { “firstname”, “businessphone”, “lastname” });

Entity contact = _dynamics.Retrieve(“contact”, new Guid(d.Value), new ColumnSet(columns));

Retrieve Multiple Records

If you’re looking for something in particular, or want to return more than one result you can ‘Retrieve Multiple’ but you need to define your search criteria first.

You do this by creating a Query Expression. A query expression is like a code version of an advanced find. You tell it the entity name, the columns, and the conditional criteria to be applied. You can add as many condition expressions as you want in the filter expression to make it either super specific or super broad.

Once you have defined your search criteria, you use can pass it to your service to ‘retrieve multiple’ results into a DataCollection of your entity.

QueryExpression ContractQuery = new QueryExpression

{

EntityName = “contract”,

ColumnSet = new ColumnSet(“contractid”, “title”, “customerid”),

Criteria = new FilterExpression

{

Conditions = {

new ConditionExpression

{

AttributeName = “title”,

Operator = ConditionOperator.BeginsWith,

Values = { “Annual” }

},

new ConditionExpression

{

AttributeName = “statuscode”,

Operator = ConditionOperator.Equal,

Values = { “3” } //3 is enum for Active

}

}

}

};

 

DataCollection<Entity> contracts;

contracts = _dynamics.RetrieveMultiple(ContractQuery).Entities;

Reading the Data Returned from a Query

Because we are returning a generic Entity object, you can’t access it like you would if you had a model, but it is still nice and simple to do. Just declare a variable and explicitly access the named value from your object.

var contractname = contract[“name”];

My preference is to place a breakpoint on the Retrieve Multiple line and run the application until it hits it. Then put that object (i.e. contracts) into the immediate window to return your response. You can then paste this into another window or notepad for an easy reference of how to access all the returned fields when you are writing your code.

NOTE: If you returned multiple you will need to do something like a for-each loop to get to the individual instance of the entity.

 

Creating an Entity Object

To create an object, call the Create method on the service with an object you have created that’s been prepopulated with the relevant data.

Be wary to ensure that all the names are as per the database i.e. incident not case, customerid not accountid etc and that they type matches exactly to the expected type in dynamics.

Note: all names are lowercase

// Make new incident object and populate it

Entity incident = new Entity();

incident.LogicalName = “incident”;

//incident[“title”] = “New Case Raised by SDK”;

incident[“title”] = CaseTitle;

incident[“description”] = description;

incident[“customerid”] = new EntityReference(“account”, accountId);

incident[“ownerid”] = new EntityReference(“systemuser”, ownerId);

incident[“createdon”] = DateTime.Now;

var newIncidentId = _dynamics.Create(incident);

Update an Entity Object – Standard Data

To update an Entity, you simply call the ‘Update’ Method and pass in a local instance of an entity with the correct entity name and GUID and then add Attributes to reflect the changed content.

var UpdateOpportunity = new Entity(“opportunity”);

var id = new Guid(OpportunityGuid);

UpdateOpportunity.Attributes.Add(“opportunityid”, id);

UpdateOpportunity.Attributes.Add(“custom_field”, CustomVariable);

_dynamics.Update(UpdateOpportunity);

Update an Entity Object – Special Data

There are some functions in Dynamics that trigger additional activities when they are called. This additional activity wouldn’t be called if updated using the SDK, so these values are restricted into their own ‘Requests’ which need to be called instead.

Note: You can set the values for some entities with restricted fields like status, but doing so will not trigger any associated workflows. To ensure everything happens that you would expect to happen, always use the associated SDK requests.

The easiest way of remembering whether this has its own special Request is to think in terms of a Dynamics Workflow. We have below options for Create, Update, Assign, Change Status and more.

 

In this example, we can look at Assigning Records as well as Changing Status of records.

To assign a record, create a new ‘AssignRequest’ as below.

This creates an object with the following values – the assignee is the person you want to assign to and accepts an entityreference. The second is the target, which is an entityreference to the thing you are updating.

When you’re done, pass it to the service as an ‘Execute’ request.

// Set the task owner

// Create the Request Object and Set the Request Object’s Properties

AssignRequest assignTask = new AssignRequest

{

Assignee = new EntityReference(“systemuser”,

new Guid(“63e21a3d-42a7-4f7b-893b-eacea28cbbf9”)),

Target = new EntityReference(“task”,

newActivityId)

};

// Execute the Request

_dynamics.Execute(assignTask);

 

To change the state/status, call the SetStateRequest.

// Create the Request Object

SetStateRequest state = new SetStateRequest();

// Set the Request Object’s Properties

state.State = new OptionSetValue(2)

state.Status = new OptionSetValue(5);

// Point the Request to the case whose state is being changed

state.EntityMoniker = caseReference;

// Execute the Request

SetStateResponse stateSet = (SetStateResponse)_dynamics.Execute(state);

Summary

So that’s it! You’ve just learnt the basics of Microsoft Dynamics 365 SDK. With these functions, you can safely work with data in your system, apply your own business logic and really add value to your company.

Have fun!

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.