Archive for the ‘Free Code’ Category

Authorize.Net Code Release

September 29, 2008 6 comments

Back in February I posted the beginnings of a project to wrap Authorize.Net credit card transactions in C# .NET code. I have been working on this project off and on, in conjunction with a new website we are developing, and have been meaning to post the production version for some time.

Today, I am publishing the current version of the code, DevelopingForDotNet.AuthorizeNet, along with a few supporting updates. I’d like to thank everyone who posted comments on that entry and the First Foray into Unit Testing entry. Most of those suggestions made it into the final version and I learned a lot about Unit Testing along the way.

This version is slightly different than the original post. Here are the major differences:

Validity Checking

This version incorporates validity checking on the following TransactionRequest class properties:

  • EMail
  • Zip
  • SecurityCode
  • CardNumber
  • ExpDate

EMail, CardNumber, and ExpDate validation have been completely rewritten.

ExpDate now accepts the following formats:

  • MMYY
  • MM/YY
  • MM-YY

The Validity Checking uses a set of Regular Expression patterns that I have put into another namespace, DevelopingForDotNet.RegexSupport. It will be available on the Free Code page as well.

Right now, all the failures throw an ArgumentException, which is very heavy handed but I haven’t had a need to improve it yet.


Each of the three classes implements INotifyPropertyChanged so you can use them for data binding if you wish. If you have never implemented this interface before, it is very easy. Add a reference to System.ComponentModel to your code. Then add the inheritance statement to your class:

public class TransactionRequestInfo : INotifyPropertyChanged

Then implement the PropertyChangedEventHandler and add a method to fire the event:

public event PropertyChangedEventHandler PropertyChanged;

protected void OnPropertyChanged(string propertyName)
    if (this.PropertyChanged != null)
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));

Then call the method whenever a property changes:

public string FirstName
    get { return _first; }
        _first = value;

Easy as can be!


Transaction is a static class with ProcessPayment as its single static method. In reviewing the project, I realized that this was a perfect case for an Extension Method, so I added this before the first keyword, and now calling the method is even nicer than before:

// Account is built above...
TransactionResponseInfo pmtResponse = pmtInfo.ProcessPayment(Account);

Unit Testing

I really got my feet wet with Unit Testing on this project. I followed the advice I got from FreekShow and implemented the testing of Exceptions in a much cleaner fashion. The whole experience got me thinking about why Unit Testing is so beneficial, and as I began rewriting the code I started by writing tests that fail first and then coding my way into success. Just for grins, the testing project for this solution is included in the download.


Extensions update and new Namespace added to Free Code

September 29, 2008 Comments off

In support of the Authorize.Net project, I have updated the Free Code page:

Categories: .NET 3.5, Free Code

Extension Methods Update

January 2, 2008 Comments off

I’ve been working on some more Extension Method stuff (I’ll be sharing soon!), and in the process I updated the DevelopingForDotNet.Extensions namespace.? Here is a list of the updated methods:

  • DateTime.GetDateString() – accepts an Enum for the format of the DateTime string (Enum is part of the namespace).? Overridden to allow control over the separator character.
  • DateTime.TwoDigitYear() – returns the Year of the DateTime in two digit format.? Great for aligning with legacy data.
  • IDictionary.ExecuteOnValues<K, V>() – performs an Action<V> on each Value in a Dictionary.
  • decimal.ConvertToMoney() – Converts any decimal to a two decimal precision numeric.? Overridden to allow control over rounding behavior.
  • decimal.GetMoneyString() – Converts a decimal to Money and returns a properly formatted string.
  • decimal.GetUSMoneyString() – implements the above, but specific to US Currency.? Also overridden for rounding.
  • long.ConvertToWords() – converts a long value to spelled out words.
  • decimal.GetDecimalNumbers() – returns just the decimal portion to the right of the decimal point as an integer.
  • StringBuilder.Clear() – clears all text from a StringBuilder (sets its length to 0).

Be sure to download the update.? Keep watching, there will be more to come.

Categories: .NET 3.5, C# 3.0, Free Code

Upgrade your C# Skills part 1 – Extension Methods

November 26, 2007 9 comments

DOWNLOAD the Code!

Now that I have VS2008 and .NET 3.5 installed, I am going to begin a series of articles on some of the new features you can use in C#. My hope is to add one new article a day for the rest of this week. Along the way, we’ll explore some of the new language features for C# 3.0. Truthfully, they aren’t all that new since C# 3.0 has been around for about a year, but support for them is now built in to Visual Studio, so using them is now realistic. Also, with the release of VS208, I’m sure this will be the first time most developers will be exposed to them. I’m going to start by introducing one of my favorite enhancements: Extension Methods.

Extension Methods

Extension methods offer us a way to expand class functionality even if we do not have access to the code for those classes (including sealed classes). In other words, we can add our own functionality to any object type. Have you ever looked at the String class and said “why can’t I do {fill in the blank} with a String?” If so, you probably created your own method, passed it the string in question, and consumed the return value:

string s = "1234";
string z = Reverse(s);

If you’ve ever written code like this, then Extension Methods are for you. In the case above, it should be obvious that Reverse is a static method, since it is not attached to an instance. Wouldn’t it be nice instead to write this?

string s = "1234";
string z = s.Reverse();

I know it is a subtle difference, and in this case not a terribly functional one, but hopefully you can see the difference. Instead of passing the string variable to a static method, you can treat your methods as though they belong to the string class. And these new methods are available in Intellisense: when I type “s.”, I will see my extension methods right alongside all the native methods, which makes finding and using them much more palatable. And you will find in the new Intellisense that Microsoft itself is making heavy use of Extension Methods. You can tell in two ways: first, the icon for extension methods is the familiar purple box but accented with a blue down arrow. Secondly, when the method description pops up in Intellisense, the description is preceded by “(extension)”.

Let’s look at a more reasonable example. Using the Regex class, you can determine whether or not string matches a Regular Expression pattern by passing a string and a pattern to the Regex.IsMatch() method:

string s = "This is awesome";
if (Regex.IsMatch(s, "awe"))
    Console.WriteLine("Yep, this is a match!");
    Console.WriteLine("Sorry, no match.");

I think it would be handy on occasion to simply “ask” the string itself if it matches a certain pattern:

string s = "This is awesome";
if (s.IsRegexMatch("awe"))
    Console.WriteLine("Yep, this is a match!");
    Console.WriteLine("Sorry, no match.");

Pretty neat, huh? OK, I admit it doesn’t appear to lessen your code, but to me it can make your code make more syntactic sense. And given a more complex example, it could do a lot for you. Richard Hale Shaw showed us an example of a .ForEach extension for IEnumerable<T> collections that would knock your socks off! Imagine being able to loop through an entire Collection and perform some action on each item in a single line of code, without passing the Collection off to a method? It would look something like this:

DirectoryInfo dir = new DirectoryInfo("C:\\");
FileInfo[] files = dir.GetFiles();
files.ForEach<fileinfo>(f => Console.WriteLine("{0} {1}", f.FullName, f.Length));

For now, ignore the code between the () – that’s a Lambda Expression, and we’ll get to those later in the week. Just understand that with this sample above, each FileInfo object in the array will have the passed Action applied to it. How many foreach loops do you think this little nugget could eliminate?

Now, I hope this will get you interested in Extension methods: it didn’t take me too long to think these are very cool! To get you started, I’m adding a new project called DevelopingForDotNet.Extensions to the Free Code page . My take on Richard’s method(s) are included, along with a handful of String and Numeric operations. Nothing too fancy, but hopefully enough to help get you started.

Enough already, how do I do it?

Creating Extension Methods is very simple. First, you must follow these simple rules:

  1. Extension Methods must be static, defined in a static class
  2. Extension Methods must be public
  3. The this keyword precedes the first parameter

We’ll take these one at a time. First, the method must be static because of how the compiler handles extensions. Behind the scenes, whenever an Extension Method is employed, the compiler actually generates code to call the static method. The idea of the Extension Method is just a visual layer for the developer: behind the scenes the actual static method is being called. Also, these methods can be called in a static fashion, rather than as methods attached to an instance. Which brings up another good point: the class name the Extension Methods are in is essentially irrelevant (unless you are going to call them explicitly). I put all my extensions in a single static class (imaginatively called “ExtensionMethods”).

Second, they probably do not absolutely have to be public, but if they aren’t then you are severely limiting the functional scope, so what’s the point?

Finally, preceding the first parameter with “this” is what tells the compiler that this is an Extension Method. It is also probably going to be the main source of initial confusion, because you do not pass this parameter (unless you are calling the method explicitly).

Overall, these are fairly simple rules to follow. Here is a handy method I’ve used for a while:

public static string RightAdjust(string s, int Size, char FillCharacter)
    string ch = FillCharacter.ToString();

    if (s.Length > Size)
        throw new ArgumentException("Size of Value larger than Requested Size.");

    while (s.Length < Size)
        s = ch + s;

    return s;

This method receives a string and right adjusts it to the given size, filling the leading characters in with the passed char. Calling it looks like this:

string s = "1234";
s = RightAdjust(s, 7, '0');
// Value of s is now "0001234"

Now, let’s convert this to an Extended Method:

public static string RightAdjust(this string s, int Size, char FillCharacter)
    string ch = FillCharacter.ToString();

    if (s.Length > Size)
        throw new ArgumentException("Size of Value larger than Requested Size.");

    while (s.Length < Size)
        s = ch + s;

    return s;

All we did was add “this” before the first parameter. Now we can call it like so:

string s = "1234";
s = s.RightAdjust(7, '0');
// Value of s is now "0001234"

Naturally, you will need to add a reference to the DLL that contains your Extension Methods in order to find and use them.

Overloading Extension Methods:

Just like other methods, Extension Methods can be easily overloaded. My approach for overloading has always been to put all the functionality in the method that requires the most parameters. I then simply have my overloading method signatures call the primary method, sending it the appropriate parameter values. Looking at the RightAdjust method above, I want to establish a method that will use a blank character as the default fill character if one is not supplied. What’s different about overloading extension methods, is that I actually employ the primary extension method in my overloading methods:

public static string RightAdjust(this string s, int Size)
    return s.RightAdjust(Size, ' ');

So now I can call this method passing it just the Size parameter, and that method then calls the primary method using the Extension Method mechanism.


Extension Methods can be as simple or complex as you like. They are a nice syntactical enhancement to the language that lets you enhance other objects and use them how you would like. But beware: you could easily go overboard. I mean, there is no reason to create a MakeDirectory method for a TimeStamp instance, but you could. Just use common sense and make sure that the extensions you create apply to the object type and way that you would use them.

FilmStrip Control

November 11, 2007 Comments off

One of the current projects I am working on is Image Management software for one of our legacy government applications. Basically, JPG images are stored on a Windows server and our iSeries machine issues local PC calls (using STRPCCMD) to initiate the image manager. The manager then finds and displays all the images associated with the particular database record. The details are irrelevant to this post, but each database record can have up to 99 images associated with it, all organized and retrieved by naming conventions, so managing these images is not a trivial matter.

The original version of this software was written in VB a decade ago (probably VB4 or VB5). It was sufficient but unpleasant so about 5 years ago the company contracted with a local developer to rewrite the application, which he did … in FoxPro. It is also functionally but unpleasant to use, and so I find myself looking at a good target for a .NET rewrite!

One of the problems with the current version of the software is you can only see one image at a time. Unfortunately, this means you have to view each one to find the correct image, a real annoyance when dealing with large numbers of images. So my solution is to incorporate a FilmStrip control to view and scroll through a list of thumbnail images. I also, naively, thought this would be a fairly standard control, but alas it does not exist in the MS toolbox. This means creating one of my own, not a task I relish. I haven’t had lots of luck with User Controls or drawing my own. I find it tedious and frustrating: in other words, it just isn’t my cup of tea.

Fortunately, we have Google. A quick search for “C# FilmStrip” turned up this gem on CodeProject (one of my favorite sites). Most of the nitty gritty and the solution for my project came directly from that version, so I want to give full credit. The example was an excellent starting point, but I have, naturally, added some goodies of my own.

First of all, the original version required the user to pass the path string to the AddPicture method. Instead, I wanted to make this Control a little more portable: since it deals primarily with a collection of Images, I decided to have the FilmStrip work with Image objects and let the consuming code worry about pathing. The original also provides a way to print labels for the images, but they are based solely on a parsing of the image name. Instead, my version allows the user to assign a label to associate with the image. These are both done through a custom Struct named PictureInfo. Currently the Struct is pretty limited with just these two properties, but it could be easily expanded to contain any associated data. Also, I wanted to add some way of selecting and identifying one of the Images (PictureBoxes), so I added code to track which PictureBox is currently active and I change the BorderStyle of the active PictureBox to identify it as such.

Finally, I need the FilmStrip to report to the consuming software when the selected PictureBox changes, so I added an ActivePictureBoxChangedEvent, complete with its own ActivePictureBoxChangedEventArgs class that exposes the PictureInfo object of the newly selected PictureBox. By exposing the PictureInfo object, the consumer has direct access to the original image and whatever other information gets added to the PictureInfo struct.

The FilmStrip dynamically sets the size of its child PictureBox controls based on the size of the FilmStrip control and even calculates and applies the correct aspect ratio to the thumbnail based on the aspect ratio of the actual image. The full image is stored in the PictureInfo Struct so it can be reclaimed at anytime. I used a Generic Dictionary<PictureBox, PictureInfo> list to keep the PictureBox controls associated with the correct PictureInfo instance.

The public DisplayImages method can be used: just monitor the Resize event and call it accordingly.

Possible improvements:

  • Replace the scroll bar with navigation buttons.
  • Display the images as an automatically wrapping collection, always center the active image in the display.
  • Make the active image a larger size than the other images.
  • Add the ability to set the active picture box border color and/or style.

I hope you like this Control. Download it and try it today. Let me know what you think!

DataTables ToolKit

September 25, 2007 Comments off

Howdy readers!

I have something new for you which I hope you find useful. Most of my projects are database oriented, which in ADO.NET land means a hefty reliance on DataTable objects. In fact, my first serious .Net program was an Ad Hoc SQL tool that allowed the user to connect to virtually any database and issue SQL commands. Beginning with that program, I wanted the ability to take the data from a DataTable object and export it to CSV. In several subsequent projects I needed the same feature, but I never took the time to externalize it. Well, a couple of weeks ago a new project came across my desk that required this feature again.


And so the DevelopingForDotNet.DataTables namespace is born. As of this writing, there is only one class in the namespace: DataTablesToolkit. This is a static class containing, at the moment, two interesting methods.


The first is the one mentioned above, DataTableToCSV. This method does exactly what you think: it takes a DataTable object and generates a string representing its contents in CSV format. The first line can optionally contain the list of Column names. String values are wrapped in double quotes and lines are terminated with \r\n.

There is one limitation: support for complex data types is limited to their .ToString() implementation. If a DataTable contained a type without an appropriate implementation, “unexpected results may occur.”

I have some future enhancements in mind:

  • Add additional terminator support. Depending on the consumer, the output may need just line feeds or carriage returns. This would be simple enough to add via a parameter.
  • While it would no longer be CSV, a similar method for Tab Delimited would be useful.
  • Add the ability to save the string to the file rather than requiring the consuming code to implement the IO.


While working on this project, an interesting problem cropped up. The database in question stores US Zip codes as numeric(5,0) fields. This causes a problem for zip codes beginning with a “0”: the leading zeros are lost when the data is read in from the database. In order to address this, we created a custom data type that replaced the missing leading zero and stored the value as a 5 character string.

Unfortunately, this meant that we could not rely on the DataTable automatically filled by our xxxDataAdapter. Instead, we had to read the data out of the DataTable and store it in our custom data type objects. This worked great and solved the problem (as well as a couple of others relating to the data), but it introduced a new problem: the DataTableToCSV
code we just created was now unusable! Our data was no longer in a DataTable!

I was about to write custom code to create a new DataTable based on the properties of our custom data type when it hit me: I could use Reflection to do that for me. Better yet, I could make it generic enough that I could create a DataTable based on ANY object I wanted. And so I did.

This was my first real foray into Reflection, and I have to admit I thought it was going to be a lot more complicated than it ended up. I mean, I slaved for MINUTES on this code! The longest part was in me finally getting a good understanding of the Type type in my thick skull. Once I had that, the rest was very easy. So now, I simply pass the Type of my object in and I get a DataTable object back, complete with a collection of appropriate DataColumn objects that match the properties of the Type.

This too has some limitations:

  • As written, it can only handle properties that expose primitive data types. Complex data types are ignored. This will make perfect sense if you think about it: how would a Collection, or a FileStream, or something of that nature be depicted in a DataTable? For now, I think this is a reasonable limitation.
  • Only public, non-static properties are currently reflected. Support could, and probably should, be added for protected members, but I think that would need to be optional. When I was writing this, it just didn’t seem to make sense to me to expose static properties, but it would be easy enough to add if desired.

Now, I can use this to create my new and improved DataTable, and I can easily loop through my collection of custom data type objects to populate its rows.

And so altogether, this represents the DataTablesToolkit. Download the code and try it out. Let me know how it works for you.

Categories: .NET 2.0, C# 2.0, Free Code

More on PropertyBuilder

September 11, 2007 Comments off

I have posted an update to the PropertyBuilder code. Actually, the code hasn’t changed but the solution now includes a Setup Project. I also put a copy of the MSI file in the root PropertyBuilder directory, so if you just want the tool and don’t want to worry with the code you can just install it and use it locally.

There were a couple of things about the code I failed to mention in the previous post. First, it uses Compile Time Directives to branch the code into different groups based on a Defined variable. I’ll have to write a post about this – it is a neat way to test variations and modifications to code. Currently, the code is using Regex.Replace() to make its changes, but the original version was a bit more brute force and was left in place to show the differences between the two approaches. The Regex version also takes advantages of templates rather than inline strings. On the Code Generation front, these templates could come from anywhere, such as external text files, XML, settings, or even a database.

The one thing I don’t like about the tool is that it always places the variable declaration directly above the property. I’m a bit anal about stuff like that, and I like to have all my class level variables defined before the constructor, so having it inline like that grates on my nerves. In a future version, I am going to add a split panel option to generate the variables in one textbox and the properties in a separate textbox. That way they can easily be copied and pasted separately into my code at the appropriate places.

Now what would be REALLY cool is to be able to integrate this with Visual Studio and provide the option to select a variable and automatically generate the Property from the variable, kind of like the inheritance and constructor stubbing we already have. But truth be told, I’ll probably never have time to figure all that out.

Categories: .NET 2.0, C# 2.0, Free Code