SlideShare a Scribd company logo
1 of 65
Download to read offline
APPLIED CODE GENERATION IN
           .NET
        Dmytro Mindra
        Lohika, Odessa
What’s the matter ?
• We are engineers !
• Engineers’ time is valuable and expensive;
• Engineers don’t like repetitive tasks;
Task classification
• Brains
• Experience
• Procedures
Houston, we’ve got a problem !

Our business domain contains 500+ entities.
         Each entity needs CRUD.
Houston, we’ve got a problem !
         And you have lots of time.
           The whole 4 months.

For your big team of 4 developers that should
               not be a problem !
Houston, we’ve got a problem !
Oh, and we’re not sure which parts will stay
 generic and which won’t
Houston, we’ve got a problem !
Be agile, don’t wait for the analysts to finish their
job, because we don’t have that kind of time.

Just change your code when the Requirements are
finished.
Houston, we’ve got a problem !
For each domain entity we should have
• Stored Procedures
• Repository
• Service
• Controller
• Views
• etc

That’s about 1000 lines of code per entity.
Houston, we’ve got a problem !
But we have 500+ entities

500*1000 = 500000 lines of code.

Who wants to type this in ?
Houston, we’ve got a problem !
• And when the changes arrive someone should
  make corrections to 500*1000 lines of code.
What are the solutions ?
• Hand-code everything (and every change)
   – Hire a lot of monkeys coders

• Design everything generically, correctly the first time
   – Mission impossible

• Use only code generation
   – And spend your life changing generator to match all
     possible requirements

• Use combination of tools including code generation.
   – This seems reasonable
Boilerplate
• Interestingly, the term (boilerplate) arose
  from the newspaper business. Columns
  and other pieces that were syndicated
  were sent out to subscribing newspapers
  in the form of a mat (i.e. a matrix). Once
  received, boiling lead was poured into this
  mat to create the plate used to print the
  piece, hence the name boilerplate. As the
  article printed on a boilerplate could not
  be altered, the term came to be used by
  attorneys to refer to the portions of a
  contract which did not change through
  repeated uses in different applications,
  and finally to language in general which
  did not change in any document that was
  used repeatedly for different occasions.
CODE GENERATION is code that writes code
Some common terms
• Code generation
• Automatic programming
• Generative programming
IDE Generated Code Example
Tools evolution
Code Smith
http://www.codesmithtools.com/

            Demo
Generator




Input
          Code      Output
        Generator
Why CG?
•   Productivity
•   Quality
•   Consistency
•   Abstraction
PROS
•   Code uniformity
•   Easy to debug
•   Easy to introduce huge changes
•   No more boilerplate code
CONS
• Someone should maintain the generator
• Generator has learning curve
• Generator usually has limitations
Applications
•   Database Access
•   Generate Test Data
•   Generate Integration Tests
•   User Interface
•   Documentation
•   Unit tests
•   File Formats
•   Web services
•   Business logic
•   DLL Wrappers
•   Firewall configuration
•   Website configuration
•   Looking for localizable strings
Code Generation is Fun ?
• CG makes boring job for you

• Writing generator is fun

• Once written generator works for you

• You can experiment with different implementations by
  modifying generator and regeneration the code.

• While writing the generator you get deeper into the
  technology instead of doing dull job.
Scaffolding and prototyping
• Code generation can help you to build fast
  prototypes.
MVC Scaffolding Demo
Rules
1. Give the proper respect to hand-coding
2. Handwrite the code first
3. Control the source code
4. Make a considered decision about the
   implementation language
5. Integrate the generator into the development
   process
Rules
6.  Include warnings
7.  Make it friendly
8.  Include documentation
9.  Keep in mind that generation is a cultural
   issue
10. Maintain the generator
A note about DSL

A domain-specific language (DSL) is a
programming language or specification
language dedicated to a particular problem
domain
Model Driven Architecture
Model Driven Architecture
• Code generation has a dramatic impact on
  development time and engineering productivity.

• The application is amenable to change on a large scale.

• The business rules are abstracted into files that are free
  of language or framework details that would hinder
  portability.

• The code for the application is of consistently high
  quality across the code base.
Benefits of MDA
•   Quality
•   Consistency
•   A single point of knowledge
•   More design time
•   Design decisions that stand out
Software Factories
Industrializing Software Development
Software Factory
Consider this:
• Code generation has a large initial schedule
  overhead;

• Code generators are ideal for well-known large-
  scale problems;

• Code generation is powerful when used
  appropriately;

• Always keep in mind code generation limitations!
Code Generation Skills
•   Text Templates
•   Regular Expressions
•   XML Parsing
•   Reflection
Show me
the tools
Available tools
•   StringBuilder
•   CodeSnippets
•   XSLT
•   Reflection Emit
•   EnvDTE
•   CodeDom
•   T4
•   … (Python, Ruby,
StringBuilder
• Advantages
  – Almost all .net developers should feel comfortable using
    the StringBuilder class so it requires no additional
    languages / tools to learn.
  – Even with the disadvantages, the StringBuilder can be an
    excellent choice if you need to generate code quickly.
    Especially if you don’t need to maintain the “template”
    long term.
• Disadvantages
  – Unable to truly see the “template” within the control logic.
  – Requires a recompile if the “template” should be changed.
Code Snippets
• Advantages
  – Simple Xml based template with numerous
    samples provided within Visual Studio.
  – Several open source code snippet libraries
    available.
• Disadvantages
  – Limited snippet functions and at the present time
    developers are unable to author additional
    snippet functions!
XSLT
• Advantages
  – Xml based template.
  – Simple code generation technique for those
    developers comfortable with XSLT
    transformations.
• Disadvantages
  – While Xml is a relatively simple technology, XSLT
    has been known to bring grown men to tears!
  – XSLT can be difficult to debug.
Reflection Emit
It is rocket science mixed with the black arts.

• Full representation of physical structure
• Allows building modules and assemblies at
  runtime
   – Transient code only used at runtime
   – Persistent code for reuse
• Create classes, types and emit IL
• Used by .NET compilers to build .NET apps
• Can be as fast as normal code
EnvDTE
• EnvDTE is an assembly-wrapped COM library
  containing the objects and members for Visual
  Studio core automation.

• Using EnvDTE you can develop your own add-
  ins for Visual Studio that can generate code.
CodeDom
• Advantages
  – Allows a single “template” to generate code within several
    target languages, such as VB and C#.
  – Additional language providers can be written to support
    other languages.
  – Proven technology, used by Microsoft for code generation
    in all versions of Visual Studio since .net was released.
• Disadvantages
  – Unable to truly see the “template” within the control logic.
  – Requires a recompile if the “template” should be changed.
  – Very few developers have experience using the CodeDom
    even though it has been with us since the .net framework
    1.0.
Text
Template
Transformation
Toolkit
How T4 Works ?
T4 Tools
• Tangible T4 Editor for Visual Studio 2010
  RTM adds IntelliSense and Syntax Coloring to
  T4 Text Templates.

• T4 Toolbox
T4 Pros and Cons
• Advantages
   – Ability to embed C# control logic within the template.
   – Syntax that will be somewhat familiar to classic ASP developers..
   – Preferred code generation technique for Entity Framework 4.0
     and the Visual Studio 2010 modeling tools., which means lots of
     samples on MSDN, etc.
   – Templates can be precompiled.
• Disadvantages
   – While third parties have written language support for Visual
     Studio no built in support for editing T4 templates exists in
     Visual Studio today.
   – Relatively new technology, therefore not many developers have
     experience with T4 templates.
ReSharper 6.0
           Code Generation

Create from Usage
Generate Type Members
Generate Type Constructor
Generate Properties
Generate Delegating Members
Generate Formatting Members
Generate Equality Members
Implement/Override Methods
Some advices
Shall I Generate Interfaces?
Shall I Generate Interfaces?
No !
Shall I Unit Test generated code ?
• You shouldn’t unit test generated code. You
  may unit test generator instead.
Real World
Case Studies
Case 1: Client – Server Communication



 Existing    Generated     Communication   Generated
                              channel
   API      Server Proxy                   Client Proxy
Legacy API

Adapter
                Case 2: API Wrapper




   Existing
  Application
Case 3: Protocol Parser
Case 4: Model Driven DAL



          Hand written services


                        Generated Repositories


XML                       Generated Entities
Model

                        Partially generated DB
It’s an Engineering, Baby !
Conclusion:
  • Not a silver bullet but another good
  tool;

  • Makes life easier when applied
  properly;

  • Writing generator is much more fun
  than writing boilerplate code;

  • Generated code is easier to debug;

  • You can make huge changes in
  regenerated code easily;
Do try this !
• Code generation can make you flexible and
  responsive. Do try this at home. (Or at work)
Applied Code Generation in .NET

More Related Content

What's hot

Pragmatic Smalltalk
Pragmatic SmalltalkPragmatic Smalltalk
Pragmatic SmalltalkESUG
 
Top programming Languages in software Industry companies
Top programming Languages in software Industry companiesTop programming Languages in software Industry companies
Top programming Languages in software Industry companiesKiran Patil
 
Be armed to the teeth to maintain a high quality iOS code
Be armed to the teeth to maintain a high quality iOS codeBe armed to the teeth to maintain a high quality iOS code
Be armed to the teeth to maintain a high quality iOS codeAnastasia Kazakova
 
Ruby vs Java: Comparing Two Popular Programming Languages For Developing Ente...
Ruby vs Java: Comparing Two Popular Programming Languages For Developing Ente...Ruby vs Java: Comparing Two Popular Programming Languages For Developing Ente...
Ruby vs Java: Comparing Two Popular Programming Languages For Developing Ente...Katy Slemon
 
Rootcon X - Reverse Engineering Swift Applications
Rootcon X - Reverse Engineering Swift ApplicationsRootcon X - Reverse Engineering Swift Applications
Rootcon X - Reverse Engineering Swift Applicationseightbit
 
Wahckon[2] - iOS Runtime Hacking Crash Course
Wahckon[2] - iOS Runtime Hacking Crash CourseWahckon[2] - iOS Runtime Hacking Crash Course
Wahckon[2] - iOS Runtime Hacking Crash Courseeightbit
 
BP203 limitless languages
BP203 limitless languagesBP203 limitless languages
BP203 limitless languagesMark Myers
 
Language Engineering With Xtext
Language Engineering With XtextLanguage Engineering With Xtext
Language Engineering With XtextSven Efftinge
 
Pragmatic DSL Design with Xtext, Xbase and Xtend 2
Pragmatic DSL Design with Xtext, Xbase and Xtend 2Pragmatic DSL Design with Xtext, Xbase and Xtend 2
Pragmatic DSL Design with Xtext, Xbase and Xtend 2Dr. Jan Köhnlein
 
Leveraging more then DDD Lite in the startup project
Leveraging more then DDD Lite in the startup projectLeveraging more then DDD Lite in the startup project
Leveraging more then DDD Lite in the startup projectThomas Jaskula
 
The Ring programming language version 1.6 book - Part 6 of 189
The Ring programming language version 1.6 book - Part 6 of 189The Ring programming language version 1.6 book - Part 6 of 189
The Ring programming language version 1.6 book - Part 6 of 189Mahmoud Samir Fayed
 
Introduction to c_sharp
Introduction to c_sharpIntroduction to c_sharp
Introduction to c_sharpJayanta Basak
 
The Ring programming language version 1.7 book - Part 6 of 196
The Ring programming language version 1.7 book - Part 6 of 196The Ring programming language version 1.7 book - Part 6 of 196
The Ring programming language version 1.7 book - Part 6 of 196Mahmoud Samir Fayed
 
Architecting Domain-Specific Languages
Architecting Domain-Specific LanguagesArchitecting Domain-Specific Languages
Architecting Domain-Specific LanguagesMarkus Voelter
 
From Programming to Modeling And Back Again
From Programming to Modeling And Back AgainFrom Programming to Modeling And Back Again
From Programming to Modeling And Back AgainMarkus Voelter
 

What's hot (20)

P1 2018 python
P1 2018 pythonP1 2018 python
P1 2018 python
 
Pragmatic Smalltalk
Pragmatic SmalltalkPragmatic Smalltalk
Pragmatic Smalltalk
 
Top programming Languages in software Industry companies
Top programming Languages in software Industry companiesTop programming Languages in software Industry companies
Top programming Languages in software Industry companies
 
Be armed to the teeth to maintain a high quality iOS code
Be armed to the teeth to maintain a high quality iOS codeBe armed to the teeth to maintain a high quality iOS code
Be armed to the teeth to maintain a high quality iOS code
 
P1 2017 python
P1 2017 pythonP1 2017 python
P1 2017 python
 
Ruby vs Java: Comparing Two Popular Programming Languages For Developing Ente...
Ruby vs Java: Comparing Two Popular Programming Languages For Developing Ente...Ruby vs Java: Comparing Two Popular Programming Languages For Developing Ente...
Ruby vs Java: Comparing Two Popular Programming Languages For Developing Ente...
 
Rootcon X - Reverse Engineering Swift Applications
Rootcon X - Reverse Engineering Swift ApplicationsRootcon X - Reverse Engineering Swift Applications
Rootcon X - Reverse Engineering Swift Applications
 
Wahckon[2] - iOS Runtime Hacking Crash Course
Wahckon[2] - iOS Runtime Hacking Crash CourseWahckon[2] - iOS Runtime Hacking Crash Course
Wahckon[2] - iOS Runtime Hacking Crash Course
 
BP203 limitless languages
BP203 limitless languagesBP203 limitless languages
BP203 limitless languages
 
Language Engineering With Xtext
Language Engineering With XtextLanguage Engineering With Xtext
Language Engineering With Xtext
 
Cucumber in Practice(en)
Cucumber in Practice(en)Cucumber in Practice(en)
Cucumber in Practice(en)
 
Cucumber_Training_ForQA
Cucumber_Training_ForQACucumber_Training_ForQA
Cucumber_Training_ForQA
 
Pragmatic DSL Design with Xtext, Xbase and Xtend 2
Pragmatic DSL Design with Xtext, Xbase and Xtend 2Pragmatic DSL Design with Xtext, Xbase and Xtend 2
Pragmatic DSL Design with Xtext, Xbase and Xtend 2
 
Leveraging more then DDD Lite in the startup project
Leveraging more then DDD Lite in the startup projectLeveraging more then DDD Lite in the startup project
Leveraging more then DDD Lite in the startup project
 
The Ring programming language version 1.6 book - Part 6 of 189
The Ring programming language version 1.6 book - Part 6 of 189The Ring programming language version 1.6 book - Part 6 of 189
The Ring programming language version 1.6 book - Part 6 of 189
 
Introduction to c_sharp
Introduction to c_sharpIntroduction to c_sharp
Introduction to c_sharp
 
The Ring programming language version 1.7 book - Part 6 of 196
The Ring programming language version 1.7 book - Part 6 of 196The Ring programming language version 1.7 book - Part 6 of 196
The Ring programming language version 1.7 book - Part 6 of 196
 
C c#
C c#C c#
C c#
 
Architecting Domain-Specific Languages
Architecting Domain-Specific LanguagesArchitecting Domain-Specific Languages
Architecting Domain-Specific Languages
 
From Programming to Modeling And Back Again
From Programming to Modeling And Back AgainFrom Programming to Modeling And Back Again
From Programming to Modeling And Back Again
 

Similar to Applied Code Generation in .NET

10 Reasons You MUST Consider Pattern-Aware Programming
10 Reasons You MUST Consider Pattern-Aware Programming10 Reasons You MUST Consider Pattern-Aware Programming
10 Reasons You MUST Consider Pattern-Aware ProgrammingPostSharp Technologies
 
Domain Driven Design Big Picture Strategic Patterns
Domain Driven Design Big Picture Strategic PatternsDomain Driven Design Big Picture Strategic Patterns
Domain Driven Design Big Picture Strategic PatternsMark Windholtz
 
Design Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best PracticesDesign Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best PracticesInductive Automation
 
Design Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best PracticesDesign Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best PracticesInductive Automation
 
Domain specific modelling (DSM)
Domain specific modelling (DSM)Domain specific modelling (DSM)
Domain specific modelling (DSM)PG Scholar
 
Coding Standard And Code Review
Coding Standard And Code ReviewCoding Standard And Code Review
Coding Standard And Code ReviewMilan Vukoje
 
The Architect Way - JSCamp.asia 2012
The Architect Way - JSCamp.asia 2012The Architect Way - JSCamp.asia 2012
The Architect Way - JSCamp.asia 2012Jan Jongboom
 
Modern Web-site Development Pipeline
Modern Web-site Development PipelineModern Web-site Development Pipeline
Modern Web-site Development PipelineGlobalLogic Ukraine
 
Build software like a bag of marbles, not a castle of LEGO®
Build software like a bag of marbles, not a castle of LEGO®Build software like a bag of marbles, not a castle of LEGO®
Build software like a bag of marbles, not a castle of LEGO®Hannes Lowette
 
.Net programming with C#
.Net programming with C#.Net programming with C#
.Net programming with C#NguynSang29
 
Starting from scratch in 2017
Starting from scratch in 2017Starting from scratch in 2017
Starting from scratch in 2017Stefano Bonetta
 
Putting Compilers to Work
Putting Compilers to WorkPutting Compilers to Work
Putting Compilers to WorkSingleStore
 
Continuous Integration
Continuous IntegrationContinuous Integration
Continuous IntegrationXPDays
 
Build software like a bag of marbles, not a castle of LEGO®
Build software like a bag of marbles, not a castle of LEGO®Build software like a bag of marbles, not a castle of LEGO®
Build software like a bag of marbles, not a castle of LEGO®Hannes Lowette
 
Programming Languages #devcon2013
Programming Languages #devcon2013Programming Languages #devcon2013
Programming Languages #devcon2013Iván Montes
 
How to write good quality code
How to write good quality codeHow to write good quality code
How to write good quality codeHayden Bleasel
 

Similar to Applied Code Generation in .NET (20)

10 Reasons You MUST Consider Pattern-Aware Programming
10 Reasons You MUST Consider Pattern-Aware Programming10 Reasons You MUST Consider Pattern-Aware Programming
10 Reasons You MUST Consider Pattern-Aware Programming
 
C#: Past, Present and Future
C#: Past, Present and FutureC#: Past, Present and Future
C#: Past, Present and Future
 
Code Inspection
Code InspectionCode Inspection
Code Inspection
 
Domain Driven Design Big Picture Strategic Patterns
Domain Driven Design Big Picture Strategic PatternsDomain Driven Design Big Picture Strategic Patterns
Domain Driven Design Big Picture Strategic Patterns
 
Design Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best PracticesDesign Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best Practices
 
Design Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best PracticesDesign Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best Practices
 
Domain specific modelling (DSM)
Domain specific modelling (DSM)Domain specific modelling (DSM)
Domain specific modelling (DSM)
 
Coding Standard And Code Review
Coding Standard And Code ReviewCoding Standard And Code Review
Coding Standard And Code Review
 
The Architect Way - JSCamp.asia 2012
The Architect Way - JSCamp.asia 2012The Architect Way - JSCamp.asia 2012
The Architect Way - JSCamp.asia 2012
 
Modern Web-site Development Pipeline
Modern Web-site Development PipelineModern Web-site Development Pipeline
Modern Web-site Development Pipeline
 
Build software like a bag of marbles, not a castle of LEGO®
Build software like a bag of marbles, not a castle of LEGO®Build software like a bag of marbles, not a castle of LEGO®
Build software like a bag of marbles, not a castle of LEGO®
 
.Net programming with C#
.Net programming with C#.Net programming with C#
.Net programming with C#
 
Starting from scratch in 2017
Starting from scratch in 2017Starting from scratch in 2017
Starting from scratch in 2017
 
Putting Compilers to Work
Putting Compilers to WorkPutting Compilers to Work
Putting Compilers to Work
 
Continuous Integration
Continuous IntegrationContinuous Integration
Continuous Integration
 
Build software like a bag of marbles, not a castle of LEGO®
Build software like a bag of marbles, not a castle of LEGO®Build software like a bag of marbles, not a castle of LEGO®
Build software like a bag of marbles, not a castle of LEGO®
 
Programming Languages #devcon2013
Programming Languages #devcon2013Programming Languages #devcon2013
Programming Languages #devcon2013
 
How to write good quality code
How to write good quality codeHow to write good quality code
How to write good quality code
 
Javascript best practices
Javascript best practicesJavascript best practices
Javascript best practices
 
Compilers.pptx
Compilers.pptxCompilers.pptx
Compilers.pptx
 

More from Dmytro Mindra

Introduction to Value Planning for iHUB
Introduction to Value Planning for iHUBIntroduction to Value Planning for iHUB
Introduction to Value Planning for iHUBDmytro Mindra
 
Mastering public speaking skills
Mastering public speaking skillsMastering public speaking skills
Mastering public speaking skillsDmytro Mindra
 
XP Days Ukraine 2014 - Refactoring legacy code
XP Days Ukraine 2014 - Refactoring legacy codeXP Days Ukraine 2014 - Refactoring legacy code
XP Days Ukraine 2014 - Refactoring legacy codeDmytro Mindra
 
Odessa .NET User Group - Kinect v2
Odessa .NET User Group - Kinect v2Odessa .NET User Group - Kinect v2
Odessa .NET User Group - Kinect v2Dmytro Mindra
 
Building Windows Phone 8 Games With Unity3d
Building Windows Phone 8 Games With Unity3dBuilding Windows Phone 8 Games With Unity3d
Building Windows Phone 8 Games With Unity3dDmytro Mindra
 
IT Brunch - SpecFlow and Gherkin by Example
IT Brunch - SpecFlow and Gherkin by ExampleIT Brunch - SpecFlow and Gherkin by Example
IT Brunch - SpecFlow and Gherkin by ExampleDmytro Mindra
 
Odessa Pluralsight Study Group 28.11.2012
Odessa Pluralsight Study Group 28.11.2012Odessa Pluralsight Study Group 28.11.2012
Odessa Pluralsight Study Group 28.11.2012Dmytro Mindra
 
Тестируем код с Visual Studio 2012 - XP Days Ukraine 2012
Тестируем код с Visual Studio 2012 - XP Days Ukraine 2012Тестируем код с Visual Studio 2012 - XP Days Ukraine 2012
Тестируем код с Visual Studio 2012 - XP Days Ukraine 2012Dmytro Mindra
 
Compilable Specifications - XPDays Ukraine 2012
Compilable Specifications - XPDays Ukraine 2012Compilable Specifications - XPDays Ukraine 2012
Compilable Specifications - XPDays Ukraine 2012Dmytro Mindra
 
NetworkUA - 2012 - Introduction TypeScript
NetworkUA - 2012 - Introduction TypeScript NetworkUA - 2012 - Introduction TypeScript
NetworkUA - 2012 - Introduction TypeScript Dmytro Mindra
 
Ciklum .NET Saturday - Introduction to TypeScript
Ciklum .NET Saturday - Introduction to TypeScriptCiklum .NET Saturday - Introduction to TypeScript
Ciklum .NET Saturday - Introduction to TypeScriptDmytro Mindra
 
Lean Lego Game for Agileee 2012
Lean Lego Game for Agileee 2012Lean Lego Game for Agileee 2012
Lean Lego Game for Agileee 2012Dmytro Mindra
 
Lohika .Net Day - What's new in Windows Azure
Lohika .Net Day - What's new in Windows AzureLohika .Net Day - What's new in Windows Azure
Lohika .Net Day - What's new in Windows AzureDmytro Mindra
 
Web В РЕАЛЬНОМ ВРЕМЕНИ С Node.js - AgileBaseCamp - 2012
Web В РЕАЛЬНОМ ВРЕМЕНИ С Node.js - AgileBaseCamp - 2012Web В РЕАЛЬНОМ ВРЕМЕНИ С Node.js - AgileBaseCamp - 2012
Web В РЕАЛЬНОМ ВРЕМЕНИ С Node.js - AgileBaseCamp - 2012Dmytro Mindra
 
Windows Azure & NodeJS Microsoft SWIT 2012
Windows Azure & NodeJS Microsoft SWIT 2012 Windows Azure & NodeJS Microsoft SWIT 2012
Windows Azure & NodeJS Microsoft SWIT 2012 Dmytro Mindra
 
Lean Software Development
Lean Software DevelopmentLean Software Development
Lean Software DevelopmentDmytro Mindra
 
Craftsmanship - XP Days 2011
Craftsmanship - XP Days 2011Craftsmanship - XP Days 2011
Craftsmanship - XP Days 2011Dmytro Mindra
 
IT Brunch - 12.11.2011 - Myths about Design
IT Brunch - 12.11.2011 - Myths about DesignIT Brunch - 12.11.2011 - Myths about Design
IT Brunch - 12.11.2011 - Myths about DesignDmytro Mindra
 

More from Dmytro Mindra (20)

Introduction to Value Planning for iHUB
Introduction to Value Planning for iHUBIntroduction to Value Planning for iHUB
Introduction to Value Planning for iHUB
 
Mastering public speaking skills
Mastering public speaking skillsMastering public speaking skills
Mastering public speaking skills
 
XP Days Ukraine 2014 - Refactoring legacy code
XP Days Ukraine 2014 - Refactoring legacy codeXP Days Ukraine 2014 - Refactoring legacy code
XP Days Ukraine 2014 - Refactoring legacy code
 
Odessa .NET User Group - Kinect v2
Odessa .NET User Group - Kinect v2Odessa .NET User Group - Kinect v2
Odessa .NET User Group - Kinect v2
 
Building Windows Phone 8 Games With Unity3d
Building Windows Phone 8 Games With Unity3dBuilding Windows Phone 8 Games With Unity3d
Building Windows Phone 8 Games With Unity3d
 
IT Brunch - SpecFlow and Gherkin by Example
IT Brunch - SpecFlow and Gherkin by ExampleIT Brunch - SpecFlow and Gherkin by Example
IT Brunch - SpecFlow and Gherkin by Example
 
Odessa Pluralsight Study Group 28.11.2012
Odessa Pluralsight Study Group 28.11.2012Odessa Pluralsight Study Group 28.11.2012
Odessa Pluralsight Study Group 28.11.2012
 
Тестируем код с Visual Studio 2012 - XP Days Ukraine 2012
Тестируем код с Visual Studio 2012 - XP Days Ukraine 2012Тестируем код с Visual Studio 2012 - XP Days Ukraine 2012
Тестируем код с Visual Studio 2012 - XP Days Ukraine 2012
 
Compilable Specifications - XPDays Ukraine 2012
Compilable Specifications - XPDays Ukraine 2012Compilable Specifications - XPDays Ukraine 2012
Compilable Specifications - XPDays Ukraine 2012
 
NetworkUA - 2012 - Introduction TypeScript
NetworkUA - 2012 - Introduction TypeScript NetworkUA - 2012 - Introduction TypeScript
NetworkUA - 2012 - Introduction TypeScript
 
Ciklum .NET Saturday - Introduction to TypeScript
Ciklum .NET Saturday - Introduction to TypeScriptCiklum .NET Saturday - Introduction to TypeScript
Ciklum .NET Saturday - Introduction to TypeScript
 
Lean Lego Game for Agileee 2012
Lean Lego Game for Agileee 2012Lean Lego Game for Agileee 2012
Lean Lego Game for Agileee 2012
 
Lohika .Net Day - What's new in Windows Azure
Lohika .Net Day - What's new in Windows AzureLohika .Net Day - What's new in Windows Azure
Lohika .Net Day - What's new in Windows Azure
 
Web В РЕАЛЬНОМ ВРЕМЕНИ С Node.js - AgileBaseCamp - 2012
Web В РЕАЛЬНОМ ВРЕМЕНИ С Node.js - AgileBaseCamp - 2012Web В РЕАЛЬНОМ ВРЕМЕНИ С Node.js - AgileBaseCamp - 2012
Web В РЕАЛЬНОМ ВРЕМЕНИ С Node.js - AgileBaseCamp - 2012
 
Windows Azure & NodeJS Microsoft SWIT 2012
Windows Azure & NodeJS Microsoft SWIT 2012 Windows Azure & NodeJS Microsoft SWIT 2012
Windows Azure & NodeJS Microsoft SWIT 2012
 
Lean Software Development
Lean Software DevelopmentLean Software Development
Lean Software Development
 
Craftsmanship - XP Days 2011
Craftsmanship - XP Days 2011Craftsmanship - XP Days 2011
Craftsmanship - XP Days 2011
 
Agile architecture
Agile architectureAgile architecture
Agile architecture
 
DCI
DCIDCI
DCI
 
IT Brunch - 12.11.2011 - Myths about Design
IT Brunch - 12.11.2011 - Myths about DesignIT Brunch - 12.11.2011 - Myths about Design
IT Brunch - 12.11.2011 - Myths about Design
 

Recently uploaded

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
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.pdfsudhanshuwaghmare1
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 

Recently uploaded (20)

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
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
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 

Applied Code Generation in .NET

  • 1. APPLIED CODE GENERATION IN .NET Dmytro Mindra Lohika, Odessa
  • 2.
  • 3. What’s the matter ? • We are engineers ! • Engineers’ time is valuable and expensive; • Engineers don’t like repetitive tasks;
  • 4. Task classification • Brains • Experience • Procedures
  • 5. Houston, we’ve got a problem ! Our business domain contains 500+ entities. Each entity needs CRUD.
  • 6. Houston, we’ve got a problem ! And you have lots of time. The whole 4 months. For your big team of 4 developers that should not be a problem !
  • 7. Houston, we’ve got a problem ! Oh, and we’re not sure which parts will stay generic and which won’t
  • 8. Houston, we’ve got a problem ! Be agile, don’t wait for the analysts to finish their job, because we don’t have that kind of time. Just change your code when the Requirements are finished.
  • 9. Houston, we’ve got a problem ! For each domain entity we should have • Stored Procedures • Repository • Service • Controller • Views • etc That’s about 1000 lines of code per entity.
  • 10. Houston, we’ve got a problem ! But we have 500+ entities 500*1000 = 500000 lines of code. Who wants to type this in ?
  • 11. Houston, we’ve got a problem ! • And when the changes arrive someone should make corrections to 500*1000 lines of code.
  • 12. What are the solutions ? • Hand-code everything (and every change) – Hire a lot of monkeys coders • Design everything generically, correctly the first time – Mission impossible • Use only code generation – And spend your life changing generator to match all possible requirements • Use combination of tools including code generation. – This seems reasonable
  • 13. Boilerplate • Interestingly, the term (boilerplate) arose from the newspaper business. Columns and other pieces that were syndicated were sent out to subscribing newspapers in the form of a mat (i.e. a matrix). Once received, boiling lead was poured into this mat to create the plate used to print the piece, hence the name boilerplate. As the article printed on a boilerplate could not be altered, the term came to be used by attorneys to refer to the portions of a contract which did not change through repeated uses in different applications, and finally to language in general which did not change in any document that was used repeatedly for different occasions.
  • 14.
  • 15. CODE GENERATION is code that writes code
  • 16. Some common terms • Code generation • Automatic programming • Generative programming
  • 20. Generator Input Code Output Generator
  • 21. Why CG? • Productivity • Quality • Consistency • Abstraction
  • 22.
  • 23. PROS • Code uniformity • Easy to debug • Easy to introduce huge changes • No more boilerplate code
  • 24. CONS • Someone should maintain the generator • Generator has learning curve • Generator usually has limitations
  • 25. Applications • Database Access • Generate Test Data • Generate Integration Tests • User Interface • Documentation • Unit tests • File Formats • Web services • Business logic • DLL Wrappers • Firewall configuration • Website configuration • Looking for localizable strings
  • 26. Code Generation is Fun ? • CG makes boring job for you • Writing generator is fun • Once written generator works for you • You can experiment with different implementations by modifying generator and regeneration the code. • While writing the generator you get deeper into the technology instead of doing dull job.
  • 27. Scaffolding and prototyping • Code generation can help you to build fast prototypes.
  • 29. Rules 1. Give the proper respect to hand-coding 2. Handwrite the code first 3. Control the source code 4. Make a considered decision about the implementation language 5. Integrate the generator into the development process
  • 30. Rules 6. Include warnings 7. Make it friendly 8. Include documentation 9. Keep in mind that generation is a cultural issue 10. Maintain the generator
  • 31. A note about DSL A domain-specific language (DSL) is a programming language or specification language dedicated to a particular problem domain
  • 33.
  • 34. Model Driven Architecture • Code generation has a dramatic impact on development time and engineering productivity. • The application is amenable to change on a large scale. • The business rules are abstracted into files that are free of language or framework details that would hinder portability. • The code for the application is of consistently high quality across the code base.
  • 35. Benefits of MDA • Quality • Consistency • A single point of knowledge • More design time • Design decisions that stand out
  • 39. Consider this: • Code generation has a large initial schedule overhead; • Code generators are ideal for well-known large- scale problems; • Code generation is powerful when used appropriately; • Always keep in mind code generation limitations!
  • 40. Code Generation Skills • Text Templates • Regular Expressions • XML Parsing • Reflection
  • 42. Available tools • StringBuilder • CodeSnippets • XSLT • Reflection Emit • EnvDTE • CodeDom • T4 • … (Python, Ruby,
  • 43. StringBuilder • Advantages – Almost all .net developers should feel comfortable using the StringBuilder class so it requires no additional languages / tools to learn. – Even with the disadvantages, the StringBuilder can be an excellent choice if you need to generate code quickly. Especially if you don’t need to maintain the “template” long term. • Disadvantages – Unable to truly see the “template” within the control logic. – Requires a recompile if the “template” should be changed.
  • 44. Code Snippets • Advantages – Simple Xml based template with numerous samples provided within Visual Studio. – Several open source code snippet libraries available. • Disadvantages – Limited snippet functions and at the present time developers are unable to author additional snippet functions!
  • 45. XSLT • Advantages – Xml based template. – Simple code generation technique for those developers comfortable with XSLT transformations. • Disadvantages – While Xml is a relatively simple technology, XSLT has been known to bring grown men to tears! – XSLT can be difficult to debug.
  • 46. Reflection Emit It is rocket science mixed with the black arts. • Full representation of physical structure • Allows building modules and assemblies at runtime – Transient code only used at runtime – Persistent code for reuse • Create classes, types and emit IL • Used by .NET compilers to build .NET apps • Can be as fast as normal code
  • 47. EnvDTE • EnvDTE is an assembly-wrapped COM library containing the objects and members for Visual Studio core automation. • Using EnvDTE you can develop your own add- ins for Visual Studio that can generate code.
  • 48. CodeDom • Advantages – Allows a single “template” to generate code within several target languages, such as VB and C#. – Additional language providers can be written to support other languages. – Proven technology, used by Microsoft for code generation in all versions of Visual Studio since .net was released. • Disadvantages – Unable to truly see the “template” within the control logic. – Requires a recompile if the “template” should be changed. – Very few developers have experience using the CodeDom even though it has been with us since the .net framework 1.0.
  • 51. T4 Tools • Tangible T4 Editor for Visual Studio 2010 RTM adds IntelliSense and Syntax Coloring to T4 Text Templates. • T4 Toolbox
  • 52. T4 Pros and Cons • Advantages – Ability to embed C# control logic within the template. – Syntax that will be somewhat familiar to classic ASP developers.. – Preferred code generation technique for Entity Framework 4.0 and the Visual Studio 2010 modeling tools., which means lots of samples on MSDN, etc. – Templates can be precompiled. • Disadvantages – While third parties have written language support for Visual Studio no built in support for editing T4 templates exists in Visual Studio today. – Relatively new technology, therefore not many developers have experience with T4 templates.
  • 53. ReSharper 6.0 Code Generation Create from Usage Generate Type Members Generate Type Constructor Generate Properties Generate Delegating Members Generate Formatting Members Generate Equality Members Implement/Override Methods
  • 55. Shall I Generate Interfaces?
  • 56. Shall I Generate Interfaces? No !
  • 57. Shall I Unit Test generated code ? • You shouldn’t unit test generated code. You may unit test generator instead.
  • 59. Case 1: Client – Server Communication Existing Generated Communication Generated channel API Server Proxy Client Proxy
  • 60. Legacy API Adapter Case 2: API Wrapper Existing Application
  • 62. Case 4: Model Driven DAL Hand written services Generated Repositories XML Generated Entities Model Partially generated DB
  • 63. It’s an Engineering, Baby ! Conclusion: • Not a silver bullet but another good tool; • Makes life easier when applied properly; • Writing generator is much more fun than writing boilerplate code; • Generated code is easier to debug; • You can make huge changes in regenerated code easily;
  • 64. Do try this ! • Code generation can make you flexible and responsive. Do try this at home. (Or at work)