Tigraine

Daniel Hoelbling-Inzko talks about programming

Pandora now likes concrete classes

While getting into WPF and the MVVM pattern (you should check out this Webcast by Jason Dolinger if you need a tutorial to get started on MVVM) I found myself somehow dealing more with concrete classes then I was used to. Usually I hide everything behind some interface and try to think really hard before violating that habit. Nonetheless, ViewModel classes are just that, ViewModel classes very special to their View and you really can’t hide them behind a meaningful Interface (without looking too silly).

So, after writing a fairly small application with only 3 ViewModel classes I found myself writing this utterly meaningless block of code:

container.Register(p =>
{
    p.Service<PersonViewModel>()
        .Implementor<PersonViewModel>();
    p.Service<AddressesViewModel>()
        .Implementor<AddressesViewModel>();
    p.Service<ProductViewModel>()
        .Implementor<ProductViewModel>();
});

It’s not completely meaningless after all, everything that keeps me from writing new PersonViewModel() somewhere in my code is just awesome. Only, it’s a bit too much of ceremony for something that simple. By asking for a concrete type you already tell Pandora everything it needs to know.

So, now Pandora can resolve concrete types directly if there is no registration that says otherwise. If you ask for a concrete class A, you’ll get a concrete class A even if the container is totally blank.
Now, if a class A is registered with the container it will use that one, if not Pandora will try to figure it out.

That also leaves open one way of extending your system. You can start off with an implicitly registered concrete class A, and if you want to subclass it later to modify behavior you only register the new subclass B as implementor for service A with Pandora and you’re set.

So, quick recap on how this works:

When a concrete type is requested and can’t be found in the configuration it will be instantiated if:

  1. It’s a concrete type
  2. You are not resolving to a name
  3. The dependencies of the requested type can be satisfied.

Also keep in mind that the default lifestyle for Pandora is singleton, so once you request A, you’ll always get the same instance back as long as you don’t change that through an explicit registration.

As always you can grab the source from the BitBucket site. There is no new binary release (I only moved up a minor version), but compiling Pandora is a pretty straightforward process as long as you have Visual Studio installed.

Ps: I was amazed how easy it was to implement this. Basically all I did was write a wrapper around the ComponentLookup service to implement the new functionality. It’s all in one place :).

Help! My provider hijacks my DNS requests!

Today I followed a link to a no longer active domain and suddenly found myself on UPC’s (my provider) search looking for that URL:

image

My first reflex was to check if my default search provider may be set wrong:

image

Woot? No, my search provider is Google. I just queried a DNS record that does not exist, and I got a result back instead of a DNS error. Now, imagine my head going red and some danger lights starting to flash.

First test I did to confirm my suspicions: open a raw putty connection on port 80 to some random DNS I know doesn’t exist:

image

Then I just did a basic HTTP GET request from my console to see what the server would return:

image

Ok, so what just happened here? First of all, there should be no web server to accept my connection! Hell, I shouldn’t even be able to resolve to an IP address!

So, running a quick nslookup turned up something interesting:

nslookup www.lksdafklsdlkfdsf.com Server:  viedns09.chello.at Address:  195.34.133.21
Apparently, UPC is abusing the trust I place in them (by using their DNS server) and resolves ALL requests that can’t be resolved (don’t exist) to their own server that will redirect all HTTP traffic with a 302 status code to their search service.

Now, why is this bad? Isn’t search something I like when mistyping a URL?

Oh, it’s bad I promise you. It’s bad for many different reasons:

  1. All browsers will search anyway if a URL can’t be resolved
  2. My browser thinks the bad domain name actually exists
  3. UPC search sucks
  4. I can’t do anything about it short for changing my DNS server
I do set that search provider inside my browser quite consciously, and I do that for a reason. Google knows my preferences, Google has a search history I use quite often, Google is set to US so it won’t sort German results to the top of the list. And most important: Google has a cached version of almost every page on the interwebz so even expired sites can be looked at with Google.

So, whenever UPC is hijacking my bad DNS request to redirect me to their stupid little search, they take away my freedom of choice and force me (and all users of Chello/Inode in Austria) to override my browsers default behavior in favor of an inferior solution so they generate more search volume on their stupid service!

Only Solution: Pick another DNS. There are plenty of DNS servers out there that will gladly satisfy requests, only drawback is that they aren’t located in my provider’s subnet and therefore won’t be as fast as the one I used before.

This is just sad. Very very sad.

Filed under internet, personal

Medical Guesswork

Warning: This post is strictly non-technical. No .NET code was harmed during the writing of this and if you go on reading this you may lose 10 minutes of your life you’ll never get back! So proceed with caution and only if you don’t mind reading about my personal life.

My girlfriend recently went to see an orthopedist because her right wrist was hurting. After examining her for some time he said:

Could be [weird desease that involves necrosis inside the joint], let’s run some tests.

And off she went with an appointment 2 weeks down the road, waiting for the tests to prove that she has a necrotic bone inside her right wrist.

At 21 you don’t take such things very lightly (especially if they involve permanent damage to the right hand), and those two weeks of waiting for the “real thing" proved to be quite stressful for her. Thank god the tests came back and proved that the pain was caused by something else!

Now, fast forward one month, I went to see the same doctor because I felt pain in my left wrist over the last week. After doing a 3 minute examination (if you want to call some touching my wrist that way) he said:

Could be carpal tunnel, otherwise the wrist looks fine. Let’s run some more tests.

He then gave me the number of 3 other doctors to go to and run tests, to find out if I’ve really got carpal tunnel.

Guess what? I don’t care. I won’t go to see any of those and I certainly won’t ever go back to see that one again.

Why? Simple: I’m a programmer, my wrists are a very very valuable thing to me. I just wanted to make sure that everything is ok, not embark on a 3 week roundtrip to 3 doctors with the thought in mind “This CTS thing could ruin my life”. (And the pain was really just a small annoyance I wanted to get checked out, nowhere near actual pain)

Seriously? What doctor tells his 21/24 year old patient his “first guess” at a diagnosis? Especially such a bad one? Do I walk around my customers and tell them “Hey, from the look of the app I get the impression this codebase is unrecoverable, I’ll run some analysis but prepare to pay for a rewrite.”?

I guess you have figured out that I’m slightly annoyed right now. But rest assured that I am currently at perfect health. If my wrist-pain comes back I’ll see a (better) doctor – I promise.

Filed under personal

WebKit like focus indicator for WPF Windows

If you like Chrome/Safari or not, one thing that both have and all others lack is a good focus indicator that graphically shows me where my focus currently is. Jeff Atwood wrote something interesting on the topic of Where the Heck is My Focus:

But even if developers do remember to test for basic keyboard behavior, there's a deeper problem here. Keyboard navigation relies heavily on the focus. In order to move from one area to the next, you have to be able to reliably know where you are. Unfortunately, web browsers make it needlessly difficult to tell where the focus is.

I believe he not only has a valid point here, but also that his criticism this should not be limited to web browsers. Most if not all Windows applications do this thing badly, and it’s up to us developers to fix it.

So, I decided to try to put my recent WPF research to good use and tried to implement a small class that applies/removes a WebKit like focus caret:

image

The whole implementation is completely encapsulated inside a class named WebkitFocusEffect that only needs to be initialized during your window construction:

public Window1()
{
    InitializeComponent();

    WebkitFocusEffect.Initialize(this); }

How does it work?

First of all, the source is available on BitBucket in my repository, so you can just go ahead and look at it. But I’ll also try to shed some light about what goes on there.

Routed Events

WPF introduced a cool concept called RoutedEvents, meaning that an Event like GotFocus/LostFocus will travel through the object model to the point where it gets handled and stops there. This technique is important because, unlike Windows Forms, WPF controls can contain other UIElements. This gives you far more control over the look and feel of your application, allowing for crazy things like a button with a image instead of text:

<Button Width="100">
    <Image Source="http://upload.wikimedia.org/wikipedia/commons/thumb/8/85/Smiley.svg/100px-Smiley.svg.png"></Image>
</Button>

Resulting in this:

image

And that leads to the point of RoutedEvents: How do you know that the button was clicked? The event that was fired was the image’s click event, not the button. So, WPF introduced the concept of RoutedEvents that can traverse the object tree upwards and downwards. What means that the image’s ClickEvent gets passed on to it’s direct parent (our friend the button) to get handled there.

 image

If not handled at some level the event would travel up through the whole tree until reaching the root.

I used this technique to hook up the GotFocus/LostFocus events on our window (being the root element), relying on the fact that any GotFocus events by it’s children will bubble upwards the graph eventually reaching the window’s handler.

The handler then just unwraps the event’s source object (the source of the RoutedEvent gets passed along through the RoutedEventArgs parameter) and modifies it’s Effect property:

protected virtual void WindowGotFocus(object sender, RoutedEventArgs e)
{
    try
    {
        if (!(e.Source is UIElement)) return;

        var element = (UIElement) e.Source;         if (element.Effect == null)         {             var effect = new DropShadowEffect {Color = Colors.Gold, ShadowDepth = 0, BlurRadius = 8};             element.Effect = effect;             removeEffect = true;         }     }     catch (Exception ex)     {         Log(ex);     } }

One problem still remained: RoutedEvents can stop bubbling if they get handled at a lower level. This is how the button stops the image’s click event from spreading to it’s parent element, therefore containing it. So if you set an RoutedEventArgs.Handled property to true, it will stop bubbling up the tree:

private void LoginButton_GotFocus(object sender, RoutedEventArgs e)
{
    //This Event was handled and will not call Window's GotHandled eventhandler
    e.Handled = true;
}

Cool though is that RoutedEvents can’t really be stopped from bubbling, they do so anyway. Handled events just don’t invoke any event handlers up the tree any more, and that can be overridden explicitly when subscribing to the event:

window.AddHandler(UIElement.GotFocusEvent, new RoutedEventHandler(WindowGotFocus), true);

The last parameter is “handledEventsToo” and if set to true the event handler will be fired even if the event was already handled at a lower level. Allowing us to still do our thing while not getting in your way when subscribing to GotFocus / LostFocus events.

Effect

One little limitation is there though. Currently there is no EffectGroup container similar to the BitmapEffectGroup, and therefore only one effect can be applied to any UIElement at one time. So WebkitFocusEffect will just skip elements that already have a Effect defined.

I consciously went with the DropShadowEffect and not with the OuterGlowBitmapEffect because Effects are hardware accelerated (means they get processed by your idle graphics card instead of the CPU) and will not slow your application down as BitmapEffects would.

You can download the WebkitFocusEffect.cs through Bitbucket.

Filed under net, programmierung, wpf

imagineClub &ndash; Students for Students

In Austria every university has a institution called ÖH that is there to support students throughout their studies. They provide legal advice, course material and many other things.
The downside of this great service is that it’s directly associated with the university and therefore subject to some regulations regarding what they can do and what not.

Amongst the things that the regular ÖH isn’t able to do is provide course material other than the official things the professors provide. Student generated content could be wrong and that would look bad for the organization.
imagineClub was founded to solve this problem in 2007 and had a lot of success by requiring members to pay for their membership through term-paper submissions to contribute to the overall knowledgebase.

imagineClub also managed to partner with Microsoft and therefore was allowed to offer the MSDN-Academic Alliance service to all of their members. Allowing members to freely download and use Microsoft development software like Visual Studio, Windows etc..

Why am I telling you all of this?

Well, half a year ago I agreed to become the assistant chairman of imagineClub! The old team is still there, but jobs and other things have taken over, so I was brought in to try to get iC back on track and to again provide real value to our members.

Right now, one of the major roadblocks for imagineClub is it’s website. In it’s current state none of the board members are able to add news or change anything about the site since the input forms are broken. Paper submissions have to go through email and get added to the database through raw SQL, making the MSDN-AA subsection of the site the only “working” part that doesn’t require direct SQL manipulation. Naturally, all of this has led to a terribly outdated website, no new papers since 2008 and besides MSDN-AA no real service for our members.

I’m planning to change this through writing a completely new website that does what it’s supposed to do, but also is completely open source!
I decided to go with the Castle MonoRail framework on this one since I already did enough ASP.NET MVC Projects in the past. A positive side-effect of this should also be to work on the MonoRail documentation to get it updated once again.

The whole project is once again up on Bitbucket, currently more of a project skeleton than a real application. But I do plan to finish the site sometime in July. I’m also very happy to announce that Kristof, a young designer/artist I’ve had the pleasure working with during my last projects, has agreed to contribute a brand new site design. He promised me to finish it this week, so work on the site should start pretty soon.

Filed under imagineclub, personal

My beef with Ruby/Python

I just spent some time poking around Ruby after some poking around Python. And both times I find the typing concept awkward.
Not so much because there is none, but because there is one visible to the trained programmer, implicit but still there.

That being true for primitive types, for classes this makes a whole lot more sense, since we can use the concept of duck typing:

"when I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck."

Some patterns we came to use in static languages are just obsolete in dynamic settings. But the cost to me is that I also have no metadata present about the object I am currently dealing with. It could be anything, and I don’t know before I execute it.  
In C# I can simply hit object. and see all available methods/properties/events, allowing me to look at their documentation and so on. In Ruby, not even the smarter IDEs like RubyMine can do that for you. 

That in itself is no big deal if you are only working with your own classes and methods, where you know how they work or have a general understanding of how they work. Where I really need this metadata is when working with complex frameworks and libraries that expose tons of stuff through protected members from superclasses, that are just invisible to me. That said, to me the whole Ruby/Python experience was more of a running around and hunting method signatures rather than getting something done.

I guess that experience is normal and I am rather sure I’ll get the hang of it rather sooner than later. But coming from years of static typing dynamic languages just feel weird and especially their way of interacting with you as a programmer are different (no Intellisense being my #1 problem with all of them)

Filed under programmierung, personal

Pandora release 0.1

I finally decided it’s time to release Pandora. The current build is stable and meets all of my current requirements, so I feel the best way to advance Pandora is to dogfood it on another project.

Also, this gives me a bit of an opportunity to catch up on the documentation side of things and work out bugs that may be there.

Upcoming features

I still have a pretty interesting wish list (Generics, Factory Methods, AutoConfiguration), but those features are all rather non-trivial and I feel Pandora should stay a simple and minimalistic container right now.

Where to get

You can download the compiled Pandora release from Bitbucket or you can grab the source and compile it for yourself.

Compiling Pandora

Just run the build.bat script and NAnt (supplied within the repository) will fire up and compile everything into the build\ directory. By default the script will also compile and run the accompanying unit tests, leaving you with a Pandora.Test-Result.htm file you can then review if you please.

To compile without tests simply run “build compile”, and you’ll end up only with Pandora.dll/pdb and the common service locator library.

Using Pandora

If you didn’t run build compile, you end up with lots of stuff in your build directory:

Pandora result

If you plan on using Pandora you only need the following:

image 

If you are interested in the ServiceLocation.dll you can read about it here: Common Service Locator Adapter for Pandora

Twitter passes 2,147,483,647 tweets

I guess this screen will look really odd to non-programmers using the awesome Twitter client blu:

image

The text in the box says:

The value for a Int32 was too big or too small.
Any programmer knows this can only mean: Twitter just surpassed the boundaries of a 32 bit signed integer with their Tweed ids and has rendered a number of Twitter clients useless without an update.

Oh, and we all knew this is coming, thanks to http://www.twitpocalypse.com/

Filed under internet

WPF Sample, badly done

While trying out some WPF, I ended up downloading this code sample on Drag&Drop that contained the following piece  of code:

if (e.Source == MyCanvas)
{
}
else
{
    _isDown = true;
    _startPoint = e.GetPosition(MyCanvas);
    _originalElement = e.Source as UIElement;
    MyCanvas.CaptureMouse();
    e.Handled = true;
}

Come on? I’ve seen 6 year olds that knew the use of != and ==.

Please Microsoft: Documentation is as important as shipping code. At least review what crap is getting put out there. It just looks bad to say the least.

Filed under net, programmierung

Juggling generics

I’ve spent the last two days working on true generic registrations inside Pandora to enable scenarios like this:

[Fact]
public void CanResolveRealGenericAsSubdependency()
{
    store.Register(p =>
                       {
                           p.Service<IService>()
                               .Implementor<ClassDependingOnGenericClass>();
                           p.Generic(typeof (GenericClass<>))
                               .Implementor(typeof (GenericClass<>))
                               .ForAllTypes();
                       });
    Assert.DoesNotThrow(() => container.Resolve<IService>());
}

Well, if you look at the last changeset, I apparently succeeded for the above example, but decided to revert the changes and start over fresh. Generics are a difficult topic to tackle, and the current implementation feels too much like a hack to me.

But there are some things this failed experiment has taught me:

First: Generic types are just Types. And there are two subclasses of them:

  1. GenericTypeDefinition – This one represents the generic with no supplied type argument. Eg: typeof(Service<>)  Cannot be activated.
  2. GenericType – Represents the final type that can be treated like a normal type. Eg: typeof(Service<string>)

So, how do you tell those 3 apart (the third being a normal non-generic)?
Simple: Both generic types have the IsGenericType property set to true and GenericTypeDefinition also has IsGenericTypeDefinition set to true.

If you are faced with a GenericType, you can always extract the GenericTypeDefinition by calling GetGenericTypeDefinition() (very useful if you try to compare types in some scenarios).


The inverse can also be done (creating a GenericType from a definition) by calling MakeGenericType():

var type = typeof (string);
Type genericType = typeof (GenericClass<>).MakeGenericType(type);

And, in case you want to know what the argument type (T part) of a generic type is you can use the GetGenericArguments() method to find out:

[Fact]
public void ExtractGenericArgumentType()
{
    var type = typeof (SuperGeneric<string, int, long, float>);
    Type[] arguments = type.GetGenericArguments();
    foreach (var argument in arguments)
    {
        Console.WriteLine(argument.Name);
    }
}

The above produces the following:

String
Int32


Int64


Single

Ps: Try this stuff out for yourself! Reflection is real fun and surely helped me understand some things better. Don’t let yourself be thrown off by comments like “Reflection is too slow, never use it” etc.. Reflection and dynamic activation can make your life much easier if you know how to use it!

Filed under net, programmierung

My Photography business

Projects

dynamic css for .NET

Archives

more