SlideShare a Scribd company logo
1 of 12
Introduction to Aspect Oriented
Programming in .NET with PostSharp
              Zubair Ahmed
        twitter.com/zubairdotnet
             zubairahmed.net
         inbox@zubairahmed.net
Agenda
•   The problem
•   What is AOP?
•   PostSharp
•   Writing Aspects in Visual Studio 2010
•   Learning Resources
The problem
• There was nothing in the beginning
  public class CustomerProcesses
  {
  }
The problem
• Then there was business code
  public class CustomerProcesses
  {
      public void RentBook( int bookId, int customerId )
      {
          Book book = Book.GetById( bookId );
          Customer customer = Customer.GetById( customerId );

          book.RentedTo = customer;
          customer.AccountLines.Add(
           string.Format( "Rental of book {0}.", book ), book.RentalPrice );
          customer.Balance -= book.RentalPrice;
      }
  }
The problem
• Then there was logging and exception handling
  internal class CustomerProcesses
  {
      private static readonly TraceSource trace =
          new TraceSource( typeof (CustomerProcesses).FullName );

          public void RentBook( int bookId, int customerId )
          {
             trace.TraceInformation(
                  "Entering CustomerProcesses.CreateCustomer( bookId = {0},
                   customerId = {1} )",
                  bookId, customerId );
             try
             {
                  Book book = Book.GetById( bookId );
                  Customer customer = Customer.GetById( customerId );

                  book.RentedTo = customer;
                  customer.AccountLines.Add(
                      string.Format( "Rental of book {0}.", book ), book.RentalPrice );
                  customer.Balance -= book.RentalPrice;

                  trace.TraceInformation(
                    "Leaving CustomerProcesses.CreateCustomer( bookId = {0}, customerId = {1} )",
                    bookId, customerId );
              }
              catch ( Exception e )
              {
                  trace.TraceEvent( TraceEventType.Error, 0,
                                    "Exception: CustomerProcesses.CreateCustomer(
                                    bookId = {0}, customerId = {1} ) failed : {2}",
                                    bookId, customerId, e.Message );
                   throw;
              }
      }
  }
The problem
• Then precondition checks
  internal class CustomerProcesses
  {
      private static readonly TraceSource trace =
          new TraceSource(typeof(CustomerProcesses).FullName);

      public void RentBook(int bookId, int customerId)
      {
          if (bookId <= 0) throw new ArgumentOutOfRangeException("bookId");
          if (customerId <= 0) throw new ArgumentOutOfRangeException("customerId");

          trace.TraceInformation(
              "Entering CustomerProcesses.CreateCustomer( bookId = {0}, customerId = {1} )",
              bookId, customerId);

          try
          {
                  . . . .
      }
  }
The problem
• Resulting code is:
  – B oil e r pl a te
  – H ig hl y Coupl e d
What is AOP?
• An approach that extends OOP and addresses the
  issue of Cross -cutting concerns
  – Enca ps ul a te cro s s -cutting co nce rns into As pe cts
  – Im prov e s cod e re us a b il ity, m od ul a rity a nd
    s e pa ra tion of conce rns
  – Re d uce s d e f e cts b y re d ucing b o il e r -pl a te cod e
Identify Cross-cutting concerns
• Ca nnot b e s e pa ra te d into a m od ul e
• Cha l l e ng e to a chie v e s e pa ra tion of conce rns
• Some cros s -cutting co nce rns
   – Exception Handling
   – Caching
   – Tracing
   – Validation
   – Authorization
   – Transactions
PostSharp
• A AOP Framework for .NET
• Works w ith a l l v e rs ions of .N ET
• Inte g ra te s into Vis ua l Stud io
• Supports s ta tic ‘b uil t -tim e ’ w e a v ing
Demo
• Aspects with PostSharp in Visual Studio 2010
Learning Resources
•   sharpcrafters.com/postsharp/documentation/screencasts
•   sharpcrafters.com/postsharp/documentation#blogposts
•   infoq.com/presentations/Advanced -AOP
•   dimecasts.net/Casts/ByTag/PostSharp
My Contacts
• twitter.com/zubairdotnet
• zubairahmed.net
• inbox@zubairahmed.net

More Related Content

Similar to Introduction to Aspect Oriented Programming in .NET with PostSharp by Zubair Ahmed

In memory OLAP engine
In memory OLAP engineIn memory OLAP engine
In memory OLAP engine
WO Community
 
S01 e01 schema-design
S01 e01 schema-designS01 e01 schema-design
S01 e01 schema-design
MongoDB
 
SH 1 - SES 8 - Stitch_Overview_TLV.pptx
SH 1 - SES 8 - Stitch_Overview_TLV.pptxSH 1 - SES 8 - Stitch_Overview_TLV.pptx
SH 1 - SES 8 - Stitch_Overview_TLV.pptx
MongoDB
 

Similar to Introduction to Aspect Oriented Programming in .NET with PostSharp by Zubair Ahmed (20)

Evolve your coding with some BDD
Evolve your coding with some BDDEvolve your coding with some BDD
Evolve your coding with some BDD
 
How to survive in a BASE world
How to survive in a BASE worldHow to survive in a BASE world
How to survive in a BASE world
 
In memory OLAP engine
In memory OLAP engineIn memory OLAP engine
In memory OLAP engine
 
Super spike
Super spikeSuper spike
Super spike
 
S01 e01 schema-design
S01 e01 schema-designS01 e01 schema-design
S01 e01 schema-design
 
W5_Modeling Design Diagram (2) - OBJECT ORIENTED DESIGN.pptx
W5_Modeling Design Diagram (2) - OBJECT ORIENTED DESIGN.pptxW5_Modeling Design Diagram (2) - OBJECT ORIENTED DESIGN.pptx
W5_Modeling Design Diagram (2) - OBJECT ORIENTED DESIGN.pptx
 
ITB2017 - Intro to Behavior Driven Development
ITB2017 - Intro to Behavior Driven DevelopmentITB2017 - Intro to Behavior Driven Development
ITB2017 - Intro to Behavior Driven Development
 
SH 1 - SES 8 - Stitch_Overview_TLV.pptx
SH 1 - SES 8 - Stitch_Overview_TLV.pptxSH 1 - SES 8 - Stitch_Overview_TLV.pptx
SH 1 - SES 8 - Stitch_Overview_TLV.pptx
 
Webinar: Position and Trade Management with MongoDB
Webinar: Position and Trade Management with MongoDBWebinar: Position and Trade Management with MongoDB
Webinar: Position and Trade Management with MongoDB
 
VBA API for scriptDB primer
VBA API for scriptDB primerVBA API for scriptDB primer
VBA API for scriptDB primer
 
HashiCorp Vault Plugin Infrastructure
HashiCorp Vault Plugin InfrastructureHashiCorp Vault Plugin Infrastructure
HashiCorp Vault Plugin Infrastructure
 
GraphQL - when REST API is not enough - lessons learned
GraphQL - when REST API is not enough - lessons learnedGraphQL - when REST API is not enough - lessons learned
GraphQL - when REST API is not enough - lessons learned
 
API-Entwicklung bei XING
API-Entwicklung bei XINGAPI-Entwicklung bei XING
API-Entwicklung bei XING
 
Power & flexibility of the Google Sheets API
Power & flexibility of the Google Sheets APIPower & flexibility of the Google Sheets API
Power & flexibility of the Google Sheets API
 
LJC Conference 2014 Cassandra for Java Developers
LJC Conference 2014 Cassandra for Java DevelopersLJC Conference 2014 Cassandra for Java Developers
LJC Conference 2014 Cassandra for Java Developers
 
MongoDB at ZPUGDC
MongoDB at ZPUGDCMongoDB at ZPUGDC
MongoDB at ZPUGDC
 
Cooking your Ravioli "al dente" with Hexagonal Architecture
Cooking your Ravioli "al dente" with Hexagonal ArchitectureCooking your Ravioli "al dente" with Hexagonal Architecture
Cooking your Ravioli "al dente" with Hexagonal Architecture
 
Functional programming in C#
Functional programming in C#Functional programming in C#
Functional programming in C#
 
Using AI to solve business challenges
Using AI to solve business challengesUsing AI to solve business challenges
Using AI to solve business challenges
 
Node.js extensions in C++
Node.js extensions in C++Node.js extensions in C++
Node.js extensions in C++
 

Recently uploaded

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Recently uploaded (20)

Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 

Introduction to Aspect Oriented Programming in .NET with PostSharp by Zubair Ahmed

  • 1. Introduction to Aspect Oriented Programming in .NET with PostSharp Zubair Ahmed twitter.com/zubairdotnet zubairahmed.net inbox@zubairahmed.net
  • 2. Agenda • The problem • What is AOP? • PostSharp • Writing Aspects in Visual Studio 2010 • Learning Resources
  • 3. The problem • There was nothing in the beginning public class CustomerProcesses { }
  • 4. The problem • Then there was business code public class CustomerProcesses { public void RentBook( int bookId, int customerId ) { Book book = Book.GetById( bookId ); Customer customer = Customer.GetById( customerId ); book.RentedTo = customer; customer.AccountLines.Add( string.Format( "Rental of book {0}.", book ), book.RentalPrice ); customer.Balance -= book.RentalPrice; } }
  • 5. The problem • Then there was logging and exception handling internal class CustomerProcesses { private static readonly TraceSource trace = new TraceSource( typeof (CustomerProcesses).FullName ); public void RentBook( int bookId, int customerId ) { trace.TraceInformation( "Entering CustomerProcesses.CreateCustomer( bookId = {0}, customerId = {1} )", bookId, customerId ); try { Book book = Book.GetById( bookId ); Customer customer = Customer.GetById( customerId ); book.RentedTo = customer; customer.AccountLines.Add( string.Format( "Rental of book {0}.", book ), book.RentalPrice ); customer.Balance -= book.RentalPrice; trace.TraceInformation( "Leaving CustomerProcesses.CreateCustomer( bookId = {0}, customerId = {1} )", bookId, customerId ); } catch ( Exception e ) { trace.TraceEvent( TraceEventType.Error, 0, "Exception: CustomerProcesses.CreateCustomer( bookId = {0}, customerId = {1} ) failed : {2}", bookId, customerId, e.Message ); throw; } } }
  • 6. The problem • Then precondition checks internal class CustomerProcesses { private static readonly TraceSource trace = new TraceSource(typeof(CustomerProcesses).FullName); public void RentBook(int bookId, int customerId) { if (bookId <= 0) throw new ArgumentOutOfRangeException("bookId"); if (customerId <= 0) throw new ArgumentOutOfRangeException("customerId"); trace.TraceInformation( "Entering CustomerProcesses.CreateCustomer( bookId = {0}, customerId = {1} )", bookId, customerId); try { . . . . } }
  • 7. The problem • Resulting code is: – B oil e r pl a te – H ig hl y Coupl e d
  • 8. What is AOP? • An approach that extends OOP and addresses the issue of Cross -cutting concerns – Enca ps ul a te cro s s -cutting co nce rns into As pe cts – Im prov e s cod e re us a b il ity, m od ul a rity a nd s e pa ra tion of conce rns – Re d uce s d e f e cts b y re d ucing b o il e r -pl a te cod e
  • 9. Identify Cross-cutting concerns • Ca nnot b e s e pa ra te d into a m od ul e • Cha l l e ng e to a chie v e s e pa ra tion of conce rns • Some cros s -cutting co nce rns – Exception Handling – Caching – Tracing – Validation – Authorization – Transactions
  • 10. PostSharp • A AOP Framework for .NET • Works w ith a l l v e rs ions of .N ET • Inte g ra te s into Vis ua l Stud io • Supports s ta tic ‘b uil t -tim e ’ w e a v ing
  • 11. Demo • Aspects with PostSharp in Visual Studio 2010
  • 12. Learning Resources • sharpcrafters.com/postsharp/documentation/screencasts • sharpcrafters.com/postsharp/documentation#blogposts • infoq.com/presentations/Advanced -AOP • dimecasts.net/Casts/ByTag/PostSharp My Contacts • twitter.com/zubairdotnet • zubairahmed.net • inbox@zubairahmed.net