Tuesday, 1 April 2014

TeamCity hidden shortcuts

My colleague says, that he hates JetBrains as a company. He cannot find anything wrong or ineffective in their products. He is surprised that they just work. Work as expected and even better. They foresee our needs and our requirements and have already implemented them.

In this post I would like to share you the keyboard shortcuts I found in TeamCity:

p is a shortcut for searching among project names. Strike "p" and then start typing a project name Available in TeamCity 7.0

j is a shortcut for searching projects and build configurations in the same root project. Strike "j" and then start typing a project name or a build configuration name. Available from TeamCity 8.0

And the most powerful:
q is a shortcut for searching both projects and build configurations. Strike "j" and then start typing a project name or a build configuration name. Available from TeamCity 8.0

P.S. Thanks to JetBrains and Pluralsignt for supporting CleanCodeAlliance group.

UPDATE: I've got a reply from JetBrains employee on twitter that there are even more keyboard shortcuts in TeamCity's Changes page in version 8.1:

up/down to navigate, right/left to expand changes.  And 'f', 'b', 't' to open specific tabs of the selected change

Thanks to Kirill Maximov @maxkir

According to Kirill there is no official documentation about the shortcuts. So I will maintain this post as a sporadic one.

Monday, 17 March 2014

Clean Code Alliance group on Meetup

My friend Itzik Saban and I opened a new group on Meetup: Clean Code Alliance. You may ask, who needs another group and more meetings when there are a lot of them talking about almost every technical aspect of software engineering. Most of the groups are focused on specific technology or domain. The purpose of Clean Code Alliance is to return to the basics - to quality and clean code. We would like to talk about clean code principles, TDD issues, domain driven design concepts, applicative information security principles, anti-patterns in programming and testing, quality code metrics.

Feel free to join the group on meetup: Clean Code Alliance

Thursday, 20 February 2014

How to follow best practices of NHibernate with WCF integration?

If you work with NHibernate, you are probably familiar with its best practices. When working with WCF we need to maintain UnitOfWork and transactions. There is a library that makes this integration seamless: NHJump by James Lanng and Richard Penrose.

Marking your service class with an attribute will do the magic:
  • will create a unit of work per request
  • will open a transaction
  • will commit it at the end of the request or rollback it if an exception was thrown
 [ServiceContract] 
public interface IPersistenceService  {  ...  }  
[UnitOfWork]
public class PersistenceService : IPersistenceService  {  ...  }

Sounds nice? It has also ASP.NET MVC integration.

Samples can be found on SVN repository:

Available on nuget:

PM> Install-Package NhJump.Persistence

Wednesday, 29 January 2014

How to merge multiple .NET assemblies into one

Sometimes we need to deliver our code as a single assembly for different reasons. There are a few techniques for doing that.

The first one and maybe the most obvious is ILMerge. A command line tool that disassembles multiple assemblies into IL code and then reassembles them to a single one.

When to use ILMerge:
 - When all the assemblies are from the same provider. If the assemblies have strong name, they will be re-signed with the snk file of the first of them (or executable if exists).
- ILMerge works well on Microsoft.NET framework only. Supported version is only 2.0 and higher

When we cannot use ILMerge:
- When merging assemblies from different providers. For example, one assembly written by our company which references a few 3rd party assemblies.
- When merging WPF assemblies, because they use embedded resources, that needs to be serialized
- ILMerge won't work on other .NET frameworks, such as Mono or Rotor.
- ILMerge won't merge assemblies from .NET Framework 1.1


Another technique makes use of embedding assemblies as resources within the main assembly. So here are the steps:
1. Add referenced assembly as embedded resource to the main assembly.
2. Don't forget to select "Embedded Resource" in Build Action on File Properties
3. Add a code that loads assembly from the resources (see below)

When to use loading assemblies from resources:
- When we need to load multiple strong named assemblies from different providers.
- Any case that is not supported by ILMerge

Here is a sample code that loads assemblies from resources. It started from Jeffrey Richter's blog post and enhanced to support loading multiple assemblies. When I used the code as is in his post I got an exception saying "Method not found". So here is the modified piece of code. It needs to be initialized in a static constructor of your "main" class, i.e. the first class user would access before accessing other classes.

 

public class AssemblyResolver
{
    private readonly Dictionary<string,Assembly> m_LoadedAssemblies = new Dictionary<string,Assembly>();

    public Assembly CurrentDomainAssemblyResolve(object sender, ResolveEventArgs args)
    {
        var assemblyResource = BuildAssemblyResourceName(args.Name);

        return m_LoadedAssemblies.ContainsKey(assemblyResource)
            ? m_LoadedAssemblies[assemblyResource]
            : LoadAssembly(assemblyResource);
    }

    private static string BuildAssemblyResourceName(string requestedAssemblyFullName)
    {
        var containingAssemblyName = Assembly.GetExecutingAssembly().GetName().Name;
        var indexOfComma = requestedAssemblyFullName.IndexOf(",", StringComparison.Ordinal);
        var requestedAssemblyName = indexOfComma > 0
            ? requestedAssemblyFullName.Substring(0, indexOfComma)
            : requestedAssemblyFullName;
        var assemblyFullName = String.Format("{0}.Resources.{1}.dll", containingAssemblyName, requestedAssemblyName);
        return assemblyFullName;
    }

    private Assembly LoadAssembly(string assemblyName)
    {
        using (var assemblyStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(assemblyName))
        {
            if (assemblyStream == null) return null;

            using (var reader = new BinaryReader(assemblyStream))
            {
                var readBytes = reader.ReadBytes((int) assemblyStream.Length);
                var assembly = Assembly.Load(readBytes);
                m_LoadedAssemblies.Add(assemblyName, assembly);
                return assembly;
            }
        }
    }

    public AssemblyResolver Attach()
    {
        AppDomain.CurrentDomain.AssemblyResolve += CurrentDomainAssemblyResolve;
        return this;
    }

    public void Dettach()
    {
        AppDomain.CurrentDomain.AssemblyResolve -= CurrentDomainAssemblyResolve;
    }
}
Yes, I know there is a lot of code, but let's try to understand it one by one.

AssemblyResolver class holds list of already loaded assemblies. If an AssemblyResolve event occurs, the resolver looks up in the m_LoadedAssemblies and return the already preloaded instance from it. If the requested assembly is not loaded yet, LoadAssembly method will load it from the embedded resources and add it to m_LoadedAssemblies. BuildAssemblyResourceName method concatenates resource name assuming that dependend assemblies reside in Resources folder in the main assembly.

Please note that it ignores the version of the requested assembly and its public key. It assumes that the correct assembly was added to the embedded resources.

Here is the usage from another class:

public class MainClass : IDisposable
{
    static readonly AssemblyResolver Resolver = new AssemblyResolver();

    static MainClass()
    {
        Resolver.Attach();
    }

    public void Dispose()
    {
        Resolver.Dettach();
    }
}
That's all! Hope it helps

Thursday, 26 December 2013

The process was terminated due to an internal error in the .NET Runtime


If your .NET process crashes unexpectedly with the following message in the Event Log: "The process was terminated due to an internal error in the .NET Runtime...", there are a few things we can do to investigate it. Unfortunately, the exception already occurred, the process crashed and there is nothing interesting in the logs. First of all we'd like to find out what happens that causes to this crash and where in the code it happens. In order to do this we can start by downloading and installing Debug Diagnostic tool. Then configuring it in the following matter:

Select Crash, because that's what we're investigating:


Select a specific process, because we know what process crashes:


Select the process you want to investigate:


Select "Full Userdump":

With the DebugDiag running in the background, reproduce the scenario that causes the initial process termination. When the process crashes, we'll find in DebugDiag log folder with a few files. The log folder is
C:\Program Files\DebugDiag\Logs
The interesting file is the one with .DMP extension. Double click it and it will be opened in DeBug Diagnostic Analysis. It will convert the DMP file to HTML report and will open it in IE. Yes, yes, IE, even if your favorite browser is Chrome. Ok, ok, just give me the call stack

We are looking for any errors, crashes in that HTML log. In my case I found "access violation" exception and call stack of the exception. Surprisingly, the call stack is pretty obvious code. It accesses a property which is null, so I would expect a NullReferenceException. But it was access violation. What is more interesting, is that that piece of code is surrounded by try/catch block.

Starting from .NET 4.0, access violation exceptions and similar are not thrown in the regular way. They just terminate the process and are not caught in try block. But there are two still to catch them:
  • 1. Using attribute HandleProcessCorruptedStateExceptions on the suspicious method
  • 2. Using <legacyCorruptedStateExceptionsPolicy enabled="true" />
Below code demonstrates how to apply HandleProcessCorruptedStateExceptions attribute on suspicious method. It enables catching the access violation exception.
 

    internal class Program
    {
        private static void Main(string[] args)
        {
            var crashingThread = new Thread(CrashingThread);
            crashingThread.Start();

            Console.ReadKey();
        }

        [HandleProcessCorruptedStateExceptions]
        private static void CrashingThread()
        {
            try
            {
                CrashMe();
            }
            catch (Exception exception)
            {
                Console.WriteLine("I caught access violation");
                Console.WriteLine(exception.ToString());
            }
        }

        private static unsafe void CrashMe()
        {
            unsafe
            {
                int read = *((int*) long.MaxValue - 8);
            }
        }
    }



A few last notes about that attribute:
It can be applied on any level on the call stack of the suspicious code. Even on the Main method. However it won't work if you apply the attribute on the main method, but the exception occurs in another thread. It should be applied on the method that is on the crashing thread!

Please note, that it is not recommended to leave that attribute in production code. It should be used only for debugging purposes.

Enjoy your debugging!