Aspect Oriented Programming Adnan Masood www Adnan Masood

  • Slides: 41
Download presentation
Aspect Oriented Programming Adnan Masood www. Adnan. Masood. com

Aspect Oriented Programming Adnan Masood www. Adnan. Masood. com

About Me aka. Shameless Self Promotion • Sr. Software Engineer / Tech Lead for

About Me aka. Shameless Self Promotion • Sr. Software Engineer / Tech Lead for Green Dot Corp. (Financial Institution) • Design and Develop Connected Systems • Involved with So. Cal 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 adnanmasood@acm. org • Read my Blog at www. Adnan. Masood. 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

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 – Aspect. J (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

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

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

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 (Aspect. J, 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

Example • class Fraction { int numerator; int denominator; . . . public Fraction multiply(Fraction that) { trace. Enter("multiply", new Object[] {that}); Fraction result = new Fraction( this. numerator * that. numerator, this. denominator * that. denominator); result = result. reduce. To. Lowest. Terms(); trace. Exit("multiply", result); return result; } • Now imagine similar code. . . in every method you might } want to trace 8

Introducing Aspect. NET Framework Design User Aspect. NET Framework Aspect Source Code Aspect. NET.

Introducing Aspect. NET Framework Design User Aspect. NET Framework Aspect Source Code Aspect. NET. ML Converter Aspect Library Weaver Application Source Code Compiler Target Application 9

Aspect. NET goals • Aspect. NET is an aspect-oriented tool that allows you to

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

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

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

%aspect Test //ML language public class Test { %modules Aspect. ML private static void Test. Run() { Converter Write. Line(”test”); } %rules public class Test: Aspect//Attribute annotation { [Aspect. Action(“%before %call Write*")] public static void Test. Run. Action() { Test. Run(); } } } Aspect Library (DLL) C# Compiler 13

Aspect. NET ML Example %aspect Politeness public class Politeness { %modules private static void

Aspect. NET ML Example %aspect Politeness public class Politeness { %modules private static void Say. Scanning. Hello() { Console. Write. Line("Welcome to Aspect. NET scanning system!"); } %rules %before %call *Some. Method %action public static void Say. Scanning. Hello. Action() { Politeness. Say. Scanning. Hello(); } }// Politeness 14

Custom attributes (example) public class Politeness: Aspect { private static void Say. Scanning. Hello()

Custom attributes (example) public class Politeness: Aspect { private static void Say. Scanning. Hello() { Console. Write. Line("Welcome to Aspect. NET scanning system!"); } [Aspect. Action(“%before %call *Some. Method”)] public static void Say. Scanning. Hello. Action() { Politeness. Say. Scanning. Hello(); } }// Politeness 15

Current Aspect. NET ML expressive power (1/3) • Can inject actions before, after or

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 Target. Object; Member. Info Target. Member. Info; Type Within. Type; Method. Base Within. Method; \this. Current. Method(); – string Source. File. Path; – string Source. File. Line. – – – \this keyword \p. Target. Method(. . ); \Target. Method as Method. Info \this. Get. Type(); \*. cs filepath \source line number • And more… 16

Current Aspect. NET ML expressive power (2/3) • Weaving rules are specified by a

Current Aspect. NET ML expressive power (2/3) • Weaving rules are specified by a mask and a regular expression. %before %call Namespace. Class. Method. Name or %before %call *Method. Name • Signature filtering. %instead %call static public void *Method(float, string, . . ) 17

Current Aspect. NET ML expressive power (3/3) • Arguments capturing Aspect. Action(“%after %call *Method(int)

Current Aspect. NET ML expressive power (3/3) • Arguments capturing Aspect. Action(“%after %call *Method(int) && args(arg[1])”) static public void Method. Action(int i) { Console. Write. Line({0}, i); } Additional restrictions on join points placement %within(*Some. Type) %withincode(*Some. Method) %instead %call *Method && %within(*My. Type) && %!withincode(*. ctor) 18

Why Cross Cutting Concern? • Some programming tasks cannot be neatly encapsulated in objects,

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 •

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

Aspect. NET architecture • • • Aspect. NET. ML converters (currently for C#) to definitions of Aspect. Def 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) Aspect. Rotor – a separate console version of Aspect. NET for Rotor environment 21

Example: the Politeness aspect %aspect Politeness public class Politeness { %modules public static Say.

Example: the Politeness aspect %aspect Politeness public class Politeness { %modules public static Say. Hello () { System. Console. Write. Line(“Hello”); } public static Say. Bye () { System. Console. Write. Line(“Bye”); } %rules %before %call * %action public static void Say. Hello. Action { Politeness. Say. Hello()} %after %call * %action public static void Say. Bye. Action { Politeness. Say. Bye()}

Example: Weaving Politeness %to My. Application %apply Politeness (the same can be done by

Example: Weaving Politeness %to My. Application %apply Politeness (the same can be done by means of Aspect editor) 23

Aspect. NET working screenshot 24

Aspect. NET working screenshot 24

Installing Aspect. NET Pre-requisites: • • 1) Microsoft Visual Studio 2005 beta 2 installed.

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 Aspect. NETFramework. 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

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

How to create an aspect in Aspect. NET ML? • • Aspect is a special VS C# project template. So, please create a new project (say MAdd. Nop. Counter) specified with aspect template. 27

How to create an aspect? • • The wizard generates the simple aspect skeleton

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”.

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 Aspect. Def. Then, the standard C# compiler compiles it to the aspect assembly and places it into the debug folder (say MAdd. Nop. Counter. 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

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

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

Weaving aspects • Visualization Tab represents program modules, with aspect actions woven, as colored chart. 32

Example of Weaving • MAdd. Nop is a basic sample included into Phoenix RDK

Example of Weaving • MAdd. Nop 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 MAdd. Nop. Counter 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 MAdd. Nop. cs file

Step by Step playing with Aspect. NET • Turn the MAdd. Nop. cs file from Phoenix. RDKsrcSamplesmaddnop into VS project named MAdd. Nop. • Lets weave our aspect to MAdd. Nop project and check the results. 34

Step by Step playing with Aspect. NET • First of all load the source

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 MAdd. Nop. Counter assembly

Step by Step playing with Aspect. NET • Load the MAdd. Nop. Counter assembly to the Aspects list. 36

Step by Step playing with Aspect. NET • Click “Find Joinpoints” button and wait

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

Step by Step playing with Aspect. NET • • • To weave the actions to the join points, click “Weave Aspects” button and check the resulting assembly ~MAdd. Nop. exe in the debug folder of your project. Lets try how it works on the testapp. exe shipped with Phoenix. RDK. Copy testapp. exe and testapp. pdb from Phoenix. RDKApplicationsTests into debug folder of MAdd. Nop project. Run “~MAdd. Nop. exe testapp. exe newapp. exe” and “MAdd. Nop. 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

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

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

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