Archive for the 'Free Code' Category
Authorize.Net Code Release
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:
- Zip
- SecurityCode
- CardNumber
- ExpDate
EMail, CardNumber, and ExpDate validation have been completely rewritten.
ExpDate now accepts the following formats:
- MMYY
- MM/YY
- MM-YY
- MMYYYY
- MM/YYYY
- MM-YYYY
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.
INotifyPropertyChanged
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:
{
…
}
Then implement the PropertyChangedEventHandler and add a method to fire the event:
protected void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
Then call the method whenever a property changes:
{
get { return _first; }
set
{
_first = value;
OnPropertyChanged("FirstName");
}
}
Easy as can be!
Transaction.ProcessPayment
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:
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.
2 commentsExtensions update and new Namespace added to Free Code
In support of the Authorize.Net project, I have updated the Free Code page:
- DevelopingForDotNet.Extensions – updated with many new Extension Methods.
- DevelopingForDotNet.RegexSupport – contains a list of useful Regular Expression Patterns.
Extension Methods Update
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.
No commentsUpgrade your C# Skills part 1 – Extension Methods
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 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 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:
if (Regex.IsMatch(s, "awe"))
{
Console.WriteLine("Yep, this is a match!");
}
else
{
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:
if (s.IsRegexMatch("awe"))
{
Console.WriteLine("Yep, this is a match!");
}
else
{
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:
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:
- Extension Methods must be static, defined in a static class
- Extension Methods must be public
- 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:
{
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:
s = RightAdjust(s, 7, ’0′);
// Value of s is now "0001234"
Now, let’s convert this to an Extended Method:
{
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:
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:
{
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.
Conclusion:
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.
9 commentsFilmStrip Control
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!
No comments
