Monday, June 4, 2012

How to create a timer job in SharePoint programmatically.

To add a Timer Job in SharePoint site through code we need to go through following steps. It will add a simple timer job to site which will update Task list in every five minutes with current Date and Time.

Step 1: Add a new class to Visual Studio which is inheriting from SPJobDefinition for getting this include this namespace :

 using Microsoft.SharePoint.Administration;

public class TimerJobAction : SPJobDefinition
    {
        public TimerJobAction()
            : base()
        {
        }

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

        public TimerJobAction(string jobName, SPWebApplication webApplication)
            : base(jobName, webApplication, null, SPJobLockType.ContentDatabase)
        {
            this.Title = "Task Logger";
        }

        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 "Tasks" list in the RootWeb of the first site collection in the content database
            SPList taskList = contentDb.Sites[0].RootWeb.Lists["Tasks"];
            // create a new task, set the Title to the current day/time, and update the item
            SPListItem newTask = taskList.Items.Add();
            newTask["Title"] = DateTime.Now.ToString();
            newTask.Update();
        }
    }

Step 2: Now add a new feature of a site scoped and put this code in the Feature Activation to associate timer job to particular site :

 public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {

            SPSite spSite = properties.Feature.Parent as SPSite;
            foreach (SPJobDefinition spJob in spSite.WebApplication.JobDefinitions)
            {
                if (spJob.Name == TASK_LOGGER_JOB_NAME)
                {
                    spJob.Delete();
                }
            }

            TimerJobAction timerJobAction = new TimerJobAction(TASK_LOGGER_JOB_NAME, spSite.WebApplication);

            SPMinuteSchedule schedule = new SPMinuteSchedule();
            schedule.BeginSecond = 0;
            schedule.EndSecond = 59;
            schedule.Interval = 5;
            timerJobAction.Schedule = schedule;

            timerJobAction.Update();
        }

Step 3: Now to dissociate timer job from particular site we need to put the following code in Feature Deactivation :

 public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPSite spSite = properties.Feature.Parent as SPSite;
           
            foreach (SPJobDefinition spJob in spSite.WebApplication.JobDefinitions)
            {
                if (spJob.Name == TASK_LOGGER_JOB_NAME)
                {
                    spJob.Delete();
                }
            }

        }

Now deploy this feature to your site and activate it. It will update the Tasks in every 5 minute and you should check it in Central Admin that Timer Job is running and deployed properly. 


How to retract, uninstall, install, a WSP solution through a .bat file.

@echo off

set SPAdminTool=%CommonProgramFiles%\Microsoft Shared\web server extensions\12\BIN\stsadm.exe

set DeploymentLogName="Deployment_SolutionName.log"

set Title="Your Site Title"

set url="http://servername:portname/sites/sitename"

echo ============ Deployment Started on %Date% at %Time% ============ >>%DeploymentLogName% 2>&1

@pause
echo Deployment Started...
echo.

echo ============ Installing %Title% Application Please wait ...  You might get the message "Press any Key to  continue" before resetting the IIS. You have to hit any key to continue the deployment============
echo.
echo ============ Adding solution and features ============>>%DeploymentLogName% 2>&1
echo.

@pause
echo Retracting Solution...
echo.

echo ====== Retracting package "SolutionName.wsp" if already exists... >>%DeploymentLogName% 2>&1
echo Please ignore the warning message if it does not exists...>>%DeploymentLogName% 2>&1
echo.>>%DeploymentLogName% 2>&1

"%SPAdminTool%" -o retractsolution -name "SolutionName.wsp" -immediate -allcontenturls>>%DeploymentLogName% 2>&1
"%SPAdminTool%" -o execadmsvcjobs>>%DeploymentLogName% 2>&1

@pause
echo Deleting Solution...
echo.

echo ====== Deleting package "SolutionName.wsp" if already exists... >>%DeploymentLogName% 2>&1
echo Please ignore the warning message if it does not exists...>>%DeploymentLogName% 2>&1

"%SPAdminTool%" -o deletesolution -name "SolutionName.wsp" -override>>%DeploymentLogName% 2>&1

@pause
echo Adding Solution...
echo.

echo ====== Adding package "SolutionName.wsp" ...>>%DeploymentLogName% 2>&1

"%SPAdminTool%" -o addsolution -filename "SolutionName.wsp" >>%DeploymentLogName% 2>&1

@pause
echo Deploying Solution...
echo.

echo ====== Deploying package "SolutionName.wsp" >>%DeploymentLogName% 2>&1

"%SPAdminTool%" -o deploysolution -name "SolutionName.wsp" -allowgacdeployment -url "%url%" -immediate -force>>%DeploymentLogName% 2>&1
"%SPAdminTool%" -o execadmsvcjobs >>%DeploymentLogName% 2>&1


@pause

echo ============ Adding solution and features ends ============>>%DeploymentLogName% 2>&1

@pause
echo.>>%DeploymentLogName% 2>&1
echo DEPLOYMENT COMPLETED at %Time% !!! >>%DeploymentLogName% 2>&1
echo DEPLOYMENT COMPLETED !!! Please review at the Deployment.log for any errors...
echo Please Reset IIS manually in all the Web Front End Servers.
@pause