Ejemplo n.º 1
0
        private static void SetupListening()
        {
            ConsoleWrite.LineLine("Starting setting up DiagnosticSource listening.");

            IDisposable listenerSubscription = DiagnosticListening.SubscribeToAllSources(ObserverAdapter.OnNextHandler(
                                                                                             (DiagnosticListenerStub diagnosticListener) =>
            {
                ConsoleWrite.Line($"Subscriber called: diagnosticSourceObserver(diagnosticListener.Name: \"{diagnosticListener.Name}\")");

                if (diagnosticListener.Name.Equals("DemoXxx.UseDiagnosticSource.Name1", StringComparison.Ordinal))
                {
                    IDisposable eventSubscription = diagnosticListener.SubscribeToEvents(
                        ObserverAdapter.OnNextHandler((KeyValuePair <string, object> eventInfo) =>
                    {
                        ConsoleWrite.Line($"Event Handler called: eventObserver(eventName: \"{eventInfo.Key}\", payloadValue: {(eventInfo.Value ?? "<null>")})");
                    }),
                        (string eventName, object arg1, object arg2) =>
                    {
                        Validate.NotNull(eventName, nameof(eventName));
                        bool res = eventName.StartsWith("EventXyzName", StringComparison.OrdinalIgnoreCase) &&
                                   (arg1 == null || !(arg1 is Int32 arg1Val) || arg1Val >= 0);
                        ConsoleWrite.Line($"Filter called: isEventEnabledFilter(eventName: \"{eventName}\", arg1: {(arg1 ?? "<null>")}, arg2: {(arg2 ?? "<null>")})."
                                          + $" Returning: {res}.");
                        return(res);
                    });
                }
            }));

            ConsoleWrite.Line("Finished setting up DiagnosticSource listening.");
        }
        private static void SetupListening()
        {
            ConsoleWrite.LineLine("Starting setting up DiagnosticSource listening.");

            IDisposable listenerSubscription = DiagnosticListener.AllListeners.Subscribe(ObserverAdapter.OnNextHandler(
                                                                                             (DiagnosticListener diagLstnr) =>
            {
                // This lambda looks at ALL Diagnostic Listeners (aka Sources),
                // picks the one it is inderested in and subscibes to that particular Source.

                ConsoleWrite.Line($"Subscriber called: OnNext(diagLstnr.Name: \"{diagLstnr.Name}\")");

                if (diagLstnr.Name.Equals("DemoXxx.UseDiagnosticSource.Name1", StringComparison.Ordinal))
                {
                    IDisposable eventSubscription = diagLstnr.Subscribe(ObserverAdapter.OnNextHandler(
                                                                            (KeyValuePair <string, object> eventInfo) =>
                    {
                        ConsoleWrite.Line($"Event Handler called: OnNext(eventInfo.Key: \"{eventInfo.Key}\", eventInfo.Value: {(eventInfo.Value ?? "<null>")})");
                    }),
                                                                        (name, arg1, arg2) =>
                    {
                        Validate.NotNull(name, nameof(name));
                        bool res = name.StartsWith("EventXyzName", StringComparison.OrdinalIgnoreCase) &&
                                   (arg1 == null || !(arg1 is Int32 arg1Val) || arg1Val >= 0);
                        ConsoleWrite.Line($"Filter called: IsEnabled(name: \"{name}\", arg1: {(arg1 ?? "<null>")}, arg2: {(arg2 ?? "<null>")})."
                                          + $" Returning: {res}.");
                        return(res);
                    });
                }
            }));

            ConsoleWrite.Line("Finished setting up DiagnosticSource listening.");
        }
Ejemplo n.º 3
0
        // This demo shows how to use the stub APIs directly, without protecting against dynamic invocation exceptions.
        // The corresponding Net Core demo shows one of several possible ways for dealing with such exceptions.
        // Other demos show other approaches for dealing with these exceptions.

        public static void Main(string[] _)
        {
            ConsoleWrite.Line(typeof(Program).FullName);

            UseDiagnosticSourceStub.Run();

            ConsoleWrite.Line("Done. Press enter.");
            Console.ReadLine();
        }
        public static void Run()
        {
            // This demo shows one of several possible ways for dealing with dynamic invocation exceptions.
            // The corresponding Net Fx demo shows how to use the APIs directly.
            // Other demos show other approaches for dealing with these exceptions.

            ConsoleWrite.LineLine($"STARTING DEMO '{nameof(UseDiagnosticSourceStub)}'.");

            SetupListening();

            DiagnosticSourceSafeExtensions.Configure.LogComponentMoniker    = "Demo.Slimple.NetCore31";
            DiagnosticSourceSafeExtensions.Configure.IsLogExceptionsEnabled = true;

            ConsoleWrite.LineLine("Starting to create new Diagnostic Sources.");

            if (!DiagnosticSourceSafeExtensions.CreateNewSourceSafe("DemoXxx.UseDiagnosticSource.Name1", out DiagnosticSourceStub diagnosticSource1, out _))
            {
                ConsoleWrite.Line("Cannot create DiagnosticSource. Error was logged. Bailing out.");
                return;
            }

            if (!DiagnosticSourceSafeExtensions.CreateNewSourceSafe("DemoXxx.UseDiagnosticSource.Name2", out DiagnosticSourceStub diagnosticSource2, out _))
            {
                ConsoleWrite.Line("Cannot create DiagnosticSource. Error was logged. Bailing out.");
                return;
            }

            ConsoleWrite.Line("Finished creating new Diagnostic Sources.");

            ConsoleWrite.LineLine("Starting to emit DiagnosticSource events.");
            for (int i = 0; i < 1000; i++)
            {
                if (diagnosticSource1.IsEnabledSafe("EventXyzName.A", out bool isEventEnabled, out _) && isEventEnabled)
                {
                    diagnosticSource1.WriteSafe("EventXyzName", new EventXyzNamePayload("Foo", 42, i), out _);
                }

                if (diagnosticSource1.IsEnabledSafe("EventXyzName.B", arg1: "Something", arg2: 13.7, out isEventEnabled, out _) && isEventEnabled)
                {
                    diagnosticSource1.WriteSafe("EventXyzName", new EventXyzNamePayload("Bar", new[] { 1, 2, 3 }, i), out _);
                }

                if (diagnosticSource1.IsEnabledSafe("EventXyzName.C", arg1: -1, out isEventEnabled, out _) && isEventEnabled)
                {
                    diagnosticSource1.WriteSafe("EventXyzName", new EventXyzNamePayload(null, null, i), out _);
                }

                diagnosticSource2.WriteSafe("EventAbcName", new { Value = "Something", IterationNr = i }, out _);

                ConsoleWrite.LineLine($"-----------{i}-----------");
            }

            ConsoleWrite.Line("Finished to emit DiagnosticSource events.");

            ConsoleWrite.LineLine($"FINISHED DEMO '{nameof(UseDiagnosticSourceStub)}'.");
        }
Ejemplo n.º 5
0
        private async Task Plugin()
        {
            //const string DSAssemblyNameForPlugin = "System.Diagnostics.DiagnosticSource, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51";
            const string DSAssemblyFileForPlugin = "PluginRessource.System.Diagnostics.DiagnosticSource.dll";
            const int    RunningTimeMillis       = 500;

            string currentDirectory = Directory.GetCurrentDirectory();
            string assemblyPath     = Path.Combine(currentDirectory, DSAssemblyFileForPlugin);

            ConsoleWrite.LineLine($"Mock Plug-In: Loading assembly from \"{assemblyPath}\".");

            var      asmLoadCtx = new MockPluginAssemblyLoadContext();
            Assembly dsAsm      = asmLoadCtx.LoadFromAssemblyPath(assemblyPath);

            ConsoleWrite.Line($"Mock Plug-In: Assembly loaded ({dsAsm.FullName}) from \"{dsAsm.Location}\".");
            ConsoleWrite.Line($"Mock Plug-In: Doing mock work.");

            await Task.Delay(RunningTimeMillis);

            ConsoleWrite.LineLine($"Mock Plug-In: Mock work done. Unloading plugin and assemblies.");

            dsAsm = null;
            asmLoadCtx.Unload();

            var asmLoadCtxWeakRef = new WeakReference(asmLoadCtx);

            asmLoadCtx = null;

            int unloadWaitIterations = 0;

            while (asmLoadCtxWeakRef.IsAlive)
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
                unloadWaitIterations++;

                if (unloadWaitIterations % 100 == 0)
                {
                    ConsoleWrite.Line($"Plugin => Waiting To Unload => unloadIterations={unloadWaitIterations}.");
                }
                else if (unloadWaitIterations % 10 == 0)
                {
                    await Task.Delay(1);
                }
            }

            ConsoleWrite.LineLine($"Mock Plug-In: Plugin and assemblies unloaded. That's it.");
        }
Ejemplo n.º 6
0
        public static void Run()
        {
            // This demo shows how to use the stub APIs directly, without protecting against dynamic invocation exceptions.
            // The corresponding Net Core demo shows one of several possible ways for dealing with such exceptions.
            // Other demos show other approaches for dealing with these exceptions.

            ConsoleWrite.LineLine($"STARTING DEMO '{nameof(UseDiagnosticSourceStub)}'.");

            SetupListening();

            ConsoleWrite.LineLine("Starting to create new Diagnostic Sources.");

            DiagnosticSourceStub diagnosticSource1 = DiagnosticListening.CreateNewSource("DemoXxx.UseDiagnosticSource.Name1");
            DiagnosticSourceStub diagnosticSource2 = DiagnosticListening.CreateNewSource("DemoXxx.UseDiagnosticSource.Name2");

            ConsoleWrite.Line("Finished creating new Diagnostic Sources.");

            ConsoleWrite.LineLine("Starting to emit DiagnosticSource events.");
            for (int i = 0; i < 1000; i++)
            {
                if (diagnosticSource1.IsEnabled("EventXyzName.A"))
                {
                    diagnosticSource1.Write("EventXyzName", new EventXyzNamePayload("Foo", 42, i));
                }

                if (diagnosticSource1.IsEnabled("EventXyzName.B", arg1: "Something", arg2: 13.7))
                {
                    diagnosticSource1.Write("EventXyzName", new EventXyzNamePayload("Bar", new[] { 1, 2, 3 }, i));
                }

                if (diagnosticSource1.IsEnabled("EventXyzName.C", arg1: -1))
                {
                    diagnosticSource1.Write("EventXyzName", new EventXyzNamePayload(null, null, i));
                }

                diagnosticSource2.Write("EventAbcName", new { Value = "Something", IterationNr = i });

                ConsoleWrite.LineLine($"-----------{i}-----------");
            }

            ConsoleWrite.Line("Finished to emit DiagnosticSource events.");

            ConsoleWrite.LineLine($"FINISHED DEMO '{nameof(UseDiagnosticSourceStub)}'.");
        }
        private static void SetupListening()
        {
            ConsoleWrite.LineLine("Starting setting up DiagnosticSource listening.");

            if (!DiagnosticSourceSafeExtensions.SubscribeToAllSourcesSafe(ObserverAdapter.OnNextHandler(
                                                                              (DiagnosticListenerStub diagnosticListener) =>
            {
                diagnosticListener.GetNameSafe(out string diagnosticListenerName, out _);
                ConsoleWrite.Line($"Subscriber called: diagnosticSourceObserver(diagnosticListener.Name: \"{diagnosticListenerName}\")");

                if (diagnosticListenerName.Equals("DemoXxx.UseDiagnosticSource.Name1", StringComparison.Ordinal))
                {
                    if (!diagnosticListener.SubscribeToEventsSafe(
                            ObserverAdapter.OnNextHandler((KeyValuePair <string, object> eventInfo) =>
                    {
                        ConsoleWrite.Line($"Event Handler called: eventObserver(eventName: \"{eventInfo.Key}\", payloadValue: {(eventInfo.Value ?? "<null>")})");
                    }),
                            (string eventName, object arg1, object arg2) =>
                    {
                        Validate.NotNull(eventName, nameof(eventName));
                        bool res = eventName.StartsWith("EventXyzName", StringComparison.OrdinalIgnoreCase) &&
                                   (arg1 == null || !(arg1 is Int32 arg1Val) || arg1Val >= 0);
                        ConsoleWrite.Line($"Filter called: isEventEnabledFilter(eventName: \"{eventName}\", arg1: {(arg1 ?? "<null>")}, arg2: {(arg2 ?? "<null>")})."
                                          + $" Returning: {res}.");
                        return(res);
                    },
                            out IDisposable eventSubscription,
                            out _))
                    {
                        ConsoleWrite.LineLine("Could not set up an events subscription. Likely no events will be received. Error has been logged.");
                    }
                }
            }),
                                                                          out IDisposable listenerSubscription,
                                                                          out _))
            {
                ConsoleWrite.LineLine("Could not set up an all-sources-subscription. Likely no events will be received. Error has been logged.");
            }

            ConsoleWrite.Line("Finished setting up DiagnosticSource listening.");
        }
Ejemplo n.º 8
0
        private Assembly AssemblyResolveEventHandler(object sender, ResolveEventArgs args)
        {
            if (!GetPhaseOneCompleted())
            {
                ConsoleWrite.Line($"AssemblyResolveEventHandler: Phase One not completed => doing nothing.");
                return(null);
            }

            string asmNameRequestedStr = args?.Name;

            if (asmNameRequestedStr == null)
            {
                ConsoleWrite.Line($"AssemblyResolveEventHandler: No good arguments => doing nothing.");
                return(null);
            }

            string       dsAsmFilePath = Path.Combine(DiagnosticSourceAssemblyHiddenPath, DiagnosticSourceAssemblyFilename);
            AssemblyName asmNameAtPath = GetAssemblyNameFromPath(dsAsmFilePath);

            if (asmNameAtPath == null)
            {
                ConsoleWrite.Line($"AssemblyResolveEventHandler: Cannot extract assembly name from \"{dsAsmFilePath}\". Doing nothing.");
                return(null);
            }
            else
            {
                AssemblyName asmNameRequested = new AssemblyName(asmNameRequestedStr);
                if (AreEqual(asmNameAtPath, asmNameRequested))
                {
                    ConsoleWrite.Line($"AssemblyResolveEventHandler: Match. Loading DS from special location.");
                    return(Assembly.Load(asmNameAtPath));
                }
                else
                {
                    ConsoleWrite.Line($"AssemblyResolveEventHandler: No Match. Doing nothing.");
                    ConsoleWrite.Line($"    Requested assembly: \"{asmNameRequested.FullName}\";");
                    ConsoleWrite.Line($"    Present assembly:   \"{asmNameAtPath.FullName}\".");
                    return(null);
                }
            }
        }
        public static void Run()
        {
            ConsoleWrite.LineLine($"STARTING DEMO '{nameof(UseDiagnosticSource)}'.");

            SetupListening();

            ConsoleWrite.LineLine("Starting to create new Diagnostic Sources.");

            DiagnosticSource diagnosticSource1 = new DiagnosticListener("DemoXxx.UseDiagnosticSource.Name1");
            DiagnosticSource diagnosticSource2 = new DiagnosticListener("DemoXxx.UseDiagnosticSource.Name2");

            ConsoleWrite.Line("Finished creating new Diagnostic Sources.");

            ConsoleWrite.LineLine("Starting to emit DiagnosticSource events.");
            for (int i = 0; i < 1000; i++)
            {
                if (diagnosticSource1.IsEnabled("EventXyzName.A"))
                {
                    diagnosticSource1.Write("EventXyzName", new EventXyzNamePayload("Foo", 42, i));
                }

                if (diagnosticSource1.IsEnabled("EventXyzName.B", arg1: "Something", arg2: 13.7))
                {
                    diagnosticSource1.Write("EventXyzName", new EventXyzNamePayload("Bar", new[] { 1, 2, 3 }, i));
                }

                if (diagnosticSource1.IsEnabled("EventXyzName.C", arg1: -1))
                {
                    diagnosticSource1.Write("EventXyzName", new EventXyzNamePayload(null, null, i));
                }

                diagnosticSource2.Write("EventAbcName", new { Value = "Something", IterationNr = i });

                ConsoleWrite.LineLine($"-----------{i}-----------");
            }

            ConsoleWrite.Line("Finished to emit DiagnosticSource events.");

            ConsoleWrite.LineLine($"FINISHED DEMO '{nameof(UseDiagnosticSource)}'.");
        }
Ejemplo n.º 10
0
        public void Run()
        {
            const int MaxIterations      = 2000;
            const int PhaseOneIterations = 500;

            const int ReceivedEventsVisualWidth = 100;

            ConsoleWrite.Line();
            ConsoleWrite.Line($"Welcome to {this.GetType().FullName} in {Process.GetCurrentProcess().ProcessName}");

            ConsoleWrite.Line();
            ConsoleWrite.Line($"{nameof(HideDiagnosticSourceAssembly)} = {HideDiagnosticSourceAssembly}");

#pragma warning disable CS0162 // Unreachable code detected: intentional controll via a const bool.
            if (HideDiagnosticSourceAssembly)
            {
                string destination = Path.Combine(DiagnosticSourceAssemblyHiddenPath, DiagnosticSourceAssemblyFilename);

                try
                {
                    Directory.CreateDirectory(DiagnosticSourceAssemblyHiddenPath);

                    if (File.Exists(destination))
                    {
                        File.Delete(destination);
                    }
                }
                catch { }

                File.Move(DiagnosticSourceAssemblyFilename, destination);

                ConsoleWrite.Line($"Moved \"{DiagnosticSourceAssemblyFilename}\" to \"{destination}\".");

                ConsoleWrite.Line();
                ConsoleWrite.Line($"Setting up the AssemblyResolve handler for the current AppDomain.");

                AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolveEventHandler;
            }
            else
            {
                ConsoleWrite.Line("Did not hide the DS assembly.");
            }
#pragma warning restore CS0162 // Unreachable code detected

            ConsoleWrite.LineLine($"Setting up {nameof(StubbedDiagnosticEventsCollector)}.");

            var directResultsAccumulator  = new ReceivedEventsAccumulator(MaxIterations);
            var stubbedResultsAccumulator = new ReceivedEventsAccumulator(MaxIterations);
            var stubbedCollector          = new StubbedDiagnosticEventsCollector(directResultsAccumulator, stubbedResultsAccumulator);

            SetPhaseOneCompleted(false);

            ConsoleWrite.LineLine($"Starting {nameof(StubbedDiagnosticEventsGenerator)}.");

            var  stubbedGenerator     = new StubbedDiagnosticEventsGenerator(MaxIterations, PhaseOneIterations);
            Task stubbedGeneratorTask = Task.Run(stubbedGenerator.Run);

            stubbedGenerator.PhaseOneCompletedEvent.Wait();

            ConsoleWrite.LineLine($"Phase one of {nameof(stubbedGenerator)} completed.");
            SetPhaseOneCompleted(true);

            ConsoleWrite.Line($"Starting {nameof(DirectDiagnosticEventsGenerator)}.");

            var  directGenerator     = new DirectDiagnosticEventsGenerator(MaxIterations, PhaseOneIterations);
            Task directGeneratorTask = Task.Run(directGenerator.Run);

            Task.WaitAll(stubbedGeneratorTask, directGeneratorTask);

            ConsoleWrite.LineLine($"Both, {nameof(stubbedGenerator)} and {nameof(directGenerator)} finished.");

            ConsoleWrite.LineLine($"Summary of {nameof(stubbedResultsAccumulator)}:"
                                  + $" Received events: {stubbedResultsAccumulator.ReceivedCount}; Proportion: {stubbedResultsAccumulator.ReceivedProportion}.");
            ConsoleWrite.Line(Environment.NewLine + stubbedResultsAccumulator.GetReceivedVisual(ReceivedEventsVisualWidth));

            ConsoleWrite.LineLine($"Summary of {nameof(directResultsAccumulator)}:"
                                  + $" Received events: {directResultsAccumulator.ReceivedCount}; Proportion: {directResultsAccumulator.ReceivedProportion}.");
            ConsoleWrite.Line(Environment.NewLine + directResultsAccumulator.GetReceivedVisual(ReceivedEventsVisualWidth));

            ConsoleWrite.LineLine("All done. Press enter to exit.");

            Console.ReadLine();
            ConsoleWrite.Line("Good bye.");
        }
Ejemplo n.º 11
0
        public void Run()
        {
            const int MaxIterations      = 2000;
            const int PhaseOneIterations = 500;

            const int ReceivedEventsVisualWidth = 100;

            ConsoleWrite.LineLine($"Welcome to {this.GetType().FullName} in {Process.GetCurrentProcess().ProcessName}");

            ConsoleWrite.Line($"Starting {nameof(DirectDiagnosticEventsGenerator)}.");

            var  directGenerator     = new DirectDiagnosticEventsGenerator(MaxIterations, PhaseOneIterations);
            Task directGeneratorTask = Task.Run(directGenerator.Run);

            ConsoleWrite.LineLine($"Setting up {nameof(StubbedDiagnosticEventsCollector)}.");

            var directResultsAccumulator  = new ReceivedEventsAccumulator(MaxIterations);
            var stubbedResultsAccumulator = new ReceivedEventsAccumulator(MaxIterations);
            var stubbedCollector          = new StubbedDiagnosticEventsCollector(directResultsAccumulator, stubbedResultsAccumulator);

            {
                ConsoleWrite.LineLine($"Kicking off the DS magic.");
                bool prevInit = DiagnosticSourceAssembly.IsInitialized;
                bool nowInit  = DiagnosticSourceAssembly.EnsureInitialized();
                ConsoleWrite.Line($"DiagnosticSourceAssembly-magic status: prevInit={prevInit}, nowInit={nowInit}.");
            }

            directGenerator.PhaseOneCompletedEvent.Wait();

            ConsoleWrite.LineLine($"Phase one of {nameof(directGenerator)} completed.");

            ConsoleWrite.LineLine($"Starting {nameof(StubbedDiagnosticEventsGenerator)}.");

            var  stubbedGenerator     = new StubbedDiagnosticEventsGenerator(MaxIterations, PhaseOneIterations);
            Task stubbedGeneratorTask = Task.Run(stubbedGenerator.Run);

            stubbedGenerator.PhaseOneCompletedEvent.Wait();

            ConsoleWrite.LineLine($"Phase one of {nameof(stubbedGenerator)} completed.");

            ConsoleWrite.LineLine($"Starting Mock Plug-In."
                                  + $" directGen.Iteration={directGenerator.CurrentIteration}; stubbedGen.Iteration={stubbedGenerator.CurrentIteration}.");

            Task pulginTask = Task.Run(Plugin);

            pulginTask.Wait();

            ConsoleWrite.LineLine($"Completed Mock Plug-In."
                                  + $" directGen.Iteration={directGenerator.CurrentIteration}; stubbedGen.Iteration={stubbedGenerator.CurrentIteration}.");

            ConsoleWrite.LineLine($"Waiting for event generators to finish.");

            Task.WaitAll(stubbedGeneratorTask, directGeneratorTask);

            ConsoleWrite.LineLine($"Both, {nameof(stubbedGenerator)} and {nameof(directGenerator)} finished.");

            ConsoleWrite.LineLine($"Summary of {nameof(stubbedResultsAccumulator)}:"
                                  + $" Received events: {stubbedResultsAccumulator.ReceivedCount}; Proportion: {stubbedResultsAccumulator.ReceivedProportion}.");
            ConsoleWrite.Line(Environment.NewLine + stubbedResultsAccumulator.GetReceivedVisual(ReceivedEventsVisualWidth));

            ConsoleWrite.LineLine($"Summary of {nameof(directResultsAccumulator)}:"
                                  + $" Received events: {directResultsAccumulator.ReceivedCount}; Proportion: {directResultsAccumulator.ReceivedProportion}.");
            ConsoleWrite.Line(Environment.NewLine + directResultsAccumulator.GetReceivedVisual(ReceivedEventsVisualWidth));

            ConsoleWrite.LineLine("All done. Press enter to exit.");

            Console.ReadLine();
            ConsoleWrite.Line("Good bye.");
        }