News...

Castle goes RC2


Well it's an exciting week for Castle users, RC2 is out the door, and with it a new website look and feel with up-to-date content, and most interesting to me is the introduction of a new entity "CastleStronghold" a commercial venture, run by Hammet which offers professional support for developers and organisations implementing solutions in Castle, including guaranteed response times to inquiries and access to additional skilled development resources.

Personally Castle Stronghold is great news, as a developer for a company which has been using the Castle IoC for over a year now it adds a certain weight to our decision to run with this technology, and I think it offers a clear indication of the longevity this technology and product has... In time as our customer base grows it certainly looks appealing to have guaranteed support backing us up - and also helps customers to understand it's not some half backed open source project that's just going to fizzle out one day...

The RC2 release itself is exciting from a community point of view, it should be better then ever for people to pick up and play with this stuff - though we generally use interim snapshots of the trunk (ie. the last trunk release that didn't break our build...) so we've been exposed to most of the features for a while now, albeit without alot of the bug fixes ;o)

IronPython


I've been a bit quiet on the IronPython front... which is mostly because I haven't had the time to play around with it much lately - however I'll try to finish off my look into IronPython as a scripting engine, and in particular the good and bad aspects of getting it to play with your .Net code... In the mean time a collection of useful IronPython links is slowly growing here: http://ironpython-urls.blogspot.com/

Base4.Net


A week into using the Base4.Net's latest release, with compile-time query support, I'm loving it... it definitely gives a huge leap in productivity and expressability (if that's even a word ;o) - looking forward to seeing these features rounded out at some point (with support for scopes, projections and ordering) - Alex James is talking about migrations (my "most-wanted" feature) and it's looking encouraging, it's where I feel the most pain at the moment as base4 isn't particularly friendly when you try to approach the problem of building your schema in a YAGNI fashion - there is quite a bit of pain involved in adding and removing properties from types during development as requirements are refined.

The rub is that the current "on the table" solution will require restarting the base4 service to apply the migration... which at the moment means restarting the windows service with a different command line... or more likely, stopping the service, then starting the standalone server with the right command line arguments, waiting till it's done, stopping the standalone server and starting the service again...  I was originally thinking of implementing these as a Nant or MSBuild task (much like RoR's migrations work with rake) but I think it might be a bit chunky... I need to think about it a bit more.

Splicer


I haven't forgot about my little side project (Splicer is a library I've written for "attempting" to eliminate the pain of using DirectShow.Net to encode audio and video) - and I do intend to keep updating and supporting it as-needed... next release should see WinForm samples for encoding audio and video added, and updated code examples... after that I might review the implementation a bit, to see how effects and transitions can be made easier to use via relative times - I'm interested in DSL's at the moment, so maybe I could create a DSL for video editing ;o)... if nothing else it would be amusing... I've yet to establish if anyone actually uses the library yet (other than myself of course).
Read More

Generics and Castle...

Though I knew you could do it, I never have till today... and that's supplying a type for a generic parameter in another type, which is registered in a container... Of course I didn't have to do it that way, but it it kept the configuration a little thinner.

Basically I have some simple WCF services I wanted to host in a container.. here's the service's interface...

[ServiceContract(Namespace="http://localhost/schemas/testrunner/", SessionMode=SessionMode.Required)]
public interface ITestRunner
{
[OperationContract]
Guid StartTestRun(Guid testSuiteId);

[OperationContract]
TestRunStatus GetRunStatus(Guid testRunId);
}

To get this to work for my implementation I had to do one thing, which was set the InstanceContextMode to "single" for the service implementations behaviour, otherwise the service host would die when I tried to pass in an instance (it expects a type for any other mode)... I haven't dug very deep into WCF, but it would be nice if they supported a mechanism for supplying a component activator instead...

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class TestRunner : ITestRunner
{

Now, I build a component for hosting my service... it implements IStartable...

public class HostingWrapper : IStartable
where T: class
{
private ServiceHost _host;
private T _service;
private ILogger _log;

public HostingWrapper(ILogger log, T service)
{
if (log == null) throw new ArgumentNullException("log");
if (service == null) throw new ArgumentNullException("service");

_log = log;
_service = service;
}

public void Start()
{
_host = new ServiceHost(_service);
if (_log.IsDebugEnabled) _log.Debug("Opening ServiceHost for service: {0}", _service.GetType());
_host.Open();
if (_log.IsInfoEnabled) _log.Info("Opened ServiceHost for service: {0}", _service.GetType());
}

public void Stop()
{
if (_log.IsDebugEnabled) _log.Debug("Closing ServiceHost for service: {0}", _service.GetType());
_host.Close();
((IDisposable)_host).Dispose();
if (_log.IsInfoEnabled) _log.Info("Closed ServiceHost for service: {0}", _service.GetType());
_host = null;
}
}

And then you just need to regsiter it in the container's configuration:



service="BoatsForGoats.Services.Testing.ITestRunner, BoatsForGoats.Services"
type="BoatsForGoats.Services.Testing.TestRunner, BoatsForGoats.Services" />


type="BoatsForGoats.Services.HostingWrapper`1[[BoatsForGoats.Services.Testing.ITestRunner, BoatsForGoats.Services]], BoatsForGoats.Services" />

About the only tricky thing is that I guessed (incorrectly) that I would only need a single set of square brackets around the generic parameter.

Read More

Blowing up the burner..

Well I blew up my feedburner yesterday... my RSS feed was set to max out at 50 items, which, with my love for pasting html-bloated source code was well over the 256K limit.... but feedburner never bothered tell me it was dead... only noticed today... at any
rate, I tried resetting the size to a max of 6 posts in the feed... and pinging it... but it was still dead, so I did a resync... still no joy... In the end I found that I had to turn
off feed burner support in das blog and then resync the feed.

Moral of the story, don't bloat your feed (It was bad form at any rate, especially in bandwidth starved New Zealand ;o)

If you can see this post it's all working again happily...

Read More

Base4.net compile-time query handling support

Well lots to blog about, but no time to do it... at least not today - at any rate I just thought I would say if you haven't considered using Base4 up until now, why not give it a go with the latest drop :) I'm loving these new changes with the support for Compile-time query handling... I think at this point you can start prototyping stuff with base4 very quickly, between the UI for designing or discovering an existing schema, and now the ability to avoid learning the ObjectPath query syntax it's pretty compelling...



At any rate, as mentioned in the various posts from Alex James, you can now write these kinds of queries:



IItemList matchingFiles = StorageContext.Find(FileBase.Fields.FileSize > 1024000 && FileBase.Fields.MimeType == "audio/wav");


Faboo, and of course you can drill through the relationships:


Track track =  StorageContext.FindOne(Track.Fields.Name == reference.TrackName
&& Track.Fields.Release.Name == reference.ReleaseName
&& Track.Fields.Release.Artist.Name == reference.ArtistName);


This is for a simple hierarchy, where we have Artists-> Releases -> Tracks (sadly organising Music in reality isn't quite this easy...)



But as you can see these queries are getting quite verbose, personally this is where the elegance of this approach comes in... reuse is possible, for example - we can build a static class to hold common queries:


public static class FileBaseQueries
{
public static ExpressionField LargerThenOneMegabyte
{
get
{
return FileBase.Fields.FileSize > 1024000;
}
}

public static ExpressionField MimeTypeIsAudioWav
{
get
{
return FileBase.Fields.MimeType == "audio/wav";
}
}
}



And now the first query could be rewritten:


StorageContext.Find(FileBaseQueries.LargerThenOneMegabyte && FileBaseQueries.MimeTypeIsAudioWav);


The main thing I like about this approach is your queries start looking like sentences... "Larger Then One Megabyte and Mime Type Is Audio Wav"...



Another idea might be to use a method on the static class instead...


public static ExpressionField MimeTypeIs(string type, string subType)
{
return FileBase.Fields.MimeType == string.Format("{0}/{1}", type, subType);
}


And then writing something like:


StorageContext.Find(FileBaseQueries.LargerThenOneMegabyte && FileBaseQueries.MimeTypeIs("audio","wav"));


At this point it still reads quite nicely, but it's a little more flexible...



Edit: I just noticed this entry wasn't actually marked as syndicated... fixed it now.
Read More

Intermediate IoC...

I think there's 3 levels of skill involved with the Castle IoC
implementation... first off you get a handle of the XML
configuration, registering components, using existing
facilities... pretty much getting away largely with cut 'n paste
coding.



Then you get to the intermediate level.. writing basic
facilities, tweaks to the component model, writing your own sub
dependency resolvers or component activator, having a go with
binsor configuration.



I think the third level is reserved for the Castle team alone...
;o)



This post is going to be straddling the beginner to intermediate
kinda level... which is generally all I ever reach with Castle's
IoC... it's not often you have to dig deeper day-to-day... though
it's always good to know there is a lot of untapped potential
there.



So.. for today, say you have a component, like the Base4Host, which has some explicit constructors:


public
Base4Host(string appName,
int port)

{

    if
(string.IsNullOrEmpty(appName))
throw new ArgumentNullException("appName");

    if (port
<= 1024)="">throw
new ArgumentOutOfRangeException("port",
"port should be greater then
1024"
);

    _appName = appName;

    _port = port;

}

 

public
Base4Host(string appName,
int port, string root)

    : this(appName, port)

{

    if
(string.IsNullOrEmpty(root))
throw new ArgumentNullException("root");   
       

    _root = root;

}




You can register it the container easy enough, and provide values
for them in XML configuration, but what if you want to do the
same programatically... generally your first stop would be to
examine the IWindsorContainer for a suitable overload...
alas it doesn't get us far, so we dig in to the underlying
IKernel itself... the kernel exposes some possible
candidates:


void
AddComponentWithExtendedProperties(String key, Type classType, IDictionary extendedProperties);

void
AddComponentWithExtendedProperties(String key, Type serviceType, Type classType, IDictionary extendedProperties);




So you experiment with them, but supplying the dictionary of
extended properties does nothing... hmm... time to file a bug
report? well no... extended properties having nothing to do with
satisfying parameter or property dependencies on your component -
not directly at least.



So why don't we just create the component ourselves.. and then
add it to the container?



Well you can, via the Kernel.AddComponentInstance method
but you're going to miss out on some things... for instance the
startable facility won't be "concerned" with your component, and
as such if it implements IStartable it won't get started
and stopped... Though I haven't confirmed this, I dont think the
container will bother to dispose of any IDisposable
components registered in this fashion either... the container
doesn't consider itself the owner of the component (and generally
this is what we want).



So we're going to have to get a little more intimate with the
container implementation ... so every time a component is
registered in the container a corresponding ComponentModel
is generated for the component, this basically keeps track of
the:
  • Components dependencies
  • Constructor candidates

  • Parameters (sounds like us...)
  • Name, implementation type and service type.
  • Lifecycle, Lifestyle...
  • And some other stuff you can discover for yourself.

Now we could get heavy handed and jump into contributing to
the construction of the component model itself... but it's pretty
uncessary, we just want to tweak the end result... so we can use
an event handler on the Kernel -
ComponentModelCreated.



So here we have an implementation that solves our problems...
This is being implemented inside a facility, but you could do
this anywhere... wire it up in your custom container that's
derived from WindsorContainer maybe, obviously you want to
remove the if statement for checking the Implemenation type is
Base4Host though. :)


private const string AdditionalParametersKey =
"AdditionalParameters";

 

private void
Kernel_ComponentModelCreated(Castle.Core.ComponentModel model)

{

    if
(model.Implementation == typeof(Base4Host))

    {

        if ((model.Configuration ==
null)

           
&&
model.ExtendedProperties.Contains(AdditionalParametersKey))

        {

           
Dictionarystring, object> additionalParameters =
(Dictionarystring, object>)model.ExtendedProperties[AdditionalParametersKey];

           
foreach (string parameterName in additionalParameters.Keys)

            {

           
    model.Parameters.Add(parameterName,
Convert.ToString(additionalParameters[parameterName]));

            }

        }

    }

}

 

protected override void Init()

{

    Kernel.ComponentModelCreated +=
new ComponentModelDelegate(Kernel_ComponentModelCreated);

}




Now I can register my component by doing something like
this:


Dictionarystring, object> additionalParameters =
new Dictionarystring, object>();

additionalParameters.Add("appName", _applicationName);

additionalParameters.Add("port", _port);

additionalParameters.Add("root", _baseDirectory);

 

Hashtable properties =
new Hashtable();

properties.Add(AdditionalParametersKey,
additionalParameters);

 

Kernel.AddComponentWithProperties("base4.defaultHost", typeof(Base4Host), properties);




Here we're passing all our additional parameters as a
Dictionary inside our
IDictionary of additional properties....  this isn't
the most elegant implementation, but this is all code internal to
a single facility so it's not really important to me... and it
gets the job done just fine.





Read More