B4J Question Accessing Sharepoint?

BlueVision

Active Member
Licensed User
Longtime User
My company is switching from an FTP solution to Sharepoint. Actually, FTP would be the more suitable solution for hosting files (and worked until now) , transporting these files to the requesting client and then deleting them on the host, because nothing else happens in this case...
So be it. The only possible access for me is via HTTPS (user/password), which is completely new territory for me.
So as not to start off on the wrong foot, has anyone done this before and maybe have some sample code for me?
Theoretically, there is the REST service running on Sharepoint. I could perhaps use this to get Sharepoint to communicate with my B4J client somehow, probably via HTTPS/JSON. Am I completely wrong now?
As I said, any code snippets are absolutely welcome. FTP was very convenient, fast and simple. However, FTP has been banned from the company's IT infrastructure for security reasons. I'm not of the same opinion, but I have to bend to the rules and find a way quickly...

Cheers from Berlin
 

walt61

Active Member
Licensed User
Longtime User
Just a thought based on what I used to do when I was still in the midst of corporate insanity - this may be completely out of whack/useless but I thought I'd mention it anyway as it might spark some inspiration. I used to (until about 4 years ago) access SharePoint document libraries by syncing them to (and 'from' !) my PC with OneDrive. That way, I could just do whatever I like in the local folders and they would get synced automatically with SharePoint.
 
Upvote 0

LucaMs

Expert
Licensed User
Longtime User
I asked ChatGPT:

Generate code in B4J language (not pure Java) that performs the following tasks on SharePoint:
- get a list of files
- download a file
- delete the downloaded file


It generated code that used a non-existent jShare library. So I wrote it to use OKHttpUtils2.

Its answer:

To interact with SharePoint using the OkHttpUtils2 library in B4J, you will need to handle HTTP requests directly. Below is an example of how to get a list of files, download a file, and delete the downloaded file from SharePoint using OkHttpUtils2.

Example Code​

Here's a B4J example demonstrating these tasks:

  1. Add OkHttpUtils2 Library:
    • Ensure you have the OkHttpUtils2 library in your B4J project. You can add it via Tools -> Libraries... and select OkHttpUtils2.
  2. SharePoint API Configuration:
    • Ensure you have the necessary SharePoint API endpoints and permissions configured.

Complete Example Code

B4X:
#Region Project Attributes
    #MainFormWidth: 600
    #MainFormHeight: 400
#End Region

' Import required libraries
#AdditionalJar: okhttp-3.12.1
#AdditionalJar: okio-1.15.0
#AdditionalJar: commons-codec-1.10
#AdditionalJar: commons-logging-1.2
#AdditionalJar: httpclient-4.5.2
#AdditionalJar: httpcore-4.4.4

Sub Process_Globals
    Private fx As JFX
    Private MainForm As Form
    Private job As HttpJob
    Private SharePointSiteUrl As String = "https://your-sharepoint-site-url"
    Private SharePointUsername As String = "your-username"
    Private SharePointPassword As String = "your-password"
End Sub

Sub AppStart (Form1 As Form, Args() As String)
    MainForm = Form1
    MainForm.Show

    ' Example usage:
    ' List files in a SharePoint library
    ListFiles("/sites/yoursite/Documents")
   
    ' Download a file from SharePoint
    DownloadFile("/sites/yoursite/Documents/SampleFile.txt", "C:\Downloads\SampleFile.txt")
End Sub

Sub ListFiles(libraryPath As String)
    Dim url As String = SharePointSiteUrl & "/_api/web/GetFolderByServerRelativeUrl('" & libraryPath & "')/Files"
    job.Initialize("ListFiles", Me)
    job.Username = SharePointUsername
    job.Password = SharePointPassword
    job.Download(url)
End Sub

Sub DownloadFile(filePath As String, destinationPath As String)
    Dim url As String = SharePointSiteUrl & "/_api/web/GetFileByServerRelativeUrl('" & filePath & "')/$value"
    job.Initialize("DownloadFile", Me)
    job.Username = SharePointUsername
    job.Password = SharePointPassword
    job.Download(url)
    job.GetRequest.SetResponseDestination(destinationPath)
End Sub

Sub DeleteFile(filePath As String)
    Try
        File.Delete(filePath)
        Log($"File '${filePath}' deleted."$)
    Catch
        Log($"Failed to delete file '${filePath}'."$)
    End Try
End Sub

Sub JobDone(Job As HttpJob)
    If Job.Success Then
        Select Job.JobName
            Case "ListFiles"
                Log("Files: " & Job.GetString)
            Case "DownloadFile"
                Log("File downloaded successfully.")
        End Select
    Else
        Log("Error: " & Job.ErrorMessage)
    End If
    Job.Release
End Sub

Explanation​

  • Initialization:
    • job.Initialize initializes the HTTP job for each task (list files, download file).
    • job.Username and job.Password are used to authenticate the requests.
  • List Files:
    • ListFiles function sends a GET request to the SharePoint REST API to list files in the specified libraryPath.
  • Download File:
    • DownloadFile function sends a GET request to download a file from SharePoint to the specified local destinationPath.
  • Delete File:
    • DeleteFile function deletes the downloaded file from the local file system.
  • JobDone:
    • Handles the completion of the HTTP job and logs the response or any errors.

Notes​

  • Ensure you replace "https://your-sharepoint-site-url", "your-username", and "your-password" with your actual SharePoint credentials and site URL.
  • The SharePoint API endpoints used here are RESTful and might require specific permissions and configurations on your SharePoint site.
  • Make sure to handle errors and exceptions appropriately in your actual implementation.
  • Adjust file paths and library names (libraryPath) as per your SharePoint site structure and requirements.
This example provides a basic framework for interacting with SharePoint using OkHttpUtils2 in B4J. You may need to customize it further based on your specific SharePoint setup and requirements.

--------------------------------------------------

Obviously I haven't tested the source code (I haven't even read it)
 
Upvote 0

BlueVision

Active Member
Licensed User
Longtime User
Just a thought based on what I used to do when I was still in the midst of corporate insanity - this may be completely out of whack/useless but I thought I'd mention it anyway as it might spark some inspiration. I used to (until about 4 years ago) access SharePoint document libraries by syncing them to (and 'from' !) my PC with OneDrive. That way, I could just do whatever I like in the local folders and they would get synced automatically with SharePoint.
Thank you for your comment. The problem is that OneDrive is completely unsuitable in this case. The SharePoint link hides folders with return documents. In principle, synchronisation with OneDrive works, you're absolutely right. In my case, however, a selected and downloaded document must be deleted immediately on the host so that no other colleague can use this document. 300 colleagues access it within the company. Everyone would have to synchronise the folders...
In my case, I think direct access to a file, downloading it and deleting it immediately is the least risky way of preventing duplicate use. As I said, FTP was ideal for this case but it is no longer wanted. Newer versions (SFTP, FTPS) are also outdated and insecure (at least according to IT). They are simply no longer ‘chic’.
 
Upvote 0

LucaMs

Expert
Licensed User
Longtime User
I asked ChatGPT:

Generate code in B4J language (not pure Java) that performs the following tasks on SharePoint:
- get a list of files
- download a file
- delete the downloaded file


It generated code that used a non-existent jShare library. So I wrote it to use OKHttpUtils2.

Its answer:

To interact with SharePoint using the OkHttpUtils2 library in B4J, you will need to handle HTTP requests directly. Below is an example of how to get a list of files, download a file, and delete the downloaded file from SharePoint using OkHttpUtils2.

Example Code​

Here's a B4J example demonstrating these tasks:

  1. Add OkHttpUtils2 Library:
    • Ensure you have the OkHttpUtils2 library in your B4J project. You can add it via Tools -> Libraries... and select OkHttpUtils2.
  2. SharePoint API Configuration:
    • Ensure you have the necessary SharePoint API endpoints and permissions configured.

Complete Example Code

B4X:
#Region Project Attributes
    #MainFormWidth: 600
    #MainFormHeight: 400
#End Region

' Import required libraries
#AdditionalJar: okhttp-3.12.1
#AdditionalJar: okio-1.15.0
#AdditionalJar: commons-codec-1.10
#AdditionalJar: commons-logging-1.2
#AdditionalJar: httpclient-4.5.2
#AdditionalJar: httpcore-4.4.4

Sub Process_Globals
    Private fx As JFX
    Private MainForm As Form
    Private job As HttpJob
    Private SharePointSiteUrl As String = "https://your-sharepoint-site-url"
    Private SharePointUsername As String = "your-username"
    Private SharePointPassword As String = "your-password"
End Sub

Sub AppStart (Form1 As Form, Args() As String)
    MainForm = Form1
    MainForm.Show

    ' Example usage:
    ' List files in a SharePoint library
    ListFiles("/sites/yoursite/Documents")
  
    ' Download a file from SharePoint
    DownloadFile("/sites/yoursite/Documents/SampleFile.txt", "C:\Downloads\SampleFile.txt")
End Sub

Sub ListFiles(libraryPath As String)
    Dim url As String = SharePointSiteUrl & "/_api/web/GetFolderByServerRelativeUrl('" & libraryPath & "')/Files"
    job.Initialize("ListFiles", Me)
    job.Username = SharePointUsername
    job.Password = SharePointPassword
    job.Download(url)
End Sub

Sub DownloadFile(filePath As String, destinationPath As String)
    Dim url As String = SharePointSiteUrl & "/_api/web/GetFileByServerRelativeUrl('" & filePath & "')/$value"
    job.Initialize("DownloadFile", Me)
    job.Username = SharePointUsername
    job.Password = SharePointPassword
    job.Download(url)
    job.GetRequest.SetResponseDestination(destinationPath)
End Sub

Sub DeleteFile(filePath As String)
    Try
        File.Delete(filePath)
        Log($"File '${filePath}' deleted."$)
    Catch
        Log($"Failed to delete file '${filePath}'."$)
    End Try
End Sub

Sub JobDone(Job As HttpJob)
    If Job.Success Then
        Select Job.JobName
            Case "ListFiles"
                Log("Files: " & Job.GetString)
            Case "DownloadFile"
                Log("File downloaded successfully.")
        End Select
    Else
        Log("Error: " & Job.ErrorMessage)
    End If
    Job.Release
End Sub

Explanation​

  • Initialization:
    • job.Initialize initializes the HTTP job for each task (list files, download file).
    • job.Username and job.Password are used to authenticate the requests.
  • List Files:
    • ListFiles function sends a GET request to the SharePoint REST API to list files in the specified libraryPath.
  • Download File:
    • DownloadFile function sends a GET request to download a file from SharePoint to the specified local destinationPath.
  • Delete File:
    • DeleteFile function deletes the downloaded file from the local file system.
  • JobDone:
    • Handles the completion of the HTTP job and logs the response or any errors.

Notes​

  • Ensure you replace "https://your-sharepoint-site-url", "your-username", and "your-password" with your actual SharePoint credentials and site URL.
  • The SharePoint API endpoints used here are RESTful and might require specific permissions and configurations on your SharePoint site.
  • Make sure to handle errors and exceptions appropriately in your actual implementation.
  • Adjust file paths and library names (libraryPath) as per your SharePoint site structure and requirements.
This example provides a basic framework for interacting with SharePoint using OkHttpUtils2 in B4J. You may need to customize it further based on your specific SharePoint setup and requirements.

--------------------------------------------------

Obviously I haven't tested the source code (I haven't even read it)

Next, me:

Are you sure I don't need an access token?

Answer:

Yes, you're correct. To interact with SharePoint Online, you generally need to use OAuth 2.0 for authentication, which involves obtaining an access token. This token is then used to authenticate your API requests.

Below is an updated example demonstrating how to obtain an access token and use it to list files, download a file, and delete the downloaded file from SharePoint using OkHttpUtils2 in B4J.

Prerequisites​

  1. Register an App in Azure AD: You need to register an application in Azure Active Directory to obtain the client ID and client secret required for OAuth 2.0 authentication.
  2. Set Permissions: Ensure your application has the necessary permissions to access SharePoint.

Example Code​

Here’s how to implement these tasks using OkHttpUtils2:


B4X:
#Region Project Attributes
    #MainFormWidth: 600
    #MainFormHeight: 400
#End Region

' Import required libraries
#AdditionalJar: okhttp-3.12.1
#AdditionalJar: okio-1.15.0
#AdditionalJar: commons-codec-1.10
#AdditionalJar: commons-logging-1.2
#AdditionalJar: httpclient-4.5.2
#AdditionalJar: httpcore-4.4.4

Sub Process_Globals
    Private fx As JFX
    Private MainForm As Form
    Private HttpJob1 As HttpJob
    Private HttpJob2 As HttpJob
    Private AccessToken As String

    ' Azure AD and SharePoint details
    Private TenantId As String = "your-tenant-id"
    Private ClientId As String = "your-client-id"
    Private ClientSecret As String = "your-client-secret"
    Private SharePointSiteUrl As String = "https://your-sharepoint-site-url"
    Private Username As String = "your-username"
    Private Password As String = "your-password"
End Sub

Sub AppStart (Form1 As Form, Args() As String)
    MainForm = Form1
    MainForm.Show

    ' Obtain an access token
    GetAccessToken
End Sub

Sub GetAccessToken
    Dim url As String = $"https://login.microsoftonline.com/${TenantId}/oauth2/v2.0/token"$
    Dim j As HttpJob
    j.Initialize("GetToken", Me)
    j.PostString(url, "grant_type=password&client_id=" & ClientId & "&client_secret=" & ClientSecret & "&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default&username=" & Username & "&password=" & Password)
    j.GetRequest.SetContentType("application/x-www-form-urlencoded")
    j.GetRequest.SetHeader("Accept", "application/json")
    j.GetRequest.SetHeader("Host", "login.microsoftonline.com")
    j.GetRequest.SetHeader("Content-Type", "application/x-www-form-urlencoded")
End Sub

Sub JobDone(Job As HttpJob)
    If Job.Success Then
        Select Job.JobName
            Case "GetToken"
                Dim parser As JSONParser
                parser.Initialize(Job.GetString)
                Dim map As Map = parser.NextObject
                AccessToken = map.Get("access_token")
                Log("Access Token: " & AccessToken)
                
                ' Now that we have the token, we can list files
                ListFiles("/sites/yoursite/Documents")
                
            Case "ListFiles"
                Log("Files: " & Job.GetString)
                
            Case "DownloadFile"
                Log("File downloaded successfully.")
        End Select
    Else
        Log("Error: " & Job.ErrorMessage)
    End If
    Job.Release
End Sub

Sub ListFiles(libraryPath As String)
    Dim url As String = SharePointSiteUrl & "/_api/web/GetFolderByServerRelativeUrl('" & libraryPath & "')/Files"
    HttpJob1.Initialize("ListFiles", Me)
    HttpJob1.Download(url)
    HttpJob1.GetRequest.SetHeader("Authorization", "Bearer " & AccessToken)
End Sub

Sub DownloadFile(filePath As String, destinationPath As String)
    Dim url As String = SharePointSiteUrl & "/_api/web/GetFileByServerRelativeUrl('" & filePath & "')/$value"
    HttpJob2.Initialize("DownloadFile", Me)
    HttpJob2.Download(url)
    HttpJob2.GetRequest.SetHeader("Authorization", "Bearer " & AccessToken)
    HttpJob2.GetRequest.SetResponseDestination(destinationPath)
End Sub

Sub DeleteFile(filePath As String)
    Try
        File.Delete(filePath)
        Log($"File '${filePath}' deleted."$)
    Catch
        Log($"Failed to delete file '${filePath}'."$)
    End Try
End Sub

Explanation​

  1. OAuth 2.0 Authentication:
    • GetAccessToken sends a POST request to Azure AD to obtain an access token using the resource owner's password credentials (ROPC) grant.
    • The token request includes the tenant ID, client ID, client secret, username, and password.
    • The access token is extracted from the response and stored in the AccessToken variable.
  2. List Files:
    • ListFiles sends a GET request to the SharePoint REST API to list files in the specified library.
    • The request includes the access token in the Authorization header.
  3. Download File:
    • DownloadFile sends a GET request to download a file from SharePoint to the specified local destination path.
    • The request includes the access token in the Authorization header.
  4. Delete File:
    • DeleteFile deletes the downloaded file from the local file system.
  5. JobDone:
    • Handles the completion of the HTTP job and processes the response.

Notes​

  • Replace "your-tenant-id", "your-client-id", "your-client-secret", "https://your-sharepoint-site-url", "your-username", and "your-password" with your actual Azure AD and SharePoint details.
  • Ensure your application in Azure AD has the necessary permissions to access SharePoint resources.
  • Handle errors and exceptions appropriately in your actual implementation.
  • Adjust file paths and library names (libraryPath) as per your SharePoint site structure and requirements.
This example provides a comprehensive approach to interacting with SharePoint using OAuth 2.0 authentication and OkHttpUtils2 in B4J. You may need to customize it further based on your specific SharePoint setup and requirements.
 
Upvote 0

BlueVision

Active Member
Licensed User
Longtime User
I asked ChatGPT:
Thanks Luca, that might be worth a try. The problem with this type of code:
Are all these additional libraries necessary? http itself is integrated and I completely miss libraries like okhttputils2 (also internal) in this case.
As I said, totally new territory for me and that makes me very insecure. JSON is completely missing and I'm afraid I'll also need this library.
Please don't get me wrong. I am grateful for any help that can point me in the right direction. Thank you for your help. But as far as I understood about Sharepoint, it can only be accessed via the REST service. You can address it via https and get JSON input back, which you can then evaluate with the client and make the next https request:
MICROSOFT:
Perform basic create, read, update and delete operations, also known as CRUD operations (Create, Read, Update, Delete), for folders and files using the SharePoint REST interface.
 
Last edited:
Upvote 0

aeric

Expert
Licensed User
Longtime User
ChatGPT is not a B4X developer.
The code has some problems such as not using WaitFor for JobDone and not using OkHttpUtils2.
I don't recommend to use it but if you just want some idea, maybe you can take it as a reference.
Just read SharePoint documentation on how to use the REST API and learn how to make Http call using OkHttpUtils with WaitFor.
 
Upvote 0
Top