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.

Saturday, 1 June 2013

Implementing a generic Singleton in C#

This article will present the necessary code to implement a generic Singleton class in C#. Singletons are implemented in code, where you want to be sure there is one and only one instance of an object. An alternative is static classes, but static classes can only contain static methods and static properties / fields. Often your class be a non-static class, and in some contexts it is desired to be sure there is only one instance. There are some help in Inversion of Control (IoC) such as MEF to create a singleton (PartCreationPolicy.Shared), but sooner or later a need for creating a singleton is present. Let us first review the code for the generic singleton:

    public class Singleton<T> where T : new()
    {
        private static readonly T instance;

        static Singleton()
        {
            instance = new T();
        }

        public static T Instance
        {
            get { return instance; }
        }

        private Singleton()
        {

        }

    }

The Singleton Instance property is static and returns the private static readonly instance field of type T. It is important that the Instance property is returning the same instance here obviously, which is why we do not have a setter on this property. We constrain the Singleton class to have the generic constraint new, such that we can easily instantiate the object of type T. As you can see, we do not support specifying an overloaded constructor on the object of type T here. Without the use of the new generic constraint, one would have to instantiation via Activator.CreateInstance or some other means. In addition, we add a private default constructor, we do not want consumers to instantiate new Singleton objects of this class. For a demonstration of this, let us take this sample class, with a simple derived class:

    public class ProgramManager
    {
        private Guid guid;

        public ProgramManager()
        {
            guid = Guid.NewGuid();
        }

        public void PrintGuid()
        {
            Console.WriteLine("Guid is:" + guid);
        }

    }
 
    public class OperationManager : ProgramManager
    {



    }

I have created these three classes in a simple console application, this is how the running demo looks like:

            var programManager = Singleton<ProgramManager>.Instance;
            var secondProgramManager = Singleton<ProgramManager>.Instance;
            var operationManager = Singleton<OperationManager>.Instance;
            var secondOperationManager = Singleton<OperationManager>.Instance;
            programManager.PrintGuid();
            secondProgramManager.PrintGuid();
            operationManager.PrintGuid();
            secondOperationManager.PrintGuid();
            Console.WriteLine("Press any key to continue ..."); 
            Console.ReadKey(); 

The output is:

Guid is:842edf61-56c7-4916-a766-783e911361c8
Guid is:842edf61-56c7-4916-a766-783e911361c8
Guid is:987a113e-c664-4681-b9fb-6d463768327a
Guid is:987a113e-c664-4681-b9fb-6d463768327a
Press any key to continue ... .


Of course, the guids above will differ for each execution of the console application, but note that we got the same Guid in both cases for the two different classes. Our Singleton<T> Instance property always returns the same object, and keeps via the generic type argument separate instances of the Singleton generic instance demonstrated here. This shows this generic Singleton class can be used for many different scenarios. One feature I would like to add is the possibility to specify which constructor to call in the instantiation of the object of type T. I have not found a correct way to implement this yet using the code above.