Saturday, October 4, 2014

DryIoc + ASP.NET MVC + NHibernate boilerplate code

IoC wiring:

using Erp.Controllers;

using DryIoc;

using System;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

using System.Linq;


namespace Erp
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {

        
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);


            var ioc = new DryIocDependencyResolver();
            ControllerBuilder.Current.SetControllerFactory(ioc);          
        }
    }


    class DryIocDependencyResolver : System.Web.Mvc.DefaultControllerFactory
    {
        DryIoc.Container _container;

        public DryIocDependencyResolver()
        {
            _container = new DryIoc.Container();
            RegisterTheIocs();
        }

        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            System.Web.Mvc.IController ic = controllerType == null
                ? null
                : (System.Web.Mvc.IController)_container.Resolve(controllerType);       

           // _container.ResolvePropertiesAndFields(ic);  // uncomment this if you want to use DI on controller's properties

           return ic;
        }

        void RegisterTheIocs()
        {
            // ISessionFactory definition

            System.Reflection.Assembly assembly = typeof(HomeController).Assembly;

            foreach (var controller in assembly.GetTypes().Where(t => typeof(Controller).IsAssignableFrom(t)))
            {
                _container.Register(controller, DryIoc.Reuse.InResolutionScope);                
            }


            // _container.Register(typeof(Elmah.Mvc.ElmahController), DryIoc.Reuse.InResolutionScope);

            // http://www.ienablemuch.com/2013/11/typical-nhibernate-sessionfactory.html
            _container.RegisterDelegate<NHibernate.ISessionFactory>(x => Erp.DomainMapping.Mapper.SessionFactory, DryIoc.Reuse.Singleton);

            _container.Register<UnitTestFriendlyDal.IDataStore, UnitTestFriendlyDal.DataStore>(DryIoc.Reuse.InResolutionScope);
        }

  
    }
}



Sample Controller, we need to call _ds.Dispose() to effect the transaction:
using Erp.Domain.TheModels;
using Erp.Dto.Dtos;

using UnitTestFriendlyDal;

using System.Web.Mvc;


namespace Erp.Controllers
{
    public class CompaniesController : Controller
    {
        IDataStore _ds;

        public CompaniesController(IDataStore ds)
        {
            _ds = ds;
        }
        

        public ViewResult Summary(int id = 0)
        {
            var company = _ds.Get<company>(id);
            
            var companyDto = company.Summary(_ds);

            return View(companyDto);
        }

        
        public ViewResult Search(SearchedCompanyDto sc)
        {
            Company.SearchCompanies(_ds, sc);            

            return View(sc);
        }


        protected override void Dispose(bool disposing)
        {
            _ds.Dispose();
            base.Dispose(disposing);
        }
    }
}



IDataStore definition:
using System;
using System.Linq;

using NHibernate.Linq;

namespace UnitTestFriendlyDal
{
    public interface IDataStore : IDisposable
    {
        IQueryable<T> Query<T>();
        T Get<T>(object id);
        T Load<T>(object id);
        object Save(object transientObject);
    }

    public class DataStore : IDataStore
    {

        NHibernate.ISessionFactory _sessionFactory;
        NHibernate.ISession _session;
        NHibernate.ITransaction _transaction;

        public DataStore(NHibernate.ISessionFactory sessionFactory)
        {
            _sessionFactory = sessionFactory;
            _session = _sessionFactory.OpenSession();
            _transaction = _session.BeginTransaction();
        }


        IQueryable<T> IDataStore.Query<T>()
        {
            return _session.Query<T>();
        }


        T IDataStore.Get<T>(object id)
        {
            return _session.Get<T>(id);
        }

        T IDataStore.Load<T>(object id)
        {
            return _session.Load<T>(id);
        }

        object IDataStore.Save(object transientObject)
        {
            return _session.Save(transientObject);
        }

        
        // Because transaction is a cross-cutting concern. It should be automated
        void IDisposable.Dispose()
        {
             // http://www.hibernatingrhinos.com/products/nhprof/learn/alert/donotuseimplicittransactions
                    
            _transaction.Commit();
            _transaction.Dispose();
            _session.Dispose();
        }




    }



    /// <summary>
    /// cross-cutting concern    
    /// MakeCacheable replaces Cacheable, so IQueryable detection provider can be done here
    /// Can't use NHibernate's built-in .Cacheable on non-NHibernate IQueryable, it will throw an error    
    /// </summary>
    public static class NHibernateLinqExtensionMethods
    {
        public static IQueryable<T> MakeCacheable<T>(this IQueryable<T> query)
        {
            if (query.Provider.GetType() == typeof(NHibernate.Linq.DefaultQueryProvider))
                query = query.Cacheable();

            return query;
        }


    }

}



Sample Domain Model:
using Erp.Dto.Dtos;

using UnitTestFriendlyDal;


using System.Linq;



[assembly:System.Runtime.CompilerServices.InternalsVisibleTo("Erp.Domain.Test")]

namespace Erp.Domain.TheModels
{
    
    // What is Anemic Domain Model
    // http://en.wikipedia.org/wiki/Anemic_domain_model
    // http://www.martinfowler.com/bliki/AnemicDomainModel.html    

    // this is a non-Anemic Domain Model
    public class Company
    {
        // Use Virtuosity.Fody to eliminate the use of virtual keywords on NHibernate
        // https://www.nuget.org/packages/Virtuosity.Fody/
        // http://github.com/Fody/Virtuosity

        public int CompanyId { get; protected internal set; }
        public string CompanyName { get; protected internal set; }
        public string CompanyUrl { get; protected internal set; }
        public byte[] TinyLogo { get; protected internal set; }



        public static void SearchCompanies(IDataStore ds, SearchedCompanyDto sc)
        {           
            var q = from c in ds.Query<Company>().MakeCacheable()
                    where string.IsNullOrWhiteSpace(sc.q) || c.CompanyName.StartsWith(sc.q)
                    select c;
            
            // http://www.ienablemuch.com/2014/10/proper-way-to-query-reference-entity.html
            sc.Companies = q.ToList().Select(c => new CompanyDto { CompanyId = c.CompanyId, CompanyName = c.CompanyName, TinyLogo = c.TinyLogo });            
        }

        // Just ready this parameter IDataStore,
        // so if this one entity need  information from another domain model(s) that is not in its navigable properties, 
        // it's easy to access those information
        public CompanyDto Summary(IDataStore ds)
        {                        
            return new CompanyDto { CompanyName = this.CompanyName };
        }
    }
}




Sample Unit Test:
using Erp.Domain.TheModels;

using UnitTestFriendlyDal;

using Erp.Dto.Dtos;

using Moq;

using System.Linq;


using Microsoft.VisualStudio.TestTools.UnitTesting;



namespace Erp.Domain.Test
{
    [TestClass]
    public class UnitTest
    {
        [TestMethod]
        public void Test_if_search_code_is_done()
        {

            // Arrange
            var companies = new[] {
                new Company { CompanyName = "Alpha" },
                new Company { CompanyName = "Beta" },
                new Company { CompanyName = "Delta" },
                new Company { CompanyName = "Atlantis" },
            }.AsQueryable();


            var ds = new Mock<IDataStore>();
            ds.Setup(x => x.Query<Company>()).Returns(companies);



            // Act
            var sc = new SearchedCompanyDto { q = "A" };
            Company.SearchCompanies(ds.Object, sc);



            // Assert
            Assert.AreEqual(2, sc.Companies.Count());
        }
    }
}



Happy Coding!

Proper way to query a reference entity

When caching a query, especially reference entities, select the whole entity; otherwise, the cached query won't be able to cache the entities


A test:
[TestClass]
public class FailingTest
{
    [TestMethod]
    Test_if_theres_entity_cache_when_cacheable_query_didnt_select_the_whole_entity()
    {
        // Arrange
        var sf = Common.BuildSessionFactory();

        using (var session = sf.OpenSession())
        {
            var q = from c in session.Query<Company>().Cacheable()
                    select new CompanyDto { CompanyId = c.CompanyId, CompanyName = c.CompanyName, TinyLogo = c.TinyLogo };

            q.ToList();
        }


        // Act
        Mapper.NHibernateSQL = "";

        using (var session = sf.OpenSession())
        {
            session.Get<Company>(1); // this won't be able to get an entity cache from the cacheable query above
        }

        // Assert
        Assert.IsTrue(Mapper.NHibernateSQL == ""); // SQL will not be empty
    }
}


Output:
Test Name:    Test_if_theres_entity_cache_when_cacheable_query_didnt_select_the_whole_entity()
Test Outcome:    Failed
Result Message:    Assert.IsTrue failed.
NHibernate: 
    select
        company0_.company_id as col_0_0_,
        company0_.company_name as col_1_0_,
        company0_.tiny_logo as col_2_0_ 
    from
        Company company0_
NHibernate: 
    SELECT
        company0_.company_id as company1_2_0_,
        company0_.company_name as company2_2_0_,
        company0_.company_url as company3_2_0_,
        company0_.tiny_logo as tiny4_2_0_ 
    FROM
        Company company0_ 
    WHERE
        company0_.company_id=:p0;
    :p0 = 1 [Type: Int32 (0)]


As you can see, the cached-entity-aware Get was not able to obtain a cached entity from the cacheable query before it. Inefficient


Here's the recommended way:

[TestClass]
public class PassingTest
{
    [TestMethod]
    public void Test_if_theres_entity_cache_when_cacheable_query_didnt_select_the_whole_entity()
    {
        // Arrange
        var sf = Common.BuildSessionFactory();

        using (var session = sf.OpenSession())
        {
            var q = from c in session.Query<Company>().Cacheable()
                    select c;

            q.ToList().Select(c => new CompanyDto { CompanyId = c.CompanyId, CompanyName = c.CompanyName, TinyLogo = c.TinyLogo });
        }


        // Act
        Mapper.NHibernateSQL = "";

        using (var session = sf.OpenSession())
        {
            session.Get<Company>(1); // this will be able to get an entity cache from the queryable cache above
        }

        // Assert
        Assert.IsTrue(Mapper.NHibernateSQL == ""); // SQL will not be empty
    }
}

Output:
Test Name:    Test_if_theres_entity_cache_when_cacheable_query_didnt_select_the_whole_entity
Test Outcome:    Passed
NHibernate: 
    select
        company0_.company_id as company1_2_,
        company0_.company_name as company2_2_,
        company0_.company_url as company3_2_,
        company0_.tiny_logo as tiny4_2_ 
    from
        Company company0_


The session.Get<Company>(1) is able to obtain a cached entity from the cached query before it. Efficient


Happy Coding!

Wednesday, October 1, 2014

When ASP.NET programming model(s) gives you lemon

The default programming model of ASP.NET encourages us to do everything on server-side. That is, events and view modifications are done on C#. UpdatePanel encourages that more as this can prevent full page refresh


However, UpdatePanel is not a silver bullet, you'll encounter performance problem with it soon enough


So here are the ways ASP.NET communicates changes between server and client, listed from the least desirable approach up to the modern approach:

Built-in approaches:
  • Post back
    • Full page refresh
    • All resources(image, css, etc) are reloaded, and view states are reconstructed too
  • UpdatePanel
    • No full page refresh
    • However, all view states (even the ones outside of UpdatePanel) are re-sent back to server. Bad to network load
    • All view modifications done from the server are received back by the client. Bad to network load
    • All changes on form inputs are received back by the server. A good thing. Callback can't read changes to inputs done by the user
    • Not so leaky abstraction. Simplest to implement, as ASP.NET WebForms' programming model is still maintained, e.g., the events and view modifications are still done in C#, not in JavaScript
    • The programming model of ASP.NET WebForms was the selling factor of ASP.NET when it was introduced, VB6 coders can feel at home with the programming model of WebForms as the code looks like VB6 or WinForms
  • Callback
    • No full page refresh
    • However, all view states are re-sent back to server. Bad to network load
    • View states re-sent back to server are of limited use, can modify them at the server-side, but won't be received back by the client, essentially making the view state a read-only thing. This is a bad thing as this would make us use javascript for UI stuff instead of doing everything in C# (ideal programming model); this is good for network traffic though
    • However, as view modifications done on server is of no use client, we have to turn to javascript to reflect back the changes to view, a leaky abstraction
    • User-changed values in form inputs (e.g., textbox) can't be read back on server. When the user change the value of text, the server side can only read the initial value of textbox, can't read the new value. This severely limits the use of view state re-sent to server. This might compelled the developer to use again the UpdatePanel
    • Complex to setup, see: http://msdn.microsoft.com/en-us/library/vstudio/ms178208(v=vs.100).aspx
  • WebMethod (the best way if ASP.NET Web API is not available to your project)
    • No full page refresh
    • No view states are re-sent back to server. Good to network load
    • The client won't received back any view states. Good to network load
    • Leaky abstraction, we have to turn to javascript when modifying the value of the controls
    • Easy to setup
  • ASP.NET Web API
    • Similar to WebMethod
    • ASP.NET Web API just have richer functionality, e.g., it can bind the JSON sent to it to strongly-typed model


Commercial approaches:
  • ASPxCallbackPanel
    • Virtually similar with UpdatePanel
  • ASPxCallback
    • All the view state are re-sent to server. Same as the built-in Callback
    • User-changed values in form inputs (e.g., textbox) can be read back on server. A good thing. The built-in callback can only read the initial state of the inputs
    • The view's values can not be updated at the server-side. To report back the changes to UI, use the control's ClientSideEvents to run a javascript that can manipulate the value of textbox, labels, etc


Demo code: https://github.com/MichaelBuen/PlayAspNetOptimization


Here's a sample network traffic on each approaches:

Built-in approaches:

Sent Received Total
Post back 45,211 7,569 52,780
UpdatePanel 44,791 1,795 46,586
Callback 44,715 1,088 45,803
WebMethod 605 543 1,148
ASP.NET Web API 609 506 1,115


Commercial approaches:

Sent Received Total
ASPxCallbackPanel 44,638 2,000 46,638
ASPxCallback 44,657 896 45,553



Happy Coding!

Importance of unit test, some code are unpredictable

This doesn't work:

[WebMethod]        
public static object SwitchLeaders(string jsonString)
{
    dynamic json = JsonConvert.DeserializeObject(jsonString);

    return new { Autobot = json.Decepticon, Decepticon = json.Autobot };
}
Returns wrong data: json: {"d":{"Autobot":[],"Decepticon":[]}}



This works:

[WebMethod]        
public static object SwitchLeaders(string jsonString)
{
    dynamic json = JsonConvert.DeserializeObject(jsonString);

    string a = json.Decepticon;
    string b = json.Autobot;

    return new { Autobot = a, Decepticon = b };
}
Returns correct json {"d":{"Autobot":"Megatron”,"Decepticon":"Optimus Prime"}}



Happy Coding!

Not doing explicit interface implementation waste our time on debugging

If you received this kind of error, you'll wonder why MSDN writers can't be bothered to implement interfaces explicitly

Additional information: The target '__Page' for the callback could not be found or did not implement ICallbackEventHandler.






I thought I followed the sample code from MSDN to a tee: http://msdn.microsoft.com/en-us/library/vstudio/ms178210(v=vs.100).aspx


Had MSDN writers written this code..

public void RaiseCallbackEvent(String eventArgument)
{
 if (catalog[eventArgument] == null)
 {
  returnValue = "-1";
 }
 else
 {
  returnValue = catalog[eventArgument].ToString();
 }
}

public String GetCallbackResult()
{
 return returnValue;
}

..using explicit interface implementation..
void ICallbackEventHandler.RaiseCallbackEvent(String eventArgument)
{
 if (catalog[eventArgument] == null)
 {
  returnValue = "-1";
 }
 else
 {
  returnValue = catalog[eventArgument].ToString();
 }
}

ICallbackEventHandler String GetCallbackResult()
{
 return returnValue;
}


..there would be no time wasted on debugging and googling for solution, especially when we are fond of Ctrl+F5 instead of F5. We often need to use Ctrl+F5 it's faster, F5 slows down the coding-running cycle


Explicitly implementing those interface methods, it would be readily apparent that we just forgot to add the interface to class as the explicit interface implementation would not compile if we forgot to add the interface:

public partial class Default : System.Web.UI.Page, ICallbackEventHandler



Happy Coding!