{"id":847,"date":"2014-08-18T13:05:00","date_gmt":"2014-08-18T07:35:00","guid":{"rendered":"https:\/\/www.inogic.com\/blog\/?p=847"},"modified":"2021-12-21T10:03:07","modified_gmt":"2021-12-21T04:33:07","slug":"clone-records-in-dynamics-crm","status":"publish","type":"post","link":"https:\/\/www.inogic.com\/blog\/2014\/08\/clone-records-in-dynamics-crm\/","title":{"rendered":"Clone Records in Dynamics CRM"},"content":{"rendered":"<p>Very often we are troubled with writing huge codes and end up spending our valuable time for cloning\/copying Dynamics CRM entity record. Just imagine the time needed if you are asked to create a cloned record with more than 100 attributes. Don\u2019t you think it\u2019s a time-consuming effort and how great would it be if all this could happen just with a two line code?<\/p>\n<p>The below sample code will guide you on how to create a cloned record using Clone() function of <strong>Microsoft.Xrm.Client<\/strong> Namespace:<\/p>\n<p>\/\/Add references<\/p>\n<p>using Microsoft.Crm.Sdk;<\/p>\n<p>using Microsoft.Xrm.Sdk;<\/p>\n<p>using OrganizationXrm;<\/p>\n<p>using Microsoft.Crm.Sdk.Messages;<\/p>\n<p>using Microsoft.Crm.Sdk.Samples;<\/p>\n<p>using Microsoft.Xrm.Sdk.Client;<\/p>\n<p>\/\/Used for Clone Function<\/p>\n<p>using Microsoft.Xrm.Client;<\/p>\n<p>&nbsp;<\/p>\n<p>\/\/Declare Variables<\/p>\n<p>Entity parentaccount= new Entity(\u201caccount\u201d);<\/p>\n<p>Guid parentaccountid = Guid.Empty;<\/p>\n<p>Entity childaccount;<\/p>\n<p>Guid childaccountid = Guid.Empty;<\/p>\n<p>&nbsp;<\/p>\n<p>try<\/p>\n<p>{<\/p>\n<p>\/\/Set attributes of the Parent Account<\/p>\n<p>parentaccount.Attributes[&#8220;name&#8221;] = &#8220;Parent Account&#8221;;<\/p>\n<p>parentaccount.Attributes[&#8220;telephone1&#8221;] = &#8220;Telephone1&#8221;;<\/p>\n<p>\/\/create the parent account<\/p>\n<p>parentaccountid = _service.Create(parentaccount);<\/p>\n<p>\/\/Clone the Account Record using Clone function;<\/p>\n<p>\/\/Clone function takes a bool parameter which relates the Related Entities of the parent<\/p>\n<p>\/\/record to the cloned records, if set to true.<\/p>\n<p>\/\/The bool parameter passed to Clone method is set to true by default.<\/p>\n<p>childaccount = parentaccount.Clone(true);<\/p>\n<p>\/\/Remove all the attributes of type primaryid as all the cloned records will have their own primaryid<\/p>\n<p>childaccount.Attributes.Remove(childaccount.LogicalName + &#8220;id&#8221;);<\/p>\n<p>\/\/Remove the telephone1 attribute from the cloned record to differentiate between the parent and cloned record<\/p>\n<p>childaccount.Attributes.Remove(&#8220;telephone1&#8221;);<\/p>\n<p>\/\/create the cloned record<\/p>\n<p>childaccountid = _service.Create(childaccount);<\/p>\n<p>}<\/p>\n<p>catch (SaveChangesException ex)<\/p>\n<p>{<\/p>\n<p>throw ex;<\/p>\n<p>}<\/p>\n<p><strong><span style=\"text-decoration: underline;\">Notes<\/span>:<\/strong><\/p>\n<ul>\n<li>It is limited to an On-Premise environment only.<\/li>\n<li>Add reference\u00a0<strong>Microsoft.Xrm.Client<\/strong>.<\/li>\n<li>Works with commonly used <strong>OOB and Custom<\/strong> entities.<\/li>\n<li>Removing primaryid attribute from the attribute collection of cloned instance is mandatory.<\/li>\n<\/ul>\n<p><strong>Cloning a record using JavaScript<\/strong><\/p>\n<p>Cloning a Dynamics CRM record is not only limited to a<strong>Custom Workflow<\/strong> or a <strong>Plug-in, <\/strong>the same functionality can be very well achieved in JavaScript with the below workaround.<\/p>\n<p>Below example explains how to Clone Line Items of one Quote onto another Quote.<\/p>\n<p><strong>1. Retrieve Data:<\/strong><\/p>\n<p>The first step to start off with is to retrieve the records that we need to clone\/copy.\u00a0 In this example since we are Cloning the Line Items, so we`ll retrieve all the Line Items of the Quote from which we need to Clone. All the retrieved Line Items will be stored in a variable called &#8220;retrievedProducts&#8221;. This variable will be later on used to \u201cCreate\u201d the Line Items for other Quote.<\/p>\n<p>\/\/Retrieve the Values<\/p>\n<p>XrmServiceToolkit.Rest.RetrieveMultiple<\/p>\n<p>(&#8220;QuoteDetailSet&#8221;,<\/p>\n<p>\/\/Here you can have some selected fields or all the fields<\/p>\n<p>options,<\/p>\n<p>function successCallback(results) {<\/p>\n<p>\/\/get the retrieved result in a variable<\/p>\n<p>retrievedProducts = results;<\/p>\n<p>},<\/p>\n<p>function errorCallback(error) {<\/p>\n<p>showError(error, functionName);<\/p>\n<p>},<\/p>\n<p>function onComplete() { },<\/p>\n<p>false);<\/p>\n<p><strong>2. Delete Extra Data<\/strong><\/p>\n<p>The next step is to remove the extra data. The extra data involves all the ID attributes that can create Duplicity issue. And, the &#8220;__metadata&#8221; attribute, this attribute contains extra data that is not needed for us to Clone the record and hence we`ll remove it. To remove the unwanted data from the &#8220;retrievedProducts&#8221; Object, we`ll use thedeletefunctionality.<\/p>\n<p>In this example the &#8220;deleteExtraData&#8221; function is called at the time of creating the records.<\/p>\n<p>\/\/This function deletes the extra data from the Object<\/p>\n<p>function deleteExtraData(retrievedObject) {<\/p>\n<p>\/\/Remove all the extra fields<\/p>\n<p>delete retrievedObject.__metadata;<\/p>\n<p>delete retrievedObject.QuoteId;<\/p>\n<p>delete retrievedObject.QuoteDetailId;<\/p>\n<p>&nbsp;<\/p>\n<p><strong>\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 <\/strong>\/\/Check for all the __metadata fields and remove it<\/p>\n<p>delete retrievedObject.__metadata;<\/p>\n<p>\/\/Loop through Objects in Object<\/p>\n<p>for (var key in retrievedObject) {<\/p>\n<p>if (retrievedObject.hasOwnProperty(key)) {<\/p>\n<p>\/\/Check if the value is null if it is null then do nothing<\/p>\n<p>if (retrievedObject[key] == null) {<\/p>\n<p>&nbsp;<\/p>\n<p>} else {<\/p>\n<p>\/\/Check the type is the type is object, remove metadata<\/p>\n<p>if (typeof (retrievedObject[key]) == &#8220;object&#8221;) {<\/p>\n<p>\/\/deletes the metadata from the object<\/p>\n<p>delete retrievedObject[key].__metadata;<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p><strong>3. Create the Record<\/strong><\/p>\n<p>The final step is the creation of the record. In this step we`ll loop through the retrieved values which in this example is stored in the variable &#8220;retrievedProducts &#8221; and create the Line Items one by one for the desired Quote. Since we have removed the Quote Id we need to associate a Quote Id.And, in this step we`ll pass the &#8220;retrievedProducts &#8221; Object to the\u00a0\u00a0\u00a0\u00a0 &#8220;deleteExtraData&#8221; function. And, the formatted value would be passed for the creation.<\/p>\n<p>for (var j in retrievedProducts) {<\/p>\n<p>\/\/Get the formatted value. formattedQuoteProduct is an Object.<\/p>\n<p>formattedQuoteProduct[j] = deleteExtraData(retrievedProducts[j]);<\/p>\n<p>\/\/Since we removed the Quote Id we need to associate it with another Quote Id as the Quote Line Items needs to have a Quote Id.<strong>newQuoteId\u00a0<\/strong>can be the Quote Id of the Quote on which you need to clone the Line Items<\/p>\n<p>formattedQuoteProduct[j].QuoteId = {<\/p>\n<p>Id: newQuoteId,<\/p>\n<p>LogicalName: &#8220;quote&#8221;<\/p>\n<p>};<\/p>\n<p>\/\/Create the products<\/p>\n<p>XrmServiceToolkit.Rest.Create(formattedQuoteProduct[j],<\/p>\n<p>&#8220;QuoteDetailSet&#8221;,<\/p>\n<p>function successCallback() { },<\/p>\n<p>function errorCallback(error) {<\/p>\n<p>showError(error, functionName);<\/p>\n<p>}, false);<\/p>\n<p>&nbsp;<\/p>\n<p>}<\/p>\n<p><strong><span style=\"text-decoration: underline;\">Creating a cloned record using fetch expression<\/span>:<\/strong><\/p>\n<p>We have introduced how to clone record using\u00a0 <strong>.Clone()<\/strong>function in On-Premise environment and also by using\u00a0 JavaScript and now we would like to introduce another method of cloning records which can be used in any environment and allows us to define the attributes to be replicated on the cloned record.<\/p>\n<p><strong><span style=\"text-decoration: underline;\">Working<\/span>: <\/strong><\/p>\n<p>At first, we will fetch the entity for which we have to clone the records and in the attributes, we will add only those attributes which we need to copy the cloned records.<\/p>\n<p>Here, we have taken the \u201cAccount\u201d entity of the CRM to create cloned records:<\/p>\n<p>string sourceqry = @&#8221;&lt;fetch version=&#8217;1.0&#8242; output-format=&#8217;xml-platform&#8217; mapping=&#8217;logical&#8217; distinct=&#8217;false&#8217;&gt;&#8221; +<\/p>\n<p>&#8220;&lt;entity name=&#8217;account&#8217;&gt;&#8221;+<\/p>\n<p>&#8220;&lt;attribute name=&#8217;name&#8217;\/&gt;&#8221;+<\/p>\n<p>&#8220;&lt;attribute name=&#8217;primarycontactid&#8217;\/&gt;&#8221;+<\/p>\n<p>&#8220;&lt;attribute name=&#8217;telephone1&#8217;\/&gt;&#8221;+<\/p>\n<p>&#8220;&lt;attribute name=&#8217;accountid&#8217;\/&gt;&#8221;+<\/p>\n<p>&#8220;&lt;order attribute=&#8217;name&#8217; descending=&#8217;false&#8217;\/&gt;&#8221;+<\/p>\n<p>&#8220;&lt;filter type=&#8217;and&#8217;&gt;&#8221;+<\/p>\n<p>&#8220;&lt;condition attribute=&#8217;name&#8217; operator=&#8217;eq&#8217; value=&#8217;XXXXXX&#8217;\/&gt;&#8221; +<\/p>\n<p>&#8220;&lt;\/filter&gt;&#8221;+<\/p>\n<p>&#8220;&lt;\/entity&gt;&#8221;+<\/p>\n<p>&#8220;&lt;\/fetch&gt;&#8221;;<\/p>\n<p>&nbsp;<\/p>\n<p>\/\/Declare an entity collection to hold the entities retreived by the query<\/p>\n<p>EntityCollection AccountsCollection = service.RetrieveMultiple(newFetchExpression(sourceqry));<\/p>\n<p>&nbsp;<\/p>\n<p>if (AccountsCollection.Entities.Count &gt; 0)<\/p>\n<p>{<\/p>\n<p>for (int count = 0; count &lt; AccountsCollection.Entities.Count; count++)<\/p>\n<p>{<\/p>\n<p>Entity account = AccountsCollection.Entities[count];<\/p>\n<p>&nbsp;<\/p>\n<p>\/\/Set the EntityState to null, so that a new cloned record can be created<\/p>\n<p>account.EntityState = null;<\/p>\n<p>&nbsp;<\/p>\n<p>\/\/remove the PrimaryId of the record<\/p>\n<p>account.Attributes.Remove(account.LogicalName + &#8220;id&#8221;);<\/p>\n<p>&nbsp;<\/p>\n<p>\/\/Set any field of the cloned record to differentiate between the parent and the cloned record<\/p>\n<p>account.Attributes[&#8220;name&#8221;] = &#8220;Cloned record created at: &#8221; + System.DateTime.Now;<\/p>\n<p>&nbsp;<\/p>\n<p>\/\/set a unique id to the cloned record<\/p>\n<p>account.Id = Guid.NewGuid();<\/p>\n<p>&nbsp;<\/p>\n<p>\/\/Create the new cloned record<\/p>\n<p>service.Create(account);<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>catch (SaveChangesException ex)<\/p>\n<p>{<\/p>\n<p>throw ex;<\/p>\n<p>}<\/p>\n<p>catch (FaultException&lt;OrganizationServiceFault&gt; ex)<\/p>\n<p>{<\/p>\n<p>throw ex;<\/p>\n<p>}<\/p>\n<p>catch (Exception ex)<\/p>\n<p>{<\/p>\n<p>throw ex;<\/p>\n<p>}<\/p>\n<p>In the above code snippet we have cloned the \u201cAccount\u201d entity records where name of the \u201cAccount\u201d is \u201cXXXXX\u201d and we have just added only few attributes in the fetch expression which we need to get copied to the new cloned records.<\/p>\n<p><strong><span style=\"text-decoration: underline;\">Note<\/span>:<\/strong><\/p>\n<ul>\n<li>Set the <strong>\u201cEntityState\u201d<\/strong> to<strong>\u201dnull\u201d<\/strong>.<\/li>\n<li>Remove the <strong>\u201cPrimaryId\u201d<\/strong> of the record.<\/li>\n<li>Any (<strong>OOB + Custom<\/strong>) entity can be cloned.<\/li>\n<\/ul>\n<p>Also, explore our 1 Click productivity app \u2013 <a href=\"https:\/\/www.inogic.com\/product\/productivity-apps\/click-2-clone-microsoft-dynamics-crm-records\">Click2Clone<\/a> \u2013 to copy\/clone Dynamics 365 CRM records in just a single click.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Very often we are troubled with writing huge codes and end up spending our valuable time for cloning\/copying Dynamics CRM entity record. Just imagine the time needed if you are asked to create a cloned record with more than 100 attributes. Don\u2019t you think it\u2019s a time-consuming effort and how great would it be if\u2026 <span class=\"read-more\"><a href=\"https:\/\/www.inogic.com\/blog\/2014\/08\/clone-records-in-dynamics-crm\/\">Read More &raquo;<\/a><\/span><\/p>\n","protected":false},"author":13,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[16,19],"tags":[],"class_list":["post-847","post","type-post","status-publish","format-standard","hentry","category-dynamics-365","category-dynamics-crm"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.inogic.com\/blog\/wp-json\/wp\/v2\/posts\/847","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.inogic.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.inogic.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.inogic.com\/blog\/wp-json\/wp\/v2\/users\/13"}],"replies":[{"embeddable":true,"href":"https:\/\/www.inogic.com\/blog\/wp-json\/wp\/v2\/comments?post=847"}],"version-history":[{"count":0,"href":"https:\/\/www.inogic.com\/blog\/wp-json\/wp\/v2\/posts\/847\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.inogic.com\/blog\/wp-json\/wp\/v2\/media?parent=847"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.inogic.com\/blog\/wp-json\/wp\/v2\/categories?post=847"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.inogic.com\/blog\/wp-json\/wp\/v2\/tags?post=847"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}