Wednesday, 10 October 2012

Caller Information Attributes

Version 4.5 of the .Net framework introduces 3 new attributes in the System.Runtime.Compiler namespace. These are CallerFilePathAttributeCallerLineNumberAttribute and CallerMemberNameAttribute. They are used to obtain information about the caller to a method, and are handy for tracing call flow for diagnostics. The CallerMemberNameAttribute is also particularly useful when calling a PropertyChanged method, if your class implements INotifyPropertyChanged.

A quick code example shows the usage ( all code here is available as a GitHub:Gist)
The output from this demo is:
The new attributes are at lines 20, 21 and 22 of the code. As you can see in the example, to use one of the attributes, it must be used to decorate an optional parameter on a method - the parameter will be set to the correct value at runtime.

INotifyPropertyChanged Usage

One major benefit of the CallerMemberNameAttribute is in a class that implements the INotifyPropertyChanged interface. This interface has an event in the form of PropertyChanged(string propertyName), and will be called from each property's setter method when the value changes. This leads to a lot of magic strings in code, for example:
This brittle code can be avoided by using the attribute like this:

What members does it work with?

As well as methods, properties and events, the attributes will work for these member types:
  • Constructor, value is ".ctor
  • Explicit conversion operator, value is "op_Explicit"
  • Implicit conversion operator, value is "op_Implicit"
  • Indexer, value is "Item"
  • Operator overload, value is e.g. "op_Addition"
  • Finaliser, value is "Finalize"

Where does the info come from?

The attributes work by inspecting the IL of the calling code. For instance, the IL for the Main() method of my first example contains these items of info:

As I said before, all code here is available as a GitHub:Gist

Monday, 1 October 2012

Simple Breakpoint Options in VS2012

When you create a breakpoint in Visual Studio 2012, you have certain options available that determine exactly when the debugger breaks and what happens when it does. These options are available via the Breakpoints window (Debug -> Windows -> Breakpoints, or Alt+F9)...

...or by right-clicking the breakpoint:
I'll go through the first few of these menu options and describe its use.

Delete Breakpoint

No surprises here; selecting this menu item has the same effect as hitting F9. It deletes the breakpoint.

Disable Breakpoint

This option disables the breakpoint, so Visual Studio won't break at this breakpoint until it is enabled.

Location...

This shows a window that allows the code location of the breakpoint to be edited:
This is useful if e.g. you have multiple code statements on the same line; it allows you to set a breakpoint on a specific statement, by selecting the character position of a character in the required statement (note, this can also be achieved by selecting the statement and hitting F9) :
The screen gives the option to Allow the source code to be different from the original version. When this option is selected, if the source file of a debugged library has changed from the version referenced, the debugger will still allow the referenced version to be debugged.

Condition...

This shows a window that allows you to change the condition that must be satisfied before the debugger stops the code at the breakpoint:
The condition can be set to Is true, i.e. when the condition is met, or Has changed, i.e. when the specified variable or expression evaluates to a new value.
The example above sets the breakpoint to break when the variable loopCounter is equal to 719 0r 725:

Hit Count...

This shows a window that allow you to specify the number of times the breakpoint needs to be hit before the debugger breaks:
The default for a breakpoint is for it to break every time the statement is reached. Other options allow you to specify a numeric value that is used to calculate whether the debugger should break:
This example causes the debugger to break when the statement has been hit 183 times:
While the debugger is paused at the breakpoint, opening the Hit Count window shows the current hit count, and allows you to reset it so that the count starts again from zero.


Sunday, 16 September 2012

Custom Key Combinations for Swapping Windows Keyboard Language

Occasionally I pair program with a developer who uses a Mac keyboard with his Windows machine. In order to use the Mac keyboard accurately, his default keyboard language is English (US). Although there's also a regular UK windows keyboard plugged in and ready to use, it requires time and effort to navigate the mouse to the language bar and swap to UK layout. This breaks the flow required to successfully pair program.

Good news - the language bar allows keyboard shortcuts to switch between languages. The default key combination SHIFT + LEFT ALT will loop through all the installed keyboard languages, in this instance toggling between US and UK keyboard layouts. But you can also set key combinations that will jump to a specific language.

From the Control Panel or the Start Menu, open the Region and Language settings page, navigate to the Keyboards and Languages tab and click the "Change keyboards" button:
On the Advanced Key Settings tab of the keyboards form, you can see the current settings for keyboard shortcuts:
To set up a shortcut combination to jump to a specific language, select the language (in the above case, English (UK), and click the Change Key Sequence button. This shows the following dialog box which can be used to define the keystroke required to jump directly to that keyboard language:

Thursday, 13 September 2012

Treat Warnings as Errors: Exclude specifics warnings

As every Visual Studio user knows, you should build your project with the "Treat warnings as errors" switched on. This gives you very quick feedback when your project has problems that could otherwise get ignored.

This setting is toggled on the Build tab of the project's properties page:

As it says on the tin, this causes any problem that would normally be reported as a warning to be reported as an error, and prevent the project building:

If there are warnings that you don't want to break your build, you can suppress them specifically. You'll need the warning number, which will be reported in the Output window:

This number, without the CS prefix, needs to be entered in the "Suppress warnings" box, on the Build tab. Multiple warnings can be suppressed, by separating multiple warning codes with a comma.

Victory!

Alternatively, you can use a #pragma compiler directive in the code to suppress your warning:



Sunday, 2 September 2012

Double Buffering Windows DataGridView

Years ago I wrote a WinForms application, that I still use every day. I tinker with the source code pretty much every day too. One of my recent issues to address was the rendering speed of the DataGridView controls; they'd take, roughly, forever to display around 30 items.

I did what I could think of to speed up the rendering (mainly around optimising data access) but couldn't get the rendering time down. Then I Googled it, and it appears that I'm not the first developer to have this problem; the DataGridView is notoriously slow to render. The annoying part is that the problem is so easy to fix - set the grid's DoubleBuffered property on.

This property is protected, so you need to either use Reflection to set it on your grid instance, or create a specialised DataViewGrid. I created a DoubleBufferedDataGridView:

When I use this in place of the DataGridView, the results are pretty good. A test app shows the time taken (ms) to render a sample datasource of 16 items on a standard DataGridView, versus a DoubleBufferedDataGridView.

It's so easy to fix, it seems odd that DoubleBuffered is not set to true by default, but hey.
The code for the sample form above is available as a GitGist

Saturday, 25 August 2012

Project Template Locations in VS2012

Adding a Project Template 

If you've seen my post on creating a console application in VS Express 2012 for Web, you'll be thinking "why doesn't he create a template?" Well I did, via the Export Template Wizard in visual studio (File -> Export Template...)

This wizard creates a zip file of all the items in the current project. When this is copied to the correct location on your machine, it can be used to create a new project with all your previous goodness. The location to copy it to is [Visual Studio 2012 folder]\Templates\ProjectTemplates\Visual C# or[Visual Studio 2012 folder]\Templates\ProjectTemplates\Visual Basic

This allows you to select your template in the New Project dialog box

Specifying the Project Type


If you want the template to appear under one of the project types, e.g. Windows, put the .zip file into a directory of that name, e.g. [Visual Studio 2012 folder]\Templates\ProjectTemplates\Visual C#\Windows

Can I Have it in Both?

If you want it in both locations, Visual C# and Windows, you need to edit your template. Open the .zip file and there'll be a .vstemplate file; this is the definition of the project template. You need to add an element NumberOfParentCategoriesToRollUp. This tells VS to show the template in the project subtype (Windows) and its parent (Visual C#). Here's an example:

Creating a Console App in Visual Studio Express 2012 for Web

I've installed and am using Visual Studio Express 2012 for Web as my primary IDE for C#. There isn't a template for a console application, so if you want 1980s goodness, create a new class library and on the Properties page, setting Output Type to Console Application, like this

This then allows you to create a class with a Main method

and run the app with a push of F5

**UPDATE** I have created a project template that creates a console application, it's available on github, here with instructions on how to install it.