tag:blogger.com,1999:blog-16685366627908553942024-03-13T18:28:47.927+00:00Personal InertiaA collection of learnings and opinions.Tomashttp://www.blogger.com/profile/00258760670089542893noreply@blogger.comBlogger31125tag:blogger.com,1999:blog-1668536662790855394.post-88419272991226367852010-12-01T14:43:00.000+00:002010-12-01T14:43:48.921+00:00Inversion of Control with Dependency Injection<p>
Dependency Injection (DI) is a way of implementing the general Inversion of Control (IoC) -pattern. We do this to make our classes independent of each other. Combined with a preference for programming against interfaces instead of directly referencing the implementing classes we can achieve what is called <em>loose coupling</em>. The implementation details of one class have minimal impact on the innards classes using it. Additionaly using Dependency Injection makes your classes easier to unit-test, as they expose their dependencies externally and you can pass in mocks and stubs instead of full implementations.
</p>
<p>
It is easier to understand the pattern by looking at code-examples. We're creating code for a coffee-shop, and we're looking at the implemetation of a barista (the scrawny, wierd guy who makes the coffee). In my examples I will not show the interfaces, and just assume that all methods are defined in them.
</p>
<p>
Our barista has one method, where he uses his experience, a nice, big coffe-maker and some extras to concoct a potion:
</p>
<!-- code formatted by http://manoli.net/csharpformat/ -->
<div title="Barista01" class="csharpcode">
<pre class="alt"><span class="lnum"> 1: </span> <span class="kwrd">public</span> <span class="kwrd">class</span> Barista : IBarista {</pre>
<pre><span class="lnum"> 2: </span> <span class="kwrd">private</span> <span class="kwrd">const</span> <span class="kwrd">int</span> _yearsOfExperience = 5;</pre>
<pre class="alt"><span class="lnum"> 3: </span> <span class="kwrd">private</span> IEducation _major = <span class="kwrd">new</span> LiberalArtsMajor(); </pre>
<pre><span class="lnum"> 4: </span> </pre>
<pre class="alt"><span class="lnum"> 5: </span> <span class="kwrd">public</span> IBeverage MakeMeAn(IOrder order) {</pre>
<pre><span class="lnum"> 6: </span> var knowledge = <span class="kwrd">new</span> Experience(_yearsOfExperience, _major);</pre>
<pre class="alt"><span class="lnum"> 7: </span> var plan = knowledge.HowDoIMake(order);</pre>
<pre><span class="lnum"> 8: </span> </pre>
<pre class="alt"><span class="lnum"> 9: </span> var coffeeMaker = <span class="kwrd">new</span> BigAstra();</pre>
<pre><span class="lnum"> 10: </span> </pre>
<pre class="alt"><span class="lnum"> 11: </span> var beverage = coffeeMaker.MakeBeverageAccordingTo(plan);</pre>
<pre><span class="lnum"> 12: </span> </pre>
<pre class="alt"><span class="lnum"> 13: </span> var otherStuff = <span class="kwrd">new</span> AssortedCreamsAndSyrups();</pre>
<pre><span class="lnum"> 14: </span> </pre>
<pre class="alt"><span class="lnum"> 15: </span> var additives = knowledge.WhatShouldIAddAccordingTo(plan);</pre>
<pre><span class="lnum"> 16: </span> beverage.Add(additives);</pre>
<pre class="alt"><span class="lnum"> 17: </span> </pre>
<pre><span class="lnum"> 18: </span> <span class="kwrd">return</span> beverage;</pre>
<pre class="alt"><span class="lnum"> 19: </span> }</pre>
<pre><span class="lnum"> 20: </span> }</pre>
</div>
<p>
This piece of code is pretty readable, so it's not the worst code in the world. However, it is tighlty coupled to several other classes. Firstly it binds to the LiberalArtsMajor -class (which is apt, but still not a good thing) to set its private field <code>_major</code>. Inside the method itself it binds to the classes <code>Experience</code>, <code>BigAstra</code> and <code>AssortedCreamsAndSyrups</code>. All of these object have to be created for the Barista to make a lovely, warm, black and brown elixir of wakefullnes. Thus these direct couplings make our Barista <em>brittle</em>.
</p>
<p>
Experience tells us that our classes should be as small and simple as possible, and that they should have <em>one and only one</em> reason to change. It is not far-fetched to imagine the <code>BigAstra</code> class acquiring constructor parameters requiring the caller to provide a source of water, a source of power and a repository of coffee-beans (as this fits neatly with what it would need in real-life).
</p>
<!-- code formatted by http://manoli.net/csharpformat/ -->
<div title="BigAstra01" class="csharpcode">
<pre class="alt"><span class="lnum"> 1: </span> <span class="kwrd">public</span> <span class="kwrd">class</span> BigAstra : ICoffeeMaker {</pre>
<pre><span class="lnum"> 2: </span> <span class="kwrd">public</span> BigAstra(IWaterSource water, IPowerSourceAt220Hz power, ICoffeeRepository godlyBeans) {</pre>
<pre class="alt"><span class="lnum"> 3: </span> <span class="rem">// something very clever and difficult...</span></pre>
<pre><span class="lnum"> 4: </span> }</pre>
<pre class="alt"><span class="lnum"> 5: </span> <span class="rem">// the rest is left as an exercise for the reader</span></pre>
<pre><span class="lnum"> 6: </span> }</pre>
</div>
<p>
This change means that we will have to change the implementation of our barista because the implementation of the coffee-maker he is using changed. Furthermore, this change in how you make a <code>BigAstra</code> coffe-maker will cascade into all the places where the <code>BigAstra</code> is used. The same is true for all the other classes used by our Barista and in fact all the classes in the system. Good tools can certainly help us deal with this to a certain extent, but we quickly find ourselves in what I call combinatorial hell. Our barista has too many reasons to change - he is too tightly coupled to what he uses. How can we improve on this?
</p>
<p>
One solution to this problem I've seen used is to forgo object-orientation altogether and make the classes into a simple collection of static methods. By doing this we are binding ourselves tightly to one implementation, and refusing ourselves powerful object-oriented techniques like inheritance and polymorphism. In essence we are creating a Singleton implementation of the object we need. This technique transports us back into imperative programming in a fell swoop. Please, please do not do this! If you want to read more about why this is a bad idea I recomment Steve Yegge's "Singleton Considered Stupid" -post, and for a shorter view you can read <a href="http://stackoverflow.com/questions/205689/class-with-single-method-best-approach">Rasmussen's answer</a> on StackOverflow. Seriously, kittens die and hamsters get palsy when we do this.
</p>
<p>
How <em>can</em> we solve our combinatorial problem without throwing 30 years of object-oriented goodness on the pyre? By reversing the control through dependency injection, that's how (how's that for a tagline?). This is not a new technique, in fact you've already seen it in this post. When our <code>BigAstra</code> changed its constructor to expose what it needed (its dependencies) it enabled Dependency Injection. There are several flavours of Dependency Injection, but common to them all is that they expose what the class depends on to the outside, allowing its behaviour to be modified without changing its innards. This is also known as <em>the open / closed principle</em>, which says the class should be open to extension but closed to modification. By exposing its dependencies <code>BigAstra</code> is also explicitly signalling that while it needs these things to function it does not accept responsibility for creating them (which follows from the <em>single responsibility principle</em>).
</p>
<p>
Some ways to acheive DI are to expose the dependencies using a <em>Factory</em> -pattern, expose them through properties / public fields (<em>property injection</em>), require them as constructor parameters (<em>constructor injection</em>) or we could use a <em>Service Locator</em> to build them up runtime (I'm sure there are other ways that slip my mind right now).
</p>
<p>
I strongly prefer using <em>constructor injection</em>, and also exposing any dependencies that have to change run-time to <em>property injection</em>. When I set up the object-graph I prefer to use a <em>Service Locator</em> which lets me declare how to construct objects when needed and call this when required. In the best of all possible worlds this should be exactly once in every application's lifetime.
</p>
<p>
We are going to change our barista to support DI by pulling all of his dependencies out into the class and exposing them through the constructor. The coffee-maker and the condiments may need to be replaced in the barista's lifetime (though baristas tend to seem quite frail, and cooffee-machines always look strong and shiny), so we will expose these to <em>property injection</em> as well as <em>constructor injection</em>.
</p>
<!-- code formatted by http://manoli.net/csharpformat/ -->
<div title="Barista02" class="csharpcode">
<pre class="alt"><span class="lnum"> 1: </span><span class="kwrd">public</span> <span class="kwrd">class</span> Barista : IBarista {</pre>
<pre><span class="lnum"> 2: </span> <span class="kwrd">private</span> <span class="kwrd">const</span> <span class="kwrd">int</span> _yearsOfExperience = 5;</pre>
<pre class="alt"><span class="lnum"> 3: </span> <span class="kwrd">private</span> IEducation _major;</pre>
<pre><span class="lnum"> 4: </span> <span class="kwrd">private</span> IExperience _attitude;</pre>
<pre class="alt"><span class="lnum"> 5: </span> <span class="kwrd">public</span> ICoffeeMachine ShinyThing { get; set; } <span class="rem">// Property Injection</span></pre>
<pre><span class="lnum"> 6: </span> <span class="kwrd">public</span> ICondiments Flourish { get; set; } <span class="rem">// Property Injection</span></pre>
<pre class="alt"><span class="lnum"> 7: </span> </pre>
<pre><span class="lnum"> 8: </span> <span class="rem">// Constructor Injection</span></pre>
<pre class="alt"><span class="lnum"> 9: </span> <span class="kwrd">public</span> Barista(IEducation educatedAs, IExperience relevantExperience, </pre>
<pre><span class="lnum"> 10: </span> ICoffeeMachine toolOfTrade, ICondiments sugarAndSpice) {</pre>
<pre class="alt"><span class="lnum"> 11: </span> _major = educatedAs;</pre>
<pre><span class="lnum"> 12: </span> _attitude = relevantExperience;</pre>
<pre class="alt"><span class="lnum"> 13: </span> ShinyThing = toolOfTrade;</pre>
<pre><span class="lnum"> 14: </span> Flourish = sugarAndSpice;</pre>
<pre class="alt"><span class="lnum"> 15: </span> }</pre>
<pre><span class="lnum"> 16: </span> </pre>
<pre class="alt"><span class="lnum"> 17: </span> <span class="kwrd">public</span> IBeverage MakeMeAn(IOrder order) {</pre>
<pre><span class="lnum"> 18: </span> var plan = _attitude.HowDoIMake(order);</pre>
<pre class="alt"><span class="lnum"> 19: </span> var beverage = ShinyThing.MakeBeverageAccordingTo(plan);</pre>
<pre><span class="lnum"> 20: </span> var additives = Flourish.WhatShouldIAddAccordingTo(plan);</pre>
<pre class="alt"><span class="lnum"> 21: </span> beverage.Add(additives);</pre>
<pre><span class="lnum"> 22: </span> </pre>
<pre class="alt"><span class="lnum"> 23: </span> <span class="kwrd">return</span> beverage;</pre>
<pre><span class="lnum"> 24: </span> }</pre>
<pre class="alt"><span class="lnum"> 25: </span>}</pre>
</div>
<p>
It is now apparent what our barista depends upon by just looking at the constructor's parameters. Actually, there's something a bit off here. Is the barista really dependent upon his education? Isn't he merely using it as a part of his experience? When we explicitly expose our dependencies like this we'll often find such overlapping (and even conflicting) dependencies. This is a good opportunity for some cleanup, and we end up with a slightly cleaner barista as follows:
</p>
<!-- code formatted by http://manoli.net/csharpformat/ -->
<div title="Barista03" class="csharpcode">
<pre class="alt"><span class="lnum"> 1: </span><span class="kwrd">public</span> <span class="kwrd">class</span> Barista : IBarista {</pre>
<pre><span class="lnum"> 2: </span> <span class="kwrd">private</span> IExperience _attitude;</pre>
<pre class="alt"><span class="lnum"> 3: </span> <span class="kwrd">public</span> ICoffeeMachine ShinyThing { get; set; }</pre>
<pre><span class="lnum"> 4: </span> <span class="kwrd">public</span> ICondiments Flourish { get; set; }</pre>
<pre class="alt"><span class="lnum"> 5: </span> </pre>
<pre><span class="lnum"> 6: </span> <span class="kwrd">public</span> Barista(IExperience questionableExperience, ICoffeeMachine toolOfTrade,</pre>
<pre class="alt"><span class="lnum"> 7: </span> ICondiments sugarAndSpice) {</pre>
<pre><span class="lnum"> 8: </span> _attitude = questionableExperience;</pre>
<pre class="alt"><span class="lnum"> 9: </span> ShinyThing = toolOfTrade;</pre>
<pre><span class="lnum"> 10: </span> Flourish = sugarAndSpice;</pre>
<pre class="alt"><span class="lnum"> 11: </span> }</pre>
<pre><span class="lnum"> 12: </span> </pre>
<pre class="alt"><span class="lnum"> 13: </span> <span class="kwrd">public</span> IBeverage MakeMeAn(IOrder order) {</pre>
<pre><span class="lnum"> 14: </span> var plan = _attitude.HowDoIMake(order);</pre>
<pre class="alt"><span class="lnum"> 15: </span> var beverage = ShinyThing.MakeBeverageAccordingTo(plan);</pre>
<pre><span class="lnum"> 16: </span> var additives = Flourish.WhatShouldIAddAccordingTo(plan);</pre>
<pre class="alt"><span class="lnum"> 17: </span> beverage.Add(additives);</pre>
<pre><span class="lnum"> 18: </span> </pre>
<pre class="alt"><span class="lnum"> 19: </span> <span class="kwrd">return</span> beverage;</pre>
<pre><span class="lnum"> 20: </span> }</pre>
<pre class="alt"><span class="lnum"> 21: </span>} </pre>
</div>
<p>
We are happy with this - our barista is ready to have his dependencies set on creation, two of them can even be changed run-time (this is not thread-safe). The barista has no knowledge of how to set up a coffee-machine, how to get the condiments or how to make the experience he got. He doesn't know or care about you or your band, he just makes killer Cortados.
</p>
<p>
Haven't we just moved our problem, though? Mustn't whosoever calls the barista now need to know how to set up all the barista's dependencies? In our case the barista is used by a poor, underpaid Cashier. She used to look like this:
</p>
<!-- code formatted by http://manoli.net/csharpformat/ -->
<div title="Cashier01" class="csharpcode">
<pre class="alt"><span class="lnum"> 1: </span><span class="kwrd">public</span> <span class="kwrd">class</span> Cashier : ICashier {</pre>
<pre><span class="lnum"> 2: </span> <span class="kwrd">public</span> IBeverage GetDrinkForCustomer(ICustomer currentCustomer){</pre>
<pre class="alt"><span class="lnum"> 3: </span> var order = ConstructAnOrderFrom(currenCustomer.Demands);</pre>
<pre><span class="lnum"> 4: </span> </pre>
<pre class="alt"><span class="lnum"> 5: </span> var jerk = <span class="kwrd">new</span> Barista();</pre>
<pre><span class="lnum"> 6: </span> var drink = jerk.MakeMeAn(order);</pre>
<pre class="alt"><span class="lnum"> 7: </span> </pre>
<pre><span class="lnum"> 8: </span> <span class="kwrd">return</span> drink;</pre>
<pre class="alt"><span class="lnum"> 9: </span> }</pre>
<pre><span class="lnum"> 10: </span>}</pre>
</div>
<p>
After we've meddled with the Barista's constructor to appease our false gods of object-orientation she now has to look like this abomination?
</p>
<!-- code formatted by http://manoli.net/csharpformat/ -->
<div title="Cashier02" class="csharpcode">
<pre class="alt"><span class="lnum"> 1: </span><span class="kwrd">public</span> <span class="kwrd">class</span> Cashier : ICashier {</pre>
<pre><span class="lnum"> 2: </span> <span class="kwrd">private</span> <span class="kwrd">const</span> <span class="kwrd">int</span> _yearsOfExperience = 5;</pre>
<pre class="alt"><span class="lnum"> 3: </span> </pre>
<pre><span class="lnum"> 4: </span> <span class="kwrd">public</span> IBeverage GetDrinkForCustomer(ICustomer currentCustomer){</pre>
<pre class="alt"><span class="lnum"> 5: </span> var order = ConstructAnOrderFrom(currenCustomer.Demands);</pre>
<pre><span class="lnum"> 6: </span> </pre>
<pre class="alt"><span class="lnum"> 7: </span> var experience = <span class="kwrd">new</span> Experience(_yearsOfExperience, </pre>
<pre><span class="lnum"> 8: </span> <span class="kwrd">new</span> LiberalArtsMajor());</pre>
<pre class="alt"><span class="lnum"> 9: </span> </pre>
<pre><span class="lnum"> 10: </span> /probably has some municipality and plumber dependencies</pre>
<pre class="alt"><span class="lnum"> 11: </span> var waterTap = <span class="kwrd">new</span> WaterTap(...);</pre>
<pre><span class="lnum"> 12: </span> <span class="rem">//probably some municipality and electrician dependencies</span></pre>
<pre class="alt"><span class="lnum"> 13: </span> var powerSource = <span class="kwrd">new</span> PowerSource(...); </pre>
<pre><span class="lnum"> 14: </span> <span class="rem">//probably depenent on suppliers and service getting container from stock</span></pre>
<pre class="alt"><span class="lnum"> 15: </span> var coffeeBeans = <span class="kwrd">new</span> CoffeStore(...); </pre>
<pre><span class="lnum"> 16: </span> var coffeMakerForJerk = <span class="kwrd">new</span> BigAstra(waterTap,</pre>
<pre class="alt"><span class="lnum"> 17: </span> powerSource,</pre>
<pre><span class="lnum"> 18: </span> coffeeBeans);</pre>
<pre class="alt"><span class="lnum"> 19: </span> </pre>
<pre><span class="lnum"> 20: </span> <span class="rem">// dependent on suppliers I guess?</span></pre>
<pre class="alt"><span class="lnum"> 21: </span> var condiments = <span class="kwrd">new</span> AssortedCreamsAndSyrups(...); </pre>
<pre><span class="lnum"> 22: </span> </pre>
<pre class="alt"><span class="lnum"> 23: </span> var jerk = <span class="kwrd">new</span> Barista(experience, </pre>
<pre><span class="lnum"> 24: </span> coffeMakerForJerk,</pre>
<pre class="alt"><span class="lnum"> 25: </span> condiments);</pre>
<pre><span class="lnum"> 26: </span> var drink = jerk.MakeMeAn(order);</pre>
<pre class="alt"><span class="lnum"> 27: </span> </pre>
<pre><span class="lnum"> 28: </span> <span class="kwrd">return</span> drink;</pre>
<pre class="alt"><span class="lnum"> 29: </span> }</pre>
<pre><span class="lnum"> 30: </span>}</pre>
</div>
<p>
Ouch! The answer to this is obviously to push the dependencies of our cashier into her constructor, making the next level up the chain responsible for the instantiation. But this seems like a reductio-ad-absurdum, as we'll have to have a god-class on top setting up our entire object-graph. That can't be good, can it? Well, yes and no. What we want is a <em>Service Locator</em>, or in our case an IoC container. I like <a href="http://structuremap.net/structuremap/index.html">StructureMap</a>, as it's easy to work with and lets me define in a declarative way how it should work. It is one of the oldest of its kind in the .Net world, and time-proven.
</p>
<p>
To get StructureMap's help we have to tell it how to make the objects we are going to require. StructureMap has the concept of a <code>Registry</code>, which lets us declare what to do when asked for types in a declarative way, like "When asked for A you should return B". StructureMap is smart enough to inspect the constructors of the Bs it can return, and if the constructor requires something it knows how to make it puts that into it. This works well as long as you have defined all the types you need (the configuration is valid), and there are no circle-dependencies (ie. Foo requires a Bar, which requires a Foo). A registry for our coffee-shop might look like this:
</p>
<!-- code formatted by http://manoli.net/csharpformat/ -->
<div title="CoffeeShopRegistry01" class="csharpcode">
<pre class="alt"><span class="lnum"> 1: </span><span class="kwrd">public</span> CoffeeShopRegistry : Registry {</pre>
<pre><span class="lnum"> 2: </span> <span class="rem">//could be gotten from a config-file or somesuch</span></pre>
<pre class="alt"><span class="lnum"> 3: </span> <span class="kwrd">private</span> <span class="kwrd">const</span> <span class="kwrd">int</span> _yearsOfExperience = 5; </pre>
<pre><span class="lnum"> 4: </span> </pre>
<pre class="alt"><span class="lnum"> 5: </span> <span class="kwrd">public</span> CoffeShopRegistry() {</pre>
<pre><span class="lnum"> 6: </span> ForRequestedType<ICoffeeShop>()</pre>
<pre class="alt"><span class="lnum"> 7: </span> .TheDefaultIsConcreteType<CoffeShop>();</pre>
<pre><span class="lnum"> 8: </span> ForRequestedType<ICashier>()</pre>
<pre class="alt"><span class="lnum"> 9: </span> .TheDefaultIsConcreteType<Cashier>();</pre>
<pre><span class="lnum"> 10: </span> ForRequestedType<IBarista>()</pre>
<pre class="alt"><span class="lnum"> 11: </span> .TheDefaultIsConcreteType<Barista>();</pre>
<pre><span class="lnum"> 12: </span> </pre>
<pre class="alt"><span class="lnum"> 13: </span> ForRequestedType<IEducation>()</pre>
<pre><span class="lnum"> 14: </span> .TheDefaultIsConcreteType<LiberalArtsMajor>();</pre>
<pre class="alt"><span class="lnum"> 15: </span> ForRequestedType<ICoffeeMaker>()</pre>
<pre><span class="lnum"> 16: </span> .TheDefaultIsConcreteType<BigAstra>();</pre>
<pre class="alt"><span class="lnum"> 17: </span> ForRequestedType<IWaterSource>()</pre>
<pre><span class="lnum"> 18: </span> .TheDefaultIsConcreteType<WaterTap>();</pre>
<pre class="alt"><span class="lnum"> 19: </span> ForRequestedType<IPowerSourceAt220Hz>()</pre>
<pre><span class="lnum"> 20: </span> .TheDefaultIsConcreteType<MainsLine>();</pre>
<pre class="alt"><span class="lnum"> 21: </span> ForRequestedType<ICoffeeRepository>()</pre>
<pre><span class="lnum"> 22: </span> .TheDefaultIsConcreteType<SomeCoffeStorage>();</pre>
<pre class="alt"><span class="lnum"> 23: </span> </pre>
<pre><span class="lnum"> 24: </span> ForRequestedType<IExperience>()</pre>
<pre class="alt"><span class="lnum"> 25: </span> .TheDefault.Is</pre>
<pre><span class="lnum"> 26: </span> .ConstructedBy(context => </pre>
<pre class="alt"><span class="lnum"> 27: </span> <span class="kwrd">new</span> Experience(_yearsOfExperience, </pre>
<pre><span class="lnum"> 28: </span> context.GetInstance<IEducation>()));</pre>
<pre class="alt"><span class="lnum"> 29: </span> }</pre>
<pre><span class="lnum"> 30: </span>}</pre>
</div>
<p>
StructureMap won't initialize any objects until asked to, so defining the types our barista depend on after the barista itself is not a problem as long as the internal graph of StructureMap contains all it needs when it is called upon to provide an IBarista. StructureMap can also do other, cool things - like managing the lifetime of the objects, but that's a subject for another post.
</p>
<p>
We want to kick off StructureMap as one of the very first things in our application, and preferrably we'd only like to call upon it to construct something once (or as few times as possible). A possible <code>Main</code> would be:
</p>
<!-- code formatted by http://manoli.net/csharpformat/ -->
<div title="CoffeeShopProgram01" class="csharpcode">
<pre class="alt"><span class="lnum"> 1: </span><span class="kwrd">public</span> CoffeShopProgram {</pre>
<pre><span class="lnum"> 2: </span> <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> Main(<span class="kwrd">string</span>[] args) {</pre>
<pre class="alt"><span class="lnum"> 3: </span> ObjectFactory.Initialize(context => </pre>
<pre><span class="lnum"> 4: </span> context.AddRegistry(<span class="kwrd">new</span> CoffeeShopRegistry()));</pre>
<pre class="alt"><span class="lnum"> 5: </span> </pre>
<pre><span class="lnum"> 6: </span> <span class="rem">// Exception if we've missed anything</span></pre>
<pre class="alt"><span class="lnum"> 7: </span> ObjectFactory.AssertConfigurationIsValid();</pre>
<pre><span class="lnum"> 8: </span> </pre>
<pre class="alt"><span class="lnum"> 9: </span> <span class="rem">// depends on having a cashier and a barista - MAGIC!</span></pre>
<pre><span class="lnum"> 10: </span> var shop = ObjectFactory.GetInstance<ICoffeShop>(); </pre>
<pre class="alt"><span class="lnum"> 11: </span> </pre>
<pre><span class="lnum"> 12: </span> shop.Open();</pre>
<pre class="alt"><span class="lnum"> 13: </span> <span class="kwrd">while</span> (shop.IsOpen) {</pre>
<pre><span class="lnum"> 14: </span> var customer = ObjectFactory.GetInstance<ICustomer>();</pre>
<pre class="alt"><span class="lnum"> 15: </span> shop.ServeCustomer(customer);</pre>
<pre><span class="lnum"> 16: </span> }</pre>
<pre class="alt"><span class="lnum"> 17: </span> }</pre>
<pre><span class="lnum"> 18: </span>}</pre>
</div>
<p>
We're setting up ObjectFactory by adding the registry we made, in effect telling it what types it should know about, and how to return something when called upon. We haven't seen any ICoffeeShop implementors, but let's just say that is a class depending on an ICashier for its constructor. StructureMap knows how to make an ICashier - that's an instance of the Cashier -class. But Cashier depends on an IBarista! No problem, StructureMap knows that's a Barista instance, etc.
</p>
<p>
Implementing Dependency Injection loosens our classes' coupling against other classes, in effect delegating that to somewhere else. The actual calling of constructors is done by our IoC -container, freeing us up to simply declare that we want an IBarista, and assuming one will be created for us. So, instead of needing to know the intimate details of the implementing classes' constructors and dependencies to use an IBarista we just have to ask for one.
</p>
<p>
And, that's all kinds of cool!
</p>Tomashttp://www.blogger.com/profile/00258760670089542893noreply@blogger.com0tag:blogger.com,1999:blog-1668536662790855394.post-18746987698587739252010-05-20T14:55:00.001+01:002010-05-21T09:42:34.896+01:00Getting a WeekNumber from a Date in SSRS 2005 and 2008Many reports have to deal with week numbers. Often you'll have a DateTime to work with, either from a dataset or a parameter.<br />
<br />
So, how do we convert this lovely little DateTime to a WeekNumber? Search for that online and you'll get some solutions suggesting you change your query to give you a weeknumber, some solutions will do some fancy (and mostly erroneous) math to calculate the WeekNumber and yet others suggest you just don't do that.<br />
<br />
Getting the WeekNumber from your DataSet really is what you want, but then again you don't really want your DataSource to calculate the WeekNumber in all instances. The reason for that is related to the reason why DateTime does not have a WeekNumber:<br />
<br />
What, really, is a weeknumber? Why, silly, it's the number of the week the day is a part of. <br />
<br />
That's true, but how are the weeks numbered? Do they start with week 0 or week 1? If the week numbering starts at week 1 the last week should be week 53, or should it be week 52 (a week with more than 7 days)? How about if the year starts on a non-monday, what week are the first days in (they could be in the last week of the previous year, in the first (0th or 1st) of the new year, or perhaps even week-less). <br />
<br />
How about weeks, do they start on Mondays, Sundays, Saturdays, Fridays or some other day? That's kind of important when trying to calculate the first week of the year and counting the weeks until a date.<br />
<br />
Calendaring issues get complicated very fast, and the fun thing about them is that there are so many ways people keep track of their measured days. The year could start at wildly differing dates, it's silly to assume that the first of January is the first day of a year, and if it's not you'd better not be DateDiffing that modulus 7 to get a WeekNumber.<br />
<br />
I'll just happily ignore systems with weeks of more or less than 7 days. That would get hard.<br />
<br />
With all this in mind also consider that your datasource may not be using the same calendaring as your reporting system. If your report may be run in Tehran and your DataSource is a database of some sort in Tel-Aviv they may not be using the same calendar, but it'd be an admirable instance of Persian/Semittic cooperation.<br />
<br />
To get your week number you really should defer all the international issues to the people who've researched it and been paid to do a good job of it. Luckilly the .Net framework is produced by just such people, and I just love it when I can let it do the work for me.<br />
<br />
The .Net framework (in which you report is running) knows about the locale it's running in, and this information can be used to derive the WeekNumber without ever adding together two days.<br />
<br />
You just add this code snippet to your Code tab in your report properties:<br />
<br />
<pre>Function getWeekNumber(ByVal d As DateTime) As Integer
dim culture as System.Globalization.CultureInfo
culture = system.Globalization.CultureInfo.CurrentCulture
dim weekRule as System.Globalization.CalendarWeekRule
weekRule = culture.DateTimeFormat.CalendarWeekRule
dim firstDayOfWeek as System.DayOfWeek
firstDayOfWeek = culture.DateTimeFormat.FirstDayOfWeek
return culture.Calendar.GetWeekOfYear(d, weekRule, firstDayOfWeek)
End Function</pre><br />
Explanation:<br />
First we get the current culture the report is running under (this would be the culture of the locale of the server running SSRS in our case). From this culture you extract the rule for starting weeks relative to the year and which day of the week the weeks start on. These two values, together with the date you have are passed into the Calendar of the current culture to get the WeekNumber of the date in that context.<br />
<br />
It really is harder than it should be, but with this code (which you can just copy/paste) you make a new Calculated Field on your dataset with the following expression (I assume the Date field you want to convert to a WeekNumber is called Date in this instance):<br />
<br />
<pre>=Code.getWeekNumber(Fields!Date.Value)</pre><br />
And, as they say, Robert is your mother's brother.<br />
<br />
Addendum:<br />
<br />
If you don't want to go through adding the WeekNumber to your DataSet you could of course just use the above expression straight in your textboxen or the like.<br />
<br />
If you don't want the code you can inline it all as such (this is UGLY, don't do it!):<br />
<pre>=System.globalization.CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(Fields!Date.Value, System.globalization.CultureInfo.CurrentCulture.DateTimeFormat.CalendarWeekRule, System.globalization.CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek)</pre>Tomashttp://www.blogger.com/profile/00258760670089542893noreply@blogger.com0tag:blogger.com,1999:blog-1668536662790855394.post-36978743661824891312009-10-05T21:03:00.000+00:002009-10-05T21:03:57.094+00:00Simpler reference equality on mocksWhen mocking with <a href="http://code.google.com/p/moq/">MoQ</a> I find myself regularly setting up the <code>.Equals()</code> method on the mocks. It just makes for more readable code to be able to ask a collection whether it <code>.Contains()</code> the mock than writing out the iteration myself.<br />
<br />
But it does bloat my test-cases somewhat. Here's an example setting up a mock of a class with the equality set that returns <code>true</code> if it's compared to itself:<br />
<pre>[Test(Description = "Mock of equals on an instance succeeds")]
public void MockingEquals_SameInstance_AreEqual() {
var mocker = new Mock<SomeClass>();
mocker.Setup(x => x.Equals(mocker.Object)).Returns(true);
var mockedObject = mocker.Object;
Assert.That(mockedObject.Equals(mockedObject));
}
</pre><br />
That's fine if it's only in one test, but I don't like to repeat that all over my code. My first thought was to make a convenience method which set up the equality for me:<br />
<pre>public static Mock<T> ReferenceEquals<T>(Mock<T> mock) where T : class {
mock.Setup(m => m.Equals(mock.Object)).Returns(true);
return mock;
}
</pre><br />
Sticking this in some public place now allows me to set up my test from before like this:<br />
<br />
<pre>[Test(Description = "Mock of equals on an instance succeeds")]
public void MockingEquals_SameInstance_AreEqual() {
var mocker = new Mock<SomeClass>();
ReferenceEquals(mocker);
var mockedObject = mocker.Object;
Assert.That(mockedObject.Equals(mockedObject));
}
</pre><br />
That's certainly better. But, we can do better than that, can't we? Let's make it an <a href="http://msdn.microsoft.com/en-us/library/bb383977.aspx">extension-method</a>, for great success! To use this code the class containing the extension-method must be static.<br />
<br />
<pre>public static void HasReferenceEquality<T>(this Mock<T> mock) where T : class {
mock.Setup(m => m.Equals(mock.Object)).Returns(true);
}
</pre><br />
And with that our test has been transferred to the (in my opinion) much more readable:<br />
<pre>[Test(Description = "Mock of equals on an instance succeeds")]
public void MockingEquals_SameInstance_AreEqual() {
var mocker = new Mock<SomeClass>();
mocker.HasReferenceEquality();
var mockedObject = mocker.Object;
Assert.That(mockedObject.Equals(mockedObject));
}
</pre><br />
Great success!Tomashttp://www.blogger.com/profile/00258760670089542893noreply@blogger.com0tag:blogger.com,1999:blog-1668536662790855394.post-69548658912394412192009-09-25T08:00:00.003+00:002009-09-25T08:55:25.801+00:00MoQ with Collections, or equality woesStill working with the fine mocking-framework MoQ, I came across a somewhat surprising facet (and I don't like surprises).<br />I'm mocking out a class which should be added to a collection after a method-call, like so:<br /><pre><br />public class SomeClass{<br /> <br />}<br /><br />public class Container {<br /> private List<SomeClass>; classes = new List<SomeClass>();<br /> <br /> public IEnumerable<SomeClass> Classes {<br /> get {<br /> return classes;<br /> }<br /> }<br /> <br /> public void addSomeClass(SomeClass instance) {<br /> classes.Add(instance);<br /> }<br />}<br /><br />[Test]<br />public void ContainerContainsAddedClassAfterAdd() {<br /> var mockSomeClass = new Mock<SomeClass>(); <br /> mockSomeClass.Setup(c => c.Equals(mockSomeClass.Object)).Return(true);<br /> <br /> var Container = new Container();<br /> Container.addSomeClass(mockSomeClass.Object);<br /> <br /> Assert(Container.Classes.Contains(mockSomeClass.Object));<br />}<br /></pre><br />This works well, the mock is added to the <code>Container</code>'s collection and the setup of the <code>Equals</code> method on the mock makes sure the <code>IEnumerable.Contains()</code> return true.<br />However there's always some complication. The class I'm really mocking out is not as simple as our <code>SomeClass</code>. It's something like this:<br /><pre><br />public class SomeClassOverridingEquals{<br /> public virtual Equals(SomeClassOverridingEquals other) {<br /> return false; <br /> }<br /> <br /> public override Equals(object obj) {<br /> var other = obj as SomeClassOverridingEquals;<br /> <br /> if (other != null) return Equals(other); // calls the override<br /> return false;<br /> }<br />}<br /><br />[Test]<br />public void ContainerContainsAddedClassOverridingEqualsAfterAdd() {<br /> var mockSomeClass = new Mock<SomeClassOverridingEquals>(); <br /> mockSomeClass.Setup(c => c.Equals(mockSomeClass.Object)).Return(true);<br /> <br /> var Container = new Container();<br /> Container.addSomeClass(mockSomeClass.Object);<br /> <br /> Assert(Container.Classes.Contains(mockSomeClass.Object)); // fails<br />}<br /></pre><br />The class contains an override for the Equals method for its own specific type, and the <code>Setup</code> method for the mock does not seem to be able to mock out that specific method (only overriding the more general <code>Equals(object)</code>). Thus the test fails.<br /><br />I have so far found no way of working around this quite common pattern, other than rewriting the class not to use the overriding equals.<br /><br />I don't like that.<br /><br />Anyone have any ideas?Tomashttp://www.blogger.com/profile/00258760670089542893noreply@blogger.com0tag:blogger.com,1999:blog-1668536662790855394.post-3495712499562437142009-09-24T10:54:00.005+00:002009-09-24T11:24:21.846+00:00Mocking expectations on Property setters with MoQWhen mocking out your classes using the fabulous <a href="http://code.google.com/p/moq/">MoQ</a> mocking-framework you may sometimes need to mock out an expectation that a property on your mocked object should be set.<br /><br />It took me some time to figure out how to do this. The documentation on the <a href="http://code.google.com/p/moq/wiki/QuickStart">MoQ quickstart wiki</a> says to use the following pattern:<br /><pre class="prettyprint"><br />// expects an invocation to set the value to "foo"<br />mock.SetupSet(foo => foo.Name = "foo");<br /></pre><br /><br />Well, I tried this with an object:<br /><pre class="prettyprint"><br />public class SomeClass {<br /> public string Something { get; set; }<br />}<br /><br />[Test]<br />public void PropertySetupOnMock() {<br /> const string someString = "Should be set";<br /> var mocker = new Mock<SomeClass>();<br /><br /> mocker.SetupSet(x => x.Something = someString); //exception here<br /> mocker.Object.Something = someString;<br /> mocker.VerifySet(x => x.Something);<br />}<br /></pre><br />This only gave me an error on the line with the <code>SetupSet</code>:<br /><pre>System.ArgumentException: Invalid expectation on a non-overridable member.</pre><br />Well, that's strange. After some looking around it turns out that MoQ does its magic by extending the class that's being mocked. It cannot extend non-virtual properties, so this <code>Something</code> property cannot be extended and thus cannot be Setup.<br />What can be done about this? The easiest immediate solution would be to mark the property <code>virtual</code>, like so:<br /><pre class="prettyprint"><br />public class SomeClass {<br /> public <span style="color:red;font-weight:bold;">virtual</span> string Something { get; set; }<br />}</pre><br />But do we really want to decorate every property on the objects as virtual? Not really. A better solution is to push the property up to an interface and mock that interface instead, like so:<br /><pre class="prettyprint"><br />public interface IWithProperty {<br /> public string Something { get; set; }<br />}<br /><br />public class SomeClass : IWithProperty {<br /> public string Something { get; set; }<br />}<br /><br />[Test]<br />public void PropertySetupOnInterfaceMock() {<br /> const string someString = "Should be set";<br /> var mocker = new Mock<IWithProperty>();<br /><br /> mocker.SetupSet(x => x.Something = someString); //no exception here<br /> mocker.Object.Something = someString;<br /> mocker.VerifySet(x => x.Something);<br />}</pre><br />Thus allowing me to mock it out and test that the property setter was indeed called. Yay!<br />If anyone has any better ways of doing this I'd love to hear from you!Tomashttp://www.blogger.com/profile/00258760670089542893noreply@blogger.com2tag:blogger.com,1999:blog-1668536662790855394.post-51654819154416100212009-02-10T07:28:00.002+00:002009-02-10T07:30:06.304+00:00Listing the properties of an object<div xmlns='http://www.w3.org/1999/xhtml'>Sometimes you just want to print out the state of some reasonably rich object (for logging or GUI mock-up or whatever). This code gives you a PropertyGetter class with two easy-to-use static methods. listProperties returns a name: value string listing of the properties on the input object, for easy logging.<br /><br />If you want the object's properties as a list of properties you can get that as well.<br /><br />NB: This simple class does not recurse through complex objects, so you will only ever get the top-level of a property.<br /><br />Code:<br /><pre><br />using System.Collections.Generic;<br />using System.Reflection;<br />using System.Text;<br /><br />namespace Code_Examples {<br /> class PropertyGetter {<br /> public static string listProperties(object someObject) {<br /> StringBuilder sb = new StringBuilder();<br /><br /> List<pair> props = getProperties(someObject);<br /><br /> foreach (Pair prop in props) {<br /> sb.AppendLine(prop.Name + ": " + prop.Value);<br /> }<br /> return sb.ToString();<br /> }<br /><br /> public static List<pair> getProperties(object someObject) {<br /> List<pair> dic = new List<pair>();<br /><br /> PropertyInfo[] props = someObject.GetType().GetProperties();<br /> foreach (PropertyInfo prop in props) {<br /> Pair t = new Pair {<br /> Name = prop.Name,<br /> Value = prop.GetValue(someObject, null)<br /> };<br /> dic.Add(t);<br /> }<br /> return dic;<br /> }<br /> }<br /><br /> public class Pair {<br /> public string Name {<br /> get;<br /> set;<br /> }<br /> public object Value {<br /> get;<br /> set;<br /> }<br /> }<br />}</pre></div>Tomashttp://www.blogger.com/profile/00258760670089542893noreply@blogger.com0tag:blogger.com,1999:blog-1668536662790855394.post-1306226406392479112009-01-26T12:05:00.003+00:002009-01-26T12:07:13.857+00:00Logging snippets ready to go<div xmlns='http://www.w3.org/1999/xhtml'>My last post was some simple intro to how you can make your own snippets - here are some easy ones I made to make logging with log4net easier.<br /><br />This first one is one I use simply to get a logger with the name of the current class. I put this in most every class. Nothing fancy here, just type log and press tab to get a logger named log.<br /><pre class='xml' name='code'><br /><?xml version="1.0" encoding="utf-8"?><br /><CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet"><br /> <CodeSnippet Format="1.0.0"><br /> <Header><br /> <Title>Logging<br /> </Title><br /> <Author>Tomas Ekeli</Author><br /> <Description>Initializes a logger with the name of the current class</Description><br /> <HelpUrl /><br /> <SnippetTypes /><br /> <Keywords /><br /> <Shortcut>log</Shortcut><br /> </Header><br /> <Snippet><br /> <References><br /> <Reference><br /> <Assembly>log4net.dll</Assembly><br /> <Url /><br /> </Reference><br /> </References><br /> <Imports><br /> <Import><br /> <Namespace>log4net</Namespace><br /> </Import><br /> </Imports><br /> <Declarations /><br /> <Code Language="CSharp" Kind="" Delimiter="$"><![CDATA[protected static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); ]]></Code><br /> </Snippet><br /> </CodeSnippet><br /></CodeSnippets><br /></pre><br /><br />Now you've got a logger up and running you'll be doing a lot of calls to log.debug("somestring") and even more with formatting on that string. So here's a snippet for that:<br /><br /><pre name='code' class='xml'><br /><?xml version="1.0" encoding="utf-8"?><br /><CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet"><br /> <CodeSnippet Format="1.0.0"><br /> <Header><br /> <Title>logFormattedString</Title><br /> <Author>Tomas Ekeli</Author><br /> <Description>log formatted string</Description><br /> <HelpUrl></HelpUrl><br /> <SnippetTypes /><br /> <Keywords /><br /> <Shortcut>lsf</Shortcut><br /> </Header><br /> <Snippet><br /> <References><br /> <Reference><br /> <Assembly>log4net</Assembly><br /> <Url /><br /> </Reference><br /> </References><br /> <Imports><br /> <Import><br /> <Namespace>log4net</Namespace><br /> </Import><br /> </Imports><br /> <Declarations><br /> <Literal Editable="true"><br /> <ID>Level</ID><br /> <Type /><br /> <ToolTip>Log level</ToolTip><br /> <Default>Debug</Default><br /> <Function /><br /> </Literal><br /> <Literal Editable="true"><br /> <ID>Message</ID><br /> <Type /><br /> <ToolTip /><br /> <Default>field value: {0}</Default><br /> <Function /><br /> </Literal><br /> <div class="youtube-video"><object Editable="true"><br /> <ID>Field</ID><br /> <Type>Object</Type><br /> <ToolTip>The field to log</ToolTip><br /> <Default></Default><br /> <Function /><br /> </object></div><br /> </Declarations><br /> <Code Language="csharp" Kind="method body" Delimiter="$"><![CDATA[log.$Level$(string.Format("$Message$", $Field$));]]></Code><br /> </Snippet><br /> </CodeSnippet><br /></CodeSnippets><br /></pre><br /><br />Finally a very nice thing about logging is when you can push the context on a stack for inclusion. I use this all the time. This snippet can be used as a surrounding snippet as well (mark the text you want to surround in a context and right-click -> Surround-with<br /><br /><pre name='code' class='xml'><br /><?xml version="1.0" encoding="utf-8"?><br /><CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet"><br /> <CodeSnippet Format="1.0.0"><br /> <Header><br /> <Title>logFormattedString</Title><br /> <Author>Tomas Ekeli</Author><br /> <Description>log formatted string</Description><br /> <HelpUrl></HelpUrl><br /> <SnippetTypes /><br /> <Keywords /><br /> <Shortcut>lsf</Shortcut><br /> </Header><br /> <Snippet><br /> <References><br /> <Reference><br /> <Assembly>log4net</Assembly><br /> <Url /><br /> </Reference><br /> </References><br /> <Imports><br /> <Import><br /> <Namespace>log4net</Namespace><br /> </Import><br /> </Imports><br /> <Declarations><br /> <Literal Editable="true"><br /> <ID>Level</ID><br /> <Type /><br /> <ToolTip>Log level</ToolTip><br /> <Default>Debug</Default><br /> <Function /><br /> </Literal><br /> <Literal Editable="true"><br /> <ID>Message</ID><br /> <Type /><br /> <ToolTip /><br /> <Default>field value: {0}</Default><br /> <Function /><br /> </Literal><br /> <div class="youtube-video"><object Editable="true"><br /> <ID>Field</ID><br /> <Type>Object</Type><br /> <ToolTip>The field to log</ToolTip><br /> <Default></Default><br /> <Function /><br /> </object></div><br /> </Declarations><br /> <Code Language="csharp" Kind="method body" Delimiter="$"><![CDATA[log.$Level$(string.Format("$Message$", $Field$));]]></Code><br /> </Snippet><br /> </CodeSnippet><br /></CodeSnippets><br /></pre></div>Tomashttp://www.blogger.com/profile/00258760670089542893noreply@blogger.com0tag:blogger.com,1999:blog-1668536662790855394.post-57644775159467103922009-01-26T11:43:00.002+00:002009-01-26T11:55:23.012+00:00Code snippets<div xmlns='http://www.w3.org/1999/xhtml'>I like anything which makes my day easier. <a href='http://en.wikipedia.org/wiki/Snippet_%28programming%29' target='_blank'>Code snippets</a> are one of these things. You can <a href='http://msdn.microsoft.com/en-us/library/ms379562%28VS.80%29.aspx' target='_blank'>make your own</a> code-snippets by editing xml directly, using the <a href='http://msdn.microsoft.com/en-us/library/ms171418%28VS.80%29.aspx'>code snippet schema reference</a>, or you could use a tool. <a href='http://www.codeplex.com/SnippetEditor' target='_blank'>Snippet Editor</a> is just such a tool. With it making and editing snippets is dead simple!<br /><br />One thing I've noticed with it, though, is that you cannot make a "<a href='http://msdn.microsoft.com/en-us/library/ms171442.aspx'>SurroundsWith</a>" snippet in this tool. To do this you have to edit the xml yourself. It's easy when you know how - just add the following to the header section of your snippet definition:<br /><br /><pre class='xml' name='code'><br /><SnippetTypes><br /> <SnippetType>Expansion</SnippetType><br /> <SnippetType>SurroundsWith</SnippetType><br /></SnippetTypes><br /></pre><br /><br />And in your snippet section you add <em>selected</em> and <em>end</em> fields where you would insert the code you want to surround with the snippet (the following example would surround the selected code with curly braces).<br /><br /><pre name="code" class="xml"><br /><Code Language="csharp" Kind="method body" Delimiter="$"><br /> <![CDATA[{ $selected$ $end$}]]><br /></Code><br /></pre><br /></div>Tomashttp://www.blogger.com/profile/00258760670089542893noreply@blogger.com0tag:blogger.com,1999:blog-1668536662790855394.post-20084817530655060322008-10-14T21:20:00.001+00:002008-10-14T21:20:36.831+00:00Developing ASP pages with Firefox<div xmlns='http://www.w3.org/1999/xhtml'>I prefer<a href='http://www.mozilla.com/en-US/firefox/' target='_blank'> Firefox 3</a> to <a href='http://www.microsoft.com/windows/products/winfamily/ie/default.mspx' target='_blank'>IE7</a> when developing (understatement of the week), particularly because it has <a href='http://getfirebug.com/' target='_blank'>Firebug</a> and <a href='http://developer.yahoo.com/yslow/' target='_blank'>YSlow</a> (an add-on for an add-on, would that be a quasi-add-on?). IE7 has the <a href='http://www.microsoft.com/downloads/details.aspx?familyid=e59c3964-672d-4511-bb3e-2d5e1db91038&displaylang=en' target='_blank'>developer toolbar</a>, but it's not as good (in my experience).<br/>Naturally I have Firefox as my default browser, so when I launch ASP pages in the development server from Visual Studio they open in Firefox. And it is soooo slooooow. It's ridiculous, it's like being on my old <a href='http://en.wikipedia.org/wiki/Modem#V.34_.2F_28.8k_and_33.8k' target='_blank'>28.8 modem</a> back in the mid-90s.<br/>How can this be? Firefox isn't slower than IE7. That cannot be, no <a href='http://ejohn.org/blog/javascript-performance-rundown/' target='_blank'>benchmarks</a> point in that direction (OK, those are just javascript, but you get the gist of it).<br/>It turns out the problem is with Firefox 3 and the development server (<a href='http://en.wikipedia.org/wiki/Cassini_Web_Server' target='_blank'>Cassini</a>). I haven't dug deeply into it, just observed the problem, found <a href='http://anydiem.com/2008/06/26/firefox-3-slow-in-aspnet-development-server/' target='_blank'>the fix</a> and applied it.<br/><ul><li>enter <font face='Courier New'>about:config</font> into your <a href='http://blog.mozilla.com/blog/2008/04/21/a-little-something-awesome-about-firefox-3/' target='_blank'>awesome-bar</a></li><li>filter to <a href='http://kb.mozillazine.org/Network.dns.disableIPv6' target='_blank'><font face='Courier New'>network.dns.disableIPv6</font></a></li><li>set the value to <font face='Courier New'>true</font></li></ul><font face='sans-serif'>I've no time to check it right now, but disabling IPv6 seems a bit ham-handed. It should be possible to just include <font face='Courier New'>localhost </font>in the </font><a href='http://kb.mozillazine.org/Network.dns.ipv4OnlyDomains' target='_blank'><font face='Courier New'>network.dns.ipv4OnlyDomains</font></a> preference. This is a string containing a comma-separated list of domains.<br/><br/>Technorati Tags: <a rel='tag' href='http://technorati.com/tag/Cassini' class='performancingtags'>Cassini</a>, <a rel='tag' href='http://technorati.com/tag/firefox' class='performancingtags'>firefox</a>, <a rel='tag' href='http://technorati.com/tag/slow' class='performancingtags'>slow</a>, <a rel='tag' href='http://technorati.com/tag/development' class='performancingtags'>development</a>, <a rel='tag' href='http://technorati.com/tag/yslow' class='performancingtags'>yslow</a>, <a rel='tag' href='http://technorati.com/tag/firebug' class='performancingtags'>firebug</a>, <a rel='tag' href='http://technorati.com/tag/about:config' class='performancingtags'>about:config</a>, <a rel='tag' href='http://technorati.com/tag/clientside' class='performancingtags'>clientside</a>, <a rel='tag' href='http://technorati.com/tag/ipv6' class='performancingtags'>ipv6</a></div>Tomashttp://www.blogger.com/profile/00258760670089542893noreply@blogger.com0tag:blogger.com,1999:blog-1668536662790855394.post-61744853061994726622008-10-07T07:56:00.001+00:002008-10-07T08:11:30.492+00:00C# Compiler Could Not Be Created<div xmlns='http://www.w3.org/1999/xhtml'>I was having memory-problems on my dev machine (2 Gigs don't go far these days), and after a few resets I was getting an exception whenever I tried to open a solution containing a C# project in VS2005. It told me the C# compiler could not be loaded, and I should reinstall VS.<br/>Eh? No way. That's an entire day, getting it back to where I want it.<br/>So I open the Help -> About to see if I can get some info about what's wrong. There I'm hit by a Package Load Failure, coming from <a href='http://www.jetbrains.com/resharper/' target='_blank'>ReSharper</a> (we loves it). This looks like something.<br/>A quick <a href='http://google.com' target='_blank'>google </a>for this, and I find <a href='http://blogs.msdn.com/astebner/default.aspx' target='_blank'>Aaron Stebner</a> has a possible <a href='http://blogs.msdn.com/astebner/archive/2005/09/06/461804.aspx' target='_blank'>solution</a>. The tool he references in that post didn't find any problems, but running through the steps to re-build the native libraries did.<br/>So these are the steps in case that blog ever disappears:<br/><ol><li><font size='2' face='Verdana'>Open a cmd prompt</font></li><li><font size='2' face='Verdana'>Run <strong>del %windir%\Assembly\NativeImages_v2.0.XXXXX_32\Microsoft.VisualStu#</strong><br />(where XXXXX is the build number of the .NET Framework 2.0 that<br />you have installed - you can figure that out by looking at the name of<br />the folder at %windir%\Microsoft.NET\Framework\v2.0.XXXXX)</font></li><li><font face='Verdana'><font size='2'>Run <strong>%windir%\Microsoft.NET\Framework\v2.0.XXXXX\ngen.exe update /queue</strong></font></font></li></ol>That's done it. A restart of VS and we're up and running again. Now I just have to convince my boss I should get 2 more gigs of RAM.<br/></div>Tomashttp://www.blogger.com/profile/00258760670089542893noreply@blogger.com0tag:blogger.com,1999:blog-1668536662790855394.post-36552156486211841092008-10-01T10:16:00.005+00:002008-10-01T10:37:04.474+00:00Personal Information Numbers<div xmlns='http://www.w3.org/1999/xhtml'>A quick set of Regexes to check for Personal Information Numbers from the nordic countries. <br/>I use these to check the format only, no fancy calculation of checksums etc.<br/><br/><ul><li>Norwegian: DDMMYYXXXXX<br/><pre>\b[0-4]\d[014]\d{3}\d{5} </pre></li><br /><li>Swedish: YYMMDDCXXXX (C == '-' || '+')<br /><pre>\b\d{2}[01]\d[0-3]\d[-\+]\d{4}</pre></li><br /><li>Danish: DDMMYY-XXXX<br /><pre>\b[0-3]\d[01]\d{3}-\d{4}</pre> </li><br /><li>Finnish: DDMMYYCZZZQ (C == '-'||'+'||'A' ; Q == [01234536789ABCDEFHJKLMNPRSTUVWXY])<br /><pre>\b[0-3]\d[01]\d{3}[-\+A]\d{3}[0-9A-FHJ-NPR-Y]</pre></li><br /><li>Icelandic: DDMMYY-XXXC (C == 0 || 9)<br /><pre>\b[0-3]\d[01]\d{3}-\d{3}[09]</pre></li></ul></div>Tomashttp://www.blogger.com/profile/00258760670089542893noreply@blogger.com0tag:blogger.com,1999:blog-1668536662790855394.post-74524254492276545132008-09-30T18:02:00.002+00:002008-09-30T18:05:38.746+00:00Podcasts<div xmlns='http://www.w3.org/1999/xhtml'>I listen to a lot of podcasts. What can I say, I bore easily. When I have to do something that's not social and takes more than a few minutes I often pop the <a href='http://www.sennheiser.com/sennheiser/home_en.nsf/product.html?ReadForm&path=private_headphones_classic-line_cxseries&product=500830' target='_blank'>earbuds</a> in and start listening. My player, <a href='http://en.wikipedia.org/wiki/Zen_v' target='_blank'>the Zen V 2Gb</a>, is far too small to contain any music, and podcasts are a great way of getting some intelectual topping in the daily drudgery. <br/><br/>I thought I'd post the list of podcasts I enjoy regularly:<br/><ul><li><a href='http://www.cbc.ca/podcasting/includes/quirksaio.xml' target='_blank'>CBC Radio Quirks and Quarks</a><br/>A great show about the stories breaking in science. Definitely a Canadian slant, and they've been running theme shows about Canada's carbon-footprint and such lately (which doesn't interest me that much), but still one of the greatest.</li><br/><li><a href='http://www.leoville.tv/podcasts/floss.xml' target='_blank'>FLOSS Weekly</a><br/>This show died for a while, but they're back with a vengeance. In-depth interviews with important people in the open-source world. Could it be better?</li><br/><li><a href='http://www.bbc.co.uk/radio4/history/inourtime/' target='_blank'>In Our Time With Melvyn Bragg</a><br/>Melvyn is a delightfully pretentious British chap interviewing academics on interesting themes. Always interesting, and a really eclectic selection of themes.</li><a href='http://feeds.conversationsnetwork.org/channel/itc' target='_blank'><br/></a><li><a href='http://feeds.conversationsnetwork.org/channel/itc' target='_blank'>IT Conversations</a><br/>One of the really early podcasts, this is excellent quality. I listen to the entire feed, which I think syndicates a lot of other feeds. Great content from biomedical/genetics to philosophy and CTO-grade stuff. There's always something here you haven't heard about.</li><a href='http://www.aracnet.com/%7Eeseligma/mm/MM_RSS_feed.xml' target='_blank'><br/></a><li><a href='http://www.aracnet.com/%7Eeseligma/mm/MM_RSS_feed.xml' target='_blank'>Math Mutation</a><br/>This is a new one for me. Erik Seligman talks very briefly (3-5 minutes) about some interesting topics from the world of Math and Numbers. Good content!</li><br/><li><a href='http://www.abc.net.au/newsradio/podcast/STARSTUFF.xml' target='_blank'>StarStuff with Stuart Gary</a><br/>I'm a sucker for the starry nights, and this recent discovery seems right up my alley. I've only listened to two yet, but I think it's a keeper!</li><br/><li><a href='http://feeds.feedburner.com/javaposse' target='_blank'>The Java Posse</a><br/>My favourite! The posse have weekly commentaries on the tech-world with a heavy java-slant. All the members are world-class developers with strong opinions and the arguments to back them up. It makes my day every time I see a new one pop into my playlist.</li><a href='http://www.theskepticsguide.org/rss.xml' target='_blank'><br/></a><li><a href='http://www.theskepticsguide.org/rss.xml' target='_blank'>The Skeptic's Guide to the Universe</a><br/>Tackling the idiocy and numb-thinking out there head on, the Skeptical Rogues are not afraid to delve deeply into any theme they find. It's so refreshing to see that there are intelligent people out there, not just nuts.</li><br/><li><a href='http://www.twis.org/audio/podcast.rss' target='_blank'>This Week in Science - The Kickass Science Podcast</a><br/>Another recent discovery on my part. I'm not sure if this is a keeper yet. The themes seem interesting, but they're just not catching me yet. I'll keep them around for a few weeks, and see if they're worth it.</li><br/><li><a href='http://leoville.tv/podcasts/twit.xml' target='_blank'>This Week in Tech</a><br/>I've a feeling this is the big one. Leo Laporte is a great host, and he gets a lot of interesting punters. Whenever they talk about something I know they always manage to get it dead-wrong though, so I take their opinions with a grain of salt. Still, the show is a gem.</li></ul>Definitely a Tech/Science slant, eh? Any others I should know about, or comments are much appreciated :)<br/></div>Tomashttp://www.blogger.com/profile/00258760670089542893noreply@blogger.com1tag:blogger.com,1999:blog-1668536662790855394.post-2404287167304888662008-09-25T20:45:00.011+00:002008-09-26T14:08:12.622+00:00CountDistinct - How About SumDistinct - Or Just AggregateDistinct?<p>Making a report in Microsoft SQL Server 2005 Reporting Services today I needed to sum up several levels in a table. However, the numbers where available only at an intermediate aggregated level, so I needed to sum up only the distinct sublevel-items. Got that? Maybe it's easier if I show an example:</p><br /><p>Let's concoct an example here. I'm extracting data in the following groups: Firm, ProductType, Product, Account, Item. Say I'm summing up one measure, BalanceAmount, on products, but my dataset returns other measures on the lowest level, Item.</p><br /><p>Here's an example DataSet</p><br /><style type="text/css">.nobrtable br { display: none }</style><br /><div class="nobrtable"><br /><table style="width: 811px; height: 567px;" border="1" cellpadding="10"><br /><tbody><tr><br /> <th width="5em">Firm</th><br /> <th width="10em">ProductType</th><br /> <th width="8em">Product</th><br /> <th width="8em">Account</th><br /> <th width="5em">Item</th><br /> <th width="10em">BalanceAmount</th><br /> <th width="8em">ItemMeasure</th><br /> </tr><br /> <tr><br /> <td>Acme</td><br /> <td>Explosive</td><br /> <td>Nitroglyserin</td><br /> <td>C-001</td><br /> <td>Bottle</td><br /> <td>$200</td><br /> <td>$2.14</td><br /> </tr><br /> <tr><br /> <td>Acme</td><br /> <td>Explosive</td><br /> <td>Nitroglyserin</td><br /> <td>C-001</td><br /> <td>Mug</td><br /> <td>$200</td><br /> <td>$4.87</td><br /> </tr><br /> <tr><br /> <td>Acme</td><br /> <td>Explosive</td><br /> <td>TNT</td><br /> <td>C-001</td><br /> <td>Stick</td><br /> <td>$200</td><br /> <td>$0.79</td><br /> </tr><br /> <tr><br /> <td>Acme</td><br /> <td>Explosive</td><br /> <td>Plastique</td><br /> <td>C-001</td><br /> <td>Wad</td><br /> <td>$200</td><br /> <td>$7.64</td><br /> </tr><br /> <tr><br /> <td>Acme</td><br /> <td>Prop</td><br /> <td>Fake rock</td><br /> <td>C-001</td><br /> <td>Crate</td><br /> <td>$200</td><br /> <td>$4.55</td><br /> </tr><br /> <tr><br /> <td>Acme</td><br /> <td>Explosive</td><br /> <td>TNT</td><br /> <td>C-124</td><br /> <td>Stick</td><br /> <td>$89</td><br /> <td>$0.79</td><br /> </tr><br /> <tr><br /> <td>Acme</td><br /> <td>Explosive</td><br /> <td>TNT</td><br /> <td>C-124</td><br /> <td>Half-stick</td><br /> <td>$89</td><br /> <td>$0.40</td><br /> </tr><br /> <tr><br /> <td>Acme</td><br /> <td>Explosive</td><br /> <td>Nitroglyserin</td><br /> <td>C-089</td><br /> <td>Stick</td><br /> <td>$40</td><br /> <td>$0.79</td><br /> </tr><br /></tbody></table><br /></div><br /><p>In the report I need to show this as a drill-down table, with the measures down on the lowest level (Item) summed up on every level, and the aggregated measure (BalanceAmount) summed up on every level where it makes sense.</p><br /><p>The problem is that if you use the common SUM function the report would sum up all BalanceAmounts on the Account level resulting in a BalanceAmount of $1000 for Account C-001, not $200 which is the correct value (that would be $200, Einstein).</p><br /><p>What you really need is something like CountDistinct, but just for Sum. In fact, this is a specific case of a more general problem where you need to conduct some aggregation on some scope. How do I do something like that?</p><br /><p>It's not really hard. What I need is some way to make just the first instance of a value in whatever scope needed be the counting one. To get this I enter the<br />following into the Code tab of you Report properties:</p><br /><br /><pre> Dim scopes As System.Collections.Hashtable<br /> Function getDistinct(ByVal checkMe As Object, ByVal scope As String) As Boolean<br /> Dim firstTimeSeen As Boolean<br /><br /> If (scopes Is Nothing) Then<br /> scopes = New System.Collections.Hashtable<br /> End If<br /><br /> If (Not scopes.Contains(scope)) Then<br /> scopes.Add(scope, New System.Collections.ArrayList)<br /> End If<br /><br /> If (Not CType(scopes(scope), System.Collections.ArrayList).Contains(checkMe)) Then<br /> firstTimeSeen = True<br /> CType(scopes(scope), System.Collections.ArrayList).Add(checkMe)<br /> Else<br /> firstTimeSeen = False<br /> End If<br /><br /> Return firstTimeSeen<br /> End Function</pre><br /><p>The usage pattern to get SumDistinct in this case is:</p><br /><pre>=SUM(IIF(Code.getDistinct(Fields!account.Value, "scopeId"), Fields!BalanceAmount.Value, 0))</pre><br /><p>The "scopeId" string identifies the current scope, so it will change from group to group. E.g. in the Firm group you'd enter "firm", in the ProductType group you'd enter "prodType", etc.</p><br /><p>So what am I doing here? We're remembering the values of the checkMe parameter in the context of the scope, and returning True in only the first instance. Thus we can just sum the first of every checkMe value. You could use this to do your own CountDistinct by entering the following expression (but this would be a bit roundabout for that use-case):</p><br /><pre>=COUNT(IIF(Code.getDistinct(Fields!account.Value, "scopeId"), Fields!BalanceAmount.Value, 0))</pre><br /><p> I hope you get some use out of this. This kind of code is easy to crank out, but even easier to just copy-paste.</p>Tomashttp://www.blogger.com/profile/00258760670089542893noreply@blogger.com1tag:blogger.com,1999:blog-1668536662790855394.post-64871244457296662242008-08-10T22:20:00.000+01:002008-08-10T22:21:46.889+01:00The 21 Laws of Computer Programming<div xmlns='http://www.w3.org/1999/xhtml'>These had me in stitches. Particularly number 19: "If you automate a mess, you get an automated mess". So true, and taken with another favourite saying of mine, "If it's worth doing once it's worth automating" we've got a true mess on our hands :)<br/><br/><a href='http://www.devtopics.com/21-laws-of-computer-programming/' target='_blank'>Read 21 laws of computer programming</a><br/></div>Tomashttp://www.blogger.com/profile/00258760670089542893noreply@blogger.com0tag:blogger.com,1999:blog-1668536662790855394.post-87301497457935600382008-08-10T18:41:00.000+01:002008-08-10T18:42:27.580+01:00The Great Office War<div xmlns='http://www.w3.org/1999/xhtml'><strong>Epic:</strong><br/><br/><br/><div class='youtube-video'><object height='225' width='400'> <param value='true' name='allowfullscreen'> </param> <param value='always' name='allowscriptaccess'> </param> <param value='http://www.vimeo.com/moogaloop.swf?clip_id=1193942&server=www.vimeo.com&show_title=1&show_byline=1&show_portrait=0&color=&fullscreen=1' name='movie'> </param> <embed height='225' width='400' allowscriptaccess='always' allowfullscreen='true' type='application/x-shockwave-flash' src='http://www.vimeo.com/moogaloop.swf?clip_id=1193942&server=www.vimeo.com&show_title=1&show_byline=1&show_portrait=0&color=&fullscreen=1'> </embed> </object></div><br/><a href='http://www.vimeo.com/1193942?pg=embed&sec=1193942'>The Great Office War</a> from <a href='http://www.vimeo.com/user545209?pg=embed&sec=1193942'>Runawaybox</a> on <a href='http://vimeo.com?pg=embed&sec=1193942'>Vimeo</a>.</div>Tomashttp://www.blogger.com/profile/00258760670089542893noreply@blogger.com0tag:blogger.com,1999:blog-1668536662790855394.post-17228860937342130282007-08-02T14:05:00.001+00:002007-08-02T14:20:57.952+00:00DropDownList with a blank item on top<div xmlns="http://www.w3.org/1999/xhtml">The DropDownList (DDL) is a nice little databindable control in ASP.Net. The easiest way to use it is to databind it to some value from your database and let the user select.<br /><br />The problem with straight on databinding is that the first item in the DDL will be the first item in the databound collection (naturally), thus making choosing that item "a little too easy" and "a little too hard". When the user wants to select the top item you might be in for problems, as that selection won't fire off a <i>SelectedIndexChanged</i> -event, which is what you'd normally listen for.<br /><br />There are ways around this - I've seen several suggestions. None of these are even starters in my opinion:<br /><ul><li>Don't handle changes in the DDL, read from it on some other event (typically a button)</li><ul><li>This makes it very hard to create responsive UIs, as your user will always have to keep clicking buttons</li></ul><li>Set whatever you want to happen on changes in the DDL as if the first choice was already chosen (pre-choose for the user)</li><ul><li>Badness - especially in a stateless media like the web - your user may never correct your initial (possibly wrong) assumption<br /></li></ul><li>Add an empty record in the databound object (typically your database)</li><ul><li>Perhaps the worst idea I've seen. The database should <i>not</i> contain filler like this. It's a bit better if you're working with some transient object - but still it's a <i>hack</i>. We don't like hacks.</li></ul></ul>The way to fix this problem is really not very hard. What you want is an empty item on the top of the list that the user will not expect to work, with a known value you can check for in your <i>SelectedIndexChanged</i> handler.<br /><br />To do this add a <i>ListItem</i> to the DDL in the page/control's definition with your sentinel value and an empty string as the Text property. Normally this item would disappear on databinding, but wait: set the <i>AppendDataBoundItems</i> property on the DDL to <i>True</i>, and your empty initial value will survive!<br /><br />Two things to beware: Make sure you check for your sentinel value in the handler, and remember to clear all but the initial item of the DDL's ItemListCollection if you're databinding that control again later (unless you want to keep appending).<br /><br /><strong>Here's your illustrative code:</strong><br />A standard DDL:<br /><pre><br /> <asp:DropDownList id="ddBasic" runat="server" autopostback="True"><br /> <!-- Selecting the top item will not fire an event (it will be pre-selected) --><br /> </asp:DropDownList><br /></pre><br /><br />A DDL with the empty top-item:<br /><pre><br /> <asp:DropDownList id="ddWithEmptyTop" runat="server" autopostback="True" appenddatabounditems="True"><br /> <asp:ListItem value="-1" text=""> </asp:ListItem><br /> </asp:DropDownList><br /></pre><br /><br />Technorati Tags: <a rel="tag" href="http://technorati.com/tag/asp.net" class="performancingtags">asp.net</a>, <a rel="tag" href="http://technorati.com/tag/dropdownlist" class="performancingtags">dropdownlist</a>, <a rel="tag" href="http://technorati.com/tag/databinding" class="performancingtags">databinding</a>, <a rel="tag" href="http://technorati.com/tag/ui" class="performancingtags">ui</a></div>Tomashttp://www.blogger.com/profile/00258760670089542893noreply@blogger.com15tag:blogger.com,1999:blog-1668536662790855394.post-67297720971541270942007-07-26T20:05:00.001+00:002007-07-27T07:41:53.848+00:00Glotton - word glutton<a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://photos-b.ak.facebook.com/photos-ak-sctm/v103/18/106/869530320/n869530320_882753_8491.jpg"><img style="margin: 0pt 0pt 10px 10px; float: right; cursor: pointer; width: 320px;" src="http://photos-b.ak.facebook.com/photos-ak-sctm/v103/18/106/869530320/n869530320_882753_8491.jpg" alt="" border="0" /></a><br /><div xmlns="http://www.w3.org/1999/xhtml">I've launched a new small open-source application, Glotton. Get it at http://code.google.com/p/glotton/<br /><br />It's my summer holiday, and I've been playing some word-games (in particular <a href="http://en.wikipedia.org/wiki/Scrabble">Scrabble</a> and <a href="http://www.popcap.com/gamepopup.php?theGame=bookworm">BookWorm</a>). I'm not particularly good at these, but I find them fun.<br /><br />What I can do, however, is to get a computer to help me. So I did - I created Glotton.<br /><br />It is free, open-source and available for whatever use anyone may put it to. The easiest way to use it is to download the <a href="http://glotton.googlecode.com/files/glotton_v1.zip">pre-packaged zip</a>, extract this and run the jar-file.<br /><br />Send me a note if you like it or find any bugs.<br /><br /><br /><p class="poweredbyperformancing">Powered by <a href="http://scribefire.com/">ScribeFire</a>.</p></div>Tomashttp://www.blogger.com/profile/00258760670089542893noreply@blogger.com0tag:blogger.com,1999:blog-1668536662790855394.post-33360369208797961222007-06-27T14:15:00.001+00:002007-06-27T14:15:11.505+00:00Error ... error ... whence cometh thou?<div xmlns='http://www.w3.org/1999/xhtml'>I'm working on a page that will allow our users to view a table in a database in ASP.Net. To do this I am writing a <a href='http://msdn2.microsoft.com/en-us/library/system.web.ui.usercontrol.aspx'>UserControl </a>where I am connecting to the database through a <a href='http://msdn2.microsoft.com/en-us/library/dz12d98w%28vs.80%29.aspx'><u>SqlDataSource</u></a>, and I bind a <a href='http://msdn2.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview%28VS.80%29.aspx'>GridView </a>on the UserControl to this datasource. If you are unfamiliar with <a href='http://msdn2.microsoft.com/en-us/library/ms752347.aspx#what_is_data_binding'>databinding</a> this simply means that I hook the presenting controller (the GridView) up to an object that can provide it with data. This automagically populates the presenter with the data from the source. But, as with all automagical things can, and do, go horribly wrong.<br/><br/><i>Small digression:</i> I'm from the <a href='http://en.wikipedia.org/wiki/Java_%28programming_language%29'>Java </a>plains, but I've recently set up shop in the .Net woods where I mostly hang around in the soppy marshes of <a href='http://en.wikipedia.org/wiki/ASP.NET'>ASP</a>, the glossy banks of <a href='http://www.microsoft.com/sql/technologies/reporting/overview.mspx'>MSSQL-RS</a> and more recently the crags of <a href='http://en.wikipedia.org/wiki/Ado.net'>ADO</a>. Being quite new in these parts I get to do a lot of really stupid things, and I'm building an appreciation of each land's pros and cons. One of my gripes with the marshes of ASP is the incessant focus on doing things <a href='http://en.wikipedia.org/wiki/Declarative_programming'>declaratively</a> as the first-choice. Sure, it's great if what you want is static, but I don't want static content!<br/><br/>Why this rant? Declarativity just bit me in the rump, like a particularly nasty <a href='http://en.wikipedia.org/wiki/Donkey'>ass</a>.<br/><br/>So, I was binding my GridView to the SQLDataSource declaratively, like a good <a href='http://www.youtube.com/watch?v=aqTaqVi9J8k'>ASP-ape</a>. Everything was working as expected until I started testing the page with non-standard inputs. The datasource is setup with the data it needs to connect to the database, and an initial select statement to get at the data you want. If any of this is incorrect the entire page explodes in a messy way. Red goo all over the walls.<br/><br/>My test-case was simply setting up the datasource with an incorrect login. This caused an SQL-exception when the SQLDataSource tried to perform the initial Select (as one would expect). Now, .Net does not have checked exceptions (expect a post on this later), so being from the Java-land I am always a bit surprised and worried to see exceptions being thrown willy-nilly run-time.<br/><br/>Well, this exception I should be able to deal with. It is a real problem, but the application should be able to handle such problems gracefully. I just had to find some place to catch this exception, and handle it.<br/><br/>There are several places you can handle an error in ASP.Net:<br/><ul><li><a href='http://msdn2.microsoft.com/en-us/library/2027ewzw.aspx'>global.asax</a> (where you can handle application-level errors), overriding one of the following methods<br/></li><ul><li>Gobal_Error</li><li>Application_Error</li></ul><li>Page_Error (where you can handle errors on a page-level)</li></ul>In addition to this you can define a page to send the user to in case of an error, so the plebs don't have to see the ugly innards of your app. All of these solutions are good, but not for my use-case where I actually wanted to handle the exception, should it occur. These solutions let you do things like <i>log</i> and <i>redirect</i> on errors, but offer little in the way of actually handling the problem.<br/><br/>Yes, on a page I could have used the Page_Error, the problem is that I am building a UserControl, which is <i>part</i> of a page, but not the page itself. And, a UserControl has no onError event to catch, and on Error method to override. In effect the UserControl blew up, killing all bystanding controls and page-elements.<br/><br/>Digging in to where the error originated I saw that it was spawned when the controls on the page where coming to life, in the <i>preRender</i> -stage of the lifecycle. This tells me that I must place some code to handle this before that stage of the lifecycle to avoid this error. In the purely declarative mannar I would declare a handler for some SqlDataSource error event, but that component does not have one. So I am relegated to provoking the error myself, and handling it correctly.<br/><br/>This is not really all that hard, once you've gotten to this level (the realisation that I had to do it this way took much longer than the coding of the fix). What you're forced to do is to <b>not bind the GridView to the SQLDataSource declaratively</b>. Read that again. To handle the error you're forced to step out of the declarative world and do the binding yourself. Now, this isn't <i>hard</i>, but it suddenly seems as if the declarative way of doing things is second-rate and sunshine-days-only. I can live with that, but what I really don't like is how every example focuses on declarative implementation, when it's the less powerful and (to me) less natural way of doing things. Sigh.<br/><br/>Oh, well, on to the fix. Just remove the <i>DataSourceID="someDataSource"</i> element from your GridView decalaration, and add something like this to you Page.Load handler:<br/><pre><br/>Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load<br/> theGridView.DataSource = someDataSource<br/> Try<br/> GridView1.DataBind()<br/> btnSave.Visible = True<br/> lblError.Visible = False<br/> Catch exc As SqlException<br/> lblError.Visible = True<br/> btnSave.Visible = False<br/> lblError.Text = "Could not load table: " & exc.Message<br/> End Try<br/>End Sub<br/></pre><br/>This will let the UserControl come up, even if the datasource experienced an error. Much better, but I'm left feeling it's dumb that I have to do it this way.<br/><br/><br/><br/>Technorati Tags: <a rel='tag' href='http://technorati.com/tag/asp' class='performancingtags'>asp</a>, <a rel='tag' href='http://technorati.com/tag/usercontrol' class='performancingtags'>usercontrol</a>, <a rel='tag' href='http://technorati.com/tag/exceptions' class='performancingtags'>exceptions</a>, <a rel='tag' href='http://technorati.com/tag/declarative' class='performancingtags'>declarative</a>, <a rel='tag' href='http://technorati.com/tag/gridview' class='performancingtags'>gridview</a>, <a rel='tag' href='http://technorati.com/tag/datasource' class='performancingtags'>datasource</a>, <a rel='tag' href='http://technorati.com/tag/error' class='performancingtags'>error</a></div>Tomashttp://www.blogger.com/profile/00258760670089542893noreply@blogger.com0tag:blogger.com,1999:blog-1668536662790855394.post-46245517491503608732007-06-26T14:39:00.001+00:002007-06-26T14:39:27.971+00:00Let's Talk About It...<div xmlns='http://www.w3.org/1999/xhtml'>"Let's talk about it..." that's the name of the latest version of <a href='http://jade.cselt.it/'>Jade</a>, that was released yesterday! That's right, a new version of everyone's favourite <a href='http://www.fipa.org/repository/standardspecs.html'>FIPA</a>-compliant <a href='http://java.sun.com/'>Java</a>-based multi-agent framework has a new release. And this is just, what, a month or two since the first book about the framework was released (<a href='http://www.amazon.com/Developing-Multi-Agent-Systems-Wiley-Technology/dp/0470057475'>Developing Multi-Agent Systems with JADE</a>).<br></br><br></br>Exciting times!<br></br><br></br>So, what's new in this release? Any breaking changes? Let's have a look at the <a href='http://jade.cselt.it/news-art.php?id=40'>press-release</a> (I haven't had time to try it out yet. I'll do that at my first opportunity and post my impressions).<br></br><br></br><ul><li>A whole new communication mechanism: Publish/Subscribe!</li><ul><li>A whole new mechanism where agents can simply register a topic they are interested in, and every message that is broadcast with that topic will be sent to them. This sounds like a good idea to me, uncoupling the broadcaster and subscribers. It is only applicable to general broadcasts, though, and I wonder how they implement "closed" lists.<br></br></li><li>Sounds like they are implemented by making a proxy-AID representing the topic, to ensure compatibility. I wonder if this is a good thing, is breaking the agent-AID binding really something you want to do?<br></br></li></ul><li>A "<i>completely restructured version of the Web Service Integration Gateway</i>"</li><ul><li>Web app (can be deployed to app servers, like <a href='http://tomcat.apache.org/'>Apache Tomcat</a>)!</li><li>Web-services are derived from the actions in the ontologies registered to the Directory Facilitator.</li><li><a href='http://www.w3.org/TR/wsdl'>WSDL</a> document generated for each agent service exposed (how did they do it before?)</li><li>I haven't used the WSID earlier, so I can't really add any thoughts to this, check out the guide <a href='http://jade.tilab.com/doc/tutorials/WSIG_Guide.pdf'>here</a>.<br></br></li></ul><li>Improved detection of main container using <a href='http://www.javaworld.com/javaworld/jw-10-1999/jw-10-step.html'>UDP Multicast</a> packets<br></br></li><ul><li>Excellent, this makes it easier to set up multi-platform environments!</li></ul><li>A reflector, finally allowing us to use the <a href='http://java.sun.com/j2se/1.4.2/docs/guide/collections/reference.html'>Java Collections Framework</a> when working with ontologies</li><ul><li>Excellent stuff, now just port the entire thing to <a href='http://java.sun.com/j2se/1.5.0/'>Java 1.5</a> to give us <a href='http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html'>generics</a>!<br></br></li></ul></ul>All in all some exciting stuff! Let's hope this one doesn't break anything, eh? I've not touched it yet, and so far on the mailing-lists there's one user who's had problems with the multicasting on his machine, but it looks like a he found a workaround (detect-main option set to false).<br></br><br></br>Let the bugsearch ensue :-)<br></br><a rel='tag' href='http://technorati.com/tag/udp%20multicast%20' class='performancingtags'> </a><br></br></div>Tomashttp://www.blogger.com/profile/00258760670089542893noreply@blogger.com0tag:blogger.com,1999:blog-1668536662790855394.post-60684250305721799052007-06-26T12:21:00.001+00:002007-06-26T14:36:44.518+00:00If you met God on your commute<div xmlns='http://www.w3.org/1999/xhtml'>Here's a nice little story...<br></br><br></br><a href='http://www.fullmoon.nu/articles/art.php?id=tal'>Talking to God...</a><br></br><br></br><br></br></div>Tomashttp://www.blogger.com/profile/00258760670089542893noreply@blogger.com0tag:blogger.com,1999:blog-1668536662790855394.post-33902788648711761712007-06-25T14:26:00.001+00:002007-06-25T20:36:52.126+00:00Which tables do I have available?<div xmlns='http://www.w3.org/1999/xhtml'>Sometimes when you're connecting to a database you'd like to know what tables are available. I'm no DBA, so it took me a while to find out how to do that.<br></br><br></br>In this case I've just gotten the connection stuff from the user, and I run this code when the user presses a "Connect" button to connect to the database the user has specified and populate a drop-down box with the user-tables in that database. The real meat here is the <i>selectTables</i> string in there, which gets the user-tables from the <i>sysobjects</i> table. Once I get this I bind the drop-down box (<i>ddTableSelect</i>) to these to show all the tables.<br></br><pre>Protected Sub btnConnect_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnConnect.Click<br></br> Dim builder As New System.Data.SqlClient.SqlConnectionStringBuilder<br></br><br></br> builder.DataSource = txtDatasource.Text<br></br> builder.InitialCatalog = txtInitialCatalog.Text<br></br> builder.UserID = txtUserID.Text<br></br> builder.Password = txtPassword.Text<br></br><br></br> Dim selectTables As String = "SELECT sysobjects.name, sysobjects.id " _<br></br> & "FROM sysobjects " _<br></br> & "WHERE sysobjects.type = 'U'"<br></br><br></br> Dim source As SqlDataSource = New SqlDataSource(builder.ConnectionString, selectTables)<br></br><br></br> ddTableSelect.DataSource = source<br></br> ddTableSelect.DataTextField = "name"<br></br> Try<br></br> ddTableSelect.DataBind()<br></br> connectedState()<br></br> Catch ex As Exception<br></br> lblError.Text = "Could not connect: " & ex.Message<br></br> errorState()<br></br> End Try<br></br>End Sub<br></br></pre>To be perfectly clear, as VB can be a real pain on the eyes (and SQL is <i>soooo </i>much better, right!?) this is the SQL that gets the tables:<br></br><br></br><pre>SELECT sysobjects.name, sysobjects.id <br></br> FROM sysobjects<br></br> WHERE sysobjects.type = 'U'<br></br></pre><br></br><br></br>Yes, I know, catching all exceptions in the end there is <i>bad</i>, but this is me feeling my way, ok?<br></br><br></br></div>Tomashttp://www.blogger.com/profile/00258760670089542893noreply@blogger.com2tag:blogger.com,1999:blog-1668536662790855394.post-85908872612426479022007-06-25T09:06:00.001+00:002007-06-25T14:35:25.689+00:00There's a bug in the compiler<div xmlns="http://www.w3.org/1999/xhtml">Or so they say.<br /><br /><br /><br />I was making a new <a href="http://msdn2.microsoft.com/en-US/library/aa479564.aspx">page-control</a> today for my app. Using <a href="http://en.wikipedia.org/wiki/Visual_studio">VS</a> this can be done by adding a new controller to the page through menus, or you can just do what I do. I copy an old one, and paste it in, changing the Class names and removing most of the code. This bypasses all the tedious setup, and all the bits that have to be there for the framework I'm working on are already there. Goodness.<br /><br /><br /><br />Happily I build, expecting no errors, but I get a nasty message. "<b>Custom_Report is ambiguous in the namespace 'ASP'</b>". Not good. Custom_Report was the name of the control I copied, so I go back and double-check that I changed the class-name. Yes, yes I did.<br /><br /><br /><br />That's strange. Well, a quick search online told me that this might be a result of a known bug in the compiler. The fix was easy, you have to compile your app in non-batch -mode. How do you do this, I hear you asking. Simple: enter the <i>compilation</i> section of your <i>web.config</i>, and set <i>batch="false"</i>, as so:<br /><br /><pre><compilation debug="true" batch="false"><br /><br />...<br /><br /></compilation><br /><br /></pre><br />This has been your small-problem, small-fix.<br /></div>Tomashttp://www.blogger.com/profile/00258760670089542893noreply@blogger.com1tag:blogger.com,1999:blog-1668536662790855394.post-10261660437700515182007-03-11T21:49:00.000+00:002007-03-11T23:47:40.237+00:00Don't Store That Password (Client)<span style="font-weight: bold;">Passwords, passwords, passwords. They're all around us, and they're a pain to remember. How do we cope? There are hundreds, possibly thousands of places where I use passwords. I have trouble remembering one password, those numbers would be ludicrous to even try. How do you cope? You make up a strategy, or you get tooled up.</span><br /><br />Traditionally we say there’s three main ways of asserting an identity. Something you are, something you know and something you have. Identification consists of proving one or more of these to a given level of confidence. A low level of security could include simply asking someone who they are. If you want a higher degree of certainty you could ask for more than one element of identification.<br /><br />The most common way of doing this is by asking for two of the three elements above, who you are and something you know (username and password). When you want higher degrees of security you can add the third element (something you have, like a <a href="http://en.wikipedia.org/wiki/Key_%28lock%29">key</a>) or you can go deeper into each of the elements. Going deeper into who you are is the direction of <a href="http://en.wikipedia.org/wiki/Biometrics">biometrics</a>. Delving into something you know would include asking questions you’d know but none others would, and not asking the same question every time. Gaining security on the “have” element would include making very sure the item really does belong to the person who’s trying to identify himself and making equally sure that thing really is that thing. <a href="http://en.wikipedia.org/wiki/One-time_pad">One-time pads</a> and secure transfers are key here.<br /><br />This all seems nice, and it is. You know what else it is? It’s a hassle. So far most services contend themselves with a two-pronged check (username/<a href="http://wolfram.org/writing/howto/password.html">password</a>), so you need to give that to get access. This is fine for one or two services, but we’re all consumers of hundreds or thousands of services. To add to this you really should keep different passwords for each service, to ensure your security. If you use the same password for every service and one of your providers are hacked (or *gasp* are <a href="http://en.wikipedia.org/wiki/Phishing">bad-guys</a> and sell or use your password) all your information is compromised. So we make up passwords.<br /><br />To protect ourselves from brute-force hacks we make up complicated passwords with at least 8 characters and combinations of upper-case (A-Z), lower-case (a-z) and numbers (0-9). The really paranoid among us throw in a couple of non-obvious ones too (β, æ, °, etc). And you have to remember all of this. It’s all a bit hairy.<br /><br />We need some way to solve this problem. Luckily there are solutions. What you need is a strategy to keep track of your passwords. There are three obvious strategies (well, more, but this isn’t a book, it’s just a post).<br /><br />1. Make up a (hopefully strong) password and stick with it for every service.<br />This is a bad idea in general, but it’ll do if you don’t care about the information you put into the services. This means your information is wide-open to any hacker after they’ve somehow gotten hold of your password.<br /><br />2. Make up a few (hopefully strong) passwords and use different ones for different services.<br />This is what most people do. You have one password for your work-things, one for throwaway-accounts you don’t care about, one for your personal stuff, etc. Although this is a step up from number 1 it’s still not what I’d call security. Two things to think of here are:<br />a. Are you sure your other passwords aren’t stored somewhere you can get to from one of the identities? If you store a list of passwords on one account any hacker who’s gotten into that has access to all your other information.<br />b. Are you sure you won’t try all possibilities if you can’t gain access on one service? If a hacker has control over some service you use and changes the password he could probably get a few good passwords out of you when you try all the possibilities. I know I would try every option before giving up.<br /><br />3. Make up some personal rule for your passwords. This is a good way of coping with the problem as long as you keep this rule secret. Say your rule is “<span style="font-style: italic;">The first three letters are from the beginning of my pet’s name, after that every even character spells out my post-code backwards, every odd character spells out the name of the service. Every other letter is upper-case.</span>” This would make my youtube –account’s password “<span style="font-style: italic;">eRo1E6b1U5tUoY</span>”. Kind of cool, and quite hard to break as long as you don’t tell anyone what your rule is.<br /><br />So we have some inkling on how we could do this, but it’s still a hassle (well, number one isn’t really). So we’d like some tools to help us. Number one doesn’t really need a tool, perhaps a paper-note if you’re a goldfish. Number two could also be covered by a piece of paper, but with tools we can improve on this. This is where personal password-keepers live. You make up a set of passwords and keep them somewhere safe (like in a database). Safe as in – won’t disappear, and hopefully safe as in won’t get to others. However if your password-database is compromised you’ll effectively have shot your guard in the rear. You’re wide open. And, let’s be fair here, you won’t use all those random passwords anyway. It’ll be too much of a pain and you’ll go back to your old scheme of one or a few passwords.<br /><br />The third option though is still fascinating. If it’s an easy rule you can use quickly you won’t need a tool. However, with a tool you can make a really complex rule that nobody would ever guess! The world would be your oyster! A <a href="http://mathworld.wolfram.com/TrapdoorOne-WayFunction.html">one-way-function</a> would be ideal for just this purpose! <a href="http://en.wikipedia.org/wiki/Cryptographic_hash_function">Hashing-functions</a> are popular for this purpose.<br /><br />Hashing for dummies:<br /><span style="font-style: italic;">For our purposes</span> hashing-functions are a black box you put some number into, and some other number comes out. Every time you put the same number in the result is the same, and crucially, there’s no easy way to go the other way! If someone had your result (the hash) and the hashing-function (the black box) they still have no easier way of finding the number you put into the black-box than trying every possible number. <span style="font-style: italic;">(This is all slightly false, but it’ll do for now)</span>.<br /><br />So, what you do is get yourself a hash-function and enter the name of the service into that function. This way the hasher can make you a service-password that’s unique for that service, has no apparent connection to you and will be generated every time you put the name of the service into the function. Oh, you say, but<span style="font-style: italic;"> everybody else using the same hashing-function would get the same password!</span> And, you’re right, I’m proud of you. You’ve obviously been paying attention. What you do is you “salt” the hash. Salting the hash means you don’t just enter the name of the service but also enter something else. This “something else” would be your master-password.<br /><br />Let’s assume you’re able to remember one password and what you called the service – this will always give you the password for the service. As long as nobody else has the same password and name for the service they’d not have the same service-password. Even if they did any hacker with control of the service wouldn’t know what the password-name-combination was, he’d only see the service-password.<br /><br />This is great, the problem is solved. Well, the problem was already solved with strategy 3 back up there, but people are too lazy to think of strategies. Now, how can lazy people get to use this marvelous technology? We have to give people hash-functions! Luckily these are available. Popular ones are <a href="http://en.wikipedia.org/wiki/MD4">MD4</a>, <a href="http://en.wikipedia.org/wiki/MD5">MD5 </a>and <a href="http://en.wikipedia.org/wiki/SHA">SHA-1</a> (I know, they’re broken but they’ll do for our purposes). You can try them out at <a href="http://pajhome.org.uk/crypt/md5/">http://pajhome.org.uk/crypt/md5/</a><br /><br />If you use <a href="http://getfirefox.com">Firefox </a>(and I think you should) you can install a bookmarklet called <a href="http://labs.zarate.org/passwd_new/">SuperGenPass </a>This makes the entire operation automated, and it fills in the generated password based on the name of the server you’re trying to connect to and your master-password. It’s so easy you’d never think it was safe, but it really is!<br /><br />This has been a short essay about how the client can get some security from hacked or malicious services. As a developer I see the problem from the other side as well. I’ll delve into that next…Tomashttp://www.blogger.com/profile/00258760670089542893noreply@blogger.com0tag:blogger.com,1999:blog-1668536662790855394.post-62694463556698912312007-03-11T13:00:00.000+00:002007-03-11T13:03:06.272+00:00Been SickI've been out sick for a while, sorry. That's why there's been no new posts for a few days. Just thought I'd tell all my millions of readers.<br /><br />The good news is that I'm well again, and I've got a few posts coming out soon.<br /><br />For now, take a look at the interesting things I've put on the sidebar. Not my content, but all of that is stuff I found interesting and worth a little time.Tomashttp://www.blogger.com/profile/00258760670089542893noreply@blogger.com0tag:blogger.com,1999:blog-1668536662790855394.post-43777016750516919142007-03-05T09:05:00.000+00:002007-03-05T15:06:26.862+00:00Tell Me When Something HappensEvents are a staple of object-oriented design. They are a way decoupling objects and that is almost always a good thing. A short synopsis of the idea:<br /><br />You have some object (Foo) and you want to be able to know when something happens to Foo. Say Foo is a button and you want to know when it's been pressed in order to do something. You could just code Foo to do the thing you wanted, but then you'd have to code every button for everything you want to do. You could tell Foo to execute some method (possibly in some other Object) when it was pressed, but then you'd lock Foo and the method together. You'd have problems if someone later changed that method also, as they may not know that Foo calls it. The solution to this is to let Foo have events, and code the actual behavior in some other Object or method which handles that event.<br /><br />In Java this is done through a pattern called the event-listener. I call it that, anyway. What you do is you let Foo implement a method that takes the listener (addListener(FooListener l)).<br /><br /><pre>public class Foo {<br /> private List(FooListener) listeners = new LinkedList(FooListener);<br /><br /> public void addListener(FooListener l) {<br /> listeners.add(l);<br /> }<br />}<br /></pre><br /><br />FooListener is an interface that includes one method to handle the event when the listener gets it. You can put whatever you want into the FooEvent, depending on what kind of event your particular implementation raises. Often you only need to send an event, that's enough information in itself.<br /><br /><pre>public interface FooListener {<br />public void handleEvent(FooEvent e);<br />}<br /></pre><br /><br />In Foo you decide when you want to send an event to the listeners, and you do it something like this:<br /><pre>private void doSomething() {<br />for(FooListener l : listeners) {<br /> l.handleEvent(new FooEvent("Something"));<br />}<br />}<br /></pre><br /><br />This works, but it's a bit verbose, and worse - it's up to the developers to decide how to do this and if they will.<br /><br />In .Net classes have events themselves. The engineers over at MS have taken this pattern and hardcoded it into their platform. So, what you do here is slightly different:<br /><br />Events and listeners are what I know from Java, but in VB.NET they're called Events and Handlers. I can live with that, it parses. What's really cool though is that like properties (which I really like) the events are language-features. So, you've got some kind of standard to follow, it's not something you have to explore on your own or make up on the spot.<br /><br />When you add a button in VB.NET your app already knows about the events that can generate (they are part of the specification of the Button class). This makes it easy for the code-generator to give you the boilerplate for a handler. In fact, that's what it does when you double-click a button in the form-designer. Coding has never been so easy, and I like that.<br /><br />The problem with this easy code-generation (for me, and this may be a problem with me) is that it doesn't teach you how to do this yourself. My case was that I wanted to add a handler to a control that only exists after a certain set of actions have been taken in my program.<br /><br />When I add a handler to a button which exists the code is easy. Let's say I have a button called btnFoo on my form. To handle a click from this I just type in (VB.Net):<br /><pre>Public Sub handleButtonFoo(ByVal sender as System.Object, ByVal e as System.EventArgs) Handles btnFoo.Click<br /> Console.Out.WriteLine("Click")<br />End Sub</pre><br /><br />It gets a little more hairy when you're handling dynamically created Objects, though. This took me some time to find, and it led me to a foray into delegates. I'll get back to them some other time though.<br /><br />What you have to do is create a method with the same signature as the event. Say I'm looking to handle a LostFocus event on a Control. That has the signature: Public Event <span style="font-weight: bold;">LostFocus</span>(ByVal sender As <span style="font-weight: bold;">Object</span>, ByVal e As <span style="font-weight: bold;">System.EventArgs</span>). So what I need is a method that matches that signature. Behold!<br /><br /><pre>Private Sub HandleSomethingLostFocus(ByVal sender As System.Object, ByVal a As EventArgs)<br /> Console.Out.WriteLine("Give me back my focus!")<br />End Sub</pre><br /><br />This is not the whole story though. You may have noticed that the handleButtonFoo method had the keyword handles after it with a reference to the event it wanted. My little lost-focus method has no such thing, as no object exists yet that I want to handle. When one exists though, I can pipe the events to my method with the following code:<br /><pre>Private Sub createWidget()<br /> 'Make something that can lose focus<br /> Dim widget As New TextBox<br /><br /> 'Add the widget to the main form (which we're in)<br /> Me.Controls.Add(widget)<br /><br /> 'pipe the LostFocus events to the handler we wrote<br /> AddHandler widget.LostFocus, AddressOf Me.HandleSomethingLostFocus<br /><br />End Sub</pre><br /><br />This will delegate the LostFocus events to my method. Yay!<br /><br />As you may have noticed this is a better way to handle this than in Java. You get a set pattern on how to do it, defined at the language level (AddHandler is a reserved word). It's also less verbose than the Java-way, as that one included code in two classes and one interface. It may do the same, but I like it better.<br /><br />Now I've got to get home, I have a sick child. Till next time!Tomashttp://www.blogger.com/profile/00258760670089542893noreply@blogger.com0