SPFarm, SPServer, SPServiceInstance and SPWebApplication and SPSite

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

farmservices

Here are the steps:

  1. 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;

  2. Connect to or loop over the servers part of the farm.

    SPServer myServer = myFarm.Servers["springfield"];

  3. 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.

     
  4. listBox1.DisplayMember = "TypeName";
    foreach (SPServiceInstance servinst in myServer.ServiceInstances)
    {
        listBox1.Items.Add(servinst);
    }
     

  5. One of these services is the Windows SharePoint Services Web Application. Grab it and cast the Service property to the SPWebService:

  6. SPServiceInstance servinst = (SPServiceInstance)listBox1.SelectedItem;

    if (servinst.Service is SPWebService)
    {
         SPWebService serv = (SPWebService)servinst.Service;

     

  7. Next retrieve the IIS Web Applications under the control of this service

  8.     listBox2.DisplayMember = "DisplayName";
        foreach (SPWebApplication webapp in serv.WebApplications)
        {
            listBox2.Items.Add(webapp);
        }
    }
       

  9. And then you can work with your site collections:

  10. SPWebApplication webapp = (SPWebApplication)listBox2.SelectedItem;

    listBox3.Items.Clear();
    listBox3.DisplayMember = "Url";
    foreach (SPSite sitecol in webapp.Sites)
    {
        listBox3.Items.Add(sitecol);
    }