Quantcast
Channel: The SharePoint Viking » Programming
Viewing all articles
Browse latest Browse all 2

A SharePoint 2010 Timer Job example with e-mail notification

$
0
0

I have from time to time seen requests for code samples using Timer Jobs in SharePoint 2010 (yes, not everyone has switched to 2013 yet!)  together with e-mail notification  in order to send reports from the job to recipients. A couple of months a go I did a project which monitored changes to doc libraries on a given site. To be specific,  I monitored changes to the Modified fields in the libraries.  I made it into a Timer Job that ran daily at 17.00 PM , checked if there had been any changes, and then created a simple report on the changes as a mail message to a list of subscribers. For the e-mail interface I used the System.Net.Mail library. Here’s a walkthrough of how I built the solution:

Create Project

Open Visual Studio 2010, create a new SharePoint 2010 Empty Project and give it an appropriate name,  eg.  “MonitorChanges”. Specify a SharePoint site for the deployment and set the project to deploy as  a Farm Solution.

Next, in Solution Explorer, richt click “Features” and then “Add Feature”.  Right click the new Feature1 node and rename it to “MonitorChangesFeature”.  The solution should now look like this:

Double-click the MonitoreChangesFeature node to open the Feature Designer. Set title to “MonitorChanges”, add some text in the Description field, and set scope to “WebApplication”.

Set the Job Schedule

To set up the timer schedule for the job when it’s deployed to the farm, we are going to use an event receiver. In Solution Explorer, right-click the MonitorChangesFeature node and then select “Add Event Receiver”.

Open up the newly created .cs file, uncomment the FeatureActivated and FeatureDeactivating events, and remove the remaining commented code lines.  Add the following code to the FeatureActivated event:

The code checks for existing instances of the job and deletes them if there are any. Our job is associated with a web application so we have to cast the parent feature accordingly in order to get a reference to the running job. Next it creates an instance to an SPJobDefinition-derived class (which we will create shortly).  I then use an SPDailySchedule  object to set up the job to run on a daily basis starting at 17.00 PM . Finally I assign it to the job’s Schedule property and call its Update() method.

Add the code below to the FeatureDeactivating event to make sure any instances of the job are deleted when the feature is deactivated:

Create SPJobDefinition-derived class

With the scheduling functionality in place, it’s time to add the job functionality itself.  Add a new class to the project  ( in Solution Explorer, right-click project name , then “Add New Item->Class”).  Name the file MonitorChanges and click “Add” . Open the file and add 2 using statements for Microsoft.SharePoint and Microsoft.SharePoint.Administration.

Set the MonitorChanges class to inherit from SPJobDefinition. Then add the following 3 constructors:

The last constructor is the one being invoked from the FeatureActivated event. As you can see I have set the SPJobLockType enum to Job, which forces the job to run on only one machine in the farm ( I only have one machine in mine, so setting SPJobLockType to None would probably have same effect).

In order to make the job  run,  you have to override the Execute() method of the SPJobDefinition class. Add the following code below the constructors:

To ensure that the job has full control rights, I run the code inside a RunWithElevatedPrivileges block. This may not always be necessary, so depending on the type of task to be executed, the block can be removed. Then set the url in the SPSite constructor to point to the site you specified during the creation of the project.

I want to check for changes in all document libraries in all the subsites under the current site. To achieve that goal I use a SPSiteDataQuery object with the Webs property  set to the Recursive scope and Lists set to 101.  The query returns the Title field from all documents with changes in the Modified field during the last 24 hours.  The results are put in a DataTable object ( you may have to add another using statement for System.Data).  Then the titles are read into a local List object.

Add the E-Mail functionality

With a list of changed document titles available, it’s time to add the code that creates and sends the mail message  with the data to the subscribers. To keep things simple, the subscribers are stored in a default custom list on the site where the e-mail addresses are located in the Title field.

Add the e-mail helper method below to the MonitorChanges class ( you may have to add a using statement for System.Net.Mail):

The SPWebApplication.OutBoundMailServiceInstance.Server.Name property contains the registered mail server name from the farm settings (found in Central Admin->System Settings->Configure outbound e-mail settings->Outbound SMTP Server ) .  The rest of the code composes the mail header and body into a message listing the changed document names. I also use a couple of helper methods to get the e-mail addresses from the subscribers list to populate the MailMessage.To property and to create the mail body:

Finally,  add a call to MailChangesToSubscribers() at the end of the Execute() method (after the for (int i…) loop):

Build and deploy the project.  If everything went well, your timer job should now be listed along with the  others on the scheduled jobs page .  Open Central Admin->Monitoring->Review Job Definitions and verify that the MonitorChanges  job is listed. Double-click the title to open the Edit Timer Job page and verify that the job is set to run daily at 17 PM.

To test it, create the Subscribers list as a default list on the test site, and add a new item with your mail address in the Title field.  Add a document to the Shared Documents library or edit an existing one, and verify that you receive a mail after 17 PM,  containing the new document title in the mail body. Then try changing several documents in different libraries and run another job test.

Happy coding , and I hope you won’t become too annoyed by my obsession with black code editor backgrounds !


Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles



Latest Images