Tuesday, December 1, 2009
Dependency Injection Principle
First, the book Agile Principles, Patterns, and Practices in C#, written by Robert C. Martin and Micah Martin, and published by Prentice-Hall, provides an excellent definition along with several clear examples of the Dependency Injection Principle. It is an all-around excellent book on proper application development.
In preparing this talk, I also found threee excellent articles on the web:
http://ctrl-shift-b.blogspot.com/2008/12/examining-dependency-inversion.html
http://codebetter.com/blogs/jeremy.miller/pages/129543.aspx
http://code-magazine.com/articleprint.aspx?quickid=0705071
Enjoy!
Friday, September 11, 2009
Exceptional Data
As I begin this blog entry, it is early in the day, so I do not yet know if this will be an exceptional day. Nevertheless, I would like to talk about exceptions.
All exceptions have a Data property, which can be very useful. I cannot say whether or not Microsoft uses it for any of their exception handling, say, for example, within their applications such as Excel, or within the code for their .NET framework. However, I can say that I have never seen it used in any projects I have been involved with over the last seven years in the .NET world.
Notice the Data property in the following listing for the ‘ex’ variable in the Watch1 window:
It is obviously empty in this case. However, observe that it is a free-form dictionary. It has
a Keys collection and a Values collection. The elements of both are of type object. Thus you can add just about anything that you feel might be useful to this dictionary. (NOTE: If this illustration or any other is too small for you to read, just double-click it to temporarily view it in a separate window. Then navigate back to the original page.)
To illustrate the use of the Data property, I have, believe it or not, developed a simple application that brews beer. A brewing application must have a Beer class, so here it is:
Since I have not yet perfected the brewing process, the Brew method throws an ApplicationException. To assist with determining what the error might be, the Brew method adds the value of the makeDark local variable and the Beer instance that caused the exception to the Data dictionary.
The main program, which defined the beer and initiated the brewing process, needs to collect this information, so that I can achieve perfection:
Here is the output:
Now, you might say that I could have developed a custom BrewingException class which included the two elements that I placed in the dictionary. This is true. However, even when using a custom exception class, I am sure you can imagine situations where you might like to collect additional information. This is a perfect job for the Exception class’s Data dictionary.
I hope you have an Exceptional day!
Friday, September 4, 2009
Feeling List<>-less?
Today I responded to a question on the Microsoft Visual C# Developer Center. The person (I’ll call him Mr. X) wanted to break a generic list of objects into separate generic lists, where each of the new lists contained entries with a common value for a particular property. He wanted to combine these new lists into a list of lists. I responded that he might consider creating a dictionary instead of creating a list of lists, but that, if he really wanted a list of lists, he could use the dictionary to create it. Let’s look at the details of how we might accomplish this. (Note: if an image below is too small for you to read, just double-click it. Then, when you are done viewing it, just navigate back to the blog page.)
Mr. X was working with a CarType class consisting of four elementary properties. Starting from a list of CarType objects,
he wanted to break this into separate lists, where the entries in each list have a common value for ID.
So … the first thing we do is to create the original list:
Then we create a dictionary of type Dictionary<int,List<CarType>> and load it in a simple foreach loop. Note that when we
encounter an entry in the original list for which there is no existing list in the dictionary, we first create the requisite new list.
If we are doing this in a console application, we can verify that the dictionary lists were properly created with the following two-level loop:
Note that each entry in the dictionary is of type KeyValuePair<int,List<CarType>>. This object enables us to easily retrieve the key (int) and the corresponding value (List<CarType>) of each dictionary entry.
If we wish to put the final results in a list of lists, we just create the list of lists and dump the dictionary contents into it as follows:
The validation is similar to that for the dictionary. Here is the final result, expressed in the Main method of a console application:
Go ye forth and make lists!
Wednesday, July 22, 2009
Using Custom Attributes in an ASP.NET Application
In this post I present an ASP.NET application that illustrates how this can be done. It is simple, and perhaps simplistic, but it is sufficient to demonstrate the technique. (NOTE: If any of the included illustrations appear too small to read, just double-click on them to view them in a separate window.)
This application consists of a single web page whose purpose is to enable a user to maintain either of two types of employees – workers or managers. The type handled is controlled by a custom EmployeeType attribute. In support of this functionality, the solution consists of a single ASP.NET project that includes three business object classes (Employee, Worker, and Manager), a custom attribute class (EmployeeTypeAttribute), an enumeration (EmployeeType), and, of course, the web page (default.aspx):

The Employee class serves as a base class for Worker and Manager:

The Worker class adds two additional properties:

Similarly, the Manager class adds two different additional properties – GolfCourse and HealthClub. (I guess the users of this application are interested in truly identifying the workers but only interested in the social standing of the managers!)
As mentioned above, the enumeration, which is used by both the custom attribute and the web page code-behind, identifies the possible types of employees:

The custom attribute makes use of this enumeration to define the type of employee with which the web page should work:

Notice the attribute on the attribute – AttributeUsage. Its property setting of AttributeTargets.Class specifies, as you might expect, that the attribute can be applied to a class. For a list and explanation of other possible settings, refer to http://msdn.microsoft.com/en-us/library/system.attributetargets.aspx . Also notice that the custom attribute must inherit from System.Attribute.
With this attribute defined, it is now available for use by the web page code-behind:

Notice that the class is tagged with the custom EmployeeType attribute and that its TypeOfEmployee property is being set to ‘Manager’. Behind the scenes, .NET is actually calling the EmployeeTypeAttribute constructor to set the property. Then, the Page_Load event handler captures this attribute by using the GetCustomAttributes method of the System.Reflection.MethodInfo class. If we set a break point on the ‘if’ statement, we see in the Watch window that the custom attribute is actually the first of many:

Lastly, Page_Load casts the first attribute in the array to an instance of CustomerTypeAttribute and retrieves the value of its TypeOfEmployee property, setting a corresponding private field.
The attribute property value is now available for use in any of the code-behind methods. In this application, it is used by two methods. The InitializeForm method uses the value to make the proper set of labels and textboxes visible and the others invisible:
Tuesday, July 21, 2009
Using the Decorator Pattern to Evaluate Complex Conditions
For those of you who may not be familiar with this pattern, http://www.dofactory.com/Patterns/PatternDecorator.aspx defines it as a means of attaching additional responsibilities to an object dynamically. The most common example found is some variation of incrementally adding cost components to some base entity, such as toppings on pizza or condiments in coffee. An example of this, using cars as the base entity, may be found at http://www.codeproject.com/KB/architecture/PatternsIntro_Decorator.aspx . It’s time for a change!
In this blog post I present a console application in which the user is allowed to enter an integer (let’s call it ‘x’), and the application then determines whether or not it satisfies the following complex condition:
1 <= x <= 5 OR x > 7
This application represents a major simplification of the task I was asked to perform in my current project.
First let’s look at the main method of the application:

How is this accomplished? Let’s begin by looking at the two constructors found in the Main method. The 3-parameter constructor specifies the variable whose value is to be evaluated, the value to which it is to be compared, and the type of comparison to be made. The options for the latter are defined in the ArithmeticOperator enumeration:

The five-parameter constructor first specifies the three values found in the former. In addition, it specifies a second condition to be evaluated in conjunction with the ‘current’ one, and the logical operator to be used when jointly evaluating the two conditions:

Going back to the Main method, notice that the final result is obtained by merely retrieving the ConditionResult property value for the last Condition instance in the chain. This is some powerful property!
The TestCondition method is nothing but simple arithmetic comparison of the variable to be evaluated against the specified comparison value:
Thursday, July 16, 2009
How to Create a Class Instance Dynamically
I am currently working on a project in which, a while back, I had to write a utility application to extract snippets of HTML from specified nodes in an incoming XML file, and transform that HTML in a number of different ways. A full explanation of this utility application is beyond the scope of this post. However, relevant to this post, the application needed to handle an incoming XML file whose format was not constant from one run of the application to the next, but was limited to one of several specific formats. I therefore defined the following simple interface:
The intended purpose of the single method in this interface was, as you might guess, to get the HTML snippets from the incoming XML file. I then defined a separate class for each possible XML file format, implementing the interface in each class. For example, one of the formats contained full HTML documents in a specified node. I appropriately named this class ‘FullHtmlRepository’. The following is the code for this class:
Here I took advantage of the Type.GetType( string ) static method, which converts a string that describes a type into a Type variable. I obtained that description from the application’s app.config file:

Now this is perhaps not the best way of getting the description. An application intended for production might, for example, ask the user to specify which format to process during a given run (pick from a listbox) and then validate the input file against the appropriate schema. But, remember, regardless of how sophisticated you might think this application was, it was a utility, throw-away application. Quick and dirty – within reason – was the modus operandi.
Let’s examine the string presented in the value attribute of the above ‘add’ node. Note that it really consists of two comma-delimited strings. The first string is the fully-qualified name (namespace plus class name) of the class to be instantiated. The second string is the name of the assembly that contains the code for that class. So, it really doesn’t matter what the source of the class description string is, as long as it contains these two elements … and as long as they exist, of course.
Going back to the GetRepository method, note that the return statement first creates an instance of the FullHtmlRepository class, and then casts that instance to an IRepository type so that it can be used in a class-agnostic manner elsewhere in the application.
That’s it. Elementary, my dear Watson!
Wednesday, July 15, 2009
Incremental Addition of 2 Float Variables
I gave the following response:
I should have pointed out that this is not the best piece of code ever written. First, several other responders suggested that the decimal data type should be used instead of the float data type. (By the way, the response immediately following mine was too quickly conceived – the code presented would not build if plugged into a console application.) I agree with using the decimal data type unless there is some reason for the developer having to use floating point numbers. After all, this does appear to be a science/engineering “application,” and you know how scientists and engineers love their floating point numbers! Using the decimal data type would avoid the conflict which the developer experienced between the decimal number system which we humans use, and the binary number system which computers use.Second, I am not really comfortable with constructing this kind of ‘for loop’. It is too complex for my liking. I have two possible assumptions related to this issue:
(1) The developer is trying to capture a certain number of data points; or
(2) The developer is trying to capture points until the denominator has reached a specific value.
It appears on the surface that the latter is true. However, perhaps the developer just doing this as a way of capturing the required number of data points. Obviously, I don’t really know for sure.
So, with all this in mind, I’ve constructed two possible coding solutions. Both assume that, for some reason, the developer needs to use floating point numbers. You will notice that I’ve used variable name ‘denominator’ instead of ‘loop_index’. I would suggest coming up with a more meaningful name – one that reflects what it really represents in the formula being used.
The first example assumes that the developer is trying to capture a specific number of data points:

The second example assumes that the developer is trying to capture points until the denominator reaches a specific value:
If the developer is allowed to use the decimal data type rather than using float/double, the examples would not change much. However, he/she would not be faced with the rounding issue.Monday, June 29, 2009
WPF and MVVM - A Look at the Microsoft Toolkit, Part 2
Recall that the only files in the project folder itself are App.xaml and its code-behind file App.xaml.cs. These files are responsible for “kicking off” the application. Let’s begin by looking at App.xaml:
The critical element here is the Startup attribute of the Application tag. Its value says, “Invoke the code found in the OnStartup event handler." This event handler is found in the code-behind file App.xaml.cs:
Looking at the XAML for MainView, we find an initial File menu with an Exit menu item that is linked to ‘ExitCommand’, and an empty grid:
Notice that it is a read-only property of type ICommand. The ICommand interface, which must be implemented in all commands that interact with WPF, exposes two methods and an event. The first method, Execute, defines the method that is called when the command is invoked. The signature for this method must agree with that of the Action delegate:
public delegate void Action
The second method, CanExecute, defines the method that determines whether or not the command can execute in its current state. Its signature must agree with that of the Predicate delegate:
public delegate bool Predicate
The other class in the Commands folder, CommandReference, provides a Command dependency property, so you can more easily bind a keyboard sequence – e.g., Control + X – to a command. A discussion of dependency properties is beyond the scope of this blog entry. Just bear in mind that all bindable control properties are dependency properties.
You will no doubt note that in MainViewModel, only the Execute method – aptly named Exit – is defined. MainViewModel relies on the default implementation of CanExecute provided by DelegateCommand, which merely returns ‘true’. Neither does it subscribe to the CanExecuteChanged event, for which, again DelegateCommand provides a default handler implementation.
The other mystery found in the MainViewModel class definition is the fact that it is a sub-class of ViewModelBase. This base class implements the INotifyPropertyChanged interface, which consists of a single event – PropertyChanged. It also provides a handler for that event:
That’s about it for an overview of the application project generated by the WPF-MVVM template. However, as you may recall, this template also gives you the option of generating a test project to go along with the application. If you refer back to Figure 1, you will notice that a single test class, MainViewModelTest, is generated. Within that class a single test method is generated. This method provides a stub for testing the MainViewModel constructor.
One of the primary advantages of adopting the MVVM pattern when developing a WPF application is that it enables you to test all of your code, including command execution, in a manner that is independent of the application UI. If you adopt this template, I would suggest that you define folders in the test project that correspond to the folders in the application project, and that you create one test class per application class.
With this overview behind us, we will proceed with the development of the Investment Tracker application in the next post.
Previous posts in this series:
Tuesday, June 23, 2009
WPF and MVVM - A Look at the Microsoft Toolkit, Part 1
The toolkit comes with a project template, a sample application, and two white papers. The first paper provides a brief description of the MVVM pattern. The second paper provides step-by-step instructions for developing the sample application yourself. While I would not consider the application to be "complete," it does provide an excellent initial look at how to use the template and how to implement the MVVM pattern in a WPF application.
First, let's look at the template. Suppose, you want to develop an application called MyWpfApp. From Visual Studio, you would select from the menu: FileNewProject. This action, of course, brings up the New Project dialog. In the dialog, select, in the left pane, project type Visual C#Windows. Then, in the right pane, select the WPF Model-View Application template. Finally, in the first textbox of the lower portion of the dialog, name your project MyWpfApp:


After you click OK, a solution with a WPF/MVVM project (hereafter called the main project) and a test project is set up for you:

Notice that the only files in the main project folder itself are app.xaml and its code-behind file app.xaml.cs. Sub-folders are defined which, except for one, correspond to the different application "layers" associated with the MVVM pattern: Models, Views, and ViewModels. A folder that you might not have expected is the Commands folder. The Views, ViewModels, and Commands folders are populated with an initial set of files which may be used in developing your application. We will examine the contents and purpose of these files in the next post.
Previous posts in this series:
Wednesday, June 10, 2009
WPF and MVVM - Orientation
In what time I have available I've been researching how to best achieve the separation of tasks described in the first post. There are quite a few blog entries out on the web, most of which really don't work except in specific cases, which, or course, the author presents. There are, though, several very good posts and two Microsoft sites that you may be interested in.
Joshua Smith has an excellent article and accompanying code example on MSDN: WPF Apps With The Model-View-ViewModel Design Pattern. In this article he introduces a concept which he calls the Relay Command.
Kent Boogaart has written a good series of articles. The final one in the series is MVVM Infrastructure: ActiveAware Command. The article contains links to the three prior articles in the series.
If you need to develop a large and/or complex WPF application, you might be interested in Microsoft's Prism - a composite application library. Check out Patterns & Practices: Composite WPF and Silverlight.
For smaller applications, Microsoft has a WPF MVVM Toolkit: WPF Toolkit - March 2009 Release.
In the end, and after a bit of experimentation, I decided to use an adaptation of the template that comes with the Microsoft toolkit. The template creates a solution with a single project with separate folders for the different segments of the MVVM pattern. I would have preferred separate projects in place of the folders, so I gave that a try, reworking the sample application that comes with the toolkit. It worked, so that's what I've decided to use in developing the Investment Tracking application.
Previous entries in this series:
WPF and MVVM - Intro
Thursday, April 30, 2009
WPF and MVVM - Intro
My wife has been after me for quite some time to keep better track of our investments. That's a pretty good idea actually. So, I'm going to learn by developing an Investment Tracking application. For those of you who decide to follow along, feel free to chime in with some suggestions.
Let's start by looking at M-V-VM itself. My understanding is that it is an offshoot of the Model-View-Controller pattern. The 'M', or Model, describes the business which your application is supporting, and is comprised of a related set of classes traditionally called business objects in a standard 3-tier application. The 'V', or View, is the UI - the portion of the application where the user interacts with your application and its data. The 'VM', or View Model, sits in between the View and the Model. It models the data displayed in the UI, which might not exactly correspond to the business objects of the Model. It also controls all the behaviors which the View must support. Thus the View is "dumb", and the View Model contains all the requisite "smarts." None of these layers directly address data access, so really, the way I understand the situation, you end up with having at least a 4-tiered application.
One of the selling points of M-V-VM is supposed to be the ability to apply unit tests to much more of the application - specifically to the Model, View Model, and Data Access tiers. We're going to find out, folks!
With all of this in mind, the first step is to set up the solution with a starting set of projects. They should be fairly self-explanatory:















