Get your facts right.

I just read this article: http://www.simple-talk.com/dotnet/.net-framework/10-reasons-why-visual-basic-is-better-than-c/ . And I’m pissed. Why? Allow me to elaborate

First of all, because on the top right there is “a service from redgate”. You’d expect to get their facts right.

And that’s the main issue with this article. There will always be fights among developers about which language is better, VB.NET or C#. I don’t care. Use what works best for you. And I’m always interested in a well argumented comparison between the two. (and I’m not going to show my preference here, I worked in both languages, and I like to think I know what I’m talking about).

Alright, let’s take a look at Andy Brown’s points:

Point number 1

Not a good point to start with, very personal point, so I’m like: ‘whatever dude’

Point number 2

Again, bad point, it’s a language feature, I have no problem with typing out an if else statement. However the second part of your argument is utterly wrong. C# doesn’t allow fall through in a case statement, meaning the compiler will complain if you omit the break statement:

case fallthrough C#

Point number 3

If I change the name of my control in the designer it just updates everything. I guess your Visual Studio 2010 is broken.

Point number 4

The one I hate the most. Not only are you PUSHING your personal preference to other people, you’re doing it with the wrong arguments. Allow me to explain:

&& in C# is NOT And in VB.NET. The && is a Contitional And, the And operator is logical, meaning it will execute both sides. We can read this on the MSDN page on this topic.

Let me prove it to you with an example:

C# &&

As you can see it only executes the Foo one, it completely omits the Bar!

If we follow the ‘comparison’ Andy wrote this would translate to the following VB.NET code:

VB.NET And

Well, it seems that we need the AndAlso operator in VB.NET to get the same behavior. You can get the And behavior in C# by using a single & instead of a double.

The same is for the || and the Or, you need the OrElse to achieve the || result, or, to use the Or in C#, you need the single | instead of a double.

Point number 5

First of all this is a IDE feature, not a language feature. But fine, I’ll bite: you have that too in C#. Type prop+<tab>+<tab> and you’ve got your property.

Point number 6

You are relying on the Microsoft.VisualBasic namespace. If you want to you can even add it to your C# project. The issue with this function is the following: reading the documentation doesn’t give me a single clue on what the restrictions are, what culture does it use?

You can always do int.TryParse or double.TryParse. Hec, you can even do a Regular Expression like ^[0-9]$ and then something else for the commas. I’m not a Regex Expert, and probably never will be Smile with tongue out.

And for your PMT function (click, decompiled from the dll):

PMT

Point number 7

Language feature, personal preference. No argument there.

Point number 8

First you start off by writing how to declare and define variables and then you come up with the out keyword? And if you have problems with the out keyword, you do realize that VB.NET doesn’t offer a way to the programmer to restrict him to give either an initialized variable or a non initialized variable. VB.NET only supports ByVal and ByRef, where the first is always a pointer (like in C#) and the second one is ref. No out available Sad smile. And then there is this behavior: Force an Argument to Be Passed by Value.

Point number 9

An enum in C# is an enum, even though it inherits from int. It’s just the compiler that complains. Of all the things you mentioned you have a fair point here. I’ll give you that.

Point number 10

You say it yourself, the whole point of an array is that it is fixed size. Use a list. They’re there for a reason.

I do not want to rant. I just want to get the facts right. And I feel bad. From your bio I read that you are a trainer. While they don’t have to go too deep for an introduction, you should get your facts right.

Signing off,

-Kristof

Your project dependencies matter (when using NuGet)

At work we had the following issue, we had a Silverlight project consuming some NuGet package, this project was being exposed in a Web application.

In order to keep our solution clean – we didn’t want an ‘assemblies’ folder – we used NuGet package restore.

We did it like the book said, don’t check in the packages folder, enable NuGet package restore, add the required repositories to the nuget.targets, you know the drill.

When building locally we didn’t have any issues. Everybody was able to run the project perfectly. The packages were downloaded from the repository when unavailable locally.

The issue rose when we committed our code to our source control system and ran builds of it with MSBuild.

In order to explain my issue I managed to create a very simple test case.

I created a solution with 2 projects, a web project, and a Silverlight project.

Solution window

The NuGetTest.Client had a NuGet reference to the package ‘MvvmLight’.

When you commit code to source control and run builds of it with MSBuild, it is supposed to download the NuGet package, and then build of that.

However, if we invoke the build we are presented with the following error:

Ugh, error.

What? Why?

So I went to check the packages folder on the Build location:

It's there!

It’s there! How could it not find the dll?

Time to dig deeper.

The command line executed for the project was simple:

C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe /nologo /noconsolelogger "C:\Builds\1\NuGetTest\New Build Definition 1\Sources\Dev\NuGetTest.sln" /m:1 /fl /flp:"logfile=C:\Builds\1\NuGetTest\New Build Definition 1\Sources\Dev\NuGetTest.log;encoding=Unicode;verbosity=diagnostic" /p:SkipInvalidConfigurations=true  /p:OutDir="C:\Builds\1\NuGetTest\New Build Definition 1\Binaries\\" /p:VCBuildOverride="C:\Builds\1\NuGetTest\New Build Definition 1\Sources\Dev\NuGetTest.sln.vsprops"  /dl:WorkflowCentralLogger,"C:\Program Files\Microsoft Team Foundation Server 2010\Tools\Microsoft.TeamFoundation.Build.Server.Logger.dll";"Verbosity=Diagnostic;BuildUri=vstfs:///Build/Build/8;InformationNodeId=622;TargetsNotLogged=GetNativeManifest,GetCopyToOutputDirectoryItems,GetTargetPath;TFSUrl=http://localhost:8080/tfs/DefaultCollection;"*WorkflowForwardingLogger,"C:\Program Files\Microsoft Team Foundation Server 2010\Tools\Microsoft.TeamFoundation.Build.Server.Logger.dll";"Verbosity=Diagnostic;"

I slimmed it down to the real deal (removed logging), and ended up with this:

C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe "C:\Builds\1\NuGetTest\New Build Definition 1\Sources\Dev\NuGetTest.sln" /m:1 /p:SkipInvalidConfigurations=true

Now I download the latest version of the project locally, and execute that command line:

"d:\Personal\Documents\Visual Studio 2010\Projects\NuGetTest\NuGetTest.sln" (default target) (1) ->"d:\Personal\Documents\Visual Studio 2010\Projects\NuGetTest\NuGetTest.Host\NuGetTest.Host.csproj" (default target) (2) ->"d:\Personal\Documents\Visual Studio 2010\Projects\NuGetTest\NuGetTest.Client\NuGetTest.Client.csproj" (default target) (3:2) ->(CoreCompile target) ->  ViewModel\MainViewModel.cs(1,7): error CS0246: The type or namespace name 'GalaSoft' could not be found (are you missing a using directive or an assembly reference?) [d:\Personal\Documents\Visual Studio 2010\Projects\NuGetTest\NuGetTest.Client\NuGetTest.Client.csproj]  ViewModel\MainViewModel.cs(17,34):errorCS0246: The type or namespace name 'ViewModelBase' could not be found (are you missing a using directive or an assembly reference?) [d:\Personal\Documents\Visual Studio 2010\Projects\NuGetTest\NuGetTest.Client\NuGetTest.Client.csproj]  ViewModel\ViewModelLocator.cs(15,7): error CS0246: The type or namespace name 'GalaSoft' could not be found (are you missing a using directive or an assemblyreference?)[d:\Personal\Documents\Visual Studio 2010\Projects\NuGetTest\NuGetTest.Client\NuGetTest.Client.csproj]

 

And we’re greeted with a lot of text, and at the end the same error. So it’s not the user that executes the build (he has sufficient rights).

What seems to happen here?

If we check the log we can see that the NuGetTest.Client is built because NuGetTest.Host depends on it:

Project "d:\Personal\Documents\Visual Studio 2010\Projects\NuGetTest\NuGetTest.Host\NuGetTest.Host.csproj" (2) is building "d:\Personal\Documents\Visual Studio 2010\Projects\NuGetTest\NuGetTest.Client\NuGetTest.Client.csproj" (3) on node 1 (GetXapOutputFile target(s)).

If we then continue reading the log file we can see that NuGet’s RestorePackages task is only executed after this task, which results in MSBuild trying to build the Silverlight project before all the required assemblies are downloaded.

How can we solve this? We can specify that the Silverlight project should be built before the web project, and thus forcing the RestorePackages to execute in order (before the build of the Silverlight project).

We can do this by going to project dependencies in the Solution Explorer, just do a right mouse on your solution and go to “Properties”.

In that window go to “Project Dependencies”:

Properties for solution, build order

In the “Project” dropdown you select your host project (here “NuGetTest.Host”), and check the checkbox of every Silverlight Project it depends on. This will make MSBuild explicitly build that project before continuing to the web project.

Good luck & have a good one!

Thoughts on a Resharper 6 refactoring

Consider the following code:

If we want to know if there are no items in the list we have 3 possibilities (probably more, but I’ll limit myself to 3 possibilities in this scope).

Which just uses List’s implementation of ICollection.Count.

Second option is:

Last option is:

As you might know, since ReSharper 6, the second option is suggested to be refactored to the last option.

image

However it is not the same to do an Enumerable.Count() and a Enumerable.Any() on an ICollection.

If we take a closer look using a decompile tool (Reflector, Resharper Decompile, JustDecompile, …) at the Count() and Any() extension methods we see the following:

Count:
image

Any:
image

We can clearly see that when using the Count() extension method the system actually first tries to see if the the IEnumerable<TSource> is an ICollection<TSource> or an ICollection, and using the Count property if possible, before enumerating over the entire list.

So I say: not everything Resharper says is correct, always use it carefully, think before you do an automatic refactoring. And more importantly: think about the design of your code. Is it needed that you pass in an IEnumerable? Is a ICollection<TSource> or an IList<TSource> more useful?

Have a good one!

Team Foundation 2010: Associate work item with changeset AFTER check in.

Today I was struggling associating a work item with a changeset after a check in. There is however no options for this in the UI. Or is there? Let’s check:

Cannot edit work items from changeset window

Ok, so not through the changeset UI.

Let’s check the command line.

c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC>tf changeset /?
TF - Team Foundation Version Control Tool, Version 10.0.30319.1
Copyright (c) Microsoft Corporation.  All rights reserved.

Displays information about a changeset and lets you change the associated
attributes, such as comments and check-in notes.

tf changeset [/comment:("comment"|@commentfile)]
             [/notes:("NoteFieldName"="NoteFieldValue"|@notefile)] [/noprompt]
             [/collection:TeamProjectCollectionUrl]
             [changesetnumber | /latest] [/login:username,[password]]

(emphasis mine).

So not through the command line. Now what? Let’s think: we want to associate a changeset with a work item. Why not look the other way around?

After the successful commit remember the changeset # (in our example 25464), go to the work item you want to associate the changeset to.

Right bottom you’ll see a tab called ‘Links’ (1), click it, and then click the ‘Link to’ (2) button.

Associate work item with changeset

In the next window, select ‘Changeset’ (1) and enter the number in the box (2). Hit  ‘OK’ (3).

Associate part II

After that hit ‘CTR+S’ to save your work item.

After that go back to your changeset:

It's there!

It works!

Have a good one!

-Kristof

Silverlight 4: Bug in TabControl.TabStripPlacement = Dock.Left and OnApplyTemplate

At work I ran into a bug with the Silverlight TabControl, more specifically when setting the TabStripPlacement to Dock.Left and hiding one of the TabItems in the parent’s OnApplyTemplate.

The way to get to this bug is quite specific. For example, you can’t do it when you’re using a UserControl, since in that kind of class OnApplyTemplate is never called.

You need to build a class which inherits from Control.

public class TabControlTest : Control

Then we have the style of this particular class:

<Style TargetType="TabControlTest:TabControlTest"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="TabControlTest:TabControlTest"> <Grid x:Name="LayoutRoot" Background="White"> <Grid.RowDefinitions> <RowDefinition Height="*" /> <RowDefinition Height="38" /> </Grid.RowDefinitions> <sdk:TabControl TabStripPlacement="{TemplateBinding TabStripPlacement}" Grid.Row="0"> <sdk:TabItem Header="First"> <sdk:TabItem.Content> <TextBlock Text="A" /> </sdk:TabItem.Content> </sdk:TabItem> <sdk:TabItem Header="Second" x:Name="middleTabItem"> <sdk:TabItem.Content> <TextBlock Text="B" /> </sdk:TabItem.Content> </sdk:TabItem> <sdk:TabItem Header="Last"> <sdk:TabItem.Content> <TextBlock Text="C" /> </sdk:TabItem.Content> </sdk:TabItem> </sdk:TabControl> <Button HorizontalAlignment="Center" Grid.Row="1" Content="{TemplateBinding ShowOrHide}" Command="{TemplateBinding ShowOrHideCommand}" /> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style>

As you can see I’ve named the middle TabItem (“middleTabItem”) so I can retrieve it in the OnApplyTemplate:

public override void OnApplyTemplate()
{
    this._middleTabItem = (TabItem) this.GetTemplateChild("middleTabItem");
    this._middleTabItem.Visibility = Visibility.Collapsed;

    base.OnApplyTemplate();
}

Now if the following 2 conditions are matched:

  1. TabStripPlacement is set to Dock.Left (it doesn’t happen on ‘Top’)
  2. We set the Visibility of the said TabItem to Collapsed in the OnApplyTemplate of the surrounding Control

Then we cannot make the TabItem Visible anymore.

To show or hide I use the following code:

this.ShowOrHideCommand = new Command(() =>
                                         {
                                            this.ShowOrHideText = string.Format(SwitchTo, this._middleTabItem.Visibility);
                                            this._middleTabItem.Visibility = this._middleTabItem.Visibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
                                         });

The solution to this is to call the OnApplyTemplate of the TabControl itself so that it recalculates it’s children’s location (or something, I’m not sure):

Give the TabControl a name, fetch it in OnApplyTemplate of your Control:

<sdk:TabControl TabStripPlacement="{TemplateBinding TabStripPlacement}" x:Name="TabControl" Grid.Row="0">
public override void OnApplyTemplate()
{
    this._middleTabItem = (TabItem) this.GetTemplateChild("middleTabItem");
    this._middleTabItem.Visibility = Visibility.Collapsed;
    this._tabControl = (TabControl) this.GetTemplateChild("TabControl");
    base.OnApplyTemplate();
}

And call the _tabControl’s OnApplyTemplate after switching the Visibility to Visible:

this.ShowOrHideCommand = new Command(() =>
                                         {
                                            this.ShowOrHideText = string.Format(SwitchTo, this._middleTabItem.Visibility);
                                            this._middleTabItem.Visibility = this._middleTabItem.Visibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
                                            this._tabControl.OnApplyTemplate();
                                         });

This will make the UI respond correctly. For your convenience I’ve added the SL project, and you can download it here.

Visual Studio 2010 SP1: DebuggerTypeProxy works again! *yay*

A while ago I bumped into a bug in Visual Studio 2010 + Silverlight 4.

While working with a List / Dictionary / … it didn’t show the items in the list, instead it showed the normal ‘raw view’:

No debug view

As you can see, there was no view to see the items.

What you would expect to see is this:

DebugView!

I reported the bug (many others did too!). The problem was that it was fixed in SL3, but not ported to SL4.

Now it’s fixed! This makes my work a lot easier. When we get SP1 @ work too that is!

Cheers!

Dictionary<TKey, TValue> finding key: try/catch vs TryGetValue

Today I saw some code where the developer accessed a dictionary like this:

  1. void Foo(int keyToFindInDictionary)
  2. {
  3.     Dictionary<int, string> dictionary = new Dictionary<int, string>();
  4.  
  5.     try
  6.     {
  7.         DoSomethingWithTheResult(dictionary[keyToFindInDictionary]);
  8.     }
  9.     catch (KeyNotFoundException)
  10.     {
  11.         // fallback
  12.     }
  13. }
  14.  
  15. private void DoSomethingWithTheResult(string s)
  16. {
  17.     // do something
  18. }

As you can see he catches the exception to handle the fact that the given key was not found in the dictionary.

I told him that there was a better way, i.e. Dictionary<TKey, TValue>.TryGetValue.

And then the curious part of me started thinking, how much better is it? Is it faster? Slower?

So I wrote the following small piece of code to test my statement that TryGetValue is better than catching the KeyNotFoundException.

  1. namespace DictionaryTryGetValueVersusException
  2. {
  3.     using System;
  4.     using System.Collections.Generic;
  5.     using System.Diagnostics;
  6.  
  7.     internal class Program
  8.     {
  9.         private static void Main()
  10.         {
  11.             // create a dictionary with some values
  12.             Dictionary<string, string> dictionary = new Dictionary<string, string>();
  13.  
  14.             // add 10,000 items
  15.             for (int i = 0; i < 10000; i++)
  16.             {
  17.                 if (i == 5000)
  18.                 {
  19.                     // skip
  20.                     continue;
  21.                 }
  22.  
  23.                 dictionary.Add(string.Format("Key{0}", i), string.Format("Value{0}", i));
  24.             }
  25.  
  26.             Stopwatch stopwatch = new Stopwatch();
  27.  
  28.             stopwatch.Start();
  29.  
  30.             const string keyToFindInDictionary = "Key5000";
  31.  
  32.             for (int i = 0; i < 10000; i++)
  33.             {
  34.                 // 5000 does not exist
  35.                 try
  36.                 {
  37.                     // execute a method on the variable, so that he compiler doesn't optimize it.
  38.                     dictionary[keyToFindInDictionary];
  39.                 }
  40.                 catch (Exception)
  41.                 {
  42.                     // ignore
  43.                 }
  44.             }
  45.  
  46.             stopwatch.Stop();
  47.             Console.WriteLine("Dictionary lookup with try/catch took: {0}", stopwatch.ElapsedTicks);
  48.  
  49.             stopwatch.Restart();
  50.  
  51.             for (int i = 0; i < 10000; i++)
  52.             {
  53.                 string notFound;
  54.                 // 5000 does not exist
  55.                 dictionary.TryGetValue(keyToFindInDictionary, out notFound);
  56.             }
  57.  
  58.             stopwatch.Stop();
  59.             Console.WriteLine("Dictionary lookup with TryGetValue took: {0}", stopwatch.ElapsedTicks);
  60.  
  61.             Console.WriteLine("Done, press enter to exit");
  62.             Console.ReadLine();
  63.         }
  64.     }
  65. }

As you can see we add 10,000 items to the dictionary, skipping the 5000th item, and then we do a lookup in the dictionary, 10,000 times, on the key that doesn’t exist, to measure the performance difference between the 2 previously discussed methods.

To run this test I did a Release Build in Visual Studio 2010, .NET 4.0, Any CPU, and this is the result:

Results

Dictionary lookup with try/catch took: 1069625
Dictionary lookup with TryGetValue took: 864
Done, press enter to exit

As you can see there is a HUGE difference. The TryGetValue-way was about 1237 faster!

Exception throwing is very heavy! Don’t forget that. It doesn’t mean that you need to program without exceptions, but when you EXPECT that a Key is not present in a given dictionary, don’t use the exception. Use the TryGetValue. If you always expect it to be there then it’s normal to catch the exception, because it’s exceptional that the key was not found.

PS: I tried the code again by skipping the 9999th item, and the results were about the same, take or leave a few milliseconds. So searching in the dictionary is very performant (close to O(1), as written in the Remarks section on this page.)

Stopping Casini before (re)building website in Visual Studio revisited

This is an update of an older post of mine on stopping Casini.

The code posted in the previous article (yes, read it!) only stops Webdev.Webserver, which is included in Microsoft Visual Studio 2010.

Now the problem is that when you’re using Blend and accidently run the app from there (which I hate, I’d prefer it to switch to Visual Studio).

This shortcut will allow you to quickly kill the webdev server of Blend (and that of Visual Studio too). So just keep it as a shortcut.

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe Stop-Process -Name @('WebDev.WebServer*', 'Microsoft.Expression.Web*')

Good luck :)

Enum dependency property caveat

Hi all,

A while ago I was creating a custom control in Silverlight with an enum Dependency property.

It looked like this:

  1. public partial class SomeCustomControl
  2. {
  3.     public static readonly DependencyProperty OnOrOffDependencyProperty = DependencyProperty.Register("OnOrOff", typeof (OnOff), typeof (SomeCustomControl), new PropertyMetadata(-1, OnPropertyChangedCallback));
  4.  
  5.     public SomeCustomControl()
  6.     {
  7.         this.InitializeComponent();
  8.     }
  9.  
  10.     public OnOff OnOrOff
  11.     {
  12.         get
  13.         {
  14.             return (OnOff) this.GetValue(OnOrOffDependencyProperty);
  15.         }
  16.         set
  17.         {
  18.             this.SetValue(OnOrOffDependencyProperty, value);
  19.         }
  20.     }
  21.  
  22.     private static void OnPropertyChangedCallback(DependencyObject o, DependencyPropertyChangedEventArgs e)
  23.     {
  24.         SomeCustomControl instance = (SomeCustomControl) o;
  25.  
  26.         instance.UpdateBackgroundColor((OnOff) e.NewValue);
  27.     }
  28.  
  29.     private void UpdateBackgroundColor(OnOff newValue)
  30.     {
  31.         switch (newValue)
  32.         {
  33.             case OnOff.On:
  34.                 this.Rectangle.Fill = new SolidColorBrush(Colors.Green);
  35.                 break;
  36.             case OnOff.Off:
  37.                 this.Rectangle.Fill = new SolidColorBrush(Colors.Red);
  38.                 break;
  39.         }
  40.     }
  41. }

The enum itself was quite simple:

  1. public enum OnOff
  2. {
  3.     On,
  4.     Off
  5. }

The control just changes background color when you set the enum to On (green), or Off (red). Very simple.

The problem is that the dependency property will take the enum member with number 0 as default, OnOff.On that is. And when setting the value in XAML (or code for that matter) will not update the property backing the dependency property:

Where is the green color? :(

The code to render this is found here:

  1. <EnumProblem:SomeCustomControl OnOrOff="On"
  2.                                        Grid.Row="1">
  3.         </EnumProblem:SomeCustomControl>
  4.         <EnumProblem:SomeCustomControl OnOrOff="Off"
  5.                                        Grid.Row="1"
  6.                                        Grid.Column="1">

As you can see the left one is NOT green.

This is because the default is OnOff.On (value 0), and setting it (again) to On doesn’t trigger the execution of OnPropertyChangedCallback.

We can solve this (of course, otherwise what would be the point of writing this? :P )

The first solution you might think about is setting the default value of the Dependency Property’s default value. Maybe –1 for example, so that at least the engine can detect a change.

  1. public static readonly DependencyProperty OnOrOffDependencyProperty = DependencyProperty.Register("OnOrOff", typeof (OnOff), typeof (SomeCustomControl), new PropertyMetadata(-1, OnPropertyChangedCallback));

Running the app like this will cause an exception, since it cannot convert the –1 to the OnOff enum.

Error when PropertyMetaData.Default = -1

The other solution is setting the value of the first member to a positive value, which makes the code work:

  1. public enum OnOff
  2. {
  3.     On = 1,
  4.     Off
  5. }

It works!

Now you might think: What’s the difference, the first time it tries to convert –1 to OnOff, and the second time it tried to convert 0 to OnOff, and it both cases it the value doesn’t exist in the enum.

The reason here is that you can have an enum that starts at 1, but you can still set create an instance of that enum with a value of 0.

Enum to 0

But creating the enum with a value of –1 doesn’t work:

-1 doesn't work

This is why setting –1 to the default value of the dependency property doesn’t work (unless you of course have a –1 value in the enum!)

If you want the source, and you know a good place to upload it, please mail me :)