Friday, February 22, 2013
Azure Adventures - 1
Since I have an MSDN (Microsoft Developers Network) subscription, I thought I'd take advantage of the 'free' Windows Azure account that it provides in order to learn about that technology. So, last night I signed up. For a list of what you get for different level subscriptions, you may go to http://www.windowsazure.com/en-us/pricing/member-offers/msdn-benefits/
I plan to begin my adventures this weekend. I'll let you know how it goes.
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!








