Thursday, July 30, 2009

DynamicProxy tutorials - Krzysztof Koźmic

Currently looking at DynamicProxy tutorials by Krzysztof Koźmic Any AOP type development is a candidate to be done by DP.

Excellent tutorial series...

Leave the irrelevant standards out of the coding standards...

Coding standards are put in place primarily for maintainability purposes but how far does an organisation/company or induvidual go in relation to coding standards?

Heres my opinion on coding standards: Once the code is some way consistent - that is acceptable enough to me.

Having to define exactly how many lines are between methods, and spacing rules are irrelevant in comparison to the quality of the code that is actually written.

Some open source projects that I have looked at (Castle and NHibernate to name a few) have general coding standards but don't go down to a spacing level.

I recently worked on a project where coding standards were so stringent that we had to run regression tests again due to spacing issues! - The word "practicality" comes to mind

Monday, July 27, 2009

Binsor 2.0 Spike

Recently, I tasked myself with the responsibility of spiking Binsor and checking if my current projects castle configuration (which we have in an XML config file) could be fully converted.

Binsor is a DSL language for Castle Windsor and is a feature offered in the reknowned open source Rhino.Commons assembly. There are quite a few "basic" posts about Binsor but there were a few configuration scenarios that I had to dig deeply for. This post attempts to describe these scenarios and also give an overall verdict of Binsor as a whole.


1. Import statements

You must import all assembly types in a Binsor file e.g.
import Billy.CommonLibraries
import Billy.Application.Facade from Billy.Application.Facade.RC2

Note that if you have a type with a namespace that is different to the assembly name e.g. all types under Billy.Application.Facade, you must specify in the format <namespace> from <assembly name>


2. Properties

Properties are simply represented via boo variable declaration e.g.
<properties>
<p1>00:02:00</p1>
<p2>SampleString</p2>
</properties>

would be represented as:

p1 = "00:02:00"
p2= "SampleString"

3. Comments


All comment lines start with '#' e.g.

# Properties

4. Facilities

Declaring facility usage is simple e.g.

<facility
id="factory_Support"
type="Castle.Facilities.FactorySupport.FactorySupportFacility, Castle.MicroKernel" />
would be represented as:

facility FactorySupportFacility



5. Components

The following component Billy.CommonTypes.Handler.Default

<component
id="exceptionHandler"
service="Billy.CommonTypes.IHandler, Billy.CommonTypes"
type="Billy.CommonTypes.Handler.Default, Billy.CommonTypes">
</component>
would be represented as:

component "exceptionHandler", Billy.CommonTypes.IHandler, Billy.CommonTypes.Handler.Default




6. Types instantiated using instance fields

The following component configuration for Billy.CommonTypes.SystemClock

<component
id="clock"
service="Billy.CommonTypes.IClock, Billy.CommonTypes"
type="Billy.CommonTypes.SystemClock, Billy.CommonTypes"
instance-accessor="Instance">
</component>
would be represented as:
component "clock", Billy.CommonTypes.IClock, Billy.CommonTypes.SystemClock: 
createUsing Instance



7. Components with parameters


<component
id="exceptionLogger"
service="Billy.CommonTypes.Exception.ILogger, Billy.CommonTypes"
type="Billy.CommonTypes.Exception.Logger.EventLog, Billy.CommonTypes">
<parameters>
<logName>#{exceptionLogName}</logName>
<source>#{exceptionLogSource}</source>
</parameters>
</component>
would be represented as:

component "exceptionHandler", Billy.CommonTypes.Exception.ILogger, Billy.CommonTypes.Exception.Logger.EventLog:
logName = exceptionLogName
source = exceptionLogSource



8. Components instantiated using factories


<component
id="sampleTypeInstantiatedWithFactory"
service="Billy.CommonTypes.IProviderFactory, Billy.CommonTypes"
type="Billy.CommonTypes.ProviderFactory, Billy.CommonTypes"
factoryId="mySampleFactory"
factoryCreate="GetSampleType">
</component>
would be represented as:

component "sampleTypeInstantiatedWithFactory", Billy.CommonTypes.IProviderFactory, Billy.CommonTypes.ProviderFactory"
createUsing @mySampleFactory.GetSampleType



9. Event wiring


<component
id="eventingBroker"
service="Billy.CommonTypes.Eventing.IBroker, Billy.CommonTypes"
type="Billy.CommonTypes.Eventing.Broker, Billy.CommonTypes">
<subscribers>
<subscriber
id="subscriber1"
event="Event1"
handler="OnEvent1Firing" />
<subscriber
id="subscriber2"
event="Event2"
handler="OnEvent2Firing" />
</subscribers>
</component>
would be represented as:

component "eventingBroker", Billy.CommonTypes.Eventing.IBroker, Billy.CommonTypes.Eventing.Broker:
wireEvent Event1:
to @subscriber1.OnEvent1Firing
wireEvent Event2:
to @subscriber2.OnEvent2Firing



10. Startable components


<component
id="myStartableComponent"
type="Billy.CommonTypes.Type1, Billy.CommonTypes"
startable="true">
</component>
would be represented as:

component "myStartableComponent", Billy.CommonTypes.Type1:
@startable = true



11. Transient components


<component
id="myTransientComponent"
type="Billy.CommonTypes.Type2, Billy.CommonTypes"
lifestyle="transient">
</component>
would be represented as:

component "myTransientComponent", Billy.CommonTypes.Type2:
lifestyle Transient



12. WCF client components


<component
id="myWCFClient"
type="Billy.Clients.IClient, Billy.Clients"
wcfEndpointConfiguration="MyClient">
</component>
would be represented as:

component "myWCFClient", Billy.Clients.IClient:
wcfEndpointConfiguration="MyClient"

Conclusion


Excellent overall as it reduced the size of my castle configuration file down to 38% of its original size. The Binsor file is also much more readable and eradicates all the XML fluff! However the downside is that I had to reference the Rhino.Commons assembly. Binsor may get integrated into Castle in a future release so I am nearly more inclined to wait until this happens!

A big thank you to Craig Neuwirt for answering any Binsor questions that I had (via Castle forum)

Friday, May 15, 2009

Setter injection - when its makes sense to use it

It is common enough to have a bunch of subclasses that all implement the same contract and have a common base class,dependencies, ctor etc.

Sometimes one of these subclasses needs an extra dependency. If you are working within a TTD framework, it is likely that you inject all dependencies into your classes via the ctor (i.e. ctor dependency injection). Now, because your new class breaks the mould, what do you do?

1. Do you update the base class to include this new dependency? - Bad as every other subclass does not require this dependency.

2. Do you create a subclass base class that contains this dependency. This isnt too bad but if you know that no other class will need this dependency then a subclass base class is wasteful.

3. Simply new up the dependency object in the subclass that requires it. This is ideal from a functional perspective. However we still cannot test the subclass as we cannot mock up the dependency.

4. Simply new up the dependency object in the subclass that requires it but in addition, add a setter method in the subclass to enable you to set the dependency with a mocked up dependency for testing purposes. In the actual code, the real dependency is still instantiated in the ctor. See the code extract below:


public class Class1: Base
{
private IExtraDependency c_extraDependency;

public IExtraDependency ExtraDependency
{
set { this.c_extraDependency= value; }
}

public Class1(Param1 p1) : base(p1)
{
this.c_extraDependency = new ConcreteExtraDependency();
}



The production code will never call the setter but the test code will. When using Castle Windsor or any other IOC container for that matter, I like to use constructor injection. However if an "oddball" dependency surfaces, that must be covered in testing - it doesnt make sense to always have to inject that dependency via ctor.

In the example above it makes sense to tightly bind Class1 with its extra dependency but we also make it testable via setter injection.

Monday, May 11, 2009

More NHibernate Validator...

[CreditCardNumber]
public readonly string CreditCard;

Two things to quickly point out:

1. Works on readonly attributes (big thing where defining immutable types where attributes are only set vai ctor)

2. [CreditCardNumber] validation performs luhn check! - didnt expect that...

Sunday, May 10, 2009

NHibernate Validator

In a domain driven design codebase, all value types should be immutable. Also, where concerns such as concurrency raises its head, defining as many entities as possible as immutable can really simplify things.

NHibernate validator helps you to ensure that value/entity types never enter an invalid state.

You can implement validation using NHibernate Validator by declarative tags, fluent interfaces or defining the validation in an xml file. I really like the latter mechanism i.e. defining validation in an xml file as you are not polluting entity/value type ddfinition with validation logic.

In relation to ORMs, one major problem that has been discussed numerous times in DDD forums is that when a value type is retrieved from the database, it may be in an invalid state. Before with NHibernate, we got around this by validating the object retrieved manually via a PostLoadEventListener handler. However NHibernate Validator has full integration with the NHibernate lifecycle and it really makes it easy now to validate post load.

Overall, Im very impressed with NHibernate Validator...

Saturday, May 2, 2009

Epicenter 2009

The irish software show (epicenter) is on in Dublin on August 24th - 28th 2009. From what I know it is an amalgamation of microsoft, opensource, java, database and architecture tracks so I would highly recommend going to this if you are around the dublin area: Ref: http://epicenter.irishdev.com/

Tuesday, March 31, 2009

Performing GET with secure data

You shouldnt full stop! Even if the GET is performed over HTTPS, the complete GET URL with associated query string parameters are logged by the web server (in my case IIS logs) but would assume that Apache and other popular/capable web servers would do the same! Any web intermediaries would also log the data.

If you need to get secure data passed from the browser where the current domain is HTTPS to a different HTTPS domain you cannot perform the following:
1. Perform a POST (see previous post)
2. Perform a GET (cant as web servers log the data - not advised)

So what is the solution?
Really, the only solution is to perform a server to server call. Rather than calling direct from the browser, pass the secure data to the website/applications associated web server and perform a server to server call from there!

Posting across secure domains

Came across this issue in the last few days. If your browser is at https://securedomain1/... and you need to POST to https://securedomain2/..., you cannot trust this as IE and FF browsers later versions (and I would assume Opera + other browsers also) detect this and notify the user who is given the option to manually move on or not!

This is just a point of note. Usually one should aspire to design a web application where posting from one secure domain to another does not occur. Typically in an e-business website, the payment detail page will be secure and often hosted by a third party. Hence the rest of the website is non-secure as it is not required. You don't want your website to be over HTTPS and then having to redirect to a third party in a different secure domain over HTTPS.

Tuesday, March 24, 2009

Building domain specific languages in Boo

Started reading building domain specific languages in Boo ref: http://www.amazon.com/Building-Domain-Specific-Languages-Boo/dp/1933988606

Want to learn how to write DSLs, when to write them etc. Would be more in favour of writing using a language like Ruby but we will see how Boo goes I suppose. Will post on this in the future.

Monday, March 23, 2009

QUnit for javascript unit testing - my recommendations

QUnit - the unit testing test runner used for jQuery has turned out to be a valuable investment and javascript related bugs have been reduced considerably in a project I have been working on primarily due to its adoption.

I am not going to explain how to integrate QUnit tests, to learn how to do so please refer to http://docs.jquery.com/QUnit

The following are points of note in relation to how I have applied QUnit:

1. Have a 1-1 relationship between your js file and the QUnit htm file i.e. example.js should have a corresponding example.htm file

2. As all tests for a particular js file are in a single test QUnit .htm file, I tend to only use a single module. Using the module, you can perform setup and teardown functionality (which gets executed for every QUnit test)


module("sample module",
{
setup: function()
{
//do setup stuff...
}
teardown: function()
{
//do teardown stuff...
}
});

test("first test with setup")
{
// set conditions
$("#control1").val("testval");

// execute javascript function
sampleFunction();

// assert
assertTrue($("#control2").val(), 10);
};


3. All HTML controls that are used by the javascript you are testing need to be replicated in the .htm file.

4. All tests are similar to above in format i.e. set, execute and assert

The only problem I currently have is integrating QUnit tests into automated builds - using WatiN! - Will do future post when this issue is resolved

Wednesday, February 25, 2009

QUnit - Unit testing javascript

Started using QUnit for unit testing javascript/jquery code. Using the likes of Watin with NUnit, we can write a unit test that browses to a .htm page that contains the QUnit tests. By checking the actual html rendered by by the QUnit test runner (using Watin of course) we can verify if all the tests passed or failed.

Will update this post with technical examples soon...

Tuesday, February 3, 2009

Managed Entity Framework (MEF)

Started looking at this today. Its main aim is to make application extensible - in my opinion from first impressions it is just a glorified IOC container.

Will see over the coming days if this is the case...

Saturday, January 31, 2009

DDD + NHibernate dosen't fit 100%

Before I start, I think NHibernate is a classy open source piece of software and in my opinion is by far the best ORM out there! I am just outlining some of the problems I have encounterd with it when trying to integrate it into a DDD codebase.

One of the most major domain driven design principles is the concept of "persistence ignorance".
If you have entities in your domain that you want to persist through NHibernate, you must include a default constructor in the entity (although it can be private) - a small price to pay to use the power of NHibernate but persistence ignorance is broken (see following entity example):


public class SampleEntity
{
// Persistence ignorance broken...
private SampleEntity() { }


public void Method1()
{
. . .
}
}


When trying to convince the development team in my company to adopt NHibernate into the codebase, the default constructor requirement was a major stumbling block - as the domain was completely persistence ignorant!


Also, if you are developing a system where multiple threads of execution are in play regularly, making sure that all your value types are "immutable" avoids many concurrency issues. The problems working with immutable types and NHibernate are as follows:

1. Immutable types only work at a field level, not at a property level
2. Even if your types class is immutable (guard checks are performed via constructor), an invalid type can be retrieved back from the database (as the default constructor is called by NHibernate through reflection). There are ways around this using PostLoadEventListener to call the constructor with the guard checks is one solution - there are others

Has anyone else experienced the same proplems as described?

New blog

Ok, I have decided to start blogging, mainly because I have a major interest in software patterns, best practices, interest in open source software etc...

Also I would like to use this blog to get some of my own ideas out there...

Anyway we will give it a shot anyway...