Integrate SharePoint with Salesforce?

This is the era of cloud. Everything everywhere is connected with each other via cloud hosted web services and people can access these services from anywhere in globe, anytime. Such are the powers of cloud. But is everything really connected as is expected?

Not every cloud based service can be connected with every other service, but fortunately most popular Apps can be integrated. And so can Salesforce and Microsoft SharePoint be integrated – two of the most popular Software-as-a-Service (SaaS) products.

However it is not that simple. In this post we are going to discuss different ways by which you can integrate Salesforce with SharePoint. But first let us identify why would you even need to integrate the two?

Why Salesforce SharePoint Integration?

SharePoint is a very robust content management and document management platform used by all kinds of companies, mainly for storing business related documents and content. It is mostly used as a secure document repository for intranet portals, websites, cloud based services, and of course as independent repository as well. However it is mostly used by businesses using other Microsoft Office products like Excel and Word to create documents. Now since they belong to the same product family, the created documents can be easily exported to SharePoint.

Salesforce on the other hand is a huge SaaS platform used by millions of companies to manage their business processes. It mainly started as a Customer Relationship Management Platform but thanks to its versatility regarding integrations and extensions along with a boost in its ever-growing list of features, it has evolved into a complete sales, marketing and support business process management platform and can be used for many many kind of analysis for businesses.

However it was never known for its document storage capabilities. You can store documents there but it charges quite high fees for storage and is not as robust as Microsoft 365 in this aspect.

So why not simply integrate the two? Most companies having a Microsoft 365 account don’t want to spend more on Salesforce storage. So integration remains the best option.

Salesforce SharePoint Integration Using Microsoft Azure Service

There are a number of ways you can integrate SharePoint with Salesforce. However Microsoft has not released any API to facilitate direct Salesforce SharePoint interactions so we need to involve a third-party adapter or service. The different ways are:

  • Integrating using a third party system installed adapter
  • Integrating using a Microsoft Azure hosted service.
  • Integrating using a third party integration service.

The first way involves building a third-party adapter that had to be physically installed on a computer system and therefore severely limits the cloud based capabilities. The third way involves using a paid or even free integration service, it is easy to use but it is not as flexible as a custom adapter and may prove to be a security risk. Moreover the main point of integration was to save cost so paying to save cost needs to properly analyzed.

So the best cloud integration method left is to use a Microsoft Azure hosted service to integrate your Salesforce and SharePoint.

This method involves multiple steps

  • Step 1: Salesforce sends authentication request to the Adapter.
  • Step 2: The Adapter passes on the request to the SharePoint.
  • Step 3: SharePoint authenticates the information and passes on a security token for further use.
  • Step 4: The adapter receives the token and passes on the token to Salesforce.
  • Step 5: Using the token as an authentication key, Salesforce then send request to view specific or all accessible files and folders.
  • Step 6: The Adapter passes on the request along with the token and receives an output which it again passes on to the Salesforce installation.
  • Step 7: Either the token expires and the process is repeated again, or using the same token more requests are sent and received.
Salesforce integration with Sharepoint


It seems simple when I present the steps like this but in reality if the coder is experienced and careful it’s just as simple.

How Salesforce Performs Step 1
The main point for cloud based integration is to host a running service on Microsoft’s cloud app platform Azure, and leveraging it to interact with SharePoint. Since the service is hosted on a cloud platform, we usually access it via web-based URL. So our methods from Salesforce side to request authentication token look something like this:

01public static String getToken(){
02    String token;
03    if(!Test.isRunningTest()){
04        token = SharePointAPIUtility.SharePointAPIGet('http://testingalgoworks.azurewebsites.net/Api/Values/GetAuthToken','[email protected]','TestingPassword');
05    }
06    system.debug('token>>> '+token);
07    if(token != null){
08        return EncodingUtil.urlEncode(token.replaceAll('"',''), 'UTF-8');
09    }
10    return null;
11}
12
13public static String SharePointAPIGet(String endpointUrl,String username, String password){
14    try{
15        HttpRequest httpRequestObject = new HttpRequest();
16        httpRequestObject.setEndPoint(endpointUrl);
17        httpRequestObject.setmethod('GET');
18        Blob headerValue = Blob.valueOf(username + ':' + password);
19        String authorizationHeader = 'BASIC ' + EncodingUtil.base64Encode(headerValue);
20        httpRequestObject.setHeader('Authorization', authorizationHeader);
21        httpRequestObject.setTimeout(120000);
22        system.debug('httpRequestObject>> '+httpRequestObject);
23        Http http = new Http();
24        HttpResponse httpResponse ;
25        if(!test.isRunningTest())
26            httpResponse = http.send(httpRequestObject);
27        if(httpResponse != null && httpResponse.getStatus() == 'OK' && httpResponse.getStatusCode() == 200){
28            system.debug('httpResponse.getBody();>>>>'+httpResponse.getBody()+'httpResponse.getBody();>>>>');
29            return httpResponse.getBody();
30        }else if(httpResponse != null){
31            return 'SharePoint Server Error: Status '+ httpResponse.getStatus()+' Status Code '+ httpResponse.getStatusCode() +' Body '+httpResponse.getBody();
32        }
33    }catch(CalloutException ce){
34        throw ce;
35    }catch(Exception ex){
36        throw ex;
37    }
38    return null;
39}

This code hits the Azure service using the URL and receives the authentication token which the Azure service sends.

We will come to the steps 2,3 and 4 right after the 5th:

How Salesforce Performs Step 5
Once Salesforce has authentication token, it uses that to request files and folders from the adapter. Once again it uses the Azure service URL to hit the service.

Here’s a method to request files and a method to request folders

01   public static List<String> getAllFolders(SharePoint365APIParser objSharePoint365APIParser){
02        try{
03            list<String> objFolders = new list<String>();
04            if(objSharePoint365APIParser.folders != null && objSharePoint365APIParser.folders.size()>0)//null check
05                for(SharePoint365APIParser.folders sp:objSharePoint365APIParser.folders){
06                    objFolders.add(sp.name);
07                }
08            return objFolders;
09        }catch(Exception ex){
10            throw ex;
11        }
12        return null;
13}
14
15    public static List<String> getFilesByFolder(String folderName, SharePoint365APIParser objSharePoint365APIParser){
16        //if(!test.isRunningTest()){
17            try{
18                if(objSharePoint365APIParser.folders != null && objSharePoint365APIParser.folders.size()>0)
19                for(SharePoint365APIParser.folders sp:objSharePoint365APIParser.folders){
20                    if(sp.name.equalsIgnoreCase(folderName)){
21                        if(sp.files.size() > 0){
22                            return sp.files;
23                        }else{
24                            return new list<String>();
25                        }
26                    }
27                }
28            }catch(Exception ex){
29                throw ex;
30            }
31        //}//end running test loop
32        return null;
33    }

How Azure Performs Step 2, 3, and 4
Once Salesforce has sent the request for authentication token, here’s how Azure platform service authenticates login.

01[HttpPost]
02      public bool Login(string email, string password)
03      {
04             //throw new Exception("This is error!!");
05             bool validateLogin = false;
06             List<string> MessageList = new List<string>();
07             //string decryptedPassword = Encryption.Decrypt(encryptedPassword);
08             if (email == ConfigurationManager.AppSettings["Email"] && password == ConfigurationManager.AppSettings["Password"])
09             {
10             string authInfo = email + ":" + password;
11             authInfo = Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(authInfo));
12             //authInfo = Encryption.Encrypt(authInfo);
13             System.Web.HttpContext.Current.Response.AppendHeader("Authorization""Basic " + authInfo);
14             // Insert User Token
15             MessageList.Add("Login Successful");
16             validateLogin = true;
17             }
18             else
19             {
20             MessageList.Add("Invalid Username Or Password");
21             }
22             return validateLogin;
23      }

How Azure service handles Step 6
Now that Salesforce has authentication token and is logged in on SharePoint, here’s how our Azure service parses the request for file and folder lists.

01[AuthorizeWebAPI()]
02       [HttpGet]
03       public Folders GetResourceData()
04       {
05              Folders fld = new Folders();
06              try
07              {
08
09                using (ClientContext clientContext = new ClientContext("https://yourprojectname.SharePoint.com/Resources"))
10                {
11                     SecureString passWord = new SecureString();
12
13                     foreach (char c in "TestPassword".ToCharArray()) passWord.AppendChar(c);
14
15                     clientContext.Credentials = new SharePointOnlineCredentials("[email protected]", passWord);
16
17                     Web rootweb = clientContext.Web;
18
19                     var folders =
20       rootweb.GetFolderByServerRelativeUrl("/Resources").Folders;
21                     string pString = @"\Resources\";
22
23                   clientContext.Load(folders);
24                     clientContext.ExecuteQuery();
25                     fld.folders = new List<Folders>();
26                     fld.name = "Resources";
27                     foreach (Microsoft.SharePoint.Client.Folder myFolder in folders)
28                     {
29                     fld.folders.Add(GetFoldersAndFiles(myFolder, clientContext, pString));
30                     }
31              }
32
33            }
34              catch (Exception)
35              { fld.name = "Some error happened."; }
36              return fld;
37
38       }
39
40       private Folders GetFoldersAndFiles(Microsoft.SharePoint.Client.Folder mainFolder, ClientContext clientContext, string pathString)
41       {
42              Folders fldr = new Folders();
43              List<string> fls = new List<string>();
44              fldr.folders = new List<Folders>();
45              clientContext.Load(mainFolder, k => k.Files, k => k.Folders);
46         clientContext.ExecuteQuery();
47              foreach (var folder in mainFolder.Folders)
48              {
49              string folderPath = string.Format(@"{0}{1}\", pathString, folder.Name);
50              if (folder.Name != "Forms")
51                     fldr.folders.Add(GetFoldersAndFiles(folder, clientContext, folderPath));
52              }
53
54              foreach (var file in mainFolder.Files)
55              {
56              fls.Add(file.Name);
57              }
58
59              fldr.files = fls;
60              if (mainFolder.Name != "Forms")
61              fldr.name = mainFolder.Name;
62
63              return fldr;
64
65       }

As you may see, we have saved all our content on SharePoint as resources and the service retrieves the data from that resource folder.

How To Display SharePoint Files

Now the integration won’t be as effective if we are not able to display the retrieved files somewhere. In our experience it is best to retrieve files using Salesforce and create a separate Visualforce page to display the retrieved files. Using SharePoint’s inbuilt features it is very easy to display retrieved files. You just have to embed a single line of code in your Visualforce page.

Embedded office control

1/code

To retrieve single file you would also need your Azure service. That code would look something like this:

01public ActionResult DisplayFile(string filePath, string token)
02       {
03
04            try
05              {
06              var decrypt = new Encryption();
07              DateTime dt = new DateTime();
08              if (DateTime.TryParse(decrypt.Decrypt(token), out dt))
09              {
10                     if (DateTime.UtcNow.Subtract(new TimeSpan(0, 3, 0)) < dt &&
11                     DateTime.UtcNow.Add(new TimeSpan(0, 3, 0)) > dt)
12                     {
13                         var filename = Path.GetFileName(filePath);
14                     var dirName = Path.GetDirectoryName(filePath);
15                     var contentType = "application/octet-stream";
16                     var localFilePath = Server.MapPath("~/SharedDownloads/");
17                     var localFileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + "_" + filename;
18                     var wholePath = Path.Combine(localFilePath, localFileName);
19                     ValuesController api = new ValuesController();
20
21                     (from f in new DirectoryInfo(localFilePath).GetFiles()
22                           where f.CreationTime < DateTime.Now.Subtract(TimeSpan.FromMinutes(30))
23                           select f).ToList()
24                      .ForEach(f => f.Delete());
25
26                     using (ClientContext clientContext = new ClientContext("https://yourprojectname.SharePoint.com/Resources"))
27                     {
28                           SecureString passWord = new SecureString();
29
30                           foreach (char c in "TestPassword".ToCharArray()) passWord.AppendChar(c);
31
32                           clientContext.Credentials = new SharePointOnlineCredentials("[email protected]", passWord);
33
34                               Web rootweb = clientContext.Web;
35                           Microsoft.SharePoint.Client.File file = rootweb.GetFileByServerRelativeUrl(filePath);
36                           clientContext.Load(file);
37                           clientContext.ExecuteQuery();
38                           contentType = GetMimeType(Path.GetExtension(filePath));
39                           api.DownloadFile(clientContext, filePath, localFilePath, localFileName);
40                         }
41                     return View(new FileModel { FileName = "/SharedDownloads/" + localFileName, ContentType = contentType });
42                     }
43              }
44              }
45              catch (Exception)
46              {
47               return View(new FileModel { FileName = "Error" });
48              }
49              return View(new FileModel { FileName = "Error" });
50       }

Using Salesforce Files Connect

Salesforce and Microsoft, in an obvious strategy of mutual benefit went into an extended partnership. On December 17 Salesforce launched its new features via Salesforce Files Connect. It was released after much research and is touted as a method to integrate Microsoft 365 products as well as Microsoft OneDrive. For CRM license holders this service is available for free in limited capacity of course, and can be used to integrate Salesforce with SharePoint directly. But since it’s a new service it’s still not tested for the most optimum performance and security standards by third party users. We here at Algoworks have an immense experience with such third party service integration services- both system based and Azure service based. We can safely assume that in the near future Files Connect would be the dominant way to integrate both SaaS platforms.

Cheers!!!

Oh hi there 👋
It’s nice to meet you.

Sign up to receive awesome content in your inbox, every month.

We don’t spam! Please check your mail for confirmation.

Leave a Comment

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

Select Language »