Enable item scheduling by codeeI’m developing a site template, which requires item scheduling on the page library. I don’t want our users to enable the item scheduling manually at the “_layouts/ ManageItemScheduling.aspx” page. Unfortunately I was not able to find any online documentation about how to do this with code.

It required me to dig deeper and .Net reflector turned out to be the right way to go. Microsoft made a lot of the required functions internal, which means that we cannot access the functions from our own code. By analyzing the steps I was able to add item scheduling on the pages library with the code below.

Step 1: Enable Moderation and Minor versions
To allow item scheduling, we must enable moderation and minor versions on the pages list.

SPWeb web = new SPSite(“http://web”).OpenWeb();
SPList list = web.Lists[“Pages”];

//Enable moderation and minor versions
list.EnableModeration = true;
list.EnableMinorVersions = true;

Step 2: Register Scheduling Events
The item scheduling requires us to register 2 events.
First we will retrieve the assembly and class information of the ScheduledItemEventReceiver and then we will create the 2 events.

//get type information
Type scheduledItemType = typeof(Microsoft.SharePoint.Publishing.Internal.ScheduledItemEventReceiver);
string assemblyName = scheduledItemType.Assembly.FullName.ToString();
string className = scheduledItemType.FullName;

//Get the eventreceivers
SPEventReceiverDefinitionCollection eventReceivers = list.EventReceivers;

//Register the updating event
SPEventReceiverDefinition updateDef = eventReceivers.Add();
updateDef.Name = “Item Updating Event Handler For Scheduling”;
updateDef.Type = SPEventReceiverType.ItemUpdating;
updateDef.Assembly = assemblyName;
updateDef.Class = className;

//Register the added event
SPEventReceiverDefinition addDef = eventReceivers.Add();
addDef.Name = “Item Added Event Handler For Scheduling”;
addDef.Type = SPEventReceiverType.ItemAdded;
addDef.Assembly = assemblyName;
addDef.Class = className;

Step 3: Unhide the startdate and expirydate fields
The list already contains the startdate and expirydate fields, but they are hidden. With the following code we will unhide the fields.

//Get the field guids of the startdate and expirydate
Guid startDateGuid = Microsoft.SharePoint.Publishing.FieldId.StartDate;
Guid expiryDateGuid = Microsoft.SharePoint.Publishing.FieldId.ExpiryDate;

//update the visibility of the startdate
SPField startDateField = list.Fields[startDateGuid];
startDateField.Hidden = false;

//update the visibility of the expirydate
SPField expiryDateField = list.Fields[expiryDateGuid];
expiryDateField.Hidden = false;

And that’s it. With these coding steps we enabled item scheduling at the Page library.