Inkey Solution Logo
banner

Blogs

Upload document to SharePoint from Microsoft D365 CE using C# Web API & manage SharePoint document metadata

, March 20, 2019 9881 Views

The integration of Microsoft D365 CE with SharePoint has enabled the document management in SharePoint precisely in the form of folders and subfolders, in a structured way.

Today in this blog, let’s learn how we can upload the documents in SharePoint from the D365 CE using the Dot Net c# web API code with a secured authentication using the Azure Web App.

Example: Upload the documents, which are attached with the Notes in D365 CE to the SharePoint folder.

For this, we are creating a CRM plug-in to execute on the create of Notes record in D365 CE. This will then invoke the Dot Net Web API, where we authorize and authenticate the SharePoint user in Azure and process further to upload the document in SharePoint using the metadata by a secured authentication of the Azure web App.

Below is the plug-in code that is executed on the creation of Notes record in D365 CE:

  • Web App & SharePoint authentication:
//Specify the web App authentication credentials here
AuthenticationResponse authenticationResponse = Common.GetWebAPIAuthenticationResponse(clientId, resourceId, appKey, aadInstance, iTracingService);

HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authenticationResponse.access_token);

      //Specify the SharePoint metadata details here
      object parameters = new
      {
       SiteUrl = SharePointConnectorURL,
       ListName = documentCategoryText,
       FolderURL = SharePointDocumentURL,
       FileContent = documentBody,
       FileName = SharePointDocumentName,
       TaxonomyFields = taxonomyFields,
       StandardFields = standardFields
      };
  • Send the object to the Web API hosted in Azure by converting it into JSON format:
StringContent stringContent = new StringContent(JsonConvert.SerializeObject(parameters), Encoding.UTF8, "application/json");

HttpResponseMessage httpResponseMessage = httpClient.PostAsync(string.Format("{0}/Api/UploadDocuments/Post", apiBaseAddress), stringContent).Result;

Then create a Dot Net Web API project and add the following parameters into the model class:

public class UploadDocuments
{
 public string SiteUrl { get; set; }
 public string ListName { get; set; }
 public string FolderURL { get; set; }
 public string FileContent { get; set; }
 public string FileName { get; set; }
 public Dictionary<String, String> TaxonomyFields { get; set; }
 public Dictionary<String, String> StandardFields { get; set; }
}

Next, we need to create a controller class for authenticating and getting a connection to the SharePoint site. Provide the valid credentials for the connection using “CloudConfigurationManager”.

And, don’t forget to use the proper namespaces for connecting with Azure like “Microsoft.Azure”, “Microsoft.SharePoint.Client”, “Microsoft.SharePoint.Client.Taxonomy”.

Credentials:

string UserName = CloudConfigurationManager.GetSetting("UserName");
string Password = CloudConfigurationManager.GetSetting("UserPassword");

Create an object of ClientContext with the siteUrl & credentials of SharePoint:

ClientContext clientContext = new ClientContext(parameters.SiteUrl);
clientContext.Credentials = new SharePointOnlineCredentials(UserName, ConvertToSecureString(Password));

Create an object of Web class:

Web clientWebContext = clientContext.Web;

Get the file content as below:

byte[] file = Convert.FromBase64String(parameters.FileContent);

FileCreationInformation newFile = new FileCreationInformation();
newFile.ContentStream = new MemoryStream(file);
newFile.Url = parameters.FileName;
newFile.Overwrite = true;

Upload the file to SharePoint:

List documents = clientWebContext.Lists.GetByTitle(parameters.ListName);
Microsoft.SharePoint.Client.File uploadFile;
if (string.IsNullOrWhiteSpace(parameters.FolderURL) == true)
{ 
 uploadFile = documents.RootFolder.Files.Add(newFile); 
}
else
{
 Folder targetFolder = clientWebContext.GetFolderByServerRelativeUrl(parameters.FolderURL);
 uploadFile = targetFolder.Files.Add(newFile);
}
clientContext.Load(uploadFile, uf => uf.ListItemAllFields);

clientContext.ExecuteQuery();
ListItem item = uploadFile.ListItemAllFields;
clientContext.Load(item);

 

I hope this helps you.


 

Insert data into Many-to-Many relationship in Dynamics CRM very easily & quickly, using the Drag and drop listbox.
http://www.inkeysolutions.com/what-we-do/dynamicscrmaddons/drag-and-drop-listbox

Comply your Lead, Contact, and User entities of D365 CRM with GDPR compliance using the GDPR add-on.
https://www.inkeysolutions.com/microsoft-dynamics-365/dynamicscrmaddons/gdpr

Create a personal / system view in Dynamics CRM with all the fields on the form/s which you select for a particular entity using the View Creator.
http://www.inkeysolutions.com/what-we-do/dynamicscrmaddons/view-creator

mm

Inkey

INKEY is your solution partner.
Our focus is to deliver you in-time intelligent innovative solutions ("key") for the problems in hand. Maintaining a quality standard right from the inception of a project is our top most priority.

Our team of talented professionals will execute your projects with dedication and excellence. We take ownership and accountability for the effort that goes into meeting our client’s needs.

Years of experience and proven success of delivering innovative custom solutions.

More posts by

2 responses to “Upload document to SharePoint from Microsoft D365 CE using C# Web API & manage SharePoint document metadata”

  1. Tobias says:

    hi,

    can you provide the complete plugin-project? how do you manage all the 3rd-party-references in the plugin? usually this is not allowed, is it?

    • Admin says:

      Dear Tobias,

      It would be difficult for us to provide you the complete project. There are no 3rd Party references for this implementation. Only couple of DLLs references are needed and we’ve already specified the name of those DLLs in our blog, “Microsoft.Azure”, “Microsoft.SharePoint.Client”, “Microsoft.SharePoint.Client.Taxonomy”.

      It is allowed to take references of such Dlls in CRM plug-in.

      Feel free to ask if you have any further questions.

Leave a Reply

Your email address will not be published. Required fields are marked *

The maximum upload file size: 2 MB. You can upload: image, audio, video, document, spreadsheet, interactive, text, archive, code, other. Drop file here

Would you like to digitize your business and put it on the cloud?
Do you need clear, concise reports for your organization?