Simulate SharePoint Online Timer Jobs Using Azure Functions

Introduction

SharePoint Server provides native Timer Jobs that inherit SPJobDefinition class to run at regular intervals defined in the SPSchedule object. This way, we can create solutions that have to be iteratively run to process logic at regular intervals. However, in the case of SharePoint Online, Native Timer Jobs cannot be used.

Though we can use Windows Service/Task Scheduler to simulate Timer Jobs in SharePoint Online, it is still not a complete cloud solution. However, now we have the option to create pure cloud solutions for SharePoint Online Timer Jobs using Azure Function.

What are we going to do?

In this article, we will explore the process of simulating Timer Jobs for SharePoint Online using Azure Functions. The video recording of the demo is shared here

Requirement for Simulating Timer Job in SharePoint Online using Azure web jobs

We have a List named ‘SLA’ that contains action items and an associated SLA date. Every day if the SLA date for the action item has reached, we have to intimate the concerned person about the items whose SLA has reached. Since the logic to check for SLA has to run every day, we will create a timer job solutions using Azure Function. As shown below, there are two items that have reached the SLA of 6/17/2017.

SharePoint

The Azure function timer job will get the SharePoint Online List items that have reached the SLA(checks if the SLA date is today) and will send the mail to the concerned Service User.

SharePoint

Create Azure Function to work as a SharePoint Timer

We will create an Azure Function app that will contain the code that implements the logic which will be scheduled to run at regular intervals. Once we have logged in to the Azure Portal, search for Function App and select it.

SharePoint

Specify the App name and the other Function App details that will be used to create the Azure Function App.

SharePoint

Click on Create to provision the Function App.

SharePoint

Once the Azure Function App is running, we can add the function where we will add the code. Select the Plus option and select ‘Timer Trigger C#’ option to simulate a timer that will run on a schedule.

SharePoint

We can specify a name for the Function and specify the schedule. By default it is set to run every 5 minutes.

SharePoint

Develop the Timer Code

Once created, it will open up the run.csx file with the below default code block.

SharePoint

Before adding the code to access SharePoint Online List, we must upload the SharePoint Client libraries that we will be using within the code. To do this, select the Azure Function App and from Platform Features click on Advanced Tools(Kudu).

SharePoint

From the Debug Console, Select the option ‘PowerShell’.

SharePoint

It will open the folder structure. We must navigate to the site –> wwwroot –> <Function Name> location

SharePoint

The function name is ‘ExpiredSLAIdenitifier’. Click on the folder to go inside the folder where we will create a new folder.

SharePoint

Create the New Folder and let's name it as bin.

SharePoint

Finally drag and drop the client dlls which we can find at,

C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI

If we are working from a Non-SharePoint Server machine, we can download the client dlls from here .The Client Dlls that we will be using are :

  • Microsoft.SharePoint.Client.dll
  • Microsoft.SharePoint.Client.runtime.dll

    SharePoint

Now we can go ahead to the function and add the code that implements the logic.

SharePoint

By default the code fragment will look like below,

SharePoint

Replace the above code with the below section so that it will connect to the SharePoint Online list and fetch the list items whose SLA is today. It will also send a mail to the specified service engineer alerting the action items that has to be resolved.

Code 

  1. #r "Microsoft.SharePoint.Client.Runtime.dll"   
  2. #r "Microsoft.SharePoint.Client.dll"  
  3. using System;   
  4. using System.Net;   
  5. using Microsoft.SharePoint.Client;   
  6.    
  7.      
  8. public static void Run(TimerInfo myTimer, TraceWriter log)   
  9. {   
  10.                
  11.         //In real scenario, make use of Azure Key Vault to store and retrieve password  
  12.         string password = "<Your Office 365 Credential>";   
  13.         System.Security.SecureString securePassword = new System.Security.SecureString();   
  14.         foreach (char pass in password) {  
  15.             securePassword.AppendChar(pass);  
  16.     }                
  17.         //Get SPOnline User Credentials  
  18.         SharePointOnlineCredentials spOnlineCredentials = newSharePointOnlineCredentials("[email protected]", securePassword);   
  19.         try{   
  20.                
  21.              //Create the Client Context  
  22.             using (var SPClientContext = new ClientContext("https://ctsplayground.sharepoint.com   "))   
  23.             {   
  24.           
  25.    //Instantiate List Object and get the SLA Expired items  
  26.                 SPClientContext.Credentials = spOnlineCredentials;   
  27.                 Web spWeb = SPClientContext.Site.RootWeb;   
  28.                 List spList = spWeb.Lists.GetByTitle("SLA");   
  29.                 CamlQuery spQuery =  new CamlQuery();     
  30.                 spQuery.ViewXml = "<View><Query><Where><Eq><FieldRef Name='SLADate'/><Value Type='DateTime'><Today /></Value></Eq></Where></Query><RowLimit>100</RowLimit></View>";  
  31.                 ListItemCollection spListIems = spList.GetItems(spQuery);   
  32.                     
  33.                 SPClientContext.Load(spListIems);    
  34.                 SPClientContext.ExecuteQuery();    
  35.                    
  36.                 //Email the expired items to user using SPUtility  
  37.          string emailBody = "<b>Expedite the below items by EOD</b> </br><table style='border: 1px solid black;'>";  
  38.                 foreach (ListItem spListItem in spListIems)  
  39.                 {  
  40.                     emailBody +=   "<tr style='color:red;'><td><b>"+ spListItem["Title"] +"</b></td><td>"+spListItem["SLADate"]+"</td></tr>";  
  41.                     
  42.                 }  
  43.                 emailBody +=  "</table>";   
  44.    
  45.                 Microsoft.SharePoint.Client.Utilities.EmailProperties emailProperties = newMicrosoft.SharePoint.Client.Utilities.EmailProperties();  
  46.                 emailProperties.To = new string[] { "[email protected]" };  
  47.                 emailProperties.Subject = "Attention : Below Items have expired their SLA";  
  48.                 emailProperties.Body = emailBody;  
  49.                 Microsoft.SharePoint.Client.Utilities.Utility.SendEmail(SPClientContext, emailProperties);  
  50.            
  51.                 SPClientContext.ExecuteQuery();  
  52.                 log.Info($"Count of List Items with Expired SLA: {spListIems.Count}");   
  53.             }   
  54.         }   
  55.         catch(Exception ex){   
  56.             log.Info($"Azure Function Exception: {ex.Message}");   
  57.         }      
  58.  }  

Once the code is added, save and run the code.

SharePoint

The logs section will show the progress of the compilation. We have also outputted the retrieved count of the list items with expired SLA. In case we face any error, we can view these logs in the Monitor section. As shown below, I once got an authentication exception.

SharePoint

Demo of SharePoint Online Timer Simulation using Azure Function

The demo of the code is shown below. We have 2 items that have SLA Date as today(date the code was run is 6/17/2017)

SharePoint

The Azure Function has triggered and the items have been picked from SharePoint List and the mail has been triggered to Service User.

SharePoint

We can see the complete run time logs of the azure function by going to the Monitor section.

SharePoint

We can change the schedule at which the timer has to be triggered from the Integrate section as shown below. By default, it will be triggered every 5 minutes. We can set the schedule using the CRON format as mentioned here.

SharePoint

If we want to stop the timer from triggering we can go ahead to the Manage Section and Set the Function State to Disabled so that it doesn’t trigger unless enabled again.

SharePoint

Once it is disabled, we can see the function with a disabled state as shown below.

SharePoint

Azure Function in Action

The video recording of the demo is shared here

Summary

Thus, we have seen the implementation of Azure Functions to simulate Timer Jobs for SharePoint Online.

Up Next
    Ebook Download
    View all
    Learn
    View all