SlideShare a Scribd company logo
Metaprogramming in
.NET
Jason Bock
Practice Lead
»http://www.magenic.com
»http://www.jasonbock.net
»https://www.twitter.com/jasonbock
»https://www.github.com/jasonbock
»jasonb@magenic.com
Personal Info
https://github.com/JasonBock
Downloads
»Definitions
»Reflection
»Snippets
»Expressions
»Modification
»Compilation
Overview
Remember…
https://github.com/JasonBock
Definitions
http://kauilapele.files.wordpress.com/2011/11/magic.gif
Definitions
http://en.wikipedia.org/wiki/Metaprogramming
Metaprogramming:The writing of
computer programs that write or
manipulate other programs (or
themselves) as their data, or that do
part of the work at compile time that
would otherwise be done at runtime.
Definitions
http://manning.com/hazzard/
Definitions
http://manning.com/hazzard/
“The meta prefix can mean changed
or higher. It can also mean after or
beside, depending on the context. All
of those terms describe … various
forms of metaprogramming.”
Definitions
http://1.bp.blogspot.com/-MoYos-iLGR0/Tclyxk6kH6I/AAAAAAAAF08/8aX2fOxBKlo/s1600/magical-merlin-sundara-
fawn.jpg
dynamic x = Program.Create();
x.MyProperty = 42;
x.Calculate();
Definitions
http://1.bp.blogspot.com/-MoYos-iLGR0/Tclyxk6kH6I/AAAAAAAAF08/8aX2fOxBKlo/s1600/magical-merlin-sundara-
fawn.jpg
var x = 40;
eval('x = x + 2');
Definitions
http://www.wired.com/images_blogs/photos/uncategorized/2008/04/15/complexity.jpg
Definitions
http://www.machinemart.co.uk/images/library/range/large/1010.jpg
Definitions
http://www.machinemart.co.uk/images/library/range/large/1010.jpg
…if you’ve come this far, maybe you’re
willing to come a little further.
Reflection
http://scarlettlibrarian.files.wordpress.com/2010/12/reflection.jpg
Reflection
[TestClass]
public class MyTests
{
[TestMethod]
public void MyTest() { }
[TestMethod]
public void AnotherTest() { }
}
Find test classes
MyTests
Find test methods
MyTest
AnotherTest
Reflection
public class AClass {}
public class AnotherClass {}
public class MyClass
{
public void MyMethod(string arg1,
Guid arg2) { ... }
}
Reflection
Assembly
TypeTypeType
MethodBase
ParameterInfoParameterInfo
Reflection
MyAssembly
AnotherClassMyClassAClass
MyMethod
arg2arg1
Reflection
var arg2Type = typeof(MyClass)
.GetMethod("MyMethod")
.GetParameters()[1].ParameterType;
Reflection
var mine = new MyClass();
var invoke = typeof(MyClass)
.GetMethod("MyMethod")
.Invoke(mine, new object[]
{ "data", Guid.NewGuid() });
Reflection
http://www.theawall.com/images/blog/time.jpg
Demo: Automatically Adding Business
Rules
Metaprogramming in .NET
Snippets
http://osx.wdfiles.com/local--files/icon:snippet/Snippet.png
Snippets
Snippets
Demo: ArgumentNullException Code
Snippet
Metaprogramming in .NET
Expressions
Expressions
Expressions
public sealed class NotNullAttribute :
InjectorAttribute<ParameterDefinition>{}
Expressions
»System.Reflection.Emit
»DynamicMethod
Expressions
http://www.theawall.com/images/blog/time.jpg
Expressions
public string SayHello()
{
return "Hello";
}
Expressions
.method public hidebysig instance string
SayHello() cil managed
{
.maxstack 8
ldstr "Hello"
ret
}
Expressions
.method public hidebysig instance string
SayHello() cil managed
{
.maxstack 8
ret
}
Expressions
*
3 x
/
2
+
4
f(x) = ((3 * x) / 2) + 4
Expressions
var method = new DynamicMethod("m",
typeof(double), new Type[] { typeof(double) });
var parameter = method.DefineParameter(
1, ParameterAttributes.In, "x");
var generator = method.GetILGenerator();
generator.Emit(OpCodes.Ldc_R8, 3d);
generator.Emit(OpCodes.Ldarg_0);
generator.Emit(OpCodes.Mul);
generator.Emit(OpCodes.Ldc_R8, 2d);
generator.Emit(OpCodes.Div);
generator.Emit(OpCodes.Ldc_R8, 4d);
generator.Emit(OpCodes.Add);
generator.Emit(OpCodes.Ret);
var compiledMethod = method.CreateDelegate(
typeof(Func<double, double>)) as Func<double, double>;
Expressions
var parameter =
Expression.Parameter(typeof(double));
var method = Expression.Lambda(
Expression.Add(
Expression.Divide(
Expression.Multiply(
Expression.Constant(3d), parameter),
Expression.Constant(2d)),
Expression.Constant(4d)),
parameter).Compile() as Func<double, double>;
Expressions
var propertyName = this.GetPropertyName(
_ => _.FirstName);
// Or, in C#6...
// var propertyName =
// nameof(this.FirstName);
Demo: Evolving Code
Metaprogramming in .NET
Modification
[MaximumCalls(2)]
public void MyMethod { }
Modification
private int myMethodCalls;
[MaximumCalls(2)]
public void MyMethod
{
if(this.myMethodCalls < 2)
{
//...
this.myMethodCalls++;
}
}
Demo: Injectors
Metaprogramming in .NET
Compilation
Compilation
SyntaxTree
API
Symbol API Binding and Flow API EmitAPI
https://github.com/dotnet/roslyn
Compilation
ITest
CallMe()
var rock = new Rock<ITest>;
rock.HandleAction<int>(
_ => _.CallMe(),
() => { return 42; });
var chunk = rock.Make();
chunk.CallMe();
Rock841914
: ITest
Compilation
http://phillbarron.files.wordpress.com/2012/01/confused.jpg
Compilation
Demo: Rocks
Metaprogramming in .NET
Summary
»What didn’t I cover?
› CodeDom
› T4
› Reflection.Emit
› CCI (like Cecil) (http://ccimetadata.codeplex.com/)
› dynamic, ExpandoObject
› Clay (http://clay.codeplex.com/), Gemini (http://amirrajan.net/Oak/)
Summary
http://upload.wikimedia.org/wikipedia/commons/d/de/CERO_fear.png
Summary
http://upload.wikimedia.org/wikipedia/commons/d/de/CERO_fear.png
Metaprogramming in
.NET
Jason Bock
Practice Lead
Remember…
 https://github.com/JasonBock (see notes for specific repos)
 http://www.slideshare.net/jasonbock/metaprogramming-in-net
 References in the notes on this slide

More Related Content

What's hot

Maintainable JavaScript 2011
Maintainable JavaScript 2011Maintainable JavaScript 2011
Maintainable JavaScript 2011
Nicholas Zakas
 
ReactJS for Programmers
ReactJS for ProgrammersReactJS for Programmers
ReactJS for Programmers
David Rodenas
 
My java file
My java fileMy java file
My java file
Anamika Chauhan
 
Talk about Testing at vienna.rb meetup #2 on Apr 12th, 2013
Talk about Testing at vienna.rb meetup #2 on Apr 12th, 2013Talk about Testing at vienna.rb meetup #2 on Apr 12th, 2013
Talk about Testing at vienna.rb meetup #2 on Apr 12th, 2013
Anton Bangratz
 
Inside PyMongo - MongoNYC
Inside PyMongo - MongoNYCInside PyMongo - MongoNYC
Inside PyMongo - MongoNYC
Mike Dirolf
 
201913046 wahyu septiansyah network programing
201913046 wahyu septiansyah network programing201913046 wahyu septiansyah network programing
201913046 wahyu septiansyah network programing
wahyuseptiansyah
 
Your code are my tests
Your code are my testsYour code are my tests
Your code are my tests
Michelangelo van Dam
 
ES3-2020-07 Testing techniques
ES3-2020-07 Testing techniquesES3-2020-07 Testing techniques
ES3-2020-07 Testing techniques
David Rodenas
 
TDD CrashCourse Part5: Testing Techniques
TDD CrashCourse Part5: Testing TechniquesTDD CrashCourse Part5: Testing Techniques
TDD CrashCourse Part5: Testing Techniques
David Rodenas
 
2013-06-15 - Software Craftsmanship mit JavaScript
2013-06-15 - Software Craftsmanship mit JavaScript2013-06-15 - Software Craftsmanship mit JavaScript
2013-06-15 - Software Craftsmanship mit JavaScript
Johannes Hoppe
 
2013-06-24 - Software Craftsmanship with JavaScript
2013-06-24 - Software Craftsmanship with JavaScript2013-06-24 - Software Craftsmanship with JavaScript
2013-06-24 - Software Craftsmanship with JavaScript
Johannes Hoppe
 
Beautiful java script
Beautiful java scriptBeautiful java script
Beautiful java script
Ürgo Ringo
 
PHP 5 Magic Methods
PHP 5 Magic MethodsPHP 5 Magic Methods
PHP 5 Magic Methods
David Stockton
 
Rethrowing exception- JAVA
Rethrowing exception- JAVARethrowing exception- JAVA
Rethrowing exception- JAVA
Rajan Shah
 
Shipping Pseudocode to Production VarnaLab
Shipping Pseudocode to Production VarnaLabShipping Pseudocode to Production VarnaLab
Shipping Pseudocode to Production VarnaLab
Dobromir Nikolov
 
Java Bytecode For Discriminating Developers - GeeCON 2011
Java Bytecode For Discriminating Developers - GeeCON 2011Java Bytecode For Discriminating Developers - GeeCON 2011
Java Bytecode For Discriminating Developers - GeeCON 2011
Anton Arhipov
 
ATG Advanced RQL
ATG Advanced RQLATG Advanced RQL
ATG Advanced RQL
Kate Semizhon
 
CLR Exception Handing And Memory Management
CLR Exception Handing And Memory ManagementCLR Exception Handing And Memory Management
CLR Exception Handing And Memory Management
Shiny Zhu
 
Clean Code - A&BP CC
Clean Code - A&BP CCClean Code - A&BP CC
Clean Code - A&BP CC
JWORKS powered by Ordina
 
UA testing with Selenium and PHPUnit - PFCongres 2013
UA testing with Selenium and PHPUnit - PFCongres 2013UA testing with Selenium and PHPUnit - PFCongres 2013
UA testing with Selenium and PHPUnit - PFCongres 2013
Michelangelo van Dam
 

What's hot (20)

Maintainable JavaScript 2011
Maintainable JavaScript 2011Maintainable JavaScript 2011
Maintainable JavaScript 2011
 
ReactJS for Programmers
ReactJS for ProgrammersReactJS for Programmers
ReactJS for Programmers
 
My java file
My java fileMy java file
My java file
 
Talk about Testing at vienna.rb meetup #2 on Apr 12th, 2013
Talk about Testing at vienna.rb meetup #2 on Apr 12th, 2013Talk about Testing at vienna.rb meetup #2 on Apr 12th, 2013
Talk about Testing at vienna.rb meetup #2 on Apr 12th, 2013
 
Inside PyMongo - MongoNYC
Inside PyMongo - MongoNYCInside PyMongo - MongoNYC
Inside PyMongo - MongoNYC
 
201913046 wahyu septiansyah network programing
201913046 wahyu septiansyah network programing201913046 wahyu septiansyah network programing
201913046 wahyu septiansyah network programing
 
Your code are my tests
Your code are my testsYour code are my tests
Your code are my tests
 
ES3-2020-07 Testing techniques
ES3-2020-07 Testing techniquesES3-2020-07 Testing techniques
ES3-2020-07 Testing techniques
 
TDD CrashCourse Part5: Testing Techniques
TDD CrashCourse Part5: Testing TechniquesTDD CrashCourse Part5: Testing Techniques
TDD CrashCourse Part5: Testing Techniques
 
2013-06-15 - Software Craftsmanship mit JavaScript
2013-06-15 - Software Craftsmanship mit JavaScript2013-06-15 - Software Craftsmanship mit JavaScript
2013-06-15 - Software Craftsmanship mit JavaScript
 
2013-06-24 - Software Craftsmanship with JavaScript
2013-06-24 - Software Craftsmanship with JavaScript2013-06-24 - Software Craftsmanship with JavaScript
2013-06-24 - Software Craftsmanship with JavaScript
 
Beautiful java script
Beautiful java scriptBeautiful java script
Beautiful java script
 
PHP 5 Magic Methods
PHP 5 Magic MethodsPHP 5 Magic Methods
PHP 5 Magic Methods
 
Rethrowing exception- JAVA
Rethrowing exception- JAVARethrowing exception- JAVA
Rethrowing exception- JAVA
 
Shipping Pseudocode to Production VarnaLab
Shipping Pseudocode to Production VarnaLabShipping Pseudocode to Production VarnaLab
Shipping Pseudocode to Production VarnaLab
 
Java Bytecode For Discriminating Developers - GeeCON 2011
Java Bytecode For Discriminating Developers - GeeCON 2011Java Bytecode For Discriminating Developers - GeeCON 2011
Java Bytecode For Discriminating Developers - GeeCON 2011
 
ATG Advanced RQL
ATG Advanced RQLATG Advanced RQL
ATG Advanced RQL
 
CLR Exception Handing And Memory Management
CLR Exception Handing And Memory ManagementCLR Exception Handing And Memory Management
CLR Exception Handing And Memory Management
 
Clean Code - A&BP CC
Clean Code - A&BP CCClean Code - A&BP CC
Clean Code - A&BP CC
 
UA testing with Selenium and PHPUnit - PFCongres 2013
UA testing with Selenium and PHPUnit - PFCongres 2013UA testing with Selenium and PHPUnit - PFCongres 2013
UA testing with Selenium and PHPUnit - PFCongres 2013
 

Similar to Metaprogramming in .NET

Relevance trilogy may dream be with you! (dec17)
Relevance trilogy  may dream be with you! (dec17)Relevance trilogy  may dream be with you! (dec17)
Relevance trilogy may dream be with you! (dec17)
Woonsan Ko
 
Powerful persistence layer with Google Guice & MyBatis
Powerful persistence layer with Google Guice & MyBatisPowerful persistence layer with Google Guice & MyBatis
Powerful persistence layer with Google Guice & MyBatis
simonetripodi
 
Metaprogramming
MetaprogrammingMetaprogramming
Metaprogramming
Mehmet Emin İNAÇ
 
10 ways to make your code rock
10 ways to make your code rock10 ways to make your code rock
10 ways to make your code rock
martincronje
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury
 
Tornadoweb
TornadowebTornadoweb
Tornadoweb
Osman Yuksel
 
Catch a spider monkey
Catch a spider monkeyCatch a spider monkey
Catch a spider monkey
ChengHui Weng
 
Dlr
DlrDlr
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Tsuyoshi Yamamoto
 
React mit TypeScript – eine glückliche Ehe
React mit TypeScript – eine glückliche EheReact mit TypeScript – eine glückliche Ehe
React mit TypeScript – eine glückliche Ehe
inovex GmbH
 
Static Analysis in IDEA
Static Analysis in IDEAStatic Analysis in IDEA
Static Analysis in IDEA
HamletDRC
 
前端概述
前端概述前端概述
前端概述
Ethan Zhang
 
Multilingualism makes better programmers
Multilingualism makes better programmersMultilingualism makes better programmers
Multilingualism makes better programmers
Alexander Varwijk
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLs
intelliyole
 
Deploying Machine Learning Models to Production
Deploying Machine Learning Models to ProductionDeploying Machine Learning Models to Production
Deploying Machine Learning Models to Production
Anass Bensrhir - Senior Data Scientist
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for Joomla
Luke Summerfield
 
Red Hat Agile integration Workshop Labs
Red Hat Agile integration Workshop LabsRed Hat Agile integration Workshop Labs
Red Hat Agile integration Workshop Labs
Judy Breedlove
 
From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)
Jose Manuel Pereira Garcia
 
Backbone Basics with Examples
Backbone Basics with ExamplesBackbone Basics with Examples
Backbone Basics with Examples
Sergey Bolshchikov
 
dojo.Patterns
dojo.Patternsdojo.Patterns
dojo.Patterns
Peter Higgins
 

Similar to Metaprogramming in .NET (20)

Relevance trilogy may dream be with you! (dec17)
Relevance trilogy  may dream be with you! (dec17)Relevance trilogy  may dream be with you! (dec17)
Relevance trilogy may dream be with you! (dec17)
 
Powerful persistence layer with Google Guice & MyBatis
Powerful persistence layer with Google Guice & MyBatisPowerful persistence layer with Google Guice & MyBatis
Powerful persistence layer with Google Guice & MyBatis
 
Metaprogramming
MetaprogrammingMetaprogramming
Metaprogramming
 
10 ways to make your code rock
10 ways to make your code rock10 ways to make your code rock
10 ways to make your code rock
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Tornadoweb
TornadowebTornadoweb
Tornadoweb
 
Catch a spider monkey
Catch a spider monkeyCatch a spider monkey
Catch a spider monkey
 
Dlr
DlrDlr
Dlr
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
 
React mit TypeScript – eine glückliche Ehe
React mit TypeScript – eine glückliche EheReact mit TypeScript – eine glückliche Ehe
React mit TypeScript – eine glückliche Ehe
 
Static Analysis in IDEA
Static Analysis in IDEAStatic Analysis in IDEA
Static Analysis in IDEA
 
前端概述
前端概述前端概述
前端概述
 
Multilingualism makes better programmers
Multilingualism makes better programmersMultilingualism makes better programmers
Multilingualism makes better programmers
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLs
 
Deploying Machine Learning Models to Production
Deploying Machine Learning Models to ProductionDeploying Machine Learning Models to Production
Deploying Machine Learning Models to Production
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for Joomla
 
Red Hat Agile integration Workshop Labs
Red Hat Agile integration Workshop LabsRed Hat Agile integration Workshop Labs
Red Hat Agile integration Workshop Labs
 
From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)
 
Backbone Basics with Examples
Backbone Basics with ExamplesBackbone Basics with Examples
Backbone Basics with Examples
 
dojo.Patterns
dojo.Patternsdojo.Patterns
dojo.Patterns
 

Recently uploaded

The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024
Yara Milbes
 
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
Luigi Fugaro
 
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
gapen1
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
Remote DBA Services
 
Kubernetes at Scale: Going Multi-Cluster with Istio
Kubernetes at Scale:  Going Multi-Cluster  with IstioKubernetes at Scale:  Going Multi-Cluster  with Istio
Kubernetes at Scale: Going Multi-Cluster with Istio
Severalnines
 
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptxOperational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
sandeepmenon62
 
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSISDECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
Tier1 app
 
Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !
Marcin Chrost
 
Oracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptxOracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptx
Remote DBA Services
 
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
kalichargn70th171
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
dakas1
 
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Paul Brebner
 
Modelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - AmsterdamModelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - Amsterdam
Alberto Brandolini
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
Grant Fritchey
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
Patrick Weigel
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
dakas1
 
DevOps Consulting Company | Hire DevOps Services
DevOps Consulting Company | Hire DevOps ServicesDevOps Consulting Company | Hire DevOps Services
DevOps Consulting Company | Hire DevOps Services
seospiralmantra
 
Liberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptxLiberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptx
Massimo Artizzu
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
ICS
 

Recently uploaded (20)

The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024
 
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
 
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
 
Kubernetes at Scale: Going Multi-Cluster with Istio
Kubernetes at Scale:  Going Multi-Cluster  with IstioKubernetes at Scale:  Going Multi-Cluster  with Istio
Kubernetes at Scale: Going Multi-Cluster with Istio
 
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptxOperational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
 
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSISDECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
 
Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !
 
Oracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptxOracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptx
 
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
 
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
 
Modelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - AmsterdamModelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - Amsterdam
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
 
DevOps Consulting Company | Hire DevOps Services
DevOps Consulting Company | Hire DevOps ServicesDevOps Consulting Company | Hire DevOps Services
DevOps Consulting Company | Hire DevOps Services
 
Liberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptxLiberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptx
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
 

Metaprogramming in .NET

Editor's Notes

  1. It’s all magic….but not really 
  2. This is a pretty typical definition of metaprogramming.
  3. So I co-authored a book… 
  4. This is the definition I used in my book, but what does it mean? Let’s look at a couple of simple examples.
  5. With C# 4, you can use the dynamic keyword to manipulate members at runtime.
  6. In JavaScript, you can write code as a string, and have the JS environment evaluate the code for you (though eval is considered ‘evil’)
  7. Metaprogramming can be viewed as taking complex code, and reducing its visibility. There’s still complex things to be done, but metaprogramming techniques can reduce it and lead you to a design where it’s relatively easy to manage
  8. You’re going to acquire a new set of tools. Used wisely, it can make your programming life easier.
  9. Doing metaprogramming in .NET requires some dedication to learn new ideas, use frameworks that may be unfamiliar, etc. However, keep at it. The further you go, the easier it becomes, and you’ll start to see your programs in a whole new way.
  10. Reflection provides you to find out information about your code, and execute it if you want.
  11. A testing framework uses reflection to find all of the test classes and test methods.
  12. Here’s a simple piece of code, let’s look at how it would be represented in a Reflection graph
  13. You have an assembly, types, methods, parameters, as well as events, properties, etc.
  14. Here’s what that code sample looks like with its names.
  15. If you’d want to get the type of the 2nd argument, here’s the code.
  16. If you wanted to invoke a method on an object, here’s the code
  17. While Reflection is a powerful tool for metaprogramming, it can be slow. Always consider performance when using Reflection.
  18. You can generate code based on a template in Visual Studio. These are called Code Snippets
  19. Once you create the snippet, you can import it via the Code Snippets Manager
  20. And then use it in your code
  21. How do I make a code snippet for ArgumentNullException?
  22. There’s a tool called ILDasm that’s been in the .NET installation since 1.0. It lets you see the guts of an assembly at its metadata level…
  23. ….and at the IL level.
  24. With IL knowledge, you can do all sorts of tricks that C# or VB don’t support. For example, you can create generic attributes that can be consumed by C# and VB.
  25. Knowing IL is required if you want to run new code at runtime. If you wanted to create a new type, SRE was the way to do it. If you just needed a new method, use DynamicMethod (added in 2.0)
  26. With SRE, you can create dynamic proxies, which are used extensively by mocking engines.
  27. So what the issue with IL? It’s harder to understand, and it’s pretty easy to mess up. Take this simple function.
  28. Here’s the same function in IL.
  29. If the ldstr op code is gone, it’ll probably compile in ilasm, but running it will create all sorts of issues (e.g. InvalidProgramException)
  30. Expressions allow you to view your code as a data structure – a tree. Basing an API on that can make it safer to generate code.
  31. Here’s what that function looks like as a dynamic method
  32. Here’s what it looks like using the LINQ expressions API.
  33. We’ve all seen the property name trick, which uses LINQ expressions. It’s a little slower, but it’s “safe”. But there’s some really cool things you can do with expressions, like genetic programming.
  34. While C# doesn’t support AOP out-of-box, it’s possible through assembly parsing frameworks like Cecil or CCI to add aspects via the presence of attributes.
  35. But you need good debugging experience
  36. Traditionally, compilers are black boxes. You don’t get access to what’s going on, and there’s lot of valuable information within.
  37. Roslyn opens up the compiler, providing APIs to different parts of the pipeline.
  38. There’s lot of crazy things you can do if you can compile code on the fly. Let’s create a dynamic class that is a mock of another class (useful for testing)
  39. Makes total sense, right? 
  40. But I can take the generated proxy class, save it to disk, and step into the code
  41. Knowing IL is required if you want to run new code at runtime. If you wanted to create a new type, SRE was the way to do it. If you just needed a new method, use DynamicMethod (added in 2.0)
  42. Don’t fear metaprogramming. The tools may be a little more advanced than unusual, and you may need to invest some time, but it’s worth it.
  43. Embrace metaprogramming. It’ll make your coding peaceful 
  44. GitHub repos Csla.AutoAddBusinessRules CodeSnippets ExpressionEvolver Injectors Rocks References Code Snippets (C#) - https://msdn.microsoft.com/en-us/library/f7d3wz0k(v=vs.90).aspx Creating and Using IntelliSense Code Snippets - https://msdn.microsoft.com/en-us/library/vstudio/ms165392(v=vs.100).aspx Comparison of code generation tools - http://en.wikipedia.org/wiki/Comparison_of_code_generation_tools Sigil: Adding Some (More) Magic To IL - http://kevinmontrose.com/2013/02/14/sigil-adding-some-more-magic-to-il/ Visual Studio Code Snippets - http://visualstudiocodesnippets.com/ Visual Studio code snippets - http://www.codeproject.com/Articles/737354/Visual-Studio-code-snippets