Last updated on 03.10.2006


Start here

AspectDNG is a .NET multi-language aspect weaver.

Aspects and base code may be written in any programming language (C#, VB.NET, J#...), as soon as it compiles into CIL.

The last version of AspectDNG (1.0.3) can be downloaded in two forms:


Aspect Oriented Programming (AOP)

What is an Aspect?

An Aspect is a piece of code that is developped separately and that can be "applied" or "weaved" on an existing code (the target code). Weaving an Aspect enables to intercept method invocations (including constructors) and field access to introduce a behavioral added-value. Weaving also can introduce language elements (types, methods, fields, properties) on to existing types to enhance them and to help them supporting cross-cutting features (be they technical or functional)

What kind of things can I automate using AOP?

The first Aspects we have weaved are technical ones:

Functional Aspects are not (yet) very popular since we lack a modeling technique to discover them early in the requirement / analysis phases. But people like Ivar Jacobson give a try in this direction; this is very interesting an promising... let's stay open to these new ideas!

Are there books I can read about AOP?

Yes. Very good ones. In English first:

And for those who read French:


What is AspectDNG?

AspectDNG is a static .net aspect weaver. This means it works on assemblies (either .dll or .exe) that may have been generated from any .net programming language. The result of the weaving is a new assembly in which Aspects have been integrated to the target code.

How to run AspectDNG?

If Aspects are located in the same assembly as the target code (but typically in a separate Namespace), then it is easy: aspectdng.exe yourAssembly.exe (or .dll)

If Aspects are compiled in a separate assembly: aspectdng.exe yourTargetAssembly.exe (or .dll) yourAspectAssembly.dll

The preceding ways are very straightforward but won't give you a full control over Aspectdng. The most accurate way to specify the weaving is to write a configuration file and to run: aspectdng.exe yourConfigFile.xml

How to test XPath queries on a target assembly?

Internally, AspectDNG uses XPath to identify the aspects to weave and the target joinpoints. If you want to test an XPath query on a pre-compiled assembly, just query it like that: aspectdng.exe -query yourAssembly.exe (or .dll) //Type[match(., '*MyType*')]

The XPath queries will in fact be re-factored by AspectDNG. The real query will be displayed on the command line.

The standard XPath functions are available, and you can also use the match() function that uses Regular Expressions to check a string content.

There is no serious doc but a short quickstart. How to learn AspectDNG features?

Every feature of AspectDNG is unit tested. The best way to learn how to weave with this tool is to download the src distribution and to read the source code you'll find in the unittests folder.

Licensing modes

How is AspectDNG licensed?

AspectDNG is a Public Domain Software. This means you can use it, read its source code, adapt it, copy as many times you want and even make business based on it (as a service provider or software vendor). There is absolutely no limit to what you can do with AspectDNG's source and binary code. Of course, everything is for free (as in free beer).

Support, customization and prototypes

Where can I ask questions?

The best place is still AspectDNG's forum , hosted at Even if this forum is mainly in French, feel free to post in English and we'll stick to this language for the whole thread.

We also typically use this forum to inform users of a new release of AspectDNG, hence it is the best place to poll to keep up to date with recent developments.

What is the status of AspectDNG's development?

AspectDNG v1.0.0 has been delivered on the 17 september 2006 by Thomas GIL. It is also the date when Thomas decided to change licenses (AspectDNG used to be a Free Software under the GPL license) and to leave the project. Changing licenses to Public Domain can be interpreted as follows :

How can I get involved in AspectDNG's development?

Send an email to Thomas ( He has full access to and will be pleased to give you "the keys of his house".




AspectDNG is a .NET static aspect weaver

Copyright (c) 2004 DotNetGuru SARL

Author: Thomas Gil (

All rights reserved.

This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License (whose text follows) for more details.


Version 2, June 1991

Copyright (C) 1989, 1991 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.


The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too.

When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.

To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.

For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.

We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.

Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.

Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.

The precise terms and conditions for copying, distribution and modification follow.


0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".

Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.

1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.

You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.

2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:

a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.

b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.

c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)

These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.

Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.

In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.

3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:

a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,

b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,

c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)

The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.

If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.

4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.

5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.

6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.

7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.

If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.

It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.

This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.

8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.

9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.

Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.

10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.






Cecil is a .NET Common Intermediary Language (CIL) read/write library, part of the Mono project

Copyright (c) 2004 Jean-Baptiste EVAIN

Author: Jean-Baptiste EVAIN (

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.



Download and install AspectDNG

AspectDNG comes in two different distributions: src and bin .

As an end user, first download the bin one, which only contains aspectdng.exe and a pre-configurated VisualStudio.NET solution that you can just open, build and run (this solution integrates AspectDNG by running the weaver at the end of the compilation process, just before launching the executable).

The src distribution contains the source code of AspectDNG and Cecil. It also contains unit tests we use to check the behavior of our weaver. Reading them will give you a precise idea of what is possible to do with AspectDNG and how to do it.

Sample application (in one unique assembly)

Target code

First, create a simple project (console or windows application, library...), composed of one unique class. Let's consider the example of the Sample class:

using System;

public class Sample{
        public int i;

        public static void Main(){
                Sample s = new Sample("Very simple sample");
        public Sample(string s){
                Console.WriteLine("Sample constructor: " + s);  
        public void Test(){
                Console.WriteLine("Test method");       

Then add another class (that will become an aspect). This class is completely normal, except that its method must a special signature, like in AspectSample :

using DotNetGuru.AspectDNG.MetaAspects;
using DotNetGuru.AspectDNG.Joinpoints;
using System;

public class AspectsSample{
        [AroundCall("* Sample::Test(*)")]
        public static object YourMethodCallInterceptor(JoinPoint jp) {
                Console.WriteLine("Code before calls to '.. Sample.Test(..)'");
                object result = jp.Proceed();
                Console.WriteLine("Code after calls to '.. Sample.Test(..)'");
                return result;

        [AroundBody("* Sample::Test(*)")]
        public static object YourMethodBodyInterceptor(JoinPoint jp) {
                Console.WriteLine("Code before body of '.. Sample.Test(..)'");
                object result = jp.Proceed();
                Console.WriteLine("Code after body of '.. Sample.Test(..)'");
                return result;

        public static object YourConstructorCallInterceptor(JoinPoint jp) {
                Console.WriteLine("Code before calls to 'new Sample(..)'");
                object result = jp.Proceed();
                Console.WriteLine("Code after calls to 'new Sample(..)'");
                return result;

Compiling and weaving

Once you have added the target and and aspect classes to your project, just compile as usual (using an IDE, a Nant or MSBuild script...). Since your Aspect classes use the JoinPoint class, you'll have to reference aspectdng.exe . The result will be a .exe or .dll assembly. Suppose it is named mySample.exe .

Then you weave (that's to say you apply aspects to target code) using the simple command:
aspectdng.exe mySample.exe
This will generate a new assembly named mySample-weaved.exe that integrates your aspects code. Then you can run it as usual.

To sum up, in our example we can run:

csc /out:mySample.exe /r:aspectdng.exe Sample.cs Aspects.cs
aspectdng.exe mySample.exe

The output will be:

A project using multiple assemblies

You may want to separate the target code and the aspects code into different assemblies. In this case:


Table of contents

[Feedback appreciated] If you feel the need of some piece of information that doesn't appear in this documentation, please inform us through AspectDNG's forum. We'll do our best to enhance this document accordingly to your needs.



Aspect Oriented Programming is an instrumentation technique that enables to weave advice at specific joinpoints, i.e. to insert some additional code at specific locations in an existing code. For example, it is possible to place some additional code before, after or around method or constructor calls to trigger some repetitive behavior at that locations.

Technical and repetitive things are generally good candidates (but not the only ones):

AOP also has another interesting feature: structural weavings (sometimes called inter-declarations). This enables you to check or modify the structure of an existing application to add features that weren't present or to verify some structural patterns (of code, of design...). Here is what is typically possible:

To sum up and for being precise, let's give some definitions:

Target code
The core code you write to build your application. We call it "target" because it represents the bulk the aspects will operate on
A piece of code you write separately, and that will be inserted into the target code
Some location in your target code. Example: the beginning of the Main method
A set of JoinPoint where you want to weave your advice to
Software component that contains the Advice you want to weave, and the PointCuts where you want to weave those Advice
The operation that consists in inserting the Advice code into the right locations (identified by PointCuts) inside the Target code
Aspect Weaver
The tool you run to implement the weaving. Examples: AspectJ in Java, AspectDNG in .NET


AspectDNG is a free (GPL) aspect weaver for .NET applications. It can work with the .NET framework version 1.0, 1.1 and 2.0, be it an implementation by Microsoft or Mono.

Here is what a typical project build process looks like when you use AspectDNG:

  1. Build your "target" application. You can use C#, VB.NET or any other languages that can be compiled into a .NET assembly (a .exe or a .dll).
  2. Create a separate "aspect" assembly that will contain your Aspects (advice and pointcuts)
  3. Launch AspectDNG on the target application, giving it the aspect assembly as a parameter. During this process, AspectDNG will run across the aspect assembly, understand what must be weaved and where, and then update the target application accordingly to what it has understood from your aspects.

To be more precise, there are two ways of specifying your pointcuts: in .NET custom attributes (located in your aspect assembly) or in a separated XML configuration file. In fact you can even mix both without problem.

In some projects, you'll want to simplify the build process and keep all your code inside one unique assembly. This doesn't bother AspectDNG: you can locate both your target and your aspect code inside the same assembly, and still use either custom attributes or an external XML configuration to specify what and where to weave.

To sum up, here are some typical project organizations when using AspectDNG:

First steps with AspectDNG

Before reading what follows, if you want to setup a simple project and have a look at how target code and aspects are organized, we recommand you read this first . It tells you in brief how to implement an aspect using Custom Attributes, how to weave it and run the result of your weaving.


You already know that configuration can be done using either .NET custom attributes or XML files. Now let's have a look at what can be specified:


Advice signature:  
// If you are sure the target is a method
public static object Interceptor(MethodJoinPoint jp) 
// If you are sure the target is a constructor
public static object Interceptor(ConstructorJoinPoint jp)  
// If you are not sure
public static object Interceptor(OperationJoinPoint jp) 

Your advice will replace the target operations (methods or constructors). The original operations will be renamed but stay in the same scope (class or struct). If you call joinpoint.Proceed() from within your advice, this will automatically invoke the original operation.

Your advice must return a value whose type is compatible with the target operation return type. Very often, advice will want to return the value that was returned by a call to joinpoint.Proceed(). This value is always legal. But of course, if you target constructors or methods that return void, AspectDNG will discard your advice return type.

Note that using AroundBody is very profitable since the weaving only happens once (at the target operation's place) and automatically impacts all the calls to the original operation. Be they made inside or outside the target assembly (which is particularly important if you weave on a code library)


Advice signature:  
// If you are sure the target is a method
public static object Interceptor(MethodJoinPoint jp) 
// If you are sure the target is a constructor
public static object Interceptor(ConstructorJoinPoint jp)  
// If you are not sure
public static object Interceptor(OperationJoinPoint jp) 

Your advice will replace the target operation call (your call may target either a method or a constructor). The original method is not touched at all (by the way it could be a method defined in an external assembly, even a System one), only the call is modified.

This is more precise than weaving AroundBody because you can choose to weave AroundCall to a methode that takes place inside some specific scope (method or constructor). However, this flexibility has a price: the weaving will be done for each method call you target! Hence, if you have the choice (if you want every call to be modified and if the target method is inside the target assembly), prefer using AroundBody .

As in AroundBody, your advice must return a value whose type is compatible with the return type of the target method. Again, the result type of joinpoint.Proceed() is guaranteed to be type compliant.


Advice signature:  
public static object Interceptor(FieldJoinPoint jp) 

This feature works like AroundCall except that it targets fields direct read access (fields are sometimes called "attributes" but it is confusing in .NET).

Calling joinpoint.Proceed() will return the field value, which you are free to return again yourself, or to modify before returning. If fact you are not obliged at all to call joinpoint.Proceed(): the only requirement as usual now is to return something which type conforms to the target field type.


Advice signature:  
public static object Interceptor(FieldJoinPoint jp) 

This feature works like AroundCall except that it targets fields direct write access (fields are sometimes called "attributes" but it is confusing in .NET).

Calling joinpoint.Proceed() will assign a value to the field, but you are free to modify that value before calling joinpoint.Proceed() so that the assigned value is not the same as what the original code told the compiler. Modifying the value is done by assigning joinpoint.Value (again, with a type compatible value).


Insert is different from the previous features. It doesn't aim at modifying the behavior of your target code, but to change its structure.

Here is typically what we mean by Insert :

  • Insert a field into target types
  • Insert a method into target types
  • [Remark] Inserting the "get_XX" and "set_XX" methods really means inserting the XX property into some target type
  • Insert a type (class, interface, delegate, enum, struct...) into the target assembly
  • Insert a type as an inner type into target types

After weaving, nobody will be able to make a difference between elements (types, operations, fields...) that were in your target assembly before weaving and weaved elements. What you insert will be available for use as any other element of the target assembly.


This is not really a weaving feature in the sense that it doesn't modify either the structure nor the behavior of your target assembly. We could call such a feature a "read only weaving".

The aim of Warning is to emit a warning trace during weave time when something you don't want appears in the target assembly. For example, you can emit Warnings :

  • if any type, method or public field starts with a lower case (this mimics the behavior of static analysis tools such as FxCop)
  • if any string or other "magic value" is used in the middle of your code
  • if some metric is reached (more than 30 methods per type), more than 50 types per namespace
  • if an "illegal" dependency appears (a call to a technical library from within your business objects)


Error works exactly as Warning does, except that it breaks the weaving process if any illegal thing is detected. AspectDNG will stop, the weaving won't occur.


As the name indicates, this features enables you to modify the inheritance relationship between a target type and its parent. For example, you can have target classes inherit from a new class you'll Insert so that they benefit from methods, properties or fields you have implemented in the inserted class.

Modifying the base type is generally safe when target classes are children of System.Object. But if it's not the case, be sure to make the target classes inherit from a class that is type-compatible with the original parent class of your targets.


Lighter than modifying the inheritance hierarchy, you can force a target type implementing an interface of your choice. Target types can be either structs or classes.

The difficulty of this feature is that implementing an interface is generally just the first part of the process (except if you use "Marker" interfaces). The second one will be to Insert a default implementation of all the methods and properties that are required by the interface but not already implemented by the target types.

Hence it is possible that you end up with types that cannot be loaded in memory after weaving because they don't implement everything that is required by the interface. If you face such a situation, try to review your interfaces and to understand what lacks to your target types to implement them.


Advice signature:  
public static string Generator(TypeDefinition t) 

Last but not least, this feature is a first step of AspectDNG towards an new technique called GAOP (Generic AOP). The main difference between AOP and GAOP is that in AOP, everything you weave is decided before weave time: once you have compiled your advice, they will be automatically but statically applied to the target assembly. Whereas in GAOP, your advice can decide what to weave during weave time and make that decision depending on what they are weaved on .

In the advice signature, you noticed that the parameter is not a JoinPoint any more. It is a TypeDefinition, ie a Cecil type that completely describes the content of a target type (fields, events, properties, operations, down to local variables and instructions). This is what you need to discover the weaving context (where your advice is weaved, what the target type contains)

Then, depending on what you find in the TypeDefinition, you have 2 ways of interacting with that target type:

The Cecil Way
TypeDefinitions are read-write objects, hence you can use their API to add new fields, properties, methods, etc... to the target type. This is very easy to do till you need to dynamically create operation bodies (you need to know how to program in CIL to create method bodies, which is not very natural for the majority of us)
The Code Generation Way
You can also use the TypeDefinition as a read-only object, and dynamically generate a string that will contain C# code. That code will typically be made of member definitions, i.e. anything you would write inside a Type definition (such as field definitions, but also method definitions and body, properties...). Since this is standard C# code, it is much easier to generate dynamic type content that way. But since it is only a string, there is no compile-type checking of what you do in that string: you'll have to wait for weave time to be sure that the code you generated could be weaved to the target types.

Whatever the means you choose, this feature enables us to implement elegant ideas such as :

  • Generating "xxIsLoaded" fields to help implementing a lazy-loading process (for persistence frameworks for example)
  • Generating type safe and efficient serialization methods (to text, to xml or whatever). Your aspect stays generic, but its weaving creates different method bodies on different types (to serialize fields/properties of each specific target type) so that you don't need introspection (or reflection) any more at runtime.

AspectDNG usage

AspectDNG is a command line tool. It can be launched:

Multiple assemblies weaving

[Remark] This supposes you use Custom attributes to tell AspectDNG what must be weaved and where. See next section to learn more about Aspect configuration.

You can compile your target assembly (say Target.exe ) and your aspects assembly (say Aspects.dll ) separately. That way, there is absolutely no dependency between your target code and the code you want to weave.

Then, to weave the aspects on to your target code, just run :

aspectdng.exe Target.exe Aspects.dll

After weaving, a Target.exe.backup file will be produced. It contains the old version of your assembly before weaving. So that if you are not satisfied by your weaving, you can "rollback" it by running :

move /y Target.exe.backup Target.exe

The Target.exe will contain the weaved code. It is directly executable and should reflect both the original behavior and the additional one you specified in your aspects.

Of course, we gave the example of a .exe target assembly, but AspectDNG is also able to weave on .dll assemblies. Same process except of course that the weaved assembly is not executable.

Single assembly weaving

[Remark] This supposes you use Custom attributes to tell AspectDNG what must be weaved and where. See next section to learn more about Aspect configuration.

Depending on your project organization and build process, you may want to gather your target code and your aspects in the same assembly (say Target.exe or Target.dll). You'd typically use Namespaces to distinguish who is what, but strictly speaking it is not required.

In this case, running AspectDNG is even simpler:

aspectdng.exe Target.exe

Xml weaving

The previous settings required your aspects contain Custom Attributes to tell AspectDNG what to do. This can be seen as a strong dependency between your aspects code and AspectDNG itself, and hence a risk if you ever want to change Aspect weavers in the future.

To lighten that dependency, you could just write your target code, your aspect code, and tell AspectDNG what to do in a separated XML configuration file. This will typically suit projects that provide "off the shelf" aspects that don't know where they will be weaved in target assemblies. Not only you'll reduce Aspects-AspectDNG dependency but also Aspects-Specific target project dependency: your aspects will be more reusable that way.

aspectdng.exe someAspectDngConfig.xml

The details of the XML file will be described in the next section. They gloabally express the same thing as what you can specify in Custom Attributes, but in fact they are a bit more powerful. For example, you can weave multiple aspects into multiple targets using XML syntax whereas you can only weave one aspect into multiple targets using Custom Attributes.

Note that if you use "XML weaving" and that you still leave some Custom Attributes in your Aspects assembly, AspectDNG will follow both specifications (the union of all the weavings expressed in Attributes and XML).

The weave report

In the XML config file, you'll be able to specify where you want that AspectDNG generates a textual report of what has really be done during weaving (if it succeeds of course).

This report is generated in XML format, but can be opened in a Web browser and still be understood by a human being thanks to an XSLT stylesheet. The aim of this report is for technical people to make sure their weavings have really taken place, how many aspects were weaved on how many targets...

In the future, this report may be enhanced and used to integrate the same kind of information in an IDE such as VisualStudio.NET 2005. But we'll go on maintaining the XSLT stylesheet so that people who don't want or can use VS.NET are still able to review the weaved report.


Using custom attributes

Each custom attribute in the following list accepts a string that can contain either a regular expression or an XPath query. AspectDNG uses the first character to understand which syntax you're going to use: if your string starts with a slash (/), it will be interpreted as an XPath query (all XPath queries are absolute here).

  • Must be set on an interceptor method (see "Features" to see the required signature)
  • The query must target operations (constructors or methods)
  • Must be set on an interceptor method (see "Features" to see the required signature)
  • The query must target operation calls, not operations themselves
  • Must be set on an interceptor method (see "Features" to see the required signature)
  • The query must target fields access, not fields themselves
  • Must be set on an interceptor method (see "Features" to see the required signature)
  • The query must target fields access, not fields themselves
  • Can be set on types, operations, fields, events
  • The query must target the target parent you want to insert the following thing to ("thing" may be a field, operation, inner type...)
  • Can be set anywhere. This is an assembly-level attribute
  • Can be set anywhere. This is an assembly-level attribute
  • Must be set on the new base type
  • The query must target classes
  • Must be set on the interface to be implemented by target types
  • The query must target classes or structs
  • Must be set on a generator method (see "Features" to see the required signature)
  • The query must target a class or a struct

Using XML

The same constraints (the kinds of advice and target elements) must be respected when using XML configuration files. The main difference is syntaxic: for historical reasons we used to specify explicitly whether a query is a RegExp or an XPath. We may synchronize that syntax in the future and only keep "target" and "aspect"

  • Attribute aspectRegExp or aspectXPath must target interceptors
  • Attribute targetRegExp or targetXPath must target operations
  • Attribute aspectRegExp or aspectXPath must target interceptors
  • Attribute targetRegExp or targetXPath must target operation calls (not operations)
  • Attribute aspectRegExp or aspectXPath must target interceptors
  • Attribute targetRegExp or targetXPath must target fields read access (not fields)
  • Attribute aspectRegExp or aspectXPath must target interceptors
  • Attribute targetRegExp or targetXPath must target fields write access (not fields)
  • Attribute aspectRegExp or aspectXPath must target the elements to be inserted
  • Attribute targetRegExp or targetXPath must target the target parent elements you want to insert aspects to
  • Attribute targetRegExp or targetXPath must target what you want to discourage (may be a type, field, call, instruction, variable... anything)
  • Attribute targetRegExp or targetXPath must target what you want to forbid (may be a type, field, call, instruction, variable... anything)
  • Attribute aspectRegExp or aspectXPath must target the new parent type
  • Attribute targetRegExp or targetXPath must target the type that will inherit from the previous parent type
  • Attribute aspectRegExp or aspectXPath must target the interfaces to be implemented
  • Attribute targetRegExp or targetXPath must target the types that will implements the previous interfaces
  • Attribute aspectRegExp or aspectXPath must target generators
  • Attribute targetRegExp or targetXPath must target the types you want to insert elements to (the elements we speak about are those generated by your Generator method. They may be fields, methods, inner types...)

Weaving queries

In AOP, two things have equivalent importance: the advice (the code you want to weave) and the weaving language that expresses where you want the weaving to occur. It is very important that your feel comfortable with the weaving language of AspectDNG so that it becomes rapidly easy for you to weave your advice exactly where you want.

AspectDNG proposes in fact two languages to express your weavings : XPath or a simplified version of Regular Expressions. As you'll rapidly understand, the most powerful in AspectDNG is XPath, but the simplest is Regular Expressions. Depending on your needs, we invite you to use Reg Exps everywhere it is enough (because simpler) and to switch to XPath when you need to express more subtle constraints or use integrated functions.

AspectDNG query object model

The first thing you should know is the model your queries are going to be evaluated on. This model is a highly simplified version of Cecil object models, it only shows what you need to identify the right weaving locations (or joinpoints).

The following is a textual hierarchical representation of AspectDNG object model. @ means attributes, elements themselves are emphasized.


ILML dumps

Suppose you want to work on a specific assembly and try out some XPath queries. One way could be to use AspectDNG to "dump" your assembly in an XML text representation (called ILML in our jargon) and save it to the disk. Then you can use any tool you want (a graphical editor such as Xml Cooktop or a command line one such as Xml Starlet for example) to issue XPath queries on that XML file.

To dump an assembly (.exe or .dll) into XML, just run:

aspectdng.exe -ilml someOutputFilePath.xml

Note that dumping an assembly into XML may serve other needs than AOP. What about :

[Warning] However, be informed that AspectDNG exposes that XPath object model in "read-only". It is not possible to dump in XML, modify the XML and re-create an assembly out of the modified XML file. We used to do so in older versions of AspectDNG but performance issues discouraged this technique: in fact in the current implementation, we never generate any XML Document in memory but just simulate an XPath navigator that directly crosses Cecil object model. This is far more efficient in terms of performances and memory occupation than the previous implementations we had that used to work in XSLT (pipelines of transformations) then in C# on XML documents.

Testing XPath queries

If you don't need to dump assemblies in an XML file but you just want to run some XPath queries on the AspectDNG object model, a simpler way is to launch:

aspectdng.exe -query //Type[@Namespace='YourNS']

This way, you can run any query on any assembly from the command line. Don't be too cautious about whitespaces in your query: AspectDNG joins all the command line parameters into only one for your convenience.

Here are some typical XPath queries we run :

//Type[@Namespace = 'MyApp.Domain']

You can also use integrated XPath methods and an AspectDNG extension, match() that brings simplified regular expressions (more on this in the next section).

//Method[match('SomeReturnType *.SomeType::SomeName(*)')]
//Method[match('* *.SomeName::*(*)')]
//Method[match('* *.SomeName::*(*)')]//Call[match('* *::SomeOtherMethod(*)')]
//Method[match('* *.SomeName::*(*)')]//LdFld[match('* *::SomeField')]
//Constructor[match('* *::.ctor(*)')]//Call[match('* *::SomeField')]
//Constructor[match('* *::.cctor(*)')]//Call[match('* *::SomeField')]

We also implemented a utility method to test if a type is a descendant of another one (in other words, if a type can be casted into another one). For example, to get all the types that implement the System.Collections.IEnumerator interface (careful, the fully qualified type name is required!)


Using simplified regular expressions

Every component of the AspectDNG object model (Type, Method, Constructor, Instruction...) has a redefined version of ToString() that returns an adapted, fully qualified description. For example, a method would give something like:

System.String MyNamespace.MyType::MyMethod(System.String,System.Int32)

When Regular Expressions are used to match AspectDNG objects, they are in fact executed on the result of ToString() on those objects.

AspectDNG uses Regular Expressions as a pattern matching facility only. No replacement is made by those expressions. And for the sake of simplicity, because we only match types, operations and other members (which contain a lot of dots and parenthesis), we have redefined the meaning of some special characters:

Strictly speaking, there is no possibility [yet] in AspectDNG to test a simplified RegExp as you can test XPath queries. However, since the "match()" extension method has exactly the same behavior as simplified RegExp, here is a way to test your RegExp in command line anyway :

aspectdng.exe -query //*[match('YourRegExpHere')

Here are some typical RegExp queries we run :

* SomeNamespace.SomeType::SomeMethod(FirstParamType,SecondParamType,*)
* *::*(FirstAndOnlyParamType)
* *::{MethodName|OtherMethodName}(FirstAndOnlyParamType)
* *::FieldName

A few examples

Weave around execution

Around execution of all methods named "TargetMethod". First, let's use XPath:

public class YourAspectClass {
	[AroundBody("//Method[@Name = 'TargetMethod']")]
	public static object YourAspectMethod(MethodJoinPoint jp) {
		// Behavior before method execution
		object result = jp.Proceed();
		// Behavior after method execution
		return result;

Or the same using regular expressions:

public class YourAspectClass {
	[AroundBody("* *::TargetMethod()")]
	public static object YourAspectMethod(MethodJoinPoint jp) {
		// Behavior before method execution
		object result = jp.Proceed();
		// Behavior after method execution
		return result;

Around execution of "TargetMethod" in "TargetClass" in any package below "Business", supposing TargetMethod takes one String as a first parameter, and that it takes at least 2 parameters (one after the string at least):

[AroundBody("* Business.*.TargetClass::TargetMethod(System.String,*)")]

Weave around call

Around calls to constructors of "TargetClass".

[AroundCall("* *.TargetClass::.ctor(*)")]
public static object YourAspectMethod(ConstructorJoinPoint jp) {

Around calls to constructors of "TargetClass". This time, we only want the calls located in the "CallerClass" methods. XPath is required in this example, we cannot express both constraints using only Regular Expressions.

[AroundCall("//Method[match('* *CallerClass::*(*)')]//Call[match('*.TargetClass::.ctor(*)')]")]

Set base type and implement interface

The "NewBaseType" class will become the parent of "TargetClass" if you weave (suppose we use an XML configuration file this time):

<SetBaseType aspectRegExp="*.NewBaseType" targetRegExp="*.TargetClass"/>

The same effect can be obtained by:

public class NewBaseType{}

Having the "TargetClass" implement a "INewInterface" is similar to setting base type:

public interface INewInterface{}

Using Attributes to mark your targets

Suppose you have defined a custom Attribute named "PersistentAttribute" and that you have set it on any number of classes. You could insert a new integer field named "m_Id" on every class which is "Persistent" using the following syntax:

public class YourAspectClass{
	[Insert("//Type[match(Attribute/@Constructor, '*.Persistent::*')]")]
	private int m_Id;

Release notes

AspectDNG 1.0.3 (03.10.2006)

AspectDNG 1.0.2 (21.09.2006)

AspectDNG 1.0.1 (17.09.2006)

AspectDNG 1.0.0 (17.09.2006)

AspectDNG 0.9.96 (28.06.2006)

AspectDNG 0.9.95 (19.06.2006)

AspectDNG 0.9.94 (29.05.2006)

AspectDNG 0.9.93 (19.05.2006)

AspectDNG 0.9.92 (15.05.2006)

AspectDNG 0.9.91 (12.05.2006)

AspectDNG 0.9.90 (11.05.2006)

AspectDNG 0.9.83 (10.05.2006)

AspectDNG 0.9.82 (07.05.2006)

AspectDNG 0.9.81 (03.05.2006)

AspectDNG 0.9.80 (01.05.2006)

AspectDNG 0.9.79 (29.04.2006)

AspectDNG 0.9.78 (28.04.2006)

AspectDNG 0.9.77 (27.04.2006)

AspectDNG 0.9.76 (24.04.2006)

AspectDNG 0.9.74 (23.04.2006)

AspectDNG 0.9.73 (22.04.2006)

AspectDNG 0.9.72 (21.04.2006)

AspectDNG 0.9.60 (12.04.2006)

AspectDNG 0.9.59 (11.04.2006)

AspectDNG 0.9.56 (02.04.2006)

AspectDNG 0.9.55 (01.04.2006)

AspectDNG 0.9.41 to 0.9.53 (21.03.2006)

AspectDNG 0.9.32 to 0.9.40 (31.01.2006)

AspectDNG 0.9.36 (21.01.2006)

AspectDNG 0.9.35 (17.01.2006)

AspectDNG 0.9.34 (16.01.2006)

AspectDNG 0.9.33 (15.01.2006)

AspectDNG 0.9.32 (11.01.2006)

AspectDNG 0.9.31 (01.12.2005)

AspectDNG 0.9.30 (24.11.2005)

AspectDNG 0.9.19 (5.11.2005)

AspectDNG 0.9.15 (2.11.2005)

AspectDNG 0.9.13 (1.11.2005)

AspectDNG 0.9 (24.10.2005)

AspectDNG 0.8 (21.10.2005)

AspectDNG 0.7 (13.08.2005)

AspectDNG 0.6.4 (devel)

AspectDNG 0.6.3

AspectDNG 0.6.2

AspectDNG 0.6.1

AspectDNG 0.6

AspectDNG 0.5.6

AspectDNG 0.5.5 Symposium

AspectDNG 0.5.4

AspectDNG 0.5.3

AspectDNG 0.5.2

AspectDNG 0.5.1

AspectDNG 0.5

Todo List