Sample code to delete instance using Online Management API in Dynamics 365 Customer Engagement


Sharing a sample code that can be used to delete the instance in Dynamics 365 CE using Online Admin API.

Read the previous post for more details

We basically need to get the instace id and use the HTTP Delete to achieve this

https://docs.microsoft.com/en-in/rest/api/admin.services.crm.dynamics.com/Instances/DeleteInstance

Production instance needs to be converted to Sandbox before it can be deleted else we’d get the operation not supported error.

The sample code :-

private static void Main(string[] args)
{
var authContext = new AuthenticationContext(Authority, false);
var credentials = new UserCredential(UserName, Password);

// Get the token
_authResult = authContext.AcquireToken(Resource, ClientId, credentials);

Task.WaitAll(Task.Run(async () => await DeleteInstance()));
}
private static async Task DeleteInstance()
{
var httpClient = new HttpClient
{
BaseAddress = new Uri(Resource),
Timeout = new TimeSpan(0, 2, 0)
};

httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",
_authResult.AccessToken);

var retrieveResponse =
await httpClient.DeleteAsync("/api/v1.1/Instances/{instanceGuid}/Delete");

if (retrieveResponse.IsSuccessStatusCode)
{
var jRetrieveResponse =
retrieveResponse.Content.ReadAsStringAsync().Result;

}
}

Hope it helps..

Advertisements

Author: Nishant Rana

I love working in and sharing everything about Microsoft.NET technology !

One thought on “Sample code to delete instance using Online Management API in Dynamics 365 Customer Engagement”

Please share your thoughts

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 )

Google+ photo

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

Twitter picture

You are commenting using your Twitter 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.