SPContent types lack internal names

As you could read in my last post I had a little issue with a feature that create a new list item and writes this to list. However, turning custom errors off didn't help that much: I had everything in a try/catch and I still got a null reference exception.

As I was testing, it turned out that the problem had something to do with the Dutch language pack. So I installed the Dutch language pack on my dev machine (yeah, I know... should have done that from the moment I started developing for this client) and bingo.

The problem was that I assumed the value of SPContentType.Name is an internal name and behaves the same as SPField.

So setting the content type on the list like this:
SPContentTypeId contactTypeId = _currentList.ContentTypes["Contacts"].Id;
Will work for English lists, but will cause a null reference exception for Dutch ones, since the name for this content type is "ContactPersonen" in Dutch...

Instead we need to do it like this:
// 0x0106 : Parent Id for Contacts
SPContentTypeId baseTypeId = new SPContentTypeId("0x01060018141B8367FAC64C9CFF864F77742CCB");
SPContentTypeId contactTypeId = _currentList.ContentTypes.BestMatch(baseTypeId);

The trick is to create a bogus SPContentTypeId with the same parentId as the actual one and then use the BestMatch method of the SPList.ContentTypes.
This way we always get the correct content type Id.

Happy hacking!!

2 comments:

Julien Moorrees said...

Interesting finding :).

Looks like you're getting into sharepoint very deeply ;).


Groetjes,
Julien.

Unknown said...

Hey Julien, thanks! Hope it's useful :-)

Getting deeper into SharePoint everyday :-D

Bastiaan

Post a Comment