Wednesday, March 14, 2007

Creating webpartpages in SharePoint 2007 using the SharePoint object model

I have been looking for a way to dynamically create webpartpages with code in SharePoint 2007. I already knew that it was possible using the Frontpage RPCs since I posted about this about a year ago - SharePoint WebPartpages when I found an excellent posting a newsgroup from Todd Bleeker. This still works in SharePoint 2007.

You can find limited documentation for the /_vti_bin/owssvr.dll?CS=109
command using in the spcf.aspx page in the WSS SDK under "Windows SharePoint Services RPC Methods", specifically the NewWebPage Method. The parameters of this method are posted to the dll using mostly hidden form fields defined throughout the spcf.aspx page.

<Method ID="Text">
<SetList Scope="Request">GUID</SetList>
<SetVar Name="Cmd">NewWebPage</SetVar>
<SetVar Name="ID">New</SetVar>
<SetVar Name="Type">[WebPartPageBasicPage]</SetVar>
<SetVar Name="WebPartPageTemplate">[1-8<</SETVAR&GT;
<SetVar Name="Overwrite">[truefalse]&tl;/SetVar>
<SetVar Name="Title">Text</SetVar>

For those of you who don't know how to use SharePoint and FrontPage RPCs take a look at these postings: SharePoint RPC - two targets for FrontPage RPCS and Want a good example of FPRPC? Try SharePad! , SharePad has been updated and SharePoint and RPCs.

What I did not know that you can actually achieve the same thing using the SharePoint object model untill I stumbled on this posting - How to programmatically create a ghosted web part page.

using (SPSite sitecollection = new SPSite("http://server"))
using (SPWeb site = sitecollection.OpenWeb())
site.AllowUnsafeUpdates = true;
SPList list = site.Lists["Pages"];
string postInformation =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<Batch>" +
"<Method>" +
"<SetList Scope=\"Request\">" + list.ID + "</SetList>" +
"<SetVar Name=\"ID\">New</SetVar>" +
"<SetVar Name=\"Cmd\">NewWebPage</SetVar>" +
"<SetVar Name=\"Type\">WebPartPage</SetVar>" +
"<SetVar Name=\"WebPartPageTemplate\">2</SetVar>" +
"<SetVar Name=\"Title\">" + sTitle + "</SetVar>" +
"<SetVar Name=\"Overwrite\">true</SetVar>" +
"</Method>" +
string processBatch = site.ProcessBatchData(postInformation);

The code above also seems to work in SharePoint Server 2007 - for more information take a look at the SPWeb.ProcessBatchData method documentation on MSDN.

No comments: