How to – Clone a record in Dataverse / Dynamics 365 (C#)


Here we will be cloning the below contact record –

For it, we can make use Clone method of EntityExtensions class

If we run the below code, we will get the “Cannot insert duplicate key” exception.

Because we need to set the ID for the newly cloned record to either empty or a new GUID.

Also, we need to remove the contactid attribute or entity’s id field else we will get the below exception – “Entity Id must be the same as the value set in property bag

Also if we are retrieving all the attributes we need to make sure we remove those attribute which can cause below unique constraint errors.

Sql error: The operation attempted to insert a duplicate value for an attribute with a unique constraint. CRM ErrorCode: -2147012606 Sql ErrorCode: -2146232060 Sql Number: 2627

In case of contact, we had to remove the address id attributes, to get the record cloned.

Now let us clone the same contact record with its related leads.

  • Here first we need to retrieve contact along with its associated lead record.
  • Then remove the id attribute that could duplicate issues in the child lead records also.

Please refer the helpful posts –

https://debajmecrm.com/clone-record-dynamics-crm-clone-method/

https://www.inogic.com/blog/2014/08/clone-records-in-dynamics-crm/

https://dyncrmexp.com/2017/10/24/retrieve-primary-entities-along-with-related-entities-with-one-queryexpression/comment-page-1/

https://dynamict.eu/2016/08/09/create-record-with-related-records-in-a-single-request-using-c/

Hope it helps..

 // related lead records of contact
                    QueryExpression query = new QueryExpression("lead");                    
                    query.ColumnSet = new ColumnSet(true);

                    // contact and lead - 1 - n relationship
                    Relationship relationship = new Relationship("lead_parent_contact");
                    relationship.PrimaryEntityRole = EntityRole.Referenced;

                    RelationshipQueryCollection relatedEntity = new RelationshipQueryCollection();
                    relatedEntity.Add(relationship, query);

                    RetrieveRequest request = new RetrieveRequest();
                    request.RelatedEntitiesQuery = relatedEntity;
                    request.ColumnSet = new ColumnSet(true);
                    request.Target = new EntityReference("contact", new Guid("ca0aa844-57c6-ec11-a7b6-00224826af1e"));

                    RetrieveResponse response = (RetrieveResponse)svc.Execute(request);
                    var contactToBeCloned = response.Entity;                   
                    var clonedContact = contactToBeCloned.Clone(true);

                    // remove attribute that can cause error from main entity             
                    clonedContact.Id = Guid.NewGuid();
                    clonedContact.Attributes.Remove("contactid");                    
                    clonedContact.Attributes.Remove("address1_addressid");
                    clonedContact.Attributes.Remove("address2_addressid");
                    clonedContact.Attributes.Remove("address3_addressid");

                    // remove attribute that can cause error from child / related entities
                    foreach (var relatedEntities in clonedContact.RelatedEntities)
                    {
                        foreach(var leadEntity in relatedEntities.Value.Entities)
                        {
                            leadEntity.Id = Guid.NewGuid();
                            leadEntity.Attributes.Remove("leadid");
                            leadEntity.Attributes.Remove("address1_addressid");
                            leadEntity.Attributes.Remove("address2_addressid");
                        }
                    }
                    svc.Create(clonedContact);
Advertisements

How to – Use Import Column to Upload files to File Column / Attribute in SSIS KingswaySoft(Dynamics 365 / CRM)


A few weeks back had posted on how to upload files to the File Column type field using KingswaySoft’ s Integration Toolkit and Premium Flat File Source and Premium Derived column which are part of the SSIS Productivity Pack of KingswaySoft

https://nishantrana.me/2022/03/17/how-to-upload-files-from-file-column-attribute-using-ssis-kingswaysoft-dynamics-365-crm/

Here we will see an example of achieving the same without using the KingswaySoft Productivity Pack’s Premium Flat File Source and Derived column. (although would recommend using it as it includes over 300 premium components making it easier to rapidly build efficient solutions)

https://www.kingswaysoft.com/products/ssis-productivity-pack

Below is our source file

The contact records in CRM

Below is how the package looks like

The Flat File Source points to the location where we have the source csv file containing email, file path, and file name.

Import Column takes the File Path as the Input.

For the Input and Output properties, add an output column (BinaryColumn) of DataType = image.

In the FilePath input column properties, specify the column id of the output column.

Finally, in the CDS / CRM Destination Component, we are performing an upsert using the Email id as a match.

Here we have mapped the output column of the Import Column i.e. BinaryColumn to the binary content field of the file type attribute of the CRM.

Let us now run the package.

Let us now open the records and check.

As expected we can see the file uploaded.

Also, check out –

To extract attachments from notes-https://nishantrana.me/2021/02/10/extracting-attachments-from-notes-in-dynamics-365-dataverse/

To download files using Download Block Requesthttps://nishantrana.me/2022/03/14/how-to-download-file-from-file-column-using-initializefileblocksdownload-and-downloadblock-request-dynamics-365-crm-dataverse/

To upload files using Upload Block Requesthttps://nishantrana.me/2022/03/15/how-to-upload-file-to-file-column-using-initializefileblocksupload-and-uploadblock-request-dynamics-365-crm/

Understand File and Image Data Typehttps://nishantrana.me/2021/10/01/using-file-and-image-data-type-in-dataverse-dynamics-365/

Try out the wonderful, feature-rich, and powerful SSIS Integration Toolkit for Dynamics 365 by KingswaySofthttps://www.kingswaysoft.com/products/ssis-integration-toolkit-for-microsoft-dynamics-365/download

Check other articles on SSIS plus CRM – https://nishantrana.me/2018/11/26/ssis-and-microsoft-dynamics-365/

Hope it helps..

Advertisements

How to – Use Script Component to Upload files to File Column / Attribute in SSIS – KingswaySoft (Dynamics 365 / CRM)


A few weeks back had posted on how to upload files to the File Column type field using KingswaySoft’ s Integration Toolkit and Premium Flat File Source and Premium Derived column which are part of the SSIS Productivity Pack of KingswaySoft

https://nishantrana.me/2022/03/17/how-to-upload-files-from-file-column-attribute-using-ssis-kingswaysoft-dynamics-365-crm/

Here we will see an example of achieving the same without using the KingswaySoft Productivity Pack’s Premium Flat File Source and Derived column. (although would recommend using it as it includes over 300 premium components making it easier to rapidly build efficient solutions for different scenarios)

https://www.kingswaysoft.com/products/ssis-productivity-pack

Here we will be using Script Component to read the file from the path and convert it to DT_IMAGE.

Below is our source file

The contact records in CRM

Below is how the package looks like

The Flat File Source points to the location where we have the source CSV file containing email, file path, and file name.

Script Component has File Path and File Name as the input.


Add a column using Add Column in the Output Columns, with Data Type as image [DT_IMAGE]


Click on Edit Script..

Add the below code to read the bytes from the file path and add it to the output column.

Finally, in the CDS / CRM Destination Component, we are performing an upsert using the Email id as a match.

Here we have mapped the output column of the Import Column i.e. DerviedFileContent to the binary content field of the file type attribute of the CRM.

Let us now run the package.

Let us now open the records and check.

As expected we can see the file uploaded.

Also, check out –

To extract attachments from notes-https://nishantrana.me/2021/02/10/extracting-attachments-from-notes-in-dynamics-365-dataverse/

To download files using Download Block Requesthttps://nishantrana.me/2022/03/14/how-to-download-file-from-file-column-using-initializefileblocksdownload-and-downloadblock-request-dynamics-365-crm-dataverse/

To upload files using Upload Block Requesthttps://nishantrana.me/2022/03/15/how-to-upload-file-to-file-column-using-initializefileblocksupload-and-uploadblock-request-dynamics-365-crm/

Understand File and Image Data Typehttps://nishantrana.me/2021/10/01/using-file-and-image-data-type-in-dataverse-dynamics-365/

Try out the wonderful, feature-rich, and powerful SSIS Integration Toolkit for Dynamics 365 by KingswaySofthttps://www.kingswaysoft.com/products/ssis-integration-toolkit-for-microsoft-dynamics-365/download

Check other articles on SSIS plus CRM – https://nishantrana.me/2018/11/26/ssis-and-microsoft-dynamics-365/

Hope it helps..

Advertisements

Import Data (Import Data Wizard) – Few key points


Let us understand a few points about the Import Data feature with a simple example –

Say for example we have exported the following 4 records.

The exported file will have the view name along with the timestamp.

The exported file – 

It has 3 hidden columns that allow for re-import of these records possible.

1st column contains the GUID of the record, the second contains the Row Checksum which it uses to make sure to update only those records or rows which are changed, and the 3rd column is Modified On which it uses to track if the record has been modified since it was exported.

Now let us update one of the records we exported inside CRM.

On importing the same file,

as expected we get 1 failure.

Error message – “You cannot import data to this record because the record was updated in Microsoft Dynamics 365 after it was exported” for the same record which we updated inside the app.

Now let us update one of the records (which has a possible duplicate) and re-import the file.

During import, we have let the Allow Duplicates settings be default i.e. No.

This time also apart from the previous error we get one partial failure.

The error message says – “A record was not created or updated because a duplicate of the current record already exists.

This is because the record that was modified and imported was having another record having the same email id, triggering our duplicate detection rules. Also, we had specified Allow Duplicates as No while importing the file.

This time let us set Allow Duplicates as Yes and try the import with the same file.

As expected there was no partial error this time.

And the record got updated this time.

Another point to remember is if we export and import the file without any changes, or for the rows with no modification, it will not perform any action, i.e. trigger a create/update for any of the records.

For tracking the changes, as we mentioned earlier it uses the Row Checksum column’s hash value.

Now let’s update the GUID of the record in the 1st row (changed b to c in the end) and the modified date (changed to 55 from 53 minute part) for the 4th row and see the results.

As expected both these records failed – 1st one where we changed the GUID with the error message – “The record could not be updated because the original record no longer exists in Microsoft Dynamics 365” and the 4th row with the error that “You cannot import data to this record because the record was updated in Microsoft Dynamics 365 after it was exported” as we had changed the Modified Date in the imported excel file.

Lastly, let us restore the original value of those 2 fields of the hidden columns and try the import to see the results.

As expected we do not get any error for those 2 rows as we had restored the original value.

  • For .zip files 32 MB is the max size limit for other file types i.e. xlsx, csv, txt and xml it is 8 MB.

G

  • Microsoft recommends import to be limited to 20K rows or fewer.

Just in case we are interested to see how the data validation works especially for the option set field in the exported excel file from CRM.

Select the field in excel and open the Data Validation from the Data tab, which refers to the hiddenSheet.

To see the hiddenSheet, right-click the worksheet and select the View Code option.

It opens the VBA window, where we can select the hiddenDataSheet object and change its Visible property to -1-xlsSheetVisible.

Back in our excel, we can see the hiddenSheet visible and the values of our option-set fields.

Hope it helps..

Advertisements

Fixed – Unable to add record type ‘Lead’. It is invalid to create component msdyn_decisioncontract with the same export value as an existing component in Unified Routing (Dynamics 365)


Recently while trying to enable Unified Routing on Lead table/ entity we got the below error.

“Unable to add record type ‘Lead’. It is invalid to create component msdyn_decisioncontract with the same export value as an existing component

The issue was that the we forgot to enable the unified routing on lead before migrating lead related unified routing records in that environment, from the development environment.

So as per the details in the error message, we found the below record and deleted it.

After deletion it allowed us to enabled the Unified routing on Lead as shown below.

Hope it helps..

Advertisements

Run as option in When a row is added, modified or deleted trigger – Power Automate


Let us see Run As option of When a row is added, modified or deleted trigger in action, to understand its behavior.

Below is our example flow – it triggers when a field on the case is updated and then it updates the lead record.

Here we have not specified any value for Run as for When a row is added, modified or deleted trigger step.

On updating a case record using the User 1 account who is also the Flow Owner, we can see the modified user as User 1 for the lead record.

Let us trigger the flow this time through User 2.

This time also modified by for the lead record is User 1, even though the Modifying User and Row Owner were different.

So if Runs as is not specified, the Microsoft Dataverse actions are performed using the context of the Flow Owner.

To test it further let us remove the update rights of User 1, who is the flow owner, and trigger the flow again using User 2.

As expected the flow run fails this time.

Principal with id 7252e222-c07f-ec11-8d22-000d3a98d479 does not have WriteAccess right(s) for record with id 8ce6c6de-1bff-e411-80d4-c4346bac4730 of entity lead

Not let us specify Run as = Modifying User this time, and trigger the flow using User 2 again. (we have restored the rights of User 1)

This time also we can see the modified by the user as User 1 (Nishant Rana) the flow owner.

For it to run under the context of the user set as “Run As” in When a row is added, modified or deleted trigger, we need to select the Use invoker’s connection setting for the Update a row step.

Let us trigger the flow again through User 2, remember we have Run As set as modifying user.

Interestingly it still shows User 1 as the Modified By user.

Let us again remove the write rights of User 1 and trigger the flow using User 2.

This time flow is successful. If you remember it failed last time when we removed the User 1 rights and the Run as was default Flow Owner.

And this time, it shows modified by as User 2. (as we can see for user 1, the record is read-only as we have the rights removed)

This time it worked because had set Run As as Modifying User and specified Use invoker’s connection for the subsequent step i.e. update a row in this case, so it used User 2’s context which modified the case record to trigger the flow, which in turn updated the lead record using user 2’s context.

Now it will fail if User 1 updates the case record and triggers the flow because it will try to update the lead record using its context i.e. Run as = modified by

We will observe a similar behavior with Run As = Row Owner.

In case the owner of the record is a team, instead of a user, then it falls back to the flow owner option.

Get all the details here – https://docs.microsoft.com/en-us/power-automate/dataverse/create-update-delete-trigger#user-impersonation-using-run-as

Also check – https://d365demystified.com/2020/10/30/run-as-context-in-cds-current-environment-flow-trigger-power-automate/

Hope it helps..

Advertisements
%d bloggers like this: