Blue Theme Orange Theme Green Theme Red Theme
 
Nevron Chart
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
6 Months Free & No Setup Fees ASP.NET Hosting!
Search :       Advanced Search »
Home » Visual C# » Aspect Oriented Programming in C#.NET: Part I

Aspect Oriented Programming in C#.NET: Part I

A lot has been written about AOP (Aspect Oriented Programming) on the Web, but none of the articles cover how to implement it practically in C#. This articles covers it practically using C#.

Author Rank :
Page Views : 15332
Downloads : 0
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Nevron Chart
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


Introduction

A lot has been written about AOP (Aspect Oriented Programming) on the Web, but none of the articles cover how to implement it practically in C#.

Let's start with a small definition on AOP first:

        "Aspect Oriented Programming is a methodology to separate cross cut code across different modules in a software system."

In short all the cross cut code is moved to a separate module, thus increasing more modularity and bringing in ease of maintenance. Okay, that was a theoretical definition, let's try to understand why we really need AOP when we have decent methodologies like "Object Oriented Programming" and "Procedural Oriented Programming".

        "Aspect oriented programming is not introduced in order to replace OOP, but assists it to remove its short comings. I see AOP as a brother of OOP".

Every requirement is a Concern

        "Software development exists because of business concerns".

Software development is nothing but addressing a collection of concerns in real life. For instance, a customer sales software application has the following concerns:

  • User should be able to add, update and delete customer related information.
  • User should be able to track sales related to customer.
  • User should have a facility to print customer and sales information.
  • User should have a facility to email customer and sales information.

Okay, now readers will be wondering what's so special about these concerns, it can easily be implemented using OOP. In the next section we will try to implement the above concerns using the OOP methodology and see why we need AOP.

Cross Cutting Concern and Tangled code

Figure 1.1 Class diagram for Customer Sales Software Application

Above is the class diagram for the Customer Sales Software Application discussed in the first section. We are trying to address the four concerns for the application: Customer Maintenance, Sales Maintenance, Printing and Sending Email. So by abiding to all laws of OOP, the above class diagram is drawn. "ClsCustomer" class is responsible for adding, updating and deleting the customer records. "ClsSales" class is responsible for maintaining sales information for a customer, you can see the link between "ClsCustomer" and "ClsSales" classes. There were also some technical concerns. Printing and sending email are addressed by "ClsPrint" and "ClsEmail" classes. Also note both classes "ClsCustomer" and "ClsSales" have a dependency relationship on both of these classes ("ClsPrint" and "ClsEmail") to achieve the technical functionality.

Now according to OOP literature the first very important thing is that every object should be independent and should be concerned only about its functionality. Example, the "ClsCustomer" should only be concerned about adding, updating and deleting customer records. The Customer class should not have responsibilities of Sales or Print class. All the objects should work using messaging to achieve certain business functionality. In the above class diagram, all the classes are collaborating to make work the complete "Customer Sales Application".

OK, now it's time to look at the implementation of the above class diagram.

Figure 1.2 Explorer look of Customer Sales Application

As dictated by the class diagram, all the classes are included in the Explorer. OK, let's look at one of the implementations, that is the customer class implementation, i.e. the "Add" method of the Customer class. Below is a paste of the "Add" method of the Customer class.

public void Add()
{
    /////////////////////////////////////////
 

    // This method adds customer information 

    //  

    // Adding code will go here 

    //////////////////////////////////////// 

    // After adding to database email is sent 

    ClsEmail pobjClsEmail = new ClsEmail();
    pobjClsEmail.Send(); 

    // After sending email its printed 

    ClsPrint pobjClsPrint = new ClsPrint();

    pobjClsPrint.Print();

}

Okay, the "Add" method of "ClsCustomer" is doing some really heavy duty like:

  • It adds the customer data to the customer database.
  • Then it sends email using the class "ClsEmail".
  • Finally it prints the customer details using the "ClsPrint" class.

Don't you think guys "ClsCustomer" is doing some really heavy job, specially it's doing a lot of things which is not its concern. Example: sending email and printing is not its concern at all. Also note the same implementation has to be done with the "ClsSales" class. So in the Sales class also, we have to use both the classes: "ClsEmail" and "ClsPrint". In short the "Print" and "Email" span across more than one module. Such types of concerns are called as "Cross Cut Concerns". The code over there is quiet messed up as we are using lots of objects. These types of code are called as "Tangled code" in AOP terminology.

Okay, so here are some observations about concerns. All software applications have two types of concerns:

  • Core / Main concern. (Example: Customer and Sales maintenance concerns).
  • Cross cut concerns. (Printing, logging, sending email etc. which spans across modules).

Now we are aware of our problem "tangled code".

Solution for Tangled code: Weaving

Simply separate the Cross cut concerns from the Core concerns. So create modules for Cross cut and Core Concerns separately and then feed both the modules to the compiler. AOP supported compilers then compile both the modules and generate one single executable......isn't that cool guys? Hmmm.. now how do we attain that with .NET compilers? Well, till now .NET compilers did not support actual AOP compiling. So we had to do quiet a hack to attain AOP functionality in .NET. AspectJ is an AOP compiler which does AOP implementation for Java. But I hope the way .NET framework is architected it should not be a big deal to get AOP to action....can you hear me Microsoft, we trust you.

        "Weaving is a process of compiling the Core and Cross cut concerns together".

Figure 1.3 AOP weaver in action

In the coming sections, we will try to see the different kinds of weavers documented for AOP. Let us see which type of weaving can we implement in C#. But for now, let's try to understand some basic terminology which you will come across again and again.

Join points, Point cuts and Advice

Join points, Point cuts and Advice are some basics which you will need to understand for AOP.

Join point is a point where a concern will cross cut the main code. Join points can be a method call, function, constructor etc. Join points are useful in identifying problem points in a code. In our customer sales application, we have two join points:

  • pobjClsEmail.Send();
  • pobjClsPrint.Print();

Point Cut tells when it should match a Joint Point. In the above example I can say to match the email join point only when it's called in conjunction with "Invoke". Example:

Invoke( pobjClsEmail.Send(); )

So I have defined my point cut with the Email joint point using the Invoke method.

Advice when defined decides the sequence of execution of advice code with respect to joint point. Advice code is the code which you want to execute before or after the joint point. In AOP you can specify the advice code to execute before, around or after the joint point is matched.

Note: Whatever is the case before, after or around, point cut must trigger first.

So depending on what you have specified, the advice code will execute before, after or around the joint point. Like in our example we will want to execute the send and print afterwards.

Types of AOP compilers

OK, AOP compilers come in different flavors and the type of weaving decides what type of compiler it is. There are four types of compilers, or to be specific, weaving types in AOP:

  • Compile time weaving: This type of weaving happens at the compiler level and is not supported currently in .NET. But there are other compilers which I will discuss in my next part of the AOP tutorial. In compile time, Core concern code and the Cross cut code is weaved before being compiled to MSIL code. So before the JIT compilation takes place, using .NET compilers Aspect code is compiled and fed to the main compiler. There are many third party compilers which are available which extend the .NET compiler module and implement this feature. I am sure when Microsoft implements this feature in .NET compilers.......it's going to be party time guys.
  • Link time weaving: This type of compilers compile core and cross cut code after the MSIL is generated. Again this has to be done at linker level. So at this moment not supported, we will either have to use third party or wait for Microsoft's AOP compiler.
  • Run time weaving: This type of weaving is done by using the .NET runtime. In short your code detects the Core, Cross cut etc. and executes them at run time. This is supported at this moment in .NET and we will see how we can implement Run time weaving. Again many AOP gurus do argue that it is not actual AOP.... I leave that to the readers.

From my point of view, compiler is AOP featured when it has keyword support for Aspect, Join points, Point cut, Advice etc. So till then .NET guys can go around using the round about methods (which I will explain in the second part) to claim that .NET is AOP featured.

I hope I was able to explain the fundamentals of AOP.

In the second part of this tutorial "Aspect Oriented Programming in .NET: Part 2", we will see how we can implement the above AOP features in .NET.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Shivprasad
I am currently a CEO of a small E-learning company in India. We are very much active in making training videos , writing books and corporate trainings. You can visit about my organization at www.questpond.com and also enjoy the videos uploaded for Design patter, FPA , UML , Project and lot. I am also actively involved in RFC which is a financial open source madei in C#. It has modules like accounting , invoicing , purchase , stocks etc.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
Become a Sponsor
 Comments
Re: by dennis On March 17, 2009
Hi there, nice article, IMHO there is one thing i dont' agree is that your Add() Method in Customer class should not do send() or print() method otherwise it violateds Single responsibility principle. as far as your customer class concerns, it should only do full crud action for customers. you might want to have another class does the integrated action something like template pattern or factory pattern. cheers Dennis Leng
Reply | Email | Modify 
Excellent Description!! by nazish On January 13, 2011
Good article and very clear description about AOP. but MS should do some development or atleast encourage communities to work on it.
Reply | Email | Modify 
Team Foundation Server Hosting
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.