April 16, 2015

I’m a Microsoft Most Valuable Professional!

MVP_Logo_Horizontal_Preferred_Cyan300_CMYK_72ppiI’m pleased to announce that I’ve been awarded with this prestigious award. I’ve been recognized for my contributions to community before within the local MSP (Microsoft Student Partner) program, but this is a completely different level. As of writing this, there’s only 375 MVPs with the .NET technical expertise in the whole world and I’m proud to be one of them!

I think that the .NET expertise has been introduced this year because when I was nominated back in the December 2014, I didn’t see it there and had to choose Windows Development Platform. I also noticed that with introduction of this expertise few other disappeared, namely Visual C#, Visual F# and Visual Basic. I deduced that they have been merged into .NET which probably also includes WPF and a few other areas of the .NET Framework. I think that this step is logical considering that VB.NET is getting some features from C# and vice versa, and development of both these languages is handled by a single design team taking inspiration from some F# features.

Two weeks after being awarded, I’m still overwhelmed with a number of new channels I can communicate through with other MVPs, number of new events I can participate in and number of new opportunities that presents to me. I feel that this year will be amazing!

Finally, I would like to express my gratitude to my MSP peers and mainly local MSP program manager who saw me fit for the award, for nominating me. It would be hardly possible without their support. Thank you.


Here’s my MVP profile listing all my contributions in case you are interested.

February 23, 2015

Get info about your machine

Today’s article is about a static class from .NET Framework which provides some information about your machine and platform used – System.Environment. I find this class immensely useful only for some very specific tasks, because not every application could benefit from what it provides. I’ll discuss only few of its public members, because it’s quite well documented on MSDN.


I use this when I need to know a full path of a configuration file or any other resource file on a disk in case I placed it in the same folder as my application binaries are placed.

var path = Path.Combine(Environment.CurrentDirectory, "config.xml");

But there’s one catch, this does not work with Windows services, because when they are started by a system, their default working directory is in C:\Windows\System32 since Service Control Manager is placed there. So if you are not sure if your code will run from a Windows service, it’s safer to use something like as follows.

Path.GetDirectory(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath);


No need to describe, I just want to point it out, because I use it a client or server identifier in a network communication.


This one is not really self-explanatory and can be easily overlooked, but I place it among my best findings in .NET Framework. Have you ever tried to debug a Windows Service? Right, not a very pleasant business. This could make a whole nother article, so here’s a random example for now, maybe I’ll do one later myself.


You probably know how to access command line arguments from a console application, but how to access then from a WinForms app or a class library? That’s where Environment.GetCommandLineArgs() shines. Just know that the first arguments is always a path to the executing assembly or just its name, it depends where a working directory is.


An easy way to get paths to many special system folders like Desktop, MyDocuments or Program Files.

February 16, 2015

Concurrency in C# Cookbook review

book cover
Concurrency is a topic that many programmers, even some senior ones, still didn't get right. These days, it's mostly misconceptions about asynchronous programming, but apart from that, not many people heard about reactive programming (Rx) or used TPL Dataflow.

What I like about the book is that it covers all different types of concurrency and clearly explains when would you use one in favor of the other. It's also easy to skip what you already know thanks to its cookbook format.

Follows a short extract from the first chapter "Concurrency: An Overview" that is in my opinion a very good start to this topic and every single programmer should know even if he/she don't use it.

    Doing more than one thing at a time.
    A form of concurrency that uses multiple threads of execution.
Parallel Processing
    Doing lots of work by dividing it up among multiple threads that run concurrently.
Asynchronous Programming
    A form of concurrency that uses futures or callbacks to avoid unnecessary threads.
Reactive Programming
    A declarative style of programming where the application reacts to events.

The book is all about introducing you to all these topics by providing you with short and clean code samples with explanations. Then there are chapters that describe how to test concurrent code, how to interop between different styles, how it fits into OOP world and few other. Amongst them, I particularly enjoyed a chapter called "Collections" which describes various types of concurrency-friendly collections. Have you heard about immutable or blocking collections yet? I certainly had not before I read the book. Now I even know which one to choose when dealing with concurrency in my code.

I recommend this book to everyone who had not chance to use threading much to get a nice high-level view on concurrency, but also to everyone who started with threads in early .NET Framework versions and still use it these days. Basically, you should not need to call new Thread(); in your code anymore.

Head to the author's blog for more.

February 9, 2015

Assembly versioning the right way

When I started working on projects that matter and people actually use, I also started use assembly versioning system provided by the .NET Framework. For one thing, I like seeing a version number increase because it reminds me of how much work I’ve done. For another, it helps me solve problems when someone reports a bug and I can just ask for a version being used. But thruth to be said, there’s more to it than just increasing numbers, I learned my lesson and I share the experience through this article.


assemblyinfo Every new project you create in Visual Studio has a file called AssemblyInfo with an extension depending on a language you use. For C#, it’s .cs extension. This file is located in a special project folder called Properties.
It’s information in this file that affects what you can see in assembly details when you right-click it in Windows Explorer and select Properties and navigate to Details tab


or when you reference it from another project and inpsect it in Properties window.



There are 3 different versions that assembly can have.


[assembly: AssemblyInformationalVersion("2.0 beta")]

This is the Product version in assembly properties details and it’s by default not included in AssemblyInfo file because it’s ment to be consistent across a whole product, which can consist of many different assemblies. Typically, a build server adjusts this version. It does not have to be a number, it can be just any string. The default value is the same as AssemblyVersion.


[assembly: AssemblyFileVersion("")]

This is the File version in assembly properties details and is the same as AssemblyVersion if not specified otherwise. Its format should abide by the major.minor.build.revision convention. Typically, you set the major and minor numbers the same as in AssemblyVersion and the last two are incremented with each build. However, there’s no trivial way how to specify this behaviour unless you are using a build server to do it for you. If you don’t use a build server and still want to achieve auto-incrementing, I recommend this CodeProject article that I followed with success.

Remember, this is the version you should be using for problem solving.


[assembly: AssemblyVersion("")]

This version is not visible in assembly properties details, but you can see it in VS reference properties, for instance. Its format should abide by the major.minor.build.revision convention and if not specified, it’s This version is probably the most important one, because it’s used by the .NET Framework runtime to bind to strongly named assemblies, which means, that even a slightest change in the version can result in a compile time error or a runtime exception in a project that references it, if there’s a version mismatch while loading assemblies to an AppDomain. This version supports auto-increment directly by setting the two first number manually and replacing the rest with an asterisk.
[assembly: AssemblyVersion("2.0.*")]

I use this notation in many internal tools because they are not being built by a build server and no other projects depend on them. Once, I created a shared library, forgot about the rule emphasized above and it cost me and some of my colleagues many hours every time I did some small yet important changes, and committed a new assembly to projects I was familiar with. Finally, one day someone drew my attention to this issues and I decided to write an article about it.

What exactly can cause such problems? Let’s say you have a logging library that a project CoreLib uses. There’s also a console project SomeConsole and it uses both CoreLib and the logging library. But you are only the author of the logging library and you know about CoreLib. So when you add a new cool logging feature, rebuild the project, commit the new assembly to a repository and rebuild CoreLib to use it, now you have a problem. A person who maintains SomeConsole starts using a newer version of CoreLib but does not know about a new version of the logging library will get a compile time error. And that’s just one dependency. Now imagine, that SomeConsole also uses few other core libraries some of which discovered your logging library in a different time and therefore use a different version each. There’s a true madness.

For more explanations, navigate to this SO question. I find particularly answer from Daniel Fortunov very explaining and I like his example of mscorlib.dll.

February 5, 2015

Post-increment confusion

Recently answering a question about post-increment behaviour and then asking around a bit convinced me that this concept is still misunderstood by many. Apparently, different languages can interpret some post-increment statements differently, so I’ll stick to the .NET platform as I’ll try to clarify how it really works.

To start with something simple, we can all agree on the fact that the following code snippet

int a = 10;                        
int b = a++;

stores 10 in a variable a, then copies the value to a variable b and increases value stored in the variable a to 11. But what the following code does?

int a = 10;                        
a = a++;

In order to be sure, let’s peek at generated IL code (you can try it yourself using LINQPad, for instance).

IL_0001:  ldc.i4.s    0A // stack: 10
IL_0003:  stloc.0        // a = 10, stack: empty
IL_0004:  ldloc.0        // stack: 10
IL_0005:  dup            // stack: 10, 10
IL_0006:  ldc.i4.1       // stack: 10, 10, 1
IL_0007:  add            // stack: 10, 11
IL_0008:  stloc.0        // a = 11, stack: 10
IL_0009:  stloc.0        // a = 10, stack: empty

I supplemented the output by comments to see what’s happening on the evaluation stack. As you can see, in order to be able to return the previous value, it’s preserved by duplicating it first, then increment takes place followed by an assigment of the new value to the variable and finally the old value returned (as post-increment promises) and assigned to the variable.

I consider the previous nearly self-explanatory and I could leave it as it is now, but admittedly, it’s not always enough to look at the corresponding IL to understand or even start with it for that matter. Therefore, remember that the right side expression of an assignment statement is always evaluated first in .NET. It’s a well defined behaviour of operator precedence and associativity.

To use it in our situation - a++ expression is completely evaluated before a value it returns is assigned to a variable on the left side, which means, that a is really 11 for a moment before it’s overwritten by the previous value.

January 25, 2015

Button with << in content

This post is inspired by a question on SO. Its author defined two buttons in XAML in a WPF application, set content of the first one to >> and content of the other one to << through a Content property but the compiler complained and left him puzzled. Why closing brackets can be used but opening ones cannot?

My first guess was that
<Button Content="<<" />

is by the compiler translated to

before processing, because the two forms are equivalent, but after I’ve done some research I found that this is not true. Why would I even think that? Because I know that bracket matching can be easily determined by pushing opening brackets onto a stack and popping them as closing brackets are read by a text reader. Then it’s clear that it’s syntactically incorrect, because the compiler is confused with opening brackets missing their closing brackets. Two closing brackets are not a problem, if there’s nothing on the stack, then it has to be content. It makes sense. So how it is really?

When you try those two snippets in Visual Studio, compiler provides different error messages in both cases.

In the first case:
  • when you point with a mouse cursor on a Button text underlined with a red squiggly or on the brackets, it says: “XML element is not closed”,
  • when you point right after a closing quotation mark of content, it says: “Whitespace is missing.” and 
  • finally, when you point on a closing tag, it says: “The open angle bracket character ‘<’ is not valid in an attribute. It should be written as ‘&lt;’.”.
In the second case:
  • when you point on brackets, it says: “Invalid tag header” and
  • when you point on a closing tag, it says: “Closing tag for element ‘<>’ was not found.”.
Now we see the difference in how are these two forms processed. One thing to notice is that it actually provides a solution in one of the error messages. Still, the question is why it does not work with two opening brackets?

To explain this behavior we need to know the following:

Button is one of content controls, which are simply controls that are constrained to contain a single item. Content controls all derive from System.Windows.Controls.ContentControl, which has a Content property of type Object that contains the single item. Because a content control’s single item can be any arbitrary object, the control can contain a potentially large tree of objects. There just can be only one direct child. [1]

Having this on mind it’s now clear that in the second case the compiler can actually represent a button’s content as a UIElement if it’s syntactically correct (therefore those two error messages implying creation of a new element) or just print a text. In the first case, it can be only plain text or a markup extension ({…}).

[1] – WPF 4 Unleashed, Adam Nathan

January 12, 2015

Field or property?

While answering questions on Stack Overflow I see developers use fields where properties should be used again and again. And while it was not too much appealing to use properties in times when the feature made it to the language, it became really compelling over the years. With this article, I’ll try to clear all your doubts about using properties instead of public and protected fields.

Why bother with properties?

The first question, why even consider properties as a replacement of public fields?
  1. Encapsulation. When you declare a public field on a type you allow everyone to set its value whenever they want, unless the field is readonly, of course. But what happens if you decide to change the logic of setting it to include some sort of a check, for instance? You would have to add a getter and setter methods and make the field private, which breaks your API. This applies to protected fields too.
  2. Data-binding. Not having to set all UI components manually to a new value whenever you obtain it, but rather let them to change automatically when the source changes, is a huge advantage. You can’t bind to a field, period.

Concerned about performance?

An auto-property is translated into a private backing field with a getter method and a setter method by the C# compiler.
public int Number { get; set; }
// is translated into
private int number;
public int Number
    get { return number; }
    set { number = value; }
// and getter and setter are nothing else but
int get_Number()
    return number;

void set_Number(int value)
    number = value;

“This sure involves a performance penalty, right? A field is just a fiield and it’s accessed directly whereas a property is a field accessed through methods – an extra level of indirection.”

It sure looks like what you think, but the JIT compiler is very clever about this and optimizes it away. How? It’s out of the scope of this article, but I’ll get to it someday. For those eager of you, it’s called inlining.

Writing a property is slower!

You might think that, but did you know that there are code-snippets in VS for different kinds of properties? Try writting prop and press Tab or Enter in order to generate an auto-property and then simply change its type (followed by pressing Tab or Enter) and name. Follows a list of other property code-snippets available in VS:
  • propg – auto-property with a private setter
  • propfull – property in the expanded form
  • propdp – dependency property
As it’s all fast enough when using code-snippets, the only thing that can discourage you from using properties are extra lines of code. If you wanted to use properties before auto-properties (short form of auto-implemented properties) made it to the language in 2007 (C# 3.0), you had to write them in the expanded form shown in the example above. You still need to write them in that manner if you want to
  • include some getter or setter logic or
  • have a truly readonly property (auto-property with a private setter in not readonly).
Good news is that the later one has been revisited for C# 6.0. If you don’t know what I’m talking about, check the following code example.
// auto-property initializers
public int Number { get; set; } = 10;

// getter-only auto-properties
public int Number { get; } = 10;

These two new features combined make a huge difference in resulting number of lines of code. There’s no reason to write
public readonly int number = 10;

anymore, because it simply does not offer any benefits over a property. There may be some scenarios where a public field makes more sense, but I’m not aware of any. If you are, feel free to comment.