示例#1
0
        public async override Task SendAsync(string deviceId, Message message, TimeSpan?timeout = null)
        {
            if (string.IsNullOrWhiteSpace(deviceId))
            {
                throw new ArgumentNullException(nameof(deviceId));
            }

            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }
            Outcome outcome;

            using (AmqpMessage amqpMessage = message.ToAmqpMessage())
            {
                amqpMessage.Properties.To = "/devices/" + WebUtility.UrlEncode(deviceId) + "/messages/deviceBound";
                try
                {
                    SendingAmqpLink sendingLink = await GetSendingLinkAsync().ConfigureAwait(false);

                    if (timeout != null)
                    {
                        outcome = await sendingLink.SendMessageAsync(amqpMessage, IotHubConnection.GetNextDeliveryTag(ref sendingDeliveryTag), AmqpConstants.NullBinary, (TimeSpan)timeout).ConfigureAwait(false);
                    }
                    else
                    {
                        outcome = await sendingLink.SendMessageAsync(amqpMessage, IotHubConnection.GetNextDeliveryTag(ref sendingDeliveryTag), AmqpConstants.NullBinary, OperationTimeout).ConfigureAwait(false);
                    }
                }
                catch (TimeoutException exception)
                {
                    throw exception;
                }
                catch (Exception exception)
                {
                    if (exception.IsFatal())
                    {
                        throw;
                    }

                    throw AmqpClientHelper.ToIotHubClientContract(exception);
                }
            }
            if (outcome.DescriptorCode != Accepted.Code)
            {
                throw AmqpErrorMapper.GetExceptionFromOutcome(outcome);
            }
        }
        private async Task <AmqpMessage> RoundTripTwinMessage(AmqpMessage amqpMessage, CancellationToken cancellationToken)
        {
            string      correlationId = Guid.NewGuid().ToString();
            AmqpMessage response      = null;


            try
            {
                Outcome         outcome;
                SendingAmqpLink eventSendingLink = await this.GetTwinSendingLinkAsync(cancellationToken);

                amqpMessage.Properties.CorrelationId = correlationId;

                this.twinResponseCompletions[correlationId] = new TaskCompletionSource <AmqpMessage>();

                outcome = await eventSendingLink.SendMessageAsync(amqpMessage, new ArraySegment <byte>(Guid.NewGuid().ToByteArray()), AmqpConstants.NullBinary, this.operationTimeout);

                if (outcome.DescriptorCode != Accepted.Code)
                {
                    throw AmqpErrorMapper.GetExceptionFromOutcome(outcome);
                }

                response = await this.twinResponseCompletions[correlationId].Task;
            }
            finally
            {
                TaskCompletionSource <AmqpMessage> throwAway;
                this.twinResponseCompletions.TryRemove(correlationId, out throwAway);
            }

            return(response);
        }
示例#3
0
        protected override async Task OnSendAsync(IEnumerable <BrokeredMessage> brokeredMessages)
        {
            TimeoutHelper timeoutHelper = new TimeoutHelper(this.OperationTimeout, true);

            using (AmqpMessage amqpMessage = AmqpMessageConverter.BrokeredMessagesToAmqpMessage(brokeredMessages, true))
            {
                SendingAmqpLink amqpLink = await this.SendLinkManager.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false);

                if (amqpLink.Settings.MaxMessageSize.HasValue)
                {
                    ulong size = (ulong)amqpMessage.SerializedMessageSize;
                    if (size > amqpLink.Settings.MaxMessageSize.Value)
                    {
                        // TODO: Add MessageSizeExceededException
                        throw new NotImplementedException("MessageSizeExceededException: " + Resources.AmqpMessageSizeExceeded.FormatForUser(amqpMessage.DeliveryId.Value, size, amqpLink.Settings.MaxMessageSize.Value));
                        ////throw Fx.Exception.AsError(new MessageSizeExceededException(
                        ////Resources.AmqpMessageSizeExceeded.FormatForUser(amqpMessage.DeliveryId.Value, size, amqpLink.Settings.MaxMessageSize.Value)));
                    }
                }

                Outcome outcome = await amqpLink.SendMessageAsync(amqpMessage, this.GetNextDeliveryTag(), AmqpConstants.NullBinary, timeoutHelper.RemainingTime()).ConfigureAwait(false);

                if (outcome.DescriptorCode != Accepted.Code)
                {
                    Rejected rejected = (Rejected)outcome;
                    throw Fx.Exception.AsError(AmqpExceptionHelper.ToMessagingContract(rejected.Error));
                }
            }
        }
示例#4
0
        async Task <Outcome> SendAmqpMethodResponseAsync(AmqpMessage amqpMessage, CancellationToken cancellationToken)
        {
            if (Logging.IsEnabled)
            {
                Logging.Enter(this, amqpMessage, cancellationToken, $"{nameof(AmqpTransportHandler)}.{nameof(SendAmqpMethodResponseAsync)}");
            }
            Outcome outcome;

            try
            {
                SendingAmqpLink methodRespSendingLink = await this.GetMethodSendingLinkAsync(cancellationToken).ConfigureAwait(false);

                outcome = await methodRespSendingLink.SendMessageAsync(amqpMessage, new ArraySegment <byte>(Guid.NewGuid().ToByteArray()), AmqpConstants.NullBinary, this.operationTimeout).ConfigureAwait(false);
            }
            catch (Exception exception) when(!exception.IsFatal() && !(exception is OperationCanceledException))
            {
                throw AmqpClientHelper.ToIotHubClientContract(exception);
            }
            finally
            {
                if (Logging.IsEnabled)
                {
                    Logging.Exit(this, amqpMessage, cancellationToken, $"{nameof(AmqpTransportHandler)}.{nameof(SendAmqpMethodResponseAsync)}");
                }
            }

            return(outcome);
        }
        public override async Task <Twin> SendTwinGetAsync(CancellationToken cancellationToken)
        {
            Outcome outcome;

            try
            {
                await EnableTwinAsync(cancellationToken);

                SendingAmqpLink eventSendingLink = await this.GetTwinSendingLinkAsync(cancellationToken);

                // This is test code and will be re-written in future commits

                AmqpMessage getTwinMessage   = AmqpMessage.Create();
                string      getCorrelationId = Guid.NewGuid().ToString();
                getTwinMessage.Properties.CorrelationId            = getCorrelationId;
                getTwinMessage.MessageAnnotations.Map["operation"] = "GET";

                outcome = await eventSendingLink.SendMessageAsync(getTwinMessage, new ArraySegment <byte>(Guid.NewGuid().ToByteArray()), AmqpConstants.NullBinary, this.operationTimeout);
            }
            catch (Exception exception)
            {
                if (exception.IsFatal())
                {
                    throw;
                }

                throw AmqpClientHelper.ToIotHubClientContract(exception);
            }

            return(null);
        }
        // This call is executed over AMQP.
        public override async Task SendAsync(string deviceId, string moduleId, Message message)
        {
            Logging.Enter(this, $"Sending message with Id [{message?.MessageId}] for device {deviceId}, module {moduleId}", nameof(SendAsync));

            if (string.IsNullOrWhiteSpace(deviceId))
            {
                throw new ArgumentNullException(nameof(deviceId));
            }

            if (string.IsNullOrWhiteSpace(moduleId))
            {
                throw new ArgumentNullException(nameof(moduleId));
            }

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

            if (_clientOptions?.SdkAssignsMessageId == SdkAssignsMessageId.WhenUnset && message.MessageId == null)
            {
                message.MessageId = Guid.NewGuid().ToString();
            }

            if (message.IsBodyCalled)
            {
                message.ResetBody();
            }

            using AmqpMessage amqpMessage = MessageConverter.MessageToAmqpMessage(message);
            amqpMessage.Properties.To     = "/devices/" + WebUtility.UrlEncode(deviceId) + "/modules/" + WebUtility.UrlEncode(moduleId) + "/messages/deviceBound";
            try
            {
                SendingAmqpLink sendingLink = await GetSendingLinkAsync().ConfigureAwait(false);

                Outcome outcome = await sendingLink
                                  .SendMessageAsync(
                    amqpMessage,
                    IotHubConnection.GetNextDeliveryTag(ref _sendingDeliveryTag),
                    AmqpConstants.NullBinary,
                    OperationTimeout)
                                  .ConfigureAwait(false);

                Logging.Info(this, $"Outcome was: {outcome?.DescriptorName}", nameof(SendAsync));

                if (outcome.DescriptorCode != Accepted.Code)
                {
                    throw AmqpErrorMapper.GetExceptionFromOutcome(outcome);
                }
            }
            catch (Exception ex) when(!ex.IsFatal())
            {
                Logging.Error(this, $"{nameof(SendAsync)} threw an exception: {ex}", nameof(SendAsync));
                throw AmqpClientHelper.ToIotHubClientContract(ex);
            }
            finally
            {
                Logging.Exit(this, $"Sending message with Id [{message?.MessageId}] for device {deviceId}, module {moduleId}", nameof(SendAsync));
            }
        }
示例#7
0
 internal static async Task <Outcome> SendAmqpMessageAsync(
     SendingAmqpLink sendingAmqpLink,
     AmqpMessage message,
     TimeSpan timeout)
 {
     return(await sendingAmqpLink.SendMessageAsync(
                message,
                new ArraySegment <byte>(Guid.NewGuid().ToByteArray()),
                AmqpConstants.NullBinary,
                timeout
                ).ConfigureAwait(false));
 }
示例#8
0
        public void AmqpWebSocketTransportTest()
        {
            string address = "ws://localhost:28088";
            var    broker  = new TestAmqpBroker(new string[] { address }, null, null, null);

            try
            {
                broker.Start();

                string queue = "AmqpWebSocketTransportTest";
                broker.AddQueue(queue);

                AmqpConnection connection = AmqpConnection.Factory.OpenConnectionAsync(address).GetAwaiter().GetResult();

                AmqpSession session = connection.CreateSession(new AmqpSessionSettings());
                session.Open();

                SendingAmqpLink sLink = new SendingAmqpLink(session, AmqpUtils.GetLinkSettings(true, queue, SettleMode.SettleOnSend));
                sLink.Open();

                int messageCount = 100;
                for (int i = 0; i < messageCount; i++)
                {
                    AmqpMessage message = AmqpMessage.Create(new AmqpValue()
                    {
                        Value = "message" + i
                    });
                    sLink.SendMessageAsync(message, AmqpConstants.EmptyBinary, AmqpConstants.NullBinary, TimeSpan.FromSeconds(10)).Wait();
                }

                sLink.Close();

                ReceivingAmqpLink rLink = new ReceivingAmqpLink(session, AmqpUtils.GetLinkSettings(false, queue, SettleMode.SettleOnReceive, 100));
                rLink.Open();

                for (int i = 0; i < messageCount; i++)
                {
                    AmqpMessage message2 = rLink.ReceiveMessageAsync(TimeSpan.FromSeconds(60)).GetAwaiter().GetResult();
                    Assert.NotNull(message2);

                    rLink.AcceptMessage(message2, false);
                    message2.Dispose();
                }

                rLink.Close();

                connection.Close();
            }
            finally
            {
                broker.Stop();
            }
        }
示例#9
0
        private async Task <AmqpMessage> RoundTripTwinMessage(AmqpMessage amqpMessage, CancellationToken cancellationToken)
        {
            if (Logging.IsEnabled)
            {
                Logging.Enter(this, amqpMessage, cancellationToken, $"{nameof(AmqpTransportHandler)}.{nameof(RoundTripTwinMessage)}");
            }
            string      correlationId = Guid.NewGuid().ToString();
            AmqpMessage response      = null;

            try
            {
                Outcome         outcome;
                SendingAmqpLink eventSendingLink = await this.GetTwinSendingLinkAsync(cancellationToken).ConfigureAwait(false);

                amqpMessage.Properties.CorrelationId = correlationId;

                var taskCompletionSource = new TaskCompletionSource <AmqpMessage>();
                this.twinResponseCompletions[correlationId] = taskCompletionSource;

                outcome = await eventSendingLink.SendMessageAsync(amqpMessage, new ArraySegment <byte>(Guid.NewGuid().ToByteArray()), AmqpConstants.NullBinary, this.operationTimeout).ConfigureAwait(false);

                if (outcome.DescriptorCode != Accepted.Code)
                {
                    throw AmqpErrorMapper.GetExceptionFromOutcome(outcome);
                }

                var receivingTask = taskCompletionSource.Task;
                if (await Task.WhenAny(receivingTask, Task.Delay(TimeSpan.FromSeconds(ResponseTimeoutInSeconds))).ConfigureAwait(false) == receivingTask)
                {
                    // Task completed within timeout.
                    // Consider that the task may have faulted or been canceled.
                    // We re-await the task so that any exceptions/cancellation is rethrown.
                    response = await receivingTask.ConfigureAwait(false);
                }
                else
                {
                    // Timeout happen
                    throw new TimeoutException();
                }
            }
            finally
            {
                TaskCompletionSource <AmqpMessage> throwAway;
                this.twinResponseCompletions.TryRemove(correlationId, out throwAway);
                if (Logging.IsEnabled)
                {
                    Logging.Exit(this, amqpMessage, cancellationToken, $"{nameof(AmqpTransportHandler)}.{nameof(RoundTripTwinMessage)}");
                }
            }

            return(response);
        }
        private async Task <Outcome> SendAmqpMessageAsync(AmqpMessage amqpMessage, TimeSpan timeout)
        {
            if (Logging.IsEnabled)
            {
                Logging.Enter(this, $"{nameof(SendAmqpMessageAsync)}");
            }

            return(await _sendingAmqpLink.SendMessageAsync(
                       amqpMessage,
                       new ArraySegment <byte>(Guid.NewGuid().ToByteArray()),
                       AmqpConstants.NullBinary,
                       timeout).ConfigureAwait(false));
        }
示例#11
0
        /// <summary>
        ///    Sends a set of messages to the associated Queue/Topic using a batched approach.
        /// </summary>
        ///
        /// <param name="messageFactory"></param>
        /// <param name="timeout"></param>
        /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param>
        ///
        internal virtual async Task SendBatchInternalAsync(
            Func <AmqpMessage> messageFactory,
            TimeSpan timeout,
            CancellationToken cancellationToken)
        {
            var stopWatch = Stopwatch.StartNew();

            using (AmqpMessage batchMessage = messageFactory())
            {
                string messageHash = batchMessage.GetHashCode().ToString();

                ArraySegment <byte> transactionId      = AmqpConstants.NullBinary;
                Transaction         ambientTransaction = Transaction.Current;
                if (ambientTransaction != null)
                {
                    transactionId = await AmqpTransactionManager.Instance.EnlistAsync(
                        ambientTransaction,
                        _connectionScope,
                        timeout).ConfigureAwait(false);
                }

                SendingAmqpLink link = await _sendLink.GetOrCreateAsync(UseMinimum(_connectionScope.SessionTimeout, timeout)).ConfigureAwait(false);

                // Validate that the message is not too large to send.  This is done after the link is created to ensure
                // that the maximum message size is known, as it is dictated by the service using the link.

                if (batchMessage.SerializedMessageSize > MaxMessageSize)
                {
                    throw new ServiceBusException(string.Format(Resources.MessageSizeExceeded, messageHash, batchMessage.SerializedMessageSize, MaxMessageSize, _entityPath), ServiceBusException.FailureReason.MessageSizeExceeded);
                }

                // Attempt to send the message batch.

                var     deliveryTag = new ArraySegment <byte>(BitConverter.GetBytes(Interlocked.Increment(ref _deliveryCount)));
                Outcome outcome     = await link.SendMessageAsync(
                    batchMessage,
                    deliveryTag,
                    transactionId, timeout.CalculateRemaining(stopWatch.Elapsed)).ConfigureAwait(false);

                cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>();

                if (outcome.DescriptorCode != Accepted.Code)
                {
                    throw (outcome as Rejected)?.Error.ToMessagingContractException();
                }

                cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>();
                stopWatch.Stop();
            }
        }
示例#12
0
        public void AmqpWebSocketTransportTest()
        {
            string queue = "AmqpWebSocketTransportTest";

            broker.AddQueue(queue);

            AmqpConnection connection = AmqpConnection.Factory.OpenConnectionAsync(
                TestAmqpBrokerFixture.WsAddress.OriginalString).GetAwaiter().GetResult();

            AmqpSession session = connection.CreateSession(new AmqpSessionSettings());

            session.Open();

            SendingAmqpLink sLink = new SendingAmqpLink(session, AmqpUtils.GetLinkSettings(true, queue, SettleMode.SettleOnSend));

            sLink.Open();

            int messageCount = 1800;

            for (int i = 0; i < messageCount; i++)
            {
                AmqpMessage message = AmqpMessage.Create(new AmqpValue()
                {
                    Value = "message" + i
                });
                sLink.SendMessageAsync(message, EmptyBinary, NullBinary, TimeSpan.FromSeconds(10)).Wait();
            }

            sLink.Close();

            ReceivingAmqpLink rLink = new ReceivingAmqpLink(session, AmqpUtils.GetLinkSettings(false, queue, SettleMode.SettleOnReceive, 100));

            rLink.Open();

            for (int i = 0; i < messageCount; i++)
            {
                AmqpMessage message2 = rLink.ReceiveMessageAsync(TimeSpan.FromSeconds(60)).GetAwaiter().GetResult();
                Assert.NotNull(message2);

                rLink.AcceptMessage(message2);
                message2.Dispose();
            }

            rLink.Close();

            connection.Close();
        }
示例#13
0
        public override async Task SendAsync(string deviceId, string moduleId, Message message)
        {
            if (string.IsNullOrWhiteSpace(deviceId))
            {
                throw new ArgumentException("Value should be non null and non empty", nameof(deviceId));
            }

            if (string.IsNullOrWhiteSpace(moduleId))
            {
                throw new ArgumentException("Value should be non null and non empty", nameof(moduleId));
            }

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

            Outcome outcome;

            using (AmqpMessage amqpMessage = message.ToAmqpMessage())
            {
                amqpMessage.Properties.To = "/devices/" + WebUtility.UrlEncode(deviceId) + "/modules/" + WebUtility.UrlEncode(moduleId) + "/messages/deviceBound";
                try
                {
                    SendingAmqpLink sendingLink = await this.GetSendingLinkAsync();

                    outcome = await sendingLink.SendMessageAsync(amqpMessage, IotHubConnection.GetNextDeliveryTag(ref this.sendingDeliveryTag), AmqpConstants.NullBinary, this.OperationTimeout);
                }
                catch (Exception exception)
                {
                    if (exception.IsFatal())
                    {
                        throw;
                    }

                    throw AmqpClientHelper.ToIotHubClientContract(exception);
                }
            }

            if (outcome.DescriptorCode != Accepted.Code)
            {
                throw AmqpErrorMapper.GetExceptionFromOutcome(outcome);
            }
        }
        private async Task <Outcome> SendAmqpMessageAsync(AmqpMessage amqpMessage, CancellationToken cancellationToken)
        {
            if (Logging.IsEnabled)
            {
                Logging.Enter(this, nameof(SendAmqpMessageAsync));
            }

            try
            {
                return(await _sendingAmqpLink
                       .SendMessageAsync(
                           amqpMessage,
                           new ArraySegment <byte>(Guid.NewGuid().ToByteArray()),
                           AmqpConstants.NullBinary,
                           cancellationToken)
                       .ConfigureAwait(false));
            }
            catch (Exception e) when(!e.IsFatal())
            {
                Exception ex = AmqpIotExceptionAdapter.ConvertToIotHubException(e, _sendingAmqpLink);

                if (ReferenceEquals(e, ex))
                {
                    throw;
                }
                else
                {
                    if (ex is AmqpIotResourceException)
                    {
                        _sendingAmqpLink.SafeClose();
                        throw new IotHubCommunicationException(ex.Message, ex);
                    }
                    throw ex;
                }
            }
            finally
            {
                if (Logging.IsEnabled)
                {
                    Logging.Exit(this, nameof(SendAmqpMessageAsync));
                }
            }
        }
示例#15
0
        /// <summary>
        ///    Sends a set of messages to the associated Queue/Topic using a batched approach.
        /// </summary>
        ///
        /// <param name="messageBatch"></param>
        /// <param name="timeout"></param>
        /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param>
        ///
        internal virtual async Task SendBatchInternalAsync(
            ServiceBusMessageBatch messageBatch,
            TimeSpan timeout,
            CancellationToken cancellationToken)
        {
            var stopWatch = Stopwatch.StartNew();

            AmqpMessage messageFactory() => AmqpMessageConverter.BatchSBMessagesAsAmqpMessage(messageBatch.AsEnumerable <ServiceBusMessage>());

            using (AmqpMessage batchMessage = messageFactory())
            {
                //ServiceBusEventSource.Log.SendStart(Entityname, messageHash);

                string messageHash = batchMessage.GetHashCode().ToString();

                SendingAmqpLink link = await _sendLink.GetOrCreateAsync(UseMinimum(_connectionScope.SessionTimeout, timeout)).ConfigureAwait(false);

                // Validate that the message is not too large to send.  This is done after the link is created to ensure
                // that the maximum message size is known, as it is dictated by the service using the link.

                if (batchMessage.SerializedMessageSize > MaximumMessageSize)
                {
                    throw new ServiceBusException(string.Format(Resources1.MessageSizeExceeded, messageHash, batchMessage.SerializedMessageSize, MaximumMessageSize, _entityName), ServiceBusException.FailureReason.MessageSizeExceeded);
                }

                // Attempt to send the message batch.

                var deliveryTag = new ArraySegment <byte>(BitConverter.GetBytes(Interlocked.Increment(ref _deliveryCount)));
                var outcome     = await link.SendMessageAsync(batchMessage, deliveryTag, AmqpConstants.NullBinary, timeout.CalculateRemaining(stopWatch.Elapsed)).ConfigureAwait(false);

                cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>();

                if (outcome.DescriptorCode != Accepted.Code)
                {
                    throw AmqpError.CreateExceptionForError((outcome as Rejected)?.Error, _entityName);
                }

                //ServiceBusEventSource.Log.SendStop(Entityname, messageHash);

                cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>();
                stopWatch.Stop();
            }
        }
        async Task RunClientAsync(string address)
        {
            AmqpConnectionFactory factory = new AmqpConnectionFactory();

            factory.Settings.TransportProviders.Add(
                new TlsTransportProvider(
                    new TlsTransportSettings()
            {
                CertificateValidationCallback = (a, b, c, d) => true
            },
                    AmqpVersion.V100));

            AmqpConnection connection = await factory.OpenConnectionAsync(address);

            AmqpSession session = connection.CreateSession(new AmqpSessionSettings());
            await session.OpenAsync(TimeSpan.FromSeconds(20));

            SendingAmqpLink sLink = new SendingAmqpLink(session, AmqpUtils.GetLinkSettings(true, queue, SettleMode.SettleOnSend));
            await sLink.OpenAsync(TimeSpan.FromSeconds(20));

            AmqpMessage message = AmqpMessage.Create(new AmqpValue()
            {
                Value = "AmqpConnectionFactoryTest"
            });
            Outcome outcome = await sLink.SendMessageAsync(message, EmptyBinary, NullBinary, TimeSpan.FromSeconds(10));

            Assert.Equal(Accepted.Code, outcome.DescriptorCode);

            ReceivingAmqpLink rLink = new ReceivingAmqpLink(session, AmqpUtils.GetLinkSettings(false, queue, SettleMode.SettleOnDispose, 10));
            await rLink.OpenAsync(TimeSpan.FromSeconds(20));

            var receivedMessage = await rLink.ReceiveMessageAsync(TimeSpan.FromSeconds(20));

            Assert.NotNull(receivedMessage);
            outcome = await rLink.DisposeMessageAsync(receivedMessage.DeliveryTag, new Accepted(), false, TimeSpan.FromSeconds(20));

            Assert.Equal(Accepted.Code, outcome.DescriptorCode);

            await connection.CloseAsync(TimeSpan.FromSeconds(20));
        }
        async Task <Outcome> SendAmqpMessageAsync(AmqpMessage amqpMessage)
        {
            Outcome outcome;

            try
            {
                SendingAmqpLink eventSendingLink = await this.GetEventSendingLinkAsync();

                outcome = await eventSendingLink.SendMessageAsync(amqpMessage, IotHubConnection.GetNextDeliveryTag(ref this.eventsDeliveryTag), AmqpConstants.NullBinary, this.OperationTimeout);
            }
            catch (Exception exception)
            {
                if (exception.IsFatal())
                {
                    throw;
                }

                throw AmqpClientHelper.ToIotHubClientContract(exception);
            }

            return(outcome);
        }
示例#18
0
        async Task <Outcome> SendAmqpMethodResponseAsync(AmqpMessage amqpMessage, CancellationToken cancellationToken)
        {
            Outcome outcome;

            try
            {
                SendingAmqpLink methodRespSendingLink = await this.GetMethodSendingLinkAsync(cancellationToken);

                outcome = await methodRespSendingLink.SendMessageAsync(amqpMessage, new ArraySegment <byte>(Guid.NewGuid().ToByteArray()), AmqpConstants.NullBinary, this.operationTimeout);
            }
            catch (Exception exception)
            {
                if (exception.IsFatal())
                {
                    throw;
                }

                throw AmqpClientHelper.ToIotHubClientContract(exception);
            }

            return(outcome);
        }
        async Task OnSendAsync(IList <Message> messageList)
        {
            TimeoutHelper timeoutHelper = new TimeoutHelper(this.OperationTimeout, true);

            using (AmqpMessage amqpMessage = AmqpMessageConverter.BatchSBMessagesAsAmqpMessage(messageList, true))
            {
                SendingAmqpLink amqpLink = null;
                try
                {
                    amqpLink = await this.SendLinkManager.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false);

                    if (amqpLink.Settings.MaxMessageSize.HasValue)
                    {
                        ulong size = (ulong)amqpMessage.SerializedMessageSize;
                        if (size > amqpLink.Settings.MaxMessageSize.Value)
                        {
                            // TODO: Add MessageSizeExceededException
                            throw new NotImplementedException("MessageSizeExceededException: " + Resources.AmqpMessageSizeExceeded.FormatForUser(amqpMessage.DeliveryId.Value, size, amqpLink.Settings.MaxMessageSize.Value));
                            ////throw Fx.Exception.AsError(new MessageSizeExceededException(
                            ////Resources.AmqpMessageSizeExceeded.FormatForUser(amqpMessage.DeliveryId.Value, size, amqpLink.Settings.MaxMessageSize.Value)));
                        }
                    }

                    Outcome outcome = await amqpLink.SendMessageAsync(amqpMessage, this.GetNextDeliveryTag(), AmqpConstants.NullBinary, timeoutHelper.RemainingTime()).ConfigureAwait(false);

                    if (outcome.DescriptorCode != Accepted.Code)
                    {
                        Rejected rejected = (Rejected)outcome;
                        throw Fx.Exception.AsError(AmqpExceptionHelper.ToMessagingContractException(rejected.Error));
                    }
                }
                catch (Exception exception)
                {
                    throw AmqpExceptionHelper.GetClientException(exception, amqpLink?.GetTrackingId());
                }
            }
        }
示例#20
0
        protected override async Task OnSendAsync(IEnumerable <EventData> eventDatas, string partitionKey)
        {
            bool shouldRetry;
            int  retryCount = 0;

            var timeoutHelper = new TimeoutHelper(EventHubClient.ConnectionStringBuilder.OperationTimeout, startTimeout: true);

            do
            {
                using (AmqpMessage amqpMessage = AmqpMessageConverter.EventDatasToAmqpMessage(eventDatas, partitionKey))
                {
                    shouldRetry = false;

                    try
                    {
                        try
                        {
                            // Always use default timeout for AMQP sesssion.
                            SendingAmqpLink amqpLink = await SendLinkManager.GetOrCreateAsync(
                                TimeSpan.FromSeconds(AmqpClientConstants.AmqpSessionTimeoutInSeconds)).ConfigureAwait(false);

                            if (amqpLink.Settings.MaxMessageSize.HasValue)
                            {
                                ulong size = (ulong)amqpMessage.SerializedMessageSize;
                                if (size > amqpLink.Settings.MaxMessageSize.Value)
                                {
                                    throw new MessageSizeExceededException(amqpMessage.DeliveryId.Value, size, amqpLink.Settings.MaxMessageSize.Value);
                                }
                            }

                            Outcome outcome = await amqpLink.SendMessageAsync(
                                amqpMessage,
                                GetNextDeliveryTag(),
                                AmqpConstants.NullBinary,
                                timeoutHelper.RemainingTime()).ConfigureAwait(false);

                            if (outcome.DescriptorCode != Accepted.Code)
                            {
                                Rejected rejected = (Rejected)outcome;
                                throw new AmqpException(rejected.Error);
                            }
                        }
                        catch (AmqpException amqpException)
                        {
                            throw AmqpExceptionHelper.ToMessagingContract(amqpException.Error);
                        }
                    }
                    catch (Exception ex)
                    {
                        // Evaluate retry condition?
                        TimeSpan?retryInterval = RetryPolicy.GetNextRetryInterval(ex, timeoutHelper.RemainingTime(), ++retryCount);
                        if (retryInterval != null && !EventHubClient.CloseCalled)
                        {
                            await Task.Delay(retryInterval.Value).ConfigureAwait(false);

                            shouldRetry = true;
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
            } while (shouldRetry);
        }
示例#21
0
文件: Sender.cs 项目: Bigsby/PoC
        static void Main(string[] args)
        {
            try
            {
                var connection = AmqpConnection.Factory.OpenConnectionAsync("amqp://localhost:5672").Result;

                var sessionSettings = new AmqpSessionSettings
                {
                };
                //AmqpSessionSettings.Create(new Begin())
                var session = connection.CreateSession(sessionSettings);

                var linkSettings = new AmqpLinkSettings
                {
                    LinkName = "theExchange",
                    Handle   = 1234,

                    Role   = false,
                    Target = new Target
                    {
                        Address = "theQueue",
                        Durable = 1
                    }
                };

                var sender = new SendingAmqpLink(session, linkSettings);
                session.Open();
                sender.Open();
                var key = ConsoleKey.A;
                var i   = 0;
                do
                {
                    Console.WriteLine("Press any key to send message");

                    var body    = "Hello, AMQP1.0!";
                    var message = AmqpMessage.Create(new AmqpValue()
                    {
                        Value = body
                    });
                    var tag     = new ArraySegment <byte>(BitConverter.GetBytes(i++));
                    var outcome = sender.SendMessageAsync(message, tag, AmqpConstants.NullBinary, TimeSpan.FromSeconds(3)).Result;

                    if (outcome.DescriptorCode == Accepted.Code)
                    {
                        Console.WriteLine(" [x] Sent {0}", body);
                    }
                    else
                    {
                        Console.WriteLine("Error sending message!");
                    }
                } while (key != ConsoleKey.Q);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
                throw;
            }

            Console.WriteLine(" Press [enter] to exit.");
            Console.ReadLine();
        }