The sample

Show the sample class to divide two numbers

This class is in a C# project named Math.csproj

public class Computer
{
    public int Divide(int a, int b)
    {
        return a / b;
    }
}

Set up your project

To use NetAspect in your .Net projects

Visual Studio 2010/2012/2013

Just add the NetAspect Nuget package to the Math.csproj

Visual Studio 2005/2008

Download the latest version of NetAspect Here and unzip it in the directory you want. For example : C:\NetAspect.
Now edit the Math.csproj project with an XML Editor and put the following line :

<Import Project="C:\NetAspect\NetAspect.targets" Condition="Exists('C:\NetAspect\NetAspect.targets')" />

This line must be after the following line :

<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />

Define the aspect

Imagine we want to log when an exception occured in our Divide method

To handle the exception, we must create an aspect :

public class LogAttribute : Attribute
{
    public bool NetAspectAttribute = true;
    public static StringWriter writer = new StringWriter();
    public void OnExceptionMethod()
    {
        writer.Write("An exception !");
    }
}

Define the weaving

To indicate to the weaver that our Divide Method must handle our aspect

Now we must weave our Divide method to the aspect. That's why, we add the aspect attribute to the method :

public class Computer
{
    [Log]
    public int Divide(int a, int b)
    {
        return a / b;
    }
}

Build ant test

Just see the results !

Now you can write and run the following test :

[TestFixture]
public class MathAspectTest
{
   [Test]
   public void CheckDivideByZero()
    {
        var computer = new Computer();
        try
        {
            computer.Divide(12, 0);
        }
        catch (Exception)
        {
            Assert.AreEqual("An exception !", LogAttribute.writer.ToString());
        }
    }
}