Creating a Document Library with Content Type in code

Posted by David Jacobus on Geeks with Blogs See other posts from Geeks with Blogs or by David Jacobus
Published on Tue, 15 Oct 2013 12:39:24 GMT Indexed on 2013/10/18 3:56 UTC
Read the original article Hit count: 322

Filed under:

Originally posted on: http://geekswithblogs.net/djacobus/archive/2013/10/15/154360.aspx

In the past, I have shown how to create a list content type and add the content type to a list in code.  As a Developer, many of the artifacts which we create are widgets which have a List or Document Library as the back end.   We need to be able to create our applications (Web Part, etc.) without having the user involved except to enter the list item data.  Today, I will show you how to do the same with a document library.    A summary of what we will do is as follows:

 

1.   Create an Empty SharePoint Project in Visual Studio

2.   Add a Code Folder in the solution and Drag and Drop Utilities and Extensions Libraries to the solution

3.   Create a new Feature and add and event receiver  all the code will be in the event receiver

4.   Add the fields which will extend the built-in Document content type

5.   If the Content Type does not exist, Create it

6.   If the Document Library does not exist, Create it with the new Content Type inherited from the Document Content Type

7.   Delete the Document Content Type from the Library (as we have a new one which inherited from it)

8.   Add the fields which we want to be visible from the fields added to the new Content Type

 

Here we go:

  Create an Empty SharePoint Project in Visual Studio

image

 

   Add a Code Folder in the solution and Drag and Drop Utilities and Extensions Libraries to the solution

    image

 

The Utilities and Extensions Library will be part of this project which I will provide a download link at the end of this post.  Drag and drop them into your project.  If Dragged and Dropped from windows explorer you will need to show all files and then include them in your project.  Change the Namespace to agree with your project.

 

image

Create a new Feature and add and event receiver  all the code will be in the event receiver.  Here We added a new Feature called “CreateDocLib”  and then right click to add an Event Receiver

image

All of our code will be in this Event Receiver.  For this Demo I will only be using the Feature Activated Event. 

 

 

From this point on we will be looking at code! 

 

We are adding two constants for use columGroup (How we want SharePoint to Group them, usually Company Name) and ctName(ContentType Name)

 

using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
namespace CreateDocLib.Features.CreateDocLib
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("56e6897c-97c4-41ac-bc5b-5cd2c04f2dd1")]
    public class CreateDocLibEventReceiver : SPFeatureReceiver
    {

        const string columnGroup = "DJ";

        const string ctName = "DJDocLib";





        
    }
}

 

 

Here we are creating the Feature Activated event.   Adding the new fields (Site Columns) ,  Testing if the Content Type Exists, if not adding it.  Testing if the document Library exists, if not adding it.

 

        #region DocLib
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {


            using (SPWeb spWeb = properties.GetWeb() as SPWeb)
            {


                //add the fields
                addFields(spWeb);

                //add content type
                SPContentType testCT = spWeb.ContentTypes[ctName];
                // we will not create the content type if it exists 
                if (testCT == null)
                {
                    //the content type does not exist add it
                    addContentType(spWeb, ctName);

                }

                if ((spWeb.Lists.TryGetList("MyDocuments") == null))
                {
                    //create the list if it dosen't to exist
                    CreateDocLib(spWeb);
                }
            }
        }
        #endregion
 
The addFields method uses the utilities library to add site columns to the site. We can add as many fields within this 
method as we like.  Here we are adding one for demonstration purposes.  Icon as a Url type.
 
        public void addFields(SPWeb spWeb)
        {

            Utilities.addField(spWeb, "Icon", SPFieldType.URL, false, columnGroup);


        }
The addContentType method add the new Content Type to the site Content Types. We have already checked to see that it does 
not exist.  In addition, here is where we add the linkages from our site columns previously created to our new Content Type
 
 
        private static void addContentType(SPWeb spWeb, string name)
        {
            SPContentType myContentType = new SPContentType(spWeb.ContentTypes["Document"], spWeb.ContentTypes, name) { Group = columnGroup };

            spWeb.ContentTypes.Add(myContentType);
            addContentTypeLinkages(spWeb, myContentType);


            myContentType.Update();
        }

Here we are adding just one linkage as we only have one additional field in our Content Type

        public static void addContentTypeLinkages(SPWeb spWeb, SPContentType ct)
        {

            Utilities.addContentTypeLink(spWeb, "Icon", ct);

        }

Next we add the logic to create our new Document Library, which we have already checked to see if it exists.  We create the document library and turn on content types. 

Add the new content type and then delete the old “Document” content types.

 

 private void CreateDocLib(SPWeb web)
        {


            using (var site = new SPSite(web.Url))
            {
                var web1 = site.RootWeb;

      



                var listId = web1.Lists.Add("MyDocuments", string.Empty, SPListTemplateType.DocumentLibrary);
                var lib = web1.Lists[listId] as SPDocumentLibrary;

                lib.ContentTypesEnabled = true;
                var docType = web.ContentTypes[ctName];
                lib.ContentTypes.Add(docType);
                lib.ContentTypes.Delete(lib.ContentTypes["Document"].Id);
              


                lib.Update();
                
                AddLibrarySettings(web1, lib);

                 
            }

        }
 
 
Finally, we set some document library settings on our new document library with the AddLibrarySettings method.  
We then ensure that the new site column is visible when viewed in the browser.
 
        private void AddLibrarySettings(SPWeb web, SPDocumentLibrary lib)
        {
            lib.OnQuickLaunch = true;
            lib.ForceCheckout = true;
            lib.EnableVersioning = true;
            lib.MajorVersionLimit = 5;
            lib.EnableMinorVersions = true;
            lib.MajorWithMinorVersionsLimit = 5;
             
            lib.Update();

           

              var view = lib.DefaultView;
               view.ViewFields.Add("Icon");
                view.Update();
             
        }
 
Okay, what's cool here:  In a few lines of code, we have created site columns, A content Type, a document library.  
As a developer, I use this functionality all the time.  For instance, I could now just add a web part to this same solution
which uses this document Library.  I love SharePoint! Here is the complete solution: Create Document Library Code

© Geeks with Blogs or respective owner