Archive for April, 2011

Friendly visual studio solution names for working with multiple branches

April 29th, 2011 7 comments

If you have the latest version of the Visual Studio 2010 extension VSCommands you can give your solutions friendly names that display in the window’s title bar.  This is nice when you are working in different branches, so that you can differentiate which solution you are actually looking at.  I wrote the following regex to put the Branch Name after the Solution name, so for example if you have the client solution open in both Dev and Release, one will be called “Client.sln – Dev” and the other “Client.sln – Release”.

To use this, in Visual Studio go to Tools -> Options -> VSCommands 2010-> IDE Enhancements and then paste in the following (without the quotes):

Friendly Name: “{solutionName} – {branchName}”

Friendly Name – Solution Path Regex: “.*\(?<branchName>.*)\(?<solutionName>.*(?:.sln))”



Happy coding!

— Update —

Here is the new regex that I prefer to use instead now which shows the directories that the solution is sitting in:

Friendly Name: “{solutionName} – {dir1}{dir2}{dir3}”

Regex: “.*\(?<dir1>.*)\(?<dir2>.*)\(?<dir3>.*)\(?<solutionName>.*(.sln)Z)”

— Update 2 for VS 2012 —

These are the settings that I like to use for VS Commands 11 for VS 2012:

Branch Name Regex: “.*\(?<dir1>.*)\(?<dir2>.*)\(?<branchDirectoryName>.*)\(?<solutionFileName>.*(.sln)Z)”

Branch Name Pattern: “{branchDirectoryName} Branch”

Git Branch Name Pattern: “{git:head} Branch”

Main Window Title Pattern: “{solutionFileName} – {dir1}{dir2}{branchDirectoryName} ({sln:activeConfig}|{sln:activePlatform})”

Solution Explorer Window Title Pattern: “ – {solutionFileName} • {vsc:branchName}”

TFS GoToWorkItem VS command and keyboard shortcut

April 29th, 2011 No comments

The button to jump directly to a work item by specifying its ID looks to be on the Work Item Tracking toolbar by default in VS / TFS 2010.  This button is not on the toolbar by default in VS / TFS 2008 though.  To add it yourself just go to Tools => Customize, then choose the category Team and the command Go To Work Item…, and you can drag the command into one of your existing toolbars.

If you want to setup a keyboard shortcut for the command, just go to Tools => Options => Environment => Keyboard, and the command is called Team.GotoWorkItem.  I map it to Ctrl+Shift+/ since Ctrl+/ is the C# keyboard shortcut to search in a file.

Solution won’t build on TFS Build Server

April 17th, 2011 1 comment

So if you are able to build (compile) the solution on your local machine, but it won’t build on the TFS build server and you are getting an error message similar to:

1 error(s), 1 warning(s)
$/TeamProject/Dev/RQ4/FBs/4.1.4_eSec/RQ4.Client.sln – 1 error(s), 1 warning(s), View Log File
IntegrationfrmGetIntegrationAuthorization.xaml.cs (1138): The type or namespace name ‘BillingFields’ could not be found (are you missing a using directive or an assembly reference?)
C:WindowsMicrosoft.NETFramework64v4.0.30319Microsoft.Common.targets (1360): Could not resolve this reference. Could not locate the assembly "IQ.Core.Resources, Version=, Culture=neutral, processorArchitecture=MSIL". Check to make sure the assembly exists on disk. If this reference is required by your code, you may get compilation errors.

Then the problem is likely one of the following:


1 – The project/dll being reference is set to "Specific Version", so open the reference’s properties and change it to "Any Version".


2 – The project is not set to be built under the specific configuration.  Right click on the solution in the Solution Explorer, and choose Configuration Manager.  All projects should be set to be build (i.e. have a checkmark), and all of their platforms should be set to the same value.  Change the Active Solution Platform to the platform you use and ensure that all projects are still set to always build.


3 – The path to the refenced project/dll is too long.  Windows/.NET has a limitation where the reference path cannot be more than 260 characters, and the directory it’s in cannot be more than 248 characters.  So the work around for this is usually to rename your build definition to something shorter, or if you just added a new project/namespace to the project, to shorten its name so the path stays under the limit.

Categories: Build, TFS Tags: , , , ,

Adding ValueChanged events to Dependency Objects in WPF

April 17th, 2011 No comments

You may be wondering which is the best way to hookup a DependencyProperty’s Callback event handler to handle Value Changed events.  The two methods to consider are:

Method 1 – Use static event hanlders, like so:

public virtual int SelectedID
	get { return (int)GetValue(SelectedIDProperty); }
	set { SetValue(SelectedIDProperty, value); }

public static readonly DependencyProperty SelectedIDProperty =
	DependencyProperty.Register("SelectedID", typeof(int), typeof(SelectorBase), 
                new PropertyMetadata(0, new PropertyChangedCallback(OnSelectedIDChanged)));

private static void OnSelectedIDChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
	// Perform event handler logic


Method 2 – Hookup event handler at initialize, and remove it during Dispose(), like so:

// Constructor
public SelectorBase()

private void HookupEventHandlers()
	TypeDescriptor.GetProperties(this)["SelectedID"].AddValueChanged(this, SelectedID_ValueChanged);

private void RemoveEventHandlers()
	TypeDescriptor.GetProperties(this)["SelectedID"].RemoveValueChanged(this, SelectedID_ValueChanged);

protected override void Dispose(bool isDisposing)
	// If managed resources should be released
	if (isDisposing)

public virtual int SelectedID
	get { return (int)GetValue(SelectedIDProperty); }
	set { SetValue(SelectedIDProperty, value); }

public static readonly DependencyProperty SelectedIDProperty =
	DependencyProperty.Register("SelectedID", typeof(int), typeof(SelectorBase), new PropertyMetadata(0));

private void SelectedID_ValueChanged(object sender, EventArgs e)
	// Perform event handler logic

So the advantage to using method 1 is that we have access to the property’s old and new values, we don’t have to worry about memory leaks (since the event handler is static), and if we create 100 instances of the control we still only have one static event handler in memory, instead of 100 local ones.  The disadvantage to method 1 is that these event handlers are going to exist in memory for the entire lifetime of the app, even if the view/control they are on is never referenced.

The advantage to using method 2 is that the event handlers only exist in memory if the view/control they are on is actually open.  The disadvantage is that we don’t have access to the property’s old value, and the developer has to remember to properly unhook the event in order to avoid a memory leak.

So method 1 is best suited to items that are used in many places (such as custom controls that may be plastered all of the place), while method 2 is best suited for views where there is likely to never be more than a few instances open at any given time, or in places that may not be accessed at all (e.g. a settings menu that is rarely accessed).

My WPF Binding won’t work. WTF!

April 17th, 2011 No comments

At one point or another I’m sure we’ve all been confused as to why our binding won’t work.  Here’s a couple things to keep in mind:

– have you set the DataContext to be the class containing the property you are binding to?  This can be done in XAML or in the code-behind.  For example, put "this.DataContext = this" in the code-behind file’s constructor.

– is the property you’re binding to public?  Also, it must be a property (with get; set; accessors), not a field (i.e. class variable).

– if you are using two way binding, do you have both a Get and Set accessor on the propery?

– if you are trying to set bindings on a usercontrol that you are placing on your form, you may have to set the DataContext in that control, or reference the property dynamically using something like:


  CanModifyAmount="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type src:WpfViewBase}},

Path=CashOutViewModel.CanModifyAmount, Mode=OneWay}"

  CashDetail="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type src:WpfViewBase}},

Path=CashOutViewModel.CashOutModel.CashOut.CashDetail, Mode=OneWay}"/>

If you still don’t know why your binding isn’t working, be sure to check the Output window in Visual Studio while debugging, as it will display any binding errors that occur and (hopefully) give you more information about the problem.  You can also change the level of verbosity that is displayed for Binding errors, so if you aren’t getting enough information, in Visual Studio go into Tools -> Options -> Debugging -> Output Window and make sure Data Binding is at least set to Warning.

If changes made to the UI propogate to the code-behind, but changes made in the code-behind don’t propogate to the UI, you will either need to use the INotifyPropertyChanged pattern, or implement your code-behind properties as DependencyProperties, in order to let the UI know that the value has been updated and show the change.

Categories: Binding, WPF Tags: , , ,

Setting focus to an element in WPF

April 17th, 2011 No comments

So if you are trying to set focus to a WPF element, but are unable to.  Here is a quick checklist to go through:

– is the control you are trying to set focus to Enabled, Visible, Loaded, and Focusable.  If any of these properties are false, you cannot set focus to the element.

If you are using Binding to set these properties, make sure the binding is firing before you are trying to set the focus.

– does the control that already has focus allow focus to be taken away? If the control that currently has focus overrides the PreviewLostFocus event, it can set e.Handled to true to prevent other controls from stealing focus from it.

If all of these conditions seem to be met, but you still cannot seem to set the focus to a control, is another operation moving focus from your control to another control after you set focus to your control?  From a dispatcher perhaps?

Using the tool Snoop is great for viewing what control in your WPF application has focus, and is very useful in debugging for seeing what controls are recieving focus.  Once you know what control is getting focus instead of your control, you can put a breakpoint in the control’s GotFocus event to debug and see when focus is being moved to the control, and what fuction is performing the operation to move the focus.

Categories: WPF Tags: , , , ,

Some Visual Studio 2010 Shortcuts and C# 4.0 Cool Stuff

April 17th, 2011 1 comment

A list of some shortcus and new features to VS 2010 and C# 4.0:

  • Default values for parameters
  • Can access parameters by name (i.e. SomeFunction(name: "Dan", age: 26);
  • Can now put Labels on breakpoints and filter the breakpoints, as well as import and export breakpoints.
  • Window => New Window to open up same file in two separate tabs, or can drag the splitter at the top-right corner of the edit window.
  • Edit => Outlining => Hide Selection to collapse any region of code
  • Alt + Mouse Left Drag for box selection instead of line selection, then just start typing; you can also use Alt+Shift+Arrow Keys to do box selection with the keyboard.
  • Alt+Arrow Keys to move current line up/down.  Can also select multiple lines and use Alt+Up/Down to move the whole selection up/down.
  • In NavigateTo search window (Ctrl + Comma) use capitals to search for camel casing (i.e. CE to find displayCustomerEmails) and a space to do an "and" search (i.e. "email customer" would find displayCustomerEmails).
  • Ctrl + I to do an incremental search of a document, then F3 and Shift + F3 to move to next/previous matches.
  • Use snippets to automatically create code and save time.
  • Ctrl + Period to access VS tickler window instead of having to hover over the variable with the mouse.
  • Ctrl + Alt + Spacebar to change VS to suggest variable names instead of auto completing them.
  • Can right click in document to remove and sort using statements.
  • Enum.TryParse() has been added to match a string or number to an enumerated type.
  • Contract.Requires() and .Ensures() to ensure that function conditions are met (at compile time).
  • String.IsNullOrWhitespace(string);
  • Lazy<T> for thread-safe lazy loading of variables.
  • VS => Options => Debugging => Output Window => Data Binding to give more info about errors.
  • Using System.Threading.Tasks for parallel processing.  Parallel.For() and .ForEach
  • PLINQ => myCollection.InParallel().Where(x => …..);
  • New Dynamic keyword type => just like Object except not checked at compile time.
  • Ctrl+Shift+V to cycle through clipboard ring
  • Alt+Ctrl+Down to access tab menu
  • Ctrl+Shift+Up/Down to move between instances of the highlighted variable
  • Ctrl+] to move back and forth between a functions opening and closing braces (i.e. "{" and "}"). This appears to also work in XAML!
  • Alt+Arrow Keys to move current line up/down.  Can also select multiple lines and use Alt+Up/Down to move the whole selection up/down.
  • Rather than selecting a whole line first, just use Ctrl+C or Ctrl+X to Copy/Cut the entire line. You can also use Shift+Delete to delete an entire line without selecting it.