23. June 2009 08:14
I've decided to do a little series on SharePoint Tips for Developers, which will focus on common tasks that aren't immediately obvious, hopefully saving people some time in their day to day work.
Our first tip is about enumerating the objects in your farm. Specifically, taking an SPFarm object, finding all the web applications in the farm, all the sites, and all the pages within them. Some portion of that enumeration is likely to come up quite often in your work.
First, Getting all Web Applications in a farm is probably one of the lesser known tasks:
SPWebService webService = farm.Services.GetValue<SPWebService>("");
foreach (SPWebApplication webApp in webService.WebApplications)
{
//Do Something with Web Application here
}
In the above example, the variable farm is an SPFarm object, which you can get in a variety of ways, depending where your code is running. In a timer job you might just do "this.Farm" -- in a web part you can get the farm from the site object in SPContext.Current.
Now we can go through all the sites and webs. Probably the simplest way to do this is to loop through the Sites collection of your web app, and call a recursive helper function on each web, which will enumerate through all child webs regardless of depth.
foreach (SPSite site in webApp.Sites)
{
//Pass web to helper function to enumerate
GetWeb(site.RootWeb);
}
private void GetWeb(SPWeb web)
{
//TODO: Do something with the web object
//Process the sub webs recursively
foreach (SPWeb subweb in web.Webs)
{
GetWeb(subweb);
}
}
Once you have the web, there are a variety of ways you might find the pages you are interested in. For example, if it is a publishing site you might want to find all the Pages libraries and get only the published pages -- You could do this with the web object you have available in GetWeb(...):
foreach (SPList list in web.Lists)
{
if(list.Title == "Pages")
{
foreach (SPListItem item in list.Items)
{
if (item.File.Exists &&
item.File.Url.EndsWith(".aspx") &&
item.Versions[0].Level == SPFileLevel.Published)
{
//Do something clever with the page which is item.File.Url
}
}
}
Note that above we check if the item is published by looking at the level attribute of the version.