Sunday 14 July 2013

MEF and Memory in MEF 2

MEF - or Managed Extensibility Framework - is Microsoft's official Inversion Of Control (IoC) and Dependency Injection (DI) framework. Although MEF is not a true DI container, it has a lot of features compared to many other IoC frameworks. However, MEF is often measured as a slow IoC framework in tests and therefore is not very tempting to use. MEF on the other side is readily available in .NET. If you use .NET 4.5, you will have access to MEF 2 features such as ExportFactory. The worst feature in MEF is arguable the way the IoC container disposes objects. If you have a nonshared Part or instance (i.e not a singleton, but a part you can instantiate multiple instances of), and this instance type implements IDisposable, most likely this object will not be disposed until the container is teared down. This is not a desired feature, as object instances will accumulate and memory consumption of your application using MEF will go up. With the aid of ExportFactory, we can be able to free up object instances on demand. Let's use the ServiceLocator to get our instances from ExportFactory. When you use ExportFactory, you call CreateExport(), which returns an ExportLifetimeContext<T>. This object can then be used to dispose the object. By disposing the ExportLifetimeContext<T>, the object that was created with the ExportFactory is truly disposed and released at the same time from the IoC, finally making it possible to gather with Garbage Collection (GC), in the end freeing up memory. The code for retrieving the object instance via an ExportFactory can look like this:

    [Export]
    public class ExportFactoryProvider<T>
    {

        [Import]
        public ExportFactory<T> Factory { get; set; }

    }

Let's test out this ExportFactoryProvider with service locator. First let's create a part we can test. Let's say we got a simple view model:

    [Export(typeof(ITestViewModel))] 
    public class TestViewModel : ITestViewModel, IDisposable
    {

        public void SayHello(string message)
        {
            Debug.WriteLine(string.Format("Hi {0}!", message));
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this); 
        }

        private void Dispose(bool p)
        {
            Console.WriteLine("Disposed TestViewModel");
        }

    }

We can then create an instance of the TestViewModel using ServiceLocator using this:

            var serviceFactory = ServiceLocator.Current.GetInstance<ExportFactoryProvider<ITestViewModel>>().Factory;

            var testViewModelExport = serviceFactory.CreateExport(); 
            MessageBox.Show("About to dispose an instance of ITestViewModel: ");

            testViewModelExport.Value.SayHello("Johnny");
            testViewModelExport.Dispose();

As you can see above, we must first use the ExportFactoryProvider, then call CreateExport, then use the Value property and then use the ExportLifetimeContext<T> to control the disposing of the object from the IoC container. But as you can see, we must do some juggling to keep a reference to the lifetime context and the instance itself. These two objects are inherently tied together. Let's create a generic class to keep them together.

    [Export]
    [PartCreationPolicy(System.ComponentModel.Composition.CreationPolicy.NonShared)]
    public class ExportFactoryInstantiator<T> : IPartImportsSatisfiedNotification
    {

        [Import]
        public ExportFactory<T> Factory { get; set; }

        public T Instance { get; private set; }

        private ExportLifetimeContext<T> lifeTime;

        public void OnImportsSatisfied()
        {
            lifeTime = Factory.CreateExport();
            Instance = lifeTime.Value;
        }

        public bool DisposeOnDemand()
        {
            if (lifeTime == null)
                return false;
            lifeTime.Dispose();
            return Instance == null; 
        }

    }

You can use the class above, ExportFactoryInstantiator to create NonShared parts (object instances) via ExportFactory and via the instance created access the Instance property to get to the actual object and use the method DisposeOnDemand, which returns true if the object was set to null during the execution of this method. You can also see that we use IPartImportsSatisfiedNotification to await the resolution.

            var anotherTestViewModel = ServiceLocator.Current.GetInstance<ExportFactoryInstantiator<ITestViewModel>>();
            anotherTestViewModel.Instance.SayHello("Bob");
            anotherTestViewModel.DisposeOnDemand(); 
Note that the instance now can be easily worked against. However, still it is a bit verbose, we can create a static method to help us with that:

        public static ExportFactoryInstantiator<T> ResolveViaExportFactory<T>()
        {
            return ServiceLocator.Current.GetInstance<ExportFactoryInstantiator<T>>();
        }

We have finally reduced the complexity of being able to dispose MEF parts on demand in our applications:

            var yetAnotherTestViewModel = ResolveViaExportFactory<ITestViewModel>();
            yetAnotherTestViewModel.Instance.SayHello("Joey");
            yetAnotherTestViewModel.DisposeOnDemand(); 

To sum up, MEF 2 provides a feature where we can now dispose parts from the container on demand. This is a great improvement and will reduce the issues around memory leaks substantially. If you have complex viewmodels, disposing a view model high up in the object graph will usually dispose all child view models, properties and so on and reduce memory usage. But always be careful when disposing objects from your container. You must be sure that the object will not be useful anymore. In this StackOverflow thread you can also see an example of how to use a Part only when you need it, inside a using block: Nicholas Blumhardt on using ServiceLocator and ExportFactory As you can see, I use Nicholas Blumhardt's code as a starting point and refine it a bit to reduce complexity and tie together the Instance and provide DisponseOnDemand method. You must yourself judge when to release a part, be it a view model or some other resource. The using block are handy when you are sure you do not need the instance more than temporarily. You should consider doing that instead of importing many parts to your view model. Yes, the object creation of your view models will be quicker and yes, the execution will in fact be slower because of the need to create imported parts on demand via ServiceLocator, but at the same time, your application will keep a very low memory profile. I haven't had the opportunity to test out the code above yet against production code, so do not use it in production without verifying its validity in for example Red Gate ANTS Memory Profiler and testing it. I would like to hear from other developers using MEF and have experienced its memory usage woes for more views about MEF. If you have also tips against efficiency and performance of MEF containers, please let us other MEF developers know.

Monday 1 July 2013

Creating a Fiddler Extension

This article will quickly describe how you can create a Fiddler Extension. A Fiddler Extension can be loaded into the tool Fiddler by creating a Class library in .NET programmed in C#. If you use Fiddler 2, target .NET 2 or .NET 3.5. If you use Fiddler 4 (beta), you must actually target .NET 4 (this is not documented well on the Fiddler website at Fiddler 2).

First off, install Fiddler 4, if you have not installed it yet. You need at least Visual Studio 2005, but if you work with extensions for Fiddler 4, you must target .NET 4 (Visual Studio 2010 or 2012). Fiddler extensions are implemented using interfaces. Create a new solution in Visual Studio and select creating a Class Library. First off, add a reference to Fiddler.exe in your Fiddler installation folder. This exe file usually resides in the folder C:\Program Files (x86)\Fiddler2, the default location for installing Fiddler. After referencing the Fiddler executable, add also a reference to System.Windows.Forms, if your Fiddler extension will modify the GUI directly.

Here is a sample Fiddler extension that will remove a host by typing the command e.g. RemoveHost www.yourhosthere.com in the QuickExec command bar in Fiddler. Here www.yourhosthere.com is the hostname which is an example of a server to remove in the listing of Fiddler's capture of traffic. This Fiddler extension will remove all captures where we have a HTTP Header that contains a Host value of ww.yourhosthere.com We use the interface IHandleExecAction to add support for QuickExec here.

In addition, the Fiddler extension fakes the UserAgent by setting it to Violin. This extension is based on the tutorial at Fiddler website and the video of the Pluralsight course for Fiddler, which I have fully watched. The author, Robert Boedigheimer does an excellent job of explaining the possibilities of Fiddler tool at a basic, intermediate and advanced level. To add support for this we implement the interface IAutoTamper. Here is the source code of the extension I ended up writing in Visual Studio 2012. Remember to target .NET 4 Framework to support Fiddler 4!

using System;
using System.Collections.Generic;
using System.Text;
using System;
using System.Windows.Forms;
using Fiddler;


namespace TestFiddlerExtension
{
    public class Violin : Fiddler.IAutoTamper, IHandleExecAction    // Ensure class is public, or Fiddler won't see it!
    {
        string sUserAgent = "";

        public Violin()
        {
            /* NOTE: It's possible that Fiddler UI isn't fully loaded yet, so don't add any UI in the constructor.

               But it's also possible that AutoTamper* methods are called before OnLoad (below), so be
               sure any needed data structures are initialized to safe values here in this constructor */

            sUserAgent = "Violin";
        }

        public void OnLoad() { /* Load your UI here */ }
        public void OnBeforeUnload() { }

        public void AutoTamperRequestBefore(Session oSession)
        {
            oSession.oRequest["User-Agent"] = sUserAgent;
        }
        public void AutoTamperRequestAfter(Session oSession) { }
        public void AutoTamperResponseBefore(Session oSession) { }
        public void AutoTamperResponseAfter(Session oSession) { }
        public void OnBeforeReturningError(Session oSession) { }

        public bool OnExecAction(string sCommand)
        {
            string[] args = Fiddler.Utilities.Parameterize(sCommand);

            string command = args[0];

            if (command.ToLower() == "removehost")
            {

                if (args == null || args.Length != 2)
                {
                    FiddlerApplication.UI.SetStatusText("Specify host to remove");
                    return false;
                }

                string host = args[1];

                FiddlerApplication.UI.actSelectSessionsWithRequestHeaderValue("Host", host);
                FiddlerApplication.UI.actRemoveSelectedSessions();
            }

            return true; 

        }


    }
}


As you can see from the source code above, whenever we want to perform actions against the Fiddler GUI, we use the Fiddler.FiddlerApplication.UI object. This object has got methods for working with the Fiddler GUI. The class Fiddler.FiddlerUtilities has utility methods against fiddler. To work against Sessions (the individual rows of the Capture), we can see we can work against the Session by implementing IAutoTamper. The signature of the methods of these interfaces usually gives us the information we need, so our interface implementations can implement the behaviors of each specified interface. In addition to visiting the Project Properties of the Class Library and ensuring that .NET 4 framework is targeted, check that the Post build actions does the following:

copy "$(TargetPath)" "%userprofile%\My Documents\Fiddler2\Scripts\$(TargetFilename)"

The post action will compile the Fiddler Extension inside the class library and copy the DLL file to the users documents folder and subfolder Fiddler2\scripts folder. This is the users personal Fiddler Extensions. If you want to make your Fiddler extension available to all users, copy the compiled DLL file into the Scripts folder where Fiddler is installed, usually the folder:

C:\Program Files (x86)\Fiddler2



This article shows how you can create Fiddler extensions. This powerful HTTP Debugging proxy tools for analyzing network traffic is excellent and is able to capture traffic from diverse sources as WCF services bound to HTTPS or HTTP protocols, to acting as a reverse proxy for capturing traffic from mobile devices and regular capture of HTTP(S) traffic from a web browser.

Saturday 29 June 2013

Optimistic concurrency in Sql Server

This article will quickly describe how to enable optimistic concurrency in Sql Server. Optimistic concurrency is implemented in Sql Server through the use of row versioning and snapshots. Snapshots take two forms and both modes can be enabled. Snapshot isolation (SI) and Read Commited Snapshot Isolation (RCSI). To enable these two modes do the following (Example AdventureWorks2012):

ALTER DATABASE AdventureWorks2012
SET READ_COMMITTED_SNAPSHOT ON

ALTER DATABASE AdventureWorks2012
SET ALLOW_SNAPSHOT_ISOLATION ON

To check the status of your databases to see if these two flags are enabled:

SELECT DATABASE_ID,
NAME,
SNAPSHOT_ISOLATION_STATE_DESC,
IS_READ_COMMITTED_SNAPSHOT_ON
FROM sys.databases
For example, on my database, running this script returned the following: The column SNAPSHOT_ISOLATION_DESC concerns SI (Snapshot Isolation) and can take the following values:
  • IN_TRANSITION_TO_OFF
  • OFF
  • ON
  • IN_TRANSITION_TO_ON
  • OFF
The reason for having four states and not just two is that this command can take long time and a DBA can be blocked by running transactions in progress. To enable RCSI, a DBA must usually have exclusive access to the database and therefore no transactions in progress. The column READ_COMMITTED_SNAPSHOT_ON can have the values 0 or 1, where 0 means it is disabled and 1 means it is off. Make note that the database tempdb is created, if you have not enabled SI (and/or) RCSI earlier for your database instance. This database keeps the version history required to make snapshots work.