Ejemplo n.º 1
0
        static void Main()
        {
            Func <IFoo> getFoo              = () => new DummyFoo();
            var         module              = new CommandModule(getFoo);
            var         resolver            = new CommandHandlerResolver(module);
            var         commandMediaTypeMap = new CommandMediaTypeMap(new CommandMediaTypeWithQualifierVersionFormatter())
            {
                // Use a string to decouple command name from the command clr type. This will ensure
                // refactoring, i.e. moving CommandThatHasASyncHandler or renaming it, won't change your http API.
                { "CommandThatHasASyncHandler", typeof(CommandThatHasASyncHandler) },

                // Can use typeof().Name if you are not concerned with backwards compat or versioning.
                { typeof(CommandThatHasAnAsyncHandler).Name, typeof(CommandThatHasAnAsyncHandler) },
            };
            var settings = new CommandHandlingSettings(resolver, commandMediaTypeMap);
            var commandHandlingMiddleware = CommandHandlingMiddleware.HandleCommands(settings);

            // 5. Add the middleware to your owin pipeline
            using (WebApp.Start("http://localhost:8080",
                                app =>
            {
                app.Use(commandHandlingMiddleware);
            }))
            {
                Console.WriteLine("Press any key");
            }
        }
Ejemplo n.º 2
0
        private static void Main()
        {
            var resolver = new CommandHandlerResolver(new CommandModule());

            var commandMediaTypeMap = new CommandMediaTypeMap(new CommandMediaTypeWithQualifierVersionFormatter())
            {
                { typeof(CommandThatIsAccepted).Name, typeof(CommandThatIsAccepted) },
                { typeof(CommandThatThrowsProblemDetailsException).Name, typeof(CommandThatThrowsProblemDetailsException) }
            };

            var settings = new CommandHandlingSettings(resolver, commandMediaTypeMap);

            var commandHandlingMiddleware = CommandHandlingMiddleware.HandleCommands(settings);

            using (WebApp.Start("http://*****:*****@"..\..\wwwroot")
                });
                app.UseStaticFiles(new StaticFileOptions
                {
                    RequestPath = new PathString("/cedarjs"),
                    FileSystem = new PhysicalFileSystem(@"..\..\..\Cedar.CommandHandling.Http.Js")
                });
                app.Map("/test/commands", commandsApp => commandsApp.Use(commandHandlingMiddleware));
            }))
            {
                Process.Start("http://localhost:8080/index.html");
                Console.WriteLine("Press any key to exit");
                Console.ReadKey();
            }
        }
Ejemplo n.º 3
0
        public async Task Should_invoke_predispatch_hook()
        {
            var          module           = new CommandHandlerModule();
            string       correlationId    = null;
            const string correlationIdKey = "CorrelationId";

            module.For <Command>().Handle((commandMessage, __) =>
            {
                correlationId = commandMessage.Metadata.Get <string>(correlationIdKey);
                return(Task.FromResult(0));
            });
            var settings = new CommandHandlingSettings(new CommandHandlerResolver(module))
            {
                OnPredispatch = (metadata, headers) =>
                {
                    var correlationIdHeader = headers.SingleOrDefault(kvp => kvp.Key == correlationIdKey);
                    if (correlationIdHeader.Value != null)
                    {
                        metadata[correlationIdKey] = correlationIdHeader.Value.SingleOrDefault();
                    }
                }
            };

            var midFunc = CommandHandlingMiddleware.HandleCommands(settings);

            using (var client = midFunc.CreateEmbeddedClient())
            {
                await client.PutCommand(new Command(), Guid.NewGuid(), customizeRequest : request =>
                {
                    request.Headers.Add(correlationIdKey, "cor-1");
                });

                correlationId.Should().Be("cor-1");
            }
        }
Ejemplo n.º 4
0
        private App()
        {
            var settings = new DefaultHandlerSettings(
                new HandlerModule(),
                new DefaultRequestTypeResolver("cedar", Enumerable.Empty <Type>()));

            var commitDispatcherFailed = new TaskCompletionSource <Exception>();

            //MidFunc blah = CommandHandlingMiddleware.HandleCommands(settings);
            //_middleware = CreateGate(commitDispatcherFailed.Task)
            _middleware  = CommandHandlingMiddleware.HandleCommands(settings);
            _storeEvents = Wireup.Init().UsingInMemoryPersistence().Build();
            var eventStoreClient = new EventStoreClient(_storeEvents.Advanced);

            _durableCommitDispatcher = new DurableCommitDispatcher(
                eventStoreClient,
                new InMemoryCheckpointRepository(),
                new HandlerModule(),
                TransientExceptionRetryPolicy.Indefinite(TimeSpan.FromMilliseconds(500)));

            _durableCommitDispatcher.ProjectedCommits.Subscribe(
                _ => { },
                commitDispatcherFailed.SetResult);

            _durableCommitDispatcher.Start().Wait();
        }
Ejemplo n.º 5
0
        private static void Main()
        {
            var resolver = new CommandHandlerResolver(new CommandModule());
            var settings = new CommandHandlingSettings(resolver);
            var commandHandlingMiddleware = CommandHandlingMiddleware.HandleCommands(settings);

            using (WebApp.Start("http://*****:*****@"..\..\wwwroot")
                });
                app.UseStaticFiles(new StaticFileOptions
                {
                    RequestPath = new PathString("/cedarjs"),
                    FileSystem = new PhysicalFileSystem(@"..\..\..\Cedar.HttpCommandHandling.Js")
                });
                app.Map("/test/commands", commandsApp => commandsApp.Use(commandHandlingMiddleware));
            }))
            {
                Process.Start("http://localhost:8080/index.html");
                Console.WriteLine("Press any key to exit");
                Console.ReadKey();
            }
        }
Ejemplo n.º 6
0
        public async Task Example_exception_handling()
        {
            var resolver = new CommandHandlerResolver(new CommandModule());
            var settings = new CommandHandlingSettings(resolver)
            {
                // 10. Specify the exception -> HttpProblemDetails mapper here
                MapProblemDetailsFromException = MapExceptionToProblemDetails
            };
            var middleware = CommandHandlingMiddleware.HandleCommands(settings);

            using (HttpClient client = middleware.CreateEmbeddedClient())
            {
                // 11. Handling standard exceptions.
                try
                {
                    await client.PutCommand(new CommandThatThrowsStandardException(), Guid.NewGuid());
                }
                catch (HttpRequestException ex)
                {
                    Console.WriteLine(ex.Message);
                }

                // 12. Handling explicit HttpProblemDetailsExceptions
                try
                {
                    await client.PutCommand(new CommandThatThrowsProblemDetailsException(), Guid.NewGuid());
                }
                catch (HttpProblemDetailsException <HttpProblemDetails> ex)
                {
                    Console.WriteLine(ex.ProblemDetails.Detail);
                    Console.WriteLine(ex.ProblemDetails.Status);
                }

                // 13. Handling mapped exceptions, same as #6
                try
                {
                    await client.PutCommand(new CommandThatThrowsMappedException(), Guid.NewGuid());
                }
                catch (HttpProblemDetailsException <HttpProblemDetails> ex)
                {
                    Console.WriteLine(ex.ProblemDetails.Detail);
                    Console.WriteLine(ex.ProblemDetails.Status);
                }

                // 14. Handling custom HttpProblemDetailExceptions
                try
                {
                    await client.PutCommand(new CommandThatThrowsCustomProblemDetailsException(), Guid.NewGuid());
                }
                catch (CustomHttpProblemDetailsException ex)
                {
                    Console.WriteLine(ex.ProblemDetails.Detail);
                    Console.WriteLine(ex.ProblemDetails.Status);
                    Console.WriteLine(ex.ProblemDetails.Name);
                }
            }
        }
        public CommandHandlingFixture()
        {
            var module                  = CreateCommandHandlerModule();
            var handlerResolver         = new CommandHandlerResolver(module);
            var commandHandlingSettings = new CommandHandlingSettings(handlerResolver)
            {
                MapProblemDetailsFromException = CreateProblemDetails
            };

            _midFunc = CommandHandlingMiddleware.HandleCommands(commandHandlingSettings);
        }
Ejemplo n.º 8
0
        public void Configuration(IAppBuilder app)
        {
            app.Map("/api/commands", builder =>
            {
                var moviesCommandModule    = TinyIoCContainer.Current.Resolve <MoviesCommandModule>();
                var directorsCommandModule = TinyIoCContainer.Current.Resolve <DirectorsCommandModule>();
                var resolver = new CommandHandlerResolver(moviesCommandModule, directorsCommandModule);
                var settings = new CommandHandlingSettings(resolver);

                var commandHandlingMiddleware = CommandHandlingMiddleware.HandleCommands(settings);
                builder.Use(commandHandlingMiddleware);
            });
        }
Ejemplo n.º 9
0
        public CommandHandlingFixture()
        {
            const string vendor = "vendor";

            var handlerModule = new TestHandlerModule();

            var commandTypeFromContentTypeResolver = new DefaultRequestTypeResolver(
                vendor,
                handlerModule);
            var options = new DefaultHandlerSettings(handlerModule, commandTypeFromContentTypeResolver);

            _midFunc = CommandHandlingMiddleware.HandleCommands(options);
            _messageExecutionSettings = new CommandExecutionSettings(vendor);
        }
Ejemplo n.º 10
0
        public async Task Can_invoke_command_over_http()
        {
            // 1. Setup the middlware
            var resolver   = new CommandHandlerResolver(new CommandModule());
            var settings   = new CommandHandlingSettings(resolver);
            var middleware = CommandHandlingMiddleware.HandleCommands(settings);

            // 2. Create an embedded HttpClient. This allows invoking of the
            //    HttpPipeline in-memory without a server / listener.
            using (HttpClient client = middleware.CreateEmbeddedClient())
            {
                // 3. This is as close as you can get to simulating a real client call
                //    without needing real server.
                //    Can use this to do acceptance testing also.
                await client.PutCommand(new Command(), Guid.NewGuid());
            }
        }
Ejemplo n.º 11
0
        static void Main()
        {
            Func <IFoo> getFoo   = () => new DummyFoo();
            var         resolver = new CommandHandlerResolver(new CommandModule(getFoo));
            var         settings = new CommandHandlingSettings(resolver);
            var         commandHandlingMiddleware = CommandHandlingMiddleware.HandleCommands(settings);

            // 5. Add the middleware to your owin pipeline
            using (WebApp.Start("http://localhost:8080",
                                app =>
            {
                app.Use(commandHandlingMiddleware);
            }))
            {
                Console.WriteLine("Press any key");
            }
        }
Ejemplo n.º 12
0
        public CommandHandlingFixture()
        {
            var module          = CreateCommandHandlerModule();
            var handlerResolver = new CommandHandlerResolver(module);

            CommandMediaTypeMap = new CommandMediaTypeMap(new CommandMediaTypeWithQualifierVersionFormatter())
            {
                { typeof(Command).Name.ToLowerInvariant(), typeof(Command) },
                { typeof(CommandThatThrowsStandardException).Name.ToLowerInvariant(), typeof(CommandThatThrowsStandardException) },
                { typeof(CommandThatThrowsProblemDetailsException).Name.ToLowerInvariant(), typeof(CommandThatThrowsProblemDetailsException) },
                { typeof(CommandThatThrowsMappedException).Name.ToLowerInvariant(), typeof(CommandThatThrowsMappedException) },
                { typeof(CommandThatThrowsCustomProblemDetailsException).Name.ToLowerInvariant(), typeof(CommandThatThrowsCustomProblemDetailsException) }
            };
            var commandHandlingSettings = new CommandHandlingSettings(handlerResolver, CommandMediaTypeMap)
            {
                MapProblemDetailsFromException = CreateProblemDetails
            };

            _midFunc = CommandHandlingMiddleware.HandleCommands(commandHandlingSettings);
        }
Ejemplo n.º 13
0
        public async Task Can_invoke_command_over_http()
        {
            var resolver            = new CommandHandlerResolver(new CommandModule());
            var commandMediaTypeMap = new CommandMediaTypeMap(new CommandMediaTypeWithQualifierVersionFormatter())
            {
                { typeof(Command).FullName.ToLower(), typeof(Command) }
            };

            // 1. Create the serializer
            var jsonSerializer = new JsonSerializer();
            var settings       = new CommandHandlingSettings(resolver, commandMediaTypeMap)
            {
                // 2. Customize the deserialization
                DeserializeCommand = (commandReader, type) =>
                {
                    using (var reader = new JsonTextReader(commandReader))
                    {
                        return(jsonSerializer.Deserialize(reader, type));
                    }
                }
            };
            var middleware = CommandHandlingMiddleware.HandleCommands(settings);

            // 3. Customize the serialization
            SerializeCommand serializeCommand = (writer, command) =>
            {
                jsonSerializer.Serialize(writer, command);
            };

            // 3. Create an embedded HttpClient. This allows invoking of the
            //    HttpPipeline in-memory without a server / listener.
            using (HttpClient client = middleware.CreateEmbeddedClient())
            {
                // 3. This is as close as you can get to simulating a real client call
                //    without needing real server.
                //    Can use this to do acceptance testing also.
                await client.PutCommand(new Command(), Guid.NewGuid(), commandMediaTypeMap, serializeCommand : serializeCommand);
            }
        }
Ejemplo n.º 14
0
        public ProcessManagerHandlerTests()
        {
            TestLogger.Configure();

            var source = new TaskCompletionSource <bool>();

            _nodeStarted = source.Task;

            var notListening = new IPEndPoint(IPAddress.None, 0);

            _node = EmbeddedVNodeBuilder.AsSingleNode()
                    .WithInternalTcpOn(notListening)
                    .WithExternalTcpOn(notListening)
                    .WithInternalHttpOn(notListening)
                    .WithExternalHttpOn(notListening);

            _node.NodeStatusChanged += (_, e) =>
            {
                if (e.NewVNodeState != VNodeState.Master)
                {
                    return;
                }

                source.SetResult(true);
            };

            _node.Start();

            _connection = EmbeddedEventStoreConnection.Create(_node);

            _commands = new List <object>();

            _serializer = new DefaultGetEventStoreJsonSerializer();

            var commandHandlerModule = new CommandHandlerModule();

            commandHandlerModule.For <ShipOrder>()
            .Handle((message, _) =>
            {
                _commands.Add(message.Command);
                return(Task.FromResult(0));
            });
            commandHandlerModule.For <BillCustomer>()
            .Handle((message, _) =>
            {
                _commands.Add(message.Command);
                return(Task.FromResult(0));
            });

            var resolver = new CommandHandlerResolver(commandHandlerModule);
            var commandHandlingMiddleware =
                CommandHandlingMiddleware.HandleCommands(new CommandHandlingSettings(resolver));
            var embeddedClient = commandHandlingMiddleware.CreateEmbeddedClient();

            var processHandler = ProcessHandler.For <OrderFulfillment, CompareablePosition>(
                (command, token) => embeddedClient.PutCommand(command, Guid.NewGuid()),
                new EventStoreClientProcessManagerCheckpointRepository(_connection, _serializer))
                                 .CorrelateBy <OrderPlaced>(e => e.DomainEvent.OrderId.ToString())
                                 .CorrelateBy <OrderShipped>(e => e.DomainEvent.OrderId.ToString())
                                 .CorrelateBy <BillingSucceeded>(e => e.DomainEvent.OrderId.ToString())
                                 .CorrelateBy <BillingFailed>(e => e.DomainEvent.OrderId.ToString());


            _dispatcher = new ResolvedEventDispatcher(_connection,
                                                      new DefaultGetEventStoreJsonSerializer(),
                                                      new InMemoryCheckpointRepository(),
                                                      processHandler.BuildHandlerResolver(),
                                                      () => { });

            _orderId       = Guid.NewGuid();
            _streamId      = ("orders-" + _orderId.ToString("n")).FormatStreamIdWithBucket();
            _correlationId = _orderId.ToString();
        }