/// <summary>
        /// Creates the transport message.
        /// </summary>
        /// <param name="basicProperties"></param>
        /// <param name="body"></param>
        /// <returns>the TransportMessage</returns>
        internal static TransportMessage CreateTransportMessage(IBasicProperties basicProperties, byte[] body)
        {
            string GetStringValue(KeyValuePair <string, object> kvp)
            {
                var headerValue = kvp.Value;

                if (headerValue is byte[] headerValueBytes)
                {
                    return(HeaderValueEncoding.GetString(headerValueBytes));
                }

                return(headerValue?.ToString());
            }

            var headers = basicProperties.Headers?.ToDictionary(kvp => kvp.Key, GetStringValue)
                          ?? new Dictionary <string, string>();

            if (!headers.ContainsKey(Headers.MessageId))
            {
                AddMessageId(headers, basicProperties, body);
            }

            if (basicProperties.IsUserIdPresent())
            {
                headers[RabbitMqHeaders.UserId] = basicProperties.UserId;
            }

            if (basicProperties.IsCorrelationIdPresent())
            {
                headers[RabbitMqHeaders.CorrelationId] = basicProperties.CorrelationId;
            }

            return(new TransportMessage(headers, body));
        }
        public void CopyFrom(IBasicProperties basicProperties)
        {
            Preconditions.CheckNotNull(basicProperties, "basicProperties");

            if (basicProperties.IsContentTypePresent())         ContentType         = basicProperties.ContentType;
            if (basicProperties.IsContentEncodingPresent())     ContentEncoding     = basicProperties.ContentEncoding;
            if (basicProperties.IsDeliveryModePresent())        DeliveryMode        = basicProperties.DeliveryMode;
            if (basicProperties.IsPriorityPresent())            Priority            = basicProperties.Priority;
            if (basicProperties.IsCorrelationIdPresent())       CorrelationId       = basicProperties.CorrelationId;
            if (basicProperties.IsReplyToPresent())             ReplyTo             = basicProperties.ReplyTo;
            if (basicProperties.IsExpirationPresent())          Expiration          = basicProperties.Expiration;
            if (basicProperties.IsMessageIdPresent())           MessageId           = basicProperties.MessageId;
            if (basicProperties.IsTimestampPresent())           Timestamp           = basicProperties.Timestamp.UnixTime;
            if (basicProperties.IsTypePresent())                Type                = basicProperties.Type;
            if (basicProperties.IsUserIdPresent())              UserId              = basicProperties.UserId;
            if (basicProperties.IsAppIdPresent())               AppId               = basicProperties.AppId;
            if (basicProperties.IsClusterIdPresent())           ClusterId           = basicProperties.ClusterId;

            if (basicProperties.IsHeadersPresent())
            {
                foreach (var header in basicProperties.Headers)
                {
                    Headers.Add(header.Key, header.Value);
                }
            }
        }
Example #3
0
 private void Inject(IBasicProperties msgProps, string id)
 {
     if (msgProps != null && !msgProps.IsCorrelationIdPresent())
     {
         msgProps.CorrelationId = id;
     }
 }
        internal static ReceivedMessage CreateFromEvent(BasicDeliverEventArgs eventArgs)
        {
            if (eventArgs == null)
            {
                return(null);
            }

            IBasicProperties properties = eventArgs.BasicProperties;

            ReceivedMessage message = null;

            switch (properties?.ContentType?.ToLower())
            {
            case ContentTypes.JSON:
                message = new JSONReceivedMessage();
                break;

            case ContentTypes.Binary:
                message = new BinaryReceivedMessage();
                break;

            default:
                message = new ReceivedMessage();
                break;
            }

            message.DeliveryTag     = eventArgs.DeliveryTag;
            message.Exchange        = eventArgs.Exchange;
            message.RoutingKey      = eventArgs.RoutingKey;
            message.Redelivered     = eventArgs.Redelivered;
            message.ContentType     = (properties?.IsContentTypePresent() ?? false) ? properties.ContentType : null;
            message.ContentEncoding = (properties?.IsContentEncodingPresent() ?? false) ? properties.ContentEncoding : null;

            message.ExpandBody(eventArgs.Body);

            if (properties == null)
            {
                return(message);
            }

            message.Type             = properties.IsTypePresent() ? properties.Type : null;
            message.Persistent       = properties.IsDeliveryModePresent() && properties.Persistent;
            message.ApplicationName  = properties.IsAppIdPresent() ? properties.AppId : null;
            message.ReplyToQueueName = properties.IsReplyToPresent() ? properties.ReplyTo : null;

            if (properties.IsMessageIdPresent() && Guid.TryParse(properties.MessageId, out Guid messageId))
            {
                message.MessageID = messageId;
            }

            if (properties.IsCorrelationIdPresent() && Guid.TryParse(properties.CorrelationId, out Guid correlationId))
            {
                message.CorrelationID = correlationId;
            }

            return(message);
        }
Example #5
0
            static Guid?TryGetFromCorrelationId(IBasicProperties basicProperties)
            {
                if (basicProperties.IsCorrelationIdPresent() &&
                    Guid.TryParse(basicProperties.CorrelationId, out var id) &&
                    id != Guid.Empty)
                {
                    return(id);
                }

                return(null);
            }
Example #6
0
        public BusMessage <T> ConstructMessage <T>(DataContractKey dataContractKey, IBasicProperties properties, T data)
        {
            BusMessage <T> message = new BusMessage <T>
            {
                Data  = data,
                BusId = properties.AppId,
                Sent  = properties.Timestamp.GetDateTime()
            };

            if (properties.IsCorrelationIdPresent())
            {
                message.CorrelationId = properties.CorrelationId;
            }

            ConstructHeaders(message, properties);

            return(message);
        }
Example #7
0
        public RawBusMessage ConstructMessage(DataContractKey dataContractKey, IBasicProperties properties, object data)
        {
            RawBusMessage message = new RawBusMessage
            {
                Data      = data,
                BusId     = properties.AppId,
                Sent      = properties.Timestamp.GetDateTime(),
                Name      = dataContractKey.Name,
                Namespace = dataContractKey.Ns
            };

            if (properties.IsCorrelationIdPresent())
            {
                message.CorrelationId = properties.CorrelationId;
            }

            ConstructHeaders(message, properties);

            return(message);
        }
Example #8
0
        public SerializedBusMessage ConstructMessage(DataContractKey dataContractKey, IBasicProperties properties, byte[] data)
        {
            SerializedBusMessage message = new SerializedBusMessage
            {
                Data        = data,
                BusId       = properties.AppId,
                Sent        = properties.Timestamp.GetDateTime(),
                Name        = dataContractKey.Name,
                Namespace   = dataContractKey.Ns,
                ContentType = properties.ContentType
            };

            if (properties.IsCorrelationIdPresent())
            {
                message.CorrelationId = properties.CorrelationId;
            }

            ConstructHeaders(message, properties);

            return(message);
        }
Example #9
0
        public static Activity ExtractActivity(this IBasicProperties msgProps, string activityName = null)
        {
            if (msgProps == null)
            {
                throw new ArgumentNullException(nameof(msgProps));
            }

            if (activityName == null)
            {
                activityName = RabbitMQDiagnosticsSource.ProcessActivityName;
            }

            var activity = new Activity(activityName);

            if (msgProps.IsCorrelationIdPresent())
            {
                activity.SetParentId(msgProps.CorrelationId);
            }

            return(activity);
        }
        public MessageBasicProperties(IBasicProperties basicProperties)
            : this()
        {
            ContentTypePresent = basicProperties.IsContentTypePresent();
            ContentEncodingPresent = basicProperties.IsContentEncodingPresent();
            HeadersPresent = basicProperties.IsHeadersPresent();
            DeliveryModePresent = basicProperties.IsDeliveryModePresent();
            PriorityPresent = basicProperties.IsPriorityPresent();
            CorrelationIdPresent = basicProperties.IsCorrelationIdPresent();
            ReplyToPresent = basicProperties.IsReplyToPresent();
            ExpirationPresent = basicProperties.IsExpirationPresent();
            MessageIdPresent = basicProperties.IsMessageIdPresent();
            TimestampPresent = basicProperties.IsTimestampPresent();
            TypePresent = basicProperties.IsTypePresent();
            UserIdPresent = basicProperties.IsUserIdPresent();
            AppIdPresent = basicProperties.IsAppIdPresent();
            ClusterIdPresent = basicProperties.IsClusterIdPresent();

            ContentType = basicProperties.ContentType;
            ContentEncoding = basicProperties.ContentEncoding;
            DeliveryMode = basicProperties.DeliveryMode;
            Priority = basicProperties.Priority;
            CorrelationId = basicProperties.CorrelationId;
            ReplyTo = basicProperties.ReplyTo;
            Expiration = basicProperties.Expiration;
            MessageId = basicProperties.MessageId;
            Timestamp = basicProperties.Timestamp.UnixTime;
            Type = basicProperties.Type;
            UserId = basicProperties.UserId;
            AppId = basicProperties.AppId;
            ClusterId = basicProperties.ClusterId;

            if(basicProperties.IsHeadersPresent())
            {
                foreach (DictionaryEntry header in basicProperties.Headers)
                {
                    Headers.Add(header.Key, header.Value);
                }
            }
        }
        public void CopyFrom(IBasicProperties basicProperties)
        {
            ContentTypePresent     = basicProperties.IsContentTypePresent();
            ContentEncodingPresent = basicProperties.IsContentEncodingPresent();
            HeadersPresent         = basicProperties.IsHeadersPresent();
            DeliveryModePresent    = basicProperties.IsDeliveryModePresent();
            PriorityPresent        = basicProperties.IsPriorityPresent();
            CorrelationIdPresent   = basicProperties.IsCorrelationIdPresent();
            ReplyToPresent         = basicProperties.IsReplyToPresent();
            ExpirationPresent      = basicProperties.IsExpirationPresent();
            MessageIdPresent       = basicProperties.IsMessageIdPresent();
            TimestampPresent       = basicProperties.IsTimestampPresent();
            TypePresent            = basicProperties.IsTypePresent();
            UserIdPresent          = basicProperties.IsUserIdPresent();
            AppIdPresent           = basicProperties.IsAppIdPresent();
            ClusterIdPresent       = basicProperties.IsClusterIdPresent();

            ContentType     = basicProperties.ContentType;
            ContentEncoding = basicProperties.ContentEncoding;
            DeliveryMode    = basicProperties.DeliveryMode;
            Priority        = basicProperties.Priority;
            CorrelationId   = basicProperties.CorrelationId;
            ReplyTo         = basicProperties.ReplyTo;
            Expiration      = basicProperties.Expiration;
            MessageId       = basicProperties.MessageId;
            Timestamp       = basicProperties.Timestamp.UnixTime;
            Type            = basicProperties.Type;
            UserId          = basicProperties.UserId;
            AppId           = basicProperties.AppId;
            ClusterId       = basicProperties.ClusterId;

            if (basicProperties.IsHeadersPresent())
            {
                foreach (DictionaryEntry header in basicProperties.Headers)
                {
                    Headers.Add(header.Key, header.Value);
                }
            }
        }
Example #12
0
        public override Task HandleBasicDeliver(string consumerTag, ulong deliveryTag, bool redelivered, string exchange, string routingKey, IBasicProperties properties, byte[] body)
        {
            if (!properties.IsCorrelationIdPresent())
            {
                return(Task.FromResult(0));
            }

            CallbackInfo info;

            if (_callbacksDictionary.TryRemove(properties.CorrelationId, out info))
            {
                var rejectHeader =
                    properties.Headers.Where(pair => pair.Key == RejectedHeader.WellknownName)
                    .Select(pair => pair.Value)
                    .FirstOrDefault();

                var exceptionHeader =
                    properties.Headers.Where(pair => pair.Key == ExceptionHeader.WellknownName)
                    .Select(pair => pair.Value)
                    .FirstOrDefault();

                if (exceptionHeader != null)
                {
                    info.SetResponse(null, new RpcCallException(RpcFailureReason.HandlerError, exceptionHeader.ToString()));

                    return(Task.FromResult(0));
                }

                DataContractKey dataContractKey;
                object          data;

                if (body.Length == 0 || info.ReplyType == null)
                {
                    // Reject without data
                    if (rejectHeader != null)
                    {
                        info.SetResponse(null, new RpcCallException(RpcFailureReason.Reject));

                        return(Task.FromResult(0));
                    }

                    // Void reply or sender not interested in reply data, but only interested to be notified that work is done
                    dataContractKey = DataContractKey.Void;
                    data            = null;
                }
                else
                {
                    dataContractKey = properties.GetDataContractKey();

                    if (!_serializers.ContainsKey(properties.ContentType))
                    {
                        info.SetResponse(null,
                                         new RpcCallException(RpcFailureReason.SerializationError,
                                                              string.Format("Unsupported content type {0}", properties.ContentType)));

                        return(Task.FromResult(0));
                    }

                    try
                    {
                        ISerializer serializer = _serializers[properties.ContentType];

                        if (dataContractKey.Equals(DataContractKey.BinaryBlob))
                        {
                            data = body;
                        }
                        else
                        {
                            data = serializer.Deserialize(info.ReplyType, body);
                        }
                    }
                    catch (Exception ex)
                    {
                        info.SetResponse(null, new RpcCallException(RpcFailureReason.SerializationError, ex));

                        return(Task.FromResult(0));
                    }
                }

                // Reject with data
                if (rejectHeader != null)
                {
                    info.SetResponse(null, new RpcCallException(RpcFailureReason.Reject, data));

                    return(Task.FromResult(0));
                }

                RawBusMessage message = _messageHelper.ConstructMessage(dataContractKey, properties, data);

                _trace.MessageArrived(_busId, message, ConsumerTag);

                info.SetResponse(message, null);

                info.RegisteredHandle.Unregister(info.WaitHandle);
            }

            return(Task.FromResult(0));
        }
Example #13
0
        public static void CopyTo(this IBasicProperties basicProperties, MessageProperties messageProperties)
        {
            if (basicProperties.IsContentTypePresent())
            {
                messageProperties.ContentType = basicProperties.ContentType;
            }
            if (basicProperties.IsContentEncodingPresent())
            {
                messageProperties.ContentEncoding = basicProperties.ContentEncoding;
            }
            if (basicProperties.IsDeliveryModePresent())
            {
                messageProperties.DeliveryMode = basicProperties.DeliveryMode;
            }
            if (basicProperties.IsPriorityPresent())
            {
                messageProperties.Priority = basicProperties.Priority;
            }
            if (basicProperties.IsCorrelationIdPresent())
            {
                messageProperties.CorrelationId = basicProperties.CorrelationId;
            }
            if (basicProperties.IsReplyToPresent())
            {
                messageProperties.ReplyTo = basicProperties.ReplyTo;
            }
            if (basicProperties.IsExpirationPresent())
            {
                messageProperties.Expiration = basicProperties.Expiration;
            }
            if (basicProperties.IsMessageIdPresent())
            {
                messageProperties.MessageId = basicProperties.MessageId;
            }
            if (basicProperties.IsTimestampPresent())
            {
                messageProperties.Timestamp = basicProperties.Timestamp.UnixTime;
            }
            if (basicProperties.IsTypePresent())
            {
                messageProperties.Type = basicProperties.Type;
            }
            if (basicProperties.IsUserIdPresent())
            {
                messageProperties.UserId = basicProperties.UserId;
            }
            if (basicProperties.IsAppIdPresent())
            {
                messageProperties.AppId = basicProperties.AppId;
            }
            if (basicProperties.IsClusterIdPresent())
            {
                messageProperties.ClusterId = basicProperties.ClusterId;
            }

            if (basicProperties.IsHeadersPresent())
            {
                foreach (DictionaryEntry header in basicProperties.Headers)
                {
                    messageProperties.Headers.Add(header.Key, header.Value);
                }
            }
        }
Example #14
0
        /// <summary>
        ///     Converts IBasicProperties to a string
        /// </summary>
        /// <param name="extendedObject">objected being extended</param>
        /// <returns>formatted string of IBasicProperties</returns>
        public static string ToFormatString(this IBasicProperties extendedObject)
        {
            Arguments.NotNull(extendedObject, nameof(extendedObject));

            var sb = new StringBuilder();

            if (extendedObject.IsAppIdPresent())
            {
                sb.AppendFormat(CultureInfo.InvariantCulture, "AppID:{0} ", extendedObject.AppId);
            }

            if (extendedObject.IsClusterIdPresent())
            {
                sb.AppendFormat(CultureInfo.InvariantCulture, "ClusterId:{0} ", extendedObject.ClusterId);
            }

            if (extendedObject.IsContentEncodingPresent())
            {
                sb.AppendFormat(CultureInfo.InvariantCulture, "ContentEncoding:{0} ", extendedObject.ContentEncoding);
            }

            if (extendedObject.IsContentTypePresent())
            {
                sb.AppendFormat(CultureInfo.InvariantCulture, "ContentType:{0} ", extendedObject.ContentType);
            }

            if (extendedObject.IsCorrelationIdPresent())
            {
                sb.AppendFormat(CultureInfo.InvariantCulture, "CorrelationId:{0} ", extendedObject.CorrelationId);
            }

            if (extendedObject.IsDeliveryModePresent())
            {
                sb.AppendFormat(CultureInfo.InvariantCulture, "DeliveryMode:{0} ", extendedObject.DeliveryMode);
            }

            if (extendedObject.IsExpirationPresent())
            {
                sb.AppendFormat(CultureInfo.InvariantCulture, "Expiration:{0} ", extendedObject.Expiration);
            }

            if (extendedObject.IsHeadersPresent())
            {
                sb.AppendFormat(CultureInfo.InvariantCulture, "Headers:{0} ", extendedObject.Headers.StringFormat());
            }

            if (extendedObject.IsMessageIdPresent())
            {
                sb.AppendFormat(CultureInfo.InvariantCulture, "MessageId:{0} ", extendedObject.MessageId);
            }

            if (extendedObject.IsPriorityPresent())
            {
                sb.AppendFormat(CultureInfo.InvariantCulture, "Priority:{0} ", extendedObject.Priority);
            }

            if (extendedObject.IsReplyToPresent())
            {
                sb.AppendFormat(CultureInfo.InvariantCulture, "ReplyTo:{0} ", extendedObject.ReplyTo);
            }

            if (extendedObject.IsTimestampPresent())
            {
                sb.AppendFormat(CultureInfo.InvariantCulture, "Timestamp:{0} ", extendedObject.Timestamp);
            }

            if (extendedObject.IsTypePresent())
            {
                sb.AppendFormat(CultureInfo.InvariantCulture, "Type:{0} ", extendedObject.Type);
            }

            if (extendedObject.IsUserIdPresent())
            {
                sb.AppendFormat(CultureInfo.InvariantCulture, "UserId:{0} ", extendedObject.UserId);
            }

            return(sb.ToString());
        }
Example #15
0
        /// <summary>
        ///     Copies IBasicProperties to MessageProperties
        /// </summary>
        public void CopyFrom(IBasicProperties basicProperties)
        {
            Preconditions.CheckNotNull(basicProperties, "basicProperties");

            if (basicProperties.IsContentTypePresent())
            {
                ContentType = basicProperties.ContentType;
            }
            if (basicProperties.IsContentEncodingPresent())
            {
                ContentEncoding = basicProperties.ContentEncoding;
            }
            if (basicProperties.IsDeliveryModePresent())
            {
                DeliveryMode = basicProperties.DeliveryMode;
            }
            if (basicProperties.IsPriorityPresent())
            {
                Priority = basicProperties.Priority;
            }
            if (basicProperties.IsCorrelationIdPresent())
            {
                CorrelationId = basicProperties.CorrelationId;
            }
            if (basicProperties.IsReplyToPresent())
            {
                ReplyTo = basicProperties.ReplyTo;
            }
            if (basicProperties.IsExpirationPresent())
            {
                Expiration = basicProperties.Expiration;
            }
            if (basicProperties.IsMessageIdPresent())
            {
                MessageId = basicProperties.MessageId;
            }
            if (basicProperties.IsTimestampPresent())
            {
                Timestamp = basicProperties.Timestamp.UnixTime;
            }
            if (basicProperties.IsTypePresent())
            {
                Type = basicProperties.Type;
            }
            if (basicProperties.IsUserIdPresent())
            {
                UserId = basicProperties.UserId;
            }
            if (basicProperties.IsAppIdPresent())
            {
                AppId = basicProperties.AppId;
            }
            if (basicProperties.IsClusterIdPresent())
            {
                ClusterId = basicProperties.ClusterId;
            }

            if (basicProperties.IsHeadersPresent())
            {
                Headers = basicProperties.Headers == null || basicProperties.Headers.Count == 0
                    ? null
                    : new Dictionary <string, object>(basicProperties.Headers);
            }
        }
Example #16
0
        public void CopyFrom(IBasicProperties basicProperties)
        {
            GuardHelper.ArgumentNotNull(() => basicProperties);

            if (basicProperties.IsContentTypePresent())
            {
                ContentType = basicProperties.ContentType;
            }
            if (basicProperties.IsContentEncodingPresent())
            {
                ContentEncoding = basicProperties.ContentEncoding;
            }
            if (basicProperties.IsDeliveryModePresent())
            {
                DeliveryMode = basicProperties.DeliveryMode;
            }
            if (basicProperties.IsPriorityPresent())
            {
                Priority = basicProperties.Priority;
            }
            if (basicProperties.IsCorrelationIdPresent())
            {
                CorrelationId = basicProperties.CorrelationId;
            }
            if (basicProperties.IsReplyToPresent())
            {
                ReplyTo = basicProperties.ReplyTo;
            }
            if (basicProperties.IsExpirationPresent())
            {
                Expiration = basicProperties.Expiration;
            }
            if (basicProperties.IsMessageIdPresent())
            {
                MessageId = basicProperties.MessageId;
            }
            if (basicProperties.IsTimestampPresent())
            {
                Timestamp = basicProperties.Timestamp.UnixTime;
            }
            if (basicProperties.IsTypePresent())
            {
                Type = basicProperties.Type;
            }
            if (basicProperties.IsUserIdPresent())
            {
                UserId = basicProperties.UserId;
            }
            if (basicProperties.IsAppIdPresent())
            {
                AppId = basicProperties.AppId;
            }
            if (basicProperties.IsClusterIdPresent())
            {
                ClusterId = basicProperties.ClusterId;
            }

            if (basicProperties.IsHeadersPresent())
            {
                foreach (var header in basicProperties.Headers)
                {
                    Headers.Add(header.Key, header.Value);
                }
            }
        }
Example #17
0
        public override void HandleBasicDeliver(string consumerTag, ulong deliveryTag, bool redelivered, string exchange, string routingKey, IBasicProperties properties, byte[] body)
        {
            if (!properties.IsCorrelationIdPresent())
            {
                return;
            }

            CallbackInfo info;

            if (_callbacksDictionary.TryRemove(properties.CorrelationId, out info))
            {
                var rejectHeader =
                    properties.Headers.Where(pair => pair.Key == RejectedHeader.WellknownName)
                        .Select(pair => pair.Value)
                        .FirstOrDefault();

                var exceptionHeader =
                    properties.Headers.Where(pair => pair.Key == ExceptionHeader.WellknownName)
                        .Select(pair => pair.Value)
                        .FirstOrDefault();

                if (exceptionHeader != null)
                {
                    info.SetResponse(null, new RpcCallException(RpcFailureReason.HandlerError, exceptionHeader.ToString()));

                    return;
                }

                DataContractKey dataContractKey;
                object data;

                if (body.Length == 0 || info.ReplyType == null)
                {
                    // Reject without data
                    if (rejectHeader != null)
                    {
                        info.SetResponse(null, new RpcCallException(RpcFailureReason.Reject));

                        return;
                    }

                    // Void reply or sender not interested in reply data, but only interested to be notified that work is done
                    dataContractKey = DataContractKey.Void;
                    data = null;
                }
                else
                {
                    dataContractKey = properties.GetDataContractKey();

                    if (!_serializers.ContainsKey(properties.ContentType))
                    {
                        info.SetResponse(null,
                            new RpcCallException(RpcFailureReason.SerializationError,
                                string.Format("Unsupported content type {0}", properties.ContentType)));

                        return;
                    }

                    try
                    {
                        ISerializer serializer = _serializers[properties.ContentType];

                        data = serializer.Deserialize(dataContractKey, info.ReplyType, body);
                    }
                    catch (Exception ex)
                    {
                        info.SetResponse(null, new RpcCallException(RpcFailureReason.SerializationError, ex));

                        return;
                    }
                }

                // Reject with data
                if (rejectHeader != null)
                {
                    info.SetResponse(null, new RpcCallException(RpcFailureReason.Reject, data));

                    return;
                }

                RawBusMessage message = _messageHelper.ConstructMessage(dataContractKey, properties, data);

                _trace.MessageArrived(_busId, message, ConsumerTag);

                info.SetResponse(message, null);

                info.RegisteredHandle.Unregister(info.WaitHandle);
            }
        }
Example #18
0
        protected virtual async Task <bool> ConsumeMessage(bool redelivered, ulong deliveryTag, IBasicProperties properties, byte[] body)
        {
            DataContractKey dataContractKey = properties.GetDataContractKey();

            var subscription =
                _subscriptions.Where(p => p.Value.FilterInfo.ContractKey.Equals(dataContractKey)).Select(
                    pair =>
                    new
            {
                DataType = pair.Key,
                pair.Value.Handler
            }).FirstOrDefault();

            if (subscription == null)
            {
                RawBusMessage rawBusMessage = _messageHelper.ConstructMessage(dataContractKey, properties, (object)body);

                _errorSubscriber.UnregisteredMessageArrived(rawBusMessage);

                return(false);
            }

            object data;

            if (!_serializers.ContainsKey(properties.ContentType))
            {
                RawBusMessage rawBusMessage = _messageHelper.ConstructMessage(dataContractKey, properties, (object)body);

                _errorSubscriber.MessageDeserializeException(rawBusMessage, new Exception("Unsupported content type"));

                return(false);
            }

            ISerializer serializer;

            try
            {
                serializer = _serializers[properties.ContentType];

                if (dataContractKey.Equals(DataContractKey.BinaryBlob))
                {
                    data = body;
                }
                else
                {
                    data = serializer.Deserialize(subscription.DataType, body);
                }
            }
            catch (Exception ex)
            {
                RawBusMessage rawBusMessage = _messageHelper.ConstructMessage(dataContractKey, properties, (object)body);

                _errorSubscriber.MessageDeserializeException(rawBusMessage, ex);

                return(false);
            }

            RawBusMessage message = _messageHelper.ConstructMessage(dataContractKey, properties, data);

            if (!_receiveSelfPublish && _busId.Equals(message.BusId))
            {
                _errorSubscriber.MessageFilteredOut(message);

                return(false);
            }

            _trace.MessageArrived(_busId, message, ConsumerTag);

            RawBusMessage reply;

            try
            {
                reply = await HandleMessage(subscription.Handler, message, redelivered, deliveryTag);
            }
            catch (RejectMessageException ex)
            {
                reply = new RawBusMessage
                {
                    Data = ex.ReplyData
                };

                reply.Headers.Add(new RejectedHeader());
            }
            catch (Exception ex)
            {
                _errorSubscriber.MessageDispatchException(message, ex);

                reply = new RawBusMessage();

                reply.Headers.Add(new ExceptionHeader
                {
                    Message = ex.Message
                });
            }

            if (!_neverReply && reply != null && properties.IsReplyToPresent())
            {
                var sendParams = new SendParams
                {
                    BusId              = _busId,
                    Model              = Model,
                    CorrelationId      = properties.IsCorrelationIdPresent() ? properties.CorrelationId : "",
                    Exchange           = _replyExchange,
                    RoutingKey         = properties.ReplyTo,
                    MandatoryDelivery  = false,
                    PersistentDelivery = false
                };

                _sendHelper.Send(reply, serializer, sendParams);

                _trace.MessageSent(_busId, reply);
            }

            return(true);
        }
        internal void CopyFrom(IBasicProperties from)
        {
            if (from == null)
                throw new ArgumentNullException(nameof(from));

            if (from.IsAppIdPresent()) AppId = from.AppId;
            if (from.IsClusterIdPresent()) ClusterId = from.ClusterId;
            if (from.IsContentEncodingPresent()) ContentEncoding = from.ContentEncoding;
            if (from.IsContentTypePresent()) ContentType = from.ContentType;
            if (from.IsCorrelationIdPresent()) CorrelationId = from.CorrelationId;
            if (from.IsDeliveryModePresent()) DeliveryMode = (LinkMessageDeliveryMode) from.DeliveryMode;
            if (from.IsReplyToPresent()) ReplyTo = from.ReplyTo;
            if (from.IsExpirationPresent()) Expiration = TimeSpan.FromMilliseconds(int.Parse(from.Expiration));
            if (from.IsMessageIdPresent()) MessageId = from.MessageId;
            if (from.IsTimestampPresent()) TimeStamp = from.Timestamp.UnixTime;
            if (from.IsTypePresent()) Type = from.Type;
            if (from.IsUserIdPresent()) UserId = from.UserId;
            if (from.IsPriorityPresent()) Priority = from.Priority;

            if (from.IsHeadersPresent())
            {
                foreach (var header in from.Headers)
                {
                    Headers[header.Key] = header.Value;
                }
            }
        }
Example #20
0
        protected virtual async Task<bool> ConsumeMessage(bool redelivered, ulong deliveryTag, IBasicProperties properties, byte[] body)
        {
            DataContractKey dataContractKey = properties.GetDataContractKey();

            var subscription =
                _subscriptions.Where(p => p.Value.FilterInfo.ContractKey.Equals(dataContractKey)).Select(
                    pair =>
                        new
                        {
                            DataType = pair.Key,
                            pair.Value.Handler
                        }).FirstOrDefault();

            if (subscription == null)
            {
                 RawBusMessage rawBusMessage = _messageHelper.ConstructMessage(dataContractKey, properties, (object)body);

                _errorSubscriber.UnregisteredMessageArrived(rawBusMessage);

                return false;
            }

            object data;

            if (!_serializers.ContainsKey(properties.ContentType))
            {
                RawBusMessage rawBusMessage = _messageHelper.ConstructMessage(dataContractKey, properties, (object)body);

                _errorSubscriber.MessageDeserializeException(rawBusMessage, new Exception("Unsupported content type"));

                return false;
            }

            ISerializer serializer;
            
            try
            {
                serializer = _serializers[properties.ContentType];
                
                data = serializer.Deserialize(dataContractKey, subscription.DataType, body);
            }
            catch (Exception ex)
            {
                RawBusMessage rawBusMessage = _messageHelper.ConstructMessage(dataContractKey, properties, (object)body);

                _errorSubscriber.MessageDeserializeException(rawBusMessage, ex);

                return false;
            }
            
            RawBusMessage message = _messageHelper.ConstructMessage(dataContractKey, properties, data);

            if (!_receiveSelfPublish && _busId.Equals(message.BusId))
            {
                _errorSubscriber.MessageFilteredOut(message);

                return false;
            }

            _trace.MessageArrived(_busId, message, ConsumerTag);

            RawBusMessage reply;

            try
            {
                reply = await HandleMessage(subscription.Handler, message, redelivered, deliveryTag);
            }
            catch (RejectMessageException ex)
            {
                reply = new RawBusMessage
                {
                    Data = ex.ReplyData
                };
                
                reply.Headers.Add(new RejectedHeader());
            }
            catch (Exception ex)
            {
                _errorSubscriber.MessageDispatchException(message, ex);

                reply = new RawBusMessage();

                reply.Headers.Add(new ExceptionHeader
                {
                    Message = ex.Message
                });
            }

            if (!_neverReply && reply != null && properties.IsReplyToPresent())
            {
                _sendHelper.Send(new SendParams
                {
                    BusId = _busId,
                    BusMessage = reply,
                    Model = Model,
                    CorrelationId = properties.IsCorrelationIdPresent() ? properties.CorrelationId : "",
                    Exchange = _replyExchange,
                    RoutingKey = properties.ReplyTo,
                    Serializer = serializer,
                    MandatoryDelivery = false,
                    PersistentDelivery = false
                });

                _trace.MessageSent(_busId, reply);
            }

            return true;
        }
Example #21
0
            public EasyNetQMessageProperties(IBasicProperties basicProperties) : this()
            {
                if (basicProperties.IsContentTypePresent())
                {
                    ContentType = basicProperties.ContentType;
                }
                if (basicProperties.IsContentEncodingPresent())
                {
                    ContentEncoding = basicProperties.ContentEncoding;
                }
                if (basicProperties.IsDeliveryModePresent())
                {
                    DeliveryMode = basicProperties.DeliveryMode;
                }
                if (basicProperties.IsPriorityPresent())
                {
                    Priority = basicProperties.Priority;
                }
                if (basicProperties.IsCorrelationIdPresent())
                {
                    CorrelationId = basicProperties.CorrelationId;
                }
                if (basicProperties.IsReplyToPresent())
                {
                    ReplyTo = basicProperties.ReplyTo;
                }
                if (basicProperties.IsExpirationPresent())
                {
                    Expiration = basicProperties.Expiration;
                }
                if (basicProperties.IsMessageIdPresent())
                {
                    MessageId = basicProperties.MessageId;
                }
                if (basicProperties.IsTimestampPresent())
                {
                    Timestamp = basicProperties.Timestamp.UnixTime;
                }
                if (basicProperties.IsTypePresent())
                {
                    Type = basicProperties.Type;
                }
                if (basicProperties.IsUserIdPresent())
                {
                    UserId = basicProperties.UserId;
                }
                if (basicProperties.IsAppIdPresent())
                {
                    AppId = basicProperties.AppId;
                }
                if (basicProperties.IsClusterIdPresent())
                {
                    ClusterId = basicProperties.ClusterId;
                }

                if (!basicProperties.IsHeadersPresent())
                {
                    return;
                }

                foreach (var(key, value) in basicProperties.Headers)
                {
                    Headers.Add(key, (byte[])value);
                }
            }