SlideShare a Scribd company logo
1 of 20
Code Generation for Azure with
.NET
Marco Parenzan
marcoparenzan/CodeGenerationForAzureWithDotNet (github.com)
Senior Solution Architect in beanTech
Microsoft Azure MVP
Community Lead 1nn0va // Pordenone
1nn0va After Hour
https://bit.ly/1nn0va-video
Linkedin: https://www.linkedin.com/in/marcoparenzan/
Marco Parenzan
Code Generation for Azure with
.NET
Marco Parenzan
marcoparenzan/CodeGenerationForAzureWithDotNet (github.com)
So another story from my love
for (un)successfull/(un)tested(?) technologies 
• Faster upgrades
• Framework (.NET 6.0 anyone?)
• Cloud Services
• Enforce (best) practices
• Increase maintainability
Challenges for the modern cloud company
• Service vs. Web Service
• Servicebusiness logic
• Web Serviceprotocol adaptation
• HTTPS vs GRPC
• Azure Function vs. API App
• Develop in front of a component
• Better testing
• Single Responsability Principle!
• Business logic and protocol adaptation are two responsabilities
Value vs. Not Value
• “Code that generates code…”
• Reflection
• Powerful
• Difficult to maintain
• Difficult to customize
• DSL
• Powerful
• Difficult to maintain
• Risk to customize
• Code Generation
• Powerful
• Simpler to maintain
• Simpler(?) to customize
Dynamic (Meta)Programming
• Text-based code generation
• T4
• Yeoman
• Razor
• Roslyn-based code generation
Code Generation Tecniques
Roslyn C# compiler generation (C#
6.x+)
CSC/VBC IL
AST
AST AST
Opening up the compiler
• Roslyn packages
• Visual Studio Integration (analyzer)
The toolbox
Building your own Fix
var value = 1 + 2;
ExpressionSyntax
SyntaxToken
SyntaxTrivia
var equalsValue =
SyntaxFactory.EqualsValueClause(
SyntaxFactory.BinaryExpression(
SyntaxKind.AddExpression,
SyntaxFactory.LiteralExpression(
SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(1)),
SyntaxFactory.LiteralExpression(
SyntaxKind.NumericLiteralExpression,SyntaxFactory.Literal(2))
));
var typeSyntax =
SyntaxFactory.VariableDeclaration(
SyntaxFactory.ParseTypeName("var"),
new SeparatedSyntaxList<VariableDeclaratorSyntax>()
.Add(SyntaxFactory.VariableDeclarator(“value")
.WithInitializer(equalsValue)))
.NormalizeWhitespace(" ")
.WithAdditionalAnnotations(Formatter.Annotation);
var declaration = SyntaxFactory.LocalDeclarationStatement(typeSyntax);
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class WebApiControllerNamingConventionAnalyzer :
DiagnosticAnalyzer
{
string DiagnosticId = “WA0001";
string Description = "Controller type should end in 'Controller'";
string MessageFormat = "Type name '{0}' does not end in Controller";
internal const string Category = "Naming";
private static DiagnosticDescriptor Rule = new DiagnosticDescriptor(
DiagnosticId, Description, MessageFormat, Category,
DiagnosticSeverity.Warning, true);
// Add implementation
}
private void Analyzer(SymbolAnalysisContext
context)
{
var symbol = (INamedTypeSymbol)context.Symbol;
if (symbol.BaseType == null) return;
if ((symbol.BaseType.Name == "Controller"
|| symbol.BaseType.Name == "ApiController")
&& !symbol.Name.EndsWith("Controller"))
{
var diagnostic = Diagnostic.Create(
Rule, symbol.Locations[0],
symbol.Name);
context.ReportDiagnostic(diagnostic);
}
}
Custom Diagnostic - Analyzer
var script = CSharpScript.Create<int>("int x = 1;")
.ContinueWith("int y = 2;")
.ContinueWith("x + y");
Assert.AreEqual(
3,
(int)(await script.RunAsync()).ReturnValue);
C# Scripting / Interactive
• - Extremely verbose
• + (Extremely) Statically Typed
• + Extremely meaningful
• Can be optimizedStatical VS refactoring
• C#6+ Era of immutability
• This is why some C# syntax exists
• Partial classes
• Partial methods
Roslyn code consideration
Demo Time
Conclusions
• Maintenance first!
• Maintenance first!
• Maintenance first!
• Maintenance first!
• Maintenance first!
• Maintenance first!
• Maintenance first!
• Maintenance first!
• Maintenance first!
• Maintenance first!
• Maintenance first!
Conclusions
• Creating code generators is not “mainstream”
• Using cg yes…Razor (again) is a code generator
• Don’t increase complexity
• Don’t implement infrequent situations
• manage infrequent situations with traditional classic manual code
• Roslyn
• Mature (everything Roslyn since C# 6.0+)
• Visual Studio Code Generators
• Difficult to test
• Develop outside Analyzer (whenever possible)
• Standard2.0 basedVisual Studio is .NET 4.8 (not core!!!!)
Conclusions
Thanks!
Marco Parenzan
marcoparenzan/CodeGenerationForAzureWithDotNet (github.com)

More Related Content

What's hot

Ado.Net Data Services (Astoria)
Ado.Net Data Services (Astoria)Ado.Net Data Services (Astoria)
Ado.Net Data Services (Astoria)
Igor Moochnick
 

What's hot (20)

Empower every Azure Function to achieve more!!
Empower every Azure Function to achieve more!!Empower every Azure Function to achieve more!!
Empower every Azure Function to achieve more!!
 
Blazor, lo sapevi che...
Blazor, lo sapevi che...Blazor, lo sapevi che...
Blazor, lo sapevi che...
 
Springboot Microservices
Springboot MicroservicesSpringboot Microservices
Springboot Microservices
 
If Hemingway Wrote JavaDocs
If Hemingway Wrote JavaDocsIf Hemingway Wrote JavaDocs
If Hemingway Wrote JavaDocs
 
Durable Functions vs Logic App : la guerra dei workflow!!
Durable Functions vs Logic App : la guerra dei workflow!!Durable Functions vs Logic App : la guerra dei workflow!!
Durable Functions vs Logic App : la guerra dei workflow!!
 
Stateful patterns in Azure Functions
Stateful patterns in Azure FunctionsStateful patterns in Azure Functions
Stateful patterns in Azure Functions
 
Ado.Net Data Services (Astoria)
Ado.Net Data Services (Astoria)Ado.Net Data Services (Astoria)
Ado.Net Data Services (Astoria)
 
Azure Functions - Introduction
Azure Functions - IntroductionAzure Functions - Introduction
Azure Functions - Introduction
 
Azure Service Fabric and the Actor Model: when did we forget Object Orientation?
Azure Service Fabric and the Actor Model: when did we forget Object Orientation?Azure Service Fabric and the Actor Model: when did we forget Object Orientation?
Azure Service Fabric and the Actor Model: when did we forget Object Orientation?
 
Bulletproof Microservices with Spring and Kubernetes
Bulletproof Microservices with Spring and KubernetesBulletproof Microservices with Spring and Kubernetes
Bulletproof Microservices with Spring and Kubernetes
 
Security Patterns for Microservice Architectures - SpringOne 2020
Security Patterns for Microservice Architectures - SpringOne 2020Security Patterns for Microservice Architectures - SpringOne 2020
Security Patterns for Microservice Architectures - SpringOne 2020
 
Introduction to Spring Cloud
Introduction to Spring Cloud           Introduction to Spring Cloud
Introduction to Spring Cloud
 
"Project Tye to Tie .NET Microservices", Oleg Karasik
"Project Tye to Tie .NET Microservices", Oleg Karasik"Project Tye to Tie .NET Microservices", Oleg Karasik
"Project Tye to Tie .NET Microservices", Oleg Karasik
 
Azure paa s v2 – microservices, microsoft (azure) service fabric, .apps and o...
Azure paa s v2 – microservices, microsoft (azure) service fabric, .apps and o...Azure paa s v2 – microservices, microsoft (azure) service fabric, .apps and o...
Azure paa s v2 – microservices, microsoft (azure) service fabric, .apps and o...
 
.Net Microservices with Event Sourcing, CQRS, Docker and... Windows Server 20...
.Net Microservices with Event Sourcing, CQRS, Docker and... Windows Server 20....Net Microservices with Event Sourcing, CQRS, Docker and... Windows Server 20...
.Net Microservices with Event Sourcing, CQRS, Docker and... Windows Server 20...
 
Алексей Демедецкий: How to: RAC, TDD, MVVM
Алексей Демедецкий: How to: RAC, TDD, MVVMАлексей Демедецкий: How to: RAC, TDD, MVVM
Алексей Демедецкий: How to: RAC, TDD, MVVM
 
Application Security from the Inside - OWASP
Application Security from the Inside - OWASPApplication Security from the Inside - OWASP
Application Security from the Inside - OWASP
 
Kasten securing access to your kubernetes applications
Kasten securing access to your kubernetes applicationsKasten securing access to your kubernetes applications
Kasten securing access to your kubernetes applications
 
micro services architecture (FrosCon2014)
micro services architecture (FrosCon2014)micro services architecture (FrosCon2014)
micro services architecture (FrosCon2014)
 
70-483: PROGRAMMING IN C#
70-483: PROGRAMMING IN C#70-483: PROGRAMMING IN C#
70-483: PROGRAMMING IN C#
 

Similar to Code Generation for Azure with .net

Assuringthecodequalityofsharepointsolutionsandapps 141023024802-conversion-ga...
Assuringthecodequalityofsharepointsolutionsandapps 141023024802-conversion-ga...Assuringthecodequalityofsharepointsolutionsandapps 141023024802-conversion-ga...
Assuringthecodequalityofsharepointsolutionsandapps 141023024802-conversion-ga...
Vanessa Santangelo
 

Similar to Code Generation for Azure with .net (20)

Continuous Integration - Live Static Analysis with Puma Scan
Continuous Integration - Live Static Analysis with Puma ScanContinuous Integration - Live Static Analysis with Puma Scan
Continuous Integration - Live Static Analysis with Puma Scan
 
Code Generation for Azure with .net
Code Generation for Azure with .netCode Generation for Azure with .net
Code Generation for Azure with .net
 
Tdd,Ioc
Tdd,IocTdd,Ioc
Tdd,Ioc
 
Assuring the code quality of share point solutions and apps - Matthias Einig
Assuring the code quality of share point solutions and apps - Matthias EinigAssuring the code quality of share point solutions and apps - Matthias Einig
Assuring the code quality of share point solutions and apps - Matthias Einig
 
Looking for Bugs in MonoDevelop
Looking for Bugs in MonoDevelopLooking for Bugs in MonoDevelop
Looking for Bugs in MonoDevelop
 
Operator SDK for K8s using Go
Operator SDK for K8s using GoOperator SDK for K8s using Go
Operator SDK for K8s using Go
 
The First C# Project Analyzed
The First C# Project AnalyzedThe First C# Project Analyzed
The First C# Project Analyzed
 
(Don't) Go Tracing Server Calls
(Don't) Go Tracing Server Calls(Don't) Go Tracing Server Calls
(Don't) Go Tracing Server Calls
 
你不可不知的 ASP.NET Core 3 全新功能探索 (.NET Conf 2019)
你不可不知的 ASP.NET Core 3 全新功能探索 (.NET Conf 2019)你不可不知的 ASP.NET Core 3 全新功能探索 (.NET Conf 2019)
你不可不知的 ASP.NET Core 3 全新功能探索 (.NET Conf 2019)
 
Useful practices of creation automatic tests by using cucumber jvm
Useful practices of creation automatic tests by using cucumber jvmUseful practices of creation automatic tests by using cucumber jvm
Useful practices of creation automatic tests by using cucumber jvm
 
I want my model to be deployed ! (another story of MLOps)
I want my model to be deployed ! (another story of MLOps)I want my model to be deployed ! (another story of MLOps)
I want my model to be deployed ! (another story of MLOps)
 
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
 
Coding Naked 2023
Coding Naked 2023Coding Naked 2023
Coding Naked 2023
 
Improving code quality with Roslyn analyzers
Improving code quality with Roslyn analyzersImproving code quality with Roslyn analyzers
Improving code quality with Roslyn analyzers
 
"How to create an infrastructure in .NET", Leonid Chetverikov
"How to create an infrastructure in .NET", Leonid Chetverikov"How to create an infrastructure in .NET", Leonid Chetverikov
"How to create an infrastructure in .NET", Leonid Chetverikov
 
Data analytics master class: predict hotel revenue
Data analytics master class: predict hotel revenueData analytics master class: predict hotel revenue
Data analytics master class: predict hotel revenue
 
MongoDB.local Atlanta: Introduction to Serverless MongoDB
MongoDB.local Atlanta: Introduction to Serverless MongoDBMongoDB.local Atlanta: Introduction to Serverless MongoDB
MongoDB.local Atlanta: Introduction to Serverless MongoDB
 
Assuringthecodequalityofsharepointsolutionsandapps 141023024802-conversion-ga...
Assuringthecodequalityofsharepointsolutionsandapps 141023024802-conversion-ga...Assuringthecodequalityofsharepointsolutionsandapps 141023024802-conversion-ga...
Assuringthecodequalityofsharepointsolutionsandapps 141023024802-conversion-ga...
 
Measuring Your Code
Measuring Your CodeMeasuring Your Code
Measuring Your Code
 
Measuring Your Code 2.0
Measuring Your Code 2.0Measuring Your Code 2.0
Measuring Your Code 2.0
 

More from Marco Parenzan

More from Marco Parenzan (20)

Azure IoT Central per lo SCADA engineer
Azure IoT Central per lo SCADA engineerAzure IoT Central per lo SCADA engineer
Azure IoT Central per lo SCADA engineer
 
Azure Hybrid @ Home
Azure Hybrid @ HomeAzure Hybrid @ Home
Azure Hybrid @ Home
 
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptx
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptxStatic abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptx
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptx
 
Azure Synapse Analytics for your IoT Solutions
Azure Synapse Analytics for your IoT SolutionsAzure Synapse Analytics for your IoT Solutions
Azure Synapse Analytics for your IoT Solutions
 
Power BI Streaming Data Flow e Azure IoT Central
Power BI Streaming Data Flow e Azure IoT Central Power BI Streaming Data Flow e Azure IoT Central
Power BI Streaming Data Flow e Azure IoT Central
 
Power BI Streaming Data Flow e Azure IoT Central
Power BI Streaming Data Flow e Azure IoT CentralPower BI Streaming Data Flow e Azure IoT Central
Power BI Streaming Data Flow e Azure IoT Central
 
Power BI Streaming Data Flow e Azure IoT Central
Power BI Streaming Data Flow e Azure IoT CentralPower BI Streaming Data Flow e Azure IoT Central
Power BI Streaming Data Flow e Azure IoT Central
 
Developing Actors in Azure with .net
Developing Actors in Azure with .netDeveloping Actors in Azure with .net
Developing Actors in Azure with .net
 
Math with .NET for you and Azure
Math with .NET for you and AzureMath with .NET for you and Azure
Math with .NET for you and Azure
 
Power BI data flow and Azure IoT Central
Power BI data flow and Azure IoT CentralPower BI data flow and Azure IoT Central
Power BI data flow and Azure IoT Central
 
.net for fun: write a Christmas videogame
.net for fun: write a Christmas videogame.net for fun: write a Christmas videogame
.net for fun: write a Christmas videogame
 
Building IoT infrastructure on edge with .net, Raspberry PI and ESP32 to conn...
Building IoT infrastructure on edge with .net, Raspberry PI and ESP32 to conn...Building IoT infrastructure on edge with .net, Raspberry PI and ESP32 to conn...
Building IoT infrastructure on edge with .net, Raspberry PI and ESP32 to conn...
 
Anomaly Detection with Azure and .NET
Anomaly Detection with Azure and .NETAnomaly Detection with Azure and .NET
Anomaly Detection with Azure and .NET
 
Deploy Microsoft Azure Data Solutions
Deploy Microsoft Azure Data SolutionsDeploy Microsoft Azure Data Solutions
Deploy Microsoft Azure Data Solutions
 
Deep Dive Time Series Anomaly Detection in Azure with dotnet
Deep Dive Time Series Anomaly Detection in Azure with dotnetDeep Dive Time Series Anomaly Detection in Azure with dotnet
Deep Dive Time Series Anomaly Detection in Azure with dotnet
 
Azure IoT Central
Azure IoT CentralAzure IoT Central
Azure IoT Central
 
Anomaly Detection with Azure and .net
Anomaly Detection with Azure and .netAnomaly Detection with Azure and .net
Anomaly Detection with Azure and .net
 
Running Kafka and Spark on Raspberry PI with Azure and some .net magic
Running Kafka and Spark on Raspberry PI with Azure and some .net magicRunning Kafka and Spark on Raspberry PI with Azure and some .net magic
Running Kafka and Spark on Raspberry PI with Azure and some .net magic
 
Time Series Anomaly Detection with Azure and .NETT
Time Series Anomaly Detection with Azure and .NETTTime Series Anomaly Detection with Azure and .NETT
Time Series Anomaly Detection with Azure and .NETT
 
Deep dive time series anomaly detection with different Azure Data Services
Deep dive time series anomaly detection with different Azure Data ServicesDeep dive time series anomaly detection with different Azure Data Services
Deep dive time series anomaly detection with different Azure Data Services
 

Recently uploaded

AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
Alluxio, Inc.
 

Recently uploaded (20)

What need to be mastered as AI-Powered Java Developers
What need to be mastered as AI-Powered Java DevelopersWhat need to be mastered as AI-Powered Java Developers
What need to be mastered as AI-Powered Java Developers
 
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
 
How to install and activate eGrabber JobGrabber
How to install and activate eGrabber JobGrabberHow to install and activate eGrabber JobGrabber
How to install and activate eGrabber JobGrabber
 
how-to-download-files-safely-from-the-internet.pdf
how-to-download-files-safely-from-the-internet.pdfhow-to-download-files-safely-from-the-internet.pdf
how-to-download-files-safely-from-the-internet.pdf
 
Agnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in KrakówAgnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in Kraków
 
SQL Injection Introduction and Prevention
SQL Injection Introduction and PreventionSQL Injection Introduction and Prevention
SQL Injection Introduction and Prevention
 
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
 
5 Reasons Driving Warehouse Management Systems Demand
5 Reasons Driving Warehouse Management Systems Demand5 Reasons Driving Warehouse Management Systems Demand
5 Reasons Driving Warehouse Management Systems Demand
 
CompTIA Security+ (Study Notes) for cs.pdf
CompTIA Security+ (Study Notes) for cs.pdfCompTIA Security+ (Study Notes) for cs.pdf
CompTIA Security+ (Study Notes) for cs.pdf
 
A Guideline to Zendesk to Re:amaze Data Migration
A Guideline to Zendesk to Re:amaze Data MigrationA Guideline to Zendesk to Re:amaze Data Migration
A Guideline to Zendesk to Re:amaze Data Migration
 
Secure Software Ecosystem Teqnation 2024
Secure Software Ecosystem Teqnation 2024Secure Software Ecosystem Teqnation 2024
Secure Software Ecosystem Teqnation 2024
 
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdfA Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
 
APVP,apvp apvp High quality supplier safe spot transport, 98% purity
APVP,apvp apvp High quality supplier safe spot transport, 98% purityAPVP,apvp apvp High quality supplier safe spot transport, 98% purity
APVP,apvp apvp High quality supplier safe spot transport, 98% purity
 
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product UpdatesGraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
 
COMPUTER AND ITS COMPONENTS PPT.by naitik sharma Class 9th A mittal internati...
COMPUTER AND ITS COMPONENTS PPT.by naitik sharma Class 9th A mittal internati...COMPUTER AND ITS COMPONENTS PPT.by naitik sharma Class 9th A mittal internati...
COMPUTER AND ITS COMPONENTS PPT.by naitik sharma Class 9th A mittal internati...
 
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdf
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdfImplementing KPIs and Right Metrics for Agile Delivery Teams.pdf
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdf
 
AI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning FrameworkAI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning Framework
 
KLARNA - Language Models and Knowledge Graphs: A Systems Approach
KLARNA -  Language Models and Knowledge Graphs: A Systems ApproachKLARNA -  Language Models and Knowledge Graphs: A Systems Approach
KLARNA - Language Models and Knowledge Graphs: A Systems Approach
 
OpenChain @ LF Japan Executive Briefing - May 2024
OpenChain @ LF Japan Executive Briefing - May 2024OpenChain @ LF Japan Executive Briefing - May 2024
OpenChain @ LF Japan Executive Briefing - May 2024
 
10 Essential Software Testing Tools You Need to Know About.pdf
10 Essential Software Testing Tools You Need to Know About.pdf10 Essential Software Testing Tools You Need to Know About.pdf
10 Essential Software Testing Tools You Need to Know About.pdf
 

Code Generation for Azure with .net

  • 1. Code Generation for Azure with .NET Marco Parenzan marcoparenzan/CodeGenerationForAzureWithDotNet (github.com)
  • 2. Senior Solution Architect in beanTech Microsoft Azure MVP Community Lead 1nn0va // Pordenone 1nn0va After Hour https://bit.ly/1nn0va-video Linkedin: https://www.linkedin.com/in/marcoparenzan/ Marco Parenzan
  • 3. Code Generation for Azure with .NET Marco Parenzan marcoparenzan/CodeGenerationForAzureWithDotNet (github.com)
  • 4. So another story from my love for (un)successfull/(un)tested(?) technologies 
  • 5. • Faster upgrades • Framework (.NET 6.0 anyone?) • Cloud Services • Enforce (best) practices • Increase maintainability Challenges for the modern cloud company
  • 6. • Service vs. Web Service • Servicebusiness logic • Web Serviceprotocol adaptation • HTTPS vs GRPC • Azure Function vs. API App • Develop in front of a component • Better testing • Single Responsability Principle! • Business logic and protocol adaptation are two responsabilities Value vs. Not Value
  • 7. • “Code that generates code…” • Reflection • Powerful • Difficult to maintain • Difficult to customize • DSL • Powerful • Difficult to maintain • Risk to customize • Code Generation • Powerful • Simpler to maintain • Simpler(?) to customize Dynamic (Meta)Programming
  • 8. • Text-based code generation • T4 • Yeoman • Razor • Roslyn-based code generation Code Generation Tecniques
  • 9. Roslyn C# compiler generation (C# 6.x+)
  • 11. • Roslyn packages • Visual Studio Integration (analyzer) The toolbox
  • 12. Building your own Fix var value = 1 + 2; ExpressionSyntax SyntaxToken SyntaxTrivia var equalsValue = SyntaxFactory.EqualsValueClause( SyntaxFactory.BinaryExpression( SyntaxKind.AddExpression, SyntaxFactory.LiteralExpression( SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(1)), SyntaxFactory.LiteralExpression( SyntaxKind.NumericLiteralExpression,SyntaxFactory.Literal(2)) )); var typeSyntax = SyntaxFactory.VariableDeclaration( SyntaxFactory.ParseTypeName("var"), new SeparatedSyntaxList<VariableDeclaratorSyntax>() .Add(SyntaxFactory.VariableDeclarator(“value") .WithInitializer(equalsValue))) .NormalizeWhitespace(" ") .WithAdditionalAnnotations(Formatter.Annotation); var declaration = SyntaxFactory.LocalDeclarationStatement(typeSyntax);
  • 13. [DiagnosticAnalyzer(LanguageNames.CSharp)] public class WebApiControllerNamingConventionAnalyzer : DiagnosticAnalyzer { string DiagnosticId = “WA0001"; string Description = "Controller type should end in 'Controller'"; string MessageFormat = "Type name '{0}' does not end in Controller"; internal const string Category = "Naming"; private static DiagnosticDescriptor Rule = new DiagnosticDescriptor( DiagnosticId, Description, MessageFormat, Category, DiagnosticSeverity.Warning, true); // Add implementation } private void Analyzer(SymbolAnalysisContext context) { var symbol = (INamedTypeSymbol)context.Symbol; if (symbol.BaseType == null) return; if ((symbol.BaseType.Name == "Controller" || symbol.BaseType.Name == "ApiController") && !symbol.Name.EndsWith("Controller")) { var diagnostic = Diagnostic.Create( Rule, symbol.Locations[0], symbol.Name); context.ReportDiagnostic(diagnostic); } } Custom Diagnostic - Analyzer
  • 14. var script = CSharpScript.Create<int>("int x = 1;") .ContinueWith("int y = 2;") .ContinueWith("x + y"); Assert.AreEqual( 3, (int)(await script.RunAsync()).ReturnValue); C# Scripting / Interactive
  • 15. • - Extremely verbose • + (Extremely) Statically Typed • + Extremely meaningful • Can be optimizedStatical VS refactoring • C#6+ Era of immutability • This is why some C# syntax exists • Partial classes • Partial methods Roslyn code consideration
  • 18. • Maintenance first! • Maintenance first! • Maintenance first! • Maintenance first! • Maintenance first! • Maintenance first! • Maintenance first! • Maintenance first! • Maintenance first! • Maintenance first! • Maintenance first! Conclusions
  • 19. • Creating code generators is not “mainstream” • Using cg yes…Razor (again) is a code generator • Don’t increase complexity • Don’t implement infrequent situations • manage infrequent situations with traditional classic manual code • Roslyn • Mature (everything Roslyn since C# 6.0+) • Visual Studio Code Generators • Difficult to test • Develop outside Analyzer (whenever possible) • Standard2.0 basedVisual Studio is .NET 4.8 (not core!!!!) Conclusions