How To Create An Azure WebJob For SharePoint Online

In this article, we have discussed the process of Azure Webjob, a Remote Timer Job development. And the reasons to chose Azure WebJob or Windows Scheduler.

Recently, one of my clients moved to SharePoint Online. Therefore, we had to plan to migrate the existing custom apps in a committable state to communicate with SharePoint Online. In that process, I had to work with the timer jobs. In SharePoint Online, we don’t have the typical Full Trust Code (FTC)/Farm Solution support, and I had to go with the Remote Timer Job which was scheduled outside of SharePoint on another server. There are two options to implement the remote timer job - Windows Scheduler and Azure WebJob.

As it required  additional hardware to run the timer job code as Windows Scheduler, and I had an Azure Subscription, Azure WebJob was the best way to develop the Remote Timer job in this scenario. In this article, we are going to discuss the detailed process to create an Azure WebJob.

Azure WebJob

For a basic understanding of Azure WebJob, it is a service which comes with Azure Websites and it can be invoked by a trigger or run continuously. To understand it easily, we can say that Azure WebJob is a specialized scheduler which comes with a specialized feature. 

Prerequisites
  • A SharePoint Online Site
  • A subscription of Microsoft Azure
  • Visual Studio (Just a preferred IDE)
Steps to create Azure WebJob

So, in this article, we are going to create an Azure WebJob for SharePoint Online to deploy on Azure and will run it with a schedule. The steps to create it are given below.

Step 1
 
Open Visual Studio (v. 2017).

Step 2

Let’s create a new project with Console App (.NET Framework) or Azure WebJob (.NET Framework). There is not that much difference in these two types of projects. Just some difference in the predefined template. In this article, we are going with the first one - Console App (.NET Framework) project template.
 
Azure WebJob For SharePoint Online
Fig: Creating Web Job with Console App Project Template
 
Azure WebJob For SharePoint Online 
Fig: Creating Web Job with Azure WebJob Project Template

Step 3

Now, we need to install “AppForSharePointOnlineWebToolkit” package from NuGet Package Manager. To do that, we need to follow the steps as shown in the below figure.
 
Azure WebJob For SharePoint Online
Fig: Installing AppForSharePointOnlineWebToolkit package from NuGet Package Manager

Step 4

After installing the package in the current solution, we will see that two-class files have been added to the project - SharePointContext.cs and TokenHelper.cs.
 
Azure WebJob For SharePoint Online

Step 5

Now, to get the context information, we have two ways to authenticate - User Authentication and OAuth. We will discuss both of the ways here.

Step 6

First, if we use the user authentication, we can use the following code snippet.
  1. private static ClientContext GetClientContextbyUser(){  
  2.     try{  
  3.         string siteUrl = ConfigurationManager.AppSettings["SiteAddress"];  
  4.         string spoAccount = ConfigurationManager.AppSettings["SPOAccount"];  
  5.         SecureString securepass = new NetworkCredential("", ConfigurationManager.AppSettings["SPOPassword"]).SecurePassword;  
  6.           
  7.         ClientContext context = new ClientContext(siteUrl);  
  8.         context.Credentials = new SharePointOnlineCredentials(spoAccount, securepass);  
  9.         return context;  
  10.     }  
  11.     catch (Exception ex) {  
  12.         Console.WriteLine("Got error to getting the client context. Error: " + ex.Message);  
  13.         throw ex;  
  14.     }  

Step 7

Instead of using the user authentication, we can use OAuth (app authentication) also, which has gotten very popular nowadays. A code snippet to get the SharePoint app authentication is given below.
  1. private static ClientContext GetAppOnlyClientContext()  
  2. {  
  3.     Uri siteUri = new Uri(ConfigurationManager.AppSettings["SiteAddress"]);  
  4.     string realm = TokenHelper.GetRealmFromTargetUrl(siteUri);  
  5.     string appOnlyAccessToken = TokenHelper.GetAppOnlyAccessToken(  
  6.         TokenHelper.SharePointPrincipal,  
  7.         siteUri.Authority, realm).AccessToken;  
  8.   
  9.     using (var clientContext =  
  10.         TokenHelper.GetClientContextWithAccessToken(  
  11.             siteUri.ToString(), appOnlyAccessToken))  
  12.     {  
  13.         Console.WriteLine("Client Context Found");  
  14.         return clientContext;  
  15.     }  

Step 8

As we can see in both the functions above, ConfigurationManager.AppSettings[""]) has been used to get the values (spoAccount, Password, even Site Address). These values are gotten from the App.config file. And for the 2nd function, we can see that there is no function declared here which we can identify that the application is reading the ClientId and ClientSecret. These values are read by TokernHelper. Hence, for this, the clientid and clientsecret also needed to be in the app.config.
 
Azure WebJob For SharePoint Online
Fig: App Settings Key and Value in App.config file

Step 9

For ClientId and ClientSecret, we need to generate them from the SharePoint site where we are going to use the timer job. The details to generate and register the application in the SharePoint site are given under the App Registration heading of this article below.

Step 10

As we got the ClientContext already, we can work with the SharePoint site context information in the WebJob now. After completing the process, try to dispose of the clientcontext, which is a better practice.
 
Azure WebJob For SharePoint Online

Step 11

Now, to configure the CRON schedule, we need to create a JSON file with the name of “settings.job”.
 
Azure WebJob For SharePoint Online
Fig: Creating Scheduler Time Settings file in JSON file format

Step 12

In this JSON file, we will declare the schedule. This CRON Expression is composed of the following six fields: 

{second} {minute} {hour} {day} {month} {day of the week}

Step 13

As we wanted to schedule the webjob for the 9:00 AM, we have written the CRON express as follows: "schedule": "0 0 9 * * *".
 
Azure WebJob For SharePoint Online
Fig: The settings.job file with the declared CRON Expression

Step 14

For more examples and details about the CRON Expression, the following Microsoft documentation, “CRON Expression” has good enough information.

Step 15

This webjob is now ready to deploy. We can even run it from our deployment environment with Visual Studio in Debug Mode.

App Registration

Step 1

First, we have to register the client app on the selected site (on which SharePoint Site the application will process) and generate the client app authentication.

Step 2

Go to the following address, ~sitecollection/_layouts/15/appregnew.aspx. Then, we will get the following window.
 
Azure WebJob For SharePoint Online
Fig: App Information

Step 3

Click the button beside the Client Id to generate the client id as shown in position 1 and the same for the client secret in position 2.

Step 4

Provide your app name which you want in position 3.

Step 5

As an app domain, the server address needs to be provided where the Application will run. This can even be Localhost to Azure App Service. To run the application on an application server, we need to provide the server URL and to run in Azure. The Azure App Service URL needs to be provided in here.

Step 6

On position 4, as shown in the above figure, provide the App domain without HTTPS.

Step 7

On position 5, provide the app domain with https:// as prefix and click Create button. The App registration key with the provided app domain will be registered in the working site.

Step 8

Now, navigate to the URL ~sitecollection /_layouts/15/appinv.aspx. The following window will open.

Azure WebJob For SharePoint Online
Fig: Grant Permission of an App

Step 9

Provide the “ClientId” in the App Id field (position 1) which we have already generated and registered with the app domain. Now, click the “Lookup” button.

Step 10

Other fields such as Title, App Domain and Redirect URL will be automatically filled as provided previously.

Step 11

Now, we have to provide the App’s permission request XML in the position 2.

Step 12

The permission request XML is given below for full control of the site collection and on web.
  1. <AppPermissionRequests AllowAppOnlyPolicy="true">  
  2.     <AppPermissionRequest Scope="http://sharepoint/content/sitecollection/web" Right="FullControl" />  
  3.     <AppPermissionRequest Scope="http://sharepoint/content/sitecollection" Right="FullControl" />  
  4. </AppPermissionRequests> 

Step 13

Click on the "Create" button. Now, the client app is ready with required permissions.

Step 14

To be sure about the app existence, we can check it from the following url: _~sitecollection/layouts/15/appprincipals.aspx. Here, we will get the client app as our provided Title we have set as App Information.
 
Conslusion
 
We discussed the Azure WebJob in here, which is a remote SharePoint timer job. Also, we have demonstrated the procedure to get the ClientContext. Deploying the WebJob in Azure is pretty easy, which we will discuss in the next article. And if anyone already has a physical server, they can go with the Windows Scheduler instead of Azure WebJob.

I hope this article will help people who are new to Azure WebJobs. If anyone has any suggestions to update the article, please provide your feedback.