ADVANCED-DOTNET is being retired...

Unfortunately the old ADVANCED-DOTNET
mailing list at DevelopMentor is being put down,
like an old but still on the odd occasion faithful dog. This
would be one of the first .Net mailing lists I ever really
latched onto (about 6 years ago...) and there have been some
pretty bright sparks on their since day one.

Hi all

We are currently undertaking an infrastructure review at DevelopMentor and
have realised that apart from this one list the listserv is not really used
any more. Unfortunately we cannot really justify maintaining the server for
this one list and so we have decided to retire the listserv.

I created this list as a moderated list six and a half years ago and so feel
a bit sad to see its passing, but the world has moved on from mail
reflectors to blogs, web forums and other discussion mediums.

We will be taking the server offline on the 30th September so you have a bit
of time to get anything you need from the archives

Thanks for your involvement over the last few years

Richard Blewett
CTO
DevelopMentor


I think what's more disappointing is that in turning it off they
certainly haven't spent much time thinking about an exit plan,
because there's no archive availability (the listserv is getting
turned off completely) or alternative place identified for list
participants to move to... I often think this is something that
needs to be thought about up front (and budgeted for, 
almost in some separate trust fund) especially as communities and
social platforms proliferate - it's a shame to see information
evaporate.

That said it looks like some of the long time readers of the
group are working to migrate the server away from develop mentor,
or to move onto this google
group
- be interesting to see where this goes.

On a side note I wonder how much sites like stack overflow will errode
the last remnants of mail-only technical mailing lists...
personally (while I've been beta testing it) I've found the stack
overflow concept doesn't really gel with me - but I can see it's
appeal to others - personally I prefer discussion over problem
"resolution" and the ability for a group to collectively choose
not to answer a problem (because it's but 2 clicks away on a
simple google search) - where as with the reputation system in
Stack overflow the simple/dumb/obvious questions are like crack
for the reputation kidies. 

On the same note, how much will stack overflow and similar
concepts errode organic blog discovery (which is normally while
someone is trying to find an answer to a question).... hmmm

Read More

Choice is good - another OAuth library for .Net emerges

You may recall a few months back I released an  OAuth library for .Net (which can be found here on google code) - at the time of writing that library the only other OAuth "solution" for .Net developers was a C# file containing some simple helper functions, that didn't even produce valid results in many cases, and the rather basic implementation as part of the restful chess/myspace example.

Well the guys at Madgex in the UK have now released their own OAuth.Net library.. for more details you can:


As for differences between the two implementations... from a 50K foot glance.
  • There's a dependency on the Windsor container when using the Madgex library (if you want to use it's out the box implementation / configuration examples etc.)
  • The Madgex library includes a http module for making a provider implementation easier when building web apps.
  • The madgex library appears to take a harder dependency on HttpRequest then the DevDefined library (but that's just a hunch, saw it in a few interface definitions, rather then some wrapper equivalent).
  • The madgex library looks a little more polished (i.e. xml docs) and has a configuration section.
  • The Madgex library features some niceities like Sliding window validation support (i.e. they only allow messages to be supplied where the timestamp falls within a certain time window of the server, and keep the list of previous nonces only for the
    period of that window - flushing nonces that are not longer required via a background thread - saving on the volume of nonces to record i.e. for replay attacks).  Of course it's an in-memory solution, so not suited to farms, but still cool.
  • Slightly less fluent consumer implementation, I prefer my libraries consumer implementation, but of course that's just me :P
  • Both libraries are under the MIT license.


All said and done it's a very sound effort, great work guys!

And it's awesome to have some choice emerging in this space.

 

Read More

Avoiding strings in your Windsor fluent config

As a brief follow up to my  last post here I thought I'd quickly post about something I've
been doing lately with my own  windsor configurations, which is pretty minor - but saves me a little grief when it comes to refactoring etc.

Basically I have this extension method:

public static ComponentRegistration<> RegisterTransient(this IWindsorContainer container, ComponentRegistration registration)
{
container.Register(registration.LifeStyle.Transient);
return registration;
}

Which then lets me do this:
var serviceA = container.RegisterTransient(Component.For() .ImplementedBy());var serviceB = container.RegisterTransient(Component.For() .ImplementedBy());

container.Register(Component.For().Named("service.staff")
.ImplementedBy().ServiceOverrides(ServiceOverride
.ForKey("Repositories").Eq(serviceB.Name, serviceA.Name)));

var staffService = (StaffService)container.Resolve();

Assert.IsType(staffService.Repositories[0]);
Assert.IsType(staffService.Repositories[1]);


notice the lack of strings when registering service overrides... it's a minor thing, but I find it quite handy... plus it generally makes it easier to identify the lifestyle of the components being registered because it's a little more in your face, i.e. your making an explicit decision... though anywhere that lifestyle poses a risk you should obviously be writing some unit tests to verify your getting the expected behavior when resolving that service
anyway.

Also, while looking at ComponentRegistration -the other nice thing about the fluent component registration is it works quite well for add-ons that introduce their own services which aren't loaded into a seperate app domain or child kernel ...

Just give the add-in an installation "helper" which only exposes a method taking a ComponentRegistration for registering the component... you can then defer when those services are actually registered in the kernel, and can use the names of the components or other info to unregister them if the add-in is turned off (obviously this is a rainy day scenario and there are problems with this approach, but so far I've found it to work quite well).

Read More

Service overrides when using Windsor Fluent Component Registration

If you recall when configuring the container via xml you can do a
service override like so:




service="Namespace.IEmailSender, AssemblyName"
type="Namespace.SmtpMailSender, AssemblyName" />


service="Namespace.IEmailSender, AssemblyName"
type="Namespace.SendMailEmailSender, AssemblyName" />


type="Namespace.NewsLetterSenderService, AssemblyName">

${smtp.sender}


Check out the documentation on the
castle site
for some more details.

I recently got an email question around how to do this with the
fluent interface - unfortunately with the XML, Binsor and Fluent
interfaces all being used for registering and configuring the
MicroKernel/Windsor Container the documentation is a little patchy
across all three (with XML of course having the best coverage) - so
here's an example of service override for the fluent
interface.

First off the various services we'll be wiring up in this
example.

public interface IStaffService
{
}

public class StaffService : IStaffService
{
public IStaffRepository Repository { get; set; }
}

public interface IStaffRepository
{
}

public class StaffRepositoryA : IStaffRepository
{
}

public class StaffRepositoryB : IStaffRepository
{
}


And now the actual tests..
public class ServiceOverrideTests
{
private WindsorContainer container;

public ServiceOverrideTests()
{
container = new WindsorContainer();
container.Register(Component.For().Named("repository.staff.a").ImplementedBy().LifeStyle.Transient);
container.Register(Component.For().Named("repository.staff.b").ImplementedBy().LifeStyle.Transient);
}

[Fact]
public void ByDefaultStaffServiceWiredUpToFirstServiceRegistered()
{
container.Register(Component.For().Named("service.staff").ImplementedBy().LifeStyle.Transient);

var staffService = (StaffService)container.Resolve();

Assert.IsType(staffService.Repository);
}

[Fact]
public void WithServiceOverrideCanPickImplmentationByKey()
{
container.Register(Component.For().Named("service.staff").ImplementedBy()
.ServiceOverrides(ServiceOverride.ForKey("Repository").Eq("repository.staff.b")).LifeStyle.Transient);

var staffService = (StaffService)container.Resolve();

Assert.IsType(staffService.Repository);
}
}


With
.ServiceOverrides(ServiceOverride.ForKey("Repository").Eq("repository.staff.b"))
being the code we're interested in... obviously if it was a
constructor override we'd be using the name of the parameter in the
constructor.

The Eq method can also take of an array of strings... which,
you guessed it, means we can handle arrays of services as well ...
which can be quite handy if order is important to some kind of
service you're building where there are multiple contributors or
some form of pipeline, lets take a look at that:

public class StaffService : IStaffService
{
public IStaffRepository[] Repositories { get; set; } // <- is="" now="" an="" array="" of="" staff="">
}

And the associated test - notice we just pass in a list of the
service names...
[Fact]
public void WithServiceOverrideCanPickImplmentationByKey()
{
container.Register(Component.For().Named("service.staff").ImplementedBy()
.ServiceOverrides(ServiceOverride.ForKey("Repositories").Eq("repository.staff.b", "repository.staff.a")).LifeStyle.Transient);

var staffService = (StaffService)container.Resolve();

Assert.IsType(staffService.Repositories[0]);
Assert.IsType(staffService.Repositories[1]);
}


Hopefully this proves useful to Jason (who sent me the email) and
anyone else who's getting started with windsor and strugling a
little to setup their container.
Read More

Castle Windsor: Generic Decorators and run-time parameters

So I received a question recently via email from someone following the container tutorials, which read like so:

Read through you tutorials and great work!

Have a question for you though, that I can't seem to find an answer in google. On decorators. How do you provide state dependencies that are unknown at configuration time?

So I ask for an IRepository and I have configuration setup to wrap it in a IValidator and maybe an ISecurity. However, ISecurity has a dependency on a runtime determined role (say from multiple sources, possibly including a state value on IWidget) and the user id (for argument sake isn't available on the context).

I want to call T Get() on IRepository. How do you get it all setup?

Many Thanks!


As I see it there were two distinct questions asked:
  • How to wire up generic decorator chains (though I suspect they already know how to do that).
  • How to pass in parameters/dependencies at run time.


So Let's look at doing these two things, I'm going to steer clear of xml configuration because that's so 2 years ago ;o)

First off let's create the repository interface:

public interface IRepository
where T : class, new()
{
T Get(int id);
}


Then the root implementation (we can't keep chaining forever, at some point we have to hit an implementation which can actually return the results we want).
public class StubRepository : IRepository
where T : class, new()
{
public T Get(int id)
{
return new T();
}
}


And finally a decorator for "security"...
public class SecurityDecorator : IRepository
where T : class, new()
{
private readonly IRepository _inner;

public SecurityDecorator(IRepository inner)
{
_inner = inner;
}

public T Get(int id)
{
return _inner.Get(id);
}
}


better have a widget too... for good measure:
public class Widget
{

}


At this point we can write a test - I'm an xUnit fanboy these days (typing less == good) so let's take a look:

public class ContainerTests
{
private readonly IWindsorContainer container;

public ContainerTests()
{
container = new WindsorContainer();
container.Register(Component.For(typeof (IRepository<>)).ImplementedBy(typeof (SecurityDecorator<>)));
container.Register(Component.For(typeof (IRepository<>)).ImplementedBy(typeof (StubRepository<>)));
}

[Fact]
public void GetRepository_ForWidget_ReturnsSecurityDecoratorOfTypeWidget()
{
var widgetRepository = container.Resolve<>>();
Assert.True(widgetRepository is SecurityDecorator);
}
}

Notice we register the components in top to bottom order i.e. decorators first, followed by the underlying implementation, for something as simple as this you don't really need to use the fluent interface for registering components - but I find it's good to be consistent.

Now, the second question is about injecting "context" - this is really just another way of saying "some of my dependencies can't be known until just before I attempt to resolve the service" ... no problem... so let's make some modifications:

First off I'm going to make a user...

public interface IUser
{

}


Next thing I'm going to do is add a User property to my security context (ugh, this seems like a better job for some kind of "ICurrentUserHolder" service, but that's beside the point).
public class SecurityDecorator : IRepository
where T : class, new()
{
private readonly IRepository _inner;

public SecurityDecorator(IRepository inner)
{
_inner = inner;
}

public T Get(int id)
{
return _inner.Get(id);
}

public IUser User { get; set; } // <-- the="" current="">
}


Now let's add another test to ensure everything is being injected properly...
public class ContainerTests
{
private readonly IWindsorContainer container;
private readonly IUser user = MockRepository.GenerateStub();

public ContainerTests()
{
container = new WindsorContainer();
container.Register(Component.For(typeof (IRepository<>)).ImplementedBy(typeof (SecurityDecorator<>)));
container.Register(Component.For(typeof (IRepository<>)).ImplementedBy(typeof (StubRepository<>)));
}

[Fact]
public void GetRepository_ForWidget_ReturnsSecurityDecoratorOfTypeWidget()
{
var widgetRepository = container.Resolve<>>();
Assert.True(widgetRepository is SecurityDecorator);
}

[Fact]
public void GetRepository_ForWidget_WhenSupplyingUserInjectsUserIntoSecurityRepository()
{
var securityDecoratorForWidget = (SecurityDecorator) container.Resolve<>>(new {User = user});
Assert.Same(user, securityDecoratorForWidget.User);
}
}


Notice the additional argument of an anonymous class being passed to Resolve, this allows us to provide additional parameter dependencies (in this case a stub user is being supplied).

Finally what about passing in some roles... this is much of the same, but I'll include it for completeness... so we add a role interface:

public interface IRole
{
bool IsMember(IUser user);
}


Then we'll add a collection of roles to the decorator and provide a rather primitive check against the roles when attempting to get a widget instance:
public class SecurityDecorator : IRepository
where T : class, new()
{
private readonly IRepository _inner;

public SecurityDecorator(IRepository inner)
{
_inner = inner;
}

public T Get(int id)
{
CheckPermission();
return _inner.Get(id);
}

public IUser User { get; set; }

public IList Roles { get; set; } // <-- the="" roles="" to="">

private void CheckPermission()
{
if (User == null || Roles == null) return;
if (Roles.Any(role => !role.IsMember(User)))
{
throw new Exception("You do not have permission");
}
}
}


And finally we update our test with checks for both passing and failing on the permissions check.
public class ContainerTests
{
private readonly IWindsorContainer container;
private readonly IUser user = MockRepository.GenerateStub();
private readonly IRole failingRole = MockRepository.GenerateStub();
private readonly IRole passingRole = MockRepository.GenerateStub();

public ContainerTests()
{
container = new WindsorContainer();
container.Register(Component.For(typeof (IRepository<>)).ImplementedBy(typeof (SecurityDecorator<>)));
container.Register(Component.For(typeof (IRepository<>)).ImplementedBy(typeof (StubRepository<>)));
passingRole.Stub(stub => stub.IsMember(user)).Return(true);
}

[Fact]
public void GetRepository_ForWidget_ReturnsSecurityDecoratorOfTypeWidget()
{
var widgetRepository = container.Resolve<>>();
Assert.True(widgetRepository is SecurityDecorator);
}

[Fact]
public void GetRepository_ForWidget_WhenSupplyingUserInjectsUserIntoSecurityRepository()
{
var securityDecoratorForWidget = (SecurityDecorator) container.Resolve<>>(new {User = user});
Assert.Same(user, securityDecoratorForWidget.User);
}

[Fact]
public void Get_ForWidgetWhenUserMatchesAllRoles_ReturnsWidget()
{
var securityDecoratorForWidget = (SecurityDecorator) container.Resolve<>>(new {User = user, Roles = new List {passingRole}});
Assert.NotNull(securityDecoratorForWidget.Get(1));
}

[Fact]
public void Get_ForWidgetWhenUserDoesNotMatchAllRoles_ThrowsException()
{
var securityDecoratorForWidget = (SecurityDecorator) container.Resolve<>>(new {User = user, Roles = new List {passingRole, failingRole}});
var exception = Assert.Throws(() => securityDecoratorForWidget.Get(1));
Assert.Equal("You do not have permission", exception.Message);
}
}



And that's it... could not be simpler.
Read More