Sample Code to create and associate Folder / SharePoint Document Location (Dataverse /Dynamics 365 / SharePoint Online)


Below is our sample record for a custom table custom_contract for which we will be creating the folder in SharePoint and associated it with this record using the SharePoint Document Location record. We’d use the same naming pattern that CRM uses i.e. Name + ”_” + ”GUID”

A screenshot of a chat

Description automatically generated

Below we have passed the details of the record along with CrmServiceClient and SharePoint’s client context.

A screenshot of a computer code

Description automatically generated

The below code will first check if there is already a SharePoint Document Location created by CRM using ends with GUID condition. If it doesn’t exist, we are using the name field plus GUID of the record to create the folder in SharePoint and then associate using SharePoint Document Location record. Also we have used Regex to make sure we replace the special characters with “-“ similar to what CRM does. We are also checking if the Folder exists with that name in SharePoint before creating one.

Below is the GUID / record we have specified while creating the SharePoint Document Location record, the SharePoint Document location configured for that particular table.

A screenshot of a computer

Description automatically generated

The sample code –

  var authManager = new AuthenticationManager(applicationId, certPath, password, domain);
            ClientContext clientContext = authManager.GetContext(siteUrl);

            var serviceClient = new CrmServiceClient(connection);
            if (serviceClient.IsReady == true)
            {
                var myCRMRecord = serviceClient.Retrieve("custom_contract", 
                    new Guid("f655304e-045b-ef11-bfe2-000d3a9b4e06"), new ColumnSet("custom_name"));
                CheckIfShareDocLocationExistElseCreateandAssociate(myCRMRecord, serviceClient, clientContext);
            }

 private static void CheckIfShareDocLocationExistElseCreateandAssociate(Entity myCrmRecord, CrmServiceClient serviceClient, ClientContext clientContext)
        {
            var querySharePointDocumentLocation = new QueryExpression("sharepointdocumentlocation");
            querySharePointDocumentLocation.ColumnSet.AddColumns("name", "relativeurl", "parentsiteorlocation", "regardingobjectid");
            querySharePointDocumentLocation.Criteria.AddCondition("regardingobjectid", ConditionOperator.Equal, myCrmRecord.Id);
            querySharePointDocumentLocation.Criteria.AddCondition("relativeurl", ConditionOperator.EndsWith, myCrmRecord.Id);
            var result = serviceClient.RetrieveMultiple(querySharePointDocumentLocation);
            if (result.Entities.Count == 0)
            {                
                var folderName = myCrmRecord.Attributes["custom_name"].ToString();
                // this makes sure we replace the special characters with - similar to what CRM does when autocreating the record.
                string regexPattern = @"[~#%&*:<>?/\\{|}.""-]";
                string replacement = "-";
                folderName = Regex.Replace(folderName, regexPattern, replacement) + "_" + myCrmRecord.Id.ToString().ToUpper();
                var folderRelativeURL = "custom_contract/" + folderName;

                Web currentWeb = clientContext.Web;
                var folderExists = currentWeb.DoesFolderExists(folderRelativeURL);
                if (!folderExists)
                {
                    var list = clientContext.Web.Lists.GetByTitle("Documents");
                    list.RootFolder.Folders.Add(folderRelativeURL);
                    clientContext.ExecuteQuery();
                }

                var documentLocation = new Entity("sharepointdocumentlocation");
                documentLocation["name"] = "Documents on Default Site 1";
                documentLocation["relativeurl"] = folderName;
                // specifying the GUID of the SharePoint Document Location configured for that table
                documentLocation["parentsiteorlocation"] = new EntityReference("sharepointdocumentlocation", new Guid("cf97e6d8-0b4e-ef11-a317-6045bdd74f46"));
                documentLocation["regardingobjectid"] = new EntityReference("custom_contract", myCrmRecord.Id);
                serviceClient.Create(documentLocation);
            }
        }

The result –

A screenshot of a computer

Description automatically generated

Also refer –

Hope it helps..

Advertisements


Discover more from Nishant Rana's Weblog

Subscribe to get the latest posts sent to your email.

Unknown's avatar

Author: Nishant Rana

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

One thought on “Sample Code to create and associate Folder / SharePoint Document Location (Dataverse /Dynamics 365 / SharePoint Online)”

Please share your thoughts

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

Discover more from Nishant Rana's Weblog

Subscribe now to keep reading and get access to the full archive.

Continue reading

Power Platform Puzzles

D365 CRM, Power Platform Tips &Tricks

Power Spark

Power Spark By Shrangarika

Van Carl Nguyen

Exploration of Power Platform

My Trial

It is my experience timeline.

Power⚡Thomas

Sharing my knowledge and experience about the Microsoft Power Platform.

Arpit Power Guide

a guide to powering up community

Welcome to the Blog of Paul Andrew

Sponsored by Cloud Formations Ltd

Deriving Dynamics 365

Deriving Solutions and features on Power Platform/Dynamics 365

The CRM Ninja

Thoughts & musings from a Microsoft Business Applications Ninja!

D CRM Explorer

Learn about Microsoft Dynamics CRM Power Platform customization and implementation and other cool stuffs

Stroke // Jonas Rapp

I know pre-stroke. I will improve who I was.

Power Melange

Power Melange By Shalinee

Clavin's Blog - PPUG.ORG

AI - Power Automate - Power Apps - SharePoint Online - Azure - Nintex - K2 - Artificial Intelligence

Sat Sangha Salon

An Inquiry in Being

The Indoencers

The Influencers & Influences of Indian Music

Monika Halan's blog

Hand's-free money management

D365 Demystified

A closer look at Microsoft Dynamics 365.

Microsoft Mate (msftmate) - Andrew Rogers

Experienced consultant primarily focused on Microsoft Dynamics 365 and the Power Platform

Manmit Rahevar's Blog

One Stop Destination for Microsoft Technology Solutions

MG

Naturally Curious

Brian Illand

Power Platform and Dynamics 365

Steve Mordue

The Professional Paraphraser

Subwoofer 101

Bass defines your home theater

SQLTwins by Nakul Vachhrajani

SQL Server tips and experiences dedicated to my twin daughters.

Everything D365

Discovering Azure DevOps and D365 Business Applications

Tech Wizard

Lets do IT Spells

XRM Tricks (Power Platform & Dynamics CRM )

Power Platform & Dynamics CRM

CRM TIPS BY PRM

Mail to crmtipsbyprm@gmail.com for queries and suggestions

nijos.dev

Giving back to the community what I have learned

Power Platform Learning

Your Go-To Resource for Power Apps, Power Automate & More

xrm CRM Dynamics

Dynamics CRM Technical & Functional Info

Dynamics 365 Blogs - Explained in unique way

Sometimes you need to look at things from different perspective.