private ExampleCommand GetExample() { ExampleCommand example = new ExampleCommand(); if (IsHelpRequested(example)) { return(example); } bool metUnknownOption = false; while (!metUnknownOption && Eat() is string option) { switch (option) { case "-a": case "--all": if (example.ExampleName != null) { throw logger.Error(new OptionException(option, "Cannot specify example project name when requesting all examples")); } example.DownloadAll = GetBoolean(); break; default: metUnknownOption = example.ExampleName != null; if (!metUnknownOption) { example.ExampleName = arg; } break; } } return(example); }
public void Post([FromBody] ExampleCommand value) { value.Id = Guid.NewGuid().ToString(); Aggregate exampleDomain = new ExampleAggregate(); CommandHandler.ActivateCommand(value, exampleDomain); }
public override void Specify() { given("exactly one command is loaded", () => { var exampleCommand = new ExampleCommand(); var commands = new ConsoleCommand[] { exampleCommand }; when("no parameters are specified", () => { var output = new StringWriter(); var exitCode = arrange(() => ConsoleCommandDispatcher.DispatchCommand(commands, new string[0], output)); then_the_command_runs_without_tracing_parameter_information(output, exitCode); then("the command's property is not set", () => { expect(() => exampleCommand.Foo == null); }); }); when("the only parameter specified is the command", () => { var output = new StringWriter(); var exitCode = arrange(() => ConsoleCommandDispatcher.DispatchCommand(commands, new[] { "Example" }, output)); then_the_command_runs_without_tracing_parameter_information(output, exitCode); then("the command's property is not set", () => { expect(() => exampleCommand.Foo == null); }); }); when("the only parameter specified is not the command", () => { var output = new StringWriter(); var exitCode = arrange(() => ConsoleCommandDispatcher.DispatchCommand(commands, new[] { "/f=bar" }, output)); then_the_command_runs_without_tracing_parameter_information(output, exitCode); then("the command's property is set", () => { expect(() => exampleCommand.Foo == "bar"); }); }); when("both the command and an extra parameter are specified", () => { var output = new StringWriter(); var exitCode = arrange(() => ConsoleCommandDispatcher.DispatchCommand(commands, new[] { "Example", "/f=bar" }, output)); then_the_command_runs_without_tracing_parameter_information(output, exitCode); then("the command's property is set", () => { expect(() => exampleCommand.Foo == "bar"); }); }); }); }
public async Task HandlerCompilation() { var dispatcher = new MessageDispatcher(new Container(), Substitute.For <IBotService>()); dispatcher.Register("example", typeof(ExampleCommand)); var command = new ExampleCommand(); var message = new Message(); var node = dispatcher.RegisteredCommands["example"]; var response = Assert.IsType <MessageResponse>(node.Handler(command, message, Array.Empty <string>())); Assert.Equal("First", response.Content); node = node.Next !; Assert.NotNull(node); response = Assert.IsType <MessageResponse>(node.Handler(command, message, new[] { "arg" })); Assert.Equal("Arg: arg", response.Content); node = node.Next !; Assert.NotNull(node); response = await Assert.IsType <Task <MessageResponse> >(node.Handler(command, message, Array.Empty <string>())); Assert.Equal("fallback", response.Content); Assert.Null(node.Next); }
public async Task SendCommandToTransport() { const string TargetEndpoint = "Target"; var routes = new Collection <CommandRoute> { new CommandRoute(typeof(ExampleCommand), TargetEndpoint) }; var publisher = new MessagePublisher( mockPipeline.Object, FullNameTypeMap.Instance, routes); var command = new ExampleCommand { Property = "Hello world" }; await publisher .SendCommand(command) .ConfigureAwait(false); mockPipeline.Verify( m => m.Process( It.Is <IEnumerable <OutgoingMessage> >( value => value.Single().Body == command && value.Single().MessageTypeNames.First() == FullNameTypeMap.Instance.GetNameForType(typeof(ExampleCommand)) && value.Single().SpecificReceivingEndpointName == TargetEndpoint)), Times.Once); }
private void _onExampleCommand(ExampleCommand cmd) { // this checks the aggregate to see if a user with this Id has already been created if (_Id != null) { throw new ArgumentException("Id", "User already created"); } // here is where we can ensure that the command has all the information in it that we expect it to have if (cmd.Id == null) { throw new ArgumentException("Id", "Id is a required field"); } if (cmd.Email == null) { throw new ArgumentException("Email", "Email is a required field"); } if (cmd.Name == null) { throw new ArgumentException("Name", "Name is a required field"); } // now we assign values to the event model that we created in ExampleEvent Thread.Sleep(100); ExampleEvent exampleEvent = new ExampleEvent { Id = cmd.Id, Name = cmd.Name, Email = cmd.Email }; // And finally we send the example event off to the Event Worker to be saved, filed and published EventWorker.Work(exampleEvent); }
public async Task <ActionResult> Post([FromBody] int value) { var exampleCommand = new ExampleCommand(ExampleId.New, value); await _commandBus.PublishAsync(exampleCommand, CancellationToken.None); return(CreatedAtAction(nameof(GetExample), new { id = exampleCommand.AggregateId.Value }, exampleCommand)); }
public void Execute_ExampleFound_RunsExample() { var exampleCommand = new ExampleCommand(this.examplesMock.Object); typeof(ExampleCommand) .GetProperty(nameof(ExampleCommand.ExampleName)) .SetValue(exampleCommand, "Found"); exampleCommand.Execute(CancellationToken.None); this.exampleMock.Verify(e => e.Run(It.IsAny <CancellationToken>())); }
public void CommandAndParameterSpecified() { var exampleCommand = new ExampleCommand(); var output = new StringWriter(); var exitCode = ConsoleCommandDispatcher.DispatchCommand(exampleCommand, new[] { "Example", "/f=bar" }, output); then_the_command_runs_without_tracing_parameter_information(output, exitCode); StringAssert.AreEqualIgnoringCase("bar", exampleCommand.Foo); }
public void OnlyCommandIsSpecified() { var exampleCommand = new ExampleCommand(); var output = new StringWriter(); var exitCode = ConsoleCommandDispatcher.DispatchCommand(exampleCommand, new[] { "Example" }, output); then_the_command_runs_without_tracing_parameter_information(output, exitCode); Assert.IsNull(exampleCommand.Foo); }
public void OnInjectDependencies(Signal <float> exampleSignal) { // instantiate a command object ExampleCommand command = new ExampleCommand(); // register a command as a listener of the signal exampleSignal.AddCommand(command); // ... // further calls to exampleSignal.Dispatch( float value ) will also // invoke command.Execute( float value ) }
public void GeneratesValidCommandWithEmptyPayload() { var command = new ExampleCommand(0x01, 0x02, new byte[0]); var packet = command.GetBytes(0x31); Assert.AreEqual(7, packet.Length); Assert.AreEqual(0xff, packet[0]); // SOP1 Assert.AreEqual(0xff, packet[1]); // SOP2 Assert.AreEqual(0x01, packet[2]); // Device Assert.AreEqual(0x02, packet[3]); // Command Assert.AreEqual(0x31, packet[4]); // Sequence Assert.AreEqual(0x01, packet[5]); // Length of payload + checksum Assert.AreEqual(0xca, packet[6]); // inverted checksum }
static void CommandPattern() { Console.WriteLine("\n\nCommandPattern Pattern"); var history = new History(); var exampleService = new ExampleService("Initial value"); var exampleCommand = new ExampleCommand(history, exampleService); var undoCommand = new UndoCommand <string>(history); Console.WriteLine(exampleService.GetContent()); exampleCommand.Execute(); Console.WriteLine(exampleService.GetContent()); undoCommand.Execute(); Console.WriteLine(exampleService.GetContent()); }
public void GeneratesValidCommandWithPayload() { var command = new ExampleCommand(0xde, 0xad, new byte[] { 0x01 }); var packet = command.GetBytes(0x11); Assert.AreEqual(8, packet.Length); Assert.AreEqual(0xff, packet[0]); // SOP1 Assert.AreEqual(0xff, packet[1]); // SOP2 Assert.AreEqual(0xde, packet[2]); // Device Assert.AreEqual(0xad, packet[3]); // Command Assert.AreEqual(0x11, packet[4]); // Sequence Assert.AreEqual(0x02, packet[5]); // Length of payload + checksum Assert.AreEqual(0x01, packet[6]); // payload Assert.AreEqual(0x60, packet[7]); // inverted checksum }
public ActionResult Example([FromBody] ExampleCommand example) { try { //Commands inherit Id from their base class, this data is used to create the eventstream Id. //If that stream is derived from fields in the command or event other than a simple Id, this is the place to make assign it. Aggregate exampleAggreate = new ExampleAggregate(); CommandHandler.ActivateCommand(example, exampleAggreate); return(Ok(example.Id)); } catch (Exception e) { return(BadRequest(e.Message.ToString())); } }
public void GeneratesValidCommandWithPayload() { var command = new ExampleCommand(0xde, 0xad, new byte[] {0x01}); var packet = command.GetBytes(0x11); Assert.AreEqual(8, packet.Length); Assert.AreEqual(0xff, packet[0]); // SOP1 Assert.AreEqual(0xff, packet[1]); // SOP2 Assert.AreEqual(0xde, packet[2]); // Device Assert.AreEqual(0xad, packet[3]); // Command Assert.AreEqual(0x11, packet[4]); // Sequence Assert.AreEqual(0x02, packet[5]); // Length of payload + checksum Assert.AreEqual(0x01, packet[6]); // payload Assert.AreEqual(0x60, packet[7]); // inverted checksum }
public async Task <IActionResult> Post([FromBody] ExampleCommand request) { var bus = BusConfigurator.ConfigureBus(); var sendToUri = new Uri($"{RabbitMqConsts.RabbitMqUri}{RabbitMqConsts.ExampleQueueName}"); var endPoint = await bus.GetSendEndpoint(sendToUri); await endPoint.Send <IExampleCommand>(new { Name = request.Name, Surname = request.Surname }); return(Ok("Success")); }
public void GeneratesValidCommandWithPayload2() { var command = new ExampleCommand(0xab, 0xcd, new byte[] {0xa1, 0xa2, 0xa3, 0xa4}); var packet = command.GetBytes(0x21); Assert.AreEqual(11, packet.Length); Assert.AreEqual(0xff, packet[0]); // SOP1 Assert.AreEqual(0xff, packet[1]); // SOP2 Assert.AreEqual(0xab, packet[2]); // Device Assert.AreEqual(0xcd, packet[3]); // Command Assert.AreEqual(0x21, packet[4]); // Sequence Assert.AreEqual(0x05, packet[5]); // Length of payload + checksum Assert.AreEqual(0xa1, packet[6]); // payload Assert.AreEqual(0xa2, packet[7]); // payload Assert.AreEqual(0xa3, packet[8]); // payload Assert.AreEqual(0xa4, packet[9]); // payload Assert.AreEqual(0xd7, packet[10]); // inverted checksum }
public void Should_ReturnBadRequest_When_IncorrectModel() { // Arrange var model = new ExampleCommand() { Type = 0 }; // Act var controller = new ExampleController(); var result = controller.Post(model); // Assert var okObjectResult = result.Should().BeOfType <BadRequestObjectResult>().Subject; okObjectResult.StatusCode.Should().Be(400); }
public void GeneratesValidCommandWithPayload2() { var command = new ExampleCommand(0xab, 0xcd, new byte[] { 0xa1, 0xa2, 0xa3, 0xa4 }); var packet = command.GetBytes(0x21); Assert.AreEqual(11, packet.Length); Assert.AreEqual(0xff, packet[0]); // SOP1 Assert.AreEqual(0xff, packet[1]); // SOP2 Assert.AreEqual(0xab, packet[2]); // Device Assert.AreEqual(0xcd, packet[3]); // Command Assert.AreEqual(0x21, packet[4]); // Sequence Assert.AreEqual(0x05, packet[5]); // Length of payload + checksum Assert.AreEqual(0xa1, packet[6]); // payload Assert.AreEqual(0xa2, packet[7]); // payload Assert.AreEqual(0xa3, packet[8]); // payload Assert.AreEqual(0xa4, packet[9]); // payload Assert.AreEqual(0xd7, packet[10]); // inverted checksum }
public async Task ThrowExceptionIfNoRouteConfiguredForCommand() { var publisher = new MessagePublisher( mockPipeline.Object, FullNameTypeMap.Instance, new Collection <CommandRoute>()); var command = new ExampleCommand { Property = "Hello world" }; var exception = await Assert.ThrowsExceptionAsync <InvalidOperationException>( () => publisher .SendCommand(command)) .ConfigureAwait(false); Assert.AreEqual( "No target endpoint has been configured for the command type \"SimpleEventBus.UnitTests.ExampleCommand, SimpleEventBus.UnitTests, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\".", exception.Message); }
public async Task <RequestResult <Example> > Handle(ExampleCommand request, CancellationToken cancellationToken) { var result = new RequestResult <Example>(); var exampleResponse = await _exampleClient.GetExampleFromExternalResource(request.Value); if (exampleResponse == null) { result.AddError(new Error { Code = "EXAMPLE_CODE", Reason = "Response from external example call was null" }); result.AddError("EXAMPLE_CODE", "Response from external example call was null"); return(result); } result.Payload = await _exampleRepository.InsertExample(exampleResponse.Value); return(result); }
private Events[] _exampleCommand(ExampleCommand cmd) { //we can check the _Id field to ensure that this command hasn't already been completed. //hydrate is called below by the EventStore Interfacing methods in infra. //This way, we can control the events to make sure that the data is as expected if (!string.IsNullOrEmpty(_Id)) { throw new Exception("This example event has already been created"); } if (string.IsNullOrEmpty(cmd.Id)) { throw new Exception("Id is a required field"); } //check to see if all required fields are included //todo, build helper function to siplify required parameter checking //if all fields are correctly filled out, return an array of events return(new Events[] { new ExampleEvent { Id = cmd.Id, Name = cmd.Name } }); }
public void ShouldCallHandlerWithMatchedArgumentCount() { const string ExceptionMessage = "The argument count doesn't match"; var dispatcher = new MessageDispatcher(new Container(), Substitute.For <IBotService>()); dispatcher.Register("example", typeof(ExampleCommand)); var results = new List <object>(); var command = new ExampleCommand(); var message = new Message(); var node = dispatcher.RegisteredCommands["example"]; Assert.Equal(ExceptionMessage, Assert.Throws <ArgumentException>(() => node.Handler(command, message, new[] { "arg" })).Message); node = node.Next !; Assert.Equal(ExceptionMessage, Assert.Throws <ArgumentException>(() => node.Handler(command, message, Array.Empty <string>())).Message); Assert.Equal(ExceptionMessage, Assert.Throws <ArgumentException>(() => node.Handler(command, message, new[] { "arg", "arg2" })).Message); }
static async Task Main(string[] args) { var container = new ServiceCollection() .AddMediatR(typeof(Program).Assembly) .Scan(scan => scan .FromAssemblyOf <Program>() .AddClasses(classes => classes.AssignableTo(typeof(IValidator <>))) .AsImplementedInterfaces() .WithScopedLifetime() .AddClasses(classes => classes.AssignableTo(typeof(IPipelineBehavior <,>))) .AsImplementedInterfaces() .WithScopedLifetime()) .BuildServiceProvider(); var mediator = container.GetRequiredService <IMediator>(); var command = new ExampleCommand { ExampleValue = "Test" // valid input // ExampleValue = "qwertyuiopasdfghjklzxcvbnm" // invalid input }; await mediator.Send(command); }
public void Execute_ExampleNotFound_WritesNotFound() { var exampleCommand = new ExampleCommand(this.examplesMock.Object); typeof(ExampleCommand) .GetProperty(nameof(ExampleCommand.ExampleName)) .SetValue(exampleCommand, "NotFound"); string outputString; using (var newOut = new StringWriter(CultureInfo.InvariantCulture)) { var previousOut = Console.Out; Console.SetOut(newOut); exampleCommand.Execute(CancellationToken.None); Console.SetOut(previousOut); outputString = newOut.ToString(); } Assert.That( outputString, Is.EqualTo("Could not find example named 'NotFound'." + Environment.NewLine)); }
static void Main(string[] args) { var rmqService = new RabbitMQServiceBuilder() .UseJsonSerializer() .SetDebugWriter(txt => Console.WriteLine($"[ {DateTime.Now.ToString("HH:mm:ss.fff")} ] {txt}")) .SetOptions(opt => { opt.Hostname = "<hostname>"; opt.Port = 5671; opt.UseSSL = true; opt.Username = "******"; opt.Password = "******"; opt.VirtualHost = "/"; }) .AddListenerSubscription <ExampleEvent>(opt => { opt.QueueName = ""; opt.Exchange = "amq.topic"; opt.Exclusive = true; opt.AutoAck = true; opt.AutoDelete = true; opt.Durable = false; opt.RoutingKey = "event.example"; opt.DebugText += (txt) => { Console.WriteLine(txt); }; opt.Callback += (evt) => { Console.WriteLine($"[ {DateTime.Now.ToString("HH:mm:ss.fff")} ] Received Event with name: {evt.EventName}"); }; }) .AddRpcSubscription <ExampleCommand>(opt => { opt.QueueName = typeof(ExampleCommand).Name; opt.Exchange = ""; opt.Exclusive = false; opt.AutoAck = false; opt.AutoDelete = false; opt.Durable = true; opt.DebugText += (txt) => { Console.WriteLine(txt); }; opt.Callback += (cmd) => { Console.WriteLine($"[ {DateTime.Now.ToString("HH:mm:ss.fff")} ] Handling command"); return(new CommandResult() { StatusCode = 200, Message = cmd.CommandText }); }; }) .AddListenerSubscription(new ExampleSubscription()) .Build(); Console.WriteLine($"[ {DateTime.Now} ] Sending Event"); rmqService.Publish("amq.topic", "event.example", new ExampleEvent() { EventName = "This is an example event" }); var cmd = new ExampleCommand() { CommandText = "This is an example command" }; Console.WriteLine($"[ {DateTime.Now} ] Sending Command"); rmqService.Call <CommandResult>( exchange: "", routingKey: typeof(ExampleCommand).Name, content: cmd, timeoutSeconds: 10, ResponseCallback: (res) => { Console.WriteLine($"[ {DateTime.Now.ToString("HH:mm:ss.fff")} ] Received Command Result with code: {res.StatusCode} and message: {res.Message}"); }, TimeoutCallback: () => { Console.WriteLine($"[ {DateTime.Now.ToString("HH:mm:ss.fff")} ] Command Timed out"); }); //Example of targeting the "ExampleSubscription.cs" class. var cmd2 = new ExampleSubscriptionObject() { ObjectContent = "This is another example command" }; Console.WriteLine($"[ {DateTime.Now} ] Sending Command 2"); rmqService.Call <ExampleRpcResult>( exchange: "", routingKey: typeof(ExampleSubscriptionObject).Name, content: cmd2, timeoutSeconds: 10, ResponseCallback: (res) => { Console.WriteLine($"[ {DateTime.Now.ToString("HH:mm:ss.fff")} ] Received Command 2 Result with OK: {res.ExampleWasOk} and message: {res.ExampleResultMessage}"); }, TimeoutCallback: () => { Console.WriteLine($"[ {DateTime.Now.ToString("HH:mm:ss.fff")} ] Command Timed out"); }); Console.ReadLine(); }
public ExampleWindowVM() { Users = new Users(); ExampleCommand = new ExampleCommand(this); }