Dynamically retrieve Site Collection URL from the Sharepoint Timer Job


using following timer job i deleted two years old records, all these records are deleted at a time
I used property bag for get the site collection url 

               Open the Visual studio .Net 2012 
                click on File
                next click on  New 
                next click on Project 


                  After selecting the project it displays following screen  

  
 
                Select SharePoint 2013 –Empty Project 

               Give following details
            Name: AXALTA.DPCIFORMS.Y2ItemsDeletion (Ex: ClientName.DatabaseName.TimeJobName)
              Location: c:\users\avenkateswarlu\documents\visual studio 2012\Projects
              Solution Name: AXALTA.DPCIFORMS.Y2ItemsDeletion 

è                                 Click on OK button
           it displays following screen




è                                                   Give Site URL : http://htshydasm38/sites/Hexacorp/
è                                                 Select deploy as a farm solution
è                                                 Click on Finish button

                    Next go to solution explorer
è                                             Click on Feature
                          next click on Add Feature

                      

                        Rename The Feature: 2YItemsDeletion


                                

                      Select Feature Scope: Site

                   

                       Select the Feature Name and Right Click Add Event Reciever
                       
Add One Class for mentioning the Constants

Click on solution
select Add
next select New Item
next select Code
next select Class File
Give Class Name as Global

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AXALTA.DPCIFORMS.Y2ItemsDeletion
{
    public class Globals
    {
        public static string JobName = "TwoYearsItemsDeletionJob";
        public static string SiteCollectionURL = "SiteURL";
        public static string ListName = "TimerList";
        public static string ListName_CreatedDate = "CreatedDate";
    }
}

Above Class Includes Job name, List Name  etc.

Write the following code in feature Receiver class 

   public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            if (properties != null)
            {
                SPSite site = properties.Feature.Parent as SPSite;
                // make sure the job isn't already registered
                foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
                {
                    if (string.Equals(job.Name, Globals.JobName))
                    {
                        job.Delete();
                    }
                }
                //// install the job
                TwoYearsItemsDeletionJob siteCollectionUrlJob = new                    TwoYearsItemsDeletionJob(Globals.JobName, site.WebApplication);
                //// Below you set the property bag with site collection URL 
                    on which your timer job is registered
                  , that you can use in execute method
                siteCollectionUrlJob.Properties.Add(Globals.SiteCollectionURL, site.Url);

                SPMonthlySchedule OmonthlySchedule = new SPMonthlySchedule();
                OmonthlySchedule.BeginDay = 1;
                OmonthlySchedule.EndDay = 1;
                OmonthlySchedule.BeginHour = 1;
                OmonthlySchedule.EndHour = 1;
                OmonthlySchedule.BeginMinute = 15;
                OmonthlySchedule.EndMinute = 30;
                siteCollectionUrlJob.Schedule = OmonthlySchedule;
                siteCollectionUrlJob.Update();

               
            }
        }
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            if (properties != null)
            {
                SPSite site = properties.Feature.Parent as SPSite;
                // delete the job
                foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
                {
                    if (string.Equals(job.Name, Globals.JobName))
                    {
                        job.Delete();
                    }
                }
            }
        }

Add One Class for Running the Job


Click on solution
select Add
next select New Item
next select Code
next select Class File
Give Class Name as TwoYearsItemsDeletionJob

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AXALTA.DPCIFORMS.Y2ItemsDeletion
{
    public class TwoYearsItemsDeletionJob : SPJobDefinition
    {
         public TwoYearsItemsDeletionJob() : base() { }
         public TwoYearsItemsDeletionJob(string jobName, SPWebApplication webApp)

            : base(Globals.JobName, webApp, null, SPJobLockType.Job)
        {
            this.Title = Globals.JobName;
        }
        public override void Execute(Guid targetInstanceId)
        {
            string siteCollectionUrl = string.Empty;
            // Below you are fetching the same property bag value you set in feature activation
            if (!string.IsNullOrEmpty(this.Properties[Globals.SiteCollectionURL].ToString()))
            {
                siteCollectionUrl = this.Properties[Globals.SiteCollectionURL].ToString();
            }
            try
            {
                using (SPSite Osite = new SPSite(siteCollectionUrl))
                {
                    using (SPWeb Oweb = Osite.OpenWeb())
                    {
                        int count = 0;
                        SPList OList = Oweb.Lists[Globals.ListName];
                        SPListItemCollection OListItems = OList.Items;
                        StringBuilder sbDelete = new StringBuilder();
                        sbDelete.Append("<?xml version=\"1.0\" 
                                         encoding=\"UTF-8\"?>& lt;Batch>");
                        string command = "<Method><SetList 
                        Scope=\"Request\">" + OList.ID + "</SetList><
                        SetVar Name=\"ID\">{0}</SetVar>>
                        Delete</SetVar></Method>";
                        foreach (SPListItem it in OListItems)
                        {
                           string CeatedDate =
                                         Convert.ToString(it[Globals.ListName_CreatedDate]);
                            if (!string.IsNullOrEmpty(CeatedDate))
                            {
                           DateTime 
                          CreatedDate = Convert.ToDateTime(it[Globals.ListName_CreatedDate]);
                                DateTime CurrentDate = DateTime.Now;
                                DateTime TwoYearsoldDate = CurrentDate.AddYears(-2);
                                if (CreatedDate < TwoYearsoldDate)
                                {
                                    count += 1;
                                   sbDelete.Append(string.Format(command, it.ID.ToString()));
                                }
                            }
                        }
                        sbDelete.Append("</Batch>");
                        Oweb.AllowUnsafeUpdates = true;
                        if (count > 0)
                            Oweb.ProcessBatchData(sbDelete.ToString());
                        Oweb.AllowUnsafeUpdates = false;
                    }
                }
            }
            catch (Exception ex)
            {
                //
            }
        }
    }    
}

Click on Build à Next click on Deploy

Debugging:
In visual studio 2012.net
         Put break point at execute method
         Go to Debug menu click on attach process
         Select OWSTimer.EXE, w3wp process
        Click on OK button
Central administration:
      Monitoring
      Review Job definitions 
     Select the required Job definition
      Click on Run

Deployment commands:
Add the solution using following command 
Add-SPSolution C:\ AXALTA.DPCIFORMS.Y3ItemsDeletion.wsp 

Install the solution using following command 
Install-SPSolution -Identity "AXALTA.DPCIFORMS.Y3ItemsDeletion.wsp" -GACDeployment -CompatibilityLevel 15

we can get all features ids using following command 
get-SPFeature

Active the feature using following command  


Enable-SPFeature -Identity db39db05-c961-402f-b323-4dc6f1c68ff4 -URL http://htshydasm:1111/sites/AXALTA/ -Force -PassThru

Issues:


1.The Feature is not a Farm Level Feature and is not found in a Site level defined by the Url  


2.Something went to wrong (Critical issue)   

 we get first issue while feature activation using power shell

we get 2 issue while feature activation from the site collection features (UI)
 


3 comments: