Razor – Hiding a Section in a Layout

Layouts in Razor allow you to define placeholders named sections where content pages may insert custom content much like the ContentPlaceHolder available in ASPX master pages.

When you define a section in a Razor layout it’s possible to specify if the section must be defined in every content page using the layout or if its definition is optional allowing a page not to provide any content for that section. For the latter case, it’s also possible using the IsSectionDefined method to render default content when a page does not define the section.

However if you ever require to hide a given section from all pages based on some runtime condition you might be tempted to conditionally define it in the layout much like in the following code snippet.

if(condition) {
	@RenderSection("ConditionalSection", false)
}

With this code you’ll hit an error as soon as any content page provides content for the section which makes sense since if a page inherits a layout then it should only define sections that are also defined in it.

To workaround this scenario you have a couple of options. Make the given section optional with and move the condition that enables or disables it to every content page. This leads to code duplication and future pages may forget to only define the section based on that same condition.

The other option is to conditionally define the section in the layout page using the following hack:

@{
    if(condition) {
        @RenderSection("ConditionalSection", false)
    } 
    else {
        RenderSection("ConditionalSection", false).WriteTo(TextWriter.Null);
    }
}

Hack inspired by a recent stackoverflow question.

Introducing NFakeMail

Ever had to resort to custom code to control emails sent by an application during integration and/or system testing? If you answered yes then you should definitely continue reading.

NFakeMail makes it easier for developers to do integration/system testing on software that sends emails by providing a fake SMTP server. You’ll no longer have to manually validate the email sending process. It’s developed in C# and IronPython and targets the .NET 4.0 framework.

With NFakeMail you can easily automate the testing of components that rely on sending mails while doing its job. Let’s take a look at some sample code, we start with a simple class containing a method that sends emails.

class Notifier
{
    public void Notify()
    {
        using (var smtpClient = new SmtpClient("localhost", 10025))
        {
            smtpClient.Send("me@me.com", "you@you.com", "S1", ".");

            smtpClient.Send("me@me.com", "you@you.com", "S2", "..");
        }
    }
}

Then to automate the tests for this method we only need to the following:

[Test]
public void Notify_T001()
{
    using (var server = new FakeSmtpServer(10025))
    {
        new Notifier().Notify();

        // Verifies two messages are received in the next five seconds
        var messages = server.WaitForMessages(count: 2, timeout: 5000);

        // Verifies the message sender
        Debug.Assert(messages.All(m => m.From.Address == "me@me.com"));
    }
}

The created FakeSmtpServer instance will act as a simple SMTP server and intercept the messages sent by the Notifier class. It’s even possible to verify some fields of each intercepted message and by default all intercepted messages are saved to the file system in MIME format.

One Exception to Aggregate Them All

.NET 4.0 introduced a new type of exception, the AggregateException which as the name implies allows to aggregate several exceptions inside a single throw-able exception instance.

It is extensively used in the Task Parallel Library (TPL) and besides representing a simple collection of exceptions can also be used to represent a set of exceptions in a tree-like structure.

Besides its InnerExceptions property which is a read-only collection of exceptions, the most relevant members of this new type are the methods Flatten and Handle. The former allows to flatten a tree hierarchy removing the need to recur while working with an aggregate exception. For example, if we would flatten the exception tree illustrated in the previous figure the result would be:

The other method, Handle, accepts a predicate that is invoked for each aggregated exception and returns a boolean indicating if each exception is handled or not. If at least one exception goes unhandled then Handle throws a new AggregateException containing only the unhandled exceptions. The following code snippet illustrates this behavior and also another scenario where an aggregate exception proves useful – single threaded batch processing.

static void Main()
{
    try
    {
        ConvertAllToInt32("10", "x1x", "0", "II");
    }
    catch (AggregateException errors)
    {
        // Contained exceptions are all FormatException
        // so Handle does not thrown any exception
        errors.Handle(e => e is FormatException);
    }

    try
    {
        ConvertAllToInt32("1", "1x", null, "-2", "#4");
    }
    catch (AggregateException errors)
    {
        // Handle throws a new AggregateException containing
        // the exceptions for which the predicate failed.
        // In this case it will contain a single ArgumentNullException
        errors.Handle(e => e is FormatException);
    }
}

private static int[] ConvertAllToInt32(params string[] values)
{
    var errors = new List<Exception>();

    var integers = new List<int>();

    foreach (var item in values)
    {
        try
        {
            integers.Add(Int32.Parse(item));
        }
        catch (Exception e) { errors.Add(e); }
    }

    if (errors.Count > 0)
        throw new AggregateException(errors);

    return integers.ToArray();
}

.NET Weak Event Handlers – Part II

On the first part of this article I showed two possible ways to create weak event handlers. One using reflection and the other using a delegate.

For this performance analysis we will further differentiate between creating a delegate by providing the type of the listener at compile time (Explicit Delegate) vs creating the delegate with the type of the listener being only obtained at runtime (Implicit Delegate).

As expected, the performance between reflection/delegate differ significantly. With the reflection based approach, creating a weak event handler is just storing a MethodInfo reference while with the delegate based approach there is the need to create the delegate which will be invoked later.

So, at creating the weak event handler reflection clearly wins, but what about when the handler is invoked.

No surprises there, performing a call through reflection every time a handler is invoked is costly. In conclusion, if you want good performance when creating handlers that only sporadically get triggered use reflection, otherwise use the delegate based approach.

The explicit delegate approach always wins against the implicit delegate, but I find the syntax for the latter much more intuitive.

// Implicit delegate - The listener type is inferred at runtime from the handler parameter
public static EventHandler WrapInDelegateCall(EventHandler handler);
public static EventHandler<TArgs> WrapInDelegateCall<TArgs>(EventHandler<TArgs> handler) where TArgs : EventArgs;

// Explicite delegate - TListener is the type that defines the handler
public static EventHandler WrapInDelegateCall<TListener>(EventHandler handler);
public static EventHandler<TArgs> WrapInDelegateCall<TArgs, TListener>(EventHandler<TArgs> handler) where TArgs : EventArgs;

.NET Weak Event Handlers – Part I

In .NET when you subscribe to an event providing an instance method as the event handler the event source stores a reference to the target instance for which the event handler will be triggered.

In a scenario where you have short-lived event listeners and event sources with a long lifetime this will pose a problem because the strong reference in the event source will become the sole reason these objects don’t get garbage collected. Depending on the memory footprint of each event listener this may lead to problems in the application.

WPF introduced the weak event pattern that specifically targets this situation but involves implementing a new WeakEventManager and the IWeakEventListener interface.

However, I’ll present another approach to solve this problem, more specifically a helper class that creates weak event handlers used to subscribe to any .NET event without forcing a strong reference to the event listener.

This helper class will support two flavors of weak event handlers:

  1. Reflection based;
  2. Delegate based.

They will share a common base class since both will store a WeakReference to the event listener instance to allow it to be garbage collected if no other references exist.

internal abstract class WeakEventHandler<T> where T : EventArgs
{
    public WeakEventHandler(Delegate handler)
    {
        this.WeakRef = new WeakReference(handler.Target, false);
        this.Method = handler.Method;
    }

    protected WeakReference WeakRef { get; set; }

    protected MethodInfo Method { get; set; }

    public abstract void Invoke(object sender, EventArgs e);

    public static implicit operator EventHandler(WeakEventHandler<T> weakHandler)
    {
        return weakHandler.Invoke;
    }

    public static implicit operator EventHandler<T>(WeakEventHandler<T> weakHandler)
    {
        return weakHandler.Invoke;
    }
}

They differ on how the method representing the handler is invoked at runtime. The former uses reflection to invoke the handler…

internal sealed class ReflectionBasedWeakEventHandler<T> : WeakEventHandler where T : EventArgs
{
    public ReflectionBasedWeakEventHandler(Delegate handler)
        : base(handler) { }

    public override void Invoke(object sender, EventArgs e)
    {
        object target = this.WeakRef.Target;

        if (target != null)
        {
            this.Method.Invoke(target, new object[] { sender, e });
        }
    }
}

… while the latter creates an open instance delegate that will then be used to invoke the handler.

internal delegate void OpenInstanceEventHandler<TTarget, TArgs>(
    TTarget target,
    object sender,
    TArgs e) where TArgs : EventArgs;

internal sealed class DelegateBasedWeakEventHandler<TArgs, TListener> : WeakEventHandler where TArgs : EventArgs
{
    public DelegateBasedWeakEventHandler(Delegate handler)
        : base(handler)
    {
        var weakHandler = Delegate.CreateDelegate(
            typeof(OpenInstanceEventHandler<TListener, TArgs>),
            null,
            handler.Method,
            true);

        this.Handler = (OpenInstanceEventHandler<TListener, TArgs>)weakHandler;
    }

    private OpenInstanceEventHandler<TListener, TArgs> Handler { get; set; }

    public override void Invoke(object sender, EventArgs e)
    {
        object target = this.WeakRef.Target;

        if (target != null)
        {
            this.Handler((TListener)target, sender, (TArgs)e);
        }
    }
}

These weak event handler are created through a static helper class. The contract defined by this helper class is provided here while the full implementation with documentation is available at GitHub where you can also find the NUnit unit tests used to test it.

// Implementation available @ GitHub

public static class WeakEventHandlerWrapper
{
 public static EventHandler WrapInDelegateCall(EventHandler handler);

 public static EventHandler WrapInDelegateCall<TListener>(EventHandler handler);

 public static EventHandler<TArgs> WrapInDelegateCall<TArgs>(EventHandler<TArgs> handler) where TArgs : EventArgs;

 public static EventHandler<TArgs> WrapInDelegateCall<TArgs, TListener>(EventHandler<TArgs> handler) where TArgs : EventArgs;

 public static EventHandler<TArgs> WrapInReflectionCall<TArgs>(EventHandler<TArgs> handler) where TArgs : EventArgs;

 public static EventHandler WrapInReflectionCall(EventHandler handler);
}

This is already getting long, so stay tuned for the second part of this article where I will be talking about the performance impact of this technique.

Single Instance Windows Forms Application

On a previous post I talked about how to create a splash screen for a windows forms application. Now I will be demonstrating how to make a single instance application.

As in the other post I will be using the WindowsFormsApplicationBase class included with the .NET Framework. In order to use this class your application project must add a reference to Microsoft.VisualBasic library.

Having added the reference, the code needed is very simple:

using System;
using System.Linq;
using System.Windows.Forms;
using Microsoft.VisualBasic.ApplicationServices;

class SingleInstanceApp : WindowsFormsApplicationBase
{
    public SingleInstanceApp()
        : base()
    {
        this.IsSingleInstance = true;
    }

    protected override void OnStartupNextInstance(
        StartupNextInstanceEventArgs e)
    {
        base.OnStartupNextInstance(e);

        string[] secondInstanceArgumens = e.CommandLine.ToArray();

        // Handle command line arguments of second instance

        if (e.BringToForeground)
        {
            this.MainForm.BringToFront();
        }
    }

    protected override void OnCreateMainForm()
    {
        base.OnCreateMainForm();

        this.MainForm = new MainForm();
    }
}

static class Program
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        new SingleInstanceApp().Run(Environment.GetCommandLineArgs());
    }
}

With this sample code you will have a single instance application that, if configured to do so, will bring itself to the foreground when the user tries to launch a second instance. More advanced scenarios such as handling the command line arguments of the second instance on the first instance are also supported.