Working with Timer Jobs:
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
è
è
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 Receiver
--> Add One Class for mentioning the Constants
Click on solution -- > select Add -- > New
Item --> Code -- >Select Class File
- - > Give Class Name as Global
using Microsoft.SharePoint;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Axalta.Global.DpciformsTimerJobs
{
public class GlobalConstants
{
public static string JobName = "TwoYearsItemsDeletionJob";
public static string SiteCollectionURL = "SiteURL";
public static string ListName_NotesCda = "NotesCDA";
public static string NotesCda_Created = "Created";
public static string NotesCda_Modified = "Modified";
public static string NotesCda_Status = "Status";
/*
Resource File Name */
public static string NotesCda_EventViewer_SourceName = "Axalta.Global.DpciformsTimerJobs";
public static string NotesCda_EventViewer_LogName = "Application";
public static void EventViewerApplicationLog(Exception ex)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
if
(!System.Diagnostics.EventLog.SourceExists(GlobalConstants.NotesCda_EventViewer_SourceName))
{
System.Diagnostics.EventLog.CreateEventSource(GlobalConstants.NotesCda_EventViewer_SourceName,
GlobalConstants.NotesCda_EventViewer_LogName);
}
EventLog.WriteEntry(GlobalConstants.NotesCda_EventViewer_SourceName,
ex.Message + " ----" + ex.StackTrace, EventLogEntryType.Error);
});
}
}
}
Above Class Includes Job name, List Name etc.
Write the following code in feature Receiver class
using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.Diagnostics;
namespace Axalta.Global.DpciformsTimerJobs.Features.Y2ItemsUpdate
{
///
[Guid("b4a7ac2f-91e9-4d02-9706-da74250be1b4")]
public class Y2ItemsUpdateEventReceiver : SPFeatureReceiver
{
string SiteURL = string.Empty;
SPUserToken UserToken = null;
SPWebApplication Owebapplication = null;
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
if (properties != null)
{
using (SPSite Osite =
properties.Feature.Parent as SPSite)
{
SiteURL = Osite.Url;
UserToken =
Osite.SystemAccount.UserToken;
Owebapplication =
Osite.WebApplication;
}
// make sure the job isn't already registered
using (SPSite OSPSite = new SPSite(SiteURL, UserToken))
{
// make sure the job isn't already registered
foreach (SPJobDefinition
job in
OSPSite.WebApplication.JobDefinitions)
{
if (string.Equals(job.Name,
GlobalConstants.JobName ))
{
job.Delete();
}
}
//// install the job
Dpciforms2YItemsUpdateJob
siteCollectionUrlJob = new
Dpciforms2YItemsUpdateJob(GlobalConstants.JobName,
Owebapplication);
//// 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(GlobalConstants.SiteCollectionURL,
SiteURL);
SPWeeklySchedule
OweeklySchedule = new SPWeeklySchedule();
OweeklySchedule.BeginDayOfWeek
= DayOfWeek.Sunday;
OweeklySchedule.EndDayOfWeek = DayOfWeek.Sunday;
OweeklySchedule.BeginHour = 5;
OweeklySchedule.EndHour
= 5;
OweeklySchedule.BeginMinute
= 0;
OweeklySchedule.EndMinute = 30;
siteCollectionUrlJob.Schedule = OweeklySchedule;
siteCollectionUrlJob.Update();
}
}
});
}
catch (Exception ex)
{
GlobalConstants.EventViewerApplicationLog(ex);
}
}
public override void FeatureDeactivating(SPFeatureReceiverProperties
properties)
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
if (properties != null)
{
using (SPSite Osite =
properties.Feature.Parent as SPSite)
{
UserToken =
Osite.SystemAccount.UserToken;
SiteURL = Osite.Url;
}
// make sure the job isn't already registered
using (SPSite OSPSite = new SPSite(SiteURL, UserToken))
{
// delete the job
foreach (SPJobDefinition
job in
OSPSite.WebApplication.JobDefinitions)
{
if (string.Equals(job.Name, GlobalConstants.JobName))
{
job.Delete();
}
}
}
}
});
}
catch (Exception ex)
{
GlobalConstants.EventViewerApplicationLog(ex);
}
}
}
}
Add One Class for Running the Job
Click on solution -- >; select Add -- >New
Item Code -- >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(GlobalConstants.JobName, webApp, null, SPJobLockType.Job)
{
this.Title = GlobalConstants.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[GlobalConstants.SiteCollectionURL].ToString()))
{
siteCollectionUrl = this.Properties[GlobalConstants.SiteCollectionURL].ToString();
}
try
{
using (SPSite Osite = new SPSite(siteCollectionUrl))
{
using (SPWeb Oweb =
Osite.OpenWeb())
{
int count = 0;
SPList OList =
Oweb.Lists[GlobalConstants.ListName];
SPListItemCollection
OListItems = OList.Items;
StringBuilder sbDelete
= new
StringBuilder();
sbDelete.Append("");
string command = "" + OList.ID
+ "
{0}Delete"
;
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("
"
);
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–
-- > 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:
---------------------
1.Add the solution using following command
Add-SPSolution C:\ Axalta.Global.DpciformsY2ItemsDeletion.wsp
2.Install the solution using following command
Install-SPSolution -Identity Axalta.Global.DpciformsY2ItemsDeletion.wsp -GACDeployment -CompatibilityLevel 15
3.Active the feature
Enable-SPFeature -Identity Axalta.Global.DpciformsY2ItemsDeletionJob -URL http://htshydasm:1111/sites/AXALTA/ -Force -PassThru
4. update the solution
Update-SPSolution -Identity Axalta.Global.DpciformsY2ItemsDeletion.wsp -LiteralPath D:\Development\Axalta.Global.DpciformsY2ItemsDeletion.wsp -GACDeployment