Introduction
In SharePoint you can use timer jobs to perform scheduled tasks. These timer jobs are farm solutions or full trust solutions which needs to be deployed in SharePoint server and need to run with farm account. If we want to achieve the same functionality of timer job in SharePoint Online or any hosted environment, it is not possible as we cannot deploy farm solutions in SharePoint online and hosted environments.
Without writing farm solutions you can still achieve the functionality of timer jobs using SharePoint Apps by writing the code in operations supported by CSOM and schedule the task can be done using windows task for on premise or Azure Webjobs for cloud.
SharePoint Apps: SharePoint apps are solutions that are easy to install and uninstall and apps are hosted either client side or in cloud but not on SharePoint server..
Azure Webjobs: Azure Webjobs is a new feature of Azure websites that allow you to run programs or tasks at regular intervals. You can schedule the job to run continuously or on a particular schedule or can run on demand.
Scheduling – For on premises scheduling of the job can be done using Windows Task and for scheduling in cloud you can use new Webjobs capability of Azure websites.
Pre-requisites for this sample
- Developer site – can be on premise SharePoint site or an Office 365 developer site.
- A subscription to Microsoft Azure
To achieve this functionality we need a SharePoint App and a console application.
SharePoint app will handle the authentication and assigns permissions required to connect and access the SharePoint site.
Console application will contain the logic that needs to be executed as per schedule.
Step - 1: Create a console application.
To create a console application, launch visual studio as a administrator and click on
File ->New ->Project ->Visual C# -> and select Console Application.
Step -2: Add the Nuget packages
From Visual Studio- navigate to Tools -> Nuget Package Manager -> and select “Manage Nuget Packages for Solution” as shown in the below.
Select “Nuget.org” and search for “App for SharePoint Web Toolkit” and click on “Install”. This will add “TokenHelper.cs” and “SharePointContext.cs” classes to the solution. TokenHelper and SharePointContext classes help the console application in getting access to SharePoint site using client id and client secret.
Step -3: Write the code in console application
Write the code that needs to be executed by the job in “Program.cs” using CSOM . You can perform the operations supported using CSOM. The following sample creates a list if it does not exists and creates items. You can write any logic that needs to be executed by the job.
Add the following code in Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SharePoint.Client;
using System.Configuration;
using System.Collections.Specialized;
using System.IO;
using System.Security;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
var config = (NameValueCollection)ConfigurationManager.GetSection("Sites");
foreach (var key in config.Keys)
{
Uri siteUri = new Uri(config.GetValues(key as string)[0]);
string listname = "My List";
string realm = TokenHelper.GetRealmFromTargetUrl(siteUri);
string accessToken = TokenHelper.GetAppOnlyAccessToken(
TokenHelper.SharePointPrincipal,
siteUri.Authority, realm).AccessToken;
using (var clientContext =
TokenHelper.GetClientContextWithAccessToken(
siteUri.ToString(), accessToken))
{
CheckListExists(clientContext, listname);
AddListItem(clientContext, listname);
}
}
}
private static void CheckListExists(ClientContext clientContext, string listName)
{
ListCollection listCollection = clientContext.Web.Lists;
clientContext.Load(listCollection, lists => lists.Include(list => list.Title).Where(list => list.Title == listName));
clientContext.ExecuteQuery();
if (listCollection.Count <= 0)
{
CreateList(clientContext, listName);
}
}
private static void CreateList(ClientContext clientContext, string listName)
{
Web currentWeb = clientContext.Web;
ListCreationInformation creationInfo = new ListCreationInformation();
creationInfo.Title = listName;
creationInfo.TemplateType = (int)ListTemplateType.GenericList;
List list = currentWeb.Lists.Add(creationInfo);
list.Description = "My custom list";
list.Update();
clientContext.ExecuteQuery();
}
private static void AddListItem(ClientContext clientContext, string listName)
{
Web currentWeb = clientContext.Web;
var myList = clientContext.Web.Lists.GetByTitle(listName);
ListItemCreationInformation listItemCreate = new ListItemCreationInformation();
Microsoft.SharePoint.Client.ListItem newItem = myList.AddItem(listItemCreate);
newItem["Title"] = "Item added by Job at " + DateTime.Now;
newItem.Update();
clientContext.ExecuteQuery();
}
}
}
Step -4: Create a website in Windows Azure
Use Azure WebJobs feature of Azure websites for scheduling the job. So let’s create an Azure website first.
To create a new website, log in to Azure management portal http://manage.windowsazure.com/.
Click the “NEW” -> select “WEBSITE” -> select “QUICK CREATE” and enter the URL -> and click “CREATE WEBSITE”.
Now we are done with creating a console application and we have an azure website. Now we need an app. You can create a provider hosted app using Visual studio. When you develop an app using Visual studio and when you hit F5, visual studio will take care of app registration. This means it will generate the client id and secret and update the web.config of the provider hosted app web. This works for development environment. If you want to deploy our app to a different site then we need to register the app using /_layouts/15/appregnew.aspx. Since we don’t need any UI and we need app just for getting client id and client secret which will be used by the console application for getting access to SharePoint site. Let not create a provider hosted app instead let just register the app and use the secret in console application.
Step -5: App Registration
To register an app we need to follow the below steps
- Go to /_layouts/15/appregnew.aspx and create a client id and client secret.
- Provide permissions using /_layouts/15/appinv.aspx.
- Update the app.config of console application with client id and secret
Follow the below steps to register app using /_layouts/15/appregnew.aspx page of the Sharepoint site.
- Navigate to the following url https://<yoursharepointsitename>/sites/DevSite1/_layouts/15/appregnew.aspx
- Click on “Generate” button to generate a client id.
- Click on “Generate” to get client secret.
- Enter a name for the app in “Title”
- In App Domain – for on premise SharePoint site enter the App Domain name. For SharePoint online enter the name of the site we just created using Azure Portal.
- Click “Create”
g. Copy the Client Id and Client secret created. We need to update these details in app.config file
h. Provide App permissions by using /_layouts/15/AppInv.aspx. Follow the below steps to provide permissions to app to access SharePoint site.
- Navigate to the url. https://<yoursharepointsitename>/sites/DevSite1/_layouts/15/appregnew.aspx
- Paste the “Client id” generated in app registration page and click on “Lookup”. This will populate the details of the app in other textboxes.
- Enter the following XML in “App’s permission request XML” textbox. This will add permissions to the app.
<AppPermissionRequests AllowAppOnlyPolicy="true">
<AppPermissionRequest Scope="http://sharepoint/content/tenant" Right="Manage" />
</AppPermissionRequests>
i. Trust the App to get necessary permissions
j. Update the App.Config of the console application and copy the “Client Id” and “client secret” generated in the app registration step. Console application will use the client id and secret to authenticate and get access/connect to SharePoint.
<configuration>
<configSections>
<section name="Sites"
type="System.Configuration.NameValueSectionHandler"/>
</configSections>
<Sites>
<add key="site2"
value="https://XXX.sharepoint.com/sites/DevSite1/"/>
</Sites>
<appSettings>
<add key="ClientId" value="64d869cf-05b1-44a2-9557-ab8f0a756218"/>
<add key="ClientSecret" value="zZUV7HuLS07Hb9z1T2NV+QWFxMwHLxcx5ov4A525p5A="/>
</appSettings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
Step -6: Schedule the timer job.
You can schedule the timer job using Windows task for on premise or for cloud can use Azure Webjobs for scheduling the job. You can publish directly from Visual Studio or create webjob and upload the zip file in Azure Portal.
Create the WebJob and upload the Zip file in Azure Portal – to publish to windows azure web jobs, build the project. Go to bin-> Debug.
a. Create a Zip file of the build output of the console application
b. Go to Azure Management Portal à Websites à Click on the website you want to use for scheduling the jobc. Click on WebJobs à and click on “Add” to create a new web job
d. Enter a name for the WebJob and upload the zip file
e. You can schedule it to
- “Run Continuously” – after completing it will start and run again.
- Or create a schedule by using “Run on Schedule” – run on the schedule.
- Or use “Run on Demand” – run whenever you want
f. This will create a new job, you can check the notification as shown below. To run the job click on “RUN ONCE”
g. Upon successful execution it will show the message
Step -7: You can Publish the job directly from Visual Studio
To Publish from Visual Studio, right click project and select “Publish as Azure Website”
a. It will launch the “Add Azure Webjob” dialog. Enter name of the job and schedule details
b. After clicking “OK” it will add the Nuget packages and then will launch the “Publish Web” dialog.You can select “Publish Target”. Click on “Microsoft Azure Websites” to publish to Windows Azure.
c. It will launch the “Select Existing Website” dialog. You can select and Existing Website in Azure or create a new website. To select an existing website select the site name from the dropdown.
d. To create a new website click on the “NEW” button.
e. Enter the site name and select the region
f. Click "Create" button, this will create a new website in Azure.
g. Click the "Publish" button to publish the website.
Visual Studio will show the “site published successfully” message.
Check the job published in Azure portal.
h. The job runns successfully and creates the list in SharePoint site if it does not exists and adds an item every time the jobs runs. Following is the list create by job and tems added by job in the SharePoint site.