예제 #1
0
        async public Task <Dictionary <ServiceDictionaryKey, object> > TryGetMeals(int patientId)
        {
            Dictionary <ServiceDictionaryKey, object> dictionary = new Dictionary <ServiceDictionaryKey, object>();


            try
            {
                List <Meal> meals = await _mealRepository.GetMyMeals(patientId);

                if (meals.Count <= 0)
                {
                    dictionary.Add(ServiceDictionaryKey.ERROR, $"No meals meals for the given user: {patientId}.");
                    dictionary.Add(ServiceDictionaryKey.HTTPSTATUSCODE, HttpStatusCode.NotFound);
                    return(dictionary);
                }

                dynamic data = _messageSerializer.Serialize(meals);
                dictionary.Add(ServiceDictionaryKey.VALUE, data);
            }
            catch (Exception ex)
            {
                dictionary.AddErrorMessage(ServiceDictionaryKey.ERROR, ex, FeedbackHandler);
            }

            return(dictionary);
        }
        public void Serialize <T>(Stream output, T message)
        {
            try
            {
                using (var clearStream = new MemoryStream())
                {
                    _xmlSerializer.Serialize(clearStream, message);

                    clearStream.Seek(0, SeekOrigin.Begin);

                    using (ICryptographyService cryptographyService = new RijndaelCryptographyService(_key))
                    {
                        EncryptedStream encryptedStream = cryptographyService.Encrypt(clearStream);

                        var encryptedMessage = new EncryptedMessageEnvelope
                        {
                            CipheredMessage = Convert.ToBase64String(encryptedStream.GetBytes()),
                            Iv = Convert.ToBase64String(encryptedStream.Iv),
                        };

                        _xmlSerializer.Serialize(output, encryptedMessage);
                    }
                }
            }
            catch (SerializationException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new SerializationException("Failed to serialize message", ex);
            }
        }
        public async Task AdvertiseAsync_MessageDispatcherStarted_WebSocketShouldSendCorrectByteArray()
        {
            //arrange
            RosAdvertiseMessage rosAdvertiseMessage = new RosAdvertiseMessage()
            {
                Id    = _publisher._uniqueId,
                Topic = TOPIC,
                Type  = TYPE
            };

            byte[] serialized = _messageSerializer.Serialize(rosAdvertiseMessage);

            _clientWebSocketMock.SetupGet(clientWebSocket => clientWebSocket.State).Returns(WebSocketState.Open);

            await _messageDispatcher.StartAsync();

            //act
            await _publisher.AdvertiseAsync();

            //assert
            _clientWebSocketMock.Verify(clientWebSocket => clientWebSocket.SendAsync(
                                            It.Is <ArraySegment <byte> >(arraySegment => arraySegment.Array.SequenceEqual(serialized)),
                                            WebSocketMessageType.Text,
                                            true,
                                            _cancellationTokenSource.Token));
        }
예제 #4
0
 public async Task DeadLetterAsync(StorageQueueMessage message)
 {
     var deadLetterMessage = new CloudQueueMessage(_serializer.Serialize(message.Properties));
     await _dlQueue.AddMessageAsync(deadLetterMessage, TimeSpan.MaxValue, null, null, null)
     .ContinueWith(task => _queue.DeleteMessageAsync(message.QueueMessageId, message.PopReceipt), TaskContinuationOptions.OnlyOnRanToCompletion)
     .ConfigureAwait(false);
 }
예제 #5
0
        protected T SerializeAndReturn <T>(T obj)
            where T : class
        {
            byte[] serializedMessageData;

            using (var output = new MemoryStream())
            {
                var sendContext = new InMemorySendContext <T>(obj);

                sendContext.SourceAddress      = _sourceAddress;
                sendContext.DestinationAddress = _destinationAddress;
                sendContext.FaultAddress       = _faultAddress;
                sendContext.ResponseAddress    = _responseAddress;
                sendContext.RequestId          = _requestId;


                Serializer.Serialize(output, sendContext);

                serializedMessageData = output.ToArray();

                Trace.WriteLine(Encoding.UTF8.GetString(serializedMessageData));
            }

            return(Return <T>(serializedMessageData));
        }
예제 #6
0
        public async Task <Dictionary <ServiceDictionaryKey, object> > TryGetFavoriteFood(int patientId)
        {
            Dictionary <ServiceDictionaryKey, object> dictionary = new Dictionary <ServiceDictionaryKey, object>();


            try
            {
                List <Food> foods = await _foodRepository.Favorites(patientId);

                if (foods.Count <= 0)
                {
                    dictionary.Add(ServiceDictionaryKey.ERROR, $"No favorites found for given ID: {patientId}.");
                    dictionary.Add(ServiceDictionaryKey.HTTPSTATUSCODE, HttpStatusCode.NotFound);
                    return(dictionary);
                }

                dynamic data = _messageSerializer.Serialize(foods);
                dictionary.Add(ServiceDictionaryKey.VALUE, data);
            }
            catch (Exception ex)
            {
                dictionary.AddErrorMessage(ServiceDictionaryKey.ERROR, ex, FeedbackHandler);
            }

            return(dictionary);
        }
예제 #7
0
        private void Send <T>(T message, string topic)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }
            if (string.IsNullOrEmpty(topic))
            {
                throw new ArgumentNullException("topic");
            }

            // mutate
            if (_messageMutator != null)
            {
                message = _messageMutator.GetMutatedMessage(this, message);
            }

            // route
            if (_messageTopicRouter != null)
            {
                topic = _messageTopicRouter.GetMessageTopic(this, topic, message);
            }

            // serialize
            byte[] serializedMessage = _sendMessageSerializer.Serialize(message);

            // send
            _nsqdPublisher.Publish(topic, serializedMessage);
        }
        public void ChunkIfNeeded_SmallMessage_ReturnedWithoutChanges()
        {
            var message = new BinaryMessage
            {
                MessageId = Guid.NewGuid(),
                Content   = GetByteArray(100)
            };
            var headers           = new MessageHeaderCollection();
            var serializedMessage = _serializer.Serialize(message, headers);
            var rawBrokerMessage  =
                new RawBrokerMessage(message, headers,
                                     new TestProducerEndpoint("test")
            {
                Chunk = new ChunkSettings
                {
                    Size = 500
                }
            })
            {
                RawContent = serializedMessage
            };

            var chunks = ChunkProducer.ChunkIfNeeded(rawBrokerMessage);

            chunks.Should().HaveCount(1);
            chunks.First().Should().BeEquivalentTo(rawBrokerMessage);
        }
예제 #9
0
        private void Time(object message, IMessageSerializer serializer)
        {
            var watch = new Stopwatch();

            watch.Start();

            for (var i = 0; i < numberOfIterations; i++)
            {
                using (var stream = new MemoryStream())
                    serializer.Serialize(message, stream);
            }

            watch.Stop();
            Debug.WriteLine("Serializing: " + watch.Elapsed);

            watch.Reset();

            var s = new MemoryStream();

            serializer.Serialize(message, s);
            var buffer = s.GetBuffer();

            s.Dispose();

            watch.Start();

            for (var i = 0; i < numberOfIterations; i++)
            {
                using (var forDeserializing = new MemoryStream(buffer))
                    serializer.Deserialize(forDeserializing);
            }

            watch.Stop();
            Debug.WriteLine("Deserializing: " + watch.Elapsed);
        }
예제 #10
0
        private void Time(IMessage[] messages, IMessageSerializer serializer) {
            Stopwatch watch = new Stopwatch();
            watch.Start();

            for (int i = 0; i < numberOfIterations; i++)
                using (MemoryStream stream = new MemoryStream())
                    serializer.Serialize(messages, stream);

            watch.Stop();
            Debug.WriteLine("Serializing: " + watch.Elapsed);

            watch.Reset();

            MemoryStream s = new MemoryStream();
            serializer.Serialize(messages, s);
            byte[] buffer = s.GetBuffer();
            s.Dispose();
            Console.WriteLine(Encoding.ASCII.GetString(buffer));

            watch.Start();

            object[] result = null;

            for (int i = 0; i < numberOfIterations; i++)
                using (var forDeserializing = new MemoryStream(buffer))
                    result = serializer.Deserialize(forDeserializing);

            watch.Stop();
            Debug.WriteLine("Deserializing: " + watch.Elapsed);
        }
예제 #11
0
        public bool ConsumeAddInstanceSubscription(
            AddInstanceSubscription subscription)
        {
            pht.Batch(actions =>
            {
                var message = new MemoryStream();
                messageSerializer.Serialize(new[] { subscription }, message);
                var itemId = actions.AddItem(new AddItemRequest
                {
                    Key  = SubscriptionsKey,
                    Data = message.ToArray()
                });

                remoteInstanceSubscriptions.Add(
                    subscription.InstanceSubscriptionKey,
                    subscription.Type,
                    new Uri(subscription.Endpoint),
                    itemId);

                actions.Commit();
            });

            RaiseSubscriptionChanged();
            return(true);
        }
예제 #12
0
        public virtual Task OnResponseHandlerExceptionAsync(IRawConsumer rawConsumer, IConsumerConfiguration cfg, BasicDeliverEventArgs args, Exception exception)
        {
            _logger.LogError($"An unhandled exception was thrown in the response handler for message '{args.BasicProperties.MessageId}'.", exception);
            var innerException = UnwrapInnerException(exception);
            var exceptionInfo  = new MessageHandlerExceptionInformation
            {
                Message       = $"An unhandled exception was thrown when consuming a message\n  MessageId: {args.BasicProperties.MessageId}\n  Queue: '{cfg.Queue.FullQueueName}'\n  Exchange: '{cfg.Exchange.ExchangeName}'\nSee inner exception for more details.",
                ExceptionType = innerException.GetType().FullName,
                StackTrace    = innerException.StackTrace,
                InnerMessage  = innerException.Message
            };

            _logger.LogInformation($"Sending MessageHandlerException with CorrelationId '{args.BasicProperties.CorrelationId}'");
            rawConsumer.Model.BasicPublish(
                exchange: string.Empty,
                routingKey: args.BasicProperties?.ReplyTo ?? string.Empty,
                basicProperties: _propertiesProvider.GetProperties <MessageHandlerExceptionInformation>(p =>
            {
                p.CorrelationId = args.BasicProperties?.CorrelationId ?? string.Empty;
                p.Headers.Add(PropertyHeaders.ExceptionHeader, _messageExceptionName);
            }),
                body: _serializer.Serialize(exceptionInfo)
                );

            if (!cfg.NoAck)
            {
                _logger.LogDebug($"Nack'ing message with delivery tag '{args.DeliveryTag}'.");
                rawConsumer.Model.BasicNack(args.DeliveryTag, false, false);
            }
            return(Task.FromResult(true));
        }
예제 #13
0
        public async Task <T> Create <T>(string partitionKey, string id, T sagaData)
        {
            var json = _serializer.Serialize(sagaData);

            using (var connection = await GetConnection().ConfigureAwait(false))
            {
                var sql     = $@"INSERT INTO {_schema}.{_tableName} (PartitionKey, Id, Json) VALUES (@PartitionKey, @Id, @Json)";
                var command = GetCommandWithParameters(sql, connection, partitionKey, id);
                command.Parameters.AddWithValue("@Json", json);
                try
                {
                    await command.ExecuteNonQueryAsync();
                }
                catch (SqlException e) when(e.Number == 208)
                {
                    await CreateSagaTable(connection);

                    return(await Create(partitionKey, id, sagaData).ConfigureAwait(false));
                }
                catch (SqlException e) when(e.Number == 2627)
                {
                    throw new SagaAlreadyStartedException(partitionKey, id);
                }
            }

            return(sagaData);
        }
예제 #14
0
        protected virtual byte[] OnEncode(object message)
        {
            if (message == null)
            {
                return(new byte[0]);
            }

            if (message.GetType() == typeof(byte[]))
            {
                return((byte[])message);
            }

            if (message is InvokeMessage invoke)
            {
                //var model = Activator.CreateInstance(typeof(TInvoke),invoke);
                var model = new TInvoke();
                model.SetValue(invoke);
                return(_serializer.Serialize(model));
            }

            if (message is MessageResult result)
            {
                var model = new TResult();
                model.SetResult(result);
                return(_serializer.Serialize(model));
            }

            return(_serializer.SerializeNoType(message));
        }
예제 #15
0
        /// <summary>
        /// Performs the actual publishing of a message to the bus
        /// </summary>
        /// <param name="message">Message to publish</param>
        /// <param name="type">Type of the message</param>
        private void InternalPublish(object message, Type type)
        {
            Log.TraceFormat("Publishing message of type {0}", type);
            string messageString = _messageSerializer.Serialize(message);

            _messagePublisher.Publish(messageString, type);
            Log.TraceFormat("Published message of type {0}", type);
        }
예제 #16
0
        public static void Test <T>(IMessageSerializer <T> serializer, T message) where T : P2PMessage
        {
            byte[] serialized   = serializer.Serialize(message);
            T      deserialized = serializer.Deserialize(serialized);

            byte[] serializedAgain = serializer.Serialize(deserialized);
            Assert.AreEqual(serialized.ToHexString(), serializedAgain.ToHexString(), "test old way");
        }
예제 #17
0
        public async Task AddSubscriberAsync <TMessage>(MessageSubscriber <TMessage> messageSubscriber)
            where TMessage : Message
        {
            var subscriberKey = exchangeSubscribersResolver.GetSubscriberKey <TMessage>();
            var serialized    = messageSerializer.Serialize(messageSubscriber.MessageSubscriberInfo);

            await database.SetAddAsync(subscriberKey, serialized);
        }
예제 #18
0
        public async Task <Dictionary <ServiceDictionaryKey, object> > TryGetPatientById(HttpRequest req, string idText)
        {
            Dictionary <ServiceDictionaryKey, object> dictionary = new Dictionary <ServiceDictionaryKey, object>();

            if (!_queryHelper.IsValidId(dictionary, idText))
            {
                return(dictionary);
            }

            try
            {
                int id = Int32.Parse(idText);

                // Auth
                try
                {
                    if (!await IsAuthorized(dictionary, req, id))
                    {
                        return(dictionary);
                    }
                }
                catch
                {
                    dictionary.Add(ServiceDictionaryKey.ERROR, "Auth threw an error. Has the token lifetime expired?");
                    dictionary.Add(ServiceDictionaryKey.HTTPSTATUSCODE, HttpStatusCode.Unauthorized);
                    return(dictionary);
                }

                Patient patient = await _patientRepository.Select(id);

                if (patient.PatientId <= 0)
                {
                    dictionary.Add(ServiceDictionaryKey.ERROR, $"No patient found for given ID: {id}.");
                    dictionary.Add(ServiceDictionaryKey.HTTPSTATUSCODE, HttpStatusCode.NotFound);
                    return(dictionary);
                }

                PatientReturnModel returnModel = new PatientReturnModel()
                {
                    Id                = patient.PatientId,
                    DateOfBirth       = patient.DateOfBirth,
                    WeightInKilograms = patient.WeightInKilograms,
                    FirstName         = patient.FirstName,
                    LastName          = patient.LastName
                };

                dynamic data = _messageSerializer.Serialize(returnModel);
                dictionary.Add(ServiceDictionaryKey.VALUE, data);
            }
            catch (Exception ex)
            {
                dictionary.AddErrorMessage(ServiceDictionaryKey.ERROR, ex, FeedbackHandler);
            }

            return(dictionary);
        }
 public Task EnqueueAsync(ClaimsPrincipal user, IReadOnlyCollection <Message> messages)
 {
     foreach (var msg in messages)
     {
         var dto = new AdoNetMessageDto(user, msg, _messageSerializer);
         _messageSerializer.Serialize(dto, out var json, out var contentType);
         InsertMessage(json, contentType);
     }
     return(Task.FromResult <object>(null));
 }
예제 #20
0
        public Task <long> WriteEvents(string stream, IFullEvent[] events,
                                       IDictionary <string, string> commitHeaders, long?expectedVersion = null)
        {
            _cache.Evict(stream);

            var translatedEvents = events.Select(e =>
            {
                var descriptor = new EventDescriptor
                {
                    EventId       = e.EventId ?? Guid.NewGuid(),
                    CommitHeaders = (commitHeaders ?? new Dictionary <string, string>()).Merge(new Dictionary <string, string>
                    {
                        [Defaults.InstanceHeader]          = Defaults.Instance.ToString(),
                        [Defaults.EndpointHeader]          = Configuration.Settings.Endpoint,
                        [Defaults.EndpointVersionHeader]   = Configuration.Settings.EndpointVersion.ToString(),
                        [Defaults.AggregatesVersionHeader] = Configuration.Settings.AggregatesVersion.ToString(),
                        [Defaults.MachineHeader]           = Environment.MachineName
                    }),
                    Compressed = _compress.HasFlag(Compression.Events),
                    EntityType = e.Descriptor.EntityType,
                    StreamType = e.Descriptor.StreamType,
                    Bucket     = e.Descriptor.Bucket,
                    StreamId   = e.Descriptor.StreamId,
                    Parents    = e.Descriptor.Parents,
                    Version    = e.Descriptor.Version,
                    Timestamp  = e.Descriptor.Timestamp,
                    Headers    = e.Descriptor.Headers,
                };

                var mappedType = e.Event.GetType();
                if (!mappedType.IsInterface)
                {
                    mappedType = _mapper.GetMappedTypeFor(mappedType) ?? mappedType;
                }

                var @event = _serializer.Serialize(e.Event);

                if (_compress.HasFlag(Compression.Events))
                {
                    descriptor.Compressed = true;
                    @event = @event.Compress();
                }
                var metadata = _serializer.Serialize(descriptor);

                return(new EventData(
                           descriptor.EventId,
                           mappedType.AssemblyQualifiedName,
                           !descriptor.Compressed,
                           @event,
                           metadata
                           ));
            }).ToArray();

            return(DoWrite(stream, translatedEvents, expectedVersion));
        }
예제 #21
0
        public NetMQMessage Marshall(Message msg)
        {
            var json   = _serializer.Serialize(msg);
            var result = new NetMQMessage(new[]
            {
                new NetMQFrame(InternalMessage),
                new NetMQFrame(json),
            });

            return(result);
        }
예제 #22
0
 public async ValueTask SendAsync <TTopic, TMessage>(
     TTopic topic,
     TMessage message,
     CancellationToken cancellationToken = default)
     where TTopic : notnull
 {
     ISubscriber subscriber        = _connection.GetSubscriber();
     var         serializedTopic   = topic is string s ? s : _messageSerializer.Serialize(topic);
     var         serializedMessage = _messageSerializer.Serialize(message);
     await subscriber.PublishAsync(serializedTopic, serializedMessage).ConfigureAwait(false);
 }
예제 #23
0
        private void Send(object obj)
        {
            var msg = new Message
            {
                Label     = obj.ToString(),
                Extension = Guid.NewGuid().ToByteArray()
            };

            messageSerializer.Serialize(new[] { obj }, msg.BodyStream);
            queue.Send(msg);
        }
예제 #24
0
        public async Task <T> Create <T>(string partitionKey, string id, T sagaData, TimeSpan ttl)
        {
            var saga      = _serializer.Serialize(sagaData);
            var sagaSaved = await _db.StringSetAsync(GetKey(partitionKey, id), saga, ttl, When.NotExists).ConfigureAwait(false);

            if (!sagaSaved)
            {
                throw new SagaAlreadyStartedException(partitionKey, id);
            }
            return(sagaData);
        }
예제 #25
0
        public void ShouldRegisterSerializableTypesFromAssembly()
        {
            BinaryMessageSerializer.RegsterSerializableFrom(GetType().Assembly);
            var bytes1 = _subject.Serialize(new ResponseMessage("1", new Greeting1 {
                Hello = "hello"
            }));
            var bytes2 = _subject.Serialize(new ResponseMessage("1", new Greeting2 {
                Hello = "hello"
            }));

            Assert.That(bytes1.Length, Is.LessThan(bytes2.Length));
        }
예제 #26
0
        public static void Test <T>(IMessageSerializer <T> serializer, T message, string expectedData = null) where T : P2PMessage
        {
            byte[] serialized   = serializer.Serialize(message);
            T      deserialized = serializer.Deserialize(serialized);

            byte[] serializedAgain = serializer.Serialize(deserialized);
            Assert.AreEqual(serialized.ToHexString(), serializedAgain.ToHexString(), "test old way");

            if (expectedData != null)
            {
                Assert.AreEqual(expectedData, serialized.ToHexString());
            }
        }
예제 #27
0
        public NetMQMessage Marshall(RoutableMessage msg)
        {
            var json   = _serializer.Serialize(msg);
            var result = new NetMQMessage(new[]
            {
                new NetMQFrame(RoutableMessage),
                new NetMQFrame(EmptyByteArray),
                new NetMQFrame(msg.RoutingTarget.Bytes),
                new NetMQFrame(EmptyByteArray),
                new NetMQFrame(json),
            });

            return(result);
        }
예제 #28
0
        private async Task <object> SendInternalAsync <TMessage>(TMessage message, CancellationToken cancellation)
        {
            ThrowIfDisposed();
            await Initialization;

            // Reserve a new slot in the response table.
            using (var responseTableSlot = new ResponseTableSlot(this))
            {
                _logger?.LogInformation($"Sending message of type '{typeof(TMessage).FullName}' with seq-num '{responseTableSlot.SeqNum}'.");

                cancellation.ThrowIfCancellationRequested();

                try
                {
                    // Serialize the message and send it.
                    await SendPayloadAsync(_serializer.Serialize(message, MessageEncoding.Bson), responseTableSlot.SeqNum, 0, MessageType.Message, MessageEncoding.Bson, cancellation);
                }
                catch (Exception exc) when(!(exc is ObjectDisposedException))
                {
                    _logger?.LogError($"The message with the seq-num '{responseTableSlot.SeqNum}' could not be sent.", exc);

                    throw;
                }

                _logger?.LogInformation($"Sent message with seq-num '{responseTableSlot.SeqNum}'. Waiting for response.");

                try
                {
                    // Wait for a reponse fromthe remote end-point or cancellation alternatively.
                    await Task.WhenAny(responseTableSlot.Response, cancellation.AsTask());
                }
                catch (MessageHandlerNotFoundException)
                {
                    _logger?.LogInformation($"The receiver cannot handle the message with seq-num '{responseTableSlot.SeqNum}'. No suitable message handler was found.");

                    throw;
                }
                catch (Exception exc) when(!(exc is OperationCanceledException))
                {
                    _logger?.LogInformation($"Received response for the message with seq-num '{responseTableSlot.SeqNum}'.");

                    throw;
                }

                _logger?.LogInformation($"Received response for the message with seq-num '{responseTableSlot.SeqNum}'.");

                return(await responseTableSlot.Response);
            }
        }
예제 #29
0
        public async Task PublishAsync <T>(T message, PublishOptions?options = null, SchedulingOptions?scheduling = null, bool triggerSaveChanges = true, CancellationToken cancellationToken = default) where T : class
        {
            var address = options?.TargetAddress;

            if (address == null)
            {
                address = _addressProvider.Get(message, options);
            }

            var now = DateTime.UtcNow;

            var scheduled = now;

            if (scheduling != null)
            {
                if (scheduling.ExactDateTime != null)
                {
                    scheduled = scheduling.ExactDateTime.Value;
                }
                else if (scheduling.RelativeFromNow != null && scheduling.RelativeFromNow > TimeSpan.Zero)
                {
                    scheduled = now.Add(scheduling.RelativeFromNow.Value);
                }

                if (scheduled < now)
                {
                    scheduled = now;
                }
            }

            var entity = new OutboxMessage
            {
                OutboxMessageId = Guid.NewGuid(),
                Created         = now,
                Scheduled       = scheduled,
                Published       = null,
                TargetAddress   = address,
                Body            = _serializer
                                  .Serialize(message)
                                  .ToArray(),
                Options = options != null
                    ? _serializer.Serialize(options).ToArray()
                    : null
            };

            await _messageStore.SaveAsync <T>(entity, message.GetType(), triggerSaveChanges, cancellationToken).ConfigureAwait(false);

            StreamFlowOutboxPublisher.Continue.Set();
        }
예제 #30
0
        public Task <long> WriteEvents(string stream, IFullEvent[] events,
                                       IDictionary <string, string> commitHeaders, long?expectedVersion = null)
        {
            Logger.Write(LogLevel.Debug, () => $"Writing {events.Count()} events to stream id [{stream}].  Expected version: {expectedVersion}");

            var translatedEvents = events.Select(e =>
            {
                var descriptor = new EventDescriptor
                {
                    EventId       = e.EventId ?? Guid.NewGuid(),
                    CommitHeaders = commitHeaders ?? new Dictionary <string, string>(),
                    Compressed    = _compress.HasFlag(Compression.Events),
                    EntityType    = e.Descriptor.EntityType,
                    StreamType    = e.Descriptor.StreamType,
                    Bucket        = e.Descriptor.Bucket,
                    StreamId      = e.Descriptor.StreamId,
                    Parents       = e.Descriptor.Parents,
                    Version       = e.Descriptor.Version,
                    Timestamp     = e.Descriptor.Timestamp,
                    Headers       = e.Descriptor.Headers
                };

                var mappedType = e.Event.GetType();
                if (!mappedType.IsInterface)
                {
                    mappedType = _mapper.GetMappedTypeFor(mappedType) ?? mappedType;
                }

                var @event = _serializer.Serialize(e.Event);

                if (_compress.HasFlag(Compression.Events))
                {
                    descriptor.Compressed = true;
                    @event = @event.Compress();
                }
                var metadata = _serializer.Serialize(descriptor);

                return(new EventData(
                           descriptor.EventId,
                           mappedType.AssemblyQualifiedName,
                           !descriptor.Compressed,
                           @event,
                           metadata
                           ));
            }).ToArray();

            return(DoWrite(stream, translatedEvents, expectedVersion));
        }
예제 #31
0
        public Task PublishAsync <TMessage>(TMessage message, Guid globalMessageId, PublishConfiguration config)
        {
            var context = _contextProvider.GetMessageContext(globalMessageId);
            var props   = _propertiesProvider.GetProperties <TMessage>(config.PropertyModifier + (p => p.Headers.Add(PropertyHeaders.Context, context)));

            Task exchangeTask;

            lock (_topologyLock)
            {
                exchangeTask = _topologyProvider.DeclareExchangeAsync(config.Exchange);
            }
            var channelTask = _channelFactory.GetChannelAsync();

            return(Task
                   .WhenAll(exchangeTask, channelTask)
                   .ContinueWith(t =>
            {
                lock (_publishLock)
                {
                    var ackTask = _acknowledger.GetAckTask(channelTask.Result);
                    channelTask.Result.BasicPublish(
                        exchange: config.Exchange.ExchangeName,
                        routingKey: _config.RouteWithGlobalId ? $"{config.RoutingKey}.{globalMessageId}" : config.RoutingKey,
                        basicProperties: props,
                        body: _serializer.Serialize(message)
                        );
                    return ackTask;
                }
            })
                   .Unwrap());
        }
예제 #32
0
 public static Message FromObject(object obj, IMessageSerializer serializer)
 {
     return new Message
     {
         AssemblyQualifiedName = obj.GetType().AssemblyQualifiedName,
         ID = Guid.NewGuid(),
         TypeName = obj.GetType().Name,
         Body = serializer.Serialize(obj)
     };
 }
예제 #33
0
 public static ChannelMessage CreateChannelMessage(object message, IMessageSerializer messageSerializer)
 {
     if (messageSerializer == null) throw new ArgumentNullException(nameof(messageSerializer));
     var messageType = message.GetType();
     var stream = messageSerializer.Serialize(message);
     var channelMessage = new ChannelMessage(stream);
     channelMessage.AddHeader(MessageHeaders.MessageType, messageType.FullName);
     channelMessage.AddHeader(MessageHeaders.UserPrincipal, Environment.UserName);
     channelMessage.AddHeader(MessageHeaders.SendingMachine, Environment.MachineName);
     channelMessage.AddHeader(MessageHeaders.SendingModule, ResolveAssemblyFullName());
     return channelMessage;
 }
예제 #34
0
        internal static object Reserialize(IMessageSerializer serializer, object message)
        {
            if (serializer == null)
                return message;

            var writer = new BinaryTokenStreamWriter();
            serializer.Serialize(message, writer);

            var bytes = writer.ToByteArray();
            var reader = new BinaryTokenStreamReader(bytes);

            return serializer.Deserialize(reader);
        }
예제 #35
0
        private IMessage InvokeMutators(IMessage message, IMessageSerializer serializer)
        {
            var messageToSerialize = messageMutator.MutateOutgoing(message);
            using (var stream = new MemoryStream())
            {
                serializer.Serialize(new[] { messageToSerialize }, stream);

                stream.Position = 0;

                var result = serializer.Deserialize(stream)[0];

                return messageMutator.MutateIncoming(result);
            }
        }
예제 #36
0
        public static void Convert(TransportMessage message, IBytesMessage toSend, IMessageSerializer serializer)
        {
            byte[] body;
            if (message.Body == null && message.BodyStream != null)
            {
                body = message.BodyStream.ToBytes();
            }
            else
            {
                var stream = new MemoryStream();
                serializer.Serialize(message.Body, stream);
                body = stream.ToBytes();
            }

            toSend.WriteBytes(body);

            // TODO: clarify usage of JMSCorrelationID
            toSend.JMSCorrelationID = message.CorrelationId;
            toSend.JMSDeliveryMode = message.Recoverable ? DeliveryMode.Persistent : DeliveryMode.NonPersistent;
            toSend.SetStringProperty(HEADER_RETURNADDRESS, message.ReturnAddress);
            toSend.SetStringProperty(HEADER_IDFORCORRELATION, message.IdForCorrelation);
            toSend.SetStringProperty(HEADER_WINDOWSIDENTITYNAME, message.WindowsIdentityName);
            toSend.SetIntProperty(HEADER_MESSAGEINTENT, (int) message.MessageIntent);

            //TODO: set message expiration
            //toSend.JMSReplyTo = new Destination message.ReplyToAddress;
            //if (message.TimeToBeReceived < MessageQueue.InfiniteTimeout)
            //toSend.JMSExpiration = (long) UTCNow.message.TimeToBeReceived.TotalMilliseconds;

            if (message.Headers == null)
                message.Headers = new List<HeaderInfo>();

            var nsbHeaderKeys = new List<string>();
            foreach (var keyValue in message.Headers)
            {
                toSend.SetStringProperty(keyValue.Key.ToXmsFriendly(), keyValue.Value);
                nsbHeaderKeys.Add(keyValue.Key.ToXmsFriendly());
            }
            toSend.SetStringProperty(HEADER_NBSKEYS, WrapKeys(nsbHeaderKeys));
        }
예제 #37
0
        public void SetUp()
        {
            A.Fake<IConnectionFactory>();
            _connection = A.Fake<IConnection>();
            _lazyConnection = new Lazy<IConnection>(() =>
            {
                _connection.Start();
                return _connection;
            });
            _session = A.Fake<ISession>();
            _producer = A.Fake<IMessageProducer>();
            _serializer = A.Fake<IMessageSerializer>();
            _destination = A.Fake<IDestination>();
            _message = A.Fake<ITextMessage>();
            _messagePropertyProvider = A.Fake<IMessagePropertyProvider<IMessage>>();

            A.CallTo(() => _connection.CreateSession(A<Apache.NMS.AcknowledgementMode>.Ignored)).Returns(_session);
            A.CallTo(() => _session.CreateProducer(_destination)).Returns(_producer);
            A.CallTo(() => _session.CreateTextMessage(A<string>._)).Returns(_message);
            A.CallTo(() => _serializer.Serialize(A<object>._)).Returns("SerializedString");

            _testScheduler = new TestScheduler();
            _publisher = new MessagePublisher<IMessage>(_lazyConnection, _destination, _serializer, _messagePropertyProvider, _testScheduler);
        }
예제 #38
0
        public static MessageExecutionCompleted Success(MessageId sourceCommandId, IMessage payload, IMessageSerializer serializer)
        {
            var payloadBytes = serializer.Serialize(payload);

            return new MessageExecutionCompleted(sourceCommandId, payload.TypeId(), payloadBytes);
        }