Esempio n. 1
0
        public Task <Response <T> > GetResponse <T>(object values, CancellationToken cancellationToken, RequestTimeout timeout)
            where T : class
        {
            var message = TypeMetadataCache <TRequest> .InitializeFromObject(values);

            return(GetResponse <T>(message, cancellationToken, timeout));
        }
        /// <summary>
        /// Send the request, and complete the response task when the response is received. If
        /// the request times out, a RequestTimeoutException is thrown. If the remote service
        /// returns a fault, the task is set to exception status.
        /// </summary>
        /// <param name="client">The request client</param>
        /// <param name="values">The values to initialize the request object, anonymously</param>
        /// <param name="cancellationToken">A cancellation token for the request</param>
        /// <returns>The response Task</returns>
        public static Task <TResponse> Request <TRequest, TResponse>(this IRequestClient <TRequest, TResponse> client, object values,
                                                                     CancellationToken cancellationToken = default(CancellationToken))
        {
            TRequest request = TypeMetadataCache <TRequest> .InitializeFromObject(values);

            return(client.Request(request, cancellationToken));
        }
Esempio n. 3
0
        /// <summary>
        /// Using a filter-supplied context type, block so that the one time code is only executed once regardless of how many
        /// threads are pushing through the pipe at the same time.
        /// </summary>
        /// <typeparam name="T">The payload type, should be an interface</typeparam>
        /// <param name="context">The pipe context</param>
        /// <param name="setupMethod">The setup method, called once regardless of the thread count</param>
        /// <param name="payloadFactory">The factory method for the payload context, optional if an interface is specified</param>
        /// <returns></returns>
        public static async Task OneTimeSetup <T>(this PipeContext context, Func <T, Task> setupMethod, PayloadFactory <T> payloadFactory = null)
            where T : class
        {
            OneTime <T> newContext      = null;
            var         existingContext = context.GetOrAddPayload <OneTimeSetupContext <T> >(() =>
            {
                var payload = payloadFactory?.Invoke() ?? TypeMetadataCache <T> .InitializeFromObject(new {});

                newContext = new OneTime <T>(payload);

                return(newContext);
            });

            if (newContext == existingContext)
            {
                try
                {
                    await setupMethod(newContext.Payload).ConfigureAwait(false);

                    newContext.SetReady();
                }
                catch (Exception exception)
                {
                    newContext.SetFaulted(exception);

                    throw;
                }
            }
            else
            {
                await existingContext.Ready.ConfigureAwait(false);
            }
        }
Esempio n. 4
0
        async Task IPublishEndpoint.Publish <T>(object values, IPipe <PublishContext> publishPipe,
                                                CancellationToken cancellationToken)
        {
            if (values == null)
            {
                throw new ArgumentNullException(nameof(values));
            }

            var message = TypeMetadataCache <T> .InitializeFromObject(values);

            var adapter = new PublishPipeContextAdapter <T>(publishPipe, _publishPipe, _publishObserver, _sourceAddress, _correlationId, _conversationId, message);

            try
            {
                var sendEndpoint = await _endpointProvider.GetPublishSendEndpoint(typeof(T)).ConfigureAwait(false);

                await sendEndpoint.Send(message, adapter, cancellationToken).ConfigureAwait(false);

                await adapter.PostPublish().ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                await adapter.PublishFaulted(ex).ConfigureAwait(false);

                throw;
            }
        }
Esempio n. 5
0
        public async Task Should_allow_reconfiguration_of_prefetch_count()
        {
            IRequestClient <SetPrefetchCount, PrefetchCountUpdated> client = new PublishRequestClient <SetPrefetchCount, PrefetchCountUpdated>(Bus,
                                                                                                                                               TestTimeout);

            for (int i = 0; i < 500; i++)
            {
                await Bus.Publish(new A());

                await Task.Delay(50);
            }

            SetPrefetchCount request = TypeMetadataCache <SetPrefetchCount> .InitializeFromObject(new
            {
                PrefetchCount = (ushort)32,
                Timestamp     = DateTime.UtcNow,
                QueueName     = "input_queue",
            });

            await client.Request(request, TestCancellationToken);

            for (int i = 0; i < 500; i++)
            {
                await Bus.Publish(new A());

                await Task.Delay(50);
            }

            Assert.IsTrue(_consumer.Received.Select <A>().Any());
        }
Esempio n. 6
0
        /// <summary>
        /// Send a request from the bus to the endpoint, and return a Task which can be awaited for the response.
        /// </summary>
        /// <param name="bus">A started bus instance</param>
        /// <param name="destinationAddress">The service address</param>
        /// <param name="values">The values used to initialize the request message</param>
        /// <param name="cancellationToken">An optional cancellationToken for this request</param>
        /// <param name="timeout">An optional timeout for the request (defaults to 30 seconds)</param>
        /// <param name="callback">A callback, which can modify the <see cref="SendContext"/> of the request</param>
        /// <typeparam name="TRequest">The request type</typeparam>
        /// <typeparam name="TResponse">The response type</typeparam>
        /// <returns></returns>
        public static Task <Response <TResponse> > Request <TRequest, TResponse>(this IBus bus, Uri destinationAddress, object values,
                                                                                 CancellationToken cancellationToken = default, RequestTimeout timeout = default, Action <SendContext <TRequest> > callback = null)
            where TRequest : class
            where TResponse : class
        {
            var message = TypeMetadataCache <TRequest> .InitializeFromObject(values);

            return(Request <TRequest, TResponse>(bus, destinationAddress, message, cancellationToken, timeout, callback));
        }
Esempio n. 7
0
            public async Task <Accept <T> > Ask <T>(Guid clientId, int count)
                where T : class
            {
                var entry = await _index.Get(clientId, CreateClientInfo).ConfigureAwait(false);

                entry.Add(count);

                return(TypeMetadataCache <Accept <T> > .InitializeFromObject(new { Endpoint = (EndpointInfo)_settings, Count = count, }));
            }
Esempio n. 8
0
        public void Byte_interface_array()
        {
            var msg = TypeMetadataCache <ByteArrayMessage> .InitializeFromObject(new
            {
                Contents = new byte[] { 0x56, 0x34, 0xf3 }
            });

            var result = SerializeAndReturn(msg);

            result.Contents.SequenceEqual(msg.Contents).ShouldBeTrue();
        }
Esempio n. 9
0
        ITransform <TMessage, TMessage> Build()
        {
            var builder = new MessageTransformBuilder <TMessage, TMessage>(() => TypeMetadataCache <TMessage> .InitializeFromObject(new object()));

            for (int i = 0; i < _specifications.Count; i++)
            {
                _specifications[i].Configure(builder);
            }

            return(builder.Build());
        }
Esempio n. 10
0
        public Task RespondAsync <T>(object values, IPipe <SendContext> sendPipe) where T : class
        {
            if (values == null)
            {
                throw new ArgumentNullException(nameof(values));
            }

            var message = TypeMetadataCache <T> .InitializeFromObject(values);

            return(RespondAsync(message, sendPipe));
        }
        public Task Send <T>(object values, IPipe <SendContext <T> > pipe, CancellationToken cancellationToken)
            where T : class
        {
            if (values == null)
            {
                throw new ArgumentNullException(nameof(values));
            }

            T message = TypeMetadataCache <T> .InitializeFromObject(values);

            return(Send(message, pipe, cancellationToken));
        }
Esempio n. 12
0
        public virtual Task RespondAsync <T>(object values)
            where T : class
        {
            if (values == null)
            {
                throw new ArgumentNullException(nameof(values));
            }

            var message = TypeMetadataCache <T> .InitializeFromObject(values);

            return(RespondAsync(message));
        }
Esempio n. 13
0
        public async Task Should_allow_reconfiguration()
        {
            IRequestClient <SetConcurrencyLimit, ConcurrencyLimitUpdated> client = new PublishRequestClient <SetConcurrencyLimit, ConcurrencyLimitUpdated>(Bus,
                                                                                                                                                           TestTimeout);

            SetConcurrencyLimit request = TypeMetadataCache <SetConcurrencyLimit> .InitializeFromObject(new
            {
                ConcurrencyLimit = 16,
                Timestamp        = DateTime.UtcNow
            });

            await client.Request(request, TestCancellationToken);
        }
Esempio n. 14
0
        Task IPublishEndpoint.Publish <T>(object values, CancellationToken cancellationToken)
        {
            if (values == null)
            {
                throw new ArgumentNullException(nameof(values));
            }

            var message = TypeMetadataCache <T> .InitializeFromObject(values);

            var adapter = new PublishPipeContextAdapter <T>(_publishPipe, _publishObserver, _sourceAddress, _correlationId, _conversationId, message);

            return(Publish(cancellationToken, message, adapter));
        }
        public async Task Should_be_faster_than_json()
        {
            var now = DateTime.UtcNow;

            var inputObject = new
            {
                StringValue          = "Hello",
                IntValue             = 27,
                DateTimeValue        = now,
                NullableValue        = 42,
                NotNullableValue     = (int?)69,
                NullableDecimalValue = 123.45m,
                Numbers   = new[] { 12, 24, 36 },
                Names     = new[] { "Curly", "Larry", "Moe" },
                Exception = new IntentionalTestException("It Happens"),
                SubValue  = new { Text = "Mary" },
                SubValues = new object[] { new { Text = "Frank" }, new { Text = "Lola" }, },
                Amount    = 867.53m,
                //                AsyncValue = GetIntResult().Select(x => x.Number),
                EngineStatus = Status.Started,
                NumberStatus = 12,
                StringStatus = "Started",
                //       Strings = new Dictionary<string, string> {{"Hello", "World"}, {"Thank You", "Next"}}
            };

            var context = await MessageInitializerCache <SuperComplexRequest> .Initialize(inputObject);

            var timer = Stopwatch.StartNew();

            for (int i = 0; i < 100000; i++)
            {
                context = await MessageInitializerCache <SuperComplexRequest> .Initialize(inputObject);
            }

            timer.Stop();

            var message = TypeMetadataCache <SuperComplexRequest> .InitializeFromObject(inputObject);

            var jsonTimer = Stopwatch.StartNew();

            for (int i = 0; i < 100000; i++)
            {
                message = TypeMetadataCache <SuperComplexRequest> .InitializeFromObject(inputObject);
            }

            jsonTimer.Stop();

            Console.WriteLine("Initializer: {0}", timer.ElapsedMilliseconds);
            Console.WriteLine("JsonMessage: {0}", jsonTimer.ElapsedMilliseconds);
        }
        /// <summary>
        /// Send a message
        /// </summary>
        /// <typeparam name="T">The message type</typeparam>
        /// <param name="provider"></param>
        /// <param name="values"></param>
        /// <param name="cancellationToken"></param>
        /// <returns>The task which is completed once the Send is acknowledged by the broker</returns>
        public static async Task Send <T>(this ISendEndpointProvider provider, object values, CancellationToken cancellationToken = default)
            where T : class
        {
            var message = TypeMetadataCache <T> .InitializeFromObject(values);

            if (!EndpointConvention.TryGetDestinationAddress <T>(out var destinationAddress))
            {
                throw new ArgumentException($"A convention for the message type {TypeMetadataCache<T>.ShortName} was not found");
            }

            var endpoint = await provider.GetSendEndpoint(destinationAddress).ConfigureAwait(false);

            await endpoint.Send(message, cancellationToken).ConfigureAwait(false);
        }
Esempio n. 17
0
        Task <ScheduledMessage <T> > IMessageScheduler.ScheduleSend <T>(Uri destinationAddress, DateTime scheduledTime, object values, CancellationToken cancellationToken)
        {
            if (destinationAddress == null)
            {
                throw new ArgumentNullException(nameof(destinationAddress));
            }
            if (values == null)
            {
                throw new ArgumentNullException(nameof(values));
            }

            var message = TypeMetadataCache <T> .InitializeFromObject(values);

            return(ScheduleSend(destinationAddress, scheduledTime, message, Pipe.Empty <SendContext <T> >(), cancellationToken));
        }
Esempio n. 18
0
        /// <summary>
        ///     Sends an interface message, initializing the properties of the interface using the anonymous
        ///     object specified
        /// </summary>
        /// <typeparam name="T">The interface type to send</typeparam>
        /// <param name="context">The consume context</param>
        /// <param name="scheduledTime">The time at which the message should be delivered to the queue</param>
        /// <param name="values">The property values to initialize on the interface</param>
        /// <param name="pipe"></param>
        /// <param name="cancellationToken"></param>
        /// <returns>The task which is completed once the Send is acknowledged by the broker</returns>
        public static Task <ScheduledMessage <T> > SchedulePublish <T>(this ConsumeContext context, DateTime scheduledTime, object values, IPipe <SendContext> pipe,
                                                                       CancellationToken cancellationToken = default(CancellationToken))
            where T : class
        {
            if (values == null)
            {
                throw new ArgumentNullException(nameof(values));
            }

            var pipeProxy = new ServiceBusScheduleMessagePipe <T>(scheduledTime, pipe);

            var message = TypeMetadataCache <T> .InitializeFromObject(values);

            return(Schedule(context, scheduledTime, message, pipeProxy, cancellationToken));
        }
Esempio n. 19
0
        public void Should_property_initialize_the_values()
        {
            var values = new
            {
                CorrelationId = Guid.NewGuid(),
                Name          = "Dru",
                Timestamp     = DateTime.UtcNow,
            };

            IMessageType message = TypeMetadataCache <IMessageType> .InitializeFromObject(values);


            message.CorrelationId.ShouldBe(values.CorrelationId);
            message.Name.ShouldBe(values.Name);
            message.Timestamp.ShouldBe(values.Timestamp);
        }
        Task <ScheduledRecurringMessage <T> > IRecurringMessageScheduler.ScheduleRecurringSend <T>(Uri destinationAddress, RecurringSchedule schedule, object values,
                                                                                                   CancellationToken cancellationToken)
        {
            if (destinationAddress == null)
            {
                throw new ArgumentNullException(nameof(destinationAddress));
            }
            if (values == null)
            {
                throw new ArgumentNullException(nameof(values));
            }

            var message = TypeMetadataCache <T> .InitializeFromObject(values);

            return(ScheduleRecurringSend(destinationAddress, schedule, message, cancellationToken));
        }
Esempio n. 21
0
        /// <summary>
        ///     Sends an interface message, initializing the properties of the interface using the anonymous
        ///     object specified
        /// </summary>
        /// <typeparam name="T">The interface type to send</typeparam>
        /// <param name="context">The consume context</param>
        /// <param name="scheduledTime">The time at which the message should be delivered to the queue</param>
        /// <param name="values">The property values to initialize on the interface</param>
        /// <param name="pipe"></param>
        /// <param name="cancellationToken"></param>
        /// <returns>The task which is completed once the Send is acknowledged by the broker</returns>
        public static Task <ScheduledMessage <T> > SchedulePublish <T>(this ConsumeContext context, DateTime scheduledTime, object values, IPipe <SendContext> pipe,
                                                                       CancellationToken cancellationToken = default(CancellationToken))
            where T : class
        {
            if (values == null)
            {
                throw new ArgumentNullException(nameof(values));
            }

            var message = TypeMetadataCache <T> .InitializeFromObject(values);

            var destinationAddress = GetDestinationAddress <T>(context);

            var scheduler = context.GetPayload <MessageSchedulerContext>();

            return(scheduler.ScheduleSend(destinationAddress, scheduledTime, message, pipe, cancellationToken));
        }
        Task <ScheduledMessage <T> > IMessageScheduler.ScheduleSend <T>(Uri destinationAddress, DateTime scheduledTime, object values, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (destinationAddress == null)
            {
                throw new ArgumentNullException(nameof(destinationAddress));
            }
            if (values == null)
            {
                throw new ArgumentNullException(nameof(values));
            }

            var message = TypeMetadataCache <T> .InitializeFromObject(values);

            var pipeProxy = new ServiceBusScheduleMessagePipe <T>(scheduledTime);

            return(ScheduleSend(destinationAddress, scheduledTime, message, pipeProxy, cancellationToken));
        }
Esempio n. 23
0
        public async Task Should_be_faster_than_json()
        {
            var inputObject = new
            {
                StringValue         = _stringValue,
                BoolValue           = _boolValue,
                ByteValue           = _byteValue,
                ShortValue          = _shortValue,
                IntValue            = _intValue,
                LongValue           = _longValue,
                DoubleValue         = _doubleValue,
                DecimalValue        = _decimalValue,
                DateTimeValue       = _dateTimeValue,
                DateTimeOffsetValue = _dateTimeOffsetValue,
                TimeSpanValue       = _timeSpanValue,
                DayValue            = _dayValue,
                ObjectValue         = _objectValue,
            };

            var context = await MessageInitializerCache <TestInitializerMessage> .Initialize(inputObject);

            var timer = Stopwatch.StartNew();

            for (int i = 0; i < 100000; i++)
            {
                context = await MessageInitializerCache <TestInitializerMessage> .Initialize(inputObject);
            }

            timer.Stop();

            var message = TypeMetadataCache <TestInitializerMessage> .InitializeFromObject(inputObject);

            var jsonTimer = Stopwatch.StartNew();

            for (int i = 0; i < 100000; i++)
            {
                message = TypeMetadataCache <TestInitializerMessage> .InitializeFromObject(inputObject);
            }

            jsonTimer.Stop();

            Console.WriteLine("Initializer: {0}", timer.ElapsedMilliseconds);
            Console.WriteLine("JsonMessage: {0}", jsonTimer.ElapsedMilliseconds);
        }
Esempio n. 24
0
        public async Task <ExecutionResult> Execute(ExecuteContext <CardPaymentArguments> context)
        {
            var paymentDue = context.Arguments.PaymentDue;

            if (paymentDue == null)
            {
                throw new ArgumentNullException(nameof(PaymentDue));
            }

            string transactionId = "123456";

            return(context.CompletedWithVariables <CardPaymentLog>(new
            {
                TransactionId = transactionId,
                paymentDue.Amount
            }, new
            {
                PaymentReceipt = TypeMetadataCache <PaymentReceipt> .InitializeFromObject(new
                {
                    Source = "Credit Card",
                    paymentDue.Amount,
                })
            }));
        }
Esempio n. 25
0
 public async Task <ExecutionResult> Execute(ExecuteContext <PingArguments> context)
 {
     return(context.Completed(TypeMetadataCache <PingLog> .InitializeFromObject(new { context.Arguments.CorrelationId })));
 }
Esempio n. 26
0
        public RequestHandle <TRequest> Create(object values, CancellationToken cancellationToken = default, RequestTimeout timeout = default)
        {
            var message = TypeMetadataCache <TRequest> .InitializeFromObject(values);

            return(Create(message, cancellationToken, timeout));
        }