Aspect oriented programming
Download
1 / 41

Aspect Oriented Programming - PowerPoint PPT Presentation


  • 128 Views
  • Uploaded on

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

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about ' Aspect Oriented Programming' - paige


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
Aspect oriented programming

Aspect Oriented Programming

Adnan Masood

www.AdnanMasood.com


About me aka shameless self promotion
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


Programming paradigms
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


Introduction to aop part 1
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.


Introduction to aop part 2
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?


Introduction to aop part 3
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


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


Introducing aspect net framework design

User

Aspect.NET Framework

Weaver

Aspect.NET.ML

Converter

Aspect

Source Code

Aspect

Library

Application

Target

Application

Compiler

Application

Source Code

Introducing Aspect.NET Framework Design


Aspect net goals
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
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
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


%aspect Test //ML language

public class Test

{

%modules

private static void TestRun()

{

WriteLine(”test”);

}

%rules

Aspect.ML

Converter

public class Test: Aspect//Attribute annotation

{

[AspectAction(“%before %call Write*")]

public static void TestRunAction()

{

Test.TestRun();

}

}

}

C# Compiler

Aspect Library

(DLL)


Aspect net ml example
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


Custom attributes example
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


Current aspect net ml expressive power 1 3
Current Aspect.NET ML expressive power (1/3)

  • Can inject actions before, after or insteadcall 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…


Current aspect net ml expressive power 2 3
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 staticpublicvoid *Method(float, string, ..)


Current aspect net ml expressive power 3 3
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)


Why cross cutting concern
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
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 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


Example the politeness aspect
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 *

%actionpublic staticvoid SayHelloAction

{Politeness.SayHello()}

%after %call *

%actionpublic staticvoid SayByeAction{Politeness.SayBye()}


Example weaving politeness
Example: Weaving Politeness

%to MyApplication %apply Politeness

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



Installing aspect net
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.


Starting aspect net framework
Starting Aspect.NET Framework

  • The Aspect.NET Framework add-in window appears every time Visual Studio is started.


How to create an aspect in aspect net ml
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.


How to create an aspect
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.


How to create an aspect1
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.


Weaving aspects
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.


Weaving aspects1
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.


Weaving aspects2
Weaving aspects

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


Example of weaving
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.


Step by step playing with aspect net
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.


Step by step playing with aspect net1
Step by Step playing with Aspect.NET

  • First of all load the source project into VS IDE.


Step by step playing with aspect net2
Step by Step playing with Aspect.NET

  • Load the MAddNopCounter assembly to the Aspects list.


Step by step playing with aspect net3
Step by Step playing with Aspect.NET

  • Click “Find Joinpoints” button and wait until the obtained points will not be printed at Aspects tab.


Step by step playing with aspect net4
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.


Step by step playing with aspect net5
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


Aspect net references
Aspect.NET references

  • 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
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


ad