The SharePoint platform has huge capabilities. Because of this many of us building SharePoint customizations only have time to learn the basic SharePoint APIs which typically consist of how to work with objects such as sites, webs, list, files, features, solutions, workflows, event receivers, web parts and some others. Then often because of tight schedules we tend to start building our own helper methods on the top of the SharePoint core API instead of trying to find whether they are already implemented. And some of those custom built methods are actually already available in SharePoint.
This post is about one class which is very often forgotten or even unknown to many but which exposes some very useful methods. This is the Microsoft.SharePoint.Utility.SPUtility class and I want to show you some of its goodies.
Let’s start with these two:
public static string GetUrlDirectory(string url);
public static string GetUrlFileName(string url);
How many times you’ve had to manipulate URLs to get only the file name part or the folder path? I have always wondered why the URL versions of System.IO.Path.GetFileName() and System.IO.Path.GetDirectoryName() are not available in the .NET Framework. Well the above methods do exactly this and they work with both server relative and absolute URLs. It’s true that their implementation is very simple but why to do it yourself? Just remember those two the next time.
Another two routines that allow you to show a success or failure messages as a result of your operations are:
SPUtility.TransferToErrorPage(“Error from SPUtility!”);
SPUtility.TransferToSuccessPage(“Hello from SPUtility!”);
When you call them SharePoint will display an “Operation Completed Successfully” page or an “Error” page:
Again it is not a big deal but showing some neat messages like those only takes a single line of code. You can also specify the URL the browser will navigate to when the user clicks OK.
Sometimes you may need to open files from the 12 hive. Either your own or SharePoint configuration files or some other files. If you have been hardcoding the 12 hive path as C:\Program Files\Common Files….. then stop doing this now! The function below will return you the full path to a subfolder under the 12 hive.
for example calling GetGenericSetupPath(“Config”) will return the full path to the config folder under the 12 hive. Remember that the setup path may not necessarily be on the C drive and also in non english versions of Windows the program files folder is not called “Program Files” so start using this function.
A great function that I talked about in my What you need to know about AllowUnsafeUpdates (Part 2) post is:
It will validate the form digest of your POST request and you will not have to worry about AllowUnsafeUpdates after that for newly created instances of SPSite.
And finally take some time to look at the other methods in the SPUtility class. You may find something else to be useful.