Tuesday, March 25, 2014

“Don’t Query From the View” - Unit of Work and AOP

Maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems.


I was asked about a warning from NHProfiler from a colleague to see my opinion on the matter.  The warning was:  http://hibernatingrhinos.com/products/NHProf/learn/alert/QueriesFromViews “Don’t Query From the View”.  

The team had a session lifetime per controller action using AOP (Attribute Filters), but needed to extend this out to be active during the view rendering phase after the controller completed.  They did this by instantiating the session in the request filter chain instead of the controller attribute filters.  When they did this, they received the NHProfiler warning above.

The collegue was dismissive of the warning, partly because the implementation of the code was innocuous and partly because the warning reasons were not particularly compelling.  

There are some serious implications of the pattern that was being followed however, some of which I have covered on this blog in the past (here) and (here).

 
tldr;
·        Sessions can be open as long as you need them to be.  You do not need to arbitrarily close them if you know they will be needed again as soon as the next step in the pipeline is reached.
·        There are (arguably) valid reasons why the View rendering would be able to access an active session.
·        The longer a session is open, the more chance of unexpected behaviour from working with Entities in a connected state.  Care should be taken.


Pro1: Simplicity
One benefit from having a session opened and closed automatically using cross-cutting AOP is that your application doesn’t need to care about it.  It knows that it will have a session when used, and will commit everything when the scope ends.  This is often done as a controller/action filter attribute, or higher in the request pipeline.  You don’t need to pass a session around, check if it exists, etc.

Con1: Deferring code to View Rendering adds complexity.
I have argued that having the session active outside the controller makes it more difficult to maintain and debug your code as the session is active during the View render component.  The response was that forcing a controller action to pre-load everything the view *might* need and just pushing a dumb model prevents the view from performing optimisation of what it actually loads.  I don’t believe that the View rendering should have such an impact on code execution but the point is a valid point of contention.

Con2: Loss of control.
When using AOP to manage the session lifetime you have much less control over the failed state.  As the failure occurred outside of the business logic context, you can’t easily use business logic to handle the failure.  If the standard policy is to simply direct you to an error page or similar, then this behaviour is completely valid.  However if you needed to perform actions based on the failure (such as attempting to resolve optimistic concurrency issues automatically) then you can’t. 

Con3: Loss of traceability.
When using a long running session there is no traceability between the persistence and the application logic that made the entity changes.  If you experience an unexpected query when the unit of work commits, you can’t immediately identify which code caused this behaviour.

Con4: Unexpected change tracking.
Having a long running (and potentially ‘invisible’) session exposes you to potentially unexpected behaviour due to the session tracking all changes on the underlying entities.  If you load an entity from the data access layer, then make some changes for display purposes (perhaps change a Name property from “Jason Leach” to “LEACH, Jason”) before passing that entity to the view, when the unit of work cleanup occurs it will persist that change to the database because all of your changes are being tracked. 
A less obvious example is if you had a Parent entity with a list of Children.  In a particular controller action you want to get the parent and only a subset of the children.  So you might select the parent and all children.  Then you may do something like Parent.Children = Parent.Children.Select(x=>childfilter).ToList().  Depending on your configuration this is likely to delete all of the children not matching the filter when the unit of work completes.  Oops.

Con3 and 4 are direct side effects of leaving a session open longer.  In the Parent->Child example, you would likely only need the session active when you did the initial load of the Parent and Child entities, then close the session and start manipulating the entities.   Obviously you should be mapping entities to ViewModels and never manipulating those entities, but it is a very easy mistake to make.  Coupled with con3, it can be near impossible to identify in a complex unit of work.

Conclusion
As long as you are careful about what you are doing, and not arbitrarily altering domain model entities while a session is open, then long-running sessions are not a problem.  However there is significant potential of issues if your devs don't understand the risks.
As long as you are happy with standard error/failure, or UI driven resolution workflows, then AOP for unit of work management is acceptable, again as long as the risks / limitations are acknowledged.

 

Thursday, March 20, 2014

Little Things

As I take on more architectural responsibility I write far less code.  I do however provide code samples and give advice on how to solve certain issues.

If there is a flaw in the samples provided that is obvious in the integrated solution, if not the code sample,  it is a major failing on my part to have not identified it.  I hate that.

When the flaw is obvious and the fix is equally obvious,  then is that still my failing, or a failing of the developers for blindly following a code example and not reviewing or taking the effort to understand the code. 

Probably both.

Thursday, February 27, 2014

Web Deploy / MS Deploy Connection String Parameterisation

MsDeploy/WebDeploy parameterisation is pretty useful.  It allows a decent amount of flexibility to deploy a single artefact to multiple environments. 

But it doesn’t always work quite as expected, specifically for Connection Strings in the configuration file.

Scenario:

If you create Parameter entries in parameters.xml, when you deploy a web application project you will receive a SetParameters.xml file with entries based on the parameters.xml.  When defining the parameters, you can give them friendly parameter names (and even prompt text which is used when deploying via IIS management screens).

However if you look at the parameters.xml file that is created in the zip manifest, you will see non-friendly parameter entries for the connection strings, and if you created a ‘friendly’ parameter in the source parameters.xml, this friendly entry will have no transformation rules applied.

This means during msdeploy, the friendly entries in your SetParameters file are ignored, so the connection strings are not updated in web.config during the deployment.

Details:

So if your source Parameters.xml contains
<parameter defaultvalue="" name="Connection String 1">
    <parameterentry match="/configuration/connectionStrings/add[@name='ConnectionString1']/@connectionString" scope="\\web.config$" type="XmlFile">
    </parameterentry>
</parameter>
<parameter defaultvalue="" name="Connection String 2">
    <parameterentry match="/configuration/connectionStrings/add[@name='ConnectionString2']/@connectionString" scope="\\web.config$" type="XmlFile">
    </parameterentry>
</parameter>

And the following in your SetParameters.xml file using your friendly names

<setparameter name="Connection String 1" value="{connection string you want}">
</setparameter>
<setparameter name="Connection String 2" value="{connection string you want}">
</setparameter>


The compiled manifest parameters.xml will look like
<parameter name="Connection String 1" defaultValue="" />
<parameter name="Connection String 2" defaultValue="" />

<parameter name="ConnectionString1-Web.config Connection String" description="ConnectionString1 Connection String used in web.config by the application to access the database." defaultValue="{default value here}" tags="SqlConnectionString">
<parameterEntry kind="XmlFile" scope="{magic string representing web.config}" match="/configuration/connectionStrings/add[@name='ConnectionString1']/@connectionString" />
</parameter>
<parameter name="ConnectionString2-Web.config Connection String" description="ConnectionString2 Connection String used in web.config by the application to access the database." defaultValue="{default value here}" tags="SqlConnectionString">
<parameterEntry kind="XmlFile" scope="{magic string representing web.config}" match="/configuration/connectionStrings/add[@name='ConnectionString2']/@connectionString" />
</parameter>

As you can see, the friendly name entries have no content, so when deploying your SetParameters values are read from the file, but never applied to the config file.

Resolution:

The fix is pretty simple – remove the friendly entries from source control in parameters.xml and setparameters.xxx.xml, and add non-friendly name entries just to the setparameters.xxx.xml – the non-friendly names are ‘predictable’ although if you are desparate, just check the parameters.xml in the manifest after a build.


NHibernate Cross-database Hacks

Cross-Database Queries


Ok, so this is a bit of a hack, but it does work.  Thanks to this which set me down the "right" path.

I work with a few legacy systems that have central databases for common information, and individual databases for application specific information.  The data is queried using joins across the databases to retrieve the data required.
A separate service model was introduced for the common data, but when performing filtered queries across both data sets the service model was not efficient (this is a greater issue of context boundaries that I won’t go into here).  To perform the queries that were previously performed using stored procedures using cross-database joins in nHibernate required a bit of a cheat.

nHibernate mappings have a “schema” property as well as the more commonly used “table” property.  By manipulating this schema property you can convince nHibernate to perform cross-database queries.  Setting the schema to “{database}.{schema}” any join query to that element will effectively use the full cross-database query syntax when converted to a SQL query.

Neat (but ultimately not very satisfying because it is not a very nice design).


Bigger Hack, run away


If the target database name is not known until runtime, you can even hack it more to support this.

During the configuration of the nHibernate session factory, you can make a few modifications that will allow you to update the schema property of an entity.  This is useful if you have a different ‘other’ database name for each environment (e.g. OtherDatabase-dev, OtherDatabase-prd).

First we appropriately generate the fluent configuration, and build it.
We then iterate through the class mappings.  Each persistentClass.MappedClass is the underlying POCO model object of the entity.
We check if this is one that we want to override the schema property for (IOtherDatabaseEntity is a simple blank interface, it could be done via naming convention or whatever)
And then update the schema property on the mapping
Finally we create the session factory from the modified config

var fluentConfiguration = config.Mappings(m =>
        m.FluentMappings
        .AddFromAssemblyOf()
        );
var builtConfig = fluentConfiguration.BuildConfiguration();

foreach (PersistentClass persistentClass in builtConfig.ClassMappings)
{
        if (
            typeof(IOtherDatabaseEntity)
                .IsAssignableFrom(persistentClass.MappedClass)
            )
        {
            persistentClass.Table.Schema = cdrName;
        }
}
                  
ISessionFactory sessionFactory = builtConfig
        .BuildSessionFactory();


Hacks away!

NHibernate + LINQPad

While looking at ways to assess and improve performance some nHibernate queries, I was frustrated with the tools at my disposal.

I will start with the point: I don't have access to nhprof.  It seems to be the gold standard for any nHibernate shop, but them's the breaks.

What I was doing:


It was painful to execute the entire codebase to run one or two queries and view the output sql, so I started writing integration-unit tests for query optimisation.  This was slightly better, but still required a change-compile-run-review process which was annoying.

What was I thinking:

I then remembered I have a personal LINQPad license that I hadn't used in a while and wondered if I could get it working.  I saw this which helped me on my way, but we don't use nHibernate.Linq, so the steps were a bit different.

The outcome was extremely useful however, and now I am free to tinker with my queries a lot more freely.

How I did it:

To start you need to add the references to nHibernate that you require (in my case NHibernate, Iesi.Collections, and FluentNHibernate).  You then add the references to your Domain / Models and mapping assemblies.

The next step is to create a hibernate.cfg.xml file with the appropriate configuration for your database.  Make sure you set show_sql=true in the configuration so LINQPad can display the generated SQL.

Then you can call the following code

var cfg = new Configuration().Configure(@"D:\linqpad\ahs\hibernate.cfg.xml");
var factory = Fluently.Configure(cfg)
                .Mappings(m =>
                {
                    m.FluentMappings.AddFromAssemblyOf();
                })
                .BuildSessionFactory();


using (var session = factory.OpenSession()){
    var site = session.QueryOver()
    .List();
}
and viola, you can now tinker with queries as you will, with immediate feedback on the generated SQL and execution time.


You can then save this as a query, or save the assembly references/using statements as a snippet to get you up and running quickly for new queries. 

Caveats:

This method only works with pre-compiled entity mappings, so if you intend to improve performance at the entity mapping layer you still need to do this through your application and export the assemblies for LINQPad to use.

Extensions:

LINQPad allows you to create an 'application config' file that is used when your inner assemblies require web/app.config sections.  Run the code:
AppDomain.CurrentDomain.SetupInformation.ConfigurationFile
to find the location of the file, and if it does not exist create it.  Note that unlike most .NET apps, this is not the LINQPad.exe.config, but LINQPad.config.  Enter any configuration you need into this file.  This can include the nHibernate config  instead of the separate file (but limits configuration flexibility).

This allows you to configure things like nHibernate 2nd level cache instances, such as memcache.  As long as you include the necessary libraries in the query references, and the configuration in the linqpad.config file this will work and provide even greater flexibility for performance analysis and testing.


Conclusion:

So there you go, a "poor man's" guide to nHibernate performance analysis, thanks to the ever awesome LINQPad.

Thursday, August 1, 2013

WinJS and RequireJS

I had been looking at improving my JavaScript skills and learning WinJS at the same time.  One of the key things I wanted to do was work better with larger projects and larger numbers of JavaScript files. 

RequireJS is great for that, but I had considerable trouble getting it to work with WinJS.  When I did get it working I then had trouble getting it to work properly. 

RequireJS is expected to be initialised with an include reference in the page html with a data-main tag, but this doesn't really work with the WinJS app lifecycle, so it took a bit of work to get it behaving the way I expected.

Eventually I got it working, and working with async initialisation code which was a key part of the initialisation process in my sample app.

So the basics of getting RequireJS working in WinJS is the following - I have probably made a million big JavaScript no-no's here, but as I said, still learning.

default.html - add
    <script src="/js/require.js" ></script>
before default.js

default.js - initialise requireJS and include whatever dependencies you want to use in your startup code.

app.addEventListener("activated", function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {
            if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
                // TODO: This application has been newly launched. Initialize
                // your application here.
            } else if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.closedByUser) {
                // TODO: This application has been launched after a requested shutdown. Initialize
                // your application here.
            } else {
                // TODO: This application has been reactivated from suspension.
                // Restore application state here.
            }
 
            if (app.sessionState.history) {
                nav.history = app.sessionState.history;
            }
 
            //RequireJS Initialisation here
            require.config({
                baseUrl: '/js'
            });
 
            //this creates a promise that calls complete() when the initAsync promises finish
            //all this code happens within the require context so we are guaranteed that the dependencies are resolved before the promise is resolved
            //the initAsync methods return promises that load data from internal json data files
            //persistence.loadState is synchronous code so doesn't return a promise
            var loadPromise = new WinJS.Promise(function (complete) {
                require([
                    'persistence',
                    'game/staticdata/itemClassStore',
                    'game/staticdata/itemStore',
                    'game/gamestate/world',
                    'game/gamestate/characters',
                    'game/classes/character'
                ], function (persistence, itemClassStore, itemStore, world, characters, character) {
 
                    itemClassStore.initAsync()
                        .then(function () { return itemStore.initAsync(); })
                        .then(
                            function () {
                                var data = persistence.loadState();
                                world.fromJson(data);
                                complete();
                            }
                        );
 
 
                });
            });
 
            //args.setPromise is a function on the activate event which allows you to wait for promises to complete before continuing
            args.setPromise(
                loadPromise
                    .then(function () { return WinJS.UI.processAll(); })
                    .then(
                        function () {
                            if (nav.location) {
                                nav.history.current.initialPlaceholder = true;
                                return nav.navigate(nav.location, nav.state);
                            } else {
                                return nav.navigate(Application.navigator.home);
                            }
                        }
                    )
            );
        }
    });

xPage.js - resolve your dependencies in the page ready function with a call to require(), and perform your page initialisation as per normal. 

///  
/// 
/// 
/// 
/// 
 
(function () {
    "use strict";
 
    WinJS.Namespace.define("CharacterSelect", {
        CharacterSelectViewModel: WinJS.Class.define(
            //the viewmodel constructor takes the injected requireJS dependency from the page ready code.
            function (world) {
                this._charactersModule = world.characters;
                this._itemsDataSource = new WinJS.Binding.List(this._charactersModule.characters);
                this._inventoryDataSource = new WinJS.Binding.List(null);
            },
            {
                _charactersModule: null,
                _itemsDataSource: null,
                _inventoryDataSource: null,
                _selectedCharacterId: 0,
                selectedCharacterId: {
                    get: function () {
                        return this._selectedCharacterId;
                    },
                    set: function (value) {
                        this._selectedCharacterId = value;
                        if (value == 0) {
                            this._inventoryDataSource = new WinJS.Binding.List(null);
 
                        } else {                            
                            this._inventoryDataSource = new WinJS.Binding.List(this._charactersModule.get(value).inventory.items);
                        }
                        this._getObservable().notify("selectedCharacterId", value);
                        this._getObservable().notify("inventoryDataSource", this._inventoryDataSource);
                    }
                },
 
                listDataSource: {
                    get: function () {
                        return this._itemsDataSource;
                    }
                },
                
                inventoryDataSource: {
                    get: function () {
                        return this._inventoryDataSource;
                    }
                },
 
                addNew: function () {
                    WinJS.Navigation.navigate("/pages/newCharacter/newCharacter.html");
                },
 
                deleteCharacter: function (that) {
                    that._charactersModule.deleteCharacter(this.selectedCharacterId);
                    that._itemsDataSource = new WinJS.Binding.List(this._charactersModule.characters);
 
                    that._getObservable().notify("listDataSource", that._itemsDataSource);
                }
 
            },
            {}),
 
    });
 
    WinJS.UI.Pages.define("/pages/characterSelect/characterSelect.html", {
 
        // This function is called whenever a user navigates to this page. It
        // populates the page elements with the app's data.
        ready: function (element, options) {
            require(
                [
                    'persistence',
                    "appbar",
                    "game/gamestate/world"
                ],
                function (persistence, appbar, world) {
                    //normal page initialisation code - all dependency modules are initialised at this point
                    //create view model (passing in resolved dependencies) and bind to relevant events
                    //(WinJS only has 1-way bindings and can't declaratively bind to button events that i can see)
                    var section = element.querySelector("section");
 
                    var viewModel = new CharacterSelect.CharacterSelectViewModel(world);
                    var observableviewModel = WinJS.Binding.as(viewModel);
                    WinJS.Binding.processAll(section, observableviewModel);
 
                    document.getElementById("cmdCreate").addEventListener("click", observableviewModel.addNew, false);
                    document.getElementById("cmdDeleteCharacter").addEventListener(
                        "click",
                        function(){
                            observableviewModel.deleteCharacter(observableviewModel);
                            persistence.saveState();
                        }
                        ,
                        false
                        );
 
                    document.getElementById("characters").winControl.onselectionchanged = function (ev) {
                        var selection = document.getElementById("characters").winControl.selection;
                        if (selection.getItems()._value.length > 0) {
                            viewModel.selectedCharacterId = selection.getItems()._value[0].data.id;
                            appbar.characterSelectSelected();
                        } else {
                            viewModel.selectedCharacterId = 0;
                            appbar.characterSelectDeSelected();
                        }
 
                    };
                    appbar.characterSelectInit();
 
 
                }
            );
 
 
        },
 
        unload: function () {
            // TODO: Respond to navigations away from this page.
        },
 
        updateLayout: function (element, viewState, lastViewState) {
            /// 
 
            // TODO: Respond to changes in viewState.
        }
    });
})();

Thursday, March 14, 2013

New job update

Well... This post is probably a few months late, as I have been in my new job for 9 months now.

I was getting frustrated in my old job due to a change in business direction away from my core career goals so when a .net community member advised me to hand in a resume I thought I didn't have much to lose.

So within a week of handing in a resume I was given an offer I could not refuse: a substantial pay rise, a company focusing on my strengths,  and working with a few people I had a healthy respect for.

9 months on and I am now at a new client with a substantial responsibility increase, learning a lot, and generally doing what I had expected would take me another few years to reasonably obtain at my old job if any opportunities were even to arrive.  The client even seems happy with my performance too, which is a bonus.

So far the risk of moving to a new job has paid off, and I hope to keep pushing my boundaries now that I have the opportunity to do so.