# Visual Studio 11 Beta

Microsoft have announced that the VS11 Beta will ship soon.

A second post has followed, and, like Marmite, it seems that opinion is split.

## What does VS11 Need to Get Right?

The biggest complaint about VS2010 has been the performance (e.g. builds on the UI thread). This is the single biggest thing that VS11 needs to achieve is better performance. Adding an SSD drive to your machine to get decent performance out of VS2010, should not be a requirement for developers.

## The New UI

Some commenters seem to like the new UI. Whilst it is superficially less distracting, the use of capital letters in the titles of the docking panels is awful: just searching for why capitals are bad gives this link, amongst many others.

It seems that the Windows 8 split personality has spread to Visual Studio: is it Metro, or is it Windows? I can’t imagine anyone doing any serious development on a Windows tablet using the touch-screen keyboard. So it is a Windows application, and should continue to look and feel like one.

Third party plugins such as Code Rush, and Resharper, use colour to great effect when animating refactorings, code layout, searching and so on; even Visual Studio’s built in syntax highlighting does the same: it uses colour! By turning the rest of the UI into monochrome, this will make things look odd, in my opinion.

The new icons, sorry, ‘glyphs’, are just ‘OK’. VS11 is, after all, an IDE, and you should spend most of your time typing (or debugging), rather than looking at icons.

## Customization and the Keyboard to the Rescue

Until we actually get to use the beta, there’s not much else to say. However, like all previous versions of Visual Studio you can remove the toolbars, and create your own. In fact, this is how my VS2010 UI looks in daily usage:

If VS11 ships as-is, I can see that I will recreate quite a few toolbars by hand using text only for key commands.

Keyboard shortcuts are the most important thing for me, so the one huge plus point so far is that there is a ‘Quick Launch’ (Ctrl+Q) option. This is just the ‘Quick Access’ function from the Productivity Power Tools in VS2010.

## One Edition and Pricing

With Apple charging next to nothing for XCode and only having ONE version, isn’t it about time Microsoft did the same? It is doubtful VS will ever be given away, but Microsoft should reconsider their pricing and marketing ‘strategy’ (whatever happened to Developers! Developers! Developers!). Please just release one version, and make things like ‘Team Foundation’ download-able plug-ins.

## Looking Forward

The best thing about VS11 is for C++ developers. The bulk of the C++11 spec is being shipped, along with a complete STL, and C++ AMP. In many cases, just recompiling the code under C++11 will result in faster executing code. For .NET programmers, the framework gets bumped to .NET 4.5, which seems to be a modest incremental release.

## Updated

Some users are already mocking up improved Zune-style UIs on the Visual Studio UserVoice site. This:

shows that the new UI has lots of room for improvement.

And guess what the number 1 IDE request now is? Add some colour to the VS11 Beta.

# A WPF/MVVM Countdown Timer

## Requirements and Features

The Countdown Timer is going to be relatively simple:

• The starting time can be chosen by the user.
• Notify the user visually (in the application and task tray) and audibly.
• The application has settings that the user can change.
• The Windows 7 taskbar icon shows the progress of the timer.

The original motivation for this was that I came across the Pomodoro Technique whilst browsing the web and thought it would be fun to write a countdown timer that could be used for this. It is, in short, a ‘getting things done’ idea which can be boiled down to:

• work for 25 minutes
• break for 5 minutes
• repeat

So I decided that the default setting for the timer is 25 minutes, and that it should record the number of completed countdowns unobtrusively, should someone wish to use this application in that way.

## Choosing the Underlying Timer

We use the WPF DispatchTimer to perform a count. We are not making any guarantees about the accuracy of the timer.

In fact neither does the documentation:

Timers are not guaranteed to execute exactly when the time interval occurs, but they are guaranteed to not execute before the time interval occurs. This is because DispatcherTimer operations are placed on the Dispatcher queue like other operations. When the DispatcherTimer operation executes is dependent on the other jobs in the queue and their priorities.

By leveraging the .NET framework, we use a TimeSpan that allows us to increment, and importantly, decrement by a specified amount. We then simply decrement our starting value every time the DispatchTimer ticks, until we get a negative TimeSpan, and then we stop.

The code is written in such a way that the TimerModel is just a concrete implementation of ITimerModel and the concrete instantiation of an ITimerModel is generated from a single factory method: in other words you could write your own ITimerModel derived class instead and update the factory method as required (e.g. use System.Threading.Timer instead).

## MVVM

Since all ‘good’ WPF applications use MVVM to structure themselves, I’ll attempt to automatically make this application ‘good’ by default, by using an MVVM framework!

What does this mean? The application will be divided into:

• Views – XAML-only layouts that the application uses: i.e. the GUI and all its windows!
• ViewModels – translate the data between the Views and the Models.
• Models – the actual code that does the work (and everything else).

If you find this confusing or want to know more, please see another of my articles: WPF/MVVM Quick Start Tutorial.

## Application Settings

All applications have settings and this one is no different: to persist the application’s settings, we take advantage of the class System.Configuration.ApplicationSettingsBase. This is subclassed for the WPF application when you create it, so you can then just address the application settings programmatically, for example:

_timer.Duration = Properties.Settings.Default.Duration;


where we have created a Duration property.

In the same way that we hide the implementation of the Timer behind a ITimerModel interface, we also use an interface called ISettingsModel class, and use a concrete instances called SettingsModel, along with a factory method to retrieve an instance of the class. This gives us the option, as before, to change the settings backing store, to something else in the future (ini file anyone?).

## Updating Settings Between Application Versions

To cater for updates to the application we can use the following method: define UpgradeRequired in our settings, and set to True by default. We then use:

if (Properties.Settings.Default.UpgradeRequired)
{
Properties.Settings.Default.Save();
}


to force the upgrade of the application settings only when the UpgradeRequired flag is true. For newly versioned assemblies, all settings take their default values, this code is triggered, and the settings are copied from a previous application version, if it exists, to the new one.

It is worth noting that for this ‘trick’ to work, you always need to define this field in your application settings in the very first version of your application.

## The Views and ViewModels

Ther application has several views that are all UserControls and hosted in the MainWindow. This means no pop-up dialogs! They are:

• The main TimerView
• The SettingsView
• The AboutView

with the corresponding ViewModels:

• The TimerViewModel
• The SettingsViewModel
• The AboutViewModel

## Changing Views and Messaging

As we want to use ‘separation of concerns’, or ‘encapsulation’ (if you prefer), we do not want view-models to communicate directly. In order to do this, we simply use message passing, in other words:

The MVVMLight Toolkit provides us with a singleton Messenger class that we can register message consumers and message producers with. So to raise an ‘event’ in one view model from another, we simple pass a message, for example:

public class MainViewModel : ViewModelBase
{
public MainViewModel()
{
//  Lastly, listen for messages from other view models.
Messenger.Default.Register<SimpleMessage>(this, ConsumeMessage);
}

private void ConsumeMessage(SimpleMessage message)
{
switch (message.Type)
{
case MessageType.TimerTick:
WindowTitle = message.Message;
break;
// ....
}
}
}


and in the TimerViewModel:

public class TimerViewModel : ViewModelBase
{
private void OnTick(object sender, TimerModelEventArgs e)
{
Messenger.Default.Send(new SimpleMessage(MessageType.TimerTick, TimerValue));
}
}


What this achieves is as follows: the TimerViewModel updates the TimerView countdown clock in the main window’s ContentControl, but we want to update the window’s title to also show the countdown. The main window View is bound to the MainViewModel, so to do this, and to keep the view-models separate we pass a message containing the time remaining. The reason we update the window title bar is discussed a little later.

## The TaskBar Preview and the Window Title

As you can see in this screenshot:

The countdown value is shown in the taskbar item thumbnail, and in the main window’s title. The reason we update the window’s title is that when a window is minimzed, the taskbar item thumbnail is not updated by Windows, so if you were to hover your mouse pointer over the icon on the task bar when the item is minimized, the thumbnail preview will display the countdown at the time you minimized the window. Fortunately, the title of the window is updated in the thumbnail preview, so we ensure that we update that to provide a visual clue to the user.

We need a second message type to comminicate task bar progress updates in Windows 7: since the MainWindow ‘view’ is bound to the MainViewModel, we need to receive messages from the TimerViewModel that are appropriate to update the task bar progress indicator. Fortunately this is relatively straightforward, and once again we make use of the Messenger.Default.Register and Messenger.Default.Send pattern we saw earlier.

The second message class is simply:

public class TaskbarItemMessage
{
{
Value = -1.0;
}
public TaskbarItemProgressState State { get; set; }

public double Value { get; set; }

public bool HasValue { get { return ! (Value < 0.0); } }
}


Our TimerViewModel just send instances of these messages and the MainViewModel receives them, and via the magic of data-binding, between the view model (MainViewModel) and the view (MainWindow) the taskbar progress indicator just updates:

<Window x:Class="Btl.MainWindow"
DataContext="{Binding Main,
Source={StaticResource Locator}}">
<ThumbButtonInfoCollection>
<ThumbButtonInfo Command="{Binding PlayCommand}"
Description="Start"
DismissWhenClicked="False"
ImageSource="Resources\icon.play.png" />
<ThumbButtonInfo Command="{Binding PauseCommand}"
Description="Pause"
DismissWhenClicked="False"
ImageSource="Resources\icon.pause.png" />
</ThumbButtonInfoCollection>
<!-- ELIDED  -->
</Window>


Since the TaskBarItemInfo thumbnail previews offer us more than just the preview, we can add a thumbnail ‘Start’ and ‘Pause’ button (just like Media Player), so we can control the countdown timer from the thumbnail preview, hence the ThumbButtonInfo elements above.

## A Note on the UI Design

There is some method to the madness of the Countdown Timer UI: since the Play and Pause buttons are likely to be the most used, they are the largest, then the settings and reset buttons are smaller so they are less likely to be clicked on. The ‘About’ window is accessed by a small ‘?’ in the bottom right hand corner.

Similarly, the ‘Ok’ and ‘Cancel’ buttons are widely separated in the Settings view so it is clear which one you want to click on.

And lastly, aside from the button icons (play, pause etc.), I’ve left the theming of the application alone, so that the OS can choose how to theme it. Of course, since this is an MVVM application, you can take the source code, fire up Blend, and change it however you like.

There are even some third-party libraries that will do a lot of the work for you, e.g. MahApps.Metro.

## Bonus Features

In the apps section of this site there is an MSI installer for anyone that cares to use it and just wants to install the timer.

All the source code is also on github and you are free to fork it, copy it, break it, etc. The MSI installer project uses Installshield, so it is part of the solution hosted on github, but not included in the zip files above (in case you, the reader, do not have it installed).

# Configuring Debian Under Virtual Box Part 2

The next step in configuring Debian linux under Virtual Box is purely cosmetic: add some new fonts.

The default set of linux fonts in the Debian distro are not very nice. The best sans font that I’ve found over the years that suits me, is Aller. These can be downloaded and installed directly.

That then leaves the the monospaced font. On Windows the best, in my opinion, is Consolas. Due to licensing, the best free alternative that looks similar is Inconsolata. This can be added via the Synaptic package manager.

The desktop now looks like this:

Which is much better than before. After that it is just a case of updating the fonts used in KDevelop

In no particular order, the following packages have also been installed:

• git
• g++
• gcc
• gnu make
• cmake

# C++ 11 Part 2: Going Native 2012 and Practical Experience

The Going Native Conference has now been and gone but some of the videos are now online.

So much of C++11 seems like C# 4.0, however C++11 pre-dates C# as much of it had been submitted to the standards body since C++98, and pre-dates C# 4.0. What is nice is that C++ and C# (and Java) have used the experience in creating both languages to improve each other.

Now that I have some practical experience of writing C++11 using the VS11 Developer Preview, and GCC, the auto keyword is incredibly useful for reducing the verbosity of STL loops and the like. Additionally, lambda functions are also really nice to use.

Compare:

for (vector<int>::iterator i=v.begin(); i != v.end(); ++i)
{
total += *i;
}


versus:

for (auto d : v) { total += d; }


in C++11 (or auto & to get the reference to the item in the collection). C++11 is so much nicer.

And as Herb says, always use make_shared and add your own cbegin and cend (for the time being). If you watch one of these videos, watch Herb’s.

# A XAML-Only Font ComboBox

I needed a simple ComboBox to select a FontFamily in a WPF application (I don’t care about the font-weight). After some searching I found Pete O’Hanlon’s article, describing what I wanted.

So why another (short!) article? The first commenter in the article suggested this:

<ListBox ItemsSource="{Binding Source={x:Static Member=Fonts.SystemFontFamilies}}">
<ListBox.ItemTemplate>
<DataTemplate>
<Label FontFamily="{Binding .}" Content="{Binding Source}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>


as an alternative, which made me think about combining the two as a pure XAML solution that you can cut and paste (as Pete’s code has a tiny bit of code-behind). In order to create the XAML solution I found out a few interesting things that I thought I would share in a real example (as I’m still getting to grips with the many facets of WPF).

## Show Me The XAML!

Here it is, in its entirety:

    <ComboBox
xmlns:ComponentModel="clr-namespace:System.ComponentModel;assembly=WindowsBase"
ItemTemplate="{DynamicResource FontTemplate}">
<ComboBox.Resources>

<CollectionViewSource x:Key="myFonts" Source="{Binding Source={x:Static Fonts.SystemFontFamilies}}">
<CollectionViewSource.SortDescriptions>
<ComponentModel:SortDescription PropertyName="Source" />
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>

<Style x:Key="FontStyle">
<Setter Property="Control.FontFamily" Value="{Binding Source}" />
<Setter Property="Control.FontSize" Value="16" />
</Style>

<DataTemplate x:Key="FontTemplate">
<StackPanel VirtualizingStackPanel.IsVirtualizing="True">
<TextBlock Style="{StaticResource FontStyle}"
Text="{Binding Source}"
ToolTip="{Binding Source}" />
</StackPanel>
</DataTemplate>

</ComboBox.Resources>

<ComboBox.ItemsSource>
<Binding Source="{StaticResource myFonts}" />
</ComboBox.ItemsSource>
</ComboBox>


You should be able to cut’n'paste this directly into your code. You would then bind the ComboBox‘s SelectedValue to a property of your choice. The SelectedValue is of type System.Windows.Media.FontFamily.

## What is Going On?

There are several things going on that we need to describe. Beware! More verbose XAML!

### A Sorted List of Fonts

Skipping directly to the ComboBox.Resources section: we get the full collection of system fonts. However, by default they only come partially sorted (by FamilyName), so we sort them into our own collection called myFonts. We do this by importing the ComponentModel namespace via this XAML markup:

xmlns:ComponentModel="clr-namespace:System.ComponentModel;assembly=WindowsBase"


and then create our own collections sorted by the Source property (which is the font family name):

<CollectionViewSource x:Key="myFonts" Source="{Binding Source={x:Static Fonts.SystemFontFamilies}}">
<CollectionViewSource.SortDescriptions>
<ComponentModel:SortDescription PropertyName="Source" />
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>


### Data Template

We declare a simple template that renders the fonts in their own type face, and provides a tooltip, within the ComboBox.

### Static Resources

Lastly we bind the ComboBox.ItemsSource to our sorted collection of fonts, myFonts using the long-hand XAML binding. Why do we do this last, and not directly as a ComboBox attribute?

The ItemsSource attribute requires that it is bound to a static resource. Suppose we do this:

    <ComboBox
xmlns:ComponentModel="clr-namespace:System.ComponentModel;assembly=WindowsBase"
ItemTemplate="{DynamicResource FontTemplate}"
ItemsSource="{Binding Source={StaticResource myFonts}}">


We get an exception thrown:

“Cannot find resource named ‘myFonts’. Resource names are case sensitive.”

as myFonts has not yet been declared.”

We could of course move our font collection to the UserControl/Window/Application Resources section, however in this example we only have one font combo box, so it is nice to have it within the ComboBox.Resources section.

You might also try setting the ItemsSource to reference myFonts dynamically, via:

    <ComboBox
xmlns:ComponentModel="clr-namespace:System.ComponentModel;assembly=WindowsBase"
ItemTemplate="{DynamicResource FontTemplate}"
ItemsSource="{Binding Source={DynamicResource myFonts}}">


This also fails with the exception:

“A ‘DynamicResourceExtension’ cannot be set on the ‘Source’ property of type ‘Binding’. A ‘DynamicResourceExtension’ can only be set on a DependencyProperty of a DependencyObject.”

So in answer to our question: as XAML has a ‘one-pass compiler’, a StaticResource has to be declared lexically before it is referenced: if we declare the binding last, then we can create our sorted list of fonts StaticResource, within ComboBox.Resources, and then bind to it within the XAML of the ComboBox, hence this piece of XAML:

<ComboBox.ItemsSource>
<Binding Source="{StaticResource myFonts}" />
</ComboBox.ItemsSource>


## Using This XAML Snippet.

As mentioned above, if you intending on using this XAML (and using the font combobox multiple times), move the sorted font collection:

<CollectionViewSource x:Key="myFonts" Source="{Binding Source={x:Static Fonts.SystemFontFamilies}}">
...
</CollectionViewSource>


into your ‘Application/Window/UserControlResources section, and put this attribute:

xmlns:ComponentModel="clr-namespace:System.ComponentModel;assembly=WindowsBase"


into the corresponding XAML document root.

## A Final Word on Safe Font Usage.

Never, ever, choose Comic Sans. Ever.

Cross posted to Code Project

# Configuring Debian Under Virtual Box Part 1

## Adding a Custom Screen Resolution

I am running Gnome 2.4 on Debian, and it’s been a while since I’ve hacked an xorg.conf file. So long in fact, that you don’t need to do that any more: you now use xrandr.

Firstly start an xterm as root, and type xrandr:

root@debian:/home/me# xrandr
Screen 0: minimum 64 x 64, current 1920 x 1200, maximum 32000 x 32000
VBOX1 connected 1920x1200+0+0 0mm x 0mm
1920x1200      60.0*+
1680x1050      60.0
1600x1024      60.2
1400x1050      60.0
1280x1024      60.0
1440x900       59.9
1280x960       60.0
1360x768       59.8
1152x864       60.0
1024x768       60.0
800x600        60.3
640x480        59.9
1920x1200_60.00   59.9


Note the VBOX“ that’s the output adaptor for the Virtual Box video.

Next run cvt:

root@debian:/home/me# cvt -h

usage: cvt [-v|--verbose] [-r|--reduced] X Y [refresh]

-r|--reduced : Create a mode with reduced blanking (default: normal blanking).
X : Desired horizontal resolution (multiple of 8, required).
Y : Desired vertical resolution (required).
refresh : Desired refresh rate (default: 60.0Hz).

Calculates VESA CVT (Coordinated Video Timing) modelines for use with X.


So we want to add a custom mode for 1920×1200 pixels:

root@debian:/home/me# cvt 1920 1200
# 1920x1200 59.88 Hz (CVT 2.30MA) hsync: 74.56 kHz; pclk: 193.25 MHz
Modeline "1920x1200_60.00"  193.25  1920 2056 2256 2592  1200 1203 1209 1245 -hsync +vsync


Then finally, these are the commands that we want to execute in a root xterm to change the screen resolution:

xrandr --newmode "1920x1200_60.00"  193.25  1920 2056 2256 2592  1200 1203 1209 1245 -hsync +vsync

xrandr --output VBOX1 --mode 1920x1200_60.00


However this is only temporary, so we need to add it to Gnome’s start up configuration;

Edit /etc/gdm3/Init/Default, and add the above three lines immeadiately near the top, e.g.:

#!/bin/sh
# Stolen from the debian kdm setup, aren't I sneaky
# Plus a lot of fun stuff added
#  -George

PATH="/usr/bin:$PATH" OLD_IFS=$IFS

#
xrandr --newmode "1920x1200_60.00"  193.25  1920 2056 2256 2592  1200 1203 1209 1245 -hsync +vsync