DateTime parsing in ASP.NET MVC RouteEngine

After doing so much winforms development lately I am getting started on an upcoming an MVC project. And while thinking about the basic structure of the whole thing and trying out some things I discovered some pretty funny behavior in the DateTime parsing of the routing engine.

Typical example. A route that should map urls like:

http://www.website.com/Archive/10-12-2008/

I have my route laid out like this:

routes.MapRoute("Archive",
                "Archive/{date}/",
                new {controller = "Archive", action = "Show"});

And the controller action looks like this:

public class ArchiveController : Controller     
{
    public ActionResult Show(DateTime date)
    {
        return View();
    }
}

Now, when I open the browser and point it to the following URL it works

http://localhost:51942/Archive/12.12.2008

While this one doesn’t

http://localhost:51942/Archive/15.11.2009

The second one returns the following error:

The parameters dictionary does not contain a valid value of type 'System.DateTime' for parameter 'date' which is required for method 'System.Web.Mvc.ActionResult Show(System.DateTime)' in 'MVCDateTimeParseTest.Controllers.ArchiveController'. To make a parameter optional its type should either be a reference type or a Nullable type.

 

Needless to say that I am a bit lost at the moment. Both are perfectly valid dates and yet one works the other doesnt. I had the same problem when trying other formattings when I tried dd-MM-yyyy. Why and when dates get parsed correctly is very random it seems.

I didn’t constrain the route on purpose to test out how to create links with dates in them (and doing a 2008/11/12 style link also doesn’t really work too well). The only formatting that seems to be working 100% of the time is http://localhost:51942/Archive/2009-12-12. And that’s not really how I (Austria formats dd.MM.yyyy) like it.

Any suggestions?

Read more →

Inevitable leaking of control Information

I’m wondering if anyone of you has a better solution (or thoughts) for this.

Assume I have a business rule that states “If there is already a bill for one special order, the user should be warned when trying to create another bill”.
So, obviously I simply display a MessageBox telling the user he’s about to do something stupid (but he should have the choice).

I see a “leak” of business logic from the Controller to the GUI when I have the GUI question the controller layer if there is already a bill for the Order. The decision about whether to proceed or not has to happen in the GUI since it’s the only layer capable of displaying a messagebox to the user (simply reference wise). But the semantics of this decision actually belong into the controller. And frankly, I can’t really find a viable way to separate the logic from the Gui on this case.

The system is layered as follows:

image 

The root cause of this problem is that I’m not really following the MVC pattern on this one. The GUI always calls down to the controller instead of the controller calling the GUI. This way I often see myself struggling to somehow push logic down into the controller while trying to keep the GUI free from logic. But when it comes to complex interaction I realize now that the GUI is actually driving the whole thing, and that makes this whole thing a pain to re-wire later.

One way to detect things like this is when your controller classes don’t contain actual state. Most of my controller methods are just taking input and applying logic to it, not actually controlling the information flow inside the application (and that should have made me suspicious a long time ago).

So, I guess I can blame myself on this one and will have to try to minimize the damage done until I get time to refactor the system at a later stage.
Still bugs me that I fell for this, but the whole point in failing is to be able to learn from mistakes. :)

What also supports my case is that the controller and repository layers are very well tested, so I may be able to divide the controller layer into multiple strategy classes (logic dumps) while reworking how control flow is handled by the system.

Read more →

2008 Gadget List

While reading Georg’s list of gadgets he bought in 2008 and suggests I thought it might be interesting to compile such a list myself.
So, here it is: A list of gadgets I bought and would recommend (and it’s boring to be honest).

Dell XPS M1330

image After running Ubuntu on my old laptop (1.6ghz Acer Aspire) for almost a year due to the lack of system resources I finally got myself a new laptop this year. The old one was a quite heavy 15” WXGA screen so I decided that this time I’d go with something smaller and more portable.
Since I like Dell for their brilliant support I choose the XPS M1330 (the only 13” laptop available from Dell at that time).
Haven’t regretted it since, I’ve been working exclusively on my laptop for quite some time now and this thing hasn’t failed me since. It’s speedy (except for fancy 3d graphics) and still light and has great battery life.
I also found that 13” is enough to actually program on, but it takes some time to get used to bringing up most panels through shortcuts while working in VS fullscreen.

Canon EOS 450D

image I’ve never had a camera before. I never even bothered to buy one because I simply never deemed the price appropriate for what I’d get.
While occasionally taking some snapshots with various point and shoot cameras I was never really content with the results once I’d try to view the images on my PC. Pictures would either be noisy due to bad light, or when using flash all colors would simply look wrong.
This time though, I found the EOS 450D at pricey 470€ and gave it a try.
The camera is everything I asked for and more. It’s light, fast, picture quality is great and the battery lasts me for more than 2000 pictures (still amazed about that). Although I may still suck at photography (I hear little Yoda whisper to me “much to learn you have padawan” all the time *g*), I think some of my pictures actually don’t look too bad, so I've put them on Flickr.

Since my girlfriend blogs for a German speaking magazine on art and culture the woman-acceptance-factor on this one was quite high since can borrow it to take pictures of events she’s blogging about.

XBox 360 Elite

imageOk, maybe it was just silly to buy this thing 1 month before the WoW addon Wrath of the Lich King was released, but I haven’t really regretted it either. The XBox is just another awesome console that simply works. There are tons of games (although too few that can be played in coop and aren’t of the shooter kind), and using it as a media center extender also works quite well. Since the console also gave me an excuse to get myself a new TV and transform my basement into a “media room” I’m quite happy with the investment after all :).
Why consoles? Put in a DVD and play, it just works. No installs, no settings no hassle. I don’t have too much time for games, and not wasting on installation / configuration issues any more was totally worth it.
I’d also suggest getting yourself Guitar Hero: Legends of Rock, the most fun game I’ve played for quite a long time.

Note: This has a very low WAF so consider buying her something nice too before confessing your sin :).

iPhone

(I’ll spare you the obvious picture ;)) My old phone broke and I needed a new one, since I didn’t want to switch carriers (tele.ring) I was stuck with a very bad selection of low-end consumer phones that didn’t really satisfy my needs. But buying a smartphone in Austria without signing a contract usually means spending >500€. Since the dollar was so low at that time it I got an original iPhone for less than 300€ and unlocked it myself.
Still convinced that it’s the best smartphone available to date. But I guess that may change with new releases from Android and the Palm Pre looks interesting. I’d also like to note that it’s not really smart to buy an iPod nano and order an iPhone 2 weeks later.

HP w2408h 24” Widescreen Monitor

imageSeriously, do yourself a favor and get one of these. More space is always better, and I’m already waiting for the Dell 30” displays to drop in price because I need even more space. 1920x1600 pixel of space provide plenty of room for parallelism, and the display simply looks awesome. Although some people don’t like TN panels, the colors are just stunning.
Also with the new Windows7 dock features the big resolution will be even more useful.

 

So that's it. I guess I spent way too much money on way too few things ;). Now this year will probably get a bit heavier on photography equipment (still looking for some maybe a new zoom lens). And with Windows7 up ahead I will probably also update my home pc once again (components are just ridiculously cheap right now)

Read more →

Printing in .NET is simply broken

Ok, I blogged about the failed GDI+ API yesterday and complained about it. Those of you who are following me on twitter may already know that my little liaison with GDI+ is due to some printing my application has to do and the experience hasn’t been good so far.

My requirement is quite simple, print invoices and some other papers that may (or may not) span multiple pages.
So I came up with a very simple design for my printing needs that lets me reuse all printing dialogs by supplying different strategy classes that do the printing.

image

This has worked out so far, but I’ll have to adjust since I found out that printing multiple pages works totally different from what I expected. In my stupid little world I was thinking that going on to the next page would be as easy as calling NextPage() somewhere and the Graphics object would start drawing to the new page.

And I was so wrong.
Apparently, how it really works is by specifying in your print event that your document has multiple pages and the print event will fire as long as eventargs.HasMorePages is true. Yep, that’s right, the event will fire again!

So apparently, all code that gets called has some way of determining what stuff doesn’t fit on the page (that itself is a huge pain in the ass with graphics.MeasureString and everything) and it also has to find out what parts have already been printed to another page.

So, in a simpler world I’d have a switch statement that would branch depending on the page number like this:

private int pages = 3;
private void PrintDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
    switch (pages)
    {
        case 1: 
            //print page 1
            break;
        case 2:
            //...
            break;
    }
    pages -= 1;
    e.HasMorePages = pages > 0;
    if (pages == 0)
        pages = 3;
}

The irony of this is that this no longer works if you can hit a new page once your string exceeds one page. You’d have to cut off the string (after heaving measured that it won’t fit), and somehow store it so that when the method gets called next time the “part” that’s not printed yet will get printed. Can it get more stupid than that?
Having multiple entries into one method just seems plain wrong and leaves me no option as to have code everywhere to determine if something has already been printed (no need to say all the hassle there is to cut off something on page A and print the overflow on page B).


This whole RectangleF/SizeF acrobatics with almost static method calls in between feels so much like last century that I am very well inclined to write some OO library in the future to save me the hassle next time.

By the way, first I was thinking that if printing from within .NET turns out to be too hard I had this fallback plan to just generate HTML, display it in a Webbrowser control and print it from there. I should have done it that way, simple things tend to work :).

Read more →

GDI Drawing: String with word-wrap

GDI drawing is magic and not very well documented. Finding out how to make GDI draw a string inside a fixed width without constraining the height took me about 20 minutes, hopefully this post saves you 20 minutes of your life nobody will give you back :).

The problem with Graphics.DrawString() is that you can either supply a PointF that will be used as the origin, or you supply a RectangleF as layout rectangle. The rectangle’s sizes and position will be forced upon the text and word-wrap will happen to fit the text inside the rectangle, anything not fitting in the rectangle (given the font-size) will be cut off.
So if you don’t want to confine width or the height, setting that property on the RectangleF to 0 will make GDI not "cut off” but expand the rectangle as needed.

Needless to say that this behavior isn’t mentioned on the MSDN page for DrawString, that may have saved me time.

Read more →

Feeling like Bruce Wayne

IMG_1861

Although I don’t dress up with a fancy black suit and hunt criminals by night, holiday season means living a double life for me.
Most of my friends study in Vienna or Graz and only visit during holidays, so whenever they are all in town I have to maintain a student life during the night while still working during the day. That usually means getting up at 9am while staying up till 5am.

Believe me, when 6 people don’t accept no for an answer and want to play poker at your place, you’d better restock on coffee and make sure you eat light so you don’t ruin your stomach completely. (I start regretting having built my own poker table)

And still, it’s holidays so trying to maintain a 8 hour per day pace is almost impossible. Besides your family obligations at various christmas celebrations and the usual shopping madness there isn’t really enough space to get focussed on something long enough to actually finish it in a good way.

So today I came back to office and started filling out the holes in my application I left during the holidays. Working my way from //TODO: statement to the next, revisiting the old code I noticed one thing: Code quality doesn’t matter.

When I write code I can’t forget it afterwards. I mean, I suck at remembering syntax or class names (man I love google for bringing back my memories over and over again), but if I feel like a solution isn’t elegant enough or a module should be restructured to make more sense I’ll think about it whenever not occupied and eventually come up with something better.
What would have taken me hours to get right the first time, was fixed in a matter of minutes after I had time to think about it. So this leads to the interesting conclusion that nothing I’ll write today will actually matter next week, as long as I constantly rethink and rework my code I’ll end up with high-quality code no matter how bad it was when I first wrote it.

So the most important thing to consider when writing code the first time is not let implementation details “leak” out to other parts of your system, so reworking one part of the system won’t affect the other. Also writing tests for one-line methods may seem dumb and repetitive, but once you start juggling around stuff while a release date is coming at you at alarming speed, those one-line tests will assure that your app won’t blow up once deployed.

Read more →

Mapping large text or binary values with NHibernate

I encountered the following error when trying to map a large String to my SQL2005 database:

SQL Error Code -2146232060: “String or binary data would be truncated”

The issue here is that Nhibernate maps all string values by default as nvarchar(255) and so inserting something bigger to a field causes this nasty sql error. My mapping declaration looked like this:

<property name="Comments" />

After some searching I found Ayende’s post on NHibernate and large text fields gotchas that almost solved the issue, except for one thing, I didn’t know where to put the sql-type attribute. Turns out it’s defined in chapter 15 of the NHibernate doc (while mapping files are chapter 5).  
The sql-type=”NTEXT” attribute can only reside on the <column node beneath the <property node. So the correct mapping looks like this:

<property name="Comments" type="StringClob">
  <column name="Comments" sql-type="NTEXT"/>
</property>

If you don’t define the sql-type attribute even the StringClob field will be created as a nvarchar(255) by NHibernate (but it can map to a NText field if the schema exists).

Read more →

Don&rsquo;t get spoiled by LinQ To SQL

I got introduced to LinQ through the famous posts by ScottGu on Linq-to-Sql and always thought of LinQ as some really cool language thing that automagically enabled me to write queries within .NET.

All of ScottGu’s samples look like actual SQL Queries with real keywords within the language like:

var result =   from s in strings
               where s.StartsWith("d")
               select s;

So, when I was just briefly trying to get stuff done I used all those keywords as they seemed to fit and didn’t really try to understand the “deeper” concept behind those (as they magically generated SQL queries). MS introduced new keywords into the language, so be it, I was looking them up in MSDN and used them as such when using the LinQ-to-Sql datacontext.

Now, that I (and apparently Microsoft) have departed from LinQ-to-Sql I somehow forgot about LinQ for quite some time simply because I had no need for in-memory-queries for quite some time. And to be honest, I also never really thought about applying that strange LinQ syntax to objects in memory (I considered the above mentioned LinQ query more as a “c# strongly typed version of SQL” rather than a in-memory query method)

So, I was quite amazed of what you can actually do with LinQ if you abandon this strange undiscoverable SQL syntax and simply use method chaining. The above query can be rewritten without any “keyword magic” but with plain objects to look like this:

var result = strings.Where(s => s.StartsWith("d"));

The beauty of it? All the LinQ overloads reside on the IEnumerable<T> interface, and most of these methods will return an IEnumerable<T> so you can “chain” those method calls together like this:

var result = strings
            .Where(s => s.StartsWith("d"))
            .OrderBy(p => p.Length)
            .Select(p => p.Substring(0, 4));

And now the whole thing started to make sense. I can easily grasp how this is supposed to work, instead of looking at awe at the “SQL query” that magically works. And that’s where I went wrong the first time.

Instead of learning LinQ to objects first, I got caught in the database centric world of LinQ-to-Sql that made me not think of LinQ as anything other than a Database query tool.

Read more →

The power of delegates in C#

The common way to learn OOP design and best practices is through books on Java or books on C# that got translated from Java.
And since Java and C# both work pretty similar as far as objects are concerned, I never saw delegates put to good use except for events where they were automagically generated and used by the winforms designer.
I always knew delegates as a method signature that had to be present for an event to work (since the event requires a delegate type), but knew little else about their usage and workings.

So, I was quite amazed when I found out how useful delegates really are besides when doing events.
The delegate is simply put a “method signature type”, something like a interface for a method (or you could call it “function pointer” if you’re an oldschool C guy).
So it is essentially a type that represents a method, allowing you to call or pass around any method that matches that signature as a object.

So imagine the following two classes that share a common signature but no supertype or interface:

public class Class1
{
    public void Notify()
    {}
}
public class Class2
{
    public void Notify()
    {}
}

Now imagine you need to have those Subject classes in a list and you need to loop through them and call Notify on each of them. No problem if they share a supertype or a interface, and if they don’t you could extract an interface easily.

But if you don’t control that code (because it’s from a 3rd party etc), you’re forced to write some sort of adapter class that provides a common interface if you want to call that one method on all of them in some unified way.

Now C# has solved this problem gracefully by treating methods as a type, so if you omit the parentheses on your method call it will return a object representing that method. And that object can then be stored in a variable of a delegate type that matches the original method’s signature.

So I could define a delegate that can then be called to reference methods in different classes as long as they match my delegate signature:

public delegate void doNotify();

I could then create a variable of type doNotify that contains a reference to my Notify method in Class1 and call that variable instead of the concrete method on Class1:

doNotify method1 = new Class1().Notify;
method1();

The real beauty of this is that I can also pass that delegate around to other methods that know nothing about the type, only about that one method signature. Therefore I could write code like this:

public static void DoSomethingAndNotifyAll(IList<doNotify> subjects)
{
    foreach (var notify in subjects)
    { notify(); }
}

Where this came really handy (and where I found out about it) was when doing a pretty simple list interface that had a dropdown field that controlled sorting of the list. It was pretty standard, I had 3 methods that sorted the list (and I know I should have extracted strategy classes, but that seemed too heavy for the task at hand) and depending on the selected item in the dropdown one of those 3 should get called. The usual course of action would be to switch on the value of the dropdown, but that would have created a maintenance nightmare in the long term (inserting and dealing with the value would be somewhat redundant and I’d have to update 2 code passages for one change in the future). So the simplest solution I came up with was to create a delegate for the sort methods (public delegate void doSort()) and create a class that took a text and that delegate and exposed it as fields. Now I could use the DisplayMember property on my dropdown to display the text for the sort function and when needed I could just call the sort function through the delegate.

This then leads me to the apparent lack of generic controls in .NET that make all this interface work feel awkward and wrong because you are casting to and forth all the time, but that’s another story.

That all being said, I can’t say I encourage heavy use of delegates because the concept can be so easily abused. In most cases it’s better to use interfaces and object composition because they are not only better known, but also more explicit (you don’t see the delegate use as easy as some implemented interface). Use them wisely and you have a very powerful tool at hand, overuse it and you will end up with some pretty hard to read code.

Read more →

When Amazon became Ebay

There are many things I love about Amazon: free shipping, recommendations, customer reviews, good product pictures, awesome website, gift lists. I could go on and on, all those things make Amazon the #1 shopping site on the internet, and I love buying my stuff there. They offer free shipping on everything above 20€ and all books ship for free too. So, whatever you buy, you never think about shipping, you never think about returns or anything. You always know, there’s this big-ass company called Amazon that takes customer satisfaction etc pretty serious and will not cause you any troubles on returns etc. They always ship on time and they have almost everything.

Now, Amazon decided some time ago that “almost” everything isn’t enough and they went to really everything.
They opened the Amazon platform up through a program called Marketplace, where other vendors can sell their products through the Amazon.com website. And man do I hate that feature!
I never went to Amazon because they had everything, I went there because they had almost everything completely hassle-free.
Now, when I am searching for something I end up at 3rd party vendors 90% of the time (feels like Amazon stopped selling themselves almost) that have different shipping policies (almost nobody offers free shipping except for Amazon) and different return policies. Hell, I’ve seen 1-man-shops surface on Amazon that didn’t even have a rightful email address (listing a hotmail address in your company profile does NOT generate trust!).

Last week I decided to order a Canon EOS 450D DSLR and went to Amazon to shop for accessories  like memory, batteries etc.
Guess what? It took me almost 30 clicks to get to a product that was offered by Amazon! When searching for a SanDisk SDHC Extreme III 8gb card I found it 4 times, from 4 different 3rd party vendors but not from Amazon.
I gave up after 30 minutes of searching and ordered another SD card, completely pissed and very unsatisfied. And there is no way to turn the marketplace off, there is a filter that lets you select vendors but apparently this isn’t working when selecting Amazon (you still end up with a listing of 3rd party vendor sold products, yikes!).

The best thing is: Apparently Amazon is selling the SanDisk SDHC Extreme III 8gb card, I just couldn’t find it last week but did so now.

So why did Amazon destroy one of the most pleasant buying experiences of all time? I go to Amazon to buy their products, not to buy some other guys products he is selling from his basement, getting charged shipping costs and not knowing how returns or reclamations are going to be handled! Are those people insane? If I’d be into that kind of things I would be shopping at Ebay not at a respected and well trusted Amazon!

I can only hope Amazon will change their mind on this and create some “Amazon products only” button, so I can enjoy shopping again. Now it’s more a quest to filter 30 products for their vendor.

Read more →