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.

CurrentDirectory

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);

MachineName


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


UserInteractive


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.


GetCommandLineArgs()


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.


GetFolderPath(Environment.SpecialFolder)


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.

Concurrency
    Doing more than one thing at a time.
Multithreading
    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

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


props

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

vsprops

Versions

There are 3 different versions that assembly can have.

AssemblyInformationalVersion

[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.

AssemblyFileVersion

[assembly: AssemblyFileVersion("2.0.1.5")]

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.

AssemblyVersion

[assembly: AssemblyVersion("2.0.0.0")]

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 0.0.0.0. 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.