Archive for the ‘Castle’ Category

Semi final release – Windsor 2.5 beta 2 (now with Silverlight support)

Wednesday, July 21st, 2010

A bit later than expected (ah, work) I pub­lished beta 2 of Wind­sor 2.5 today. The release has the fol­low­ing changes as com­pared to beta 1.

  • Sil­verlight ver­sion (for Sil­verlight 3 and Sil­verlight 4) is now included in the package.
  • Syn­chro­nize Facil­ity is now included in the pack­age (.NET only)
  • The fol­low­ing code changes and fixes were made (incl. one break­ing change)
  • - added sup­port for select­ing com­po­nents based on cus­tom attrib­utes and their prop­er­ties. See Component.HasAttribute<T>() methods

    - added WithService.DefaultInterface() to flu­ent API. It matches Foo to IFoo, Super­FooEx­tended to IFoo and IFooEx­tended etc. If you know how Default­Con­ven­tion works in Struc­tureMap, this is pretty similar

    - added sup­port for Castle­Com­po­nen­tAt­tribute in flu­ent API. Also added helper fil­ter method Component.IsCastleComponent

    - added abil­ity to spec­ify inter­cep­tors selec­tor as a ser­vice, not just as instance

    - added abil­ity to spec­ify proxy hook in flu­ent API

    - index­ers on IKer­nel are now obsolete.

    - added With­Ap­p­Con­fig() method to log­ging facil­ity to point to log­ging con­fig­u­ra­tion in AppDomain's con­fig file (web.config or app.config)

    - BREAKING CHANGE: Restruc­tured life­cy­cle con­cerns — intro­duced ICom­mis­sion­Con­cern and IDe­com­mis­sion­Con­cern and favors them over old enum dri­ven style.

    - Fixed how con­tex­tual argu­ments are han­dled. Null is no longer con­sid­ered a valid value (That would cause an excep­tion later on, now it's ignored).

    - Changed method Deferred­Start on Startable­Fa­cil­ity. It now does not take a bool para­me­ter. A DeferredTryS­tart() method was intro­duced instead.

     

This is prob­a­bly the last pre-release for 2.5 and if no crit­i­cal issues are found, we’ll release final release in 2, 3 weeks. Go grab the bits, see if it works for you and if it does not report back. I’m also look­ing for peo­ple who want to con­tribute sam­ple appli­ca­tions for the final release. Ping me if you’d like to con­tribute to that.

Castle Windsor 2.5… the final countdown – beta 1 released (and Core, DynamicProxy, Dictionary Adapter)

Monday, July 5th, 2010

Well it’s about time. Due to cer­tain events (like me relo­cat­ing to the other part of the world) it’s later than planned but it’s here – beta 1 of Cas­tle Wind­sor 2.5 is avail­able for down­load.

There’s been quite a lot of changes in the release. Not just in the code but in the entire Cas­tle Project.

We migrated from Sub­ver­sion to Git, and you can now access the repos­i­to­ries on github. Hope­fully this will make things eas­ier for any­one who wants to con­tribute fea­tures and patches to get going, and will raise the level of com­mu­nity con­tri­bu­tions to the project (actu­ally it already has, although not as much as I’d like).

We moved from out pre­vi­ous doc­u­men­ta­tion to the new open wiki engine. The doc­u­men­ta­tion is still being migrated and updated but I can say that for Wind­sor the doc­u­men­ta­tion is already pretty com­plete and it cov­ers all the new fea­tures in ver­sion 2.5. The wiki is open for any­one to reg­is­ter and con­tribute, either by proof­read­ing and fix­ing spelling errors, expand­ing exist­ing top­ics or adding new ones.

Also it’s worth men­tion­ing the awe­some work that Andy Pike’s been doing on Castle­Casts. The web­site (built on Cas­tle stack obvi­ously) con­tains free short screen­casts that will help you learn dif­fer­ent aspects of the Cas­tle stack. While most of the scren­casts are ded­i­cated to Mono­rail, Andy recently started cov­er­ing Wind­sor as well. And the best part is – Castle­Casts is an open place for Castle-related screen­casts so if you want to record one, and share your knowl­edge with oth­ers go ahead.

What’s in it – Core (now incl. Dynam­icProxy and Dic­tio­nary Adapter)

Here are some of the high­lights of the release for Castle.Core.dll

  • Castle.DynamicProxy.dll got now merged into Castle.Core.dll (same with Dic­tio­nary Adapter) so now you need to ref­er­ence just sin­gle assem­bly instead of two.
  • Sup­ports .NET 4 (and .NET 4 client profile)
  • Dynam­icProxy has now new kind of prox­ies – Class proxy with tar­get. I blogged about lim­i­ta­tions of this approach, so use this with caution
  • Dynam­icProxy will now let you inter­cept explic­itly imple­mented inter­face meth­ods on class proxy
  • Dynam­icProxy will now let you inter­cept calls to meth­ods on System.Object (ToString, Equals, GetH­ash­Code) – the default Prox­y­Gen­er­a­tionHook will still opt out of this though
  • Dic­tio­nary Adapter per­for­mance improve­ments.  Proxy class are cached so DA no longer tra­verses assem­blies to find type
  • Dic­tio­nary Adapter auto­matic sup­port for Noti­fyProp­er­ty­Changed. EditableOb­ject, IDataEr­ror­Info, and val­i­da­tion capa­bil­i­ties.  Just extend from the interface(s) and fea­ture is enabled
  • Dic­tio­nary Adapter sup­port for cus­tom HashCode/Equals strat­egy so you can bet­ter sup­port per­sis­tence in which and Id usu­ally used for equality
  • Abil­ity to coerce one Dic­tio­nary Adapter into another and/or copy prop­er­ties from one to another.
  • Inte­grated sup­port for Xml/XPath using stan­dard Xml Seri­al­iza­tion attrib­utes – this gives you strongly typed con­fig files (for example)

Plus many more minor fixes, fea­tures and improve­ments. You can see the entire list in changelog.

What’s in it – Windsor

The main dish is obvi­ously Wind­sor, and there are plenty inter­est­ing new fea­tures and improve­ments as well.

And heaps of other smaller improve­ments and gen­eral polish.

Break­ing changes

This is a point-five release, which means it is highly com­pat­i­ble with pre­vi­ous release and upgrad­ing should be pretty straight­for­ward and quick. There are some changes though, and we tried to doc­u­ment all of them in breakingchanges.txt file included in the release. Read the file to see the list of break­ing changes and upgrade path for each of them. If you find any break­ing change not described in the file, or some infor­ma­tion that is inac­cu­rate of miss­ing let us know, so that we can improve that for the final release.

In addi­tion to that also some API was made obso­lete in this release (most notably the old reg­is­tra­tion API) to dis­cour­age users from its usage. It is not going away any­time soon, but it is highly rec­om­mended to migrate code using the now-obsolete API to the alternatives.

What’s next

This is beta 1 release. It means that before the final release no new major fea­tures will be added and no break­ing changes will be intro­duced (unless nec­es­sary to fix a crit­i­cal bug, which is unlikely). This release con­tains only .NET ver­sion of Wind­sor. Ver­sion for Sil­verlight is still in works and will be part of beta 2 release. We’re also work­ing on some sam­ple appli­ca­tions to help you get started using Wind­sor. The sam­ples will be also included in beta 2 release. So far we have a win­forms sam­ple almost ready. If you’d like to con­tribute a web sam­ple feel more than wel­come to contribute.

ETA for beta 2 is in two weeks, if no big issues are found, final release will be out around two weeks after.

Get it, play with it, give us your feedback!

The bits are here, to dis­cuss the release go to our google users group.

New Castle Windsor feature – debugger diagnostics

Friday, July 2nd, 2010

What you’re see­ing here, is a fea­ture in very early stages of devel­op­ment. It’s very likely to change in the very near future, hope­fully based on your feed­back which I’m look­ing for­ward to.

It is often the case with IoC con­tain­ers, espe­cially when reg­is­ter­ing com­po­nents by con­ven­tion, that you end up with mis­con­fig­ured com­po­nents, or with an excep­tion say­ing that your com­po­nent can’t be resolved. To aid work­ing in these sit­u­a­tions Struc­tureMap pro­vides meth­ods like What­DoI­Have and Assert­Con­fig­u­ra­tionIs­Valid. That’s the only con­tainer I know of that pro­vides this kind of diagnostics.

Wind­sor also has sim­i­lar abil­ity to StructureMap’s What­DoI­Have method. It’s very pow­er­ful as well, since Wind­sor tracks inter­nally the entire graph of objects and lets you access it you can for exam­ple visu­al­ize it.

The Assert­Con­fig­u­ra­tionIs­Valid is a tougher nut to crack. Thing is – you can’t really say when the con­fig­u­ra­tion is valid in any non triv­ial sit­u­a­tion. You can’t say when it’s non-valid either. The rea­son for that is that there are mul­ti­ple dynamic mov­ing parts that you can’t really sta­t­i­cally analyse to out­put a yes/no value.

What Wind­sor does

To help with these sit­u­a­tions when debug­ging, in Wind­sor 2.5 I added debug­ging prox­ies to the most impor­tant classes in Wind­sor, so that when look­ing at them in the debug­ger you will be pre­sented with much more help­ful view of what’s in the con­tainer and what’s poten­tially not right.

debugger_visualizer

You will see a very min­i­mal­is­tic view of what’s going on in the container:

  • All com­po­nents – will give you a list of all exist­ing com­po­nents in the con­tainer, kind of like WhatDoIHave
  • Facil­i­ties will give you the list of the installed facilities
  • Poten­tially mis­con­fig­ured com­po­nents – this is a list of com­po­nents that don’t look to good to Wind­sor and may have some depen­den­cies miss­ing. It also is a very sim­pli­fied view. At the first glance it will only tell you the key of the com­po­nent (in this case fully qual­i­fied name), slash service/implementation. In this case both ser­vice and imple­men­ta­tion are the same, so it won’t repeat the infor­ma­tion.
    When you drill down, you will also see the lifestyle of the com­po­nent and most impor­tantly its sta­tus, which will tell you why Wind­sor thinks there may be some­thing wrong with the component.

debugger_visualizer2

This pretty nicely tells you what might be wrong. If you are sure you pro­vid­ing these val­ues dynam­i­cally, be it from the call site or via dynamic para­me­ters, you can move on, oth­er­wise it can remind you of the miss­ing dependencies.

I want your feedback

How do you like this fea­ture? How would you change it? What other infor­ma­tion you think would be use­ful in this view? Leave a com­ment, or go to user­voice site to share your ideas.

Thanks

Castle Windsor and child containers: Revolutions

Thursday, June 3rd, 2010

Con­tin­u­ing the topic from the pre­vi­ous posts.

What would happen?

Cur­rent behav­ior of Wind­sor is some­what flawed. What it will do is it will resolve foo, and pro­vide it with bar. The flaw of this behav­ior is that now when we resolve foo via any of the tree con­tain­ers we’ll  get the same instance (since it’s a sin­gle­ton). This intro­duced two issues:

  • com­po­nent from childA (bar) will now be avail­able via childB and par­ent while log­i­cally think­ing – it should not.
  • we have tem­po­ral cou­pling in our code. Depend­ing on the order of con­tain­ers we’ll use to resolve foo we’ll get dif­fer­ent results

So what should happen?

Ok, so now that we agreed that cur­rent behav­ior is indeed flawed (we did, didn’t we?) what are our options for fix­ing it? We basi­cally have two options (both of which were men­tioned in com­ments to pre­vi­ous post).

It all boils down to scop­ing. If we have a per-web-request object – should sin­gle instance be shared among mul­ti­ple con­tain­ers or should it be per-web-request-and-per-container? If we have sin­gle­ton should it be sin­gle instance per con­tainer, per con­tainer hier­ar­chy or per process?

Let’s con­sider slightly more com­pli­cated picture.

containers_2

Now we have two com­po­nents for bar, one in childA and one in par­ent. Also we have one more com­po­nent; baz, which is reg­is­tered in childB.

classes_2

Baz has depen­dency on foo, foo still has depen­dency on bar. All of these depen­den­cies are optional, and all com­po­nents are singletons.

There can only be one

We want to scope instances strictly per their con­tainer. So that foo is scoped in par­ent (thus vis­i­ble from its child con­tain­ers as well), and bar is scoped per childA. This appears to be the sim­plest setup, and the most in line with def­i­n­i­tion of sin­gle­ton, but then we run into prob­lems out­lined above.

We then could add another con­straint – depen­den­cies can only face upwards the con­tainer hier­ar­chy. We would then get foo with its depen­dency on bar pulled from par­ent con­tainer, con­sis­tently, regard­less of the con­tainer we’d resolve it from. More­over, we could resolve baz from childB and its depen­dency would be prop­erly pop­u­lated from par­ent since it comes from a con­tainer that is higher in the hier­ar­chy, so we’re safe to pull that dependency.

On the other hand this robs us of one of nice (and often used) side effect of child con­tain­ers, that is con­tex­tual over­rid­ing of com­po­nents from con­tain­ers higher up the hierarchy.

If we have bar in childA, we’d expect to get foo pulled via childA to have that bar, not parent’s bar.

Or per­haps not?

We can approach the prob­lem from another angle alto­gether. We can nar­row down the scope of a com­po­nent instance, to the scope of its out­er­most depen­dency. What do I mean by that?

When resolv­ing foo from childA the out­er­most depen­dency of foo would be the bar liv­ing in childA. There­fore the instance of foo would have bar pulled from par­ent, but scoped in childA. There­fore when we’d request foo again, but this time from childB we’d get another instance of foo, with depen­dency on bar pulled from par­ent. This could poten­tially lead to prob­lems as well, since if you’re depend­ing on the fact that sin­gle instance of your com­po­nent will ever live in the appli­ca­tion at given point in time you may end up with problems.

So what do you think? Which approach would you pre­fer, or is there some­thing I’m miss­ing here?

To those who though I’m seri­ously going to remove sup­port for nested con­tain­ers rest assured this is not going to hap­pen. I still think this could be a viable option and I wanted to throw it into the air, but its become such a core fea­ture of each IoC con­tainer, that Wind­sor would look crip­pled if it didn’t have it, regard­less of whether or not it’d be actu­ally needed.

Castle Windsor and child containers

Tuesday, June 1st, 2010

Neal started look­ing into behav­iour of child con­tain­ers in Wind­sor. This is an area that’s very rarely used, and as Ham­mett wrote two years ago – this is speak­ing with the devil him­self. No one really ever uses it so it never got well defined and as Neal found out there are cer­tain incon­sis­ten­cies, and grey areas there.

This was a don’t ask, don’t tell area, and since Neil opened that can of worms, it’s time to deal with the issue. I’m con­sid­er­ing sev­eral solu­tions, and the one I’m lean­ing towards most would be prob­a­bly the most controversial.

Remove sup­port for child con­tain­ers altogether?

Basi­cally han­dler selec­tors and sub-resolvers give you all the power you need to han­dle sce­nar­ios where you would want to use child con­tainer instead. I think remov­ing the child con­tain­ers, and add some nicer sup­port for con­tex­tual scop­ing of com­po­nents would be the best solution.

The point of this post how­ever is to get your thoughts on this issue. Are you using child con­tain­ers in Wind­sor? What are you using it for? How are you using it? Write a com­ment or if you don’t want to share that in pub­lic just drop me an email. I’d really like to get a clean pic­ture of how usage of this fea­ture looks like at this point in time, before I make a decision.

.NET OSS dependency hell

Thursday, February 25th, 2010

Paul, whom some of you may know as the main­tainer of Horn project, left a com­ment on my blog, that was (or to be more pre­cise – I think it was) a con­tin­u­a­tion of series of his tweets about his dis­sat­is­fac­tion with the state of affairs when it comes to depen­den­cies between var­i­ous OSS projects in .NET space, and within Cas­tle Project in particular.

paul_twitter

I must say I under­stand Paul, and he’s got some valid points there, so let’s see what can be done about it.

Prob­lems

One of the goals of Cas­tle Project from the very begin­ning has been mod­u­lar­ity of its ele­ments. As cas­tle main page says:

Offer­ing a set of tools (work­ing together or inde­pen­dently) and inte­gra­tion with oth­ers open source projects, Cas­tle helps you get more done with less code and in less time.

How do you achieve mod­u­lar­ity. Say you have two projects, Foo and Bar that you want to inte­grate. You could just ref­er­ence one from the other.

eb1c2cc[1]

This how­ever means that when­ever you use Foo, you have to drag Bar with you. For exam­ple, when­ever you want to use Mono­Rail, you’d need to drag ActiveRe­cord with it, along with entire set of its depen­den­cies, and their depen­den­cies, etc.

Instead you employ Depen­dency Inver­sion (do not con­fuse with Depen­dency Injec­tion). You make your com­po­nents depend on abstrac­tions, not the imple­men­ta­tion. This how­ever means, that in .NET assem­bly model, you need to intro­duce third assem­bly to keep the abstrac­tions in.

51067fb6[1]

Now we have 3 assem­blies instead of 2 to inte­grate two projects. Within Cas­tle itself com­mon abstrac­tions are being kept in Castle.Core.dll. But what if we want to take more direct advan­tage of one project in another project still main­tain­ing the decou­pled struc­ture? We need to extract the func­tion­al­ity bridg­ing the two projects to yet another assem­bly. Tick – now we have 4 of them.

607f68d4[1]

In this case the Foo­Bar project would be some­thing like ActiveRe­cord inte­gra­tion facil­ity, which inte­grates ActiveRe­cord with Wind­sor.

When you mix mul­ti­ple projects together you enter another prob­lem – versioning.

Say you want to inte­grate few projects together, some of which are inter­de­pen­dent (via bridg­ing assem­blies, not shown here for brevity)

69f20a13[1]

Now, once a new ver­sion of one of the projects is released, you either have to wait for all the other projects to update their depen­dency to the lat­est ver­sion, do it your­self (pos­si­bly with some help from Horn), or stick to the old ver­sion. The sit­u­a­tion gets even more com­pli­cated when there were some break­ing changes intro­duced, in which case plain recom­pi­la­tion will not do – some actual code would need to be writ­ten to com­pen­sate for that.

These are the main issues with this model, let’s now look at pos­si­ble solutions.

Solu­tions

First thing that comes to mind – if hav­ing some assem­blies means you’ll need even more assem­blies, per­haps you should try to min­i­mize that num­ber? This has already come to our minds. With last wave of releases we per­formed some inte­gra­tion of projects. EmailSender got inte­grated into Core, one less assem­bly. Log­ging adapters for log4net and nlog were merged into core project, which means they still are sep­a­rate assem­blies (as they bridge Cas­tle with 3rd party projects) but they’re now synced with Core and are released with it, which means this is one less ele­ment in your ver­sion­ing matrix for you to worry about. Sim­i­lar thing hap­pened with Log­ging Facil­ity, which now is ver­sioned and released with Wind­sor itself.

For the next major ver­sion, there are sug­ges­tions to take this one step fur­ther. Merge Dynam­icProxy with Dic­tio­naryAdapter and (parts of) Core into a sin­gle assem­bly; Merge Wind­sor and Micro­Ker­nel (and other parts of Core) into an other assem­bly. With that you get from 5 assem­blies to 2.

That reduces Castle’s inter­nal depen­den­cies, but what about other projects that depend on it? After the recent release, we started a log of break­ing changes, along with brief expla­na­tion and sug­gested upgrade paths, to make it eas­ier for appli­ca­tions and frame­works to upgrade. We have yet to see how this plays out.

What else can be done?

This is the actual ques­tion to you? What do you think can be done, for Cas­tle specif­i­cally, but more broadly – for entire .NET OSS ecosys­tems to make prob­lems Paul men­tioned go away, or at least make them eas­ier to sort out?

Learning in the Open: II – first relation and more ActiveRecord

Tuesday, February 2nd, 2010

It took a lit­tle longer than I planned but here we go again. In the mean­time ActiveRe­cord 2.1 was released, and soon after that a minor update bring­ing one cool big fea­ture. From now on we’ll be work­ing on ver­sion 2.1.2. Pick­ing up from where we left off last time. We have a user entity. Since we’re build­ing a web­site where users can pub­lish bench­mark results, we’ll cre­ate now a bench­mark entity, and cre­ate a rela­tion between these two.

I want to see results!

Let’s start by adding an appro­pri­ate field to the User class:

private readonly ICollection<BenchmarkResult> benchmarkResults = new HashSet<BenchmarkResult>();

We also cre­ate a property:

public IEnumerable<BenchmarkResult> BenchmarkResults

{

    get

    {

        foreach (var result in benchmarkResults)

        {

            yield return result;

        }

    }

}

So far this is just a reg­u­lar prop­erty. To map it as a one-to-many rela­tion we use the Has­Man­y­At­tribute.

[HasMany(Access = PropertyAccess.FieldCamelcase, 

    Cascade = ManyRelationCascadeEnum.SaveUpdate, 

    RelationType = RelationType.Set,

    Inverse = true)]

public IEnumerable<BenchmarkResult> BenchmarkResults

There’s quite a lot going on here, so let’s go over it piece by piece

  • Access prop­erty Field­Camel­case spec­ify we want ActiveRe­cord (and NHiber­nate under­neath it) to go to the field directly, which makes sense since we’re expos­ing it as mere enumerable.
  • Cas­cade spec­i­fies that when sav­ing or updat­ing our user, all new and changed bench­mark results in the col­lec­tion should also be appro­pri­ately saved or updated.
  • Usu­ally we wouldn’t have to spec­ify type of the rela­tion. Usu­ally it will infer it from the kind of col­lec­tion we expose, and would use set for ISet, map for IDic­tionary, bag for ICol­lec­tion etc. How­ever since we’re expos­ing only IEnu­mer­able it does not have enough infor­ma­tion to decide, that’s why we have to be explicit here.
  • We also spec­ify Inverse prop­erty to be true, which basi­cally means that it’s child’s task to main­tain the rela­tion­ship. That also means that child needs to have a ref­er­ence to the par­ent.

Let’s now build our Bench­markRe­sult class.

[ActiveRecord]

public class BenchmarkResult : ActiveRecordLinqBase<BenchmarkResult>

{

    protected BenchmarkResult()

    {

    }

 

    public BenchmarkResult(User user, string benmchmarkName, string computerModel, double score)

    {

        if (user == null)

        {

            throw new ArgumentNullException("user");

        }

        if (benmchmarkName == null)

        {

            throw new ArgumentNullException("benmchmarkName");

        }

        if (computerModel == null)

        {

            throw new ArgumentNullException("computerModel");

        }

 

        User = user;

        BenmchmarkName = benmchmarkName;

        ComputerModel = computerModel;

        Score = score;

    }

}

So far there’s noth­ing new here. Com­puter con­fig­u­ra­tion and bench­mark will become enti­ties them­selves soon, but let’s not get ahead of ourselves.

The only inter­est­ing prop­erty at this point is the User.

[BelongsTo]

public User User { get; private set; }

It has a BelongsToAt­tribute to denote it points to another entity (on our case the ‘one’ end of our one-to-many).

Let’s now let our users to actu­ally save bench­mark results, and we’re more or less done:

public BenchmarkResult RunBenchmark(string benchmarkName, string computerModel, double score)

{

    var result = new BenchmarkResult(this, benchmarkName, computerModel, score);

    benchmarkResults.Add(result);

    return result;

}

Test

We now have all the logic in place, so let’s build a test:

[Fact]

public void Can_perform_benchmark_runs()

{

    var stefan = new User

    {

        Email = "stefan@gmail.com",

        Name = "Stefan",

        Password = "Super compilcated password!",

        About = "Stefan is a very cool."

    };

    stefan.RunBenchmark("Foo bar!", "AyeMack Pro", 3.2);

    stefan.Save();

 

    var user = User.FindAll().Single();

 

    Assert.NotEmpty(user.BenchmarkResults);

    Assert.Equal(1, user.BenchmarkResults.Count());

 

    var result = user.BenchmarkResults.Single();

 

    Assert.NotNull(result);

    Assert.Equal("Foo bar!", result.BenmchmarkName);

    Assert.Equal("AyeMack Pro", result.ComputerModel);

    Assert.Equal(3.2, result.Score);

}

If we run it now, it will fail. Good news is, that it does not have any­thing to do directly with our logic. Bad news is, that we have a pass­ing test nonethe­less, so let’s have a look at it.

Error

We get “Incor­rect syn­tax near the key­word 'User'.” error mes­sage. Here’s the SQL that was sent to the database:

error_sql

Looks good doesn’t it? Well not – really, User is a SQL Server key­word, as we can’t just use it as iden­ti­fier – we have to escape it. To do it, we have to spec­ify the col­umn name explic­itly, and escape it by enclos­ing it within two ` char­ac­ters (located above tab key on my keyboard).

Yes I’m aware of hbm2ddl.keywords auto-quote. How­ever I had some issues get­ting it to work with ActiveRe­cord. Any help doing this will be appreciated.

[BelongsTo(Column = "`User`")]

public User User { get; private set; }

Now the test will pass, and the fol­low­ing SQL will be generated:

ok_sql

Now that we have the cor­rect SQL, let’s look at what our schema looks like:

schema_inverse_true

Transparently releasing components in Windsor

Wednesday, January 27th, 2010

Dis­claimer:

This post is about the idea, not about the imple­men­ta­tion. The imple­men­ta­tion is crip­pled, not thread safe, will work only in few sce­nar­ios and only if used prop­erly. Do not copy and blindly use this code.

The prob­lem

One of unique fea­tures of Wind­sor is that it man­ages the life­cy­cle of objects it cre­ates for you. What this means (among other things) is that it will dis­pose all dis­pos­able objects it instan­ti­ates. How­ever to do this, it has to keep a ref­er­ence to these com­po­nents. Also that means that in order to prop­erly release the com­po­nents you have to get hold of the con­tainer and once you’re done using the com­po­nents – explic­itly release them with the container.

It may be not desir­able from your per­spec­tive to do it like this. Ide­ally, you’d rather use your com­po­nent, call Dis­pose and then have Wind­sor release the com­po­nent. This is not quite pos­si­ble, since there’s no way by which Wind­sor can be noti­fied that your com­po­nent was dis­posed. Or is there?

The idea

Since Dis­pose is an inter­face method and Wind­sor has quite pow­er­ful AOP capa­bil­i­ties, we can take advan­tage of that and inter­cept the call to Dis­pose and trans­par­ently release our com­po­nent. Let’s build a dis­pos­able com­po­nent first:

public interface IController : IDisposable

{

    int DoSomething();

 

    bool Disposed { get; set; }

}

 

public class Controller : IController

{

    // notice it's not virtual!

    public void Dispose()

    {

        // some clean up logic here

        Disposed = true;

    }

 

    public int DoSomething()

    {

        return 42;

    }

 

    public bool Disposed

    {

        get; set;

    }

}

One impor­tant thing to notice about this code – Dis­pose is not imple­mented vir­tu­ally. This will make our sam­ple sim­pler since we won’t have to deal with recursion.

Then we set up the stage:

[TestFixture]

public class TransparentReleasingTest

{

    private WindsorContainer container;

 

    [SetUp]

    public void SetUp()

    {

        container = new WindsorContainer();

        container.Register(Component.For<ReleaseComponentInterceptor>());

        container.Register(Component.For<IController>().ImplementedBy<Controller>()

                               .LifeStyle.Transient

                               .Interceptors<ReleaseComponentInterceptor>());

    }

 

    [TearDown]

    public void CleanUp()

    {

        container.Dispose();

    }

}

We’ll dis­cuss the ReleaseC­om­po­nentIn­ter­cep­tor, which is the gist of this post, in a minute. Let’s first cre­ate a test:

[Test]

public void Dispose_releases_component()

{

    IController item;

    using (var controller = container.Resolve<IController>())

    {

        item = controller;

        controller.DoSomething();

 

        Assert.IsTrue(container.Kernel.ReleasePolicy.HasTrack(controller));

        Assert.IsFalse(controller.Disposed);

    }

 

    Assert.IsFalse(container.Kernel.ReleasePolicy.HasTrack(item));

    Assert.IsTrue(item.Disposed);

}

Notice that in order for the inter­cep­tor to inter­cept the call to Dis­pose we need to cast com­po­nent to IDis­pos­able before call­ing the method (‘using’ will do that for us). Notice impor­tant aspect of this test – it is com­pletely con­tainer agnos­tic. It does not need any kind of explicit nor indi­rect ref­er­ence to the con­tainer to work and to release the com­po­nent prop­erly. Let’s now see what hap­pens behind the scenes.

Inter­cep­tor

The hero of the day, is the fol­low­ing interceptor:

[Transient]

public class ReleaseComponentInterceptor : IInterceptor

{

    private static readonly MethodInfo dispose = typeof(IDisposable).GetMethods().Single();

    private readonly IKernel kernel;

 

    public ReleaseComponentInterceptor(IKernel kernel)

    {

        this.kernel = kernel;

    }

 

    public void Intercept(IInvocation invocation)

    {

        if (invocation.Method == dispose)

        {

            kernel.ReleaseComponent(invocation.Proxy);

        }

        else

        {

            invocation.Proceed();

        }

    }

}

Most of the time it just sits there and does noth­ing. How­ever if it detects a call to Dis­pose, it releases the com­po­nent from the con­tainer, which will in turn invoke the Dis­pose again (this time on the class, not inter­face, and since the inter­face is imple­mented non-virtually that sec­ond call won’t be inter­cepted), per­form all other decom­mis­sion job for the com­po­nent as well as all its depen­den­cies and it will release it, so that it can be garbage col­lected afterwards.

This is just another use­ful trick, worth know­ing if you want to keep your design con­tainer agnos­tic while still reap­ing full ben­e­fits it provides.

Castle Windsor 2.1, Dynamic Proxy 2.2 and more released!

Monday, January 11th, 2010

Update: Due to a regres­sion error dis­cov­ered in Wind­sor Fac­tory Sup­port Facil­ity, we decided to act fast and pro­vide updated pack­age of Wind­sor, with­out the issue. Get it here. Sorry for the inconvenience.

Castle Project

What bet­ter way of start­ing a new year can there be, than fresh set of releases from Cas­tle Project?!

Core 1.2 (with more)

Cas­tle Core 1.2 has now its own, sep­a­rate pack­age. Since the beta few things have changed

  • Email sender com­po­nent is now inte­grated with Core, so if you were using it, you now should look for it in Castle.Core.dll. The ver­sion shipped with Core 1.2 has the fol­low­ing major break­ing changes:
    — Removed Mes­sage, Mes­sageAt­tach­ment and Mes­sageAt­tach­ment­Col­lec­tion classes and replaced them with MailMes­sage, Attach­ment and Attach­ment­Col­lec­tion from .NET classes in System.Net.Mail
  • Log­ging ser­vices (inte­gra­tion of Castle’s log­ging abstrac­tion with log4net and NLog) is now pack­aged with Core. Notice that these are depen­dent on Core (just like it used to be). Cas­tle does not have depen­dency on any of these, so don’t freak out.
  • few minor bugs were fixed, but noth­ing seri­ous. You should be able to just switch the ref­er­ence to new ver­sion and start using it with no changes to your code.
  • We ship four ver­sions: for .NET 2.0, for .NET 3.5, for Sil­verlight 3.0 and for Mono 2.6

Get it here.

Dynamic Proxy 2.2

This is a pretty sig­nif­i­cant release. If you haven’t before, read what we had in beta. Since then, the fol­low­ing has changed

  • Inter­face mem­bers on prox­ies are behav­ing almost iden­ti­cal to ver­sion 2.1 (change from beta). That means that they take long name of explicit imple­men­ta­tion (InterfaceName.Method() instead of Method()), only if you already have a method called Method() on your proxy, either from base class or other inter­face. And even then, it will still be pub­lic, which makes it more trans­par­ent to the user.
  • We ship three ver­sions: for .NET 2.0 (this is the last ver­sion to sup­port .NET 2.0), .NET 3.5 and Sil­verlight 3.0

Get it here.

MicroKernel/Windsor 2.1.1 (with sup­port for Silverlight)

Prob­a­bly the biggest thing about this release is that it includes a Sil­verlight ver­sion. There are a cou­ple more high­lights thought

  • revamped typed fac­tory facil­ity
  • added abil­ity to spec­ify Type For­ward­ing via XML con­fig with the fol­low­ing syntax:
    <component

      id="hasForwards"

      type="Castle.MicroKernel.Tests.ClassComponents.TwoInterfacesImpl, Castle.MicroKernel.Tests"

      service="Castle.MicroKernel.Tests.ClassComponents.ICommon, Castle.MicroKernel.Tests">

      <forwardedTypes>

        <add service="Castle.MicroKernel.Tests.ClassComponents.ICommon2, Castle.MicroKernel.Tests" />

      </forwardedTypes>

    </component>

  • added Dynam­ic­Pa­ra­me­ters (with addi­tional option to return del­e­gate to be called upon component’s destruction)
  • added OnCre­ate method, which lets you act upon com­po­nent after it’s cre­ated, and before it’s removed (see this Tehlike’s post. Notice it’s not in a facil­ity now, so it just works out of the box.)
  • added lazy com­po­nent loader
  • major per­for­mance improve­ments in cer­tain sce­nar­ios
  • and many bug­fixes, see com­mit log for full list if you’re interested
  • We ship two ver­sions: for .NET 3.5 and for Sil­verlight 3.0
  • There is also log­ging facil­ity included in the pack­age. Again – nei­ther Micro­Ker­nel, nor Wind­sor depend on it, so don’t freak out.

Get it here.

We're already gath­er­ing ideas for the next ver­sion, so go ahead to the Cas­tle User­Voice page and tell us, what you'd like to see in the next version!

Learning in the Open: I – Starting with ActiveRecord

Sunday, January 10th, 2010

We’re build­ing an appli­ca­tion to gather and com­pare per­for­mance met­rics of var­i­ous lap­top con­fig­u­ra­tions in given set of bench­marks. As such we’re going to start with cer­tain set of enti­ties, first of which will be the User. We’ll start off by defin­ing our User entity, con­fig­ur­ing ActiveRe­cord, and some basic tests.

Get­ting started

First thing’s first – we need to get our­selves a fresh ver­sion of required libraries. At this point in time I’m using the trunk ver­sion. You can get the lat­est bina­ries here. Every­thing I show here will work with ActiveRe­cord 2.1 final ver­sion though.

So let’s cre­ate our­selves a new solu­tion, with class library and add required references:

references

We need Castle.ActiveRecord.dll, Castle.ActiveRecord.Linq.dll, which is where inte­gra­tion with NHibernate.Linq lives, and NHibernate.dll. Hav­ing that in place we can start cod­ing our first entity.

User is always right

Let’s start by declar­ing our User class:

[ActiveRecord]

public class User : ActiveRecordLinqBase<User>

{

}

We mark our class with ActiveRe­cor­dAt­tribute. By doing this we let Active Record know that this class is per­sis­tent. We use ActiveRecordLinqBase<User> as our base class. This gives us access to all stan­dard Active Record pat­tern meth­ods, as well as IQueryable<User> so that we can use LINQ to query for our users. Alter­na­tively if we didn’t want to have this base class we can use ActiveRecordMediator<User> which pro­vides the same per­sis­tence ser­vices as our base class.

Now, that we told ActiveRe­cord it should per­sist our User class, we’ll need a pri­mary key property.

private Guid id;

 

[PrimaryKey(Access = PropertyAccess.NosetterCamelcase)]

public Guid Id

{

    get { return id; }

}

Cou­ple of things to notice about this piece of code. We use Pri­ma­ryKey­At­tribute to mark our prop­erty as hold­ing pri­mary key. Also we use Guid as our sur­ro­gate pri­mary key type, for sev­eral rea­sons. If you’ve used older ver­sions of ActiveRe­cord, you may notice I didn’t spec­ify pri­mary key gen­er­a­tor kind. ActiveRe­cord 2.1 will infer it from prop­erty type and will use guid.comb. We also don’t expose set­ter for this prop­erty. By using PropertyAcess.NosetterCamelcase we tell ActiveRe­cord to use get­ter to retrieve value of this prop­erty, and to use back­ing field which has iden­ti­cal name as the prop­erty, but writ­ten in camel case to write it.

We’re going to need a cou­ple of other prop­er­ties for our users:

[Property(Unique = true, NotNull = true)]

public string Name { get; set; }

 

[Property]

public string Email { get; set; }

We use Prop­erty­At­tribute to mark prop­er­ties that should be per­sisted. While we don’t put any non default con­straints on the Email prop­erty at this point, we’ll make user name unique, and we’ll dis­al­low nulls.

[Property(Access = PropertyAccess.FieldCamelcase)]

public string Password { set { password = Hash(value); } }

 

[Property(Length = 10000)]

public string About { get; set; }

For pass­word we expose only set­ter. Also since we don’t want to store pass­words of our users, we hash it, and store the hash. About is a prop­erty that has Length set to 10000. This means nvarchar(max) for SQL Server 2005 (which is what we’ll use) or cor­re­spond­ing data type if you use other data­base engine.

Let’s set up a test project for our­selves and start writ­ing some basic logic. But before we do this, we’ll need to set up a data­base and con­fig­ure ActiveRecord.

Con­fig­u­ra­tion

For our data­base we’ll use SQL Server .mdf file. When we cre­ate it, we' need to cre­ate an App­Do­main con­fig­u­ra­tion file and put some basic con­fig­u­ra­tion in it. We could alter­na­tively put ActiveRe­cord con­fig­u­ra­tion in some other file it we wanted.

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

  <configSections>

    <section name="activerecord"

             type="Castle.ActiveRecord.Framework.Config.ActiveRecordSectionHandler, Castle.ActiveRecord" />

  </configSections>

    <connectionStrings>

        <add name="Wawel"

             connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=f:\ComputerBenchmark\sql\Wawel.mdf;Integrated Security=True;User Instance=True"

             providerName="System.Data.SqlClient" />

    </connectionStrings>

  <activerecord pluralizeTableNames="true">

    <config database="MsSqlServer2005"

            connectionStringName="Wawel" />

  </activerecord>

</configuration>

We start by declar­ing active record sec­tion and reg­is­ter­ing han­dler for it. We then put stan­dard Active Record con­fig­u­ra­tion. We tell it to plu­ral­izeTable­Names, so that for our User class a Users table will be cre­ated. We then spec­ify what kind of data­base engine we want to use (MsSqlServer2005) and name of the con­nec­tion string to use. That’s it. If you’ve used pre­vi­ous ver­sions of ActiveRe­cord you may remem­ber it used to require quite a bit more con­fig­u­ra­tion. Now it will just use default val­ues for these, which you can always over­ride if you want. We can now move on to cre­at­ing tests.

Tests

We’ll use XUnit.NET as our test­ing frame­work. Sine ActiveRe­cord is built on top of NHiber­nate we also use NHProf to gain insight into what’s going on under the cover. Here’s the setup code.

public class UserTests:IDisposable

{

    public UserTests()

    {

        // performs initialization using information from appdomain config file

        ActiveRecordStarter.Initialize();

        // registers all active record types from the assembly

        ActiveRecordStarter.RegisterAssemblies(typeof(User).Assembly);

        // generates database schema

        ActiveRecordStarter.UpdateSchema();

 

        NHibernateProfiler.Initialize();

    }

 

    public void Dispose()

    {

        NHibernateProfiler.Stop();

        ActiveRecordStarter.DropSchema();

 

        // this is only for tests

        ActiveRecordStarter.ResetInitializationFlag();

    }

}

ActiveRecordStarter.Initialize reads all set­tings from the app.config file we dis­cussed above and ini­tial­izes its engine. We then feed it with infor­ma­tion about our Active Record classes, and call UpdateSchema. ActiveRe­cord will now gen­er­ate our com­plete data­base schema for us.

sshot-2

As you can see table name is nicely plu­ral­ized, and all the infor­ma­tion we spec­i­fied in attrib­utes was used to cre­ate cor­rect schema. Hav­ing that, we can now cre­ate our first test.

[Fact]

public void Can_save_and_read_User()

{

    var stefan = new User

    {

        Email = "stefan@gmail.com",

        Name = "Stefan",

        Password = "Super compilcated password!",

        About = "Stefan is a very cool."

    };

 

    stefan.Save();

    var users = User.Queryable

        .Where(u => u.Name.StartsWith("S"))

        .ToList();

    Assert.NotEmpty(users);

    Assert.Equal("Stefan", users.Single().Name);

}

We cre­ate a user, than call method Save, inher­ited from our base class which per­sists the user to the data­base. We then can use sta­tic Queryable prop­erty which exposes LINQ engine to cre­ate a fancy LINQ query to retrieve our user.

sshot-3

Fan­tas­tic! We have a work­ing per­sis­tent user entity!