This post will show you how to auto detect your Web Applications and Site Collections using the object model. In SPS2003 there was a SPGlobalAdmin object in the Microsoft.SharePoint.Administration namespace. That has been depracted, in MOSS 2007 we have a new object called SPFarm in the same namespace (Microsoft.SharePoint.Administration).
To auto detect your SharePoint environment, the first thing we do is get a reference to the local farm using the static variables Local on the SPFarm object.
SPFarm oFarm = SPFarm.Local;
NOTE: There is also a static method on the SPFarm object called Open that takes a database connection string. This can be a connection string to a configuration database for a different farm. I have actually used this before so the farm that this code is running on can connect to other SharePoint farms. There are some security considerations there, but Microsoft has put the hooks in for one farm to connect to another.
Now that we have a reference to the local farm, we can start to auto detect the objects in our farm.There is a collection property on the farm object called Services. This property is a SPServiceCollection which contains SPService objects. We simply loop through the services in our farm. When we loop through our services we check to see if the SPService object is a SPWebService object. If it is then we cast into a SPWebService object which contains a collection of Web Applications. You can now loop through each of the Web Applications of the Web Service object. The SPWebApplication object has a property called Sites that contain all the site collection belonging to the Web Application. Once you have the SPSite object you can get the root web (SPWeb) object from the property RootWeb. From there you can loop through the child webs or do whatever processing you need to do. Below is the full code.
// Get a reference to the local farm
SPFarm oFarm = SPFarm.Local;
// Loop through the services in the farm
foreach (SPService oService in oFarm.Services)
{
// See if this service is a SPWebService
if (oService is SPWebService)
{
// Cast into a SPWebService
SPWebService oWebService = (SPWebService)oService ;
// Loop through the web applications in the web service
foreach (SPWebApplication oWebApplication in oWebService.WebApplications)
{
// Loop through the site collections
foreach (SPSite oSite in oWebApplication.Sites)
{
// Get the root web object
SPWeb oWebRoot = oSite.RootWeb;
// Put your processing code here……
// Be sure to dispose the SPSite and SPWeb objects for memory cleanup
oWeb.Dispose();
oSite.Dispose();
}
}
}
}
NOTE: After you open and use a SPSite and/or SPWeb objects you MUST be sure to dispose them for cleanup. If you do not then you could get nasty memory leaks in your runtime library.
Enjoy!!!