Friday, October 3, 2008

Reading ClientConfig values in Silverlight

This turns out to not be too difficult.  It's just a bit nonobvious since there are no configuration reading classes included in the Silverlight runtime as there are in the full CLR.  Since I have seen the question posted from time to time, I figured I would explain why you might need to do this and how it is done.

While writing our new Silverlight application, we ran into a problem with authentication.  I have a whole other blog post about that, but one of the issues that needed to be resolved was how to read the WCF service addresses from the client configuration file.  The solution to our authentication problem required that we instantiate our service clients with the constructor overload that accepts a ChannelBinding and an EndpointAddress.  Since we needed to provide the address as a string to the EndpointAddress constructor, we needed a way to read the values from the configuration file.

The approach requires just a few short lines of code.

private static EndpointAddress ReadAddress(string contract)
EndpointAddress result = null;

var streamInfo = Application.GetResourceStream(new Uri("ServiceReferences.ClientConfig", UriKind.Relative));
var config = XDocument.Load(streamInfo.Stream);
var endpoints = from endpoint in config.Descendants("endpoint")
where endpoint.Attribute("contract").Value == contract
select new { Address = endpoint.Attribute("address").Value };

foreach (var endpoint in endpoints)
result = new EndpointAddress(endpoint.Address);

if (null == result)
throw new InvalidOperationException(string.Format("Cannot create endpoint for contract {0}.", contract));

return result;

Obviously, you can change the file name and create your own settings files, and the LINQ query can be tailored to any XML schema you come up with.  This piece of code specifically extracts an endpoint address from the ServiceReferences.ClientConfig file.  We wrapped this method in a factory that is used to create all of our message level authenticated service clients.  We also cache the values so that we only read them from the file the first time.

1 comment:

  1. Just wanted to let you know that I found this very helpful. Thanks!