[Aka: Make Content Type Inheritance Work for XML Based Content types]
[Note:Updated Nov 6]
If you are working with XML based content types, you’ll sooner or later fall into a trap well hidden by Microsoft. Simply put Content Type inheritance don’t work for XML based content types. SharePoint does not check what fields you’ve added/deleted/changed since you last deployed your content type feature, so you don’t have the “luxury” (it bloody well should work!) of choosing whether or not to propagate changes down to inherited content types as in the web interface or object model.
I found MS mention it briefly here.
The Role of List Content Types
I’ll take a small detour here to explain the concept of list content types. Whenever you assign a content type to a list (e.g. the pages document library for publishing webs) a new list content type is created which inherits from the site content type that you are assigning to the list and with the same name.
Actually the inheritance copies the site content type definition to the list content type in its entirety and assigns an “inherited” content type id to the new list content type.
If you later modify the site content type, through the web or object model, you have the option of propagating those changes to inherited content types, which in particular includes all the list content types on the site.
Don’t Disconnect the Content Type
Another small detour before I’ll present what to do about this mess. It should be stressed that any modification of the site content type through the web or object model, will disconnect the site content type from the underlying xml metadata file. If it happens you my reestablish the link as described here. This is very bad news. It not only means that you should be careful about what you do to your content types, but it also means that there is no simple way to propagate the changes code wise – we can’t just update the site content type (re-add fields) and have the changes propagate through the object model.
The Code to Propagate
Finally I’m ready to present the code I used to propagate changes to my content types.
The procedure is:
- Locate the site content type in question (run it multiple times if needed)
- Start at the root web site
- Go through all lists on the web
- If the list is associated with the site content type (actually the inherited list content type)
- Compare every field on the site content type with the list content type
- Add, remove or change the field in question on the list content type
- Go recursively through every subweb and continue from step a
I created the following code as a new extension to stsadm, called like this:
stsadm -o cbPropagateContentType -url <site collection url> -contenttype <contenttype name> [-verbose] [-removefields] [-updatefields]
For instance:
stsadm -o cbPropagateContentType -url http://localhost -contenttype “My Article Page” –verbose
The “removefields” switch specifies whether or not fields found in the list content type that are not in the site content type should be removed or not. Default is not. New fields in the site content type will always be added to the list content types.
Note: I’ve not tried to create an “update” field. I’ve not had a use for that yet and it will also require considerably more testing to ensure that it works correctly. You really don’t want to break your list content types in case of errors…
Updated (Nov 6): An update option has now been added you should consider that option as beta.
Note 2: If the job stops prematurely no harm is done. Restart it and it will continue from where it stopped – it will examine and skip the webs/lists that it already has processed.
Finally something tangible:
Save the following as “stsadmcommands.CBPropagateContentType.xml” and save it into “\Config” in the root of the SharePoint install folder (remember to update the assembly reference to whatever you compile the code into):
<?xml version="1.0" encoding="utf-8" ?>
<commands>
<command name="cbpropagatecontenttype"
class="Carlsberg.SharePoint.Administration.STSAdm.CBPropagateContentType,
Carlsberg.SharePoint.Administration, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=55c69d084ac6678f"/>
</commands>
And finally the code you need to compile to an assembly that the xml file should specify:
Updated (Nov 6): Code has been updated a bit. Some mistakes with display name/internal name have been fixed and the update option has been added. I’m not yet satisfied with the testing of the update method so consider it to be beta.
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.StsAdmin;
namespace Carlsberg.SharePoint.Administration.STSAdm
{
///
/// A custom STSAdm command for propagating site content types to lists
/// content types.
///
/// The code is provided as is, I don't take any responsibilty for
/// any errors or data loss you might encounter.
///
/// Use freely with two conditions:
/// 1. Keep my name in there
/// 2. Report any bugs back to http://soerennielsen.wordpress.com
///
/// Enjoy
/// Søren L. Nielsen
///
///
class CBPropagateContentType : ISPStsadmCommand
{
#region Input parameters
private string providedUrl;
private string contentTypeName;
private bool removeFields = false;
private bool verbose = false;
private bool updateFields = false;
private bool UpdateFields
{
get { return updateFields; }
set { updateFields = value; }
}
private bool Verbose {
get { return verbose; }
set { verbose = value; }
}
private bool RemoveFields {
get { return removeFields; }
set { removeFields = value; }
}
private string ContentTypeName {
get { return contentTypeName; }
set { contentTypeName = value; }
}
private string ProvidedUrl {
get { return providedUrl; }
set { providedUrl = value; }
}
#endregion
///
/// Runs the specified command. Called by STSADM.
///
/// The command.
/// The key values.
/// The output.
///
public int Run(string command, StringDictionary keyValues,
out string output) {
//Parse input
// make sure all settings are valid
if (!GetSettings(keyValues)) {
Console.Out.WriteLine(GetHelpMessage(string.Empty));
output = "Required parameters not supplied or invalid.";
}
SPSite siteCollection = null;
SPWeb rootWeb = null;
try {
// get the site collection specified
siteCollection = new SPSite(ProvidedUrl);
rootWeb = siteCollection.RootWeb;
//Get the source site content type
SPContentType sourceCT =
rootWeb.AvailableContentTypes[ContentTypeName];
if (sourceCT == null) {
throw new ArgumentException("Unable to find "
+ "contenttype named \"" + ContentTypeName + "\"");
}
// process the root website
ProcessWeb(rootWeb, sourceCT);
output = "Operation successfully completed.";
Log( output, false );
return 0;
}
catch (Exception ex) {
output = "Unhandled error occured: " + ex.Message;
Log(output, false);
return -1;
}
finally {
if (rootWeb != null) {
rootWeb.Dispose();
}
if (siteCollection != null) {
siteCollection.Dispose();
}
}
}
///
/// Go through a web, all lists and sync with the source content
/// type.
/// Go recursively through all sub webs.
///
///
///
private void ProcessWeb(SPWeb web, SPContentType sourceCT) {
//Do work on lists on this web
Log("Processing web: " + web.Url);
//Grab the lists first, to avoid messing up an enumeration
// while looping through it.
List lists = new List();
foreach (SPList list in web.Lists) {
lists.Add(list.ID);
}
foreach (Guid listId in lists) {
SPList list = web.Lists[listId];
if (list.ContentTypesEnabled) {
Log("Processing list: " + list.ParentWebUrl + "/"
+ list.Title);
SPContentType listCT =
list.ContentTypes[ContentTypeName];
if (listCT != null) {
Log("Processing content type on list:" + list);
if (UpdateFields) {
UpdateListFields(list, listCT, sourceCT);
}
//Find/add the fields to add
foreach (SPFieldLink sourceFieldLink in
sourceCT.FieldLinks) {
if (!FieldExist(sourceCT, sourceFieldLink)) {
Log(
"Failed to add field "
+ sourceFieldLink.DisplayName + " on list "
+ list.ParentWebUrl + "/" + list.Title
+ " field does not exist (in .Fields[]) on "
+ "source content type", false);
}
else {
if (!FieldExist(listCT, sourceFieldLink)) {
//Perform double update, just to be safe
// (but slow)
Log("Adding field \""
+ sourceFieldLink.DisplayName
+ "\" to contenttype on "
+ list.ParentWebUrl + "/" + list.Title,
false);
if (listCT.FieldLinks[sourceFieldLink.Id]
!= null) {
listCT.FieldLinks.Delete(sourceFieldLink.Id);
listCT.Update();
}
listCT.FieldLinks.Add(new SPFieldLink(
sourceCT.Fields[sourceFieldLink.Id]));
listCT.Update();
}
}
}
if (RemoveFields) {
//Find the fields to delete
//WARNING: this part of the code has not been
// adequately tested (though
// what could go wrong?
... )
//Copy collection to avoid modifying enumeration
// as we go through it
List listFieldLinks =
new List();
foreach (SPFieldLink listFieldLink in
listCT.FieldLinks) {
listFieldLinks.Add(listFieldLink);
}
foreach (SPFieldLink listFieldLink in
listFieldLinks) {
if (!FieldExist(sourceCT, listFieldLink)) {
Log("Removing field \""
+ listFieldLink.DisplayName
+ "\" from contenttype on :"
+ list.ParentWebUrl + "/"
+ list.Title, false);
listCT.FieldLinks.Delete(
listFieldLink.Id);
listCT.Update();
}
}
}
}
}
}
//Process sub webs
foreach (SPWeb subWeb in web.Webs) {
ProcessWeb(subWeb, sourceCT);
subWeb.Dispose();
}
}
///
/// Updates the fields of the list content type (listCT) with the
/// fields found on the source content type (courceCT).
///
///
///
///
private void UpdateListFields(SPList list, SPContentType listCT,
SPContentType sourceCT) {
Log("Starting to update fields ", false);
foreach (SPFieldLink sourceFieldLink in sourceCT.FieldLinks) {
//has the field changed? If not, continue.
if (listCT.FieldLinks[sourceFieldLink.Id]!= null
&& listCT.FieldLinks[sourceFieldLink.Id].SchemaXml
== sourceFieldLink.SchemaXml) {
Log("Doing nothing to field \"" + sourceFieldLink.Name
+ "\" from contenttype on :" + list.ParentWebUrl + "/"
+ list.Title, false);
continue;
}
if (!FieldExist(sourceCT, sourceFieldLink)) {
Log(
"Doing nothing to field: " + sourceFieldLink.DisplayName
+ " on list " + list.ParentWebUrl
+ "/" + list.Title + " field does not exist (in .Fields[])"
+ " on source content type", false);
continue;
}
if (listCT.FieldLinks[sourceFieldLink.Id] != null) {
Log("Deleting field \"" + sourceFieldLink.Name
+ "\" from contenttype on :" + list.ParentWebUrl + "/"
+ list.Title, false);
listCT.FieldLinks.Delete(sourceFieldLink.Id);
listCT.Update();
}
Log("Adding field \"" + sourceFieldLink.Name
+ "\" from contenttype on :" + list.ParentWebUrl
+ "/" + list.Title, false);
listCT.FieldLinks.Add(new SPFieldLink(
sourceCT.Fields[sourceFieldLink.Id]));
//Set displayname, not set by previus operation
listCT.FieldLinks[sourceFieldLink.Id].DisplayName
= sourceCT.FieldLinks[sourceFieldLink.Id].DisplayName;
listCT.Update();
Log("Done updating fields ");
}
}
private static bool FieldExist(SPContentType contentType,
SPFieldLink fieldLink)
{
try
{
//will throw exception on missing fields
return contentType.Fields[fieldLink.Id] != null;
}
catch(Exception)
{
return false;
}
}
private void Log(string str, bool verboseLevel) {
if (Verbose || !verboseLevel) {
Console.WriteLine(str);
}
}
private void Log(string str) {
Log(str, true);
}
///
/// Parse the input settings
///
///
///
private bool GetSettings(StringDictionary keyValues) {
try {
ProvidedUrl = keyValues["url"];
//test the url
new Uri(ProvidedUrl);
ContentTypeName = keyValues["contenttype"];
if (string.IsNullOrEmpty(ContentTypeName)) {
throw new ArgumentException("contenttype missing");
}
if (keyValues.ContainsKey("removefields")) {
RemoveFields = true;
}
if (keyValues.ContainsKey("verbose")) {
Verbose = true;
}
if (keyValues.ContainsKey("updatefields"))
{
UpdateFields = true;
}
return true;
}
catch (Exception ex) {
Console.Out.WriteLine("An error occuring in retrieving the"
+ " parameters. \r\n(" + ex + ")\r\n");
return false;
}
}
///
/// Output help to console
///
///
///
public string GetHelpMessage(string command) {
StringBuilder helpMessage = new StringBuilder();
// syntax
helpMessage.AppendFormat("\tstsadm -o {0}{1}{1}", command,
Environment.NewLine);
helpMessage.Append("\t-url " + Environment.NewLine);
helpMessage.Append("\t-contenttype " + Environment.NewLine);
helpMessage.Append("\t[-removefields]" + Environment.NewLine);
helpMessage.Append("\t[-updatefields]" + Environment.NewLine);
helpMessage.Append("\t[-verbose]" + Environment.NewLine);
// description
helpMessage.AppendFormat("{0}This action will propagate a site"
+ " content type to all list content types within the "
+ "site collection.{0}Information propagated is field "
+ "addition/removal.{0}{0}", Environment.NewLine);
helpMessage.AppendFormat("{0}Søren Nielsen (soerennielsen."
+ "wordpress.com){0}{0}", Environment.NewLine);
return helpMessage.ToString();
}
}
}
Final Comments
I’ve made zero attempts to optimize the code. It doesn’t really matter how long it takes, does it? Give it 10 minutes till a couple of hours for huge site collection (I’ve tested with about 400 sub sites).
I recommend that you use the verbose flag and pipe the output to a file, so that you can review that it did everything correctly.
The code does not handle site content types on sub sites I’ll probably add it fairly soon if I need it or time permits (does it ever?)
License
Use the above code freely, with two conditions:
- Leave my name and link in there
- Report bug and improvements back to me
15 Nov 2007 at 22:40
Very helpful and thought provoking article. I’ll be putting your code to use later.
For now, I thought you might like to know that I’ve cracked (part of) the mystery of the inherited content type in XML. Check out the link to see the article I wrote, and thanks for getting me started in the right direction!
11 Dec 2007 at 15:16
[...] feature deployment as that will disconnect your content type (see my two posts on that, 1 and 2) from the underlying xml [...]
01 Feb 2008 at 14:48
A really good article. Thanks a lot for giving me valuable insight.
While looking into our own implementation we discovered the SPContentTypeUsage class. It will return a list of all content types based on a given content type. By using it you do not have to recurse through all sub webs and check the lists.
It ought to be significantly faster.
// Mats
03 Feb 2008 at 21:51
Mats: That sounds very interesting. I’ll look into it when I update it the next time.
Thanks for the input.
I really need to include those site/web scoped content types as well…
06 Mar 2008 at 20:08
[...] types are disconnected or not (column “definition” is null – see my other blog on this). There’s even a dedicated stored procedure that will tell you the ghosting state of a given [...]
24 Mar 2008 at 15:25
thanks much, man
21 May 2008 at 12:05
[...] – ja lahendus ise asub siin – geniaalselt lihtne kasutada: http://soerennielsen.wordpress.com/2007/09/11/propagate-site-content-types-to-list-content-types/ Posted: Wednesday, May 21, 2008 2:05 PM by [...]
25 Aug 2008 at 17:18
Excellent article! I’m not finding much on the web about some of the nuances of site vs list content types, so I was ecstatic to run across yours!
I’m a little concerned about our planned implementation of our MOSS ‘07 site after reading this, though. The idea was that we could create custom content types for all the types of lists that we have on our sub-webs and then if a new field was necessary, changing the content type would propogate the change to all the inherited types. Now after reading this article, it sounds like this is quite a fragile relationship between lists and content types, which greatly concerns me.
Are you suggesting that lists based on custom content types may not be the most maintainable/upgradable way to go?
30 Sep 2008 at 20:57
[...] täiendasin seda esialgset koodi paari [...]
07 Nov 2008 at 17:25
I just wanted to share this fix.
I created a list from a content type and therefore content type management of the list wasn’t enabled
so this line in ProcessWeb
if (list.ContentTypesEnabled)
was false when in fact the list is using the content type
Instead I replaced this line with a call to this function:
bool ListUsesContentType(SPList list, SPContentType contentType)
{
try
{
if (list.ContentTypes.Count == 0)
return false;
foreach (SPContentType cType in list.ContentTypes)
{
if (cType.Parent == contentType)
return true;
}
}
catch (Exception ex)
{
Log(ex.Message);
}
return false;
}
24 Nov 2008 at 17:24
Hi Soren,
This is fantastic. Couple of things that I have updated in your code. As you mention when a content type is assigned to a list it becomes a new child content type is assigned to the list and a new contenttypeid is assigned.
I had an issue where a content type on a list had a different name to the parent content type and therefore the stsadm command didnt find it.
To fix this I modified the code so that there is a new private class member called contentTypeID, a new private property ContentTypeID and the ProcessWeb function is updated to:-
private void ProcessWeb(SPWeb web, SPContentType sourceCT)
{
//Do work on lists on this web
Log(“Processing web: ” + web.Url);
//Grab the lists first, to avoid messing up an enumeration
// while looping through it.
List lists = new List();
foreach (SPList list in web.Lists)
{
lists.Add(list.ID);
}
foreach (Guid listId in lists)
{
SPList list = web.Lists[listId];
if (list.ContentTypesEnabled)
{
Log(“Processing list: ” + list.ParentWebUrl + “/”
+ list.Title);
SPContentType listCT=null;
try
{
SPContentTypeId childCTId = list.ContentTypes.BestMatch(ContentTypeID);
//validate that the contenttype returned via Best Match is actually is related to the content type!
if(childCTId.IsChildOf(ContentTypeID))
listCT = list.ContentTypes[childCTId];
}
catch (Microsoft.SharePoint.SPException spex)
{
}
catch (Exception ex)
{
}
I also added the try/catch as I was seeing getting an error 0×81070215 which is mostly likely down to my dev environment.
I have started to use this on our test system and will keep you updated if anything new is learnt.
Thanks for your hard work though – the code works a dream!
Hope that helps.
Regards
Simon
24 Nov 2008 at 19:38
Sorry for a very basic question. I just want to make sure I am doing the steps correctly.
I am creating an stsadm extension to propagate content types changes – being specific I want to change the fields available in a content type used in a page layout).
I have updated the site columns and site content types by upgrading and reactivating the feature solutions that contain the original definitions.
I can see the new columns in the Site Settings > Site Column Gallery and Site Settings > Site Content Type Gallery > Site Content Type.
I know I can’t see the columns in the List Content Type as I need to propagate them, hence the reason for the stsadm extension.
My questions.
1. Am I correct in making my changes to the original feature solution? i.e. to add the Site Columns/update the Site Content Type.
2. Is it better to use an stsadm extension or a Feature Receiver or are they just two potential ways of doing the same thing?
Thank you.
23 Dec 2008 at 13:13
Sorry for slow response.
Hi Lily
You are correct – right place to update
Feature receiver or stsadm command is interchangeable. Depends on how easily you want to kick it off. I consider it a very useful operation, however not one I do lightly therefore it’s not a receiver in my deployments.
You risk overwritting some (legitimate) customizations on the list content type when you propagate, therefore I’ll want to doublecheck before I press the button.
10 Dec 2008 at 11:09
Does it propagate a new Event Receiver ???
23 Dec 2008 at 13:16
xsolon and simon
Thank you for sharing your fixes
I guess the point is that it’s impossible to fully test and anticipate the behaviour in other installations.
07 Feb 2009 at 19:48
[...] The first thing I discovered is that if you Deactivate your feature, Retract it, Delete it, Install it, Deploy it, and Activate your feature again, new fields that you’ve added to the Content Type in XML do, in fact, appear. The only problem is, everything that inherits from that Content Type (let’s say, oh, a few million list items?) does not see any of the changes. This is because a new “list” Content Type is created any time you assign a content type to a list, and the new List Content Type inherits from the “real” one that you deployed through your feature. Soren Nielsen describes this briefly in his blog post. [...]
11 Jun 2009 at 3:00
Thanks, you’ve broken my sharepoint site.
Don’t update the display name property, that won’t work and will cancel the effect of re-applying the field. You should trust the fact that you are re-attaching the field, no updates on display name needed.
Cheers
12 Aug 2009 at 15:46
you’re welcome ;-( Please tell me that you did this on your test environment first..
To be honest I don’t believe that I tested it with display names.
I’m fairly certain that they follow the same rules as every other property in regards to whether or not they update automatically (i.e. only updated at the very root and subsequently created instances).
You should probably take note of the fact that the code actually uses the displayname to figure out what fields it should touch.
11 Aug 2009 at 21:11
[...] http://soerennielsen.wordpress.com/2007/09/11/propagate-site-content-types-to-list-content-types/ http://msdn.microsoft.com/en-us/library/aa543504.aspx [...]
12 Aug 2009 at 15:46
in your method UpdateListFields isnt the line
if (!FieldExist(sourceCT, sourceFieldLink)) {
always true? Why would it not? Maybe the line must be:
if (!FieldExist(listCT, sourceFieldLink)) {
Thanks