Archive for the ‘Castle’ category

Fantastic Friday – Links, thoughts and more…!

December 4th, 2009

Happy Friday to you  :)   I’m looking forward to my employer’s (Strategic Data Systems) Christmas party tommorow night.  It’s always a fun time.

SquareUp by Twitter

http://squareup.com/
Twitter founder formally unveils ‘Square’ project  – this is pretty cool I think – the ability to have “mobile-payments”.  

Here is a description:

The Square hardware is a small, inexpensive card reader that plugs into the audio jack of a compatible device, including a mobile phone (it’s starting with the iPhone and currently has job postings up for BlackBerry and Android engineers). It processes credit card payments, geotags their locations on a map, and e-mails a receipt to the buyer.

I think it’s a great idea – pretty cool stuff. 

Visual NHibernate Beta

At first I thought this might be ‘free’  :)   But it’s not.  However, I must say, it’s looking very nice.  Based on some NH google lists the developer(s) are very responsive to adding features and bug fixes.  That was good to see.  One of the ‘complaints’ that I hear sometimes about NHibernate (vs. like EF, L2S, or commercial ORMs) is that it’s complex to get up and running if your not familiar with how mapping files, etc… work.   So Visual NHibernate provides a visual designer and mapping tool for creating and editing NHibernate projects.

Ryan Cromwell – Castle Windsor

Not sure if I blogged on this before (yeah… I know I can search…) but I really like working with Castle Windsor’s Inversion of control container.  Ryan Cromwell (fellow contractor at Strategic Data Systems) provides a couple of good blog posts on it’s usage.  I was recently asked about factory facility for Windsor, and I was able to refer that person to Ryan’s post (see ‘Injecting WCF Channel as Dependency..’ below)

Strategy Pattern with Castle Windsor (he includes a sample project – thanks Ryan!)

Registering WPF “Views” with Windsor Fluent API

Injecting a WCF Channel as Dependency via Windsor – this shows off the Factory facility for Windsor.

By the way – a plug for Ryan:  He is our TFS specialist and can help setup, provide guidance, etc… for TFS.  If your looking for someone to do that for you – he is definitely the man to get!  I should add, he is a heck of a WPF programmer as well – he does some really fine work!

MVC Turbine – Plugin for ASP.NET MVC

http://mvcturbine.codeplex.com/

From CodePlex:

MVC Turbine is a plugin for ASP.NET MVC that has IoC baked in and auto-wires controllers, binders, view engines, http modules, etc. that reside within your application. Thus you worry more about what your application should do, rather than how it should do it.

This is very good to see from my perspective.  One of the features I really enjoyed while experimenting with Grails was how easy it was to have everything injected under the covers without needing to get into the weeds (in Grails case – Spring).  MVC Turbine offers this same functionality for the ASP.NET MVC programming.

Turbine is not exclusive to a particular IoC container.  Here is a feature list:

Features

  • Visual Studio 2008 Solution Templates for IoCs
    • Ninject
    • Castle Windsor
    • StructureMap
    • Unity
  • New runtime framework that allows extensibility
    • Blades (components) that are auto-registered and loaded at runtime.
    • Introduced the Core Blades to setup the basic runtime of an MVC application:
      • MvcBlade — wiring for MVC related components (Controllers, View Engines, etc).
      • WebBlade — wiring for System.Web components (IHttpModule, etc.).
      • RoutingBlade — wiring for the IRouteConfigurator implementation.
    • RotorContext that works with the Blades to setup the runtime.
  • Auto-registration of View Engines (VE)
  • Auto-registratrion of MVC Filters to support constructor injection.
    • Added new InjectableFilter attribute to associate a filter to an action.
    • Added support for IActionFilter, IAuthorizationFilter, IErrorFilter and IResultFilter
  • InferredViewResult handles inferred actions and reports HTTP 404 for missing actions.
  • Works with ASP.NET MVC in Mono

 

Service Orientation Requires Data Orientation

More and more the conversations are around SOA.  This one article at InfoQ stuck out to me regarding ‘service data’

Most of today’s SOA literature and implementations concentrate on defining business aligned services and rarely discuss the role and impact enterprise data has in the context of SOA

 

How to Uninstall – or make Message Stop loading up on Windows 7?

How to uninstall/remove Messenger on Windows 7 ?    My dad just got a new computer with Windows 7.  Anytime he starts it up, it wants him to sign in to Messenger.  He doesn’t use Messenger, and doesn’t want to use Messenger. 

What I find irritating is there isn’t any ‘don’t show this on startup’ or ‘turn this off’ within the Messenger pop-up.  At best you have to go out to the internet and start looking for hacks or ways to turn this off.

Microsoft – I don’t mind if you want to promote your own chat program in your OS, but please be kind enough to make it easy to turn off for non-computer expert users. 

Caliburn SL Nav Walkthrough/Intro

I’ve blogged in the past regarding ‘Caliburn’ by Rob Eisenberg.  Just a reminder:

Designed to aid in the development of WPF and Silverlight applications, Caliburn implements a variety of UI patterns for solving real-world problems. Patterns that are enabled by the framework include MVC, MVP, Presentation Model (MVVM), Commands and Application Controller.

Rob is in the process of ‘releasing various starter kits/samples for Caliburn’.  His first sample just recently released is :

Silverlight Navigation Walkthrough

Using jQuery to Scroll Just in Time for Paging Records..like Bing

Rob Conery blogs about using jQuery to scroll down a list of records with ‘just in time scrolling’ for paging.  Pretty cool – I have seen this feature used in different application.  I suspect this will become the defacto standard in paging lists.  Check out his how to here.

TFS Offline

Quote of the day… ‘Don’t work offline’.  I’ll keep the source of that quote unnamed, but I did think it was rather funny.  I hope TFS improves it’s offline capabilities.  This is very reminiscent of Visual SourceSafe – which I really didn’t like much.  SVN, Git, etc… all have pretty good offline capabilities.   While we are at it – I do hope TFS also integrates with explorer so if you edit a file outside of studio that it picks it up.  (Maybe you can, but I haven’t seen it).

UPDATE  I’ve been corrected that TFS does provide explorer integration with the  TFS power tools.

(My only response though… I was told this has been around since 2005… seems almost 5 years later this would be an installation option for TFS for Visual Studio ?  Guess you just have ‘know’ this is available – lol)

Google Docs

I am setting up my ‘Google’ realm of Wave, Gmail, Docs, Reader, etc… so far… I’m loving it.  Just recently I received an email with Excel spreadsheet.  Opened it up in Gmail, which prompted to use Google docs !  Worked out great.  And to share that document with my wife, I didn’t have to forward that document around.  Just share it exclusively to her.  All stored up securely on the Google cloud.

I did notice in the Excel to Google Doc conversion that lookups aren’t exactly the same, so it didn’t properly convert the lookup lists.  I hope they fix that.   I really see the world approaching of using this approach more and more.   With the cloud storage, feature rich word processor, spreadsheet and slide creation capability… who needs an expensive desktop copy of Office!

Steve’s Final ‘Thoughts of the Day’ – (or rather ‘Stirring the ORM Pot in the .NET world…’)

Douglass Starnes has a series on different data model approaches with asp.net mvc, showing how to setup them up and use them.

In part II of the series he makes this comment: 

In the ASP.NET MVC space I see three ORMs being used most commonly.  By far the favorite outside of Microsoft is NHibernate.  Inside of Microsoft there are two competing offerings: LINQ to SQL and Entity Framework.

This view/perspective – is it a correct one ?  Is Microsoft competing against NHibernate OSS .NET projects created by it’s own community ?  Or is Microsoft just giving more options ?  Microsoft doesn’t need to include NHibernate in any of it’s products – too many legal traps I’m sure.  What if it didn’t create it’s own ORM and merely demo’d features using NHibernate in it’s examples ?  I’m all for competition to make products better, but in this case, is MS having 2 ORM’s that are catching up in functionality, but still lagging behind NHibernate and other .NET ORM’s in the market a wise thing ?  Is that how you see it ?  I went to use EF in a project, but because it didn’t handle an ‘append only’ with ‘hilo’ id generation – and because it wasn’t poco based – where the entities are the domain objects – it was finally deemed impossible to use.  Meanwhile, we prototyped NHibernate and were able to implement everything needed in the Legacy system.  Personally, I want to pick the best of breed, not pick something just because of ‘who’ makes it.  

I don’t want to distract from his series, but that comment seems to be a prevailing one in the .net community.   What I wonder is ‘doesn’t Microsoft understand that is how it will be perceived’ – and if so… is their position to outdo the products, or do they consider this a core piece of the .NET framework to provide ORM solutions ?

I keep pointing to jQuery and ASP.NET MVC – they provide jQuery in the project templates for ASP.NET MVC.   How does that compare to including NHibernate support – or even just promoting it without including it ? 

Personally I can think of 3 examples of where they could make a difference:

1. Provide a Linq provider just like they did for EF and L2S (yes, there are Nhibernate linq providers in work – there is a basic one available now)

2. Provide a NHibernate DomainService out of the box for RIA.NET

3. Provide support for NHibernate out of the box for ADO.NET Data Services.

All three could be extensions that are referenced but included in each release.

Craftsmanship Dilemma:

Last thought… I was told to just ‘get something done’ basically… hack it.  No tests, no real design, just get it done now.  Do you think that is ok ?  How does that compare to craftsmanship ?  I don’t think I have to craft the perfect 100% solution, but how it gets built – ie. with a test, with some design/OO principles in place – shouldn’t we push back a bit to not just create ‘junk’ ?  I am noticing this trend in many industries.  Just ‘build the car’, doesn’t have to last, we need it cheap and now to compete.  At what point does quality matter ?  How would you feel if the rollercoaster your going to ride is built with that mentality?  Or the bridge ?  Or the airplane ?  Or how about the breaks on your car?  Why isn’t software engineers able to defend their craft in these situations ?  I guess it’s all about the $$$  ?  There is ‘agile’ … then there is ‘craftsmanship’…

 

Well, that is enough for the day – everyone have a great weekend!

Windor WCF Integration…bump!

February 21st, 2009

Mike Hadlow’s blog has a great writeup on using Castle Windsor with WCF.

http://mikehadlow.blogspot.com/2008/11/windsor-wcf-integration.html

Also included is information on using WCF with Windsor/NHibernate:

http://mikehadlow.blogspot.com/2009/02/wcf-windsor-integration-using.html

I followed his advice, pulled down his sample code, and was quickly able to implement in my WCF services.  Thanks Mike!

Fluent Interface – Programmatically Registering with Windsor

December 1st, 2008

Castle Windsor is my ‘favorite’ IOC – as it offers quite a bit of functionality, and it’s fairly easy to understand and setup.  Let’s review how to programmatically add components to the container.

By default the registration of components is all done via xml configuration files.  However, Castle Windsor does support programmatic registration of components to the container.  Why would you do this?  Well, one example is where I register components in ‘one fell swoop’ that exist in an assembly, making it completely hands off when adding a new component.  Due to the autowiring nature of Windsor, most of the work is done by the container.  Let’s look at an example:

ie. I have an assembly with my ‘services’ and assembly with my ‘dao’s’.  

The flow is:  My controller uses ‘service(s)’.  My services uses dao(s).

Controller => Service Layer => Dao/Repository Layer

I’ll pseudo code this:

//The controller

public class EmployeeController
{
   private readly IEmployeeService EmployeeService;
 
  public EmployeeController(IEmployeeService EmployeeService)
  {
        this.EmployeeService = EmployeeService;
  }

  public ActionResult SaveEmployee(string id)
  {
       Employee employee = EmployeeService.GetEmployeeById(id);
       employee.FirstName = ….
       EmployeeService.SaveEmployee(employee);
       return ….
  }

}

//The Service:

public class EmployeeService : IEmployeeService
{
   private readly IEmployeeDao EmployeeDao;
 
  public EmployeeService(IEmployeeDao EmployeeDao)
  {
        this.EmployeeDao= EmployeeDao;
  }

  public void SaveEmployee(Employee employee)
  {
     using(ITransaction trans = …BeginTransaction())
     {
         EmployeeDao.Save(employee);
         trans.Commit();
         …
     }
  }
}

//The Dao:

public class EmployeeDao : Dao<T>
{
      …. Save(T entity)…
}

So we have our tiered environment, the controller passes off the employee object ‘stuff’ to the service.  The service handles the transactional aspects, etc… and calls the underlying Dao database calls.  The beauty here, it’s all constructor injection, no ‘new object’ etc…

So, along comes Castle Windsor.  If you noticed, I’m using a controller with action result – that is from asp.net mvc.  The MvcContrib contains code to register the controllers with the container, which can be accomplished in three lines of code in the startup of the application (Global.cs):

IWindsorContainer _container = new WindsorContainer();
ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(_container));
_container.RegisterControllers(Assembly.Load("Bistro.Controllers"));

After that we can register the services and daos:
ie.

_container.Register(
                        AllTypes.Pick().FromAssemblyNamed("Services")
                        .Configure(c => c.LifeStyle.Transient)
                        .If(s => s.Name.Contains("Service"))
                        .WithService.FirstInterface()
                    );

This fluent interface sample will look at each type in the Service assembly, were name contains ‘service’, and then add the interface.  (This does require a bit of naming convention on my part, ie. EmployeeService : IEmployeeService  – ‘service’ in the name, however, I do like that if I want to exclude something it can be done quite easily)

The registration of the dao is similiar to above.

_container.Register(
                        AllTypes.Pick().FromAssemblyNamed("Dao")
                        .Configure(c => c.LifeStyle.Transient)
                        .If(s => s.Name.Contains("Dao"))
                        .WithService.FirstInterface()
                    );

So, I’ve registered all the controllers, all the services, and all the daos.  They are autowired by Windsor, meaning, I don’t have to hand by hand register each type with instructions on who uses what – it uses reflection to handle that – seeing for example, that I have a IEmployeeService being injected – so look for that type in the container and create a new one on my behalf.

The last example is : what about the facilities ?  ie. Castle Windsor has great support for EventWiring:

http://www.castleproject.org/container/facilities/trunk/eventwiring/index.html

And a great sample by Hammett:

http://hammett.castleproject.org/?p=115

The beauty of this is that you can register your subscribers in the container!  I think it’s fanatastic

We’ll take a similiar example to what Hammett uses.

ie. in my sample (read Hammett’s blog), WITHOUT Windsor, we’d have to code up all the registrations, etc…:

INotificationService notification = new DefaultNotificationService();

//subscribers
SuccessSubscriber subscriber1 = new SuccessSubscriber();
FailedSubscriber subscriber2 = new FailedSubscriber();

//subscribing
notification.Succeeded += new NotificationHandler(subscriber1.OnSuccess);
notification.Failed += new ErrorNotificationHandler(subscriber2.OnFailure);

TheService service = new TheService(notification);

//use the app:
service.DoService();

Let’s see what is would be like with Castle Windsor and a configuration file:

Here is my config file that we will convert to the fluent registration:

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

    <configSections>
        <section
            name="castle"
            type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor" />
    </configSections>

    <castle>
        <facilities>

            <facility id="event.wiring"
                      type="Castle.Facilities.EventWiring.EventWiringFacility, Castle.MicroKernel" />

        </facilities>
        <components>

            <!– Subscribers –>

            <component id="SuccessSubscriber"
                       type="MyEventSample.SuccessSubscriber, MyEventSample" />
      <component id="FailedSubscriber"
                       type="MyEventSample.FailedSubscriber, MyEventSample" />

            <!– Notification service –>

            <component id="notification.service"
                       service="MyEventSample.INotificationService, MyEventSample"
                       type="MyEventSample.DefaultNotificationService, MyEventSample" >
                <subscribers>
                    <subscriber id="SuccessSubscriber"
                                event="Succeeded"
                                handler="OnSuccess"/>
                    <subscriber id="FailedSubscriber"
                                event="Failed"
                                handler="OnFailure"/>
                </subscribers>
            </component>

            <!– Services –>

            <component id="TheService"
                       type="MyEventSample.TheService, MyEventSample" />

        </components>
    </castle>
</configuration>

So, we tell Castle about the facility.  We add our components that are being used.  Then we add our subscribers in the notification service:

WindsorContainer container = new WindsorContainer(new XmlInterpreter(new ConfigResource()));

TheService service = container.Resolve<TheService>();
service.DoService();

That is excellent – in 3 lines of code, we have all our subscribers wired up, etc… In this example, we are telling the container to read the configuration file above.

But what if, we want to dynamically register these components, without the xml (the point of the blog post – lol) ?

We do so using the fluent interfaces – with special attention given to ‘how to register a facility’:

Here is the code:

IWindsorContainer container = new WindsorContainer();
            container.AddFacility<EventWiringFacility>();
            container.AddComponent<SuccessSubscriber>("SuccessSubscriber");
            container.AddComponent<FailedSubscriber>("FailedSubscriber");
            container.AddComponent<TheService>("TheService");
            container.Register(Component.For<INotificationService>()
                .ImplementedBy<DefaultNotificationService>()
                    .Configuration(Child.ForName("subscribers")
                                         .Eq(
                                                Child.ForName("subscriber").Eq(
                                                    Attrib.ForName("id").Eq("SuccessSubscriber"),
                                                    Attrib.ForName("event").Eq("Succeeded"),
                                                    Attrib.ForName("handler").Eq("OnSuccess")
                                                ),
                                                Child.ForName("subscriber").Eq(
                                                    Attrib.ForName("id").Eq("FailedSubscriber"),
                                                    Attrib.ForName("event").Eq("Failed"),
                                                    Attrib.ForName("handler").Eq("OnFailure")
                                                )
                                         )
                                   )
                              );

Then it is used the same way as above:

TheService service = container.Resolve<TheService>();
service.DoService();

With some imagination, you can see how easy it would be to register all subscribers in an assembly, all services in a assembly, then wire them all up dynamically.

(To see how I did the facility you can look at this test)

So in summary, you can add items to the config, and read it.  Or you can dynamically add them in code.  It is possible as well to mix the two.  I initially did this, where I load the config with the subscriber information, then add in my components programmatically.

I hope this helps, if anyone would like some sample code to go along with this, I can provide it – just let me know. 

ASP.NET MVC – Castle Binders from MvcContrib

November 10th, 2008

Unfortunately, there is no wiki documentation, etc… on the Castle Binders in the MvcContrib.  So I thought I’d hop in and write up a sample for anyone else interested in using these binders:

First, for some background information from the Castle website : http://www.castleproject.org/monorail/documentation/trunk/usersguide/smartcontroller.html

These binders were originally created for Monorail, and outside of a few items, most of that documentation applies to using with MvcContrib.

I’m using the latest MvcContrib from the trunk (SVN) at :

http://mvccontrib.googlecode.com/svn/trunk

After building the MvcContrib, there assemblies referenced are from:

trunk\src\MvcContrib.Castle\bin\Release (I just added them all to a new Mvc project)

(I’ll include the source here if you just want to download and try it)

The goal of the binders is to provide the ability to include a strongly typed object as the recipient to a form post to an action.  As described in the document above, the default would be:

ie.

Person person = new Person();
person.FirstName = Request.Form[“FirstName”];

Step One: Create Controller implementing the ICastleBindingContainer interface

image

Step Two : Create Actions to handle the Form post

image

(note: the HttpVerbs allow you to specify one named Action – for different uses: the Get is for the form load, the Post is for the form post)

The post action of BindersView takes a ‘Person’ object.   We use the ‘CastleBind’ attribute to specify the binding.

There are a few optional parameters with the CastleBind: The prefix to use, and the Exclude option. 

image

This allows you to specify a prefix of any name in the form itself (I show form next).  The exclude allows for properties to not be included in the post request.

(For example, if you have a sensitive property of Person, ie. social security – you can exclude it from the binding)

Step Three : The Model

image 

Step Four : The Form

Let’s show the form now:

image

The first form fields represent the ‘Person’, and I’m also including form fields for the spouse to be added.

Note the ‘person.FirstName’ – the prefix is required.  Also, the Spouse object is referenced as ‘person.Spouse.FirstName’.  This will help instruct how to bind to the object.

(You can read more about this in the Castle documention  link above)

Let’s run it:

image

On save:

image

As you can see – it has bound to the person object as expected.

I hope this helps show, in a simple example, how to use the Castle Binders in MvcContrib.

(source here)