Pablo Picasso
"Computers are useless. They can only give you answers."
My Latest Tweets
Tags

This will be shown to users with no Flash or Javascript.
Calendar
<<  September 2010  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910
Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

Sign in

So Visual Studio 2010 has this cool new feature called Reference Highlighting. If you don’t know anything about it yet, go and read the excellent Visual Studio Tips & Tricks blog to find out how to use it. What Zain Nabousi’s post doesn’t say however is that you can also customize the color of the highlighted symbols:

  1. Go to Tools > Options > Fonts and Colors.
  2. Select Text Editor in the Show settings for dropdown.
  3. Select Highlighted Reference from the Display items list.
  4. Change the item foreground and background to your preferred colors.

Reference Highlighting

Now when the cursor is place on a field for example, all references are highlighted as shown below and you can navigate between them using Ctrl + Shift + Down/Up Arrows.Visual Studio highlighted referenceNote that to remove the highlight, you need to move the cursor away from the field.

ReSharper has had a similar functionality since as far as I can remember - that is since at least version 3. To activate it press Shift + Alt + F11 and use Ctrl + Alt + Page Up/Down to move between the highlighted references. But, as usual, ReSharper goes one step further by highlighting where the symbol is being used (blue by default) or set (pink by default). ReSharper also places a coloured and clickable marker in the vertical margin that corresponds to the symbol’s usage within the file. To remove the highlighting simply Escape.ReSharper highlighted referenceThat’s it!

In my previous post, I showed how you could use a T4 template within Visual Studio to generate a C# ImageLibrary class based on a WPF file called ImageResources.xaml.

If you want to do something similar but the resource file is not in the same folder as the template, you should refer to it using its relative path.

First set the hostspecific attribute to true in the template directive:

 <#@ template debug="false" hostspecific="true" language="C#" #>

Then use the code snippet below (in my example, the ImageResources.xaml file is one level up in a folder called Resources) to work out the absolute file path:

string root = Host.ResolvePath(string.Empty); 
string relativePath = @"..\Resources\ImageResources.xaml";

string filePath = Path.Combine(root, relativePath);

You can now start reading the file from within your T4 template and extract the information required for auto-generating the code.

A couple of weeks ago, I started getting a VerificationException on a newly created unit test project which had already a bunch of tests in it. The full message was:

method [TEST_METHOD_NAME] threw exception. System.Security.VerificationException: Operation could destabilize the runtime.

For the story, my work project is currently using MSTest, VS2010 RC1 and targets .NET 4.

Heading straight to MSDN for more details, I got the following information:

"The exception that is thrown when the security policy requires code to be type safe and the verification process is unable to verify that the code is type safe".

I don't know about you but this didn't give me much clue about who/what exactly was causing that error. This was rather puzzling as thus far the tests were running perfectly well on my local Dev environment and on the build server. What I noticed however was that switching code coverage on seemed to cause this error to crop up. Since code coverage is a must have, I had to find a way of resolving this.

Another MSDN entry Troubleshooting Exceptions: System.Security.VerificationException looked promising. The only thing that it suggested though was to ensure that the “application is not loading two conflicting versions of a class library”. I couldn't really imagine this to be the reason the VerificationException was thrown as without code coverage it all worked fine on exactly the same code base and environments. No code coverage, no problem; code coverage on, tests aborted!

So my next step was to identify the project and the assembly that was triggering the exception. After a while I managed to track this down to one of the solution's project that was reusing some libraries written against previous versions of the .NET Framework. They in turn were referencing the System.Configuration v2 assembly. My first thought was to add a binding redirect in the configuration file as shown below:

<configuration>
...
   <runtime>
      <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
         <dependentAssembly>
            <assemblyIdentity name="System.Configuration" publicKeyToken="B03F5F7F11D50A3A" culture="neutral"/>
            <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0"/>
         </dependentAssembly>
      </assemblyBinding>
   </runtime>
...
</configuration> 

Unfortunately MSTest would still refuse to run the tests under code coverage. I then recalled some 'trust' issues I had in the past with System.Configuration on a .NET 3.5 application. More specifically this assembly requires full trust from the calling assembly otherwise a security exception is thrown. Here is an excerpt from an MSDN article that mattered to me:

There is no programmatic way for partially trusted code to call a library that does not have the AllowPartiallyTrustedCallersAttribute. If an application does not receive full trust by default, an administrator must choose to modify security policy and grant the application full trust before it can call such a library.

Only a few .NET Framework libraries installed in the GAC will allow partially trusted callers and System.Configuration is not one of them! So marking the assembly with the AllowPartiallyTrustedCallers attribute (APTCA) would not work (*).

[assembly: AllowPartiallyTrustedCallers(PartialTrustVisibilityLevel = PartialTrustVisibilityLevel.VisibleToAllHosts)] 

I could only conclude from the above that MSTest Code Coverage - presumably through the vshost.exe process? - was not, for reasons I still don't know, fully trusted and did not therefore have the right set of permissions to instrument the code. In the 'old' days of CAS (Code Access Security), I might have been able to apply an assembly level attribute in the AssemblyInfo.cs file to circumvent that with a SkipVerification permission request which tells the CLR to skip the type safety verification that happens during JIT compilation:

[assembly: SecurityPermission(SecurityAction.RequestMinimum, UnmanagedCode = true, SkipVerification = true, Execution = true)] 

But .NET 4 has changed all of that (Security Changes in the .NET Framework 4). Security policy decisions are now handed over to the host and managed desktop applications run automatically with full trust, leaving system administrators the responsibility of managing permissions at the operating system level. More importantly CAS policy has been disabled by default and is no longer the 'preferred security supplier'. This also means that the SecurityAction.RequestMinimum and others are now obsolete. Visual Studio will display a friendly warning when you add it:

SecurityAction.RequestMinimum Note that you can re-enable CAS in your configuration file as shown below:

<configuration>
...
   <runtime>
      <NetFx40_LegacySecurityPolicy enabled="true" />
   </runtime>
...
</configuration> 

However since I've always found CAS confusing and rather difficult to grok, it's not an avenue I wanted to even explore.

After some further reading (**) on the new security model in .NET 4 and in particular a short post on the .NET Security Blog Transparency Models: A tale of two levels, it dawned on me that what was required was to apply the level 1 rule set to my .NET 4 assembly calling the .NET 2 code. Level 1 corresponds to the security transparency model baked in the CLR v2 and effectively allows for backward compatibility with .NET 4. Level 2 is the model that comes with the .NET 4 CLR.

The follow-up post Differences Between the Security Rule Sets describes the effect of the APTCA attribute as follows:

Allows partial trusted callers access to the assembly by removing an implicit link demand for full trust on all code in signed assemblies.

I therefore added the explicit attribute below in my AssemblyInfo.cs file:

using System.Security; 

[assembly: SecurityRules(SecurityRuleSet.Level1)] 

Although the application I am working on is for internal use only and I probably could have left it at that, I decided to surround the SecurityRules attribute with a ‘COVERAGE’ conditional compilation symbol as I still want to be warned of any other potential issues.

using System.Security; 

#if COVERAGE 

[assembly: SecurityRules(SecurityRuleSet.Level1)] 

#endif

After that all my tests were passing with code coverage enabled. Result!

I don't know for sure whether my diagnosis is even close to being 50% correct as I honestly can’t say I fully understand .NET security. Not as much as I should do anyway. Like a majority of Devs, I suspect, I develop most of the time in a fully trusted environment with Admin privileges. I only had to worry about CAS on a few rare occasions. I know, I can hear some say “develop with a user account instead” but let's face it there is a reason most programmers don't: it’s hard and really a pain in the @~!#$. That could also be part of the reason CAS is being superseded.

At least this experience gave me an opportunity to start learning about .NET 4 security and being more aware of potential issues when developing a mixed solution with assemblies compiled against different versions of the framework. Hopefully this might also help some other people who are facing the same problem.

For now I need to return to my tests and get that code coverage back up to an acceptable level. Until next time,

Happy Programming!

(*)  You can find more details on Allowing Partially Trusted Callers.
(**) For a good introductory article on the new security model, check out Exploring the .NET Framework 4 Security Model.

Today my colleague Rob pointed out to me that enabling Code Analysis (aka FxCop) on our solution was slowing down the build time on his machine to a rather unacceptable level. After some very unscientific perf testing, watch in hand, we saw the build time increase by more than 20 seconds with code analysis turned on. Rob therefore asked me whether there was a way we could bypass it – apart from disabling code analysis altogether which is not something we were willing to consider. The only thing I could suggest was to run the solution build out-of-proc using an ‘old’ trick I’ve applied for quite a while to VS2008, courtesy of Scott Hanselman’s Parallel MSBuilds from within the Visual Studio IDE. As we have moved over to VS2010, here is how I adapted it on my machine.

  1. Go to Tools > External Tools…
  2. Click on Add
  3. Fill in the following details:
  • Title: Parallel Build
  • Command: C:\Windows\Microsoft.NET\Framework\v4.0.30128\MSBuild.exe
  • Arguments: /m $(SolutionFileName) /v:m /t:Rebuild /p:Configuration=Debug
  • Initial directory: $(SolutionDir)

The arguments break down is as follows:

/m Switch that allows projects to be built in parallel.
/v:m Specifies the verbosity level for logging - q[uiet], m[inimal], n[ormal], d[etailed], and diag[nostic].
/t:Rebuild Forces a solution cleanup and then a full rebuild.
/p:Configuration=Debug Sets the solution configuration to build for.

 External Tools

Moments later, Rob came back with an answer to our original problem with Code Analysis. As it happens, all that is required is an extra property at the end of the arguments list as shown below:

/m $(SolutionFileName) /v:m /t:Rebuild
/p:Configuration=Debug /p:RunCodeAnalysis=False

After that all we had to do was to bind the new external command to a keyboard shortcut to give us the flexibility of a faster build and hopefully save us a lot of compile time in the long run.

A lot of Developers who have never seen ReSharper in action often do not appreciate how much more productive they could be if they would start using it. Their arguments for not trying it out usually ranges from “I don't want to rely on a tool to do my coding” to “Why should I use R# when Visual Studio is already doing most of what I want/need” or “I don't like R# telling me what to do”. While these can be easily refuted, I think the main issue is that learning the tool itself can be a bit daunting at first. There are a lot of shortcuts to remember, options to set and functionality to digest. It also means adapting the way you work with the IDE and unlearn some old habits.

So if you are one of these reluctant Developers or just want to become a R# Jedi but don't know where to start, here is my advice: Learn the three shortcuts that rule them all... and the rest will follow!

1. Navigation

Navigation shortcut Navigation options

 

2. Code Generation

 Code generation shortcut Code generation options

3. Refactoring

 Refactoring shortcutRefactoring options

Note that all the options displayed are context sensitive and depend on where the caret is placed. Hence you will get different menu items based on whether your cursor is on a class, a method, etc.

I have been coding with ReSharper since version 3.0 and I simply can't work without it. It is IMO a must-have productivity tool and because of that I have encouraged any .NET Developer I work with to start exploring its capabilities by learning these three shortcuts. So far none of them have gone back to using plain vanilla Visual Studio. Hopefully if you break down the learning curve this way, you will also reap the benefits of what some people have called “the best IDE for Visual Studio”!

…Bonus Shortcuts: Go to type and Go to file.

Search shortcuts

Some time ago, while reinstalling StyleCop for ReSharper, I had to restart Visual Studio in order to reload the add-in. I then realised that restarting VS actually requires quite a lot of ‘clicking’ around. First you have to exit the editor, then you need to launch Visual Studio again and finally you have to re-open the solution you were working on just before you closed the IDE. This did not seem very efficient and, a quick macro later, I had a way to restart VS easily with one single click.

Public Sub RestartVisualStudio()
    Dim solution As String = DTE.Solution.FullName
    DTE.Solution.Close(True)
 
    If String.IsNullOrEmpty(solution) Then
        solution = String.Empty
    Else
        solution = """ """ & solution
    End If
 
    Dim process As System.Diagnostics.Process = New System.Diagnostics.Process()
    Dim arguments As String = "/c start """" /high """ & DTE.FullName & solution & """ /nosplash"
    process.StartInfo = New ProcessStartInfo("cmd.exe", arguments)
    process.StartInfo.UseShellExecute = False
    process.StartInfo.CreateNoWindow = True
    process.Start()
 
    DTE.Quit()
End Sub

As restarting VS is not something I do that often, I just added a restart button on my custom toolbar.

Restart Visual Studio

Ok. I promise this is my last post on Visual Studio macros… for 2009 :)

In my previous post I mentioned that I  usually work in full screen mode with all the toolbars removed to maximise the amount of code I can see on the screen. To activate full screen mode I just type Shift + Alt + Enter. Note that you can also squeeze in that little extra space by disabling the scrollbars under Tools > Options > Text Editor.

Visual Studio scrollbars options

However after you’ve built your solution, tracked a file within Solution Explorer and inspected a class using the ReSharper File Structure window, you end up with a fairly ‘dirty’ screen.

Visual Studio dirty full screen

All that viewing space is now lost! One solution is to set all the windows to ‘Auto Hide’. However since I find this feature rather annoying (in most cases) I tend to pin down all my working windows and therefore I need another way to recover that viewing space. As usual a small macro can do the trick. The macro below simply closes any active tool window that is currently opened.

Public Sub CloseAllToolWindows()
	Dim items As EnvDTE.Windows = DTE.Windows
	Dim item As Window

	For Each item In items
		If item.Kind.Equals("Tool") And item.Visible Then
			item.Close()
		End If
	Next
End Sub

 

Once bound to a keyboard shortcut, Alt + S in my case, I can run it and enjoy my full screen again!

Full Screen Mode

As I tend to work mainly in full screen mode within Visual Studio with all toolbars closed, I use shortcuts quite extensively to execute standard IDE and ReSharper commands. Fortunately most commands already have shortcuts associated to them. However there are a few that I need to either map to new shortcuts or rebind to different key combination.

Below are my custom keyboard mappings:

Command Shortcut
Build.BuildSelection Shift + F6
Edit.LineOpenAbove Shift + Enter
Edit.ToggleWordWrap Alt + W
File.CloseAllButThis Ctrl + \
Macros.MyMacros.TBF.CloseAllToolWindows Alt + S
Macros.MyMacros.TBF.DecreaseTextEditorFontSize Alt + [
Macros.MyMacros.TBF.IncreaseTextEditorFontSize Alt + ]
Macros.MyMacros.TBF.RemoveRegions Ctrl + Shift + #
ReSharper.CollapseInSolutionExplorerAction Ctrl + `
ReSharper.Generate Alt + I
ReSharper.GotoNextErrorInSolution Alt + 0
ReSharper.MoveDown Ctrl + Left Windows, Ctrl + Down Arrow
ReSharper.MoveLeft Ctrl + Left Windows, Ctrl + Left Arrow
ReSharper.MoveRight Ctrl + Left Windows, Ctrl + Right Arrow
ReSharper.MoveUp Ctrl + Left Windows, Ctrl + Up Arrow
TestDriven.NET.RunTests F8
TestDriven.NET.RerunTests Shift + F8

 

To change your keyboard binding in Visual Studio, follow the steps below:

  1. Go to Tools > Options > Keyboard.
  2. Select the command you would like to bind to (e.g. Macros.Samples.Accessibility.DecreaseTextEditorFondSize).
  3. Select Text Editor or Global where appropriate.
  4. Enter your shortcut key (e.g. Alt + [).
  5. Click on Assign.

 Decrease text font size key binding

Once you’ve assigned all your keyboard shortcuts simply click OK and you’re done!

As I was running a macro to increase or decrease the text font size (see previous post), I noticed that the macro balloon kept on flashing in the system tray. The reason for this is that in Visual Studio 2008, a balloon tip is shown every time you run a macro, until you click on it 5 times that is. Thereafter it will be no longer visible. The problem is that your macro might be running too quickly, giving you no time to click on it. For some background on this and why it is behaving like this by design, read Stopping the “Click here balloon” by Craig Skibo.

macro_balloon  

While I sort of understand why the VS team did this, I actually don’t care much for this feature. So I thought I’ll disable it altogether. This is easily done by adding a new registry key (HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0\DontShowMacrosBalloon) and setting its value to 6. Note that you will still see the spinning cassette icon in the system tray but this is a lot less intrusive.

Instead of doing this manually I wrote a macro to disable this feature as otherwise I’ll probably forget I ever done this.

' Suppresses the macros balloon.
Public Sub DontShowMacrosBalloon()
	Dim key As Microsoft.Win32.Registry Key
	Dim subKey As Microsoft.Win32.Registry Key

	key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\Microsoft\VisualStudio\9.0", True)
	If (Not key Is Nothing) Then
		subKey = IIf(key.OpenSubKey("DontShowMacrosBalloon") Is Nothing, key.CreateSubKey("DontShowMacrosBalloon"), key.OpenSubKey("DontShowMacrosBalloon"))
		key.SetValue("DontShowMacrosBalloon", "00000006", Microsoft.Win32.RegistryValueKind.DWord)
		subKey.Close()
		key.Close()
	End If
End Sub

Should you ever want to re-enable it, simply delete the registry key or run the macro below:

' Enables the macros balloon simply by deleting the key
Public Sub ShowMacrosBalloon()
	Dim key As Microsoft.Win32.RegistryKey

	key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\Microsoft\VisualStudio\9.0", True)
	If (Not key Is Nothing) Then
		key.DeleteValue("DontShowMacrosBalloon", False)
		key.Close()
	End If
End Sub

Warning
The macros above modify the Registry and therefore the usual precautions apply.

The other day I grew increasingly frustrated with the amount of code I could or rather couldn’t see on my screen at work, even when working in full screen mode. I therefore wanted to write a Visual Studio macro to zoom in and out of the text editor. However while browsing through the sample macros that come with Visual Studio 2008, I found two macros that are doing just what I wanted: DecreaseTextEditorFontSize and IncreaseTextEditorFontSize. To check whether they are installed on your machine, simply go to Tools > Macros > Macro Explorer or type in ALT + F8 and then drill down to Macros > Accessibility.

Macro Explorer: Decrease Increase Text Editor Font Size 

Here is the Visual Basic code (after I changed fontSizeIncrement from 2 to 1):

' Set the font size increment and minimum font size
Private Const fontSizeIncrement As Integer = 1
Private Const minimumSupportedEditorSize As Integer = 3

' Increases the font size used within the editor.
Public Sub IncreaseTextEditorFontSize()
	Dim textEditorFontsAndColors As Properties

	textEditorFontsAndColors = DTE.Properties(“FontsAndColors”, “TextEditor”)
	textEditorFontsAndColors.Item(“FontSize”).Value += fontSizeIncrement
End Sub

' Decreases the font size used within the editor.
Public Sub DecreaseTextEditorFontSize()
	Dim textEditorFontsAndColors As Properties
	Dim fontSize As [Property]

	textEditorFontsAndColors = DTE.Properties(“FontsAndColors”, “TextEditor”)
	fontSize = textEditorFontsAndColors.Item(“FontSize”)
	If fontSize.Value >= minimumSupportedEditorSize Then
		fontSize.Value -= fontSizeIncrement
	End If
End Sub

If you don’t have the Visual Studio samples, follow the steps below to add these two macros:

  1. Open the Macro IDE (Tools > Macros > Macro IDE or ALT + F11).
  2. In Project Explorer, right-click on My Macros and select Add New Item…
  3. In the Add New Item… dialog, choose Module, give it a name (e.g. MyModule) and click Add.
  4. Simply copy and paste the code above in the newly added module.
  5. Save and close the Macro IDE.

 Add new module

All I had to do after that was to bind these macros to a keyboard shortcut. I chose ALT + [ to decrease the text font size and ALT + ] to increase it.

 Decrease text font size key binding

Now, I can easily zoom code in and out in the Visual Studio Text Editor.