Introduction
Today, AOP is starting to get attention in the .NET community, and right now, there are a lot of frameworks and compilers for .NET to allow programmers to create .NET applications using AOP.
In this article, I will be talking about the NKalore Compiler. NKalore is a compiler based on MCS (Mono C# Compiler), which allows the use of AOP in your C# code with a very simple and intuitive syntax. So, when developing with NKalore, you will use keywords as ASPECT
, POINTCUT
, AFTER
, BEFORE
, AROUND
, etc.
Getting NKalore
To start using NKalore, I recommend downloading the latest version at SourceForge. The product is still in an Alpha state, but we already can start to play with NKalore and use AOP in C#.
To compile our samples, we will run NKalore in the command-line mode. At the moment, integration with Visual Studio is not available. It is possible to have a basic integration with #Develop, but it’s a subject for another article.
Creating your first AOP application
In this first sample, I will demonstrate the use of the BEFORE
advice, so we can imagine that each time before a specified method is called out, the BEFORE
advice will be called.
For this, we create a class that has a method called Sum
, as you see below:
using System;
namespace Namespace
{
public class MainClass
{
public void Sum(int a, int b)
{
Console.WriteLine("Sum = {0}", a + b);
}
public static void Main()
{
new MainClass().Sum(2,3);
}
}
}
Now, we are going to create an aspect
so every time the "Sum
" method is called, it writes a message into the console. Check it out:
using System;
namespace Namespace
{
public aspect MyAspect
{
pointcut SumPointCut void MainClass.Sum(int a, int b);
before SumPointCut(int a, int b)
{
Console.WriteLine(
"The sum of numbers {0} and {1} will be calculated.", a, b);
}
}
}
At first, the pointcut is created to identify which methods to "capture". We have put the full name (class name and method name), but we can also use the ‘%’ character to specify the pointcut like a mask.
Then, the BEFORE
advice is created. This advice runs every time the Sum
method is called. To compile the application, run NKalore in the command window passing the .cs file as a parameter, for example:
mcs before.cs
Here, mcs in the binary name of NKalore.
When you run the application, you will see the following in the console window:
Logging everything in your code with BEFORE and AFTER advices
The BEFORE
and AFTER
advices bring with them some information about the method that is being "captured", all this information is inside the "thisJoinPoint
" variable. Now, we are going to use these advices to log every code that is executed in our code.
First, we need a class that has a flow built with methods calling a method, just to demonstrate the use of the log:
namespace Namespace
{
public class MainCls
{
public MainCls() { a(2); }
void a(int a) { b("paul", 14); }
void b(string name, double age) { c(true); }
void c(bool someFlag) { return; }
public static void Main()
{
new MainCls();
}
}
}
And now, the aspect that captures all methods, with any name, returning type, or parameter, and logs every thing into the console with information that is in the "thisJointPoint
" variable. See the aspect implemented below:
using System;
using System.Reflection;
namespace Namespace
{
public aspect LoggingAspect
{
pointcut LogPointcut % %(...);
int level = 0;
void log(NKalore.Model.JoinPoint joinPoint,
string prefix, bool showParams)
{
string pad = new string('·', level - 1);
Console.WriteLine(pad + prefix + " - " +
joinPoint.MethodInfo);
if (showParams)
{
ParameterInfo[] pis =
joinPoint.MethodInfo.GetParameters();
for (int i = 0; i < pis.Length; i++)
{
Console.WriteLine(pad + "\t{0} {1} = {2}",
pis[i].ParameterType, pis[i].Name,
joinPoint.ParamsData[i]);
}
}
}
after LogPointcut()
{
log(thisJoinPoint, "after", false);
level--;
}
before LogPointcut()
{
level++;
log(thisJoinPoint, "before", true);
}
}
}
In the aspect, the AFTER
and BEFORE
advices increment or decrement the "level" variable to keep the level of the stack. And call the "log
" method to show in the console, information about thisJointPoint
. The output of the application is the following:
The AROUND advice
Another very interesting advice is the AROUND
advice. This advice is executed during the execution of the method. So, in reality, when you use this advice, when the method "captured" by the pointcut is executed, your aspect code is executed, and to execute the real method implementation, you need to use the proceed
keyword.
To illustrate, we are going to create an aspect with the AROUND
advice that calls the implementation of a method (using the proceed
keyword). The use of "proceed
" is inside a try
/catch
block, to protect the execution from errors. Take a look at our sample implementation:
using System;
using System.Reflection;
namespace AroundSample
{
public aspect AroundAspect
{
pointcut DoMethods void %.Do%(...);
around void DoMethods()
{
try
{
Console.WriteLine("Before: {0}", thisJoinPoint.MethodInfo);
proceed(...);
Console.WriteLine("After: {0}", thisJoinPoint.MethodInfo);
}
catch (Exception ex)
{
Console.WriteLine("Error in {0}: {1} ",
thisJoinPoint.MethodInfo,
ex.InnerException.Message);
}
}
}
public class MainCls
{
public void DoSum(int a, int b)
{
Console.WriteLine(a + " + " + b + " = " + (a + b));
}
public void DoMinus(int a)
{
Console.WriteLine(a + " - 1 = " + ( a - 1 ));
}
public void DoDiv(int a, int b)
{
Console.WriteLine(a + " / " + b + " = " + (a / b));
}
public static void Main()
{
MainCls mainCs = new MainCls();
mainCs.DoSum(7,3);
mainCs.DoMinus(5);
mainCs.DoDiv(5,0);
}
}
}
Every method that starts with "Do" is handled by the AROUND
advice. First, we log into the console the method that is being executed, writing "before..." and "after...", when the call to the original method is done using proceed
keyword. This is made inside a try
/catch
, block, so if any errors occur (a division by zero will occur in our samples), it will write in the console. The output of this program is:
Another possible use of AROUND
, is to cache the results of the function into a hash table, and avoid running the same method twice.
* Note that if you only whish to handle the exception, you can use the THROWING
advice.
Conclusion
NKalore offers a very simple way to implement AOP into C#, and it’s very intuitive. The project is still in the Alpha stage, but for a while, we can make little programs with it. As roadmap of NKalore says, in the future, probably we will have some more AOP features and integration with Visual Studio, which would be very nice.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.