LINQ to XML in VB.NET and Using the Right Language for the Job

I'm almost always using C# in my .NET projects, unless I'm doing Office automation where the VB-way of dealing with optional parameters helps out making the code a bit cleaner.

The last week we've been upgrading ASMX-clients to become WCF-clients for a number of old .NET 1.1 and 2.0 projects, and we ended up with a bunch of app.config files with loads and loads of WCF client endpoint sections, each of them pointing at their own binding configuration. To manually clean this up would take hours and hours of tedious work which would probably result in more than a few errors.

So I thought maybe I could do search/replace with a regexp-capable editor... or try out XML Literals in VB.NET. I wanted to remove old behaviors, extensions and bindings, then add my own behaviors and extensions and finally change some attributes on each client endpoint. Doing this with XML Literals and XDocument/XElement in VB.NET was quite straight forward and didn't result in too many lines of code:

Imports System
Imports System.Xml.Linq
Imports System.IO
Imports System.Linq
    Sub FixupConfig(ByVal infile As String, ByVal outfile As String)
        Dim defaultBindingConfigurationXml = <binding name="defaultBindingConfiguration"

        Dim behaviorsXml = <behaviors>
                                   <behavior name="FacadeSoapEndpointBehavior">
                                       <SetMaxFaultSizeBehavior size="100000"/>

        Dim extensionsXml = <extensions>
                                    <add name="SetMaxFaultSizeBehavior" 
type="SomeType.SetMaxFaultSizeBehavior, SomeAssembly, Version=,
Culture=neutral, PublicKeyToken=null
"/> <add name="ClientExceptionHandlerBehavior"
type="SomeType.ClientExceptionHandler, SomeAssembly, Version=,
Culture=neutral, PublicKeyToken=null
"/> </behaviorExtensions> </extensions> Dim xdoc = XDocument.Load(infile) xdoc...<system.serviceModel>.<behaviors>.Remove() xdoc...<system.serviceModel>.<extensions>.Remove() xdoc...<system.serviceModel>.Single().AddFirst(extensionsXml) xdoc...<system.serviceModel>.Single().AddFirst(behaviorsXml) xdoc...<system.serviceModel>.<bindings>.<basicHttpBinding>.Descendants.Remove() xdoc...<system.serviceModel>.<bindings>.<basicHttpBinding>.Single().Add(defaultBindingConfigurationXml) Dim elems = xdoc...<client>.<endpoint> For Each element In elems element.@bindingConfiguration = "defaultBindingConfiguration" element.@behaviorConfiguration = "FacadeSoapEndpointBehavior" Next xdoc.Save(outfile) End Sub

I've heard people recommend to use VB.NET when dealing with XML and I agree - use the right language for the job. When doing this - remember to import System.Linq or you'll miss some vital extensions like the .Add() and .Single() methods ;)

No Comments