Programmatically create folders and upload files in SharePoint Server 2013 through Plug-in/Workflow

By | October 13, 2015

Introduction:

Dynamics CRM has native integration with Sharepoint so that Sharepoint can be used as the document management tool for Microsoft Dynamics CRM. The Document management integration however is restricted to associating Dynamics CRM Records to Sharepoint folders and displaying them from within Dynamics CRM. All files need to be uploaded manually by the user through the Documents tab within Dynamics CRM forms.

Apart from these documents, often if you have email integration enabled, you may receive emails with attachments that are being stored with Dynamics CRM database. This increases the size of the database. One ask often is to be able to move the attachments to an external folder/location so that it does not use up the SQL database space and in case of CRM Online, save CRM space available for your organization.

Sharepoint is quite often the choice in these cases and this requires to setup an automation that would copy the attachments as and when important emails with attachments are received.

Connect to Sharepoint:

There are multiple ways in which we can connect to SharePoint.

1. Using “Client Context” as shown below.

using (ClientContext clientContext = new ClientContext(defaultSiteURL))

{

SecureString secureString = new SecureString();

foreach (char c in password.ToCharArray()) secureString.AppendChar(c);

clientContext.Credentials = new SharePointOnlineCredentials(userName, secureString);

Web web = clientContext.Web;

clientContext.Load(web);

clientContext.ExecuteQuery();

}

Limitation:

In order to make the connection using above code, we need external SharePoint libraries such as “Microsoft.SharePoint.Client.dll” and “Microsoft.SharePoint.Client.Runtime.dll

While registering the plug-in, we also need to merge these libraries with the plug-in.

Even after margining these libraries when trying to register the plugin in Sandbox mode we received below error and therefore this method probably does not support CRM Online.

System.Security.Permissions.EnvironmentPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089′ failed

2. Using REST is the other method available for connecting with Sharepoint. We don’t need to merge these external libraries in order to connect to SharePoint.

Create Folder in Sharepoint

Below code is used to create the folder to the SharePoint.

String relativePath = “lead/test lead_ 9a81460e-bf69-e511-80f3-c4346bad3608”;

Uri spSite = new Uri(“https://testOrganization.sharepoint.com”);

You need to create a token by providing the user name and password. This has been handled in the library by Scott Durrow.

string odataQuery = “_api/web/folders”;

byte[] content = ASCIIEncoding.ASCII.GetBytes(@”{ ‘__metadata’: { ‘type’: ‘SP.Folder’ }, ‘ServerRelativeUrl’: ‘” + relativePath + “‘}”);

Uri url = new Uri(String.Format(“{0}/{1}”, spSite, odataQuery));

var webRequest = (HttpWebRequest)HttpWebRequest.Create(url);

//Create the digest and pass the digest to header as shown below

webRequest.Headers.Add(“X-RequestDigest”, digest);

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);

request.Method = “POST”;

request.Accept = “application/json;odata=verbose;charset=utf-8”;

request.AllowAutoRedirect = false;

request.ContentLength = content.Length;

using (Stream s = request.GetRequestStream())

{

s.Write(requestContent, 0, requestContent.Length);

s.Close();

}

HttpWebResponse response = (HttpWebResponse)request.GetResponse();

StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(“utf-8”));

byte[] responseStream = Encoding.UTF8.GetBytes(sr.ReadToEnd());

string response = Encoding.UTF8.GetString(responseStream, 0, responseStream.Length);

Upload file in SharePoint

Below code is used to upload the file to a specific folder. In below example, we are uploading the file to the lead folder.

string defaultSite = “https:// testOrganization.sharepoint.com”;

string leadLibraryName = “lead”;

string destLocation = “Test Lead_9a81460e-bf69-e511-80f3-c4346bad3608”;

string filename= “Test File”;

byte[] content;

Uri spSite = new Uri(defaultSite);

You need to create a token by providing the user name and password. This has been handled in the library by Scott Durrow.

content = fileContent;

Uri url = new Uri(String.Format(“{0}/_api/web/GetFolderByServerRelativeUrl(‘/{1}’)/Files/add(url='{2}’, overwrite=true)”, defaultSite, leadLibraryName + “/” + destLocation, fileName));

var webRequest = (HttpWebRequest)HttpWebRequest.Create(url);

//Create the digest and pass the digest to header as shown below

webRequest.Headers.Add(“X-RequestDigest”, digest);

webRequest.ContentLength = fileContent.Length;

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);

request.Method = “POST”;

request.Accept = “application/json;odata=verbose;charset=utf-8”;

request.AllowAutoRedirect = false;

request.ContentLength = content.Length;

using (Stream s = request.GetRequestStream())

{

s.Write(requestContent, 0, requestContent.Length);

s.Close();

}

HttpWebResponse response = (HttpWebResponse)request.GetResponse();

StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(“utf-8”));

byte[] responseStream = Encoding.UTF8.GetBytes(sr.ReadToEnd());

string response = Encoding.UTF8.GetString(responseStream, 0, responseStream.Length);

Available Libraries for Sharepoint Connection

We found Sharepoint Library designed by Scott Durrow at https://code.msdn.microsoft.com/SharePoint-Integration-c5f21604#content.

This library helped us understand and accomplish the task of automating CRM Online integration with Sharepoint Online.

Cut short 90% of your manual work and repetitive data entry!

Get 1 Click apps and say goodbye to all repetitive data entry in CRM –
Click2Clone – Clone/Copy Dynamics 365 CRM records in 1 Click
Click2Export – Export Dynamics 365 CRM Report/CRM Views/Word/Excel template in 1 Click
Click2Undo – Undo & Restore Dynamics 365 CRM data in 1 Click

2 thoughts on “Programmatically create folders and upload files in SharePoint Server 2013 through Plug-in/Workflow

  1. Kartik

    Can you please let me know How to create digest and what is the requestContent?

    1. inogic

      Hi Kartik,

      You can check this link which is also included in our blog which will help you to understand the digest value.

      Let us know if you still have any query.

      Thanks!
      Sam

Comments are closed.