Update the updater to update

update-windows-update

I formatted one of my laptops and reinstalled Windows the other day. Whilst reinstalling software and bringing it up to date, Windows update gave me this ridiculous message:

“To check for updates, you must first install an update for Windows Update.”

I guess software has become so complex that even updates require various levels of abstraction. ūüôā

C# 6 Preview: Changes in VS2015 CTP 5

C# 6 and Visual Studio 2015 are both prerelease software at the moment, and thus they are subject to change at any time.

There have indeed been some changes in C# 6¬†that came out in CTP 5 but which don’t seem to have been mentioned anywhere.

String interpolation

If you’ve read my original article on string interpolation, you’ll know that the syntax was expected to change. Well, that has happened, and the expected syntax is now in place. So now, you can use string interpolation to write special formatted strings as follows:

            var name = "Chuck";
            var surname = "Norris";

            string message = $"The man is {name} {surname}";

The placeholders in the curly brackets no longer require a prefixing backslash, but a dollar sign is necessary at the start of the string to allow them to be interpreted properly.

Just like before, the placeholders are not restricted to simple variables. They may contain arbitrary expressions including properties and methods:

            var numbers = new int[] { 1, 2, 3, 4, 5 };

            string message = $"There are {numbers.Length} numbers, and their average is {numbers.Average()}";

You can use format strings in placeholders. Unlike in the original implementation, they don’t need to be enclosed in quotes if they contain operators (e.g. dashes which normally represent minus signs). However you need to be a little precise with them, as any extra space after the colon (:) appears in the output:

            var dateOfBirth = DateTime.Now;
            string message = $"It's {dateOfBirth:yyyy-MM-dd}!";

using static

I’ve also written about the using static feature before, which lets you declare a static class among the using statements and then omit the class prefix when using static methods.

The syntax has changed, and you will need to prefix the static class with the keyword “static” in the declaration. This is a good thing because it eliminates the confusion between which using statements are namespaces and which are static classes.

    using static System.Console;

    class Program
    {
        static void Main(string[] args)
        {   
            WriteLine("Hello Lilly!");

            ReadLine();
        }
    }

VS2015 Preview: Layout Management

In earlier versions of Visual Studio, if you happened to mess up your window layout in Visual Studio, you could reset it back to the default layout by using the appropriate item in the Window menu:

vs2015-windowlayouts-duringreset

This rearranges the docked windows to whatever you originally had when Visual Studio was installed:

vs2015-windowlayouts-afterreset

That’s nice and all. But you may have noticed some new items above “Reset Window Layout” in the Window menu which are pretty handy when it comes to managing your window layouts.

For instance, when developing a new WPF application, the toolbox can sometimes come in handy for those without much experience with XAML. So, after introducing the Toolbox window, you can save the current layout:

vs2015-windowlayouts-duringsave

To save a layout, you need to give it a name:

vs2015-windowlayouts-promptsave

…and if that name happens to already exist, you’re asked whether you want to replace it (this is how you update saved layouts):

vs2015-windowlayouts-promptsaveexisting

You can then load (apply) these layouts by selecting them from the list in the Window menu, or by using the appropriate shortcut key (available for the first nine layouts in order). For instance, I saved this alternate layout suitable for unit tests, and I can apply it like this:

vs2015-windowlayouts-duringapply

…and then, like magic, the selected layout is applied:

vs2015-windowlayouts-afterapply

There’s also a menu item for management of these layouts:

vs2015-windowlayouts-managemenuitem

This opens a dialog which allows you to rename, delete, or reorder layouts.

vs2015-windowlayouts-managedialog

Reordering layouts has the effect of reassigning their keyboard shortcuts, since they are assigned in order to the first nine (from Ctrl+Alt+1 to Ctrl+Alt+9).

So, there you have it! Window layout management is yet another new feature in Visual Studio 2015 to improve your productivity.

VS2015 Preview: Live Static Code Analysis

In Visual Studio 2015, the new C# and VB .NET compilers are based on the .NET Compiler Platform known as Roslyn.¬†This allows third-party tools to use the compiler itself to query the structure of code, rather than having to¬†redo the compiler’s job. It also provides the ability to¬†fix the code by modifying its structure.

You can use the NuGet Package Manager in VS2015 to install analyzers.¬†At the moment there are very few available, and they’re still prerelease software. For this demonstration we’ll use the CodeCracker C# analyzer:

vs2015-analyzers-nuget

Once you install the package, you’ll see that the analyzer has been added under a special Analyzers node under the References in Solution Explorer. If you expand the analyzer, you can see all the rules that it enforces:

vs2015-analyzers-solution-explorer

As you can see, the code analysis rules may be enforced at various levels. Those marked as errors will result in actual compiler errors, and obviously cause the build to fail.

The rules that are broken by the code will then show up in the error list, which in VS2015 has been enhanced so that you can see more info about the error/rule and also click on the error code link to go to its online documentation (at the time of writing this article,¬†the CodeCracker’s error code links are broken):

vs2015-analyzers-error-list

The best thing about¬†live static code analysis is that they’re¬†live: the rules will be checked as you’re writing your code, and you don’t even need to build for them to be evaulated.

Warnings may be sorted out by moving the caret within¬†the relevant code and pressing Ctrl+. (Control Dot), after which the Quick Actions become available. See, code analyzers don’t need to limit themselves to complaining. If a fix is available, you’ll have the option to apply it, and you can preview the changes as with any other refactoring:

vs2015-analyzers-fix

If you know better than the code analyzer, you can opt to suppress the warning instead:

vs2015-analyzers-suppress

Code analysis allows rules to be enforced on your team’s code. Roslyn facilitates this by making it easy to plug in different code analyzers (and hopefully in future there will be a wider range to choose from) and by running code analysis live, without the need to build the project.

Note: this demonstration used the CodeCracker C# analyzer in order to show the different levels of rules (e.g. warnings, errors, etc), since the StyleCop analyzer’s rules are all warnings. The CodeCracker C# analyzer is in quite a mess at the time of writing, with missing fixes, broken rule documentation links, and countless grammatical errors. But it’s prerelease, so we’ll pretend that’s a good excuse and forgive it for its sins.

Deserializing Derived Types with JSON.NET

If you’re using Json.NET¬†to serialize¬†objects which involve inheritance hierarchies,¬†there’s a little issue you might run into.

Let’s say we have a class Person:

    public class Person
    {
        public string Name { get; set; }
    }

…and we also have another class Employee which derives from Person:

    public class Employee : Person
    {
        public decimal Salary { get; set; }
    }

Then I can write the following little Console Application (in which Json.NET is installed via NuGet):

            var employee = new Employee() { Name = "John", Salary = 1000m };

            var json = JsonConvert.SerializeObject(employee);

            var deserialized = JsonConvert.DeserializeObject<Person>(json);

We’re serializing an Employee (which derives from Person), and then deserializing into a Person (the base class). Due to polymorphism, we’d expect the result to hold a reference to an Employee instance complete with Salary. Alas, this is not the case:

json-derivedclasses-problem

As you can see, the result is actually of type Person, and the Salary goes missing in the deserialization.

Apparently the solution is to turn on Type Name Handling. The code is thus transformed:

            var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All };

            var employee = new Employee() { Name = "John", Salary = 1000m };

            var json = JsonConvert.SerializeObject(employee, settings);

            var deserialized = JsonConvert.DeserializeObject<Person>(json, settings);

Once we create an instance of JsonDerializerSettings with TypeNameHandling turned on, we can pass that object as a paramater in the serialization/deserialization methods to obtain the correct result:

json-derivedclasses-solution

As you can see, the deserialized result is now an Employee, complete with Salary. You’ll also notice that the actual serialized JSON has changed: there is now type information in it, and that’s what allows the correct type to be deserialized.

So why is this functionality not enabled by default? I can only guess that it’s for performance reasons.