partial class DaveKehring : IProgrammer { }  RSS 2.0
# Sunday, February 01, 2009

Code snippets in Visual Studio are very helpful when you have to type the same old code structure again and again. I found myself doing this on a recent project and decided to create a code snippet for it. I'm using Microsofts Composite Application Guidance (a.k.a. Prism) and the Model-View-ViewModel pattern (M-V-VM). My ViewModels implement commands that are hooked into from the Xaml View. The command type is DelegateCommand<T>, a class provided by the Composite WPF library that comes with Prism. Here's my snippet:

<?xml version="1.0" encoding="utf-8"?>

<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">

  <CodeSnippet Format="1.0.0">

    <Header>

      <Title>DelegateCommand</Title>

      <Shortcut>delcom</Shortcut>

      <Author>Dave Kehring</Author>

      <Description>Creates a Prism DelegateCommand.</Description>

      <SnippetTypes>

        <SnippetType>Expansion</SnippetType>

      </SnippetTypes>

    </Header>

    <Snippet>

      <Imports>

        <Import>

          <Namespace>Microsoft.Practices.Composite.Wpf.Commands</Namespace>

        </Import>

      </Imports>

      <Declarations>

        <Literal>

          <ID>type</ID>

          <ToolTip>Parameter type</ToolTip>

          <Default>int</Default>

        </Literal>

        <Literal>

          <ID>name</ID>

          <ToolTip>Command name</ToolTip>

          <Default>MyCommand</Default>

        </Literal>

      </Declarations>

      <Code Language="csharp">

        <![CDATA[

        DelegateCommand<$type$> _$name$Command;

        public DelegateCommand<$type$> $name$Command

        {

            get

            {

                if (_$name$Command == null)

                    _$name$Command = new DelegateCommand<$type$>($name$, Can$name$);

                return _$name$Command;

            }

        }

       

        public bool Can$name$($type$ param)

        {

        }

       

        public void $name$($type$ param)

        {

        }

       

      ]]>

      </Code>

    </Snippet>

  </CodeSnippet>

</CodeSnippets>

This produces the following example property declaration:

        DelegateCommand<object> _SaveCommand;
        public DelegateCommand<object> SaveCommand
        {
            get
            {
                if (_SaveCommand == null)
                    _SaveCommand = new DelegateCommand<object>(Save, CanSave);
                return _SaveCommand;
            }
        }
        
        public bool CanSave(object param)
        {
        }
        
        public void Save(object param)
        {
        }

The code snippet creates a private DelegateCommand member and a standard property declaration with only a getter. The command is lazy-initialized. The two methods stubs are called by the DelegateCommand during runtime execution.

To use this snippet, save it in a file with the .snippet extension into %\My Documents\Visual Studio 2008\Snippets\Visual C#\My Code Snippets. Then, in Visual Studio, you simply type "delcom" to run the snippet:

Hit Tab to insert the snippet code into the IDE. Then, you provide replacement values for the DelegateCommand's type value (this is the type of the parameter passed to the command methods) and the name of the command:

 

Sunday, February 01, 2009 10:41:42 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
Visual Studio
# Thursday, November 20, 2008
How to add Intellisense in Visual Studio for custom configuration sections.
Thursday, November 20, 2008 8:57:11 AM (Eastern Standard Time, UTC-05:00)  #    Comments [1] -
Configuration
# Monday, October 06, 2008

If you have a class that contains an event, you'll want to write a unit test to test that the event gets fired at the right time and under the right conditions. The problem is that you would typically hook up an event handler in your unit test class that can run an assert to check if the event gets fired:

private bool _fired;

[Test]
public void CheckVisiblityEvent()
{
    _fired = false;
    ImageGroupListItemViewModel vm = ImageGroupListItemViewModelFactory.Build();
    vm.VisibilityChanged += new ImageGroupListItemViewModel.ImageGroupVisibilityChangedEventHandler(vm_VisibilityChanged);

vm.Visible = true;
Assert.IsTrue(_fired); } void vm_VisibilityChanged(object sender, ImageGroupVisibilityEventArgs args) { _fired = true; }

This is a bit sloppy. Instead, we could improve on this by using and anonymous method:

[Test]
public void CheckVisiblityEvent()
{
    bool fired = false;
    ImageGroupListItemViewModel vm = ImageGroupListItemViewModelFactory.Build();
    vm.VisibilityChanged += delegate(object sender, ImageGroupVisibilityEventArgs e)
    {
        fired = true;
    };
    vm.IsVisible = true;
    Assert.IsTrue(fired);
}

More compact and easier to follow. Plus, the test code is all in one place. We can improve this even more with a lambda expression:

[Test]
public void CheckVisiblityEvent()
{
    bool fired = false;
    ImageGroupListItemViewModel vm = ImageGroupListItemViewModelFactory.Build();
    vm.VisibilityChanged += (s, e) => fired = true;
    vm.IsVisible = true;
    Assert.IsTrue(fired);
}

 

Monday, October 06, 2008 10:35:17 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
NUnit | Unit Testing
# Wednesday, September 24, 2008

Here's a nice way to bind to mouse events to a RoutedCommand. My RoutedCommand is defined in a ViewModel (in the Model-View-ViewModel pattern):

<Image Name="Image" Grid.Row="0"
          
Source="{Binding DataModel.Thumbnail, Converter={StaticResource
                       
ImageConverter}}">
   
<Image.InputBindings>
       
<MouseBinding MouseAction="LeftDoubleClick"
                           
Command="vm:ThumbnailViewModel.PreviewCommand"/>
   
</Image.InputBindings>
</Image>

Wednesday, September 24, 2008 10:39:48 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
M-V-VM | WPF
# Tuesday, August 12, 2008

While trying to create unit tests for view models (using the Model-View-ViewModel pattern), I came across a problem while trying to execute unit tests from NUnit. The error I recevied was:

The calling thread must be STA, because many UI components require this.

A quick search on Google yielded an answer.

However, the configuration file in the post was incorrect and was noted by a commentor. For expediency, I have included the correct configuration text below:

<configSections>
   <
sectionGroup name="NUnit">
      
<section type="System.Configuration.NameValueSectionHandler" name="TestRunner"></section>
   
</sectionGroup>
</
configSections>

<NUnit>
   <
TestRunner>
      
<add value="STA" key="ApartmentState"></add>
   </
TestRunner>
</
NUnit>

 

Tuesday, August 12, 2008 8:52:59 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
M-V-VM | NUnit | Unit Testing | WPF
# Tuesday, October 23, 2007
I like using Guids. Sure, they're a bit long and difficult to decipher in a database but they have their uses. I typically use them as the primary key for database tables. I often have the need to display a list of values from a database table in a DropDownList control on a WebForm. The value of each entry is the Guid while the text value comes from a description field in each record. When the user selects an item from the DropDownList, I retreive the Guid from the SelectedValue property which is typically used to set a field on a business object, thus creating a reference. Typically the first item in the DropDownList reads "--Select One--" or "-- None --", indicating the the user must select a value (this is represented by the value for Guid.Empty). Consequently the field is "required" - a user must select a value from the list. I do this because I don't want to presume a default value (such as the first item).

The problem them becomes how to validate the DropDownList on the client side such that if the user does not select an item other than the default "--Select One--" item a message is display.

I found a post that shows how to use the CustomValidator control to validate a DropDownList. The problem with this solution is that it does not take into account when a control is embedded within other controls that are tagged with the INamingContainer interface. This interface tells ASP.NET to automatically generate unique "id" attribute values on the ensuing HTML tags generated for a control. This unique id is prepended with the id of each parent control up to the root control. For example, a DropDownList embedded in a Panel control might have the id "ctl00$ddlMyDropDown". Therefore, in the solution mentioned above, we can't simply us "document.getElementById" Javascript function to locate the DropDownList control.

A better solution is to utilize the ControlToValidate property of the CustomValidator control. When this is set at design-time ASP.NET will generate Javascript code to add this value as an attribute of the validator control in the HTML DOM. For instance, looking at the source of the page I'm working on the following code is generated:

var ctl00_MainContent_CustomValidator1 = document.all ? document.all["ctl00_MainContent_CustomValidator1"] : document.getElementById("ctl00_MainContent_CustomValidator1");
ctl00_MainContent_CustomValidator1.controltovalidate = "ctl00_MainContent_ddlFeedbackType";

The property "controltovalidate" contains the fully-qualified unique id of the target control we're validating. We can use the "controltovalidate" property in our Javascript function that is used to validate the DropDownList:

function ValidateFeedbackType(source, arguments)
{
var ddl = document.getElementById(source.controltovalidate);
if (null != ddl)
{
var value = ddl[ddl.selectedIndex].value;
arguments.IsValid = (value != "00000000-0000-0000-0000-00000000000");
}
else
{
arguments.IsValid = false;
}
}



Tuesday, October 23, 2007 7:34:45 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
ASP.NET
# Monday, June 25, 2007

I often run into a situation where a user tries to click a Submit button more than once on a page when processing takes more than a few seconds. To remedy this, I created a very simple control based on the standard ASP.NET Button control (System.Web.UI.WebControls.Button). I created a new WebControl and inherit from System.Web.UI.WebControls.Button to retain all of the aspects of a standard button. Next, I override the AddAttributesToRender method and include the following code:


protected override void AddAttributesToRender(HtmlTextWriter writer)
{
    base.AddAttributesToRender(writer);
    writer.AddAttribute("onclick", "this.disabled=true;"
        + this.Page.ClientScript.GetPostBackEventReference(this, ""));
}


The first line calls the base classes implementation and then the second line adds a client-side event handler for the "onclick" event of the button. When the button is clicked, it is disabled and then a postback is initiated. This is important because if you just try to disabled the button, it will not be part of the postback and its server-side processing will not fire. That's why you need to include the postback callback function for the button that can be obtained from the call to ClientScript.GetPostBackEventReference.

Monday, June 25, 2007 8:09:56 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -

# Wednesday, May 30, 2007

I was tring to create an ASP.NET website using Visual Studio.NET 2003 and got the following error that in part says:

"Unable to create web project ... The two need to map to the same server location".

I found so many threads about this with few answers. Here's how I solved my problem.

I was trying to create an ASP.NET website on one of my servers from Visual Studio.NET 2003 on my development machine. The problem was that the directory location of the "Default Web Site" node in IIS on the server did not map to the location where I was trying to create the new application based on the UNC path. For example, I was trying to create the application on the following path:

\\myserver\inetpub$\myapplication

This mapped to the physical location:

G:\Inetpub

... and translates to the URL

http://myserver/myapplication

In IIS on the server I looked at the "Default Web Site" node as this is where IIS will try to create the ASP.NET application because http://myserver translates to this location. Looking at the Home Directory tab at the Local Path parameter I noticed it was pointing to the physical location

C:\Inetpub\wwwroot

So, I simply changed this path to G:\Inetpub and it worked. So this is what the message means by "the two need to map to the same server location".

Don't forget of course that I had to create a UNC share with the appropriate permissions for this to work.

Hope this saves someone some time.

Wednesday, May 30, 2007 12:30:52 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -

Navigation
Archive
<February 2009>
SunMonTueWedThuFriSat
25262728293031
1234567
891011121314
15161718192021
22232425262728
1234567
About the author/Disclaimer

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

© Copyright 2012
Dave Kehring
Sign In
Statistics
Total Posts: 11
This Year: 0
This Month: 0
This Week: 0
Comments: 2
Themes
Pick a theme:
All Content © 2012, Dave Kehring
DasBlog theme 'Business' created by Christoph De Baene (delarou)