# Friday, January 06, 2006


I was recently working on a project where we needed to queue ajax calls on the client, and when I went looking for a JavaScript queue, was only able to find one that used certain JavaScript Array object functionality (shift() and unshift()) that does not work in IE 5.0, which we needed to support (argh). I only needed minimal functionality for that project, but I figured I might use this on my own so I came home and wrote this:


///////////////////////////////////////////////////////////////////////
/////////////////////////////// Queue /////////////////////////////////
///////////////////////////////////////////////////////////////////////
// This Queue works in older browsers where the shift() and unshift()
// methods of the later versions of the Array object, which are often
// used in other queue implementations, don't work.
function Queue()
{
    this.dequeue = Queue_Dequeue;
    this.enqueue = Queue_Enqueue;
    this.clear = Queue_Clear;
    this.count = Queue_Count;
    this.contains = Queue_Contains;
    this.peek = Queue_Peek;
    this.toArray = Queue_ToArray;
    this.m_Queue = new Array();
}
function Queue_Enqueue(value)
{
    if (value != null)
    {
        this.m_Queue[this.count()] = value;
    }
    else
    {

        throw new Error("Cannot place null value into Queue");
    }
}
function Queue_Dequeue()
{
    var objectAtFront = this.m_Queue[0];
    var temporaryQueueArray = new Array();
    for(var index = 0; index < this.count() - 1; index++)
    {
        temporaryQueueArray[index] = this.m_Queue[index + 1];
    }
    this.m_Queue = temporaryQueueArray;
    return objectAtFront;
}
function Queue_Peek()
{
    var objectAtFront = this.m_Queue[0];
    return objectAtFront;
}
function Queue_Contains(value)
{
    var currentIndex = 0;
    var quantityToInspect = this.count();
    while (quantityToInspect-- > 0)
    {
        if(value == this.m_Queue[currentIndex])
        {
            return true;
        }
        currentIndex = (currentIndex + 1) % this.count();
    }
    return false;
}
function Queue_Clear()
{
    this.m_Queue = new Array();
}
function Queue_ToArray()
{
    return this.m_Queue;
}
function Queue_Count()
{
    return this.m_Queue.length;
}



I haven't yet used it myself in anything, other than basic testing, but it does the basics and maybe someone can find use for it. It isn't rocket science, but in a pinch it sure beats spending the time to write your own (especially if supporting older browsers is important to you).

 

Kick It on DotNetKicks.com

posted on Friday, January 06, 2006 12:08:36 AM (Mountain Standard Time, UTC-07:00)  #    Comments [2]
# Tuesday, December 27, 2005


For those that use Paul Wilson's O/R mapper, here are some additional templates for generating a framework around that tool. While Paul Welter provides templates for this purpose, I don't particularly care for the pattern used in his generated classes (follows the 'Active Record' design pattern, AFAIK).

I personally don't like having business objects that 'know' anything about the concept of persistence (saving, retrieving, etc.); while this is a relatively common way of doing things (I did the same thing in the past), it doesn't work for me any longer simply because of my current personal opinions as it pertains to application architecture. Granted, 'it depends' on the application - I simply don't find myself ever needing to write an application using that pattern. :P

There is a readme.txt file that contains more than enough verbosity on what these do/don't do. However, here are some big ones:

  1. These have been verified to work in the following versions of CodeSmith (i.e. I have tried them in these versions, they may also work in others as well, YMMV):
       v2.6 (the 'free' version)
       v3.1.6
  2. These generate C# code.
  3. These have been used against SQL Server 2000 (theoretically, they work against any that CodeSmith and WilsonORMapper support)
  4. They currently target v1.1 of the .NET Framework (though they work against 2.0 as well, they simply don't support generics (yet)).

I hope someone finds these useful.

Thanks.

Kick It on DotNetKicks.com

posted on Tuesday, December 27, 2005 11:47:38 PM (Mountain Standard Time, UTC-07:00)  #    Comments [2]
# Monday, November 21, 2005

Most of the time, I am happy writing ASP.NET applications; I have been doing web development for almost 5 years, beginning with 'classic' ASP. As time goes on, I find myself writing more and more software for myself and this tends to be of the WinForms variety. Currently I am developing some software to help manage the seemingly unmanageable quantities of digital pictures that my wife and I have amassed over the last 5 years. I am still in the architecting phase of the project, but when I go to design the UI, I want to use something that will make it look slick (read: make it look familiar so that my wife will feel comfortable using it).

Via a post by Jay Kimble, I found out about a free (even for commercial use!) toolkit that provides some slick UI controls for WinForms applications (targeted at Visual Studio 2005 and 2.0 of the .NET Framework); it is called The Krypton Toolkit, and I plan on seeing how I can fit it into the aforementioned application's client piece. You can download this toolkit from Component Factory's website.

Kick It on DotNetKicks.com

posted on Monday, November 21, 2005 10:01:55 PM (Mountain Standard Time, UTC-07:00)  #    Comments [0]
# Tuesday, October 11, 2005


One of the classic "problems" with code generation is the situation where you need to add custom code to generated code. For example, it is very easy to generate simple ("anemic") domain objects from a database schema, but what about when you get to the point when you want to add behaviors to those objects? Where do you put that code? If you place it in the file that was generated, you will lose the handcrafted code unless you either never regenerate that file (very unlikely) or manually (or programmatically) remove and then re-insert the code; with the exception of programmatically preserving handcrafted code, you don't want to bother with those options.

Up until recently, the way you typically get around this is to use an inheritance model. You put all of your generated code in a base class and all of the custom code in a derived class. This allows you to regenerate the base class any time you would like without fear of losing handcrafted code. Of course, some would say there are cons to this approach, such as namespace pollution, issues accessing private base class members, etc. - I personally haven't had any problems with the inheritance model, but maybe I just don't write code that is interesting enough to suffer from these issues. :P

So, where do partial classes come into play? Well, they were, at first (by those who didn't think hard about actual implementation), hailed as a solution to the problem alluded-to previously. Instead of using contrived inheritance, we could now have one type spread across two or more files. Yippee! Now that we can have a generated file and a custom, handcrafted file that define the same type, all of our code gen related problems would be solved! But not so fast. While it does provide a great construct for some code gen situations, it is not necessarily the ideal in all cases (which is to be expected, nothing is a silver bullet) - of course, I am examining one simple situation here, it doesn't mean partial classes will not work well for other situations. Let's use an example that came up recently in my own work. In the past, I would generate code and use the following construct for the beginnings of my domain objects (i.e. before I added the handcrafted behavioral code to the domain object):


Base class:

public abstract class UserBase
{
   private string m_FirstName = string.Empty;
   private string m_LastName = string.Empty;
   private int m_Age = 0;

   public string FirstName
   {
      get { return m_FirstName; }
      set { ValidateFirstName(value); m_FirstName = value; }
   }
   
   public string LastName
   {
      get { return m_LastName; }
      set { ValidateLastName(value); m_LastName = value; }
   }

   public int Age
   {
      get { return m_Age; }
      set { ValidateAge(value); m_Age = value; }
   }

   public UserBase() { }

   public UserBase(string firstName, string lastName, int age)
   {
      FirstName = firstName;
      LastName = lastName;
      Age = age;
   }

   protected virtual void ValidateFirstName(string firstName) { }
   
   protected virtual void ValidateLastName(string lastName) { }

   protected virtual void ValidateAge(int age) { }

}


Derived class:

public
class User : UserBase
{
   public User() : base() { }
   
   public User(string firstName, string lastName, int age) : base(firstName, lastName, age) { }
   
   protected override void ValidateFirstName(string firstName)
   {
      if (firstName.ToUpper() == "FOOBAR")
      {
         throw new InvalidDataException(string.Format("Your first name cannot possibly be '{0}'!!!", firstName));
      }
   }
}


The thing I want to point out is that in the property setters in the base class, we call some virtual methods to validate data. As you can see, those methods have no implementation, so if we derive a class from UserBase, and don't override those methods, no data validation happens. That is just fine, because maybe our code gen process doesn't provide for generating that type of validation (it could if we had a more robust code gen process, but let's simply examine this simple case). So, now we are free to override the virtual methods in the derived class in order to provide data validation (as illustrated by the overridden ValidateFirstName method).

Well, guess what? This is not so easy using partial classes. If I have the following generated partial class, how do I duplicate the same behavior as illustrated above by the inheritance model?

Generated partial:

public partial class User
{
   private string m_FirstName = string.Empty;
   private string m_LastName = string.Empty;
   private int m_Age = 0;

   public string FirstName
   {
      get { return m_FirstName; }
      set { ValidateFirstName(value); m_FirstName = value; }
   }

   public string LastName
   {
      get { return m_LastName; }
      set { ValidateLastName(value); m_LastName = value; }
   }

   public int Age
   {
      get { return m_Age; }
      set { ValidateAge(value); m_Age = value; }
   }

   public User() { }

   public User(string firstName, string lastName, int age)
   {
      FirstName = firstName;
      LastName = lastName;
      Age = age;
   }

   protected void ValidateFirstName(string firstName) { }
   
   protected void ValidateLastName(string lastName) { }

   protected void ValidateAge(int age) { }

}

  

Custom partial:

public partial class User
{
   // how do I take care of writing custom data validation within this file?!
}

I was in this situation today. We (coworkers and myself) decided a few weeks ago, without giving it a terribly good deal of thought, that we would go the partial class route on our generation of domain objects and such. But now I needed to validate data on the setter of one of the properties of the class. How was I going to do that? I came up with a completely horrible hack involving delegates which I decided was out of the question. I may not write the most elegant code, but I want the code to be somewhat readable - having a delegate for each property's setter was NOT in keeping with that idea. I am either going to go back to using the inheritance model or will start using the PreserveRegions functionality of CodeSmith to preserve my handcrafted code - partial classes have not been as useful as I once hoped they would be. Oh well!

Kick It on DotNetKicks.com

posted on Tuesday, October 11, 2005 12:14:22 AM (Mountain Daylight Time, UTC-06:00)  #    Comments [0]
# Sunday, September 18, 2005

I had been on a project for the last 8 months for which we used code generation to build basic business objects and some persistence management classes based on metadata available via the database schema. We used CodeSmith templates that I originally wrote for myself (I have been using code gen in one form or another for years now; I don't see how people live without it), which generated C# code, but modified them to produce VB.NET code as required by our client (they told us that we would be doing C# when we were interviewed - that changed to VB.NET after they hired us, much to our dismay).

Coupled with Paul Wilson's excellent O/R mapper ('WilsonORMapper," aka "WORM"), the code generation framework made developing the applications we needed very enjoyable (because who really likes writing persistence layer code?!) and quick. The part of the process that we didn't really care for was when it came time to regenerate the code (this usually happened when a database change was made) - if a table was added, which usually mapped to a new business object, you would open CodeSmith and generate the code, go to Visual Studio, manually add the newly-generated files to the appropriate projects, finally you would then check those into source control (we used SourceGear's Vault, without Visual Studio integration (we had our reasons)). Sounds simple enough, but this became a tedious process (changes were made to the database almost on a daily basis (the client had modeled the database before we started on the project, and suffice it to say they didn't know much about modeling data (not to mention they were simultaneously developing other applications against the same database schema, and would neglect to tell us of fields that were added (we worked off-site, they were in another state, so we had a copy of the database)))) which we would usually screw up (forgetting to check in the new project file, and/or newly-generated code), not to mention we generated code on a certain machine because we wanted to have a single place for that to happen, to help enforce our process (you would be more likely to check things into source control, since you had just generated them, for example).

Okay, enough background - all I really want to say is that we finally took some time the other day (we are off the project alluded-to above and onto another) to add to the code generation process some things we have wanted for a long time but never took the time to create. Namely, the CodeSmith templates we use now add any newly-generated classes to the appropriate Visual Studio project files (we are using Beta 2 of VS2005) and we can also run the entire process from our own machines from within Visual Studio (no more opening CodeSmith as a separate application - we use it in batch mode (with a cmd file)) using the simple key chord of Ctrl-G, Ctrl-C (GC for 'generate code' - original, eh? ;)). Our next item is to then have it automatically check the code into Vault as well. Once that is done, the process will be muy sexy: make some changes to the DB within Enterprise Manager, switch to VS2005 and hit Ctrl-G, Ctrl-C and within a few moments, voila! Ah, the power of being lazy! Oh, and we are using partial classes now (to get around the problem of potentially losing handcrafted code associated with the generated code); while this is not ideal to me, it works and makes us feel cool for now (the reasons I feel partial classes are not ideal is another story - maybe I will blog about that sometime, or maybe I won't).

 

Kick It on DotNetKicks.com

posted on Sunday, September 18, 2005 12:09:44 AM (Mountain Daylight Time, UTC-06:00)  #    Comments [0]
# Tuesday, September 06, 2005

I don't know if I am among a small group in thinking this or not, but let's get real: why would anyone want to rebuild New Orleans? I mean, yes - it was once a "great" city (a questionable claim at best; I think Jazz is one of the only good things to come out of that place, ditto for some types of food - the decadent Mardi Gras is nothing to be proud of). Considering the large-scale environmental hazard, the fact that many no longer want to call New Orleans home, and the reality that much of the currently submarine city must be razed anyway, do we really want to deal with the work it would require to make the place habitable again?!

I am not trying to be sensational here, I really want to know what it will do for us to "rebuild" an entire city. We are not talking about some small town; this place was called home by half a million people for Pete's sake! Unless they are going to raise the city a few feet above sea level, I see no sane reason why anyone in their right mind would want to move there. Levees? Bah! The fact that people built that city in the first place smacks of insanity (yes, I know Holland is an entire country under sea level - still insane, no matter how successful they have been).

I just don't know. I agree we can't let fear and such stop us from living life to the fullest, but living in this city after an event such as this surely borders on stupidity. Anyone else agree?

Oh and by the way, this story about what to call those displaced by the hurricane's effects is one of the most absurd things I have read lately. Give me a break! ARGH!

Kick It on DotNetKicks.com

posted on Tuesday, September 06, 2005 11:31:39 PM (Mountain Daylight Time, UTC-06:00)  #    Comments [8]

(Are there any other kind of Linux-lovers?)

Although already well-documented by their actions on places like slashdot, the attitude of the seemingly typical Linux geek towards Microsoft still amazes me to this day. I think it is pretty funny that most of those I meet/observe are using Microsoft's software (particularly the evil OS) quite a bit (at work, at home, hosting their websites) all the while talking trash as they do.

Funny too that I rarely, if ever, see fond users of Microsoft products spending any time trash-talking alternative systems. Where do these people get the time to trash-talk? I mean, I am so busy with the billion other things in my life that spending time criticizing other operating systems and the compaines that create them seems to me a tremendous waste of one's time and energy.

Note to you if you are in the group of which I speak: get a life. Why not spend your time writing software that will change the world (or at the very least, makes *your* life easier)? Whining and moaning avails you nothing other than putting you in a group which, if you knew what was good for you, you would be remiss to associate with.

Kick It on DotNetKicks.com

posted on Tuesday, September 06, 2005 9:16:47 AM (Mountain Daylight Time, UTC-06:00)  #    Comments [2]
# Wednesday, May 25, 2005

I have been doing a lot with JavaScript lately (more particularly with AJAX constructs (using Ajax.NET) - very nice stuff), and one of the things I have been missing from C# (the .NET Framework, more specifically) is being able to use the static Format() method of the string object, rather than concatenating strings together in the usual fashion (yuck). For those unaware, the Format() method works like this:

foo = string.Format("Hello, {0}!", "World");

So, after this line executes, foo's value is "Hello, World!" Not a very exciting example, but it will suffice to get the point across. Simply imagine a more interesting string with more values, all placed within the string at different indices. You don't want to do something like:

foo = "So, " + firstName + " - is it true that you concatenated " + horriblyLargeNumberOfStringConcatenations + " strings together without using string.Format()?!";

For more information, see the documentation.

So, as far as I know, JavaScript doesn't provide a similar implementation. If someone knows of it, do let me know. Here is my simple implementation of it (handling only the very basic use, specifically to alleviate the mess with string concatenation), and it seems to work sufficiently.

The comments should explain things well enough, but one thing I have left out is the fact that in JavaScript, no matter how many parameters you define a function to accept, you can actually pass in as many as you want. Either way, all of the parameters are available in an array called arguments. I prototype the function to look somewhat similar to the .NET version, but I could have defined it with no parameters if I wanted to as well.

function Format(formatString, args)
{
   // get the number of objects to format
   var countOfSuppliedFormatItems = arguments.length - 1; // the 1 is the format string

   // loop through all of the args (those in addition to 
   // the string containing the format items)
   for (var i = 0; i < countOfSuppliedFormatItems; i++)
   {
      // the value to replace the format item with on this iteration
      var replacementString = arguments[i+1].toString();

      // used to find this iteration's format item in the format string
      var formatItemRegex = new RegExp("\\{[" + i.toString() + "]{1}\\}", "g")

      // do the actual replacements for this iteration
      formatString = formatString.replace(formatItemRegex, replacementString);
   }
   return formatString;
}

I hope this helps someone, I know I get tired of all of the concatenating I need to do in JavaScript, this makes things a bit more formal and readable. If anyone improves this function, do let me know as well. Eventually, I would like to extend this and make it part of an object (yes, you can create your own objects in JavaScript, if you didn't already know that) that supports more complex format items; i.e. support the {index[,alignment][:formatString]} construct even more.

[EDIT: In order to make this even more so emulate the syntax of say, C#, you would add this function as a static function on the native String object of JavaScript with the following line:

String.format = Format;

This would allow you to call it like this:

String.Format("{0}, {1}", lastName, firstName);

Good stuff!]

Kick It on DotNetKicks.com

posted on Wednesday, May 25, 2005 10:43:31 AM (Mountain Daylight Time, UTC-06:00)  #    Comments [2]
# Tuesday, May 10, 2005

The next version of Visual Studio .NET (hereafter, collectively, "VS"), Visual Studio 2005 (they are dropping the ".NET" branding), will include refactoring capabilities for C#, but not for Visual Basic .NET (hereafter, "VB.NET"). However, there were apparently a lot of people more than a little upset about this, so Microsoft partnered with Developer Express to provide to VB.NET users, for free, a version of their Refactor! Pro refactoring plug-in, specifically for VB.NET for VS 2005.

Since I have begun playing with VS 2005 in earnest, I thought it would be cool to see what this plug-in did for VB.NET, notwithstanding my aversion to spending too much time in the language, since I simply prefer C# (no, I am not going to say anything as dogmatic as "VB.NET is for kids and real programmers choose C# over it"; I simply don't enjoy writing code in VB.NET as much as I do in C#). Rather than reiterate all of the features of this tool, you can check out their overview for yourself.

Since they do not offer a trial version of their full-product, Refactor! Pro, I decided to take Developer Express up on their 60-day money-back guarantee and went ahead and purchased the full version of this tool. One thing that I don't understand and was pretty disappointed with was the fact that although you purchase it online and download it from their site, you have to wait at least 1 business day for the order to be processed. What is up with that?! I mean, I ordered it Friday afternoon, and I didn't get to download it until Tuesday morning. LAME! Why can't I simply download it the very minute I finish placing my order?! I mean, I purchased Half Life 2 online a month or two ago, and was able to begin the download immediately, and I was able to play within an hour or so. This is a 7.5MB file, and I had to wait over a weekend to get the thing.

Okay, enough of my ranting about that. I simply want to say that in addition to the expected refactorings (extract method, encapsulate field, etc.) there are some that I was pleasantly surprised to see. For example, a common thing to do is concatenate strings together to spit stuff out to the UI, like so (please excuse the contrived example):

Response.Write("Hello " + firstName + ", your username is " + username + " and your password is " + password + ".");

Well, if you highlight all of the code starting with the opening quotation mark inside the open paren, and ending with the quotation mark just before the closing paren, you can select from the Refactor! Pro menu, "Composition to Format Call," and it will turn the previous code into this:

Response.Write(String.Format("Hello {0}, your username is {1} and your password is {2}.", firstName, username, password));

Much nicer. I find myself doing this type of refactoring quite often, so having the ability to highlight the code and have Refactor! Pro do all the work is a nice time-saving feature. Maybe I will write more about this tool as time goes on and I (hopefully) fall in love with it. If the 60 days is up and I don't, perhaps I will write of that decision as well.

As an FYI, there are numerous other third-party refactoring plug-ins for VS, including Xtreme Simplicity's C# Refactory (I have used this tool and quite enjoyed it - they are also working on a VB.NET version), KnowDotNet's NET Refactor (downloaded the trial version and used it for 2 days, it caused some issues with VS, but seemed like a decent tool), and JetBrains' ReSharper (it does more than refactoring, I have never used this tool).

Kick It on DotNetKicks.com

posted on Tuesday, May 10, 2005 8:28:36 PM (Mountain Daylight Time, UTC-06:00)  #    Comments [0]
# Thursday, May 05, 2005


I was reading Aaron's blog the other day, and when I read his post about the AssemblyVersion attribute not showing up when he used some code to reflect the metadata of an assembly, I vaguely remember reading about why this happens in some of my more recent reading. I own the book, Applied .NET Attributes, so I looked there, but didn't see it. Then, it came to me: it was Löwy's book I was in need of.

In his wonderful book, Programming .NET Components, Juval states:

"The AssemblyVersion attribute . . . is a special attribute; its value isn't recorded in the metadata, but rather in the manifest. If you want to programmatically reflect the assembly version, you can . . . using the GetName() method of the Assembly type," just as Aaron discovered. As for there being other attributes that behave similarly, there is no mention of such by Juval that I can see . . .

 

Kick It on DotNetKicks.com

posted on Thursday, May 05, 2005 10:02:58 AM (Mountain Daylight Time, UTC-06:00)  #    Comments [0]