Introduction
Hi All, In this article I would like to discuss how to create a delete request for Dynamics 365 CRM using the XRM SDK and Dataverse Client. This example will use C#, and is a simple console application, it’s dynamic that allows the user to type/paste in the fetchXML, provide the entity name and the main entity id.
Understanding the Xrm SDK for Microsoft Dynamics 365
Microsoft Dynamics 365 is a powerful cloud-based service that provides a suite of tools and resources for building and customizing business applications. As a developer, one of the key resources you’ll likely use when working with Dynamics 365 is the Xrm SDK. In this article, I will show you how I used theĀ Xrm SDK to create a delete request.
First, let’s start with the basics. The Xrm SDK is a software development kit (SDK) that provides developers with a set of resources for working with Dynamics 365. The SDK includes a variety of different components, such as documentation, sample code, and other resources that can be used to create custom solutions for Dynamics 365. The SDK is designed to be used by developers who are creating custom solutions for Dynamics 365, such as plugins, custom workflows, and other customizations.
One of the key features of the Xrm SDK is its ability to allow developers to access the underlying data and functionality of Dynamics 365. This means that developers can create custom solutions that integrate with Dynamics 365 and take advantage of its powerful capabilities. For example, a developer could create a custom plugin that allows users to create custom reports within Dynamics 365, or a custom workflow that automates a specific business process.
Another important aspect of the Xrm SDK is its support for multiple programming languages. The SDK supports C#, JavaScript, and TypeScript, so developers can use the language they are most comfortable with. Additionally, the SDK also provides a set of tools and resources for debugging and testing custom solutions.
In conclusion, the Xrm SDK is an essential resource for developers working with Microsoft Dynamics 365. It provides a comprehensive set of tools and resources that allow developers to create custom solutions that integrate with Dynamics 365 and take advantage of its powerful capabilities. With support for multiple programming languages and debugging and testing tools, the Xrm SDK makes it easy for developers to create high-quality custom solutions for Dynamics 365.
Console Application
you will need to create a console application using either Visual studio code or Visual studio, I’ve used Visual studio. You will then need to install the following nuget packages:
Nuget Packages
1 2 3 4 |
<ItemGroup> <PackageReference Include="Microsoft.PowerPlatform.Dataverse.Client.Dynamics" Version="1.0.26" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.2" /> </ItemGroup> |
Program.cs
I proceed to create a verbatim connection string:
1 2 3 4 5 6 7 |
string connectionString = $@" AuthType = ClientSecret; Url = https://your_crm_url; ClientId = your_client_id; ClientSecret = your_client_secret; RequireNewInstance=true; "; |
I then created the following variables:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
ServiceClient.MaxConnectionTimeout = TimeSpan.FromMinutes(60); //INCREASE THE TIMEOUT OF THE CONNECTION FROM 4 MINUTES TO 1 HOUR string fetchXml = ""; string entityName = ""; string entityidname = ""; Console.WriteLine("Please enter fetch xml:"); fetchXml = Console.In.ReadToEnd(); Console.WriteLine(); Console.WriteLine("Please eneter the entity name:"); entityName = Console.ReadLine(); Console.WriteLine(); Console.WriteLine("Please enter the entity primary id: "); entityidname = Console.ReadLine(); |
I then used a ‘using’ statement to wrap the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 |
using (ServiceClient serviceClient = new(connectionString)) { if (serviceClient.IsReady) { // Define the fetch attributes. // Set the number of records per page to retrieve. int fetchCount = 2000; //BY DEFAULT THIS IS 5000, I WANTED TO 2000 // Initialize the page number. int pageNumber = 1; // Initialize the number of records. int recordCount = 0; // Specify the current paging cookie. For retrieving the first page, // pagingCookie should be null. string pagingCookie = null; Console.WriteLine(); Console.WriteLine(); Console.WriteLine("Retrieving data in pages\n"); Console.WriteLine("#\tID To Delete\t\t\t"); while (true) { string xml = CreateXml(fetchXml, pagingCookie, pageNumber, fetchCount); var maxRequestsPerBatch = 100; // Excute the fetch query and get the xml result. RetrieveMultipleRequest fetchRequest1 = new RetrieveMultipleRequest { Query = new FetchExpression(xml) }; EntityCollection returnCollection = ((RetrieveMultipleResponse)serviceClient.Execute(fetchRequest1)).EntityCollection; List<Entity> entityList = new List<Entity>(returnCollection.Entities); //I AM USING PARALLEL, TO HELP SPEED UP DELETING A LARGE NUMBER OF ROWS OVER A MAXIMUM OF 10 THREADS. Parallel.ForEach(entityList, new ParallelOptions { MaxDegreeOfParallelism = 10 }, () => new { ServiceClient = serviceClient.Clone(), }, (item, loopState, index, threadLocalState) => { Console.WriteLine("{0}, Thread Id= {1}", item.Attributes["incidentid"], Thread.CurrentThread.ManagedThreadId); try { threadLocalState.ServiceClient.Delete(item.LogicalName, new Guid(item.Attributes["incidentid"].ToString())); return threadLocalState; } catch (Exception ex) { //continue Console.WriteLine("Error deleting: " + item.Attributes[entityidname].ToString() + " Error: " + ex.Message); return threadLocalState; } }, (threadLocalState) => { if (threadLocalState != null) { threadLocalState.ServiceClient.Dispose(); } }); // THIS SECTION DEALS WITH PAGING. // Check for morerecords, if it returns 1. if (returnCollection.MoreRecords) { Console.WriteLine("\n****************\nPage number {0}\n****************", pageNumber); Console.WriteLine("#\tIndicent ID\t\t\t"); // Increment the page number to retrieve the next page. pageNumber++; // Set the paging cookie to the paging cookie returned from current results. pagingCookie = returnCollection.PagingCookie; } else { // If no more records in the result nodes, exit the loop. break; } } } } |
This is the code that deals with the CreateXml:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
static string CreateXml(string xml, string cookie, int page, int count) { StringReader stringReader = new StringReader(xml); var reader = new XmlTextReader(stringReader); // Load document XmlDocument doc = new XmlDocument(); doc.Load(reader); XmlAttributeCollection attrs = doc.DocumentElement.Attributes; if (cookie != null) { XmlAttribute pagingAttr = doc.CreateAttribute("paging-cookie"); pagingAttr.Value = cookie; attrs.Append(pagingAttr); } XmlAttribute pageAttr = doc.CreateAttribute("page"); pageAttr.Value = System.Convert.ToString(page); attrs.Append(pageAttr); XmlAttribute countAttr = doc.CreateAttribute("count"); countAttr.Value = System.Convert.ToString(count); attrs.Append(countAttr); StringBuilder sb = new StringBuilder(1024); StringWriter stringWriter = new StringWriter(sb); XmlTextWriter writer = new XmlTextWriter(stringWriter); doc.WriteTo(writer); writer.Close(); return sb.ToString(); } |
References
- The Microsoft Dynamics 365 Developer Center (https://developer.microsoft.com/en-us/dynamics365/) provides a wealth of information on the Xrm SDK, including documentation, sample code, and other resources.
- The Dynamics 365 Community (https://community.dynamics.com/) is an online community where developers can share information and ask questions about the Xrm SDK and other Dynamics 365 topics.
- The Dynamics 365 Developer Blog (https://cloudblogs.microsoft.com/dynamics365/) provides articles and tutorials on a variety of Dynamics 365 development topics, including the Xrm SDK.
- The Dynamics 365 Developer Toolkit (https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/developer-toolkit) is a set of tools that can be used to create, debug, and deploy custom solutions for Dynamics 365 using the Xrm SDK.
- The Dynamics 365 SDK (https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/developer-toolkit) is the official documentation for the Xrm SDK, it provides detailed information on how to use the SDK and create custom solutions for Dynamics 365.
It’s worth to mention that the SDK is evolving and the links provided may be outdated, in that case use the Microsoft Dynamics 365 Developer Center as a reference and look for the latest version of the SDK.