How To Create An Azure WebJob For SharePoint Online

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 that 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 that comes with a specialized feature.

Prerequisites

  • A SharePoint Online Site
  • A subscription to 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 differences in the predefined template. In this article, we are going with the first one the Console App (.NET Framework) project template.

Console app

Fig. Creating Web Job with Console App Project Template

Azure web job

Fig. Creating Web Job with Azure WebJob Project Template

Step 3. Now, we need to install the “AppForSharePointOnlineWebToolkit” package from NuGet Package Manager. To do that, we need to follow the steps as shown in the below figure.

App for share point 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.

Test web job

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.

private static ClientContext GetClientContextbyUser()
{
    try
    {
        string siteUrl = ConfigurationManager.AppSettings["SiteAddress"];
        string spoAccount = ConfigurationManager.AppSettings["SPOAccount"];
        SecureString securepass = new NetworkCredential("", ConfigurationManager.AppSettings["SPOPassword"]).SecurePassword;
        ClientContext context = new ClientContext(siteUrl);
        context.Credentials = new SharePointOnlineCredentials(spoAccount, securepass);
        return context;
    }
    catch (Exception ex)
    {
        Console.WriteLine("Got error to getting the client context. Error: " + ex.Message);
        throw ex;
    }
}

Step 7. Instead of using user authentication, we can use OAuth (app authentication) also, which has become very popular nowadays. A code snippet to get the SharePoint app authentication is given below.

private static ClientContext GetAppOnlyClientContext()
{
    Uri siteUri = new Uri(ConfigurationManager.AppSettings["SiteAddress"]);
    string realm = TokenHelper.GetRealmFromTargetUrl(siteUri);
    string appOnlyAccessToken = TokenHelper.GetAppOnlyAccessToken(
        TokenHelper.SharePointPrincipal,
        siteUri.Authority, realm).AccessToken;
    using (var clientContext = 
        TokenHelper.GetClientContextWithAccessToken(
            siteUri.ToString(), appOnlyAccessToken))
    {
        Console.WriteLine("Client Context Found");
        return clientContext;
    }
}

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.

App setting key

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 on the SharePoint site are given under the App Registration heading of this article below.

Step 10. As we have 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 client context, which is a better practice.

Click contentalready

Step 11. Now, to configure the CRON schedule, we need to create a JSON file with the name “settings. job”.

Settings job

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 web job for 9:00 AM, we have written the CRON express as follows: "schedule": "0 0 9 * * *".

Cron express

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 web job 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.

App information

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 here.

Step 6. Position 4, as shown in the above figure, provides the App domain without HTTPS.

Step 7. On position 5, provide the app domain with https:// as prefix and click the 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.

Look up

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 position 2.

Step 12. The permission request XML is given below for full control of the site collection and on the web.

<AppPermissionRequests AllowAppOnlyPolicy="true">
    <AppPermissionRequest Scope="http://sharepoint/content/sitecollection/web" Right="FullControl" />
    <AppPermissionRequest Scope="http://sharepoint/content/sitecollection" Right="FullControl" />
</AppPermissionRequests>

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

Step 14. To be sure about the app's 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.

Conclusion

We discussed the Azure WebJob 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.