Ejemplo n.º 1
0
        public TMessage GetMessage <TMessage>(ISerializationStrategy serializationStrategy, bool retry)
            where TMessage : class
        {
            TMessage message = default(TMessage);

            if (!retry)
            {
                Console.WriteLine("Getting message ...");
                BasicGetResult args = _channel.BasicGet(_queueName, true);
                if (args != null)
                {
                    message = new BinarySerializationStrategy().Deserialize <TMessage>(args.Body);
                }
                return(message);
            }

            new Action(() =>
            {
                try
                {
                    var consumer = new QueueingBasicConsumer(_channel);
                    Console.WriteLine("Consuming messages ...");
                    _channel.BasicConsume(_queueName, true, "", null, consumer);
                    var args = (BasicDeliverEventArgs)consumer.Queue.Dequeue();
                    message  = serializationStrategy.Deserialize <TMessage>(args.Body);
                }
                catch (EndOfStreamException)
                {
                }
            }).Background().BlockUntil(() => message != null)();

            return(message);
        }
Ejemplo n.º 2
0
        public static T Deserialize <T>(this string serializedValue, ISerializationStrategy serializationStrategy) where T : class
        {
            if (typeof(T) == typeof(String))
            {
                return(serializedValue as T);
            }

            return((T)serializationStrategy.Deserialize(typeof(T), serializedValue));
        }
Ejemplo n.º 3
0
        // I do have dependecy in my project on JSON.Net, but who said, that I can't abstract using it, so I could change serializer without having to modify code, that depends on serialization/deserialiation
        protected async Task <T> Get <T>(string endpoint, ISerializationStrategy <T> serializationStrategy)
        {
            string responseBody = null;

            HttpResponseMessage response = await this.HttpClient.GetAsync(endpoint);

            if (response.IsSuccessStatusCode)
            {
                responseBody = await response.Content.ReadAsStringAsync();

                T result = serializationStrategy.Deserialize(responseBody);

                return(result);
            }

            return(default(T));
        }
Ejemplo n.º 4
0
        public IMessageContext <TMessage> GetMessage()
        {
            Logger.Current.Write(string.Format("Pulling message from queue:\'{0}\' auto-acknowledge:{1}",
                                               _consumeInfo.QueueName, _consumeInfo.IsAutoAcknowledge), TraceEventType.Information);
            IMessageContext <TMessage> messageContext = null;
            BasicGetResult             result         = _channel.BasicGet(_consumeInfo.QueueName, _consumeInfo.IsAutoAcknowledge);

            if (result != null)
            {
                ISerializationStrategy serializationStrategy = _consumeInfo.SerializationStrategy ?? _defaultSerializationStrategy;
                object message = serializationStrategy.Deserialize <TMessage>(result.Body);
                messageContext = new MessageContext <TMessage>(_deadLetterStrategy, (TMessage)message, _consumeInfo, _channel, result.DeliveryTag,
                                                               result.Redelivered, result.Exchange, result.RoutingKey,
                                                               result.BasicProperties, result.Body, _messagePublisher);
            }

            return(messageContext);
        }
Ejemplo n.º 5
0
        public IBasicProperties GetMessageProperties <TMessage>(ISerializationStrategy serializationStrategy)
            where TMessage : class
        {
            TMessage message           = default(TMessage);
            BasicDeliverEventArgs args = null;

            new Action(() =>
            {
                try
                {
                    var consumer = new QueueingBasicConsumer(_channel);
                    _channel.BasicConsume(_queueName, true, "", null, consumer);
                    args    = (BasicDeliverEventArgs)consumer.Queue.Dequeue();
                    message = serializationStrategy.Deserialize <TMessage>(args.Body);
                }
                catch (EndOfStreamException)
                {
                }
            }).Background().BlockUntil(() => message != null).Then(() => _channel.Close())();

            return(args.BasicProperties);
        }
Ejemplo n.º 6
0
        void Subscribe(IModel channel)
        {
            ILogger logger = Logger.Current;

            _stopwatch.Start();

            string log =
                string.Format(
                    "Starting thread for subscription to messages from host: {0}, port: {1}, exchange: {2}, queue: {3}, routingKey: {4}",
                    _connection.Endpoint.HostName,
                    _connection.Endpoint.Port,
                    _consumeInfo.ExchangeName,
                    _consumeInfo.QueueName,
                    _routingKey);

            logger.Write(log, TraceEventType.Information);

            while (true)
            {
                if (WaitExceeded() || _threadCancelled)
                {
                    break;
                }

                BasicDeliverEventArgs eventArgs = null;

                try
                {
                    object eArgs = null;
                    _consumer.Queue.Dequeue(1000, out eArgs);

                    if (eArgs != null)
                    {
                        eventArgs = (BasicDeliverEventArgs)eArgs;
                        logger.Write(string.Format("Message received: {0} bytes", eventArgs.Body.Length), TraceEventType.Information);
                        ISerializationStrategy serializationStrategy = _consumeInfo.SerializationStrategy ??
                                                                       _defaultSerializationStrategy;
                        object message = serializationStrategy.Deserialize <TMessage>(eventArgs.Body);

                        var messageContext = new MessageContext <TMessage>(_deadLetterStrategy, (TMessage)message,
                                                                           _consumeInfo,
                                                                           channel,
                                                                           eventArgs.DeliveryTag, eventArgs.Redelivered,
                                                                           eventArgs.Exchange, eventArgs.RoutingKey,
                                                                           eventArgs.BasicProperties, eventArgs.Body,
                                                                           _messagePublisher);

                        _callback(messageContext);

                        if (_subscriptionType == SubscriptionType.RemoteProcedure)
                        {
                            log =
                                string.Format(
                                    "Terminating RPC subscription to messages from host: {0}, port: {1}, exchange: {2}, queue: {3}, routingKey: {4}",
                                    _connection.Endpoint.HostName,
                                    _connection.Endpoint.Port,
                                    _consumeInfo.ExchangeName,
                                    _consumeInfo.QueueName,
                                    _routingKey);
                            logger.Write(log, TraceEventType.Information);
                            break;
                        }
                    }
                }
                catch (EndOfStreamException)
                {
                    logger.Write("Received EndOfStreamException.", TraceEventType.Information);
                    InvokeErrorCallback(eventArgs, channel);
                    channel.Dispose();
                    channel = null;
                    logger.Write("Subscription terminated.", TraceEventType.Information);
                    break;
                }
                catch (AlreadyClosedException e)
                {
                    Logger.Current.Write(string.Format("An AlreadyClosedException occurred: {0} {1}", e.Message, e.StackTrace), TraceEventType.Error);
                    InvokeErrorCallback(eventArgs, channel);
                    break;
                }
                catch (Exception e)
                {
                    Logger.Current.Write("An exception occurred while dequeuing a message: " + e.Message, TraceEventType.Error);
                    InvokeErrorCallback(eventArgs, channel);
                }
            }
        }
Ejemplo n.º 7
0
 public string Deserialize(string data)
 {
     return(_serializationStrategy.Deserialize(data));
 }
Ejemplo n.º 8
0
            public Persistent <TEntity> GetObject()
            {
                var o    = new Persistent <TEntity>(objectId);
                var data = persistenceStrategy.TryLoad(objectId, collectionId);

                if (data == null)
                {
                    // data does not exist, return new with default
                    return(o);
                }

                try
                {
                    o.Entity = serializationStrategy.Deserialize <TEntity>(data);
                }
                catch (DeserializationErrorsException <TEntity> exception)
                {
                    var errorContext = new ErrorContext(exception.Errors, persistenceStrategy, collectionId,
                                                        objectId);

                    objectDeserializationErrorHandlingStrategy.Handle(errorContext);

                    if (errorContext.Decision == Decision.DoNotIgnoreAndRethrowTheException)
                    {
                        throw;
                    }
                    else if (errorContext.Decision == Decision.IgnoreErrorsAndReturnDefaultsForMissingData)
                    {
                        o.Entity = exception.DeserializedFallbackEntity;
                        return(o);
                    }
                    else if (errorContext.Decision == Decision.RetryDeserialization)
                    {
                        throw new RetryException();
                    }
                    else
                    {
                        throw new InvalidOperationException("Unknown Decision: " + errorContext.Decision);
                    }
                }

                if (o.Entity.ObjectId != objectId)
                {
                    var errorContext = new ErrorContext(
                        new[]
                    {
                        new DeserializationErrorDetails()
                        {
                            DeserializationErrorKind = DeserializationErrorKind.ObjectIdMismatch
                        }
                    },
                        persistenceStrategy, collectionId, objectId);

                    objectDeserializationErrorHandlingStrategy.Handle(errorContext);

                    if (errorContext.Decision == Decision.DoNotIgnoreAndRethrowTheException)
                    {
                        throw new InvalidOperationException(
                                  string.Format(
                                      "Deserialized entity objectId {0} is different than requested objectId {1}",
                                      o.Entity.ObjectId, objectId));
                    }
                    else if (errorContext.Decision == Decision.IgnoreErrorsAndReturnDefaultsForMissingData)
                    {
                        o.Entity.ObjectId = objectId;
                    }
                    else if (errorContext.Decision == Decision.RetryDeserialization)
                    {
                        throw new RetryException();
                    }
                    else
                    {
                        throw new InvalidOperationException("Unknown Decision: " + errorContext.Decision);
                    }
                }

                return(o);
            }