Creating Site Policy in SharePoint 2013 using server code

Site policy is new functionality introduced in SharePoint 2013 which enables to apply retention rules to complete sites. Great post about concepts, usage and configuration of site policies is posted on TechNet Blogs

In our solutions we often need to create policies programmatically, to ensure easier deployment and reusability. However, ProjectPolicy class does not provide public method to create new ProjectPolicy

How to create new ProjectPolicy?

In a nutshell, this can be accomplished by creating new Content Type that inherits from ProjectPolicy content type, and then creating new Policy object based on our newly created content type. This procedure is similar to internal ProjectPolicy method for creation of new policies (that can be verified using ILSpy). For portability and reusability reasons, new policy should be created on Content Type Hub site and then published as any other content type. In such scenario, new policy can automatically be deployed to all sites that consume content types from Content Type Hub.


using(SPSite site = new SPSite(siteUrl))  {  // ProjectPolicy Content Type ID   SPContentTypeId policyCTID= new SPContentTypeId("0x010085EC78BE64F9478aAE3ED069093B9963");   SPContentTypeCollection contentTypes = site.RootWeb.ContentTypes;  

// ProjectPolicy is parent content type

  SPContentType parentContentType = contentTypes[policyCTID];

// we create new content type based on ProjectPolicy   policyContentType = new SPContentType(parentContentType, contentTypes, "New Project Policy");   policyContentType = contentTypes.Add(policyContentType);   policyContentType.Group = parentContentType.Group;   policyContentType.Hidden = true;   policyContentType.Update(); 

// Final step is to create new Policy with new content type   Policy.CreatePolicy(policyContentType, null);         }