Saturday, 10 September 2011

Creating your own Content Type with Visual Studio 2010 programmatically

In my last post I explained how to create a content type with Visual Studio, using the content type elements.xml, this time I am going to focus of how to create a content type programmatically. I have to admit, this is my favourite approach to create content types, it is elegant and clean.

I am going to insert a piece of code to create this structure (client,client description, matter and mater description) inheriting the content type “Document”. What we can do it a simple feature add a feature receiver, and add the code into the FeatureActivated(…) event.


Go to Visual Studio 2010->New Project->Sharepoint->2010->Empty Project. Call the project netsourcecodeCT. Choose “Deploy as Farm Solution”. The nest step will be to add the feature. Go to the Features Folder Right Click, and add feature, rename the feature with this name DMSCTFeature, then right click on the feature and select Add event receiver. Your project should look like this:


Double click on DMSCTFeature.EventReceiver.cs , uncomment the event FeatureActived(…) and copy this code:

using (SPSite _sSite = new SPSite("http://yourserver")
     using (SPWeb _wWeb = _sSite.OpenWeb())   
        SPContentType _cParent= _wWeb.AvailableContentTypes["Document"];
        SPContentType CustomContentType= new SPContentType(_cParent,_wWeb.ContentTypes, "DMSCT");
        //## Adding the content type
        //## Updating it

Deploy the solution, Your new Content Type has been created and it is ready to use.

Conclusion: As you can see with six lines of code we have created exactly the same than the Elements.xml approach. I call this code “elegant, nice and clean”.

No comments: