Thursday, November 25, 2010

When to use Entity Sql vs LINQ to Entities

Microsoft now has so many different data access technologies, how do you choose? ADO.Net served us well for many years, and then Microsoft introduced LINQ - Language INtegrated Query. Dot-Net 2.0 offered LINQ to SQL. With .Net 3.5 and 4.0 we have the Entity framework and LINQ to Entities.

In addition there is also Entity SQL.

When would you use this? My take on it is that if you already know which Entity Model you're using at the time you're writing the code then LINQ to Entities is easier because you can take full advantage of intellisense. If you want to do more abstract coding that will work on any model then Entity SQL will allow you to write the SQL statement dynamically at run time.

For example, with LINQ to Entities you can do this:

NorthwindEntities context = new NorthwindEntities();
IQueryable<Product> qry = from p in context.Products
where p.UnitsInStock < p.ReorderLevel
select p;
In the above example when you type "IQueryable<", "context.", and "p." you get intellisense that helps you select the right entity and field names.

So when you know ahead of time that you want to get data from a specific table in a specific model then LINQ to Entities is easier.

Let's say that you want to do something more generic. For example, let's say you want to select the maximum value from some column of some unknown type in some table. You can do it with Entity SQL like this:

public T MaxValue<T>(ObjectContext context, MetaColumn pkCol)
{
string maxQuery = "SELECT Max(p." + pkCol.Name +
") FROM " + pkCol.Table.Name + " as p";

ObjectQuery<DbDataRecord> query =
new ObjectQuery<DbDataRecord>(maxQuery, context);

DbDataRecord rec = query.First();
return (T)rec[0];
}
We use generics to specify the type, T, of the result, which could be an int or a double, or a string, or any type that would work with the Max function. We're given an ObjectContext and the MetaColumn for which we want to find the max.

Let's say that the MetaColumn is the Id column in the Products table. The Entity SQL would end up being:

SELECT Max(p.Id) FROM Product as p

But it would work with any column of any type in any table. The ObjectQuery gives you a generic collection of generic columns which use can cast to the type that you need using generics.

So when the query is fully known at compile time then LING to Entities is easier, but when you need to construct a query at run time then Entity SQL gives you that flexibility.

Thursday, March 11, 2010

Introduction to Entity Sql

The ADO.Net Entity Framework is the latest evolution in data access from Microsoft, making ORM (object relational mapping) part of the .Net Framework. As I learn the basic of this new technology I thought I'd take you along for the ride.

There are two methods for querying an entity model within your code, Entity SQL (eSql) and LINQ to Entities. The latter is an extension of LINQ (Language INtegrated Query), Microsoft's general-purpose object query syntax that is built into .Net languages C# and VB. There are several varieties of LINQ: LINQ to SQL, LINQ to Entities, LINQ to XML, etc. You can create your own extensions to LINQ if have a specialized set of objects you wish to query.

Entity SQL uses a syntax that is similar to SQL and returns a generic collection, ObjectQuery>T<.

The basic syntax for an eSql query is:

SELECT Entity.property FROM Entity

It is similar to transact-Sql except all column or property names must qualified in select clause. You use aliases in the FROM clause to save typing:

SELECT e.property FROM Entity AS e

If you were querying from an entity model of the Northwinds database this would be a valid query:

SELECT v.AccountNumber, v.Name FROM Vendors AS v

One thing to remember is that entity collections are plural. So eventhough the underlying Sql Server table is Vendor, singular, the entity collection is Vendors, plural.

Where do you use this Sql statement? You create an object query, which can either be of an entity type or use the generic dbDataRecord. The constructor of the ObjectQuery takes two arguments:

  • The Entity Sql
  • An Entity Context

AdventureWorksEntities advEnt = new AdventureWorksEntities();
String sql = "SELECT v.AccountNumber, v.Name FROM Vendors AS v";

ObjectQuery query = new ObjectQuery(sql, advEnt);

The above code will return a collection of that you can index just like an array:

foreach (DbDataRecord rec in query)
{
Console.WriteLine("{0}\t{1}", rec[0], rec[1]);
}

That gets us started with Entity Sql. In future posts I'll many of the other features of this new data access method.

Tuesday, January 6, 2009

Using Web User Controls to Create Rich Internet Application Subassembies - Part 2

In my previous blog entry I gave an overview of the advantages of using ASP.Net web user controls to create generic, reusable subassemblies that can form the basis of your own library of web application building blocks. In this post I will walk you step-by-step through a real world example.

Creating our Visual Studio Project

To follow along, first make sure you have the AJAX Control Toolkit installed for your version of Visual Studio. If you’re using Visual Studio 2008 then go to the ASP.Net AJAX CodePlex site to download the latest version. If you’re still using Visual Studio 2005 then you’ll need to create a new AJAX Control Toolkit Website, which should appear under My Templates after you have installed the AJAX Control Toolkit for ASP.NET 2.0.

After you get the toolkit then you need to add it to the Visual Studio toolbox so that you can drop and drop the components into your web page using the designer. MBrock.com has a helpful blog entry that walks you through the process.

Open Visual Studio 2008 and create a net ASP.NET Web Site named AJAXsubassemblyExample. Lets keep our web user controls separate from the other parts of the site by creating a folder for them called “UIControls.”

Building the Web User Control

Right-click the UIControls folder and select Add New Item. Select Web User Control and name it NumericData.

The first item we’ll add will to the web user control will be text box. Drag a textbox from the Standard tab and change the ID to txtNumericData.

Next, add a Masked Edit Extender. Set TargetControlID="txtNumericData", MaskType="Number" and Mask="999999999999".

12 digits will be our default; later we’ll add some properties for minimum and maximum values and then programmatically adjust the mask to match the property settings.

We want to support a public property named, “IsRequired” that can control whether our numeric data subassembly will be a required field on the page. Add a RequiredFieldValidator from under the Validation tab, make ControlToValidate="txtNumericData" and Enabled="false". This makes the field not required by default. We’ll add a property later that will allow the user to set this.

Finally, we’ll add a RangeValidator, again setting ControlToValidate="txtNumericData" and Enabled="false". The source for UIControls/NumericData.ascx will look like this:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="NumericData.ascx.cs" Inherits="UIControls_NumericData" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

<asp:TextBox ID="txtNumericData" runat="server"></asp:TextBox>

<cc1:MaskedEditExtender ID="MaskedEditExtender1" runat="server"

TargetControlID="txtNumericData"

MaskType="Number" Mask="999999999999">

</cc1:MaskedEditExtender>

<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"

ControlToValidate="txtNumericData" Enabled="false"

ErrorMessage="RequiredFieldValidator">

</asp:RequiredFieldValidator>

<asp:RangeValidator ID="RangeValidator1" runat="server"

ControlToValidate="txtNumericData" Enabled="false"

ErrorMessage="RangeValidator">

</asp:RangeValidator>

We now have all the components for numeric data subassembly in one neat little package.

Defining the Public Properties

Text Box Pass-Through Properties

The web user control will appear as a “black box” to the web pages that are using it. The only properties available are those of the UserControl class and any public properties that we define. Since the text box, txtNumericData, is the main UI element then we should allow users to get and set some of its properties. We’ll start with a short list and add more as needed:

  • Height
  • Width
  • Font and Colors
  • Borders
  • CSS Class

For each property that we want to expose we can define a public property in the NumericData.ascx.cs code file and tie to the text box’s property. Here’s how you would define the Height property:

public Unit Height

{

get { return txtNumericData.Height; }

set { txtNumericData.Height = value; }

}

There’s really not much code at all; we’re just tying the property of the web user control directly to the property of the text box. The property type is Unit, which is the same data type as the text box Height property. Any errors that occur when setting the property would get thrown through to the code that’s doing the setting, so it behaves the same as a regular text box.

The rest of the properties from our list above are done in the same way. Fonts, colors, and borders are actually controlled by many properties so I will spare you the tedium of going through each one and let you look through the source code below.

using System.Web.UI.WebControls;

using System.Drawing;

...

#region TextBox Properties

public Unit Height

{

get { return txtNumericData.Height; }

set { txtNumericData.Height = value; }

}

public Unit Width

{

get { return txtNumericData.Width; }

set { txtNumericData.Width = value; }

}

public Color BackColor

{

get { return txtNumericData.BackColor; }

set { txtNumericData.BackColor = value; }

}

public Color BorderColor

{

get { return txtNumericData.BorderColor; }

set { txtNumericData.BorderColor = value; }

}

public BorderStyle BorderStyle

{

get { return txtNumericData.BorderStyle; }

set { txtNumericData.BorderStyle = value; }

}

public Unit BorderWidth

{

get { return txtNumericData.BorderWidth; }

set { txtNumericData.BorderWidth = value; }

}

public String CssClass

{

get { return txtNumericData.CssClass; }

set { txtNumericData.CssClass = value; }

}

public FontInfo Font

{

get { return txtNumericData.Font; }

}

public CssStyleCollection Style

{

get { return txtNumericData.Style; }

}

public Color ForeColor

{

get { return txtNumericData.ForeColor; }

set { txtNumericData.ForeColor = value; }

}

public int MaxLength

{

get { return txtNumericData.MaxLength; }

set { txtNumericData.MaxLength = value; }

}

#endregion

The Value Property

I did not add Text to the list of properties because we want this control to be specialized and handle only numeric data. Therefore we’ll have a Value property instead which will handle validation and conversion. We want the control to handle either numeric or integer data so we should make Value type a double so that it can handle all types of numbers.

Here’s the code for getting the value:

public double Value

{

get

{

try { return Double.Parse(txtNumericData.Text); }

catch (Exception ex)

{

throw new Exception("Invalid numeric data in control " + ID, ex);

}

}

We have a try-catch and inside the try we use the Parse method of the double type to parse whatever is in the text into a double. If the Masked Edit Extender is doing its job then this parsing will work. If something goes wrong we throw the exception, adding a message which will identify to the programmer the ID of the control that encountered the error.

The set function is similar:

set

{

try { txtNumericData.Text = value.ToString(); }

catch (Exception ex)

{

throw new Exception("Invalid numeric data in control " + ID, ex);

}

}

Because the property type is double then the try-catch should never fail because the error checking would happen in the code trying to assign a value to this property of type double. However, it doesn’t hurt to have the error handling just in case.

Value as Int

The requirements also specify that we be able to limit the values entered to integers if the situation calls for it. It would then make sense to have a property that provides the value as an integer. This becomes a little complicated because what if you access the integer value when the control is configured to accept real numbers? We have to choose whether to truncate, round or throw an exception. Let’s try to be as user-friendly as possible. The Int.Parse() method will throw an exception if you give it a string that includes a decimal point. What we can do is start with Int.Parse(), then try to truncate if that fails:

public int ValueInt

{

get

{

try

{

return int.Parse(txtNumericData.Text);

}

catch

{

return (int)Math.Truncate(Value);

}

}

set

{

try { txtNumericData.Text = value.ToString(); }

catch (Exception ex)

{

throw new Exception("Invalid numeric data in control " + ID, ex);

}

}

}

Notice that in the catch of the get we call the Value property. This lets us reuse the error handling built into the get of that property. If the text in the numeric text box can be converted to a double then the Math.Truncate method will get the integer portion for us.

The set ends up being the same as that for the Value property, since the data type of ValueInt is int, then any errors would occur in the calling code and we merely need to convert the int value to a string if we get this far.

Is Required Property

Is Required allows the user to turn the required field validator on or off. It’s off by default because that’s the way we set it in the control designer. We can tie the property directly to the Enabled property of the validator:

public bool IsRequired

{

get { return RequiredFieldValidator1.Enabled; }

set { RequiredFieldValidator1.Enabled = value; }

}

Range Validation

We want our numeric data control to support range validation. We added a Range Validator to our control and can deal with the range validation in a similar way, exposing the minimum and maximum values as properties. One variation that we can add is changing the type. On a standard range validator the minimum and maximum values are strings. This is because the validators can be used for numbers, text, dates, and currency. Since our control is specialized for numbers only then we can make the minimum and maximum values of type double. Furthermore, since we want to make the values optional then we will make our property types nullable doubles:

public double? MinimumValue

{

get

{

if (String.IsNullOrEmpty(RangeValidator1.MinimumValue))

return null;

else return double.Parse(RangeValidator1.MinimumValue);

}

set

{

if (value == null)

RangeValidator1.MinimumValue = String.Empty;

else RangeValidator1.MinimumValue = value.ToString();

SetRangeValidationEnabled();

}

}

public double? MaximumValu

{

get

{

if (String.IsNullOrEmpty(RangeValidator1.MaximumValue))

return null;

else return double.Parse(RangeValidator1.MaximumValue);

}

set

{

if (value == null)

RangeValidator1.MaximumValue = String.Empty;

else RangeValidator1.MaximumValue = value.ToString();

SetRangeValidationEnabled();

}

}

private void SetRangeValidationEnabled()

{

if (MinimumValue == null &

MaximumValue == null)

RequiredFieldValidator1.Enabled = false;

else

RequiredFieldValidator1.Enabled = true;

}

The last feature to add is determining whether the validator will need to be enabled. If both values are null then we can turn it off. Since the code is the same for both properties I moved it into a help function SetRangeValidationEnabled.

Number Format Properties

The next two properties will determine how the number gets formatted: DecimalPlaces and ShowCommas. These properties will be used when creating the input mask. The rule for DecimalPlaces is that it can’t be negative. ShowCommas does not require any special logic so we’ll take advantage of the new automatic properties feature in C# 3:

int _decimalPlaces = 0;

public int DecimalPlaces

{

get { return _decimalPlaces; }

set

{

if (value < 0)

throw new ArgumentOutOfRangeException("decimal places can not be less than 0.");

else

_decimalPlaces = value;

}

}

public bool ShowCommas { get; set; }

Setting the Mask

Now we have enough groundwork done that we can determine the mask for the masked edit extender. The factors that go into the mask are:

  • Number of decimal places
  • Show commas
  • The magnitude of the minimum and maximum values

The mask will consist of nines, since this is a numeric control, combined with commas and the negative sign. The first thing we need to determine is the number of digits left of the decimal place. For this we can use the logarithm of the maximum and minimum values, rounding up:

int maxNumDigits;

maxNumDigits = (int)Math.Ceiling(Math.Log10((double)MaximumValue));

Note that because MaximumValue is a nullable double (double?) we need to cast it to a double within the Log10 function. We also should have code that deals with the null situation and sets the maximum digits to some default number of digits, maybe 18 so that we can handle up to a quadrillion. If we need anything more we just set the maximum value higher. We also have to allow for the possibility that the minimum value could all accept more digits than the maximum. Here’s what that part of the code would look like:

const int DEFAULT_MAX_DIGITS = 18

private void SetMask()

{

int maxNumDigits;

if (MaximumValue == null MinimumValue == null)

maxNumDigits = DEFAULT_MAX_DIGITS;

else

{

maxNumDigits = Math.Max((int)Math.Ceiling(Math.Log10((double)MinimumValue)),

(int)Math.Ceiling(Math.Log10((double)MinimumValue)));

}

Testing the Control

In my next post I will demonstrate how to create a custom web user control test page that will let you play with all the different properties and provide examples on how to use your component.

Summary

This post demonstrates how you can combine several AJAX extenders with other web UI elements into a nice, reusable package. You can use the code-behind of your web user controls to expose the properties, do error handling and set defaults.

You can have a highly-functional generic control which will work well simply by adding it to a page. Through the various properties the developer can customize it to his or her desires making your control very flexible as well.

Sunday, November 9, 2008

Test Driven Development with Visual Studio 2008 Task Lists

Totally Integrated TDD Example

In my previous blog post, Integrated TDD Environment, I explained how you can do all of your Test Driven Delopment steps without leaving the Visual Studio 2008 IDE by adding a new Task List comment type: TEST

In this blog I will demonstrate step-by-step using a simple example how create a functional class from scratch using integrated TDD within VS 2008.

The Requirements

Every software development project should begin with requirements. Our example will have the following requirement:

  • Provide a web form where the user can enter a temperature in either Fahrenheit or Celsius and see the conversion to the other system.

Our design will separate the user interface from the business logic. For our example we will only test the business logic. We start by creating a new Windows class library project. Name it WebControls. Delete Class1.cs and add a new class named Temperature. This is the class we will build using TDD.

Generate the Test Project

Since we are doing TDD, then all of the development will be driven from our unit tests. We want to have a test project for each project in our solution and a test fixture for each class in each project. Lets add a new project to our solution by selecting Project Type, "Test" and the "Test Project" template. Name the project "WebControlsTestProject."

Select WebControlsProjects in the solution explorer and select "Add" then "Unit Test." You can then browse all the projects in your solution. Select the Web Controls project and the Temperture class:

Visual Studio will create your unit test module shell with the necessary includes and several procedures, including many that are commented out in the "Additional test attributes" region, including setup and tear-down routines, which you can easily uncomment and use.

Since we created a class named "Temperature" then the Visual Studio unit test wizard created a class called "TemperatureTest." We will add our test list in this module.

Add TEST to the Task List Comment Tokens

Start by defining a new Task List token for the test list. On the Tools menu select Options, then select Task List from the list on the left of the options dialog.

Type "TEST" in the Name field, click Add and then OK. Now you will be able add test list items anywhere in your code by adding a comment that begins with the TEST: followed by the description of your test:

// TEST: Here is a unit test description.

This comment now appears on the Comments Task List:

Create the Test List

We are ready to create our test list. We start with our requirement and test for the following:

  • Valid results
  • Error conditions
  • Limit conditions

If you remember back to 6th grade, these are the key facts concerning conversion between Fahrenheit and Celsius:

  • Water freezes at 32 F and 0 C
  • Water boils at 100 C and 212 F
  • The formula for converting is C = (5/9)*(F - 32)
  • There is a temperature called "absolute zero" which is the lowest posible temperature. It is -273.15 C or -459.67 F

We can make of these facts to generate the initial test list and then add more tests as we think of them. Open the TemperatureTest.cs class file, move to the end, and insert the following comments before the two end brackets for class and namespace:

// TEST: Verify 32 F converts to 0 C // TEST: Verify 0 C converts to 32 F // TEST: Verify 100 C converts to 212 F // TEST: Verify 212 F converts to 100 C // TEST: Verify that the Celsius temperature equals Farenheit minus 32 times 5/9 // TEST: Verify that the Farenheit temperature equals Celsius times 9/5 plus 32 // TEST: Verify that a negative Farenheit temperture converts to the correct value // TEST: Verify that a negative Celsius temperture converts to the correct value // TEST: Verify that entering a temperture less than -273.15 C throws and exception

} }

If this doesn't cover all the code we need to write, it should give us a good start. We can easily add new tests as we think of them just by entering comments. Our VS Task List should now look like this:

image

Implementing the Tests

We're now ready to start TDD. Let's start with the first test, "Verify 32 F converts to 0 C." You can double-click the item in the task list to jump right to it. Add the following code below the comment:

Code01

Now we want to write some code and see if the test passes. First we have a design decision to make: do we want this class to require an object to be instanited or use static methods? Static methods are easier to call, but if we need data persisted within the object we have a problem because static methods are global. If you look back at the requirement we see that we need to support a web form, which would have a view state, so our temperture convertor probably won't need to remember anything. We'll start with a static method and hopefully that'll get through all the tests.

We start by writing the code in the test first, then updating the Temperture class so that it compiles, and eventually passes the test.

f1

It seems reasonable that the Temperature class would have a static method named "ToCelsius" that takes a double (since we can have fractions of a degree) representing the Fahrenheit temperature and returns the Celsius temperture as a double.

We have not written the "ToCelsius" method yet, so Visual Studio puts a wavy red line under the method indicating a syntax error. Here is where the refactoring capabilies come in handy. Hold the mouse over the "ToCelsius" method name then you get a drop list where you can select "Generate method stub for Temperature.ToCelsius." We do so and now we can compile and run the test. Of course it fails:

f2

To fix the test we right-click the ToCelsius method "Go To Definition," and then fix the method with the minimum amount of code for the test to pass:

f3

Run the test again and now it passes:

f4

Our first test is done, so we remove it from the list. Since our Task List is driven by comments then we need to delete the TEST: from the comment. We can leave the description so that we have some documentation left behind.

f5

The Task List now has 8 tests remaining. The next test is to verify that 32 F converts to 0 C. If we follow the same method as before we write this test:

f6

We implement this method to get the tests to pass:

f7

And we run all the tests and verify they pass:

f8

Note that there are actually 3 tests, because Visual Studio automatically adds a test for the class constructor. Since we're using static methods and don't do anything in the construtor, then I changed the default test to simply verify that the class can be created:

ct

When we did the freezing point tests we wrote the minimum amount of code by simply returning the hard-coded expected results of 0 or 32. We could do the same with the boiling points, but let's skip ahead a couple tests and see if these two tests don't take care of some of the others:

// TEST: Verify that the Celsius temperature equals Farenheit minus 32 times 5/9 // TEST: Verify that the Farenheit temperature equals Celsius times 9/5 plus 32

Again we start by writing the test code first, then adjusting the class methods for the tests to pass. We can use the same to static method to convert Fahrenheit to Celsius and copy the previous test, then edit the code to create the test below:

to Celsius

For the above test I picked a random temperature, 72 F, and then calculated what the result should be. We now run the test, and since our "ToCelsius" mthod is still hard-coded to return 0 then, of course, it fails:

to celsius test result

We can now go to the ToCelsius method and fix it:

to celsius method

Let's rerun the tests and see what happens:

Notice that not only does the ConvertToCelsiusTest pass, but the previous tests also pass so that we know we have not broken any of the previously working code with our new changes. That's one of the benefits of TDD: as you build your software in small steps you build a collection of regression test that get re-run at each step, immediately alerting you when when new code causes previous code to fail.

At this point I won't bore you too much more with doing the next few tests step-by-step. The Convert to Fahrenheit test can be done the same way we just did the Celsius conversion, and the two boiling point tests can be added and run to check that our formulas work at both ends of the scale:

tests

Now we have one more test to do:

// TEST: Verify that entering a temperture less than -273.15 C throws and exception

But this suggests one companion test, verifying that absolute zero on the Fahrenheit scale also generates an exception. We can quickly add tests as we think of them by simply typing in a comment:

// TEST: Verify that entering a temperture less than -459.67 F throws and exception

Let's do absolute zero on the Celsius scale first. This is different from the previous tests, because instead of testing an assertion, we want to test that certain will generate an exception. So we need to use the ExpectedException attribute. We add it as a decoration inside square brackets between the TestMethod() attribute and the unit test method declaration. It takes a parameter for the expected exception type, so that's the first thing we need to decide, the type of exception we should generate. We could define our own custom exception, but lets just use an Overflow Exception, since we are overflowing the range of valid temperatures. Here's what the test code would look like:

Abs0CelsiusTestCode

Notice that we added the ExpectedException attribute and gave it the System.OverflowException parameter, using the typeof() function to provide the correct type for the parameter. The test code itself does not need to use the Assert method. The test method just needs to execute code we expect to generate the exception. So we take the out-of-range Celsius value, give it to the ToFahrenheit method, and try to assign it to a variable. When we run this test we get the following result:

The code did not throw an exception, therefore the test failed. We now adjust the ToFahrenheit to throw the expected exception:

Abs test fix

The test now passes:

Abs0CelsiusTestFixResult

The process for the absolute zero Fahrenheit is similar. We add the test, adjust the code ustil it passes, then we can re-run all our tests and they now all pass:

We keep removing the TEST: attribute from our comments each time a test passes and our Task List is now empty:

Summary

This demonstrates how you can do TDD, Test Driven Development, without leaving the Visual Studio 2008 environment. We added a new task type, TEST and then managed our TDD test list through the Task List. We used the integrated unit test and refactoring capabilities of VS 2008 to build a new class from scratch using the red/green/refactor methodology.

Sunday, October 19, 2008

Using Web User Controls to Create Rich Internet Application Subassembies

Web user controls provide an opportunity to combine multiple related controls into one neat package. If you combine standard form elements with components from the AJAX control toolkit then you can build a library of rich internet application elements.

Example: A Numeric Entry Control

To illustrate what I mean, let’s consider a basic web user control for numeric data entry. Of the basic HTML form elements, text box, check box, list box, radio button, etc., the only one that would work for entering numbers is the text box. But the text box will allow you to enter either text or numbers, so if you have a data entry field for a numeric values then you would need to supplement it by adding either server-side or client-side code to prevent the user from entering anything other than numbers.

Since this is a common programming task, it would be nice if we could make a generic control for numeric entry that we could then easily reuse anytime we need numeric data input.

The requirements for this control are:

  • It will only accept numeric values
  • You can set a minimum and maximum value
  • You can set it accept either integers or decimal numbers
  • You can set it add comma separators if desired

AJAX Control Subassemblies

We can make use of Microsoft’s AJAX Control Toolkit to perform the client-side tasks which will limit the user to entering only numbers within a specified range into a textbox.

The AJAX Control Toolkit uses the “extender” design pattern. What this means is that instead of creating specialized controls that that will do one particular task, they offer control extenders which all have a “target control” parameter. The extender adds some additional capability or feature to its target. Different extenders can operate on the same target control. This gives more flexibility for adding exactly the features and behaviors that you desire in a particular control.

Scott Guthrie has a great discussion of ASP.Net control extenders in his blog.

The disadvantage is that every time you want to add a particular type of control that makes use of multiple AJAX extenders then you have to combine all the parts together and wire them up for each and every field on every web page. We can give up a little flexibility but still have very useful generic components by creating web user control subassemblies that combine elements that are commonly used together.

The properties of the subassemblies are:

  • Two or more extenders are pre-wired to a common target control
  • The web user control assembly exposes public properties that control the key attributes of the extenders
  • The extenders will have reasonable default values so that you can drop the web user control onto your web page and use it with a minimal amount of effort, setting only those properties that are unique to the specific field.

AJAX Extenders for our Sample Numeric Control

We can meet the above requirements be making use of the following AJAX extender controls:

Control

Description (from http://www.asp.net/ )

MaskedEdit

MaskedEdit is an ASP.NET AJAX extender that attaches to a TextBox control to restrict the kind of text that can be entered. MaskedEdit applies a "mask" to the input that permits only certain types of characters/text to be entered. The supported data formats are: Number, Date, Time, and DateTime.

RangeValidator

The RangeValidator server control tests whether an input value falls within a given range. RangeValidator uses three key properties to perform its validation. ControlToValidate contains the value to validate. MinimumValue and MaximumValue define the minimum and maximum values of the valid range.

The range validator is actually a standard ASP.Net control but it does use the same extender design pattern. You will often combine validation controls with text boxes and AJAX extenders. By preassembling these parts you can save yourself some work.

In my next post I will take you step-by-step through a real-world example by creating a web user control subassembly for numeric data input.

Summary

The AJAX Control Toolkit and other ASP.Net components such as validators use the Extender Design Pattern, which makes them very flexible for adding features and behaviors to existing controls and allowing you to pick and choose multiple extenders to work on the same control. The drawback is that you have to do a lot more work to custom define the features and behaviors of every individual control that you desire to have a rich user interface. You can reduce this effort by creating a subassembly that combines ASP.Net AJAX and other web interface components into a web user control.

One example of such a web user control is a numeric data input control which I describe here and will create in my next post.

Saturday, October 11, 2008

Use Visual Studio Task List to Create Test Lists for Test Driven Development

Integrated TDD Environment

Introduction

The Visual Studio 2008 SP1 now includes integrated unit testing, making TDD (Test Driven Development or Test Driven Development) easier than ever before. However, if you want to use VS 2008 as a fully-integrated TDD environment, you'll need to make creative use of the Task List.

Test Driven Design and Development

The idea behind TDD is that you write all the code for your application through a series of small steps by creating unit tests. The mantra is, "Never write a single line of code unless you have a test that fails." There are a couple advanatages to doing it this way:
  • By doing things in small steps, you can go quicker with less errors
  • You create unit tests as you go and rerun them with each coding change, immediately finding any code that gets broken when you add new features

So how do you start?

Like any software project, TDD starts with requirements. What does the software need to do? You take each requirement and generate a "test list," a list of all the criteria that must be met to fulfill the requirement.

The basic TDD process is Red/Green/Refactor:

  1. Write a test that fails so that the unit test shows a red light
  2. Add code to make the test pass and show a green light
  3. Refactor to avoid duplication

Using Visual Studio as TDD Environment

Visual Studio now helps with this process. Visual Studio 2008 Professional Edition now includes the Visual Studio Test Suite (previously only Team Edition had it) which gives you the red and green lights. The Visual Studio editor also includes some built-in refactoring support.

However I would like to do everything within a single IDE if possible. I would prefer to do the Test Lists within my code editor rather than entering them into a spreadsheet, text file, or writting them down on paper. One way to do this is with the Visual Studio Task List.

Visual Studio Task List

The Task List has been part of VS since the original .Net 1.0 release. It provides a mechanism for reminders of things that developers need to complete.

You can open the Task List by selecting it from the View menu. There are two types of tasks: User and Comments. User tasks are things that you enter manually and manage yourself. Comments are created by adding comments with special key words to your code. You can then jump from your task list to the spot in the code where you put the comment.

Visual Studio provides three default tokens for comment tasks:

  • TODO: Something that needs to be started or completed. VS will automatically generate some of these, for example when you create a new class it adds, "TODO: Add constructor logic here."
  • HACK: Quickly written code that needs to be reworked later.
  • UNDONE: Code changes that have been reversed.

To create a comment you enter the comment characters, (// in C#, ' in VB), the token followed by a colon (:) and the text of the task.

We can use the Task List for TDD by adding our own comment token: TEST.

To add a custom token we select options from the Tools menu and then select Task List under Environment:

To add our new token we enter TEST in the Name field and then click Add. We can now add a Test Task anywhere in our code by starting a comment, typing TEST: and a description of our test. Now you can create your TDD test list right inside the VS source code editor for your test project.: // TEST: Verify a user can add a new record // TEST: Verify a user can update an existing record // TEST: Verify a user can delete an existing record // TEST: Verify an error occurs when add a duplicate record To implement each test you add your test code after the comment and delete the TEST: part of the comment to remove the test from the Task List:

// Verify a user can add a new record [TestMethod()] public void AddNewRecord() { // TODO: Add Test Logic }

As you think of new tests while your in the middle of coding others you add a TEST: comment and then go back to what you're working on. Later, you can double-click on an item in the Task List to go directly to that spot in the code.

In my next blog post I'll walk you through a simple example.

Happy not to be Spam

This is first cold morning of the season here in Colorado. I'm sipping my Starbuck's pumpkin spice latte and rejoicing that my blog has been cleared by the Blogger spam cops. You see, soon after I posted my first entry I received an email saying, "Your blog has been identified as a potential spam blog. To correct this, please request a review by filling out the form [here]." I checked my blog this morning and it's all back to normal again. I've been approved. Now that I've been approved, where do I start? Yesterday a was a bit of downer at work. It was the last day for several of the contractors because the company I work for is feeling the credit crunch and economic downturn that is dominating the news now. Last week was the "worst week in stock market history." I've heard that before. The economy goes in cycles. We're near the bottom now, there's brighter days. It's just hard to believe it at the moment, but we can ride the coming bull market to success. After working in IT for 20 years I've come to accept the fact that software developers are an expense that every business needs to minimize in order to be successful. The key to success as a programmer is to be a partner with your employers to deliver the highest quality software at the lowest cost possible. Today we have many tools and methodologies to help achieve that goal. In future blog posts I will be covering things like the newest versions of languages and developer tools, Test Driven Development, MVC, agile development, combining it all together into the "Get 'er Done" methodology.

Sunday, October 5, 2008

Finally starting to blog

Hi, My name is Ray Wampler and this is my first blog. Why would anyone want read a blog by me? There are a few areas where I have some expertise that other people might find interesting:
  • I've worked in the IT/Software industry for over 20 years for a variety of companies and industries. I keep up on the latest technologies and trends.
  • I've been in Toastmasters for 8 years, earning the distinction of Advnaced Communicator Silver and Advanced Leader Silver, and I'm currently working on my Distinguished Toastmaster.
  • I keep informed on a variety of topics including health and nutrition, travel, volleyball, business, and investing.

These subjects will hopefully provide a wealth of topics for interesting and entertaining blog posts. I plan to add to this blog on a regular basis, providing usefull information to my readers.

Regards,

Ray Wampler