 Tuesday, October 21, 2008
 Wednesday, September 24, 2008
Favor Composition Over Inheritance
I've come across all kinds of architectures in my time. Some have been good, some bad (yet somehow the bad vastly outnumber the good). Even on some of the good architectures I've seen, a common problem I've found is the abuse of object inheritance. It's tempting to create an inheritance hierarchy to quickly get all the functionality provided by a common base class. Through one little symbol or keyword, you can easily extend your object to get all the functionality provided by some other class. However, be aware this kind of modeling comes with a price, and many times it's a price more steep than you should be willing to pay. Which is why a lot of people much smarter than me - Josh Bloch, Venkat Subramaniam, Andy Hunt, Dave Thomas, Robert "Uncle Bob" Martin, and Steve McConnell - have all argued that using composition instead of inheritance creates a much more Agile object model. There are many reasons why Agile developers feel this way. Conceptually "Is-a" vs. "Has-a" In inheritance modeling, class inheritance should only be used to represent true "subtype" relationships. Every subclass should be a subtype of the class it is extending. Object B should only extend Object A if a logical "is-a" relationship exists. In other words, you need to ask yourself, "Is every B really an A?" If you cannot truthfully answer yes to this question, there is no reason for B to extend A other than simple convenience. And convenience is not a good reason for creating an inheritance hierarchy. Steve McConnell explains further in his seminal book Code Complete, "If the derived class isn't going to adhere completely to the same interface contract defined by the base class, inheritance is not the right implementation technique." Rather, you are better served modeling a "has-a" relationship between the two classes, where A is a private instance in the implementation details of B. B may depend on the services provided by A, but is not a logical subtype of it. By "wrapping" the reference to A, you will have a more conceptually accurate and flexible implementation. It's all about the context! A consumer of an object should be able to intuitively decipher its purpose from its public API. When you force an inheritance hierarchy of two objects that don't have an "is-a" relationship, you have created an subclass object that contains methods, properties, fields, etc. from two different contexts. By combining these contexts, you have created a confusing API that causes the consumer of it to have to actively track down the meaning behind methods exposed from the two contexts. For example, suppose I have an Account object that extends TransactionCoordinator. The two objects have two different contexts, and the design of their individual APIs most likely reflect that fact. As a consumer of the Account object, when I see methods such as Start(), Commit(), Rollback() that have been inherited from the base class representing a different context, I am confused. Intuitively, an Account is not a TransactionCoordinator, and I would have to know that inheritance relationship even exists to understand why I am seeing these methods. Normally, I wouldn't expect to see them there. What do these methods mean? What do they do? If I'm lucky, I can look at the API documentation (if it exists) on the Account object and it will detail each method and its functionality and implications when called from the subclass. More likely, I will have to open the Account object up, see that it extends the TransactionCoordinator, and go there to research what each method actually does. And only then can I have the ability to decide if that behavior is something I want to invoke on my subclass. Here’s the lesson - don't make consumers of your API work any harder than they have to. Liskov's Substitution Principle Barbara Liskov wrote one of most ground-breaking papers on object-oriented programming in 1998. In this paper, Liskov proposed that you shouldn't inherit from a base class unless the derived class truly "is-a" more specific version of the base class. In what became known as the "Liskov Substitution Principle", Liskov argued that any derived class must be able to be completely substituted for its base class interface without any knowledge of the calling class. In other words, subclasses must only change the implementation and not the meaning or intent of the base class interface. Say you have an abstract base Account object. Callers that reference the base class API should not have to know or care which whether a CheckingAccount or SavingsAccount derived class actually provides the implementation. To take the example further, suppose there is a CalculateInterest() method declared on the Account object. In normal implementations it calculates the interest due to the consumer. Suppose you introduce a BankLoanAccount which changes the implementation to calculate the interest for the bank. This class violates the LSP since it changes the meaning of the implementation of the CalculateInterest() method, so now the caller cannot freely call the method on the base class reference. Single Responsibility Principle I'm a firm believer in the Single Responsibility Principle. Classes should have one responsibility, and one responsibility only. Think of it as the old Henry Ford assembly line - classes should do their one thing and do it well. There is no reason for them to know the inner details or the workings in the classes in which it interacts. This leads to smaller, more focused classes. And small, purposeful classes are A GOOD THING. Single responsibility creates classes that are highly cohesive, while limiting coupling to external dependencies. High cohesion and low coupling is an admirable goal in any software architecture. Planning for change By limiting classes to one responsibility, you are also creating a class that has only one reason to change. As a developer who believes in Agile methodologies, I know change is going to come. Limiting the reasons for classes to change, as well as the surface area in which that change will be felt, will go a long way towards making those changes easier to implement. Technical Introduces Dependencies Anytime you inherit from a class, you are explicitly creating a dependency on that super class. The code to the super class may change over time. Each time it does change, it can potentially directly or indirectly break some or all of its subclasses, even though the code in subclasses may not have changed at all. Most likely, the subclasses had no idea the change even occurred at all. And unless you have planned for this contingency in your unit test (you are writing unit tests, right???), you may not even find this breaking change until after the code is deployed. And if you are writing unit tests, that's just more (seemingly avoidable) unit tests you need to write to handle these cases. This creates a lot more work for the API producer. All subclasses now will have to be designed (and tested) to evolve in conjunction with their super classes. That's more code and more unit tests you now have to write and maintain. Fragile classes Due to rules we must live with when choosing a static, compiled language, we limit ourselves in the structuring of our API. Anytime we define a method signature in any class, this signature causes a ripple effect up and down the inheritance hierarchy. That's both good and bad. Each base class automatically inherits the new functionality, but guess what - it may not want to do so. Or worse yet, it can break existing functionality in the subclass. For example, introducing or changing a method signature in the base class will flow down to every class that derives from it. What if that subclass already has a method defined in that class with the same name? This will cause either: a compilation error if the method cannot be overridden; or worse yet unexpected behavior at runtime if the method can be overridden as the subclass implementation is now unknowingly invoked. Or, what about if the subclass has the same method name but a different signature? You will be forced to change your API in one of the classes just to get them to compile. The same problems manifest itself as methods are introduced in base classes, but at least you are a probably little more aware of the potentially breaking changes. Think this is a far-fetched example? I don't. Imagine common method names like Execute(), Activate(), Register(), or IsAvailable(), Open(), Load(), or Save(). All of these are all methods names that are prolific in our object models, and could easily have much different signatures as well as potentially meaning very different things in different contexts. What if the behavior introduced in a base class implementation is not desired in the subclass? Sorry, your S.O.L. Good and bad, you get everything that comes down from the base. Refactoring Due to all the problems with carrying "API baggage", classes with deep hierarchies are much harder to refactor. Are you completely comfortable with the API provided by your super class? Because anytime you extend it, any flaws/issues/concerns you have with it are propagated down to the subclasses. Not only that, the flaws now become further spread across your object model through the expanded surface area of all of its own and now its subclasses consumers. Composition is much more flexible. It has the advantage of masking, improving, or changing the API to encapsulate the existing concerns. Not only that, but now you have tied yourself to this mis-matched inheritance hierarchy, and it will be much harder to introduce a new base class if a new valid one ever presents itself. Summary Inheritances is one of the most powerful and most abused concepts in object-oriented programming languages today. True, inheritance is an easy and useful way to provide quick code reusability across your object model. But the drawbacks of doing so far outweigh the short-term gains achieved. Oftentimes the reusability gained comes as the expense of code extensibility, maintainability, and testability. In the long run, ironically both producers and consumers of the API will have to do more work to maintain the fragile inheritance hierarchy. Favor composition over inheritance to limit fragile inheritance hierarchies and create a much more flexible and powerful API.
Wednesday, September 24, 2008 10:30:23 PM (Eastern Standard Time, UTC-05:00) .Net | Back To Basics
 Monday, September 22, 2008
Atlanta ALT.Net Meetup
The Atlanta ALT.Net user group is meeting again this Wednesday, September 24 at the Thinking Man Tavern in Decatur. If you plan on attending, the organizers are asking people to RSVP in order to get an accurate head count. We are going to spend some time talking about ASP.Net MVC, but I imagine it will be open to discussion on all topics. Hope to see you there! View Larger Map
Monday, September 22, 2008 10:26:11 AM (Eastern Standard Time, UTC-05:00) .Net | alt.net
 Saturday, August 09, 2008
Isolated Storage
In my last post, I showed how to write stuff out to a temporary directory. After I wrote the post, I started thinking about how people could misconstrue the meaning of it. The post was intended to show how to dump stuff easily to a random directory on the file system. The code that drove me to write that particular example came from a unit test that was using the temporary directory as a repository for the output of the XmlSerializer. In other words, I really was not doing anything meaningful with the data. To clear things up, I thought I would write a post that showed how use a unknown storage directory as a meaningful repository for application data. What constitutes meaningful data? I don't know, it's your app!!! But common possibilities include application settings, user-specific data, etc... I'm thinking of things that might be otherwise be stored in the registry. Yeah, don't do that anymore. I don't know about you, but the just the word "registry" causes me to shudder. .Net has introduced a new concept called "Isolated Storage" to hold this type of information. Isolated storage is an unspecified location on the file system that is hidden away from the application. Even though the location is unknown, the application is guaranteed to have full permissions to it, even if it is running in a restricted security mode. As it name implies, the location is "isolated" so that any data written to it does not affect other applications or anything else on the file system. So as far as security goes, you're limited to only hurting yourself by maliciously or ignorantly (mis)using this repository. Here's a code sample of how you would use it to store data: // get the location specific to this user/assembly
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForAssembly();
// create a file to write the data to
using ( var outStream = new IsolatedStorageFileStream("foo.txt", FileMode.Create, isf) )
{
using ( var sw = new StreamWriter(outStream) )
{
// write out the text
sw.Write("Random text");
sw.Close();
}
}
And here is how you can retrieve it: IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForAssembly();
// open the file
using ( var inStream = new IsolatedStorageFileStream("foo.txt", FileMode.Open, isf) )
{
string[] files = isf.GetFileNames("foo.txt");
if ( files.length > 0 )
{
StringBuilder sb = new StringBuilder();
foreach ( var file in files )
{
using ( var sr = new StreamReader(inStream) )
{
sb.AppendLine(sr.ReadLine());
}
}
}
}
This method is a much more "enterprise-y" way to access data in your applications.
Saturday, August 09, 2008 3:45:26 PM (Eastern Standard Time, UTC-05:00) .Net | C#
 Friday, August 08, 2008
Using Temp directories in .Net
Have you ever found the need to use a temporary directory on the file system in your code? This issue came up with me recently (and bit me in the ass), so I thought I would share some experiences on how I overcame the problem. At the root of the problem is that you need some sort of permanent storage, but nothing that is stringent enough to require it reside in some "known" directory where it can be accessed at a later time. You don't really care where you store a file, but you need to store it somewhere. I recently came across a piece of code in a unit test that serialized a class using the XmlSerializer. The person who wrote the test must have wanted to see what the class looked like in serialized form. The code was written so that the xml version of the class was dumped to the file system. However, when the test was written, the file was hard-coded to the C:\Temp directory. As part of my task, I was incorporating the unit tests on this component into the continuous build. Guess what happened when the test was moved the build server? FAIL!!! No C:\Temp directory on that machine means lots of red on the build server and the IT director screaming WTF?!?!? The lesson is, never make assumptions when accessing the file system. In this case, the test was counting on the directory both existing and the user having permissions to it. Obviously, that's not a good idea. There are other ways to get to a valid "temporary" directory in .Net. The following code sample shows how you can try a few known places in .Net that should work as "temporary" directories. /// <summary>
/// Get a valid "temporary" directory on the machine that is running this code
/// </summary>
/// <returns>a temporary directory</returns>
private string GetTemporaryDirectory()
{
// try this first
string dir = Path.GetTempPath();
if ( String.IsNullOrEmpty(dir) || !Directory.Exists(dir) )
{
// see if the "TEMP" environment variable is set
dir = Environment.GetEnvironmentVariable("TEMP");
if ( String.IsNullOrEmpty(dir) || !Directory.Exists(dir) )
{
// hmmm ... let's create one in "My Documents"
string myDocsDir = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if ( String.IsNullOrEmpty(myDocsDir) || !Directory.Exists(myDocsDir) )
{
// no "My Documents" directory???
throw new Exception(
"Cannot determine a valid temporary directory on this system. " +
"Please set a valid directory for the \"TEMP\" environment variable.");
}
dir = String.Format("{0}\\Temp", myDocsDir);
if ( !Directory.Exists(dir) )
{
Log.Info("Creating new Temp directory in {0}", myDocsDir);
Directory.CreateDirectory(dir);
}
}
}
if ( dir.EndsWith("\\") )
{
// cut the last char off
dir = dir.Substring(0, dir.Length - 1);
}
return dir;
}
The code example above tries to use the .Net libraries to query the file system for some well-known directories that can be used for temporary files. If a valid one is not found, it will try to create a "Temp" directory in the current user's "My Documents" directory. At worst, the user should have access to this directory, and the build should not break based on a hard-coded assumption.
Friday, August 08, 2008 12:46:30 AM (Eastern Standard Time, UTC-05:00) .Net | C#
 Tuesday, July 29, 2008
Is MS-Linux next???
Take a look at this little announcement that came out of OSCON last week... http://port25.technet.com/archive/2008/07/25/oscon2008.aspx Amazingly, Microsoft has agreed to join the Apache Software Foundation as a platinum sponsor. Oh, in case you weren't aware, Microsoft has this little product called "IIS" that kind of directly competes against the open-source Apache web server. Paradoxically, IIS would die to get the market share enjoyed by Apache, yet is neither free as in beer nor as in speech. A fact that I imagine probably makes for a tough sell for the Microsoft marketing department. The cynics are saying this is a bold move by Microsoft to help ease the sting caused by the PR fiasco known as "Windows Vista." "Hey, look at us, you might think we suck and are inherently evil, but suddenly we love open source (well, not anything that is GPL'ed - but I guess that's just common sense)." I honestly don't know what to make of it. I guess in the grand scheme of things, the $100,000 ponied up to join Apache can't even be considered a drop in the bucket for Microsoft. As they said on TWiT this last weekend, "That just gets them on the mailing list." Maybe it's like Sun-Tzu said (and later echoed by Michael Coreleone in Godfather II), "Keep your friends close, but your enemies even closer."
Tuesday, July 29, 2008 10:01:31 PM (Eastern Standard Time, UTC-05:00) .Net | Apache | IIS | Open Source
 Sunday, July 20, 2008
 Saturday, July 19, 2008
Don't call virtual methods in a constructor
I ran into a piece of code today similar to this: public class Base
{
public Base()
{
this.Initialize();
}
protected virtual void Initialize()
{
Debug.WriteLine("Base.Initialize()");
}
}
public class Derived : Base
{
public Derived() : base() {}
protected override void Initialize()
{
base.Initialize();
}
}
public class FurtherDerived : Derived
{
public FurtherDerived() : base() {}
protected override void Initialize()
{
Debug.WriteLine("FurtherDerived.Initialize()");
}
}
public class Tester
{
public static void Main(string[] args)
{
Base myBase = new Base();
Derived myDerived = new Derived();
FurtherDerived myFurtherDerived = new FurtherDerived();
Console.ReadLine();
}
}
See any problems here? Even though the compiler lets you call virtual methods from a base constructor, it's generally a "bad idea". That's because the constructor in the derived classes defers its construction up to its base classes before it executes its own constructor (even if we don't explicitly call the base constructor like in the example). Yet the call to a virtual function in the base class constructor is executed in the derived class implementation. This can cause subtle, unexpected problems.
In the example above, things "happen" to go well. It actually runs just fine. It outputs the following as you'd probably expect: Base.Initialize()
Base.Initialize()
FurtherDerived.Initialize()
But that's only because we didn't do anything significant in the derived constructors. What happens if we change the FurtherDerived class: public class FurtherDerived : Derived
{
StringBuilder _sb;
public FurtherDerived() : base()
{
_sb = new StringBuilder();
}
protected override void Initialize()
{
_sb.Append("FurtherDerived.Initialize()");
Debug.WriteLine(_sb.ToString());
}
}
Guess what happens when we run this code? FAIL!!! The dreaded, "Object reference not set to a reference of an object". Since the Initialize() method in the FurtherDerived class is called from the Base constructor, we are trying to access the _sb class level parameter before it's ever initialized. We are calling a method on an class we know has not been fully constructed. That ain't good.
The lesson is - never call a virtual method from a constructor. At best, you are introducing a bug waiting to happen. At worst, you've already done so.
Friday, July 18, 2008 11:57:17 PM (Eastern Standard Time, UTC-05:00) .Net | Back To Basics | C#
 Monday, July 07, 2008
 Friday, May 30, 2008
New release of Miado
This new release contains significant changes. First and foremost, all the implementation classes have had their public scope removed, so you will now have to program exclusively against the interfaces. I have also moved the IMiadoDao interface to IMiadoRepository in order to encourage composition and not force an inheritance hierarchy. Combined with that change, I also moved the functionality from SimpleSql into IMiadoRepository, as well as making that interface the point where you access an IDbStatement, making the IMiadoRepository the main worker module of Miado. Another change is that you need to use the MiadoRepositoryFactory to create an instance of the IMiadoRepository. Enough with the talk, let's see some code... public AdddressDao { private static readonly string INSERT_ADDRESS_SQL = "insert into Address(Address1, Address2, City, State, ZipCode) " + "values(@Addr1, @Addr2, @City, @State, @ZipCode)"; private static readonly string SELECT_ADDRESS_SQL = "select AddressId, Address1, Address2, City, " + "State, ZipCode " + "from Address "; private static readonly string SELECT_ADDRESS_BY_ID = SELECT_ADDRESS_SQL + "where AddressId = @Id "; private static readonly string SELECT_ADDRESS_BY_ZIP_CODE = SELECT_ADDRESS_SQL + "where ZipCode = @ZipCode "; private static readonly string SELECT_COUNT_BY_STATE = "select count(*) from Address where State = @State ";
// uses MiadoRepositoryFactory.CreateMiadoRepository() public AddressDao() : this(MiadoRepositoryFactory.CreateMiadoRepository( SqlClientFactory.Instance, ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString)) {}
public AdddressDao(IMiadoRepository repository) { this.MiadoRepository = repository; } protected IMiadoRepository MiadoRepository { get; set; } public void SaveAddress(Address addr) { // uses SQL right in IMiadoRepository this.MiadoRepository .ExecuteNonQuery(INSERT_ADDRESS_SQL, addr.Address1, addr.Address2, addr.City, addr.State, addr.ZipCode) } public ICollection<Address> FindAddressesByZipCode(string zipCode) { // build IDbStatement and do the mapping in a lambda expression ICollection<Address> addresses = this.MiadoRepository .CreateDbStatement(SELECT_ADDRESS_BY_ZIP_CODE) .AddParameter("ZipCode", zipCode) .QueryForResults<Address>( row => new Address() { AddressId = row.GetValue<int>("AddressId"), Address1 = row.GetValue<string>("Address1"), Address2 = row.GetValue<string>("Address2"), City = row.GetValue<string>("City"), State = row.GetValue<string>("State"), ZipCode = row.GetValue<string>("ZipCode") }); return addresses; } public Address LoadAddress(int addrId) { // uses delegate method to do the mapping return this.MiadoRepository .CreateDbStatement(SELECT_ADDRESS_BY_ID) .AddParameter("Id", addrId) .QueryForOne<Address>(CreateAddress); } public int FindCountByState(string state) { return this.MiadoRepository .CreateDbStatement(SELECT_COUNT_BY_STATE) .AddParameter("State", state) .QueryForOne<int>(row => row.GetValue<int>(0)); } private static Address CreateAddress(IResultSetRow row) { return new Address() { AddressId = row.GetValue<int>("AddressId"), Address1 = row.GetValue<string>("Address1"), Address2 = row.GetValue<string>("Address2"), City = row.GetValue<string>("City"), State = row.GetValue<string>("State"), ZipCode = row.GetValue<string>("ZipCode") }; } }
Friday, May 30, 2008 10:57:03 PM (Eastern Standard Time, UTC-05:00) .Net | C# | Miado
 Wednesday, May 21, 2008
Using LINQ to generate a random confirmation number
Igor Ostrovsky recently published a great blog post about 7 tricks for using LINQ to simplify your programs. Posts like this really make me re-evaluate how I am writing my code in C# 3.0. For example, I had written a piece of code for my current project that generates a random confirmation number for a reservation system. After reading Igor's post, I built off one of his examples and refactored my code to use LINQ to build my confirmation number. I must admit, the refactored code is much more elegant:
private static readonly char[] AVAILABLE_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890123456789".ToCharArray();
private static string GenerateConfirmationNumber(int length) { int lastIndex = AVAILABLE_CHARS.length - 1; Random rand = new Random(); var confNbr = Enumerable.Repeat<int>(0, length) // loop N times .Select<int, int>(loopNbr => rand.Next(0, lastIndex)) // get a random index .Select<int, char>(index => AVAILABLE_CHARS[index]) // pull a char .ToArray(); // project the results to a char[] return new String(confNbr); }
I think it's important to remember that LINQ is much, much more than just LINQ-to-SQL (which is what most people immediately think of when you refer to LINQ). In fact, none of the examples in Igor's post have anything to do with SQL. Take a look at his post (and other LINQ examples online) and hopefully it will give you ideas on how to code using more of a dynamic language type syntax.
Wednesday, May 21, 2008 9:42:57 AM (Eastern Standard Time, UTC-05:00) .Net | C# | Linq
 Wednesday, May 14, 2008
C# Extension Methods
In my last post, I showed an example of how you can create an extension method on an existing class in javascript. Well, C# 3.0 has now added the exact same functionality. And it just so happens that today I needed to create one, so I thought I would post an example of how it's done in C#.
public static class StringExtensions { public static byte[] ToByteArray(this string s) { return ASCIIEncoding.UTF8.GetBytes(s); } }
Extension methods act like static methods on existing classes, and as such they can only be declared in static classes. To mark a method as an extension method, you must preface the declaration of the first parameter in the method signature with the keyword "this". The compiler will then add the method to the type of class declared in the first parameter. Any other parameters declared after the first one will become the signature to the extension method.
Now we can call the extension method we added to the String class:
public class Program { public static void Main(string[] args) { string myString = "Foo"; byte[] bytes = myString.ToByteArray(); } }
The other cool thing is that Visual Studio provides full Intellisense on all extension methods! So in the example I provided, ToByteArray() is now offered up as a potential method anytime I reference a string.
Wednesday, May 14, 2008 12:43:26 AM (Eastern Standard Time, UTC-05:00) .Net | C#
 Monday, May 12, 2008
Visual Studio 2008 and .Net 3.5 SP1 Beta Released
Microsoft announced today the release of the first public beta of Service Pack 1 for Visual Studio 2008 and the 3.5 version of the .Net framework. Rather than an extended re-hash of what's included in the release, I'll defer to the experts:
Some of the highlights for me are:
- Rails-like "Scaffolding" support via ASP.Net Dynamic Data (I need to play around with this and see if there's a need to get Miado to work with this)
- ASP.Net AJAX script combining to reduce the number of requests to the server
- ASP.Net AJAX back button support!
- Improved Javascript intellisense and formatting
- Support for ADO.Net Data Services (the project formerly known as Astoria), which aids in the creation of a data access layer using REST-ful web services
Since this is a *beta* version of a service pack, at this point I personally wouldn't install this in anything but a VM.
Monday, May 12, 2008 4:45:45 PM (Eastern Standard Time, UTC-05:00) .Net | Visual Studio
 Saturday, May 03, 2008
Sort and Remove Unused Usings in Visual Studio 2008
When I first starting developing in .Net, I had been a Java programmer for many years. I remember when I first started the transition, a long-time VB developer told me how much I was going to *love* Visual Studio. It was as if programming Java in Eclipse was akin to living in the stone age and he had suddenly granted me the programming gift equivalent to fire. "Here you go ... but use this power wisely. With great power, comes great responsibility." Hey, it's not like I was using vi on an terminal emulator! (by the way, have you seen any old school guys program in vi (and still choose to do it)? It's *scary* how fast they are.) Anyway, it's 2004 and I start my era as a .Net developer using Visual Studio. Dare I say, I actually begin to *miss* some things that were in Eclipse. Example - In Java, you have "import" statements at the top of every class you write. They are very similar to "using" declarations at the top of a C# class. They basically tell the compiler what packages (i.e. namespaces in .Net) you need to compile the class. Whereas in .Net you only can include an entire namespace, in Java you have the ability to import an entire package: import java.util.*;
or individual classes within a package without having to import the entire package: import java.util.Calendar; import java.util.Date; import java.util.List;
Flash back to circa 2002 or so. I was working on a J2EE project with a team of developers. Another developer and I were working on a couple of the same files. After he checked a file in and I was going to work on it, I would do a diff on the file to see what he had changed. I noticed every time he checked a file in, along with the changes he had made, he would rearrange the import statements. Now, the usual ordering of imports in a java class are that all the java.* classes go first, then the javax.*, followed by any org.*, and finally your application classes last. The project we were working on was for the state of Georgia, so some of our application packages started with gov.*. Well, he would always move those imports above the java.* packages. I would move them back to the bottom (where they actually belonged). When he checked it back in, they would be right back at the top. I thought to myself, "Man, this guy must be really anal to go through the effort of expanding out and ordering all the imports statements that way. I wonder why."
One day I finally asked him about it. "Why do you re-order the imports statements every time you check a file in and put the gov ones first?" He looked at me with a puzzled look. "Huh?" Then he realized what was happening. "Oh, I just hit Ctrl-Shift-O every time before I save a file to organize the imports." And he showed it to me. In Eclipse, you could use that keyboard shortcut (or access it through the menu) to automatically figure out your individual class imports and arrange them via a configuration of your choice (since he hadn't set up the gov ones in any order, it defaulted them to be first alphabetically).
Wow! Pretty cool! This was 6 years ago mind you. So I got in the habit every time I saved a file: Ctrl-Shift-O, Ctrl-S ... Ctrl-Shift-O, Ctrl-S ... Ctrl-Shift-O, Ctrl-S. I quickly became a "creature of habit".
Back to starting out in Visual Studio in 2004 ... Let's see, I'd like to organize my using declarations. Ok, Ctrl-Shift-O doesn't do that. Hmm ... I wonder where that setting *is* in Visual Studio ... Looks of looking, lots of googling ... Nothing. Well, damn. That kinda sucks. You mean I actually have to manage this myself?!?!? I think to myself, "Am I the only one out there who is wanting this sort of thing???"
Time passes, I am surviving by organizing my usings by hand (barely). The more and more .Net blogs I read, I start hearing about people using and loving ReSharper. Last year, after going solo and starting my own company, I finally decided to pull the trigger and buy myself a copy. And boy, was I glad I did! Along with a bunch of other great things, I notice that it let's you sort and remove unused usings. "There it is, there it is!!!" Ctrl-Alt-O! Organize and remove usings!
Last year, Visual Studio 2008 comes out, but damn - ReSharper is not quite ready for it. Well, work still needs to get done so I need to carry on, albeit without ReSharper for the time being. I am playing around with Visual Studio 2008, and I notice a new menu option under Edit->Intellisense. Whoa, what's this? "Organize Usings". I click on it, and lo and behold, there it is - three options: 1) Remove Unused Usings; 2) Sort Usings; 3) Remove and Sort. Finally!!!
There is no native keyboard shortcut mapped to the "Remove and Sort". Well, we can change that easily enough:
There, I've mapped Ctrl-Alt-O to Remove and Sort. I'm back baby! Ctrl-Alt-O, Ctrl-S! Let's see it in action ...
Before:
And after:
The bottom line is - yes, Visual Studio is a great IDE. But don't fool yourselves .Net developers. Eclipse, IntelliJ, and even NetBeans (my preferred IDE for working in Ruby) are all very strong IDEs that in reality actually do some things (gasp!) *better* than Visual Studio.
Saturday, May 03, 2008 2:52:09 PM (Eastern Standard Time, UTC-05:00) .Net | Eclipse | Java | ReSharper | Visual Studio
 Wednesday, April 30, 2008
Using Miado with Powershell
One of the nice things about Miado is that it wraps a lot of tedious, repetitive ADO.Net code and therefore greatly reduces the amount of code you actually do need to write. Here's a quick example. One of the tasks I had to do at my last last gig was upload a set of prices from a CSV file every month. I wrote a PowerShell script to use Miado to do the DB inserts:
- function BuildSql()
- {
-
- $sb = New-Object System.Text.StringBuilder
- $sb.Append("insert into VendorPrice(VendorID, FixedPrice, VariablePrice, ");
- $sb.Append("CreationDate, LastUpdatedDate) ");
- $sb.Append("values(@VendorID, @FixedPrice, @VariablePrice, ");
- $sb.Append("current_timestamp, current_timestamp)");
-
- return $sb.ToString();
- }
-
- [Reflection.Assembly]::LoadFile("C:\dev\VS2008\Miado\src\Miado\bin\Release\Miado.dll")
-
-
- $connString = "Data Source=.\SQLEXPRESS;Initial Catalog=MyDatabase;User Id=user;Password=passw0rd"
- $dbProvider = System.Data.SqlClient.SqlClientFactory::Instance;
- $repository = Miado.MiadoRepositoryFactory::CreateMiadoRepository($dbProvider, $connString);
-
- $sql = BuildSql;
-
- foreach ( $row in Import-Csv prices.csv | Select VendorID, FixedPrice, VariablePrice )
- {
- $repository.ExecuteNonQuery($sql.ToString(), $row.VendorID, $row.FixedPrice, $row.VariablePrice);
- }
As you can see, the script iterates over each row in the CSV file and inserts a record for each row. There's no need to write all the code necessary to create the DbConnection and DbCommand objects, nor do you have to dynamically create DbParameter objects for each row. Just pass the SQL and the variables (in order of replacement) into the IMiadoRepository.ExecuteNonQuery() call and Miado takes care of all the ugly details. One line for each insert - that's it! Edit: This post was updated to reflect the changes in the 0.7.10530.1
Wednesday, April 30, 2008 11:38:38 AM (Eastern Standard Time, UTC-05:00) .Net | Miado | Powershell
 Wednesday, April 16, 2008
 Monday, April 14, 2008
New Release of Miado out on CodePlex
I have uploaded a new version of Miado out on CodePlex. I am still calling this a beta. There are a few features I would like to add before I officially proclaim a 1.0 version (ability to use SqlServer-type syntax with an ODBC provider and integrated caching with the IDbStatement are two at the top of my list).
For this latest version, I have moved the DbProvider and vendor specific stuff to the Miado.Configuration namespace. I have added an IParameterParser interface which is used in the SimpleSql class to determine the parameter name declarations in a SQL statement based on whether you are using the ODBC-type syntax or newer syntax for variable declaration.
For example,
MyParam = ?
vs.
MyParam = @MyParam
This week I am going to try and come up with a good set of DAOs that use the AdventureWorks DB so people can see samples of how the API should be used.
Monday, April 14, 2008 6:52:06 AM (Eastern Standard Time, UTC-05:00) .Net | Miado
 Thursday, April 10, 2008
Starting out with ASP.Net Ajax and the Ajax Control Toolkit
So only javascript gurus can make slick Ajax-enabled web pages, right? Wrong! Want to know the dirty little secret? It's actually really easy!
If you are not using Ajax already on your ASP.Net pages, here's a great place to start. It's always bothered me how on something as simple as paging and sorting on a GridView caused a full postback. Wrap that sucker in an UpdatePanel and you’ve instantly Ajax-enabled your page! By including the declaration ChildrenAsTriggers="true" (or not declaring it at all – it’s the default option), any postback event triggered in the UpdatePanel will automatically cause the page to partially re-render its contents. That’s it! No javascript needed. Well, actually there’s a ton of javascript involved – just none of it written by you.
First off, you need a couple of resources to get started. If you are using the 3.5 version of the framework, ASP.Net Ajax is already included by default. If you are using .Net 2.0, you will need to download the ASP.Net Ajax Extensions 1.0 (could they make it *any* more confusing?).
I am using the Ajax Control Toolkit to perform the animations during the partial post-back. The Ajax Control Toolkit has a nice set of tools to use to help you build rich web UIs, and as Clark Howard would say, "Hey, it's free!!!!" In the example below, I am using the UpdatePanelAnimationExtender to declaratively set a FadeOut animation to occur on the div container surrounding the UpdatePanel as the page posts back, and a FadeIn animation as it re-renders.
OK, so I lied. I am actually using a little javascript to dynamically show a spinning loading image centered on the grid during the postback. But, again, the ASP.Net Ajax library to the rescue! It makes our life a lot easier by providing all sorts of nice javascript shortcuts that are cross-browser compatible (like the Sys.UI.DomElement.getBounds() call I’m using).
Oh, you need to check out this site that will generate a custom loading image for you. Make sure you select a transparent background when you build your image.
Here is the code: <!-- loading image is hidden by default --> <img id="imgLoading" src="images/ajax-loader.gif" alt="Loading..." width="30" height="30" style="display: none;" /> <div id="container"> <asp:UpdatePanel ID="updPnl" runat="server" ChildrenAsTriggers="true"> <ContentTemplate> <asp:GridView ID="gvw" runat="server" CssClass="grid" HeaderStyle-CssClass="header" AutoGenerateColumns="false" RowStyle-CssClass="odd" AllowPaging="true" AllowSorting="true" AlternatingRowStyle-CssClass="even"> <Columns> <asp:BoundField SortExpression="ID" HeaderText="ID" DataField="ID" /> <asp:BoundField SortExpression="Name" HeaderText="Name" DataField="Name" /> <asp:BoundField SortExpression="BirthDate" HeaderText="Date Of Birth" DataField="BirthDate" /> </Columns> </asp:GridView> </ContentTemplate> </asp:UpdatePanel> </div> <ajaxToolkit:UpdatePanelAnimationExtender ID="animator" runat="server" TargetControlID="updPnl"> <Animations> <OnUpdating> <Sequence> <!-- shows the loading image in the center of our grid --> <ScriptAction Script="showInProcessImage($get('imgLoading'), $get('container'));" /> <Parallel duration=".10" Fps="30"> <FadeOut AnimationTarget="container" minimumOpacity="0" /> </Parallel> </Sequence> </OnUpdating> <OnUpdated> <Sequence> <Parallel duration=".25" Fps="30"> <FadeIn AnimationTarget="container" minimumOpacity="0" /> </Parallel> <!-- hides the loading image --> <ScriptAction Script="hideInProcessImage($get('imgLoading'));" /> </Sequence> </OnUpdated> </Animations> </ajaxToolkit:UpdatePanelAnimationExtender>
And the javascript: <script language="javascript" type="text/javascript">
// show the image in the center of the container function showInProcessImage(img, container) { // get the bounds of both the container and the image var containerBounds = Sys.UI.DomElement.getBounds(container); var imgBounds = Sys.UI.DomElement.getBounds(img);
// figure out where to position the element (the center of the container) var x = containerBounds.x + Math.round(containerBounds.width / 2) - Math.round(imgBounds.width / 2); var y = containerBounds.y + Math.round(containerBounds.height / 2) - Math.round(imgBounds.height / 2);
// set the position of the in progress image Sys.UI.DomElement.setLocation(img, x, y); // finally un-hide it img.style.display = ''; }
// hide the image function hideInProcessImage(img) { img.style.display = 'none'; }
</script>
I've left out the details of actually handling the paging and sorting events on the GridView. I assume you are doing that already (or know how to do it).
One more thing to keep in mind - even though you are partially rendering the screen, you are still hitting the server (and your code-behind page). On your partial post-backs, don't perform any extra work in the code-behind that's not going to be rendered in the update panel (e.g. hitting the DB, populating drop-down lists, setting headings, etc.). And don’t be fooled into thinking that Ajax-enabled web apps take a significant burden off the server. If they are designed to be too "chatty", they can even make things worse!
Thursday, April 10, 2008 9:42:23 PM (Eastern Standard Time, UTC-05:00) .Net | Ajax | Ajax Control Toolkit | ASP.Net
 Monday, April 07, 2008
 Sunday, April 06, 2008
Miado is out on CodePlex
I have been refining some data access code that I have used on a bunch of my projects to the point where I've made it fairly generic. I decided to publish it as a project on CodePlex. I just put the initial release out today. If you are interested, please take a moment to check it out and give me any feedback. Keep in mind, I wrote this specifically for those people who have (or want) to use straight SQL and ADO.Net in their data access layer. So if you want to use LINQ, Nhibernate, Subsonic, etc... they are absolutely great tools, but they try to hide/remove the SQL from your code, whereas this project just makes it much easier for those who use SQL. Here is an example of how to use it to create a collection of custom business objects: // ideally this declaration would be buried in your base DAO class
// or injected via an IoC container
IDbConfigurable dbConfig = new DbConfiguration(SqlClientFactory.Instance, connString);
IDbStatement dbStmt = new DbStatement(dbConfig);
ICollection<Address> addresses =
dbStmt.LoadSql("SELECT AddressId, Address1, Address2, City, State, ZipCode " +
"FROM Address WHERE City = @City")
.AddParameter("City", "Atlanta")
.QueryForResults<Address>(
row => new Address()
{
AddressId = row.GetValue<int>("AddressId"),
Address1 = row.GetValue<string>("Address1"),
Address2 = row.GetValue<string>("Address2"),
City = row.GetValue<string>("City"),
State = row.GetValue<string>("State"),
ZipCode = row.GetValue<string>("ZipCode")
});
Notice how it removes all the usual boiler plate code from a normal ADO.Net implementation. The only things you really need to do are provide the SQL, set the parameters, and then map the result set to properties on your business object. I'm using lambda expressions in these examples, but if you want to re-use the result set-to business object mappings, I normally create a method in my DAOs to use as a delegate: ICollection<Address> addresses = dbStmt.LoadSql("SELECT AddressId, Address1, Address2, City, State, ZipCode " + "FROM Address WHERE City = @City") .AddParameter("City", "Atlanta") .QueryForResults<Address>(CreateAddress); ... private Address CreateAddress(IResultSetRow row) { // full details not provided return new Address() { AddressId = row.AddressId }; }
If you embed the creation of the IDbStatement interface in a base class (or use the one provided in Miado.Integration), you can see how the code reads even more like a Domain-Specific-Language: // CreateSqlStatment() method is provided in Miado.Integration.MiadoDao
ICollection<Product> products =
this.CreateSqlStatement("SELECT ProductId, Name, Description, Color, Quantity " +
"FROM Product WHERE Color = @Color and Quantity > @Qty")
.AddParameter("Color", "Blue")
.AddParameter("Qty", 20)
.QueryForResults<Product>(
row => new Product()
{
ProductId = row.GetValue<int>("ProductId"),
Name = row.GetValue<string>("Name"),
Description = row.GetValue<string>("Description"),
Color = row.GetValue<string>("Color"),
Quantity = row.GetValue<int>("Quantity")
});
There is also a SimpleSql object that can be used similar to IDbStatement but the syntax is a little more terse since you don't have to map the parameters - they are merely replaced in the order you provide them: IDbConfigurable dbConfig = new DbConfiguration(SqlClientFactory.Instance, connString);
SimpleSql sql = new SimpleSql(dbConfig);
sql.ExecuteNonQuery("UPDATE Person SET FirstName = @FirstName, " +
"LastName = @LastName " +
"WHERE PersonId = @PersonId",
"John", "Smith", 1001);
// again, I like to embed this in a base class so it reads:
// this.CreateSimpleSql().ExecuteNonQuery(sql, param1, param2);
For this first release, SimpleSql is not supported for ODBC SQL statements (since it uses pattern matching to substitute the SQL parameters).
Here's another example where you can see how easy it is to get a count: int count =
this.CreateSimpleSql()
.QueryForOne<int>("SELECT count(*) FROM Employee WHERE YearsOfService > @YearsOfSvc",
new object[] { 15 },
row => row.GetValue<int>(0));
And yes, it supports the creation of DataSets and DataTables: DataSet |