Exemplo n.º 1
0
        public IEnumerable<HosepipeMessage> GetMessagesFromQueue(QueueParameters parameters)
        {
            using (var connection = HosepipeConnection.FromParamters(parameters))
            using (var channel = connection.CreateModel())
            {
                try
                {
                    channel.QueueDeclarePassive(parameters.QueueName);
                }
                catch (OperationInterruptedException exception)
                {
                    Console.WriteLine(exception.Message);
                    yield break;
                }

                var count = 0;
                while (count++ < parameters.NumberOfMessagesToRetrieve)
                {
                    var basicGetResult = channel.BasicGet(parameters.QueueName, noAck: parameters.Purge);
                    if (basicGetResult == null) break; // no more messages on the queue

                    var properties = new MessageProperties(basicGetResult.BasicProperties);
                    var info = new MessageReceivedInfo(
                        "hosepipe",
                        basicGetResult.DeliveryTag,
                        basicGetResult.Redelivered,
                        basicGetResult.Exchange,
                        basicGetResult.RoutingKey,
                        parameters.QueueName);

                    yield return new HosepipeMessage(errorMessageSerializer.Serialize(basicGetResult.Body), properties, info);
                }
            }
        }
Exemplo n.º 2
0
 public PublishedMessageEvent(string exchangeName, string routingKey, MessageProperties properties, byte[] body)
 {
     ExchangeName = exchangeName;
     RoutingKey = routingKey;
     Properties = properties;
     Body = body;
 }
Exemplo n.º 3
0
        private void OldSendMessages(RabbitTemplate template)
        {
            IBasicProperties basicProperties = template.Execute<IBasicProperties>(delegate(IModel model)
                                                                                      {
                                                                                          return model.CreateBasicProperties();
                                                                                      });

            /*
             * System.ArgumentNullException: String reference not set to an instance of a String.
                Parameter name: s
                    at System.Text.Encoding.GetBytes(String s)
                    at RabbitMQ.Client.Impl.WireFormatting.WriteShortstr(NetworkBinaryWriter writer, String val)
             */
            IMessageProperties messageProperties = new MessageProperties(basicProperties);

            //write all short props
            messageProperties.ContentType = "text/plain";
            messageProperties.ContentEncoding = "UTF-8";
            messageProperties.CorrelationId = Encoding.UTF8.GetBytes("corr1");

            messageProperties.DeliveryMode = MessageDeliveryMode.PERSISTENT;
            messageProperties.Priority = 0;

            byte[] byteMessage = Encoding.UTF8.GetBytes("testing");
            template.Send("amq.direct", "foo", delegate
                                                   {
                                                       Message msg = new Message(byteMessage, messageProperties);
                                                       Console.WriteLine("sending...");
                                                       return msg;
                                                   });

            //template.Send("amq.direct", "foo", channel => new Message(Encoding.UTF8.GetBytes("testing"), messageProperties));
        }
Exemplo n.º 4
0
		protected AdwsRequestMsg(string instance)
		{
			this._messageProperties = new MessageProperties();
			this._messageHeaders = new MessageHeaders(this.Version, 7);
			this.Headers.Action = this.Action;
			this.Headers.Add(MessageHeader.CreateHeader("instance", "http://schemas.microsoft.com/2008/1/ActiveDirectory", instance));
		}
Exemplo n.º 5
0
        public void SendWithTemplate()
        {
            QpidTemplate template = InitializeAndCreateTemplate();

            IMessageProperties messageProperties = new MessageProperties();


            //write all short props
            messageProperties.ContentType = "text/plain";
            messageProperties.ContentEncoding = "UTF-8";
            messageProperties.CorrelationId = Encoding.UTF8.GetBytes("corr1");


            messageProperties.DeliveryMode = MessageDeliveryMode.PERSISTENT;
            messageProperties.Priority = 0;


            for (int i = 0; i < 10; i++)
            {
                template.Send("amq.direct", "routing_key", delegate
                {
                    Message msg = new Message(Encoding.UTF8.GetBytes("Message " + i), messageProperties);
                    Console.WriteLine("sending...");
                    return msg;
                });
            }
            template.Send("amq.direct", "routing_key", delegate
            {
                Message msg = new Message(Encoding.UTF8.GetBytes("That's all, folks!"), messageProperties);
                Console.WriteLine("sending...");
                return msg;
            });
            
        }
        public void SetUp()
        {
            postAckCallbackWasRun = false;

            //var logger = new ConsoleLogger();
            var logger = MockRepository.GenerateStub<IEasyNetQLogger>();
            var consumerErrorStrategy = MockRepository.GenerateStub<IConsumerErrorStrategy>();

            handlerRunner = new HandlerRunner(logger, consumerErrorStrategy);

            Func<byte[], MessageProperties, MessageReceivedInfo, Task> userHandler = (body, properties, info) =>
                Task.Factory.StartNew(() =>
                    {
                        deliveredBody = body;
                        deliveredProperties = properties;
                        deliveredInfo = info;
                    });

            var consumer = MockRepository.GenerateStub<IBasicConsumer>();
            channel = MockRepository.GenerateStub<IModel>();
            consumer.Stub(x => x.Model).Return(channel).Repeat.Any();

            var context = new ConsumerExecutionContext(
                userHandler, messageInfo, messageProperties, messageBody, consumer);

            context.SetPostAckCallback(() => postAckCallbackWasRun = true);

            var autoResetEvent = new AutoResetEvent(false);
            ((HandlerRunner) handlerRunner).SynchronisationAction = () => autoResetEvent.Set();

            handlerRunner.InvokeUserMessageHandler(context);

            autoResetEvent.WaitOne(1000);
        }
Exemplo n.º 7
0
        public void AppendTo( MessageProperties messageProperties )
        {
            messageProperties.Type = messageType;

            if( alternativeTypes.Any() )
                messageProperties.Headers[ AlternativeMessageTypesHeaderKey ] = string.Join( AlternativeMessageTypeSeparator, alternativeTypes );
        }
        public void SetUp()
        {
            //var logger = new ConsoleLogger();
            var logger = MockRepository.GenerateStub<IEasyNetQLogger>();
            var consumerErrorStrategy = MockRepository.GenerateStub<IConsumerErrorStrategy>();
            var eventBus = new EventBus();

            handlerRunner = new HandlerRunner(logger, consumerErrorStrategy, eventBus);

            Func<byte[], MessageProperties, MessageReceivedInfo, Task> userHandler = (body, properties, info) => 
                Task.Factory.StartNew(() =>
                    {
                        deliveredBody = body;
                        deliveredProperties = properties;
                        deliveredInfo = info;
                    });

            var consumer = MockRepository.GenerateStub<IBasicConsumer>();
            channel = MockRepository.GenerateStub<IModel>();
            consumer.Stub(x => x.Model).Return(channel).Repeat.Any();

            var context = new ConsumerExecutionContext(
                userHandler, messageInfo, messageProperties, messageBody, consumer);

            var autoResetEvent = new AutoResetEvent(false);
            eventBus.Subscribe<AckEvent>(x => autoResetEvent.Set());

            handlerRunner.InvokeUserMessageHandler(context);

            autoResetEvent.WaitOne(1000);
        }
Exemplo n.º 9
0
        public Dictionary<string, string> ValidateMessagePropertyHeaders()
        {
            Dictionary<string, string> headerCollection = new Dictionary<string, string>();
            try
            {
                HttpRequestMessageProperty property;
                object obj;
                MessageProperties properties = new MessageProperties(OperationContext.Current.IncomingMessageProperties);
                if (properties.TryGetValue(HttpRequestMessageProperty.Name, out obj))
                {
                    property = obj as HttpRequestMessageProperty;
                    WebHeaderCollection collection = property.Headers;

                    string[] headers = collection.AllKeys;
                    foreach (string s in headers)
                    {
                        string[] values = collection.GetValues(s);
                        headerCollection.Add(s, String.Join(",", values));
                    }
                }
                else
                {
                    headerCollection.Add("ERROR", "No HttpRequestMessageProperty was found!");
                }
            }
            catch (Exception ex)
            {
                headerCollection.Add("ERROR", string.Format("An exception was thrown: {0}", ex.Message));
            }

            return headerCollection;
        }
Exemplo n.º 10
0
        public TestHttpRequestMessageProperty EchoHttpRequestMessageProperty()
        {
            object obj;
            MessageProperties properties = new MessageProperties(OperationContext.Current.IncomingMessageProperties);
            if (properties.TryGetValue(HttpRequestMessageProperty.Name, out obj))
            {
                HttpRequestMessageProperty property = (HttpRequestMessageProperty)obj;
                if (property != null)
                {
                    TestHttpRequestMessageProperty testProperty = new TestHttpRequestMessageProperty();
                    testProperty.SuppressEntityBody = property.SuppressEntityBody;
                    testProperty.Method = property.Method;
                    testProperty.QueryString = property.QueryString;

                    WebHeaderCollection collection = property.Headers;
                    foreach (string s in collection.AllKeys)
                    {
                        string[] values = collection.GetValues(s);
                        testProperty.Headers.Add(s, String.Join(",", values));
                    }
                    return testProperty;
                }
            }

            return null;
        }
Exemplo n.º 11
0
        public void Should_be_able_to_write_debug_properties()
        {
            const string expectedDebugProperties =
                "ContentType=content_type, ContentEncoding=content_encoding, " +
                "Headers=[key1=value1, key2=value2], DeliveryMode=10, Priority=3, CorrelationId=NULL, " +
                "ReplyTo=reply_to, Expiration=expiration, MessageId=message_id, Timestamp=123456, Type=type, " +
                "UserId=userid, AppId=app_id, ClusterId=cluster_id";

            var stringBuilder = new StringBuilder();
            var headers = new Dictionary<string, object>
                {
                    {"key1", "value1"},
                    {"key2", "value2"}
                };

            var properties = new MessageProperties
                {
                    AppId = "app_id",
                    ClusterId = "cluster_id",
                    ContentEncoding = "content_encoding",
                    ContentType = "content_type",
                    //CorrelationId = "correlation_id",
                    DeliveryMode = 10,
                    Expiration = "expiration",
                    Headers = headers,
                    MessageId = "message_id",
                    Priority = 3,
                    ReplyTo = "reply_to",
                    Timestamp = 123456,
                    Type = "type",
                    UserId = "userid",
                };

            properties.ToString().ShouldEqual(expectedDebugProperties);
        }
Exemplo n.º 12
0
        public void WriteSomeFiles()
        {
            var directory = new DirectoryInfo(tempDirectory);
            foreach (var file in directory.EnumerateFiles())
            {
                file.Delete();
            }

            var properties = new MessageProperties();
            var info = Helper.CreateMessageRecievedInfo();
            var writer = new FileMessageWriter();
            var messages = new List<HosepipeMessage>
            {
                new HosepipeMessage("This is message one", properties, info),
                new HosepipeMessage("This is message two", properties, info),
                new HosepipeMessage("This is message three", properties, info)
            };

            var parameters = new QueueParameters
            {
                QueueName = "Queue EasyNetQ_Tests_TestAsyncRequestMessage:EasyNetQ_Tests_Messages",
                MessageFilePath = tempDirectory
            };

            writer.Write(messages, parameters);

            foreach (var file in directory.EnumerateFiles())
            {
                Console.Out.WriteLine("{0}", file.Name);
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Constructor.
        /// </summary>
        protected AmfMessageBase()
        {
            _properties = new MessageProperties();

            //Make sure that there is no wrapping applied to this message
            _headers = new MessageHeaders(MessageVersion.None);
        }
Exemplo n.º 14
0
 public AckEvent(MessageReceivedInfo info, MessageProperties properties, byte[] body , AckResult ackResult)
 {
     ReceivedInfo = info;
     Properties = properties;
     Body = body;
     AckResult = ackResult;
 }
Exemplo n.º 15
0
 public void Setup()
 {
     MessageData = Encoding.UTF8.GetBytes("hej");
     ChannelConfigurator = new ChannelConfigurator();
     Exchange = null;
     MessageProperties = new MessageProperties() { MessageId = MessageId };
     _message = new ReceivedMessage(MessageData, GetExchangeName(), MessageProperties);
 }
 public void AddOrReplaceInMessageProperties(MessageProperties properties)
 {
     if (properties == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("properties");
     }
     properties["ContextMessageProperty"] = this;
 }
 public void ReturnProperties(MessageProperties properties)
 {
     if (properties.CanRecycle)
     {
         properties.Recycle();
         this.recycledProperties = properties;
     }
 }
    public static bool TryGet(MessageProperties properties, out System.ServiceModel.Channels.ContextMessageProperty contextMessageProperty)
    {
      Contract.Ensures(Contract.Result<bool>() == (Contract.ValueAtReturn(out contextMessageProperty) != null));

      contextMessageProperty = default(System.ServiceModel.Channels.ContextMessageProperty);

      return default(bool);
    }
        public void AddTo(MessageProperties properties)
        {
            if (properties == null)
            {
                throw FxTrace.Exception.ArgumentNull("properties");
            }

            properties.Add(NetworkInterfaceMessageProperty.Name, this);
        }
		internal DefaultMessageBuffer (int maxBufferSize, MessageHeaders headers, MessageProperties properties, BodyWriter body, bool isFault)
		{
			this.max_buffer_size = maxBufferSize;
			this.headers = headers;
			this.body = body;
			this.closed = false;
			this.is_fault = isFault;
			this.properties = properties;
		}
Exemplo n.º 21
0
		public void AllowOutputBatching ()
		{
			var mp = new MessageProperties ();
			Assert.IsFalse (mp.AllowOutputBatching, "#0");
			mp.AllowOutputBatching = true;
			Assert.AreEqual (1, mp.Count, "#1");
			foreach (KeyValuePair<string,object> p in mp)
				Assert.AreEqual ("AllowOutputBatching", p.Key, "#2");
		}
Exemplo n.º 22
0
 internal ChunkingMessage(MessageVersion version, string action, ChunkingReader reader, Guid messageId)
 {
     this.version = version;
     this.chunkReader = reader;
     this.properties = new MessageProperties();
     this.headers = new MessageHeaders(this.version);
     this.headers.Action = action;
     this.messageId = messageId;
 }
Exemplo n.º 23
0
		public void Via ()
		{
			var mp = new MessageProperties ();
			Assert.IsNull (mp.Via, "#0");
			mp.Via = new Uri ("urn:foo");
			Assert.AreEqual (1, mp.Count, "#1");
			foreach (KeyValuePair<string,object> p in mp)
				Assert.AreEqual ("Via", p.Key, "#2");
		}
Exemplo n.º 24
0
		public void Encoder ()
		{
			var mp = new MessageProperties ();
			Assert.IsNull (mp.Via, "#0");
			mp.Encoder = new TextMessageEncodingBindingElement ().CreateMessageEncoderFactory ().Encoder;
			Assert.AreEqual (1, mp.Count, "#1");
			foreach (KeyValuePair<string,object> p in mp)
				Assert.AreEqual ("Encoder", p.Key, "#2");
		}
    public static bool TryGet(MessageProperties properties, out System.ServiceModel.Channels.CorrelationDataMessageProperty property)
    {
      Contract.Requires(properties != null);
      Contract.Ensures(Contract.Result<bool>() == (Contract.ValueAtReturn(out property) != null));

      property = default(System.ServiceModel.Channels.CorrelationDataMessageProperty);

      return default(bool);
    }
 public void AddTo(MessageProperties properties)
 {
     this.ThrowIfDisposed();
     if (properties == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("properties");
     }
     properties.Add(Name, this);
 }
 public HttpStreamMessage(MessageHeaders headers, MessageProperties properties, BodyWriter bodyWriter)
 {
     if (bodyWriter == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("bodyWriter");
     }
     this.headers = new MessageHeaders(headers);
     this.properties = new MessageProperties(properties);
     this.bodyWriter = bodyWriter;
 }
 bool MatchInternal(MessageProperties messageProperties)
 {
     object value;
     if (messageProperties.TryGetValue(EndpointNameKey, out value))
     {
         string messageEndpoint = value.ToString();
         return string.Equals(messageEndpoint, this.endpointName, StringComparison.Ordinal);
     }
     return false;
 }
Exemplo n.º 29
0
        public HosepipeMessage(string body, MessageProperties properties, MessageReceivedInfo info)
        {
            if(body == null) throw new ArgumentNullException("body");
            if(properties == null) throw new ArgumentNullException("properties");
            if(info == null) throw new ArgumentNullException("info");

            Body = body;
            Properties = properties;
            Info = info;
        }
 public HttpStreamMessage(BodyWriter writer)
 {
     if (writer == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
     }
     this.bodyWriter = writer;
     this.headers = new MessageHeaders(MessageVersion.None, 1);
     this.properties = new MessageProperties();
 }
Exemplo n.º 31
0
        /// <inheritdoc />
        public void HandleBasicDeliver(
            string consumerTag,
            ulong deliveryTag,
            bool redelivered,
            string exchange,
            string routingKey,
            IBasicProperties properties,
            ReadOnlyMemory <byte> body
            )
        {
            if (logger.IsDebugEnabled())
            {
                logger.DebugFormat("Message delivered to consumer {consumerTag} with deliveryTag {deliveryTag}", consumerTag, deliveryTag);
            }

            if (disposed)
            {
                // this message's consumer has stopped, so just return
                logger.InfoFormat(
                    "Consumer with consumerTag {consumerTag} on queue {queue} has stopped running. Ignoring message",
                    ConsumerTag,
                    Queue.Name
                    );

                return;
            }

            var bodyBytes           = body.ToArray();
            var messageReceivedInfo = new MessageReceivedInfo(consumerTag, deliveryTag, redelivered, exchange, routingKey, Queue.Name);
            var messageProperties   = new MessageProperties(properties);
            var context             = new ConsumerExecutionContext(OnMessage, messageReceivedInfo, messageProperties, bodyBytes);

            eventBus.Publish(new DeliveredMessageEvent(messageReceivedInfo, messageProperties, bodyBytes));
            handlerRunner.InvokeUserMessageHandlerAsync(context)
            .ContinueWith(async x =>
            {
                var ackStrategy = await x.ConfigureAwait(false);
                consumerDispatcher.QueueAction(() =>
                {
                    var ackResult = ackStrategy(Model, deliveryTag);
                    eventBus.Publish(new AckEvent(messageReceivedInfo, messageProperties, bodyBytes, ackResult));
                });
            },
                          TaskContinuationOptions.ExecuteSynchronously
                          );
        }
Exemplo n.º 32
0
        public IMessage DeserializeMessage(MessageProperties properties, byte[] body)
        {
            string message;

            switch (_serializer.BytesToMessage(typeof(object), body))
            {
            case string messageTmp:
                message = messageTmp;
                break;

            case var messageTmp:
                message = ((JObject)messageTmp).ToString();
                break;
            }

            return(MessageFactory.CreateInstance(typeof(string), message, properties));
        }
Exemplo n.º 33
0
        public MessageInspector_CustomHeaderAuthentication.ResultObject <string> UserGetAuthToken()
        {
            MessageInspector_CustomHeaderAuthentication.ResultObject <string> resultObject = null;

            try
            {
                HttpRequestMessageProperty property;
                object            obj;
                MessageProperties properties = new MessageProperties(OperationContext.Current.IncomingMessageProperties);
                if (properties.TryGetValue(HttpRequestMessageProperty.Name, out obj))
                {
                    property = obj as HttpRequestMessageProperty;
                    WebHeaderCollection collection = property.Headers;
                    string authValue = collection.Get(Enum.GetName(typeof(HttpRequestHeader), HttpRequestHeader.Authorization));

                    if (authValue == "Not Allowed")
                    {
                        resultObject = MessageInspector_CustomHeaderAuthentication.ResultObject <string> .CreateFailureObject <string>();

                        resultObject.Result = resultObject.ResultMessage;
                    }
                    else if (authValue == "Allow")
                    {
                        resultObject = MessageInspector_CustomHeaderAuthentication.ResultObject <string> .CreateSuccessObject <string>();

                        resultObject.Result = resultObject.ResultMessage;
                    }
                }
                else
                {
                    resultObject = MessageInspector_CustomHeaderAuthentication.ResultObject <string> .CreateFailureObject <string>();

                    resultObject.Result        = "ERROR";
                    resultObject.ResultMessage = "No HttpRequestMessageProperty was found on the incoming Message.";
                }
            }
            catch (Exception ex)
            {
                resultObject = MessageInspector_CustomHeaderAuthentication.ResultObject <string> .CreateFailureObject <string>();

                resultObject.Result        = ex.ToString();
                resultObject.ResultMessage = ex.Message;
            }

            return(resultObject);
        }
Exemplo n.º 34
0
        public void ProcessWithRetry(MessageMetadata product, IList <Subscription> subscriptionGroup, int tryIndex = 0)
        {
            var deliveryCount = tryIndex + 1;
            int nextDelay;

            try
            {
                ProcessSubscriptionGroup(product, subscriptionGroup);
                return;
            }
            catch (Exception e)
            {
                Log.Warning(e, $"Error occured when retry count: {deliveryCount}");
                switch (deliveryCount)
                {
                case 1:
                    nextDelay = (int)TimeSpan.FromSeconds(5).TotalMilliseconds;
                    break;

                case 2:
                    nextDelay = (int)TimeSpan.FromSeconds(15).TotalMilliseconds;
                    break;

                default:
                    Log.Error(e, $"Exceeded Retry Count: {deliveryCount}");
                    return;
                }
            }

            var properties = new MessageProperties()
            {
                Headers = new Dictionary <string, object>()
                {
                    { "x-delay", nextDelay }
                }
            };

            var redeliveribleInformationResource = new RedeliveribleMessage()
            {
                DeliveryCount = deliveryCount,
                Message       = product,
                Subscriptions = subscriptionGroup
            };

            _bus.Publish(_retryExchanger, String.Empty, true, new Message <RedeliveribleMessage>(redeliveribleInformationResource, properties));
        }
Exemplo n.º 35
0
        /// <summary>
        /// Getting sender IP address and port
        /// </summary>
        /// <returns>IP address with port</returns>
        private string GetClientEndpoint()
        {
            OperationContext context = OperationContext.Current;

            if (context != null)
            {
                MessageProperties             messageProperties = context.IncomingMessageProperties;
                RemoteEndpointMessageProperty endpointProperty  =
                    messageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;

                return(endpointProperty.Address.Replace("::1", "127.0.0.1") + ":" + endpointProperty.Port);
            }
            else
            {
                return("127.0.0.1");
            }
        }
Exemplo n.º 36
0
        /// <summary>Create a message from the object with properties.</summary>
        /// <param name="obj">The obj.</param>
        /// <param name="messageProperties">The message properties.</param>
        /// <returns>The Message.</returns>
        public Message ToMessage(object obj, MessageProperties messageProperties)
        {
            if (messageProperties == null)
            {
                messageProperties = new MessageProperties();
            }

            var message = this.CreateMessage(obj, messageProperties);

            messageProperties = message.MessageProperties;
            if (this.createMessageIds && messageProperties.MessageId == null)
            {
                messageProperties.MessageId = Guid.NewGuid().ToString();
            }

            return(message);
        }
        public void MultipleCodecs()
        {
            var properties = new MessageProperties {
                ContentEncoding    = "deflate, gzip",
                ContentTypePresent = true
            };

            var input   = new RawMessage(properties, Encoding.UTF8.GetBytes("test"));
            var subject = new ExtensibleContentEncodingInterceptor();
            var encoded = subject.OnProduce(input);

            Assert.Equal(new Byte[] { 147, 239, 230, 96, 0, 3, 110, 109, 79, 93, 61, 70, 6, 158, 186, 250, 27, 44, 64, 46, 0 }, encoded.Body);

            var decoded = subject.OnConsume(encoded);

            Assert.Equal("test", Encoding.UTF8.GetString(decoded.Body));
        }
        public void CodecDeflate()
        {
            var properties = new MessageProperties {
                ContentEncoding    = "deflate",
                ContentTypePresent = true
            };

            var input   = new RawMessage(properties, Encoding.UTF8.GetBytes("test"));
            var subject = new ExtensibleContentEncodingInterceptor();
            var encoded = subject.OnProduce(input);

            Assert.Equal(new byte[] { 43, 73, 45, 46, 1, 0 }, encoded.Body);

            var decoded = subject.OnConsume(encoded);

            Assert.Equal("test", Encoding.UTF8.GetString(decoded.Body));
        }
        public void CodecIdentity()
        {
            var properties = new MessageProperties {
                ContentEncoding    = "identity",
                ContentTypePresent = true
            };

            var input   = new RawMessage(properties, Encoding.UTF8.GetBytes("test"));
            var subject = new ExtensibleContentEncodingInterceptor();
            var encoded = subject.OnProduce(input);

            Assert.Equal("test", Encoding.UTF8.GetString(encoded.Body));

            var decoded = subject.OnConsume(encoded);

            Assert.Equal("test", Encoding.UTF8.GetString(decoded.Body));
        }
Exemplo n.º 40
0
        public ConsumerExecutionContext(
            Func <byte[], MessageProperties, MessageReceivedInfo, Task> userHandler,
            MessageReceivedInfo info,
            MessageProperties properties,
            byte[] body
            )
        {
            Preconditions.CheckNotNull(userHandler, "userHandler");
            Preconditions.CheckNotNull(info, "info");
            Preconditions.CheckNotNull(properties, "properties");
            Preconditions.CheckNotNull(body, "body");

            UserHandler = userHandler;
            Info        = info;
            Properties  = properties;
            Body        = body;
        }
        public void CodecGzip()
        {
            var properties = new MessageProperties {
                ContentEncoding    = "gzip",
                ContentTypePresent = true
            };

            var input   = new RawMessage(properties, Encoding.UTF8.GetBytes("test"));
            var subject = new ExtensibleContentEncodingInterceptor();
            var encoded = subject.OnProduce(input);

            Assert.Equal(new Byte[] { 31, 139, 8, 0, 0, 0, 0, 0, 0, 11, 43, 73, 45, 46, 1, 0, 12, 126, 127, 216, 4, 0, 0, 0 }, encoded.Body);

            var decoded = subject.OnConsume(encoded);

            Assert.Equal("test", Encoding.UTF8.GetString(decoded.Body));
        }
Exemplo n.º 42
0
        protected override void Write(LogEventInfo logEvent)
        {
            var message    = GetMessage(logEvent);
            var routingKey = GetRoutingKey(logEvent.Level.Name);

            var properties = new MessageProperties
            {
                AppId           = AppId,
                ContentEncoding = "utf8",
                ContentType     = "application/json",
                Timestamp       = GetEpochTimeStamp(logEvent),
                UserId          = _rabbitMqHostHostConfig.UserName,
                Type            = "Log",
            };

            Bus.Publish(_exchange, routingKey, true, false, properties, message);
        }
        public void CodecBrotli()
        {
            var properties = new MessageProperties {
                ContentEncoding    = "br",
                ContentTypePresent = true
            };

            var input   = new RawMessage(properties, Encoding.UTF8.GetBytes("test"));
            var subject = new ExtensibleContentEncodingInterceptor();
            var encoded = subject.OnProduce(input);

            Assert.Equal(new Byte[] { 139, 1, 128, 116, 101, 115, 116, 3 }, encoded.Body);

            var decoded = subject.OnConsume(encoded);

            Assert.Equal("test", Encoding.UTF8.GetString(decoded.Body));
        }
Exemplo n.º 44
0
        public static async Task <Model> ModifyAsync(ulong channelId, ulong msgId, BaseDiscordClient client, Action <MessageProperties> func,
                                                     RequestOptions options)
        {
            var args = new MessageProperties();

            func(args);

            if ((args.Content.IsSpecified && string.IsNullOrEmpty(args.Content.Value)) && (args.Embed.IsSpecified && args.Embed.Value == null))
            {
                Preconditions.NotNullOrEmpty(args.Content.IsSpecified ? args.Content.Value : string.Empty, nameof(args.Content));
            }

            if (args.AllowedMentions.IsSpecified)
            {
                AllowedMentions allowedMentions = args.AllowedMentions.Value;
                Preconditions.AtMost(allowedMentions?.RoleIds?.Count ?? 0, 100, nameof(allowedMentions.RoleIds), "A max of 100 role Ids are allowed.");
                Preconditions.AtMost(allowedMentions?.UserIds?.Count ?? 0, 100, nameof(allowedMentions.UserIds), "A max of 100 user Ids are allowed.");

                // check that user flag and user Id list are exclusive, same with role flag and role Id list
                if (allowedMentions != null && allowedMentions.AllowedTypes.HasValue)
                {
                    if (allowedMentions.AllowedTypes.Value.HasFlag(AllowedMentionTypes.Users) &&
                        allowedMentions.UserIds != null && allowedMentions.UserIds.Count > 0)
                    {
                        throw new ArgumentException("The Users flag is mutually exclusive with the list of User Ids.", nameof(allowedMentions));
                    }

                    if (allowedMentions.AllowedTypes.Value.HasFlag(AllowedMentionTypes.Roles) &&
                        allowedMentions.RoleIds != null && allowedMentions.RoleIds.Count > 0)
                    {
                        throw new ArgumentException("The Roles flag is mutually exclusive with the list of Role Ids.", nameof(allowedMentions));
                    }
                }
            }

            var apiArgs = new API.Rest.ModifyMessageParams
            {
                Content         = args.Content,
                Embed           = args.Embed.IsSpecified ? args.Embed.Value.ToModel() : Optional.Create <API.Embed>(),
                Flags           = args.Flags.IsSpecified ? args.Flags.Value : Optional.Create <MessageFlags?>(),
                AllowedMentions = args.AllowedMentions.IsSpecified ? args.AllowedMentions.Value.ToModel() : Optional.Create <API.AllowedMentions>(),
            };

            return(await client.ApiClient.ModifyMessageAsync(channelId, msgId, apiArgs, options).ConfigureAwait(false));
        }
Exemplo n.º 45
0
        public object BeforeCall(string operationName, object[] inputs)
        {
            Type       serviceType = OperationContext.Current.EndpointDispatcher.DispatchRuntime.Type;
            MethodInfo methodInfo  = serviceType.GetMethod(operationName);

            ParameterInfo[] parameters = methodInfo.GetParameters();
            //            var ssoCookie = new SSOCookie(HttpContext.Current.Request.Cookies[ConfigurationManager.AppSettings["SSO_CookieName"]]);
            //Validate contract objects using DataAnnotation Attributes
            //            methodInfo.Attributes
            //            var authorization = methodInfo.GetCustomAttributes(true).SingleOrDefault(a => a.GetType().Equals(typeof(ServiceAuthorization))) as ServiceAuthorization;
            //            if (authorization != null)
            //            {
            //                authorization.Authorize();
            //            }
            //            inputs.Where(i => i != null && i.GetType().BaseType == typeof(ModelBase)).ToList().ForEach(i => i.Validate());

            try
            {
                // Log that we're starting the call, who the caller is, etc.
                OperationContext  context = OperationContext.Current;
                MessageProperties incomingMessageProperties = context.IncomingMessageProperties;

                RemoteEndpointMessageProperty endpoint = incomingMessageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
                string clientIP = endpoint.Address;

                _log.Info(string.Format("Beginning execution of {0}.{1} called from [{2}]", serviceType, operationName, clientIP));
            }
            catch (Exception exception)
            {
                _log.Error(string.Format("Error in BeforeCall.  {0}", exception.Message), exception);
                throw;
            }

            //          try
            //			{
            //				OperationState.State["StartDateTime"] = Stopwatch.StartNew();
            //				return null;
            //			}
            //			catch (Exception exception)
            //			{
            //				_log.Error("Error in BeforeCall.  " + exception.Message, exception);
            //				throw;
            //			}
            return(null);
        }
Exemplo n.º 46
0
        public async Task SendRpcRequest <T>(string requestName, T message, Action <IHandlerRegistry> registrar)
        {
            var correlationId = Guid.NewGuid().ToString();
            var handlerId     = string.Format("{0}.{1}", requestName, correlationId);
            var handlers      = GetHandlers(handlerId, registrar);
            var exchange      = CreateRpcRequestExchange();
            var serialized    = _serializationStrategy.Serialize(message);
            var props         = new MessageProperties()
            {
                Type          = serialized.Item1,
                ReplyTo       = _clientId.ToString(),
                CorrelationId = correlationId,
                DeliveryMode  = 1
            };

            ReceiveRpcResponse(requestName, correlationId, handlerId);
            await _bus.Advanced.PublishAsync(exchange, requestName, false, false, props, serialized.Item2);
        }
Exemplo n.º 47
0
        protected void MoveToDeadLetter(object message, MessageProperties properties, Exception exception)
        {
            var serializedMessage = Serializer.Get(properties.ContentType).Serialize(message);

            properties.Headers.Add("x-death", new Dictionary <string, object>
            {
                { "count", 1 },
                { "reason", "error" },
                { "error", exception.Message },
                { "queue", QueueConfiguration.Name },
                { "exchange", ExchangeConfiguration.Name },
                { "routing-keys", QueueConfiguration.RoutingKey },
                { "time", ((DateTimeOffset)DateTime.UtcNow).ToUnixTimeMilliseconds() }
            }
                                   );

            Bus.Publish(_deadLetterExchange, _deadLetterRoutingKey, true, properties, serializedMessage);
        }
Exemplo n.º 48
0
        /// <summary>
        /// Gets the ImpersonateOnSerializingReplyMessageProperty property from MessageProperties.
        /// </summary>
        /// <param name="properties">The MessagePropeties object.</param>
        /// <param name="property">An output paramter to hold the ImpersonateOnSerializingReplyMessageProperty property.</param>
        /// <returns>True if the ImpersonateOnSerializingReplyMessageProperty property was found.</returns>
        public static bool TryGet(MessageProperties properties, out ImpersonateOnSerializingReplyMessageProperty property)
        {
            if (properties == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(properties));
            }

            if (properties.TryGetValue(PropertyName, out object value))
            {
                property = value as ImpersonateOnSerializingReplyMessageProperty;
            }
            else
            {
                property = null;
            }

            return(property != null);
        }
Exemplo n.º 49
0
        /// <summary>
        /// Grab the user IP address from the current WCF operation
        /// </summary>
        /// <param name="context">The current operation context (e.g. "OperationContext.Current")</param>
        /// <returns>The IP address if all is well, otherwise empty string.</returns>
        public static string GetUserIPFromOperationContect(OperationContext context)
        {
            string result = string.Empty;

            MessageProperties messageProperties = context.IncomingMessageProperties;

            if (messageProperties != null)
            {
                RemoteEndpointMessageProperty endpointProperty = messageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;

                if (endpointProperty != null)
                {
                    result = endpointProperty.Address;
                }
            }

            return(result);
        }
Exemplo n.º 50
0
        public static Message GenerateMessage(object payload, MessageProperties messageSpecificProperties, IMessageGenerator messageGenerator = null)
        {
            messageGenerator = messageGenerator ?? new MessageGenerator();
            var message = messageGenerator.GenerateMessage(payload);

            var messageType = payload.GetType();

            message.MessageId   = Guid.NewGuid().ToString();
            message.ContentType = messageType.SimpleQualifiedName();
            message.UserProperties["MessageType"] = messageType.FullName;

            message.PopulateCorrelationId(
                messageSpecificProperties?.CorrelationIdProvider.CorrelationId);

            message.AddProperties(messageSpecificProperties?.CustomProperties);

            return(message);
        }
Exemplo n.º 51
0
        public static CorrelationCallbackContext CreateCorrelationCallbackContext(MessageProperties messageProperties)
        {
            CallbackContextMessageProperty callbackMessageContextProperty;

            if (CallbackContextMessageProperty.TryGet(messageProperties, out callbackMessageContextProperty))
            {
                EndpointAddress listenAddress;
                IDictionary <string, string> context;
                callbackMessageContextProperty.GetListenAddressAndContext(out listenAddress, out context);

                return(new CorrelationCallbackContext
                {
                    ListenAddress = EndpointAddress10.FromEndpointAddress(listenAddress),
                    Context = context
                });
            }
            return(null);
        }
Exemplo n.º 52
0
            internal PendingMessageWrapper(T msg)
            {
                Message = msg;

                WasCancelled = false;
                WasFinished  = true;

                Properties = new MessageProperties {
                    CorrelationId = "UNIT-TEST",
                    DeliveryTag   = 1234,
                    Exchange      = "UNIT-TEST",
                    OriginalType  = typeof(T).Name,
                    SenderName    = "UNIT-TEST"
                };

                Cancel = () => { WasCancelled = true; };
                Finish = () => { WasFinished = true; };
            }
Exemplo n.º 53
0
        private Type ToType(MessageProperties properties)
        {
            var inferredType = properties.InferredArgumentType;

            if (inferredType != null && !inferredType.IsAbstract && !inferredType.IsInterface)
            {
                return(inferredType);
            }

            var typeIdHeader = RetrieveHeaderAsString(properties, DEFAULT_CLASSID_FIELD_NAME);

            if (typeIdHeader != null)
            {
                return(FromTypeHeader(properties, typeIdHeader));
            }

            return(typeof(object));
        }
        internal static bool TryGet(MessageProperties properties, out ChannelBindingMessageProperty property)
        {
            if (properties == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(properties));
            }

            property = null;
            object value;

            if (properties.TryGetValue(ChannelBindingMessageProperty.Name, out value))
            {
                property = value as ChannelBindingMessageProperty;
                return(property != null);
            }

            return(false);
        }
        public void MessageToSerializedObject()
        {
            var converter  = new SimpleMessageConverter();
            var properties = new MessageProperties();

            properties.ContentType = MessageProperties.CONTENT_TYPE_SERIALIZED_OBJECT;
            var binaryFormatter = new BinaryFormatter();
            var byteStream      = new MemoryStream();
            var testObject      = new TestObject("foo");

            binaryFormatter.Serialize(byteStream, testObject);
            var bytes   = byteStream.ToArray();
            var message = new Message(bytes, properties);
            var result  = converter.FromMessage(message);

            Assert.AreEqual(typeof(TestObject), result.GetType());
            Assert.AreEqual(testObject, result);
        }
Exemplo n.º 56
0
        public static async Task <Message> ModifyInteractionResponseAsync(BaseDiscordClient client, string token, Action <MessageProperties> func,
                                                                          RequestOptions options = null)
        {
            var args = new MessageProperties();

            func(args);

            var embed  = args.Embed;
            var embeds = args.Embeds;

            bool hasText       = !string.IsNullOrEmpty(args.Content.GetValueOrDefault());
            bool hasEmbeds     = embed.IsSpecified && embed.Value != null || embeds.IsSpecified && embeds.Value?.Length > 0;
            bool hasComponents = args.Components.IsSpecified && args.Components.Value != null;

            if (!hasComponents && !hasText && !hasEmbeds)
            {
                Preconditions.NotNullOrEmpty(args.Content.IsSpecified ? args.Content.Value : string.Empty, nameof(args.Content));
            }

            var apiEmbeds = embed.IsSpecified || embeds.IsSpecified ? new List <API.Embed>() : null;

            if (embed.IsSpecified && embed.Value != null)
            {
                apiEmbeds.Add(embed.Value.ToModel());
            }

            if (embeds.IsSpecified && embeds.Value != null)
            {
                apiEmbeds.AddRange(embeds.Value.Select(x => x.ToModel()));
            }

            Preconditions.AtMost(apiEmbeds?.Count ?? 0, 10, nameof(args.Embeds), "A max of 10 embeds are allowed.");

            var apiArgs = new ModifyInteractionResponseParams
            {
                Content         = args.Content,
                Embeds          = apiEmbeds?.ToArray() ?? Optional <API.Embed[]> .Unspecified,
                AllowedMentions = args.AllowedMentions.IsSpecified ? args.AllowedMentions.Value?.ToModel() : Optional <API.AllowedMentions> .Unspecified,
                Components      = args.Components.IsSpecified ? args.Components.Value?.Components.Select(x => new API.ActionRowComponent(x)).ToArray() : Optional <API.ActionRowComponent[]> .Unspecified,
                Flags           = args.Flags
            };

            return(await client.ApiClient.ModifyInteractionResponseAsync(apiArgs, token, options).ConfigureAwait(false));
        }
Exemplo n.º 57
0
        /// <summary>Creates an AMQP Message from the provided Object.</summary>
        /// <param name="obj">The obj.</param>
        /// <param name="messageProperties">The message properties.</param>
        /// <returns>The message.</returns>
        /// <exception cref="MessageConversionException"></exception>
        protected override Message CreateMessage(object obj, MessageProperties messageProperties)
        {
            byte[] bytes = null;

            if (obj is byte[])
            {
                bytes = (byte[])obj;
                messageProperties.ContentType = MessageProperties.CONTENT_TYPE_BYTES;
            }
            else if (obj is string)
            {
                try
                {
                    bytes = SerializationUtils.SerializeString((string)obj, this.defaultCharset);
                }
                catch (Exception e)
                {
                    throw new MessageConversionException("failed to convert to Message content", e);
                }

                messageProperties.ContentType     = MessageProperties.CONTENT_TYPE_TEXT_PLAIN;
                messageProperties.ContentEncoding = this.defaultCharset;
            }
            else if (obj.GetType().IsSerializable || (obj != null && obj.GetType().IsSerializable))
            {
                try
                {
                    bytes = SerializationUtils.SerializeObject(obj);
                }
                catch (Exception e)
                {
                    throw new MessageConversionException("failed to convert to serialized Message content", e);
                }

                messageProperties.ContentType = MessageProperties.CONTENT_TYPE_SERIALIZED_OBJECT;
            }

            if (bytes != null)
            {
                messageProperties.ContentLength = bytes.Length;
            }

            return(new Message(bytes, messageProperties));
        }
Exemplo n.º 58
0
        /// <summary>
        /// 插入评论
        /// </summary>
        /// <param name="rData"></param>
        /// <returns></returns>
        private int InsertComments(CommentsData rData)
        {
            string puid       = rData.puid ?? string.Empty;
            string sourceId   = rData.srcid ?? string.Empty;
            string content    = rData.content ?? string.Empty;
            string sourceType = rData.type ?? string.Empty;
            string url        = rData.url ?? string.Empty;
            int    us_id      = int.Parse(rData.us_id);
            string us_name    = rData.us_name;

            CommentInfo cmt = new CommentInfo();

            cmt.cmt_accept       = 0;
            cmt.cmt_checkRemark  = string.Empty;
            cmt.cmt_checkTime    = string.Empty;
            cmt.cmt_checkUser    = string.Empty;
            cmt.cmt_content      = content;
            cmt.cmt_createTime   = DateTime.Now;
            cmt.cmt_createUser   = us_name;
            cmt.cmt_createUserID = us_id;
            cmt.cmt_id           = 0;

            OperationContext              context           = OperationContext.Current;
            MessageProperties             messageProperties = context.IncomingMessageProperties;
            RemoteEndpointMessageProperty endpointProperty  =
                messageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;

            cmt.cmt_ip = endpointProperty.Address;

            cmt.cmt_ipArea     = string.Empty;
            cmt.cmt_parentIds  = string.Empty;
            cmt.cmt_sourceId   = sourceId;
            cmt.cmt_sourceType = sourceType;
            cmt.cmt_status     = 1;
            cmt.cmt_title      = string.Empty;
            cmt.cmt_uid        = GetCmtUID(sourceId);

            cmt.cmt_sourceCateId = rData.cmt_sourceCateId;
            cmt.cmt_platform     = rData.cmt_platform;
            cmt.cmt_device       = rData.cmt_device;
            cmt.cmt_title        = rData.cmt_title;

            return(DataAccess_News.Comments_Insert(cmt, puid, url));
        }
Exemplo n.º 59
0
        internal static string GetTrackingId(MessageProperties messageProperties, MessageHeaders messageHeaders, WebOperationContext webOperationContext)
        {
            string id;
            TrackingIdMessageProperty trackingIdMessageProperty;
            TrackingIdHeader          trackingIdHeader;

            if (!TrackingIdMessageProperty.TryGet <TrackingIdMessageProperty>(messageProperties, out trackingIdMessageProperty))
            {
                string str = null;
                if (webOperationContext != null)
                {
                    str = webOperationContext.IncomingRequest.Headers.Get("TrackingId");
                }
                if (TrackingIdHeader.TryRead(messageHeaders, out trackingIdHeader))
                {
                    id = trackingIdHeader.Id;
                }
                else if (messageHeaders.RelatesTo != null)
                {
                    Guid trackingId = TrackingContext.GetTrackingId(messageHeaders.RelatesTo);
                    id = TrackingContext.AppendRoleInstanceInformationToTrackingId(trackingId.ToString());
                }
                else if (messageHeaders.MessageId != null)
                {
                    Guid guid = TrackingContext.GetTrackingId(messageHeaders.MessageId);
                    id = TrackingContext.AppendRoleInstanceInformationToTrackingId(guid.ToString());
                }
                else if (string.IsNullOrEmpty(str))
                {
                    Guid guid1 = Guid.NewGuid();
                    id = TrackingContext.AppendRoleInstanceInformationToTrackingId(guid1.ToString());
                }
                else
                {
                    id = TrackingContext.AppendRoleInstanceInformationToTrackingId(str);
                }
                TrackingIdMessageProperty.TryAdd(messageProperties, id);
            }
            else
            {
                id = trackingIdMessageProperty.Id;
            }
            return(id);
        }
Exemplo n.º 60
0
        public static async Task <Model> ModifyAsync(IMessage msg, BaseDiscordClient client, Action <MessageProperties> func,
                                                     RequestOptions options)
        {
            if (msg.Author.Id != client.CurrentUser.Id)
            {
                throw new InvalidOperationException("Only the author of a message may change it.");
            }

            var args = new MessageProperties();

            func(args);
            var apiArgs = new API.Rest.ModifyMessageParams
            {
                Content = args.Content,
                Embed   = args.Embed.IsSpecified ? args.Embed.Value.ToModel() : Optional.Create <API.Embed>()
            };

            return(await client.ApiClient.ModifyMessageAsync(msg.Channel.Id, msg.Id, apiArgs, options).ConfigureAwait(false));
        }