Every once
in while, you learn something new even though you’ve been working with a
particular technology for quite some time. Today’s post is courtesy
of Kimmo (and, yes, he feels guilt for not having blogged yet). A couple
months ago, he asked the age old question…
Kimmo: “Is there a way to programmatically create a ghosted
page?”
My reply: “Unfortunately, there is
no way to programmatically create ghosted pages.”
Bear in
mind that has been my answer for the past few years. In fact, Kimmo went
on to ask “How about using a http post
like spcf.aspx does?” That was logical alternative, but not elegant in my
opinion. You could create an http post and mimic the page behavior.
I was correct in saying that the OM did not *specifically* offer a means to create a
ghosted page, but what Kimmo had in mind was completely different than what I
had interpreted by his second question. Two weeks later, Kimmo presented
me with a code snippet that completely changed how I would forever more respond
to the question above. The solution? It all lies with SPWeb.ProcessBatchData.
Here’s
the code that will allow you to create a ghosted page…
using (SPSite site = new SPSite
("http://redhorse")) {
using (SPWeb web =
site.OpenWeb()) {
SPList list = web.Lists ["Shared Documents"];
string postInformation
=
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+
"<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\">MyWebPartPageName</SetVar>"
+
"<SetVar Name=\"Overwrite\">true</SetVar>"
+
"</Method>";
string processBatch =
web.ProcessBatchData(postInformation);
// Display the results...
Console.WriteLine(processBatch);
Console.ReadLine ();
}
}
The yellow
highlights are the variables that represent options on the New Web Part Page. Nice surprise – the OM does in fact allow you to create ghosted pages. :)
-Maurice