Sunday 6 July 2008

Programmatically adding a Web Part to the Web Part Gallery.

While developing some custom migration tools to migrate Web Parts from SPS2003 to MOSS 2007 purely using the object model I came across a problem!

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

After spending hours trying to figure out various solutions I was getting no where! 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.
  • Create the .dwp xml file dynamically
  • Add it to the Web Part Gallery SPList
Finally, here is how to do it:

using (SPWeb _web = site.OpenWeb())
{
CreateDwpFile();
FileInfo f = new FileInfo("myFile.dwp");
FileStream s = f.Open(FileMode.Open, FileAccess.Read);

_web.AllowUnsafeUpdates = true;
site.AllowUnsafeUpdates = true;
SPList _list = _web.Lists["Web Part Gallery"];
SPFolder _root = _list.RootFolder;
SPFile _spFile = _root.Files.Add("ContentEditor.dwp",s);
_spFile.Update();
}

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.