The more I work with SharePoint the more I realise that it's not
just a product; it's a framework for web development. The static
SPUtility class provides a number of helper methods that are very
useful when doing any SharePoint development. I use this class at
least once in every piece of code I write these days.
In order to use it, just include the following namespace and
you're away.
using Microsoft.SharePoint.Utilities;
Here are a couple of examples of how it can be used.
- Send Email
This is handy as it uses the outgoing email settings that you
configure in Central Admin.
// get web reference
SPWeb web = SPContext.Current.Site.OpenWeb();
// email subject
string subject = "Message from " + web.Title;
// construct message body
string body = "Hello from SharePoint";
// send email
SPUtility.SendEmail(web, false, false, "someone@somewhere.com", subject, body);
- Get a 12 Hive directory path
Previous to discovering this method I was hard coding in the path.
// get path to features directory
string featurePath = SPUtility.GetGenericSetupPath("template\\features");
// returns C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES
- Redirect to the SharePoint Error Page
This is a nice way of handling errors cleanly and consistently.
try
{
// some code that might fail
}
catch (SPException ex)
{
SPUtility.TransferToErrorPage("An error occurred.\n" + ex.Message);
}
- Redirect to any page
I find this really handy as you can provide flags that let you
redirect relative to the layouts directory (if you have some custom
layout pages).
// send user to login page
SPUtility.Redirect("login.aspx", SPRedirectFlags.RelativeToLayoutsPage, HttpContext.Current);
I tend to live by the theory that the less code you write
yourself, the more stable your application will be. The SPUtility
class is great in that respect. There are heaps of other useful
things you can do with this class, I'm sure that I have only just
scratched the surface.