How to integrate Salesforce with Sharepoint

Salesforce is an amazing platform when it comes to sales, marketing and business process management.

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

That’s why a lot of companies prefer to simply integrate Salesforce with Sharepoint to get the most benefits from both.

If you want to walk this path, you should know that there are two primary ways to make the integration possible – by using Microsoft Azure service or with the help of Files Connect.

Salesforce SharePoint Integration Using Microsoft Azure Service

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

How does Salesforce send authentication request to the Adapter – 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.

Because the service is hosted on a cloud platform, we usually access it via web-based URL.

The way for Salesforce to request authentication token is by using the following code:

public static String getToken() {
String token;
if(!Test.isRunningTest()) {
token = SharePointAPIUtility.SharePointAPIGet('https://testingalgoworks.azurewebsites.net/Api/Values/GetAuthToken','[email protected]','TestingPassword');
}
system.debug('token>>> '+token);
if(token != null) {
return EncodingUtil.urlEncode(token.replaceAll('"',''), 'UTF-8');
}
return null;
}
public static String SharePointAPIGet(String endpointUrl,String username, String password) {
try {
HttpRequest httpRequestObject = new HttpRequest();
httpRequestObject.setEndPoint(endpointUrl);
httpRequestObject.setmethod('GET');
Blob headerValue = Blob.valueOf(username + ':' + password);
String authorizationHeader = 'BASIC ' + EncodingUtil.base64Encode(headerValue);
httpRequestObject.setHeader('Authorization', authorizationHeader);
httpRequestObject.setTimeout(120000);

system.debug('httpRequestObject>> '+httpRequestObject);

Http http = new Http();
HttpResponse httpResponse ;

if(!test.isRunningTest())
httpResponse = http.send(httpRequestObject);
if(httpResponse != null && httpResponse.getStatus() == 'OK' && httpResponse.getStatusCode() == 200) {
system.debug('httpResponse.getBody();>>>>'+httpResponse.getBody()+'httpResponse.getBody();>>>>');
return httpResponse.getBody();
}
else if(httpResponse != null) {
return 'SharePoint Server Error: Status '+ httpResponse.getStatus()+' Status Code '+ httpResponse.getStatusCode() +' Body '+httpResponse.getBody();
}
} catch(CalloutException ce) {
throw ce;
} catch(Exception ex) {
throw ex;
}
return null;
}

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

How does Salesforce request files and folders from the adapter – with the help of the authentication token Salesforce request files and folders from the adapter.

To do that it uses the Azure service URL to hit the service.

So here’s how to request files and how to request folders.

public static List getAllFolders(SharePoint365APIParser objSharePoint365APIParser){
try {
list objFolders = new list();
if(objSharePoint365APIParser.folders != null && objSharePoint365APIParser.folders.size()>0) //null check
for(SharePoint365APIParser.folders sp:objSharePoint365APIParser.folders) {
objFolders.add(sp.name);
}
return objFolders;
} catch(Exception ex) {
throw ex;
}
return null;
}
public static List getFilesByFolder(String folderName, SharePoint365APIParser objSharePoint365APIParser) {
//if(!test.isRunningTest()) {
try{
if(objSharePoint365APIParser.folders != null && objSharePoint365APIParser.folders.size()>0)
for(SharePoint365APIParser.folders sp:objSharePoint365APIParser.folders) {
if(sp.name.equalsIgnoreCase(folderName)) {
if(sp.files.size() > 0) {
return sp.files;
} else {
return new list();
}
}
}
} catch(Exception ex) {
throw ex;
}
//}//end running test loop

return null;
}

How does Azure platform service authenticate login – the next step after sending the request for the authentication token is for Azure platform service authenticates login.

Here’s how to do that:

[HttpPost]
public bool Login(string email, string password) {
//throw new Exception("This is error!!");
bool validateLogin = false;
List MessageList = new List();
//string decryptedPassword = Encryption.Decrypt(encryptedPassword);
if (email == ConfigurationManager.AppSettings["Email"] && password == ConfigurationManager.AppSettings["Password"]) {
string authInfo = email + ":" + password;
authInfo = Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(authInfo));
//authInfo = Encryption.Encrypt(authInfo);
System.Web.HttpContext.Current.Response.AppendHeader( "Authorization", "Basic " + authInfo);
// Insert User Token
MessageList.Add("Login Successful");
validateLogin = true;
}
else {
MessageList.Add("Invalid Username Or Password");
}
return validateLogin;
}
How Azure service does parses the request for file and folder lists – so at this point Salesforce has authentication token and is logged in on SharePoint.
The next step is for the Azure service to parse the request for file and folder lists.
[AuthorizeWebAPI()]
[HttpGet]
public Folders GetResourceData() {
Folders fld = new Folders();
try {
using (ClientContext clientContext = new ClientContext("https://yourprojectname.SharePoint.com/Resources"))
{
SecureString passWord = new SecureString();
foreach (char c in "TestPassword".ToCharArray())
passWord.AppendChar(c);

clientContext.Credentials = new SharePointOnlineCredentials("[email protected]", passWord);
Web rootweb = clientContext.Web;
var folders = rootweb.GetFolderByServerRelativeUrl("/Resources").Folders;
string pString = @"\Resources\";
clientContext.Load(folders);
clientContext.ExecuteQuery();
fld.folders = new List();
fld.name = "Resources";
foreach (Microsoft.SharePoint.Client.Folder myFolder in folders)
{
fld.folders.Add(GetFoldersAndFiles(myFolder, clientContext, pString));
}
}
}
catch (Exception)
{
fld.name = "Some error happened."; }
return fld;
}
private Folders GetFoldersAndFiles(Microsoft.SharePoint.Client.Folder mainFolder, ClientContext clientContext, string pathString) {
Folders fldr = new Folders();
List fls = new List();
fldr.folders = new List();
clientContext.Load(mainFolder, k => k.Files, k => k.Folders);
clientContext.ExecuteQuery();
foreach (var folder in mainFolder.Folders)
{
string folderPath = string.Format(@"{0}{1}\", pathString, folder.Name);
if (folder.Name != "Forms")
fldr.folders.Add(GetFoldersAndFiles(folder, clientContext, folderPath));
}
foreach (var file in mainFolder.Files)
{
fls.Add(file.Name);
}
fldr.files = fls;
if (mainFolder.Name != "Forms")
fldr.name = mainFolder.Name;
return fldr;
}

As a result of all of these steps so far, you will see that you have successfully saved all our content on SharePoint as resources.
Not only has that but, the service retrieved the data from that resource folder as well.

How to display Sharepoint files – to have an effective integration you should be able to display your retrieved files somewhere.

The best option is to retrieve files using Salesforce and create a separate Visualforce page to display the retrieved files.

You can very easily display these received files using SharePoint’s inbuilt features.

To do that you need to embed a single line of code in your Visualforce page.

Embedded office control

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

public ActionResult DisplayFile(string filePath, string token)
{
try
{
var decrypt = new Encryption();
DateTime dt = new DateTime();
if (DateTime.TryParse(decrypt.Decrypt(token), out dt))
{
if (DateTime.UtcNow.Subtract(new TimeSpan(0, 3, 0)) < dt && DateTime.UtcNow.Add(new TimeSpan(0, 3, 0)) > dt)
{
var filename = Path.GetFileName(filePath);
var dirName = Path.GetDirectoryName(filePath);
var contentType = "application/octet-stream";
var localFilePath = Server.MapPath("~/SharedDownloads/");
var localFileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + "_" + filename;
var wholePath = Path.Combine(localFilePath, localFileName);
ValuesController api = new ValuesController();
(from f in new DirectoryInfo(localFilePath).GetFiles()
where f.CreationTime < DateTime.Now.Subtract(TimeSpan.FromMinutes(30)) select f).ToList() .ForEach(f => f.Delete());
using (ClientContext clientContext = new ClientContext("https://yourprojectname.SharePoint.com/Resources"))
{
SecureString passWord = new SecureString();
foreach (char c in "TestPassword".ToCharArray())
passWord.AppendChar(c);
clientContext.Credentials = new SharePointOnlineCredentials("[email protected]", passWord);
Web rootweb = clientContext.Web;
Microsoft.SharePoint.Client.File file = rootweb.GetFileByServerRelativeUrl(filePath);
clientContext.Load(file);
clientContext.ExecuteQuery();
contentType = GetMimeType(Path.GetExtension(filePath));
api.DownloadFile(clientContext, filePath, localFilePath, localFileName);
}
return View(new FileModel { FileName = "/SharedDownloads/" + localFileName, ContentType = contentType });
}
}
}
catch (Exception)
{
return View(new FileModel { FileName = "Error" });
}
return View(new FileModel { FileName = "Error" });
}

Integrating Salesforce and SharePoint using Files Connect

Because of the growing demand for an easier integration Salesforce created Files Connect.

Files Connect is a tool that allows you to integrate SalesForce with Sharepoint much more easily.

With its help you can access files from external locations and use it in standard SFDC objects like Accounts and Cases, or custom Salesforce objects.

So here’s how to integrate Salesforce and SharePoint using Files Connect:

Enabling Salesforce Files Connect – before anything else you should enable Files Connect. To do that you need to go to Build-> Customize -> Salesforce Files -> Settings -> Files connect.

There you need to click on Edit and select Enable Files Connect.

Enable the ‘copy’ option if you’d like to share files with Salesforce users that don’t have similar access to SharePoint or don’t have access to SharePoint at all.

User access permissions for File Connect – after this, you need to setup user permissions for Files Connect.

If you’d like to use permission sets for managing user permissions, then go to Permission Set -> System Permissions -> Edit
After this select “Files Connect Cloud” and click Save.

If you’d like to use on premise SharePoint version like SharePoint 2010 or 2013, you would have to select “Files Connect On-Premises”.

When you go to “Manage Assignments” you can check which users has the above-configured permission. All users that you want to have access to SharePoint must have permission set configured in their user profile.

You also need to check if the profile that the users are connected to have permissions to access the tool.

To check that go to the Files Connect Cloud permissions settings in the “Profile” section.

Creating an Auth Provider – the next step is to setup the auth provider. To do that go to Quick Find in setup and find Auth Provider.

After that click on “New”.

Once you do that, you would need to select the “Provider Type”.

To connect SharePoint select Microsoft Access control Services.

Here you will need to fill out the following info:

  • Name
  • URLSuffix
  • Consumer Key
  • Consumer Secret
  • Authorize Endpoint URL
  • Token Endpoint URL

Then click Save and you would be directed to an Auth Provider Detail screen. On that screen you will see “Callback URL” which you will need to copy because we’re going to use it later.

Configuration in SharePoint – login to your SharePoint instance and go to any Site Collection that you want to connect.

Be sure you write down the site collection path, as you would need it later.

So in order to configure SharePoint, you would need to create a small Microsoft 365 app.

To do that you would need to go to the URL https://[your company name].SharePoint.com/[site collection path]/_layouts/15/appregnew.aspx
As a result an App Information page will be opened.

Select an app running on a server and click on Generate button in front of Client ID.

Use the same steps to generate Client Secret and name it as you’d like.

As a result of doing this, your App domain becomes your Salesforce domain. Check the subdomain of your SFDC instance and with that as the prefix, input the App Domain values.

In Redirect URL put the callback URL that you have from creating an Auth Provider.

Finally, click on “Create” to create the app. As a result, you will be directed to a new page displaying the newly generated and inputted values.

SharePoint App Configuration – in this step you would need to configure the newly created app.

To do that go to the following URL https://[your company name].SharePoint.com/[site collection path]/_layouts/15/appinv.aspx

As a result, a new form will be opened.

In AppID you need to fill in the client ID that you generated when you configured SharePoint.

After this click on click on Lookup.

This will auto-populate the values of other boxes except Permission Request XML.

The value of Permission Request XML, as the title suggest, defines the level of access the connecting application will have in respecting to accessing SharePoint files collections.

The standard input here is

Here you have 3 options for Scope:

https://SharePoint/content/sitecollection/web – this lets SFDC users to access a single site collection, though you cannot access the subsites.

https://SharePoint/content/sitecollection – This is used to allow access to single site collection along with all its subsites.

https://SharePoint/content/tenant – This is used to allow access to all site collections.

ReConfiguring Salesforce Files Connect – so after you have created and configured our SharePoint App, you also need to reconfigure your Salesforce Files Connect settings.

To do that you need to first Reopen Salesforce Files Connect.

In the field of Consumer Key, enter the value corresponding with Client ID in SharePoint.

Consumer Secret here is Client Secret that you generated in SharePoint in the previous step.

In the field of Authorize Endpoint URL you would have to enter the value https://[your company name].sharepoint.com/[site collection path]/_layouts/15/OauthAuthorize.aspx

In the field of Token Endpoint URL, enter the value https://accounts.accesscontrol.windows.net/[your company name].onmicrosoft.com/tokens/OAuth/2?resource=00000003-0000-0ff1-ce00-000000000000/[your company name].sharepoint.com@[your company name].onmicrosoft.com

Write the name and the label you want and be sure to remember them. You would need them later.

After clicking save, you will successfully configure and create your Auth Provider in Salesforce.

Creating External Data Source – here you need to create an external data source in Salesforce.

To do that go to Setup -> Build -> Develop -> External Data Source and click on New External Data Source.

In Type Select Files Connect: SharePoint Online.

In the URL you can add SharePoint Site collection URL or the sub-site collection URL, depending on which one you are connecting with Salesforce.

For Identity type select Per User and for Authentication Protocol select OAuth 2.0.

In Authentication Provider, click on lookup and select the Authentication Provider you have created in the previous steps.
You can choose any name and label you want. However, it’s best if they are similar names to authentication provider and other apps.

After you do this, don’t forget to click on save.

Configuring Permission Sets –
your last step is to enable the external data source in permission set.

To do that go to Permission set -> External Data Source -> Edit.

Then you need to Select and add the newly created data source to the Enabled External Data Source section. Do this and click Save.

After you do this, each of your user with same permission sets with now see SharePoint in External Files tab.

In Conclusion

The integration between Salesforce and Sharepoint is not as easy as it looks.

Your best options are to either use Microsoft Azure Service or Files Connect

In all cases, if you’re not tech-savvy, it’s better to ask a knowledgeable developer for help.

That way you will know for sure that the integration has been done the right way without worrying about making mistakes and messing things up.

What do you think about integrating Salesforce and Sharepoint? Do you plan on doing it? Let us know in the comments below.