In conjunction with the WCF Client Proxy Generator I published the other day, I wrote another code generator that I also had great use for in my daily job. Namely an extension that generates the implementation for an
EventSource class from an abstract class definition. We used T4 for this too, but the old EnvDTE API fell quite short to be able to provide the capabilities I wanted. But now with the .NET Compiler Platform (previously, and mostly still actually, known as Roslyn) this became possible, and much easier.
Below is an excerpt from the introduction on the GitHub page. For more information, head over there and continue reading.
What is the EventSource class?
For more information about how to use the System.Diagnostics.Tracing.EventSource (or Microsoft.Diagnostics.Tracing.EventSource) classes to implement sematic logging utilizing ETW, see for example the following links:
* Vance Morrison’s Blog
* Kathleen Dollard’s Blog
* Vance Morrison’s video on Channel 9
* Pluralsight course on ETW
There are however a few problems when it comes to writing implementations of the EventSource class;
- You need to write the implementation for each event-method, and the event ID used in the method must match that in the
[Event]attribute on the method. Implementations of these methods look identical, and these should preferrably be automatically generated.
- For the highest performance you can write overloads of the WriteEvent methods using unsafe code. This involves writing complicated code using pointers and some other usafe features not commonly used in normal .NET development. It would be great if the neccessary overloads were automatically generated.
- You cannot create a base class with common events to be used by multiple EventSources. Any base class must be abstract and contain no event-methods.
The Alphaleonis C# Event Source generator attempts to overcome these problems by generating code based on an abstract class that you define, without having to manually write the implementation for any method.
The Event Source Generator
The Alphaleonis C# Event Source Generator is a Visual Studio 2015 extension that provides a CustomTool that can be applied to a C#-file and then generates the actual implementation of an EventSource deriving from an abstract class defined by you, where all event methods are defined as abstract methods. It will also generate any WriteEvent-overloads required, to avoid using the less performant generic overload in the base class.
The extension supports both the
System.Diagnostics.Tracing.EventSource in .NET 4.5 and 4.6, as well as the NuGet package
Microsoft.Diagnostics.Tracing.EventSource. The NuGet package is required for channel support in .NET 4.5. (.NET 4.6 supports this out of the box).