Category Archives: Development

Launching ClickOnce Application with parameters from a shortcut

ClickOnce is a handy technology from Microsoft that makes it easy to deploy desktop Windows applications using the web browser. IE is naturally supported out of the box, Firefox and Chrome have add-ons and apps respectively to make ClickOnce work.

When installed, ClickOnce created shortcuts for the application under user’s Start Menu (Windows 7 and 10) in the folder whose name matches the name of the company specified in the manifest of the application. But the shortcuts to ClickOnce applications are not your typical *.lnk files, they are .appref-ms files. An appref-ms file is a text file saved in UTF-16 or “UCS2 Little Endian” format. Format is important getting it wrong will make the file unrecognizable to the system.

Here’s a typical text from the appref-ms file.

https://www.application.com/MyApplication.application#MyApplication.app, Culture=neutral, PublicKeyToken=f89fd69c4bd8bc85, processorArchitecture=x86

It consists of 4 parts separated by comas:

  1. Url#Name – I noticed that the URL is not important, but the bame is – it has to match the name of the application in the manifest
  2. Culture – in the format “Culture=”
  3. PublicKeyToken – in the format “PublicKeyToken=”
  4. Target CPU – in the format “processorArchitecture=”
  5. To pass parameters to the clickonce application you must invoke the appref.ms file either from the command line with parameters. I was hoping to create a real shortcut (lnk) file with the appref.ms file as a target along with arguments, but Windows does not make it easy. It’s a lot easier to manage shortcuts to normal executable files, so that’s the approach I would recommend in this solution.

    You can add a second windows executable file to your solution. It’s job would be to generate a temporary appref.ms file on the fly and launch it with parameters using .NET’s Process.Start command. When your real app starts, make sure to copy this helper executable to user’s %appdata%\YourAppName location or ClickOnce’s ApplicationDeployment.CurrentDeployment.DataDirectory (will only be available once properly deployed). Then you can create a shortcut to the executable anywhere you like and even add command line arguments to it. Your executable then will generate the appref.ms file on the fly somewhere in temp directory, and launch it along with the arguments you specified. You can get the parts necessary to generate this file from the ApplocationIdentity object: http://msdn.microsoft.com/en-us/library/system.applicationidentity.fullname%28v=vs.110%29.aspx

    Hope this works for you.

    PS. Don’t forget to delete the dummy appref.ms file you generate after your app launches.

    Advertisements

Microsoft mechanism to load WPF resources is broken. (looking for a better title)

I’ve been using WPF along with .NET and have been a staunch supported of the technology for years now. The pattern of separating presentation from logic gained a lot of traction. Technologies such as iOS’s cocoa touch, JavaFX and others follow same model. Even HTML5 forced all the pure presentation/layout markup out from HTML and into CSS. So the idea is sound. But what about execution.

WPF implements this pattern using XAML. XAML markup is used to design the visual this xaml is stored in the xaml file, whose name usually matches the name of the class. For example, MyWindow.xaml. During compilation, an auto-generated file marries the code that defines the visual (MyWindow.xaml.cs) and the xaml file itself (MyWindow.xaml.cs). The autogenerate file would be named MyWindow.g.i.cs and it would contain the implementation of the InitializeComponent() method that’s referenced in the main MyWindow.xaml.cs class. The contents of the method looks something like this:

[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
public void InitializeComponent() {
	if (_contentLoaded) {
		return;
	}
	_contentLoaded = true;
	System.Uri resourceLocater = new System.Uri("/MyLibrary;component/mainwindow.xaml", System.UriKind.Relative);
	
	#line 1 "..\..\MainWindow.xaml"
	System.Windows.Application.LoadComponent(this, resourceLocater);
	
	#line default
	#line hidden
}

So far so good right. OK, let’s talk about some of the advanced uses of .Net. Specifically support for having multiple versions of same assembly (dll) to be loaded in a single AppDomain. Such use case comes handy in a framework use case. A framework supports multiple plug-in modules, each can be developed by other developers who may rely on different versions of common libraries. I am not talking about things like log4net, I am talking about shared assemblies that define common logic and can be reused by each module. If 2 modules are loaded into a single app-domain and both depend on their ‘private’ version of the common assembly, a good framework should not force both modules to share latest version of the library, because

  • ‘latest’ does not mean backwards-compatible
  • ‘latest’ may have bugs that ‘earlier’ version did not
  • …I can go on for a while on this one. It’s 2014, dll hell is well known to software developers of the 20th century.

Now, let’s say that 2 different versions of the shared library called MyLibrary are loaded and one version is used by Module1 and another version is used by Module2. During compilation, assembly name along with the version are recorded in modules’ manifests so that when .NET encounters request to execute code defined in MyLibrary the source module will tell .Net which version of MyLibrary contains the code it wants executed. This is a basic building block of .NET and a very attractive feature.

Now, what about WPF? Well that’s not that clear is it? Look at Line #8 above: System.Uri resourceLocater = new System.Uri(“/MyLibrary;component/mainwindow.xaml”, System.UriKind.Relative). It defines what it calls a resourcelocator which the system will use to find the xaml resouce in an assembly called MyLibrary. I don’t know how WPF resolves the assembly, but if I were to write the logic for resolution, I would not have enough information to find a proper assembly MyLibrary, because I don’t know which version to load. I would have to guess. And as we know in any science guessing is bad. Computer Science is an exact… well… science. Guessing, hoping, holding fingers crossed or other techniques that do not produce determinate result will break at the worst possible moment! I can see how developers armed with inaccurate knowledge or with little experience make mistakes like this, but when Microsoft’s tools generated code that’s faulty, and make it impossible to intercept and fix, there is no other way to call it – they fucked up! How can they expect developers to trust their tooling if they, themselves, auto-generate code that sometimes breaks.

This breaks in a most bizarre way, too. MyLibrary version 2 was loading the MainWindow class, which then was running the InitializeComponent() method above, encountered the LoadComponent call, which asked to load the resource from the MyLibrary assembly without a version, and the code picked the wrong version of the MyLibrary assembly, which did not have the MyWindow class, nor the resource. What a way to blow up!

Such nonsense was reported to them too! This connect ticket marked as “Wont’t Fix” describes the problem: https://connect.microsoft.com/VisualStudio/feedback/details/668914/xaml-generated-code-uses-resource-uri-without-assembly-strong-name. StackOverflow also has references to this problem: http://stackoverflow.com/questions/1453107/how-to-force-wpf-to-use-resource-uris-that-use-assembly-strong-name-argh/6341678#6341678. Luckily one of the suggestions led me to the best solution.

The Fix


We were lucky to have our builds automated via scripts which rely on MSBuild to build the solutions. All I needed to do is to modify the script and pass the /p:AssemblyInfo=$version parameter to MSBuild. (http://stackoverflow.com/a/26689750/195275). This would tell the build system to add assembly version to the Resource reference in line 8. It now looks like the code below. Problem solved, but could have been avoided on the first place!

Shame on you, Microsoft!

[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
public void InitializeComponent() {
	if (_contentLoaded) {
		return;
	}
	_contentLoaded = true;
	System.Uri resourceLocater = new System.Uri("/MyLibrary;V1.0.23;component/mainwindow.xaml", System.UriKind.Relative);
	
	#line 1 "..\..\MainWindow.xaml"
	System.Windows.Application.LoadComponent(this, resourceLocater);
	
	#line default
	#line hidden
}

Am I smarter than the fifth grader?

I thought I was, until my 10 year-old brought home a math homework from her school asking her to solve a few problems that look like this:

Replace letters with digits from this list [1, 2, 3, 4, 5, 7, 8, 9]
All letters to digit mapping is unique

   CAN
x  SAY
======
 BRAND

I thought such problem would have a quick-and-easy solution, like any others in a 5th grade math, but I was stumped. I tried several tricks to see if there was a shortcut to solving these, but found nothing. The only way to solve a problem like this was to iteratively try out various number combinations to see if the result would match the constraints of the problem.

Constraints

In a problem above the constraints are as follows:

  1. 2nd digit in the 2nd number must match 2nd digit in the 1st number
  2. 2nd and 3rd digit in the 1st number must match 3rd digit and 4th digits result
  3. Result must have 5 digits
  4. None of the digits of the result except for the 3rd and 4th can be present in the first two numbers

Solving such problem.

I learned that the type of these problems are called cryptarithms or verbal arithmetic. There’s a wikipedia page dedicated to these problems as well as a laundry list of sites hosting examples and explanations to these. There is no simple solution to such problem. The solution to them is defined as having NP-Complete in its difficulty, which according to Wikipedia is

In computational complexity theory, a decision problem is NP-complete when it is both in NP and NP-hard. The set of NP-complete problems is often denoted by NP-C or NPC. The abbreviation NP refers to “nondeterministic polynomial time”.

Although any given solution to an NP-complete problem can be verified quickly (in polynomial time), there is no known efficient way to locate a solution in the first place; indeed, the most notable characteristic of NP-complete problems is that no fast solution to them is known.

My Solution

The only way to solve it was to write a program, which I did below. I figured that I have to start with a basic mapping of letters to digits and “increment” the mapping by “1” at every iteration. The difficult part was to implement the “increment” because no two letters can be mapped to the single digit, I could not completely mimic the way we increment regular numbers in base 10. Plus the universe of digits can also be constrained if the problem creator chooses to do so.

The code is written in C#, and is lazy-coded, where the inputs are hard-coded in the main method, because I own the code and can easily change the definitions. It supports multiplication and addition. It managed to solve all the problems that I found online, so I am fairly confident that it works.

Perhaps I am still smarter than the 5th grader, even if slightly.

namespace WordMultiplication
{
    class Program
    {
        static void Main(string[] args)
        {
            var digits = new int[] { 1, 2, 3, 4, 5,  7, 8, 9 }.OrderBy(n => n).ToArray();
            var word1 = "CAN";
            var word2 = "SAY";
            var result = "BRAND";

            var orderedInputLetters = word1.Union(word2).Distinct().ToArray();
            if (orderedInputLetters.Length > digits.Length)
            {
                Console.WriteLine("More letters than digits!");
                return;
            }

            var numbersToLetterMap = new SortedDictionary<int, char?>();
            var lettersToNumbersMap = new Dictionary<char, int>();

            InitialSetup(orderedInputLetters, digits, numbersToLetterMap, lettersToNumbersMap);

            bool found;
            bool couldIncrement;
            do
            {
                couldIncrement = false;
                int number1 = GetNumberForWord(word1, lettersToNumbersMap);
                int number2 = GetNumberForWord(word2, lettersToNumbersMap);

                var mathResult = number1 * number2;

                found = number1.ToString().Length == word1.Length &&
                        number2.ToString().Length == word2.Length &&
                        Verify(mathResult, result, word1, word2, new Dictionary<char, int>(lettersToNumbersMap), digits);
                if (found)
                    Console.WriteLine("{0} x {1} = {2}", number1, number2, mathResult);
                else
                    couldIncrement = TryIncrement(orderedInputLetters.Length - 1, orderedInputLetters, digits, numbersToLetterMap, lettersToNumbersMap);


            } while (!found && couldIncrement);

            if (!found)
                Console.WriteLine("Result not found");
        }

        private static bool TryIncrement(int index, char[] inputLetters, int[] digits,
            IDictionary<int, char?> numbersToLetterMap, IDictionary<char, int> lettersToNumbersMap)
        {
            if (index == -1)
                return false;

            var currLetter = inputLetters[index];
            var currDigit = lettersToNumbersMap[currLetter];

            int nextDigit;
            //If we reached the end
            if (!numbersToLetterMap.Any(kvp => kvp.Key > currDigit && !kvp.Value.HasValue))
            {
                //put current letter aside
                numbersToLetterMap[currDigit] = null;
                lettersToNumbersMap[currLetter] = -1;

                //Try to increment a digit of higher significance
                if (TryIncrement(index - 1, inputLetters, digits, numbersToLetterMap, lettersToNumbersMap))
                    //If succeeded, find the first available empty spot for the current letter
                    nextDigit = numbersToLetterMap.First(kvp => !kvp.Value.HasValue).Key;
                else
                    return false;
            }
            else
            {
                numbersToLetterMap[currDigit] = null;
                nextDigit = numbersToLetterMap.First(kvp => kvp.Key > currDigit && !kvp.Value.HasValue).Key;
            }

            numbersToLetterMap[nextDigit] = currLetter;
            lettersToNumbersMap[currLetter] = nextDigit;

            return true;
        }


        private static void InitialSetup(char[] inputLetters, int[] digits, IDictionary<int, char?> numbersToLetterMap, IDictionary<char, int> lettersToNumbersMap)
        {
            foreach (var digit in digits)
                numbersToLetterMap[digit] = null;

            foreach (var c in inputLetters)
                lettersToNumbersMap[c] = -1;

            //Place letters in the beginning of the digit line
            for (int i = 0; i < inputLetters.Length; i++)
            {
                lettersToNumbersMap[inputLetters[i]] = digits[i];
                numbersToLetterMap[digits[i]] = inputLetters[i];
            }
        }

        private static bool Verify(int mathResult, string result, string word1, string word2, IDictionary<char, int> allletters, int[] digits)
        {
            if (mathResult.ToString().Length != result.Length)
                return false;

            for (int i = 0; i < result.Length; i++)
            {
                var resultChar = result[i];
                var digitForChar = (mathResult / (int)Math.Pow(10, result.Length - i - 1) % 10);
                
                //Can result be even used?
                if (Array.IndexOf(digits, digitForChar) == -1)
                    return false;

                if (allletters.Keys.Contains(resultChar))
                {
                    if (allletters[resultChar] != digitForChar)
                        return false;
                }
                else if (allletters.Values.Contains(digitForChar))
                {
                    if (allletters.First(kvp => kvp.Value == digitForChar).Key != resultChar)
                        return false;
                }
                else
                {
                    allletters[resultChar] = digitForChar;
                }
            }

            return true;

        }

        private static int GetNumberForWord(string word, IDictionary<char, int> allletters)
        {
            var number = 0;
            for (int i = 0; i < word.Length; i++)
            {
                number += allletters[word[i]] * (int)Math.Pow(10, (word.Length) - i - 1);
            }

            return number;
        }
    }
}

WPF: The real difference between ContentControl and ContentPresenter

Most of the resources on the web specify that ContentPresenter supports a special property called ContentSource, with a default value of “Content“, which makes it easy for it to automatically set the values of these properties used to render content:

    • Content
    • ContentTemplate
    • ContentTemplateSelector
    • ContentStringFormat (3.5 sp1 +)

Basically, the property specifies the string prefix used to bind to properties of the parent. If you change the value of the ContentSource property to something else, like “Header“, the ContentPresenter’s properties would auto-bind to bind to these properties of the control you are templating using ControlTemplate:

    • Header
    • HeaderTemplate
    • HeaderTemplateSelector
    • HeaderStringFormat (3.5 sp1 +)

The web is siltent, however, about one major difference in behavior that’s important to note. 

ContentPresenter’s DataContext is automatically set to the value of its Content property, while ContentControl’s DataContext is not.

Why is it important?  In one word – bindings.  Bindings are resolved relatived to the value of the  DataContext property.  If you declare a binding on the ContentPresenter, the moment its content is set, the binding would be re-evaluated.  For example, let’s say you are building a dual-content control like this:

<UserControl x:Class="ContentPresenterVsContentControl.DualContentControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <ContentPresenter Grid.Row="0" 
                          Content="{Binding ContentOne}" 
                          ContentTemplate="{Binding ContentOneTemplate}" 
                          ContentTemplateSelector="{Binding ContentOneTemplateSelector}"/>
        <ContentPresenter Grid.Row="1" 
                          Content="{Binding ContentTwo}" 
                          ContentTemplate="{Binding ContentTwoTemplate}" 
                          ContentTemplateSelector="{Binding ContentTwoTemplateSelector}"/>
    </Grid>
</UserControl>

using System.Windows;
using System.Windows.Controls;

namespace ContentPresenterVsContentControl
{
    /// <summary>
    /// Interaction logic for DualContentControl.xaml
    /// </summary>
    public partial class DualContentControl : UserControl
    {
        public static readonly DependencyProperty ContentOneProperty = DependencyProperty.Register("ContentOne", typeof(object), typeof(DualContentControl));
        public static readonly DependencyProperty ContentOneTemplateProperty = DependencyProperty.Register("ContentOneTemplate", typeof(DataTemplate), typeof(DualContentControl));
        public static readonly DependencyProperty ContentOneTemplateSelectorProperty = DependencyProperty.Register("ContentOneTemplateSelector", typeof(DataTemplateSelector), typeof(DualContentControl));

        public static readonly DependencyProperty ContentTwoProperty = DependencyProperty.Register("ContentTwo", typeof(object), typeof(DualContentControl));
        public static readonly DependencyProperty ContentTwoTemplateProperty = DependencyProperty.Register("ContentTwoTemplate", typeof(DataTemplate), typeof(DualContentControl));
        public static readonly DependencyProperty ContentTwoTemplateSelectorProperty = DependencyProperty.Register("ContentTwoTemplateSelector", typeof(DataTemplateSelector), typeof(DualContentControl));


        public DualContentControl()
        {
            InitializeComponent();
            DataContext = this;
        }

        public object ContentOne
        {
            get { return GetValue(ContentOneProperty); }
            set { SetValue(ContentOneProperty, value); }
        }

        public DataTemplate ContentOneTemplate
        {
            get { return (DataTemplate) GetValue(ContentOneTemplateProperty); }
            set { SetValue(ContentOneTemplateProperty, value); }
        }


        public DataTemplateSelector ContentOneTemplateSelector
        {
            get { return (DataTemplateSelector) GetValue(ContentOneTemplateSelectorProperty); }
            set { SetValue(ContentOneTemplateSelectorProperty, value); }
        }

        public object ContentTwo
        {
            get { return GetValue(ContentTwoProperty); }
            set { SetValue(ContentTwoProperty, value); }
        }

        public DataTemplate ContentTwoTemplate
        {
            get { return (DataTemplate)GetValue(ContentTwoTemplateProperty); }
            set { SetValue(ContentTwoTemplateProperty, value); }
        }


        public DataTemplateSelector ContentTwoTemplateSelector
        {
            get { return (DataTemplateSelector)GetValue(ContentTwoTemplateSelectorProperty); }
            set { SetValue(ContentTwoTemplateSelectorProperty, value); }
        }

    }
}

Now, let’s use it in the project:

<Window x:Class="ContentPresenterVsContentControl.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:ContentPresenterVsContentControl"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <local:DualContentControl 
            ContentOne="Hello"
            ContentTwo="World">
            
            <local:DualContentControl.ContentOneTemplate>
                <DataTemplate>
                   <Label Background="Orange" Content="{Binding}" 
                          HorizontalContentAlignment="Center" VerticalContentAlignment="Center"/>
                </DataTemplate>
            </local:DualContentControl.ContentOneTemplate>

            <local:DualContentControl.ContentTwoTemplate>
                <DataTemplate>
                    <Label Background="Green" Content="{Binding}" 
                           HorizontalContentAlignment="Center" VerticalContentAlignment="Center"/>
                </DataTemplate>
            </local:DualContentControl.ContentTwoTemplate>
        </local:DualContentControl>
    </Grid>
</Window>

You would expect something like this,image below, right?

DualContentControlWindow

Well, if you used ContentPresenters in your UserControl, you would see this, instead:

DualContentControlWindowBad

You would also see strange binding errors in the console

System.Windows.Data Error: 40 : BindingExpression path error: 'ContentTwoTemplate' 
property not found on 'object' ''String' (HashCode=-1506748533)'. 
BindingExpression:Path=ContentTwoTemplate; DataItem='String' (HashCode=-1506748533); 
target element is 'ContentPresenter' (Name=''); target property is 'ContentTemplate' (type 'DataTemplate')

System.Windows.Data Error: 40 : BindingExpression path error: 'ContentTwoTemplateSelector' 
property not found on 'object' ''String' (HashCode=-1506748533)'. BindingExpression:Path=ContentTwoTemplateSelector; DataItem='String' (HashCode=-1506748533); 
target element is 'ContentPresenter' (Name=''); target property is 'ContentTemplateSelector' (type 'DataTemplateSelector')

System.Windows.Data Error: 40 : BindingExpression path error: 'ContentOneTemplate' 
property not found on 'object' ''String' (HashCode=-694847)'. 
BindingExpression:Path=ContentOneTemplate; DataItem='String' (HashCode=-694847); 
target element is 'ContentPresenter' (Name=''); target property is 'ContentTemplate' (type 'DataTemplate')

System.Windows.Data Error: 40 : BindingExpression path error: 'ContentOneTemplateSelector' 
property not found on 'object' ''String' (HashCode=-694847)'. BindingExpression:Path=ContentOneTemplateSelector; DataItem='String' (HashCode=-694847); 
target element is 'ContentPresenter' (Name=''); target property is 'ContentTemplateSelector' (type 'DataTemplateSelector')

Notice that for some reason the ContentOneTemplate, ContentOneTemplateSelector, ContentTwoTemplate and ContentTwoTemplateSelector are bound to an object of type ‘String’. Why? Because the moment you sent the ContentProperty of the ContentPresenter its DataContext was switch to match the value of the Content property. Since the Content of the both ContentPresenters are string, “Hello” and “World” all other bindings on the ContentPresenter are now resolved against these string values!

If you replace ContentPresenters with ContentControls, the system works as expected.

<UserControl x:Class="ContentPresenterVsContentControl.DualContentControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <ContentControl Grid.Row="0" 
                          Content="{Binding ContentOne}" 
                          ContentTemplate="{Binding ContentOneTemplate}" 
                          ContentTemplateSelector="{Binding ContentOneTemplateSelector}"/>
        <ContentControl Grid.Row="1" 
                          Content="{Binding ContentTwo}" 
                          ContentTemplate="{Binding ContentTwoTemplate}" 
                          ContentTemplateSelector="{Binding ContentTwoTemplateSelector}"/>
    </Grid>
</UserControl>

How to use .NET WebClient synchronously and still receive progress updates

Recently, I had to implement our custom package deployment mechanism for our UI framework where packages are hosted on a web-accessible URI. During the download process, the UI should display a progress bar which updates the user on the progress the download. After download is complete, the client performs a few more steps including

  • checking file integrity against its md5 hash
  • expanding the compressed file into the destination
  • cleaning up

The implementation uses TPL; for each package that user chose to upgrade, a task is created which performs the steps above. During this process, the UI displays a progress of each task.

The download portion of the process is implemented using WebClient.DownloadFile method. It’s short and sweet, hiding most of the complexity of opening a connection, getting a response stream and reading it one chunk at a time. But its simplicity comes a shortcoming: during download the thread doing the downloading is blocked an no progress is reported, so downloading a large file would cause the user to think that the system froze, because even though the wait spinner is spinning, the progress bar is stuck. What I want is to get updates on the progress of my download while waiting for download to complete.

The WebClient class has convenient DownloadProgressChanged event which seems like a perfect candidate to help me here, so I attached a delegate to it, but it was never called. Upon careful reading of the documentation, I learned that I must use the asynchronous version of the DownloadFile mehtod, DownloadFileAsync to receive any progress updates.

While I could switch my code around to accommodate new asynchronous calling pattern, I did not want to drastically redesign my existing code. It was already relying on the TPL for asynchrony, adding another asynchronous mechanism would add more complexity to my code. So I decided to try to keep the method that deals with WebClient synchronous, but still receive updates. To do this, I would need to call the DownloadFileAsync method, but then block my thread until download completes or fails. Luckily, WebClient has the DownloadFileCompleted event which would come in handy here. Since I would block my thread after calling the DownloadFileAsync method, when the DownloadFileCompleted fires, I would unblock my calling thread. Here’s the code that implements this solution


public void DownloadFile(Uri uri, string desintaion)
{
  using(var wc = new WebClient())
  {
    wc.DownloadProgressChanged += HandleDownloadProgress;
    wc.DownloadFileCOmpleted += HandleDownloadComplete;

    var syncObj = new Object();
    lock(syncObject)
    {
       wc.DownloadFileAsync(sourceUri, destination, syncObject);
       //This would block the thread until download completes
       Monitor.Wait(syncObject);
    }
  }
 
  //Do more stuff after download was complete
}

public void HandleDownloadComplete(object sender, AsyncCompletedEventArgs args)
{
   lock(e.UserState)
   {  
      //releases blocked thread
      Monitor.Pulse(e.UserState);
   }
}


public void HandleDownloadProgress(object sender, DownloadProgressChangedEventArgs args)
{
  //Process progress updates here
}

At the end, I still use WebClient synchronously without losing the benefits that come with its asynchronous usage.

Happy Downloading!

Powershell -match operator

I think Powershell’s -match operator deserves its own blog post because it does so much. I’ve been automating our build process using Powershell and I gained a lot of respect for this operator. The examples below, would usually refer to the SVN url parsing.

Matching

Firstly, it returns true ($true in Powershell) if the original string matches the regex expression you passed into it. For example,

$string = &amp;quot;Hello&amp;quot;
$string -match &amp;quot;Hello&amp;quot; #return true

$string -cmatch &amp;quot;hello&amp;quot; #return false, cmatch performs case-sensitive match

$string -cmatch &amp;quot;[H|h]ello&amp;quot; #return true  

Group Matching

In addition to regular matching the -match operator will populate a special $matches variable. For example

$string = &amp;quot;Hello World&amp;quot;
$string -match &amp;quot;Hello&amp;quot;

$matches[0] #prints &amp;quot;Hello&amp;quot;

$string = &amp;quot;Hello World&amp;quot;
$string -match &amp;quot;(?'first'Hello)&amp;quot;

Name    Value                                                                                                 
----    -----                                                                                                 
first   Hello                                                                                                 
0       Hello 

Group Matching and Replacing

If you are crafty enough, you can come up with a match and replace strategy for the strings you are working with. For example, if you have to figure out the full path of the svn path if you know the name of the tag, given the current branch path, you’ll do the following:


$url = &amp;quot;http://subversion.url.com/project/branches/VERSION-1.0/path/to/code&amp;quot;
$search = &amp;quot;(.*)(?'branch'branches/[^/]*)(.*)&amp;quot; #Generates 3 groups (1,2, and branch)

$url -match $search
True

$matches

Name     Value                                                                                                 
----     -----                                                                                                 
branch   branches/VERSION-1.0                                                                                  
2        /path/to/code                                                                                         
1        http://subversion.url.com/project/                                                                    
0        http://subversion.url.com/project/branches/VERSION-1.0/path/to/code           

#use the replace method of the Match object to replace branche path with tag path:
$newUrl = $matches[0].Replace($matches['branch'], 'tags/TAG-123') #replaces branch path with new tag path

$newUrl
http://subversion.url.com/project/tags/TAG-123/path/to/code

Automate Visual Studio project management from Package Manager Console

Visual Studio 2012 and above comes with the Package Manager Console, PowerShell-based tool used to automate NuGet package management from the command line.  But you can use it to access and change solutions and projects loaded into your Visual Studio using the DTE API, same interface Visual Studio exposes to its Addins.

In this post, I will demonstrate how you can replace all references to binaries (dll or exe files) with references to projects loaded into your solution. Such operation is necessary when you need to debug the code inside the dependencies. This use case is a frequent occurrence in development shops that split their code base into core, more technie, low-level functionality and higher level business-level code. The lower-level code is encapsulated into one or more dlls and the higher-level developers reference those dlls when developing their client-facing solutions.

Usually, the lower-level code has been well designed, developed and properly unit tested to make them work as expected. But sometimes something is not right, and it’s up to the app developer, who is on the deadline to figure out why. So the app developer would check out the code for the lower-level API and would load the lower-level API  solution into their existing higher-level app solution. You can do this by

  1. right-clicking on the existing loaded solution
  2. picking Add -> Existing Project,
  3. changing the dropdown in the file picker to Solution Files (*.sln)
  4. picking the dependency solution in the dialog

The next step, would be for developers to manually replace references in your higher-level projects, removing references to the binary dll or exe files and pointing them to their equivalent projects that are now part of your solution.  This operation is tedious and error prone and is a perfect candidate for Powershell automation.   Let’s get started.

Before we begin, however, lets make it easier to separate the two sets of projects into the lower-level projects and the higher level projects.  The best way to segregate inside a single solution is to use solution folders.  So let’s create a folder called “Dependencies” and drag all the lower-level API projects under it.  You can create a solution folder by right-clicking on your solution and picking Add -> New Solution Folder.  We are ready now!

Switch to or open the Package Manager Console.  In VS2012  you can open it from TOOLS -> NuGet Package Manger -> Package Manager Console.  You should now be in the command prompt.  Here’s a script to perform such replacements.

function Update-References() 
{
	#find the solution folder called &amp;quot;Dependencies&amp;quot; where the dependency projects live
	$depFolder = $dte.Solution.Projects | where { $_.Kind -eq &amp;quot;{66A26720-8FB5-11D2-AA7E-00C04F688DDE}&amp;quot; -and $_.Name -eq 'Dependencies' }
	if(-not $depFolder)
	{
		Write-Error &amp;quot;Did not find a Dependencies folder in your solution.  It must be a top-level folder&amp;quot;;
		return -1
	}

	#Load a list of all the dependency projects into a hashtable
	$depProjects = @{}
	$depFolder.ProjectItems | % { $_.Object }  | % { $depProjects.add($_.Name, $_) }

	#load a list of all high-level projects (my projects)
	$myProjects = $dte.Solution.Projects | where { $_.Kind -eq '{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}' }

	#iterate through references in my projects and remember those that match the dependency projects.  Once matched, remove the old reference
	$projectToRefName = @{}
	foreach ($project in $myProjects.Object) 
	{ 	
		$lst = new-object system.collections.arraylist
		$projectToRefName.Add($project, $lst)
		foreach($reference in $project.References  | where { $depProjects.Contains($_.Identity) } )	 
		{ 
			$lst.add($reference.Identity)
			$reference.Remove() 
		}
	}

	#replace add a project reference for all the binary references we removed
	foreach ($project in $myProjects.Object) 
	{ 	
		$lst = $projectToRefName[$project]
        $depProjects.Values | where { $lst.Contains($_.Name) }  | % { $project.References.AddProject($_) } 
	}
}

Export-ModuleMember Update-References 

You can save this script into a script module file (*.psm1) somewhere and then use Import-Module command to load it. The Import-Module command takes the full path to the psm1 file like this:

Import-Module C:\MyPowershellModules\UpdateReferences.psm1

#if you need to make a change to the file, you will need to remove module first, because importing it again
Remove-Module UpdateReferences