Wednesday, January 14, 2009

Setting List Item's Content Type even though Content Type is Read Only

I was taking over a project which did bulk imports of files into a SharePoint Document Library with specific "Content Types" for each document.

The guys who had done this developed a console application which would read an xml file and churn through it uploading the file and reading the Content Type and setting it as part of the file upload using this approach:

**Note removed non-important code

SPList list = web.Lists["List Name"];
SPFolder itemFolder = list.RootFolder;
SPListItem listItem;
SPFile file;

file = itemFolder.Files.Add(string.Concat(itemFolder.Url, "/", fileName), stream, true);
file.Update()

listItem = file.Item;

SPContentType contentType = list.ContentTypes["Name of Your Content Type"];

listItem["ContentTypeId"] = contentType.Id;
listItem.SystemUpdate();

**Note: We can't use the listItem.ContentType = contentType as the .ContentType property is read-only.

This seemed to do the trick and everything was all okay in SharePoint. I could see that the documents where updated with the correct Content Type and it all seemed to be pretty correct.

The issue came when the user's started to open the document in Word 2003 and when they clicked on "File Properties" it would always seem to default to the Document Library's default Content Type - not the Content Type in SharePoint - the one that we set during import.

This was unusual the CT was correct in SharePoint but the Word 2003 properties said otherwise, had a look at the properties in Word and sure enough the ContentTypeId was the correct one (one from SharePoint and migration), however the Content Type property was the default document library one instead. Weird!!!!

A few hours of digging around and found that I had to set the "ContentType" property as well not just the "ContentTypeId". Once this was done the File Properties document now knew which "Content Type" it was and populated the correct value now. Wowsers it all worked and with only one line of additional code:

listItem["Content Type"] = contentType.Name;

Couldn't believe that. I mean why make it Read Only when I can modify the property of the list item? Only issue now was to re-bulk upload 1593 documents JOY!!!!!

1 comment:

Anonymous said...

I played Ameba Pico on Facebook and I enjoyed playing it. anstfriend.com