Microsoft .NET Samples

repository·master·Indexed 20 days ago

https://github.com/microsoft/dotnet-samples

A collection of specialized .NET samples demonstrating advanced usage of core libraries and diagnostic tools. Includes demonstrations for System.Numerics (SIMD), System.Reflection.Metadata (MD Dumper), Microsoft.Diagnostics.Runtime (CLR MD), and Microsoft.Diagnostics.Tracing (EventSource and TraceEvent). Additionally provides samples for handling High DPI (Per-Monitor and System Aware) in Windows Forms applications.

Tokens
19.7K
Snippets
40
Records
72
Agent score
71%

What's inside microsoft-dotnet-samples

  1. Explore Windows Forms HDPI sample types

    master

    The repository contains two primary types of HDPI implementation samples:

    1. Per Monitor Aware: Demonstrates how to implement an application that responds to individual monitor DPI changes. This includes handling new event messages sent when a window is moved between monitors with different scaling factors.
    2. System-Aware: Demonstrates improvements at the control and scenario level, focusing on how individual controls behave under system-wide scaling settings.
  2. Explore .NET Samples for Microsoft.Diagnostics.Runtime

    master
    This repository provides samples for Microsoft.Diagnostics.Runtime, specifically the CLR MD sample. Use this to learn how to inspect the state of a managed runtime (CLR) during debugging or post-mortem analysis.
  3. Explore .NET Samples for System.Numerics

    master
    This repository provides samples for System.Numerics, specifically focusing on SIMD (Single Instruction, Multiple Data) operations. Use these samples to understand how to leverage hardware acceleration for numerical computations in .NET.
  4. Explore .NET Samples for Microsoft.Diagnostics.Tracing

    master
    This repository provides samples for Microsoft.Diagnostics.Tracing, covering both EventSource and TraceEvent. These samples demonstrate how to implement event tracing and consume trace events for diagnostic purposes.
  5. Capabilities of the TraceEvent library

    master

    The TraceEvent library provides extensive capabilities for ETW monitoring and analysis, including:

    • Real-time & File Monitoring: Monitor ETW events in real-time (via programmatic callbacks or IObservable for Reactive Extensions) or scan .etl files.
    • Provider Management: Selectively enable providers using ETW 'Keywords' and 'Levels', and enumerate system/process providers.
    • File Operations: Merge multiple .etl files or read/write/filter ETL files (Windows 8+).
    • Stack Tracing: Capture and convert stacks to symbolic form for .NET, JScript, and native code.
    • Advanced Formats: Store events in the ETLX format for efficient random access and backward/forward enumeration.
    • Code Generation: Use TraceParserGen to generate strongly typed C# parsers from any ETW manifest.
    • Kernel Event Access: Monitor process/thread lifecycle, CPU samples, context switches, page faults, disk/file/network I/O, registry access, and system calls.
    • CLR (.NET) Event Access: Monitor GCs, allocations, object movement, JIT compilation, exceptions, and Task scheduling.
    • Specialized Runtimes: Access ASP.NET, WCF, and JScript runtime events.
  6. Explore .NET Samples for Windows Forms HDPI

    master

    This repository provides samples for handling High DPI in Windows Forms, specifically demonstrating:

    • Per-Monitor Aware settings
    • System Aware settings

    Use these to ensure Windows Forms applications scale correctly across different monitor DPI settings.

  7. What is EventSource and how does it work?

    master

    Concept: EventSource for ETW

    EventSource is a central class used by managed-code developers to create strongly typed specifications for logging events that can be captured by Event Tracing for Windows (ETW).

    Instead of passing verbosity levels or event IDs at every call site, you define a class that encapsulates the event structure. This results in a 'minimal' call site where you only provide the logging object, the method representing the event, and the necessary strongly typed parameters.

    Key Benefits:

    • Strong Typing: Parameters (like int, string, or DateTime) are preserved through the event pipeline, eliminating the need for string parsing in viewers.
    • Minimal Call Sites: The application code remains clean, focusing only on the data being logged rather than the tracing infrastructure.
    • ETW Integration: Events are natively compatible with ETW tools like PerfView.
    // Example of a minimal call site
    MinimalEventSource.Log.Load(0x40000, "MyFile0");
  8. Use abstract base classes for EventSource hierarchies

    master

    While EventSource classes should generally be sealed, you can use an abstract base class to provide common, optimized WriteEvent overloads to multiple derived EventSource types.

    Constraints for Abstract Base Classes:

    • They cannot define ETW-specific elements like Keywords, Tasks, Opcodes, Channels, or Events.
    • They can only provide methods (like optimized WriteEvent wrappers) to be used by derived classes.
    public abstract class UtilBaseEventSource : EventSource
    {
        protected UtilBaseEventSource() : base() { }
        protected UtilBaseEventSource(bool throwOnEventWriteErrors) : base(throwOnEventWriteErrors) { }
    
        protected unsafe void WriteEvent(int eventId, int arg1, short arg2, long arg3)
        {
            if (IsEnabled())
            {
                EventSource.EventData* descrs = stackalloc EventSource.EventData[3];
                descrs[0].DataPointer = (IntPtr)(&arg1);
                descrs[0].Size = 4;
                descrs[1].DataPointer = (IntPtr)(&arg2);
                descrs[1].Size = 2;
                descrs[2].DataPointer = (IntPtr)(&arg3);
                descrs[2].Size = 8;
                WriteEventCore(eventId, 3, descrs);
            }
        }
    }
    
    [EventSource(Name = "OptimizedEventSource")]
    public sealed class OptimizedEventSource : UtilBaseEventSource
    {
        public static OptimizedEventSource Log = new OptimizedEventSource();
    
        [Event(1, Keywords = Keywords.Kwd1, Level = EventLevel.Informational, 
               Message = "LogElements called {0}/{1}/{2}.")]
        public void LogElements(int n, short sh, long l)
        {
            WriteEvent(1, n, sh, l); // Calls UtilBaseEventSource.WriteEvent
        }
    
        public static class Keywords
        {
            public const EventKeywords Kwd1 = (EventKeywords)1;
        }
    }
    public abstract class UtilBaseEventSource : EventSource
    {
        protected UtilBaseEventSource() : base() { }
        protected UtilBaseEventSource(bool throwOnEventWriteErrors) : base(throwOnEventWriteErrors) { }
    
        protected unsafe void WriteEvent(int eventId, int arg1, short arg2, long arg3)
        {
            if (IsEnabled())
            {
                EventSource.EventData* descrs = stackalloc EventSource.EventData[3];
                descrs[0].DataPointer = (IntPtr)(&arg1);
                descrs[0].Size = 4;
                descrs[1].DataPointer = (IntPtr)(&arg2);
                descrs[1].Size = 2;
                descrs[2].DataPointer = (IntPtr)(&arg3);
                descrs[2].Size = 8;
                WriteEventCore(eventId, 3, descrs);
            }
        }
    }
    
    [EventSource(Name = "OptimizedEventSource")]
    public sealed class OptimizedEventSource : UtilBaseEventSource
    {
        public static OptimizedEventSource Log = new OptimizedEventSource();
    
        [Event(1, Keywords = Keywords.Kwd1, Level = EventLevel.Informational, 
               Message = "LogElements called {0}/{1}/{2}.")]
        public void LogElements(int n, short sh, long l)
        {
            WriteEvent(1, n, sh, l); // Calls UtilBaseEventSource.WriteEvent
        }
    
        public static class Keywords
        {
            public const EventKeywords Kwd1 = (EventKeywords)1;
        }
    }
  9. EventSource versioning and namespaces

    master

    The EventSource class is available in two primary forms:

    1. Framework Version: Included in mscorlib.dll (starting from .NET 4.5) in the System.Diagnostics.Tracing namespace.
    2. NuGet Package (Microsoft.Diagnostics.Tracing.EventSource): Contains features from v4.5.1+ (like activity tracing and ETW channel support). This package uses the Microsoft.Diagnostics.Tracing namespace.

    Use the NuGet package if you need advanced features on .NET v4.0 or if you want to access new features before they are integrated into the core framework.

  10. Understand the difference between Publication and Registration in ETW

    master

    In the context of ETW, it is important to distinguish between these two concepts:

    • Publication: This is the static process of making provider schema information (the manifest) available to consumers (e.g., via wevtutil or attaching it to a DLL). It updates a system-wide database so names and keyword descriptions can be looked up.
    • Registration: This is a dynamic process that occurs when an EventProvider starts running (e.g., an EventSource is instantiated). The provider registers its unique GUID with the OS. This allows the OS to track which providers are currently active or available for a session to enable.

    Note on EventSources: EventSource instances do not automatically publish manifests via the standard wevtutil mechanism, which means they may not appear in logman query providers lists, even though they are registered with the OS via their GUID.