How to set an Expiration Policy through code

I’ve been working on a project that requires custom site provisioning through code based on the information a user completes in a form.  A workflow creates a new site collection, sub site, and a list within the sub site. It also sets some basic security and adds a custom content type to the site collection (which is used by the list).Another requirement was to delete any items in the list that past a 72 month expiration. A SharePoint Information Management Policy would work to meet this requirement, but I needed to set the Information Policy through code during the site provisioning process. Below is the code that I used to create the policy and attach it to the custom content type. The user is asked to provide a Retention Period as they complete the initial form, making it dynamic.One thing to note is that I was not able to use the Created or Modified date of the item as part of the policy. Only date fields that are a part of the content type were available. So I had to create a hidden field that is set to be the same as the creation date when the item is added to the list. I then use that date as part of the policy.using(SPSite site =newSPSite(siteURL)){using(SPWeb web = site.RootWeb){var policyFeatureId = "Microsoft.Office.RecordsManagement.PolicyFeatures.Expiration";var contentType = web.ContentTypes[newSPContentTypeId("0x0100edce6975c7734f4d9c02af7045fecaa0")];var data =newStringBuilder();// Create a policy if it doesn't already exist.if(Policy.GetPolicy(contentType) ==null){Policy.CreatePolicy(contentType,null);}// Edit the PolicyPolicy expirationPolicy = Policy.GetPolicy(contentType);expirationPolicy.Name = "Transcription Job Expiration";expirationPolicy.Description = "Deletes and Transcription Job when it reaches the expiration period.";if(expirationPolicy.Items[policyFeatureId] ==null){data.Append("");data.Append("");data.AppendFormat("{0}", _Client.RetentionPeriod);// Set the Retention Perioddata.Append("PrecyseArchiveDate");// Internal name of a Date Field within the Content Typedata.Append("months");data.Append("");data.Append("");data.Append("");expirationPolicy.Items.Add(policyFeatureId, data.ToString());}}}image002

The best Timer Job is a dumb Timer Job!

Introduction to Upgrade in SharePoint Server 2010