Search This Blog

Wednesday, December 17, 2014

Create custom Timer jobs in sharepoint 2010-- For Sending Email

In this article, I am going to show you how to create custom timer jobs in SharePoint 2010.

Formally creating a custom Timer jobs using visual studio 2010 is very straight forward. Open your visual studio, Select New project in File menu, choose “Empty SharePoint Project” option, then enter your project and solution name and click OK.

SharePoint wizard window shows two type of trust level option. In these, select “Deploy as a farm solution” option (The timer jobs dll will be put it on GAC folder), click Finish. Now, the empty SharePoint project is created.

Add a new class in your project and inherits Microsoft.SharePoint.Administration.SPJobDefinition class into your created class. To implement Timer jobs, you have to create few constructor and Execute method in your class file. After creating constructor and Execute method you can see your class file look like below code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.Net.Mail;
namespace Sending_Email_Using_Timer_jobs
{
    class SendingEmail:SPJobDefinition
    {
        public SendingEmail():base()
        {

        }
          public SendingEmail(string jobName, SPService service, SPServer server, SPJobLockType targetType):base(jobName, service, server, targetType)
        {

        }

          public SendingEmail(string jobName, SPWebApplication webApplication): base(jobName, webApplication,nullSPJobLockType.ContentDatabase)
        {
            this.Title = "Creating list";
        }

        public override void Execute(Guid contentDbId)
        {
            // get a reference to the current site collection's content database
            SPWebApplication webApplication = this.Parent as SPWebApplication;
            SPContentDatabase contentDb = webApplication.ContentDatabases[contentDbId];

            // get a reference to the "Creating list" in the RootWeb of the first site collection in the content database
            SPList Listjob = contentDb.Sites[0].RootWeb.Lists["List"+DateTime.Today.ToString()];
            // create a new list Item, set the Title to the current day/time, and update the item
            SPListItem newList = Listjob.Items.Add();
            newList["Title"] = DateTime.Now.ToString();
            newList.Update();

            /*sending email after list created successfully in site*/

            if (!string.IsNullOrEmpty(Convert.ToString(contentDb.Sites[0].RootWeb.Lists.TryGetList("List" +DateTime.Today.ToString()))))
            {
                SmtpClient smtpClient = new SmtpClient();
                MailMessage message = new MailMessage();
                smtpClient.Host = "your host address";
                message.IsBodyHtml = true;
                message.From = new MailAddress("balamurugan@mail.com");
                message.To.Add("smmani@mail.com");
                message.Subject = "Test Timer jobs";
                AlternateView htmlView = AlternateView.CreateAlternateViewFromString("The list has been created successfully<br/>" + contentDb.Sites[0].RootWeb.Lists["List" + DateTime.Today.ToString()].DefaultViewUrl + "",null"text/html");
                message.AlternateViews.Add(htmlView);
                message.Priority = MailPriority.Normal;
                smtpClient.Send(message);
            }
        }
    }
}


In code, you can see “SPJobLockType” enum method which indicates timer jobs instance running level. I will explain this in my later post. Keep focusing on timer job creation.

Execute method is a place for writing our business logic in the timer jobs. Override Execute method and write your business logic. In my example, I have added a sending email code after the list created in the site.

To create a feature to deploy your timer jobs in your environment .Go to Feature folder, right click and add Feature. Right now, we have created a feature to activate the timer jobs . 


To install/uninstall the timer jobs on server, we have to do a little bit of code stuff. To create Event receiver code, Go to just now created feature file, Right click and choose Add Event Receiver Option. Now, you can see a new event receiver class file added into your solution package 



Add install and uninstall timer jobs code in Feature activated and feature deactivated method. In my code, I am activating createlist timer jobs in web application level and running in every 5 minutes interval.

The following class is providing you to run the timer jobs as per business criteria using code

    SPOneTimeSchedule –Represents a schedule that specifies the time range during which the job will run.
    SPMinuteSchedule – runs job a minute schedule
    SPHourlySchedule – runs job an Hourly schedule
    SPDailySchedule – runs job a Daily schedule
    SPMonthlySchedule – runs job a Monthly schedule
    SPWeeklySchedule – runs job a Weekly schedule
    SPYearlySchedule – runs job a Yearly schedule

using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Administration;

namespace Sending_Email_Using_Timer_jobs.Features.Timer_jobs
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("e550963a-1a8c-4751-9f53-eeaa0200ec03")]
    public class Timer_jobsEventReceiver : SPFeatureReceiver
    {
       
        const string Create_list = "Creating list";
        // Uncomment the method below to handle the event raised after a feature has been activated.

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPWebApplication webapplication = properties.Feature.Parent as SPWebApplication;

            // make sure the job isn't already registered

            foreach (SPJobDefinition job in webapplication.JobDefinitions)
            {

                if (job.Name == Create_list)

                    job.Delete();

            }

            // install the job

            SendingEmail createlistJob = new SendingEmail(Create_list, webapplication);
            SPMinuteSchedule schedule = new SPMinuteSchedule();
            schedule.BeginSecond = 0;
            schedule.EndSecond = 59;
            schedule.Interval = 5;
            createlistJob.Schedule = schedule;
            createlistJob.Update();

        }

        // Uncomment the method below to handle the event raised before a feature is deactivated.

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPWebApplication webapplication = properties.Feature.Parent as SPWebApplication;

            // delete the job

            foreach (SPJobDefinition job in webapplication.JobDefinitions)
            {

                if (job.Name == Create_list)

                    job.Delete();

            }

        }
    }
}


Select correct feature scope before deploying your solution. I have used web application scope to run my timer jobs.


After select correct scope, our package is ready to deploy .Right click solution and select Build, and then Deploy.


No comments:

Post a Comment