RSCG_Examples

About this book

Content of the book

You will find in this book code examples about >10 Roslyn Source Code Generator (RSCG) that can be useful for you. That means, you will write more elegant and concise code - even if the generators code is not always nice to look.

Are those examples ready for production?

I have done due diligence to test the RSCG that I have shown to you here. However, I cannot guarantee that will fit your code. That means that you can test it for your case and, because all are open source on Github.com, you can contribute to improve them ;-)

How to read this book

For each chapter, you will find

  1. Name of the RSCG and link to the NuGet package / GitHub repository
  2. What the RSCG can do
  3. What you need to include in .csproj file
  4. What will be the initial code
  5. How to use the Code generated by RSCG
  6. Code Generated by RSCG
  7. Link to the downloadable code to practice

I have a suggestion for a new RSCG that is worth mentioning in this book. What can I do?

Please send me an email to ignatandrei@yahoo.com

I want to make a RSCG that will be useful. How can I do?

In the introduction I have put the links to get you started with RSCG.

And, if you bought this book from Amazon, you are entitled to have 1 hour free of consultancy with me. I can help you make one.

I want the book / sponsor you

Glad that you have asked. Please goto Amazon: https://amzn.to/3f6gll3

( and this will remain free: https://ignatandrei.github.io/RSCG_Examples/)

Introduction

What is a Roslyn Source Code Generator?

A Roslyn Source Code Generator (RSCG) is a program that generates code in the compile time, based on the previous source code and/or another data. This new source code is added to the compilation and compile with the previous source code.

How can I make a Roslyn Source Code Generator?

For creating the RSCG you will simply create a .NET Standard 2.0 project, add those 2 references

    <PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.1" PrivateAssets="all" />
    <PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="3.8.0" />

and start implementing

public interface ISourceGenerator
{
    void Initialize(GeneratorInitializationContext context);
    void Execute(GeneratorExecutionContext context);
}

Start from examples at https://github.com/dotnet/roslyn-sdk/tree/main/samples/CSharp/SourceGenerators Also, you can read the source code for the RSCG presented in this book.

Show me some code for RSCG

Start read

https://github.com/dotnet/roslyn/blob/main/docs/features/source-generators.md

and

https://github.com/dotnet/roslyn/blob/main/docs/features/source-generators.cookbook.md .

After that, you can play with the examples from https://github.com/dotnet/roslyn-sdk/tree/main/samples/CSharp/SourceGenerators or from https://sourcegen.dev/ (see AutoNotify in the dropdown)

How the RSCG can help me to write faster / better the code ?

Glad that you asked. You can see in action a RSCG for automatically generating code for automating testing (see DynamicMocking ) , parsing enum (see Enum ) , generating controllers actions from a interface ( SkinnyControllers ), currying functions and many more. In this book you will find more than 10 examples of some RSCG that can help you. Also, you can find the source code of the examples at https://github.com/ignatandrei/RSCG_Examples.

RSCG number 1 : ThisAssembly

What RSCG ThisAssembly can do

The ThisAssembly.Info allows you access to the Assembly Information as constants, instead of going to reflection each time. I found useful to see the assembly version right away in any project that I have.

Example code

Here is the csproj with the references for RSCG ThisAssembly

csprj code

The initial code that you start with is

start code

The code below will use the RSCG ThisAssembly

usage code

The code that is generated by RSCG ThisAssembly

gc code

More details about RSCG ThisAssembly

The author of RSCG ThisAssembly is Daniel Cazzulino

You cand find RSCG ThisAssembly at Nuget.org : https://www.nuget.org/packages/ThisAssembly and the sources at https://github.com/devlooped/ThisAssembly

For more usage features please read : https://www.clarius.org/ThisAssembly/

https://github.com/ignatandrei/RSCG_Examples/tree/main/ApplicationVersion

RSCG number 2 : Enum

What RSCG Enum can do

This will generate code to fast parsing a int or a string to an enum

Example code

Here is the csproj with the references for RSCG Enum

csprj code

The initial code that you start with is

start code

The code below will use the RSCG Enum

usage code

The code that is generated by RSCG Enum

gc code

More details about RSCG Enum

The author of RSCG Enum is Andrei Ignat

You cand find RSCG Enum at Nuget.org : https://www.nuget.org/packages/AOPMethodsCommon/ https://www.nuget.org/packages/AOPMethodsGenerator/ and the sources at http://github.com/ignatandrei/aop_With_Roslyn/

For more usage features please read : http://msprogrammer.serviciipeweb.ro/category/roslyn/

https://github.com/ignatandrei/RSCG_Examples/tree/main/Enum

RSCG number 3 : JsonByExampleGenerator

What RSCG JsonByExampleGenerator can do

This will generate C# classes from json files.

Example code

Here is the csproj with the references for RSCG JsonByExampleGenerator

csprj code

The initial code that you start with is

start code

The code below will use the RSCG JsonByExampleGenerator

usage code

The code that is generated by RSCG JsonByExampleGenerator

gc code

More details about RSCG JsonByExampleGenerator

The author of RSCG JsonByExampleGenerator is Robin Hermanussen

You cand find RSCG JsonByExampleGenerator at Nuget.org : https://www.nuget.org/packages/JsonByExampleGenerator/ and the sources at https://github.com/hermanussen/JsonByExampleGenerator/

For more usage features please read : https://github.com/hermanussen/JsonByExampleGenerator/

https://github.com/ignatandrei/RSCG_Examples/tree/main/JsonToClass

Author of JsonByExampleGenerator , Robin Hermanussen

Short info about you , Robin Hermanussen

I’m a Software Architect at Iquality (software company in the Netherlands). I’m passionate about software development in general, but with a particular interest in .NET.

Why did you start this JsonByExampleGenerator ?

I have written a bunch of C# analyzers in the past that served specific needs and now wanted to get some experience in writing source generators. It seemed like a good idea to me to generate classes based on example JSON, because it replaces a task that I often find a bit tedious; writing data contract classes and then tests to ensure they get properly (de)serialized with the JSON that I’m using.

How do yourself use your JsonByExampleGenerator ?

I’m not really using it in real world projects right now, as I’m not working on any projects that require it.

What other RSCG do you use ?

I’ve used ThisAssembly and a few others, for learning purposes.

Any other feedback ?

If anyone wants to use JsonByExampleGenerator and give me feedback from the real world, let me know! I’ll be happy to help out with any issues or questions you may run into. Just add an issue to the project on GitHub to get in touch.

RSCG number 4 : CopyConstructor + Deconstructor

What RSCG CopyConstructor + Deconstructor can do

This will generate code for a POCO to generate copy constructor and deconstructor

Example code

Here is the csproj with the references for RSCG CopyConstructor + Deconstructor

csprj code

The initial code that you start with is

start code

The code below will use the RSCG CopyConstructor + Deconstructor

usage code

The code that is generated by RSCG CopyConstructor + Deconstructor

gc code

More details about RSCG CopyConstructor + Deconstructor

The author of RSCG CopyConstructor + Deconstructor is Andrei Ignat

You cand find RSCG CopyConstructor + Deconstructor at Nuget.org : https://www.nuget.org/packages/AOPMethodsCommon/ https://www.nuget.org/packages/AOPMethodsGenerator/ and the sources at http://github.com/ignatandrei/aop_With_Roslyn/

For more usage features please read : http://msprogrammer.serviciipeweb.ro/category/roslyn/

https://github.com/ignatandrei/RSCG_Examples/tree/main/CopyConstructor

RSCG number 5 : GeneratedMapper

What RSCG GeneratedMapper can do

AutoMapping from a POCO to a DTO. Lots of customizations

Example code

Here is the csproj with the references for RSCG GeneratedMapper

csprj code

The initial code that you start with is

start code

The code below will use the RSCG GeneratedMapper

usage code

The code that is generated by RSCG GeneratedMapper

gc code

More details about RSCG GeneratedMapper

The author of RSCG GeneratedMapper is Thomas Bleijendaal

You cand find RSCG GeneratedMapper at Nuget.org : https://www.nuget.org/packages/GeneratedMapper/ and the sources at https://github.com/ThomasBleijendaal/GeneratedMapper

For more usage features please read : https://github.com/ThomasBleijendaal/GeneratedMapper

https://github.com/ignatandrei/RSCG_Examples/tree/main/DTOMapper

Author of GeneratedMapper , Thomas Bleijendaal

Short info about you , Thomas Bleijendaal

I’m Thomas Bleijendaal, I’m a .NET developer working for Triple in Alkmaar, The Netherlands.

Why did you start this GeneratedMapper ?

I’ve started GeneratedMapper to get more familiar with source generation. While the tooling is a bit rough now, I do believe that this feature can really bring a lot of value to .NET.

I’ve been burned before by a lot of hard-to-find bugs caused by badly behaving mappers and runtime surprises from badly handled null-references. I wanted to create a object-to-object mapper that would be very picky and raise compilation errors instead of runtime exceptions. Being able to see what the mapper will do by simply inspecting the code is very handy, and makes you trust your mapper even more.

How do yourself use your GeneratedMapper ?

I use the GeneratedMapper in a project where I map models coming from Contentful to DTOs that are used in views. I’ve also tried to use it in another project, but because that targeted an older runtime I could not make that work. But, since I could copy all the generated mappers and maintain those manually, switching away from it wasn’t that bad. I think that is also very valuable of code generation, you still have a copy of what a generator made for you.

What other RSCG do you use ?

I haven’t really used any other RSCGs yet, other than a metadata generator that Microsoft made for the out-of-process .NET-based Azure Functions (https://github.com/Azure/azure-functions-dotnet-worker/). That stuff is all very preview still, so it could be removed from the product, but it’s cool to see Microsoft starting to use it too.

Any other feedback ?

Cool book!

RSCG number 6 : Skinny Controllers

What RSCG Skinny Controllers can do

This will generate code for WebAPI for each method of a field in the controller

Example code

Here is the csproj with the references for RSCG Skinny Controllers

csprj code

The initial code that you start with is

start code

The code below will use the RSCG Skinny Controllers

usage code

The code that is generated by RSCG Skinny Controllers

gc code

More details about RSCG Skinny Controllers

The author of RSCG Skinny Controllers is Andrei Ignat

You cand find RSCG Skinny Controllers at Nuget.org : https://www.nuget.org/packages/SkinnyControllersCommon/ https://www.nuget.org/packages/SkinnyControllersGenerator/ and the sources at http://github.com/ignatandrei/aop_With_Roslyn/

For more usage features please read : http://msprogrammer.serviciipeweb.ro/category/roslyn/

https://github.com/ignatandrei/RSCG_Examples/tree/main/SkinnyControllers

RSCG number 7 : data-builder-generator

What RSCG data-builder-generator can do

Implements the Builder Design pattern for any class. Useful , at least, for test projects

Example code

Here is the csproj with the references for RSCG data-builder-generator

csprj code

The initial code that you start with is

start code

The code below will use the RSCG data-builder-generator

usage code

The code that is generated by RSCG data-builder-generator

gc code

More details about RSCG data-builder-generator

The author of RSCG data-builder-generator is Martin Andreas Ulrich

You cand find RSCG data-builder-generator at Nuget.org : https://www.nuget.org/packages/DasMulli.DataBuilderGenerator/ and the sources at https://github.com/dasMulli/data-builder-generator

For more usage features please read : https://github.com/dasMulli/data-builder-generator

https://github.com/ignatandrei/RSCG_Examples/tree/main/DP_Builder

Author of data-builder-generator , Martin Andreas Ulrich

Short info about you , Martin Andreas Ulrich

I am a software engineer working on diverse tech stacks but focusing mostly on .NET in C#, Web Technologies and iOS/Swift.

I am a technology enthusiast who always works on improving development and DevOps processes at our company to make life easier for developers and help deliver high. I was awarded Microsoft MVP for community and open-source work around .NET Core.

Why did you start this data-builder-generator ?

How do yourself use your data-builder-generator ?

In “enterprise” contexts (I hate that term) one usually has to deal with business logic working on data objects. Writing tests is really important in these contexts but creating lots of test data for various scenarios can be quite cumbersome. You usually have some set of defaults (e.g. a base order with a dummy customer and items, an insurance application from a dummy customer etc.) and then deviate from it a little for each scenario. This is where C# 9 records would come in handy, but they were at the time not released and adopting them could be challenging (e.g. proper EF support while we’re still on EF Core 3.1 anyway) so we opted for a test data builder approach where the builder classes would be generated. I did something similar a few years back at a previous company based on https://github.com/AArnott/CodeGeneration.Roslyn (which is now archived in favor of rolsyn source generators) and decided that for a current project I’ll have a go and try to create something similar based on roslyn. While there are still a few bugs in the generator (get-only properties for example), this works quite well just annotating all EF model POCOs and then creating a few default builders that can be used from tests (Think TestData.DefaultOrder.WithoutCustomerAddress().Build()

What other RSCG do you use ?

Currently this is the only one. I hope that OpenAPI processing / generation will be a source generator soon - this is currently patched in via NSwag/MSBuild for some projects.

Any other feedback ?

As mentioned I hope that some patterns of how to implement fast source generators emerge. This one likely isn’t the best but I wanted to hold off a few months before refactoring. I don’t plan on making a huge deal out of it, I just thought it’s good to put useful tools we’re building on GitHub for discussion and maybe it helps someone else as well.

RSCG number 8 : Metadata from object

What RSCG Metadata from object can do

This will generate code to retrieve the values of properties directly, not by reflection

Example code

Here is the csproj with the references for RSCG Metadata from object

csprj code

The initial code that you start with is

start code

The code below will use the RSCG Metadata from object

usage code

The code that is generated by RSCG Metadata from object

gc code

More details about RSCG Metadata from object

The author of RSCG Metadata from object is Andrei Ignat

You cand find RSCG Metadata from object at Nuget.org : https://www.nuget.org/packages/AOPMethodsCommon/ https://www.nuget.org/packages/AOPMethodsGenerator/ and the sources at http://github.com/ignatandrei/aop_With_Roslyn/

For more usage features please read : http://msprogrammer.serviciipeweb.ro/category/roslyn/

https://github.com/ignatandrei/RSCG_Examples/tree/main/MetadataFromObject

RSCG number 9 : MockSourceGenerator

What RSCG MockSourceGenerator can do

This will generate Mock classes directly for any interface - with your implementation.

Example code

Here is the csproj with the references for RSCG MockSourceGenerator

csprj code

The initial code that you start with is

start code

The code below will use the RSCG MockSourceGenerator

usage code

The code that is generated by RSCG MockSourceGenerator

gc code

More details about RSCG MockSourceGenerator

The author of RSCG MockSourceGenerator is Robin Hermanussen

You cand find RSCG MockSourceGenerator at Nuget.org : https://www.nuget.org/packages/MockSourceGenerator/ and the sources at https://github.com/hermanussen/MockSourceGenerator/

For more usage features please read : https://github.com/hermanussen/MockSourceGenerator/

https://github.com/ignatandrei/RSCG_Examples/tree/main/DynamicMocking

Author of MockSourceGenerator , Robin Hermanussen

Short info about you , Robin Hermanussen

I’m a Software Architect at Iquality (software company in the Netherlands). I’m passionate about software development in general, but with a particular interest in .NET.

Why did you start this MockSourceGenerator ?

I have written a bunch of C# analyzers in the past that served specific needs and now wanted to get some experience in writing source generators. The thing about libraries like Moq or NSubstitute that I don’t really like is how it takes so much code to set them up and then I don’t find them very readable. MockSourceGenerator takes an approach that allows people to mock something in a single statement (with an object initializer) and I think it is more readable this way.

How do yourself use your MockSourceGenerator ?

I’m not really using it in real world projects right now, as I’m not working on any projects that require it.

What other RSCG do you use ?

I’ve used ThisAssembly and a few others, for learning purposes.

Any other feedback ?

If anyone wants to use MockSourceGenerator and give me feedback from the real world, let me know! I’ll be happy to help out with any issues or questions you may run into. Just add an issue to the project on GitHub to get in touch.

RSCG number 10 : Method decorator

What RSCG Method decorator can do

This will generate code to decorate methods with anything you want ( stopwatch, logging , authorization…)

Example code

Here is the csproj with the references for RSCG Method decorator

csprj code

The initial code that you start with is

start code

The code below will use the RSCG Method decorator

usage code

The code that is generated by RSCG Method decorator

gc code

More details about RSCG Method decorator

The author of RSCG Method decorator is Andrei Ignat

You cand find RSCG Method decorator at Nuget.org : https://www.nuget.org/packages/AOPMethodsCommon/ https://www.nuget.org/packages/AOPMethodsGenerator/ and the sources at http://github.com/ignatandrei/aop_With_Roslyn/

For more usage features please read : http://msprogrammer.serviciipeweb.ro/category/roslyn/

https://github.com/ignatandrei/RSCG_Examples/tree/main/MethodDecorator

RSCG number 11 : PartiallyApplied

What RSCG PartiallyApplied can do

This will generate curry for your functions

Example code

Here is the csproj with the references for RSCG PartiallyApplied

csprj code

The initial code that you start with is

start code

The code below will use the RSCG PartiallyApplied

usage code

The code that is generated by RSCG PartiallyApplied

gc code

More details about RSCG PartiallyApplied

The author of RSCG PartiallyApplied is Jason Bock

You cand find RSCG PartiallyApplied at Nuget.org : https://www.nuget.org/packages/PartiallyApplied/ and the sources at https://github.com/JasonBock/PartiallyApplied

For more usage features please read : https://github.com/JasonBock/PartiallyApplied

https://github.com/ignatandrei/RSCG_Examples/tree/main/PartiallyFunction

RSCG number 12 : IFormattable

What RSCG IFormattable can do

This will generate code to add IFormattable to any class, based on the properties of the class

Example code

Here is the csproj with the references for RSCG IFormattable

csprj code

The initial code that you start with is

start code

The code below will use the RSCG IFormattable

usage code

The code that is generated by RSCG IFormattable

gc code

More details about RSCG IFormattable

The author of RSCG IFormattable is Andrei Ignat

You cand find RSCG IFormattable at Nuget.org : https://www.nuget.org/packages/AOPMethodsCommon/ https://www.nuget.org/packages/AOPMethodsGenerator/ and the sources at http://github.com/ignatandrei/aop_With_Roslyn/

For more usage features please read : http://msprogrammer.serviciipeweb.ro/category/roslyn/

https://github.com/ignatandrei/RSCG_Examples/tree/main/IFormattable

RSCG number 13 : AutoInterface

What RSCG AutoInterface can do

Implement the Design Pattern Decorator. Based on template - you can modify the source code generated

Example code

Here is the csproj with the references for RSCG AutoInterface

csprj code

The initial code that you start with is

start code

The code below will use the RSCG AutoInterface

usage code

The code that is generated by RSCG AutoInterface

gc code

More details about RSCG AutoInterface

The author of RSCG AutoInterface is beakona

You cand find RSCG AutoInterface at Nuget.org : https://www.nuget.org/packages/BeaKona.AutoInterfaceGenerator and the sources at https://github.com/beakona/AutoInterface

For more usage features please read : https://github.com/beakona/AutoInterface

https://github.com/ignatandrei/RSCG_Examples/tree/main/DP_Decorator

Author of AutoInterface , beakona

Short info about you , beakona

I am a dad and software developer with more than 15 years of working experience in various industries and technologies. I am working mostly on embedded and desktop solutions mainly in C and C#.

Why did you start this AutoInterface ?

After the Source Generator public announcement, I decided to give them a try. I realized that Source Generators would allow us to explore composition-over-inheritance in its new form (from C# perspective). Technically, this approach uses interface invocation (which impacts performance) but one can view it as one form of composition. I consider myself a language designer and I wanted to explore the mechanics of this approach (regardless of poor performance) on existing and reputable language that I use daily.

How do yourself use your AutoInterface ?

I use it experimentally as a tool that allows a class to be composed-of-members and yet acts as inherited-as. Young and experimental languages have similar concepts as an alternative to inheritance. Those who find this interesting can explore the approach chosen by Jonathan Blow in its language Jai

What other RSCG do you use ?

There is only one Source Generator that I use in production; AutoCoder and it is not public because I didn’t find time to make it configurable and polished. It automatically implements ICoding interface for the target class (Bridge pattern). I have been using this approach for years because the existing infrastructure does not work for me. The main concept is inspired by Foundation framework class NSCoder but is implemented in the C# way. Abstraction-side has two directions IEncoding/IDecoding and there are two implementers: IEncoder and IDecoder. AutoCoder acts on behalf of the abstraction side by offering targeted fields/properties to IEncoder/IDecoder. The author of IEncoder/IDecoder can decide what, how, when, and in which context to encode/decode. In other words, AutoCoder automates boring stuff and does not make typos.

Any other feedback ?

If you have special, funny, or helpful paragraphs that acts like mentor or life coach concept I think there is worth mentioning TED talk: Why you will fail to have a great career by Larry Smith or book: “Hold on to Your Kids: Why Parents Need to Matter More Than Peers”, 2019, by Dr. Gabor Maté and Gordon Neufeld.

RSCG number 14 : Property Expression Generator

What RSCG Property Expression Generator can do

This will generate code to add function to be used with Entity Framework to search for any property of a class

Example code

Here is the csproj with the references for RSCG Property Expression Generator

csprj code

The initial code that you start with is

start code

The code below will use the RSCG Property Expression Generator

usage code

The code that is generated by RSCG Property Expression Generator

gc code

More details about RSCG Property Expression Generator

The author of RSCG Property Expression Generator is Andrei Ignat

You cand find RSCG Property Expression Generator at Nuget.org : https://www.nuget.org/packages/AOPMethodsCommon/ https://www.nuget.org/packages/AOPMethodsGenerator/ and the sources at http://github.com/ignatandrei/aop_With_Roslyn/

For more usage features please read : http://msprogrammer.serviciipeweb.ro/category/roslyn/

https://github.com/ignatandrei/RSCG_Examples/tree/main/PropertyExpressionGenerator

RSCG - worth mention

There are more RSCG that you could see - here is a list that you may want to look at:

  1. AutoEmbed https://github.com/chsienki/AutoEmbed
  2. Cloneable https://github.com/mostmand/Cloneable
  3. fonderie https://github.com/jeromelaban/fonderie
  4. Generators.Blazor https://github.com/excubo-ag/Generators.Blazor
  5. Generators.Grouping https://github.com/excubo-ag/Generators.Grouping
  6. JsonMergePatch https://github.com/ladeak/JsonMergePatch
  7. MemoizeSourceGenerator https://github.com/Zoxive/MemoizeSourceGenerator
  8. MiniRazor https://github.com/Tyrrrz/MiniRazor/
  9. MockGen https://github.com/thomas-girotto/MockGen
  10. ProxyGen https://github.com/Sholtee/ProxyGen
  11. Rocks https://github.com/JasonBock/Rocks
  12. RoslynWeave https://github.com/Jishun/RoslynWeave
  13. SmallSharp https://github.com/devlooped/SmallSharp
  14. StaticProxyGenerator https://github.com/robertturner/StaticProxyGenerator
  15. ValueChangedGenerator https://github.com/ufcpp/ValueChangedGenerator
  16. Web-Anchor https://github.com/mattiasnordqvist/Web-Anchor
  17. WrapperValueObject https://github.com/martinothamar/WrapperValueObject

Final Chapter

Conclusion

I am happy that you have read / or practice / the RSCG presented in this book. I hope that inspired you to produce yours - and send me to review and maybe add to this book .

One hour of free consultancy

If you bought this book from Amazon, https://amzn.to/3f6gll3, you are entitled to have 1 hour free of consultancy with me.

Thanks ! Andrei