Exemplo n.º 1
0
        public void TestExporter() {
            var listener = new ObservableEventListener();
            listener.EnableEvents(TflEventSource.Log, EventLevel.Verbose);
            var subscription = listener.LogToConsole(new LegacyLogFormatter());

            var file = Path.GetTempFileName();
            File.WriteAllText(file, @"t1,t2,t3,t4
Monday,10,1.1,1/1/2014
Tuesday,11,2.2,2/1/2014
Wednesday,12,3.3,3/1/2014
Wednesday,12,3.3,3/1/2014
Thursday,13,4.4,4/1/2014
Friday,14,5.5,5/1/2014
Saturday,15,6.6,6/1/2014");

            File.Delete(OUTPUT);

            var profile = new Profiler().Profile(file);
            new ProfileExporter().Export(profile, OUTPUT);

            subscription.Dispose();
            listener.DisableEvents(TflEventSource.Log);
            listener.Dispose();

            Assert.IsTrue(File.Exists(OUTPUT));
        }
        /// <summary>
        ///     Initializes a new instance of the <see cref="TestBase" /> class.
        /// </summary>
        protected TestBase()
        {
            var observableEventListener = new ObservableEventListener();

            observableEventListener.EnableEvents(ExceptionLoggingEventSource.Log, EventLevel.LogAlways);

            observableEventListener.LogToConsole();
        }
 protected override void Given()
 {
     ColorMapper = new MockDefaultConsoleColorMapper();
     MockConsole = new MockConsoleOutput();
     Formatter = new EventTextFormatter(EventTextFormatter.DashSeparator) { VerbosityThreshold = EventLevel.Informational };
     Listener = new ObservableEventListener();
     Listener.LogToConsole(Formatter, ColorMapper);
     Listener.EnableEvents(TestEventSource.Log, EventLevel.LogAlways);
 }
Exemplo n.º 4
0
        static void Main(string[] args)
        {
            // optimizing IOCP performance
            int minWorkerThreads;
            int minCompletionPortThreads;
            ThreadPool.GetMinThreads(out minWorkerThreads, out minCompletionPortThreads);
            ThreadPool.SetMinThreads(minWorkerThreads, Math.Max(16, minCompletionPortThreads));

            int threadCount = Environment.ProcessorCount;
            if (args.Length > 0)
            {
                threadCount = int.Parse(args[0]);
            }

            var eventListener = new ObservableEventListener();
            eventListener.LogToConsole();
            eventListener.EnableEvents(BootstrapperEventSource.Log, EventLevel.Verbose);
            eventListener.EnableEvents(MqttIotHubAdapterEventSource.Log, EventLevel.Verbose);
            eventListener.EnableEvents(ChannelEventSource.Log, EventLevel.Verbose);
            eventListener.EnableEvents(BootstrapEventSource.Log, EventLevel.Verbose);
            eventListener.EnableEvents(ExecutorEventSource.Log, EventLevel.Verbose);
            eventListener.EnableEvents(MqttEventSource.Log, EventLevel.Verbose);

            try
            {
                var cts = new CancellationTokenSource();

                var certificate = new X509Certificate2("protocol-gateway.contoso.com.pfx", "password");
                var settingsProvider = new AppConfigSettingsProvider();
                BlobSessionStatePersistenceProvider blobSessionStateProvider = BlobSessionStatePersistenceProvider.CreateAsync(
                    settingsProvider.GetSetting("BlobSessionStatePersistenceProvider.StorageConnectionString"),
                    settingsProvider.GetSetting("BlobSessionStatePersistenceProvider.StorageContainerName")).Result;

                TableQos2StatePersistenceProvider tableQos2StateProvider = TableQos2StatePersistenceProvider.CreateAsync(
                    settingsProvider.GetSetting("TableQos2StatePersistenceProvider.StorageConnectionString"),
                    settingsProvider.GetSetting("TableQos2StatePersistenceProvider.StorageTableName")).Result;

                var bootstrapper = new Bootstrapper(settingsProvider, blobSessionStateProvider, tableQos2StateProvider);
                Task.Run(() => bootstrapper.RunAsync(certificate, threadCount, cts.Token), cts.Token);

                while (true)
                {
                    string input = Console.ReadLine();
                    if (input != null && input.ToLowerInvariant() == "exit")
                    {
                        break;
                    }
                }

                cts.Cancel();
                bootstrapper.CloseCompletion.Wait(TimeSpan.FromSeconds(20));
            }
            finally
            {
                eventListener.Dispose();
            }
        }
Exemplo n.º 5
0
        private static void RegisterLogger()
        {
            var listener = new ObservableEventListener();
            listener.EnableEvents(WebApiTracing.Log, EventLevel.LogAlways, Keywords.All);

            listener.LogToConsole();
            listener.LogToFlatFile("test.log");
            listener.LogToWindowsAzureTable(instanceName: "Protiviti", connectionString: "UseDevelopmentStorage=true");
        }
Exemplo n.º 6
0
        static void Main(string[] args)
        {
            if (args.Length < 5)
            {
                Console.WriteLine("Mamemaki.Slab.BigQuery.PlayGround.exe <projectId> <datasetId> <tableId> <serviceAccountEmail> <privateKeyFile>");
                return;
            }
            var projectId = args[0];
            var datasetId = args[1];
            var tableId = args[2];
            var serviceAccountEmail = args[3];
            var privateKeyFile = args[4];
            var tableSchemaFile = args[5];

            using (var listenerConsole = new ObservableEventListener())
            using (var listener = new ObservableEventListener())
            {
                var formatterConsole = new EventTextFormatter(
                    "+=========================================+");

                // Setup listener for debug
                listenerConsole.EnableEvents(SemanticLoggingEventSource.Log, EventLevel.LogAlways);
                listenerConsole.EnableEvents(BigQuerySinkEventSource.Log, EventLevel.LogAlways);
                listenerConsole.LogToConsole(formatterConsole);

                // Setup listener for playgrond
                listener.EnableEvents(PlayGroundEventSource.Log, EventLevel.LogAlways);
                listener.LogToConsole(formatterConsole);
                listener.LogToBigQuery(
                    projectId: projectId,
                    datasetId: datasetId,
                    tableId: tableId,
                    authMethod: "private_key",
                    serviceAccountEmail: serviceAccountEmail,
                    privateKeyFile: privateKeyFile,
                    privateKeyPassphrase: "notasecret",
                    autoCreateTable: true,
                    tableSchemaFile: tableSchemaFile,
                    insertIdFieldName: "%uuid%",
                    bufferingInterval: TimeSpan.FromSeconds(1),
                    bufferingCount: 3,
                    bufferingFlushAllTimeout: Constants.DefaultBufferingFlushAllTimeout,
                    maxBufferSize: 30000);

                PlayGroundEventSource.Log.Trace("start");
                InsertRows(3);
                Thread.Sleep(1);
                InsertRows(3);
                PlayGroundEventSource.Log.Trace("end");
            }

            Console.WriteLine("Press any key to exit");
            Console.ReadLine();
        }
        public static void Start()
        {
            if (_listener != null)
            {
                throw new InvalidOperationException("Logging infrastucture already running");
            }

            _listener = new ObservableEventListener();
            _listener.EnableEvents(EtwSampleServerEventSource.Log, EventLevel.LogAlways);
            _listener.LogToConsole(new SampleFormatter());
        }
Exemplo n.º 8
0
        static void Main(string[] args)
        {
            Options options = new Options();

            CommandLine.Parser.Default.ParseArguments(args, options);

            if (!options.ShowingHelp)
            {
                ObservableEventListener Listener = new ObservableEventListener();
                Listener.EnableEvents((EventSource)Harmonize.Instrumentation.Error, EventLevel.LogAlways, Keywords.All);
                Listener.EnableEvents((EventSource)Harmonize.Instrumentation.Harmonization, EventLevel.LogAlways, Keywords.All);

                //ObservableEventListener harmonyEventListener = new ObservableEventListener();
                //harmonyEventListener.EnableEvents((EventSource)With.Harmony.Instrumentation.State, EventLevel.LogAlways, Keywords.All);

                //ObservableEventListener owlCommandEventListener = new ObservableEventListener();
                //owlCommandEventListener.EnableEvents((EventSource)With.Owl.Intuition.Instrumentation.Command.Endpoint, EventLevel.LogAlways, Keywords.All);

                //ObservableEventListener owlPacketEventListener = new ObservableEventListener();
                //owlPacketEventListener.EnableEvents((EventSource)With.Owl.Intuition.Instrumentation.Packet.Endpoint, EventLevel.LogAlways, Keywords.All);

                //ObservableEventListener owlStateEventListener = new ObservableEventListener();
                //owlStateEventListener.EnableEvents((EventSource)With.Owl.Intuition.Instrumentation.State.Machine, EventLevel.LogAlways, Keywords.All);

                //ObservableEventListener xmppEventListener = new ObservableEventListener();
                //xmppEventListener.EnableEvents((EventSource)With.Harmony.Instrumentation.Xmpp, EventLevel.LogAlways, Keywords.All);

                //ObservableEventListener alljoynEventListener = new ObservableEventListener();
                //alljoynEventListener.EnableEvents(With.Alljoyn.Instrumentation.Coordinator, EventLevel.LogAlways, Keywords.All);

                //ObservableEventListener storeEventListener = new ObservableEventListener();
                //storeEventListener.EnableEvents((EventSource)State.Instrumentation.Store, EventLevel.LogAlways, Keywords.All);

                //ObservableEventListener messagingEventListener = new ObservableEventListener();
                //messagingEventListener.EnableEvents((EventSource)With.Messaging.Instrumentation.Messages, EventLevel.LogAlways, Keywords.All);

                options.TraceEvents.Split(',').Select(name => Listener.EnableEvents(name, EventLevel.LogAlways, Keywords.All)).ForEach(Cons.WriteLine);

                using (new CompositeDisposable(Listener.LogToConsole()))
                {
                    Client client = new Client(options);

                    client.Start();

                    System.Console.WriteLine("Started");
                    System.Console.WriteLine("Hit Return to stop");
                    System.Console.ReadLine();

                    client.Stop();
                }
            }
        }
        public void SetupTest()
        {
            var listener = new ObservableEventListener();
            listener.EnableEvents(WebApiTracing.Log, EventLevel.LogAlways, Keywords.All);
            listener.LogToConsole();
            listener.LogToTestInMemorySink(_testResults);

            _cts = new CancellationTokenSource();

            _config.Routes.MapHttpRoute("DefaultApi", "{controller}/{id}", new { id = RouteParameter.Optional });
            _config.Services.Replace(typeof(ITraceWriter), new SlabTraceWriter());
            var server = new HttpServer(_config);
            _client = new HttpMessageInvoker(server);
        }
Exemplo n.º 10
0
        static void Main(string[] args) {

            var listener = new ObservableEventListener();
            listener.EnableEvents(TflEventSource.Log, EventLevel.Informational);
            var subscription = listener.LogToConsole(new LegacyLogFormatter());

            ValidateArguments(args);

            new ProfileExporter().Export(new Profiler().Profile(_input, _sample), _output);

            subscription.Dispose();
            listener.DisableEvents(TflEventSource.Log);
            listener.Dispose();
        }
Exemplo n.º 11
0
        private static async Task MainAsync(string[] args)
        {
            var observableEventListener = new ObservableEventListener();

            observableEventListener.EnableEvents(
              WarmStorageEventSource.Log, EventLevel.Informational);

            observableEventListener.LogToConsole();

            await CommonConsoleHost.RunWithOptionsAsync(new Dictionary<string, Func<CancellationToken, Task>>
            {
                { "Provision Resources", ProvisionResourcesAsync },
                { "Run Warm Storage Consumer", RunAsync }
            });
        }
        static void Main()
        {
            using (var listener = new ObservableEventListener())
            {
                listener.EnableEvents(SampleEventSource.Log, EventLevel.LogAlways, SampleEventSource.Keywords.SampleApp);

                listener.LogToConsole();
                listener.LogToSeq("http://my-seq");

                SampleEventSource.Log.Greeting(Environment.UserName);
            }

            Console.WriteLine("Done");
            Console.ReadKey(true);
        }
Exemplo n.º 13
0
    static void Main(string[] args)
    {
      ObservableEventListener listener = new ObservableEventListener();
      listener.EnableEvents(MyCompanyEventSource.Log, EventLevel.LogAlways, Keywords.All);

      listener.LogToConsole();

      // Modify these settings to match your SMTP service requirements.
      listener.LogToEmail("smtp.live.com", 587, "*****@*****.**", "In Proc Sample", "etw");

      MyCompanyEventSource.Log.Failure("No response from servers, general network failure!!");

      listener.DisableEvents(MyCompanyEventSource.Log);
      listener.Dispose();
    }
Exemplo n.º 14
0
        static async Task RunClientAsync()
        {
            var eventListener = new ObservableEventListener();
            eventListener.LogToConsole();
            eventListener.EnableEvents(DefaultEventSource.Log, EventLevel.Verbose);

            var group = new MultithreadEventLoopGroup();

            X509Certificate2 cert = null;
            string targetHost = null;
            if (EchoClientSettings.IsSsl)
            {
                cert = new X509Certificate2("dotnetty.com.pfx", "password");
                targetHost = cert.GetNameInfo(X509NameType.DnsName, false);
            }
            try
            {
                var bootstrap = new Bootstrap();
                bootstrap
                    .Group(group)
                    .Channel<TcpSocketChannel>()
                    .Option(ChannelOption.TcpNodelay, true)
                    .Handler(new ActionChannelInitializer<ISocketChannel>(channel =>
                    {
                        IChannelPipeline pipeline = channel.Pipeline;

                        if (cert != null)
                        {
                            pipeline.AddLast(new TlsHandler(stream => new SslStream(stream, true, (sender, certificate, chain, errors) => true), new ClientTlsSettings(targetHost)));
                        }
                        pipeline.AddLast(new LengthFieldPrepender(2));
                        pipeline.AddLast(new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2));

                        pipeline.AddLast(new EchoClientHandler());
                    }));

                IChannel bootstrapChannel = await bootstrap.ConnectAsync(new IPEndPoint(EchoClientSettings.Host, EchoClientSettings.Port));

                Console.ReadLine();

                await bootstrapChannel.CloseAsync();
            }
            finally
            {
                group.ShutdownGracefullyAsync().Wait(1000);
                eventListener.Dispose();
            }
        }
Exemplo n.º 15
0
        private static void Main(string[] args)
        {
            var observableEventListener = new ObservableEventListener();

            var configuration = SimulatorConfiguration.GetCurrentConfiguration();

            observableEventListener.EnableEvents(ScenarioSimulatorEventSource.Log, configuration.GetLogLevel());

            observableEventListener.LogToConsole();

            var hostName = ConfigurationHelper.SourceName;

            _deviceSimulator = new SimulationProfile(hostName, configuration);

            // check for scenario specified on the command line
            if (args.Length > 0)
            {
                var scenario = args.Contains("/default", StringComparer.OrdinalIgnoreCase)
                    ? SimulationScenarios.DefaultScenario()
                    : args.First(x => !x.StartsWith("/",StringComparison.Ordinal));

                var ct = args.Contains("/webjob", StringComparer.OrdinalIgnoreCase)
                    ? GetWebJobCancellationToken()
                    : CancellationToken.None;

                ProvisionDevicesAsync(ct).Wait();

                _deviceSimulator.RunSimulationAsync(scenario, ct).Wait();

                return;
            }

            var options = new Dictionary<string, Func<CancellationToken, Task>>();

            options.Add("Provision Devices", ProvisionDevicesAsync);

            // no command line arguments, so prompt with a menu.
            foreach (var scenario in SimulationScenarios.AllScenarios)
            {
                options.Add("Run " + scenario, (Func<CancellationToken, Task>)(token => _deviceSimulator.RunSimulationAsync(scenario, token)));
            }

            //options.Add("Deprovision Devices", DeprovisionDevicesAsync);

            Tests.Common.ConsoleHost.RunWithOptionsAsync(options).Wait();
        }
Exemplo n.º 16
0
        static async Task RunServerAsync()
        {
            var eventListener = new ObservableEventListener();
            eventListener.LogToConsole();
            eventListener.EnableEvents(DefaultEventSource.Log, EventLevel.Verbose);

            var bossGroup = new MultithreadEventLoopGroup(1);
            var workerGroup = new MultithreadEventLoopGroup();
            X509Certificate2 tlsCertificate = null;
            if (EchoServerSettings.IsSsl)
            {
                tlsCertificate = new X509Certificate2("dotnetty.com.pfx", "password");
            }
            try
            {
                var bootstrap = new ServerBootstrap();
                bootstrap
                    .Group(bossGroup, workerGroup)
                    .Channel<TcpServerSocketChannel>()
                    .Option(ChannelOption.SoBacklog, 100)
                    .Handler(new LoggingHandler(LogLevel.INFO))
                    .ChildHandler(new ActionChannelInitializer<ISocketChannel>(channel =>
                    {
                        IChannelPipeline pipeline = channel.Pipeline;
                        if (tlsCertificate != null)
                        {
                            pipeline.AddLast(TlsHandler.Server(tlsCertificate));
                        }
                        pipeline.AddLast(new LengthFieldPrepender(2));
                        pipeline.AddLast(new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2));

                        pipeline.AddLast(new EchoServerHandler());
                    }));

                IChannel bootstrapChannel = await bootstrap.BindAsync(EchoServerSettings.Port);

                Console.ReadLine();

                await bootstrapChannel.CloseAsync();
            }
            finally
            {
                Task.WaitAll(bossGroup.ShutdownGracefullyAsync(), workerGroup.ShutdownGracefullyAsync());
                eventListener.Dispose();
            }
        }
Exemplo n.º 17
0
    static void SimpleEventSource()
    {
      // Set up and enable the event listener - typically done when the application starts
      var listener = new ObservableEventListener();
      listener.LogToConsole();
      listener.EnableEvents(MyCompanyEventSource.Log, EventLevel.LogAlways, Keywords.All);

      // Log some messages
      MyCompanyEventSource.Log.Startup();
      MyCompanyEventSource.Log.Failure("Couldn't connect to server.");
      Console.WriteLine("Written two log messages.\nUsing a basic console listener to capture them.");
      Console.WriteLine("The color is determined by the severity level.\n");
      
      // Disable the event listener - typically done when the application terminates
      listener.DisableEvents(MyCompanyEventSource.Log);
      listener.Dispose();
     }
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);


            var listener = new ObservableEventListener();
            listener.EnableEvents(TestEvents.Log, EventLevel.LogAlways, Keywords.All);

            listener.LogToConsole();
            listener.LogToElasticsearch("SLABEL", "http://localhost:9200", "myindex", "mytype", bufferingCount: 1);

            TestEvents.Log.Critical("Hello world In-Process Critical");
            TestEvents.Log.Error("Hello world In-Process Error");
            TestEvents.Log.Informational("Hello world In-Process Informational");
        }
Exemplo n.º 19
0
        static void Main()
        {
            Application.ThreadException +=
                new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);

            //create formatter
            var formatter = new JsonEventTextFormatter(EventTextFormatting.Indented);

            using (var listener = new ObservableEventListener())
            {
                listener.LogToConsole(formatter);
                listener.LogToWindowsAzureTable("Calculator", "UseDevelopmentStorage=true;");
                listener.EnableEvents(CalculatorEventSource.Log, EventLevel.LogAlways, Keywords.All);

                Form entryForm = new MainForm();
                Application.EnableVisualStyles();
                Application.Run(entryForm);
            }
        }
Exemplo n.º 20
0
        private static async Task MainAsync(string[] args)
        {
            var observableEventListener = new ObservableEventListener();

            var configuration = SimulatorConfiguration.GetCurrentConfiguration();

            observableEventListener.EnableEvents(ScenarioSimulatorEventSource.Log, configuration.EventLevel);

            observableEventListener.LogToConsole();

            _deviceSimulator = new SimulationProfile("Console", configuration);

            // check for scenario specified on the command line
            if (args.Length > 0)
            {
                var scenario = args.Contains("/default", StringComparer.OrdinalIgnoreCase)
                    ? SimulationScenarios.DefaultScenario()
                    : args.First(x => !x.StartsWith("/"));

                var ct = args.Contains("/webjob", StringComparer.OrdinalIgnoreCase)
                    ? GetWebJobCancellationToken()
                    : CancellationToken.None;

                await _deviceSimulator.RunSimulationAsync(scenario, ct).ConfigureAwait(false);

                return;
            }

            var options = new Dictionary <string, Func <CancellationToken, Task> >();

            options.Add("Provision Devices", ProvisionDevicesAsync);

            // no command line arguments, so prompt with a menu.
            foreach (var scenario in  SimulationScenarios.AllScenarios)
            {
                options.Add("Run " + scenario, (Func <CancellationToken, Task>)(token => _deviceSimulator.RunSimulationAsync(scenario, token)));
            }

            //options.Add("Deprovision Devices", DeprovisionDevicesAsync);

            await Tests.Common.ConsoleHost.RunWithOptionsAsync(options).ConfigureAwait(false);
        }
Exemplo n.º 21
0
        static async Task RunServer()
        {
            var eventListener = new ObservableEventListener();

            eventListener.LogToConsole();
            eventListener.EnableEvents(DefaultEventSource.Log, EventLevel.Verbose);

            var bossGroup   = new MultithreadEventLoopGroup(1);
            var workerGroup = new MultithreadEventLoopGroup();

            try
            {
                var bootstrap = new ServerBootstrap();
                bootstrap
                .Group(bossGroup, workerGroup)
                .Channel <TcpServerSocketChannel>()
                .Option(ChannelOption.SoBacklog, 100)
                .Handler(new LoggingHandler(LogLevel.INFO))
                .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;

                    if (EchoServerSettings.IsSsl)
                    {
                        pipeline.AddLast(TlsHandler.Server(new X509Certificate2("dotnetty.com.pfx", "password")));
                    }

                    pipeline.AddLast(new EchoServerHandler());
                }));

                IChannel bootstrapChannel = await bootstrap.BindAsync(EchoServerSettings.Port);

                Console.ReadLine();

                await bootstrapChannel.CloseAsync();
            }
            finally
            {
                Task.WaitAll(bossGroup.ShutdownGracefullyAsync(), workerGroup.ShutdownGracefullyAsync());
                eventListener.Dispose();
            }
        }
Exemplo n.º 22
0
        static async Task RunClient()
        {
            var eventListener = new ObservableEventListener();

            eventListener.LogToConsole();
            eventListener.EnableEvents(DefaultEventSource.Log, EventLevel.Verbose);

            var group = new MultithreadEventLoopGroup();

            try
            {
                var bootstrap = new Bootstrap();
                bootstrap
                .Group(group)
                .Channel <TcpSocketChannel>()
                .Option(ChannelOption.TcpNodelay, true)
                .Handler(new ActionChannelInitializer <ISocketChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;

                    if (EchoClientSettings.IsSsl)
                    {
                        var cert          = new X509Certificate2("dotnetty.com.pfx", "password");
                        string targetHost = cert.GetNameInfo(X509NameType.DnsName, false);
                        pipeline.AddLast(TlsHandler.Client(targetHost, null, (sender, certificate, chain, errors) => true));
                    }

                    pipeline.AddLast(new EchoClientHandler());
                }));

                IChannel bootstrapChannel = await bootstrap.ConnectAsync(new IPEndPoint(EchoClientSettings.Host, EchoClientSettings.Port));

                Console.ReadLine();

                await bootstrapChannel.CloseAsync();
            }
            finally
            {
                group.ShutdownGracefullyAsync().Wait(1000);
                eventListener.Dispose();
            }
        }
Exemplo n.º 23
0
        public void WhenPayloadHasDifferentTypesAndNull()
        {
            var consoleOutputInterceptor = new MockConsoleOutputInterceptor();
            var formatter = new EventTextFormatter(EventTextFormatter.DashSeparator);
            var logger    = MockEventSourceNoTask.Logger;

            using (var eventListener = new ObservableEventListener())
            {
                eventListener.LogToConsole();
                eventListener.EnableEvents(logger, EventLevel.LogAlways);
                logger.DifferentTypes(null, 500000);
            }

            var entry = Regex.Split(consoleOutputInterceptor.Ouput, formatter.Header).Where(c => !string.IsNullOrWhiteSpace(c)).SingleOrDefault();

            Assert.IsNotNull(entry);
            Assert.IsTrue(entry.Count() > 0);
            StringAssert.Contains(entry, @"strArg : ");
            StringAssert.Contains(entry, @"longArg : 500000");
        }
Exemplo n.º 24
0
        public void WhenCriticalVerbosityForFormatter()
        {
            var consoleOutputInterceptor = new MockConsoleOutputInterceptor();
            var formatter = new EventTextFormatter(EventTextFormatter.DashSeparator);

            using (var eventListener = new ObservableEventListener())
            {
                eventListener.LogToConsole(formatter);
                formatter.VerbosityThreshold = EventLevel.Critical;
                eventListener.EnableEvents(MockConsoleListenerEventSource.Logger, EventLevel.Critical);
                MockConsoleListenerEventSource.Logger.Critical("This is to log critical in Console");
            }

            var entry = Regex.Split(consoleOutputInterceptor.Ouput, formatter.Header).Where(c => !string.IsNullOrWhiteSpace(c)).SingleOrDefault();

            Assert.IsNotNull(entry);
            StringAssert.Contains(entry, "200");
            StringAssert.Contains(entry, "Keywords : None");
            Assert.AreEqual(DefaultConsoleColorMapper.Critical, consoleOutputInterceptor.OutputForegroundColor);
        }
Exemplo n.º 25
0
        static TestHelpers()
        {
            ServiceBusConnectionString = GetTestSetting("ServiceBusConnectionString");
            if (string.IsNullOrWhiteSpace(ServiceBusConnectionString))
            {
                throw new ArgumentException("A ServiceBus connection string must be defined in either an environment variable or in configuration.");
            }

            StorageConnectionString = GetTestSetting("StorageConnectionString");
            if (string.IsNullOrWhiteSpace(StorageConnectionString))
            {
                throw new ArgumentException("A Storage connection string must be defined in either an environment variable or in configuration.");
            }

            TaskHubName = ConfigurationManager.AppSettings.Get("TaskHubName");

            eventListener = new ObservableEventListener();
            eventListener.LogToConsole();
            eventListener.EnableEvents(DefaultEventSource.Log, EventLevel.LogAlways);
        }
        public void OpenAndStartServiceHostTest()
        {
            eventListener = new ObservableEventListener();
            eventListener.LogToConsole();
            eventListener.EnableEvents(DefaultEventSource.Log, EventLevel.LogAlways);

            TraceSource source = new TraceSource("DurableTask");

            source.Listeners.AddRange(Trace.Listeners);

            IOrchestrationServiceInstanceStore instanceStore = new AzureTableInstanceStore(TaskHubName, StorageConnectionString);
            ServiceBusOrchestrationService     orchestrationServiceAndClient =
                new ServiceBusOrchestrationService(ServiceBusConnectionString, TaskHubName, instanceStore, null, null);

            orchestrationServiceAndClient.CreateIfNotExistsAsync().Wait();

            TaskHubClient taskHubClient = new TaskHubClient(orchestrationServiceAndClient);
            TaskHubWorker taskHub       = new TaskHubWorker(orchestrationServiceAndClient);

            taskHub.AddTaskOrchestrations(typeof(CounterOrchestration));
            taskHub.AddTaskActivities(typeof(Task1), typeof(Task2));

            var rnts = ((AzureTableInstanceStore)instanceStore).GetJumpStartEntitiesAsync(1000).Result;

            var byNameQuery = new OrchestrationStateQuery();

            byNameQuery.AddStatusFilter(OrchestrationStatus.Pending);
            byNameQuery.AddNameVersionFilter(typeof(CounterOrchestration).FullName);

            var results = ((AzureTableInstanceStore)instanceStore).QueryOrchestrationStatesAsync(byNameQuery).Result;

            var instance = taskHubClient.CreateOrchestrationInstanceAsync(typeof(CounterOrchestration), Guid.NewGuid().ToString(), new TestOrchestrationInput()).Result;

            taskHub.StartAsync().Wait();

            var state = instanceStore.GetOrchestrationStateAsync(instance.InstanceId, true).Result;

            var res = taskHubClient.GetOrchestrationHistoryAsync(instance).Result;

            taskHubClient.WaitForOrchestrationAsync(instance, TimeSpan.MaxValue).Wait();
        }
Exemplo n.º 27
0
        public void WhenSingleLineTextFormatter()
        {
            var consoleOutputInterceptor = new MockConsoleOutputInterceptor();
            var formatter = new EventTextFormatter(EventTextFormatter.DashSeparator);

            using (var eventListener = new ObservableEventListener())
            {
                eventListener.LogToConsole(formatter);
                eventListener.EnableEvents(MockConsoleListenerEventSource.Logger, EventLevel.Error);
                MockConsoleListenerEventSource.Logger.Critical("This is to log critical in Console");
                MockConsoleListenerEventSource.Logger.Verbose("This is should not be logged in Console");
            }

            var entry = Regex.Split(consoleOutputInterceptor.Ouput, formatter.Header).Where(c => !string.IsNullOrWhiteSpace(c)).SingleOrDefault();

            Assert.IsNotNull(entry);
            Assert.IsFalse(entry.Contains("This is should not be logged in Console"));
            Assert.IsTrue(entry.Contains("This is to log critical in Console"));
            Assert.IsTrue(entry.Contains("\r\nProviderId : "));
            Assert.IsTrue(entry.Contains("\r\nEventId : 200\r\nKeywords : None\r\nLevel : Critical\r\nMessage : Functional Test\r\nOpcode : Info\r\nTask : 65334\r\nVersion : 0\r\nPayload : [message : This is to log critical in Console] \r\nEventName : CriticalInfo\r\nTimestamp :"));
        }
Exemplo n.º 28
0
        static void Main(string[] args)
        {
            using (var listener = new ObservableEventListener())
            {
                listener.LogToConsole(new ConsoleFormatter());
                listener.EnableEvents(EngineEventSource.Log, EventLevel.Verbose, Keywords.All);
                listener.EnableEvents(TableStorageEventSource.Log, EventLevel.Verbose, Keywords.All);

                var eventContext = new TableStorageJobEventContext(
                    CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageAccount")));

                var host = new JobHost(eventContext);
                host.Add(new LogCleanupJob());
                host.Add(new SendNewsletterJob());
                host.Add(new LongRunningJob());
                host.Start();

                Console.WriteLine("Waiting...");
                Console.ReadLine();
            }
        }
Exemplo n.º 29
0
        public void WhenEventWithMessageInAttribute()
        {
            var consoleOutputInterceptor = new MockConsoleOutputInterceptor();
            var formatter      = new EventTextFormatter(EventTextFormatter.DashSeparator);
            var eventformatter = new EventTextFormatter("----", "-----", EventLevel.Informational);

            eventformatter.DateTimeFormat = "dd/MM/yyyy";
            var logger = TestEventSourceNoAttributes.Logger;

            using (var eventListener = new ObservableEventListener())
            {
                eventListener.LogToConsole(eventformatter);
                eventListener.EnableEvents(logger, EventLevel.LogAlways);
                logger.ObjectArrayEvent4(1000, "stringstringarg10", 2000, "stringstringarg20", 3000);
            }

            var entry = Regex.Split(consoleOutputInterceptor.Ouput, formatter.Header).Where(c => !string.IsNullOrWhiteSpace(c)).SingleOrDefault();

            Assert.IsNotNull(entry);
            StringAssert.Contains(entry, "[arg0 : 1000] [arg1 : stringstringarg10] [arg2 : 2000] [arg3 : stringstringarg20] [arg4 : 3000]");
            StringAssert.Contains(entry, "Message : Check if it is logged");
        }
Exemplo n.º 30
0
        public void WhenMultipleEvents()
        {
            var consoleOutputInterceptor = new MockConsoleOutputInterceptor();
            var formatter = new EventTextFormatter(EventTextFormatter.DashSeparator);
            var logger    = MockConsoleListenerEventSource.Logger;

            using (var eventListener = new ObservableEventListener())
            {
                eventListener.EnableEvents(logger, EventLevel.LogAlways);
                eventListener.LogToConsole();
                for (int n = 0; n < 300; n++)
                {
                    logger.Informational("Some message to console " + n);
                }
            }

            var output = Regex.Split(consoleOutputInterceptor.Ouput, formatter.Header).Where(c => !string.IsNullOrWhiteSpace(c));

            Assert.IsNotNull(output);
            StringAssert.Contains(output.First(), "Some message to console 0");
            StringAssert.Contains(output.First(), "Some message to console 299");
        }
Exemplo n.º 31
0
        public void WhenEventWithMessageInAttributeUsingXml()
        {
            var consoleOutputInterceptor = new MockConsoleOutputInterceptor();
            var formatter    = new EventTextFormatter(EventTextFormatter.DashSeparator);
            var xmlFormatter = new XmlEventTextFormatter();

            xmlFormatter.DateTimeFormat = "dd/MM/yyyy";
            var logger = TestEventSourceNoAttributes.Logger;

            using (var eventListener = new ObservableEventListener())
            {
                eventListener.LogToConsole(xmlFormatter);
                eventListener.EnableEvents(logger, EventLevel.LogAlways);
                logger.ObjectArrayEvent4(1000, "stringstringarg10", 2000, "stringstringarg20", 3000);
            }

            var entry = Regex.Split(consoleOutputInterceptor.Ouput, formatter.Header).Where(c => !string.IsNullOrWhiteSpace(c)).SingleOrDefault();

            Assert.IsNotNull(entry);
            StringAssert.Contains(entry, "<Data Name=\"arg0\">1000</Data><Data Name=\"arg1\">stringstringarg10</Data><Data Name=\"arg2\">2000</Data><Data Name=\"arg3\">stringstringarg20</Data><Data Name=\"arg4\">3000</Data>");
            StringAssert.Contains(entry, "<Message>Check if it is logged</Message>");
        }
Exemplo n.º 32
0
        public void WhenOneSourceTwoListeners()
        {
            var consoleOutputInterceptor = new MockConsoleOutputInterceptor();
            var formatter = new EventTextFormatter(EventTextFormatter.DashSeparator);

            using (var eventListener = new ObservableEventListener())
                using (var eventListener2 = new ObservableEventListener())
                {
                    eventListener.LogToConsole(new EventTextFormatter(), null);
                    eventListener2.LogToConsole();
                    string errorMessage = string.Concat("Error ", Guid.NewGuid());
                    string infoMessage  = string.Concat("Message", Guid.NewGuid());
                    eventListener2.EnableEvents(MockConsoleListenerEventSource.Logger, EventLevel.Error);
                    eventListener.EnableEvents(MockConsoleListenerEventSource.Logger, EventLevel.Informational);
                    MockConsoleListenerEventSource.Logger.Informational(infoMessage);
                    MockConsoleListenerEventSource.Logger.Error(errorMessage);

                    var entry = Regex.Split(consoleOutputInterceptor.Ouput, formatter.Header).Where(c => !string.IsNullOrWhiteSpace(c)).SingleOrDefault();
                    Assert.IsNotNull(entry);
                    StringAssert.Contains(entry, "100");
                    StringAssert.Contains(entry, "300");
                }
        }
Exemplo n.º 33
0
        private static async Task MainAsync(string[] args)
        {
            var observableEventListener = new ObservableEventListener();

            var configuration = SimulatorConfiguration.GetCurrentConfiguration();

            observableEventListener.EnableEvents(ScenarioSimulatorEventSource.Log, configuration.EventLevel);

            observableEventListener.LogToConsole();

            var deviceSimulator = new SimulationProfile("Console", 1, configuration);

            // check for scenario specified on the command line
            if (args.Length > 0)
            {
                var scenario = args.Contains("/default", StringComparer.OrdinalIgnoreCase)
                    ? SimulationScenarios.DefaultScenario()
                    : args.First(x => !x.StartsWith("/"));

                var ct = args.Contains("/webjob", StringComparer.OrdinalIgnoreCase)
                    ? GetWebJobCancellationToken()
                    : CancellationToken.None;

                await deviceSimulator.RunSimulationAsync(scenario, ct);
                return;
            }

            // no command line arguments, so prompt with a menu
            var options = SimulationScenarios
                .AllScenarios
                .ToDictionary(
                    scenario => "Run " + scenario,
                    scenario => (Func<CancellationToken, Task>)(token => deviceSimulator.RunSimulationAsync(scenario, token)));

            await Tests.Common.ConsoleHost.RunWithOptionsAsync(options);
        }
Exemplo n.º 34
0
        static void Main(string[] args)
        {
            #region SLAB
            var ObservableEventListener = new ObservableEventListener();
            ObservableEventListener.EnableEvents(ControllerEvents.Log, EventLevel.LogAlways, Keywords.All);
            ObservableEventListener.EnableEvents(GlobalEvents.Log, EventLevel.LogAlways, Keywords.All);
            ObservableEventListener.EnableEvents(HubClientEvents.Log, EventLevel.LogAlways, Keywords.All);
            var formatter = new PrefixEventTextFormatter("-----------", null, "# ", @"yyyy-MM-dd hh\:mm\:ss\.fff");
            ObservableEventListener.LogToConsole(formatter);
            #endregion

            string name = "AA";

            var myHubClient = new MyHubClient();
            while (true)
            {
                string key = Console.ReadLine();
                if (key.ToUpper() == "A")
                {
                    if (myHubClient.State == ConnectionState.Connected)
                    {
                        myHubClient.SendAllClient(name, "hello all");
                    }
                    else
                    {
                        HubClientEvents.Log.Warning("Can't send message, connectionState= " + myHubClient.State);
                    }
                }
                if (key.ToUpper() == "B")
                {
                    if (myHubClient.State == ConnectionState.Connected)
                    {
                        myHubClient.SendToSingle(Console.ReadLine(), name, "hello world");
                    }
                    else
                    {
                        HubClientEvents.Log.Warning("Can't send message, connectionState= " + myHubClient.State);
                    }
                }
                if (key.ToUpper() == "H")
                {
                    if (myHubClient.State == ConnectionState.Connected)
                    {
                        myHubClient.Heartbeat();
                    }
                    else
                    {
                        HubClientEvents.Log.Warning("Can't send message, connectionState= " + myHubClient.State);
                    }
                }
                if (key.ToUpper() == "S")
                {
                    name = Console.ReadLine();
                    if (myHubClient.State == ConnectionState.Connected)
                    {
                        myHubClient.Subscribe(name);
                    }
                    else
                    {
                        HubClientEvents.Log.Warning("Can't send message, connectionState= " + myHubClient.State);
                    }
                }

                if (key.ToUpper() == "Q")
                {
                    if (myHubClient.State == ConnectionState.Connected)
                    {
                        myHubClient.Unsubscribe(name);
                    }
                    else
                    {
                        HubClientEvents.Log.Warning("Can't send message, connectionState= " + myHubClient.State);
                    }
                }

                if (key.ToUpper() == "C")
                {
                    myHubClient.CloseHub();
                    HubClientEvents.Log.Informational("Closed Hub");
                }
            }
        }
        private void EnableNonTransientErrorsHandling()
        {
            var observable = new ObservableEventListener();
            this.slabNonTransientErrors = observable;

            if (this.consoleMode)
            {
                observable.LogToConsole();
            }
            else
            {
                observable.Subscribe(new ServiceEventLogSink(this.EventLog));
            }

            EventLevel level;
            if (!Enum.TryParse(ConfigurationManager.AppSettings[NonTransientErrorsEventLevelKey], out level))
            {
                level = EventLevel.LogAlways;
            }

            this.slabNonTransientErrors.EnableEvents(SemanticLoggingEventSource.Log, level, Keywords.All);

            // Capture any unhandled error in worker threads
            AppDomain.CurrentDomain.UnhandledException += this.OnAppDomainUnhandledException;

            // Handle unobserved task exceptions
            TaskScheduler.UnobservedTaskException += this.OnUnobservedTaskException;
        }
Exemplo n.º 36
0
        static void Main(string[] args)
        {
            var listener = new ObservableEventListener();
            listener.EnableEvents(RxFloodQuickStartEventSource.Log, EventLevel.LogAlways, Keywords.All);

            // ThrottleEventsWithEventId is a custom extension method that shows how you can leverage the power of Reactive Extensions (Rx) 
            // to perform filtering (or transformation) of the event stream before it is sent to the underlying sink.
            // In this case, ThrottleEventsWithEventId will throttle entries with EventID=4 and mute additional occurrences for 15 seconds.
            // This prevents a particular event from flooding the log sink, making it difficult to diagnose other issues.
            // This can be useful in the case that a high-throughput event does not have a keyword or verbosity setting that makes it easy
            // to exclude it in the call to listener.EnableEvents(EventSource, EventLevel, EventKeywords).

            // Note: For basic scenarios without this extra filtering, you DO NOT need to use Rx, and SLAB does not depend on it.

            var subscription = listener
                                .ThrottleEventsWithEventId(TimeSpan.FromSeconds(15), ThrottledEventId)
                                .LogToConsole(SingleLineFormatter);

            // The previous custom extension method (ThrottleEventsWithEventId) is all that is needed to call to throttle
            // an event that is flooding the log. 
            // The rest of the code in this QuickStart is here to show an interactive demo of how it looks if this filter is turned on or off.
            bool currentlyThrottling = true;

            var cts = new CancellationTokenSource();

            Console.WriteLine("This program simulates the scenario of a particular event being logged multiple times in succession when a certain condition occurs,");
            Console.WriteLine("such as when there is a transient or expected connectivity error during system upgrades.");
            Console.WriteLine();
            Console.WriteLine("While the application is logging messages, use the following commands:");
            Console.WriteLine(" [ESC]      Exists the application.");
            Console.WriteLine(" [Spacebar] Toggles the throttling filter.");
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("Press any key to start doing background work.");

            var key = Console.ReadKey(false);
            if (key.Key == ConsoleKey.Escape)
            {
                return;
            }

            DoBackgroundWork(cts.Token);

            while (!cts.IsCancellationRequested)
            {
                key = Console.ReadKey(false);
                switch (key.Key)
                {
                    case ConsoleKey.Spacebar:
                        subscription.Dispose();
                        if (currentlyThrottling)
                        {
                            Console.WriteLine("Filter toggled: event entries will not be throttled. In this scenario, if there is no post-filtering of events, important messages could go unnoticed.");
                            Thread.Sleep(TimeSpan.FromSeconds(3));
                            currentlyThrottling = false;

                            // Note that the events are sent directly to the console, without using Reactive Extensions.
                            subscription = listener
                                                .LogToConsole(SingleLineFormatter);
                        }
                        else
                        {
                            Console.WriteLine("Filter toggled: event entries with ID {0} will be throttled for 15 seconds to prevent that type of entry to flood the log.", ThrottledEventId);
                            Thread.Sleep(TimeSpan.FromSeconds(3));
                            currentlyThrottling = true;

                            // Note that the events are filtered first and then sent to the console, using Reactive Extensions.
                            subscription = listener
                                                .ThrottleEventsWithEventId(TimeSpan.FromSeconds(15), ThrottledEventId)
                                                .LogToConsole(SingleLineFormatter);
                        }
                        
                        break;

                    case ConsoleKey.Escape:
                        cts.Cancel();
                        break;
                }
            }

            listener.Dispose();
        }
Exemplo n.º 37
0
        static void Main(string[] args)
        {
            eventListener = new ObservableEventListener();
            eventListener.LogToConsole();
            eventListener.EnableEvents(DefaultEventSource.Log, EventLevel.LogAlways);

            if (CommandLine.Parser.Default.ParseArgumentsStrict(args, ArgumentOptions))
            {
                string serviceBusConnectionString = GetSetting("ServiceBusConnectionString");
                string storageConnectionString    = GetSetting("StorageConnectionString");
                string taskHubName = ConfigurationManager.AppSettings["taskHubName"];

                //IOrchestrationServiceInstanceStore instanceStore = new AzureTableInstanceStore(taskHubName, storageConnectionString);

                //var orchestrationServiceAndClient =
                //    new ServiceBusOrchestrationService(serviceBusConnectionString, taskHubName, instanceStore, null, null);

                var orchestrationServiceAndClient =
                    new DurableTask.Emulator.LocalOrchestrationService();

                var taskHubClient = new TaskHubClient(orchestrationServiceAndClient);
                var taskHub       = new TaskHubWorker(orchestrationServiceAndClient);

                if (ArgumentOptions.CreateHub)
                {
                    orchestrationServiceAndClient.CreateIfNotExistsAsync().Wait();
                }

                OrchestrationInstance instance = null;

                if (!string.IsNullOrWhiteSpace(ArgumentOptions.StartInstance))
                {
                    string instanceId = ArgumentOptions.InstanceId ?? Guid.NewGuid().ToString();
                    Console.WriteLine($"Start Orchestration: {ArgumentOptions.StartInstance}");
                    switch (ArgumentOptions.StartInstance)
                    {
                    case "Greetings":
                        instance = taskHubClient.CreateOrchestrationInstanceAsync(typeof(GreetingsOrchestration), instanceId, null).Result;
                        break;

                    case "Greetings2":
                        if (ArgumentOptions.Parameters == null || ArgumentOptions.Parameters.Length != 1)
                        {
                            throw new ArgumentException("parameters");
                        }

                        instance = taskHubClient.CreateOrchestrationInstanceAsync(typeof(GreetingsOrchestration2), instanceId,
                                                                                  int.Parse(ArgumentOptions.Parameters[0])).Result;
                        break;

                    case "Cron":
                        // Sample Input: "0 12 * */2 Mon"
                        instance = taskHubClient.CreateOrchestrationInstanceAsync(typeof(CronOrchestration), instanceId,
                                                                                  (ArgumentOptions.Parameters != null && ArgumentOptions.Parameters.Length > 0) ? ArgumentOptions.Parameters[0] : null).Result;
                        break;

                    case "Average":
                        // Sample Input: "1 50 10"
                        if (ArgumentOptions.Parameters == null || ArgumentOptions.Parameters.Length != 3)
                        {
                            throw new ArgumentException("parameters");
                        }

                        int[] input = ArgumentOptions.Parameters.Select(p => int.Parse(p)).ToArray();
                        instance = taskHubClient.CreateOrchestrationInstanceAsync(typeof(AverageCalculatorOrchestration), instanceId, input).Result;
                        break;

                    case "ErrorHandling":
                        instance = taskHubClient.CreateOrchestrationInstanceAsync(typeof(ErrorHandlingOrchestration), instanceId, null).Result;
                        break;

                    case "SumOfSquares":
                        instance = taskHubClient.CreateOrchestrationInstanceAsync(
                            "SumOfSquaresOrchestration",
                            "V1",
                            instanceId,
                            File.ReadAllText("SumofSquares\\BagOfNumbers.json"),
                            new Dictionary <string, string>(1)
                        {
                            { "Category", "testing" }
                        }).Result;
                        break;

                    case "Signal":
                        instance = taskHubClient.CreateOrchestrationInstanceAsync(typeof(SignalOrchestration), instanceId, null).Result;
                        break;

                    case "SignalAndRaise":
                        if (ArgumentOptions.Parameters == null || ArgumentOptions.Parameters.Length != 1)
                        {
                            throw new ArgumentException("parameters");
                        }

                        instance = taskHubClient.CreateOrchestrationInstanceWithRaisedEventAsync(typeof(SignalOrchestration), instanceId, null, ArgumentOptions.Signal, ArgumentOptions.Parameters[0]).Result;
                        break;

                    case "Replat":
                        instance = taskHubClient.CreateOrchestrationInstanceAsync(typeof(MigrateOrchestration), instanceId,
                                                                                  new MigrateOrchestrationData {
                            SubscriptionId = "03a1cd39-47ac-4a57-9ff5-a2c2a2a76088", IsDisabled = false
                        }).Result;
                        break;

                    default:
                        throw new Exception("Unsupported Orchestration Name: " + ArgumentOptions.StartInstance);
                    }

                    Console.WriteLine("Workflow Instance Started: " + instance);
                }
                else if (!string.IsNullOrWhiteSpace(ArgumentOptions.Signal))
                {
                    Console.WriteLine("Run RaiseEvent");

                    if (string.IsNullOrWhiteSpace(ArgumentOptions.InstanceId))
                    {
                        throw new ArgumentException("instanceId");
                    }

                    if (ArgumentOptions.Parameters == null || ArgumentOptions.Parameters.Length != 1)
                    {
                        throw new ArgumentException("parameters");
                    }

                    string instanceId = ArgumentOptions.InstanceId;
                    instance = new OrchestrationInstance {
                        InstanceId = instanceId
                    };
                    taskHubClient.RaiseEventAsync(instance, ArgumentOptions.Signal, ArgumentOptions.Parameters[0]).Wait();

                    Console.WriteLine("Press any key to quit.");
                    Console.ReadLine();
                }

                if (!ArgumentOptions.SkipWorker)
                {
                    try
                    {
                        taskHub.AddTaskOrchestrations(
                            typeof(GreetingsOrchestration),
                            typeof(GreetingsOrchestration2),
                            typeof(CronOrchestration),
                            typeof(AverageCalculatorOrchestration),
                            typeof(ErrorHandlingOrchestration),
                            typeof(SignalOrchestration),
                            typeof(MigrateOrchestration),
                            typeof(SumOfSquaresOrchestration)
                            );

                        taskHub.AddTaskOrchestrations(
                            new NameValueObjectCreator <TaskOrchestration>("SumOfSquaresOrchestration", "V1", typeof(SumOfSquaresOrchestration)));

                        taskHub.AddTaskActivities(
                            new GetUserTask(),
                            new SendGreetingTask(),
                            new CronTask(),
                            new ComputeSumTask(),
                            new GoodTask(),
                            new BadTask(),
                            new CleanupTask(),
                            new EmailTask(),
                            new SumOfSquaresTask()
                            );

                        taskHub.AddTaskActivitiesFromInterface <IManagementSqlOrchestrationTasks>(new ManagementSqlOrchestrationTasks());
                        taskHub.AddTaskActivitiesFromInterface <IMigrationTasks>(new MigrationTasks());

                        taskHub.StartAsync().Wait();

                        Console.WriteLine("Waiting up to 60 seconds for completion.");

                        OrchestrationState taskResult = taskHubClient.WaitForOrchestrationAsync(instance, TimeSpan.FromSeconds(60), CancellationToken.None).Result;
                        Console.WriteLine($"Task done: {taskResult?.OrchestrationStatus}");

                        Console.WriteLine("Press any key to quit.");
                        Console.ReadLine();

                        taskHub.StopAsync(true).Wait();
                    }
                    catch (Exception e)
                    {
                        // silently eat any unhandled exceptions.
                        Console.WriteLine($"worker exception: {e}");
                    }
                }
                else
                {
                    Console.WriteLine("Skip Worker");
                }
            }
        }
Exemplo n.º 38
0
 /// <summary>
 /// Creates an event listener that logs using a <see cref="ConsoleSink"/>.
 /// </summary>
 /// <param name="formatter">The formatter.</param>
 /// <param name="colorMapper">The color mapper instance.</param>
 /// <returns>An event listener that uses <see cref="ConsoleSink"/> to display events.</returns>
 public static EventListener CreateListener(IEventTextFormatter formatter = null, IConsoleColorMapper colorMapper = null)
 {
     var listener = new ObservableEventListener();
     listener.LogToConsole(formatter, colorMapper);
     return listener;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="RedisCacheManagerTests"/> class.
 /// </summary>
 public RedisCacheManagerTests()
 {
     activityEventListener = new ObservableEventListener();
     activityEventListener.EnableEvents(ActivityLoggingEventSource.Log, EventLevel.LogAlways);
     activityEventListener.LogToConsole();
 }
Exemplo n.º 40
0
        //[Ignore("Depends on NorthWind database on local SQL Server.")]
        public void TestProfileAndExportDatabaseTable() {

            var listener = new ObservableEventListener();
            listener.EnableEvents(TflEventSource.Log, EventLevel.Verbose);
            var subscription = listener.LogToConsole(new LegacyLogFormatter());

            var result = new Profiler().Profile("localhost.NorthWind.dbo.Customers");
            new ProfileExporter().Export(result);

            subscription.Dispose();
            listener.DisableEvents(TflEventSource.Log);
            listener.Dispose();

            Assert.NotNull(result);
        }
Exemplo n.º 41
0
    static void SimpleEventSourceWithXMLFormatter()
    {
      // Set up and enable the event listener - typically done when the application starts
      var listener = new ObservableEventListener();
      listener.LogToConsole(new XmlEventTextFormatter(EventTextFormatting.Indented));
      listener.EnableEvents(MyCompanyEventSource.Log, EventLevel.LogAlways, Keywords.All);

      // Log some messages
      MyCompanyEventSource.Log.Startup();
      MyCompanyEventSource.Log.Failure("Couldn't connect to server.");
      Console.WriteLine("Written two log messages.\nUsing a console listener with an XML formatter to capture them.");

      // Disable the event listener - typically done when the application terminates
      listener.DisableEvents(MyCompanyEventSource.Log);
      listener.Dispose();
    }
Exemplo n.º 42
0
    static void SimpleEventSourceWithColorMapper()
    {
      // Set up and enable the event listener - typically done when the application starts
      var listener = new ObservableEventListener();
      listener.LogToConsole(new JsonEventTextFormatter(EventTextFormatting.Indented), new MyCustomColorMapper());
      listener.EnableEvents(MyCompanyEventSource.Log, EventLevel.LogAlways, Keywords.All);

      // Log some messages
      MyCompanyEventSource.Log.Startup();
      MyCompanyEventSource.Log.PageStop(99);
      Console.WriteLine("Written two log messages.\nUsing a console listener with a JSON formatter to capture them.");

      // Disable the event listener - typically done when the application terminates
      listener.DisableEvents(MyCompanyEventSource.Log);
      listener.Dispose();
    }
Exemplo n.º 43
0
    static void MultipleEventListenersLevel()
    {
      // Set up and enable the event listeners - typically done when the application starts
      var listener1 = new ObservableEventListener();
      var listener2 = new ObservableEventListener();
      listener1.EnableEvents(MyCompanyEventSource.Log, EventLevel.Error, Keywords.All);
      listener2.EnableEvents(MyCompanyEventSource.Log, EventLevel.LogAlways, Keywords.All);
      listener1.LogToConsole();

      var subscription = listener2.LogToFlatFile(@"C:\Temp\DemoSemanticLogging.log", new EventTextFormatter("===================", "==================="));

      // Log some messages
      MyCompanyEventSource.Log.Startup();
      MyCompanyEventSource.Log.Failure("Couldn't connect to server.");
      Console.WriteLine("Written two log messages.\nUsing a basic console listener and a Flat File listener to capture them.");
      Console.WriteLine("Only the critical message appears in the console, both appear in: \nC:\\Temp\\DemoSemanticLogging.log.\n");
      
      // Flush the sink
      subscription.Sink.FlushAsync().Wait();

      // Disable the event listener - typically done when the application terminates
      listener1.DisableEvents(MyCompanyEventSource.Log);
      listener2.DisableEvents(MyCompanyEventSource.Log);

      listener1.Dispose();
      listener2.Dispose();
    }
Exemplo n.º 44
0
    static void MultipleEventListenersKeywords()
    {
      var listener1 = new ObservableEventListener();
      var listener2 = new ObservableEventListener();
      listener1.EnableEvents(MyCompanyEventSource.Log, EventLevel.LogAlways, MyCompanyEventSource.Keywords.Perf | MyCompanyEventSource.Keywords.Diagnostic);
      listener2.EnableEvents(MyCompanyEventSource.Log, EventLevel.LogAlways, Keywords.All);
      // Set up and enable the event listeners -  typically done when the application starts
      listener1.LogToConsole();
      // The SinkSubscription is used later to flush the buffer
      var subscription = listener2.LogToSqlDatabase("Demo Semantic Logging Instance", connectionString);

      // Log some messages
      MyCompanyEventSource.Log.PageStart(23, "http://mysite/demopage");
      MyCompanyEventSource.Log.Startup();
      MyCompanyEventSource.Log.Failure("Couldn't connect to server.");
      Console.WriteLine("Written three log messages.\nUsing a basic console listener and a SQL listener to capture them.");
      Console.WriteLine("Only the messages with the Perf or Diagnostic keywords appears in the console, \nall three appear in the SQL Database:\n");

      // Disable the event listener - typically done when the application terminates
      listener1.DisableEvents(MyCompanyEventSource.Log);
      listener2.DisableEvents(MyCompanyEventSource.Log);

      // Manually flush the buffer so you can see what's in the database
      subscription.Sink.FlushAsync().Wait();
      ShowContentsOfSqlDatabaseTable();

      listener1.Dispose();
      listener2.Dispose();
    }