Example #1
0
        public void Subscribe <TDomainEvent>(string database, string channel,
                                             Action <TDomainEvent> handler)
            where TDomainEvent : IDomainEvent
        {
            if (string.IsNullOrWhiteSpace(channel))
            {
                throw new ArgumentException("Channel not specified.", nameof(channel));
            }

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

            var subscriber = _connModule.GetSubscriber(database);

            subscriber.Subscribe(channel, (onChannel, message) =>
            {
                var messageParts = ChannelMessageEncoder.UnPack(message);

                TDomainEvent domainEvent = _serializationMgr.Deserialize <TDomainEvent>(
                    messageParts.contentType,
                    messageParts.messageData);

                LogReceivedDomainEvent(database, channel, domainEvent);
                handler(domainEvent);
            });
        }
Example #2
0
        public IDisposable SendRequestAsync <TRequest, TResponse>(
            TRequest request,
            Endpoint endpoint,
            Action <TResponse> callback,
            Action <Exception> onFailure,
            long timeout,
            string processingGroup = null)
        {
            if (m_Disposing.WaitOne(0))
            {
                throw new InvalidOperationException("Engine is disposing");
            }

            using (m_RequestsTracker.Track())
            {
                try
                {
                    var           session       = m_TransportManager.GetMessagingSession(endpoint.TransportId, GetProcessingGroup(endpoint, processingGroup));
                    RequestHandle requestHandle = session.SendRequest(
                        endpoint.Destination.Publish,
                        SerializeMessage(endpoint.SerializationFormat, request),
                        message =>
                    {
                        try
                        {
                            var responseMessage = m_SerializationManager.Deserialize <TResponse>(endpoint.SerializationFormat, message.Bytes);
                            callback(responseMessage);
                        }
                        catch (Exception e)
                        {
                            onFailure(e);
                        }
                        finally
                        {
                            m_RequestTimeoutManager.Schedule(1);
                        }
                    });

                    lock (m_ActualRequests)
                    {
                        requestHandle.DueDate = DateTime.UtcNow.AddMilliseconds(timeout);
                        m_ActualRequests.Add(requestHandle, onFailure);
                        m_RequestTimeoutManager.Schedule(timeout);
                    }
                    return(requestHandle);
                }
                catch (Exception e)
                {
                    _log.WriteError(nameof(SendRequestAsync), $"Failed to register handler. Transport: {endpoint.TransportId}, Destination: {endpoint.Destination}", e);
                    throw;
                }
            }
        }
Example #3
0
        private async Task StartWorkerAsync <T>(IMessageConsumer consumer, SubscriptionInfo <T> subscriptionInfo, ConcurrentQueue <ITextMessage> queue, CancellationToken cancellationToken) where T : class, Options.IMessage
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                ITextMessage messageInfo;

                //messageInfo = consumer.Receive(TimeSpan.FromMilliseconds(2000));
                var result = queue.TryDequeue(out messageInfo);
                if (messageInfo != null)
                {
                    var jsonMessage = messageInfo.Text;
                    var message     = serializationManager.Deserialize <T>(jsonMessage);
                    try
                    {
                        await subscriptionInfo.OnReceivedAsync?.Invoke(message, cancellationToken);

                        messageInfo.Acknowledge();
                    }
                    catch (Exception ex)
                    {
                        await subscriptionInfo?.OnErrorAsync?.Invoke(message, ex, cancellationToken);
                    }
                }
                await Task.Delay(1000, cancellationToken);
            }
        }
Example #4
0
 public static T Deserialize <T>(this ISerializationManager serializationManager, byte[] inputValue)
 {
     using (var ms = new System.IO.MemoryStream(inputValue))
     {
         return((T)serializationManager.Deserialize(ms, typeof(T)));
     }
 }
 public static object Deserialize(this ISerializationManager serializationManager, byte[] inputValue, Type type)
 {
     using (var ms = new System.IO.MemoryStream(inputValue))
     {
         return(serializationManager.Deserialize(ms, type));
     }
 }
Example #6
0
        private async Task SubscribeToChannels(IEnumerable <MessageChannelSubscriber> subscribers)
        {
            foreach (var msgSubscriber in subscribers)
            {
                ISubscriber subscriber = ConnModule.GetSubscriber(msgSubscriber.DatabaseName);

                // Callback invoked when message published to channel:
                await subscriber.SubscribeAsync(msgSubscriber.Channel, (channel, message) =>
                {
                    Type messageType = msgSubscriber.DispatchInfo.MessageType;
                    var messageParts = ChannelMessageEncoder.UnPack(message);

                    // Deserialize message byte array into domain-event type associated with handler:
                    IDomainEvent domainEvent = (IDomainEvent)_serializationManager.Deserialize(
                        messageParts.contentType,
                        messageType,
                        messageParts.messageData);

                    LogReceivedDomainEvent(channel, domainEvent, msgSubscriber);

                    // Invoke the in-process handler:
                    DispatchModule.InvokeDispatcherInNewLifetimeScopeAsync(
                        msgSubscriber.DispatchInfo,
                        domainEvent).Wait();
                });
            }
        }
        public object Get(string key, Type type)
        {
            var typeCode = Type.GetTypeCode(type);

            switch (typeCode)
            {
            case TypeCode.Boolean: return(preferences.GetBoolean(key, false));

            case TypeCode.String: return(preferences.GetString(key, null));

            case TypeCode.Single: return(preferences.GetFloat(key, 0));

            case TypeCode.Int64: return(preferences.GetLong(key, 0));

            case TypeCode.Int16:
            case TypeCode.Int32:
                return(preferences.GetInt(key, 0));

#if FEATURE_SERIALIZATION
            case TypeCode.Object:
            {
                var stringValue = preferences.GetString(key, null);
                return(serializationManager.Deserialize(stringValue, type));
            }
#endif

            default:
                throw new NotSupportedException();
            }
        }
Example #8
0
        public async Task ProcessMessagesAsync <T>(SubscriptionInfo <T> subscriptionInfo, CancellationToken cancellationToken) where T : class, IMessage
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                try
                {
                    var messages = await _sqsClient.ReceiveMessageAsync(new ReceiveMessageRequest
                    {
                        MaxNumberOfMessages = 2,
                        QueueUrl            = "http://localhost:9324/queue/default"
                    });

                    var data = messages.Messages;


                    foreach (var item in data)
                    {
                        var message = _serializationManager.Deserialize <T>(item.Body);
                        await subscriptionInfo.OnReceivedAsync?.Invoke(message, cancellationToken);

                        await _sqsClient.DeleteMessageAsync(new DeleteMessageRequest { QueueUrl = "http://localhost:9324/queue/default", ReceiptHandle = item.ReceiptHandle });
                    }
                }
                catch (Exception ex)
                {
                    throw;
                }

                await Task.Delay(1000);
            }
        }
Example #9
0
        private void RpcConsumerReplyReceived(BasicDeliverEventArgs deliveryEvent)
        {
            ValidateRpcReply(deliveryEvent);

            // Determine the command type based on the type name stored in basic properties.  NOTE: a command type name is
            // just a value used to identify the type used to determine the C# class type on the receiving end corresponding
            // to the type on the caller's end.  They may or may not be the same physical C# type.
            string typeName    = deliveryEvent.BasicProperties.Type;
            Type   commandType = _brokerState.RpcTypes[typeName];

            // Dispatch the message the handler to obtain the result.
            MessageDispatchInfo dispatcher = _messagingModule.GetInProcessCommandDispatcher(commandType);
            IMessage            message    = _serializationMgr.Deserialize(commandType, deliveryEvent);
            object result = null;

            try
            {
                result = _messagingModule.InvokeDispatcherAsync(dispatcher, message).Result;

                // Publish the reply back to the publisher that made the request on the
                // queue specified by them in the message header on a new channel.
                PublishConsumerReply(result, deliveryEvent.BasicProperties);
            }
            catch (AggregateException ex)
            {
                PublishConsumerExceptionReply(ex.InnerException, deliveryEvent.BasicProperties);
            }
            catch (Exception ex)
            {
                PublishConsumerExceptionReply(ex, deliveryEvent.BasicProperties);
            }
        }
        /// <summary>
        /// Publishes a message to a consumer defined queue used for receiving
        /// RPC style messages.  The caller awaits the reply response message.
        /// </summary>
        /// <param name="message">The RPC style message to publish.</param>
        /// <returns>Future result after the reply is received.</returns>
        public async Task PublishToRpcConsumerAsync(IMessage message, CancellationToken cancellationToken)
        {
            Check.NotNull(message, nameof(message));

            AssertRpcCommand(message);

            var rpcCommandAttrib = message.GetAttribute <RpcCommandAttribute>();
            var command          = message as ICommand;

            RpcProperties rpcProps = new RpcProperties {
                ContentType      = rpcCommandAttrib.ContentType,
                ExternalTypeName = rpcCommandAttrib.ExternalTypeName
            };

            // Obtain the consumer queue on which the message should be published.
            RpcMessagePublisher rpcPublisher = GetRpcPublisher(rpcCommandAttrib);

            string[] orderedContentTypes =
            {
                message.GetContentType(),
                rpcProps.ContentType,
                rpcPublisher.ContentType
            };

            byte[] messageBody = _serializationMgr.Serialize(command, orderedContentTypes);

            LogPublishedRpcMessage(message, rpcPublisher, rpcProps);

            // Publish the RPC request the consumer's queue and await a response.
            rpcProps.ContentType = command.GetContentType();
            byte[] replyBody = null;

            try
            {
                replyBody = await rpcPublisher.Client.Invoke(command, rpcProps, cancellationToken, messageBody);

                object reply = _serializationMgr.Deserialize(rpcProps.ContentType, command.ResultType, replyBody);
                command.SetResult(reply);
                LogReceivedRpcResponse(message, rpcPublisher);
            }
            catch (RpcReplyException ex)
            {
                var dispatchEx = _serializationMgr.Deserialize <MessageDispatchException>(rpcProps.ContentType, ex.Exception);
                _logger.LogError(RabbitMqLogEvents.PUBLISHER_RPC_RESPONSE, "RPC Exception Reply.", dispatchEx);
                throw dispatchEx;
            }
        }
Example #11
0
        public T CloneObject <T>(T objectToClone) where T : class
        {
            var updatable = objectToClone as IUpdatable;

            if (updatable != null)
            {
                return(Clone(updatable) as T);
            }

            var stream = _serializationManager.Serialize(objectToClone);
            var clone  = _serializationManager.Deserialize <T>(stream);

            _objectIdResetter.ResetIdFor(clone);
            return(clone);
        }
        public static object Deserialize(this ISerializationManager serializationManager, string input, Type type, Encoding encoding = null)
        {
            if (encoding == null)
            {
                if (serializationManager is ISerializationManager_TextEncoding)
                {
                    encoding = ((ISerializationManager_TextEncoding)serializationManager).Encoding;
                }
                else
                {
                    // TODO: Do a policy thing here, throw exception or a default
                    encoding = Encoding.UTF8;
                }
            }

            var stream = new ReadonlyStringStream(input, encoding);

            return(serializationManager.Deserialize(stream, type));
        }
Example #13
0
        // Deserialize the message into the type associated with the message dispatch
        // metadata and delegates to the messaging module to dispatch the message to
        // consumer handlers.
        private void MessageReceived(MessageConsumer messageConsumer, IModel channel, BasicDeliverEventArgs deliveryEvent)
        {
            IMessage message = _serializationMgr.Deserialize(messageConsumer.DispatchInfo.MessageType, deliveryEvent);

            message.SetAcknowledged(false);

            LogReceivedExchangeMessage(message, messageConsumer);

            // Delegate to the Messaging Module to dispatch the message to queue consumer.
            Task <object> futureResult = _messagingModule.InvokeDispatcherAsync(
                messageConsumer.DispatchInfo, message);

            futureResult.Wait();

            if (!messageConsumer.QueueSettings.IsNoAck)
            {
                HandleAcknowledgeMessage(message, channel, deliveryEvent);
            }

            HandleRejectedMessage(message, channel, deliveryEvent);
        }
        public ISubscription Subscribe <T>(Func <T, MessageContext, Task> callback, SubscriptionOptions?options = null)
        {
            var autoAck  = options?.AutoAck ?? true;
            var exchange = options?.Exchange ?? _config.DefaultExchange;

            if (exchange is null)
            {
                throw new InvalidExchangeException();
            }

            var model = CreateModel();

            EnsureExchangeCreated(model, exchange, options.ExchangeType());
            var queueName = EnsureQueueCreated(model, exchange, options?.Queue, options?.RoutingKeys);

            var consumer    = new AsyncEventingBasicConsumer(model);
            var consumerTag = model.BasicConsume(queue: queueName, autoAck: autoAck, consumer: consumer);

            consumer.Received += async(_, eventArgs) =>
            {
                var context  = new MessageContext(eventArgs, autoAck, model);
                var activity = MessageDiagnostics.StartMessageIn(context);

                try
                {
                    var obj = _serialization.Deserialize <T>(eventArgs.Body, eventArgs.BasicProperties.ContentType);
                    await callback(obj, context);
                }
                finally
                {
                    MessageDiagnostics.StopMessageIn(activity, context);
                }
            };

            return(new SubscriptionImpl(model, consumerTag));
        }
 public static T Deserialize <T>(this ISerializationManager serializationManager, string input, Encoding encoding = null)
 {
     return((T)serializationManager.Deserialize(input, typeof(T), encoding));
 }
Example #16
0
        public virtual T SerializeAndDeserialize(T source, SerializationContext serializationContext = null)
        {
            var stream = _serializationManager.Serialize(source);

            return(_serializationManager.Deserialize <T>(stream, serializationContext));
        }
        public object Get(string key, Type type)
        {
            var valueByteArray = blobCache.Get(key).Wait();

            return(serializationManager.Deserialize(valueByteArray, type));
        }
Example #18
0
        public virtual T SerializeAndDeserialize(T source)
        {
            var stream = _serializationManager.Serialize(source);

            return(_serializationManager.Deserialize <T>(stream));
        }
Example #19
0
        public object Get(string key, Type type)
        {
            var value = cache.Get(key);

            return(serializationManager.Deserialize(value, type));
        }
 public TObject Deserialize <TObject>(byte[] serializationBytes, SerializationContext serializationContext = null)
 {
     return(_serializationManager.Deserialize <TObject>(decompressedByte(serializationBytes), serializationContext));
 }
 public static T Deserialize <T>(this ISerializationManager serializationManager, byte[] input)
 {
     return((T)serializationManager.Deserialize(input, typeof(T)));
 }
Example #22
0
 public TObject Deserialize <TObject>(string serializationString)
 {
     return(_serializationManager.Deserialize <TObject>(bytesFrom(serializationString)));
 }