Tuesday, January 25, 2011

Some useful methods in SPUtility class

SPUtility is a very rich class, which contains a number of useful functions; it also contains a number of obsolete functions. I found following methods very useful in our daily programming. 

1. System DateTime to ISO8601 DateTime
Converts a system DateTime value to ISO8601 DateTime format (yyyy-mm-ddThh:mm:ssZ)
string isoDateTime = SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now());
//Output: 2010-03-30T15:30:33Z

2. Redirect
Signature of Redirect method:
public static bool Redirect(string url, SPRedirectFlags flags, HttpContext context)
The below link will provide you detailed information about the SPRedirectFlags.
3. Transfer to Success or Error Page
These methods are useful when you are
    SPUtility.TransferToErrorPage("Hi this is an Error Page", "this is link","{your_url}");

    SPUtility.TransferToErrorPage("Hi this is an Error Page {0}, {1}", "click here to Go to Top site", "{your_url}");
    SPUtility.TransferToSuccessPage("Hi this is an Sucess Page");
    SPUtility.TransferToSuccessPage("Hi this is an Sucess Page {0},{1}", "{url}", "This is Link", "{url}");
Useful link:
4. Email
Send an email from the context of the given SPWeb.
SPWeb web = SPContext.Current.Site.OpenWeb();
string subject = "Email from the " + web.Title + " web";
string body = "The body of the email";
SPUtility.SendEmail(web, false, false, "someone@somewhere.com", subject, body);

5. 12-hive Path:
Returns the filesystem path for the 12-Hive, or any of the folders beneath it.
(C:\Program Files\Common Files\Microsoft Shared\web server extensions\12)
string featuresPath = SPUtility.GetGenericSetupPath("Template\\Features");

6. Full URL:
Return absolute url from relative url
string webUrl = "/sub/default.aspx";
SPUtility.GetFullUrl(SPContext.Current.Site, webUrl);
//Output: "http://localhost/sub/default.aspx"

There are methods that I did not describe; I will publish them as soon as I find out how they can be used.

Reference Links:

1 comment: