Reading Web Service Definition from Other Program’s app.config or web.config

The ConfigurationManager class allows you to open your own app.config (renamed to .exe.config) or web.config, but also the design-mode app.config of any other application by providing a ExeConfigurationFileMap parameter to the OpenMappedExeConfiguration method:

var config =
  ConfigurationManager.OpenMappedExeConfiguration(
    new ExeConfigurationFileMap { ExeConfigFilename = cfg },
    ConfigurationUserLevel.None);

You can then access the <host> configuration like this

ServiceModelSectionGroup serviceModel =
  ServiceModelSectionGroup.GetSectionGroup(config);
if (serviceModel != null
    && serviceModel.Services != null
    && serviceModel.Services.Services != null)
{
  foreach (ServiceElement service in serviceModel.Services.Services)
  {
    foreach (BaseAddressElement addr in service.Host.BaseAddresses)
      Console.WriteLine(addr.BaseAddress);
  }
}

This method works fine unless the services section has been extended by custom config sections such as a custom behavior

<extensions>
  <behaviorExtensions>
    <add name="myBehaviorExtension"
      type="My.BehaviorExtension, My.BehaviorExtension.Library" />
  </behaviorExtensions>
</extensions>

Such a custom extension without an accessible library implementing the type causes a ConfigurationErrorsException:

The type ‘x’ registered for extension ‘y’ could not be loaded

If this is the case, the only way I found was to load the .config file as an XmlDocument

XmlDocument xml = new XmlDocument();
xml.Load(cfg);

and process the results of the xml’s SelectNodes() method

foreach (XmlNode nd in xml.SelectNodes(
  "/configuration/system.serviceModel/" +
  "services/service/host/baseAddresses/add"))
{
  var url = nd.Attributes["baseAddress"];
  if (url != null)
    Console.WriteLine(url.Value);
}
Advertisements

One Response to Reading Web Service Definition from Other Program’s app.config or web.config

  1. […] extracts URLs of .asmx files and web service declarations from app.config. […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: