July 23, 2008

How to display all the web applications where a custom MembershipProvider is installed

The following piece code is a little console application which displays all the web applications where a custom MembershipProvider passed as argument is installed:

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint.Administration;
using System.Web.Configuration;
 
namespace DisplayWebAppsUsingACustomProvider
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                if (args == null  args.Length != 1)
                {
                    throw new ArgumentException("Invalid argument.");
                }
 
                string myMembershipProvider = args[0];
 
                SPFarm farm = SPFarm.Local;
                Console.WriteLine(string.Format("Connected to farm: {0}.", farm.DisplayName));
 
                SPWebService service = farm.Services.GetValue<SPWebService>("");
                Console.WriteLine("Services has been retrieved.");
 
                foreach (SPWebApplication webApp in service.WebApplications)
                {
                    Console.WriteLine(string.Format("Connected to Web Application: {0}.", webApp.DisplayName));
 
                    if (!webApp.IsAdministrationWebApplication)
                    {
                        foreach (SPUrlZone zone in webApp.IisSettings.Keys)
                        {
                            SPIisSettings setting = webApp.IisSettings[zone];
                            if (setting.AuthenticationMode == AuthenticationMode.Forms)
                            {
                                if (setting.MembershipProvider.ToLower() == myMembershipProvider.ToLower())
                                {
                                    Console.WriteLine(string.Format("MembershipProvider \"{0}\" found.", myMembershipProvider));
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("Message: {0} {1} Stack:{2}.", ex.Message, System.Environment.NewLine, ex.StackTrace));
            }
            Console.WriteLine("Press a touch to exit.");
            Console.ReadLine();
        }
    }
}

No comments: