Beispiel #1
0
        public void Test_BadEventSource_MismatchedIds()
        {
#if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864.
            // We expect only one session to be on when running the test but if a ETW session was left
            // hanging, it will confuse the EventListener tests.   
            EtwListener.EnsureStopped();
#endif // USE_ETW

            TestUtilities.CheckNoEventSourcesRunning("Start");
            var onStartups = new bool[] { false, true };
            var listenerGenerators = new Func<Listener>[]
            {
                () => new EventListenerListener(),
#if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864.
                () => new EtwListener()
#endif // USE_ETW
            };
            var settings = new EventSourceSettings[] { EventSourceSettings.Default, EventSourceSettings.EtwSelfDescribingEventFormat };

            // For every interesting combination, run the test and see that we get a nice failure message.  
            foreach (bool onStartup in onStartups)
            {
                foreach (Func<Listener> listenerGenerator in listenerGenerators)
                {
                    foreach (EventSourceSettings setting in settings)
                    {
                        Test_Bad_EventSource_Startup(onStartup, listenerGenerator(), setting);
                    }
                }
            }

            TestUtilities.CheckNoEventSourcesRunning("Stop");
        }
        [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))] // ActiveIssue: https://github.com/dotnet/corefx/issues/29754
        public void Test_BadEventSource_MismatchedIds_WithEtwListener()
        {
            // We expect only one session to be on when running the test but if a ETW session was left
            // hanging, it will confuse the EventListener tests.
            if (TestUtilities.IsProcessElevated)
            {
                EtwListener.EnsureStopped();
            }

            TestUtilities.CheckNoEventSourcesRunning("Start");
            var onStartups = new bool[] { false, true };

            var listenerGenerators = new List <Func <Listener> > {
                () => new EventListenerListener()
            };

            if (TestUtilities.IsProcessElevated)
            {
                listenerGenerators.Add(() => new EtwListener());
            }

            var settings = new EventSourceSettings[] { EventSourceSettings.Default, EventSourceSettings.EtwSelfDescribingEventFormat };

            // For every interesting combination, run the test and see that we get a nice failure message.
            foreach (bool onStartup in onStartups)
            {
                foreach (Func <Listener> listenerGenerator in listenerGenerators)
                {
                    foreach (EventSourceSettings setting in settings)
                    {
                        Test_Bad_EventSource_Startup(onStartup, listenerGenerator(), setting);
                    }
                }
            }

            TestUtilities.CheckNoEventSourcesRunning("Stop");
        }
Beispiel #3
0
        public void WhenEnumsInPayload()
        {
            var validConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["valid"].ConnectionString;

            DatabaseHelper.CleanLoggingDB(validConnectionString);
            var logger = MockEventSourceOutProcEnum.Logger;
            EventTextFormatter formatter = new EventTextFormatter();

            System.Data.DataTable eventsDataTable = null;
            var subject = new EventEntrySubject();

            subject.LogToSqlDatabase("testInstance", validConnectionString, "Traces", bufferingCount: 1);
            EventSourceSettings settings     = new EventSourceSettings("MockEventSourceOutProcEnum", null, EventLevel.LogAlways);
            SinkSettings        sinkSettings = new SinkSettings("sqlDBsink", subject, new List <EventSourceSettings>()
            {
                { settings }
            });
            List <SinkSettings> sinks = new List <SinkSettings>()
            {
                { sinkSettings }
            };
            TraceEventServiceConfiguration svcConfiguration = new TraceEventServiceConfiguration(sinks);

            TestScenario.WithConfiguration(
                svcConfiguration,
                () =>
            {
                logger.SendEnumsEvent16(MockEventSourceOutProcEnum.MyColor.Blue, MockEventSourceOutProcEnum.MyFlags.Flag3);

                eventsDataTable = DatabaseHelper.PollUntilEventsAreWritten(validConnectionString, 1);
            });

            Assert.AreEqual(1, eventsDataTable.Rows.Count);
            StringAssert.Contains(eventsDataTable.Rows[0]["payload"].ToString(), @"""a"": 1");
            StringAssert.Contains(eventsDataTable.Rows[0]["payload"].ToString(), @"""b"": 4");
        }
Beispiel #4
0
 protected EventSource(EventSourceSettings settings);
Beispiel #5
0
 public EventSourceTestByteArray(EventSourceSettings settings) : base(settings)
 {
 }
Beispiel #6
0
        private void Test_WriteEvent_ByteArray(bool useSelfDescribingEvents, Listener listener)
        {
            EventSourceSettings settings = EventSourceSettings.EtwManifestEventFormat;

            if (useSelfDescribingEvents)
            {
                settings = EventSourceSettings.EtwSelfDescribingEventFormat;
            }

            using (var logger = new EventSourceTestByteArray(settings))
            {
                var tests = new List <SubTest>();
                /*************************************************************************/
                /**************************** byte[] TESTING *****************************/
                /*************************************************************************/
                // We only support arrays of any type with the SelfDescribing case.
                /*************************************************************************/
                byte[] blob = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
                tests.Add(new SubTest("Write/Array/EventWithByteArrayArg",
                                      delegate()
                {
                    logger.EventWithByteArrayArg(blob, 1000);
                },
                                      delegate(Event evt)
                {
                    Assert.Equal(logger.Name, evt.ProviderName);
                    Assert.Equal("EventWithByteArrayArg", evt.EventName);

                    if (evt.IsEventListener)
                    {
                        byte[] retBlob = (byte[])evt.PayloadValue(0, "blob");
                        Assert.NotNull(retBlob);
                        Assert.True(Equal(blob, retBlob));
                        Assert.Equal(1000, (int)evt.PayloadValue(1, "n"));
                    }
                }));

                if (!useSelfDescribingEvents)
                {
                    /*************************************************************************/
                    tests.Add(new SubTest("Write/Array/NonEventCallingEventWithBytePtrArg",
                                          delegate()
                    {
                        logger.NonEventCallingEventWithBytePtrArg(blob, 2, 4, 1001);
                    },
                                          delegate(Event evt)
                    {
                        Assert.Equal(logger.Name, evt.ProviderName);
                        Assert.Equal("EventWithBytePtrArg", evt.EventName);

                        if (evt.IsEtw)
                        {
                            Assert.Equal(2, evt.PayloadCount);
                            byte[] retBlob = (byte[])evt.PayloadValue(0, "blob");
                            Assert.Equal(4, retBlob.Length);
                            Assert.Equal(retBlob[0], blob[2]);
                            Assert.Equal(retBlob[3], blob[2 + 3]);
                            Assert.Equal(1001, (int)evt.PayloadValue(1, "n"));
                        }
                        else
                        {
                            Assert.Equal(3, evt.PayloadCount);
                            byte[] retBlob = (byte[])evt.PayloadValue(1, "blob");
                            Assert.Equal(1001, (int)evt.PayloadValue(2, "n"));
                        }
                    }));
                }

                tests.Add(new SubTest("Write/Array/EventWithLongByteArray",
                                      delegate()
                {
                    logger.EventWithLongByteArray(blob, 1000);
                },
                                      delegate(Event evt)
                {
                    Assert.Equal(logger.Name, evt.ProviderName);
                    Assert.Equal("EventWithLongByteArray", evt.EventName);

                    Assert.Equal(2, evt.PayloadCount);
                    byte[] retBlob = (byte[])evt.PayloadValue(0, "blob");
                    Assert.True(Equal(blob, retBlob));

                    Assert.Equal(1000, (long)evt.PayloadValue(1, "lng"));
                }));

                // If you only wish to run one or several of the tests you can filter them here by
                // Uncommenting the following line.
                // tests = tests.FindAll(test => Regex.IsMatch(test.Name, "ventWithByteArray"));

                // Next run the same tests with the TraceLogging path.
                EventTestHarness.RunTests(tests, listener, logger);
            }
        }
 public BadEventSource_MismatchedIds(EventSourceSettings settings) : base(settings)
 {
 }
Beispiel #8
0
 public EventSourceCreatedMessage(string name, Guid guid, EventSourceSettings settings) : this()
 {
     Name     = name;
     Guid     = guid;
     Settings = settings;
 }
Beispiel #9
0
        /// <summary>
        /// A helper that can run the test under a variety of conditions
        /// * Whether the eventSource is enabled at startup
        /// * Whether the listener is ETW or an EventListern
        /// * Whether the ETW output is self describing or not.  
        /// </summary>
        private void Test_Bad_EventSource_Startup(bool onStartup, Listener listener, EventSourceSettings settings)
        {
            var eventSourceName = typeof(BadEventSource_MismatchedIds).Name;
            Debug.WriteLine("***** Test_BadEventSource_Startup(OnStartUp: " + onStartup + " Listener: " + listener + " Settings: " + settings + ")");

            // Activate the source before the source exists (if told to).  
            if (onStartup)
                listener.EventSourceCommand(eventSourceName, EventCommand.Enable);

            var events = new List<Event>();
            listener.OnEvent = delegate (Event data) { events.Add(data); };

            using (var source = new BadEventSource_MismatchedIds(settings))
            {
                Assert.Equal(eventSourceName, source.Name);
                // activate the source after the source exists (if told to).  
                if (!onStartup)
                    listener.EventSourceCommand(eventSourceName, EventCommand.Enable);
                source.Event1(1);       // Try to send something.  
            }
            listener.Dispose();

            // Confirm that we get exactly one event from this whole process, that has the error message we expect.  
            Assert.Equal(events.Count, 1);
            Event _event = events[0];
            Assert.Equal("EventSourceMessage", _event.EventName);
            string message = _event.PayloadString(0, "message");
            Debug.WriteLine(String.Format("Message=\"{0}\"", message));
            // expected message: "ERROR: Exception in Command Processing for EventSource BadEventSource_MismatchedIds: Event Event2 is given event ID 2 but 1 was passed to WriteEvent. "
            Assert.True(Regex.IsMatch(message, "Event Event2 is givien event ID 2 but 1 was passed to WriteEvent"));
        }
Beispiel #10
0
 public EventSource(string eventSourceName, EventSourceSettings config, params string[] traits);
 /// <summary>
 /// Construct an EventSource with a given name for non-contract based events (e.g. those using the Write() API).
 ///
 /// Also specify a list of key-value pairs called traits (you must pass an even number of strings).
 /// The first string is the key and the second is the value.   These are not interpreted by EventSource
 /// itself but may be interpreted the listeners.  Can be fetched with GetTrait(string).
 /// </summary>
 /// <param name="eventSourceName">
 /// The name of the event source. Must not be null.
 /// </param>
 /// <param name="config">
 /// Configuration options for the EventSource as a whole.
 /// </param>
 /// <param name="traits">A collection of key-value strings (must be an even number).</param>
 public EventSource(
     string eventSourceName,
     EventSourceSettings config,
     params string[]?traits)
     : this(
         GenerateGuidFromName((eventSourceName ?? throw new ArgumentNullException(nameof(eventSourceName))).ToUpperInvariant()),
Beispiel #12
0
 public EventSourceTestByteArray(EventSourceSettings settings) : base(settings) { }
Beispiel #13
0
        /// <summary>
        /// A helper that can run the test under a variety of conditions
        /// * Whether the eventSource is enabled at startup
        /// * Whether the listener is ETW or an EventListern
        /// * Whether the ETW output is self describing or not.
        /// </summary>
        private void Test_Bad_EventSource_Startup(bool onStartup, Listener listener, EventSourceSettings settings)
        {
            var eventSourceName = typeof(BadEventSource_MismatchedIds).Name;

            Debug.WriteLine("***** Test_BadEventSource_Startup(OnStartUp: " + onStartup + " Listener: " + listener + " Settings: " + settings + ")");

            // Activate the source before the source exists (if told to).
            if (onStartup)
            {
                listener.EventSourceCommand(eventSourceName, EventCommand.Enable);
            }

            var events = new List <Event>();

            listener.OnEvent = delegate(Event data) { events.Add(data); };

            using (var source = new BadEventSource_MismatchedIds(settings))
            {
                Assert.Equal(eventSourceName, source.Name);
                // activate the source after the source exists (if told to).
                if (!onStartup)
                {
                    listener.EventSourceCommand(eventSourceName, EventCommand.Enable);
                }
                source.Event1(1);       // Try to send something.
            }
            listener.Dispose();

            // Confirm that we get exactly one event from this whole process, that has the error message we expect.
            Assert.Equal(1, events.Count);
            Event _event = events[0];

            Assert.Equal("EventSourceMessage", _event.EventName);
            string message = _event.PayloadString(0, "message");

            Debug.WriteLine(string.Format("Message=\"{0}\"", message));
            // expected message: "ERROR: Exception in Command Processing for EventSource BadEventSource_MismatchedIds: Event Event2 was assigned event ID 2 but 1 was passed to WriteEvent. "
            if (!PlatformDetection.IsNetFramework) // .NET Framework has typo
            {
                Assert.Contains("Event Event2 was assigned event ID 2 but 1 was passed to WriteEvent", message);
            }

            // Validate the details of the EventWrittenEventArgs object
            if (_event is EventListenerListener.EventListenerEvent elEvent)
            {
                EventWrittenEventArgs ea = elEvent.Data;
                Assert.NotNull(ea);
                Assert.Equal(EventSource.CurrentThreadActivityId, ea.ActivityId);
                Assert.Equal(EventChannel.None, ea.Channel);
                Assert.Equal(0, ea.EventId);
                Assert.Equal("EventSourceMessage", ea.EventName);
                Assert.NotNull(ea.EventSource);
                Assert.Equal(EventKeywords.None, ea.Keywords);
                Assert.Equal(EventLevel.LogAlways, ea.Level);
                Assert.Equal((EventOpcode)0, ea.Opcode);
                Assert.NotNull(ea.Payload);
                Assert.NotNull(ea.PayloadNames);
                Assert.Equal(ea.PayloadNames.Count, ea.Payload.Count);
                Assert.Equal(Guid.Empty, ea.RelatedActivityId);
                Assert.Equal(EventTags.None, ea.Tags);
                Assert.Equal(EventTask.None, ea.Task);
                Assert.InRange(ea.TimeStamp, DateTime.MinValue, DateTime.MaxValue);
                Assert.Equal(0, ea.Version);
            }
        }
        public void TwoCollectorsSameEventSourceDifferentSinkTypes()
        {
            var validConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["valid"].ConnectionString;

            DatabaseHelper.CleanLoggingDB(validConnectionString);
            string fileName = "TwoCollectorsSameEventSourceDifferentSinkTypes.log";

            File.Delete(fileName);
            string              header    = "===========";
            var                 logger    = MockEventSourceOutProc.Logger;
            EventTextFormatter  formatter = new EventTextFormatter(header);
            EventSourceSettings settings  = new EventSourceSettings("MockEventSourceOutProc", null, EventLevel.LogAlways);

            var subject = new EventEntrySubject();

            subject.LogToSqlDatabase("testInstance", validConnectionString, "Traces", TimeSpan.FromSeconds(1), 1);
            SinkSettings sinkSettings = new SinkSettings("dbSink", subject, new List <EventSourceSettings>()
            {
                { settings }
            });

            var subject2 = new EventEntrySubject();

            subject2.LogToFlatFile(fileName, formatter);
            SinkSettings sinkSettings2 = new SinkSettings("ffSink", subject2, new List <EventSourceSettings>()
            {
                { settings }
            });

            System.Data.DataTable eventsDataTable = null;
            List <SinkSettings>   sinks           = new List <SinkSettings>()
            {
                sinkSettings, sinkSettings2
            };
            TraceEventServiceConfiguration svcConfiguration = new TraceEventServiceConfiguration(sinks);
            IEnumerable <string>           entries          = null;

            using (TraceEventService collector = new TraceEventService(svcConfiguration))
                using (TraceEventService collector2 = new TraceEventService(svcConfiguration))
                {
                    collector.Start();
                    collector2.Start();
                    try
                    {
                        for (int n = 0; n < 10; n++)
                        {
                            logger.LogSomeMessage("some message" + n.ToString());
                        }

                        eventsDataTable = DatabaseHelper.PollUntilEventsAreWritten(validConnectionString, 10);

                        entries = FlatFileHelper.PollUntilTextEventsAreWritten(fileName, 10, header);
                    }
                    finally
                    {
                        collector.Stop();
                        collector2.Stop();
                    }
                }

            Assert.AreEqual(10, eventsDataTable.Rows.Count);
            StringAssert.Contains(eventsDataTable.Rows[0]["payload"].ToString(), "some message");

            Assert.AreEqual(10, entries.Count());
            StringAssert.Contains(entries.First(), "some message0");
            StringAssert.Contains(entries.Last(), "some message9");
        }
Beispiel #15
0
 public BadEventSource_MismatchedIds(EventSourceSettings settings) : base(settings) { }
Beispiel #16
0
 protected EventSource(EventSourceSettings settings, params string[] traits);
Beispiel #17
0
 public EventSource(string eventSourceName, EventSourceSettings config);
Beispiel #18
0
 protected EventSource(EventSourceSettings settings)
     : this()
 {
     this.Settings = settings;
 }
 public EventSource(
     string eventSourceName,
     EventSourceSettings config)
     : this(eventSourceName, config, null)
 {
 }
Beispiel #20
0
 public EventSource(string eventSourceName, EventSourceSettings config)
     : this(eventSourceName)
 {
     this.Settings = config;
 }