Deploying documents with content types and associating content types with libraries (Part III)

Part III: Using Feature Event Receiver to create a library and associate a content type

In previous post we showed how to use ContentTypeBinding to bind the content type to an existing document library. In this post, we will learn how to achieve similar results but using the feature event receiver. In this post we will create a new document library, remove all existing content types from the created library and then add our content type to the list. Instead of create a new library from the code, you could also reference an existing one that’s already on the SharePoint server. In this example we will use the same project we created in Part I. So, let's start by opening that project which contains the content type and a document. When project opens, expand the Features folder, right click the Feature1 folder and finally select the Add Event Receiver option to add a feature event receiver to the project. Next, uncomment the FeatureActivated method and add the following code:

SPWeb web = properties.Feature.Parent as SPWeb;

string libraryName = "Sample library name - " + DateTime.Now.Millisecond.ToString ();

Guid listGuid = web.Lists.Add(libraryName, string.Empty, SPListTemplateType.DocumentLibrary);

SPList list = web.Lists[listGuid];

// Delete all content types from the list

for (int i = 0; i < list.ContentTypes.Count; i++)

{

  list.ContentTypes[i].Delete();

}

SPContentType myContentType = web.ContentTypes[new SPContentTypeId("0x010100a9fe27b0556b4de8a60d9e04c6db71de")];

list.ContentTypes.Add(myContentType);

list.ContentTypesEnabled = true;

list.Update();

 

In the above code we are adding a library to the SharePoint site. The Add method returns the Guid of the created list/library. In the for statement, we iterate through all the content types that are in the list (since we created a new document library there should be only 1 content type (Document) in the library) and we delete them.

After we removed all content types from the list, we add a new content type to the list (similar as in Part II, we are referring to the content type by its ID). You can use the Server Explorer to get the content type ID. Finally, we enable the content type management in the list and we update the list to save the changes.

If you press F5 you will notice that the "My New Document Library" is created on SharePoint. If you click the Documents tab and then open the New Document menu you will notice a document we associated with the content type shows up.

Peter Jausovec