Session Scoped Bindings With Ninject 2

An entry about inversion of control | ninject | asp.net | asp.net mvc Publication date 2. June 2010 18:33

Ninject 2 comes out of the box with a set of standard scoping options for activations: transient, singleton, threaded etc. There’s also an ASP.NET specific “request” scope, which ensures that all activations for a binding returns the same instance throughout one request. However, there’s no session scope (at least not that I could dig up), so if you want a scope such that activations of a binding returns the same instance throughout the lifetime of an entire ASP.NET session, you’ll have to roll your own.

Googling for a while, I couldn’t find anyone having blogged about this before. Which I find weird, because surely this is a common scoping requirement for web applications? I guess everyone is too busy twittering these days to blog much (not me though, nu uh :-p).

Anyways, we can roll our own solution for this fairly easily using the InScope() method, which Nate Kohari explains how works like this:

The object returned by the callback passed to InScope() becomes the "owning"
object of instances activated within the scope. This has two meanings:

1. If the callback returns the same object for more than one activation,
Ninject will re-use the instance from the first activation.

2. When the object returned from the callback is garbage collected, Ninject
will deactivate ("tear down", call Dispose(), etc.) any instances associated
with that object.

Armed with this knowledge, all we need to do is ensure that InScope is given a callback that returns the same, unique object for each session. My first idea was to simply pass it HttpContext.Current.Session – but ASP.NET is built so that it rebuilds the HttpContext object (and the Session bag) for each request, so this essentially makes the scoping a request scope. So we’ll need to make things a little bit more complicated:

public static class NinjectSessionScopingExtention

{

    public static void InSessionScope<T>(this IBindingInSyntax<T> parent)

    {

        parent.InScope(SessionScopeCallback);

    }

 

    private const string _sessionKey = "Ninject Session Scope Sync Root";

 

    private static object SessionScopeCallback(IContext context)

    {

        if (HttpContext.Current.Session[_sessionKey] == null)

        {

            HttpContext.Current.Session[_sessionKey] = new object();

        }

 

        return HttpContext.Current.Session[_sessionKey];

    }

}

Here we’re essentially using the ASP.NET session bag to store an object throughout the lifetime of the session, which we can then use as the scope owner. And that’s it, we can now set up bindings InSessionScope().

Check out my session on the Dependency Inversion Principle (track 7, day 3) at NDC 2010 in a couple of weeks for an in depth discussion on taking full advantage of modern IOC containers scoping features.

Currently rated 3.0 by 55 people

  • Currently 3/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Resolving relative URL’s from JavaScript

An entry about javascript | asp.net | asp.net mvc Publication date 22. August 2009 14:50

On the server side of an ASP.NET or ASP.NET MVC application, we’re used to working with relative URL’s in the style of “~/Images/logo.png”. This makes our application safely deployable to virtual directories within IIS applications without messing up the URL’s. However, what do we do if we need the same functionality in our JavaScript?

I’m solving this by sticking the following script in my Site.Master file:

Url = function() { }

Url.prototype =
{
    _relativeRoot: '<%= ResolveUrl("~/") %>',

    resolve: function(relative) {
        var resolved = relative;
        if (relative[0] == '~') resolved = this._relativeRoot + relative.substring(2);
        return resolved;
    }
}

$Url = new Url();

Now, anywhere I need to resolve a relative url in a script, I can do this:

var logoUrl = $Url.resolve("~/Images/logo.png");

Currently rated 4.6 by 8 people

  • Currently 4.625/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

MSDN Live - Stavanger, Bergen & Trondheim Done!

An entry about asp.net | conferences Publication date 11. September 2008 15:06

I've just finished my last session at the MSDN Live event in Trondheim, after doing Stavanger last week and Bergen on Tuesday. Its been great so far, and I'm really looking forward to the final event in Oslo on the 30th of September. Rumour has it that a very special guest will be making a surprise keynote appearance, so you really don't want to miss it! ;)

For those of you that have attended my Introduction to ASP.NET sessions so far, go check out the project site at http://www.assembla.com/spaces/msdn_live_wiki, where you can download all the slides and the demo application.

Currently rated 4.0 by 1 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Ninject Module for ASP.NET MVC Controller Bindings

An entry about asp.net | asp.net mvc | inversion of control Publication date 25. August 2008 11:00

Setting up Ninject for use with ASP.NET MVC is dead easy; just use the integration API included in the MvcContrib project. However, registering all your controllers by hand can be tedious. Writing a custom module that automatically loads all the controllers in a given assembly is straight-forward, however:

public class ControllerModule : StandardModule
{
    private readonly Assembly _assembly;
 
    public ControllerModule(Assembly assembly)
    {
        _assembly = assembly;
    }
 
    public override void Load()
    {
        Type controllerType = typeof (IController);
 
        // find all types in the assembly that implement the IController interface
        foreach(Type type in _assembly.GetTypes())
        {
            if(controllerType.IsAssignableFrom(type))
            {
                string controllerName = type.Name;
 
                // strip the "Controller" suffix from name
                int cutIndex = controllerName.LastIndexOf("Controller");
                if(cutIndex > 0) controllerName = controllerName.Substring(0, cutIndex);
 
                // register controller binding
                Bind<IController>().To(type).Only(When.Context.Variable("controllerName").EqualTo(controllerName));
            }
        }
    }
}

And then your Global.asax will look like this:

public class GlobalApplication : HttpApplication
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
 
        // *snip* route registration
    }
 
    protected void Application_Start()
    {
        RegisterRoutes(RouteTable.Routes);
        InitializeNinject();
    }
 
    public void InitializeNinject()
    {
        NinjectKernel.Initialize(new ControllerModule(Assembly.GetExecutingAssembly()));
        ControllerBuilder.Current.SetControllerFactory(typeof(NinjectControllerFactory));
    }
}

Happy days!

Currently rated 5.0 by 2 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Deploying Asp.Net Sites to IIS7 from Visual Studio

An entry about asp.net | visual studio Publication date 29. March 2008 12:02

To be able to deploy Asp.Net sites to IIS7 from Visual Studio 2008 when running on Windows Vista, there's a couple of things that needs to be set up first. Aside from the fact that you need to be running Visual Studio as an administrator (either by choosing 'run as Administrator' when launching it, or by disabling the UAC), there are a few IIS6 compatibility features that needs to be installed. These can be found by going to Control Panel > Programs > Turn Windows features on or off, and ensuring that the following are checked:

Windows features

With that in place, you can go to the Web tab on the properties page for your ASP.NET project and select 'Use IIS web server' instead of the built-in development server, just like we're used to:

Asp.Net project server settings

Currently rated 2.7 by 6 people

  • Currently 2.666667/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Sharing Variables Between JavaScript and C#

An entry about asp.net | javascript Publication date 11. January 2008 17:53

You know, I think the most difficult part of this blog post was coming up with a descriptive title for it - it just needs more words to be explained. The story goes like this: While working on a JavaScript-heavy web application, I found myself wanting to share a set of variables between my server side C# code and the client-side JavaScript code. I wanted to be able to set a value in the JavaScript code running in the clients browser, and then later retrieve that same value on the server in the code behind of the page upon the next postback - and vice versa. It might sound a bit tricky (or maybe not?), but it proved to be quite simple - in fact, its perfect for some Friday afternoon blogging indulgence, before we get started on dinner :)

Aim First...

Whenever I decide to create a component, the first thing I do is think about how I want to use it. I find writing some mock code the perfect way to settle on an interface for the component, before even writing a line of code for it (TDD, anyone?). This way, I'm sure I'm actually making what I need, and not what I think I might need. So, let's look at some code that mimics what we want to accomplish with our component.

What I'd like to do, is to be able to drop it onto a Web Form and access it both from my JavaScript and my code behind. So, something like this:

 

<idc:ClientDictionary 
    ID="_myDictionary"
    runat="server" />

 

Having declared that in my markup, I want to be able to do this from the client-side JavaScript:

$find('_myDictionary').setValue("key", "value");

 

And then, when the form is submitted, I want to be able to retrieve that value from the server-side C#:

string value = _myDictionary.Values["key"];

 

...and Fire at Will

Okay, so hopefully you've got an idea of what I'm up to. Basically, what I want is a hidden input field - but one that can store more than one value. Instantly, I'm thinking Asp.Net Ajax - or more precisely, a Control Extender. I could write one that targets the HiddenField control, transporting my dictionary between the client and server by serializing it into the hidden input field. But while that would take care of the client-side part, I need to extend the HiddenField serverside aswell. To do that, I'll write a new component that wraps the HiddenField and the said extender control into a composite control, ready to be dropped onto a form and just work.

Without any further ado, lets look at the source code I came up with for this control:

public class ClientDictionary : CompositeControl
{
    private Dictionary<string,string> _values;
 
    /// <summary>
    /// The name of the dictionary, used for accessing the dictionary on the client using $find([name]).
    /// </summary>
    public string Name
    {
        get
        {
            EnsureChildControls();
            return _hiddenFieldExtender.BehaviorID; // we map the name to the behavior ID of the hidden field extender 
        }
        set
        {
            EnsureChildControls();
            _hiddenFieldExtender.BehaviorID = value;
        }
    }
 
    public override bool EnableViewState
    {
        get
        {
            // this control does not need view state
            return false;
        }
        set
        {
            throw new InvalidOperationException();
        }
    }
 
    /// <summary>
    /// Gets or sets the values stored in the dictionary
    /// </summary>
    public Dictionary<string, string> Values
    {
        get { return _values; }
        protected set { _values = value; }
    }
 
    protected override void OnInit(EventArgs e)
    {
        EnsureChildControls();
 
        // the hidden field contains our javascript dictionary, which we'll want to deserialize into a C# dictionary
        string serializedDictionary = this.Page.Request.Form[_field.UniqueID];
 
        if (!String.IsNullOrEmpty(serializedDictionary))
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            this.Values = serializer.Deserialize<Dictionary<string, string>>(serializedDictionary);
        }
        else
        {
            // no client-side dictionary was present, so create a new blank one
            this.Values = new Dictionary<string, string>();
        }
 
        base.OnInit(e);
    }
 
    private HiddenField _field;
    private ClientDictionaryExtender _hiddenFieldExtender;
 
    protected override void CreateChildControls()
    {
        _field = new HiddenField(); // we use the hidden field to transport our data between the server and client parts
        _field.ID = "fl";
        this.Controls.Add(_field);
 
        // the extender makes sure a client-side behavior component representing the dictionary is available
        this._hiddenFieldExtender = new ClientDictionaryExtender();
        this._hiddenFieldExtender.BehaviorID = this.Name;
        this._hiddenFieldExtender.ID = "xt";
        this._hiddenFieldExtender.TargetControlID = _field.ID;
        this.Controls.Add(this._hiddenFieldExtender);
    }
 
    protected override void OnPreRender(EventArgs e)
    {
        // its time to save the server-side dictionary into the hidden field, which will transport it to the client side component
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        _field.Value = serializer.Serialize(this.Values);
 
        base.OnPreRender(e);
    }
}

 

The comments should make the above code pretty much self-explanatory, so lets just keep rolling and dive right into the javascript code:

Type.registerNamespace('Iridescence.Web.UI');
 
Iridescence.Web.UI.ClientDictionaryBehavior = function(element)
{
    Iridescence.Web.UI.ClientDictionaryBehavior.initializeBase(this, [element]);
    this._dictionary = null;
    this._onSubmitDelegate = null;
}
 
Iridescence.Web.UI.ClientDictionaryBehavior.prototype = 
{
    initialize : function()
    {
        Iridescence.Web.UI.ClientDictionaryBehavior.callBaseMethod(this, 'initialize');
 
        this._onSubmitDelegate = Function.createDelegate(this, this._onSubmit);
        $addHandler(window, "submit", this._onSubmitDelegate);
        this._deserialize();
    },
 
    getValue : function(name)
    {
        var value = this._dictionary[name];
 
        return value;
    },
 
    setValue : function(name, value)
    {        
        this._dictionary[name] = value;
    },
 
    _onSubmit : function()
    {
        // serialize the dictionary to the hidden field    
        this.get_element().value = Sys.Serialization.JavaScriptSerializer.serialize(this._dictionary);
    },
 
    _deserialize : function()
    {
        // deserialize the dictionary from hidden field    
        this._dictionary = Sys.Serialization.JavaScriptSerializer.deserialize(this.get_element().value);          
    },
 
    clear : function()
    {
        this._dictionary = null;
        this._dictionary = new Object();
    },
 
    dispose : function()
    {
        Iridescence.Web.UI.ClientDictionaryBehavior.callBaseMethod(this, 'dispose');  
    }
}
 
Iridescence.Web.UI.ClientDictionaryBehavior.registerClass('Iridescence.Web.UI.ClientDictionaryBehavior', AjaxControlToolkit.BehaviorBase);

 

The only thing left to define is the ClientDictionaryExtender, which is dead simple:

[ClientScriptResource("Iridescence.Web.UI.ClientDictionaryBehavior", "Iridescence.Web.UI.ClientDictionaryBehavior.js")]
[TargetControlType(typeof(HiddenField))]
internal class ClientDictionaryExtender : ExtenderControlBase
{}

 

There's no server-side functionality in the extender, its job is just to hook up the JavaScript component to the hidden field. I've made it internal as well, as it makes little sense to use it without the plumbing being handled by the ClientDictionary control.

And that is all there is to it! Dropping the ClientDictionary component onto a form, I can now set and get values from its dictionary both from the client-side JavaScript and the server-side codebehind, and it will be synchronized both ways.

I've created a demo project which you can download here, which includes the working source code and a small Asp.Net application that demos the basic functionality. Enjoy!

Currently rated 3.8 by 20 people

  • Currently 3.8/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Powered by BlogEngine.NET 1.4.5.0

Welcome!

My name is Fredrik Kalseth, and this is my blog - thanks for visiting! I am fortunate enough to work with what I love for a living, and this blog is essentially the biproduct of that.

I work as a senior consultant for Capgemini, and am also an active participant in the Norwegian .NET community, as an avid attendee but also as a speaker (most recently at NNUG and MSDN Live).

As a developer, I have a wide circle of interest. My primary passion is for agile, test-driven development, with focus on best practices and clean code. That said, I also love to work on the frontend, especially with web development.

On Twitter? My handle is fkalseth. On LinkedIn? I`m there too.


Disclaimer

This is a personal blog; any opinions expressed here are my own and do not necessarily reflect those of my employer. All content herein is my own original creation, and as such is protected by copyright law. Unless otherwise stated, all source code posted on this blog is freely usable under the Microsoft Permissive License.

What Readers Talk About

Comment RSS