This class allows a Salesforce Developer to leverage the sFiles application to code custom behavior. The API allows the developer to create, delete and update metadata fields for files and folders.
Constructors
global ClientApi()
Initializes the class. This class is only available to organizations with the API Access permission enabled. All method in the ClientApi class require that namedCredentialName, sharepointSiteId and documentLibraryId are all set to valid values. All methods in ClientApi will make callouts, so you cannot execute any DML operations prior to calling a method. Be sure to reserve DML operations until after ClientApi methods are complete.
In the example below, notice that these values can be pulled from either the SharePoint Settings or SharePoint Object Settings metadata types.
Example
//get auth info from the Settings MDTfileforcem1__SharePoint_Settings__mdtorgSettings=[SELECTfileforcem1__Named_Credential__c,fileforcem1__Document_Library_Id__c,fileforcem1__Site_Id__cFROMfileforcem1__SharePoint_Settings__mdtWHEREDevelopername='Default'limit1];//get the root folder id for the account objectfileforcem1__SharePoint_Object_Settings__mdtobjectSettings=[SELECTfileforcem1__Root_Folder_Id__c,fileforcem1__Site_Id__c,fileforcem1__Document_Library_Id__c,fileforcem1__Named_Credential__cFROMfileforcem1__SharePoint_Object_Settings__mdtWHEREMasterLabel='Account'LIMIT1];//Initialize the client objectfileforcem1.ClientApiapiClient=newfileforcem1.ClientApi();apiClient.namedCredentialName=String.isNotBlank(objectSettings.fileforcem1__Named_Credential__c)?objectSettings.fileforcem1__Named_Credential__c:orgSettings.fileforcem1__Named_Credential__c;apiClient.sharepointSiteId=objectSettings.fileforcem1__Site_Id__c;apiClient.documentLibraryId=objectSettings.fileforcem1__Document_Library_Id__c;
Fields
global documentLibraryId → string
The Document Library Id that will be used for the SharePoint Operation. This can be pulled from one of the metadata settings or with the ID Utility. This value is required.
global enforceSecurity → boolean
Whether sFiles should enforce record-level security before allowing an API action. The default value is false. When true, the Client API property, “objectSettingsLabel” must have a value. NOTE: This parameter currently only applies to the “getDownloadLink” method.
global namedCredentialName → string
Specify which named credential to use for SharePoint operations. If the ClientApi class is called from a trigger or user-initiated action, this can be a “per user” named credential. If the code is to be called from scheduled apex, a platform event trigger or any other system-initiated process, use a “named principal” named credential that corresponds to a SharePoint user with appropriate access. This value can be pulled from one of the metadata settings or from your named credentials list. This value is required.
global objectSettingsLabel → string
The master label of the SharePoint Object Settings that sFiles should use to enforce Salesforce record-level security on an API action. This property will only apply if the Client API property “enforceSecurity” equals true. NOTE: This parameter currently only applies to the “getDownloadLink” method.
global sharepointSiteId → string
The SharePoint site id that will be used for the SharePoint Operation. This can be pulled from one of the metadata settings or with the ID Utility. This value is required.
Methods
global Boolean copyItem(string itemId, string parentFolderId)
global Boolean copyItem(string itemId, string parentFolderId, string destLibraryId)
global Boolean copyItem(string itemId, string parentFolderId, string destLibraryId, string newFileName)
Copy a file or folder and its descendants from one folder in SharePoint to another. Use this to have a Salesforce-triggered backup or publishing of a folder, for instance.
Parameters
Param
Description
itemId
The SharePoint id of the file or folder that is to be copied.
parentFolderId
The SharePoint folder id to copied the item to.
destLibraryId
(optional) Specifies the destination document library to copied to. This document library may be in a different site then the ClientApi instance.
newFileName
(optional) A new file or folder name to give the copied item. If filename, include the extension.
Returns
Type
Description
Boolean
A boolean that returns true if the item copied successfully and false if it did not.
global SharePointFileInfo createFolder(string parentFolderId, string folderName)
Create a folder within a specified folder. The parentFolderId can be obtained from the ID utility or set from the SharePoint_Id__c field on a record.
In the example below, the client is initialized from Metadata settings shared by sFiles. After this is complete, the folder is created. The resulting SharePointFileInfo object is then utilized to record the SharePoint Folder Id on the account.
Parameters
Param
Description
parentFolderId
Must be an existing folder within the Site and Document Library that the user has access to.
folderName
The name that you want to give the folder. Be sure to clean your string of forbidden folder name characters.
Accountacct=[SOQLSTATEMENTHERE];//Create the account folder and record the IDfileforcem1.SharePointFileInfoacctFolder=apiClient.createFolder(objectSettings.fileforcem1__Root_Folder_Id__c,acct.Name);acct.SharePoint_Folder_Id__c=acctFolder.Id;updateacct;
global String createSharingLink(String itemId)
global String createSharingLink(String itemId, String type)
global String createSharingLink(String itemId, String type, DateTime expirationDateTime)
global String createSharingLink(String itemId, String type, DateTime expirationDateTime, String password)
A string with the SharePoint Id of the folder or file to share.
type
(Optional) The type of sharing link to create. Defaults to “view”. (view
edit)
expirationDateTime
(Optional) A String with format of yyyy-MM-ddTHH:mm:ssZ of DateTime. Defaults to never expire or to default expiration policy of organization.
password
(Optional) The password of the sharing link.
scope
(Optional) The scope of the link to create. “anonymous” or “organization” or “users”. Anonymous allows anyone with link to access without signing in. Organization allows only those signed into your tenant to use the link. Users will only share the link with individual recipients and requires that the recipients list is populated
recipients
(Optional) When sharing to specific email addresses, provide the email addresses in a list of string
Returns
Type
Description
String
A string of the sharing link created.
global SharePointFileInfo createURLFile(string parentFolderId, string itemId)
Creates a url file for a SharePoint Item.
Parameters
Param
Description
parentFolderId
The id of the SharePoint folder where the url file will be created.
itemId
The SharePoint Item that the url file will link to.
A boolean that returns true if the item deleted successfully and false if it did not.
global ContentVersion downloadFile(string fileId)
Download file from SharePoint. This method takes a SharePoint file id and retrieves the file from SharePoint. It then saves the file in Salesforce Files as a ContentDocument. It then returns the newly created ContentVersion record which can be used in additional automation. If the file is larger than ~5MB the method will return an error, this is dependent on the heap size for executing code. The heap limit is increased if this method is called as a future or queueable. The example below shows downloading a file from SharePoint based on file Id.
Parameters
Param
Description
fileId
Id of existing file to download, within a Site and Document Library that the user has access to.
Returns
Type
Description
ContentVersion
A ContentVersion of the file downloaded from SharePoint.
//Get Document Libraries for a given siteList<fileforcem1.SharePointDocumentLibrary>myDocumentLibraries=apiClient.getDocumentLibraries();
global string getDocumentLibraryRootFolderId()
Get the Id for a document library root folder.
Returns
Type
Description
string
The Id of the Root Folder of the Document Library
Example
//Set the Site and Document Library to getIdapiClient.sharepointSiteId='yourSiteId';apiClient.documentLibraryId='yourDocumentLibraryId';//Get the Document Library Root IdStringmyDocumentLibraryRootFolderId=apiClient.getDocumentLibraryRootFolderId();
global String getDownloadLink(string fileId)
Download file from SharePoint. This method returns a link to download a file without a limit to file size. Optionally, you can enforce Salesforce record-level security by leveraging the ‘enforceSecurity’ and ‘objectSettingsLabel’ parameters on the client api class. See an example of this below.
Parameters
Param
Description
fileId
Id of existing file to download, within a specified Site and Document Library on the clientApi class that the user has access to. The Id must be of a file and not a folder.
Returns
Type
Description
String
A String of the link to download the file from SharePoint.
Example
apiClient.namedCredentialName='sFilesConnection';apiClient.sharepointSiteId='yourSiteId';apiClient.documentLibraryId='yourDocumentLibraryId';//Optional: check For salesforce record-level securityapiClient.enforceSecurity=true;//Declare the SharePoint Object Settings Label to use for security.apiClient.objectSettingsLabel='account';StringmyDownloadedFile=apiClient.getDownloadLink(yourFileId);
global list<SharePointFileInfo> getFolderContents(string folderId, Boolean getNextPage)
Query and list the contents of a folder. * This method will return a list of SharePointFileInfo objects of up to 200 results. If there are more results available after the query, * morePagesAvailable will return true. To query the next page, set getNextPage to true.
Parameters
Param
Description
folderId
The SharePoint folder id usually pulled from a record’s SharePoint_Folder_Id__c field.
getNextPage
Set to true in order to query the next page from the last query in the current running context. Set to false to get the first page.
//Get the folderfileforcem1.SharePointFileInfoacctFolder=apiClient.getItemById(objectSettings.fileforcem1__Root_Folder_Id__c);
global SharePointFileInfo getItemByPath(string path)
Retrieves a single file or folder by specifying the path to the file in a document library. This allows automation options such as retrieval of SharePoint folder ids to set the Sharepint_Folder_Id__c on a record. In the example below, a SharePoint Folder Id is retrieved by querying its path within the document library.
Parameters
Param
Description
path
The path within the Document Library to a file or folder. For instance, “/Accounts/Bob’s Account” would return the “Bob’s Account” folder information. It must have the slash at the beginning. Relative folder paths such as ../ or ./ are not available.
global SharePointUrlResponse getItemBySharePointURL(string sharePointUrl)
When provided with a URI directly from a SharePoint Location. This method Retrieves a SharePointUrlResponse class which returns the following when successful. Will throw an APIException if there is an error. - ID’s of the URL’s folder, document library, document library folder and site - SharePointFileInfo objects of the URL’s folder, document library and site
Parameters
Param
Description
sharePointUrl
A url that is copied from the browser location of a folder within SharePoint.
Gets the temporary url for the preview of the file.
Parameters
Param
Description
itemId
The item Id.
Returns
Type
Description
string
A string of the temporary url to preview the file.
global string getListItemIdFromLibraryId(string libraryId)
This method takes a Document Library ID and returns a list item Id.
Parameters
Param
Description
libraryId
The id of the Document Library
Returns
Type
Description
string
The list item id of the Document Library
global List<SharePointSite> getSites()
Get a list of all sites in the root of your SharePoint domain as specified in the “Default” custom metadata type “SharePoint Settings”.
Returns
Type
Description
List<SharePointSite>
A list of SharePointSite objects of each site in the domain specified in the SharePoint Settings.
global List<SharePointSite> getSites(string hostname)
Get a list of all sites in a domain.
Parameters
Param
Description
hostname
The SharePoint hostname or site Id to get the list of sites from. E.g., myothersite.sharepoint.com or mysite.sharepoint.com,123f4bd5-678e-991e-b8c7-54e93f81d3ac,123e4e5d-678a-9f1e-1f23-45adba6789ad
Returns
Type
Description
List<SharePointSite>
A list of SharePointSite objects of each site in the domain specified as a parameter.
global string getUploadSessionURL(string destinationFolderId, string fileName, boolean replaceFile)
Provides a one-time url to upload a file to the specified folder. This is designed to be used with custom client-side javascript to upload a file directly to a location. This method is useful to customers only under certain conditions. Please contact support to determine if this can be used in your solution.
Parameters
Param
Description
destinationFolderId
The id of the folder to upload into
fileName
the name of the file to be uploaded along with extension
replaceFile
a boolean value of whether or not to replace a file if a file by the same specified name already exists in the destination folder.
Returns
Type
Description
string
A string of the one-time upload session url
global boolean morePagesAvailable()
See the documentation for getFolderContents for usage.
Returns
Type
Description
boolean
Returns true if more pages are available to continue the most recent query using getFolderContents.
global SharePointFileInfo moveItem(string itemId, string parentFolderId)
Move a file or folder and its descendants from one folder in SharePoint to another. Use this to have a Salesforce-triggered archive of files, for instance. An item can only be moved within its original document library. Use copyFile to place a file or folder in a different document library.
Parameters
Param
Description
itemId
The SharePoint id of the file or folder that is to be moved.
global List<SharePointFileInfo> searchForItems(string searchTerm)
global List<SharePointFileInfo> searchForItems(string searchTerm, string folderId, boolean searchSubfolders)
Searches a document library or specified folder for all files and folders that match a search term.
Parameters
Param
Description
searchTerm
The keyword to search for a file/folder. NOTICE: The searchForItems function will search for this keyword not just in the name, but across all SharePoint columns.
folderId
The specific SharePoint folder Id where searchForItems should search.
searchSubfolders
Boolean of whether to search the subfolders of the given folderId. If false, sFiles will only return search results of items directly inside the folderId. If true, sFiles will return all matching results from all folders nested in the folderId.
Returns
Type
Description
List<SharePointFileInfo>
A list of SharePointFileInfo objects of the SharePoint Files/Folders that match the search term.
Example
fileforcem1.ClientApiapiClient=newfileforcem1.ClientApi();apiClient.namedCredentialName='sFilesConnection';//Specify the Site and Document Library where to searchapiClient.sharepointSiteId=yourSiteID;apiClient.documentLibraryId=yourDocumentLibraryId;//Get SharePoint Items matching the search term 'Burlington'List<fileforcem1.SharePointFileInfo>mySearchResults=apiClient.searchForItems('Burlington');StringfolderToSearchIn='015MBR2B3GJVBBHR2DNZB3L4XFNAGJTM6B';List<fileforcem1.SharePointFileInfo>mySearchResults=apiClient.searchForItems('Burlington',folderToSearchIn,false);
global SharepointFileInfo setupFolder(string recordId, string parentFolderId, string objectSettingsLabel)
global SharepointFileInfo setupFolder(string recordId, string parentFolderId, string objectSettingsLabel, string conflictBehavior)
This method mimics the UI button functionality: “Set Up in SharePoint”. Leverage this functionality to set up a folder for a given record exactly as is done in the UI. It will setup a folder according to the configuration of a specific SharePoint Object Settings record. The method will: • Create a folder for the record in the specified parent folder. • Name the folder according to the field specified in SharePoint Object Settings. • Set custom SharePoint fields on the new folder as specified in SharePoint Object Settings. • Create the child folder hierarchy as specified in SharePoint Object Settings and set SharePoint custom fields on the newly created folders. • Update the Salesforce record with the newly created SharePoint Folder Id.
Parameters
Param
Description
recordId
The Salesforce record id to create a folder for. It must correspond to the object type specified in the SharePoint Object Settings record
parentFolderId
The SharePoint folder id in which to place the new folder. This can be populated from the SharePoint Object Settings record or set manually
objectSettingsLabel
The label of the SharePoint Object Settings metadata record to use to set the folder up.
conflictBehavior
What the method will do if a folder already exists with the same name in the root folder. The three supported conflict behaviors are ‘fail’ (sFiles will not setup the folder), ‘replace’ (sFiles will replace the existing folder) and ‘rename’ (sFiles will append a number at the end of the newly created folder to rename it). The default behavior is rename.
global SharePointFileInfo updateCustomFields(string fileId, Map<String,String> customFields)
Manually sets custom field/value combinations to a document or folder in SharePoint The example below shows how to set SharePoint custom text fields “SalesforceAccountId” to a hard-coded value and “Type” to a referenced account type.
Parameters
Param
Description
fileId
The Id value from a SharePointFileInfo object
customFields
The format for the map is that the key is the SharePoint field name and the value is the value to write to that field.
global SharePointFileInfo uploadFile(string parentFolderId, string fileName, Blob fileContents)
A very simple upload method. This allows an upload of up to 4 MB and does not require a contentversion. This can be used to upload any blob as a file. Unlike other methods listed here, it does not set SharePoint fields automaticaly. Because of the 4 MB size limitation, uploadLargeFile is recommended.
Parameters
Param
Description
parentFolderId
Must be an existing folder within the Site and Document Library that the user has access to.
fileName
The file name with extension of the file to be uploaded. Be sure to make sure that no illegal characters are in the fileName.
Upload that will also set SharePoint custom field values. This allows an upload of up to 4 MB and does not require a contentversion. This can be used to upload any blob as a file. The file will be uploaded, and upon completion, custom fields will be set in SharePoint.
Because of the 4 MB size limitation, uploadLargeFile is recommended.
Usage The example below shows querying a contentversion by ContentDocumentId and uploading the file with custom SharePoint fields. It sets the SharePoint field, “SalesforceAccountId” to a hard-coded value and “Type” to a referenced account type.
Parameters
Param
Description
parentFolderId
Must be an existing folder within the Site and Document Library that the user has access to.
fileName
The file name with extension of the file to be uploaded. Be sure to make sure that no illegal characters are in the fileName.
fileContents
A blob value for the contents of the file
recordId
This is the Salesforce Record ID that is associated with the file. It is required.
customFields
The format for the map is that the key is the SharePoint field name and the value is the value to write to that field.
Upload that will also set SharePoint custom field values. This allows an upload of up to 4 MB and does not require a contentversion. This can be used to upload any blob as a file. The file will be uploaded, and upon completion, custom fields will be set in SharePoint.
Because of the 4 MB size limitation, uploadLargeFile is recommended.
Usage The example below shows querying a contentversion by ContentDocumentId and uploading the file with custom SharePoint fields. It sets the SharePoint field, “SalesforceAccountId” to a hard-coded value and “Type” to a referenced account type.
Parameters
Param
Description
parentFolderId
Must be an existing folder within the Site and Document Library that the user has access to.
fileName
The file name with extension of the file to be uploaded. Be sure to make sure that no illegal characters are in the fileName.
fileContents
A blob value for the contents of the file
recordId
This is the Salesforce Record ID that is associated with the file. It is required.
customFields
The format for the map is that the key is the SharePoint field name and the value is the value to write to that field.
conflictBehavior
What the method will do if a file already exists with the same name in the root folder. The three supported conflict behaviors are ‘fail’ (sFiles will not upload the file), ‘replace’ (sFiles will replace the existing file) and ‘rename’ (sFiles will append a number at the end of the newly created file to rename it). The default behavior is replace.
Upload a file up to 11 MB but requires a ContentVersionId The file will be uploaded as a
Parameters
Param
Description
parentFolderId
Must be an existing folder within the Site and Document Library that the user has access to.
fileName
The file name with extension of the file to be uploaded. Be sure to make sure that no illegal characters are in the fileName.
documentVersionId
The ContentVersion Id of the file
recordId
This is the Salesforce Record ID that is associated with the file. It is used by future methods to set custom fields on the record.
customFields
The format for the map: the key is the SharePoint field name and the value is the value to write to that field.
autodelete
(Optional) Boolean that determines whether ContentVersion created when uploading file to SharePoint is automatically deleted or not. Defaults to true (will automatically delete ContentVersion upon upload).
replaceFile
(Optional) Boolean that determines whether the file uploaded will be replaced or renamed if another file with the same name exists.
Future method. Upon completion, custom fields will be set in SharePoint and a File_Uploaded_Community__e platform event will be fired. Code can be written to subscribe to the platform event to further extend functionality. All fields are required in order to set custom fields upon upload.
This method always returns null.
Usage The example below shows querying a contentversion by ContentDocumentId and uploading the file with custom SharePoint fields. It sets the SharePoint field, “SalesforceAccountId” to a hard-coded value and “Type” to a referenced account type.
This method will log sFiles Debug information in the sFiles Debug Log Object. The following must be in place for this method to work: • The log level in SharePoint Settings (Setup > Custom Metadata Types > SharePoint Setttings > Default) must be set to a value other than “None”. • This method must be called after all sFiles methods and DML operations are complete. • NOTE: Return the log level in step 1 to “None” when not in use to avoid unnecessary operations.