示例#1
0
        public IEnumerable <KeyValuePair <string, object> > GetAll()
        {
            if (_basicProperties.IsHeadersPresent())
            {
                return(_basicProperties.Headers);
            }

            return(Enumerable.Empty <KeyValuePair <string, object> >());
        }
示例#2
0
            public SerializableMessageProperties(IBasicProperties fromProperties)
            {
                AppId           = fromProperties.AppId;
                ClusterId       = fromProperties.ClusterId;
                ContentEncoding = fromProperties.ContentEncoding;
                ContentType     = fromProperties.ContentType;
                CorrelationId   = fromProperties.CorrelationId;
                DeliveryMode    = fromProperties.IsDeliveryModePresent() ? (byte?)fromProperties.DeliveryMode : null;
                Expiration      = fromProperties.Expiration;
                MessageId       = fromProperties.MessageId;
                Priority        = fromProperties.IsPriorityPresent() ? (byte?)fromProperties.Priority : null;
                ReplyTo         = fromProperties.ReplyTo;
                Timestamp       = fromProperties.IsTimestampPresent() ? (long?)fromProperties.Timestamp.UnixTime : null;
                Type            = fromProperties.Type;
                UserId          = fromProperties.UserId;

                if (fromProperties.IsHeadersPresent())
                {
                    Headers = new Dictionary <string, string>();

                    // This assumes header values are UTF-8 encoded strings. This is true for Tapeti.
                    foreach (var(key, value) in fromProperties.Headers)
                    {
                        Headers.Add(key, Encoding.UTF8.GetString((byte[])value));
                    }
                }
                else
                {
                    Headers = null;
                }
            }
示例#3
0
        public BasicPropertiesWrapper(IBasicProperties basicProperties)
        {
            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())
            {
                Headers = new HybridDictionary();
                foreach (DictionaryEntry header in basicProperties.Headers)
                {
                    Headers.Add(header.Key, header.Value);
                }
            }
        }
示例#4
0
        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);
                }
            }
        }
        private static Dictionary <string, string> GetResponseHeaderDictionary(IBasicProperties basicProperties)
        {
            if (basicProperties == null)
            {
                return(null);
            }

            var allHeaders = new Dictionary <string, string>()
            {
                { HEADER_APPID, basicProperties.AppId },
                { HEADER_CLUSTERID, basicProperties.ClusterId },
                { HEADER_CONTENTENCODING, basicProperties.ContentEncoding },
                { HEADER_CONTENTTYPE, basicProperties.ContentType },
                { HEADER_CORRELATIONID, basicProperties.CorrelationId },
                { HEADER_EXPIRATION, basicProperties.Expiration },
                { HEADER_MESSAGEID, basicProperties.MessageId }
            }
            .Where(h => h.Value != null)
            .ToDictionary(h => h.Key, h => h.Value);

            if (basicProperties.IsHeadersPresent())
            {
                basicProperties.Headers.ToList().ForEach(x => allHeaders[x.Key] = Encoding.UTF8.GetString(x.Value as byte[]));
            }

            return(allHeaders);
        }
示例#6
0
        private static string WriteBasicProperties(IBasicProperties props)
        {
            if (props == null)
            {
                return(string.Empty);
            }

            var sb = new StringBuilder();

            //{:content_type=>"application/json", :headers=> {"validatedUtcTimestamp"=>1542078341898, "receivedUtcTimestamp"=>1542078341892, "respondedUtcTimestamp"=>1542078341908, "_uid_"=>"b6a6e220-2cd3-4d8e-99b9-684c1bc66a13", "Content-Type"=>"application/json"}, :delivery_mode => 1, :priority => 0, :correlation_id => "j9501f21e-6264-44b1-a83d-6689303c4e31"}
            sb.Append("ContentType=").Append(props.ContentType);
            if (props.IsHeadersPresent())
            {
                sb.Append(", Headers={").Append(string.Join(", ", props.Headers.Select(s => $"{s.Key}={WriteHeaderValue(s.Value)}"))).Append("}");
            }
            sb.Append(", DeliveryMode=").Append(props.DeliveryMode);
            sb.Append(", Priority=").Append(props.Priority);
            sb.Append(", CorrelationId=").Append(props.CorrelationId);
            if (props.IsTimestampPresent())
            {
                sb.Append(", Timestamp=").Append(props.Timestamp.UnixTime);
            }

            return(sb.ToString());
        }
示例#7
0
        public void FulfillBasicProperties(IBasicProperties basicProperties)
        {
            if (IsHeadersPresent())
            {
                if (basicProperties.IsHeadersPresent())
                {
                    if (basicProperties.Headers == null)
                    {
                        basicProperties.Headers = this.Headers;
                    }
                    else
                    {
                        foreach (var item in this.Headers)
                        {
                            basicProperties.Headers[item.Key] = item.Value;
                        }
                    }
                }
                else
                {
                    basicProperties.Headers = this.Headers;
                }
            }

            if (IsPersistentPresent())
            {
                basicProperties.Persistent = this.Persistent;
            }
        }
示例#8
0
        public BasicPropertiesWrapper(IBasicProperties basicProperties)
        {
            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())
            {
                Headers = new Dictionary <string, object>();
                foreach (var header in basicProperties.Headers)
                {
                    Headers.Add(header.Key, header.Value);
                }
            }
        }
示例#9
0
        public void SetPublishTag(ulong publishTag)
        {
            PublishTag = publishTag;

            if (_properties.IsHeadersPresent())
            {
                _properties.Headers["publishId"] = publishTag.ToString("F0");
            }
        }
示例#10
0
        // A basic implementation of publishing batches but using the ChannelPool. If message properties is null, one is created and all messages are set to persistent.
        public async Task <bool> PublishBatchAsync(
            string exchangeName,
            string routingKey,
            IList <ReadOnlyMemory <byte> > payloads,
            bool mandatory = false,
            IBasicProperties messageProperties = null)
        {
            Guard.AgainstBothNullOrEmpty(exchangeName, nameof(exchangeName), routingKey, nameof(routingKey));
            Guard.AgainstNullOrEmpty(payloads, nameof(payloads));

            var error       = false;
            var channelHost = await _channelPool.GetChannelAsync().ConfigureAwait(false);

            if (messageProperties == null)
            {
                messageProperties = channelHost.GetChannel().CreateBasicProperties();
                messageProperties.DeliveryMode = 2;
                messageProperties.MessageId    = Guid.NewGuid().ToString();

                if (!messageProperties.IsHeadersPresent())
                {
                    messageProperties.Headers = new Dictionary <string, object>();
                }
            }

            // Non-optional Header.
            messageProperties.Headers[Constants.HeaderForObjectType] = Constants.HeaderValueForMessage;

            try
            {
                var batch = channelHost.GetChannel().CreateBasicPublishBatch();

                for (int i = 0; i < payloads.Count; i++)
                {
                    batch.Add(exchangeName, routingKey, mandatory, messageProperties, payloads[i]);
                }

                batch.Publish();
            }
            catch (Exception ex)
            {
                _logger.LogDebug(
                    LogMessages.Publishers.PublishFailed,
                    $"{exchangeName}->{routingKey}",
                    ex.Message);

                error = true;
            }
            finally
            {
                await _channelPool
                .ReturnChannelAsync(channelHost, error);
            }

            return(error);
        }
        public override void HandleBasicDeliver(string consumerTag,
                                                ulong deliveryTag,
                                                bool redelivered,
                                                string exchange,
                                                string routingKey,
                                                IBasicProperties properties,
                                                byte[] body)
        {
            base.HandleBasicDeliver(consumerTag, deliveryTag, redelivered, exchange, routingKey, properties, body);

            var      data = Encoding.Default.GetString(body);
            DateTime timestamp;

            Console.WriteLine(_identifier + " -- ");
            var application = Encoding.Default.GetString(properties.Headers?["Application"] as byte[]);

            if (properties.IsHeadersPresent())
            {
                foreach (var kvp in properties.Headers)
                {
                    object kvpValue = null;
                    if (kvp.Value is byte[])
                    {
                        kvpValue = Encoding.Default.GetString((byte[])kvp.Value);
                    }
                    else
                    {
                        kvpValue = kvp.Value;
                    }

                    Console.WriteLine("{0:-10} - {1}", kvp.Key, kvpValue);
                }
            }

            if (properties.ContentType?.Equals("application/json", StringComparison.InvariantCultureIgnoreCase) ?? false)
            {
                var o = JsonConvert.DeserializeObject(data) as JObject;
                timestamp = GetDateTime(o, "Timestamp") ?? DateTime.UtcNow;

                Console.WriteLine(o["RenderedMessage"]?.Value <string>());
                Console.WriteLine(timestamp.ToUniversalTime());
                Console.WriteLine(timestamp);
                Console.WriteLine(o["Level"]?.Value <string>());
            }
            else
            {
                timestamp = DateTime.UtcNow;
            }

            _logStore.StoreLogEntry(application, timestamp, data);

            Console.WriteLine(data);
        }
        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);
                }
            }
        }
示例#13
0
        // A basic implementation of publish but using the ChannelPool. If message properties is null, one is created and all messages are set to persistent.
        public async Task <bool> PublishAsync(
            string exchangeName,
            string routingKey,
            ReadOnlyMemory <byte> payload,
            bool mandatory = false,
            IBasicProperties messageProperties = null,
            string messageId = null)
        {
            Guard.AgainstBothNullOrEmpty(exchangeName, nameof(exchangeName), routingKey, nameof(routingKey));

            var error       = false;
            var channelHost = await _channelPool.GetChannelAsync().ConfigureAwait(false);

            if (messageProperties == null)
            {
                messageProperties = channelHost.GetChannel().CreateBasicProperties();
                messageProperties.DeliveryMode = 2;
                messageProperties.MessageId    = messageId ?? Guid.NewGuid().ToString();

                if (!messageProperties.IsHeadersPresent())
                {
                    messageProperties.Headers = new Dictionary <string, object>();
                }
            }

            // Non-optional Header.
            messageProperties.Headers[Constants.HeaderForObjectType] = Constants.HeaderValueForMessage;

            try
            {
                channelHost
                .GetChannel()
                .BasicPublish(
                    exchange: exchangeName ?? string.Empty,
                    routingKey: routingKey,
                    mandatory: mandatory,
                    basicProperties: messageProperties,
                    body: payload);
            }
            catch (Exception ex)
            {
                _logger.LogDebug(LogMessages.Publishers.PublishFailed, $"{exchangeName}->{routingKey}", ex.Message);
                error = true;
            }
            finally
            {
                await _channelPool
                .ReturnChannelAsync(channelHost, error);
            }

            return(error);
        }
        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);
                }
            }
        }
示例#15
0
        public Task <Tuple <TResponse, MessageMetadata, string> > RequestAsync <TResponse>(IMessage message, MessageMetadata metadata)
            where TResponse : class, IMessage
        {
            string queueName = null;

            try
            {
                var    taskCompletionSource = new TaskCompletionSource <Tuple <TResponse, MessageMetadata, string> >();
                string routingKey           = string.IsNullOrEmpty(metadata.ReplyTo)
                    ? string.IsNullOrEmpty(metadata.Topic) ? message.GetType().Name : metadata.Topic
                    : metadata.ReplyTo;

                IModel channel = RabbitMqConnection.CreateChannel(this);
                queueName = RabbitMqConnection.CreateQueue(channel, string.Empty, true, false, false);

                metadata.MessageId = string.IsNullOrEmpty(metadata.ReplyTo) ? queueName : metadata.ReplyTo;
                metadata.ReplyTo   = queueName;

                RabbitMqConnection.CreateBinding(channel, queueName, MessageMetadata.RpcDestination, metadata.ReplyTo);
                EventingBasicConsumer consumer = RabbitMqConnection.CreateEventingBasicConsumer(channel);

                consumer.Received += ConsumerOnReceived;
                RabbitMqConnection.ConsumeQueue(this, channel, queueName, string.Empty, true, consumer);

                IBasicProperties basicProperties = RabbitMqConnection.CreateBasicProperties(channel, message, metadata);
                basicProperties.ReplyTo = string.IsNullOrEmpty(metadata.ReplyTo) ? queueName : metadata.ReplyTo;

                if (!basicProperties.IsHeadersPresent())
                {
                    basicProperties.Headers = new Dictionary <string, object>();
                }
                basicProperties.Headers[MessageMetadata.ResponseDestinationHeaderKey] = MessageMetadata.RpcDestination;
                RegisterResponseAction(basicProperties.CorrelationId, queueName, consumer, typeof(TResponse), taskCompletionSource);

                byte[] body = SerializeMessage(message, metadata.SerializationType);

                Logger.LogInformation(
                    $"Send request to: {metadata.Destination} with routingkey: {routingKey} - ReplyTo: {basicProperties.ReplyTo} of type: {typeof(TResponse).Name} id: {basicProperties.CorrelationId}");
                RabbitMqConnection.PublishMessage(channel, metadata.Destination, basicProperties, body, routingKey);
                return(taskCompletionSource.Task);
            }
            catch (Exception e)
            {
                Logger.LogError(e, $"{nameof(RequestAsync)}");
                if (queueName != null)
                {
                    ForgetMessage(queueName);
                }
                throw;
            }
        }
        public static MotorCloudEvent <byte[]> ExtractCloudEvent <T>(this IBasicProperties self,
                                                                     IApplicationNameService applicationNameService, ICloudEventFormatter cloudEventFormatter,
                                                                     ReadOnlyMemory <byte> body,
                                                                     IReadOnlyCollection <ICloudEventExtension> extensions)
        {
            var specVersion = CloudEventsSpecVersion.V1_0;
            var attributes  = new Dictionary <string, object>();
            IDictionary <string, object> headers = new Dictionary <string, object>();

            if (self.IsHeadersPresent() && self.Headers != null)
            {
                headers = self.Headers;
            }

            foreach (var header in headers
                     .Where(t => t.Key.StartsWith(CloudEventPrefix))
                     .Select(t =>
                             new KeyValuePair <string, object>(
                                 t.Key.Substring(CloudEventPrefix.Length),
                                 t.Value)))
            {
                if (string.Equals(header.Key, CloudEventAttributes.DataContentTypeAttributeName(specVersion),
                                  StringComparison.InvariantCultureIgnoreCase) ||
                    string.Equals(header.Key, CloudEventAttributes.SpecVersionAttributeName(specVersion),
                                  StringComparison.InvariantCultureIgnoreCase))
                {
                    continue;
                }

                attributes.Add(header.Key, header.Value);
            }

            if (attributes.Count == 0)
            {
                return(new MotorCloudEvent <byte[]>(applicationNameService, body.ToArray(), typeof(T).Name,
                                                    new Uri("rabbitmq://notset"), extensions: extensions.ToArray()));
            }

            var cloudEvent = new MotorCloudEvent <byte[]>(applicationNameService, body.ToArray(), extensions);

            foreach (var attribute in attributes)
            {
                cloudEvent.GetAttributes().Add(attribute.Key, cloudEventFormatter.DecodeAttribute(
                                                   cloudEvent.SpecVersion, attribute.Key, (byte[])attribute.Value, extensions));
            }

            return(cloudEvent);
        }
示例#17
0
        protected Dictionary <string, string> GetHeaders(IBasicProperties props)
        {
            if (props == null || props.IsHeadersPresent() == false)
            {
                return(null);
            }


            var dict = new Dictionary <string, string>();

            foreach (var key in props.Headers.Keys)
            {
                dict.Add(key, Encoding.UTF8.GetString((byte[])props.Headers[key]));
            }

            return(dict);
        }
示例#18
0
		public static Dictionary<string, object> FromProperties(IBasicProperties properties)
		{
			var headers = Map
				.Where(g => g.HasValue(properties))
				.ToDictionary(
					g => g.Name,
					g => g.GetValue(properties));

			if (properties.IsHeadersPresent())
			{
				foreach (var pair in properties.Headers)
				{
					headers.Add(pair.Key, pair.Value);
				}
			}

			return headers;
		}
示例#19
0
        internal MessageMetadata CreateMetadata(IBasicProperties properties, string topic, ISerializer serializer, ulong?deliveryTag = null)
        {
            MessageMetadata metadata = new MessageMetadata
            {
                ReplyTo     = properties.ReplyTo,
                MessageId   = properties.CorrelationId,
                Destination =
                    properties.IsHeadersPresent() &&
                    properties.Headers.ContainsKey(MessageMetadata.ResponseDestinationHeaderKey)
                        ? serializer.ByteArrayToObject <string>(properties.Headers[MessageMetadata.ResponseDestinationHeaderKey] as byte[])
                        : null,
                Topic = topic
            };

            if (deliveryTag != null)
            {
                metadata.DeliveryTag = deliveryTag.Value;
            }
            return(metadata);
        }
示例#20
0
        private void _consumer_Received(IBasicConsumer sender, BasicDeliverEventArgs args)
        {
            var              payload = JObject.Parse(Encoding.UTF8.GetString(args.Body));
            string           token   = null;
            IBasicProperties props   = args.BasicProperties;

            uint expiry = 0;

            if (payload == null ||
                !props.IsHeadersPresent() ||
                string.IsNullOrWhiteSpace((token = props.GetStringHeader("device-token"))) ||
                !uint.TryParse(props.GetStringHeader("expiry"), out expiry))
            {
                // the message is too incomplete to handle
                this.Model.BasicNack(args.DeliveryTag, false, false);
                return;
            }
            _queue.Enqueue(new NotificationEventArgs(this, token, expiry, payload, args.DeliveryTag));
            _wait.Set();
        }
示例#21
0
        public static string GetStringHeader(this IBasicProperties props, string headerName)
        {
            if (!props.IsHeadersPresent() ||
                !props.Headers.Contains(headerName))
            {
                return(null);
            }

            object obj = props.Headers[headerName];

            if (obj is string)
            {
                return((string)obj);
            }
            if (obj is byte[])
            {
                return(System.Text.Encoding.UTF8.GetString((byte[])obj));
            }
            return(null);
        }
示例#22
0
 public static string ReadHeaderString(this IBasicProperties basicProperties, string name)
 {
     if (string.IsNullOrEmpty(name))
     {
         return(string.Empty);
     }
     if (!basicProperties.IsHeadersPresent())
     {
         return(string.Empty);
     }
     if (basicProperties.Headers.TryGetValue(name, out object obj) && obj != null)
     {
         if (obj is byte[] data)
         {
             return(Encoding.UTF8.GetString(data));
         }
         return(obj.ToString());
     }
     return(string.Empty);
 }
        private static string WriteBasicProperties(IBasicProperties props)
        {
            if (props == null)
            {
                return(string.Empty);
            }

            var sb = new StringBuilder();

            sb.Append("ContentType=").Append(props.ContentType);
            if (props.IsHeadersPresent())
            {
                sb.Append(", Headers={").Append(string.Join(", ", props.Headers.Select(s => $"{s.Key}={WriteHeaderValue(s.Value)}"))).Append("}");
            }
            sb.Append(", DeliveryMode=").Append(props.DeliveryMode);
            sb.Append(", Priority=").Append(props.Priority);
            sb.Append(", CorrelationId=").Append(props.CorrelationId);
            if (props.IsTimestampPresent())
            {
                sb.Append(", Timestamp=").Append(props.Timestamp.UnixTime);
            }

            return(sb.ToString());
        }
示例#24
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);
                }
            }
示例#25
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);
                }
            }
        }
示例#26
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());
        }
示例#27
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);
            }
        }
示例#28
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);
                }
            }
        }
        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;
                }
            }
        }
示例#30
0
        public static IIstaMessageProperties ConvertProperties(IBasicProperties properties)
        {
            var item = new IstaMessageProperties
            {
                AppId             = properties.AppId,
                ContentEncoding   = properties.ContentEncoding,
                ContentType       = properties.ContentType,
                CorrelationId     = properties.CorrelationId,
                Expiration        = properties.Expiration,
                ExternalMessageId = properties.MessageId,
                ReplyTo           = properties.ReplyTo,
                Type   = properties.Type,
                UserId = properties.UserId,
            };

            if (properties.IsDeliveryModePresent())
            {
                item.Persistent = (properties.DeliveryMode.Equals(2));
            }

            if (properties.IsPriorityPresent())
            {
                item.Priority = properties.Priority;
            }

            if (properties.IsTimestampPresent())
            {
                item.Timestamp = properties.Timestamp.UnixTime;
            }

            if (!properties.IsHeadersPresent())
            {
                return(item);
            }

            var collection = properties.Headers as Hashtable;

            if (collection == null)
            {
                return(item);
            }

            if (collection["x-action"] != null)
            {
                var bytes = collection["x-action"] as byte[];
                if (bytes != null && bytes.Length != 0)
                {
                    item.MessageAction = Encoding.UTF8.GetString(bytes);
                }
            }

            if (collection["x-type"] != null)
            {
                var bytes = collection["x-type"] as byte[];
                if (bytes != null && bytes.Length != 0)
                {
                    item.MessageType = Encoding.UTF8.GetString(bytes);
                }
            }

            foreach (string key in collection.Keys)
            {
                if (key.Equals("x-action", StringComparison.Ordinal))
                {
                    continue;
                }

                if (key.Equals("x-type", StringComparison.Ordinal))
                {
                    continue;
                }

                item.AddHeader(key, collection[key]);
            }

            return(item);
        }