Mastering SharePoint Online Integration: A Step-by-Step Guide to Connect with Business Central using C# and AL

Several weeks ago, I had to work on SharePoint Online integration with Business Central, involving a somewhat complex folder structure. Finding the exact information on the web was quite a challenge (for me). So let's simplify it here incase anyone else ends up stuck.

Steps

  1. Create the sharepoint addin.

  2. Creating the Middleware.

  3. Create custom Business central sharepoint handler.

  4. Create global sharepoint documents page.

  5. Link with the necessary Business central pages.

Step 1 ;

To integrate to sharepoint online, one requires a registered add-in. This provides the client ID and secret which enables us to generate auth token for the API requests.

The steps to follow here are:

  1. Register add-in at appregnew.aspx page in SharePoint.

  2. Click on the “Generate” “Client Id” button and “Client secret” button. And enter below details as like the screenshot:

Then click on the “Create” button.

  1. Grant permissions to the addin.

For this procedure, I won't go into details since "SP Doctor" has explained it so well in this article: (4 Steps Sharepoint Online data access). (The article saved me. Follow it for setting up the addin. In case of challenges, reach out to me I'll gladly help.)

NOTE: In a case where there are several sites in a sharepoint tenant, for some cases you will need to add the permissions at both tenant and site level.

Step 2 ;

Prerequisites - Knowledge working with C# and .NET Core web APIs. Postman is a plus for testing the APIs.

Let's build the middleware , (Business central's AL code http is not yet where we may need it to be) So I built a middleware using .NET Core Web API with C#.

For this step to be successful, you should have followed the article in step 1 above to success.

In Visual studio create a new .NET Core Web API project. Right click on the controllers folder on the project structure and add a new empty web api controller and name it SharepointController or a name of your choice. Ensure there is controller after the name e.g OthernameController.cs. Add the following for the required packages.

using Microsoft.AspNetCore.Mvc;

using SharepointOnlineIntegration;

using System.Text.Json;

using Newtonsoft.Json;

using System.Text.Json.Nodes;

using Microsoft.Extensions.Configuration;

using System.Net.Http.Headers;

using SharepointOnlineIntegration.Models;

using System.Net;

using Newtonsoft.Json.Linq;

using Microsoft.SharePoint.Client;

using Microsoft.SharePoint;

If any of the packages is missing add using the package manager.

Now let's handle the access token. We create a class for the response and the function to generate the token.

Add this class before [ApiController] [Route("[controller]")] public class SharepointController : ControllerBase - Lines of code.

public class AccessTokenResponse {

[JsonProperty("token_type")]

public string TokenType { get; set; }

[JsonProperty("expires_in")]

public int ExpiresIn { get; set; }

[JsonProperty("not_before")]

public long NotBefore { get; set; }

[JsonProperty("expires_on")]

public long ExpiresOn { get; set; }

[JsonProperty("resource")]

public string Resource { get; set; }

[JsonProperty("access_token")]

public string AccessToken { get; set; }

}

Create the token function:
Refer to your results from step 1 to obtain the values of clientid, clientsecret, resource and the tenantId.

This function should give us the token we need to access other API resources.

Now we handle the file upload logic: - we will pass the file as base64.

Let's create a class to handle our responses: - Right-click on the project and add a class named Config. Add the code below:

Let's create a model for our requests: - In the project directory create a folder called Models. Add a class called FileUpload:

public class FileUpload

{

public string? FileName { get; set; }

public string? FileContent { get; set; }

public string? FolderName { get; set; }

}

This will handle the request body. For example

Now we create the function to upload. I have kept it simple for easier understanding. You can edit the code to loop through the folders while checking and creating them according to your desired folder structure. Check your Library name.

Next we need to add code to handle downloading our uploaded files.

Create another function as follows:

Delete the uploaded files:

To delete a file we need the following piece of code:

Security ( Optional but important).

Go to the solution explorer and add a folder called "MiddleWare" inside the project directory. Add a class called ApiKeyMiddleware.cs and add the following code:

In the AppSettings.json add the following to define the API key:

"XApiKey": "AbcdYourApiKey123",

Notes

  1. Ensure you follow Step 1 until you have the desired results as is in the provided link.

  2. Note your library name.

  3. Understand how sharepoint works in general.

Step 3 ;

In this step we create an handler codeunit to consume the APIs we created in the above step.

In visual studio code under your MSDBC365 project create a codeunit and name it Sharepoint Integration Handler. Create a function to handle http requests as follows:
Remember to separate the enum.

The CallWebService function Logic is from a blog whose name I've forgotten.

Create the function to execute various request actions: (the function names are distinctive)

You can remove the unused variables.

Create the necessary Setup tables.

Step 4 ;

Create the following objects:

Clean the uneccessary fields and variables. Modify the structure according to your requirements. Add code to handle multiple tables in the UploadDocumentForTheRecord and OpenForRecReference functions as shown in the exmples. Be keen on Keys. Create the sharepoint setup page with the necessary fields.

Step 5 ;

With everything set to this point, we need to link our sharepoint documents page to pages in business central.

Go to a page whose setup is done and table is added in the functions in step 4 and add the following page action:

   action("Upload Sharepoint Attachment&")
                {
                    ApplicationArea = All;
                    Caption = 'Upload Attachment';
                    Image = Attach;
                    Promoted = true;
                    PromotedCategory = Category7;   
                    trigger OnAction()
                    var
                        pgDocAttachment: Page "Sharepoint Documents";
                        RecRef: RecordRef;
                    begin
                        Clear(pgDocAttachment);
                        RecRef.GetTable(Rec);
                        pgDocAttachment.OpenForRecReference(RecRef);
                        pgDocAttachment.RunModal;
                    end;
                }

When the action is clicked it opens the sharepoint documents page. To upload drilldown on the file name field and select a file of your choice.

You can find the .NET Core WebAPI source code:
https://github.com/MuriungiMartin/SharepointOnlineIntegration

Hope this helps. Happy coding!