Archive for the ‘Code’ Category

MSBuild XslTransformation Xslt Task example

Goal: Change the connection string of my application while running CodedUI tests. So my dev database is left alone.

Here I’ll post a simple “Hello World” setup to alter a xml to output something else. The xml and xslt example has been taken from w3schools.

When you download this file. It will contain a cmd. It loads up environment variables for msbuild and executes the build.proj.

The build.proj looks like this :

<Project DefaultTargets="Build" xmlns="">

<!-- Xml & Xslt Examples have been taken from -->

<Target Name="Build">
<XslTransformation XslInputPath="transform.xslt" XmlInputPaths="source.xml" OutputPaths="out.html" />


The output is a html page, just as the w3schools demo.

Hope this is a good starting example for your needs.


Xml literals escaping

I am somewhat bias towards C#, but one can admire the xml literals in

This is a language feature where you can just add xml to

Dim someXml As XElement = <foo>bla<bar active=”false”/></foo>

But how do you add characters that have some a meaning in xml, like “&” or “<“. Turns out you have two options:

Look up how you should escape it (& => &amp; ) but the editor (vs2013) will show wavy underlines underneath the literal. It will compile do and work as expected.

Embed a literal string

Dim someXml As XElement = <foo>Ampersand <%= “&” %><bar active=”false”/></foo>

this uses a method to embed expressions in xml literals.

First Pull-request created.

Well, it had to happen some day.

I’ve found an issue in a project we are using @ work. I’ve created a fix and I want to share it!.

So this project is hosted on github, and it is indeed simple to add fixes.

Just follow these steps :

  1. Fork the project
  2. Create a feature / fix branch
  3. Apply fix.
  4. Push to github.
  5. View this branch on github
  6. Push the “Create Pull Request” button

It will then show you if it can be merged at all. Add some information and you are done!

better details

The fix.

I’ve created a rather simple fix. We are using the “Fluent.Ribbon” for a modern look and feel. But some of our controls are still winforms. There is nothing wrong with winforms, but a mixture of wpf and winforms is not always ideal.

Anyway, we have a combobox in our ribbon and when a winforms control has focus and you try to open this combobox in your ribbon, it acts up.  repro : 


We have found this message in the debug window:

System.Windows.Data Error: 8 : Cannot save value from target back to source. BindingExpression:Path=IsDropDownOpen; DataItem=’ComboBox’ (Name=’StyleCbx’); target element is ‘ToggleButton’ (Name=’ToggleButton’); target property is ‘IsChecked’ (type ‘Nullable`1′) NullReferenceException:’System.NullReferenceException: Object reference not set to an instance of an object.
at Fluent.ComboBox.OnDropDownOpened(EventArgs e)
at System.Windows.Controls.ComboBox.OnIsDropDownOpenChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
at System.Windows.DependencyObject.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
at System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
at System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args)
at System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType)
at System.Windows.DependencyObject.SetValueCommon(DependencyProperty dp, Object value, PropertyMetadata metadata, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType, Boolean isInternal)
at System.Windows.DependencyObject.SetValue(DependencyProperty dp, Object value)
at MS.Internal.Data.PropertyPathWorker.SetValue(Object item, Object value)
at MS.Internal.Data.ClrBindingWorker.UpdateValue(Object value)
at System.Windows.Data.BindingExpression.UpdateSource(Object value)’

Turns out that the fix was rather simple. The combobox of fluent expected the Keyboard.FocusedElement, to always be non-null.

Well this is not the case when dealing with a mixed technology window. So the fix was created and a pull request has been offered.



String equals based on Regex C#

I need to compare strings based on what is matched by a regex. So I decided to create a regex to pick the parts of a string that I felt was necessary for consideration for equals. When using a regex and leaving parts of the string outside use “non capturing groups”.   Like “(\d+)(?:st|nd|rd|th)?” with will match a number and optional some postfix like “nd” as in 2nd.


public static class StringEqualsRegex
    /// <summary>
    /// Equals the strings by regex.
    /// </summary>
    /// <param name="s1">The first string.</param>
    /// <param name="s2">The second string.</param>
    /// <param name="regex">The regex.</param>
    /// <returns><c>true</c> if the captured strings of s1 and s2 match, <c>false</c> otherwise.</returns>
    public static bool EqualsByRegex(this string s1, string s2, Regex regex)
        /*Extension Method*/
        return EqualStringByRegex(s1, s2, regex);

    /// <summary>
    /// Equals the strings by regex.
    /// </summary>
    /// <param name="s1">The first string.</param>
    /// <param name="s2">The second string.</param>
    /// <param name="regex">The regex.</param>
    /// <returns><c>true</c> if the captured strings of s1 and s2 match, <c>false</c> otherwise.</returns>
    public static bool EqualStringByRegex(string s1, string s2, Regex regex)

        string capturedS1 = GetCapturedString(s1, regex);
        string capturedS2 = GetCapturedString(s2, regex);

        return (capturedS1 != null && capturedS2 != null) && 

    private static string GetCapturedString(string s, Regex regex)
        dynamic match = regex.Match(s);

        if ((match.Success))
            var sb = new StringBuilder();
            for (var i = 1; i <= match.Groups.Count; i++)
                foreach (Capture capture in match.Groups[i].Captures)
            return sb.ToString();

        return null;



[wpdm_file id=1]


Sql Server XML Cheetsheet

Cheet sheet XML Features SQL Server

Pre-requirement: Knowledge of XPath

All the samples are based on this XML:

	<ListOwner>John Smith</ListOwner>
		<title published="1885">The Adventures of Huckleberry Finn</title>
		<author realName="Samuel Langhorne Clemens">Mark Twain</author>
		<title published="1894">Tom Sawyer Abroad</title>
		<author realName="Samuel Langhorne Clemens">Mark Twain</author>

Extract Values
select @xml.value(‘( /MyBooks/ListOwner )[1]’, ‘varchar(20)’);

Possible error:

error fix
‘value()’ requires a singleton (or empty sequence), found operand of type place the XPATH query between ‘()[1]’

Check if exists

select @xml.exist(‘ //Book[author/@realName=”Samuel Langhorne Clemens”] ‘)
select @xml.exist(‘ //Book[contains((author/@realName)[1],”Langhorne”)] ‘)

Extract Node

SELECT @xml.query(‘/MyBooks/Book’) –Results all book nodes.SELECT @xml.query(‘/MyBooks/Book[title=”The Adventures of Huckleberry Finn”]’)SELECT @xml.query(‘/MyBooks/Book[title/@published<1890]’)

Select nodes

This will allow you to run SQL queries on XML.

select t.c.value(‘(title)[1]’,’varchar(20)’) from @xml.nodes(‘ //Book ‘) as t(c)

Modify Xml


When there are namespaces in you XML you will have to do additional work.