Simulate SharePoint Online Timer Jobs Using Azure Functions

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 case of SharePoint Online Native Timer Jobs cannot be used.

 

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 

#r "Microsoft.SharePoint.Client.Runtime.dll"   
#r "Microsoft.SharePoint.Client.dll"  
using System;   
using System.Net;   
using Microsoft.SharePoint.Client;   
   
     
public static void Run(TimerInfo myTimer, TraceWriter log)   
{   
               
        //In real scenario, make use of Azure Key Vault to store and retrieve password  
        string password = "<Your Office 365 Credential>";   
        System.Security.SecureString securePassword = new System.Security.SecureString();   
        foreach (char pass in password) {  
            securePassword.AppendChar(pass);  
    }                
        //Get SPOnline User Credentials  
        SharePointOnlineCredentials spOnlineCredentials = newSharePointOnlineCredentials("Priyaranjan@SharePointChronicle.com", securePassword);   
        try{   
               
             //Create the Client Context  
            using (var SPClientContext = new ClientContext("https://ctsplayground.sharepoint.com   "))   
            {   
          
   //Instantiate List Object and get the SLA Expired items  
                SPClientContext.Credentials = spOnlineCredentials;   
                Web spWeb = SPClientContext.Site.RootWeb;   
                List spList = spWeb.Lists.GetByTitle("SLA");   
                CamlQuery spQuery =  new CamlQuery();     
                spQuery.ViewXml = "<View><Query><Where><Eq><FieldRef Name='SLADate'/><Value Type='DateTime'><Today /></Value></Eq></Where></Query><RowLimit>100</RowLimit></View>";  
                ListItemCollection spListIems = spList.GetItems(spQuery);   
                    
                SPClientContext.Load(spListIems);    
                SPClientContext.ExecuteQuery();    
                   
                //Email the expired items to user using SPUtility  
         string emailBody = "<b>Expedite the below items by EOD</b> </br><table style='border: 1px solid black;'>";  
                foreach (ListItem spListItem in spListIems)  
                {  
                    emailBody +=   "<tr style='color:red;'><td><b>"+ spListItem["Title"] +"</b></td><td>"+spListItem["SLADate"]+"</td></tr>";  
                    
                }  
                emailBody +=  "</table>";   
   
                Microsoft.SharePoint.Client.Utilities.EmailProperties emailProperties = newMicrosoft.SharePoint.Client.Utilities.EmailProperties();  
                emailProperties.To = new string[] { "Priyaranjan@SharePointChronicle.com" };  
                emailProperties.Subject = "Attention : Below Items have expired their SLA";  
                emailProperties.Body = emailBody;  
                Microsoft.SharePoint.Client.Utilities.Utility.SendEmail(SPClientContext, emailProperties);  
           
                SPClientContext.ExecuteQuery();  
                log.Info($"Count of List Items with Expired SLA: {spListIems.Count}");   
            }   
        }   
        catch(Exception ex){   
            log.Info($"Azure Function Exception: {ex.Message}");   
        }      
 }  

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.

 

原文地址:https://www.c-sharpcorner.com/article/simulate-sharepoint-online-timer-jobs-using-azure-functions/

posted @ 2019-05-29 13:28  乘奔御风  阅读(405)  评论(0编辑  收藏  举报