Exemplo n.º 1
0
        protected async Task Move(ReceiveContext context, Action <InMemoryTransportMessage, SendHeaders> preSend)
        {
            var messageId = GetMessageId(context);

            byte[] body = context.GetBody();

            var messageType = "Unknown";

            if (context.TryGetPayload(out InMemoryTransportMessage receivedMessage))
            {
                messageType = receivedMessage.MessageType;
            }

            var transportMessage = new InMemoryTransportMessage(messageId, body, context.ContentType.MediaType, messageType);

            SendHeaders headers = new DictionarySendHeaders(transportMessage.Headers);

            headers.SetHostHeaders();

            preSend(transportMessage, headers);

            transportMessage.Headers[MessageHeaders.Reason] = "dead-letter";

            await _exchange.Send(transportMessage).ConfigureAwait(false);
        }
        ConsumeContext IMessageDeserializer.Deserialize(ReceiveContext receiveContext)
        {
            try
            {
                var messageEncoding = GetMessageEncoding(receiveContext);

                MessageEnvelope envelope;
                using (var body = receiveContext.GetBody())
                using (var reader = new StreamReader(body, messageEncoding, false, 1024, true))
                using (var jsonReader = new JsonTextReader(reader))
                {
                    envelope = _deserializer.Deserialize<MessageEnvelope>(jsonReader);
                }

                return new JsonConsumeContext(_deserializer, _objectTypeDeserializer, _sendEndpointProvider, _publishEndpointProvider, receiveContext, envelope);
            }
            catch (JsonSerializationException ex)
            {
                throw new SerializationException("A JSON serialization exception occurred while deserializing the message envelope", ex);
            }
            catch (SerializationException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new SerializationException("An exception occurred while deserializing the message envelope", ex);
            }
        }
Exemplo n.º 3
0
        protected async Task Move(ReceiveContext context, Action <PublishRequest, SendHeaders> preSend)
        {
            if (!context.TryGetPayload(out ModelContext modelContext))
            {
                throw new ArgumentException("The ReceiveContext must contain a BrokeredMessageContext (from Azure Service Bus)", nameof(context));
            }

            await _topologyFilter.Send(modelContext, Pipe.Empty <ModelContext>()).ConfigureAwait(false);

            var topicArn = await modelContext.GetTopic(_destination).ConfigureAwait(false);

            var message = modelContext.CreateTransportMessage(topicArn, context.GetBody());

            if (context.TryGetPayload(out AmazonSqsMessageContext messageContext))
            {
                foreach (string key in messageContext.Attributes.Keys)
                {
                    message.MessageAttributes[key].StringValue = messageContext.Attributes[key].StringValue;
                    message.MessageAttributes[key].BinaryValue = messageContext.Attributes[key].BinaryValue;
                    message.MessageAttributes[key].DataType    = messageContext.Attributes[key].DataType;
                }
            }

            SendHeaders headers = new AmazonSnsHeaderAdapter(message.MessageAttributes);

            headers.SetHostHeaders();

            preSend(message, headers);

            var task = Task.Run(() => modelContext.Publish(message));

            context.AddPendingTask(task);
        }
        public ConsumeContext Deserialize(ReceiveContext receiveContext)
        {
            try
            {
                MessageEnvelope envelope;
                using (Stream body = receiveContext.GetBody())
                using (Stream cryptoStream = _provider.GetDecryptStream(body, receiveContext))
                using (var jsonReader = new BsonReader(cryptoStream))
                {
                    envelope = _deserializer.Deserialize<MessageEnvelope>(jsonReader);
                }

                return new JsonConsumeContext(_deserializer, _objectTypeDeserializer, _sendEndpointProvider, _publishEndpoint, receiveContext, envelope);
            }
            catch (JsonSerializationException ex)
            {
                throw new SerializationException("A JSON serialization exception occurred while deserializing the message envelope", ex);
            }
            catch (SerializationException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new SerializationException("An exception occurred while deserializing the message envelope", ex);
            }
        }
Exemplo n.º 5
0
            public ServiceBusMoveContext(ReceiveContext context)
            {
                _context    = context;
                _serializer = new CopyBodySerializer(context);

                BrokeredMessageContext messageContext;

                if (!context.TryGetPayload(out messageContext))
                {
                    throw new ArgumentException("The context must be a service bus receive context", nameof(context));
                }

                _messageBodyStream = context.GetBody();
                _brokeredMessage   = new BrokeredMessage(_messageBodyStream)
                {
                    ContentType      = context.ContentType.MediaType,
                    ForcePersistence = messageContext.ForcePersistence,
                    TimeToLive       = messageContext.TimeToLive,
                    CorrelationId    = messageContext.CorrelationId,
                    MessageId        = messageContext.MessageId,
                    Label            = messageContext.Label,
                    PartitionKey     = messageContext.PartitionKey,
                    ReplyTo          = messageContext.ReplyTo,
                    ReplyToSessionId = messageContext.ReplyToSessionId,
                    SessionId        = messageContext.SessionId
                };

                Headers = new DictionarySendHeaders(_brokeredMessage.Properties);

                foreach (KeyValuePair <string, object> property in messageContext.Properties)
                {
                    _brokeredMessage.Properties[property.Key] = property.Value;
                }
            }
Exemplo n.º 6
0
 public Task PostReceive(ReceiveContext context)
 {
     Console.WriteLine("-----------------PostReceive---------------------");
     Console.WriteLine(Encoding.Default.GetString(context.GetBody()));
     Console.WriteLine("--------------------------------------");
     return(Task.CompletedTask);
 }
Exemplo n.º 7
0
        async Task ISendTransport.Move(ReceiveContext context, IPipe <SendContext> pipe)
        {
            BrokeredMessageContext messageContext;

            if (context.TryGetPayload(out messageContext))
            {
                using (Stream messageBodyStream = context.GetBody())
                {
                    using (var brokeredMessage = new BrokeredMessage(messageBodyStream))
                    {
                        brokeredMessage.ContentType      = context.ContentType.MediaType;
                        brokeredMessage.ForcePersistence = messageContext.ForcePersistence;
                        brokeredMessage.TimeToLive       = messageContext.TimeToLive;
                        brokeredMessage.CorrelationId    = messageContext.CorrelationId;
                        brokeredMessage.MessageId        = messageContext.MessageId;
                        brokeredMessage.Label            = messageContext.Label;
                        brokeredMessage.PartitionKey     = messageContext.PartitionKey;
                        brokeredMessage.ReplyTo          = messageContext.ReplyTo;
                        brokeredMessage.ReplyToSessionId = messageContext.ReplyToSessionId;
                        brokeredMessage.SessionId        = messageContext.SessionId;

                        await _sender.SendAsync(brokeredMessage);

                        _log.DebugFormat("MOVE {0} ({1} to {2})", brokeredMessage.MessageId, context.InputAddress, _sender.Path);
                    }
                }
            }
        }
Exemplo n.º 8
0
 public Task ReceiveFault(ReceiveContext context, Exception exception)
 {
     Console.WriteLine("----------------ReceiveFault----------------------");
     Console.WriteLine(Encoding.Default.GetString(context.GetBody()));
     Console.WriteLine("--------------------------------------");
     return(Task.CompletedTask);
 }
 void IMessageSerializer.Serialize <T>(Stream stream, SendContext <T> context)
 {
     using (Stream bodyStream = _context.GetBody())
     {
         bodyStream.CopyTo(stream);
     }
 }
        ConsumeContext IMessageDeserializer.Deserialize(ReceiveContext receiveContext)
        {
            try
            {
                MessageEnvelope envelope;
                using (Stream body = receiveContext.GetBody())
                using (var jsonReader = new BsonReader(body))
                {
                    envelope = _deserializer.Deserialize<MessageEnvelope>(jsonReader);
                }

                return new JsonConsumeContext(_deserializer, _objectTypeDeserializer, receiveContext, envelope);
            }
            catch (JsonSerializationException ex)
            {
                throw new SerializationException("A JSON serialization exception occurred while deserializing the message envelope", ex);
            }
            catch (SerializationException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new SerializationException("An exception occurred while deserializing the message envelope", ex);
            }
        }
        public override bool TryGetMessage <T>(out ConsumeContext <T> message)
        {
            lock (_messageTypes)
            {
                object existing;
                if (_messageTypes.TryGetValue(typeof(T), out existing))
                {
                    message = existing as ConsumeContext <T>;
                    return(message != null);
                }

                var typeUrn = new MessageUrn(typeof(T)).ToString();

                if (_supportedTypes.Any(typeUrn.Equals))
                {
                    using (var stream = ReceiveContext.GetBody())
                    {
                        stream.Seek(_offset, SeekOrigin.Current);

                        _messageTypes[typeof(T)] = message = new MessageConsumeContext <T>(this, ProtoBuf.Serializer.DeserializeWithLengthPrefix <T>(stream, PrefixStyle.Fixed32));
                        return(true);
                    }
                }

                _messageTypes[typeof(T)] = message = null;
                return(false);
            }
        }
Exemplo n.º 12
0
        ConsumeContext IMessageDeserializer.Deserialize(ReceiveContext receiveContext)
        {
            try
            {
                var messageEncoding = GetMessageEncoding(receiveContext);

                MessageEnvelope envelope;
                using (var body = receiveContext.GetBody())
                    using (var reader = new StreamReader(body, messageEncoding, false, 1024, true))
                        using (var jsonReader = new JsonTextReader(reader))
                        {
                            envelope = _deserializer.Deserialize <MessageEnvelope>(jsonReader);
                        }

                return(new JsonConsumeContext(_deserializer, _objectTypeDeserializer, receiveContext, envelope));
            }
            catch (JsonSerializationException ex)
            {
                throw new SerializationException("A JSON serialization exception occurred while deserializing the message envelope", ex);
            }
            catch (SerializationException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new SerializationException("An exception occurred while deserializing the message envelope", ex);
            }
        }
        ConsumeContext IMessageDeserializer.Deserialize(ReceiveContext receiveContext)
        {
            try
            {
                MessageEnvelope envelope;
                using (Stream body = receiveContext.GetBody())
                    using (var jsonReader = new BsonReader(body))
                    {
                        envelope = _deserializer.Deserialize <MessageEnvelope>(jsonReader);
                    }

                return(new JsonConsumeContext(_deserializer, _sendEndpointProvider, _publishEndpoint, receiveContext, envelope));
            }
            catch (JsonSerializationException ex)
            {
                throw new SerializationException("A JSON serialization exception occurred while deserializing the message envelope", ex);
            }
            catch (SerializationException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new SerializationException("An exception occurred while deserializing the message envelope", ex);
            }
        }
        public ConsumeContext Deserialize(ReceiveContext receiveContext)
        {
            try
            {
                MessageEnvelope envelope;
                using (Stream body = receiveContext.GetBody())
                    using (Stream cryptoStream = _provider.GetDecryptStream(body, receiveContext))
                        using (var jsonReader = new BsonDataReader(cryptoStream))
                        {
                            envelope = _deserializer.Deserialize <MessageEnvelope>(jsonReader);
                        }

                return(new JsonConsumeContext(_deserializer, _objectTypeDeserializer, receiveContext, envelope));
            }
            catch (JsonSerializationException ex)
            {
                throw new SerializationException("A JSON serialization exception occurred while deserializing the message envelope", ex);
            }
            catch (SerializationException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new SerializationException("An exception occurred while deserializing the message envelope", ex);
            }
        }
Exemplo n.º 15
0
        protected async Task Move(ReceiveContext context, Action <SendMessageRequest, SendHeaders> preSend)
        {
            if (!context.TryGetPayload(out ClientContext clientContext))
            {
                throw new ArgumentException("The ReceiveContext must contain a ClientContext (from Amazon SQS)", nameof(context));
            }

            await _topologyFilter.Send(clientContext, Pipe.Empty <ClientContext>()).ConfigureAwait(false);

            var message = clientContext.CreateSendRequest(_destination, context.GetBody());

            if (context.TryGetPayload(out AmazonSqsMessageContext messageContext))
            {
                foreach (var key in messageContext.Attributes.Keys)
                {
                    if (key.StartsWith("MT-"))
                    {
                        continue;
                    }

                    message.MessageAttributes[key] = messageContext.Attributes[key];
                }
            }

            SendHeaders headers = new AmazonSqsHeaderAdapter(message.MessageAttributes);

            preSend(message, headers);

            var task = clientContext.SendMessage(message, context.CancellationToken);

            context.AddReceiveTask(task);
        }
Exemplo n.º 16
0
        public Task PreReceive(ReceiveContext context)
        {
            // called immediately after the message was delivery by the transport
            var body = Encoding.UTF8.GetString(context.GetBody());

            _log.Info($"PreReceive:{body}");
            //Console.WriteLine(body);
            return(Task.CompletedTask);
        }
Exemplo n.º 17
0
        public Task PostReceive(ReceiveContext context)
        {
            var body = Encoding.UTF8.GetString(context.GetBody());
            var bf   = $"PostReceive:{body}, ElapsedTime:{context.ElapsedTime}";

            _log.Info(bf);
            //Console.WriteLine(bf);
            return(Task.CompletedTask);
        }
        async Task ISendTransport.Move(ReceiveContext context, IPipe <SendContext> pipe)
        {
            IPipe <ModelContext> modelPipe = Pipe.New <ModelContext>(p =>
            {
                p.UseFilter(_filter);

                p.UseExecuteAsync(async modelContext =>
                {
                    try
                    {
                        IBasicProperties properties;
                        string routingKey = "";

                        RabbitMqBasicConsumeContext basicConsumeContext;
                        if (context.TryGetPayload(out basicConsumeContext))
                        {
                            properties = basicConsumeContext.Properties;
                            routingKey = basicConsumeContext.RoutingKey;
                        }
                        else
                        {
                            properties         = modelContext.Model.CreateBasicProperties();
                            properties.Headers = new Dictionary <string, object>();
                        }

                        var moveContext = new RabbitMqMoveContext(context, properties, _exchange, routingKey ?? "");

                        await pipe.Send(moveContext).ConfigureAwait(false);

                        byte[] body;
                        using (var memoryStream = new MemoryStream())
                        {
                            using (var bodyStream = context.GetBody())
                            {
                                await bodyStream.CopyToAsync(memoryStream).ConfigureAwait(false);
                            }

                            body = memoryStream.ToArray();
                        }

                        var task = modelContext.BasicPublishAsync(_exchange, "", true, properties, body, true);
                        context.AddPendingTask(task);
                    }
                    catch (Exception ex)
                    {
                        if (_log.IsErrorEnabled)
                        {
                            _log.Error("Faulted moving message to error queue: " + _exchange, ex);
                        }

                        throw;
                    }
                });
            });

            await _modelCache.Send(modelPipe, context.CancellationToken).ConfigureAwait(false);
        }
Exemplo n.º 19
0
        string GetBodyString(ReceiveContext context)
        {
            using (var stream = context.GetBody())
                using (var ms = new MemoryStream())
                {
                    stream.CopyTo(ms);

                    return(Encoding.UTF8.GetString(ms.ToArray()));
                }
        }
Exemplo n.º 20
0
        string GetBodyString(ReceiveContext context)
        {
            using (var stream = context.GetBody())
            using (var ms = new MemoryStream())
            {
                stream.CopyTo(ms);

                return Encoding.UTF8.GetString(ms.ToArray());
            }
        }
Exemplo n.º 21
0
        static XDocument GetXmlDocument(ReceiveContext receiveContext, Encoding encoding)
        {
            var bodyString = encoding.GetString(receiveContext.GetBody());

            using var reader = new StringReader(bodyString);

            var document = XDocument.Load(reader);

            return(document);
        }
Exemplo n.º 22
0
        public Task ReceiveFault(ReceiveContext context, Exception exception)
        {
            // called when an exception occurs early in the message processing, such as deserialization, etc.
            var body = Encoding.UTF8.GetString(context.GetBody());
            var bf   = $"ReceiveFault:{body}, Error:{exception.ToString()}";

            _log.Info(bf);
            //Console.WriteLine(bf);
            return(Task.CompletedTask);
        }
        ConsumeContext IMessageDeserializer.Deserialize(ReceiveContext receiveContext)
        {
            object obj;
            var headers = new Header[0];
            using (Stream body = receiveContext.GetBody())
            {
                obj = _formatter.Deserialize(body, x => headers = x);
            }

            return new StaticConsumeContext(_sendEndpointProvider, _publishEndpoint, receiveContext, obj, headers);
        }
        public ConsumeContext Deserialize(ReceiveContext receiveContext)
        {
            if (receiveContext == null)
            {
                throw new ArgumentNullException(nameof(receiveContext));
            }

            try
            {
                var encryptionDataJson = receiveContext.TransportHeaders.Get <string>(EncryptedMessageSerializer.EncryptionHeaderDataKey);
                var encryptionData     = JsonConvert.DeserializeObject <EncryptionData>(encryptionDataJson);

                if (!encryptionData.EncryptionAgent.Protocol.Equals("1.0", StringComparison.OrdinalIgnoreCase))
                {
                    throw new NotSupportedException($"Version of {encryptionData?.EncryptionAgent?.Protocol ?? "(Not set)"} encryption agent is not supported.");
                }

                var resolver = this.keyResolver();

                var result = resolver.ResolveKeyAsync(encryptionData.WrappedContentKey.KeyId, receiveContext.CancellationToken).ConfigureAwait(false).GetAwaiter().GetResult();
                var key    = result.UnwrapKeyAsync(encryptionData.WrappedContentKey.EncryptedKey, encryptionData.WrappedContentKey.Algorithm, receiveContext.CancellationToken).ConfigureAwait(false).GetAwaiter().GetResult();

                MessageEnvelope envelope = null;
                if (encryptionData.EncryptionAgent.EncryptionAlgorithm == EncryptionAlgorithm.AES_CBC_256)
                {
                    using (var provider = new AesCryptoServiceProvider())
                        using (var transform = provider.CreateDecryptor(key, encryptionData.ContentEncryptionIV))
                            using (var cryptoStream = new DisposingCryptoStream(receiveContext.GetBody(), transform, CryptoStreamMode.Read))
                                using (var bsonReader = new BsonDataReader(cryptoStream))
                                {
                                    envelope = this.deserializer.Deserialize <MessageEnvelope>(bsonReader);
                                }
                }
                else
                {
                    throw new NotSupportedException($"{encryptionData?.EncryptionAgent?.EncryptionAlgorithm} encryption algorithm detected.");
                }

                return(new JsonConsumeContext(this.deserializer, this.objectTypeDeserializer, receiveContext, envelope));
            }
            catch (JsonSerializationException ex)
            {
                throw new SerializationException("A JSON serialization exception occurred while deserializing the message envelope", ex);
            }
            catch (SerializationException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new SerializationException("An exception occurred while deserializing the message envelope", ex);
            }
        }
        ConsumeContext IMessageDeserializer.Deserialize(ReceiveContext receiveContext)
        {
            object obj;
            var    headers = new Header[0];

            using (Stream body = receiveContext.GetBody())
            {
                obj = _formatter.Deserialize(body, x => headers = x);
            }

            return(new StaticConsumeContext(_deserializer, _sendEndpointProvider, _publishEndpoint, receiveContext, obj, headers));
        }
        public ConsumeContext Deserialize(ReceiveContext receiveContext)
        {
            try
            {
                var envelope = JsonSerializer.Deserialize <MessageEnvelope>(receiveContext.GetBody(), SystemTextJsonMessageSerializer.Options);

                return(new SystemTextJsonConsumeContext(receiveContext, envelope));
            }
            catch (Exception ex)
            {
                throw new SerializationException("An error occured while deserializing the message enveloper", ex);
            }
        }
Exemplo n.º 27
0
 public Task PostReceive(ReceiveContext context)
 {
     // called after the message has been received and processed
     if (_logger.IsEnabled(LogLevel.Debug))
     {
         var body = context.GetBody();
         {
             string text = System.Text.Encoding.UTF8.GetString(body);
             _logger.LogDebug("PostReceive" + text);
         }
     }
     return(Task.FromResult(0));
 }
Exemplo n.º 28
0
 public Task PreReceive(ReceiveContext context)
 {
     // called immediately after the message was delivery by the transportif (_logger.IsAuditOn)
     if (_logger.IsEnabled(LogLevel.Debug))
     {
         var body = context.GetBody();
         {
             string text = System.Text.Encoding.UTF8.GetString(body);
             _logger.LogDebug("PreReceive" + text);
         }
     }
     return(Task.FromResult(0));
 }
Exemplo n.º 29
0
 public Task PreReceive(ReceiveContext context)
 {
     // called immediately after the message was delivery by the transportif (_logger.IsAuditOn)
     if (_logger.IsDebugEnabled)
     {
         using (var body = context.GetBody())
         {
             StreamReader reader = new StreamReader(body);
             string       text   = reader.ReadToEnd();
             _logger.Debug("PreReceive" + text);
         }
     }
     return(Task.FromResult(0));
 }
Exemplo n.º 30
0
 public Task PostReceive(ReceiveContext context)
 {
     // called after the message has been received and processed
     if (_logger.IsDebugEnabled)
     {
         using (var body = context.GetBody())
         {
             StreamReader reader = new StreamReader(body);
             string       text   = reader.ReadToEnd();
             _logger.Info("PostReceive" + text);
         }
     }
     return(Task.FromResult(0));
 }
Exemplo n.º 31
0
        public async Task ReceiveFault(ReceiveContext context, Exception exception)
        {
            string message;

            using (var reader = new StreamReader(context.GetBody()))
            {
                message = reader.ReadToEnd();
            }

            var log = new ServiceLog(Guid.Empty, LogConstansts.Protocols.Ampq, "Cannot recognize", DateTime.UtcNow,
                                     context.ElapsedTime, exception, 0, Encoding.UTF8.GetByteCount(message), "Not found",
                                     "Not found", "From JWT in headers", "From JwT in headers",
                                     LogConstansts.Levels.Debug, false, false, false, true, context, "");

            await loggingBusControl.Log(log);
        }
        public ConsumeContext Deserialize(ReceiveContext receiveContext)
        {
            var body                  = Encoding.UTF8.GetString(receiveContext.GetBody());
            var customMessage         = JsonConvert.DeserializeObject <CustomMessage>(body);
            var serviceBusSendContext = new AzureServiceBusSendContext <CustomMessage>(customMessage, CancellationToken.None);

            string[] messageTypes      = { "urn:message:MassTransitSample:CustomMessage" };
            var      serviceBusContext = receiveContext as ServiceBusReceiveContext;

            serviceBusSendContext.ContentType   = new ContentType(JsonMessageSerializer.JsonContentType.ToString());
            serviceBusSendContext.SourceAddress = serviceBusContext.InputAddress;
            serviceBusSendContext.SessionId     = serviceBusContext.SessionId;

            // sending JToken because we are using default Newtonsoft deserializer/serializer
            var messageEnv = new JsonMessageEnvelope(serviceBusSendContext, JObject.Parse(body), messageTypes);

            return(new JsonConsumeContext(JsonSerializer.CreateDefault(), receiveContext, messageEnv));
        }
Exemplo n.º 33
0
        protected async Task Move(ReceiveContext context, Action <SendMessageRequest, IDictionary <string, MessageAttributeValue> > preSend)
        {
            if (!context.TryGetPayload(out ClientContext clientContext))
            {
                throw new ArgumentException("The ReceiveContext must contain a ClientContext (from Amazon SQS)", nameof(context));
            }

            await _topologyFilter.Send(clientContext, Pipe.Empty <ClientContext>()).ConfigureAwait(false);

            var message = await clientContext.CreateSendRequest(_destination, context.GetBody()).ConfigureAwait(false);

            CopyReceivedMessageHeaders(context, message.MessageAttributes);

            preSend(message, message.MessageAttributes);

            var task = clientContext.SendMessage(message, context.CancellationToken);

            context.AddReceiveTask(task);
        }
        ConsumeContext IMessageDeserializer.Deserialize(ReceiveContext receiveContext)
        {
            try
            {
                XDocument document;
                using (Stream body = receiveContext.GetBody())
                    using (var xmlReader = XmlReader.Create(body, new XmlReaderSettings {
                        CheckCharacters = false
                    }))
                        document = XDocument.Load(xmlReader);

                var json = new StringBuilder(1024);

                using (var stringWriter = new StringWriter(json, CultureInfo.InvariantCulture))
                    using (var jsonWriter = new JsonTextWriter(stringWriter))
                    {
                        jsonWriter.Formatting = Newtonsoft.Json.Formatting.None;

                        XmlMessageSerializer.XmlSerializer.Serialize(jsonWriter, document.Root);
                    }

                MessageEnvelope envelope;
                using (var stringReader = new StringReader(json.ToString()))
                    using (var jsonReader = new JsonTextReader(stringReader))
                    {
                        envelope = _deserializer.Deserialize <MessageEnvelope>(jsonReader);
                    }

                return(new JsonConsumeContext(_deserializer, _objectTypeDeserializer, receiveContext, envelope));
            }
            catch (JsonSerializationException ex)
            {
                throw new SerializationException("A JSON serialization exception occurred while deserializing the message envelope", ex);
            }
            catch (SerializationException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new SerializationException("An exception occurred while deserializing the message envelope", ex);
            }
        }
Exemplo n.º 35
0
        protected async Task Move(ReceiveContext context, Action <IMessage, SendHeaders> preSend)
        {
            if (!context.TryGetPayload(out SessionContext sessionContext))
            {
                throw new ArgumentException("The ReceiveContext must contain a BrokeredMessageContext (from Azure Service Bus)", nameof(context));
            }

            await _topologyFilter.Send(sessionContext, Pipe.Empty <SessionContext>()).ConfigureAwait(false);

            var queue = await sessionContext.GetQueue(_destination).ConfigureAwait(false);

            var producer = await sessionContext.CreateMessageProducer(queue).ConfigureAwait(false);

            byte[] body = context.GetBody();

            var message = producer.CreateBytesMessage();

            if (context.TryGetPayload(out ActiveMqMessageContext messageContext))
            {
                foreach (string key in messageContext.Properties.Keys)
                {
                    message.Properties[key] = messageContext.Properties[key];
                }
            }

            SendHeaders headers = new ActiveMqHeaderAdapter(message.Properties);

            headers.SetHostHeaders();

            preSend(message, headers);

            message.Content = body;

            var task      = Task.Run(() => producer.Send(message));
            var closeTask = task.ContinueWith(_ =>
            {
                producer.Close();
                producer.Dispose();
            });

            context.AddPendingTask(task);
            context.AddPendingTask(closeTask);
        }
Exemplo n.º 36
0
        ConsumeContext IMessageDeserializer.Deserialize(ReceiveContext receiveContext)
        {
            try
            {
                XDocument document;
                using (Stream body = receiveContext.GetBody())
                using (var xmlReader = new XmlTextReader(body))
                    document = XDocument.Load(xmlReader);

                var json = new StringBuilder(1024);

                using (var stringWriter = new StringWriter(json, CultureInfo.InvariantCulture))
                using (var jsonWriter = new JsonTextWriter(stringWriter))
                {
                    jsonWriter.Formatting = Newtonsoft.Json.Formatting.None;

                    XmlMessageSerializer.XmlSerializer.Serialize(jsonWriter, document.Root);
                }

                MessageEnvelope envelope;
                using (var stringReader = new StringReader(json.ToString()))
                using (var jsonReader = new JsonTextReader(stringReader))
                {
                    envelope = _deserializer.Deserialize<MessageEnvelope>(jsonReader);
                }

                return new JsonConsumeContext(_deserializer, _objectTypeDeserializer, _sendEndpointProvider, _publishEndpoint, receiveContext, envelope);
            }
            catch (JsonSerializationException ex)
            {
                throw new SerializationException("A JSON serialization exception occurred while deserializing the message envelope", ex);
            }
            catch (SerializationException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new SerializationException("An exception occurred while deserializing the message envelope", ex);
            }
        }
        ConsumeContext IMessageDeserializer.Deserialize(ReceiveContext receiveContext)
        {
            try
            {
                ProtocolBuffersMessageEnvelope envelope;
                long offset;
                using (var body = receiveContext.GetBody())
                {
                    envelope = Serializer.DeserializeWithLengthPrefix<ProtocolBuffersMessageEnvelope>(body, PrefixStyle.Fixed32);

                    offset = body.Position;
                }

                return new ProtocolBuffersConsumeContext(receiveContext, envelope, offset);
            }
            catch (SerializationException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new SerializationException("An exception occurred while deserializing the message envelope", ex);
            }
        }