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.
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 ;-)
For each chapter, you will find
Please send me an email to ignatandrei@yahoo.com
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.
Glad that you have asked. Please goto Amazon: https://amzn.to/3f6gll3
( and this will remain free: https://ignatandrei.github.io/RSCG_Examples/)
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.
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.
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)
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.
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.
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
This will generate code to fast parsing a int or a string to an 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
This will generate C# classes from json files.
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
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.
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.
I’m not really using it in real world projects right now, as I’m not working on any projects that require it.
I’ve used ThisAssembly and a few others, for learning purposes.
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.
This will generate code for a POCO to generate copy constructor and 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
AutoMapping from a POCO to a DTO. Lots of customizations
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
I’m Thomas Bleijendaal, I’m a .NET developer working for Triple in Alkmaar, The Netherlands.
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.
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.
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.
Cool book!
This will generate code for WebAPI for each method of a field in the controller
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
Implements the Builder Design pattern for any class. Useful , at least, for test projects
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
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.
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()
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.
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.
This will generate code to retrieve the values of properties directly, not by reflection
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
This will generate Mock classes directly for any interface - with your implementation.
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
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.
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.
I’m not really using it in real world projects right now, as I’m not working on any projects that require it.
I’ve used ThisAssembly and a few others, for learning purposes.
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.
This will generate code to decorate methods with anything you want ( stopwatch, logging , authorization…)
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
This will generate curry for your functions
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
This will generate code to add IFormattable to any class, based on the properties of the class
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
Implement the Design Pattern Decorator. Based on template - you can modify the source code generated
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
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#.
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.
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
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
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.
This will generate code to add function to be used with Entity Framework to search for any property of a class
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
There are more RSCG that you could see - here is a list that you may want to look at:
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 .
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