Inheritance: TextWriterTraceListener
        public void when_tracing_activity_then_builds_trace_log()
        {
            if (File.Exists(LogFile))
                File.Delete(LogFile);

            var xml = new XmlWriterTraceListener(LogFile, "Xml");

            manager.AddListener("*", xml);
            manager.SetTracingLevel("*", SourceLevels.All);

            var tracer = Tracer.Get("Foo");

            using (tracer.StartActivity("Outer"))
            {
                tracer.Info("Hello info from outer");
                using (tracer.StartActivity("Inner"))
                {
                    tracer.Warn("Warn from inner");
                    Tracer.Get("Foo.Bar").Error("Something failed on another class!");
                }
            }

            xml.Flush();
            System.Threading.Thread.Sleep(1000);
            xml.Close();

            Process.Start(SvcViewer, new FileInfo(LogFile).FullName);
        }
Esempio n. 2
0
        static void Main()
        {
            DumpMaker.PathToDirectory = Application.StartupPath;

            // Получаем аргументы коммандной строки
            String[] args = Environment.GetCommandLineArgs();
            
            //_Trace.Switch.Level = SourceLevels.Error;
            String pathToExe = Application.StartupPath + @"\AppXmlLog.xml";
            _XmlLog = new XmlWriterTraceListener(pathToExe, "XmlLog");
            _XmlLog.TraceOutputOptions |= (TraceOptions.Callstack | TraceOptions.DateTime |
                TraceOptions.LogicalOperationStack | TraceOptions.ProcessId | 
                TraceOptions.ThreadId | TraceOptions.Timestamp);
            _XmlLog.Filter = new EventTypeFilter(SourceLevels.Error);
            _Trace.Listeners.Add(_XmlLog);

            //Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);

            //AppDomain.CurrentDomain.UnhandledException += DumpMaker.CurrentDomain_UnhandledException;
            
            
            // Событие необработанного исключения в других потоках
            //Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
            // Set the unhandled exception mode to force all Windows Forms errors to go through
            // our handler.
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException, true);
            
            // Событие необработанного исключения на уровне приложения
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new FormMain(args)); 
        }
		public void WriteLine1 ()
		{
			StringWriter sw = new StringWriter ();
			XmlWriterTraceListener x = new XmlWriterTraceListener (sw);
			x.WriteLine ("sample");
			x.Close ();
			Assert.AreEqual (sample1.Replace ('\'', '"'), sw.ToString ());
		}
		public void TraceEvent2 ()
		{
			StringWriter sw = new StringWriter ();
			XmlWriterTraceListener x = new XmlWriterTraceListener (sw);
			x.TraceEvent (null, "bulldog", TraceEventType.Error, 5);
			x.Close ();
			Assert.AreEqual (sample3.Replace ('\'', '"'), sw.ToString ());
		}
Esempio n. 5
0
 //------------------------------------------------------------------------------------------------------
 #endregion
 //------------------------------------------------------------------------------------------------------
 #region Constructors and Destructors
 //------------------------------------------------------------------------------------------------------
 /// <summary>
 /// Конструктор
 /// </summary>
 /// <remarks>Файл всегда находится в папке приложения и называетя AppXmlLog.xml</remarks>
 private XmlLog()
 {
     // Получаем путь к папке приложения (.exe)
     String pathToLogFile = Environment.CurrentDirectory;
     this._Log =
         new XmlWriterTraceListener(pathToLogFile + "AppXmlLog.xml", "AppXmlLog");
     // Добавляем его в коллекцию
     Trace.Listeners.Add(_Log);
 }
        public void when_activity_has_exception_then_traces_data()
        {
            var xmlFile  = Path.GetTempFileName();
            var listener = new XmlWriterTraceListener(xmlFile);

            Tracer.Configuration.AddListener("Foo", listener);
            Tracer.Configuration.SetTracingLevel("Foo", SourceLevels.All);

            var tracer = Tracer.Get("Foo");

            using (var outer = tracer.StartActivity("Outer")) {
                using (var inner = tracer.StartActivity("Inner")) {
                    tracer.Info("Hey & > 23!");
                }

                try {
                    throw new ArgumentException();
                } catch (Exception ex) {
                    ex.Data.Add("Version", "1.0");
                    ex.Data.Add("Branch", "master");
                    ex.Data.Add("Commit", "1ab314b");
                    tracer.Error(ex, "Some error!");
                }
            }

            Tracer.Configuration.RemoveListener("Foo", listener);
            listener.Flush();
            listener.Dispose();

            var xmlns       = XNamespace.Get("http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord");
            var commitFound = false;

            using (var reader = XmlReader.Create(xmlFile, new XmlReaderSettings {
                ConformanceLevel = ConformanceLevel.Fragment
            })) {
                Assert.Equal(XmlNodeType.Element, reader.MoveToContent());
                do
                {
                    var xml    = reader.ReadOuterXml();
                    var doc    = XDocument.Load(new StringReader(xml));
                    var record = doc.Descendants(xmlns + "TraceRecord").FirstOrDefault();
                    if (record != null && record.Attribute("Severity") != null && record.Attribute("Severity").Value == "Error")
                    {
                        commitFound = record.Element(xmlns + "DataItems")?.Element(xmlns + "Commit")?.Value == "1ab314b";
                    }
                } while (!commitFound && !reader.EOF);
            }

            Assert.True(commitFound, "Failed to find traced commit ID exception data.");

            //Process.Start ("notepad", xml);

            //Process.Start (@"C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6 Tools\SvcTraceViewer.exe", xml);
            //Process.Start (@"C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\SvcTraceViewer.exe", xml);
            //Process.Start (@"C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools\SvcTraceViewer.exe", xml);
            //Process.Start (@"C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools\SvcTraceViewer.exe", xml);
        }
        public void SetUp()
        {
            contentRepository = MockRepository.GenerateStub<IRepository<Content>>();
            contentOrderableService = MockRepository.GenerateStub<IOrderableService<Content>>();
            baseControllerService = MockRepository.GenerateStub<IBaseControllerService>();
            imageFileService = MockRepository.GenerateStub<IImageFileService>();
            userService = MockRepository.GenerateStub<IUserService>();

            metaWeblog = new MetaWeblogWcf(
                userService,
                contentRepository,
                baseControllerService,
                contentOrderableService,
                imageFileService);

            var url = "http://localhost:27198/MetaWeblogTest.svc";

            baseControllerService.Stub(s => s.SiteUrl).Return(theSiteUrl);
            userService.Stub(s => s.Authenticate(Arg<string>.Is.Anything, Arg<string>.Is.Anything)).Return(true);
            var user = new User
            {
                RoleId = Role.AdministratorId
            };
            userService.Stub(s => s.CurrentUser).Return(user);


            container = new WindsorContainer()
                .AddFacility<WcfFacility>(f => f.DefaultBinding = new XmlRpcHttpBinding())
                .Register(
                    Component.For<XmlRpcEndpointBehavior>(),
                    Component.For<IMetaWeblog>().Instance(metaWeblog)
                        .ActAs(new DefaultServiceModel()
                            .AddBaseAddresses(url)
                            .AddEndpoints(
                                WcfEndpoint.ForContract<IMetaWeblog>()
                            )

                        )
                    );

            //var targetUrl = url;
            var targetUrl = "http://ipv4.fiddler:27198/MetaWeblogTest.svc";
            var factory = new XmlRpcChannelFactory<IMetaWeblog>(new XmlRpcHttpBinding(), new EndpointAddress(targetUrl));
            client = factory.CreateChannel();

            // diagnostics
            var traceListener = new XmlWriterTraceListener("app_tracelog.svclog")
            {
                TraceOutputOptions = TraceOptions.Timestamp
            };
            Trace.Listeners.Add(traceListener);
        }
Esempio n. 8
0
        public void when_activity_has_exception_then_traces_data()
        {
            var xml      = Path.GetTempFileName();
            var listener = new XmlWriterTraceListener(xml);

            Tracer.Configuration.AddListener("Foo", listener);
            Tracer.Configuration.SetTracingLevel("Foo", SourceLevels.All);

            var tracer = Tracer.Get("Foo");

            using (var outer = tracer.StartActivity("Outer")) {
                using (var inner = tracer.StartActivity("Inner")) {
                    tracer.Info("Hey & > 23!");
                }

                try {
                    throw new ArgumentException();
                } catch (Exception ex) {
                    ex.Data.Add("Version", "1.0");
                    ex.Data.Add("Branch", "master");
                    ex.Data.Add("Commit", "1ab314b");
                    tracer.Error(ex, "Some error!");
                }
            }

            Tracer.Configuration.RemoveListener("Foo", listener);
            listener.Flush();
            listener.Dispose();

            using (var reader = XmlReader.Create(xml, new XmlReaderSettings {
                ConformanceLevel = ConformanceLevel.Fragment
            })) {
                Assert.Equal(XmlNodeType.Element, reader.MoveToContent());
                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element && reader.NamespaceURI == "http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord")
                    {
                        Assert.True(reader.ReadToDescendant("Commit", "http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord"));
                        Assert.Equal("1ab314b", reader.ReadElementContentAsString());
                    }
                }
            }

            //Process.Start ("notepad", xml);

            //Process.Start (@"C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6 Tools\SvcTraceViewer.exe", xml);
            //Process.Start (@"C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\SvcTraceViewer.exe", xml);
            //Process.Start (@"C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools\SvcTraceViewer.exe", xml);
            //Process.Start (@"C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools\SvcTraceViewer.exe", xml);
        }
Esempio n. 9
0
        static void Main(string[] args) {
            _execTimer.Start();

            try {
                Delay(10);
                LogLongExec("Delay(10)");
                Delay(5000);
                LogLongExec("Delay(5000)");
            } catch (Exception ex) {
                using (
                    XmlWriterTraceListener log1 =
                        new XmlWriterTraceListener($@"C:\Users\{Environment.UserName}\Pictures\Error.log")) {
                    log1.TraceEvent(new TraceEventCache(), ex.Message, TraceEventType.Error, ex.HResult);
                    log1.Flush();
                }
            }
        }
Esempio n. 10
0
 public XmlFileLogging()
 {
     // Удаляем старый лог файл, а то он быстро растет
     // и при большом размере замедляет работу
     if (File.Exists(TraceName))
     {
         try
         {
             File.Delete(TraceName);
         }
         catch (Exception)
         {
         }
     }
     _trace = new XmlWriterTraceListener(TraceName);
     Trace.Listeners.Add(_trace);
 }
Esempio n. 11
0
        public void when_tracing_exception_with_xml_then_succeeds()
        {
            var xml = Path.GetTempFileName();
            var inMemoryListener = new InMemoryTraceListener();
            var xmlListener      = new XmlWriterTraceListener(xml);

            var tracerName = MethodBase.GetCurrentMethod().Name;

            Tracer.Configuration.AddListener(tracerName, inMemoryListener);
            Tracer.Configuration.AddListener(tracerName, xmlListener);
            Tracer.Configuration.SetTracingLevel(tracerName, SourceLevels.All);

            var tracer = Tracer.Get(tracerName);

            tracer.Error(new ApplicationException("Foo Error"), "A Foo Exception occurred");

            var trace = inMemoryListener.GetTrace();

            Assert.False(string.IsNullOrEmpty(trace));
            Assert.Contains("Foo Error", trace);
            Assert.Contains("A Foo Exception occurred", trace);
        }
Esempio n. 12
0
        public void when_tracing_exception_with_xml_then_succeeds()
        {
            var xml = Path.GetTempFileName();
            var inMemoryListener = new InMemoryTraceListener();
            var xmlListener = new XmlWriterTraceListener(xml);

			var tracerName = MethodBase.GetCurrentMethod().Name;

			Tracer.Configuration.AddListener(tracerName, inMemoryListener);
            Tracer.Configuration.AddListener(tracerName, xmlListener);
            Tracer.Configuration.SetTracingLevel(tracerName, SourceLevels.All);

            var tracer = Tracer.Get(tracerName);

            tracer.Error(new ApplicationException("Foo Error"), "A Foo Exception occurred");

            var trace = inMemoryListener.GetTrace();

            Assert.False(string.IsNullOrEmpty(trace));
            Assert.Contains("Foo Error", trace);
            Assert.Contains("A Foo Exception occurred", trace);
        }
Esempio n. 13
0
        static void Main(string[] args)
        {
            WriteLine("Option 1");
            System.Diagnostics.TraceSource trace = new TraceSource("./1_Trace.log");
            trace.TraceEvent(TraceEventType.Error, 123, "Option A: System.Diagnostics.TraceSource trace");

            WriteLine("Option 2: writes a file as 'TraceEventType.Error' and source 'Option B...'");
            using (System.Diagnostics.XmlWriterTraceListener log1 = new XmlWriterTraceListener("./2_Error.log"))
            {
                log1.TraceEvent(new TraceEventCache(), "Option B: System.Diagnostics.XmlWriterTraceListener", TraceEventType.Error, 123);
                log1.Flush();
            }

            WriteLine("Option 3");
            WriteLine("Throws: An unhandled exception of type 'System.Security.SecurityException' occurred in System.dll");
            //System.Diagnostics.EventInstance errorEvent = new EventInstance(123, 1, EventLogEntryType.Error);
            //EventLog.WriteEvent("MyAppErrors", errorEvent, "the message");

            WriteLine("Option 4: writes to the EventLog");
            EventLog logEntry = new EventLog();
            logEntry.Source = "Application";
            logEntry.WriteEntry("the message", EventLogEntryType.Error);


            WriteLine("Option 5: writes a file as 'TraceEventType.Information' and source 'Trace'");
            System.Diagnostics.XmlWriterTraceListener listener = new XmlWriterTraceListener("./5_Errror.log");
            listener.WriteLine("the log message");
            listener.Flush();
            listener.Close();

            // See Output window:
            // Error.log: a trace message
            WriteLine("Option 6: Trace.WriteLine with 'Error.log' as category");
            Trace.WriteLine("a trace message", "Error.log");

            WriteLine("Done");
            ReadLine();
        }
Esempio n. 14
0
        public void when_tracing_without_args_then_success()
        {
            var xml = Path.GetTempFileName();
            var inMemoryListener = new InMemoryTraceListener();
            var xmlListener      = new XmlWriterTraceListener(xml);

            var tracerName = MethodBase.GetCurrentMethod().Name;

            Tracer.Configuration.AddListener(tracerName, inMemoryListener);
            Tracer.Configuration.AddListener(tracerName, xmlListener);
            Tracer.Configuration.SetTracingLevel(tracerName, SourceLevels.All);

            var tracer = Tracer.Get(tracerName);

            var message = "Foo";

            tracer.Info(message);

            var trace = inMemoryListener.GetTrace();

            Assert.False(string.IsNullOrEmpty(trace));
            Assert.Contains(message, trace);
        }
        public WorkingTimeObserverForm()
        {
            InitializeComponent();

            this.timeObserverData = new TimeObserverData(new TimeSpan(DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second), GetBreakArrayFromSettings());
            this.timeObserverData.BreakStarted += ShowMessageBreakStarted;
            this.timeObserverData.BreakEnded += ShowMessageBreakEnded;
            this.currentTimeLabel.Text = DateTime.Now.ToShortTimeString();
            this.updateTimer = new Timer();
            this.updateTimer.Interval = 10000;
            this.updateTimer.Tick +=
                delegate(object sender, EventArgs e)
                {
                    this.currentTimeLabel.Text = DateTime.Now.ToShortTimeString();
                    this.LogData();
                };
            this.updateTimer.Start();

            XmlWriterTraceListener traceListener = new XmlWriterTraceListener(@"C:\_temp\logfile.xml");
            traceListener.IndentLevel = 4;
            traceListener.
            Trace.Listeners.Add(traceListener);
        }
Esempio n. 16
0
		public void XPathNavigatorAsData ()
		{
			// While XmlReader, XmlDocument and XDocument are not supported as direct xml content (i.e. to not get escaped), XPathNavigator is.
			var sw = new StringWriter ();
			var xl = new XmlWriterTraceListener (sw);
			var doc = new XmlDocument ();
			string xml = "<root><child xmlns=\"urn:foo\">text</child></root>";
			doc.LoadXml (xml);
			xl.TraceData (null, "my source", TraceEventType.Information, 1, doc.CreateNavigator (), doc.CreateNavigator ());
			// Note that it does not result in "<root xmlns=''>...".
			// See XmlWriterTraceListener.TraceCore() for details.
			Assert.IsTrue (sw.ToString ().IndexOf (xml) > 0, "#1");
			Assert.IsTrue (sw.ToString ().IndexOf ("</DataItem><DataItem>") > 0, "#2");
		}
Esempio n. 17
0
		public void Fail1 ()
		{
			StringWriter sw = new StringWriter ();
			XmlWriterTraceListener x = new XmlWriterTraceListener (sw);
			TraceEventCache cc = new TraceEventCache ();
			x.Fail ("error summary", "error details");
			x.Close ();
			Assert.AreEqual (sample7.Replace ('\'', '"'), sw.ToString ());
		}
Esempio n. 18
0
		public void TraceTransfer1 ()
		{
			StringWriter sw = new StringWriter ();
			XmlWriterTraceListener x = new XmlWriterTraceListener (sw);
			x.TraceTransfer (null, "bulldog", 0, "hoge", Guid.Empty);
			x.Close ();
			Assert.AreEqual (sample6.Replace ('\'', '"'), sw.ToString ());
		}
Esempio n. 19
0
		public void when_tracing_without_args_then_success()
		{
			var xml = Path.GetTempFileName();
			var inMemoryListener = new InMemoryTraceListener();
			var xmlListener = new XmlWriterTraceListener(xml);

			var tracerName = MethodBase.GetCurrentMethod().Name;

			Tracer.Configuration.AddListener(tracerName, inMemoryListener);
			Tracer.Configuration.AddListener(tracerName, xmlListener);
			Tracer.Configuration.SetTracingLevel(tracerName, SourceLevels.All);

			var tracer = Tracer.Get(tracerName);

			var message = "Foo";

			tracer.Info(message);

			var trace = inMemoryListener.GetTrace();

			Assert.False(string.IsNullOrEmpty(trace));
			Assert.Contains(message, trace);
		}
		public void when_activity_has_exception_then_traces_data ()
		{
			var xmlFile = Path.GetTempFileName();
			var listener = new XmlWriterTraceListener(xmlFile);

			Tracer.Configuration.AddListener ("Foo", listener);
			Tracer.Configuration.SetTracingLevel ("Foo", SourceLevels.All);

			var tracer = Tracer.Get("Foo");

			using (var outer = tracer.StartActivity ("Outer")) {
				using (var inner = tracer.StartActivity("Inner")) {
					tracer.Info ("Hey & > 23!");
				}

				try {
					throw new ArgumentException ();
				} catch (Exception ex) {
					ex.Data.Add ("Version", "1.0");
					ex.Data.Add ("Branch", "master");
					ex.Data.Add ("Commit", "1ab314b");
					tracer.Error (ex, "Some error!");
				}
			}

			Tracer.Configuration.RemoveListener ("Foo", listener);
			listener.Flush ();
			listener.Dispose ();

			var xmlns = XNamespace.Get("http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord");
			var commitFound = false;

			using (var reader = XmlReader.Create (xmlFile, new XmlReaderSettings { ConformanceLevel = ConformanceLevel.Fragment })) {
				Assert.Equal (XmlNodeType.Element, reader.MoveToContent ());
				do {
					var xml = reader.ReadOuterXml();
					var doc = XDocument.Load(new StringReader(xml));
					var record = doc.Descendants(xmlns + "TraceRecord").FirstOrDefault();
					if (record != null && record.Attribute("Severity") != null && record.Attribute("Severity").Value == "Error") {
						commitFound = record.Element(xmlns + "DataItems")?.Element(xmlns + "Commit")?.Value == "1ab314b";
					}
				} while (!commitFound && !reader.EOF);
			}

			Assert.True(commitFound, "Failed to find traced commit ID exception data.");

			//Process.Start ("notepad", xml);

			//Process.Start (@"C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6 Tools\SvcTraceViewer.exe", xml);
			//Process.Start (@"C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\SvcTraceViewer.exe", xml);
			//Process.Start (@"C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools\SvcTraceViewer.exe", xml);
			//Process.Start (@"C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools\SvcTraceViewer.exe", xml);
		}
Esempio n. 21
0
        private void Form1_Load(object sender, EventArgs e)
        {
            //Rectangle rec = Screen.PrimaryScreen.Bounds;
            //Size s = System.Windows.Forms.SystemInformation.PrimaryMonitorSize;
            labelResolutionOfScreen.Text = "Разрешение экрана: " + Screen.PrimaryScreen.Bounds.Size.ToString();

            // Set the SystemEvents class to receive event notification when a user  
            // preference changes, the palette changes, or when display settings change.
            // Данное событие происходит при изменении разрешения экрана. Необходимо подключить
            // Microsoft.Win32;
            SystemEvents.DisplaySettingsChanged +=
                new EventHandler(SystemEvents_DisplaySettingsChanged);
            SystemEvents.PaletteChanged += 
                new EventHandler(SystemEvents_PaletteChanged);
            // Происходит, например, при изменении цвета окна
            SystemEvents.UserPreferenceChanged += 
                new UserPreferenceChangedEventHandler(SystemEvents_UserPreferenceChanged);
            // For demonstration purposes, this application sits idle waiting for events.
            //Console.WriteLine("This application is waiting for system events.");
            //Console.WriteLine("Press <Enter> to terminate this application.");
            //Console.ReadLine();

            if (AllocConsole())
            {
                //Console.WriteLine("Приведко,я консолько");
                //Console.ReadLine();
                //FreeConsole();
            }

            ConsoleTraceListener console = new ConsoleTraceListener();
            console.Name = "console";
            Trace.Listeners.Add(console);
            Trace.Listeners["console"].TraceOutputOptions |= (TraceOptions.Callstack | TraceOptions.Timestamp);

            XmlWriterTraceListener xmltracer = new XmlWriterTraceListener("logxml.xml", "xmltracer");
            Trace.Listeners.Add(xmltracer);
            Trace.Listeners["xmltracer"].TraceOutputOptions |= (TraceOptions.Callstack | TraceOptions.Timestamp);
            
            Trace.AutoFlush = true;
            return;
        }
        public TraceListener GetRuntimeObject()
        {
            if (_runtimeObject != null)
            {
                return((TraceListener)_runtimeObject);
            }

            try {
                string className = TypeName;
                if (String.IsNullOrEmpty(className))
                {
                    // Look it up in SharedListeners
                    Debug.Assert(_allowReferences, "_allowReferences must be true if type name is null");

                    if (_attributes != null || ElementInformation.Properties[_propFilter.Name].ValueOrigin == PropertyValueOrigin.SetHere || TraceOutputOptions != TraceOptions.None || !String.IsNullOrEmpty(InitData))
                    {
                        throw new ConfigurationErrorsException(SR.GetString(SR.Reference_listener_cant_have_properties, Name));
                    }

                    if (DiagnosticsConfiguration.SharedListeners == null)
                    {
                        throw new ConfigurationErrorsException(SR.GetString(SR.Reference_to_nonexistent_listener, Name));
                    }

                    ListenerElement sharedListener = DiagnosticsConfiguration.SharedListeners[Name];
                    if (sharedListener == null)
                    {
                        throw new ConfigurationErrorsException(SR.GetString(SR.Reference_to_nonexistent_listener, Name));
                    }
                    else
                    {
                        _runtimeObject = sharedListener.GetRuntimeObject();
                        return((TraceListener)_runtimeObject);
                    }
                }
                else
                {
                    // create a new one
                    TraceListener newListener = (TraceListener)BaseGetRuntimeObject();
                    newListener.initializeData = InitData;
                    newListener.Name           = Name;
                    newListener.SetAttributes(Attributes);
                    newListener.TraceOutputOptions = TraceOutputOptions;

                    if ((Filter != null) && (Filter.TypeName != null) && (Filter.TypeName.Length != 0))
                    {
                        newListener.Filter = Filter.GetRuntimeObject();
                        XmlWriterTraceListener listerAsXmlWriter = newListener as XmlWriterTraceListener;
                        if (listerAsXmlWriter != null)
                        {
                            // This filter was added via configuration, which means we want the listener
                            // to respect it for TraceTransfer events.
                            listerAsXmlWriter.shouldRespectFilterOnTraceTransfer = true;
                        }
                    }

                    _runtimeObject = newListener;
                    return(newListener);
                }
            }
            catch (ArgumentException e) {
                throw new ConfigurationErrorsException(SR.GetString(SR.Could_not_create_listener, Name), e);
            }
        }
Esempio n. 23
0
		public void TraceDataWithCache1 ()
		{
			StringWriter sw = new StringWriter ();
			XmlWriterTraceListener x = new XmlWriterTraceListener (sw);
			TraceEventCache cc = new TraceEventCache ();
			x.TraceData (cc, null, TraceEventType.Error, 2);
			x.TraceData (cc, null, TraceEventType.Error, 3);
			x.Close ();
			Assert.AreEqual (sample4.Replace ('\'', '"'), sw.ToString ());
		}
Esempio n. 24
0
 /// <summary>
 /// Derived method to initialize trace listener to write xml data
 /// </summary>
 /// <param name="traceSource">Trace source that holds a set of handlers</param>
 /// <param name="filterLevels">The level of trace message filtered by trace listener</param>
 /// <param name="traceOptions">Trace data options that has to be written in the trace output</param>
 /// <param name="traceListener">Trace listener object associated with the trace source</param>
 public override void InitListener(out TraceListener traceListener)
 {
     traceListener = new XmlWriterTraceListener(this.GetStreamWriter());
 }
        public void TraceCompareTest()
        {
            TraceEventCache eventCache = new TraceEventCache();
            string output1 = null;
            string output2 = null;

            using (MemoryStream stream1 = new MemoryStream())
            {

                using (TraceListener tracer = new XmlWriterTraceListener(stream1))
                {

                    tracer.TraceData(eventCache, "TestSource", TraceEventType.Information, 1,
                        new { Message = "Test of Message", Id = 123 });
                    tracer.Flush();
                    //stream.Position = 0;
                    output1 = Encoding.UTF8.GetString(stream1.ToArray());
                    Trace.WriteLine(output1);
                }

            }
            using (MemoryStream stream2 = new MemoryStream())
            {

                using (TraceListener tracer = new XmlWriterRollingTraceListener(stream2))
                {

                    tracer.TraceData(eventCache, "TestSource", TraceEventType.Information, 1,
                        new { Message = "Test of Message", Id = 123 });
                    tracer.Flush();
                    //stream.Position = 0;
                    output2 = Encoding.UTF8.GetString(stream2.ToArray());
                    Trace.WriteLine(output1);
                }

            }

            Assert.AreEqual<string>(output1, output2);
        }