Tigraine

Daniel Hoelbling-Inzko talks about programming

Castle Windsor XML Configuration Schema

While creating a Windsor XML configuration for a new project today I found myself looking too much at the reference to get started. I figured this may be because of the lack of a schema that would provide me Intellisense in Visual Studio. Shockingly I couldn’t find a xsd schema file for the Windsor configuration.

I then looked at some w3schools tutorials and figured out how to do a xsd schema myself and tried to remodel the Windsor configuration reference.

You can grab the xsd schema file here: windsor-configuration.xsd

I’ll post a little tutorial on how to load it inside Visual Studio later.

Filed under net, tools

RSS Feed moved

logo_footer

So, apparently Google has decided to finally get rid of Feedburner and moved their services over to new servers. 
That means new feed URLs for everyone, also for me.

The new Feed URL is: http://feeds2.feedburner.com/Tigraine

I changed the little subscribe button to the right, and Google has also put redirects on the old URL pointing to the new one. So, existing subscribers shouldn’t see any change.

Since I already moved (not the smartest thing), if you can read this in your reader, everything is fine.

Filed under site-news

Sharing a common AssemblyInfo between projects in a solution

Since I’m doing more and more layering I also started to split up my layers into different projects so I can’t bypass any layer by accident.

This leads to solutions with 10+ projects sometimes (tests, setup, etc..) and that looks like this sometimes:

image

So, that’s great and I can only recommend that. You get much better view over what dependencies your application has internally.

But that leads to one problem: Versioning the assemblies.
I don’t want to go through 10 projects changing AssemblyInfo.cs to correspond to the real version of my application. Since I only do the splitting into different projects to ease development, I always want all assemblies to have the same version. So, how to tackle this?

Simple: Create one master AssemblyInfo.cs (just copy one of the existing ones), and delete the others from the other projects. We want to re-insert the file, but this time as a link so changes to one AssemblyInfo.cs cause all projects to have a changed assembly information.

image

Yes, that’s right. There is a way to reference a file without copying it into the folder (well hidden behind that arrow there).

So, now the file shows up in the solution explorer twice, but changes will spread to other projects too:

image 

When having a MSI project, it won’t update a referenced assembly during setup if there hasn’t been a change to it’s version number. So I ended up installing a new version of the GUI component while the changes in the controller assembly didn’t install because there was no increment in version number. Annoying, but not so much of a problem once you know how to handle it :).

Filed under net

Change has come to Microsoft

Yes indeed, there have things changed.

After doing so much Winforms development lately I am finally back on the Web side once again. But this time not in swamped webforms land but breathing the fresh air of ASP.NET MVC. You may already know that because I’ve been already ranting about the platform and it’s love for HttpContext.

Anyway, this post is not about MVC, it’s about the great Rob Conery who made my day when I watched the first episode of his MVC Storefront series.

What impressed me?
This is the first and only sample I have seen come out of Microsoft that did not involve dropping a data grid right out of SQL server into the app, tweaking two properties and concluding: “And that’s how easy you can do xy with Microsoft XY.NET”

This is the first demo I see that did really feel like a real world solution and not like demo ware put together in an attempt to impress people with how little work is required to do something.
Developing software is hard, and it takes time and thought.
And Rob sharing his thoughts on testability, separation of concerns and his clever use of the repository pattern is just great fun to watch and follow.

This new way feels good.
I watched that webcast while deciding the structure of a very important project and it helped me very much in getting a better idea of how to tackle MVC. So, thank you very much Rob!

Oh, and yeah, I know I’m late to the party. Rob has put out 25 webcasts of the MVC Storefront series, it just happened that my attention was focused on NHibernate, Windsor, Winforms and RhinoMocks lately. I also have to admit that I dislike Webcasts since you can’t just scan through them to find out if you are interested or not.

Filed under net

ASP.NET MVC: Hide the HttpContext services with Windsor and a custom ControllerFactory

ASP.NET MVC was designed to be a very “clean” and testable framework for creating web applications from Microsoft. And they failed really badly in one place: HttpContext!

The fact that the ASP.NET MVC Contrib project has a whole project dedicated to mocking out the whole HttpContext for testing simply illustrates one point: It’s broken, period.
There is this one gigantic god hash table that has 5 other hash tables hanging from it that knows everything about the incoming request. And although it’s possible to fake the whole thing with RhinoMocks (as the MVC Contrib guys do it), it’s still a pretty stupid idea to have all those concerns in one class called “context” (and accessible to the controller code).
So, although the HttpContextBase is already an abstraction of the real context, I wanted to extract those things into specialized service classes that I have full control over (and that could then be used for even more specialized classes that handle data retrieval, thus making “magic strings” go away when dealing with requests and sessions).

I set out to create a request service class that follows a very simple Interface:

public interface IRequestService
{
    string GetRequestField(string fieldName);
}

The actual class is just a Facade for the HttpRequestBase class that gets injected into the constructor.

Problem here: I would have to new up this IRequestService in my controller, and that’s something I didn’t want to do. Object graph construction shouldn’t be in the controller at all, and so I want to inject IRequestService instances into the controller. And that can’t be done without control over the ControllerFactory.

The IControllerFactory interface is rather simple, and it’s the perfect place to leverage the power of a IoC framework to construct the controller objects.
So I simply pass the object creation off to Windsor in the CreateController method:

public class ControllerFactory : IControllerFactory
{
    private WindsorContainer container = new WindsorContainer(
                                        new XmlInterpreter(new ConfigResource("castle")));

    public IController CreateController(RequestContext requestContext, string controllerName)     {                  return (IController)container.Resolve(controllerName);     }

    public void ReleaseController(IController controller)     {         var disposeable = controller as IDisposable;         if (disposeable != null)             disposeable.Dispose();         container.Release(controller);     } }

What then took ages for me to figure out was how to instruct Windsor to use current HttpContext.Request object. Turns out, I was searching in the wrong place: That functionality is in MicroKernel and not in the Windsor container.

public IController CreateController(RequestContext requestContext, string controllerName)
{
    container.Kernel.AddComponentInstance<HttpRequestBase>(typeof (HttpRequestBase),
                                                           requestContext.HttpContext.Request);
    return (IController) container.Resolve(controllerName);
}

The AddComponentInstance method allows you to pass in a concrete instance that should be used when searching for a service. This way when Windsor constructs the RequestServiceFacade class that takes a HttpRequestBase as dependency it will simply inject the one specified instead of trying to construct the HttpRequestBase itself (that doesn’t work ;)).

This now allows me to easily swap out request implementations by just changing the Windsor configuration.

Filed under net, testing

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.

Filed under programmierung, patterns

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?

Filed under net, programmierung

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)

Filed under personal

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 :).

Filed under net, net, c, programmierung, printing

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.

My Photography business

Projects

dynamic css for .NET

Archives

more