コード例 #1
0
        public async Task <GeoLineResult> SendGeoLineRequest(GeoLineRequest geoLineRequest)
        {
            var sendOptions = new SendOptions();

            sendOptions.SetDestination("GeoAPI.GeoCalcServer");
            var geoLineResponse = await _messageSession.Request <GeoLineResult>(geoLineRequest, sendOptions);

            return(geoLineResponse);
        }
コード例 #2
0
        public static async Task <bool> TimeoutCommand(this IMessageSession ctx, ICommand command, TimeSpan timeout)
        {
            if (string.IsNullOrEmpty(Configuration.Settings.CommandDestination))
            {
                throw new ArgumentException($"Must use Configuration.SetCommandDestination to use destination-less extension methods");
            }

            var options = new SendOptions();

            options.SetDestination(Configuration.Settings.CommandDestination);
            options.SetHeader(Defaults.RequestResponse, "1");

            var cancelation = new CancellationTokenSource(timeout);

            try
            {
                var response = await ctx.Request <IMessage>(command, options, cancelation.Token).ConfigureAwait(false);

                CheckResponse(command, response);
                return(true);
            }
            catch (TaskCanceledException)
            {
                Logger.WarnEvent("TimeOut", "{CommandType}", command.GetType().FullName);
                return(false);
            }
        }
コード例 #3
0
        public Invoice CalculateInvoice(Cart cart)
        {
            var items = cart.ToList();
            var order = new Domain.Interface.Order
            {
                Equipment = items
                            .Select(item => new Domain.Interface.EquipmentOrder(item.Type, item.RentalDays))
                            .ToList()
            };
            var sendOptions = new SendOptions();

            sendOptions.SetDestination("Bondora.Rental.Domain.Interface");
            // since now message queue is used, it might be a good idea to "mark" all messages with some unique ID
            // currently I have no confidence how messages from several running web instances will be handled,
            //   and if NServiceBus does this automatically
            var reply = _messageSession
                        .Request <Domain.Interface.Invoice>(order, sendOptions)
                        .GetAwaiter()
                        .GetResult();
            // expected that invoice keeps equipment in the same order
            // following code will fail if ordering is broken
            var invoiceLines = new List <InvoiceLine>();

            for (var index = 0; index < items.Count; index++)
            {
                invoiceLines.Add(new InvoiceLine(items[index].Name, reply.Lines[index]));
            }

            return(new Invoice(invoiceLines, reply.Price, reply.LoyaltyPoints));
        }
コード例 #4
0
        public async Task <IActionResult> OnPostAsync(string textField)
        {
            if (string.IsNullOrWhiteSpace(textField))
            {
                return(Page());
            }

            #region ActionHandling

            if (!int.TryParse(textField, out var number))
            {
                return(Page());
            }
            var command = new Command
            {
                Id = number
            };

            var sendOptions = new SendOptions();
            sendOptions.SetDestination("Samples.AsyncPages.Server");

            var code = await messageSession.Request <ErrorCodes>(command, sendOptions);

            ResponseText = Enum.GetName(typeof(ErrorCodes), code);

            return(Page());

            #endregion
        }
コード例 #5
0
        public static async Task CommandToDomain <T>(this IMessageSession bus, T message, bool timeout = true) where T : StampedCommand
        {
            var options = new SendOptions();

            options.SetDestination("domain");
            options.SetHeader(Aggregates.Defaults.RequestResponse, "1");

            var response = bus.Request <Aggregates.Messages.IMessage>(message, options);

            if (timeout)
            {
                await Task.WhenAny(
                    Task.Delay(TenSeconds), response)
                .ConfigureAwait(false);
            }
            else
            {
                await response.ConfigureAwait(false);
            }

            if (!response.IsCompleted)
            {
                throw new CommandTimeoutException("Command timed out");
            }

            CheckResponse(message, response.Result);
        }
コード例 #6
0
    public ActionResult Index(string textField)
    {
        ViewBag.Title = "SendAndBlock";

        if (!int.TryParse(textField, out var number))
        {
            return(View());
        }

        #region SendAndBlockController

        var command = new Command
        {
            Id = number
        };


        var sendOptions = new SendOptions();
        sendOptions.SetDestination("Samples.Mvc.Server");
        var status = messageSession.Request <ErrorCodes>(command, sendOptions).GetAwaiter().GetResult();

        return(IndexCompleted(Enum.GetName(typeof(ErrorCodes), status)));

        #endregion
    }
コード例 #7
0
        public static async Task <object> RequestQuery <T, TResponse>(this IMessageSession bus, T message, bool timeout = true) where T : Query where TResponse : class
        {
            var options = new SendOptions();

            options.SetDestination("mongodb");
            options.SetHeader(Aggregates.Defaults.RequestResponse, "1");

            var response = bus.Request <Reply>(message, options);

            if (timeout)
            {
                await Task.WhenAny(
                    Task.Delay(TenSeconds), response)
                .ConfigureAwait(false);
            }
            else
            {
                await response.ConfigureAwait(false);
            }

            if (!response.IsCompleted)
            {
                throw new CommandTimeoutException("Request timed out");
            }

            if (response.Result.Payload == null)
            {
                throw new QueryRejectedException("No results for query");
            }

            return(response.Result.RequestQuery <TResponse>());
        }
コード例 #8
0
        public async Task <ActionResult> Index(GetUserByIdViewModel model)
        {
            var response = await _session.Request <GetUserByIdCommandReply>(model.GetUserByIdCommand);

            model.Result = response.User?.Name ?? "User Not Found";

            return(View(model));
        }
コード例 #9
0
        public async Task <string> Get()
        {
            var message = new ProcessPayment {
                ReferenceId = Guid.NewGuid().ToString(), AccountNumberEncrypted = "123456", RoutingNumber = "555555", Amount = 100.45M, RequestDate = DateTime.UtcNow
            };
            var response = await messageSession.Request <ProcessPaymentReply>(message);

            return("Payment Status: " + JsonConvert.SerializeObject(response));
        }
コード例 #10
0
        public async Task <JsonResult <ZResponse> > Get(Guid customerId)
        {
            var msg = new DoZSyncOverAsync {
                CustomerId = customerId
            };

            var response = await _messageSession.Request <ZResponse>(msg);

            return(Json(response));
        }
コード例 #11
0
        public static async Task Command(this IMessageSession ctx, ICommand command)
        {
            var options = new SendOptions();

            options.SetHeader(Defaults.RequestResponse, "1");

            var response = await ctx.Request <IMessage>(command, options).ConfigureAwait(false);

            response.CommandResponse();
        }
コード例 #12
0
        public static async Task <R.ResponsesQuery <TResponse> > RequestToElastic <T, TResponse>(this IMessageSession bus, T message, Q.QueriesQuery <TResponse> query) where T : IQuery where TResponse : class
        {
            var options = new SendOptions();

            options.SetDestination(RiakEndpoint);
            options.SetHeader(Aggregates.Defaults.RequestResponse, "1");

            var response = await bus.Request <IMessage>(message, options).ConfigureAwait(false);

            return(response.RequestQuery(query));
        }
コード例 #13
0
        public static async Task <R.ResponsesPaged <TResponse> > RequestToElastic <T, TResponse>(this IMessageSession bus, Action <T> messageConstructor, Q.QueriesPaged <TResponse> query) where T : IPaged where TResponse : class
        {
            var options = new SendOptions();

            options.SetDestination(ElasticEndpoint);
            options.SetHeader(Aggregates.Defaults.RequestResponse, "1");

            var response = await bus.Request <IMessage>(messageConstructor, options).ConfigureAwait(false);

            return(response.RequestPaged(query));
        }
コード例 #14
0
        public static async Task CommandToDomain <T>(this IMessageSession bus, T message) where T : DemoCommand
        {
            var options = new SendOptions();

            options.SetDestination(DomainEndpoint);
            options.SetHeader(Aggregates.Defaults.RequestResponse, "1");

            var response = await bus.Request <IMessage>(message, options).ConfigureAwait(false);

            response.CommandResponse();
        }
コード例 #15
0
        public static async Task DomainCommand(this IMessageSession ctx, ICommand command)
        {
            var options = new NServiceBus.SendOptions();

            options.RouteToThisEndpoint();
            options.SetHeader(Aggregates.Defaults.RequestResponse, "1");

            var response = await ctx.Request <IMessage>(command, options).ConfigureAwait(false);

            response.CommandResponse();
        }
コード例 #16
0
        public async Task <SubmitOrderResponse> SubmitOrderAsync()
        {
            var command = new SubmitOrderCommand {
                Number = DateTime.Now.Ticks
            };

            _log.LogInformation($"SubmitOrderCommand {command.Number}");

            var response = await _messageSession.Request <SubmitOrderResponse>(command);

            _log.LogInformation($"SubmitOrderResponse {response.Id}");

            return(response);
        }
コード例 #17
0
        public static async Task Command(this IMessageSession ctx, ICommand command)
        {
            if (string.IsNullOrEmpty(Configuration.Settings.CommandDestination))
            {
                throw new ArgumentException($"Must use Configuration.SetCommandDestination to use destination-less extension methods");
            }

            var options = new SendOptions();

            options.SetDestination(Configuration.Settings.CommandDestination);
            options.SetHeader(Defaults.RequestResponse, "1");

            var response = await ctx.Request <IMessage>(command, options).ConfigureAwait(false);

            CheckResponse(command, response);
        }
コード例 #18
0
        public async Task RunSample(IServiceProvider provider, IMessageSession bus, string barValue)
        {
            var subscriber = provider.GetRequiredService <ISubscriber>();

            var options = new SendOptions();

            options.SetDestination("TestDestination");

            var reply = await bus.Request <TestCommand, TestReply>(
                subscriber, cmd =>
            {
                cmd.Property1 = "foo";
                cmd.Property2 = barValue;
            }, options).WithTimeout(TimeSpan.FromSeconds(60));

            Console.WriteLine($"Instance {_instanceId} received reply \"{reply.ReplyValue}\"");
        }
コード例 #19
0
        public async Task <IActionResult> Callback()
        {
            var guid    = Guid.NewGuid();
            var message = new RequestDataMessage
            {
                DataId = guid,
                String = "String property value"
            };

            var response = await _messageSession.Request <DataResponseMessage>(message)
                           .ConfigureAwait(false);

            return(new OkObjectResult(new
            {
                RequestId = guid,
                ResponseId = response.Id,
            }));
        }
コード例 #20
0
        public static async Task <bool> TimeoutCommand(this IMessageSession ctx, ICommand command, TimeSpan timeout)
        {
            var options = new SendOptions();

            options.SetHeader(Defaults.RequestResponse, "1");

            var cancelation = new CancellationTokenSource(timeout);

            try
            {
                var response = await ctx.Request <IMessage>(command, options, cancelation.Token).ConfigureAwait(false);

                response.CommandResponse();
                return(true);
            }
            catch (TaskCanceledException)
            {
                return(false);
            }
        }
コード例 #21
0
        public static async Task <Responses.Paged <TResponse> > Request <T, TResponse>(this IMessageSession bus, T message) where T : Paged where TResponse : class
        {
            var options = new SendOptions();

            options.SetDestination("application2");
            options.SetHeader(Aggregates.Defaults.RequestResponse, "1");

            var response = bus.Request <PagedReply>(message, options);

            await Task.WhenAny(
                Task.Delay(TenSeconds), response)
            .ConfigureAwait(false);

            if (!response.IsCompleted)
            {
                throw new CommandTimeoutException("Request timed out");
            }

            return(response.Result.RequestPaged <TResponse>());
        }
コード例 #22
0
    public async Task <ActionResult> Index(string textField)
    {
        if (!int.TryParse(textField, out var number))
        {
            return(View("Index"));
        }
        #region AsyncController
        var command = new Command
        {
            Id = number
        };

        var sendOptions = new SendOptions();
        sendOptions.SetDestination("Samples.Mvc.Server");

        var status = await messageSession.Request <ErrorCodes>(command, sendOptions);

        return(IndexCompleted(Enum.GetName(typeof(ErrorCodes), status)));

        #endregion
    }
コード例 #23
0
        public static async Task <bool> TimeoutCommand(this IMessageSession ctx, ICommand command, TimeSpan timeout)
        {
            var options = new SendOptions();

            options.SetHeader(Defaults.RequestResponse, "1");

            var cancelation = new CancellationTokenSource(timeout);

            try
            {
                var response = await ctx.Request <IMessage>(command, options, cancelation.Token).ConfigureAwait(false);

                CheckResponse(command, response);
                return(true);
            }
            catch (TaskCanceledException)
            {
                Logger.WarnEvent("TimeOut", "{CommandType}", command.GetType().FullName);
                return(false);
            }
        }
コード例 #24
0
        public static async Task <bool> TimeoutCommand(this IMessageSession ctx, string destination, ICommand command, TimeSpan timeout)
        {
            var options = new SendOptions();

            options.SetDestination(destination);
            options.SetHeader(Defaults.RequestResponse, "1");

            var cancelation = new CancellationTokenSource(timeout);

            try
            {
                var response = await ctx.Request <IMessage>(command, options, cancelation.Token).ConfigureAwait(false);

                response.CommandResponse();
                return(true);
            }
            catch (TaskCanceledException)
            {
                Logger.Warn($"Command {command.GetType().FullName} timed out");
                return(false);
            }
        }
コード例 #25
0
ファイル: DeviceController.cs プロジェクト: Holden1997/IoT
        public async Task <IActionResult> Devace()
        {
            var id       = Thread.CurrentThread.ManagedThreadId;
            var clientId = HttpContext.ClientId();
            var devices  = await _devaceService.GetAllDevices(clientId);

            if (devices.Count == 0)
            {
                return(NoContent());
            }
            var         id2          = Thread.CurrentThread.ManagedThreadId;
            List <Guid> serialNamber = new List <Guid>();

            for (int i = 0; i < devices.Count; i++)
            {
                serialNamber.Add(devices[i].SirialNumber);
            }

            var response = await _message.Request <DeviceCallback>(new UserMessage(serialNamber));

            string jsonData = JsonConvert.SerializeObject(response.Devices);

            return(Content(jsonData));
        }
コード例 #26
0
 public Task <Paged <Todo.Models.TodoResponse> > Any(Todo.AllTodos request)
 {
     return(_bus.Request <Todo.Queries.AllTodos, Todo.Models.TodoResponse>(new Todo.Queries.AllTodos
     {
     }));
 }
コード例 #27
0
 public Task <Paged <Todo.Models.TodoResponse> > All()
 {
     return(_session.Request <Todo.Queries.AllTodos, Todo.Models.TodoResponse>(new Todo.Queries.AllTodos
     {
     }));
 }
コード例 #28
0
 /// <summary>
 /// Sends a <paramref name="requestMessage" /> to the configured destination and returns back a
 /// <see cref="Task{TResponse}" /> which can be awaited.
 /// </summary>
 /// <remarks>
 /// The task returned is non durable. When the AppDomain is unloaded or the response task is canceled.
 /// Messages can still arrive to the requesting endpoint but in that case no handling code will be attached to consume
 /// that response message and therefore the message will be moved to the error queue.
 /// </remarks>
 /// <typeparam name="TResponse">The response type.</typeparam>
 /// <param name="session">The session.</param>
 /// <param name="requestMessage">The request message.</param>
 /// <param name="options">The options for the send.</param>
 /// <returns>A task which contains the response when it is completed.</returns>
 public static Task <TResponse> Request <TResponse>(this IMessageSession session, object requestMessage, SendOptions options)
 {
     return(session.Request <TResponse>(requestMessage, options, CancellationToken.None));
 }
コード例 #29
0
 /// <summary>
 /// Sends a <paramref name="requestMessage" /> to the configured destination and returns back a
 /// <see cref="Task{TResponse}" /> which can be awaited.
 /// </summary>
 /// <remarks>
 /// The task returned is non durable. When the AppDomain is unloaded or the response task is canceled.
 /// Messages can still arrive to the requesting endpoint but in that case no handling code will be attached to consume
 /// that response message and therefore the message will be moved to the error queue.
 /// </remarks>
 /// <typeparam name="TResponse">The response type.</typeparam>
 /// <param name="session">The session.</param>
 /// <param name="requestMessage">The request message.</param>
 /// <param name="cancellationToken">The cancellation token used to cancel the request.</param>
 /// <returns>A task which contains the response when it is completed.</returns>
 public static Task <TResponse> Request <TResponse>(this IMessageSession session, object requestMessage, CancellationToken cancellationToken)
 {
     return(session.Request <TResponse>(requestMessage, new SendOptions(), cancellationToken));
 }