Wednesday, October 31, 2007

2008 Dodge Challenger

One thing I enjoy about living in the Detroit area is that we get to see certain cars on the street that people in other areas probably don't see. Just today I saw a 2008 Dodge Challenger barreling down the highway with manufacturer plates in the back. I first saw it in my rear view mirror and thought to myself, "damn, that car looks mean". As it passed me it just looked like a beast, yet smooth.

I was very impressed seeing the car in person. I was not as impressed when I first saw the photos online. Even though I think the car looks great, it's still not the kind of car I could see myself owning. That is the sad fact that I'm scared many others will also agree with. The car looks so good it deserves to succeed. Good luck to Dodge!

-- John Chapman

MidpointRounding Enumeration?

I learned something new yesterday, and man do I love learning new things. While evaluating how a piece of our system was behaving a discussion of the Decimal.Round method came up. The code we were evaluating was not something I wrote, but it is something a co-worker and I inherited.

All of the code which we have in this portion of our system uses the overload which takes the decimal to round and an integer describing how many decimal places to round that decimal to. But what is the algorithm that is used to perform this rounding? It's a question I had honestly never asked. I think this is a case where I just made an assumption, and you know what they say about assumptions.

My co-worker introduced me to the System.MidpointRounding enumeration. It turns out that .NET lets you specify how you want the midpoint rounded. This is the case where I always assumed it rounded up. It turns out that is one of the values (AwayFromZero), but there is also another option (ToEven). It also turned out, upon further investigation that ToEven is used by default. I have not verified that Math.Round works in the same manner, but I would assume it would (I know there goes that word again).

ToEven means that when the decimal place being rounded is half way between both options it rounds the digit to the closest even value. For example if you were rounding .215 to 2 decimal places the output would be .22, but if you were rounding .245 to 2 decimal places the output would be .24.

I believe this is to try to minimize the impact of rounding on the average. If you are dealing with a large set of numbers you should receive a relatively even split of numbers which would be rounded up as well as an even split of numbers which would be rounded down resulting in a net effect of zero. This rounding business makes a lot of sense to me now.

--John Chapman

Tuesday, October 30, 2007

Blog Rename

I have received some negative feedback from people regarding the name of this blog. People have indicated that the name is a bit negative and may put some of my intended audience.

My goal was simply to have a name which seemed catchy and memorable. I figured "Chapman's Constant Complaining" accomplished both goals. I wanted a name with alliteration. I also figured the name would be unique.

However, due to the feedback I received, effective today this blog will be known as "Chapman's Coding Corridor". I still get to keep my alliteration and I still think it is a somewhat unique name. I think it also emphasizes the positive role this blog should play.

Chapman is simple, it's my name. Coding is also simple since this is intended to be a technical blog revolving around software development. Corridor is a little less clear. I chose corridor, since, first, it begins with C and I like alliteration. But second, because corridor implies a path. It implies there is a goal with this. It indicates progress and improvement for myself as well as the people who read this.

The current feed address is still, although I do plan to change it to If your news reader stops finding my blog in the next few days, please redirect it. I'm sorry for any inconvenience this may cause.

--John Chapman

Monday, October 29, 2007

Webform_AutoFocus() before Sys.Application.Initialize()?

Recently I was developing an ASP.NET Ajax extender control which added behaviors when the target control gained focus. It was a custom implementation of an auto-complete control. Picture your standard auto-complete control but with multiple columns. So if you were to enter customer organizations you could enter by a system id, customer name or city where the customer is located. You could even enter a combination these attributes.

Anyway, if you've worked with the ASP.NET Ajax ScriptControl before you would know that you wire up your events within the initialize method, which you override from the base JavaScript "class". This allows the web browser to complete rendering of the page so all controls are created and properly registered before your code tries to use them.

However, I ran in to a bit of a snag when I tried to use the ScriptManager.Focus() method to set the focus to my target control upon first rendering of the page. I have a user entry screen where users can enter many records in sequence. So basically the users enter data in a few fields, hits submit to add the record and then the focus returns back to the first field, ready for the user to continue entering data.

The idea seemed solid to me, but I found out that the focus behavior wasn't working as I expected. I took a look at the rendered page and noticed that the Webform_AutoFocus() call which is created by the ScriptManager.Focus() runs prior to the Sys.Application.Initialize() call which calls my controls initialize! This means that my focus event handler has not yet been wired up, and there is no way for me to listen to the focus event.

Why is this? I can't think of a reason why the framework would want the focus to occur before initialize. Doesn't the name initialize even seem to imply that it would be the first function to run?

So I thought of a potential workaround. What if I could interrogate the target control to see if it currently has focus when I run the initialize method? It's not the prettiest solution, but it seems like it has potential. Unfortunately this hit a bit of a snag as well. After some research it turned out that IE has a property on the document known as activeElement which will provide the control which currently has focus. The problem? Only IE has such a property to tell me what control has focus, and I hate doing something which only works in a single browser.

Unfortunately I wasn't able to find any other workarounds, and as such only IE will appear to handle the system derived auto focus correctly. I suppose there are worse things to worry about. The control still works without listening to the focus event, it just works a little differently than I would like.

Microsoft, why couldn't you have just put the auto focus after initialize?

--John Chapman

Sunday, October 28, 2007

.NET 3.5: The Good Stuff

With my last two postings "Partial Methods. What The?" and "C# 3.0 Extension Methods? A Good Idea?" taking shots at new features in .NET 3.5, I wanted to make a new post where I look at some of the new features I'm actually excited about. Even though this blog is titled "Chapman's Constant Complaining", I'm not negative about everything! There is a lot of good on the horizon.

1. Anonymous Types

Anonymous types are tool in .NET 3.5 that allows you to specify types based on the properties contained in the type, rather than the class declaration. The type has no name, meaning that you will not be able to construct a new instance of this type by using the new className() mechanism.

Basically, anonymous types free the developer from having to define a new class for every one off purpose in the application. I'm an NHibernate addict. I think it's absolute fabulous tool, and if you're reading this and you've never tried it, go download it right now. You can find it at Anyway, with NHibernate I find myself creating classes all the time which contain just the data I want returned from a query. You then create a constructor which takes just the fields you want and then reference this type in your HQL query. This is very helpful when trying to tune an HQL query for a complex search page where you need to collect display data from many objects, or even aggregates of child data.

In theory anonymous types will free developers from this time consuming task. NHibernate, much like LINQ, would be able to construct a new anonymous type for us containing just the properties we asked the HQL to return us. Note that this is actually the main use of anonymous types in .NET 3.5, support for arbitrary data being returned from LINQ expressions.

Anonymous types go beyond just queries though. How many times have you needed a simple two or three property class to perform calculations within a method? I've created one off "info" classes in the past. I don't know why I call them info, I just do. We now have the ability to define that "info" class as an anonymous type and no longer worry about the actual class declaration.

2. LINQ (Language Integrated Query)

This is the big daddy of .NET 3.5. Who hasn't heard of LINQ? The way it has been talked about it sounds like it will solve every problem ever created by a developer. I actually think LINQ is way over hyped. over hyped or not, it's still a very cool new feature which will change how we develop applications with .NET going forward.

First, I want to cover why I think LINQ is over hyped. LINQ is being talked about like there has never been anything similar in the past. Most examples which are provided are used to query a database using LINQ to SQL which is really just a very simplified OR/M tool. What some people don't realize is that tools like NHibernate, LLBLGen Pro, Entity Spaces and others have been around for a long time, offering better OR/M tools and very sophisticated query mechanisms for some time.

Now, LINQ still deserves it's credit here because it actually takes what we've learned from our OR/M tools a bit further. I'm most exited about having strong typing on my queries written in C#. I hate that the only tools I have available to me are based on strings. If an object's property is renamed it is often very difficult to spot any potential queries which were not updated until runtime. Having this check performed at compile time is a huge advantage.

Secondly I think it helps people look at their C# objects in a different manner. When trying to explain OR/M tools to developers who haven't previously used an OR/M I try to explain that the OR/M is really a synchronization tool, not a database persistence tool. Think of the database as just your extended memory, perhaps a second level memory store. As far as you are concerned there is no difference between objects in memory and objects in a database. LINQ helps to re-enforce this thinking in that you can write the same queries against your objects in memory as you do your objects in the database. I think this may cause some issues for some people at first, but eventually will be very beneficial.

3. Object Initializers

This is sort of a minor one. Object Initializers seem like they are purely syntactic sugar which can be skipped, but they allow us to offer new features like the above mentioned anonymous types and LINQ. Object initializers also allow us to offer mechanisms to define our objects without having to worry about which constructors the class's author defined for us. I think overall it makes the code a bit cleaner and easier to read.

4. Type Inference (The C# var keyword)

This could be argued as a minor point as well, except for the necessity of the feature for the above mentioned anonymous types and LINQ. I think it is convenient to be able to declare types with a var keyword when declaring a variable with an assignment.

That being said, it is a feature I don't see myself using a whole lot. I would prefer to type the entire type when it is known. This makes it a bit easier to read the code in my opinion. If you are using an IDE like Visual Studio 2008 it should not make much of a difference, but is it really that hard to write int i = 1 instead of var i = 1? I know we're really concerned about the long generic types, but a little extra typing never hurt anyone.

So while I think this is a very useful feature, I'm a little concerned that it may be taken to the extreme in some code where every variable declaration is defined as var. Plus people already make the mistake of constructing new types only to throw them away on the next line. I hope this doesn't make that problem worse. Who hasn't seen the following code?

ArrayList list = new ArrayList();
list = RunQuery();

5. Lots of Other Stuff

There are actually many other cool features built in to .NET 3.5 for us, like built in APIs for RSS 2.0 and ATOM as well as an improved garbage collector. Overall I'm excited about .NET 3.5. Now if only we could do something about those extension methods and partial methods!

--John Chapman

Partial Methods. What The?

I alluded to this topic yesterday with my post "C# 3.0 Extension Methods? A Good Idea?". Today I want to discuss Partial Methods, another new feature of .NET 3.5. If you are unfamiliar with Partial methods, you can get a briefing here.

I think Microsoft has really gotten off track with this enhancement. The possible advantages seem so insignificant that I can't imagine why this was worth anyone's time. This is my #1 most loathed feature in all of .NET. The only feature I've seen talked about is a mechanism for lightweight event handling, or should I say pseudo-event handling?

We already have mechanisms for listening to events in .NET. If we want to perform operations in a BeforeUpdate() and AfterUpdate() manner we could listen to events which would fire named BeforeUpdate and AfterUpdate.

I understand the idea behind the "conditional method" aspect of the feature. But does it really kill us that much to use an if statement? Does one if statement which checks to see if any listeners are registered for an event kill the performance of the system? If this is your system, then I'm jealous. To get to the point where every if statement needs to be taken into consideration due to performance constraints seems like an intriguing problem, which many of us would love to work on. It just seems like there aren't many examples of this in the real world. We are ok with the statement which checks for event listeners. At least now our code is readable and we don't have to worry about not knowing what our code will output by just looking at our method's code.

This whole approach makes me think of JavaScript and the mechanism used for it's pseudo-event handling. It seems that with JavaScript we have taken the exact opposite approach to what we are seeing with partial methods. In JavaScript we used to rely (or maybe people still do) on a mechanism which is very similar to partial methods.

Haven't we all seen this:

<input id="btn" type="button" onclick="alert('button clicked');" />

or alternatively this:

document.getElementById('btn').onclick = function(e) { alert('button clicked'); };

The way this works is we assign a function to the already predefined declaration. Then the button object will call the defined method when the user clicks on the button. This is very similar to how partial methods are intended to be used. The developer (or code generator) will create a definition for the method. If you want some code of your own to run when an event takes place you simply provide the implementation of the previously defined method. There you have it, simple events in an old school JavaScript way.

But what have we learned with JavaScript? This isn't the best way to use events. What happens when we want to have multiple listeners? Using the above code whichever listener registers their method last will win, all earlier listeners will be discarded. We've been introduced to a new mechanism in JavaScript. For brevity I'll only cover the ASP.NET AJAX 1.0 approach. ASP.NET AJAX brought us the $addhandler() method which registers events on objects much like we are used to in .NET. Now we are able to have as many listeners as we want. We no longer worry about destroying prior listeners.

So if we have made these strides to move away from the "partial methods" type approach in JavaScript why is our new .NET library moving backwards? I really hope I never have to deal with partial methods in the code I work with.

What scares me most about partial methods is what happens when they get into the wrong hands. The potential for writing unreadable/unreliable code is astronomical. Lets all hope we are spared these experiences.

Am I off base here? What am I missing?

--John Chapman

Saturday, October 27, 2007

C# 3.0 Extension Methods? A Good Idea?

While I was attending the Day of .NET conference in Ann Arbor, MI last Saturday (10/20/2007) I had the opportunity to talk to an old co-worker of mine. He said something that really caught me off guard. While talking about new things that had us excited, he told me he was really excited about extensions methods and said they were really going to help him where he works. If you are new to extensions methods take a look at an old blog post by Scott Guthrie here.

I don't want this to sound like I am saying anything bad about this former colleague of mine. He's a very sharp person and an excellent developer. I'm confident that he will use this technology appropriately, but at the same time there are other options, and the statement just caught me way off guard.

Of all the new things to get excited about, extensions methods would have been near the bottom of my list. In fact the only reason they aren't at the absolute bottom is because of the wonderful new feature known as partial methods (More on that another day).

Honestly, extension methods scare me half to death. The existence of extension methods and the previously mentioned partial methods scare me so bad I could see myself recommending holding off on .NET 3.5/C# 3.0 until a proper policing process is put in place.

In a quote on the Scott Guthrie blog, Scott made a true enough statement which said "When used correctly, I think you'll find that Extension Methods can significantly improve code comprehension within code reviews, and lead to fewer lines of code and fewer bugs." Now, that is fine and all, but I'm not worried about when they are used correctly, I'm worried about when every unqualified programmer gets his or her hands on this dangerous new technology. OK, so Microsoft needed extension methods to implement LINQ, I understand that, but couldn't we have maybe hidden it from other developers? Maybe we could have found another way?

If you are wondering why I'm so paranoid about this, it is because of the massive amounts of incomprehensible code I've seen in my life. I just see this adding to it. People who do not understand the purpose of extension methods, or have the judgment to properly determine when they should use them and when they should not use them are going to litter in our code.

In most applications I have worked on the String class plays a monumental role in our development effort. I can see it now where a developer gets it in his or her head that we need mountains of extension methods written on the string class. Now you may say to me, "You'll only see them if you include that namespace though". Well, I can see these same developers saying "It's such a pain to have to keep adding a using statement to my code files when I want these awesome string extension methods everywhere! I'll just put in the the System namespace, then it'll always appear for me! Just imagine code where you could use a string for anything. Every conversion method imaginable can live on the string. The string class will have the ToInt32() method, the ToInt64() method, the ToDecimal() method, then it will get even more fun when we start seeing things like ToOrder() where the extension method will convert the string to an Order number then load the Order object from the database and return it. The possibilities are limitless!

Let's not pretend like we haven't seen developers use the string object for way more than it is supposed to be used for. I've already had to put up with it used as a rounding mechanism, if we just take a decimal/double output it to a string with two decimal places, and then parse it with the decimal/double class we'll have a rounded number to two decimal places! What if I just want a DateTime object with the date value but a time of midnight? Since I don't know about the Date property of the DateTime I might as well use the ToShortDateString() method and then DateTime.Parse() to get the new DateTime value back without a time! What could be more awesome? Can't you see these same people using the new extension methods to shoot themselves in the foot?

We'll have code reviews only to find their code is near impossible to read. A senior developer may write a library to be used throughout the application to keep things consistent, scalable, reusable or otherwise in line with the goals of the company/team, only to find that another developer though it needed some new methods which completely violate the interface of the library. Now other developers start seeing these new methods in their intellisense thinking they are part of the library, only to later find out that any code written using these extension methods now needs to be re-written.

I've had developers change core libraries on me before where they had no business doing such. I previously built a system where every message returned from our business objects was associated with a code in an enumeration. This enumeration is then used to look up the appropriate message depending on the culture/language of the user (Even if the initial releases only had English) when displayed. Developers though this was "inconvenient" and too time consuming, so what did they do? They added a new message type where you just provide the string you want to display (in English) and a generic message code like "Error". Wow, now it is so much easier to write these business object methods!

Now this was easy enough to catch, and in all honesty probably an honest mistake where they didn't properly understand why we were doing what we were doing. I fear extension methods are just going to make things like this harder to catch!

Why do we need the extension methods when we can just use the static class utility methods instead? You want to have some one off method to check for the validity of a string as an e-mail address, but don't want to write an e-mail class? How about an EmailUtilitity static class with a static method IsValidEmailAddress(string email)? Now instead of writing

if (email.IsValidEmailAddress())

you instead write

if (EmailUtility.IsValidEmailAddress(email))

What is so horrible about that syntax? To me it is far easier to read, more maintainable and what most of us are already used to! Just about any use I can think of for an extension method can be written this way instead, and that's how I would prefer to see it.

Am I off base here? Is there some big picture I am missing? Let me know, I would love to know why extension methods are actually a feature we all need. It would surely make me feel a lot better about the prospect of upgrading to .NET 3.5. As it stands now I'll probably recommend upgrading to Visual Studio 2008 for the added JavaScript support, but using the .NET 2.0 libraries instead of the 3.5 libraries.

--John Chapman

Thursday, October 25, 2007

NHibernate Non-Mapped Joins

Recently I received a question asking how to perform an HQL query which joined two entities which were not related in the mappings. I realized that this isn't a simple straight forward concept like most new NHibernate users would probably expect. It doesn't work the way I think 95% of users would initially try to accomplish it.

Some times we need such functionality because we are concerned of our collections growing too large if all collections are mapped. Lets say that for whatever reason we have a Customer class which is referenced by an Order class but the Customer does not have a collection of Orders. Lets say we also track wish list items to show items the customer would like to receive, but again do not have a collection of WishListItem objects on the Customer class.

Now we may think we would write a HQL query to show orders which were placed for an item in the customer's wish list like the following:

FROM Order o
INNER JOIN o.OrderLine ol
INNER JOIN WishListItem wli
ON (wli.Customer = o.Customer AND wli.Product = ol.Product)
WHERE o.Customer = :customer

Unfortunately we would be wrong. HQL is not SQL and does not follow the ANSI SQL syntax we have become so familiar with. Even though INNER JOIN is a keyword in HQL it does not work like it does in SQL. Instead a non-mapped join is represented much like the old style SQL joins. We would instead use the following HQL query:

FROM Order o
INNER JOIN o.OrderLine ol, WishListItem wli
WHERE o.Customer = :customer
AND wli.Product = ol.Product
AND o.Customer = wli.Customer

I hope this helps anyone struggling to create HQL queries between entities which are not explicitly mapped.

--John Chapman

Wednesday, October 24, 2007

ApplyStyleSheetSkin On System.Web.UI.Control?

I've been a big fan of the theme support which was added in ASP.NET 2.0, especially when I found the StyleSheetTheme property which lets me control at what time the skin values are applied.

Lately I've been building some reusable ASP.NET AJAX controls which are built by extending the ExtenderControl class which is a part of ASP.NET AJAX 1.0. I have been making reusable controls which serve a general purpose for the application I am working on. I like to make the control entirely configurable so I provide many properties which are settable by the consumer of that control.

I then wrap that control in a composite control with the control it extends and add context to this control. For example I may make a really cool auto complete type control and then make a composite control that understands my customer object. The composite control would include a textbox and the autocomplete ajax extender control. The control would also include information on how the list of customers should be filtered or anything else which is specific to the context of a customer.

Now, I've built many composite controls using these AJAX controls, but how do I define defaults for all of the controls? For example I want 250 millisecond delay for the AJAX control before making a web service request to filter what the user entered, how do I set this by default for all items on the site?

My first attempt was to make wrapper properties on the composite control that just exposed the child properties of the underlying autocomplete control. This works well, then I create one item in the skin of my active theme per composite control and away I go. This works, but it is areal pain, and it seems like there should be a better way.

I later stumbled upon the ApplyStyleSheetSkin method of the System.Web.UI.Control class. This looks perfect. I can call this method on my AJAX control which inherits from the ExtenderControl since ExtenderControl inherits from System.Web.UI.Control. This will be perfect. I'll just have to add one item to my skin file and then all composite controls can automatically share these defaults! What could be simpler? I can't believe I didn't know about this earlier.

So I give it a shot and see an error message saying the method only works on System.Web.UI.WebControls.WebControl! But then why put the method on System.Web.UI.Control? And why make no reference to it on the MSDN documentation? Meanwhile, I'm back to square one, making wrapper properties and duplicate entries in my skin file. Why all of the confusion Microsoft? This one makes no sense!

Yes I know I can just use IExtenderControl and basically build my own ExtenderControl which inherits from System.Web.UI.WebControl but that is a lot of logic I would prefer Microsoft worried about and I feel it shouldn't be necessary!

-John Chapman

First Post... Go Sox!

This is my first bog post of what I hope will be many. I have been meaning to get started for a long time, but I always let something get in the way of getting it up and going. I plan to be focussed around technology, with most of my focus centered around C#/.NET and probably NHibernate as well.

I am currently employed at Ryder System, Inc. and live in the Detroit area but I grew up in New England, go Red Sox!

Blogger Syntax Highliter