How to Create Custom Content Types with Code for SharePoint 2010

Creating content types is one of the fundamental features of SharePoint, and although you can create your own content types through the user interface of SharePoint, I'd like to show you a couple options on how you can create your own content types using code. I am going to jump right in, so if you need a refresher on what content types are, please review Kelly Rusk's article on content types.

Option 1: Custom Content Types (via a Content Type project)

The first (and probably the easiest) way to create a custom content type is to use Visual Studio 2010 to create a special project type of type Content Type. I'm going to create a custom content type named MovieData, which will have a choice column that will allow selection of a movie genre, when creating/uploading a document.

Launch Visual Studio 2010 and create a new project. Click on the installed project templates to display the templates in the SharePoint 2010 section, and select the template named Content Type. Give the project the name MovieData and click the OK button.

The SharePoint Customization Wizard opens, which will display a series of steps you need to provide information for, so Visual Studio can configure your project properly. On the first screen, enter the URL of the SharePoint site you want this content type to be deployed to. You should also select the Deploy as a farm solution radio button. Press the Next button to continue.

The next screen requires that you choose which content type to inherit the content type from. We want to inherit from the Document content type, so select Document from the dropdown list, and press the Finish button. Visual Studio will now create the project, and we are ready to finish coding our custom content type.

You will notice that for the Content Type project template, Visual Studio creates an elements.xml file as part of the project. This is the only file we will need to modify to complete our custom content type. Open the elements.xml file, and under the ContentType node, set the Name attribute to 'MovieData'. You can optionally set the Description attribute value to whatever you like, and if you wish to have the content type be displayed in a specific content type group, you can modify the Group attribute value. Note that the ID attribute value represents the GUID value of the content type we inherited from (the Document content type).

The next step is to create the Genre column that will be part of our MovieData content type. To do this, add a Field element inside the Elements node, right before the ContentType node. Set the Name and DisplayName attribute values to 'Genre', and make the column a choice column by setting the Type attribute to 'Choice'. You also need to give the field a unique ID value (a GUID), which you can use the GUIDGEN tool to do this for you.

Since the column we are adding is a choice column, we now need to add entries that will be displayed when the user is selecting an entry. Add a CHOICES node inside the Field element, and then add one or more CHOICE nodes inside the CHOICES node.

Once you have this column defined, you must add a field reference so the column can be displayed as part of the content type. Add a FieldRef element inside of the FieldRefs node, as seen here:

Make sure you use the same GUID that you created when you created the Field element, and give the Name and DisplayName attributes a value of 'Genre'. Save the elements.xml file when you are finished.

The project is now ready to be compiled and deployed to our SharePoint site. Right mouse click the project in Solution Explorer, and select Deploy. Visual Studio will compile the project, deploy the content type (as a Feature), and automatically activate it at the site level.

At this point, our custom content type is ready to use, but first we need to enable it in the document library that we want to use it in. I have created a normal document library in my SharePoint site named Movies. Navigate to the Document Library Settings page, and click on Advanced Settings. Enable management of content types, and click OK. This allows us to add our content type for this document library, so we can classify documents with this content type.

When you return to the Document Library Settings page, you will notice that under the Content Types section, there is the Add from existing site content types link. Click on this link to add our MovieData custom content type to this library.

I have also specified that our MovieData content type is the default content type by making it the first in the list of content types (selecting '1' in the Position from Top selection), under the Change new button order and default content type link. Click OK when finished.

That's it! We are now ready to upload (or create) a document to our library, and our content type will be used when uploading/creating the document. You will notice that a dialog is displayed when I upload a document, allowing selection of a Genre metadata field when uploading the document.

Option 2: Custom Content Types (via a blank SharePoint project)

The second way to create a custom content type is to do it with SharePoint object model code. The code will be deployed as a feature also, but the content type will be created when the feature is activated. This has the advantage that if you need to do anything custom to your content type before it gets created, you can handle that with code.

I am going to create the same MovieData content type that I created in Option 1, so you can see the differences in how the content type is created.

Launch Visual Studio 2010 and create a new project. Click on the installed project templates to display the templates in the SharePoint 2010 section, and select the template named Empty SharePoint Project. Give the project the name MovieData and click the OK button. You will notice that Visual Studio only asks you to specify whether the project should be deployed in a farm or sandbox solution (select the farm solution). Visual Studio doesn't ask you for any additional information when creating the project, as it did in Option 1. An empty SharePoint project assumes you will handle all the configurations yourself.

The next step is to create a feature, as this is how we will deploy our custom content type. Right mouse click the Features node in Solution Explorer, and click on Add Feature. This will create a feature in the project and open the designer page for the Feature1.feature file. We want to add code to the events that fire when the feature is activated/deactivated, so in order to do that we need to add an event receiver to the feature. Right mouse click the Feature1.feature file in Solution Explorer, and click on Add Event Receiver:

Visual Studio creates a Feature1.EventReceiver.cs file, which contains the event handlers for the FeatureActivated, FeatureDeactivating, FeatureInstalled, FeatureUninstalling, and FeatureUpgrading events. We are only going to add code to the FeatureActivated and FeatureDeactivating events. Uncomment the FeatureActivated event, and add the following code snippet:

SPWeb thisWeb = (SPWeb)properties.Feature.Parent;
thisWeb.AllowUnsafeUpdates = true;

SPContentTypeCollection contentTypes = thisWeb.ContentTypes;
SPContentType parent = thisWeb.ContentTypes["Document"];
SPContentTypeId parentID = parent.Id;

SPContentType MovieDataCT = new SPContentType(contentTypes[parentID], contentTypes, "MovieData");
contentTypes.Add(MovieDataCT);

string GenreField = thisWeb.Fields.Add("Genre", SPFieldType.Choice, false);
SPFieldChoice genre = (SPFieldChoice)thisWeb.Fields.GetFieldByInternalName(GenreField);
genre.Choices.Add("Comedy");
genre.Choices.Add("Documentary");
genre.Choices.Add("Drama");
genre.Choices.Add("Science Fiction");
genre.Choices.Add("Western");
genre.Update();

SPFieldLink genreLink = new SPFieldLink(genre);
MovieDataCT.FieldLinks.Add(genreLink);
MovieDataCT.Update();

SPList MovieList = thisWeb.Lists["Movies"];
MovieList.ContentTypesEnabled = true;
MovieList.Update();
MovieList.ContentTypes.Add(MovieDataCT);
MovieList.Update();

SPContentTypeCollection listCTs = MovieList.ContentTypes;

System.Collections.Generic.IList newOrder = new System.Collections.Generic.List();
newOrder.Add(listCTs["MovieData"]);
newOrder.Add(listCTs["Document"]);

MovieList.RootFolder.UniqueContentTypeOrder = newOrder;
MovieList.RootFolder.Update();

This code will execute when the feature is activated, and is responsible for all the steps of creating our custom content type. Let's go through each area of the code.

SPWeb thisWeb = (SPWeb)properties.Feature.Parent;
thisWeb.AllowUnsafeUpdates = true;

SPContentTypeCollection contentTypes = thisWeb.ContentTypes;
SPContentType parent = thisWeb.ContentTypes["Document"];
SPContentTypeId parentID = parent.Id;

SPContentType MovieDataCT = new SPContentType(contentTypes[parentID], contentTypes, "MovieData");
contentTypes.Add(MovieDataCT);

The first thing the code does is get a reference to the SharePoint site and set the AllowUnsafeUpdates property, so we can modify the site through code. We then need to reference the Document content type defined, so we can create our custom content type, inheriting from the Document content type. Once we have this, we then create our new content type called MovieData, and add it to the content type collection defined for our SharePoint site.

SPWeb thisWeb = (SPWeb)properties.Feature.Parent;
string GenreField = thisWeb.Fields.Add("Genre", SPFieldType.Choice, false);
SPFieldChoice genre = (SPFieldChoice)thisWeb.Fields.GetFieldByInternalName(GenreField);
genre.Choices.Add("Comedy");
genre.Choices.Add("Documentary");
genre.Choices.Add("Drama");
genre.Choices.Add("Science Fiction");
genre.Choices.Add("Western");
genre.Update();

The next step is to create the Genre site column that is part of our MovieData content type. This will be a Choice column, so we will instantiate a variable of type SPFieldChoice class to create the column of the proper type. We also need to add some choices to be available, and then finally calling Update() will create the site column on the SharePoint site.

Once the site column is created, we need to link it to our content type. This is done with a SPFieldLink class, specifying the site column to link. The code adds this to the FieldLinks collection of our content type, and then calling Update() on our content type actually creates the custom content type on the SharePoint site.

SPWeb thisWeb = (SPWeb)properties.Feature.Parent;
SPList MovieList = thisWeb.Lists["Movies"];
MovieList.ContentTypesEnabled = true;
MovieList.Update();
MovieList.ContentTypes.Add(MovieDataCT);
MovieList.Update();

Now that our content type has been created, we can now use it in our Movies document library. In order to do this, the code first makes sure that content type management is enabled for our document library, and then adds the content type to the document library. Note that we need the call to the Update() method after setting the ContentTypesEnabled flag to true. If we omit this, then adding the content type to our document library would throw an exception, as content type management has not been enabled.

SPWeb thisWeb = (SPWeb)properties.Feature.Parent;
SPContentTypeCollection listCTs = MovieList.ContentTypes;

System.Collections.Generic.IList newOrder = new System.Collections.Generic.List();
newOrder.Add(listCTs["MovieData"]);
newOrder.Add(listCTs["Document"]);

MovieList.RootFolder.UniqueContentTypeOrder = newOrder;
MovieList.RootFolder.Update();

The final step that the code takes is to set our MovieData content type as the default content type for the Movies document library. This is done by creating a generic list variable of type SPContentType, and adding the existing content types for our document library to it. What is important to remember here is the order in which the content types are listed in the generic list variable, as SharePoint considers the first content type in the list to be the default. The code builds this list and replaces the existing list in our document library by replacing the UniqueContentTypeOrder variable. Calling Update() on the RootFolder commits the changes back to SharePoint.

Since we are creating a content type when a feature is being activated, it makes good sense that we clean up after ourselves when the feature is deactivated. Uncomment the FeatureDeactivating event handler, and add the following code snippet:

SPWeb thisWeb = (SPWeb)properties.Feature.Parent;
thisWeb.AllowUnsafeUpdates = true;

SPContentTypeCollection contentTypes = thisWeb.ContentTypes;
SPContentType MovieDataCT = thisWeb.ContentTypes["MovieData"];
SPContentTypeId MovieDataCTID = MovieDataCT.Id;

SPList MovieList = thisWeb.Lists["Movies"];
SPContentTypeId listCTID = MovieList.ContentTypes["MovieData"].Id;

// Delete any list items of our content type first
foreach (SPListItem item in MovieList.Items)
{
if (item.ContentTypeId == listCTID)
item.Delete();
}

MovieList.ContentTypes["MovieData"].Delete();
MovieList.Update();

SPContentTypeCollection listCTs = MovieList.ContentTypes;

thisWeb.ContentTypes.Delete(MovieDataCTID);
thisWeb.Update();

thisWeb.Fields["Genre"].Delete();
thisWeb.Update();

This code snippet handles all the steps needed to remove the MovieData custom content type, as well as the Genre site column from our SharePoint site. Note that before the content type can be removed, the code goes through the Movies document library and deletes any documents that have been classified with our custom content type.

In conclusion, I've shown you two different options on how to create custom content types with code. The first option is the quickest way to accomplish this, and the second option gives you more control and flexibility, if you need to add any custom functionality or logic when implementing your custom content types.