Tuesday, December 18, 2012

Using WIX with managed custom action

WIX is a great toolset for creating installers. In most of the cases when you need an installer you need some custom logic to be executed. It's great that WIX supports managed custom actions. Anyway it wasn't so easy for me to make it work, so I want to share my experience.
I will demonstrate it using the WIX Visual Studio add-in (version v3.7.1217.0).

We will create WIX Setup project and C# Custom Action Project.
We will add a dummy text file in the setup project to be used as installation content and will change a little bit the auto created Product.wxs file.
<?xml version="1.0" encoding="UTF-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
  <Product Id="*" Name="WixWithCustomAction" Language="1033" Version="1.0.0.0" Manufacturer="Trifonov" UpgradeCode="60468a7d-6485-4e7e-bf82-503213bc43a8">
    <Package InstallerVersion="200" Compressed="yes" InstallScope="perMachine" />

    <Media Id='1' Cabinet='Dummy.cab' EmbedCab='yes' />

    <Directory Id='TARGETDIR' Name='SourceDir'>
      <Directory Id='ProgramFilesFolder'>
        <Directory Id='WixWithCustomAction' Name='WixWithCustomAction'>
          <Component Id="DummyContent" Guid="ba9028ae-0d3b-4b66-8560-f53330736265">
            <!-- Add the dummy file as content. -->
            <File Id="DummyFile" KeyPath="yes" Source="Dummy.txt" Vital="yes" />
          </Component>
        </Directory>
      </Directory>
    </Directory>

    <Feature Id="Complete" Title="WixWithCustomAction" Level="1">
      <ComponentRef Id='DummyContent' />
    </Feature>
  </Product>
</Wix>
That's how our solution looks like:

If we build the WixWithCustomAction project, WixWithCustomAction.msi will be created. If we run it WixWithCustomAction folder will be created in program files with Dummy.txt file inside.
But now we want to add a custom action which will create a file in C:\Temp folder. We will use the MyCustomActionProject for this. Let's change the CustomAction class a little bit:
using Microsoft.Deployment.WindowsInstaller;
using System.IO;

namespace MyCustomActionProject
{
    public class CustomActions
    {
        [CustomAction]
        public static ActionResult MyCustomAcion(Session session)
        {
            session.Log("Executing MyCustomAcion");

            File.CreateText(@"c:\temp\installed.txt");

            return ActionResult.Success;
        }
    }
}

Now we just need to call this custom action from the installer. To do this we will add a reference to this project in the setup project.
Now let's add the custom action in the Product.wxs file.
Adding the project as a reference allows as to use these variables.
But adding custom action is a little bit complicated. After building the MyCustomActionProject.dll file we will need a call to MakeSfxCA.exe and sfxca.dll in your installed WiX toolset as the dll need a reference to Microsoft.Deployment.WindowsInstaller.dll and has CustomAction.config attached. Calling the MakeSfxCA.exe tool will package the project output to MyCustomActionProject.CA.dll(here you can find some additional information about this).
As we use "C# Custom Action Project" there is an import added to $(MSBuildExtensionsPath)\Microsoft\WiX\v3.x\Wix.CA.targets file which will create this package on build. To check this you can build the custom action project and see the output:
So the custom action in the Product.wxs needs to reference the .CA.dll file. Thats why we cannot use
$(var.MyCustomActionProject.TargetPath) as a source for the custom action binary, but we will have to construct the source path like this:
$(var.MyCustomActionProject.TargetDir)$(var.MyCustomActionProject.TargetName).CA.dll
The other option is not to use the project reference but add the full path to the custom action output.
So we will add the following rows to the wxs file
<!--The source file should be the MyCustomActionProject.CA.dll file, that's why it's constructed this way-->
<Binary Id='CustomActionBinary' SourceFile='$(var.MyCustomActionProject.TargetDir)$(var.MyCustomActionProject.TargetName).CA.dll' />

<!--The DllEntry must be the name of the method to be called from the custom action project, in our case - MyCustomActionMethod 
http://wix.tramontana.co.hu/tutorial/events-and-actions/at-a-later-stage 
The Execute attribute will specify the deferred status of our custom action.
And finally, HideTarget will allow us to disable logging the parameteres passed to this custom action if security considerations so dictate.-->
<CustomAction Id='CustomActionId' BinaryKey='CustomActionBinary' DllEntry='MyCustomActionMethod' Execute="deferred" HideTarget="yes"/>

<InstallExecuteSequence>
  <!--We want to call the custom action before the install finalizes-->
  <Custom Action='CustomActionId' Before='InstallFinalize'/>
</InstallExecuteSequence>
And that's it. Now if we build the setup project and run the created msi installer, c:\temp\installed.txt will be created as a part of the installation process.

You can find the solution file here - WixWithCustomAction.zip

Friday, November 30, 2012

Sending stream to ServiceStack

Recently I needed to make a ServiceStack service which can receive big files, so I wanted to use streaming to accomplish this. Unfortunately there isn't much information about using streams with ServiceStack, so I decided to share my experience.

We'll create a sample solution containing both Server and Client. We will create a class library containing the service itself and an Utility project. So here is the structure of our solution:
So let's continue with the implementation of the service.
First of all we'll need to install the ServiceStack nuget package in the ServiceStackStreaming.Service project:
PM> Install-Package ServiceStack
This will add the dlls needed for ServiceStack. Now let's create the DTO:
using ServiceStack.ServiceHost;

namespace ServiceStackStreaming.Service
{
    [Route("/upload/{FileName}", "POST")]
    public class UploadPackage : IRequiresRequestStream
    {
        public System.IO.Stream RequestStream { get; set; }

        public string FileName { get; set; }
    }
}
To enable Streaming support we need to implement IRequiresRequestStream which needs a RequestStream property of type System.IO.Stream. We'll add a FileName property and include it in the Route so that we would be able to pass the uploaded file name.
The next thing to do is to create the service itself:
using ServiceStack.Common.Web;
using ServiceStackStreaming.Utility;
using System;
using System.IO;

namespace ServiceStackStreaming.Service
{
    public class UploadService : ServiceStack.ServiceInterface.Service
    {
        public object Post(UploadPackage request)
        {
            // hack - get the properties from the request
            if (string.IsNullOrEmpty(request.FileName))
            {
                var segments = base.Request.PathInfo.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
                request.FileName = segments[1];
            }

            string resultFile = Path.Combine(@"C:\Temp", request.FileName);
            if (File.Exists(resultFile))
            {
                File.Delete(resultFile);
            }
            using (FileStream file = File.Create(resultFile))
            {
                request.RequestStream.Copy(file);
            }
            
            return new HttpResult(System.Net.HttpStatusCode.OK);
        }
    }
}

Our dummy service will save the incoming file in the "C:\Temp" directory. With the code from line 12 to line 17 we are getting the FileName property if it's not set. It seems that when using streaming the additional properties are not processed and they are always null, so we'll do this little hack to get the properties parsing the request url.
The other trick we use here is the extension method of the System.IO.Stream class wich we have implemented in the ServiceStackStreaming.Utility project:
using System.IO;

namespace ServiceStackStreaming.Utility
{
    public static class StreamExtender
    {
        public static void Copy(this Stream instance, Stream target)
        {
            int bytesRead = 0;
            int bufSize = copyBuf.Length;

            while ((bytesRead = instance.Read(copyBuf, 0, bufSize)) > 0)
            {
                target.Write(copyBuf, 0, bytesRead);
            }
        }
        private static readonly byte[] copyBuf = new byte[0x1000];
    }
}
this simply copes the instance stream to the target stream. Another option is to use ServiceStack StreamExtensions WriteTo method instead of creating this utility method.
The last thing we need to do to create a functional service is to add the AppHost class, we will inherit  AppHostHttpListenerBase as we want to host the service in a window console application.
using ServiceStack.WebHost.Endpoints;

namespace ServiceStackStreaming.Service
{
    public class AppHost : AppHostHttpListenerBase
    {
        public AppHost() : base("Agent", typeof(UploadService).Assembly) { }

        public override void Configure(Funq.Container container)
        {
            // we can add the routing here instead of adding it as attribute to the DTO
            //Routes
            //    .Add("/upload/{FileName}", "POST");
        }
    }
}
We can configure the route here, but I prefer doing this with attribute.
Now let's host the service. To do this we'll need to add the same ServiceStack nuget to the SertviceStackStreaming.Server project and add the following code to the Program.cs file:
using ServiceStackStreaming.Service;
using System;

namespace ServiceStackStreaming.Server
{
    class Program
    {
        static void Main(string[] args)
        {
            var appHost = new AppHost();
            appHost.Init();
            appHost.Start("http://*:1999/");

            Console.WriteLine("Service listening on port 1999!");
            Console.ReadKey();
        }
    }
}

This will be enough to host the service listening to port 1999.
Now let's call the service from the ServiceStackStreaming.Client (again we'll have to instal the sam e nuget package here).
using ServiceStackStreaming.Utility;
using System.IO;
using System.Net;

namespace ServiceStackStreaming.Client
{
    class Program
    {
        static void Main(string[] args)
        {
            string filePath = @"c:\temp\upload.zip";
            
            HttpWebRequest client = (HttpWebRequest)WebRequest.Create("http://localhost:1999/upload/upload-copy.zip");
            client.Method = WebRequestMethods.Http.Post;
            
            // the following 4 rows enable streaming 
            client.AllowWriteStreamBuffering = false;
            client.SendChunked = true;
            client.ContentType = "multipart/form-data;";
            client.Timeout = int.MaxValue;

            using (FileStream fileStream = File.OpenRead(filePath))
            {
                fileStream.Copy(client.GetRequestStream());
            }

            var response = new StreamReader(client.GetResponse().GetResponseStream()).ReadToEnd();
        }
    }
}
And that's it. We create WebRequest, set the needed properties to enable streaming on the client and copy the file stream to the request stream. This will call the service and will upload the "C:\Temp\upload.zip" file as upload-copy.zip file.

You can find the sample code here: ServiceStackStreaming.zip

Thursday, November 15, 2012

Testing private methods with Visual Studio

When writing unit tests in most of the cases we have to test private methods. Let's see how this can be achieved using Visual Studio. I will give you three options:

  1. You can test private methods using Reflection, but this is not always a good option, as when you change the name or input arguments of a Method, you won't get any error when building, but you will get exceptions run time.
    We will use the project from my previous post Getting console output within a unit test.
    We will add a private method to the DummyClass:
    using System;
    
    namespace ConsoleLogger
    {
        public class DummyClass
        {
            public void WriteToConsole(string text)
            {
                Console.Write(text);
            }
    
            private void PrivateWriteToConsole(string text)
            {
                Console.Write("Private: " + text);
            }
        }
    }
    
    Now we can add a unit test to test the method using reflection:
    [TestMethod]
    public void PrivateWriteToConsoleReflection()
    {
        var currentConsoleOut = Console.Out;
    
        DummyClass target = new DummyClass();
        Type type = typeof(DummyClass);
    
        string text = "Hello";
    
        using (var consoleOutput = new ConsoleOutput())
        {
            var method = type.GetMethod("PrivateWriteToConsole", 
                BindingFlags.NonPublic | BindingFlags.Instance);
            method.Invoke(target, new object[1] { text });
    
            Assert.AreEqual(string.Format("Private: {0}", text), 
                consoleOutput.GetOuput());
        }
    
        Assert.AreEqual(currentConsoleOut, Console.Out);
    }
    We get and invoke the method using reflection.

  2. Another options is to use PrivateObject class. Using it you can easily call private method, but you have the same problem, you won't get compile exception when name or parameters are changed. Here is the same test written using PrivateObject:
    [TestMethod]
    public void PrivateWriteToConsolePrivateObject()
    {
        var currentConsoleOut = Console.Out;
    
        PrivateObject target = new PrivateObject(typeof(DummyClass));
    
        string text = "Hello";
    
        using (var consoleOutput = new ConsoleOutput())
        {
            target.Invoke("PrivateWriteToConsole", text);
    
            Assert.AreEqual(string.Format("Private: {0}", text), 
                consoleOutput.GetOuput());
        }
    
        Assert.AreEqual(currentConsoleOut, Console.Out);
    }
    
  3. And here is the third option which I think is the best. You can add .accessor file containing the name of the assembly whose private methods you want to see, or you can use Visual Studio "Create Unit Tests..." wizard to do this for you:

    this will add the following unit test:
    /// 
    ///A test for PrivateWriteToConsole
    ///
    [TestMethod]
    [DeploymentItem("ConsoleLogger.exe")]
    public void PrivateWriteToConsoleTest()
    {
        DummyClass_Accessor target = new DummyClass_Accessor(); // TODO: Initialize to an appropriate value
        string text = string.Empty; // TODO: Initialize to an appropriate value
        target.PrivateWriteToConsole(text);
        Assert.Inconclusive("A method that does not return a value cannot be verified.");
    }
    
    we will modify it for our needs:
    /// 
    ///A test for PrivateWriteToConsole
    ///
    [TestMethod]
    [DeploymentItem("ConsoleLogger.exe")]
    public void PrivateWriteToConsoleTest()
    {
        var currentConsoleOut = Console.Out;
    
        DummyClass_Accessor target = new DummyClass_Accessor();
    
        string text = "Hello";
    
        using (var consoleOutput = new ConsoleOutput())
        {
            target.PrivateWriteToConsole(text);
    
            Assert.AreEqual(string.Format("Private: {0}", text),
                consoleOutput.GetOuput());
        }
    
        Assert.AreEqual(currentConsoleOut, Console.Out);
    }
    
    When Visual Studio builds the project it will generate ConsoleLogger_Accessor.exe assembly, containing DummyClass_Accessor class with public methods only.
  4. Just to mention that you can test internal methods using the same approaches, but you will have one more option - in the AssemblyInfo file of the assembly being tested, you can add  InternalsVisibleTo attribute to specify which assembly will see the internal methods, in our case:
    [assembly: InternalsVisibleTo("ConsoleLogger.Tests")]
    
    now we will add an internal method to the same class:
    using System;
    
    namespace ConsoleLogger
    {
        public class DummyClass
        {
            public void WriteToConsole(string text)
            {
                Console.Write(text);
            }
    
            private void PrivateWriteToConsole(string text)
            {
                Console.Write("Private: " + text);
            }
    
            internal void InternalWriteToConsole(string text)
            {
                Console.Write("Internal: " + text);
            }
        }
    }
    
    and here is the working test method:
    [TestMethod]
    public void InternalWriteToConsoleTest()
    {
        var currentConsoleOut = Console.Out;
    
        DummyClass target = new DummyClass();
    
        string text = "Hello";
    
        using (var consoleOutput = new ConsoleOutput())
        {
            target.InternalWriteToConsole(text);
    
            Assert.AreEqual(string.Format("Internal: {0}", text),
                consoleOutput.GetOuput());
        }
    
        Assert.AreEqual(currentConsoleOut, Console.Out);
    }
    
And here's the code - ConsoleLogger.zip

Getting console output within a unit test

Today I needed to test a method which writes to the Console to validate the ouput. It is not hard to change the default console output and check the result. However you may forget to return the original output at the end. So let's take a look at my solution.

Let say we have the following class we want to test:
using System;

namespace ConsoleLogger
{
    public class DummyClass
    {
        public void WriteToConsole(string text)
        {
            Console.Write(text);
        }
    }
}

I have created a small helper class to redirect the output to a StringWriter:
using System;
using System.IO;

namespace ConsoleLogger.Tests
{
    public class ConsoleOutput : IDisposable
    {
        private StringWriter stringWriter;
        private TextWriter originalOutput;

        public ConsoleOutput()
        {
            stringWriter = new StringWriter();
            originalOutput = Console.Out;
            Console.SetOut(stringWriter);
        }

        public string GetOuput()
        {
            return stringWriter.ToString();
        }

        public void Dispose()
        {
            Console.SetOut(originalOutput);
            stringWriter.Dispose();
        }
    }
}
Now let's write the unit test:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace ConsoleLogger.Tests
{
    [TestClass]
    public class DummyClassTest
    {
        [TestMethod]
        public void WriteToConsoleTest()
        {
            var currentConsoleOut = Console.Out;

            DummyClass target = new DummyClass(); 
            
            string text = "Hello";

            using (var consoleOutput = new ConsoleOutput())
            {
                target.WriteToConsole(text);

                Assert.AreEqual(text, consoleOutput.GetOuput());
            }

            Assert.AreEqual(currentConsoleOut, Console.Out);
        }
    }
}
This way we are sure that the original output will be restored and it's easy to get the output from the console.

You can find the sample here ConsoleLogger.zip.

Thursday, November 8, 2012

How to configure local Nuget Repository

After my last posts about Nuget packaging I wanted to share another useful experience with Nuget.
You can create a local repository to store all the packages you need and not to download those every time.
  1. To do this I have created a folder C:\NugetConfig\Repo and I have copied there the Newtonsoft.Json.4.5.10.nupkg package file
  2. To make the both solutions use this local repository all I have to do is to change the following settings in the NuGet.targets file:
    <ItemGroup Condition=" '$(PackageSources)' == '' ">
        <!-- Package sources used to restore packages. By default will used the registered sources under %APPDATA%\NuGet\NuGet.Config -->
        <!--
            <PackageSource Include="https://nuget.org/api/v2/" />
            <PackageSource Include="https://my-nuget-source/nuget/" />
        -->
    </ItemGroup>
    
    and adding s new PackageSource location
    <ItemGroup Condition=" '$(PackageSources)' == '' ">
        <!-- Package sources used to restore packages. By default will used the registered sources under %APPDATA%\NuGet\NuGet.Config -->
        <!--
            <PackageSource Include="https://nuget.org/api/v2/" />
            <PackageSource Include="https://my-nuget-source/nuget/" />
        -->
        <PackageSource Include="C:\NugetConfig\Repo" />
    </ItemGroup>
    
    And that's it. This will make the solution search for the used packages in the given folder and you will get а meaningful error if the package could not be found.
  3. Furthermore you can add you local repository to the visual studio package sources
    so that you will be able to search and add packages from it to any new solution:
As usual you can find the code here NugetConfig-Local-Repo.zip.

Share Nuget packages between solutions part 2

Let's see how we can fix the problem explained here.
According to the latest release notes by now you should be able to change the packages folder by adding this setting in the Nuget.config file:
<configuration>
  <config>
    <add key="repositoryPath" value="C:\myteam\teampackages"></add>
  </config>
  ... 
</configuration>
However unfortunately I couldn't make this work :( So I found a workaround. I want to make the Second.sln use the package folder of First.sln. So I have made the following changes to the NuGet.targets file.
  1. I this section:
    <PropertyGroup Condition=" '$(OS)' == 'Windows_NT'">
        <!-- Windows specific commands -->
        <NuGetToolsPath>$([System.IO.Path]::Combine($(SolutionDir), ".nuget"))</NuGetToolsPath>
        <PackagesConfig>$([System.IO.Path]::Combine($(ProjectDir), "packages.config"))</PackagesConfig>
    </PropertyGroup>
    
    I have added the following row:
    <PackagesDir>$(SolutionDir)..\First\packages</PackagesDir> 
  2. Change the arguments of the NewGetCommand from:
    <RestoreCommand>$(NuGetCommand) install "$(PackagesConfig)" -source "$(PackageSources)" $(RequireConsentSwitch) -solutionDir "$(SolutionDir)</RestoreCommand>
    
    to:
    <RestoreCommand>$(NuGetCommand) install "$(PackagesConfig)" -source "$(PackageSources)" -o "$(PackagesDir)" $(RequireConsentSwitch) -solutionDir "$(SolutionDir)</RestoreCommand>
    
    I have added -o "$(PackagesDir)" which should make the packages to be downloaded to the PackagesDir folder
  3. To make the configuration more flexible we can change the PackagesDir definition to
    <PackagesDir Condition="'$(PackagesDir)' == ''">$(SolutionDir)..\First\packages</PackagesDir> 
    this will allow us to predefine the PackagesDir value in the .csproj.user files.
  4. To test this we can add the C:\ NugetConfig\First\Dummy\Dummy.csproj.user with the following content:
    <?xml version="1.0" encoding="utf-8"?>
    <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
        <PropertyGroup>
            <PackagesDir>C:\NugetConfig\packages</PackagesDir>
        </PropertyGroup>
    </Project>
    
    This will make the Nuget to get files in the C:\NugetConfig\packages folder.
And here is the code NugetConfig-part-2.zip

Share Nuget packages between solutions part 1

Many of you may use Nuget to add reference assemblies to your projects. Anyway sometimes we need to share a project between solutions. In this case if the relative path to this project from the different solutions is different you won't be able to use the default nuget packaging functionality.
Let me explain this with samples.
  1. Let's create an empty Console application named First in folder C:\NugetConfig\First
  2. Add a dummy class library project to this solution in the same folder.
  3. Add reference in the console application to the class library. You should have the following structure now:
  4. Now add Newtonsoft.Json package to the solution:
  5. Install the package to the Dummy project:
  6. Add a dummy class to the dummy project which references Newton Json:
    namespace Dummy
    {
        public class Dummy
        {
            public Newtonsoft.Json.Required Required { get; set; }
    
            public Dummy()
            {
                this.Required = Newtonsoft.Json.Required.Always;
            }
    
            public override string ToString()
            {
                return this.Required.ToString();
            }
        }
    } 
  7. Add a call to the dummy project in Program.cs
    using System;
    
    namespace First
    {
        class Program
        {
            public static void Main(string[] args)
            {
                var dummy = new Dummy.Dummy();
                Console.WriteLine(dummy);
            }
        }
    }
    
  8. Now enable Nuget Package Restore on this solution:

    Now if we delete the Newtonsoft.Json folder from the packages folder and run the build the package is downloaded and the solution builds successfully
  9. Let's create a new project in another solution named Second in folder in folder C:\NugetConfig\Second
  10. Add reference to the Dummy project 
  11. Add a call to the dummy project in Program.cs
    using System;
    
    namespace Second
    {
        class Program
        {
            public static void Main(string[] args)
            {
                var dummy = new Dummy.Dummy();
                Console.WriteLine(dummy);
            }
        }
    }
    
  12. We can build the second solution now as we have already downloaded the needed nuget package. But let's delete the package from C:\NugetConfig\First\packages folder. 
  13. Now we won't be able to build the solution. Let's enable Nuget Package Restore on this solution as well.
  14. Trying to build the solution leads to this error:
So here is the actual problem:
In the Dummy project there is a reference to the NewtonJson
 <Reference Include="Newtonsoft.Json">
      <HintPath>..\packages\Newtonsoft.Json.4.5.10\lib\net40\Newtonsoft.Json.dll</HintPath>
 </Reference>
But our folder looks like this:

So we search for the Newtonsoft.Json.dll in folder C:\NugetConfig\First\packages folder as the HintPath is relative from the Dummy.csproj file.
But the build downloads the package to C:\NugetConfig\Second\packages

You can find the code here NugetConfig-part-1.zip

To see how we can resolve this issue go to the part 2.

Monday, November 5, 2012

Compare two dll files programmatically using Hash

In the past days I needed to compare two .NET assemblies to see if they are functionally the same. As you may know, when you build the same project several times the resulting output .dll or .exe file is always different. That's because of the ModuleVerisonId property(MVID). So in order to check if two assemblies are the same we can disassemble them to IL code and compare them.
The easiest way to disassemble the file is to use MSIL Disassembler. However it is not in a common location. It can be in any of the following locations:

C:\Program Files\Microsoft SDKs\Windows\v6.0\bin\ildasm.exe
C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\ildasm.exe
C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\ildasm.exe
C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\x64\ildasm.exe
C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools\ildasm.exe
C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools\x64\ildasm.exe
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin\ildasm.exe
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin\x64\ildasm.exe
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools\ildasm.exe
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools\x64\ildasm.exe


So in my following solution I have embedded the ildasm.exe file in a class library to be able to use it on any machine.When we disassemble an assembly we check if the ildasm.exe file exists in the executing assembly folder and if not the file is extracted there from our dll file.
Using the ildasm file we get the IL code and save it to a temporary file.
Then we need to remove the following three rows:
  1. MVID - as I wrote before this is a unique GUID generated with every build
  2. Image Base (The image base tells us as to where the program will be loaded in memory by the Windows loader.) - this is different with every build as well
  3. Time-date stamp - the time and date when the ildasm is run
So we read the temp file content, remove these rows we use regex and then save the file content to the same file.
You can find the Disassembler file here:
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Diagnostics;
using System.Text.RegularExpressions;

namespace FileHasher
{
    public class Disassembler
    {
        public static Regex regexMVID = new Regex("//\\s*MVID\\:\\s*\\{[a-zA-Z0-9\\-]+\\}", RegexOptions.Multiline | RegexOptions.Compiled);
        public static Regex regexImageBase = new Regex("//\\s*Image\\s+base\\:\\s0x[0-9A-Fa-f]*", RegexOptions.Multiline | RegexOptions.Compiled);
        public static Regex regexTimeStamp = new Regex("//\\s*Time-date\\s+stamp\\:\\s*0x[0-9A-Fa-f]*", RegexOptions.Multiline | RegexOptions.Compiled);
        
        private static readonly Lazy<Assembly> currentAssembly = new Lazy<Assembly>(() =>
        {
            return MethodBase.GetCurrentMethod().DeclaringType.Assembly;
        });

        private static readonly Lazy<string> executingAssemblyPath = new Lazy<string>(() =>
        {
            return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
        });

        private static readonly Lazy<string> currentAssemblyFolder = new Lazy<string>(() =>
        {
            return Path.GetDirectoryName(currentAssembly.Value.Location);
        });

        private static readonly Lazy<string[]> arrResources = new Lazy<string[]>(() =>
        {
            return currentAssembly.Value.GetManifestResourceNames();
        });

        private const string ildasmArguments = "/all /text \"{0}\"";

        public static string ILDasmFileLocation
        {
            get
            {
                return Path.Combine(executingAssemblyPath.Value, "ildasm.exe");
            }
        }

        static Disassembler()
        {
            //extract the ildasm file to the executing assembly location
            ExtractFileToLocation("ildasm.exe", ILDasmFileLocation);
        }

        /// <summary>
        /// Saves the file from embedded resource to a given location.
        /// </summary>
        /// <param name="embeddedResourceName">Name of the embedded resource.</param>
        /// <param name="fileName">Name of the file.</param>
        protected static void SaveFileFromEmbeddedResource(string embeddedResourceName, string fileName)
        {
            if (File.Exists(fileName))
            {
                //the file already exists, we can add deletion here if we want to change the version of the 7zip
                return;
            }
            FileInfo fileInfoOutputFile = new FileInfo(fileName);

            using (FileStream streamToOutputFile = fileInfoOutputFile.OpenWrite())
            using (Stream streamToResourceFile = currentAssembly.Value.GetManifestResourceStream(embeddedResourceName))
            {
                const int size = 4096;
                byte[] bytes = new byte[4096];
                int numBytes;
                while ((numBytes = streamToResourceFile.Read(bytes, 0, size)) > 0)
                {
                    streamToOutputFile.Write(bytes, 0, numBytes);
                }

                streamToOutputFile.Close();
                streamToResourceFile.Close();
            }
        }

        /// <summary>
        /// Searches the embedded resource and extracts it to the given location.
        /// </summary>
        /// <param name="fileNameInDll">The file name in DLL.</param>
        /// <param name="outFileName">Name of the out file.</param>
        protected static void ExtractFileToLocation(string fileNameInDll, string outFileName)
        {
            string resourcePath = arrResources.Value.Where(resource => resource.EndsWith(fileNameInDll, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
            if (resourcePath == null)
            {
                throw new Exception(string.Format("Cannot find {0} in the embedded resources of {1}", fileNameInDll, currentAssembly.Value.FullName));
            }
            SaveFileFromEmbeddedResource(resourcePath, outFileName);
        }

        public static string GetDisassembledFile(string assemblyFilePath)
        {
            if (!File.Exists(assemblyFilePath))
            {
                throw new InvalidOperationException(string.Format("The file {0} does not exist!", assemblyFilePath));
            }

            string tempFileName = Path.GetTempFileName();
            var startInfo = new ProcessStartInfo(ILDasmFileLocation, string.Format(ildasmArguments, assemblyFilePath));
            startInfo.WindowStyle = ProcessWindowStyle.Hidden;
            startInfo.CreateNoWindow = true;
            startInfo.UseShellExecute = false;
            startInfo.RedirectStandardOutput = true;

            using (var process = System.Diagnostics.Process.Start(startInfo))
            {
                string output = process.StandardOutput.ReadToEnd();
                process.WaitForExit();

                if (process.ExitCode > 0)
                {
                    throw new InvalidOperationException(
                        string.Format("Generating IL code for file {0} failed with exit code - {1}. Log: {2}",
                        assemblyFilePath, process.ExitCode, output));
                }

                File.WriteAllText(tempFileName, output);
            }

            RemoveUnnededRows(tempFileName);
            return tempFileName;
        }

        private static void RemoveUnnededRows(string fileName)
        {
            string fileContent = File.ReadAllText(fileName);
            //remove MVID
            fileContent = regexMVID.Replace(fileContent, string.Empty);
            //remove Image Base
            fileContent = regexImageBase.Replace(fileContent, string.Empty);
            //remove Time Stamp
            fileContent = regexTimeStamp.Replace(fileContent, string.Empty);
            File.WriteAllText(fileName, fileContent);
        }

        public static string DisassembleFile(string assemblyFilePath)
        {
            string disassembledFile = GetDisassembledFile(assemblyFilePath);
            try
            {
                return File.ReadAllText(disassembledFile);
            }
            finally
            {
                if (File.Exists(disassembledFile))
                {
                    File.Delete(disassembledFile);
                }
            }
        }
    }
}

So using this class we can get the IL code of a .NET assemlby. Now we can create a Hash Calculator to calculate the hash of the file, so that we can store the hash and compare it with newer files. To calculate the hash I use the following approach:
  1. Check if the file ends with .dll or .exe - if yes this can be a .NET assembly, if no get file hash
  2. Try to open the assembly with Assembly.LoadFile to see if this is a valid .NET assembly, if there is a BadImageFormatException, this is not a .NET one so get file hash
  3. If this is a .net assembly get the IL code file and calculate it's hash
To calculate file hash we use MD5CryptoServiceProvider. So here is the Hash Calculator:
using System;
using System.IO;
using System.Reflection;

namespace FileHasher
{
    public class HashCalculator
    {
        public string FileName { get; private set; }

        public HashCalculator(string fileName)
        {
            this.FileName = fileName;
        }

        public string CalculateFileHash()
        {
            if (Path.GetExtension(this.FileName).Equals(".dll", System.StringComparison.InvariantCultureIgnoreCase)
                || Path.GetExtension(this.FileName).Equals(".exe", System.StringComparison.InvariantCultureIgnoreCase))
            {
                return GetAssemblyFileHash();
            }
            else
            {
                return GetFileHash();
            }
        }

        private string GetFileHash()
        {
            return CalculateHashFromStream(File.OpenRead(this.FileName));
        }

        private string GetAssemblyFileHash()
        {
            string tempFileName = null;
            try
            {
                //try to open the assembly to check if this is a .NET one
                var assembly = Assembly.LoadFile(this.FileName);
                tempFileName = Disassembler.GetDisassembledFile(this.FileName);
                return CalculateHashFromStream(File.OpenRead(tempFileName));
            }
            catch(BadImageFormatException)
            {
                return GetFileHash();
            }
            finally
            {
                if (File.Exists(tempFileName))
                {
                    File.Delete(tempFileName);
                }
            }
        }

        private string CalculateHashFromStream(Stream stream)
        {
            using (var readerSource = new System.IO.BufferedStream(stream, 1200000))
            {
                using (var md51 = new System.Security.Cryptography.MD5CryptoServiceProvider())
                {
                    md51.ComputeHash(readerSource);
                    return Convert.ToBase64String(md51.Hash);
                }
            }
        }
    }
}

You can find the code here AssemblyHasher.zip or on github AssemblyHasher

Wednesday, October 31, 2012

Online Html Encoder

When using SyntaxHighlighter I need to Html Encode my xml snippets and snippets containing "<" and/or ">".
That's why I have created this simple form to make the snippets friendly :)

Remove unneded scrollbars from SyntaxHighlighter

Some of you may have noticed that when using SyntaxHighlighter version 3.0.83 there are always vertical and horizontal scroll bars no matter what is the size of the text. To fix this problem you have two options.
  1. Download the shCore.css and change
    .syntaxhighlighter {
      width: 100% !important;
      margin: 1em 0 1em 0 !important;
      position: relative !important;
      overflow: auto !important;
      font-size: 1em !important;
    }
    
    to
    .syntaxhighlighter {
      width: 100% !important;
      margin: 1em 0 1em 0 !important;
      position: relative !important;
      overflow-y: hidden !important;
      overflow-x: auto !important;
      font-size: 1em !important;
    }
    and reference your version of the file.

  2. Add the following style in the head section of your template:
    <style type="text/css">
      .syntaxhighlighter { 
         overflow-y: hidden !important; 
         overflow-x: auto !important; 
      }
    </style>
    

This will show horizontal scroll bar only when needed.

Tuesday, October 30, 2012

WCF Duplex service exceeded timeout of 00:00:00

In case you use WCF duplex services using wsDualHttpBidning there is a chance to get a very strange error:

The HTTP request to 'http://vasil-trifonov.blogspot.com/DuplexService.svc' has exceeded the allotted timeout of 00:00:00. The time allotted to this operation may have been a portion of a longer timeout.
StackTrace: at System.ServiceModel.Channels.HttpChannelUtilities.SetRequestTimeout(HttpWebRequest request, TimeSpan timeout)
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.SendRequest(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)


It turns out that the server where the service is hosted did not see the machine that calls the service. So if you get this error make sure that the server can ping the caller.

Another problem can be that the server may not be able to resolve the temporary listening address as it will be something like

http://trifonov-pc/Temporary_Listen_Addresses/4881e24d-9d46-48dd-a013-399d8fab8757/ccc1d9b8-adbb-479d-a721-517b2162ad6c

the remote machine may be in another domain and may not be able to resolve the caller by name. In that case you can use the clientBaseAddress in the caller configuration
<wsDualHttpBinding>
 <binding name="duplexBinding" closeTimeout="00:01:00"
  openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false"
  transactionFlow="false" hostNameComparisonMode="StrongWildcard"
  maxBufferPoolSize="524288" maxReceivedMessageSize="1073741824"
  messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" 
  clientBaseAddress="http://192.168.0.100/Temporary_Listen_Addresses">
  <readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="16384"
    maxBytesPerRead="4096" maxNameTableCharCount="16384" />
  <reliableSession ordered="true" inactivityTimeout="00:10:00" />
  <security mode="Message">
   <message clientCredentialType="Certificate"/>
  </security>
 </binding>
</wsDualHttpBinding>
We can use the clientBaseAddress to set the IP Address as the base address for the callback channel. We can also set another port there if we want.

Monday, October 29, 2012

Securing WCF Service with Self Signed Certificates programmatically

I've spent some time to deal with WCF securing with certificates and came to a solution that I want to share.
As you probably know, WCF supports certificate authentication and it's not so hard to set up. However you will need to install certificates on both the service machine and the caller machine. This can be a problem if you want to host the service on a shared hosting environment for example. Even if the service is hosted on a machine in your network you will still need some permissions to be given to the service application pool user in order to access the certificate private key.

So with the help of this blog post I found a way to create Self Signed certificate using some windows native methods.

using System;
using System.Runtime.InteropServices;

namespace Certificate.Native
{
    internal static class NativeMethods
    {
        [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool FileTimeToSystemTime(
            [In] ref long fileTime,
            out SystemTime systemTime);

        [DllImport("AdvApi32.dll", SetLastError = true, ExactSpelling = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool CryptAcquireContextW(
            out IntPtr providerContext,
            [MarshalAs(UnmanagedType.LPWStr)] string container,
            [MarshalAs(UnmanagedType.LPWStr)] string provider,
            int providerType,
            int flags);

        [DllImport("AdvApi32.dll", SetLastError = true, ExactSpelling = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool CryptReleaseContext(
            IntPtr providerContext,
            int flags);

        [DllImport("AdvApi32.dll", SetLastError = true, ExactSpelling = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool CryptGenKey(
            IntPtr providerContext,
            int algorithmId,
            int flags,
            out IntPtr cryptKeyHandle);

        [DllImport("AdvApi32.dll", SetLastError = true, ExactSpelling = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool CryptDestroyKey(
            IntPtr cryptKeyHandle);

        [DllImport("Crypt32.dll", SetLastError = true, ExactSpelling = true)]
        public static extern IntPtr CertCreateSelfSignCertificate(
            IntPtr providerHandle,
            [In] ref CryptoApiBlob subjectIssuerBlob,
            int flags,
            [In] ref CryptKeyProviderInformation keyProviderInformation,
            IntPtr signatureAlgorithm,
            [In] ref SystemTime startTime,
            [In] ref SystemTime endTime,
            IntPtr extensions);

        [DllImport("Crypt32.dll", SetLastError = true, ExactSpelling = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool CertFreeCertificateContext(
            IntPtr certificateContext);
    }
}

I have created CertificateSerializer to serialize the certificate to base64string:
using System;
using System.IO;
using System.Security.Cryptography.X509Certificates;
namespace Certificate
{
    public class CertificateSerializer
    {
        public X509Certificate2 Deserialize(string certificateString)
        {
            byte[] numArray = Convert.FromBase64String(certificateString);
            string tempFileName = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            try
            {
                File.WriteAllBytes(tempFileName, numArray);
                X509Certificate2 certificate = new X509Certificate2(tempFileName, default(string), X509KeyStorageFlags.Exportable);
                return certificate;
            }
            finally
            {
                File.Delete(tempFileName);
            }
        }

        public string Serialize(X509Certificate2 certificate)
        {
            byte[] numArray = certificate.Export(X509ContentType.Pfx);
            string base64String = Convert.ToBase64String(numArray);

            return base64String;
        }
    }
}

In the configuration section we can store the serialized certificate and the Thumbprints and Subjects of the trusted certificates, so that we can give the service the information about the trusted parties. Here's an example of the custom section content:

    <configSections>
        <section name="certificateSection" type="Certificate.Configuration.CertificatesSection, Certificate"/>
    </configSections>
    <certificateSection certificate="MIIExgIBAzCCBIYGCSqGSIb3DQEHAaCCBHcEggRzMIIEbzCCApgGCSqGSIb3DQEHAaCCAokEggKFMIICgTCCAn0GCyqGSIb3DQEMCgECoIIBjjCCAYowHAYKKoZIhvcNAQwBAzAOBAgbm3IPSqU0BQICB9AEggFojvCBmeSJ6n4IlKxgSv1XgIB5LaD7tb06f/yTLsZRK+4rnqCaesmYFFHP889JTySdqPPyE6fNrpFXTcvcRC6lQQglLnxbRZQotPHvDv4MEzEdI67zkkfM7RsxxXRUQE+ex5H+oQxjScvVRWlKa0KXLk7DOa+Ijz/epLFCum2CE2aUE/AOdi8GCYf7D0yMa472/buQRX1qWX5MYuH+sZI1py/unS8R5R4cytRr8dKJHmn3YtLuhEwQOuXiQ/mUK5PKj+xYp6b8ssVIXQjuLpXZnnT7i/KdZipxmTCf+OtXbAysBw2VaQ9+NmR8cufy8nUb/KgSNfcE3hTHTxIaBnhddhuHxvfR5oYIAzPK3NTq/S1qCEqxDJnBFapdnRcKfHEAlDwIB/KZyHgKdVBiu16pB9e+bxl840CW6vI/tILBbpww3rjvzKKQYZZ6uPu1oNLS2TeX7JsBJE3p0HJE2DPFLfmXLPVPSkHBMYHbMBMGCSqGSIb3DQEJFTEGBAQBAAAAMFcGCSqGSIb3DQEJFDFKHkgAZgAzADEAMwBlADQAYQA4AC0AMAA2ADMANwAtADQANAA1ADAALQBiAGMANAA5AC0AMwA2AGEAMABkAGIAOQAxADkAOABhAGQwawYJKwYBBAGCNxEBMV4eXABNAGkAYwByAG8AcwBvAGYAdAAgAEUAbgBoAGEAbgBjAGUAZAAgAEMAcgB5AHAAdABvAGcAcgBhAHAAaABpAGMAIABQAHIAbwB2AGkAZABlAHIAIAB2ADEALgAwMIIBzwYJKoZIhvcNAQcGoIIBwDCCAbwCAQAwggG1BgkqhkiG9w0BBwEwHAYKKoZIhvcNAQwBBjAOBAjWmEM3BmtPWwICB9CAggGIIxS2KaegZ8TDfdq1AP55giyOzgLOvd1LYA5M1QwRmYcM4IiJe5Z6yB6usrnMa/oAJ6suBw72UTO8lTGc/AXWtbrJg6KM0CuyI7lKdoShn36FRx35djx5plXpDxVrZtR2MbOxgSdUNyUCiuRWe/FUzpwE93IWQnfIleeziH1YXuZdvxy/vTLKT2VngeZh3BjyG25n7Fj44xgy7CQM/g/q+TgHBJjnY9qD36kPdaWxkxytadpJH3GgnKLjoQCvHhFN6NEVhErnvzZo63jPZIDWHxr7EYGkbVTzwtPwlocTDgm75gS/IwCMNdAxHP9ofMM4H+2g/UV88R4ABgUoP139Drz5LrfHFsnvPx3/twygMX6lUccnwyKZTVcphjADHU6FVsm2/xJ/nqxCkiUt7ciz150FqGxJ+vxg5zo533eHjViwdDBHTMIopyypOY69xNfN1VGPMKxfc/d5z6ayKKpi9lXQMIUumoz5Xqjnq4dyschqoUbGNW1LB+0Y3BNHxeXyGlYsTsr9nYowNzAfMAcGBSsOAwIaBBRgiHbVQmQbvNqXli2R3sBoa6AirAQUeAWzhwSRejw9yMIGB2GgBY76bbM=">
        <trustedCertificates>
            <certificateInfo thumbprint="64123DFA95F03AFB818EC61C874241B62E2A4886" subject="ServiceCertificate"/>
        </trustedCertificates>
    </certificateSection>

I have created a small windows application for generating certificates and getting it's serialized value and thumbprint:
Now we will create a custom service behavior extension to take care of the service credentials:
using System;
using System.ServiceModel.Configuration;

namespace Certificate.Extensions
{
    public class CertificateExtensionBehavior : BehaviorExtensionElement
    {
        public override Type BehaviorType
        {
            get { return typeof(CertificateServiceCredentials); }
        }

        protected override object CreateBehavior()
        {
            return new CertificateServiceCredentials();
        }
    }
}
Here is the CertificateServiceCredentials class which inherits from ServiceCredentials:

using System.Configuration;
using System.Configuration;
using System.Linq;
using System.ServiceModel.Description;
using Certificate.Configuration;

namespace Certificate.Extensions
{
    public class CertificateServiceCredentials : ServiceCredentials
    {
        public CertificateServiceCredentials()
        {
            //get the information from our custom configuration section
            CertificatesSection certificateSection = (CertificatesSection)ConfigurationManager.GetSection("certificateSection");
            var trustedList = certificateSection.TrustedCertificates.Cast<TrustedCertificateInfo>().Select(x => x.Thumbprint);

            this.ServiceCertificate.Certificate = certificateSection.Certificate;
            //we use custom validation mode to check the response
            this.ClientCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.Custom;
            //and custom validator to validate if the response's certificate thumbprint is in the trusted thumbprints
            this.ClientCertificate.Authentication.CustomCertificateValidator =
                new CertificateValidator(trustedList);
        }

        protected override ServiceCredentials CloneCore()
        {
            return new CertificateServiceCredentials();
        }
    }
}

We use a custom certificate validation mode with Certificate validator who checks if the certificate in the response is in the current certificate trusted list. We get the certificate and the trusted list from our custom configuration section. And here's the CertificateValidator:
using System;
using System;
using System.Collections.Generic;
using System.IdentityModel.Selectors;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Security;

namespace Certificate
{
    public class CertificateValidator : X509CertificateValidator
    {
        private readonly IEnumerable<string> trustedThumbprints;

        public CertificateValidator(IEnumerable<string> thumbprints)
        {
            this.trustedThumbprints = thumbprints;
        }

        public override void Validate(X509Certificate2 certificate)
        {
            //check if there is a certificate in the request
            if (certificate == null)
            {
                throw new SecurityException("Missing certificate");
            }
            //check if the certificate thumbprint is in the list of the trusted ones
            if (!trustedThumbprints.Any(thumbprint => thumbprint.Equals(certificate.Thumbprint)))
            {
                throw new SecurityException("The provided certificate is not trusted!");
            }
        }
    }
}

So after that we need to set the service to use this custom extension, so the web.config of the service should look like this:
<?xml version="1.0"?>
<configuration>
  <configSections>
    <section name="certificateSection" type="Certificate.Configuration.CertificatesSection, Certificate"/>
  </configSections>
  <certificateSection certificate="MIIExgIBAzCCBIYGCSqGSIb3DQEHAaCCBHcEggRzMIIEbzCCApgGCSqGSIb3DQEHAaCCAokEggKFMIICgTCCAn0GCyqGSIb3DQEMCgECoIIBjjCCAYowHAYKKoZIhvcNAQwBAzAOBAiqwSbxN4Q2IQICB9AEggFoaa40+yIrF2Wb3/L4rYE7UpzrhI5S2O8wx72gj41tudES+QiM8DGxC1YWaHx4+THXFkQs62A6eDTKYOZUc8oMUFyVbY70Joq8un6keunCz4xP26MB2vygpx1/ASA6CTdeN3r9JEYss7DGaFnvUJKPH44oyBagaecT3fo0CA+Qa7vfcrlrhcyyovVs5lfJNUm13IF8/bNMCcOdgUnjX/tlay53YDulZSD0kP3apd60zzBAtIr2GD/h3NjiIcjSauDUf7bdvEV0LHAC78mRB/6nUaYiwZhAphky8ufR3dMzZGt5bglbEb8WkEw4bh/qrUxofA5uDmRgjnusAVtOcm0BUvK458bzsyKaRwuw8wSK+Srii5ZYjE5DSTc3msu5jCKZ5pC03w8tdeXmc5Xqq5TziKpDXW1bCa9D/O8mRnz+IsRa1FirDV/Spp37wyucLJkluKHZTpOeTWXRGy1/8Ys5kDxeXAamJxSLMYHbMBMGCSqGSIb3DQEJFTEGBAQBAAAAMFcGCSqGSIb3DQEJFDFKHkgAZAAzADAAMwBkADQAZgA2AC0AYQBmADAANQAtADQANwBjAGUALQBiAGIAZgBjAC0AMwBhAGMANQBlADgAYQBiAGUAOAA3ADcwawYJKwYBBAGCNxEBMV4eXABNAGkAYwByAG8AcwBvAGYAdAAgAEUAbgBoAGEAbgBjAGUAZAAgAEMAcgB5AHAAdABvAGcAcgBhAHAAaABpAGMAIABQAHIAbwB2AGkAZABlAHIAIAB2ADEALgAwMIIBzwYJKoZIhvcNAQcGoIIBwDCCAbwCAQAwggG1BgkqhkiG9w0BBwEwHAYKKoZIhvcNAQwBBjAOBAgatfFYOA+7qAICB9CAggGIOL+SmdG5n6oummdHrr7u0LH7+VwF3rICFqQTncXX9iVTND6DXJArJfFsYGs1fwq4mzTxmrpBArsf0pCht37x5m7m9k/JL/LeXWlh5re+tZptnEl/l/45AUvN3/fMzoaG4rD5keA1POOoir9fVTiiJjvPfIYvriI8siMwx13fyuFYNZlF+T1pkR6WQbRKTYS49nSGxhIgsoUkxXkGm64CRgXRriHqhopDqUmzCgHhE68jjt78Ff9iYl/1KYBvpJfgBTnvV0dNcXcHhmOkOLqHA6ONBFeARH6ous1i2AUoXfTVoFptTb0eSQTrZkravx2uJrSSuMtPP2qOkGkVQNE2TsJdyFVEKwhXuVyhpuDFky56Q73RDzQCfFEhZHfmleUCaZSVJlUXY86b6/Qk4ebzmGyje7+7z29PARHJBKWHJi/759fKmpTMO27gYor+ylFhqz21crjX7uae0jLKg59CjdSgJocpZ5jOK+B4sWqFuEYUMpcUcN3pZ2jkFMqQcWzOinegbwKeMzgwNzAfMAcGBSsOAwIaBBS9S/16xb6qbDTK5fY6EyjfSc/nvgQU1/tVtjNCPOGmYwOUDNupoL7hlpI=">
    <trustedCertificates>
      <certificateInfo thumbprint="625C675C8C7FF2A4041573116211367DABA71969" subject="CallerCertificate"/>
    </trustedCertificates>
  </certificateSection>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
          <certificateExtension />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
    <services>
      <service name="Service.Service">
        <endpoint name="myService"
                  address=""
                  binding="wsDualHttpBinding"
                  contract="Service.IService"
                  bindingConfiguration="certificateBinding"/>
      </service>
    </services>
    <bindings>
      <wsDualHttpBinding>
        <binding name="certificateBinding">
          <security mode="Message">
            <message clientCredentialType="Certificate" />
          </security>
        </binding>
      </wsDualHttpBinding>
    </bindings>
    <extensions>
      <behaviorExtensions>
        <add name="certificateExtension" type="Certificate.Extensions.CertificateExtensionBehavior, Certificate"/>
      </behaviorExtensions>
    </extensions>
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
</configuration>

And the app.config of the caller should look like this:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <configSections>
        <section name="certificateSection" type="Certificate.Configuration.CertificatesSection, Certificate"/>
    </configSections>
    <certificateSection certificate="MIIExgIBAzCCBIYGCSqGSIb3DQEHAaCCBHcEggRzMIIEbzCCApgGCSqGSIb3DQEHAaCCAokEggKFMIICgTCCAn0GCyqGSIb3DQEMCgECoIIBjjCCAYowHAYKKoZIhvcNAQwBAzAOBAgbm3IPSqU0BQICB9AEggFojvCBmeSJ6n4IlKxgSv1XgIB5LaD7tb06f/yTLsZRK+4rnqCaesmYFFHP889JTySdqPPyE6fNrpFXTcvcRC6lQQglLnxbRZQotPHvDv4MEzEdI67zkkfM7RsxxXRUQE+ex5H+oQxjScvVRWlKa0KXLk7DOa+Ijz/epLFCum2CE2aUE/AOdi8GCYf7D0yMa472/buQRX1qWX5MYuH+sZI1py/unS8R5R4cytRr8dKJHmn3YtLuhEwQOuXiQ/mUK5PKj+xYp6b8ssVIXQjuLpXZnnT7i/KdZipxmTCf+OtXbAysBw2VaQ9+NmR8cufy8nUb/KgSNfcE3hTHTxIaBnhddhuHxvfR5oYIAzPK3NTq/S1qCEqxDJnBFapdnRcKfHEAlDwIB/KZyHgKdVBiu16pB9e+bxl840CW6vI/tILBbpww3rjvzKKQYZZ6uPu1oNLS2TeX7JsBJE3p0HJE2DPFLfmXLPVPSkHBMYHbMBMGCSqGSIb3DQEJFTEGBAQBAAAAMFcGCSqGSIb3DQEJFDFKHkgAZgAzADEAMwBlADQAYQA4AC0AMAA2ADMANwAtADQANAA1ADAALQBiAGMANAA5AC0AMwA2AGEAMABkAGIAOQAxADkAOABhAGQwawYJKwYBBAGCNxEBMV4eXABNAGkAYwByAG8AcwBvAGYAdAAgAEUAbgBoAGEAbgBjAGUAZAAgAEMAcgB5AHAAdABvAGcAcgBhAHAAaABpAGMAIABQAHIAbwB2AGkAZABlAHIAIAB2ADEALgAwMIIBzwYJKoZIhvcNAQcGoIIBwDCCAbwCAQAwggG1BgkqhkiG9w0BBwEwHAYKKoZIhvcNAQwBBjAOBAjWmEM3BmtPWwICB9CAggGIIxS2KaegZ8TDfdq1AP55giyOzgLOvd1LYA5M1QwRmYcM4IiJe5Z6yB6usrnMa/oAJ6suBw72UTO8lTGc/AXWtbrJg6KM0CuyI7lKdoShn36FRx35djx5plXpDxVrZtR2MbOxgSdUNyUCiuRWe/FUzpwE93IWQnfIleeziH1YXuZdvxy/vTLKT2VngeZh3BjyG25n7Fj44xgy7CQM/g/q+TgHBJjnY9qD36kPdaWxkxytadpJH3GgnKLjoQCvHhFN6NEVhErnvzZo63jPZIDWHxr7EYGkbVTzwtPwlocTDgm75gS/IwCMNdAxHP9ofMM4H+2g/UV88R4ABgUoP139Drz5LrfHFsnvPx3/twygMX6lUccnwyKZTVcphjADHU6FVsm2/xJ/nqxCkiUt7ciz150FqGxJ+vxg5zo533eHjViwdDBHTMIopyypOY69xNfN1VGPMKxfc/d5z6ayKKpi9lXQMIUumoz5Xqjnq4dyschqoUbGNW1LB+0Y3BNHxeXyGlYsTsr9nYowNzAfMAcGBSsOAwIaBBRgiHbVQmQbvNqXli2R3sBoa6AirAQUeAWzhwSRejw9yMIGB2GgBY76bbM=">
        <trustedCertificates>
            <certificateInfo thumbprint="64123DFA95F03AFB818EC61C874241B62E2A4886" subject="ServiceCertificate"/>
        </trustedCertificates>
    </certificateSection>
    <system.serviceModel>
        <bindings>
            <wsDualHttpBinding>
                <binding name="certificatesBinfing">
                    <security mode="Message">
                        <message clientCredentialType="Certificate"/>
                    </security>
                </binding>
            </wsDualHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://localhost:9986/Service.svc" binding="wsDualHttpBinding"
                bindingConfiguration="certificatesBinfing" contract="IService"
                name="BasicHttpBinding_IService">
            </endpoint>
        </client>
    </system.serviceModel>
</configuration>

I have added a small WCF Extensions helper class from here.

using System;
using System.ServiceModel;

namespace Caller.Proxy
{
    public static class WcfExtensions
    {
        public static void Using<T>(this T client, Action<T> work)
            where T : ICommunicationObject
        {
            try
            {
                work(client);
                client.Close();
            }
            catch (CommunicationException)
            {
                client.Abort();
            }
            catch (TimeoutException)
            {
                client.Abort();
            }
            catch (Exception)
            {
                client.Abort();
                throw;
            }
        }
    }
}

Now the only thing we need to do is to call the service from the caller:
using System;
using System.Configuration;
using System.Linq;
using System.ServiceModel;
using Caller.Proxy;
using Certificate;
using Certificate.Configuration;

namespace Caller
{
    class Program
    {
        static void Main(string[] args)
        {
            new ServiceClient().Using(channel =>
            {
                //get the information from our custom configuration section
                CertificatesSection certificateSection = (CertificatesSection)ConfigurationManager.GetSection("certificateSection");
                var trustedList = certificateSection.TrustedCertificates.Cast().ToList();

                var endpointAddress = channel.Endpoint.Address.Uri;

                //get the first trusted certification. We assume that you will call only one service, so we will have only one item in the TrustedCertificates
                //this can be improved to select which service do you want to call an what is the response thumbprint that we expect
                string trustedSubject = trustedList.FirstOrDefault().Subject;

                //we create a dns identity from the trusted object to be able to authenticate with the service
                //
                //    
                //
                var identity = EndpointIdentity.CreateDnsIdentity(trustedSubject);

                channel.Endpoint.Address = new EndpointAddress(endpointAddress, identity);

                channel.ClientCredentials.ClientCertificate.Certificate = certificateSection.Certificate;
                //set custom validation mode
                channel.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.Custom;
                //trust results only from the certificate in the trusted list
                channel.ClientCredentials.ServiceCertificate.Authentication.CustomCertificateValidator = new CertificateValidator(trustedList.Select(x => x.Thumbprint));

                var data = channel.GetData(1);
                Console.WriteLine(data);
            });
        }
    }
}
And that's it. We can create new certificate with the generator, set the serialized value in the configuration file of one of the sides and add the certificate subject and thumbprint in the other side's trusted certificates and vice versa.

If you host the service and the site on IIS you need to set IIS Application Pool configuration (Application Pools > Advanced Settings) to load the user profile for the application pool identity user.
Otherwise the user may not be able to load the certificate.

You can find the example project here WCF_Certificates.zip