in

Nikola Malovic

.NET development and architecture
VusCode - Coding dreams since 1998

Add to Google Reader or Homepage Add to Pageflakes Subscribe in NewsGator Online Subscribe in Bloglines Add to Technorati Favorites View Nikola Malovic's profile on LinkedIn

VusCode - Coding dreams since 1998!

.NET exploration, articles, cool links, surf logs, book reviews, .net, c#, smart clients, software factories, patterns & practices, web casts and much more
  • Prism (CAL) unit testing - How to test Prism (CAL) Event Aggregator using Rhino Mocks

    I spent some time recently working with Microsoft Composite Application Guidance (A.K.A. "Prism", “CAL”) and I think it is very good platform for building composite UI by either using WPF or Silverlight.

    One of its greatest advantages is that it was done in open source manner which resulted with most of the community feedback being incorporated into lightweight, testing friendly framework. Reference implementation and samples are also good but showing only static stubs based testing which is ok but not as powerful as mocking with some mocking framework.

    My mocking framework of choice is Rhino Mocks and I am going to make couple of simple blog posts showing how to test Prism code using the Rhino Mocks in couple of typical every day scenarios.

    And that leads us to today’s blog post…

    How to test Prism (CAL) EventAggregator based code using Rhino Mocks?

    imageSUT I’ll be using today will be as simple as possible to deliver the message.

    LoggingService is service which is responsible for handling the logging of system errors in a way that:

    • subscribes to system wide events which are requested to be logged without referencing the event sources
    • decides if event needs to be published (based on severity)
    • if it does, it formats the system event adding the time stamp etc
    • calls the publishing service which is handling the publishing of formatted event

    Considering the fact that in my sample we would be having various publishing services in system publishing to different targets(eventlog, flat text file) the LoggingService gets dependency injected only a component implementing the IPublishingService.

    Subscription to system wide events on a decoupled manner is possible through EventAggregator design pattern  which implementation is in Prism provided through IEventAggregator service.

    The LogErrorEvent is an event to which LoggerService would subscribe and which carries the event argument of EventData type containing the ErrorLevel and ErrorMessage data.

    Show me the code

    Enough of my blabbering (and my English), code will speak for itself much better :)

    Sample used in today's blog post can be downloaded here.

    LoggingService

    using System;
    using System.Text;
    using Microsoft.Practices.Composite.Events;
    
    namespace Example
    {
        public class LoggingService
        {
            private readonly IEventAggregator eventAggregator;
            private readonly IPublishingService publishingService;
    
            public LoggingService(IEventAggregator eventAggregator, IPublishingService publishingService)
            {
                this.eventAggregator = eventAggregator;
                this.publishingService = publishingService;
                this.eventAggregator
                    .GetEvent<LogErrorEvent>()
                    .Subscribe(this.LogIt);
            }
    
            private void LogIt(EventData eventData)
            {
                if (eventData.ErrorLevel<=100)
                    return;
    
                var stringBuilder = new StringBuilder();
                stringBuilder
                    .AppendFormat("Date:{0}", DateTime.Now)
                    .AppendLine()
                    .Append(eventData.ErrorMessage)
                    .AppendLine();
                this.publishingService.PublishError(stringBuilder.ToString());
            }
        }
    }

    Nothing fancy there:

    • constructor accepts two parameters which provide to LoggingService access to event aggregator and publishing service through inversion of controls.
    • in constructor injected event aggregator is used for subscribing of LogIt method to LogErrorEvent.
    • LogIt method is private (wouldn’t work in case of Silverlight – but that is sepa rate blog post) and does next things:
      • makes sure that only events with level greater then 100 get published
      • formats the given error message into appropriate format
      • pass the formatted message to publishing service

     

    IPublishingService, LogErrorEvent and EventData

    namespace Example
    {
        public interface IPublishingService
        {
            void PublishError(string errorMessage);
        }
    }
    
    using Microsoft.Practices.Composite.Presentation.Events;
    
    namespace Example
    {
        public class LogErrorEvent : CompositePresentationEvent
        {
            
        }
    }
    
    namespace Example
    {
        public class EventData
        {
            public int ErrorLevel { get; set; }
            public string ErrorMessage { get; set; }
        }
    }

    No need to waste time commenting this…

    Testing the code

    I could have done test first etc, but I believe that it would obfuscate the point of this blog , which now once we see the code being tested is going to be just showing the tests 

    Test 1 – How to make sure that event is getting subscribed

            /// 
            /// Shows how to verify that event aggregator subscription occurred.
            ///
            [TestMethod()]
            public void Ctor_Default_WouldSubscribeToLogErrorEvent()
            {
                // arrange
                var publishingServiceStub = MockRepository.GenerateStub<IPublishingService>();
                var eventAggregatorMock = MockRepository.GenerateStub<IEventAggregator>();
                var logErrorEvent = MockRepository.GenerateMock<LogErrorEvent>();
    
                // event aggregator get event would return mocked log error event 
                eventAggregatorMock.Stub(p => p.GetEvent<LogErrorEvent>()).Return(logErrorEvent);
                
                // expect that LogErrorEvent would be subscribed in constructor
                logErrorEvent
                    .Expect(p => p.Subscribe(null))
                    .Return(null)
                    .IgnoreArguments() // we don't care which exact method or action subscribed, just that there was some.
                    .Repeat.Once();
    
                // act
                var loggingService = new LoggingService(eventAggregatorMock, publishingServiceStub);
    
                // assert
                logErrorEvent.VerifyAllExpectations();
            }

    The test is using Rhino Mocks AAA syntax introduced in 3.5 version (if you don’t know it, read Rhino Mocks Documentation Wiki excellent documentation).

    In Arange section test:

    • defines two stubs for the services being used (stubs because I don’t care to set any expectation related to them in this test)
    • defines the mock of the event which subscription I am about to check
    • stubs the event aggregator behavior so on GetEvent<LoggErrorEvent>() method call would return event mock I created.
    • defines expectation on that event mock that subscription would occur once (IgnoreArguments() is there because this test doesn’t care really which method exactly would subscribe to event. Test cares only that subscription had occurred)

    In Act section test just constructs the service

    In Assert section test triggers verifying of the event log expectations (which in this test were: someone subscribed to this event)

    (Note that making test for verifying that the Publish have occurred during the test would be pretty much the same as this test with a change on mocked expectations only)

    Test 2a – How to invoke event aggregator in Act test section

    Sometimes there is a behavior we want to unit test which is occurring upon the event being published through IEventAggregator and because we can be using anonymous delegate, private method handling the event (case of this blog post) there is no easy way to invoke functionality which is wanted to be tested.

    This test shows how to invoke event aggregator to publish the desired event which would trigger code being tested,

    In case of this example we want to test that not severe errors (error level <= 100) are not getting published.

            /// 
            /// An example of how to trigger event aggregator in act section
            ///
            [TestMethod()]
            public void LogIt_ErrorLevel100_WouldNotBePublished()
            {
                // arrange
                var logErrorEvent = new LogErrorEvent();
                var publishingServiceMock = MockRepository.GenerateMock<IPublishingService>();
                var eventAggregatorStub = MockRepository.GenerateStub<IEventAggregator>();
    
                eventAggregatorStub.Stub(p => p.GetEvent<LogErrorEvent>()).Return(logErrorEvent);
                
                // expect that publishing service would never be called
                publishingServiceMock
                    .Expect(p => p.PublishError(Arg<string>.Is.Anything))
                    .Repeat.Never();
                
                // act
                var loggingService = new LoggingService(eventAggregatorStub, publishingServiceMock);
                
                // invoke the event aggregator
                logErrorEvent.Publish(new EventData()
                {
                    ErrorLevel = 100,
                    ErrorMessage = "Some error message"
                });
    
               // assert
                publishingServiceMock.VerifyAllExpectations();
            }

    In this test, test is having in Arrange section:

    • An instance of the log error event (not the mock of that event like in the case of previous test example)
    • Mock of the publishing service (in previous test we had stub) because that is service we need to check it won’t be called.
    • Stub of the event aggregator with stubbed GetEvent<LogErrorEvent> method
    • An expectation that PublishError method of the publishing service would never be called (regardless of the parameter being sent to that method)

    In Act section test is :

    • constructing the logging service injecting the event aggregator stub and mock of publishing service
    • invoking the Publish method on a log error event instance passing the test data (error level == 100 in this test)

    In Assert section, we are just triggering checking of expectation defined on mock of the publishing service (no call made to publish error method)

    Test 2b – How to invoke event aggregator in Act test section

    Although from perspective of this blog post it doesn’t have a lot of value here’s the test testing that publishing service will be called in case event will be published with error level greater then 100. (The more Rhino Mocks examples we have on web, the better adopting rate will be :))

    	/// 
            /// An example of how to trigger event aggregator in act section
            ///
            [TestMethod()]
            public void LogIt_ErrorLevelGreaterThen100_WouldBePublished()
            {
                // arrange
                var logErrorEvent = new LogErrorEvent();
                var publishingServiceMock = MockRepository.GenerateMock<IPublishingService>();
                var eventAggregatorStub = MockRepository.GenerateStub<IEventAggregator>();
    
                eventAggregatorStub.Stub(p => p.GetEvent<LogErrorEvent>()).Return(logErrorEvent);
    
                publishingServiceMock
                    .Expect(p => p.PublishError(Arg<string>.Matches(param => param.Contains("Some error message"))))
                    .Repeat.Once();
    
                // act
                var loggingService = new LoggingService(eventAggregatorStub, publishingServiceMock);
                logErrorEvent.Publish(new EventData()
                {
                    ErrorLevel = 101,
                    ErrorMessage = "Some error message"
                });
                // assert
                publishingServiceMock.VerifyAllExpectations();
            }

    Almost the same sample like previous one just with two small differences:

    • In arrange section, expectation is that the PublishError method would be called once with a method parameter containing “Some error message” string (inline constrains)
    • In act section, event is published with error level >100 to trigger the positive case when publishing service is been triggered

    Green is nice :)

    image

    Conclusion

    Thanks to P&P team and community feedback, CAL\PRISM event aggregator is implemented in such a way that mocking it is very easy (if not trivial) and every framework enabling easy testing is a good framework for me :) Good work P&P!

  • Microsoft Unity Auto Mocking Container?

    How to build Microsoft Unity Auto Mocking container in less then 20 minutes of work…

    I have written before in detail about Auto Mocking Containers so I’ll skip here details on what is it etc and jump to the main point of this post: implementation of auto mocking container for Microsoft Unity.

    Faced with PIA caused by constant explicit mocking of constructor dependencies (some of them not even used in my tests), I’ve tried to Google my way out by searching for Unity AMC on Codeplex, Google code etc. To my surprise that didn’t went well with best match being Roy Osherove Unity AMC container blog post which is just a nice fluent interface allowing explicit mock creation and injection on easier way. In other words, nothing automatic happening there at least not in a sense I needed it for my tests.

    I started looking for the Object builder documentation and found some for version one scattered on couple of sites. The only thing I get from that documentation was that ObjectBuilder is one complex thing and “patching it” was far away from my end design goal: quick solution.

    So, once I realized that I can not solve this on ninja way I tried “brute force” approach and in 20 minutes I had working Unity AMC.

    The idea is simple:

    • create a class specializing the UnityContainer - “AutoMockingUnityContainer”
    • override UnityContainer “Get” methods
    • wrap in try catch block every “Resolve” call
    • if ResolutionFailedException would occur using reflection find greediest constructor (with the most parameters)
    • if no constructor info available, return a mock
    • try to resolve those parameters by using AMC resolve method
    • recourse until you won’t have complete set of arguments needed (real or mocked instances) for constructing the originally requested instance

    Code explaining the above mentioned concepts is even simpler so let cut the chase and  save you from pain caused by reading more text written with “my English” ..

    “Show me the code”

    Imagine we would have a console application which is giving the answer on the meaning of the life

    using System;
    using Microsoft.Practices.Unity;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                IUnityContainer container = new UnityContainer();
                var user = container.Resolve<User>();
                Console.WriteLine(user.WhatIsTheMeaningOfTheLife());
                Console.ReadKey();
            }
        }
    }

    (Code creates UnityContainer instance and the uses it to retrieve instance of user class which WhatIsTheMeaningOfTheLife method is then shown in console output.)

    User class is implemented like this:

    namespace ConsoleApplication1
    {
        public class User
        {
            private readonly ICompanyManager companyManager;
    
            public User(ICompanyManager companyManager)
            {
                this.companyManager = companyManager;
            }
    
            public int WhatIsTheMeaningOfTheLife()
            {
                return 42;
            }
        }
    }

    (User class constructor accepts ICompanyManager parameter which BTW is totally not used in the method used in console application.)

    Although totally irrelevant for this blog post, here’s ICompanyManger class code (just not to have any secrets :)):

    namespace ConsoleApplication1
    {
        public interface ICompanyManager
        {
            void NotImportantMethod();
        }
    }

    If I would run this code as it is I would be rewarded by the nice Unity ResolutionFailedException

    Resolution of the dependency failed, type = "ConsoleApplication1.User", name = "". Exception message is: The current build operation (build key Build Key[ConsoleApplication1.User, null]) failed: The parameter companyManager could not be resolved when attempting to call constructor ConsoleApplication1.User(ConsoleApplication1.ICompanyManager companyManager). (Strategy type BuildPlanStrategy, index 3)

    Reason is pretty obvious: Unity container didn’t have any mapping defined for ICompanyManager which is required in order for user class to be required.

    AutoMockingUnityContainer

    Is just a class looking like this

    using System.Diagnostics;
    using Microsoft.Practices.Unity;
    
    namespace UnityAMC
    {
        public class AutoMockingUnityContainer  : UnityContainer
        {
            private readonly MockingHelper mockingHelper;
    
            public AutoMockingUnityContainer()
            {
                 mockingHelper = new MockingHelper(this);
            }
            
            public override object Resolve(System.Type t, string name)
            {
                try
                {
                    return base.Resolve(t, name); 
                }
                catch (ResolutionFailedException)
                {
                    Debug.WriteLine(string.Format("Conflict resolution of type:{0}", t));
                    return mockingHelper.ConstructInstance(t);
                }
                
            }
        }
    }

    As you can see no magic there and it does exactly what everyone would expect:

    • Inherit the UnityContainer
    • Override the Resolve method
    • Adds to that override Try Catch block which in case of ResolutionFailedException exception calls the mockingHelper ConstructInstance method
    • Mocking helper instance is stored in a field and constructed with pointer to current unity container in AMCContainer constructor

    MockingHelper class

    Is just 90 line long class looking like this:

    using System;
    using System.Diagnostics;
    using System.Reflection;
    using Microsoft.Practices.Unity;
    using Rhino.Mocks;
    
    namespace UnityAMC
    {
        public class MockingHelper
        {
            private readonly IUnityContainer unityContainer;
            readonly MockRepository mockRepository = new MockRepository();
            private const string DebugCategory = "UnityAMC.MockingHelper";
    
            public MockingHelper(IUnityContainer unityContainer)
            {
                this.unityContainer = unityContainer;
            }
    
            #region Helper methods
            /// 
            /// Construct the instance.
            /// 
            /// The type which is to be constructed.
            /// An instance of service type.
            public object ConstructInstance(Type serviceType)
            {
                ConstructorInfo constructorInfo;
                try
                {
                    constructorInfo = GetGreediestConstructor(serviceType.GetConstructors());
                }
                catch (Exception)
                {
                    try
                    {
                        Debug.WriteLine(string.Format("Mock created - {0}", serviceType), DebugCategory);
    
                        // returning mock of service not added to container
                        return this.mockRepository.DynamicMock(serviceType, new object[0]);
                    }
                    catch (Exception ex2)
                    {
                        return new AutoMockingContainerContainerResolutionException(string.Format("Auto mocking failed for type:{0}", serviceType), ex2);
                    }
                }
    
                var constructorParameters = constructorInfo.GetParameters();
                var arguments = new object[constructorParameters.Length];
    
                var counter = 0;
                foreach (var parameterInfo in constructorParameters)
                {
                    arguments[counter++] = this.unityContainer.Resolve(parameterInfo.ParameterType, string.Empty);
                }
    
                return constructorInfo.Invoke(arguments);
            }
    
            /// 
            /// Gets the greediest constructor.
            /// 
            /// The constructor infos.
            /// Greediest constructor.
            private static ConstructorInfo GetGreediestConstructor(ConstructorInfo[] constructorInfos)
            {
                if (constructorInfos.Length == 0)
                {
                    throw new InvalidOperationException("No available constructors.");
                }
    
                if (constructorInfos.Length == 1)
                {
                    return constructorInfos[0];
                }
    
                var result = constructorInfos[0];
                for (int i = 1; i < constructorInfos.Length; i++)
                {
                    if (constructorInfos[i].GetParameters().Length > result.GetParameters().Length)
                    {
                        result = constructorInfos[i];
                    }
                }
    
                return result;
            }
            #endregion
        }
    }

    GetGreediestConstructor method purpose is to get from a given collection of type constructor info's the one which has the most arguments.

    ConstructInstanceMethod does next things:

    • For a given type tries to get greediest constructor
      • If no constructor available on a given type  (ex. in case of interface) it returns dynamic mock.
    • code then iterates through the greediest constructor parameters and tries to resolve each one of them
    • if resolution of any of them fails the procedure goes again just this time ConstructInstanceMethod would go one level deeper in object graph.

    And that’s about it…

    If I would modify my console app code to use AutoMockingUnityContainer instead of UnityContainer, I would end with code looking like this

    using System;
    using Microsoft.Practices.Unity;
    using UnityAMC;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                IUnityContainer container = new AutoMockingUnityContainer();
                var user = container.Resolve<User>();
                Console.WriteLine(user.WhatIsTheMeaningOfTheLife());
                Console.ReadKey();
            }
        }
    }

    Which would run just fine…

    image

    Conclusion

    Although I found this way of doing Unity AMC pretty naive and dumb, it works perfectly in my test fixtures for couple of months already with 20 minutes spent on making it. If anyone do this on ninja way, I would be more then happy to start using that but in the meantime … :)

    My little code example can be downloaded from here

    Technorati Ознаке: ,,,
  • Fluent NHibernate – Convention over configuration – AutoPersistenceModel auto map magic

    Story about how fluent nhibernate idea was born

    Fluent NHibernate is an open source project (fluent NHibernate trunk) which implements fluent interface on top of the NHibernate ORM configuration capabilities which are based on xml configuration files (as most of the Java ports are) where every entity is defined in it’s own configuration file.

    The main reason behind existence of the Fluent NHibernate project is that working with those configuration files is not something very productive and (in general) it is one of the major turning off points for developers trying to get NHibernate.

    As I mentioned in my Using NHibernate without configuration files post, it is possible to replace the act of creation of configuration files with the c# code where instead of every configuration file defining entities we would have separate mapping class.  That functionality per se is awesome improvement comparing to configuration files, but it is still cumbersome work requiring a lot of repetitive work.

    Here are couple of illustration of what kind of repentance I have on my mind with previous sentence:

    1. My tables are having the same name as my entities (just in plural form)
    2. I could have 50 entity classes where every identity property would be called ID and in database I would always have primary key consisting of “table name + ID”
    3. Data table foreign key can be always defined following the naming rule of “parent table name + ID”
    4. Most of my text based columns have 255 length characters
    5. etc

    Those rules are changing but each one of us (personally or on organization level) has a certain style of doing this things, predefined code and database standards on organization level or just agreement on team level. Based on that fact of convention existence, The Don Ayende asked for some magic to be added to Fluent NHibernate. His point was that he would like to be able to describe easily what the conventions (similar to the one I’ve enlisted above) are used in ORM area of the project and then based on those conventions fluent NHibernate should generate all of the configuration files automatically. Once those default configuration files state  would be achieved, the developer would then modify configuration mappings to cover only the cases being an exception from the conventions.

    Brilliant minds behind Fluent NHibernate get their heads together and implemented that AutoMap functionality Ayende was asking and I was recently playing with it and want to share my experiences with the community.

    (Source code of the example used in this blog post can be found here)

    Blog post set up

    I’ll use the same example as the one I’ve used in  Using NHibernate without configuration files post. The good side of that decision is that you would be able to see same example done on both (manual and auto map) ways but on the flip side (to understand in detail what is the use case scenario etc) you would have to read the original post because here I would just summarize it.

    Class diagram

    image

    SQL Database model

    image

    Couple of major points to be noted here:

    • Customer has an address (Customer.CustomerAddress property) and a collection of reference people handling his requests (References property)
    • SQL Data model has two tables while class diagram has 3 classes. The difference is that Address class data on database level is embedded into customer table. In NHibernate parlance, that is called component.
    • Class diagrams all have their identity property named “ID” while database primary key columns are named following the “table name + ID” rule.
    • Database table names are plural form of class entities. (Customer –> Customers, ReferencePerson –> ReferencePeople)
    • ReferencePerson class has property named LastName while ReferencePeople table has column named SurName
    • All of the entities implement IEntity which is totally not necessary for this example and\or your code but is something so commonly used that most of the examples on the web contain base entity class or interface. That’s why I added IEntity to this example to illustrate how AutoMap works in that use case too

    Project structure

    image


    The project structure of the solution used in this example looks like this:

    • BusinessLayer project contains entities presented in calss diagram without referencing infrastructure (PI\POCO design criteria)

    • NHibernateInfrastructure
      project contains two files:
      • Inflector – this class is “borrowed” from Active Record code base and it sole purpose is to pluralize entity names to database table names
      • NHibernateBootstrapper.cs is a class which performs complete initialization of NHibernate engine based on auto map and manual definitions and result with NHibernate session being created at the end of build up process. Most of this blog post would be related to this class
    • NHibernateInfrastructure.Test project contains test fixture (MappingTest) similar to the one from the manual map post.

     

     

    An example of Fluent NHibernate auto mapping functionality

    Before I start

    Unfortunately there are no official documents presenting “the right way” to do this auto mapping. Most of the examples on net are covering same trivial example and they are not very helpful too. (Btw, lack of documentation was the reason behind writing this blog post) .I am by no mean expert in fluent NHibernate so while the code presented in this blog post is fully functional there might be some better ways how to do some of the presented functionality. In other words, take the example code bellow more as a starting point and spend some time with Fluent NHibernate examining it. It would be very worth spent time, I can promise you that.

    Now the disclaimer is done, let’s roll :)

    High level overview

    Here’s the content of NHibernateBootstrapper.cs class (warning: significant amount of code coming but worth of reading I hope :) )

            
    public ISessionFactory InitSessionFactory()
            {
                var config =
                        MsSqlConfiguration.MsSql2005
                        .ConnectionString.Is(
                            @"Data Source=.\SQL2008;Initial Catalog=NHibernateBlog;" 
                            + @"Integrated Security=True")
                        .UseReflectionOptimizer()
                        .ConfigureProperties(new Configuration());
    
                // 1. defining conventions and scope of the auto persistence model
                var autoPersistenceModel = GetPersistenceModelFromAutoMapping();
                
                // 2. defining exclusions form auto persistence 
                UpdatePersistenceModelWithExclusions(autoPersistenceModel);
    
                // 3. overriding auto mapping defaults
                UpdatePersistenceModelWithManualMappingInformations(autoPersistenceModel);
    
                // 4. writing auto mapping definitions (needed just for blog post) 
                autoPersistenceModel.WriteMappingsTo(@"C:\Temp");
                
                // 5. Configuring NHibernate configuration using auto persistence model
                autoPersistenceModel.Configure(config);
    
                // returning session factory from given configuration
                return config.BuildSessionFactory();
            }	

    InitSessionFactory is the the only public method which is called from application assembly and which task is to return session factory created based on defined mapping informations.

    Beginning of the method is related to creating Sql 2005 standard configuration (NHibernateBlog DB backup file is given in zip file accompanying this blog post)

    Then the method perform 5 step configuration initialization:

    1. Create AutoPersistanceModel containing all the default mapping rules regarding how and what to auto map.
    2. Define domain elements which are to be excluded from the auto mapping persistence model definition due to the fact that they don’t fit to defined conventions
    3. Define all of the manual mapping information fore domain elements which are not auto mapped
    4. Write mappings xml configuration files to hard drive (not needed in production, just for you to check out the result of the fluent NHibernate auto mapping routine)
    5. Configure NHibernate configuration with AutoPeristenceModel initialized in steps #1 - #3

    Once NHibernate is configured session factory is built and returned for further consumption.

    Now when we saw high level steps, let check out how those steps look in more detail..

    Creating of AutoPersistenceModel

    Let see what is inside of the GetPerisicatnceModelFromAutoMapping method

    namespace NHConfigMappings
    {
       ...
           private static AutoPersistenceModel GetPersistenceModelFromAutoMapping()
            {
                return AutoPersistenceModel.MapEntitiesFromAssemblyOf<Customer>()
                        
                        // defining what is to be auto mapped
                        .Where(type =>
                                        typeof(IEntity).IsAssignableFrom(type) 
                                        && type.IsClass 
                                        && !type.IsAbstract
                                        && type.Namespace == "CustomerConfiguration")
                        
                        // defining convention attributes
                        .WithConvention(convention =>
                        {
                            convention.FindIdentity = p => p.Name == "ID";
                            convention.GetTableName = type => Inflector.Pluralize(type.Name);
                            convention.GetPrimaryKeyNameFromType = type => type.Name + "ID";
                            convention.GetForeignKeyNameOfParent = p => p.Name + "ID";
                            convention.DefaultStringLength = 50;
                            convention.OneToManyConvention = o => o.Cascade.All();
                        });
            }
       ...	
    }	

    AutoPersistenceMode has a static factory method MapEntitiesFromAssemblyOf<T> where T is a type defined in a assembly containing entities which are about to be auto mapped. Very cool way for providing assembly name information. In the case of this blog post, Customer type is defined in BusinessLayer asembly, so this line would provide that information to fluent nhibernate auto mapping logic.

    Then there’s a Where method which purpose is to define what types of a given assembly are to be mapped. In a sense it defines filter constraint criteria for auto mapping logic. In the case of this blog post, filter criteria is set to something like “all non abstract types implementing the IEntity which are defined in CustomerConfiguration namespace” . Any type not matching those rules wouldn’t be included in auto mapping process.

    Once I’ve defined “what”, I start defining “how” by defining auto mapping conventions which are set of general settings defining how auto mapping logic should behave.

    In the case of this blog post, conventions are defined like this:

    • Every class would have identity property with name “ID” (If your property would be named “Id” there won’t be need for explicit definition because that is default setting Fluent Nhibernate uses)
    • Database table name should be plural form of the class entity name (example: class Customer –> table Customers)
    • Primary key  column name  would consist of type name and “ID” suffix  (example: PK of Customer table would be named CustomerID)
    • Foreign key column name would consist of parent type name and ID suffix   (example: FK of ReferencePeople table would be CustomerID)
    • Every string class property would be by default mapped to 50 character length column
    • Every One – To – Many mapping would have Cascade.All cascade setting by default

    Defining exclusions from AutoPersistenceModel definition

    Now when I defined default mapping rules, I need to define what needs to be excluded from that auto mapping

    namespace NHConfigMappings
    {
            private static void UpdatePersistenceModelWithExclusions(AutoPersistenceModel persistenceModel)
            {
                persistenceModel
                        .ForTypesThatDeriveFrom<Customer>(c => c.IgnoreProperty(p => p.CustomerAddress))
                        .ForTypesThatDeriveFrom<ReferencePerson>(c => c.IgnoreProperty(p => p.LastName));
            }
       ...	
    }	

    As we can see here I’ve defined next exclusions:

    • Cutomer.CustomerAddress property shouldn’t be auto mapped (because that would be Component and not One-To-Many type of mapping)
    • ReferencePerson.LastName  property shouldn’t be auto mapped (LastName property wouldn’t be mapped to LastName column)

    Adding manual mapping definition to AutoPersistenceModel

    For all of the non mapped and excluded exceptional entities which we still need to map to database entities, Fluent Nhibernate defines  a way of adding manual mapping definitions to auto map defined auto persistence model

    Here’s the code sample:

    namespace NHConfigMappings
    {
       ...
            private static void UpdatePersistenceModelWithManualMappingInformations(AutoPersistenceModel persistenceModel)
            {
                // adding manual mapping to auto mapped persistence model 
                // 1. column level exceptions
                persistenceModel.FindMapping<ReferencePerson>().Map(p => p.LastName, "SurName");
    
                // 2. components definition
                persistenceModel.FindMapping<Customer>()
    		.Component<Address>            (
                        x => x.CustomerAddress,
                        m =>
                        {
                            m.Map(x => x.Street).WithLengthOf(100);
                            m.Map(x => x.PostalCode).WithLengthOf(6);
                            m.Map(x => x.Town).WithLengthOf(30);
                            m.Map(x => x.Country).WithLengthOf(50);
                        });
            }
       ...	
    }	
    

    UpdatePersistenceModelWithManualMappingInformations method updates persistance model like this:

    • In auto persistence model definition find mapping for ReferencePerson entity and add mapping of the LastName property (to be mapped to SurName property)
    • In auto persistence model definition find mapping for Customer entity and add component mapping for CustomerAddress property as defined in code sample

    Checking the xml configuration files

    Let’s take a quick peek at how configuration files generated from AutoPersistenceModel would look like

    CustomerConfiguration.Customer.xml

    <?xml version="1.0" encoding="utf-8"?>
    <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-lazy="true" assembly="CustomerConfiguration" namespace="CustomerConfiguration">
      <class name="ReferencePerson" table="ReferencePeople" xmlns="urn:nhibernate-mapping-2.2">
        <id name="ID" column="ReferencePersonID" type="Guid">
          <generator class="guid.comb" />
        </id>
        <property name="LastName" column="Surname" length="50" type="String">
          <column name="Surname" />
        </property>
        <property name="FirstName" column="FirstName" length="50" type="String">
          <column name="FirstName" />
        </property>
      </class>
    </hibernate-mapping>

    CustomerConfiguration.ReferencePerson.xml

    <?xml version="1.0" encoding="utf-8"?>
    <hibernate-mapping namespace="CustomerConfiguration" assembly="CustomerConfiguration" default-lazy="true" xmlns="urn:nhibernate-mapping-2.2">
      <class name="ReferencePerson" xmlns="urn:nhibernate-mapping-2.2" table="ReferencePeople">
        <property name="LastName" type="String" length="50" column="Surname">
          <column name="Surname" />
        </property>
      </class>
    </hibernate-mapping>

    Now imagine you have hundreds of tables and entities and think about how much time and effort Fluent Nhibernate auto mapping functionality saves. Neat isn’t it?

    Testing the AutoPersistenceModel based auto mappings

    For the end of the blog post there’s only one thing left and that is to run the same test I wrote for Using NHibernate without configuration files post and to show that auto mapping works like it was working with manual class map definition

    Here’s test fixture code…

    namespace NHConfigMappings.Test
    {
        using System.Collections.Generic;
        using CustomerConfiguration;
        using Microsoft.VisualStudio.TestTools.UnitTesting;
       using NHibernate;
    
        [TestClass]
        public class MappingsTest
        {
            private static ISessionFactory _sessionFactory;
    
            [ClassInitialize]
            public static void FixtureInit(TestContext testContext)
            {
                _sessionFactory = new NHibernateBootstrapper().InitSessionFactory();
            }
    
            [TestMethod]
            public void ReferencePerson_Create_ShouldCreateRowInDb()
            {
                var customer = new Customer
                   {
                       Name = "John Doe",
                       CustomerNumber = "12345",
                       CustomerAddress = new Address
                                             {
                                                 Street = "1st Mayson Street",
                                                 PostalCode = "01754",
                                                 Town = "Maynard",
                                                 Country = "USA"
                                             },
                       References = new List
                                              {
                                                  new ReferencePerson
                                                      {
                                                          FirstName = "Nikola",
                                                          LastName = "Malovic"
                                                      }
                                              }
                   };
    
                ISession session = _sessionFactory.OpenSession();
                session.Save(customer);
                session.Flush();
    
                session.Evict(customer);
                
                var customerDB= session.Get<Customer>(customer.ID);
                Assert.IsTrue(  customerDB.ID == customer.ID && customerDB.Name == customer.Name 
                                && customerDB.CustomerAddress.Street == "1st Mayson Street"
                                && customerDB.References[0].FirstName == "Nikola");
    
            }
        }
    }

    The main difference between tests in previous blog post and this one is that we don’t have in fixture init explicit session factory initialization. Instead, there’s only call to NHIbernateBootstrapper class InitSessionFactory method which I’ve already presented in this blog post. Test method is completely the same as the one from previous post. So it is the result of test run

    image

    Conclusions

    1. NHIbernate rock!
    2. Fluent NHibernate Auto mapping functionality rock!

    There are a lot of blog posts about auto mapping functionality you might want to check out:

  • Dependency injection in real world

    Patrick left a comment on one of my previous blog posts asking a couple of very interesting questions that I’ve been asking myself too:

    Is service locator legitimate way of doing IoC?

    (I’ll use example code from that blog post as a base for my today blog post so in case you are idle enough you can go and check it out)

    Dependency injection primer

    Let me start with an example how “real” dependency injection implementation code from my blog post could look like:

    using System;
    using System.Collections.Generic;
    
    namespace Example.UserManager
    {
        public class UserManagerIoC
        {
            private readonly IUserProvider userProvider;
    
            public UserManagerIoC(IUserProvider userProvider)
            {
                this.userProvider = userProvider;
            }
    
            public int NumberOfUsersActiveInLast10Days(string userName)
            {
                var userCollection = this.userProvider.GetUserCollection();
                int result = 0;
                foreach (User user in userCollection)
                {
                    if (user.Name.StartsWith(userName) && user.LastActivity > DateTime.Now.AddDays(-10))
                        result++;
                }
                return result;
            }
        }
    }

    As we can see from the simple code above, code has one constructor which accepts the IUserProvider parameter and then stores its pointer to a field  so it can be used  later in a method which performs some kind of business logic.

    Key concept here to be noticed is that class have literally no clue where from and how userProvider would get injected.

    How DI based unit test looks like?

    I’ll use Microsoft Unity and Rhino mocks to write a test for the dependency injection primer.

    Here it is:

    using System.Collections.Generic;
    using Example.UserManager;
    using Microsoft.Practices.Unity;
    using NUnit.Framework;
    using Rhino.Mocks;
    
    namespace UserManager.Test.IoC
    {
        [TestFixture]
        public class UserManagerTestIoC
        {
            private MockRepository mockRepository;
            private IUnityContainer unityContainer;
    
            [SetUp]
            public void Test_Init()        
            {
                this.mockRepository = new MockRepository();
                this.unityContainer = new UnityContainer();
            }
    
            [Test]
            public void GetActiveUsers_TestCaseOfZeroUsers_WouldReturnEmptyCollection()
            {
                var userProvider = this.mockRepository.DynamicMock<IUserProvider>();
                // injecting to unity container mocked instance of user provider
                this.unityContainer.RegisterInstance(userProvider);
                
                using (this.mockRepository.Record())
                {
                    Expect.Call(userProvider.GetUserCollection())
                        .Return(new List<User>());
                }
                using (this.mockRepository.Playback())
                {
                    // using IoC container for UserManager construction 
                    var userManager = this.unityContainer.Resolve<UserManagerIoC>();
                    
                    // and then performing tested code 
                    int numberOfUsers= userManager.NumberOfUsersActiveInLast10Days("X");
                    Assert.IsTrue(numberOfUsers == 0);
                }
            }  
        }
    }

    What I did in that test:

    • I am instantiating UnityContainer in test set up to be used as IoC container.
    • In first line of test  method I am using Rhino mocks to create mock of IUserProvider and then I inject that mock to Unity IoC container
    • In a first line of recording block, I set expectation that empty user collection would be returned
    • In playback block, I get an instance of UserManagerIoC class by using IoC container Resolve factory method. (KEY POINT)
    • IoC container would then:
      • examine the constructor of UserManagerIoC class,
      • see that IUserProvider parameter is requested
      • try to find in IoC container registered service implementing IUserProvider interface
      • mocked instance we injected at the beginning of the test would be found
      • mocked instance would be injected to UserManagerIoC
    • Method would be executed and the expected number of users checked

    NOTE #1: You could get away from explicit dependency mocking by using AutoMockingContainer but I decide to do it anyhow in this post in order to increase example readability.

    NOTE #2: You could also opt to use var userManager = new UserManager(userProvider) but this is not something typically you would do because userProvider can have it’s own dependencies and so on… Not using IoC container in the test would mean not using one of its most important features: auto dependency resolution.

    Dependency injection upsides and downsides

    As we can see, we were able to keep UserManager light and ignorant about IoC infrastructure, while utilizing the benefits dependency injection provides us (increased testability in this example)

    Still there are couple of problems (not sure if I can call them like this) related to this implementation which I’ve witnessed in last couple of months and which can be summarized as:

    • Brownfield scenarios
      UserManager is already existing class built without having dependency injection on mind (no constructor exposing abstracted dependencies). While it is hard to sell the business value of refactoring UserManager internals to expose dependencies through constructor (sell tagline: to test it) it is mission impossible getting approval for updating all of the million places  currently doing the UserManager um = new UserManager() to become unityContainer.Resolve<UserManager>() (Sith language : “What’s the business value?”) and without that change no DI going to happen.
    • Code monkey scenarios
      Vast majority of developers I know don’t get the IoC, TDD etc, which means that one would spend ton of time answering the
      “Why I can not just new the instance?”, “This is clearly an overkill…”, “Here it is him with his damn patterns making my life miserable”, “Why I need to decouple DB from my  unit tests at all?”..
      Although this reason might look “not-so-important”, if you are not lucky to work in TDD friendly environment, if you are working in company which DEV teams span across the globe this could be real show stopper.
    • “TDD == unit test”
      If you are doing unit tests AFTER the code is been done then it is very hard to sell to PMs the need for “all that complexity”.
      In other words, if they don’t get that in TDD the most important thing is not the “T” (test) but the “DD” (driven design) whole DI thing start to get harder to be sold
    • “Why IoC framework X?”
      ”Why UnityContainer?” “Why not Castle?” “Why not Spring?” “Why not StructureMap?” “On my previous job I worked with XYZ and it is the best…”

     

    ServiceLocator based dependency injection

    Luckily, I think I found a way how to go around the restrictions mentioned above with keeping the dependency injection in place and high testability. I’ve wrote in more details in my DFT blog post series so here I’ll just summarize it…

    The key points that solution has to achieve are:

    1. Core code implementation has to utilize dependency injection
    2. Code has to be “open for testing” but “close for development”  (yes, I am aware how stupid this might sound and it it stupid thing – details bellow )
    3. DI enabling existing code is not allow to cause any breaking compatibility issues (KIC - “keep it cheap” design principle)
    4. No dependency on any particular IoC framework

    Lets take a look at the same primer I’ve done with DI this time implemented using service locator

    using System;
    using Facade;
    
    namespace Example.UserManager
    {
        public class UserManagerSL
        {
            private readonly IUserProvider userProvider;
    
            public UserManagerSL(): this (ServiceLocator.Retrieve<IUserProvider>())
            {
            }
    
            internal UserManagerSL(IUserProvider userProvider)
            {
                this.userProvider = userProvider;
            }
    
            public int NumberOfUsersActiveInLast10Days(string userName)
            {
                var userCollection = this.userProvider.GetUserCollection();
                int result = 0;
                foreach (User user in userCollection)
                {
                    if (user.Name.StartsWith(userName) && user.LastActivity > DateTime.Now.AddDays(-10))
                        result++;
                }
                return result;
            }
        }
    }

    Main differences (compared to dependency injection primer) are:

    • We still have public parameter less constructor
      That parameter less  constructor uses ServiceLocator to retreive instace of IUserProvider on a same way UnityContainer retrieved it in previous test.
      ServiceLocator is just a Facade wrapper around IoC container encapsulating the type of container and hiding not used features.
      Achieved design goal: “Keep it cheap”
      Achieved design goal: “No dependency on particular IoC framework”

    • In some bootstrapper class tied to app start event I will have to define ServiceLocator mapping for service implementing the IUserProvider so the code would work normally like it was working before the dependency injection
    • Constructor taking IUserProvider parameter is now internal.
      The assembly containing UserManagerSL class would contain next attribute
      [assembly: InternalsVisibleTo("UserManager.Test.SL")]

    Result of this attribute would be that this constructor would be:

    - visible to test assembly containing test methods using UserManagerSL
    - not visible to any code outside of that test assembly (none of the “core DEV” would be aware of it)

    Achieved design goal: “Open for test, close for development”
    Achieved design goal: “Dependency injection used in code”

    How ServiceLocator based test looks like?

    Here are two examples how the service locator code can be tested..

    “White box” service locator test style

    using System.Collections.Generic;
    using Example.UserManager;
    using Facade;
    using NUnit.Framework;
    using Rhino.Mocks;
    
    namespace UserManager.Test.SL
    {
        [TestFixture]
        public class UserManagerTestSL
        {
            private MockRepository mockRepository;
            private IUserProvider userProvider;
    
            [SetUp]
            public void Test_Init()        
            {
                this.mockRepository=new MockRepository();
    
                // registering mock of IUserProvider with ServiceLocator
                this.userProvider = this.mockRepository.DynamicMock<IUserProvider>();
                ServiceLocator.InjectStub(this.userProvider);
            }
    
            [Test]
            public void GetActiveUsers_TestCaseOfZeroUsers_WouldReturnEmptyCollection_WithSL()
            {
                using (this.mockRepository.Record())
                {
                    Expect.Call(this.userProvider.GetUserCollection())
                        .Return(new List<User>());
                }
                using (this.mockRepository.Playback())
                {
                    // using internal constructor
                    var userManager = new UserManagerSL();
                    int numberOfUsers = userManager.NumberOfUsersActiveInLast10Days("X");
                    Assert.IsTrue(numberOfUsers == 0);
                }
            }
        }
    }

    In this testing style we feed the service locator with the list of internal dependencies we know it is been used by the tested code and then in our test method we totally don’t care about dependency injection (constructors used are empty, no service locator usage anywhere outside of SetUp method)

    I personally don’t like this style of testing (based on intimate knowledge of tested code) but I’ve seeing it working in the past.

    Using internal constructor

    Second approach is based on the fact that internal constructor is accessible to test assembly which makes test built on this way very simple

    using System.Collections.Generic;
    using Example.UserManager;
    using NUnit.Framework;
    using Rhino.Mocks;
    
    namespace UserManager.Test.SL
    {
        [TestFixture]
        public class UserManagerTestSL
        {
            private MockRepository mockRepository;
    
            [SetUp]
            public void Test_Init()        
            {
                this.mockRepository=new MockRepository();
            }
    
            [Test]
            public void GetActiveUsers_TestCaseOfZeroUsers_WouldReturnEmptyCollection()
            {
                IUserProvider userProvider = mockRepository.DynamicMock<IUserProvider>();
    
                using (mockRepository.Record())
                {
                    Expect.Call(userProvider.GetUserCollection())
                        .Return(new List<User>());
                }
                using (mockRepository.Playback())
                {
                    // using internal constructor
                    var userManager = new UserManagerSL(userProvider);
                    int numberOfUsers = userManager.NumberOfUsersActiveInLast10Days("X");
                    Assert.IsTrue(numberOfUsers == 0);
                }
            }
        }
    }

    In this example we don’t use at all service locator. Instead we simply inject mocked instance of user provider to internal constructor. All of the downsides of this approach (mentioned in dependency injection note #2) are applicable here to.

    Using dependency injection

    The best thing with my service locator based design approach is that while some of the “not so TDD skilled” developers can do testing on the first two ways, “TDD skilled” developer can still write exactly the same test as the one given in the dependency injection section of this blog post.

    Check it for yourself:

            [Test]
            public void GetActiveUsers_TestCaseOfZeroUsers_WouldReturnEmptyCollectio_IoC()
            {
                var userProvider = this.mockRepository.DynamicMock<IUserProvider>();
                // injecting to unity container mocked instance of user provider
                ServiceLocator.InjectStub(userProvider);
    
                using (this.mockRepository.Record())
                {
                    Expect.Call(userProvider.GetUserCollection())
                        .Return(new List<User>());
                }
                using (this.mockRepository.Playback())
                {
                    // using IoC container for UserManager construction 
                    var userManager = ServiceLocator.Retrieve<UserManagerSL>();
    
                    // and then performing tested code 
                    int numberOfUsers = userManager.NumberOfUsersActiveInLast10Days("X");
                    Assert.IsTrue(numberOfUsers == 0);
                }
            }  

    Summary

    Most of the blog posts I’ve seen present an ideal “perfect day” situation setup  for writing the test which is not always the case in real world.

    In this kind of “not-so-perfect” situations, service locator based solution I’ve presented in that blog post allowed me to increase testability and introduce TDD into existing code bases and environments not so much interested in the TDD.

    Source code for this blog post can be found here.

  • Fluent NHibernate – NHibernate without configuration files

    NHibernate is great, (no doubt about it) but every time I was supposed to work with it, the fact that I had to manually type in all those xml configuration entries was something I really didn’t like at all.

    The most important complains I personally have on NHibernate configuration files are:

    • It is error prone
    • Errors in configuration file can be hard to trace
    • It is not refactoring friendly
    • It is not C#, it is XML :-)

    I believe that the most important reason why NHibernate is not more widely adopted by general DEV population is exactly the “Java XML configuration” PIA feeling you have while working with it.

    Great news for all of us from that group: NHibernate is possible to be used WITHOUT configuration files!

    Who, what and where?

    image

    Jeremy Miller coded initial bits of the Fluent NHibernate project and then James Gregory with couple of guys more bring the project to Google code and they started finalizing it. OSS rules!

    So, if you go to http://code.google.com/p/fluent-nhibernate/ you would see names of other project members together with the simple code illustrating the goal fluent nhibernate project tries to achieve.

    As with the most OSS projects, to get the source code of FNH, download it from Subversion trunk located at http://fluent-nhibernate.googlecode.com/svn/trunk/

    Solution file consist of couple of projects:

    • LIb solution folder contains DLL you would be using in your application.
    • Test project containing a bunch of unit tests which you can use as starting point to get detail understanding on how the things works.
    • Quick start project which highlights most important concepts you need to start using NHibernate

    Note: Project is initially built with NHibernate 2.0 which collides with Linq For NHibernate (using NHibernate 2.1) so I updated FNH project references to use 2.1 too 

    Fluent NHibernate in action

    Solution project structure

    image

    In this blog post, I will use the same example Jimmy Nilsson used in his Applying Domain-Driven Design and Patterns: With Examples in C# and .NET NHibernate chapter so you can compare outcome of my blog post sample it with how it looked in his book (with the configuration files in place).

    Solution file of today’s example contains 3 projects:

    • BusinessLayer (“Domain”)
      Contains definitions of entities which we use in modeling business use cases.
      Important to be mentioned here is that BusinessLayer  project doesn’t have any reference to neither other projects of this solution nor the “3pty dlls” such is NHibernate.dll
    • NHConfigMappings (“Mapping project”)
      Contains ORM mapping definitions which enables nhibernate to persist to relational DB domain entities
    • NHCongigMappings.Test

    Contains test fixture illustrating how mappings should be consumed and how nhibernate engine could be initialized without any xml configuration files

    (Source code used in today blog post can be download from here) 

     

    Domain project

     

    image

    As you can see, it is very simple sample where we have entity customer class containing “embedded” Address value object and referencing the list of reference persons customer contacted.

    Same diagram given in code would look like this

    using System;
    using System.Collections.Generic;
    
    namespace CustomerConfiguration
    {
        public class Customer
        {
            public virtual Guid Id { get; set; }
    
            public virtual string CustomerNumber { get; set; }
    
            public virtual string Name { get; set; }
    
            public virtual Address CustomerAddress { get; set; }
    
            public virtual IList ReferencePersons { get; set; }
        }
    }

    Address type will look like this:

    namespace CustomerConfiguration
    {
        public class Address
        {
            public virtual string Street { get; set; }
            public virtual string PostalCode { get; set; }
            public virtual string Town { get; set; }
            public virtual string Country { get; set; }
        }
    }

    And ReferencePerson type would look like this:

    using System;
    
    namespace CustomerConfiguration
    {
        public class ReferencePerson
        {
            public virtual Guid Id { get; set; }
    
            public virtual string FirstName { get; set; }
    
            public virtual string SurName { get; set; }
        }
    }

    As you can see from the code above, NHibernate allows us fully persistent ignorant \POCO software development: no special attributes, no special base class or interface…

    Mapping project

    Once we have domain logic defined, we need to provide information on how NHibernate should map our classes with appropriate DB entities: tables and columns.

    For my example DB would look like this:

    image

    As you can see, although in my code I have separate Address class I don’t have it in DB. Instead I have it embedded in Customer table as last 4 columns. Also, table names in DB are in plural form while names of classes are in singular form.

    Another small difference here is that in ReferencePerson class has a LastName property while DB has column SurName.

    Mapping ReferencePerson

    I won’t throw in here example of how that would look if I would use XML configuration file, because the whole point is to forget that ASAP :) (In case you want to see it, check it out here)

    In order to define NHibernate mapping, in FNH you need to create a mapping class for each one of entities (which is something Ayende don’t get).

    That mapping class should inherit from  ClassMap<T> class in order to get access to FHN members providing programmatic access over configuration settings

    using CustomerConfiguration;
    using FluentNHibernate.Mapping;
    
    namespace NHConfigMappings
    {
        public class ReferencePersonMap : ClassMap<ReferencePerson>
        {
            public ReferencePersonMap()
            {
                TableName = “ReferencePersons”;
                
                Id(x => x.Id).GeneratedBy.GuidComb()
                    .WithUnsavedValue(“00000000-0000-0000-0000-000000000000”);
    
                Map(x => x.FirstName).WithLengthOf(50).CanNotBeNull();
                Map(x => x.LastName,”SurName”).WithLengthOf(50).CanNotBeNull();
            }
        }
    }

    Main advantage of fluent interface is that  it produces code with good readability, which I believe we can see from code snippet above.

    In a class constructor, I am defining:

    1. What is the name of data table where the class will be persisted. In my example table name and class name differs so I had to define it here, but I think it is good practice to define it always, even they are implicitly the same by the default
    2. Which class property should be used as Identity Field populating table PK. In example I took I am using ReferenceMap.Id property where NHibernate generate its value using GuidComb  value as performance effective type of GUID values. At the end I defined how unsaved value is looking like so NHibernate would be able to deduct how the class should be persisted (insert or update)
    3. That the FirstName property should be mapped to the column with the same name where the column length is 50 characters and null values are not allowed
    4. That the LastName property should be mapped to the column named “SurName” with the maximum length of 50 characters without null values being allowed

    In my opinion main advantages here are that the configuration code is human readable and refactoring friendly (if I ever do changes on ReferencePerson class mapping file will be broken so we have “type safe” configuration settings)

    Mapping Customer

    Customer class mapping definition is stored in CustomerMap (implementing the ClassMap<Customer> class looking something like this

    using CustomerConfiguration;
    using FluentNHibernate.Mapping;
    
    namespace NHConfigMappings
    {
        public class CustomerMap : ClassMap<Customer>
        {
            public CustomerMap()
            {
                TableName = “Customers”;
                
                Id(x => x.Id).GeneratedBy.GuidComb()
                    .WithUnsavedValue”00000000-0000-0000-0000-000000000000”);
                
                Map(x => x.Name).WithLengthOf(50);
                Map(x => x.CustomerNumber).WithLengthOf(50);
                
    	    HasMany<ReferencePerson>(x => x.ReferencePersons)
                    .Access.AsProperty()
                    .AsBag().WithKeyColumn("CustomerId")
                    .Cascade.All();                        
                
                Component<Address>(x => x.CustomerAddress, 
                                   m =>
                                       {
                                           m.Map(x => x.Street).WithLengthOf(100);
                                           m.Map(x => x.PostalCode).WithLengthOf(6);
                                           m.Map(x => x.Town).WithLengthOf(30);
                                           m.Map(x => x.Country).WithLengthOf(50);
                                       });
            }
        }
    }

    In a class constructor, I am defining:

    1. The name of table to which this class map
    2. Customer.Id as primary key containing guid value
    3. Customer.Name is mapped to the Name nvarchar(50) column
    4. Customer.CustomerNumber is mapped to the CustomerNumber nvarchar(50) column
    5. Customer class contains collection of ReferencePerson instances stored in Customer.ReferencePersons property
      which should be mapped in separate table (AsBag())  where role of FK will be performed by ReferencePerson.CustomerId
      and with cascading of events (Insert of Customer will result with Insert of ReferencePerson etc)
    6. Customer contains property CustomerAddress of type Address as embed value where
      1. Address.Street is nvarchar(100) column
      2. Address.PostalCode  is nvarchar(6) column
      3. Address.Town is nvarchar(30) column
      4. Address.Country is nvarchar(50) column

    Once again, take a look at the class above. I have just described something which looks like typical use case we face in real world with something which (IMHO) has very high readability and  it is easy to be written

    Unit testing fluent nhibernate mappings

    In order to present how those mappings should be used I wrote unit test project which will present:

    • how this mappings are to be used
    • how to configure nhibernate itself without the need for hibernate.cfg.xml file

    For the purpose of this test I choose MS Test just for kicks (although I am mostly using MBUnit )

    How to initialize nhibernate without hibernate.cfg.xml

    Due to the fact that initializing nhibernate engine is slow, I am initializing it once per text fixture and in test fixture of this example nhibernate initialization routine in case of fluent nhibernate is a 5 step procedure:

    • Initialize type implementing IPersistenceConfigurer (MSSqlConfiguration, SQLLiteConfiguration, PostgreSQLConfiguration are currently supported)
    • use instance of that type (in my example instance of MSSqlConfiguration) to preset properties of NHibernate.Configuration instance
    • create instance of FluentHibernate.PersistenceModel type
    • use that instance to load the assembly containing mappings
    • use that instance to inject mappings to nhibernate configuration instance

    At the end of configuration sequence I have  operational NHibernate configuration instance which I use to create session factory which I then store as a class field.

    Once I have that SessionFactory field in place, each one of the test methods just uses it to create a session needed.

    Let’s take a look at how this initialization routine could look in code

       
    	
    	private static ISessionFactory _sessionFactory;
    
            [ClassInitialize]
            public static void FixtureInit(TestContext testContext)
            {
                // initialize persistance configurer
                IPersistenceConfigurer persistenceConfigurer =
                    MsSqlConfiguration
                        .MsSql2005
                        .ConnectionString.Is(
                        “Data Source=.\SQL2008;Initial Catalog=NHibernateBlog;"
    		    + "Integrated Security=True”)
                        .ShowSql();
    
                // initialize nhibernate with persistance configurer properties
                Configuration cfg = persistenceConfigurer
    				.ConfigureProperties(new Configuration());
    
                // add mappings definition to nhibernate configuration
                var persistenceModel = new PersistenceModel();
                persistenceModel.addMappingsFromAssembly
    			(Assembly.Load(“NHConfigMappings”));
                persistenceModel.Configure(cfg);
    
                // set session factory field which is to be used in tests
                _sessionFactory = cfg.BuildSessionFactory();
            } 

    I think code above is simple enough (thanks to FNH) that it doesn’t need any extra explanations about its  concrete implementation.

    Nhibernate unit test method

    Now when we have that session factory up and going, we would make only a simple test where we will create a new customer and try to store it in DB.

    That test code could look like this:

            [TestMethod]
            public void ReferencePerson_Create_ShouldCreateRowInDb()
            {
                var customer = new Customer
                   {
                       Name = “John Doe”,
                       CustomerNumber = “12345”,
                       CustomerAddress = new Address
                                             {
                                                 Street = “1st Mayson Street”,
                                                 PostalCode = “01754”,
                                                 Town = “Maynard”,
                                                 Country = “USA”
                                             },
                       ReferencePersons = new List<ReferencePerson>
                                              {
                                                  new ReferencePerson
                                                      {
                                                          FirstName = “Nikola”,
                                                          LastName = “Malovic”
                                                      }
                                              }
                   };
    
                ISession session = _sessionFactory.OpenSession();
                Guid id=(Guid)session.Save(customer);
                session.Flush();
    
                session.Evict(customer);
                
                var customerDB= session.Get<Customer>(id);
                Assert.IsTrue(  customerDB.Id == customer.Id && customerDB.Name == customer.Name 
                                && customerDB.CustomerAddress.Street == “1st Mayson Street”
                                && customerDB.ReferencePersons[0].FirstName == “Nikola”);
    
            }

    At the beginning of the test method I create a new customer instance with CustomerAddress data and single ReferencePerson instance in ReferencePersons.

    Then I use the sessionFactory created in test fixture set up, and create a session which then I use to persist customer instance. As a result of that persistence method call I am getting customer identity value used as PK value in DB.At the end of that persistence code I just flush the session in order to commit the changes.

    Now when (hopefully) our customer is saved I need to test that and the usual way of testing save is to try to load the data from DB. That’s why I remove the customer instance from NHibernate Identity Map “cache” so I won’t get results from memory and then I am trying to retrieve data using the identity value I retrieved during persistence.

    With the retrieved customer data I do just quick value check (in real world test this check would look different).

    Test will pass therefore if retrieved data will match the data of customer instance created in this test.

    Running the test

    Once I run the test, I got successful test 

    image

    And fast look at the DB shows that data are persisted

    image

    Test passed!

    Conclusion

    Purpose of this blog post was to present a way of using NHibernate different then the standard xml configuration approach most of people use right now working with NHibernate.

    I hope you can see for yourself that it is VERY possible to use NHibernate without a single configuration file on very DEV friendly and intuitive way.

    The example I presented here is just tip of the iceberg so I strongly encourage you to sync Fluent NHibernate source code and play with quick start and test projects.

    Here are also some links you can check out too:

    Happy Hibernating!

     

  • Model View Presenter (MVP) – Tips from trenches (TFT) – Working with HttpContext (Part 2)

     

    Intro

    This is part 2 of blog post series where I am presenting solutions I came up with to some common problems developers are facing implementing the MVP pattern in real world applications.

    Previously on tips from trenches:

    Today’s hurdle: Using HttpContext without System.Web

    (Source code used in today’s example can be downloaded from here)

    One of the principles I really feel strong about can be formulated like this:”Presenter is not allowed to reference System.Web assembly at all”.

    Main reason why I feel so strong about that, is based on the fact that once referenced System.Web enables developers in your team to use types from that assembly (HttpContext, Session, Query, Cache etc) and we all know what PITA those types can be when testing Presenters.

    Here’s very simple example I’ll use in today’s post:

    Imagine you have a presenter which based on value of some query parameter is performing some redirecting or updating UI elements.

    The easiest way (referencing the System.Web into presenter) will enable very easy implementation of required functionality but testing that code will require things like creating fake web context which IMHO is good sign of of important web test smell.

    Luckily, there’s a solution :)

    Model View Presenter pattern combined with Adapter design pattern offers easy and effective way of tackling this problem and this post is showing how to do that.

    Adapter design pattern

    This pattern is one of patterns I recently rediscovered as maybe one of the most useful patterns in every day programing. The pattern itself is not very sexy, because it is very simple. It’s purpose is to handle the cases Adapter_realexamplewhenever we need to adapt the interface of one component to the interface we need.

    Canonical example mostly used in explaining the pattern is the case of US and European power adapters. I am sure I am not the only one European who found himself shocked by the fact that power outlets in USA are totally different then the European one. In other words, European power sockets are wider and round while US are narrow and flat. Luckily, there’s Ebay where one can buy himself an adapter compatible with USA power outlets with entry holes compatible to European standards. That’s how you charge your laptop using original cable adapted to custom power outlet.

    Adapter design pattern is exactly the same thing.

    As we can see on above diagram, when client calls a Target object he would get instance of Adapter inheriting from Target which will delegate to SpecificRequest method of of Adaptee object all of the calls for Request() method (Adaptee object is containing instance of Adapter).
    In other words, Adapter “implements via delegation” to Adaptee.

    Building the TDD friendly HttpContext

     

    Implementation of TDD friendly HttpContext will be based on couple of steps:

    • building System.Web agnostic interface which would:
      • perform the role of Facade by hiding most of the the members not important for MVP
      • perform a role of a service contract which would be used by IoC container where custom HttpContext service will be need
    • building special collection type which would enable us transparent intercepting interface members access
    • building HttpContext service adapter which would implement the interface by delegating all of the calls to interface members to System.Web.HttpContext
    • registering service into IoC container

    Defining IHttpContextService

    As previously mentioned, first step in implementing the TDD friendly http context is defining the feature list I am expecting to use in my Presenters. Based on some of my current experiences, that interface might look like this:

    image

    You can see from the interface definition to the left that (IMHO) important http context members are:

    • Redirect(url) method – When presenter and\or controller are responsible for driving navigation (more about controller in upcoming post)
    • QueryString property – read only name-value collection property which contains collection of string pairs representing url parameter name and value
    • User property  - IPrincipal type doesn’t require usage of System.Web and defines a lot of useful things for implementing presenters
    • ContextItems  - read only property of custom name value collection type (more about that in second) which contains collection of string pairs representing name of httpcontext item and value that item carries
    • Session – read only property of custom collection type containing string pairs representing application session variable entries

    Key point here is that none of the members is not returning types from System.Web and that there are no Response, Request etc members. Only a small subset of really needed things defined in “easy to mock” way.

    One thing Web Client Software Factory failed

    While we speak about interface definition I would like to mention here a thing I’ve been disappointed seeing how it is been implemented there.

    WCSF has IHttpContextLocatorService implemented like this (taken from reflector)

    public interface IHttpContextLocatorService
    {
        // Methods
        [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
        IHttpContext GetCurrentContext();
    }

    and that IHttpContext interface look like this (part of)

    public interface IHttpContext
    {
        // Methods
        HttpApplicationState Application { get; }
        HttpApplication ApplicationInstance { get; set; }
        Cache Cache { get; }
        HttpContext Context { get; }
        ProfileBase Profile { get; }
        HttpRequest Request { get; }
        HttpResponse Response { get; }
    }

    As you can see by the fact that interface has members of types defined in System.Web, in order to use IHttpContextLocatorService I am still required to use System.Web. In other words, to get url query parameter I would still have to use System.Web.HttpRequest.

    I might be missing something pretty big here, but IMHO there is no sense at all in how P&P team implemented this service. Testing pain I felt using WCSF related to this made me thinking about better solutions and this post is result of that :)

    HookableNameValueCollection

    Now when you saw interface definition and heard where from inspiration for this post came, let’s talk about the custom collection I used in interface while defining type of Session and ContextItems properties.

    Design goal behind the decision for creating this collection is to provide the same simple feeling working with http context adapter as the one we are used to it while using the real HttpContext.

    Here are some simple examples of  what behavior I wanted to get:

    • var x=httpContextService.Session[“SOME_KEY”]    
    • httpContextService.Session[“SOME_KEY”] =”123”; 
    • httpContextService.Session.Add(“SOME_KEY”,123); 
    • httpContextService.Session.Remove(“SOME_KEY”); 

    And here is what I was trying to avoid:

    • var x= httpContextService.GetSessionValue(“SOME_KEY”)
    • httpContextService.UpdateSessionItemValue(“SOME_KEY”,”123”)
    • httpContextService.RemoveSessionItem(“SOME_KEY”)

    One way to do that is to play again with Adapter pattern and transform HttpSessionState to IDictionary based adapter class and use that adapter type, but that would be solution specific only to this problem and (if there is an option) I always try to solve problem with reusable solutions. The way I have picked for this blog post is simply to create custom name value collection type where I am going to override Add/Remove/Set methods and raise appropriate events informing listeners that certain activity occurred.

    Something like this:

    image

    Here’s the same diagram given through plain old c# code  

    namespace Vuscode.Framework.Abstractions
    {
        using System;
        using System.Collections.Specialized;
    
        public class HookableNameValueCollection : NameValueCollection
        {
            public EventHandler<HookItemChangedEventArgs> ItemAdded;
            public EventHandler<HookItemChangedEventArgs> ItemSet;
            public EventHandler<HookItemRemovedEventArgs> ItemRemoved;
    
            public override void Add(string name, string value)
            {
                base.Add(name, value);
                if (ItemAdded != null)
                    ItemAdded(this, new HookItemChangedEventArgs(name, value));
            }
    
            public override void Set(string name, string value)
            {
                base.Set(name, value);
                if (ItemSet != null)
                    ItemSet(this, new HookItemChangedEventArgs(name, value));
            }
    
            public override void Remove(string name)
            {
                base.Remove(name);
                if (ItemRemoved != null)
                    ItemRemoved(this, new HookItemRemovedEventArgs(name));
            }
        }
    }

     

     

    Building HttpContext service adapter

    Once we have IHttpContextService and HookableNameValueCollection implemented, implementing httpcontext adapter is very simple implementation of  the context interface.

    Due to the fact that we would have to reference System.Web in order to adapt certain properties, I will create new component called Framework.Adapters and put the adapter class implementation there.

    Implementation in general would look like this:

    • Redirect method, QueryString collection property and User property would just delegate their calls to HttpContext.Current instance
    • HttpContextServiceAdapter class subscribe to ContextItems and Session add/update/set events and performs appropriate calls to HttpContext.Current.Session and HttpContext.Current.Items

    Let’s take a peek at how this implementation looks like in the C# code …

    #region
    
    using System.Collections.Specialized;
    using System.Security.Principal;
    using System.Web;
    using Vuscode.Framework.Abstractions;
    using Vuscode.Framework.Abstractions.Web;
    
    #endregion
    
    namespace Framework.Adapters.Web
    {
        public class HttpContextServiceAdapter : IHttpContextService
        {
            private readonly HookableNameValueCollection _context
                = new HookableNameValueCollection();
    
            private readonly HookableNameValueCollection _session
                = new HookableNameValueCollection();
    
            public HttpContextServiceAdapter()
            {
                InitSessionVariables();
                InitContextVariables();
            }
    
            #region IHttpContextService Members
    
            public NameValueCollection QueryString
            {
                get { return HttpContext.Current.Request.QueryString; }
            }
    
            public void Redirect(string url)
            {
                HttpContext.Current.Response.Redirect(url);
            }
    
            public IPrincipal User
            {
                get { return HttpContext.Current.User; }
                set { HttpContext.Current.User = value; }
            }
    
            public HookableNameValueCollection Session
            {
                get { return _session; }
            }
    
            public HookableNameValueCollection ContextItems
            {
                get { return _context; }
            }
    
            #endregion
    
            private void InitContextVariables()
            {
                if (HttpContext.Current.Items != null)
                    foreach (string itemsKey in HttpContext.Current.Items.Keys)
                    {
                        _context.Add(itemsKey, 
    				 HttpContext.Current.Items[itemsKey].ToString());
                    }
    
                _context.ItemAdded += ((sender, e) 
    			    => HttpContext.Current.Items.Add(e.Name, e.Value));
                _context.ItemSet += ((sender, e) 
    			    => HttpContext.Current.Items[e.Name] = e.Value);
                _context.ItemRemoved += ((sender, e) 
    			    => HttpContext.Current.Items.Remove(e.Name));
            }
    
            private void InitSessionVariables()
            {
                if (HttpContext.Current.Session != null)
                    foreach (string sessionKey in HttpContext.Current.Session.Keys)
                    {
                        _session.Add(sessionKey, 
    				 HttpContext.Current.Session[sessionKey].ToString());
                    }
    
                _session.ItemAdded += ((sender, e) 
    			    => HttpContext.Current.Session.Add(e.Name, e.Value));
                _session.ItemSet += ((sender, e) 
    			    => HttpContext.Current.Session[e.Name] = e.Value);
                _session.ItemRemoved += ((sender, e) 
    			    => HttpContext.Current.Session.Remove(e.Name));
            }
        }
    }

    Key points:

    • Constructor calls two methods:
      • InitContextVariables – which iterates through all of the  current Httpcontext.Current.Items and populate with their values custom context collection. After that, there’s code which implements event handlers for events published from context custom collection by using the lambda expressions. That’s how when ItemAdded event would be raised it would result with _httpContext.Items.Add method execution
      • InitSessionVariables – same story here. Code first populate custom session collection with the entries already stored in session and then hooks up custom events with appropriate HttpContext Session methods
    • Redirect method just delegates to _httpContext.Response.Redirect() method
    • User property delegates implementation to _httpContext.User
    • QueryString delegates implementation to _httpContext.Request.QueryString

    IoC container context service registration

    Now when we have service contract (IHttpContextService) and service (HttpContextServiceAdapter), the only thing left to be done is registering them into IoC container so presenters can use them in decoupled manner.

    Doing that is very simple… First we add a reference to Framework.Adapters to web application project in order to get access to HttpContextServiceAdapter class. Then we create a simple class called BootStrapper.cs into web application root folder looking something like this

    using Framework.Adapters.Web;
    using Vuscode.Framework;
    using Vuscode.Framework.Abstractions.Web;
    
    namespace Vuscode.Web.WebSite
    {
        public class Bootstrapper
        {
            public static void Init()
            {
                ServiceLocator.Register
    		       <IHttpContextService, HttpContextServiceAdapter>();
            }
        }
    }

    At the end we just add call to Bootstrapper Init method into Application_Start event handler of global.asx so our IoC container would be populated at the beginning of web application life cycle.  

    Solution in action

    Now when infrastructure is in place, implementing HttpContext related logic in presenter  is very trivial

    using Vuscode.Framework;
    using Vuscode.Framework.Abstractions.Web;
    using Vuscode.Framework.ModelViewPresenter;
    
    namespace Presenters
    {
        public class DefaultViewPresenter  : Presenter
        {
            private readonly IHttpContextService _httpContextService;
    
            #region .ctors
            public DefaultViewPresenter()
                : this(ServiceLocator.Retrieve<IHttpContextservice>()){ }
    
            internal DefaultViewPresenter(IHttpContextService httpContextService)
            {
                _httpContextService = httpContextService;
            } 
            #endregion
    
            public void SomeMethod()
            {
                string urlParam = _httpContextService.QueryString[“param”];
                if (!string.IsNullOrEmpty(urlParam))
                    View.Parameter =urlParam;
                if (urlParam == “nikola”)
                    _httpContextService.Redirect(“vuscode.com”);
            }
        }
    }

    At the beginning of the class we have standard poor man dependency injection combined with service locator thing.
    (In case you are not familiar with what I just said go and check one of my Design For Testability (DFT) posts)

    After we would inject the http context service it’s usage is exactly the same as it would be usage based on HttpContext.Current (which was one of the design goal) so everyone in your team should be able to start using it immediately 

    Unit testing HttpContext related presenter code

    The test og SomeMethod given above can be now written before the SomeMethod implementation and it doesn’t require  any Web reference.
    Here is the fragment of the test illustrating how simple now is to test the HttpContext related things in Presenters (complete test fixture code can be found in code sample archive attached at the beginning of this post)

            [TestMethod]
            public void SomeMethod_InCaseOfNikolaParamValue_WouldRedirectToVuscode()
            {
                using (_mockRepository.Record())
                {
                    // setting up the stage
                    SetupResult.For(_mockedHttpContextService.QueryString)
                        .Return(new NameValueCollection() { { “param”, “nikola” } });
    
                    // defining expected behavior
                    _mockedHttpContextService.Expect(x => x.Redirect(“vuscode.com”));
                }
                using (_mockRepository.Playback())
                {
                    var presenter = new DefaultViewPresenter
    				   (_mockedHttpContextService) {View = _mockedView};
                    presenter.SomeMethod();
                }
            }

    As you can see it from code above, to get url needed for test set up all one need to do is to set QueryString property of mocked IHttpContextService to contain desired URL parameters.

    Then I define expected behavior using new Rhino Mock 3.5 syntax for void methods where I said that I expect that redirection to www.vuscode.com would occur.

    Once the recording is over, in playback part I inject the mocked http context service and mocked view and call SomeMethod.

    Ain’ that piece of cake? :)

    What’s next?

    Today I showed how to implement TDD friendly http context and introduced new infrastructure component Framework.Adapters.
    My next blog post would introduce the role of Application controller in MVP (as a ported solution from WCSF)

    ‘till then…

  • Model View Presenter (MVP) – Tips from trenches (TFT) – Base types(Part 1)

     

     

    Intro

    RAD tooling style Microsoft is supporting last couple of years usually leads to the code where presentation and bossiness logic are mixed and tightly coupled which makes testability, maintainability and sustainability much more harder then they should be. In case you’ve had to work in the past with web pages containing couple of thousands lines in code behind you will know exactly what problems I am referring to here. In case not, please let me know what is the name of the place where you work :)

    One way to tackle that is using the Model View Presenter UI design pattern which provides clean separation between UI and domain logic and as a result of that come testability of the “UI code”, SRP and SOC principles appliance, clean domain model etc…

    In case you never heard about MVP pattern, before continuing reading this blog posts you might want to take some time and look at Model View Presenter (MVP) pattern (L100). In case you heard about it, but you are not familiar very much with what exactly it is, you might want to read about Supervising controller and Passive view. In case you are wondering what is the difference between MVP and “the one everyone talks about MVC”, I tried to explain that here. In case you are looking for advices on building new web site based on MVP pattern, the guys at Microsoft did great job with Web Client Software Factory, so check that out.In case you knew already all this but never had chance to apply MVP in real world and/or you face some problems applying it in real world, you are at the right place :)

    Purpose of this blog post series is to share with community my experiences on the typical hurdles I was witnessing during the MVP based web site implementation.

    Today’s hurdle: MVP wire up code noiseimage

    (Source code used in today example can be downloaded from here)

    Basically there are couple of ways to wire up  presenter and the view, but after some experiments with constructor based injection and after working for some time with Web Client Software Factory (WCSF) I kind a like setter based dependency injection style.

    Let take a look at that code noise through an example of simple web site with just a single Default page which would have a separate class library project containing view interface (which btw I name following the rule IPageNameView ) and presenter (convention I follow here is PageNameViewPresenter)

    The view interface could look for this example something like this:

    namespace Presenters
    {
        public interface IDefaultView
        {
            int SomeValue { get; set; }
        }
    }

     

     

    Here’s the presenter code example similar to a lot of presenters I’ve seen

    namespace Presenters
    {
        public class DefaultViewPresenter
        {
            private IDefaultView _view;
    
            public IDefaultView View
            {
                get { return _view; }
                set { _view = value; }
            }
    
            public void SomeMethod()
            {
                if (View.SomeValue>0)
                {
                    // do something
                }
            }
    
            public void OnViewInitialized()
            {
                // do something on view init 
            }
    
            public void OnViewLoaded()
            {
                // do something on view load 
            }
        }
    }

    Interesting points of presenter code:

    • Presenter has a View property of IDefaultView type
    • how presenter uses  view inside of SomeMethod()
    • existence of two methods which are supposed to be called upon page load and init

    Let’s take a peek now at how the view (default web page) would end wired up with the presenter

    using System;
    using System.Web.UI;
    using Presenters;
    
    namespace WebApplication1
    {
        public partial class _Default : Page, IDefaultView
        {
            protected override void OnInit(EventArgs e)
            {
                base.OnInit(e);
                Presenter = new DefaultViewPresenter();
            }
    
            protected void Page_Load(object sender, EventArgs eventArgs)
            {
                if (!Page.IsPostBack)
                {
                    Presenter.OnViewInitialized();
                }
                Presenter.OnViewLoaded();
            }
            
            private DefaultViewPresenter _presenter;
    
            public DefaultViewPresenter Presenter
            {
                get { return _presenter; }
                set
                {
                    _presenter = value;
                    _presenter.View = this;
                }
            }
    
            protected void Something_Clicked(object sender, EventArgs eventArgs)
            {
                Presenter.SomeMethod();
            }
    
            // Here goes implementation of IDefaultView
    
            
        }
    }

    Key points regarding view code:

    • OnInit method sets the Presenter property value to new DefaultViewPresenter instance
    • Inside of Presenter property setter View property of the presenter gets web page pointer casted to IDefaultView.
      Effectively, presenter gets injected with a view implicitly cast to view interface
    • Inside of page load method, presenter OnViewInitialized method is get called if the page is not postbacking itself
    • Inside of page load method, presenter OnViewLoaded method is get called regardless of postback
    • Last interesting moment here is how Presenter is get called  from a view in Something_Clicked event handler

    Hurdle summary

    Writing all of this code for every web page and every control (I will speak about this in later posts) is very tedious and repetitive task. Using WCSF helps a bit because code similar to this gets generated but still that’s a lot of lines written just in order to enable us to start to work on a page.

    Luckily, there’s a solution :)

    The solution of today’s hurdle would be encapsulating all of the code noise in set of base classes.

    The design goals here are:

    • define generic presenter which would be using generic view interfaces
    • define generic view which would perform automatic wire up to generic presenter

    Let’s see one way how this can be done….

    (My solution is based on Mario Szklanny’s Web Client Software factory solution, which I adopted for use outside of WCSF)

    Generic presenter

    The code related to this goal will be stored in a class library which I call Framework.

    Purpose of Framework assembly is to contain all the basic functionality required for most of the code regardless of it is web/UI related or not. image

    That’s why beside the MVP related code there would be (in my case):

    • ServiceLocator type (with code similar to what was described in  DFT Unity  blog post)
    • BaseClass and BaseCollection (very light, providing only basic functionality I personally use in debugging. Definitely NOT supposed to be  god class
    • More other things I won’t mention here (I would be adding them in the upcoming posts so I don’t want to spoil the surprise :))

    (In case you are puzzled with reasons behind having Rhino.Mocks reference in Framework, check this out)

    Key concern related to this class: No heavy dependencies and definitely no System.Web related references. This component is supposed to be able to be referenced by any component in application

    The IPresenter interface defines very simple generic presenter attributes

    namespace Vuscode.Framework.ModelViewPresenter
    {
        public interface IPresenter
        {
            object View { get; set; }
     
            void OnViewInitialized();
     
            void OnViewLoaded();
        }
    }

    OnViewInitialized and OnViewLoaded are methods we saw in above code as the ones handling calls from Page_Load method. The reason behind the fact that View  is of object type is that we can box any class to object type so we can store reference to boxed form of any view

    Generic Presenter class implementing the IPresenter interface could look like this

    namespace Vuscode.Framework.ModelViewPresenter
    {
        public abstract class Presenter<TView> : IPresenter
        {
            public TView View { get; set; }
    
            #region IPresenter Members
            
            object IPresenter.View
            {
                get { return View; }
                set { View = (TView) value; }
            }
    
            public virtual void OnViewInitialized()
            {
                /* do nothing*/
            }
    
            public virtual void OnViewLoaded()
            {
                /* do nothing*/
            }
    
            #endregion
        }
    }

    Looking at the code above one could realize next things:

    • Presenter class is abstract generic class accepting  TView generic parameter and implementing IPresenter interface
    • The two methods are implemented as virtual because we don’t want to enforce implementing this methods in each one of presenters inheriting generic presenter because some of them might not need some of those methods
    • The object View property defined by IPresenter interface is implemented explicitly which effectively hides it from the classes inheriting generic presenter
    • The fact that TView View property is public, combined with mentioned explicit implementation of the object View property effectively constrained View to TView

    Generic viewimage

    One of the main design principles I am trying to stay with is that Presenter assembly is not allowed to be dependable on System.Web directly or indirectly and therefore due to the fact that Presenters will reference the Framework, I can not put there generic view. 

    The reason why I can not do that is based upon the fact that each one of the pages would inherit from that base generic view, so generic view needs to inherit from System.Web.UI.Page

    All of the “base web UI” functionality I would keep in component called “Web.Base”

    From the solution explorer snapshot on the right side, we can see that project consists of 3 base views: page, control and master page. (Yes, I am applying MVP pattern even on the master page)

    using System;
    using Vuscode.Framework.ModelViewPresenter;
    
    namespace Vuscode.Web.Base
    {
        public abstract class ViewBasePage<TPresenter> : LegacyBasePage 
    						where TPresenter : IPresenter, new()
        {
            private TPresenter _presenter;
    
            protected ViewBasePage()
            {
                Presenter = new TPresenter();
            }
    
            public TPresenter Presenter
            {
                get { return _presenter; }
                set
                {
                    _presenter = value;
                    _presenter.View = this;
                }
            }
    
            protected virtual void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    Presenter.OnViewInitialized();
                }
                Presenter.OnViewLoaded();
            }
    
        }
    }

    Interesting moments here are:image

    • ViewBasePage is  abstract generic page where the generic parameter is constrained to type implementing IPresenter interface
    • ViewBasePage inherits from LegacyBasePage
      Most of us have some base page already in our web sites. This illustrates that the ViewBasePage should inherit from that page and then all of the MVP pages would therefore get access to that legacy base page and inherit all of the MVP related code
    • Rest of the code is the same code we had on default page just pulled out to base page level

    Code for generic view of control and master page is exactly the same as the page one with only difference from which base type they would inherit (UserControl or MasterPage)

    Solution in action

    Having Framework and Web.Base component built, would enable us to make changes in presenter and view which would cause them to look like this at the end

    View (Default web page)

    using System;
    using System.Web.UI;
    using Presenters;
    using Vuscode.Web.Base;
    
    namespace WebApplication1
    {
        public partial class _Default : ViewBasePage<DefaultViewPresenter>
    				    , IDefaultView
        {
            protected void Something_Clicked(object sender, EventArgs eventArgs)
            {
                Presenter.SomeMethod();
            }
    
            // Here goes implementation of IDefaultView
           
        }
    }

     

    The page just inherited form ViewBasePage<DefaultViewPresenter> and all of the plumbing code is gone from the page

    Looking much better, isn’t it? :)

    Presenter

    Presenter is even simpler

    using Vuscode.Framework.ModelViewPresenter;
    
    namespace Presenters
    {
        public class DefaultViewPresenter  : Presenter<IDefaultView>;
        {
            public void SomeMethod()
            {
                if (View.SomeValue>0)
                {
                    // do something
                }
            }
        }
    }

    All presenter had to do is to inherit from Presenter<IDefaultView> in order to get View injected and potential to override OnViewXXX methods

    Looking much better, isn’t it? :)

    What’s next?

    Today I showed how to remove code noise from the MVP related types and also set up the foundations of two components: Web.Base and Framework. My next blog post would be expanding a bit framework component in order to show how to work with HttpContext related concepts and values without referencing System.Web into presenters

    ‘till then…

     
  • Model View Presenter (MVP) – Tips from trenches (TFT) - Announcement

    I have blogged already in the past about MVP basics, MVP vs MVC, MVP Passive View and MVP Supervising Controller but recently I had some interesting experiences in applying MVP into real world applications and from that endeavor I learned couple of things and get answers on couple of common questions which I would like to share with community.

    To me, the most interesting part of this experience was that some of my MVP based coding was done using Web Client Software Factory but part of MVP coding was done without it, so I had to “port” WCSF features to standard asp net application. I would describe pieces of that port which (I guess) would be interesting for the ones not being able to sell WCSF to their managers but still wanting to use MVP in their ASP NET development.

    Another thing I would try to explain is something a lot of people don’t know: Microsoft MVC .NET framework consist of two separate parts: MVC and routing engine. In other words, routing engine is not part of MVC design pattern and it can be used with WebForms too…

    Another very important thing in real world MVP development I would try to demo is how to introduce MVP pattern usage in legacy components where the legacy model is not written in decoupled manner (Separate interface, Adapter and Translator design patterns)

    Last, but not the least, I would show how MVP pattern is looking combined with ServiceLocator I presented in Design For Testability blog post series and show examples on how to test MVP

    Once I finish presenting all this, I would use presented concepts in showing how “one interesting "real world" example” would look like done with MVP pattern and standard WebForms

    So, MVP fans stay tuned for the posts to come very fast. People not interested in MVP, please be patient… I just need to nail down MVP , “once for all” :)

    Disclaimer: The purpose of this blog post series will not be showing that MVC based web development is worst then the MVP one. MVC is awesome but unfortunately requires too big investments to be introduced in existing large web forms web applications (most noticeably the need for redesigning all code which relies on page event life cycle). For those brownfield scenarios, I found MVP much easier to be implemented and adopted by webform developers then the MVC.

  • Adobe Air 2008 Tour – Prague

    For a few of you reading my blog, this blog post would most definitely come as a big surprise knowing how passionate iPhone 172
    I am about SIlverlight and all related stuff.

    Well, although I believe that the real thing is Silverlight, I wanted to check out how the “other side” looks like.

    Considering the facts that level of my previous experience with DW, Flex, Flash and Air was zero and the fact the sessions have been presented in Staropramen brewery building I anticipated a lot of cool thing to learn and some beer to be drink.

    Both of my expectations were fulfilled.

    Before I start

    Before I start “pasting” my notes and observations from the OnAir  Adobe day, I can not avoid mentioning first the other event organized last week by Microsoft here in Prague, “Silverlight for developers”

    Not to be too much inflammatory here, I would just say that I was really disappointed with this Microsoft event.
    I was there only one hour because I didn’t want to waste of more time but during that time:

    • I saw a demo how small “flash like” games you can make with Silverlight
    • I saw a demo how with Silverlight 2.0 can make media player
    • I saw a bunch of false information's about competitors (e.g. Flash/Flex not supporting web service calls)
    • I saw whole one slide about Silverlight architecture shown in about 15 seconds and 4 sentences
    • I saw the same egg example used at literally every Silverlight presentation here

    What I didn’t saw there in that one hour is:

    • Presenter excitement about breaking and revolutionary new technology SL truly is
    • Business value Silverlight has (beside games and video players)
    • That Silverlight is NOT media player plug in
    • A big picture about how Silverlight relates to ADO Net Data Services, FeedSync, Entity framework etc
    • Why I should choose Silverlight instead of Ajax, WPF, Flex, Flesh, Air etc

    Anyhow, I saw a bunch of people taking notes so I guess the decision to make sub L100 session was the right one after all for majority of developers attending the presentation.

    Keynote

    Keynote was done by Ryan Stewart (rstewart@adobe.com,twitter:ryanstewart) who is Adobe Program Manager.

    His main points were that Flash is deployed to 99% of the computers with 8 million installations/day, with a very efficient flash sandbox update mechanism (when they roll out Flash 9 it took them only 12 months to complete update of most of Flash 8 sandboxes runing on client computers)

    He pointed that they have a long wining tradition of being the trend setters (Acrobat reader 1993, Adobe Flash 1995, Adobe Air 2008)

    Then he outlined their vision with a nice diagram showing the Adobe ecosystem where Flash covers the web needs, AIR desktop segment with Flex  providing client framework for both of them

    <place for diagram>

    Flash 9 has significant improvements in areas of multilingual support and localizations enhanced visual performances (with GPU hardware rendering, Rich media support and Dynamic streaming (streams optimized per user bandwidth), 3d visual effects (transitions and transformations)

    Most of the thing they mentioned as new in Flash 9 I can see similar to Silverlight/IIS7 stack and that is great because Flash/Silverlight crosspolination would bring only benefits to us developers

    And then he mentioned what is Adobe Air… :)

    image

    “Adobe AIR enables web developers to use existing technologies to build and deploy rich Internet applications on desktop

    My first reaction was:”Dough?”. I came here to see how Air compares to Silverlight and realized that they are not competing at all. In fact they are two technologies taking totally opposite directions:

    • Silverlight takes direction where he moves desktop programing model (WPF, .NET) to web by executing “desktop” code in SL sandbox
    • Adobe Air is opposite allowing web programing model (jscript, html, css) to be executed on AIR Sandbox allowing us doing the desktop applications using Web technologies

    I would say that behind that technology differences, there are two different business models Adobe and  Microsoft are playing on:

    Adobe plays on the fact that web applications and web developers are already deep into the enterprise so reusing the already built web applications “free of charge” in desktop environment and the same skill set of web developers. Sales pitch: “you already have the site. desktop enable it!”

    Microsoft sales pitch (IMHO) is slightly different:“We know how hard is to do web development so we have a sandbox which removes the need for web development. You just do the “client like" development without having to face the same problems you are facing now.”

    Ryan then show couple of demos, how RIA desktop application can look

    image

    image

    image

    He showed web application application done for NY Times http://www.shifd.com/ which has support for Air and demo how web site and client application cooperate. He also showed how you can SMS the data and told that iPhone support exist. Having the same app running on multiple platforms (Air and Silverlight) looks very important to both Adobe and Microsoft which I can understand considering how Mobile market is getting more and more business value .

    shifdexample

     

    He summarized at the end why we would like to do to RIA AIR development at the end:

    - Persistent connection (offline support)
    - Branded experiences (not limited by browser, pick your won window shapes etc)
    - Desktop functionality (file system, notification windows, SQLLite local DB support)
    - Data access (REST, HTTP, SOAP - same as you do in Web)
    - Efficient development 

    Building AIR application can be done free (There is free AIR free SDK and Flex SDK) but for best productivity use:

    -  Adobe products –> Fx, Dw, Fl (support for debugging, packaging for Air) or
    -  Eclipse Aptana  which is 3pty tool plug in for Eclipse

    Air future: Air 1.5 version would sync with Flash Player 10, sync up with WebKit capabilities.

    For more general level information's he recommend use of a central URL: http://www.adobe.com/go/ria 

    Hello world  in Adobe AIR

    Mike Chambers (www.mikechambers.com)  then had a small session showing how to do do hello world application using Flex Builder and AIR

    He pointed that Flex Builder is built on top of Eclipse.

    It was standard presentation where he created new Flex Project, picked on second screen that he wants to create desktop application and the default project was created (check out Flex 3 help file for how to build AIR applications with Flex 3 for detail instructions)

    Default project has two application files:

    AIRHelloWorld.mxml root application file which would be compiled to swf containing markup and ActionScript/JScript code
    AIRHelloWorld.xml - application description file (defines metadata needed by runtime: filename, files needed etc)
    Some of the elements defined in application setting xml file are:

    • <id> - unique app identifier com.mikcehambers.AIRHelloWorld (not seen by users)
    • <name> - name of application (user sees, add/remove programs, shortcuts etc)\
    • <version> - exposed to application used for auto update
    • <description> simple description which would appear on installation screen
    • <initalwindow> - elements specifying how app launch and how it looks when launch
    • <systemchrome> – values: STANDARD/NONE) – standard gives the standard windows chrome regardless of what OS user have,  none gives opaque window, without maximize, minimize buttons, title bar etc
    • <transparent> (used in combination with systemchrone -> none with true window allows having irregular shape windows)
    • <visible> default false! Once the app is ready to go set it to true (Dynamic layout)

    Note: Adobe MXML looks very, very similar to XAML!. Not sure if they have cool stuff like extensions, dependency and attached properties etc, but I can read MXML markup code without any problem

    Once the hello world app got a button in center of window and a AIR logo image in right corner, Mike exported it to release build (Project/Eporrt to release build menu item). Interesting thing regarding the building process is that AIR applications HAVE TO digitally signed (one of wizard steps ask for certificate location – with an option of temp signing in)

    This is how installing AIR application looks like
    image image

    And the message I got on my lap top after that :) (installed app was still working after that )

    image

    After hello world app was done he spoke about jscript to Air book and Flex reference poster, pointed to  www.tostring.org web site which contains online version of those books and to http://onair.adobe.con/blogs/tour as place where to go to grab presentation material from presentations made on tour.

    Adobe AIR done with Jscript

    This presentation was done by Kevin Hoyt (khoyt@adobe.com, http://blog.kevinhoyt.org) which started his presentation by doing a demo of CleVR.com site done in AIR where he uploaded couple of his panorama photos he made yesterday with his 10 MPix camera. The site took couple of his pictures and stitched them into one panorama wide picture. He emphasized couple of times that the pictures are very big and that the AIR app is smart enough to melt them together resolving their intersections automatically.

    Who said Silverlight DeepZoom? :)

    He used FlexSDK (can be downloaded from here  for free) together with Notepad (whatever the OSX name for Notepad app is) and showed how a simple standard HTML page with standard HTML tags would execute on on desktop.
    Beside the free tools, DEV could download the Dreamweaver CS4 beta from labs.adobe.com or download a AIR extension for Dreamweaver CS3. Another option is 3pty plug-in for Eclipse called Aptana which contains (beside other things) a lot of examples how to do most of  the common activities with AIR.

    He presented then very important file in FlexSDK, AIRAliases.js which performs mapping of AIR types to jscript classes.

    That’s how while working with jscript classes you are using in fact the AIR. He showed a demo of how from jscript code he can  write files to local hard drive using the mapped functionality

    He pointed also to two different commands for adl and adt (where adl allows testing air application without installation – useful for real world development)

    Integrating HTML, JavaScript and ActionScript ("ScriptBridging")


    Kevin Hoyt also did the next presentation called script bridging where he show different examples of integrating different scripts.

    He was using on this presentation Flash CS3 to show couple of demos:

    • Drag & drop functionality
    • Accessing CSS elements directly from AIR
    • How to create a browser wit some cool extensions
    • How FlexBuilder enables browser DOM debugging directly in ActionScript.

    An example of how to access DOM he used was through htmlLoade class, something like this

    web.htmlLoader.window.document.getElementById('txtName').value;

    An example of how to access flash library from AIR

    air.FileStream = window.Runtime.flash.filesystem.FileStream

    He showed also a demo of jscript application reading the content of the zip file using the library.swf ActionScript library done by David Cheng directly by jscript. According to him, this approach allows us (even if we want still to  keep jscript applications to enrich them with functions they wouldn’t have without script bridging.

    At the end he mentioned that on his blog (http://blog.kevinhoyt.org) example with zip library, custom hrome and custom grid done with CSS and jscript can be found

    Czech Flex user groups

    After the lunch (Staropramen beer, lots of tasty food on a perfect day – thanks Adobe! :) ) we had two short presentations on Czech/Slovak.

    First one was presentation of Flex user group done by Juraj Michalek (www.flexgarden.net).
    Key points: bunch of Air and Flex online seminars on their site and he said they are very willing to provide their help through their Flex user group at
    flexgarden@googlegroups.com

    Second presentation was done by authorized Adobe partner which host the   www.flash.cz site with more then 60 articles for beginners  on flash and flex and also with expert answers provided for Flex developers.

    Deploying and updating AIR applications

    Platform Evangelistsimage
    Serge Jespers
    serger@adobe.com
    http://sergejaspers.com

    Jasper showed how to deploy and update AIR application in 3 simple and straightforward steps

    1. Get your application signed
      Adobe AIR application have to be signed by some certificate so during the installation of AIR application publisher identity would be known (green icon). He mentioned that most of certificates we have now would probably be ok for AIR. In case we don’t have any certificate he recommended buying one for $299/year from thawte.com)For a limited number of applications uploaded to Adobe AIR Marketplace , Adobe would provide complimentary code signing certificate (http://adobe.com/go/marketplace )
      Once we have the certificate, signing application is very easy: all we need to do in Step 2 of publishing AIR application we need to provide location of certificate file and password and that’s all.
    2. Deploy your application
      Bad way to do that – zip air app and provide a link on site – sucks big time
      Good way: use installation badge which is kind of customized installation screen where user clicks on install button
      and the application install application and AIR (after showing two security informational screens) .
      Adobe provides 3 types of badges: standard, beta and custom.
      1. Standard is available in AIR SDK, ready to use now but only with standard use cases. Source available
      2. Beta badge – available on http://labs.adobe.com. Cool new look and extra features (can show video, help functionality)
      3. Custom badge – developer have to define everything. Most powerful, but also most complex to implement
    3. Update your application in five simple steps (Adobe “ClickOnce”)
      1. Check from application if server contains XML update file  containing information on current application version
      2. Check then if installed application is older then version on server
      3. Create instance of the Updater class
      4. call Updater.Update method
      5. Updater would close AIR app, install new version and then restart the Application

    Application update – DONE!

    ==============================================

    AIR API Overview

    Daniel Dura
    www.danieldura.com, ddura@adobe.com 
    Platform evangelist, Adobe

    iPhone 113iPhone 114DB support darag&drop clipboardmisc

    All of the examples he presented are available on his web site illustrating all of the common usage scenarios.

    He was speaking about 6 major API function groups

    1. Window API major API features:
      - Multi window support
      - Transparent windows
      - Window types  (Standard, Utility and Lightweight)
      - Z-Ordering
      - Always in front window
    2. File I/O major API features:
      - Full Read/Write access
      - Native File dialogues (save, select, select mutliple, directory)
      - Async and Sync APIs
      Note: I really don’t get why Adobe supports async mode. Due to the fact that browser is single threaded, file I/O operation would block the whole browser. To me that feature looks like a nice rope Adobe gave us DEV to hang ourselves :)
    3. Database support
      SQL Lite DB support
      Zero setup single file
      SQL Lite stores all data in one file using applicationStorageDirectory comand –> (Silverlight IsolatedStorage)
      SQL Lite supports transactions and the sql code executes 10x faster when using transactions (reducing number of file I/O operations)
      To me SQL Lite is trying to do exactly the same as Microsoft Compact SQL Server with more limited stack of operations.
    4. Drag & Drop/Clipboard
    5. Web services support
      He showed an example how to detect internet connectivity status by pininging google.com  by doing something like this
      new UrlRequest(www.google.com) class
      request.method="HEAD";
      URLMonitor(reuest)
      monitor.addEventListner(StatusEvent.STATUS, handle_status)
      monitor.start();
    6. Misc - Encrypted local store
      - dock notifications
      - idle notifications

      

    Google App Engine

    Dion Almer, cofounder ajaxian.com, works at Google code

    iPhone 121iPhone 123

    At the beginning he showed http://prague.360cities.net/ flash application powered by google maps  which looks to me as Microsoft Deep Synth competitor (Altpught DeepSynth is much more serious, compare their example with the one from 360cites site)

    The rest of the session he was speaking about Google app engine which should help building developers scalable sites in Python for free (to up to 5 million page views)

    Another Interesting thing (I’m sure my friend Lorenzo Bolognini already knows about it)  is that Django Python framework is fully supported (except ORM features)

    http://code.google.com/appengine

    Another interesting question he answered was”

    “What if popular JavaScript libraries were available and shared in the browser?“

    Well, instead of each one of us hosting jscript libraries, Google host at http://code.google.com/apis/ajaxlibs/ jscript libraries for jquery, 

    Data intensive AIR Applications

    Andrew Shorten

    iPhone 126iPhone 128  iPhone 130

    I was expecting a lot from this sessions because seeing what Adobe has to offer in this area is very important for LOB applications/sites, but I get the least from this session.

    The reason why lays in the fact that most of his presentation was wrapped around Adobe specific Blaze DS and Live Cycle server which are providing server side infrastructure for efficient RPC type of communication.

    He showed example from http://www.jamesward.com/census on what performance gain usage of Adobe servers  brings to game which looked nice but he mentioned that the data transmitted is in binary format (AMF3) with RPC which is not very firewall friendly. In post RPC era I believe we are messaging should be done by open protocols on firewall friendly ways

    The difference between the Blaze DS server and Live Cycle server (beside Blaze being Open Source solution) is that Live Cycle server supports offline scenarios allowing applications talking to services to work even application would be offline and Live Cycle Data Service server would take care about  synchronization and conflict resolution once the Internet connection would be up again.

    Live Cycle Data Management services have XML configuration file (like the BlazeDS has) where user defines SQL adapters with the sql scripts. Original CRUD operations are modified there to support the offline/online updates which occurs on commit (and use the xml defined data). So we have a XML file filled with dynamic SQL statements. Good thing that none of the DBE were not attending because I’m sure there would be DBE yelling  in that moment.

    To me this example looked very familiar with “Astoria offline” demo from Mix ‘08 and I am feeling much more comfortable with solution based on REST Atom services/ FeedSync based solutions (which is btw free) versus something which looks like closed Adobe product.

    Couple of useful links:

    Blaze DS
    http://opensource.adobe.com

    Live cycle (additional options as support for offline, conflict resolution etc)
    http://www.aobe.com/products/livecycle (1 CPU license for free)

    http://www.adobe.com/devnet/livecycle

    AIR + Ajax


    Andre Charland, CEO, Nitobi.com
    Enterprise Ajax book, RobitReplay.com, InsideRIA blog
    http://blogs.nitobi.com
    http://www.insideria.com
    twitter.com/andrecharland

     iPhone 135iPhone 138   
       iPhone 146 iPhone 140 iPhone 148

    This guy REALLY likes jscript. According to him we should be all doing jscript everywhere and anytime. And the examples he showed give him a lot of credibility in that :)

    Why Ajax in AIR?

    - Code reuse (we already have a bunch of jscript code)
    - Skill reuse (we already have a bunch of jscript developers)
    - HTML is REALLY good at some things ( build blog reader only in flash is not having sense)
    - maintain UI patterns (same UX for web and desktop)
    - JavaScript interest in DEV community is growing  (important if you are hiring)

    He showed some data graphs about sales of programming languages books showing that jscript interests is growing rapidly.

    He demo couple of very interesting applications using AIR:

    • AIR twitter client: www.getsnitter.com (jQuery, custom chrome, transparent, word count, notifications)image
    • SalesForce.com desktop client done in AIR (adobe tree controls, drag and drop of vCards)
      image
    • Robotreplay – story of usability with youtube example where everything user is not looking directly is blurred
    • MacDoc wanna be – fisheye , jscript, css and png files rotating
    • Spreadsheet like greed  (Wizard defining data binding of grid, column mapping, live scrolling or paging etc
      Dreamweaver creates php, jscript, css)
    • Nice bubble tooltip creation tool
    • ReadAIR – jQuerty built google reader clone
    • Snippetly – stores code snippets in SQL LIter (writen in jscript using Mootool linrary)
    • VOIP and SMS in AIR demo
      Tabria  client which calls the phones of both of people in chat using the local lines and allows them to talk over the Tabria network and/or to send SMS messages

    Then he was speaking about some usability pitfalls in AIR:

    - Keyboard shortcuts
    - Minimize, move close when "chromeless"
    - Mouse hints, invitations, tool tips

    Activity indicators have to be implemented explicitly

    At the end he mentioned that http://www.nitobi.com/air has bunch of useful links

    nitobi.com/air
    has bunch of links

    AIRconditioning

    Lee Brimelow
    Platform evangelist/Adobe

    http://www.gotoandlearn.com (free video tutorials about flash)
    http://www.theflashblog.com  (all of the slides he was presenting should be there)
    (worked at frogdesign  before adobe)

    iPhone 152      iPhone 163
    Lee did awesome job showing us what we can do with AIR in very funny way. His presentation started with “Flash vs Flex” where he recommended:

    • use Flex when in need for : Application layout, data binding, superior coding expereince, components sets
    • use flash when in need for: Animation, Video etc…

    He then started doing his demos:iPhone 156

    1. Windowing demo He presented an application creating different types of windows (Normal, Utility
      and Lightweight) combined with different Chrome options (System, Custom (Opaque) and
      Custom (Transparent). He also showed “staying on top” of windows and full screen mode  where air capture keystrokes even in full screen mode.
      Examples he used to show this were:
      - Hell’s kitchen custom chrome video player, 
      - a nice sidebar staying always on top with a collection of buttons producing different farts
      (Seeing that no one is laughing on that, he said “This would be really funny in US”)

      - Boss application
      He opened a game and a Safari with PiratesBay site where he typed CS3 and the list of pirated version with pirated serial keys downloads appeared (really funny), and then he press the boss key and  
      iPhone 159iPhone 160iPhone 161
      - Papervision 3D
      Thanks to using of GPU hardware acceleration, he showed really fast 3d carousel with live videos
    2. Menu-ing API
      He presented that AIR supports OSX Application menu and Windows\Linux window menu (menu attached to application window, under title bar)
      Developer have to do checks in the code during the run time to see if a given type of environment supports some type menu or not. He showed support for Dock menus (Mac only) and System tray menu(windows).
      An example he used to demo the functionality is called :SpitEmOut and it is awesome minimalistic video player with snapshot capabilities , where every snapshot taken is randomly aligned around video player
       iPhone 167iPhone 170iPhone 169
      When he was showing that context menu is not containing any “About Adobe Flash” entries (fully customizable) he called that “no Adobe usual crap in menus”   Hilarious …
    3. File class
      Worth of mentioning here (which was not mentioned before) is that AIR is in advantage over the Flash 9 with file related functions, but Flash 10 would have all the AIR file features (writing to local disk, reading from disk etc). The size of encrypted local storage is 10 Mb per application and encryption used is the default one of the user OS
      Example he tried to show to us was downloading FLV file from you tube but that didn’t work (my guess due to WiFi network being down at that time)
    4. Drag & drop functionality
      Supported D&D modes:
      - Application <->Desktop
      - Application <-> Application
      - Application <-> Browser
      You can customize the drag & drop picture.
      Example: Flash video player dragging the FLV video file to video player example
    5. OS Interaction.
      Supported: - Launch on user login mode
      - File associations (full manipulation)
      - Tracking user presence (application is aware of user being idle where idle threshold must be more then 5 seconds) - Control over application invocation and termination through appropriate events
      - Only one instance of one AIR app can run at the same time
      Example:
      Vista UAC
      ------------------iPhone 168

      The example he had was targeted to Microsoft and Vista UAC. He made a  little app which was after user was idle for 5 seconds popping up a dialog with a message like "Are you sure that you want to move mouse?"  in a dialog box looking like Vista dialog box (grayed background, system colors etc)
      A bit to much Mac-ish for my taste. Speaking about Macs: guys from Adobe looked really surprised when they saw a minority of people raising hands on “Who’s Mac owner”… I guess that’s because in US Mac has much higher penetration in the Adobe user group. Each one of the presenters was using Mac for its presentation


      FileTyper virus
      -----------------------------
      With AIR you can associate any file type on user computer to AIR application. He showed an example where he switched application handling the FLV files to start up his GoogleAds AIR application.
      I can see a bunch of people trying to do the same thing and I am not sure how AV software would prevent this because in a sense it is not real virus but the effect (in case of most users) would be the same as you have Trojans in your computer
      WiFI example
      -----------------------------
      AIR can get information from Wireless card about available networks. He used this example to show us how to pass start up parameters to AIR application. Also he showed network connectivity  AIR functionality together with cross application communication (AIR to AIR, AIR to SWF (through local connection)

    Conclusion

    Adobe organized great event here in Prague where even persons like me (new to Adobe ecosystem) get a lot of important information's.

    To me the most important thing I was hoping to get answer on was: How Adobe offerings compare to Microsoft Silverlight stack.

    The answer I got can be summarized as: Adobe doesn’t have a chance on long run. The only thing they have huge advantage is  Flash plug in penetration (99% of browsers) but IMHO is just matter of time when MS would get similar figures with SL.

    Here’s the comparison (although it is hard to figure out what to compare “AIR vs SL” or “AIR vs WPF’

    Languages

    Adobe is limited to ActionScript and jscript. Silverlight supports CLR (C#, VB)  and  DLR langauages (Iron Python and Iron Ruby) - including even php support through Phalanger project.

    The decision Microsoft made in SL 2.0 to get rid of the jscript in favor of .NET languages is perfectly fine with me.

    Tooling

    Although I was surprised with how good Flex Builder 3 and Flash IDE’s are (thanks to Eclipse) my opinion is that they are still not match to VS IDE offerings (standard with or without plug ins).

    Microsoft Blend in version  2.5 is “still not right there” but it is making big steps toward being designer friendly tool. IMHO, all Blend needs is mainstream adoption from designers which would bring significant feedback “from the trenches” which is only thing Blend team need. I am not even sure that the people criticizing it is not criticizing it because mostly “it is different then Flash”… Ah, time would tell about this

    Very important difference here between the platform is that (according to demos I saw) there is no “code behind” in Adobe case (markup and ActionScript code are mixed) which definitely makes  life difficult in case of multiple personas working on the same file (conflict resolutions etc)

    DB support

    Microsoft SQL Compact and Adobe SQL Lite look like doing the same thing on same way (no installation, app local database). I am biased a bit, but SQL Compact coding model (standard ADO NET code) looks more robust and powerful then the one I saw for SQL Lite

    Web services

    We are living in SaaS and S+S era, so Adobe proposal of using propitiatory AF3 binary format with RPC communication style looks not very convincing.
    In Microsoft stack we have WCF supporting a bunch of different messaging protocols. There are also ADO NET Data Services with their RESTfull Atom\Rss API.

    LiveCycle offers a offline mode with syncing and conflict resolution, but having FeedSync and Astoria already and Astoria Offline prototyped at Mix ‘08 removes that advantage for me.
    The big differences here are :

    • FeedSync and Astoria can work with ANY sync and data provider
    • MS Offering basically comes for free

    Web/Win/Mobile code reuse

    Adobe AIR tries to bring the html/jscript support to the desktop, which has sense on short term but I don’t think anyone would really like to do their desktop applications coding in jscript. Also, Adobe take on mobile phones support is that they al support jscript, html and most of them Flash which might and might not be true, but still (AFAIK) requires serrate coding

    Having SL as “a subset of WPF” and heavily investing into the WPF/Blend with the whole machinery MS has would (I’m sure) bring much more code reuse in case of SL/WPF then the Adobe offering. Mix ‘08 mobile demo showed SL supported on Nokia phones and windows mobile powered smart phones where the same application written for WEB/WIN would works on Mobile thanks to the WPF built in scaling features

    Summary

    We didn’t saw any demo about acceptability, internationalization features etc.. which are the features supported very well with SL… Having whole stack of supporting technologies (Entity framework (it will get right in V2), SQL Data services), best customer support (books, videos, MS evangelist, training etc) most of those technologies totally free with source code available makes this a clear choice to me:
    Silverlight rules! :)

    Posted VI 10 2008, 10:56 dop. by malovicn with 5 comment(s)
    Filed under: ,
  • Design for testability – Auto Mocking Container (AMC) – Part 9

    On my quest to design for testability, I've already covered:

    My today’s post would be covering AutoMockingContainer (AMC) in both “standard” and “service locator based” versions

    What is auto mocking container (AMC)?

    I’ll use the example from original Elutian blog post (where the concept of AMC is first mentioned) where the test setup code looks like this:

    [SetUp]
    public void Setup()
    {
      _service1 = _mocks.CreateMock<IService1>();
      _service2 = _mocks.CreateMock<IService2>();
      _service3 = _mocks.CreateMock<IService3>();
      _serviceWeAreTesting = 
           new DefaultServiceWeAreTesting
                (_service1, _service2, _service3);
    }

    This example applies transparent dependency injection style described in previous post with a class expose a constructor accepting many interface parameters "(“services”) to which class functionality is dependable on.  On first look, there is nothing wrong with the example above but once you would be doing serious testing you would probably find out two things:

    • (PIA) during test creation you would probably feel that it is too much “plumbing” code to be done to support testing
    • (REAL PIA) long after once the tests would be done someone would add to that class constructor another parameter (“service4”) and each one of the tests you created would start crashing although probably the functionality you were testing is not relying on _service4 at all.

    To tackle those two issues, smart people at Elutian combined Rhino mocks and Windsor container to tackle those problems.

    Using AMC the same test setup code would look like this:

    [SetUp] 
    public void Setup() 
    { 
      _mocks = new MockRepository(); 
      _container = new AutoMockingContainer(_mocks); 
      _service = _container.Create&lt;DefaultServiceWeAreTesting&gt;(); 
    } 


    As you can see, in case of AMC we construct AutoMockingContainer with MockRepository instance thrown as parameter.

    That allow’s us to replace explicit mock creation and concrete constructor invocation with AMC container Create method which accept as generic type parameter the type we plan to test.

    Windsor would then find out the constructor which needs to be used and for each one of the service interfaces (if they are not in container) would create a dynamic mock class implementing given interface (thanks to Rhino mocks).

    so now when we have this initialized writing the test is much simpler and looks like this (taken from the same Elutian blog post)

    [Test]
    public void DoWork_Always_AsksOtherServices()
    {
      using (_mocks.Unordered())
      {
        _container.Get&lt;Service1&gt;().DoWork();
        _container.Get&lt;Service2&gt;().DoWork();
        _container.Get&lt;Service3&gt;().DoWork();
      }
      _mocks.ReplayAll();
      _service.DoWork();
      _mocks.VerifyAll();
    }

    As you can see, we are not explicitly constructing service class and registering services to container. AMC container already created instance and add components to container in setup method so all we need to do in test is to use them.

    Obviously:

    This is much shorter to be written –> issue #1 is solved.

    Even if we would add additional  constructor parameter the AMC would recognize that IService4 was added and it would add its mock to container effectively preserving the test not depending on IService4 runable  –> issue # 2 resolved

    (To get AMC source code which you can compile on your box and use, click here)

    Auto mocking container and Unity

    As I mentioned above, the AMC solution given above is for Castle Windsor IoC framework and my IoC framework lately become Microsoft Unity (due to the reasons stated in DFT Unity post), so I did little search for Unity AMC and found out that Roy Osherove implemented it already.

    Roy provided in that blog post example how test looks:

    [Test]
    public void MockTwoDependenciesForAConstructor()
    {
    	MockRepository mocks = new MockRepository();
    	AutoMockingUnityContainer container =
            	new AutoMockingUnityContainer(mocks);
    
    	container.WillReturnAStubFor<ILogger>();
            container.WillReturnAStubFor<IEmailer>();
    
    	using (mocks.Record())
    	{   
    		//Tell our mock to return true when this method is called
            	container.Resolve<ILogger>().IsLogFileFull();
                    LastCall.Return(true);	
    	}
    
    	//runner class takes both of these mocks in its constructor
            Runner runner = container.Resolve<Runner>();
            Assert.IsNotNull(runner);
    }

    Well, although his implementation is VERY cool way of “create mock and inject it to container”  it is not (at least how I get it) the AMC like the one Elutian guys did because I am still expected to define stubs and inject them to container explicitly (although on short&easy way)  (issue #1 still exist).

    But, #2 (more important one) is handled with this because test code not depending on the additional dependency wouldn’t crash.

    So, all in one, if you do IoC with Unity go to mentioned Roy blog post and copy paste the Unity AMC source code for your own usage.

    Auto mocking container – my way

    Well, as I presented in previous post, currently the way I am writing and testing my code is that I declare internal constructor accepting the dependencies and perform mock injection without using of any IoC framework.

    But, even for me issues #1 and #2 are not a big problem (I don’t mind declaring mocks and I WANT my test to crash when tested lass change so I have to check out the tests), I can imagine that for some of people this wouldn’t be the case. For them, testing on the simplest possible way with #1 and #2 resolved would be “have to” requirement.

    The good news here is that there is solution for this almost “out of the box” thanks to the design decisions I made in previous posts:

    • I would have Facade component (ServiceLocator) encapsulating concrete IoC framework usage
    • Default constructor performs “poor man dependency injection” using the ServiceLocator

    If we think about what the problem really is AMC tries to solve we would come up with something like this:

    “When IoC container is asked to retrieve a type implementing some interface and that mapping is not defined, return a mocked instance of the interface.”

    And that is exactly what I would do…

    Modifying ServiceLocator

    ServiceLocator class is going to support testing mode when instead of IoC container exception throwing (for cases of no type can be retrieved from IoC container for a given interface) ServiceLocator would create a new mocked instance. Something like this:

    using System;
    using Microsoft.Practices.Unity;
    using Rhino.Mocks;
    
    namespace Facade
    {
        public static class ServiceLocator
        {
            private static readonly MockRepository _mockery 
                = new MockRepository();
            private static readonly UnityContainer _unityContainer
                = new UnityContainer();
    
            public static bool TestMode { get; set; }
    
            public static void InjectStub(I instance)
            {
                _unityContainer.RegisterInstance(instance
                    , new ContainerControlledLifetimeManager());
            }
    
            public static T Retrieve<T>;()
            {
                try
                {
                    return _unityContainer.Resolve<T>();
                }
                catch (ResolutionFailedException e)
                {
                    if (TestMode)
                    {
                        return _mockery.DynamicMock<T>();
                    }
                    throw new InvalidOperationException(“Can't resolve dependency.”;, e);
                }
            }
        }
    }

    As you can see service locator now has dependency to Rhino mocks (MockReporsitory class) which is ok IMHO. There is also TestMode new boolean property which represents the way to switch ServiceLocator from production to test mode. Retrieve method now puts IoC Resolve method call inside of try block. In catch block there is conditionalization based  on TestMode value: in case ServiceLocator is in test mode mocked instance is returned and in case ServiceLocator is in production mode Unity exception is been bubbled up.

    And that would be all what we need to do to support custom AMC.

    Writing tests using custom AMC

    Now when we have the AMC container done, let’s check out how the test from last blog post would look like now with custom AMC used.

    Let add first additional dependency to UserManager constructor so we would have the right use case for AMC (original constructor had only one IUserProvider in which case AMC usage doesn’t have sense)

    So the UserManager class would look after that modification something like this

        public class UserManager : IUserManager
        {
            private readonly IUserProvider _userProvider;
            private readonly ISomeOtherDependency _someOtherDependency;
    
            public UserManager()
                : this(ServiceLocator.Retrieve<IUserProvider>(),
                       ServiceLocator.Retrieve<ISomeDependency>()) { }
    
            internal UserManager(IUserProvider userProvider, ISomeDependency someDependency)
            {
                _userProvider = userProvider;
                _someOtherDependency = someOtherDependency;
            }
    
            #region IUserManager Members
            public int NumberOfUsersActiveInLast10Days(string userName)
            {
                var userCollection = _userProvider.GetUserCollection();
                var result = 0;
                foreach (var user in userCollection)
                {
                    if (user.Name.StartsWith(userName) 
                        && user.LastActivity > DateTime.Now.AddDays(-10))
                        result++;
                }
                return result;
            }
            #endregion
        }

    Note that constructor now have additional parameter of ISomeDependency type.

    The test similar to the one from last post but this time using the AMC would look like this:

        [TestFixture]
        public class UserManagerTest
        {
            private MockRepository mockRepository;
    
            [SetUp]
            public void Test_Init()        
            {
                mockRepository=new MockRepository();
                ServiceLocator.TestMode = true;
            }
    
            [Test]
            public void GetActiveUsers_TestCaseOfZeroUsers_WouldReturnEmptyCollection()
            {
                IUserProvider userProvider = 
                    mockRepository.DynamicMock<IUserProvider>();
                ServiceLocator.InjectStub(userProvider);
    
                using (mockRepository.Record())
                {
                    Expect.Call(userProvider.GetUserCollection())
                        .Return(new List<User>());
                }
                using (mockRepository.Playback())
                {
                    // using public ctor(NO EXPOSED PARAMETERS)
                    var userManager = new UserManager();
                    int numberOfUsers= userManager.NumberOfUsersActiveInLast10Days(“X”);
                    Assert.IsTrue(numberOfUsers == 0);
                }
            }  
        }

    Couple of key moments here:

    • In test init method I switch ServiceLocator to “test mode” –> command him to return mocks for all types not stored in IoC container in the moment of their retrieval request
    • In test method I am explicitly adding to ServiceLocator ONLY instance of IUSerProvider (which is related to this test) .
    • ISomeDependency parameter is not mentioned anywhere in the test (solution to #1)
    • I am using the default constructor. That is giving me the solution to #2 which looks very strange on first sight but once one would realize that behind that default constructor is ServiceLocator based poor man dependency injection things get clearer.

    Again, I am aware that this approach to AMC is probably unique (I didn’t saw anything like this on the web) but I just choose to do the AMC through component design and not by some AMC framework (although that is perfectly fine choice with me too)

    Conclusion

    Although I like to keep things in my own hands as much as possible, I see a lot of value coming from AMC usage in writing tests for people who like the AMC idea.

    For people not sure “which pill to take” there comes the list of pros and cons I found on the web (here and here)

    Pros

    1. Can be easier to maintain and write tests/Can lead to easier test maintainability.
    2. Allows easier focus on testing interaction.
    3. Automatic testing the services construction via the IoC container.

    Cons

    1. Speed/performance?
    2. It could make the test a little less readable in terms of understanding what gets injected and what the actual dependencies are.

     

    What’s next

    My DFT blog post series stops here because I am getting fed up writing about unit testing and not having fun doing it is a sign for switching gears :)

    I have recently some real world experience on MVP design pattern appliance in real world scenarios so I plan to write couple of posts describing my thoughts on how to solve common problems most of the people face doing MVP (tackling complexity, communication control\page, need for HttpContext in presenter, composite UI communication, Front controller routing  etc) so in case you are doing WebForm classic ASP NET development and you care about testing your UI stay tuned

    Useful links for AutoMockingContainer

    http://blog.eleutian.com/2007/08/05/UsingTheAutoMockingContainer.aspx
    http://www.ayende.com/Blog/archive/2007/06/08/The-Auto-Mocking-Container.aspx
    http://blog.eleutian.com/2007/02/23/TestsAutoMockingIoCContainer.aspx

    AMC custom implementation source code can be found here

     

More Posts Next page »

Powered by Community Server (Non-Commercial Edition), by Telligent Systems NAVRCHOLU.cz