Tuesday, October 6, 2009

SPWeb.AvailableContentTypes Vs SPWeb.ContentTypes

Title: SPWeb.AvailableContentTypes Vs SPWeb.ContentTypes


Scenario: Try to get the content types from using both the properties. You might notice that there is no difference. Well then why do we have 2 different properties. Here is the code to get the content types ( notice the comments ) ...

static void GetListTypeID()
{
using (SPSite oSite = new SPSite(@"http://localhost/"))
{
using (SPWeb oWeb = oSite.OpenWeb())
{
//SPContentTypeCollection ctypecoll = oWeb.ContentTypes; // USING CONTENT TYPES
SPContentTypeCollection ctypecoll = oWeb.AvailableContentTypes; // USING AVAILABLE CONTENT TYPES
foreach (SPContentType type in ctypecoll)
{
Console.WriteLine("ID: " + type.Id + " ; Name: " + type.Name);
}
}
}
}




Run the above using either of ContentTypes and AvailableContentTypes. You will see that the result is same.

From MSDN the difference is

The ContentTypes property returns only the content types that exist on the current Web site, not all content types in the current scope. Use the AvailableContentTypes property to return all content types in the current scope, including those of any parent Web sites.

Though it helped me to understand I couldnt get the real essence of it. So, the intresting concept is that AvailableContentTypes is READONLY. You cannot add a new ContentType by using AvailableContentTypes collection.

** CORRECTIONS **
My bad... Some mis-interpretation with my wordings above. The above code as is executed at Site Collection level gives the same results. As mentioned above from MSDN AvailableContentTypes gives information including subsite content types. However, my point is to bring out which one should be used to create new content types ( ContentType ) and which one is read-only ( AvailableContentTypes ). Hope you got the point right.

3 comments:

Sandeep K Nahta said...

http://snahta.blogspot.com/2009/09/spwebavailablecontenttypes-vs.html

sam said...

The difference between the two is that one gives you all content types that you can inherit and one gives you the current web site's content types. The results look the same because you're opening the site collection site and thus both look the same. If you opened a subsite then you could have different results.

Srini Sistla said...

Yes you are right and thats exactly msdn also says. I wanted to make sure that people also understand one key factor of it ( the readonly option ). Rest is already out there written by many.