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

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 worldUwe Friedrichsen
 
In memory OLAP engine
In memory OLAP engineIn memory OLAP engine
In memory OLAP engineWO Community
 
S01 e01 schema-design
S01 e01 schema-designS01 e01 schema-design
S01 e01 schema-designMongoDB
 
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.pptxemanqaroonibahrain
 
ITB2017 - Intro to Behavior Driven Development
ITB2017 - Intro to Behavior Driven DevelopmentITB2017 - Intro to Behavior Driven Development
ITB2017 - Intro to Behavior Driven DevelopmentOrtus Solutions, Corp
 
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.pptxMongoDB
 
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 MongoDBMongoDB
 
VBA API for scriptDB primer
VBA API for scriptDB primerVBA API for scriptDB primer
VBA API for scriptDB primerBruce McPherson
 
HashiCorp Vault Plugin Infrastructure
HashiCorp Vault Plugin InfrastructureHashiCorp Vault Plugin Infrastructure
HashiCorp Vault Plugin InfrastructureNicolas Corrarello
 
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 learnedMarcinStachniuk
 
API-Entwicklung bei XING
API-Entwicklung bei XINGAPI-Entwicklung bei XING
API-Entwicklung bei XINGMark Schmidt
 
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 APIwesley chun
 
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 DevelopersChristopher Batey
 
MongoDB at ZPUGDC
MongoDB at ZPUGDCMongoDB at ZPUGDC
MongoDB at ZPUGDCMike Dirolf
 
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 ArchitectureJeroen Rosenberg
 
Functional programming in C#
Functional programming in C#Functional programming in C#
Functional programming in C#Thomas Jaskula
 
Using AI to solve business challenges
Using AI to solve business challengesUsing AI to solve business challenges
Using AI to solve business challengesMarvin Heng
 

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

Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 

Recently uploaded (20)

Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 

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