Aspect Oriented Programming

Report
Aspect Oriented Programming
Adnan Masood
www.AdnanMasood.com
About Me
aka. Shameless Self Promotion
• Sr. Software Engineer / Tech Lead for Green Dot Corp. (Financial
Institution)
• Design and Develop Connected Systems
• Involved with SoCal Dev community, co-founded San Gabriel Valley .NET
Developers Group. Published author and speaker.
• MS. Computer Science, MCPD (Enterprise Developer), MCT, MCSD.NET
• Doctoral Student - Areas of Interest: Machine learning, Bayesian Inference,
Data Mining, Collaborative Filtering, Recommender Systems.
• Contact at [email protected]
• Read my Blog at www.AdnanMasood.com
• Doing a session in IASA 2008 in San Francisco on Aspect Oriented
Programming; for details visit http://www.iasaconnections.com
Programming paradigms
• Procedural programming
– Executing a set of commands in a given sequence
– Fortran, C, Cobol
• Functional programming
– Evaluating a function defined in terms of other functions
– Lisp, ML, OCaml
• Logic programming
– Proving a theorem by finding values for the free variables
– Prolog
• Object-oriented programming (OOP)
– Organizing a set of objects, each with its own set of responsibilities
– Smalltalk, Java, C++ (to some extent)
• Aspect-oriented programming (AOP)
– Executing code whenever a program shows certain behaviors
– AspectJ (a Java extension)
– Does not replace O-O programming, but rather complements
it
3
Introduction to AOP (part 1)
• Aspect-oriented programming (AOP) is an attempt to solve
the problems of development complex software.
• Each of software modules (classes, methods, procedures,
etc.) solves some definite logically independent task (event
logging, authentification, security, assertions,..). To use
new modules in our product, we need to inject their calls
into the sources.
5
Introduction to AOP (part 2)
• As a result we have a lot of tangled
code in our sources.
• What shall we do when we decide to
remove or modify such a crosscutting concern or add another one?
6
Introduction to AOP (part 3)
•
•
AOP suggests: “Let’s remove them from sources and weave directly to binaries instead,
according to our rules described in special language”
Approaches:
– Extend an existing language (AspectJ, Aspect#)
 Need special compiler for every language version.
– Dynamic execution (hooks at definite points of execution)
(Loom.NET, RAIL)
 Don’t know what kind of code is currently executing.
 Low performance
- Static weaving into assemblies (Aspect.NET)
 High performance
 Resulting code could be examined explicitly (Reflector)
 A lot of existing .NET tools can work with resulting
assemblies
7
Example
• class Fraction {
int numerator;
int denominator;
...
public Fraction multiply(Fraction that) {
traceEnter("multiply", new Object[] {that});
Fraction result = new Fraction(
this.numerator * that.numerator,
this.denominator * that.denominator);
result = result.reduceToLowestTerms();
traceExit("multiply", result);
return result;
}
• Now imagine similar
...
in every method you
}
might want to trace
8
code
Introducing Aspect.NET Framework Design
User
Aspect.NET Framework
Aspect
Source Code
Aspect.NET.ML
Converter
Aspect
Library
Weaver
Application
Application
Source Code
Compiler
Target
Application
9
Aspect.NET goals
• Aspect.NET is an aspect-oriented tool that
allows you to define some functionality by
specific aspect units and weave them into
your assemblies.
• So, the cross-cutting concerns appear to be
structured into aspects which makes the code
clearer.
• Aspect.NET is implemented as Visual
Studio.NET 2005 (Whidbey) add-in, to use
AOP technology in a comfortable manner,
alongside with using ubiquitous VS.NET
software development features.
AOP buzzwords
• joinpoint – an execution event
– function call, function execution, field access,
exception, etc.
• advice – code that the programmer wants
to be called before, after, or instead of
(around), some joinpoint
• pointcut – a pattern for matching joinpoints
– e.g., “System.Output.*”
• weaving – transforming a program to call
advice code
Formally Speaking
• Cross-cutting concern ~ a concern whose implementation cannot be
made by a generalized procedure
• Examples ~ logging; security; MT-safety; implementation of a new
source language construct in a compiler
• Aspect ~ implementation of a cross-cutting concern
• Weaving ~ applying an aspect to a target application (inserting new
modules and definitions; inserting, replacing or deleting tangled pieces
of code)
• Pointcut ~ a set of weaving rules for an aspect
• Join points ~ a set of concrete points in a target application subject to
aspect weaving
• Benefits of AOP: make software development and maintenance easier,
due to performing it in terms of aspects
12
%aspect Test
//ML language
public class Test
{
%modules
Aspect.ML
private static void TestRun()
{
Converter
WriteLine(”test”);
}
%rules
public class Test: Aspect//Attribute annotation
{
[AspectAction(“%before %call Write*")]
public static void TestRunAction()
{
Test.TestRun();
}
}
}
Aspect Library
(DLL)
C# Compiler
13
Aspect.NET ML Example
%aspect Politeness
public class Politeness
{
%modules
private static void SayScanningHello()
{
Console.WriteLine("Welcome to Aspect.NET scanning system!");
}
%rules
%before %call *SomeMethod
%action public static void SayScanningHelloAction()
{
Politeness.SayScanningHello();
}
}// Politeness
14
Custom attributes (example)
public class Politeness: Aspect
{
private static void SayScanningHello()
{
Console.WriteLine("Welcome to Aspect.NET scanning system!");
}
[AspectAction(“%before %call *SomeMethod”)]
public static void SayScanningHelloAction()
{
Politeness.SayScanningHello();
}
}// Politeness
15
Current Aspect.NET ML expressive power (1/3)
• Can inject actions before, after or instead call
instructions
• Actions have full access to the woven context through
the properties of base Aspect class:
–
–
–
–
–
Object This;
Object TargetObject;
MemberInfo TargetMemberInfo;
Type WithinType;
MethodBase WithinMethod;
\\this.CurrentMethod();
– string SourceFilePath;
– string SourceFileLine.
\\this keyword
\\p.TargetMethod(..);
\\TargetMethod as MethodInfo
\\this.GetType();
\\*.cs filepath
\\source line number
• And more…
16
Current Aspect.NET ML expressive power (2/3)
• Weaving rules are specified by a mask and a
regular expression.
%before %call Namespace.Class.MethodName
or
%before %call *MethodName
• Signature filtering.
%instead %call static public void
*Method(float, string, ..)
17
Current Aspect.NET ML expressive power (3/3)
• Arguments capturing
AspectAction(“%after %call *Method(int) && args(arg[1])”)
static public void MethodAction(int i)
{
Console.WriteLine({0}, i);
}
Additional restrictions on join points placement
%within(*SomeType)
%withincode(*SomeMethod)
%instead %call *Method && %within(*MyType)
&& %!withincode(*.ctor)
18
Why Cross Cutting Concern?
• Some programming tasks cannot be neatly
encapsulated in objects, but must be scattered
throughout the code
• Examples:
–
–
–
–
–
Logging (tracking program behavior to a file)
Profiling (determining where a program spends its time)
Tracing (determining what methods are called when)
Session tracking, session expiration
Special security management
• The result is crosscuting code--the necessary code
“cuts across” many different classes and methods
Terminology
• A join point is a well-defined point in the program
flow
• A pointcut is a group of join points
• Advice is code that is executed at a pointcut
• Introduction modifies the members of a class and
the relationships between classes
• An aspect is a module for handling crosscutting
concerns
– Aspects are defined in terms of pointcuts, advice, and
introduction
– Aspects are reusable and inheritable
Aspect.NET architecture
•
•
•
•
•
Aspect.NET.ML converters (currently for C#) to definitions
of AspectDef AOP attribute
Aspect weaver:
Target assembly + Aspect assemblies -> Target assembly*
Aspect editor + aspect GUI: locating aspects, coloring
aspects, editing aspects, deleting aspects; integrated to
Whidbey as add-in
Aspect.NET .msi-based installer (checks where the
Phoenix RDK is located on your machine)
AspectRotor – a separate console version of Aspect.NET
for Rotor environment
21
Example: the Politeness aspect
%aspect Politeness
public class Politeness
{
%modules
public static SayHello ()
{
System.Console.WriteLine(“Hello”);
}
public static SayBye ()
{
System.Console.WriteLine(“Bye”);
}
%rules
%before %call *
%action public static void SayHelloAction
{ Politeness.SayHello()}
%after %call *
%action public static void SayByeAction { Politeness.SayBye()}
Example: Weaving Politeness
%to MyApplication %apply Politeness
(the same can be done by means of Aspect editor)
23
Aspect.NET working screenshot
24
Installing Aspect.NET
Pre-requisites:
•
•
1) Microsoft Visual Studio 2005 beta 2 installed.
2) Microsoft Phoenix RDK 02/28/05 Release installed
Notes:
•
•
•
Aspect.NET Framework has been tested under
Microsoft Visual Studio 2005 beta 2 and with assemblies
written in C# only.
To install Aspect.NET, run AspectNETFramework.msi
and follow tips of the wizard.
The installer copies core assemblies, deployment files as
well as Phoenix binaries into the folder specified by the
user.
25
Starting Aspect.NET Framework
• The Aspect.NET Framework add-in window appears every
time Visual Studio is started.
26
How to create an aspect in Aspect.NET ML?
•
•
Aspect is a special VS C# project template.
So, please create a new project (say MAddNopCounter) specified with aspect template.
27
How to create an aspect?
•
•
The wizard generates the simple aspect skeleton in aspect.an file, which is container for
aspect description written in Aspect.NET ML.
Сode the body of the aspect in the .an file, based on the skeleton generated by the
wizard.
28
How to create an aspect?
• Click “Build Solution” button or execute “Rebuild
All”. At this phase, the aspect.an.cs file is created
to contain correct C# source code with ML
annotations converted into the custom attribute
AspectDef. Then, the standard C# compiler
compiles it to the aspect assembly and places it
into the debug folder (say MAddNopCounter.dll).
• One can weave this assembly as an aspect to
his/her projects.
29
Weaving aspects
• Open or Create new C# project in Visual Studio.
• In Aspect.NET Framework click "Add Existing
Aspect Module" button on "Modules" tab to add
Aspect assemblies. You can add multiple
assemblies.
• Press "Find Joinpoints" button to find the join
points in the currently active project.
• If join points have been found, Aspect.NET
Framework switches to the "Aspects" tab. Here
you can filter the joinpoints and browse them.
30
Weaving aspects
• Use the checkboxes in the join points tree to enable or
disable a join point. You can enable or disable groups of
join points by checking or unchecking parent methods,
classes and namespaces.
• You can click the join point to see its location in a source
code.
• Pressing "Weave Aspects" button results in aspects
weaving into the debug assembly of the current project.
• When weaving is finished , Aspect.NET Framework
informs you where the target assembly is located.
31
Weaving aspects
• Visualization Tab represents program modules, with aspect actions
woven, as colored chart.
32
Example of Weaving
• MAddNop is a basic sample included into Phoenix
RDK to demonstrate its capabilities. It is a simple
managed Phoenix based application to add nop's
to an existing executable.
• Let’s change its behavior without touching source
code and create an aspect MAddNopCounter to
add some tracing.
• The aspect reports on starting Phoenix
initialization process, prints Phoenix configuration
state and counts the number of nop’s inserted to
an executable.
33
Step by Step playing with Aspect.NET
• Turn the MAddNop.cs file from
\PhoenixRDK\src\Samples\maddnop into
VS project named MAddNop.
• Lets weave our aspect to MAddNop project
and check the results.
34
Step by Step playing with Aspect.NET
• First of all load the source project into VS IDE.
35
Step by Step playing with Aspect.NET
• Load the MAddNopCounter assembly to the Aspects list.
36
Step by Step playing with Aspect.NET
• Click “Find Joinpoints” button and wait until the obtained points will
not be printed at Aspects tab.
37
Step by Step playing with Aspect.NET
•
•
•
To weave the actions to the join points, click “Weave Aspects” button and
check the resulting assembly ~MAddNop.exe in the debug folder of your
project.
Lets try how it works on the testapp.exe shipped with PhoenixRDK. Copy
testapp.exe and testapp.pdb from \PhoenixRDK\Applications\Tests into debug
folder of MAddNop project.
Run “~MAddNop.exe testapp.exe newapp.exe”
and “MAddNop.exe testapp.exe newapp.exe”
in the console to compare the behavior of the assembly with the aspect
woven to that of the original assembly.
38
Step by Step playing with Aspect.NET
• The result of executing two assemblies is presented below.
• As we can see, output of our new assembly is much more
informative, as compared to the original assembly. No
Phoenix source code touched to achieve this goal
39
Aspect.NET references
1)
2)
3)
4)
5)
6)
http://aosd.net - The starting Web site on AOP
http://www.msdnaa.net/curriculum/?6219 –
Aspect.NET&doc
Safonov V. O. Aspect.NET: a new approach to aspect-oriented
programming. - .NET Developer’s Journal, 2003, #4.
Safonov V.O. Aspect.NET: concepts and architecture. - .NET
Developer’s Journal, 2004, #10.
Safonov V.O., Grigoryev D.A. Aspect.NET: aspect-oriented
programming for Microsoft.NET in practice. - .NET
Developer’s Journal, 2005, # 7.
Safonov V.O., Grigoryev D.A. Aspect.NET – an aspect-oriented
programming tool for Microsoft.NET. – Proceedings of St.
Petersburg Regional IEEE conference, St. Petersburg, May
2005.
Concluding remarks
• Aspect-oriented programming (AOP) is a new paradigm--a new
way to think about programming
• AOP is somewhat similar to event handling, where the “events”
are defined outside the code itself
• Like all new technologies, AOP may--or may not--catch on in a
big way

similar documents