Exemplo n.º 1
0
        public void DeserializeInvalidString()
        {
            DeserializationException e = Assert.Throws <DeserializationException>(delegate
            {
                IMethodInvocation deserializedMethodInvocation = testSoapMethodInvocationSerializer.Deserialize("<InvalidXml><WithoutProperClosingTag>");
            });

            Assert.That(e.Message, Is.StringStarting("Failed to deserialize method invocation."));
        }
        public void DeserializeReturnValueExceptionMetricsTest()
        {
            using (mocks.Ordered)
            {
                Expect.Once.On(mockMetricLogger).Method("Begin").With(IsMetric.Equal(new ReturnValueDeserializeTime()));
                Expect.Once.On(mockMetricLogger).Method("CancelBegin").With(IsMetric.Equal(new ReturnValueDeserializeTime()));
            }

            DeserializationException e = Assert.Throws <DeserializationException>(delegate
            {
                testSoapMethodInvocationSerializer.DeserializeReturnValue("InvalidSerializedMethodInvocation");
            });
        }
Exemplo n.º 3
0
        public void DeserializeExceptionMetricsTest()
        {
            using (mocks.Ordered)
            {
                Expect.Once.On(mockMetricLogger).Method("Begin").With(IsMetric.Equal(new MethodInvocationDeserializeTime()));
                Expect.Once.On(mockMetricLogger).Method("CancelBegin").With(IsMetric.Equal(new MethodInvocationDeserializeTime()));
            }

            DeserializationException e = Assert.Throws <DeserializationException>(delegate
            {
                testMethodInvocationSerializer.Deserialize("<?xml version=\"1.0\" encoding=\"utf-8\"?><MethodInvocationX></MethodInvocationX>");
            });
        }
Exemplo n.º 4
0
        public void DeserializeReturnValueExceptionMetricsTest()
        {
            string serializedReturnValue = "<?xml version=\"1.0\" encoding=\"utf-8\"?><ReturnValue><InvalidTag></InvalidTag></ReturnValue>";

            using (mocks.Ordered)
            {
                Expect.Once.On(mockMetricLogger).Method("Begin").With(IsMetric.Equal(new ReturnValueDeserializeTime()));
                Expect.Once.On(mockMetricLogger).Method("CancelBegin").With(IsMetric.Equal(new ReturnValueDeserializeTime()));
            }

            DeserializationException e = Assert.Throws <DeserializationException>(delegate
            {
                testMethodInvocationSerializer.DeserializeReturnValue(serializedReturnValue);
            });
        }
Exemplo n.º 5
0
        public void GetTokens_XmlDocTypeExternal_ReturnsUnparsed()
        {
            const string input =
                @"<!DOCTYPE html PUBLIC
	""-//W3C//DTD XHTML 1.1//EN""
	""http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"">
<root />";

            var tokenizer = new XmlReader.XmlTokenizer();
            DeserializationException ex = Assert.Throws <DeserializationException>(
                delegate()
            {
                var actual = tokenizer.GetTokens(input).ToArray();
            });

            Assert.Equal(0, ex.Index);
        }
Exemplo n.º 6
0
        public void Read_ArrayExtraClose_ThrowsDeserializationException()
        {
            // input from fail8.json in test suite at http://www.json.org/JSON_checker/
            var input = @"[""Extra close""]]";

            var reader = new JsonReader(new DataReaderSettings {
                AllowTrailingContent = false
            });

            DeserializationException ex = Assert.Throws <DeserializationException>(
                delegate
            {
                var actual = reader.Read(input);
            });

            // verify exception is coming from expected position
            Assert.Equal(15L, ex.Index);
        }
Exemplo n.º 7
0
        public void Read_ObjectExtraValueAfterClose_ThrowsDeserializationException()
        {
            // input from fail10.json in test suite at http://www.json.org/JSON_checker/
            var input = @"{""Extra value after close"": true} ""misplaced quoted value""";

            var reader = new JsonReader(new DataReaderSettings {
                AllowTrailingContent = false
            });

            DeserializationException ex = Assert.Throws <DeserializationException>(
                delegate
            {
                var actual = reader.Read(input);
            });

            // verify exception is coming from expected position
            // note the reader doesn't see the 2nd object until it is read
            // so the index is after the trailing value
            Assert.Equal(57L, ex.Index);
        }
Exemplo n.º 8
0
        public void GetTokens_UndeclaredPrefixes_ThrowsDeserializationException()
        {
            const string input    = @"<a:one><b:two><c:three></d:three></e:two></f:one>";
            var          expected = new[]
            {
                MarkupGrammar.TokenElementBegin(new DataName("one")),
                MarkupGrammar.TokenElementBegin(new DataName("two")),
                MarkupGrammar.TokenElementBegin(new DataName("three")),
                MarkupGrammar.TokenElementEnd,
                MarkupGrammar.TokenElementEnd,
                MarkupGrammar.TokenElementEnd
            };

            var tokenizer = new XmlReader.XmlTokenizer();

            DeserializationException ex = Assert.Throws <DeserializationException>(
                delegate()
            {
                var actual = tokenizer.GetTokens(input).ToArray();
            });

            Assert.Equal(2, ex.Index);
        }
        public async Task DoConsumeAsync(CancellationToken cancellationToken)
        {
            //Iterate while thread hasn't been canceled
            while (!cancellationToken.IsCancellationRequested)
            {
                var currentBatchCounter = _batchProcessingWorker.GetBatchSize();

                var currentBatch = new List <T>();

                BasicGetResult result;

                ulong lastDeliveryTag = 0;

                do
                {
                    result = _model.BasicGet(_queueName, false);

                    if (result != null)
                    {
                        lastDeliveryTag = result.DeliveryTag;

                        currentBatchCounter--;

                        var messageBody = GetBody(result);

                        try
                        {
                            var messageObject = _serializer.Deserialize <T>(messageBody);

                            currentBatch.Add(messageObject);
                        }
                        catch (Exception exception)
                        {
                            var deserializationException = new DeserializationException("Unable to deserialize data.", exception)
                            {
                                SerializedDataString = messageBody,
                                SerializedDataBinary = result.Body,
                                QueueName            = _queueName
                            };

                            await _messageRejectionHandler.OnRejectionAsync(deserializationException).ConfigureAwait(false);

                            //Remove message from queue after RejectionHandler dealt with it
                            _model.BasicNack(result.DeliveryTag, false, false);
                        }
                    }
                } while (currentBatchCounter > 0 && result != null);

                if (currentBatch.Count > 0)
                {
                    var batchFeedbackSender = new RabbitMQBatchFeedbackSender(_model, lastDeliveryTag);

                    try
                    {
                        await _batchProcessingWorker.OnBatchAsync(currentBatch, batchFeedbackSender,
                                                                  cancellationToken).ConfigureAwait(false);

                        if (!batchFeedbackSender.HasAcknoledged)
                        {
                            //Acknoledge message
                            batchFeedbackSender.Ack();
                        }
                    }
                    catch (Exception e)
                    {
                        //If something went wrong with message processing and message hasn't been acknoledged yet
                        if (!batchFeedbackSender.HasAcknoledged)
                        {
                            //Negatively Acknoledge message, asking for requeue
                            batchFeedbackSender.Nack(true);
                        }

                        //Rethrow caught Exception
                        throw;
                    }
                }
            }

            //Loop ended, dispose ConsumerWorker
            Dispose();
        }
 public DeserializationAggregateException(string message, Exception inner)
     : base(message, inner)
 {
     InnerExceptions = new DeserializationException[0];
 }
 public DeserializationAggregateException()
 {
     InnerExceptions = new DeserializationException[0];
 }
Exemplo n.º 12
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: private static void preProcess(ResponseCommand responseCommand, String addr) throws exception.RemotingException
        private static void preProcess(ResponseCommand responseCommand, string addr)
        {
            RemotingException e   = null;
            string            msg = null;

            if (responseCommand == null)
            {
                msg = string.Format("Rpc invocation timeout[responseCommand null]! the address is {0}", addr);
                e   = new InvokeTimeoutException(msg);
            }
            else
            {
                switch (responseCommand.ResponseStatus)
                {
                case ResponseStatus.TIMEOUT:
                    msg = string.Format("Rpc invocation timeout[responseCommand TIMEOUT]! the address is {0}", addr);
                    e   = new InvokeTimeoutException(msg);
                    break;

                case ResponseStatus.CLIENT_SEND_ERROR:
                    msg = string.Format("Rpc invocation send failed! the address is {0}", addr);
                    e   = new InvokeSendFailedException(msg, responseCommand.Cause);
                    break;

                case ResponseStatus.CONNECTION_CLOSED:
                    msg = string.Format("Connection closed! the address is {0}", addr);
                    e   = new ConnectionClosedException(msg);
                    break;

                case ResponseStatus.SERVER_THREADPOOL_BUSY:
                    msg = string.Format("Server thread pool busy! the address is {0}, id={1}", addr, responseCommand.Id);
                    e   = new InvokeServerBusyException(msg);
                    break;

                case ResponseStatus.CODEC_EXCEPTION:
                    msg = string.Format("Codec exception! the address is {0}, id={1}", addr, responseCommand.Id);
                    e   = new CodecException(msg);
                    break;

                case ResponseStatus.SERVER_SERIAL_EXCEPTION:
                    msg = string.Format("Server serialize response exception! the address is {0}, id={1}, serverSide=true", addr, responseCommand.Id);
                    e   = new SerializationException(detailErrMsg(msg, responseCommand), toThrowable(responseCommand), true);
                    break;

                case ResponseStatus.SERVER_DESERIAL_EXCEPTION:
                    msg = string.Format("Server deserialize request exception! the address is {0}, id={1}, serverSide=true", addr, responseCommand.Id);
                    e   = new DeserializationException(detailErrMsg(msg, responseCommand), toThrowable(responseCommand), true);
                    break;

                case ResponseStatus.SERVER_EXCEPTION:
                    msg = string.Format("Server exception! Please check the server log, the address is {0}, id={1}", addr, responseCommand.Id);
                    e   = new InvokeServerException(detailErrMsg(msg, responseCommand), toThrowable(responseCommand));
                    break;

                default:
                    break;
                }
            }
            if (!string.IsNullOrWhiteSpace(msg))
            {
                logger.LogWarning(msg);
            }
            if (null != e)
            {
                throw e;
            }
        }
        public async Task DoConsumeAsync(CancellationToken cancellationToken)
        {
            //Iterate while thread hasn't been canceled
            while (!cancellationToken.IsCancellationRequested)
            {
                //Create BasicDeliverEventArgs object and start trying to get the next message on the queue
                BasicDeliverEventArgs lastResult;
                var messageReceived = _subscription.Next(Convert.ToInt32(CheckAliveFrequency.TotalMilliseconds),
                                                         out lastResult);

                //If a message hasn't been succesfully fetched from the queue
                if (!messageReceived)
                {
                    //If the model has been closed
                    if (!_model.IsOpen)
                    {
                        //Dispose ConsumerWorker
                        Dispose();

                        //Throw AlreadyClosedException (model is already closed)
                        throw new global::RabbitMQ.Client.Exceptions.AlreadyClosedException(_model.CloseReason);
                    }
                }

                //If something was in fact returned from the queue
                if (lastResult != null)
                {
                    //Get message body
                    var messageBody = GetBody(lastResult);

                    //Create empty messageObject instance
                    var messageObject = default(T);

                    try
                    {
                        //Try to deserialize message body into messageObject
                        messageObject = _serializer.Deserialize <T>(messageBody);
                    }
                    catch (Exception exception)
                    {
                        //Create DeserializationException to pass to RejectionHandler
                        var deserializationException = new DeserializationException("Unable to deserialize data.", exception)
                        {
                            SerializedDataString = messageBody,
                            SerializedDataBinary = lastResult.Body,
                            QueueName            = _subscription.QueueName
                        };
                        //Pass DeserializationException to RejectionHandler
                        _messageRejectionHandler.OnRejection(deserializationException);

                        //Remove message from queue after RejectionHandler dealt with it
                        Nack(lastResult.DeliveryTag, false);
                    }

                    //If message has been successfully deserialized and messageObject is populated
                    if (messageObject != null)
                    {
                        //Create messageFeedbackSender instance with corresponding model and deliveryTag
                        IMessageFeedbackSender messageFeedbackSender = new RabbitMQMessageFeedbackSender(_model, lastResult.DeliveryTag);

                        try
                        {
                            //Call given messageProcessingWorker's OnMessage method to proceed with message processing
                            await _messageProcessingWorker.OnMessageAsync(messageObject, messageFeedbackSender,
                                                                          cancellationToken).ConfigureAwait(false);

                            //If message has been processed with no errors but no Acknoledgement has been given
                            if (!messageFeedbackSender.MessageAcknoledged)
                            {
                                //Acknoledge message
                                _subscription.Ack();
                            }
                        }
                        catch (Exception)
                        {
                            //If something went wrong with message processing and message hasn't been acknoledged yet
                            if (!messageFeedbackSender.MessageAcknoledged)
                            {
                                //Negatively Acknoledge message, asking for requeue
                                Nack(lastResult.DeliveryTag, true);
                            }

                            //Rethrow catched Exception
                            throw;
                        }
                    }
                }

                //In the end of the consumption loop, check if scaleDown has been requested
                if (_scaleCallbackFunc())
                {
                    //If so, break consumption loop to let the thread end gracefully
                    break;
                }
            }

            //Loop ended, dispose ConsumerWorker
            Dispose();
        }
        public async Task DoConsumeAsync(CancellationToken cancellationToken)
        {
            _modelConsumer.BasicQos(0, _prefetchCount, false);

            using (var subscription = new RabbitMQSubscription(_modelConsumer, _queueName, false))
            {
                //Iterate while thread hasn't been canceled
                while (!cancellationToken.IsCancellationRequested)
                {
                    //Create BasicDeliverEventArgs object and start trying to get the next message on the queue
                    var messageReceived = subscription.Next(Convert.ToInt32(CheckAliveFrequency.TotalMilliseconds),
                                                            out var lastResult);

                    if (messageReceived)
                    {
                        if (lastResult != null)
                        {
                            //Get message body
                            var messageBody = GetBody(lastResult);

                            try
                            {
                                //Try to deserialize message body into messageObject
                                var messageObject = _serializer.Deserialize <T>(messageBody);

                                //Create messageFeedbackSender instance with corresponding model and deliveryTag
                                IFeedbackSender feedbackSender = new RabbitMQMessageFeedbackSender(subscription, lastResult);

                                try
                                {
                                    //Call given messageProcessingWorker's OnMessage method to proceed with message processing
                                    var context = new RabbitMQConsumerContext(_queueClient, _modelPublisher);
                                    await _messageProcessingWorker.OnMessageAsync(messageObject, context, feedbackSender,
                                                                                  cancellationToken).ConfigureAwait(false);

                                    //If message has been processed with no errors but no Acknoledgement has been given
                                    if (!feedbackSender.HasAcknoledged)
                                    {
                                        //Acknoledge message
                                        feedbackSender.Ack();
                                    }
                                }
                                catch (Exception e)
                                {
                                    //If something went wrong with message processing and message hasn't been acknoledged yet
                                    if (!feedbackSender.HasAcknoledged)
                                    {
                                        //Negatively Acknoledge message, asking for requeue
                                        feedbackSender.Nack(true);
                                    }

                                    //Rethrow caught Exception
                                    throw;
                                }
                            }
                            catch (Exception exception)
                            {
                                //Create DeserializationException to pass to RejectionHandler
                                var deserializationException = new DeserializationException("Unable to deserialize data.", exception)
                                {
                                    SerializedDataString = messageBody,
                                    SerializedDataBinary = lastResult.Body,
                                    QueueName            = subscription.QueueName
                                };
                                //Pass DeserializationException to RejectionHandler
                                await _messageRejectionHandler.OnRejectionAsync(deserializationException).ConfigureAwait(false);

                                //Remove message from queue after RejectionHandler dealt with it
                                subscription.Nack(lastResult, false, false);
                            }
                        }
                    }
                    else
                    {
                        if (subscription.Model.IsClosed)
                        {
                            throw new Exception(
                                      $"Model is already closed for RabbitMQConsumerWorker. Queue: {_queueName}");
                        }
                    }

                    subscription.Nack(true);
                }
            }
        }
    private void OnMessage(object sender, BasicDeliverEventArgs basicDeliverEventArgs)
    {
        if (!this.model.IsOpen)
        {
            //Dispose ConsumerWorker
            this.Dispose();

            //Throw AlreadyClosedException (model is already closed)
            throw new RabbitMQ.Client.Exceptions.AlreadyClosedException(this.model.CloseReason);
        }

        byte[] bodyBytes   = basicDeliverEventArgs.Body.ToArray();
        string messageBody = Encoding.UTF8.GetString(bodyBytes);

        object messageObject = null;

        try
        {
            messageObject = Newtonsoft.Json.JsonConvert.DeserializeObject(messageBody, this.expectedType);
        }
        catch (Exception exception)
        {
            var deserializationException = new DeserializationException("Unable to deserialize data.", exception)
            {
                SerializedDataString = messageBody,
                SerializedDataBinary = bodyBytes,
                QueueName            = this.queueName
            };
            //Pass DeserializationException to RejectionHandler
            this.messageRejectionHandler.OnRejection(deserializationException);

            //Remove message from queue after RejectionHandler dealt with it
            this.Nack(basicDeliverEventArgs.DeliveryTag, false);
        }

        //If message has been successfully deserialized and messageObject is populated
        if (messageObject != null)
        {
            //Create messageFeedbackSender instance with corresponding model and deliveryTag
            IMessageFeedbackSender messageFeedbackSender = new RabbitMQMessageFeedbackSender(this.model, basicDeliverEventArgs.DeliveryTag);

            try
            {
                //Call given messageProcessingWorker's OnMessage method to proceed with message processing
                this.messageProcessingWorker.OnMessage(messageObject, messageFeedbackSender);

                //If message has been processed with no errors but no Acknoledgement has been given
                if (!messageFeedbackSender.MessageAcknoledged)
                {
                    //Acknoledge message
                    this.Ack(basicDeliverEventArgs.DeliveryTag);
                }
            }
            catch (Exception)
            {
                //If something went wrong with message processing and message hasn't been acknoledged yet
                if (!messageFeedbackSender.MessageAcknoledged)
                {
                    //Negatively Acknoledge message, asking for requeue
                    this.Nack(basicDeliverEventArgs.DeliveryTag, true);
                }
                //Rethrow catched Exception
                throw;
            }
        }
    }