Search code examples
wcfwcf-binding

Create XML representation of WCF binding instance


I'm trying to write code to convert a WCF wsHttpBinding to customBinding, using the method described on WSHttpBinding.CreateBindingElements Method .

Binding wsHttpBinding = ...
BindingElementCollection beCollection = originalBinding.CreateBindingElements();
foreach (var element in beCollection)
{
    customBinding.Elements.Add(element);
}

Once I have generated the custom binding, I want to generate an XML representation for that new custom binding. (The same XML representation that's found in an application's .config file).

Is there a way to do that?

(I'm aware of the tool referenced in this answer: https://stackoverflow.com/a/4217892/5688, but I need something I can call within an application and without depending on a service in the cloud)


Solution

  • The class I was looking for was System.ServiceModel.Description.ServiceContractGenerator

    Exemple to generate a configuration for an instance of any kind of Binding:

    public static string SerializeBindingToXmlString(Binding binding)
    {
        var tempConfig = Path.GetTempFileName();
        var tempExe = tempConfig + ".exe";
        var tempExeConfig = tempConfig + ".exe.config";
        // [... create empty .exe and empty .exe.config...]
    
        var configuration = ConfigurationManager.OpenExeConfiguration(tempExe);
        var contractGenerator = new ServiceContractGenerator(configuration);
        string bindingSectionName;
        string configurationName;
        contractGenerator.GenerateBinding(binding, out bindingSectionName, out configurationName);
    
        BindingsSection bindingsSection = BindingsSection.GetSection(contractGenerator.Configuration);
    
        // this needs to be called in order for GetRawXml() to return the updated config
        // (otherwise it will return an empty string)
        contractGenerator.Configuration.Save(); 
    
        string xmlConfig = bindingsSection.SectionInformation.GetRawXml();
    
        // [... delete the temporary files ...]
        return xmlConfig;
    }
    

    This solution feels like a hack because of the need to generate empty temporary files, but it works.

    Now I'll have to look for a way to have a fully in-memory instance of a System.Configuration.Configuration (maybe by writing my own implementation)