public void WhenUsingRollingSinkProgrammatic()
        {
            var logger = MockEventSourceOutProc.Logger;
            EventTextFormatter formatter = new EventTextFormatter(EventTextFormatter.DashSeparator);
            var fileName = "newRollingFlatfileSerial.log";
            File.Delete(fileName);
            EventSourceSettings settings = new EventSourceSettings("MockEventSourceOutProc", null, EventLevel.LogAlways);
            var subject = new EventEntrySubject();
            subject.LogToRollingFlatFile(fileName, 100, "d", RollFileExistsBehavior.Overwrite, RollInterval.Day, formatter);

            SinkSettings sinkSettings = new SinkSettings("rollingFlatFileSink", subject, new List<EventSourceSettings>() { { settings } });
            List<SinkSettings> sinks = new List<SinkSettings>() { { sinkSettings } };
            TraceEventServiceConfiguration svcConfiguration = new TraceEventServiceConfiguration(sinks);
            IEnumerable<string> entries = null;
            TestScenario.WithConfiguration(
                svcConfiguration,
                () =>
                {
                    for (int n = 0; n < 200; n++)
                    {
                        logger.LogSomeMessage("some message" + n.ToString());
                    }

                    entries = FlatFileHelper.PollUntilTextEventsAreWritten(fileName, 200, EventTextFormatter.DashSeparator);
                });

            Assert.AreEqual(200, entries.Count());
            StringAssert.Contains(entries.First(), "some message0");
            StringAssert.Contains(entries.Last(), "some message199");
        }
        public void WhenUsingSinkProgrammatically()
        {
            var validConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["valid"].ConnectionString;
            DatabaseHelper.CleanLoggingDB(validConnectionString);
            var logger = MockEventSourceOutProc.Logger;
            EventTextFormatter formatter = new EventTextFormatter();
            EventSourceSettings settings = new EventSourceSettings("MockEventSourceOutProc", null, EventLevel.LogAlways);
            var subject = new EventEntrySubject();
            subject.LogToSqlDatabase("testInstance", validConnectionString, "Traces", TimeSpan.FromSeconds(1), 1);

            System.Data.DataTable eventsDataTable = null;
            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,
                () =>
                {
                    for (int n = 0; n < 10; n++)
                    {
                        logger.LogSomeMessage("some message" + n.ToString());
                    }

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

            Assert.AreEqual(10, eventsDataTable.Rows.Count);
            StringAssert.Contains(eventsDataTable.Rows[0]["payload"].ToString(), "some message");
        }
        public void WhenConfiguringProgrammatically()
        {
            this.tableName = "testoutofprocazuretables";
            var connectionString = System.Configuration.ConfigurationManager.AppSettings["StorageConnectionString"];
            AzureTableHelper.DeleteTable(connectionString, this.tableName);
            var logger = MockEventSourceOutProc.Logger;
            EventTextFormatter formatter = new EventTextFormatter();

            IEnumerable<WindowsAzureTableEventEntry> events = null;
            EventSourceSettings settings = new EventSourceSettings("MockEventSourceOutProc", null, EventLevel.LogAlways);
            var subject = new EventEntrySubject();
            subject.LogToWindowsAzureTable("AzureInstance", connectionString, tableName, TimeSpan.FromSeconds(1));
            SinkSettings sinkSettings = new SinkSettings("azureSink", subject, new List<EventSourceSettings>() { { settings } });
            List<SinkSettings> sinks = new List<SinkSettings>() { { sinkSettings } };
            TraceEventServiceConfiguration svcConfiguration = new TraceEventServiceConfiguration(sinks);
            TestScenario.WithConfiguration(
                svcConfiguration,
                () =>
                {
                    for (int i = 0; i < 10; i++)
                    {
                        logger.Critical("Critical message");
                    }

                    events = AzureTableHelper.PollForEvents(connectionString, this.tableName, 10);
                });

            Assert.AreEqual<int>(10, events.Count());
            Assert.AreEqual<int>(2, events.First().EventId);
        }
        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");
        }
        public void WhenConcurrentEventsRaised()
        {
            var logger = MockEventSourceOutProc.Logger;
            EventTextFormatter formatter = new EventTextFormatter();
            EventSourceSettings settings = new EventSourceSettings("MockEventSourceOutProc", null, EventLevel.LogAlways);
            InMemorySink sink = new InMemorySink(formatter);

            SinkSettings sinkSettings = new SinkSettings("memorySink", sink, new List<EventSourceSettings>() { { settings } });
            List<SinkSettings> sinks = new List<SinkSettings>() { { sinkSettings } };
            TraceEventServiceConfiguration svcConfiguration = new TraceEventServiceConfiguration(sinks);
            TestScenario.WithConfiguration(
                svcConfiguration,
                () =>
                {
                    sink.WaitSignalCondition = () => sink.EventWrittenCount == 100;
                    for (int n = 0; n < 100; n++)
                    {
                        logger.LogSomeMessage("some message" + n.ToString());
                    }

                    sink.WaitOnAsyncEvents.WaitOne(TimeSpan.FromSeconds(10));
                });

            StringAssert.Contains(sink.ToString(), "some message99");
        }
        public void when_creating_instance_with_default_values()
        {
            var sources = new List<EventSourceSettings>() { new EventSourceSettings(MyCompanyEventSource.Log.Name) };
            var sink = new InMemoryEventListener();
            var sut = new SinkSettings("test", sink, sources);

            Assert.AreEqual("test", sut.Name);
            Assert.AreEqual(sink, sut.Sink);
            Assert.AreEqual(1, sut.EventSources.Count());
        }
        public TraceEventServiceWorker(SinkSettings sinkSettings, TraceEventServiceSettings serviceSettings)
        {
            Guard.ArgumentNotNull(sinkSettings, "sinkSettings");
            Guard.ArgumentNotNull(serviceSettings, "serviceSettings");

            this.sink = sinkSettings.Sink;
            this.eventSources = new List<EventSourceSettings>(sinkSettings.EventSources);
            this.sessionName = serviceSettings.SessionNamePrefix + "-" + sinkSettings.Name;
            this.Initialize();
        }
        public void when_creating_instance_with_duplicate_sinkSettings()
        {
            var sinks = new List<SinkSettings>();

            var sources = new List<EventSourceSettings>() { new EventSourceSettings("test"), new EventSourceSettings("test") };
            var sink = new SinkSettings("test", new Lazy<IObserver<EventEntry>>(() => new InMemoryEventListener()), sources);
            sinks.Add(sink);
            sinks.Add(sink);

            new TraceEventServiceConfiguration(sinks);
        }
        public void WhenUsingTwoCollectorsForSameEventSourceWithDifferentSinkTypes()
        {
            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");
        }
        public void WhenUsingTwoCollectorsForSameEventSource()
        {
            var validConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["valid"].ConnectionString;
            DatabaseHelper.CleanLoggingDB(validConnectionString);
            var logger = MockEventSourceOutProc.Logger;
            EventTextFormatter formatter = new EventTextFormatter();
            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.LogToSqlDatabase("testInstance", validConnectionString, "Traces", TimeSpan.FromSeconds(1), 1);
            SinkSettings sinkSettings2 = new SinkSettings("dbSink2", subject2, new List<EventSourceSettings>() { { settings } });

            System.Data.DataTable eventsDataTable = null;
            List<SinkSettings> sinks = new List<SinkSettings>() { sinkSettings, sinkSettings2 };
            TraceEventServiceConfiguration svcConfiguration = new TraceEventServiceConfiguration(sinks);
            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, 20);
                }
                finally
                {
                    collector.Stop();
                    collector2.Stop();
                }
            }

            Assert.AreEqual(20, eventsDataTable.Rows.Count);
            StringAssert.Contains(eventsDataTable.Rows[0]["payload"].ToString(), "some message");
        }
        public void WhenCustomFormatterThrowsAnExceptionAndUsedProgramatically()
        {
            string fileName = "FlatFileOutProcCustomFormatterHandleException.log";
            File.Delete(fileName);
            var logger = MockEventSourceOutProc.Logger;
            MockFormatter formatter = new MockFormatter(true); //this formatter throws

            EventSourceSettings settings = new EventSourceSettings("MockEventSourceOutProc", null, EventLevel.Informational);
            var subject = new EventEntrySubject();
            subject.LogToFlatFile(fileName, formatter);
            SinkSettings sinkSettings = new SinkSettings("flatFileSink", subject, new List<EventSourceSettings>() { { settings } });
            List<SinkSettings> sinks = new List<SinkSettings>() { { sinkSettings } };
            TraceEventServiceConfiguration svcConfiguration = new TraceEventServiceConfiguration(sinks);
            TestScenario.WithConfiguration(
                svcConfiguration,
                () =>
                {
                    using (var collectErrorsListener = new InMemoryEventListener())
                    {
                        try
                        {
                            collectErrorsListener.EnableEvents(SemanticLoggingEventSource.Log, EventLevel.LogAlways, Keywords.All);

                            logger.LogSomeMessage("some message using formatter that throws");
                            collectErrorsListener.WaitEvents.Wait(5000);

                            StringAssert.Contains(collectErrorsListener.ToString(), "Payload : [message : System.InvalidOperationException: Operation is not valid due to the current state of the object.");
                        }
                        finally
                        {
                            collectErrorsListener.DisableEvents(SemanticLoggingEventSource.Log);
                        }
                    }
                });
        }
        public void WhenInfoAndMoreVerboseLevelsAreFiltered()
        {
            var logger = MockEventSourceOutProc.Logger;
            EventTextFormatter formatter = new EventTextFormatter(EventTextFormatter.DashSeparator);
            var fileName = "FlatFileAllFiltered.log";
            File.Delete(fileName);

            EventSourceSettings settings = new EventSourceSettings("MockEventSourceOutProc", null, EventLevel.Error);
            var subject = new EventEntrySubject();
            subject.LogToFlatFile(fileName, formatter);

            SinkSettings sinkSettings = new SinkSettings("flatFileSink", subject, new List<EventSourceSettings>() { { settings } });
            List<SinkSettings> sinks = new List<SinkSettings>() { { sinkSettings } };
            TraceEventServiceConfiguration svcConfiguration = new TraceEventServiceConfiguration(sinks);
            IEnumerable<string> entries = null;
            TestScenario.WithConfiguration(
                svcConfiguration,
                () =>
                {
                    for (int n = 0; n < 200; n++)
                    {
                        logger.LogSomeMessage("some message " + n.ToString());
                        logger.Critical("some error " + n.ToString());
                    }

                    entries = FlatFileHelper.PollUntilTextEventsAreWritten(fileName, 200, EventTextFormatter.DashSeparator);
                });

            Assert.AreEqual(200, entries.Count());
            StringAssert.Contains(entries.First(), "some error 0");
            StringAssert.Contains(entries.Last(), "some error 199");
        }
        public void WhenSinkNameIsDuplicated1()
        {
            var validConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["valid"].ConnectionString;
            DatabaseHelper.CleanLoggingDB(validConnectionString);
            var logger = MockEventSourceOutProc.Logger;

            EventSourceSettings settings = new EventSourceSettings("MockEventSourceOutProc", null, EventLevel.LogAlways);
            var subject = new EventEntrySubject();
            subject.LogToSqlDatabase("testInstance", validConnectionString, "Traces", TimeSpan.FromSeconds(10), 200);
            SinkSettings sinkSettings = new SinkSettings("dbSink", subject, new List<EventSourceSettings>() { { settings } });
            var subject2 = new EventEntrySubject();
            subject2.LogToSqlDatabase("testInstance", validConnectionString, "Traces", TimeSpan.FromSeconds(10), 200);
            SinkSettings sinkSettings2 = new SinkSettings("dbSink", subject2, new List<EventSourceSettings>() { { settings } });
            List<SinkSettings> sinks = new List<SinkSettings>() { sinkSettings, sinkSettings2 };
            var exc = ExceptionAssertHelper.
                Throws<Microsoft.Practices.EnterpriseLibrary.SemanticLogging.Etw.Configuration.ConfigurationException>(
                            () => new TraceEventServiceConfiguration(sinks));

            StringAssert.Contains(exc.ToString(), "Duplicate sinks");
        }
 protected override void Given()
 {
     this.sinkSettings = new SinkSettings("test", new InMemoryEventListener(), new[] { new EventSourceSettings("Test") });
     this.traceEventServiceSettings = new TraceEventServiceSettings();
 }
        public void WhenThreadId()
        {
            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.SaveExpenseStarted(Guid.NewGuid());

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

            Assert.AreEqual(1, eventsDataTable.Rows.Count);
            Assert.AreEqual(ThreadHelper.GetCurrentUnManagedThreadId(), Convert.ToInt32(eventsDataTable.Rows[0]["ThreadId"]));
        }
        public void WhenUsingCustomFormatterProgramatically()
        {
            string fileName = "FlatFileCustomFormatterProgrammatic.log";
            File.Delete(fileName);
            var logger = MockEventSourceOutProc.Logger;
            CustomFormatterWithWait formatter = new CustomFormatterWithWait();
            formatter.Detailed = EventLevel.LogAlways;
            formatter.Header = "---------------";
            formatter.DateTimeFormat = "d";

            IEnumerable<string> entries = null;
            EventSourceSettings settings = new EventSourceSettings("MockEventSourceOutProc", null, EventLevel.Critical);
            var subject = new EventEntrySubject();
            subject.LogToFlatFile(fileName, formatter);
            SinkSettings sinkSettings = new SinkSettings("flatFileSink", subject, new List<EventSourceSettings>() { { settings } });
            List<SinkSettings> sinks = new List<SinkSettings>() { { sinkSettings } };
            TraceEventServiceConfiguration svcConfiguration = new TraceEventServiceConfiguration(sinks);
            TestScenario.WithConfiguration(
                svcConfiguration,
                () =>
                {
                    logger.Critical("some message using formatter");

                    entries = FlatFileHelper.PollUntilTextEventsAreWritten(fileName, 1, "---------------");
                });

            StringAssert.Contains(entries.First(), "Mock SourceId");
            StringAssert.Contains(entries.First(), "Mock EventId");
            StringAssert.Contains(entries.First(), "Payload : [message : some message using formatter]");
        }
            protected override void When()
            {
                var current = this.configuration.SinkSettings[0];
                current.EventSources.First().Level = EventLevel.Warning;
                var newSink = new SinkSettings(current.Name, current.Sink, current.EventSources);

                // will trigger changed event
                this.configuration.SinkSettings.Remove(current);
                this.configuration.SinkSettings.Add(newSink);
            }
            protected override void When()
            {
                var current = this.configuration.SinkSettings[0];
                var newSources = new List<EventSourceSettings>(current.EventSources);
                newSources.Add(new EventSourceSettings(EventSource.GetName(typeof(TestEventSource))));
                var newSink = new SinkSettings(current.Name, current.Sink, newSources);

                // will trigger changed event
                this.configuration.SinkSettings.Remove(current);
                this.configuration.SinkSettings.Add(newSink);

                // We expect 2 events
                this.inMemoryListener.WaitSignalCondition = () => inMemoryListener.EventWrittenCount == 2;
            }
        public void WhenUsingCustomSinkProgrammatically()
        {
            string fileName = "ProvidedCustomSink.log";
            File.Delete(fileName);
            var logger = MockEventSourceOutProc.Logger;
            var formatter = new EventTextFormatter();

            IEnumerable<string> entries = null;
            var subject = new EventEntrySubject();
            subject.LogToMockFlatFile(fileName, "==-==");
            EventSourceSettings settings = new EventSourceSettings("MockEventSourceOutProc", null, EventLevel.LogAlways);
            SinkSettings sinkSettings = new SinkSettings("MockFlatFileSink", subject, new List<EventSourceSettings>() { { settings } });
            List<SinkSettings> sinks = new List<SinkSettings>() { { sinkSettings } };
            TraceEventServiceConfiguration svcConfiguration = new TraceEventServiceConfiguration(sinks);
            TestScenario.WithConfiguration(
                svcConfiguration,
                () =>
                {
                    logger.LogSomeMessage("some message");
                    logger.LogSomeMessage("some message2");
                    logger.LogSomeMessage("some message3");

                    entries = FlatFileHelper.PollUntilTextEventsAreWritten(fileName, 3, "==-==");
                });

            Assert.AreEqual<int>(3, entries.Count());
            Assert.IsNotNull(entries.SingleOrDefault(e => e.Contains("Payload : [message : some message]")));
            Assert.IsNotNull(entries.SingleOrDefault(e => e.Contains("Payload : [message : some message2]")));
            Assert.IsNotNull(entries.SingleOrDefault(e => e.Contains("Payload : [message : some message3]")));
        }