Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Hosted-services / Azure

Step by step approach to create Timer Job Using SharePoint Apps

5.00/5 (4 votes)
4 Feb 2015CPOL7 min read 43.5K  
Create a timer job using SharePoint App model, CSOM and azure webjobs

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.

Image 1Step -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.

Image 2Image 3Image 4

​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”.Image 5Image 6

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

  1. Go to /_layouts/15/appregnew.aspx and create a client id and client secret.
  2. Provide permissions using /_layouts/15/appinv.aspx.
  3. 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.

  1. Navigate to the following url https://<yoursharepointsitename>/sites/DevSite1/_layouts/15/appregnew.aspx
  2. Click on “Generate” button to generate a client id.
  3. Click on “Generate” to get client secret.
  4. Enter a name for the app in “Title
  5. 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.
  6. Click “Create”

Image 7

g. Copy the Client Id and Client secret created. We need to update these details in app.config file

Image 8

 

h. Provide App permissions by using /_layouts/15/AppInv.aspx. Follow the below steps to provide permissions to app to access SharePoint site.

  1. Navigate to the url. https://<yoursharepointsitename>/sites/DevSite1/_layouts/15/appregnew.aspx
  2.  Paste the “Client id” generated in app registration page and click on “Lookup”. This will populate the details of the app in other textboxes.
  3. 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>

Image 9i. Trust the App to get necessary permissionsImage 10

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.

Image 11

a. Create a Zip file of the build output of the console applicationImage 12

b. Go to Azure Management Portal à Websites à Click on the website you want to use for scheduling the jobImage 13c. Click on WebJobs à and click on “Add” to create a new web job

Image 14d. Enter a name for the WebJob and upload the zip file

Image 15

e. You can schedule it to

  1. Run Continuously” – after completing it will start and run again.
  2. Or create a schedule by using “Run on Schedule” – run on the schedule.
  3. Or use “Run on Demand” – run whenever you want

Image 16

f. This will create a new job, you can check the notification as shown below. To run the job click on “RUN ONCE

Image 17

g. Upon successful execution it will show the message

Image 18Step -7: You can Publish the job directly from Visual Studio

To Publish from Visual Studio, right click project and select “Publish as Azure Website

Image 19

a. It will launch the “Add Azure Webjob” dialog. Enter name of the job and schedule details

Image 20

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.

Image 21

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.

Image 22d. To create a new website click on the “NEW” button.

Image 23

e. Enter the site name and select the region

Image 24

f. Click "Create" button, this will create a new website in Azure.

Image 25g. Click the "Publish" button to publish the website.

Visual Studio will show the “site published successfully” message.

Image 26

Check the job published in Azure portal.

Image 27

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.

Image 28

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)