Esempio n. 1
0
        public string RunCommand(string cmdKey, object cmd, string[] tags)
        {
            var broker = (_context.Broker ?? Implementations.Broker.Value);

            var log = new ZazLogToStringAdapter();
            var ctx = new CommandHandlingContext(tags, Thread.CurrentPrincipal, log);
            try
            {
                broker.Handle(cmd, ctx).Wait();
            }
            catch (AggregateException ex)
            {
                foreach (var child in ex.Flatten().InnerExceptions)
                {
                    log.Error(child.Message);
                }
            }

            var msg = new StringBuilder("Command " + cmdKey + " accepted.");

            if (log.HasSomething())
            {
                msg.AppendLine();
                msg.Append(log);
            }

            return msg.ToString();
        }
Esempio n. 2
0
        public Task Handle(dynamic cmd, CommandHandlingContext ctx)
        {
            var cmdType = cmd.GetType();
            var handlerType = _handlersAssembly
                .GetTypes()
                .Where(x => x.Name.EndsWith("Handler")
                            && x.GetMethod("Handle") != null
                            && x.GetMethod("Handle")
                                   .GetParameters()[0].ParameterType
                                   .IsAssignableFrom(cmdType))
                .FirstOrDefault();

            if (handlerType == null)
            {
                throw new InvalidOperationException("Zaz failed to find appropriate handler");
            }

            dynamic handler = Activator.CreateInstance(handlerType);

            var result = handler.Handle(cmd);

            if (result is Task)
            {
                return (Task) result;
            }

            return Task.Factory.StartNew(() => {});
        }
Esempio n. 3
0
 public Task Handle(object cmd, CommandHandlingContext ctx)
 {
     HandledCommands.Add(cmd);
     return Task.Factory.StartNew(() =>
                                      {
                                          Console.WriteLine("Do nothing!");
                                      });
 }
Esempio n. 4
0
 public Task Handle(dynamic cmd, CommandHandlingContext ctx)
 {
     return Task.Factory.StartNew(() =>
                               {
                                   ctx.Log.Info("Hello word! #1");
                                   Thread.Sleep(1000);
                                   ctx.Log.Info("Hello word! #2");
                                   Thread.Sleep(1000);
                                   ctx.Log.Info("Hello word! #3");
                                   Thread.Sleep(1000);
                                   ctx.Log.Info("Hello word! #4");
                               });
 }
Esempio n. 5
0
        public Task Handle(object cmd, CommandHandlingContext ctx)
        {
            if (cmd.GetType() == typeof(LongFoo1))
            {
                return Task.Factory.StartNew(() =>
                {
                    Thread.Sleep(300);
                    ctx.Trace.Info("Hello word! #1");
                    Thread.Sleep(1000);
                    ctx.Trace.Info("Hello word! #2");
                    Thread.Sleep(1000);
                    ctx.Trace.Error("Hello word! #3");
                    Thread.Sleep(1000);
                    ctx.Trace.Info("Hello word! #4");
                });
            }

            throw new InvalidOperationException("Dumb command handler cannot find how to handle " + cmd);
        }
Esempio n. 6
0
        public HttpResponseMessage RunCommand(string cmdKey, object cmd, string[] tags)
        {
            var broker = (_context.Broker ?? Implementations.Broker);

            var ctx = new CommandHandlingContext(tags ?? new string[0], Thread.CurrentPrincipal);
            var trace = new List<TraceEntry>();
            using (ctx.Trace.Subscribe(trace.Add))
            {
                try
                {
                    broker.Handle(cmd, ctx).Wait();
                }
                catch (AggregateException ex)
                {
                    foreach (var child in ex.Flatten().InnerExceptions)
                    {
                        trace.Error(child.Message);
                    }
                }
            }

            var msg = new StringBuilder("Command " + cmdKey + " accepted.");

            if (trace.Count > 0)
            {
                msg.AppendLine();
                msg.AppendLine("Trace: ");
                foreach (var traceEntry in trace)
                {
                    msg.AppendLine("[" + traceEntry.Serverity + "]" + traceEntry.Message);
                }
            }

            return new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.Accepted,
                Content = new StringContent(msg.ToString())
            };
        }
        public void Given_command_server_runnig()
        {
            var serverConfiguration = new ServerConfiguration
            {
                Registry = new FooCommandRegistry(),
                Broker = new DelegatingCommandBroker((cmd, ctx) =>
                {
                    _postedCommand = cmd;
                    _ctx = ctx;

                    _principal = Thread.CurrentPrincipal;

                    return Task.Factory.StartNew(() => { });
                }),
                ConfigureHttp = http => http.SetupBasicAuthentication("supr", "booper", "")
            };

            var config = ZazServer.ConfigureAsSelfHosted(URL, serverConfiguration);
            _host = new HttpSelfHostServer(config);

            //SimpleBasicAuthenticationHandler.Configure(config, cred => cred.UserName == "supr" && cred.Password == "booper");

            using (new HttpSelfHostServer(config))
            {
                _host.OpenAsync().Wait();

                // Client side
                var configuration = new ZazConfiguration();
                configuration.SetupSimpleBasicAuthentication("supr", "booper");

                var client = new ZazClient(URL, configuration);

                client.PostAsync(new FooCommand
                {
                    Message = "Hello world"
                }).Wait();
            }
        }
        public void Given_command_server_runnig()
        {
            var config = ZazServer.ConfigureAsSelfHosted(URL, new ServerConfiguration
            {
                Registry = new FooCommandRegistry(),
                Broker = new DelegatingCommandBroker((cmd, ctx) =>
                {
                    _postedCommand = cmd;
                    _ctx = ctx;

                    return Task.Factory.StartNew(() =>
                    {
                        ctx.Log.Info("Hello word! #1");
                        Thread.Sleep(TimeSpan.FromSeconds(1));

                        ctx.Log.Info("Hello word! #2");
                        Thread.Sleep(TimeSpan.FromSeconds(1));

                        ctx.Log.Info("Hello word! #3");
                        Thread.Sleep(TimeSpan.FromSeconds(1));

                        ctx.Log.Info("Hello word! #4");
                    });
                })
            });

            using (var host = new HttpSelfHostServer(config))
            {
                host.OpenAsync().Wait();

                var bus = new ZazClient(URL);
                bus.PostAsync(new FooCommand
                {
                    Message = "Heeeeelllllloooooo!"
                }).Wait();
            }
        }
        public void Given_command_server_runnig()
        {
            var instance = new CommandsService(new ServerContext
            (
                registry: new FooCommandRegistry(),
                broker: new DelegatingCommandBroker((cmd, ctx) =>
                {
                    _postedCommand = cmd;
                    _ctx = ctx;

                    return Task.Factory.StartNew(() => {});
                })
            ));
            var config = ConfigurationHelper.CreateConfiguration(instance);

            SimpleBasicAuthenticationHandler.Configure(config, cred => cred.UserName == "supr" && cred.Password == "booper");

            _host = new HttpServiceHost(typeof(CommandsService), config, new Uri(URL));
            _host.Open();

            // Client side

            var bus = new CommandBus(URL, new Client.Avanced.ZazConfiguration
            {
                ConfigureHttp = h =>
                {
                    h.Credentials = new NetworkCredential("supr", "booper");
                }
            });
            bus.Post(new FooCommand
            {
                Message = "Hello world"
            });

            // Close host
            _host.Close();
        }
 public Task Handle(object cmd, CommandHandlingContext ctx)
 {
     return _delegate(cmd, ctx);
 }
Esempio n. 11
0
        public PostScheduledCommandResponse PostScheduled(PostCommandRequest req)
        {
            var cmdKey = req.Key;
            var cmd = _resolver.ResoveCommand(req, cmdKey);

            var broker = (_context.Broker ?? Implementations.Broker);
            var stateProvider = (_context.StateProvider ?? Implementations.StateProvider);

            var id = Guid.NewGuid().ToString("n");
            stateProvider.Start(id, DateTime.UtcNow);
            var ctx = new CommandHandlingContext(req.Tags ?? new string[0], Thread.CurrentPrincipal);
            var traceSubscription = ctx.Trace
                .Subscribe(e => stateProvider.WriteTrace(id, DateTime.UtcNow, e.Serverity, e.Message, e.Tags));

            broker.Handle(cmd, ctx)
                .ContinueWith(t =>
                                  {
                                      traceSubscription.Dispose();
                                      stateProvider.CompleteSuccess(id, DateTime.UtcNow);
                                  });

            return new PostScheduledCommandResponse
                       {
                           Id = id
                       };
        }
Esempio n. 12
0
 public Task Handle(dynamic cmd, CommandHandlingContext ctx)
 {
     CommandsPosted.Add(cmd);
     return Task.Factory.StartNew(() => { });
 }
Esempio n. 13
0
        private Task<CommandExecutionResult> Execute(object cmd, string[] tags, IPrincipal principal, IObserver<LogEntry> log)
        {
            var broker = _context.Broker;

            var ctx = new CommandHandlingContext(tags, principal, log);

            return broker.Handle(cmd, ctx)
                .ContinueWith(t =>
                {
                    if (t.IsFaulted)
                    {
                        if (t.Exception != null)
                        {
                            var ex = t.Exception.Flatten();
                            if (ex.InnerExceptions.Count == 0)
                            {
                                log.Error(ex.GetBaseException().ToString());
                            }
                            else
                            {
                                foreach (var child in ex.InnerExceptions)
                                {
                                    log.Error(child.ToString());
                                }
                            }
                            return CommandExecutionResult.Failure(ex.GetBaseException().Message);
                        }
                        else
                        {
                            return CommandExecutionResult.Failure();
                        }
                    }
                    // TODO: Handle cancelled
                    return CommandExecutionResult.Success();
                });
        }