Wednesday, July 22, 2009

Using Custom Attributes in an ASP.NET Application

Earlier today I responded to a question on Microsoft’s Visual C# General Forum (accessible from http://social.msdn.microsoft.com/Forums/en-US/category/visualcsharp ) in which the person posing the question was having trouble accessing a custom attribute from a web page. He wanted to use the setting of this attribute in several methods of the code-behind for the web page.

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:


The btnSave_Click event handler uses the value to invoke the appropriate Save method:


The SaveManager method is as follows:


The SaveWorker method is similar.

Let’s look at the result. When the EmployeeType attribute is set to EmployeeType.Manager, the web form appears as follows:


When the EmployeeType attribute is set to EmployeeType.Worker, the form instead appears as follows:

I hope this is useful in illustrating how to implement custom attributes in an ASP.NET application.

Tuesday, July 21, 2009

Using the Decorator Pattern to Evaluate Complex Conditions

As part of a project on which I am currently working, I recently had to create a Condition class to be used in defining and evaluating complex groupings of logical and arithmetic conditions. After considering the matter for a while, I decided that this would be an ideal situation for using the Decorator Pattern.

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:


It is fairly easy to observe that the work-horse of this application is the Condition class. The first instantiation of this class defines the condition ‘x >= 1’. The second instantiation defines the condition ‘x <= 5’ and also AND’s the two conditions together. Thus, it establishes the necessary ‘environment’ for evaluating ‘1 <= x <= 5’. Similarly, the final instantiation defines the condition ‘x > 7’ and OR’s this result with the result of the second evaluation: 1 <= x <= 5 OR x > 7.

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 logic of the property ‘getter’ is fairly easy to understand. It merely evaluates the current condition, and then, if the ‘rightSide’ condition has been specified, either AND’s or OR’s the current result with the result of evaluating the other condition.
The TestCondition method is nothing but simple arithmetic comparison of the variable to be evaluated against the specified comparison value:


Thus, the Decorator Pattern provides a very powerful, simple-to-apply way of evaluating complex logical expressions.

NOTE: If any of the above images are difficult to see, just double-click them to view a larger representation.

Thursday, July 16, 2009

How to Create a Class Instance Dynamically

It is often necessary or convenient to create an instance of a class dynamically. For example, you may not know what class you need to use in a particular situation until run-time. One way of handling this situation is to use the CreateInstance method of the Activator class. (The Activator class is defined in the System namespace.) There are a number of overloads to this method. In this blog post I am presenting an illustrative example that uses the one with the signature CreateInstance( Type ). If you wish to explore the other alternatives, a good starting point is the MSDN documentation - http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx .

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:
Since I didn’t know the format of the incoming XML file before a given run, I didn’t know which class to instantiate prior to the run. I thus needed to generate the correct class dynamically at the beginning of a specific run. This is where the CreateInstance method came into play. Recall from the opening paragraph that I had decided to use the overload with the CreateInstance( Type ) signature. ‘Type’, of course, is the class to be instantiated. This is the method that I used to instantiate the appropriate 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!
NOTE: If one of the above images is too small for you to view properly, just double-click it. Then, when you are done viewing the image, click on the navigate-back arrow on your browser.

Wednesday, July 15, 2009

Incremental Addition of 2 Float Variables

Yesterday I responded to the following question on http://social.msdn.microsoft.com/ :


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.
NOTE: If you have trouble seeing one of the above images, just double-click it. Then, when you are done viewing it, click on the 'navigate back' icon on your browser.