Monday, March 16, 2009

I am Accepted to MCM SharePoint 2007 Course

Last week I was officially accepted to take the Microsoft Certified Masters training course in Microsoft Office SharePoint Server 2007. I can’t wait to fly to Redmond and get started on this 3-week course between June 1 and June 20th. I plan to post updates on my experiences preparing for the course and taking it. So far it was quite an investment of mine but pleasantly I did qualify for a 30% discount by applying early. Also judging by how the interviewers virtually tore me apart, I am expecting a survivor-type mind grinding training. Well it means it will be worth the money...

Tuesday, February 3, 2009

Framework Design Guidelines

I have noticed a book titled "Framework Design Guidelines" by Krzysztof Cwalina and Brad Abrams on my colleague's desk last week and asked if I could borrow it for a few days. Now that I've read it, I strongly recommend it to any .NET developer considering himself or herself senior. I actually plan to buy the book as it will make a great reference.

The book provides a comprehensive overview of best practices for design of reusable components, most of which should be familiar to a good developer working with .NET for some time. Even though the advice in the book is based on the experiences of .NET Framework implemnentation, which is targetting millions of people, it is perfectly well applicable for smaller frameworks. If you have enjoyed books like Code Complete by Steve McConnell or Jeffrey Richter's Applied .NET Framework, you will like this one too. Check this book out!

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.