Archive for July, 2008

Programmatically adding a Web Part to the Web Part Gallery.

July 6, 2008 5 comments

I came across a problem whereby I needed to add a Web Part to the Web Part Gallery. The Web Part had been deployed successfully but as of yet it did not appear in the Web Part Gallery SPList. This needed to be done programmatically by using the SharePoint object model.

How do we programmatically add a Web Part (that has been deployed) to the Web Part Gallery. Using the SharePoint UI this is done via the NewDwp.aspx page.

The problem is that the list you see on the NewDwp.aspx page is not an SPList! Which makes life a bit tough! The other problem is that the .dwp files displayed in there do not exist until you select them and then click “Populate” by which time they are already in the Web Part Gallery.

I believe the NewDwp.aspx page builds the list of Web Parts, available to be added to the Gallery, from the web.config safe control enteries. Once you click “Populate” the page dynamically builds the .dwp file and adds it to the Gallery.

To add the Web Part to the Gallery programmatically you have to do the same i.e.

  1. Create the .dwp xml file dynamically
  2. Add it to the Web Part Gallery SPList

Below is the code to achieve this:

private static void AddWebPartToGallery()
    using (SPSite site = new SPSite(""))
        using (SPWeb web = site.OpenWeb())
FileInfo fInfo = new FileInfo("myFile.dwp");
            FileStream fStream = fInfo.Open(FileMode.Open, FileAccess.Read);    
            web.AllowUnsafeUpdates =
            site.AllowUnsafeUpdates =
            SPList list = web.Lists["Web Part Gallery"];
            SPFolder root = list.RootFolder;
            SPFile spFile = root.Files.Add("ContentEditor.dwp", s);

The CreateDwpFile() method dynamically creates the .dwp file. Then open the Web Part Gallery List and the newly created .dwp file and add it to the root folder of the list.