Wors World
All About Wor

When Is Read Only Not Read Only?

Whilst developing some code in ID-Sharepoint to programatically create content types I came across one of those things that, as a Sharepoint developer, make you MAD!
I was accessing a content type using code like this :
SPContentType contentTypeWotIWantToChange = web.AvailableContentTypes("ContentTypeWotIWantToChange");
I then coded up the addition of a couple of site columns to the content type like this:
contentTypeWotIWantToChange.FieldLinks.Add(new SPFieldLink(……
contentTypeWotIWantToChange.FieldLinks.Add(new SPFieldLink(……
I then used this code to update the content type:
and was greeted, upon running this code, with an exception "the collection cannot be modified".
Much head scratching resulted and I checked contentTypeWotIWantToChange to see if it was set as "ReadOnly" or "Sealed" – both false so that wasn’t it…
Much more head scratching and re-reading of msdn and other info revealed that .AvailableContentTypes is a read only collection of content types that represent content types from the current web and parent webs so I guess it makes some kind of sense to disallow the update of content types that may have been provisioned at a level above where you are but I do think there should be a bit more of a clue – I guess the content types can’t be marked as read only or as sealed but I do think the property could be a bit clearer in  it’s intent i.e. maybe called it ActiveContentTypesReadOnly? 
Anyway, the solution was to use this code to get the contentytpye
SPContentType contentTypeWotIWantToChange = web.ContentTypes("ContentTypeWotIWantToChange");
Which gets the content types from the current web only and is read/write.
The rest of the code was unchanged.
Chalk up another lost hour to SharePoint dev…..
Read about AvailableContentTypes here and ContentTypes here
Happy SharePoint deving ……..

One Response to “When Is Read Only Not Read Only?”

  1. I feel your pain. I\’ve had similar issues with two properties working on the same data, only behaving differently. I was trying to control the Content Types on the start menu:http://www.novolocus.com/2009/05/26/control-the-content-types-in-the-new-menu-via-code/ Another gem I\’ve hit a few times is where an accessor returns a different copy of an object each time. For example, SPList.DefaultView returns a different SPView each time you call it. Nice :/http://www.novolocus.com/2009/02/09/wss-practice-create-a-list-columns-and-view-programmatically/

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 )

Facebook photo

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

Connecting to %s

%d bloggers like this: