#programmierung

Posts tagged programmierung

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

Read more →

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.

Read more →

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)

Read more →

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

Read more →

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.

Read more →

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!

Read more →

RFC: Is a supplied factory method useful for an IoC container?

I need your help.
Does it make sense to have something like this in a DI container?

[Fact]
public void CanSupplyFactoryMethod()
{
    store.Register(
        p => p.Service<IService>()
                 .Factory(s => 
                     {
                         Console.WriteLine("Creating type..");
                         if (SOME_STATIC_VAR == true)
                         {
                             return new ClassWithNoDependencies();
                         }
                         return new OtherClass();
                     })
        );
    var service = container.Resolve<IService>();
    Assert.IsType<ClassWithNoDependencies>(service);
}

The idea being, you can supply a function delegate (Func<IPandoraContainer, T>) to be executed when the service should be instantiated. This would make a rather interesting extensibility story, since I’d avoid having to build in all kinds of hard to find hooks to allow modification of the object creation.

Also, I’d like this delegate to be evaluated during runtime. This could enable me to resolve to another object if for example a network link is down etc.

Another obvious use for this would be to access classes that are present in the .NET BCL but can’t be instantiated and would otherwise be supplied to the container through .Instance like the HttpContext:

store.Register(
    p => p.Service<HttpContext>()
        .Factory(s => { return HttpContext.Current; }));

What do you think? Should this make it into Pandora? What do you want to see in a DI container? Please feel free to comment.

Read more →

Generic Registrations for Pandora

Yesterday I finished expanding the Pandora wiki a bit on how to configure the container and while doing so I made one discovery:

I never tested if Pandora can handle generic types!!

Wow, why didn’t I think about that. One of the most important scenarios fully untested. Thank god, simple generic registration already worked:

[Fact]
public void CanResolveSpecificGenericClass()
{
    store.Register(p => 
        p.Service<GenericClass<string>>()
        .Implementor<GenericClass<string>>());

    Assert.DoesNotThrow(() => container.Resolve<GenericClass<string>>()); }

The moment you define what generic type you are using, a generic class is just a regular class that can be used like all the others.

Still, it sucks having to specify one class explicitly 5 times if I want 5 to use it with 5 types. So I set out to support the following scenario:

[Fact(Skip = "Not implemented yet")]
public void CanRegisterAndResolveRealGenericRequests()
{
    store.Register(p => 
        p.Generic(typeof(GenericClass<>))
        .Implementor(typeof(GenericClass<>))
        .ForAllTypes());

    Assert.DoesNotThrow(() => {         var resolve = container.Resolve<GenericClass<string>>();     }); }

I want the container to just know the generic and then figure out if the generic registration can satisfy my requested service. Since this would obviously require Reflection in the resolving part of Pandora, I shelved that feature for a maybe more useful one that at least eases some of the generic pain:

store.Register(
    p => p.Generic(typeof (GenericClass<>))
             .Implementor(typeof (GenericClass<>))
             .OnlyForTypes(typeof (string), typeof (int)));

This way I can specify in one registration what types I want the generic to serve and the Fluent interface will create a distinct registration for each type in .OnlyForTypes[]. This way I don’t need any reflection code in the resolving part of Pandora.
And: It’s already implemented.

You can find the source to Pandora at the project website on Bitbucket.

Read more →

Injecting instances into Pandora

There are times when your services depend on an object you can’t construct yourself. One obvious example being the HttpContext in most ASP.NET applications.

So all DI containers have some way to inject an instance into the container to cover that. Pandora has joined them yesterday. It’s baked into the fluent interface and the ComponentStore:

Fluent:

var store = new ComponentStore();
            var instance = new ClassWithNoDependencies();
            store.Register(p => p.Service<IService>("test")
                                    .Instance(instance));

Conventional:

var store = new ComponentStore();
            var instance = new ClassWithNoDependencies();
            store.AddInstance<IService>(instance);

Read more →

Good ideas worth spreading: Guards

It’s amazing how much smarter you can become by simply looking at other people’s code. So, today I spent almost half the morning looking at different test frameworks from the TDD/BDD world looking for cool tricks I haven’t thought of (I examined MSpec, NBehave, NSpec and xUnit). One of those interesting little tricks (trivial at best, but valuable) is the following I found in xUnit’s Guard.cs:

Guard class, used for guard clauses and argument validation

Imagine the following method:

public bool Authenticate(string username, string password)
{
    return username == "daniel" && password == "tigraine";
}

Let’s say my specification for this method says: “input username and password can’t be null and should return a ArgumentNullException”. Reasonable, since we never trust input. So, usually I’d create guard clauses at the top of my method to protect me from said bad input:

public bool Authenticate(string username, string password)
{
    if (username == null)
        throw new ArgumentNullException(username);
    if (password == null)
        throw new ArgumentNullException(password);

    return username == "daniel" && password == "tigraine"; }

I always thought about this as rather readable and nice to work with, until I saw what xUnit did in Guard.cs, allowing me to shorten the above to a simple:

public bool Authenticate(string username, string password)
{
    Guard.ArgumentNotNull("username", username);
    Guard.ArgumentNotNull("password", password);

    return username == "daniel" && password == "tigraine"; }

I still believe this can be improved upon, maybe making it only one argument instead of two, but for now this is way better than what I used to write before.

Read more →