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.

image

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:

image

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");
                       
        CustomContentType.Fields.Add("client",SPFieldType.Text,true);
        CustomContentType.Fields.Add("clientdescription",SPFieldType.Text,true);
        CustomContentType.Fields.Add("matter",SPFieldType.Text,true);
        CustomContentType.Fields.Add("matterdescription",SPFieldType.Text,true);
                       
        //## Adding the content type
        _wWeb.ContentTypes.Add(CustomContentType);       
        //## Updating it
        CustomContentType.Update();   
      }
}

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: