Skip to main content

Running Timed Jobs within SharePoint


Programming a Timed Job


The Job installed in the aforementioned paragraph does not actually work because there is no "logic" to execute. To create a new Job, it is necessary to program a new class library and add it to the Global Assembly Cache (GAC) to make the logic accessible to SharePoint.
The first step is to create a new "Class Library" Visual Studio 2005 project with a suitable name, then add a reference to Windows SharePoint Services (Microsoft.SharePoint.dll) and "using" directives to Microsoft.SharePoint and Microsoft.SharePoint.Administration. The Class needs to inherit from "SPJobDefinition" and to have at least one constructor to initialize the new objects. The definition of the empty class reads:
using System;
using System.IO;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace CountDocs
{
   public class CountDocsJob : SPJobDefinition
   {
      public CountDocsJob()
      {
      }

      //public CountDocsJob(string MyJobName,
      //SPService MyService,
      //SPServer MyServer, SPJobLockType MyTargetType) :
      //base(MyJobName, MyService, MyServer, MyTargetType)
      //{
      //}

      public CountDocsJob(string MyJobName, SPWebApplication
         MyWebApplication) : base(MyJobName, MyWebApplication,
         null, SPJobLockType.Job)
      {
      }

      public override void Execute(Guid ContentDataBaseID)
      {
      }
   }
}
The base class has two constructors but if two are unnecessary, it is possible to define only one (the second one is commented in the example). The constructor of the sub-classing indicates that the third parameter (the SPServer parameter) is superfluous in this case.

blic override void Execute(Guid ContentDataBaseID)
The functional source code is written in the override "Execute" function. This function always has a parameter that receives the ID of the SharePoint's content DataBase that is executing the Job. For the example, the code reads the number of entries in a List and each time it runs, a new entry is created indicating the time and number of found entries:
{
   try
   {
      SPSite mySite = new SPSite("http://ServerName");
      SPWeb myWeb = mySite.OpenWeb();
      SPList myList = myWeb.Lists["MyJobs"];

      int intCounter = 0;
      foreach (SPListItem myItem in myList.Items)
         intCounter++;

      SPListItem newTask = myList.Items.Add();
      newTask["Title"] = "Counter of Items at " +
         DateTime.Now.ToString();
      newTask["Description"] = "At " + DateTime.Now.ToString() +
         " there are " + intCounter.ToString() +
         " items in the List";
      newTask.Update();
   }
   catch (Exception ex)
   {
      TextWriter myWriter =
         new StreamWriter(@"c:\CountDocsJobError.txt");
      myWriter.WriteLine(ex.ToString());
      myWriter.Close();
   }
}
In the case in point, the code makes a reference to the Site, Web, and List, counts the number of entries in the List, and creates a new entry. The names of the Site and List are fast-coded, but they can be configured in the web.config file of the WebApplication using code similar to this:
Configuration MyConfig =
   WebConfigurationManager.OpenWebConfiguration("/", "Sharepoint -80");
string myValue = myConfig.AppSettings.Settings["MyKeyName"].value;
or extracted from the "ContentDataBaseID" variable.
Sign the assembly with a Safe Name and install it in the GAC (obligatory). After resetting the IIS (iisreset), the previously discussed "CreateJob" routine can be modified to install the Job in the server:
static void CreateJob()
{
   SPServer myServer = SPServer.Local;
   SPSite mySite = new SPSite("http://ServerName");
   SPWebApplication myApplication = mySite.WebApplication;
   SPJobDefinitionCollection myJobsColl =
      myApplication.JobDefinitions;

   CountDocsJob myJob = new CountDocsJob("myCountDocsJob",
      myApplication);
   myJob.Title = "Docs Counter Job";

   SPMinuteSchedule myMinuteSchedule = new SPMinuteSchedule();
   myMinuteSchedule.BeginSecond = 0;
   myMinuteSchedule.EndSecond = 59;
   myMinuteSchedule.Interval = 1;
   myJob.Schedule = myMinuteSchedule;

   myJobsColl.Add(myJob);
   myApplication.Update();

   Console.WriteLine("Job Installed");
}

Comments

Popular posts from this blog

SharePoint SPFX components basic details and understanding

Microsoft developed SharePoint, a web-based platform that enables businesses and organisations to share and manage documents and information. The SharePoint Framework (SPFx) is a set of client-side tools and components that can be used to construct unique solutions on top of SharePoint. The creation of a SharePoint SPFx component will be covered in this blog. Let's address specific requirements before creating a SharePoint SPFx component. Install the necessary software on your computer: Version 10 or later of Node.js SharePoint Framework (SPFx) generator using Git Now that all the prerequisites have been deployed, let's start developing the SharePoint SPFx component. Start by making a new SPFx project. Making a new SPFx application is the initial step. Launch the command prompt and execute the following commands  yo @microsoft/sharepoint The Yeoman generator for the SharePoint Framework will be started using this command. You will be prompted to enter details about your project...

How to deal with SharePoint 2010 exception "An exception occurred when trying to issue security token: The server was unable to process the request due to an internal error"

Scenario: You receive the below exception when you try to logon to a site that has been configured to use Claims Based Authentication with a custom membership provider using FBA credentials: Event ID from Event Log  - 8306 An exception occurred when trying to issue security token: The server was unable to process the request due to an internal error.  For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug> configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework 3.0 SDK documentation and inspect the server trace logs.. Explanation: This error started to appear in our QA environment which does not have Visual Studio installed. I have tried starting the service "Claims to Windows Token Service" but that did not help either. I have made sure that all config...

Cascading drop down column in a SharePoint List

This article will show how to use codeplex project to achieve Cascading drop down columns in SharePoint list. This article will show how to achieve parent child relationship in column of SharePoint list.   Objective This article will show how to use codeplex project to achieve Cascading drop down columns in SharePoint list. This article will show how to achieve parent child relationship in column of SharePoint list. Step 1 Download the project from codeplex . Choose WSP file to download. To download the project Click here Step 2 After downloading the WSP add the solution using STSADM command. Navigate to BIN folder and add the solution. Command C:\Program Files\Common Files\microsoft shared\Web Server Extensions\12\BIN> stsa dm -o addsolution -filename c:\Stoneshare.CascadingDropDown.WithFilter.wsp Step 3 Open Central ADMIN and deploy solution. Navigate to Operation -> Global Configuration -> Solution Management. Select the Global Deployment option. St...