Enhancing the TypeSafe Enum Pattern

By: Brian Dobberteen

As I mentioned in my last post about the Typesafe Enum Pattern in C#/VB.NET, I left out a few features that I had originally wanted to include in that post.

Namely, these features were nothing more than implementing the IComparable<T> and IEquatable<T> interfaces.

Upon further investigation, I’ve found that there is no need to implement IEquatable<T> here, as we’ll see in an example in just a moment.

Also, I’m not sure how often we’d find ourselves needing to sort collections of our enum-esque class.

Here’s the original class from the previous post:

The ‘Enum’ Class

This will be our baseline to begin implementing the interface(s):

Again, if you’d like to re-familiarize yourself with the above code and its features, check out the original post: Typesafe Enum Pattern in C#/VB.NET.

Do We Need IEquatable<T>?

See for yourself:

This behaves just as a normal Enum would. Clearly, there is no need to implement IEquatable<T> in this case.

Do We Need IComparable<T>

IComparable<T>, on the other hand, might prove useful if we ever find ourselves wanting to sort an Array, etc, of UselessItem pseudo-Enums.

Without implementing IComparable<T>, we are not able to do:

Implementing IComparable<T>

IComparable<T> is definitely one of the easier interfaces to implement – it only requires the implementation of a single method:

int CompareTo(T other);

CompareTo returns:

If this object is less than the other argument, the method returns a negative integer.If this object is equal to the other argument, the method returns zero.

If this object is greater than the other argument, the method returns a positive integer.

See MSDN’s Entry on IComparable<T> for more information.

This mechanism is what allows, for example, Array.Sort() to work easily with a simple lambda expression.

So let’s implement it!

In line 18, you can see that we want to be able to sort by our ItemName property. Sorting the GUID ItemIDs is probably something of little interest, but it certainly can be done as well. In fact, this pattern can be used to make our enum-esque Class sortable by whatever property/datatype we might need for our purposes.

Let’s try a sample sort:

Not too shabby!


Well, we haven’t added a ton of real-world useful functionality to our enum-esque Class, though it was an easy way to demonstrate the implementation and usefulness of IComparable<T>. Initially, I had thought that implementing IEquatable<T> was also necessary to do simple operations such as:

But, as it turns out, the nature of our enum-esque class gives us the above capability out-of-the-box.

And free stuff, that works as expected? A rarity these days!

Setting up VisualSVN for Local Projects

By: Brian Dobberteen

This one is pretty straightforward, but potentially useful to those of you not yet familiar with source control.

In a nutshell, source control allows us to keep a historical record of any changes we’ve made to files over the course of time. This is beneficial because if multiple people are working on the same project, it can be very easy to accidentally overwrite someone else’s changes that you may not have been aware of. It also gives some peace of mind to know that copies of your teams’ work are safe from accidental local deletion, corruption, and other such maladies.

The source control system that we will be using today is known as Subversion.

Subversion (SVN) is an open-source, widely used, and in my experience, very solid choice for a version control system (VCS). To be sure, there are many others out there, such as Git, Mercurial, Team Foundation Server, CVS… the list goes on.

We’re going to quickly learn how to get an SVN server up and running on your Windows box with the aid of two software packages: VisualSVN Server and TortoiseSVN (which will serve as our client).

First, let’s grab these two packages – try and be sure to grab the latest stable release offered at each site.

VisualSVN Server: http://www.visualsvn.com/server/download/

TortoiseSVN: http://tortoisesvn.net/downloads.html

Installing VisualSVN Server

Fire up the VisualSVN Server installer that you downloaded from the above link. Follow the on-screen prompts – the default settings should be fine. Once that’s done, it should offer to take you right to the VisualSVN Server Manager Console – click OK and we’ll find ourselves at a screen that should look similar to:

VisualSVN Server Management Console

The next step is to create at least one user and one repository:

Adding Users and Repositories

Creating a new user couldn’t be simpler – just decide on a username and enter/confirm a password.

Setting up a new repository is equally simple – all you need to do at this point is give it a name, preferably something meaningful to you and your team. For now, don’t worry about the ‘Create default structure’ checkbox and make sure that it’s not checked.

And that’s it! Told you it was simple!

Installing and Using TortoiseSVN

Again, first step will be to run the TortoiseSVN installer that you downloaded earlier. Just accept any default settings. Once the installer is done, it will prompt you to reboot – go ahead and do so.

Once back in Windows, we find that our right-click context menu has some new additions:

Next, we’ll want to create a folder to create what is known as our ‘working copy’ of the project that will now be under source control.

In whatever location you deem appropriate, create a new folder, preferably with a name that matches the name of the repository you created earlier in VisualSVN Server.

Once that’s done, right click the new folder, and then click on ‘SVN Checkout…’ in the context menu, which brings us to:

All that’s needed for this screen is to type the URL of the repository you’ve created. I’m using localhost here, and this may or may not work. If it does not, replace localhost with the name of your machine.

Finally, replace where I show ‘Site1’ with the name of the repository you created earlier.

Leave all other settings as they are, then click OK.

Because we’re connecting over SSL, TortoiseSVN will prompt you about whether or not you want to accept the security certificate. Choose ‘Accept Permanently’ and you’ll be good to go for now and in the future.

Now, you have an active ‘working copy’ that is under version control by SVN!

Adding Project Files to SVN

If you already have an existing project, made up of files and directories, the first step will be to copy those items to the folder you just did the SVN Checkout to.

Note that it is easy to tell at a glance what folders/files are under source control, and what their current status is:

So, let’s add some files to our working copy folder and place them in to the repository.

The first step is to select the files that you want to place in the repository by first selecting those files/folders, right clicking your selection, and choosing TortoiseSVN -> Add…

Which brings us to:

Leave everything checked, then click OK.

TortoiseSVN will show the progress of the Add – if everything went ok, it should say so. Click OK to close the window.

Note that now each file/folder icon will be overlaid with a blue plus sign, indicating that it has been added but not committed.

The final step is to Commit these added files/folders by again, first selecting the ones you’ve just added, right-clicking that selection, and choosing ‘SVN Commit…’:

Which brings us to:

The area circled in red above is a text area to enter a log message detailing what you are committing. Personally, I think it best to always try to include some meaningful comment about what you’ve included/changed in the commit.

Messages like: ‘Pulled the javascript out of index.html and placed it in scripts/myscript.js” can definitely be of help.

Though the log message is optional for us, some shops may require a log message on each commit.

Don’t be lazy – always enter a commit log message!

Once you’re done entering your message, click OK. TortoiseSVN will show the progress of the commit, ending with a display of what revision you are now on. Since this was the very first commit, it makes sense that you should see that you are now at Revision 1.

Day to Day Usage of SVN

Frequently Updating and Commiting your project files is an excellent habit to get into. We already know what a Commit does, and I bet you can guess what an Update does.

To try it, select any files you’d like to have the latest copy of so that you can be sure that you’ve picked up any changes by other members of your team. Right click these selected files and click SVN Update…

Since you are the only one who has committed anything to this point, you’ll see that nothing has changed and that you are still on Revision 1.

Next Steps

Add more users, one for each member of your team.

Add more repositories, one for each of your projects.

Individually make and commit changes, being sure to update after each one to ensure you have the latest code.

Experiment with features such as ‘Locking’ which will prevent other team members from modifying the locked file until you release that lock.

Hopefully this has been of some use to you CVS n00bs out there – next time, we’ll go over conflict resolution, an important tenet of version control.

Typesafe Enum Pattern in C#/VB.NET

By: Brian Dobberteen

Been doing some thinking about Enum and a couple of its shortcomings.

First, let’s create a simple Enum:

From here on out, we’ll stick to C# in these examples (VB.NET source available for download soon!).

A recent project prompted me to create a number of Enums, as I have done in the past in many other projects.

For this project, however, I had a desire to have tighter control over the usage of the Enum type, as it dawned on me that:

Ok, well that’s kinda disconcerting, but I’m sure .NET has a library function to check if an Enum value is defined. Not surprisingly, they do, and even less suprisingly, it is:

Enum.IsDefined(Type enumType, Object value)

Works great:

No surprises here, right? Well… maybe not so fast.

Hit up Google for some research and immediately found widespread concern over the performance of Enum.IsDefined().

It turns out that Enum.IsDefined() uses Reflection and must access metadata in order to do its magic. Neither of these operations are real speed demons, to be sure, and when using IsDefined in a loop with a ton of iterations, these performance problems may manifest themselves in an attention-getting way.

No, I never bothered to test this.

An alternative method for checking if an in-range UsefulItem variable was given:

This works, but what about when you add another UsefulItem to your Enum definition? The code above suddenly goes stale, maintenance nighmare ensues, company goes under, and you begin your unlimited unemployment benefit checks!

And the above was for a simple enum that had integer values in the Enum definition that matched the integer values in the DB lookup table. (The use of Enums to represent DB lookup table values can be discussed at another time).

The next Enum I needed to create didn’t have any integer values to line up with. The next lookup table that I wanted to represent used GUIDs as its primary key (PK) and this doesn’t work:

I get that last snippet was a bit gratuitous – we all know by now that Enums use integers as their underlying datatype.

And not only did I want to have a GUID represent each of my quasi-Enums, but I also wanted string representation beyond the camelcase names in the Enum. I won’t bother with another silly example – clearly a string is not an int, and can in no way be tied to the members of an Enum.

During my earlier research that revealed .NET’s willingness to allow any integer to be assigned to an Enum, I stumbled across something called the Typesafe Enum Pattern.

For reasons unknown to me, Java apparently doesn’t do Enums. That may not be entirely true, but for the sake of argument, let’s just over-simplify things here and agree that Java doesn’t do Enums.

I ended up finding Replace Enums with Classes [sun.java.com] and was inspired by what I read.

It led me to develop:

Note that the version above has been somewhat stripped down for clarity – originally I had implemented both IComparable and IEquatable as well as overridden the ‘==’ and ‘!=’ operators and the ToString() and GetHashCode() methods. These changes are left as an exercise for the reader 😉

Using this newly created struct, let’s check out some of its characteristics:

Could a disgruntled fanboi do this?

Definitely not! Note lines 3 and 4 of our UselessItem Class definition – they only allow setting of these two properties from within the class itself. This is caught at compile time and simply not allowed.

Other things that the compiler will keep us safe from:

In line one above, we cannot create new UselessItem objects, thanks to our private explicit default contructor:

Lines 3 and 5 will fail to compile as nothing but UselessItem objects can be cast to UselessItem.

Though this, as contrived as it is, will only be caught at runtime:

Try the above code and get an InvalidCastException at runtime, killing the application if not caught.

And we even get the same behavior out of our class as we would a traditional Enum:

For some reason, this surprised me. At first, I thought that using a struct rather than a class would be prudent here, seeing as how structs are value types and classes are reference types.

After giving it a bit of thought, I believe it is because we cannot actually even instantiate a UselessItem object, we don’t have to worry about usual reference type behavior.

There is some tradeoff, I suppose.

Because a class can contain an explicit parameterless constructor, and a struct cannot, we end up the following difference between the two approaches:

Assume for a moment that UselessItem is indeed a struct:

Because structs are value types, they can never be set to null. This is partly the reason why they cannot have explicit parameterless constructors. Calling new on a struct is no different than declaring a new struct variable without assigning a value:

Though you aren’t able to use the ui2 variable here (compile-time error – Use of unassigned local variable ‘ui2’) it is plain to see during debugging that after line 2 above has run, both ui1 and ui2 contain the same values, which for structs, are all the default values for each type contained within (in this case, null for the ItemName and {00000000-0000-0000-0000-000000000000} for the ItemId.

On the other hand, using a class, we end up with:

Obviously, the code in line 1 above is not an issue, since it fails at compile time. ui2, though, is actually equal to null following this initial declaration. Again, this is contrast to a struct, who ends up with default values for all of its members.

I, for one, think the use of a class here is a bit cleaner, as we can just check the whole object against null rather than checking some/all of the struct members against default values to determine if our object represents an unknown, or null, UselessItem.

Pretty cool!

Would love to hear comments on this approach – go ahead, tear me a new one, I can take it.

Using PHP and MySQL to Create a Simple Contact Form and Results Browser

By: Brian Dobberteen

By request, let’s build a simple Contact Form with a PHP/MySQL backend!

(Disclaimer: I don’t pretend to be an expert in PHP [nor .NET for that matter!], so please understand that the way I go about this might be sub-optimal. Whatever, sue me.)

Building the HTML Contact Form

This part is as straightforward as can be. We’re going to create a ‘Contact Form’ with a grand total of THREE fields – extending this model is left as an exercise for the reader (lol, always wanted to write that!)

For brevity, we’re going to use the HTML5 doctype and a table-based (gasp!) layout. Feel free to change it to whatever you want.

Here goes:

Which, in IE9 renders as:

I’ve highlighted line 10 above to bring attention to the ‘action’ attribute of our opening form element. Whatever the form’s action is set to is where, on submission, the form ‘posts’ its values to. To read more about HTTP POST, please visit google.

And that completes the form!

Creating a MySQL Table to Store Form Values

Again, as a Microsoft fanboy ©, I rarely spend much time with MySQL in any real capacity. You have been warned.

We are going to assume that you have a MySQL instance installed and available to you. And that you know how to login and arrive at the MySQL ‘command line.’

Once logged in, we’ll first need to create a new database to store our new table which in turn will store our contact form values:

Not surprisingly, this creates a new database with the name MyRadContactForm. The ALL CAPS is not required, but SQL is typically written in this fashion.

Next, we must let MySQL know what database we want to use:

Now our new DB is the active one, and we can create our table in it:

Quickly, ContactID is what we call a Primary Key – it is used to uniquely identify each record in the table.

It is an INT (Integer) type, meaning it can store whole numbers.

It is a NOT NULL column, meaning that it must contain a value for each row in the table.

And finally, it is an AUTO_INCREMENT column – this means that each time we add a new record to this table, MySQL will ensure that each ID is unique by essentially adding one to the highest existing ID at the time of a new insert.

VARCHAR(100) means that we can store a string (sequence of letters, numbers, etc) up to 100 characters in length.

DATETIME… well, that should be obvious.

Our new table should now be in place, though to quickly check, we can try:

Creating PHP Server-Side Code to Store New Values

Well, now we have something the client sees (the HTML form) and something buried deep within the bowels of a database to store values input by the client.

How, then, do we manage to bridge the gap between these two pieces?

In this case, we’ll use PHP.

We assume that you have a functioning PHP installation. Check out xampp for a relatively painless way to get up and running with PHP/MySQL/Apache on various platforms.

Right, without further delay:

This example is lacking in a number of areas, but we aren’t going to care about SQL Injection or error-checking at this point.

Brief rundown of the above code:

Lines 4-6: We are creating three variables to store the values of our incoming form. Note that each item matches the ‘name’ attributes of our form inputs.

Line 11: This is the equivalent of the USE MyRadContactForm command that we issued earlier to our MySQL server prior to creating our table.
Line 13: This is the beginning of an SQL INSERT statement. Not surprisingly, this command inserts new records into our table. In the first set of parentheses, we specify which table columns that we want to store our data in. The second set of parentheses represent the actual values to store in the table.

Lines 20-22: PHP makes life a bit easier for us here, as it will automatically detect our variable names and replace them with the values they contain. NB: The $sql string we’ve created is surrounded with aka double quotes. This is crucial to get this behavior. The variable names are themselves surrounded by aka single quotes, as this is standard SQL for indicating that you are working with string values (aka VARCHAR).

Line 23: We call the MySQL built-in function NOW() to store the current date/time in ContactDateCreated at the time our insert is performed. There are other ways of handling this (such as declaring a variable in PHP), but this is easy.

Line 26: mysql_query does the actual work of sending our INSERT statement to our DB via the $sql_connection we created earlier.

Remember, this is just a primer (and not much of one at that!). Writing code like this will likely draw ire from your peers and pink slips from your employers.

Creating an HTML Contact Form Submission Viewer

So, we’ve got our form, database, table, and server-side PHP script. If all is well, we should now be adding new records to the table with each form submission.

But what good does this data do anyone if it is tucked safely away in the bowels of our MySQL server?

Let’s make a quick-and-dirty PHP page to display the input values:

Line 26: Finally, we use echo one last time to close our <table> tag.


Line 12: This time, since we want to display data already in our DB, rather than insert new records, we issue a SELECT statement. The * (asterisk) tells SQL that we want every column for each row we get back. We store the data we receive in a variable named $result.

Line 14: Using PHP’s echo command, we begin the definition of our HTML table. PHP echoes its argument to the HTML page seen by the end user.

Line 17: The keyword while indicates to PHP that we want to start a loop, in which we will output the values stored in each row of our DB. When we reach the last row, the while statement is no longer true, and the loop exits.

Line 19: Again, we use echo to get our stuff out on to the HTML page. Here, we are building a table cell (<td>) that contains whatever is stored in the ContactName field for this record. Note that PHP uses a single . (dot) character to stitch strings together. This is often referred to as ‘string concatenation.’

By request, I’ve put together a zip file containing the PHP/HTML source seen above. I haven’t actually run it to verify its accuracy, so please keep that in mind.