41
Aspect Oriented Programming Adnan Masood www.AdnanMasood.com

Aspect Oriented Programming Adnan Masood

Embed Size (px)

Citation preview

Page 1: Aspect Oriented Programming Adnan Masood

Aspect Oriented Programming

Adnan Masoodwww.AdnanMasood.com

Page 2: Aspect Oriented Programming Adnan Masood

About Meaka. 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

Page 3: Aspect Oriented Programming Adnan Masood

3

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

Page 4: Aspect Oriented Programming Adnan Masood
Page 5: Aspect Oriented Programming Adnan Masood

5

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.

Page 6: Aspect Oriented Programming Adnan Masood

6

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 cross-cutting concern or add another one?

Page 7: Aspect Oriented Programming Adnan Masood

7

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

Page 8: Aspect Oriented Programming Adnan Masood

8

• 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 code in every method you might want to trace

Example

Page 9: Aspect Oriented Programming Adnan Masood

9

Introducing Aspect.NET Framework Design

CompilerApplicationSource Code

AspectLibrary

AspectSource Code

Aspect.NET.MLConverter

Application

Weaver

User

TargetApplicatio

n

Aspect.NET Framework

Page 10: Aspect Oriented Programming Adnan Masood

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.

Page 11: Aspect Oriented Programming Adnan Masood

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

Page 12: Aspect Oriented Programming Adnan Masood

12

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

Page 13: Aspect Oriented Programming Adnan Masood

13

Aspect Library(DLL)

%aspect Test //ML languagepublic class Test {%modules private static void TestRun() { WriteLine(”test”); }%rules

Aspect.MLConverter

C# Compiler

public class Test: Aspect//Attribute annotation { [AspectAction(“%before %call Write*")] public static void TestRunAction() { Test.TestRun(); } }}

Page 14: Aspect Oriented Programming Adnan Masood

14

Aspect.NET ML Example%aspect Politenesspublic 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

Page 15: Aspect Oriented Programming Adnan Masood

15

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

Page 16: Aspect Oriented Programming Adnan Masood

16

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; \\this keyword – Object TargetObject; \\p.TargetMethod(..);– MemberInfo TargetMemberInfo; \\TargetMethod as MethodInfo

– Type WithinType; \\this.GetType();– MethodBase WithinMethod; \\this.CurrentMethod();– string SourceFilePath; \\*.cs filepath– string SourceFileLine. \\source line number

• And more…

Page 17: Aspect Oriented Programming Adnan Masood

17

Current Aspect.NET ML expressive power (2/3)

• Weaving rules are specified by a mask and a regular expression.%before %call Namespace.Class.MethodNameor%before %call *MethodName

• Signature filtering.%instead %call static public void *Method(float, string, ..)

Page 18: Aspect Oriented Programming Adnan Masood

18

Current Aspect.NET ML expressive power (3/3)

• Arguments capturingAspectAction(“%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)

Page 19: Aspect Oriented Programming Adnan Masood

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

Page 20: Aspect Oriented Programming Adnan Masood

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

Page 21: Aspect Oriented Programming Adnan Masood

21

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

Page 22: Aspect Oriented Programming Adnan Masood

Example: the Politeness aspect%aspect Politenesspublic 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()}

Page 23: Aspect Oriented Programming Adnan Masood

23

Example: Weaving Politeness

%to MyApplication %apply Politeness

(the same can be done by means of Aspect editor)

Page 24: Aspect Oriented Programming Adnan Masood

24

Aspect.NET working screenshot

Page 25: Aspect Oriented Programming Adnan Masood

25

Installing Aspect.NET

Pre-requisites:• 1) Microsoft Visual Studio 2005 beta 2 installed.• 2) Microsoft Phoenix RDK 02/28/05 Release installedNotes:• 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.

Page 26: Aspect Oriented Programming Adnan Masood

26

Starting Aspect.NET Framework• The Aspect.NET Framework add-in window appears every

time Visual Studio is started.

Page 27: Aspect Oriented Programming Adnan Masood

27

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.

Page 28: Aspect Oriented Programming Adnan Masood

28

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.

Page 29: Aspect Oriented Programming Adnan Masood

29

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.

Page 30: Aspect Oriented Programming Adnan Masood

30

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.

Page 31: Aspect Oriented Programming Adnan Masood

31

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.

Page 32: Aspect Oriented Programming Adnan Masood

32

Weaving aspects• Visualization Tab represents program modules, with aspect actions

woven, as colored chart.

Page 33: Aspect Oriented Programming Adnan Masood

33

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.

Page 34: Aspect Oriented Programming Adnan Masood

34

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.

Page 35: Aspect Oriented Programming Adnan Masood

35

Step by Step playing with Aspect.NET• First of all load the source project into VS IDE.

Page 36: Aspect Oriented Programming Adnan Masood

36

Step by Step playing with Aspect.NET• Load the MAddNopCounter assembly to the Aspects list.

Page 37: Aspect Oriented Programming Adnan Masood

37

Step by Step playing with Aspect.NET• Click “Find Joinpoints” button and wait until the obtained points will

not be printed at Aspects tab.

Page 38: Aspect Oriented Programming Adnan Masood

38

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.

Page 39: Aspect Oriented Programming Adnan Masood

39

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

Page 40: Aspect Oriented Programming Adnan Masood

Aspect.NET references1) http://aosd.net - The starting Web site on AOP2) http://www.msdnaa.net/curriculum/?6219 – Aspect.NET&doc3) Safonov V. O. Aspect.NET: a new approach to aspect-oriented

programming. - .NET Developer’s Journal, 2003, #4.4) Safonov V.O. Aspect.NET: concepts and architecture. - .NET

Developer’s Journal, 2004, #10.5) Safonov V.O., Grigoryev D.A. Aspect.NET: aspect-oriented

programming for Microsoft.NET in practice. - .NET Developer’s Journal, 2005, # 7.

6) 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.

Page 41: Aspect Oriented Programming Adnan Masood

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