Saturday, January 31, 2009

Organize your Feature Receivers

At imason I have done a lot of work with SharePoint feature receivers. As the size of solution grows, so does the number and complexity of feature receivers. This makes developers treat installation logic that lives inside feature receivers with necessary care. It is no longer some dirty through-away code and all the proven architecture techniques perfectly apply to it as well. See the full post here.

Wednesday, January 28, 2009

Toronto SharePoint Code Camp 2009 - Great Venue, Great Organization

I was presenting at the Toronto SharePoint Camp for the first time last weekend. The event has exceeded my expectations by all accounts. The venue and the organization were excellent, and the great turn-out has demonstrated a strong interest in SharePoint and growing developer community around it. Great thanks to Ed Musters and other organizers for this great event!

My topic was named "Effective Deployment of SharePoint Publishing Sites", and was largely based on the idea of authoring a custom XML document representing site hierarchy, including variations, sites, pages and web parts. Deployment automation logic would then consume this document and create actual site hierarchy from it - something I have been blogging about earlier. I have also touched on a quite interesting subject of how to assess the worthiness of an upfront effort investment into deployment automation. You can download my presentation here.

Thursday, January 15, 2009

Show Alternating Rows in Content Query Web Part

Often you need to display alternating rows in a Content Query Web Part (CQWP), so that for example you get a record on a white background, then a record on a gray background, then on white again etc. Yes, you can create a special “index” column in your source content type and based on its value determine if a given row is odd or even.

There is a better way however: from within your ItemStyleTemplate.xsl you can know the position of the current node, which you can always translate into the knowledge of whether the current row is odd or even:

<xsl:template name="AlternatingItems" match="Row[@Style='AlternatingItems']" mode="itemstyle">
<xsl:variable name="CurPosition" select="count(./preceding-sibling::*)" />
<xsl:variable name="AlternatingCssClass">
<xsl:choose>
<xsl:when test="($CurPosition mod 2 = 0)">
<xsl:value-of select="'CssClassAlt1'" />
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="'CssClassAlt2'" />
</xsl:otherwise>
</xsl:choose>
</xsl:variable>
… the rest of the template

On a related but different topic, in order to have a field exposed to your XSL file as an attribute of the Row XML element you typically need to export the CQWP to a file then edit its property named CommonViewFields as perfectly explained by Heather Solomon here.

The only thing calling for some expansion after reading this blog post is how to know which field name and which type name exactly to feed into the CommonViewFields property. The definitive source of the information about which fields are there and which are their types is located in here:

%ProgramFiles%\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES\fields\fieldswss.xml

Each field in this XML file has a Name attribute and a Type attribute, their values can be fed into the CommonViewFields property of your CQWP. Ideally we want to be able to list all applicable fields based on currently selected options for the query, but this would require extending the web part itself…

Thursday, December 18, 2008

Simple ICMP Heartbeat Monitor

I needed to make sure that if one of my servers goes down I know about it in the next 15 minutes so I wrote a little ICMP monitor program. Why write another ping utility when there are tons of tools available already, which also reveal more information about what went wrong than a simple ping tool can do?

Well, I started from an Internet research, which didn’t satisfy me quite. The tools I found either had reporting features which didn’t fit what I needed, or were too hard to operate or set up, or were pricey. So I spent 2 evenings and wrote my own tool just like a carpenter would put something simple together out of the stuff in his garage saving himself a trip to a Home Depot. My tool did what I needed and ended up being a decent exercise with .NET FCL so it is worth blogging about. I hope it can save someone the time. You can download the binaries here, and the source code here.

Features

The tool is a console application named Monitor.exe, which is intended to be invoked primarily by a Windows scheduled task and has these characteristics:
  • It sends ICMP ping requests to each IP address in a list of addresses set in its configuration file.

  • If ping to at least one address fails then it sends an Email notification to a preconfigured destination. The message includes succeeded and failed IPs, and a NetBIOS name of the server which the ping request has originated from.

  • In order to avoid an "alert storm" when there are ping errors, the tool will send a maximum of 4 notifications, keeping track of them in current user environment variable, which gets reset automatically once all configured IPs are pinged successfully.

  • Sensitive Email account information is encrypted in configuration file. The monitor utility uses Windows DPAPI for handling protection of this information. A utility named Cipher.exe allows encrypting the information so it can be placed into monitor’s config file, and the application itself uses DPAPI to decrypt it.


Installation

Installation is simple, yet it requires editing configuration file and encrypting a few pieces of information. I use Gmail as my SMTP server – they kindly allow relaying messages through their smtp.gmail.com server through port 587. It’s pretty convenient. Since I happen to have an iPhone I get my Email notification in my pocket within 15 minutes of a notification event.

So here are all the installation steps you need to follow:
  1. Extract binaries to a folder of your choice.

  2. You need to encrypt 4 pieces of information for the Email to work.

    • Sender email address.

    • Destination email address.

    • SMTP server login account.

    • SMTP server password.


    Open up command prompt and navigate to the folder where you extracted the binaries to. Use the Cipher.exe utility to encrypt the information. The generated cipher is quite long so it may be hard to copy it directly from command prompt. You can pipe the output to a text file and then copy it from there. For example:

    Cipher.exe sender@mycompany.com > sender.txt
    Cipher.exe destination@destination.com > destination.txt
    Cipher.exe SomeAccountLogin > login.txt
    Cipher.exe SomePassword > pwd.txt

  3. Make sure that the list of IP addresses to ping is proper, as well as the email server address, port, message subject template and body template. Here is an example config file which uses Gmail SMTP server and Email account:
    <configuration>
    <appSettings>
    <add key="IPsToCheck" value="192.168.0.1, 192.168.0.2, 192.168.0.3"/>
    <add key="MailServerAddress" value="smtp.gmail.com"/>
    <add key="MailServerPort" value="587"/>
    <add key="MessageSubjectTemplate" value="Ping failure alert from {0} #{1} of {2}"/>
    <add key="MessageBodyTemplate" value="Heartbeat ping errors have occurred:{0}."/>
    <add key="EncryptedSenderEmail" value="Insert encrypted value"/>
    <add key="EncryptedDestinationEmail" value="Insert encrypted value"/>
    <add key="EncryptedMailServerLogin" value="Insert encrypted value"/>
    <add key="EncryptedMailServerPassword" value="Insert encrypted value"/>
    </appSettings>
    </configuration>
  4. Configure scheduled task to run the Monitor.exe program. Make sure that firewall does not block configured SMTP server port.

  5. A good way to test whether Email notification is working is to temporarily enter at least one IP, which times out on an ICMP request to configuration file, then run the Monitor.exe from command line. This should trigger an Email message.



How it Works

The program is quite simple, yet there are 4 areas in it worth a note – ping implementation, dispatching notifications, security measures and diagnostics.


Ping Implementation

To ping a remote IP I have used WMI Win32_PingStatus class. Using mgmtclassgen.exe command-line tool coming with Visual Studio I have generated a PingStatus.cs C# proxy class abstracting WMI query generation and invokation, thanks to the great blog post by Daniel Velasquez.
On top of that I have my Icmp class, which lets me decouple business rules and WMI implementation even further. This is how the Icmp class looks like:

static class Icmp
{
private const int PingRetriesCount = 4;
private const int PingRetryInterval = 1000;
private const int PingRequiredSuccessCount = 2;


public static bool Ping(string ipAddress)
{
string condition = String.Format(
"Address='{0}'",
ipAddress);
int pingSucceesses = 0;

for (int i = 0; i < PingRetriesCount; ++i)
{
PingStatus.PingStatusCollection instances = PingStatus.
GetInstances(condition);

IEnumerator enumerator = instances.GetEnumerator();

if (enumerator.MoveNext())
{
using (PingStatus instance = (PingStatus)enumerator.Current)
{
if (PingStatus.StatusCodeValues.Success ==
instance.StatusCode)
{
pingSucceesses++;
}
}
}

if (PingRequiredSuccessCount == pingSucceesses)
{
return true;
}
else
{
Thread.Sleep(PingRetryInterval);
}
}

return false;
}
}
As you can see, the Icmp.Ping() method returns truth if it manages to get successful response back from the destination twice out of maximum of 4 attempts, and fails otherwise.

Dispatching Notifications

The application calls Icmp.Ping() method for each of the configured IP addresses and increments error counter once it receives false back. If error count is greater than 0, and if number of previous Email notifications is less than 4 then notification Email is constructed and sent out. The number of notifications is stored in user environment variable and is updated with each successful notification dispatch:

if (numberOfErrors > 0)
{
string value = Environment.GetEnvironmentVariable(
ErrorCountEnvironmentVariable,
EnvironmentVariableTarget.User);
int numberOfNotifications = 0;
Int32.TryParse(value, out numberOfNotifications);

if (numberOfNotifications < MaxNumberOfErrorNotifications)
{
numberOfNotifications++;

string failedIPs = failures.ToString();
failedIPs = failedIPs.Remove(
failedIPs.LastIndexOf(','));
string succeededIPs = successes.ToString();
succeededIPs = succeededIPs.Remove(
succeededIPs.LastIndexOf(','));

Email.SendErrorReport(
Environment.MachineName,
numberOfSuccesses,
numberOfErrors,
succeededIPs,
failedIPs,
numberOfNotifications,
MaxNumberOfErrorNotifications);

Environment.SetEnvironmentVariable(
ErrorCountEnvironmentVariable,
numberOfNotifications.ToString(),
EnvironmentVariableTarget.User);
}

Security Measures

The complexity of encryption is abstracted from us by the System.Security.Cryptography.ProtectedData class, for which I have written a simple facade type named Protection and located in the Cryptography.dll assembly. This DLL is shared between Monitor.exe, Cipher.exe and Decipher.exe. Below is the simple implenentation of the type:

public static class Protection
{
public static string Encrypt(string input)
{
byte[] encryptedData = ProtectedData.Protect(
Encoding.Unicode.GetBytes(input),
GetEntropy(),
DataProtectionScope.CurrentUser);
return Convert.ToBase64String(encryptedData);
}

public static string Decrypt(string input)
{
byte[] decrypted = ProtectedData.Unprotect(
Convert.FromBase64String(input),
GetEntropy(),
DataProtectionScope.CurrentUser);
string decryptedString = Encoding.Unicode.GetString(decrypted);
return decryptedString;
}

private static byte[] GetEntropy()
{
byte[] salt = Encoding.Unicode.GetBytes(
Assembly.GetExecutingAssembly().FullName);
return salt;
}
}
Now the rather interesting question is how secure is this protection? Well, firstly DPAPI itself is secure; at least I can rely on it as much as I do on Windows for protecting my logon information. Secondly, passing in DataProtectionScope.CurrentUser enumeration value to the ProtectedData.Protect() method ensures that other users, even those with admin rights, cannot decrypt the cipher you created. If several applications run under the same Windows user account then the only thing preventing them from deciphering the secret for another application is the fact that optional entropy used by the applications should differ.

So if a malicious user knows the account credentials under which the ICMP Monitor is executed then its secret (encrypted data) can be compromised. Even if an attacker does not know Windows credentials of the ICMP Monitor process, with sufficient rights he can read the values from the process memory after they have been decrypted and stored in a System.String variable, which is also not destroyed until the next garbage collection. Yes, there is a special FCL type addressing this particular vulnerability - System.Security.SecureString, but it cannot be used with many common APIs, such as one for sending Emails using System.Net.Mail.SmtpClient type for instance.

Concluding the security notes, make sure to use such accounts and email addresses with this tool which if compromised would not cause a major adverse impact on the rest of your system.


Diagnostics

The diagnostic means for a simple tool is simple: unhandled exceptions are captured and logged into a text file, which gets overwritten each time this happens so it stores information about the last error only. The file name is IcmpMonitor_LastError.txt. It is located under
%UserProfile%\appData\Local
folder on Windows Vista and Windows 2008 Server or under %UserProfile%\Local Settings\Application Data on Windows 2003 Server or Windows XP.

Tuesday, December 11, 2007

Master Page Deployment Through Features

Today I'd like to talk about deployment of master and layout pages in a customized SharePoint site. This is not a new topic, but I am going to focus again on the method relying on feature receivers and the MOSS API.

I needed to deploy a few master and layout pages along with accompanying images and CSS style sheets to the collaboration portal site. The destination for masters, layouts and images was the Master Page Gallery under the root site, and the Style Library for the style sheets. As far as the feature implementation is concerned it does not matter which SharePoint gallery or folder is used for the destination, as long as there is a URL associated with it. So technically I needed to solve 3 problems in order to get the master and accompanying files deployed:

  1. Access the file system directory containing the files to deploy from within the feature receiver;

  2. "Upload" the content of each file to the destination URL;

  3. Check in the changes and publish the uploaded files - I was using collaboration site template which imposed this requirement.
Accessing the file system directory with source files from the feature receiver is easy: during feature activation (and this is when all the work is done in our case) the root folder of the feature physical directory is accessible through the properties.Definition.RootDirectory, where properties is of SPFeatureReceiverProperties type and is made available to the feature receiver.

SPSite thisCollection = (SPSite)properties.Feature.Parent;
SPWeb web = thisCollection.RootWeb;

DirectoryInfo masterSourceFolder = new DirectoryInfo(
Path.Combine(
properties.Definition.RootDirectory,
"MasterPages"));

Uploading the content relies on the SaveBinary() method of the SPFile type to copy file content to the destination gallery or folder. Then the file is checked in and published. Below is an example of a method, which takes a source file system directory and non-recursively copies all files from it to the destination SharePoint folder, either creating new files or updating existing ones.

private void UpdateFolderContent(
DirectoryInfo sourceFolder,
SPFolder destinationFolder)
{
foreach (FileInfo file in sourceFolder.GetFiles())
{
SPFile spFile = null;

try
{
spFile = destinationFolder.Files[file.Name];
}
catch (ArgumentException)
{
//
// Do nothing: WSS throws an exception if a requested
// file is missing from the collection. Ignore it -
// leave spFile equal to null in this case.
//
}

using(FileStream stream = file.OpenRead())
{
if (null != spFile)
{
if (spFile.CheckOutStatus !=
SPFile.SPCheckOutStatus.None)
{
spFile.UndoCheckOut();
}

spFile.UnPublish(UpdateComment);
spFile.CheckOut();
spFile.SaveBinary(stream);
spFile.Update();
spFile.CheckIn(UpdateComment,
SPCheckinType.OverwriteCheckIn);
}
else
{
spFile = destinationFolder.Files.Add(
file.Name,
stream,
true,
UpdateComment,
true);
spFile.Update();
spFile.CheckIn(UpdateComment);
}
}

//
// We do not approve the changes in this feature receiver.
// Apparently the step of checking in a file triggers an
// asynchronous operation in SharePoint, which prevents from
// immediately approving the changes. A workaround is to call
// spFile.Approve() from the new context of a different feature.
//

spFile.Publish(UpdateComment);
}
}

One last task is to approve the changes, otherwise the master and accompanying pages will not be visible to anybody except for the user under whose identity the feature is executing. As stated in the above code example, the same file cannot be both published and then approved within the activation context of the same feature - at least I was not able to find a way to do this. I did find a workaround however - creating a new feature whose purpose would solely be approving the newly published files. The new feature's activation would be dependent on the successful activation of the master and layouts deployment feature. Below is an example of the method which approves all files in a folder within the "content approver" feature receiver.

private void ApproveFolderContent(SPFolder folder)
{
foreach (SPFile file in folder.Files)
{
if (SPFile.SPCheckOutStatus.None == file.CheckOutStatus &&
SPModerationStatusType.Pending ==
file.Item.ModerationInformation.Status)
{
file.Approve(UpdateComment);
file.Update();
}
}
}

To wrap up, it is possible and reasonably straightforward to deploy master pages, layout pages, supporting images and style sheets through features and employ WSS API for this.

Saturday, November 24, 2007

Add a Web Part to SharePoint Page Dynamically

In my last post I have talked about creating sites and pages with web parts through SharePoint feature receivers. I have left some important details of web part creation out of that discussion. I am going to cover them today.

The method AddWebPartToPage() that was in one of the code fragments in the last post does 2 things: it creates a web part, then adds it to the page into the target web part zone. All manipulations with a web part on a page are governed by the SPLimitedWebPartManager class, which is a scaled down version of SPWebPartManager class designed to do the same thing but without HTTP context available. I think that indeed Microsoft did well here: thanks to this type being available a lot of configuration tasks can be automated, including adding web parts to a page, and connecting web parts to each other. The AddWebPartToPage() method is shown below:

public string AddWebPartToPage(
SPWeb web,
string pageUrl,
string webPartName,
string zoneID,
int zoneIndex)
{
using (System.Web.UI.WebControls.WebParts.WebPart webPart =
CreateWebPart(web, webPartName))
{
using (SPLimitedWebPartManager manager = web.GetLimitedWebPartManager(
pageUrl, PersonalizationScope.Shared))
{
manager.AddWebPart(webPart, zoneID, zoneIndex);
return webPart.ID;
}
}
}
The CreateWebPart() method first constructs a CAML query, which will look up the web part in a web part gallery. Certainly this means that for the method to work the web part must already be in the web part gallery. Well this is easy to do - the site creation feature within the context of which we are operating should depend on a feature installing the web part we intend to use. The dependency can be specified in the feature manifest file using ActivationDependency element. When I was specifying the web parts in our XML configuration file (see my last post) I chose to use the web part definition files (the ones with .dwp or .webpart extensions). These files are created for custom web parts manually or automatically if you have Visual Studio WSS 3.0 Extensions installed, or for the out-of-the-box web parts, which are a part of SharePoint installation they can be found here: %ProgramFiles%\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES. Getting back to the CAML query though, it returns the web part gallery items whose definition files match the passed parameter. The field used to filter the query is FileLeafRef. Next the type and assembly of the web part are determined from the other fields of the gallery item - the WebPartTypeName and WebPartAssembly and the instance of the web part is created through reflection. Here is complete implementation of the method:

private System.Web.UI.WebControls.WebParts.WebPart
CreateWebPart(SPWeb web, string webPartName)
{
SPQuery query = new SPQuery();
query.Query = String.Format(
"<Where><Eq><FieldRef Name='FileLeafRef'/><Value Type='File'>{0}</Value></Eq></Where>",
webPartName);

SPList webPartGallery = null;

if (null == web.ParentWeb)
{
// This is the root web.
webPartGallery = web.GetCatalog(
SPListTemplateType.WebPartCatalog);
}
else
{
// This is a sub-web.
webPartGallery = web.ParentWeb.GetCatalog(
SPListTemplateType.WebPartCatalog);
}

SPListItemCollection webParts = webPartGallery.GetItems(query);

string typeName = webParts[0].GetFormattedValue("WebPartTypeName");
string assemblyName = webParts[0].GetFormattedValue("WebPartAssembly");
ObjectHandle webPartHandle = Activator.CreateInstance(
assemblyName, typeName);

System.Web.UI.WebControls.WebParts.WebPart webPart =
(System.Web.UI.WebControls.WebParts.WebPart)webPartHandle.Unwrap();
return webPart;
}
On to SetWebPartProperty() method. In the XML configuration file the property element only has name and value attributes. When setting a property programmatically the property to be set is looked up by its name using reflection, then its value obtained from the value attribute is converted to the type of the property and assigned to it. I do not list the implementation of ConvertValue() method here - it can be either trivial or quite complex, depending on the need. I have opted to switch between the expected property types and throw an exception for unexpected ones. This solution easily handles properties with the intrinsic value types and enumeration types. The SetWebPartProperty() method implementation is shown in the code fragment below:

public void SetWebPartProperty(
SPWeb web,
string pageUrl,
string webPartID,
string propertyName,
string propertyValue)
{
using (SPLimitedWebPartManager manager = web.GetLimitedWebPartManager(
pageUrl, PersonalizationScope.Shared))
{
System.Web.UI.WebControls.WebParts.WebPart part =
manager.WebParts[webPartID];
Type runtimeType = part.GetType();
PropertyInfo property =
runtimeType.GetProperty(propertyName);
object value = ConvertValue(propertyValue, property.PropertyType);
property.SetValue(part, value, null);
manager.SaveChanges(part);
}
}
Finally all what's left is connecting the web parts. Again SPLimitedWebPartManager comes at help here. The method AddWebPartConnection() first locates consumer and provider web parts by their unique IDs, which were captured earlier at a time of placing the web parts on a page; next it iterates through provider and consumer connection points to find the ones specified in the XML configuration file. By the way, these are the same as the constructor parameters used with ConnectionProviderAttribute and ConnectionConsumerAttribute types, which are used to decorate methods participating in a web part connection. When both connection points are determined we can call the SPConnectWebParts() method of SPLimitedWebPartManager to create the connection. The method implementation is shown below:

public void AddWebPartConnection(
SPWeb web,
string pageUrl,
string providerWebPartID,
string consumerWebPartID,
string providerConnectionPointName,
string consumerConnectionPointName)
{
using (SPLimitedWebPartManager manager = web.GetLimitedWebPartManager(
pageUrl, PersonalizationScope.Shared))
{
System.Web.UI.WebControls.WebParts.WebPart provider =
manager.WebParts[providerWebPartID];
System.Web.UI.WebControls.WebParts.WebPart consumer =
manager.WebParts[consumerWebPartID];

ProviderConnectionPointCollection providerPoints =
manager.GetProviderConnectionPoints(provider);
ConsumerConnectionPointCollection consumerPoints =
manager.GetConsumerConnectionPoints(consumer);

ProviderConnectionPoint providerPoint = null;

foreach (ProviderConnectionPoint point in providerPoints)
{
if (String.Equals(
providerConnectionPointName,
point.DisplayName,
StringComparison.OrdinalIgnoreCase))
{
providerPoint = point;
break;
}
}

ConsumerConnectionPoint consumerPoint = null;

foreach (ConsumerConnectionPoint point in consumerPoints)
{
if (String.Equals(
consumerConnectionPointName,
point.DisplayName,
StringComparison.OrdinalIgnoreCase))
{
consumerPoint = point;
break;
}
}

manager.SPConnectWebParts(
provider,
providerPoint,
consumer,
consumerPoint);
}
}
One last note: when putting the code fragments together I was removing the "defensive programming logic" such as checking for nulls or throwing exceptions on unexpected values - this way the examples became less cluttered. Any practical implementation of the ideas described in this and previous posts therefore would require creative refactoring of these examples. I hope though I managed to save you some time that I spent looking through SDK documentation, blogs and decompiling the source code...

Wednesday, November 21, 2007

Create a Site Using Feature Receiver and SharePoint API

In my previous post I have discussed the rationale behind using features for deployment of SharePoint 2007 based applications and feature receivers for creation of SharePoint sites. Today I will talk about implementation of a feature receiver which creates a SharePoint site.

Feature receiver is a .NET type which inherits from Microsoft.SharePoint.SPFeatureReceiver and is capable to handle installation, activation, deactivation and uninstallation events by overriding parent's abstract methods. I recommend checking Ted Pattison's MSDN columns for the background on SharePoint 2007 features and their deployment through solution packages.

Both FeatureInstalled and FeatureActivated event handlers are passed an instance of SPFeatureReceiverProperties object, which provides handy context information about the feature being installed or activated. Not all the properties are available however at a time when FeatureInstalled handler is called. For example, the following line will not initialize the site collection variable if used from within FeatureInstalled, but it will work from within FeatureActivated handler:

SPSite thisCollection = (SPSite)properties.Feature.Parent;

For this reason all the API access discussed below is made from within FeatureActivated handler implementation. I am now going to walk through the scenario of creating a publishing site under root site collection in a given web application.

First of all I need a formal way to convey what exactly needs to be created and configured in my site. I opted to capture the requirements to the site structure inside a custom XML file, which is de-serializable into an object of a custom SiteInfo type. This is how the XML file looks like:

<site
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
url="MySite"
welcomePage="Pages/Page1.aspx">
<pages>
<page id="Page1" url="Page1" layoutFile="SecondaryLayout.aspx">
<zones>
<zone id="IntroText">
<webParts>
<webPart id="wp1" definition="Company.webpart">
<properties>
<properties>
<property name="Title" value="Company Information" />
<property name="ChromeType" value="None" />
</properties>
</properties>
</webPart>
</webParts>
</zone>
<zone id="Graphs">
<webParts>
<webPart id="wp2" definition="Chart.webpart">
<properties>
<properties>
<property name="Title" value="Information" />
<property name="ChromeType" value="None" />
<property name="ChartWidth" value="480" />
</properties>
</properties>
</webPart>
</webParts>
</zone>
</zones>
<connections>
<connection id="ci1"
consumerID="wp2"
providerID="wp1"
consumerConnectionPoint="Field"
providerConnectionPoint="Data" />
</connections>
</page>
</pages>
</site>
As you can see from this snippet, the XML code defines a site in a site collection, a page or multiple pages in the site along with the information about which template is used to create a page, web part connections and zones on each page with web part instances situated inside the webpart zones, and lastly the properties on the webpart instances.

Second of all I need to design .NET types to load site structure from the XML files. In a simplistic form I would have 6 classes related to each other through containment hierarchy: SiteInfo, PageInfo, ZoneInfo, WebPartConnectionInfo, WebPartInfo, PropertyInfo. All of these would be serializable with XML serialization attributes applied to their properties to control serialization. Here is an example of a PageInfo type:

[Serializable]
public class PageInfo
{
private List<ZoneInfo> _zones;

[XmlArray(ElementName="zones", IsNullable=true)]
[XmlArrayItem(ElementName="zone")]
public List<ZoneInfo> Zones
{
get { return _zones; }
}

private List<WebPartConnectionInfo> _connections;

[XmlArray(ElementName = "connections", IsNullable = true)]
[XmlArrayItem(ElementName = "connection")]
public List<WebPartConnectionInfo> Connections
{
get { return _connections; }
}

//
// Other properties removed for brevity.
//

public PageInfo()
{
_zones = new List<ZoneInfo>();
_connections = new List<WebPartConnectionInfo>();
}
}
Lastly I need to use XmlSerializer type to create the SiteInfo objects and all their children by deserializing the above XML file. I will skip implementation details of de-serialization here since it is a well-documented topic. At this point I have all I need to start working with the WSS 3.0 and MOSS 2007 API to create the site with the specified structure.

Before I move on I'd like to answer a question I am anticipating the readers may have: why at all use custom XML and a set of .NET types to describe the site structure when one can apply CAML to achieve the same goal? Indeed there are CAML elements to do similar task, for example one named AllUsersWebPart capable of defining the web part type properties and target zone on a page. The element became available for use with the features in WSS 3.0. I have had the following reasons about going my way: 1) with my approach a programmer can easily step through all the steps of site creation process in a debugger; 2) it is easy to configure web part connections through the XML file; 3) the entire infrastructure supporting the custom XML file is simple to implement and maintain - it took me about 2 hours to write one. While my approach works, frankly I plan to revisit the CAML notation when I get time - it is the standard, and the more the standard elements are employed - the better.


OK, let's first create a site. The SPSite object represents collection of all sites including the root site. You can create a new site as follows:

public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
// Implementation of GetSiteInfo()is not shown for brevity.
// The site variable of the type SiteInfo contains all site
// structure information loaded from the XML file.
SiteInfo site = GetSiteInfo(properties.Feature);
SPSite thisCollection = (SPSite)properties.Feature.Parent;
string templateName = thisCollection.RootWeb.WebTemplate;

SPWeb web = thisCollection.AllWebs.Add(
site.Url,
site.Url,
site.Url,
DefaultLCID,
templateName,
false,
false);

// Use the new site now...
}
Assuming that the variable named site contains all required metadata for adding pages and web parts, we can proceed to creating pages, web parts and web part connections. The code snippet below demonstrates how to iterate through the PageInfo objects, and call methods creating the pages, web parts and the connections.

foreach (PageInfo page in site.Pages)
{
PublishingPage pubPage = AddPageToWeb(
web,
page.Url,
page.LayoutFile);

// SharePoint dynamically assigns IDs to web part instances
// placed on a page. We want to map the assigned IDs to the
// ones defined in the XML file, so that when connecting the
// web parts we can refer to the correct instances.
Dictionary<string, string> mapOfWebPartIDs =
AddWebParts(web, pubPage, page);
AddConnections(web, pubPage, page, mapOfWebPartIDs);

pubPage.CheckIn("New page.");
pubPage.ListItem.File.Publish("New page published.");
}
It is worth to note that the new page needs to be checked in and published in order to avoid manual steps after the feature is activated, therefore the last two steps in the snippet above are to check in and publish each newly created page. The AddPageToWeb()method finds a page layout by its name, then adds a publishing page to the site. Note that as mentioned earlier, the code example is specific to working with the MOSS publishing site. The code fragment below shows the method implementation.

public PublishingPage AddPageToWeb(
SPWeb web,
string pageFileName,
string pageLayoutName)
{
// Find the page layout to use for the new page
// by iterating through the available layouts and
// picking the right one by name.
PageLayout[] layouts = web.GetAvailablePageLayouts();
PageLayout layout = null;

for (int i = 0; i < layouts.Length; ++i)
{
if (layouts[i].Name.Equals(name,
StringComparison.OrdinalIgnoreCase))
{
layout = layouts[i];
break;
}
}

if (null == layout)
{
throw new ApplicationException(String.Format(
"Cannot find page layout named '{0}'.",
pageLayoutName));
}

PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(web);
PublishingPage page = publishingWeb.GetPublishingPages().
Add(pageFileName, layout);

return page;
}
The AddWebParts() method shown in the following fragment iterates through the zones and web parts defined in the PageInfo object and creates web part instances and sets their properties. It returns back a map between web part IDs as defined in the XML file and actual IDs assigned by SharePoint. For readability purposes implementation of the methods AddWebPartToPage() and SetWebPartProperty() is illustrated separately.

private Dictionary<string, string> AddWebParts(
SPWeb web,
PublishingPage pubPage,
PageInfo page)
{
Dictionary<string, string> mapOfWebPartIDs =
new Dictionary<string, string>();

foreach (ZoneInfo zone in page.Zones)
{
int index = 0;

foreach (WebPartInfo part in zone.WebParts)
{
string actualID = AddWebPartToPage(
web,
pubPage.Url,
part.DefinitionFileName,
zone.ID,
index);

mapOfWebPartIDs[part.ID] = actualID;
++index;

foreach (PropertyInfo property in part.Properties)
{
SetWebPartProperty(
web,
pubPage.Url,
actualID,
property.Name,
property.Value);
}
}
}

return mapOfWebPartIDs;
}
The AddConnections() method shown below iterates through WebPartConnectionInfo objects, which reflect the configurations in the XML file, and uses the map between actual and configuration IDs of the web part instances to add connections between the web parts. The AddWebPartConnection() method is illustrated separately.

private void AddConnections(
SPWeb web,
PublishingPage pubPage,
PageInfo page,
Dictionary<string, string> mapOfWebPartIDs)
{
foreach (WebPartConnectionInfo connection in page.Connections)
{
string actualConsumerID = mapOfWebPartIDs[connection.ConsumerID];
string actualProviderID = mapOfWebPartIDs[connection.ProviderID];

AddWebPartConnection(
web,
pubPage.Url,
actualProviderID,
actualConsumerID,
connection.ProviderConnectionPoint,
connection.ConsumerConnectionPoint);
}
}
Where are we? We have created an XML configuration file describing the structure of the new SharePoint publishing site. We have created .NET objects to hold the information from the XML configuration file, we have demonstrated how to add a new publishing site and pages to the site collection programmatically. What's left to do is to look inside of the AddWebPartToPage(), SetWebPartProperty() and AddWebPartConnection() methods. There are some interesting details about using SPLimitedWebPartManager class to talk about. I will cover these in my next post.