TraceEvent() private method

private TraceEvent ( System eventType, int id ) : void
eventType System
id int
return void
Ejemplo n.º 1
0
        private void Run()
        {
            try
            {
                var m = Helper.FormatTrace("Staring the Scheduler", "SchedulerWorkerRole", "Run");
                var traceSource = new TraceSource("VirtoCommerce.ScheduleService.Trace");
                traceSource.TraceEvent(TraceEventType.Information, 0, m);

                var cloudContext = Guid.NewGuid().ToString();

                var jobScheduler = new JobScheduler(cloudContext, traceSource, () => AzureConfiguration.Instance.AzureStorageAccount, new Settings());

                traceSource.TraceEvent(TraceEventType.Information, 0, Helper.FormatTrace("Staring the Scheduler", "SchedulerWorkerRole", "Run", "Starting Paralel.Invoke", cloudContext));

                Parallel.Invoke(
                    jobScheduler.JobsManagerProcess,
                    jobScheduler.SchedulerProcess);
            }
            catch (Exception ex)
            {
                var m = Helper.FormatException(ex, "WorkerRole", "Run");
                var traceSource = new TraceSource("VirtoCommerce.ScheduleService.Trace");
                traceSource.TraceEvent(TraceEventType.Error, 0, m);
            }
        }
Ejemplo n.º 2
0
        private void DoWork()
        {
            while (!_shouldStop)
            {
                try
                {
                    var nucleo = new BusinessLayer.Nucleo();

                    //DateTransaction = System.DateTime.Now.AddDays(-1);
                    DateTransaction = System.DateTime.Now;
                    fechaSwitch     = DateTransaction.ToString("yyyy/MM/dd");

                    // Verifico si el servicio esta dentro de parametro permitido para ejecutar el proceso
                    string[] strArrayInicio = StrHoraInicio.Split(':');
                    string[] strArrayHasta  = StrHoraHasta.Split(':');

                    if (strArrayInicio.Length == 2 && strArrayHasta.Length == 2)
                    {
                        if ((DateTime.Now.Hour > Convert.ToInt16(strArrayInicio[0])) ||
                            ((DateTime.Now.Hour == Convert.ToInt16(strArrayInicio[0])) &&
                             (DateTime.Now.Minute > Convert.ToInt16(strArrayInicio[1]))))
                        {
                            if ((DateTime.Now.Hour < Convert.ToInt16(strArrayHasta[0])) ||
                                ((DateTime.Now.Hour == Convert.ToInt16(strArrayHasta[0])) &&
                                 (DateTime.Now.Minute < Convert.ToInt16(strArrayHasta[1]))))
                            {
                                // Testing save Logs
                                trace.TraceEvent(TraceEventType.Start, 100, "Inicia el proceso de conciliacion de TvCable. Fecha actual: " + DateTime.Now);

                                // Verifica si existen archivos de conciliacion de los MDP pendientes de validar su formato(ENTREGADO).
                                var itemEntregado = nucleo.GetItemCatalogoPorCodigoItemCodigoCatalogo(Constants.CodeEstadoArchivosConciliacion, Constants.CodeItemEntregado);


                                trace.TraceEvent(TraceEventType.Stop, 116, "Termina el proceso de conciliacion de TvCable. Fecha actual: " + DateTime.Now);
                                System.Diagnostics.Trace.CorrelationManager.StopLogicalOperation();
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                }

                try
                {
                    Thread.Sleep(Convert.ToInt32(DefaultInterval));
                }
                catch (Exception ex)
                {
                }
                finally
                {
                }
            }
        }
Ejemplo n.º 3
0
        static void Main(string[] args)
        {
            TraceSource myTraceSource = new TraceSource("MyConsoleApp");

            myTraceSource.TraceEvent(TraceEventType.Error, 1, "Tracing Error Message.");
            myTraceSource.TraceEvent(TraceEventType.Warning, 2, "Tracing Warning Message.");
            myTraceSource.TraceEvent(TraceEventType.Information, 3, "Tracing Information.");
            myTraceSource.TraceEvent(TraceEventType.Verbose, 4, "Tracing Verbose Message.");
            myTraceSource.TraceEvent(TraceEventType.Critical, 5, "Tracing Critical Message.");

            myTraceSource.Close();
        }
Ejemplo n.º 4
0
        // ユーザー・フレンドリなダイアログを表示するメソッド
        public static void ShowErrorMessage(Exception ex)
        {
            logger.TraceEvent(System.Diagnostics.TraceEventType.Critical,
                              0, ex.ToString());

            logger.Flush();
            logger.Close();

            MessageBox.Show("エラーが発生したため、エラーログ(log\\linearerror.log)を作成しました。\n" +
                            " お手数ですが問題解決のため、エラーログをFINALSTREAMにメールでお知らせください。\n" +
                            " ご協力お願いいたします。", "クリティカルエラー", MessageBoxButtons.OK, MessageBoxIcon.Error);

            //Application.Exit();
        }
Ejemplo n.º 5
0
        public void LoggingErrorViaTraceSourceToLog4NetTraceListenerWithFilterSkipsLogging()
        {
            var logger = Mock.Create <ILog>();

            Mock.Arrange(() => logger.Fatal(Arg.IsAny <string>()))
            .IgnoreInstance()
            .OccursNever();

            var traceSource = new System.Diagnostics.TraceSource("TraceSourceWithLog4NetListenerWithFilter");

            traceSource.TraceEvent(TraceEventType.Error, 1, "TraceFromTestMethod '{0}'", DateTimeOffset.Now.ToString("O"));
            traceSource.TraceEvent(TraceEventType.Error, 1, "TraceFromTestMethod '{0}'", DateTimeOffset.Now.ToString("O"));

            Mock.Assert(logger);
        }
Ejemplo n.º 6
0
        public void LoggingVerboseViaTraceSourceToLog4NetTraceListenerWithFilterSkipsLogging()
        {
            var traceListener = Mock.Create <Log4NetTraceListener>(Behavior.CallOriginal);

            Mock.Arrange(() => traceListener.TraceEvent(Arg.IsAny <TraceEventCache>(), Arg.IsAny <string>(), Arg.IsAny <TraceEventType>(), Arg.IsAny <int>(), Arg.IsAny <string>(), Arg.IsAny <object[]>()))
            .IgnoreInstance()
            .OccursNever();

            var traceSource = new System.Diagnostics.TraceSource("TraceSourceWithLog4NetListenerWithFilter");

            traceSource.TraceEvent(TraceEventType.Verbose, 1, "TraceFromTestMethod '{0}'", DateTimeOffset.Now.ToString("O"));
            traceSource.TraceEvent(TraceEventType.Verbose, 1, "TraceFromTestMethod '{0}'", DateTimeOffset.Now.ToString("O"));

            Mock.Assert(traceListener);
        }
        public void ActivityNameForXmlListenersStrangeCharacters()
        {
            TraceSource source = new TraceSource("testScopeSource");
            var listener = source.Listeners.OfType<TestTraceListener>().First();
            listener.MethodCallInformation.Clear();
            string transferIn = "TransferIn";
            string start = "<";
            string transferOut = "TransferOut";
            string stop = "Stopping...";
            var activityName = "<";

            using (var scope = new ActivityScope(source, 11, 12, 13, 14, transferIn, start, transferOut, stop, activityName))
            {
                source.TraceEvent(TraceEventType.Warning, 2, "B");
            }

            var events = listener.MethodCallInformation;
            StringAssert.StartsWith(events[0].Message, transferIn);

            Console.WriteLine(string.Join(",", events[1].Data));
            Assert.AreEqual(1, events[1].Data.Length);
            Assert.IsInstanceOfType(events[1].Data[0], typeof(XPathNavigator));
            var navigator = (XPathNavigator)events[1].Data[0];
            var resolver = new XmlNamespaceManager(navigator.NameTable);
            resolver.AddNamespace("ns1", "http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord");
            resolver.AddNamespace("ns2", "http://schemas.microsoft.com/2006/08/ServiceModel/DictionaryTraceRecord");
            Assert.AreEqual(start, navigator.SelectSingleNode("/ns1:TraceRecord/ns1:Description", resolver).Value);
            Assert.AreEqual(activityName, navigator.SelectSingleNode("/ns1:TraceRecord/ns2:ExtendedData/ns2:ActivityName", resolver).Value);
            //StringAssert.Contains(events[1].Data[0].ToString(), activityName);
            //StringAssert.Contains(events[1].Data[0].ToString(), start);

            StringAssert.StartsWith(events[3].Message, transferOut);
            Assert.AreEqual(stop, events[4].Message);
        }
Ejemplo n.º 8
0
        public void Log <TState>(LogLevel logLevel, EventId eventId, TState state, Exception?exception, Func <TState, Exception?, string> formatter)
        {
            if (!IsEnabled(logLevel))
            {
                return;
            }

            string message = string.Empty;

            if (formatter != null)
            {
                message = formatter(state, exception);
            }
            else if (state != null)
            {
                message += state;
            }

            if (exception != null)
            {
                string exceptionDelimiter = string.IsNullOrEmpty(message) ? string.Empty : " ";
                message += exceptionDelimiter + exception;
            }

            if (!string.IsNullOrEmpty(message))
            {
                _traceSource.TraceEvent(GetEventType(logLevel), eventId.Id, message);
            }
        }
Ejemplo n.º 9
0
        private static void Main(string[] args)
        {
            using (CancellationTokenSource cts = new CancellationTokenSource())
            {
                TraceSource traceSource = new TraceSource("CleanupSample", SourceLevels.All);
                traceSource.Listeners.Add(new ConsoleTraceListener() { TraceOutputOptions = TraceOptions.DateTime | TraceOptions.ThreadId });

                CleanupGuard guard = new CleanupGuard();
                Task task = guard.RunAsync(g => RunSampleAsync(g, traceSource, cts.Token));

                Console.WriteLine("Press ENTER to stop.");
                Console.ReadLine();

                cts.Cancel();

                try
                {
                    task.Wait();
                }
                catch (Exception e)
                {
                    traceSource.TraceEvent(TraceEventType.Error, 0, "ERROR: {0}", e);
                }
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="type"></param>
        /// <param name="id"></param>
        /// <param name="msg"></param>
        public static void WriteLog(TraceEventType type, int id, string msg)
        {
            string direct = HttpContext.Current.Server.MapPath("~/Log/Api/");
            if (!Directory.Exists(direct))
                Directory.CreateDirectory(direct);
            string file = direct + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";

            TextWriterTraceListener listen = new TextWriterTraceListener(file);
            listen.TraceOutputOptions = TraceOptions.ProcessId |
                                        TraceOptions.ThreadId |
                                        TraceOptions.Timestamp |
                                        TraceOptions.DateTime |
                                        TraceOptions.LogicalOperationStack;
                                        //TraceOptions.Callstack;

            Trace.Listeners.Add(listen);
            Trace.AutoFlush = false;
            //Trace.WriteLine("Test");

            SourceSwitch sourceSwitch = new SourceSwitch("sourceSwitch");
            sourceSwitch.Level = SourceLevels.Verbose;

            TraceSource traceSource = new TraceSource("traceSource");
            traceSource.Switch = sourceSwitch;
            traceSource.Listeners.Add(listen);

            traceSource.TraceEvent(type, id, msg);
            Trace.Close();
        }
Ejemplo n.º 11
0
        public void UsesTraceSource()
        {
            Console.WriteLine("Config:"+ AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

            Assert.AreEqual("FromAppConfig", ConfigurationManager.AppSettings["appConfigCheck"]);

            // just ensure, that <system.diagnostics> is configured for our test
            Trace.Refresh();
            TraceSource ts = new TraceSource("TraceLoggerTests", SourceLevels.All);
            Assert.AreEqual(1, ts.Listeners.Count);
            Assert.AreEqual(typeof(CapturingTraceListener), ts.Listeners[0].GetType());

            CapturingTraceListener.Events.Clear();
            ts.TraceEvent(TraceEventType.Information, 0, "message");
            Assert.AreEqual(TraceEventType.Information, CapturingTraceListener.Events[0].EventType);
            Assert.AreEqual("message", CapturingTraceListener.Events[0].FormattedMessage);

            // reset events and set loggerFactoryAdapter
            CapturingTraceListener.Events.Clear();
            NameValueCollection props = new NameValueCollection();
            props["useTraceSource"] = "TRUE";
            TraceLoggerFactoryAdapter adapter = new TraceLoggerFactoryAdapter(props);
            adapter.ShowDateTime = false;
            LogManager.Adapter = adapter;

            ILog log = LogManager.GetLogger("TraceLoggerTests");            
            log.WarnFormat("info {0}", "arg");
            Assert.AreEqual(TraceEventType.Warning, CapturingTraceListener.Events[0].EventType);
            Assert.AreEqual("[WARN]  TraceLoggerTests - info arg", CapturingTraceListener.Events[0].FormattedMessage);
        }
Ejemplo n.º 12
0
        public ActionResult Index()
        {
            // Get most popular albums
            var albums = GetTopSellingAlbums(5);
            var albumCount = GetTotalAlbumns();

            Trace.Write(string.Format("Total number of Albums = {0} and Albums with 'The' = {1}", albumCount.Item1, albumCount.Item2));
            Trace.Write("Got top 5 albums");
            Trace.TraceWarning("Test TraceWarning;");
            Trace.IndentLevel++;
            Trace.TraceError("Test TraceError;");
            Trace.Write("Another trace line");
            Trace.IndentLevel++;
            Trace.Write("Yet another trace line");
            Trace.IndentLevel = 0;
            Trace.TraceInformation("Test TraceInformation;");

            HttpContext.Session["TestObject"] = new Artist { ArtistId = 123, Name = "Test Artist" };

            TraceSource ts = new TraceSource("Test source");

            ts.TraceEvent(TraceEventType.Warning, 0, string.Format("{0}: {1}", "trace", "source"));

            return View(albums);
        }
Ejemplo n.º 13
0
        public void Log <TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter)
        {
            if (!IsEnabled(logLevel))
            {
                return;
            }
            var message = string.Empty;

            if (formatter != null)
            {
                message = formatter(state, exception);
            }
            else
            {
                if (state != null)
                {
                    message += state;
                }
                if (exception != null)
                {
                    message += Environment.NewLine + exception;
                }
            }
            if (!string.IsNullOrEmpty(message))
            {
                _traceSource.TraceEvent(GetEventType(logLevel), eventId.Id, message);
            }
        }
 internal static Action<TraceEventType, Guid?, string, string> TraceLogger()
 {
     TraceSource _traceSource = new TraceSource("SikkerDigitalPost.Klient");
     return (severity, koversasjonsId, caller, message) =>
     {
         _traceSource.TraceEvent(severity, 1, "[{0}, {1}] {2}", koversasjonsId.GetValueOrDefault(), caller, message);
     };
 }
Ejemplo n.º 15
0
 public void JustForTestingLoggingConfiguration()
 {
     TraceSource traceSource = new TraceSource("DiagnosticsTracePerformanceTest");
     traceSource.TraceEvent(TraceEventType.Verbose, -1, "test trace info {0}", new MyTestObjectUnderTrace());
     //            Trace.TraceInformation("traced info");
     Trace.WriteLine("some message", "myCategory");
     Console.WriteLine("from console");
 }
Ejemplo n.º 16
0
        public void ConfigTest()
        {
            var source = new TraceSource("MSMQTEST", SourceLevels.All);

            source.TraceInformation("test1");

            source.TraceEvent(TraceEventType.Error, 1, "Test 2 {0}", 123);
        }
Ejemplo n.º 17
0
        public ActionResult TraceSource(string id)
        {
            HttpContext.Items.Add(IntegrationTestTab.Expected, id);

            var traceSource = new TraceSource("Test Source");
            traceSource.TraceEvent(TraceEventType.Warning, 0, id);

            return View(model: id);
        }
Ejemplo n.º 18
0
 private void TraceToOutput()
 {
     TraceSource traceSource = new TraceSource("TraceSource", SourceLevels.All);
     traceSource.TraceInformation("Tracing");
     traceSource.TraceEvent(TraceEventType.Critical, 0, "Critical");
     traceSource.TraceData(TraceEventType.Information, 1, new object[] { "x", "y", "z" });
     traceSource.Flush();
     traceSource.Close();
 }
        public static void TraceEvent(TraceEventType type, string message)
        {
            TraceSource ts = new TraceSource(TraceSource);
            if (Trace.CorrelationManager.ActivityId == Guid.Empty)
            {
                Trace.CorrelationManager.ActivityId = Guid.NewGuid();
            }

            ts.TraceEvent(type, 0, message);
        }
Ejemplo n.º 20
0
        public static void Main(string[] args)
        {
            TraceSource traceSource = new TraceSource("myTraceSource", SourceLevels.All);

            traceSource.TraceInformation("Tracing application...");
            traceSource.TraceEvent(TraceEventType.Critical, 0, "Critical trace");
            traceSource.TraceData(TraceEventType.Information, 1, new object[] { "a", "b", "c" });

            traceSource.Flush();
            traceSource.Close();
        }
Ejemplo n.º 21
0
        public static void HowToUseTheTraceSourceClass()
        {
            TraceSource traceSource = new TraceSource("myTraceSource", SourceLevels.All);

            traceSource.TraceInformation("Tracing app");
            traceSource.TraceEvent(TraceEventType.Critical, 0, "Critical trace");
            traceSource.TraceData(TraceEventType.Information, 1, new object[] { "a", "b", "c" });

            traceSource.Flush();
            traceSource.Close();
        }
Ejemplo n.º 22
0
        public static async Task SaveAsAsync(this ISocketMessage message, string filename)
        {
            var trace = new TraceSource("Kilo.Networking.Messaging");

            using (var input = message.GetStream())
            using (var output = new FileStream(filename, FileMode.Create))
            {
                var watch = new Stopwatch();
                watch.Start();

                trace.TraceEvent(TraceEventType.Information, 0, $"Saving message as { filename }");

                input.Position = 0;

                await input.CopyToAsync(output);

                watch.Stop();

                trace.TraceEvent(TraceEventType.Verbose, 0, $"Done in { watch.Elapsed }");
            }
        }
        /// <summary>
        /// Sets the trace source for all instances of <see cref="EFTracingConnection"/>.
        /// </summary>
        /// <param name="connection">The connection.</param>
        /// <param name="traceSource">The trace source to which to trace SQL command activity.</param>
        public static void SetTraceSource(this DbConnection connection, TraceSource traceSource)
        {
            Contract.Requires(connection != null);
            Contract.Requires(traceSource != null);

            foreach (var tracingConnection in connection.GetTracingConnections())
            {
                tracingConnection.CommandExecuting += (_, e) => traceSource.TraceInformation(e.ToFlattenedTraceString());
                tracingConnection.CommandFinished += (_, e) => traceSource.TraceInformation(e.ToFlattenedTraceString());
                tracingConnection.CommandFailed += (_, e) => traceSource.TraceEvent(TraceEventType.Error, 0, e.ToFlattenedTraceString());
            }
        }
        public void ConfigFileChangeTriggersReload()
        {
            //var configPath = Assembly.GetExecutingAssembly().Location + ".config";
            //var configPath = @"D:\Code\Diagnostics\EssentialDiagnostics\Essential.Diagnostics.Tests\bin\Debug\Essential.Diagnostics.Tests.dll.config";
            var configPath = ConfigUtility.GetConfigDirFromTestRunDirectory(TestContext.TestRunDirectory);
            Console.WriteLine("Config path: '{0}'", configPath);

            TraceSource source = new TraceSource("inmemory2Source");
            var listener1 = source.Listeners.OfType<InMemoryTraceListener>().First();
            listener1.Clear();

            // Verify starting settings
            source.TraceEvent(TraceEventType.Information, 1, "A");
            var events1 = listener1.GetEvents();
            Assert.AreEqual(666, listener1.Limit);
            Assert.AreEqual(1, events1.Length);

            using (var file = new FileResetScope(configPath))
            {
                using (var configMonitor = new TraceConfigurationMonitor(configPath, false))
                {
                    configMonitor.Start();

                    var changedConfigText = file.OriginalText.Replace("666", "777");
                    File.WriteAllText(configPath, changedConfigText);

                    // Allow time for async watcher to trigger
                    Thread.Sleep(100);

                    source.TraceEvent(TraceEventType.Information, 1, "B");

                    var listener2 = source.Listeners.OfType<InMemoryTraceListener>().First();
                    var events2 = listener2.GetEvents();
                    System.Threading.Thread.Sleep(500);
                    Assert.AreEqual(777, listener2.Limit);
                    Assert.AreEqual(1, events2.Length);
                }
            }
        }
        public static void TraceEvent(TraceEventType type, string area, string message)
        {
            TraceSource ts = new TraceSource(Internal.TraceSourceName);

            if (Trace.CorrelationManager.ActivityId == Guid.Empty)
            {
                if (type != TraceEventType.Verbose)
                {
                    Trace.CorrelationManager.ActivityId = Guid.NewGuid();
                }
            }

            ts.TraceEvent(type, 0, string.Format("{0}: {1}", area, message));
        }
Ejemplo n.º 26
0
        public ActivityTraceContext(TraceSource ts, string operationName)
        {
            this.operationName = operationName;
            this.ts = ts;

            Trace.CorrelationManager.StartLogicalOperation(operationName);

            parentActivityId = Trace.CorrelationManager.ActivityId;
            Guid activityId = Guid.NewGuid();

            ts.TraceTransfer(0, "Transfering to " + operationName, activityId);
            Trace.CorrelationManager.ActivityId = activityId;
            ts.TraceEvent(TraceEventType.Start, 0, operationName + " started");
        }
Ejemplo n.º 27
0
        public static void TraceEvent(TraceEventType type, string message, bool suppressTraceService)
        {
            TraceSource ts = new TraceSource("Ideal");

            if (Trace.CorrelationManager.ActivityId == Guid.Empty)
            {
                if (type != TraceEventType.Verbose)
                {
                    Trace.CorrelationManager.ActivityId = Guid.NewGuid();
                }
            }

            ts.TraceEvent(type, 0, message);
        }
Ejemplo n.º 28
0
        static void Main(string[] args)
        {
            TraceSource traceSource = new TraceSource("myTraceSource", SourceLevels.All);

            traceSource.TraceInformation("Tracing application.");
            traceSource.TraceEvent(TraceEventType.Critical, 0, "Critical trace");
            traceSource.TraceData(TraceEventType.Information, 1, new object[] { "a", "b", "c" });

            traceSource.Flush();
            traceSource.Close();

            Console.WriteLine("Press a key to exit");
            Console.ReadKey();
        }
Ejemplo n.º 29
0
        public void LoggingViaTraceSourceToLog4NetTraceListenerSucceeds()
        {
            var logger = Mock.Create <ILog>();

            Mock.Arrange(() => logger.Fatal(Arg.IsAny <string>()))
            .IgnoreInstance()
            .DoNothing()
            .MustBeCalled();

            var traceSource = new System.Diagnostics.TraceSource("TraceSourceWithLog4NetListener");

            traceSource.TraceEvent(TraceEventType.Critical, 1, "TraceFromTestMethod '{0}'", DateTimeOffset.Now.ToString("O"));

            Mock.Assert(logger);
        }
        public void ScopeManualStartStopMessages()
        {
            TraceSource source = new TraceSource("inmemory1Source");
            var listener = source.Listeners.OfType<InMemoryTraceListener>().First();
            listener.Clear();

            var operationId = "X";
            using (var scope1 = new LogicalOperationScope(operationId))
            {
                source.TraceEvent(TraceEventType.Start, 11, "Start {0}", operationId);

                source.TraceEvent(TraceEventType.Warning, 1, "A");

                source.TraceEvent(TraceEventType.Stop, 12, "Stop {0}", operationId);
            }

            var events = listener.GetEvents();

            Assert.AreEqual(3, events.Length);
            Assert.AreEqual("Start X", events[0].Message);
            Assert.AreEqual(11, events[0].Id);
            Assert.AreEqual("Stop X", events[2].Message);
            Assert.AreEqual(12, events[2].Id);
        }
Ejemplo n.º 31
0
 static void Main(string[] args)
 {
     TraceSource ts = new TraceSource("console");
     ts.Switch.Level = SourceLevels.All;
     ts.Listeners.Add(new ConsoleTraceListener());
     try
     {
         var clientApp = new ClientApp(ts);
         clientApp.Run(args);
     }
     catch(Exception e)
     {
         ts.TraceEvent(TraceEventType.Critical, 0, "\nERROR:\n" + e.ToString());
     }
 }
Ejemplo n.º 32
0
        public string GetHeader(string name, string ns)
        {
            Debug.Assert(name != null);
            Debug.Assert(ns != null);

            TraceSource ts = new TraceSource("MyServiceTraceSource");
            if (Trace.CorrelationManager.ActivityId == Guid.Empty)
                Trace.CorrelationManager.ActivityId = Guid.NewGuid();
            ts.TraceEvent(TraceEventType.Start, 0, "GetHeader Activity");

            try
            {
                Message reqMessage = OperationContext.Current.RequestContext.RequestMessage;
                int headerIndex = reqMessage.Headers.FindHeader(name, ns);
                if (headerIndex != -1)
                    return reqMessage.Headers.GetHeader<string>(headerIndex);
                else
                    throw new FaultException<string>(reqMessage.Headers.Action, "Header not found.  See detail for Action header.");
            }
            finally
            {
                ts.TraceEvent(TraceEventType.Stop, 0, "GetHeader Activity");
            }
        }
		public void Scheduler5MinutesTest()
		{
			JobScheduler jobScheduler=null;
			try
			{
				string m = Helper.FormatTrace("Staring the Scheduler", "SchedulerWorkerRole", "Run");
				var traceSource = new TraceSource("VirtoCommerce.ScheduleService.Trace");
				traceSource.TraceEvent(TraceEventType.Information, 0, m);
				var connectionString = ConfigurationManager.ConnectionStrings["VirtoCommerce_AzureStorage"].ConnectionString;
			
				CloudStorageAccount storageAccount;
				CloudStorageAccount.TryParse(connectionString, out storageAccount);
				var schedulerDbContext = new TestISchedulerDbContext();
				jobScheduler = new JobScheduler(
					schedulerDbContext,
					name => new TestISchedulerDbContext.TestJob(),
					"test-context",
					traceSource,
					() => storageAccount,
					new Settings("test")
					);

				Task.Run(
					() => Parallel.Invoke(
						jobScheduler.JobsManagerProcess,
						jobScheduler.SchedulerProcess));

				Thread.Sleep((5 * 60 * 1000) + 15 * 1000);


				//disable jobs, check that disablinng works - there are no tasks
				var jobs = schedulerDbContext.GetSystemJobs();
				jobs.ForEach(j => j.IsEnabled = false);
				Thread.Sleep((1 * 60 * 1000));

				Assert.Equal(schedulerDbContext.TaskSchedules.Count, 0);

				Assert.Equal(schedulerDbContext.Count, 12);
				Assert.Equal(schedulerDbContext.Error, 0);
			}
			finally
			{
				if (jobScheduler!=null)
				jobScheduler.Stop();
			}
		}
        public void ScopeDefaultMessages()
        {
            TraceSource source = new TraceSource("inmemory1Source");
            var listener = source.Listeners.OfType<InMemoryTraceListener>().First();
            listener.Clear();

            using (var scope1 = new LogicalOperationScope(source, "X"))
            {
                source.TraceEvent(TraceEventType.Warning, 1, "A");
            }

            var events = listener.GetEvents();

            Assert.AreEqual(3, events.Length);
            Assert.AreEqual("Start operation", events[0].Message);
            Assert.AreEqual("Stop operation", events[2].Message);
        }
Ejemplo n.º 35
0
        public static void HowToUseTheTraceListenerClass()
        {
            Stream outputFile = File.Create("traceFile.txt");
            TextWriterTraceListener textListener = new TextWriterTraceListener(outputFile);

            TraceSource traceSource = new TraceSource("myTraceSource", SourceLevels.All);

            traceSource.Listeners.Clear();
            traceSource.Listeners.Add(textListener);

            traceSource.TraceInformation("Tracing app");
            traceSource.TraceEvent(TraceEventType.Critical, 0, "Critical trace");
            traceSource.TraceData(TraceEventType.Information, 1, new object[] { "a", "b", "c" });

            traceSource.Flush();
            traceSource.Close();
        }
Ejemplo n.º 36
0
        private void StartDummyFeed()
        {
            TraceSource source = new TraceSource("TestingDummySource", SourceLevels.All);
            source.Listeners.Add(new ProxyTraceListener());

            DispatcherTimer timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromMilliseconds(1000);
            timer.Tick += delegate
                {
                    var types = Enum.GetValues(typeof(TraceEventType));
                    Random random = new Random();
                    int index = random.Next(0, types.Length - 1);

                    source.TraceEvent((TraceEventType)types.GetValue(index), 0, "Morgan is a cider drinker");
                };
            timer.Start();
        }
Ejemplo n.º 37
0
        public void MsmqTraceListenerTest()
        {
            var path = @"FormatName:DIRECT=OS:.\private$\test2";
            path = @".\private$\test2";

            var listener = new MsmqTraceListener(path);

            listener = xSolon.TraceListeners.Extensions.Wrap<MsmqTraceListener>(listener);

            var source = new TraceSource("MSMQTEST1", SourceLevels.All);

            source.Listeners.Add(listener);
            source.Listeners.Add(new ConsoleTraceListener());

            source.TraceInformation("test1");

            source.TraceEvent(TraceEventType.Information, 1, "Test 2 {0}", 123);
        }
Ejemplo n.º 38
0
        public void Test_BundleSource()
        {
            // Setup ConfigurationManager
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            config.Sections.Clear();
            config.SectionGroups.Clear();
            NetSectionGroup          netSectionGroup  = config.SectionGroups.Get("system.net") as NetSectionGroup;
            MailSettingsSectionGroup smtpSectionGroup = netSectionGroup.SectionGroups.Get("mailSettings") as MailSettingsSectionGroup;
            SmtpSection smtpSection = smtpSectionGroup.Sections.Get("smtp") as SmtpSection;

            smtpSection.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.SpecifiedPickupDirectory;
            smtpSection.SpecifiedPickupDirectory.PickupDirectoryLocation = AppDomain.CurrentDomain.BaseDirectory + "\\Test";
            ResetPickupDirectory(smtpSection.SpecifiedPickupDirectory.PickupDirectoryLocation);
            config.Save();
            ConfigurationManager.RefreshSection("system.net");
            ConfigurationManager.RefreshSection("mailSettings");

            SnakeEyes.EmailTraceListener listener = new SnakeEyes.EmailTraceListener();
            listener.Attributes.Add("fromAddress", "*****@*****.**");
            listener.Attributes.Add("toAddress", "*****@*****.**");
            listener.Attributes.Add("throttleSeconds", "1");

            var source = new System.Diagnostics.TraceSource("TestSource", SourceLevels.Error);

            source.Listeners.Add(listener);

            {
                DateTime startTime = DateTime.UtcNow;
                for (int i = 0; i < 5; ++i)
                {
                    source.TraceEvent(System.Diagnostics.TraceEventType.Error, 0, "Damn");
                }
                System.Threading.Thread.Sleep(1000);
                Assert.GreaterOrEqual(DateTime.UtcNow.Subtract(startTime).TotalSeconds, 5);    // See throttle time works
                Assert.AreEqual(5, System.IO.Directory.GetFiles(smtpSection.SpecifiedPickupDirectory.PickupDirectoryLocation).Length);
            }

            source.Listeners.Remove(listener);

            listener = new SnakeEyes.EmailTraceListener();
            listener.Attributes.Add("fromAddress", "*****@*****.**");
            listener.Attributes.Add("toAddress", "*****@*****.**");
            listener.Attributes.Add("throttleSeconds", "1");
            listener.Attributes.Add("formatBundleSource", "{{/TraceEvent/EventLogSource}}");
            listener.Attributes.Add("formatBody", "Message = {{/TraceEvent/EventLogSource}}");
            source.Listeners.Add(listener);
            ResetPickupDirectory(smtpSection.SpecifiedPickupDirectory.PickupDirectoryLocation);
            {
                DateTime startTime = DateTime.UtcNow;
                for (int i = 0; i < 10; ++i)
                {
                    source.TraceEvent(System.Diagnostics.TraceEventType.Error, 0, "<TraceEvent><EventLogSource>Damn</EventLogSource></TraceEvent>");
                }
                System.Threading.Thread.Sleep(1000);
                Assert.Less(DateTime.UtcNow.Subtract(startTime).TotalSeconds, 2);    // See bundle time works
                Assert.AreEqual(2, System.IO.Directory.GetFiles(smtpSection.SpecifiedPickupDirectory.PickupDirectoryLocation).Length);
            }
            source.Listeners.Remove(listener);

            // See that it can also bundle when receiving messages from different sources
            listener = new SnakeEyes.EmailTraceListener();
            listener.Attributes.Add("fromAddress", "*****@*****.**");
            listener.Attributes.Add("toAddress", "*****@*****.**");
            listener.Attributes.Add("throttleSeconds", "1");
            listener.Attributes.Add("formatBundleSource", "{{/TraceEvent/EventLogSource}}");
            listener.Attributes.Add("formatBody", "Message = {{/TraceEvent/EventLogSource}}");
            source.Listeners.Add(listener);
            ResetPickupDirectory(smtpSection.SpecifiedPickupDirectory.PickupDirectoryLocation);
            {
                DateTime startTime = DateTime.UtcNow;
                for (int i = 0; i < 5; ++i)
                {
                    source.TraceEvent(System.Diagnostics.TraceEventType.Error, 0, "<TraceEvent><EventLogSource>Damn</EventLogSource></TraceEvent>");
                    source.TraceEvent(System.Diagnostics.TraceEventType.Error, 0, "<TraceEvent><EventLogSource>Again</EventLogSource></TraceEvent>");
                }
                System.Threading.Thread.Sleep(1000);
                Assert.Less(DateTime.UtcNow.Subtract(startTime).TotalSeconds, 3);    // See bundle time works
                Assert.AreEqual(3, System.IO.Directory.GetFiles(smtpSection.SpecifiedPickupDirectory.PickupDirectoryLocation).Length);
            }
            source.Listeners.Remove(listener);
        }
Ejemplo n.º 39
0
 public static void TraceEvent(System.Diagnostics.TraceEventType eventType, int id, string message)
 {
     Source.TraceEvent(eventType, id, message);
     Source.Flush();
 }