Tips for Devs #1: Enumerate Farm Sites and Pages

23 Jun

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:

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.

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(…):

Note that above we check if the item is published by looking at the level attribute of the version.

Leave a Reply

Your email address will not be published. Required fields are marked *