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 =

new

SPSite(siteURL))

{

using

(SPWeb web = site.RootWeb)

{

var policyFeatureId = “

Microsoft.Office.RecordsManagement.PolicyFeatures.Expiration

“;

var contentType = web.ContentTypes[

new

SPContentTypeId(“

0x0100edce6975c7734f4d9c02af7045fecaa0

“)];

var data =

new

StringBuilder();

// Create a policy if it doesn’t already exist.

if

(Policy.GetPolicy(contentType) ==

null

)

{

Policy.CreatePolicy(contentType,

null

);

}

// Edit the Policy

Policy 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 Period

data.Append(“

PrecyseArchiveDate

“);

// Internal name of a Date Field within the Content Type

data.Append(“

months

“);

data.Append(“

“);

data.Append(“

“);

data.Append(“

“);

expirationPolicy.Items.Add(policyFeatureId, data.ToString());

}

}

}

image002

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.