How to Upload Files to SharePoint from Business Central Using AL and Microsoft Graph API

How to Upload Files to SharePoint from Business Central Using AL and Microsoft Graph API



Uploading documents from Business Central to SharePoint is a common requirement for businesses aiming to streamline document management. Microsoft Graph API provides an efficient way to integrate these services. This blog explains the implementation using AL code.

Overview

We'll demonstrate how to:

  • Authenticate using OAuth2.

  • Prepare file content in Business Central.

  • Upload the file directly to SharePoint using the Microsoft Graph API.

Step-by-Step Explanation

1. Authentication

To communicate securely with SharePoint, you must obtain an OAuth token:

procedure GetOAuthToken() AuthToken: SecretText
var
    ClientID: Text;
    ClientSecret: Text;
    TenantID: Text;
    AccessTokenURL: Text;
    OAuth2: Codeunit OAuth2;
    Scopes: List of [Text];
begin
    ClientID := 'your-client-id';
    ClientSecret := 'your-client-secret';
    TenantID := 'your-tenant-id';
    AccessTokenURL := 'https://login.microsoftonline.com/' + TenantID + '/oauth2/v2.0/token';
    Scopes.Add('https://graph.microsoft.com/.default');
    if not OAuth2.AcquireTokenWithClientCredentials(ClientID, ClientSecret, AccessTokenURL, '', Scopes, AuthToken) then
        Error('Failed to get access token: %1', GetLastErrorText());
end;

Replace placeholders (ClientID, ClientSecret, TenantID) with your actual Azure App Registration details.

2. Preparing and Uploading the File

Using the obtained token, upload the file:

procedure UploadFilesToSharePoint(DocAttach: Record "Document Attachment")
var
    HttpClient: HttpClient;
    HttpRequestMessage: HttpRequestMessage;
    HttpResponseMessage: HttpResponseMessage;
    Headers: HttpHeaders;
    RequestContent: HttpContent;
    AuthToken: SecretText;
    SharePointFileUrl: Text;
    ResponseText: Text;
    OutStream: OutStream;
    FileContent: InStream;
    TempBlob: Codeunit "Temp Blob";
    FileName: Text;
    TenantMedia: Record "Tenant Media";
    MimeType: Text;
begin
    AuthToken := GetOAuthToken();
    if AuthToken.IsEmpty() then
        Error('Failed to obtain access token.');

    if DocAttach."Document Reference ID".HasValue then begin
        TempBlob.CreateOutStream(OutStream);
        DocAttach."Document Reference ID".ExportStream(OutStream);
        TempBlob.CreateInStream(FileContent);
        FileName := DocAttach."File Name" + '.' + DocAttach."File Extension";
        if TenantMedia.Get(DocAttach."Document Reference ID".MediaId) then
            MimeType := TenantMedia."Mime Type";
    end;

    SharePointFileUrl := 'https://graph.microsoft.com/v1.0/sites/{site-id}/drives/{drive-id}/root:/' + FileName + ':/content';

    HttpRequestMessage.SetRequestUri(SharePointFileUrl);
    HttpRequestMessage.Method := 'PUT';
    HttpRequestMessage.GetHeaders(Headers);
    Headers.Add('Authorization', SecretStrSubstNo('Bearer %1', AuthToken));
    Headers.Add('Content-Type', MimeType);
    HttpRequestMessage.Content.WriteFrom(FileContent);

    if HttpClient.Send(HttpRequestMessage, HttpResponseMessage) then begin
        if HttpResponseMessage.IsSuccessStatusCode() then
            Message('File uploaded successfully.');
        else begin
            HttpResponseMessage.Content.ReadAs(ResponseText);
            Error('Failed to upload files to SharePoint: %1 %2', HttpResponseMessage.HttpStatusCode(), ResponseText);
        end;
    end else
        Error('Failed to send HTTP request to SharePoint');
end;

Replace {site-id} and {drive-id} with the specific details from your SharePoint instance.

Summary

By following these steps, you've set up a seamless integration between Business Central and SharePoint. Leveraging the Microsoft Graph API simplifies document handling significantly.


Reference to Yun Zhu for guidance and inspiration.


Comentarios

Entradas populares de este blog

How to Merge PDF Files in Business Central Using a Python API

Join two or more PDFs into one in Business Central

How to Print Multiple Copies in Report in AL of Microsoft Dynamics 365 Business Central