Friday, December 5, 2008

SharePoint: Add a site collection policy to a content type programmatically

In this blogpost, I wrote about how to add a Policy to a content type programmatically.

I got a question by mail how I'd add a site collection policy to a content type in code.

This is the code that can do this:

using (SPSite site = new SPSite(http://server))

{

SPContentType contentType = null;

//get content type id

foreach (SPContentType type in site.RootWeb.ContentTypes)
{

if (type.Name == "test content type")
{
contentType = type;
break;
}
}

PolicyCatalog catalog = new PolicyCatalog(site);

if (catalog != null && catalog.PolicyList != null)
{

foreach (Policy p in catalog.PolicyList)
{

if (p.Name == "test site collection policy")
{

//todo: check if contenttype has already got a Policy; then delete the Policy first
Policy.CreatePolicy(contentType, p);
}
}
}
}

By the way

I don't think the policy on the content type is updated when you update the site collection policy.. I think this should be test very good! I tried this:
- create a site collection policy (in SharePoint UI)
- assign this site collection policy to your content type (in SharePoint UI)
- watch the PolicyItem.CustomData property on the Policy of your content type in code:
Policy pol = Policy.GetPolicy(contentType);

foreach (PolicyItem item in pol.Items)

{

Console.WriteLine(item.CustomData.ToString());

}

- Change your site collection policy (in SharePoint UI)

- Rewatch the PolicyItem.CustomData property on the Policy of your content type in code...

=> The CustomDatea property on the policy on my content type was NOT changed... This is pretty weird..

3 comments:

CricketNews24/7 said...
This comment has been removed by the author.
topSpot | Find your top spot here said...

Thanks for the great post! I'll try it.. :)

digital signatures said...

You just made something that I thought was so difficult be, truly, so easy! Thanks for the post!