This week I am visiting Denmark again. Lovely place, a bit cold but knowing that next week I'll be in Cyprus and then a week of Barcelona I can take it. I am delivering my favorite course (the advanced SharePoint dev course) One of the students at WM-Data asked me about the steps to start with the server farm, loop over all of the servers, get all of the IIS Web applications running on that server and from there looping over all of the site collections and possible the individual sites. Here is a small app I have created as a demonstration
Here are the steps:
- Start by getting a reference to the SPFarm either the local or joined farm. You can even connect to a remote farm if you provide the connection string to the configuration database.
SPFarm myFarm = SPFarm.Local;
- Connect to or loop over the servers part of the farm.
SPServer myServer = myFarm.Servers["springfield"];
- Loop over all of the services running on that server represented in the object model as a SPServiceInstance type. The TypeName property is a good one to show since the DisplayName property is often an empty string.
listBox1.DisplayMember = "TypeName";
foreach (SPServiceInstance servinst in myServer.ServiceInstances)
- One of these services is the Windows SharePoint Services Web Application. Grab it and cast the Service property to the SPWebService:
SPServiceInstance servinst = (SPServiceInstance)listBox1.SelectedItem;
if (servinst.Service is SPWebService)
SPWebService serv = (SPWebService)servinst.Service;
- Next retrieve the IIS Web Applications under the control of this service
listBox2.DisplayMember = "DisplayName";
foreach (SPWebApplication webapp in serv.WebApplications)
- And then you can work with your site collections:
SPWebApplication webapp = (SPWebApplication)listBox2.SelectedItem;
listBox3.DisplayMember = "Url";
foreach (SPSite sitecol in webapp.Sites)