public void TryGetNextMessage_WhenThereIsAMessage_ReturnsValues()
        {
            //Arrange
            ulong deliveryTag = 1;
            string routingKey = "routingKey";
            byte[] byteArray = {0,1,0};
            IBasicProperties basicProperties = new BasicProperties();;
            IBasicConsumer basicConsumer = null;
            var model = Substitute.For<IModel>();
            model.BasicConsume("queueName", false, Arg.Do<IBasicConsumer>(x => basicConsumer = x));

            var sut = new ConfirmingSubscription(model);
            sut.Subscribe("queueName");

            //Act
            basicConsumer.HandleBasicDeliver(string.Empty, deliveryTag, false, string.Empty, routingKey, basicProperties, byteArray);
            DeliveredRabbitMessage message = null;
            bool result = sut.TryGetNextMessage(out message);

            //Assert
            Assert.That(message.DeliveryTag, Is.EqualTo(deliveryTag));
            Assert.That(message.RoutingKey, Is.EqualTo(routingKey));
            Assert.That(message.Body, Is.EqualTo(byteArray));
            Assert.That(message.Properties, Is.EqualTo(basicProperties));
        }
		public void	Dequeue_ShouldDispatchFromSeparateThread()
		{
			var	model =	new	Mock<IModel>();

			var	sharedQConsumer	= new SharedQueueConsumer(model.Object);

			var	msgsReceived = new List<MessageEnvelope>();

			var	curThreadId	= Thread.CurrentThread.ManagedThreadId;
			int	dispatchThreadId = 0;

			
			sharedQConsumer.Subscribe(new ActionAdapter((env) =>
			{
				msgsReceived.Add(env);
				dispatchThreadId = Thread.CurrentThread.ManagedThreadId;
			}));

			var	prop = new BasicProperties();
			sharedQConsumer.Queue.Enqueue(new BasicDeliverEventArgs()
			{
				Body = _serializer.Serialize(new MyMessage(), prop),
				BasicProperties	= prop
			});

			Thread.Sleep(100);

			msgsReceived.Count.Should().Be(1);
			dispatchThreadId.Should().BeGreaterThan(0);
			curThreadId.Should().NotBe(dispatchThreadId);
		}
        internal static IBasicProperties Copy(this IBasicProperties source)
        {
            var result = new BasicProperties
                             {
                                 AppId = source.AppId,
                                 ClusterId = source.ClusterId,
                                 ContentEncoding = source.ContentEncoding,
                                 ContentType = source.ContentType,
                                 CorrelationId = source.CorrelationId,
                                 DeliveryMode = source.DeliveryMode,
                                 Expiration = source.Expiration,
                                 MessageId = source.MessageId,
                                 Persistent = source.Persistent,
                                 Priority = source.Priority,
                                 Timestamp = source.Timestamp,
                                 Type = source.Type,
                                 UserId = source.UserId,
                                 ReplyTo = source.ReplyTo
                             };

            if (source.ReplyTo != null && source.ReplyToAddress != null)
                result.ReplyToAddress = source.ReplyToAddress;

            result.Headers = new Dictionary<String, Object>();

            if (source.Headers != null)
                foreach (var header in source.Headers)
                    result.Headers.Add(header.Key, header.Value);

            return result;
        }
        public void Should_raise_message_returned_event_when_message_returned()
        {
            const string exchange = "the exchange";
            const string replyText = "reply text";
            const string routingKey = "routing key";
            var body = new byte[0];
            var properties = new BasicProperties();
            
            publisher.Publish(channelMock, model => { }).Wait();
            
            channelMock.Raise(x => x.BasicReturn += null, null, new BasicReturnEventArgs
                {
                    Body = body,
                    Exchange = exchange,
                    ReplyText = replyText,
                    RoutingKey = routingKey,
                    BasicProperties = properties
                });

            var arg = eventBus.GetArgumentsForCallsMadeOn(x => x.Publish(Arg<ReturnedMessageEvent>.Is.Anything))[0][0];

            var messageEvent = arg as ReturnedMessageEvent;
            Assert.NotNull(messageEvent);
            Assert.AreSame(body, messageEvent.Body);
            Assert.NotNull(messageEvent.Properties);
            Assert.AreEqual(exchange, messageEvent.Info.Exchange);
            Assert.AreEqual(replyText, messageEvent.Info.ReturnReason);
            Assert.AreEqual(routingKey, messageEvent.Info.RoutingKey);
        }
        public void Should_be_able_to_subscribe_using_non_generic_extensions()
        {
            var are = new AutoResetEvent(false);
            MyMessage deliveredMessage = null;

            Action<object> onMessage = message =>
                {
                    deliveredMessage = (MyMessage)message;
                    are.Set();
                };

            mockBuilder.Bus.Subscribe(typeof (MyMessage), "subid", onMessage);

            var properties = new BasicProperties
                {
                    Type = "EasyNetQ.Tests.MyMessage:EasyNetQ.Tests"
                };

            var body = Encoding.UTF8.GetBytes("{ Text:\"Hello World\" }");

            mockBuilder.Consumers[0].HandleBasicDeliver(
                "consumer_tag",
                0,
                false,
                "exchange",
                "routing_key",
                properties,
                body);

            are.WaitOne(1000);
            deliveredMessage.ShouldNotBeNull();
            deliveredMessage.Text.ShouldEqual("Hello World");
        }
        public static void Main(string[] args)
        {
            var factory = new ConnectionFactory() { HostName = "localhost" };
            using (var connection = factory.CreateConnection())
            using (var channel = connection.CreateModel())
            {
                channel.ExchangeDeclare(exchange: "logs", type: "fanout");

                Random rand = new Random();

                while (true)
                {
                    var message = GetMessage(rand);
                    var body = Encoding.UTF8.GetBytes(message);

                    var properties = new BasicProperties();
                    properties.Headers = new Dictionary<string, object>();
                    properties.Headers.Add("type", "1");

                    channel.BasicPublish(exchange: "logs",
                                         routingKey: "",
                                         basicProperties: properties,
                                         body: body);
                    Console.WriteLine(" [x] Sent {0}", message);
                    Thread.Sleep(1000);
                }
            }

            Console.ReadLine();
        }
        protected void DeliverMessage(string correlationId, string exceptionMessage)
        {
            var properties = new BasicProperties
            {
                Type = "EasyNetQ.Tests.TestResponseMessage:EasyNetQ.Tests.Messages",
                CorrelationId = correlationId,
                Headers = new Dictionary<string, object>
                {
                    { "IsFaulted", true }
                }
            };

            if (exceptionMessage != null)
            {
                // strings are implicitly convertered in byte[] from RabbitMQ client
                // but not convertered back in string
                // check the source code in the class RabbitMQ.Client.Impl.WireFormatting
                properties.Headers.Add("ExceptionMessage", Encoding.UTF8.GetBytes(exceptionMessage));
            }

            var body = Encoding.UTF8.GetBytes("{}");

            mockBuilder.Consumers[0].HandleBasicDeliver(
                "consumer_tag",
                0,
                false,
                "the_exchange",
                "the_routing_key",
                properties,
                body
                );
        }
        public void SetUp()
        {
            mockBuilder = new MockBuilder();

            var queue = new Queue("test_queue", false);

            var are = new AutoResetEvent(false);
            mockBuilder.Bus.Advanced.Consume<ITestMessageInterface>(queue, (message, info) => Task.Factory.StartNew(() =>
                {
                    receivedMessage = message.Body;
                    are.Set();
                }));

            var publishedMessage = new Implementation { Text = "Hello Polymorphs!" };
            var body = new JsonSerializer(new TypeNameSerializer()).MessageToBytes(publishedMessage);
            var properties = new BasicProperties
                {
                    Type = new TypeNameSerializer().Serialize(typeof(Implementation))
                };

            mockBuilder.Consumers[0].HandleBasicDeliver(
                "consumer_tag",
                0,
                false,
                "exchange",
                "routing_key",
                properties,
                body
                );

            are.WaitOne(1000);
        }
Esempio n. 9
0
 public void ReadingRabbitContentType()
 {
     const String contentType = "application/custom";
     var properties = new BasicProperties
                          {
                              ContentType = contentType
                          };
     Assert.Equal(contentType, properties.ContentTypeOrDefault());
 }
Esempio n. 10
0
 public void ReadingRabbitContentEncoding()
 {
     const String contentEncoding = "UTF-16";
     var properties = new BasicProperties
                          {
                              ContentEncoding = contentEncoding
                          };
     Assert.Equal(contentEncoding, properties.ContentEncodingOrDefault());
 }
Esempio n. 11
0
        public void Copying()
        {
            const String appId = "app-id";
            const String clusterId = "cluster-id";
            const String type = "type";
            const String contentEncoding = "UTF-8";
            const String contentType = "application/xml";
            const String correlationId = "123";
            const Byte deliveryMode = 2;
            const String expiration = "60000";
            const String messageId = "456";
            const Byte priority = 3;
            const String userId = "me";
            const String replyTo = "amqp://my.host";
            var timestamp = new AmqpTimestamp(1445843868L);

            var properties = new BasicProperties
                                 {
                                     AppId = appId,
                                     ClusterId = clusterId,
                                     Type = type,
                                     ContentEncoding = contentEncoding,
                                     ContentType = contentType,
                                     CorrelationId = correlationId,
                                     DeliveryMode = deliveryMode,
                                     Expiration = expiration,
                                     MessageId = messageId,
                                     Priority = priority,
                                     UserId = userId,
                                     ReplyTo = replyTo,
                                     Headers = new Dictionary<String, Object>
                                                   {
                                                       { "h", "a" }
                                                   },
                                     Timestamp = timestamp
                                 };
            var copy = properties.Copy();

            Assert.Equal(appId, copy.AppId);
            Assert.Equal(clusterId, copy.ClusterId);
            Assert.Equal(type, copy.Type);
            Assert.Equal(contentEncoding, copy.ContentEncoding);
            Assert.Equal(contentType, copy.ContentType);
            Assert.Equal(correlationId, copy.CorrelationId);
            Assert.Equal(deliveryMode, copy.DeliveryMode);
            Assert.Equal(expiration, copy.Expiration);
            Assert.Equal(messageId, copy.MessageId);
            Assert.Equal(priority, copy.Priority);
            Assert.Equal(userId, copy.UserId);
            Assert.Equal(replyTo, copy.ReplyTo);
            Assert.Equal(PublicationAddress.Parse(replyTo), copy.ReplyToAddress);
            Assert.Equal(1, copy.Headers.Count);
            Assert.True(copy.Headers.ContainsKey("h"));
            Assert.Equal("a", copy.Headers["h"]);
            Assert.Equal(timestamp, copy.Timestamp);
        }
 public override void Send(RabbitMqMessageWrapper message)
 {
     var properties = new BasicProperties
     {
         Headers = new Dictionary<string, object>
         {
             {MessageIdHeader, GetNewMessageId().ToString()}
         }
     };
     _publishModel.BasicPublish(Configuration.ExchangeName, string.Empty, properties, message.Bytes);
 }
        public void Should_copy_from_Rabbit_client_properties()
        {
            const string replyTo = "reply to";

            var properties = new MessageProperties();
            var originalProperties = new BasicProperties {ReplyTo = replyTo};

            properties.CopyFrom(originalProperties);

            properties.ReplyTo.ShouldEqual(replyTo);
        }
Esempio n. 14
0
        public ExpectedResponse PrepareForResponse(string correlationId, BasicProperties basicProperties, AmqpModelContainer model, HttpRequestMessage request, TimeSpan requestTimeout, CancellationToken cancellationToken, TaskCompletionSource<HttpResponseMessage> taskSource)
        {
            //Set Reply to queue
            basicProperties.ReplyTo = RPCStrategyHelpers.DIRECT_REPLY_TO_QUEUENAME_ARG;
            var rpcModel = (RPCModelContainer)model;
            var arrival = new ExpectedResponse(rpcModel.ReceivedResponseEvent);
            rpcModel.ExpectResponse(correlationId, arrival);

            RPCStrategyHelpers.WaitForResponse(request, arrival, requestTimeout, model, true, cancellationToken, taskSource, () => CleanupMessagingResources(correlationId, arrival));
            return arrival;
        }
        public override void Send(RabbitMqMessageWrapper message)
        {
            var properties = new BasicProperties
            {
                Headers = new Dictionary<string, object>
                {
                    { "forward_exchange", Configuration.ExchangeName }
                }
            };

            _publishModel.BasicPublish(Configuration.StampExchangeName, "", properties, message.Bytes);
        }
Esempio n. 16
0
        public void Send(SendParams sendParams)
        {
            sendParams.BusMessage.Sent = DateTime.Now;
            sendParams.BusMessage.BusId = sendParams.BusId;

            BasicProperties basicProperties = new BasicProperties
            {
                AppId = sendParams.BusMessage.BusId,
                Timestamp = sendParams.BusMessage.Sent.ToAmqpTimestamp(),
                ContentType = sendParams.Serializer.ContentType,
                Headers = new Dictionary<string, object>()
            };

            byte[] bytes;

            if (sendParams.BusMessage.Data != null)
            {
                Type type = sendParams.BusMessage.Data.GetType();
                DataContractKey contractKey = _nameMappings.GetOrAdd(type, t => t.GetDataContractKey());

                basicProperties.Type = contractKey.Name;
                basicProperties.Headers.Add(MessagingConstants.HeaderNames.Name, contractKey.Name);
                basicProperties.Headers.Add(MessagingConstants.HeaderNames.NameSpace, contractKey.Ns);

                bytes = sendParams.Serializer.Serialize(sendParams.BusMessage);
            }
            else
            {
                bytes = new byte[0];
            }

            foreach (BusHeaderBase header in sendParams.BusMessage.Headers)
            {
                basicProperties.Headers.Add(header.Name, header.GetValue());
            }

            if (sendParams.PersistentDelivery)
            {
                basicProperties.SetPersistent(true);
            }

            if (!string.IsNullOrEmpty(sendParams.ReplyTo))
            {
                basicProperties.ReplyTo = sendParams.ReplyTo;
            }

            if (!string.IsNullOrEmpty(sendParams.CorrelationId))
            {
                basicProperties.CorrelationId = sendParams.CorrelationId;
            }

            sendParams.Model.BasicPublish(sendParams.Exchange, sendParams.RoutingKey, sendParams.MandatoryDelivery, false, basicProperties, bytes);
        }
Esempio n. 17
0
        public void Send(SendMessage messsage)
        {
            if (_publisherContext == null)
                throw new ApplicationException("The current channel can not publish  message.");

            var properties = new BasicProperties() { DeliveryMode = 2 };

            if (!_publisherContext.Durable)
                properties.DeliveryMode = 1;

            _channel.BasicPublish(_publisherContext.ExchangeName, messsage.RoutingKey, properties, messsage.ByteDatas);
        }
Esempio n. 18
0
 public void Send(GelfMessage message)
 {
     EstablishConnection();
     foreach (var bytes in encoder.Encode(messageSerializer.Serialize(message)))
     {
         var basicProperties = new BasicProperties
             {
                 DeliveryMode = configuration.Persistent ? (byte)2 : (byte)1
             };
         channel.BasicPublish(configuration.Exchange, configuration.RoutingKey, false, false, basicProperties, bytes);
     }
 }
        public void Should_copy_to_rabbit_client_properties()
        {
            const string replyTo = "reply to";

            var properties = new MessageProperties { ReplyTo = replyTo };
            var destinationProperties = new BasicProperties();

            properties.CopyTo(destinationProperties);

            destinationProperties.ReplyTo.ShouldEqual(replyTo);
            destinationProperties.IsReplyToPresent().ShouldBeTrue();
            destinationProperties.IsMessageIdPresent().ShouldBeFalse();
        }
Esempio n. 20
0
        public ExpectedResponse PrepareForResponse(string correlationId, BasicProperties basicProperties, AmqpModelContainer model, HttpRequestMessage request, TimeSpan requestTimeout, CancellationToken cancellationToken, TaskCompletionSource<HttpResponseMessage>  taskSource)
        {
            //Set Reply to queue
            basicProperties.ReplyTo = callbackQueueName;

            //Initialize response arrival object and add to expected responses dictionary
            var arrival = new ExpectedResponse();
            expectedResponses[correlationId] = arrival;

            RPCStrategyHelpers.WaitForResponse(request, arrival, requestTimeout, model, false, cancellationToken, taskSource, () => CleanupMessagingResources(correlationId, arrival));

            return arrival;

        }
Esempio n. 21
0
 public void HeadersFallbackContentType()
 {
     const String contentType = "application/custom";
     const String contentEncoding = "UTF-8";
     var encoding = Encoding.GetEncoding(contentEncoding);
     var properties = new BasicProperties
                          {
                              ContentEncoding = contentEncoding,
                              Headers = new Dictionary<String, Object>
                                            {
                                                { "Content-Type", encoding.GetBytes(contentType) }
                                            }
                          };
     Assert.Equal(contentType, properties.ContentTypeOrDefault());
 }
        public void An_exchange_is_bound_to_a_queue()
        {
            Model.ExchangeDeclare("TypeA", ExchangeType.Fanout, true, true, null);
            _queueName = Model.QueueDeclare("TypeA", true, true, true, null);

            Model.QueueBind(_queueName, "TypeA", "");
            Model.QueuePurge(_queueName);

            byte[] message = Encoding.UTF8.GetBytes("HELLO, WORLD.");

            IBasicProperties properties = new BasicProperties();
            properties.Type = "System.string";

            Model.BasicPublish("TypeA", "", properties, message);
        }
Esempio n. 23
0
        public void PublishMessagesToQueue(IEnumerable<HosepipeMessage> messages, QueueParameters parameters)
        {
            using (var connection = HosepipeConnection.FromParamters(parameters))
            using (var channel = connection.CreateModel())
            {
                foreach (var message in messages)
                {
                    var body = errorMessageSerializer.Deserialize(message.Body);

                    var properties = new BasicProperties();
                    message.Properties.CopyTo(properties);

                    channel.BasicPublish(message.Info.Exchange, message.Info.RoutingKey, properties, body);
                }
            }
        }
        public void PublishMessagesToQueue(IEnumerable<RecoveryMessage> messages, IQueueOptions options)
        {
            using (var connection = RabbitConnection.FromOptions(options))
            using (var channel = connection.CreateModel())
            {
                foreach (var message in messages)
                {
                    var body = Encoding.UTF8.GetBytes(message.Body);

                    var properties = new BasicProperties();
                    message.Properties.CopyTo(properties);

                    channel.BasicPublish(message.Info.Exchange, message.Info.RoutingKey, properties, body);
                }
            }
        }
Esempio n. 25
0
        public void BuildBasicProperties()
        {
            var collection = new HeaderCollection(new Dictionary<String, Object>(StringComparer.OrdinalIgnoreCase)
                                                      {
                                                          { "message_id", "one-id" },
                                                          { "timestamp", 123456789L }
                                                      });
            const String key = "foo";
            const String value = "bar";
            collection.AddHeader(key, value);
            var properties = new BasicProperties { Headers = new Dictionary<String, Object>() };
            collection.HydrateProperties(properties);

            Assert.Null(properties.MessageId);
            Assert.Equal(new AmqpTimestamp(0L), properties.Timestamp);
            Assert.True(collection.Headers.ContainsKey(key));
        }
        private void DeliverMessage(string message, string type)
        {
            var properties = new BasicProperties
            {
                Type = type,
                CorrelationId = "the_correlation_id"
            };
            var body = Encoding.UTF8.GetBytes(message);

            mockBuilder.Consumers[0].HandleBasicDeliver(
                "consumer tag",
                0,
                false,
                "the_exchange",
                "the_routing_key",
                properties,
                body
                );

            WaitForMessageDispatchToComplete();
        }
Esempio n. 27
0
        public void Should_be_able_to_serialize_basic_properties()
        {
            var originalProperties = new BasicProperties
            {
                AppId = "some app id",
                ClusterId = "cluster id",
                ContentEncoding = "content encoding",
                //ContentType = "content type",
                CorrelationId = "correlation id",
                DeliveryMode = 4,
                Expiration = "expiration",
                MessageId = "message id",
                Priority = 1,
                ReplyTo = "abc",
                Timestamp = new AmqpTimestamp(123344044),
                Type = "Type",
                UserId = "user id",
                Headers = new Dictionary<string, object>
                {
                    {"one", "header one"},
                    {"two", "header two"}
                }
            };

            var messageBasicProperties = new MessageProperties(originalProperties);
            var binaryMessage = serializer.MessageToBytes(messageBasicProperties);
            var deserializedMessageBasicProperties = serializer.BytesToMessage<MessageProperties>(binaryMessage);

            var newProperties = new BasicProperties();
            deserializedMessageBasicProperties.CopyTo(newProperties);

            Func<BasicProperties, string> getPropertiesString = p =>
            {
                var builder = new StringBuilder();
                p.AppendPropertyDebugStringTo(builder);
                return builder.ToString();
            };

            getPropertiesString(originalProperties).ShouldEqual(getPropertiesString(newProperties));
        }
Esempio n. 28
0
        private IBasicProperties CreateOverrideProperties(IBasicProperties properties,
                                                          IDictionary <string, object> headers)
        {
            IBasicProperties newProperties = new BasicProperties();

            newProperties.ContentType     = properties.ContentType ?? "";
            newProperties.ContentEncoding = properties.ContentEncoding ?? "";
            newProperties.Headers         = properties.Headers;
            if (newProperties.Headers == null)
            {
                newProperties.Headers = new Dictionary <string, object>();
            }
            foreach (var key in headers.Keys)
            {
                if (!newProperties.Headers.ContainsKey(key))
                {
                    newProperties.Headers.Add(key, headers[key]);
                }
            }

            newProperties.DeliveryMode = properties.DeliveryMode;
            return(newProperties);
        }
Esempio n. 29
0
        private static async Task SetAttributesAsync(IStorageItem item, FileAttributes attributes)
        {
            BasicProperties basicProperties = await item.GetBasicPropertiesAsync().TranslateWinRTTask(item.Path);

            // This works for only a subset of attributes, unsupported attributes are ignored.
            // We don't mask the attributes since WinRT just ignores the unsupported ones and flowing
            // them enables possible lightup in the future.
            var property = new KeyValuePair <string, object>("System.FileAttributes", (UInt32)ConvertFileAttributes(attributes));

            try
            {
                await basicProperties.SavePropertiesAsync(new[] { property }).AsTask().ConfigureAwait(false);
            }
            catch (Exception exception)
            {
                if (exception.HResult != HResults.ERROR_INVALID_PARAMETER)
                {
                    throw new ArgumentException(SR.Arg_InvalidFileAttrs);
                }

                throw exception.TranslateWinRTException(item.Path);
            }
        }
        /// <summary>
        /// This method purge old log files in the log folder, which are older than daysToKeepLog.
        /// </summary>
        public static async void PurgeLogFiles()
        {
            int      daysToKeepLog;
            DateTime todaysDate;
            var      logFolder = Windows.Storage.ApplicationData.Current.LocalFolder;

            try
            {
                daysToKeepLog = 5;
                todaysDate    = DateTime.Now.Date;

                logFolder = await logFolder.GetFolderAsync("Logs");

                IReadOnlyList <StorageFile> files = await logFolder.GetFilesAsync();

                if (files.Count < 1)
                {
                    return;
                }

                foreach (StorageFile file in files)
                {
                    BasicProperties basicProperties = await file.GetBasicPropertiesAsync();

                    if (file.FileType == ".log")
                    {
                        if (DateTime.Compare(todaysDate, basicProperties.DateModified.AddDays(daysToKeepLog).DateTime.Date) >= 0)
                        {
                            await file.DeleteAsync(StorageDeleteOption.PermanentDelete);
                        }
                    }
                }
            }
            catch (Exception)
            {
            }
        }
Esempio n. 31
0
        /// <summary>
        /// Loads a header from the specified stream.
        /// </summary>
        /// <param name="stream">The input stream.</param>
        /// <returns>A header loaded from the specified stream.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="stream"/> is <c>null</c>.</exception>
        public virtual Header Load(Stream stream)
        {
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            // optimization: be one byte ahead when loading columns => only one I/O read per column
            var buffer         = new byte[HEADER_SIZE + 1];
            int totalReadBytes = stream.Read(buffer, 0, buffer.Length);

            BasicProperties headerProperties = ParseBasicProperties(buffer);

            LoadColumnsResult loadColumnsResult = LoadColumns(stream, buffer.Last());

            totalReadBytes += loadColumnsResult.ReadBytes;

            int bytesToSkip = headerProperties.HeaderSize - totalReadBytes;

            if (bytesToSkip > 0)
            {
                // move to the end of the header
                if (stream.CanSeek)
                {
                    stream.Seek(bytesToSkip, SeekOrigin.Current);
                }
                else
                {
                    while (bytesToSkip > 0)
                    {
                        bytesToSkip -= stream.Read(buffer, 0, Math.Min(buffer.Length, bytesToSkip));
                    }
                }
            }

            return(CreateHeader(headerProperties, loadColumnsResult.Columns));
        }
Esempio n. 32
0
        private async Task SendResponse(FlowContext context, object message)
        {
            var reply = context.FlowState == null
                ? GetReply(context.MessageContext)
                : context.FlowState.Metadata.Reply;

            if (reply == null)
            {
                throw new YieldPointException("No response is required");
            }

            if (message.GetType().FullName != reply.ResponseTypeName)
            {
                throw new YieldPointException($"Flow must end with a response message of type {reply.ResponseTypeName}, {message.GetType().FullName} was returned instead");
            }

            var properties = new BasicProperties();

            // Only set the property if it's not null, otherwise a string reference exception can occur:
            // http://rabbitmq.1065348.n5.nabble.com/SocketException-when-invoking-model-BasicPublish-td36330.html
            if (reply.CorrelationId != null)
            {
                properties.CorrelationId = reply.CorrelationId;
            }

            // TODO disallow if replyto is not specified?
            if (reply.ReplyTo != null)
            {
                await publisher.PublishDirect(message, reply.ReplyTo, properties);
            }
            else
            {
                await publisher.Publish(message, properties);
            }

            await context.Delete();
        }
        internal static IBasicProperties Copy(this IBasicProperties source)
        {
            var result = new BasicProperties
            {
                AppId           = source.AppId,
                ClusterId       = source.ClusterId,
                ContentEncoding = source.ContentEncoding,
                ContentType     = source.ContentType,
                CorrelationId   = source.CorrelationId,
                DeliveryMode    = source.DeliveryMode,
                Expiration      = source.Expiration,
                MessageId       = source.MessageId,
                Persistent      = source.Persistent,
                Priority        = source.Priority,
                Timestamp       = source.Timestamp,
                Type            = source.Type,
                UserId          = source.UserId,
                ReplyTo         = source.ReplyTo
            };

            if (source.ReplyTo != null && source.ReplyToAddress != null)
            {
                result.ReplyToAddress = source.ReplyToAddress;
            }

            result.Headers = new Dictionary <String, Object>();

            if (source.Headers != null)
            {
                foreach (var header in source.Headers)
                {
                    result.Headers.Add(header.Key, header.Value);
                }
            }

            return(result);
        }
Esempio n. 34
0
        static void Main(string[] args)
        {
            string input   = "";
            var    factory = new ConnectionFactory()
            {
                Uri = "amqp://*****:*****@192.168.1.25:5672/test"
            };

            // 心跳超时,默认60秒
            factory.RequestedHeartbeat = 60;
            using (IConnection conn = factory.CreateConnection())
            {
                using (IModel channel = conn.CreateModel())
                {
                    while ("exit" != (input = Console.ReadLine()))
                    {
                        var msgBody = new RabbitReq();
                        msgBody.FunctionName = "Login";
                        msgBody.Parameters.Add("Account", "xingchao");
                        msgBody.Parameters.Add("Password", "123456");
                        var msgBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(msgBody));
                        var prop     = new BasicProperties();
                        prop.ContentType     = "application/json";
                        prop.ContentEncoding = "UTF-8";

                        //var client = new SimpleRpcClient(channel, "ExchangeName", ExchangeType.Direct, "RoutingKey");
                        var client = new SimpleRpcClient(channel, "QueueName");
                        IBasicProperties replyProp = new BasicProperties();
                        var replyMsgBytes          = client.Call(prop, msgBytes, out replyProp);

                        var response = JsonConvert.DeserializeObject <RabbitRes>(Encoding.UTF8.GetString(replyMsgBytes));

                        Console.WriteLine(JsonConvert.SerializeObject(response));
                    }
                }
            }
        }
Esempio n. 35
0
        private async void Save_ClickAsync(object sender, RoutedEventArgs e)
        {
            try
            {
                this.Document.TryGetFile(out StorageFile file);

                bool?overWrite = true;

                if (file != null)
                {
                    BasicProperties properties = await file.GetBasicPropertiesAsync();

                    if (properties.DateModified != this.Document.FileProperties.DateModified)
                    {
                        overWrite = await this.ShowOverWriteDialog(file.Name);
                    }
                }

                if (overWrite.HasValue == false)
                {
                    // User hit cancel.
                    return;
                }
                else if (overWrite.Value && file != null)
                {
                    this.ShowMessage(await this.Document.Save(file));
                }
                else
                {
                    this.SaveAs_ClickAsync(sender, e);
                }
            }
            catch (Exception ex)
            {
                this.ShowMessage($"ERROR OCCURRED: {ex.Message}");
            }
        }
        public static void Main(string[] args)
        {
            var factory = new ConnectionFactory()
            {
                HostName = "localhost"
            };

            using (var connection = factory.CreateConnection())
                using (var channel = connection.CreateModel())
                {
                    channel.ExchangeDeclare(exchange: "logs", type: "fanout");

                    Random rand = new Random();


                    while (true)
                    {
                        var message = GetMessage(rand);
                        var body    = Encoding.UTF8.GetBytes(message);

                        var properties = new BasicProperties();
                        properties.Headers = new Dictionary <string, object>();
                        properties.Headers.Add("type", "1");

                        channel.BasicPublish(exchange: "logs",
                                             routingKey: "",
                                             basicProperties: properties,
                                             body: body);
                        Console.WriteLine(" [x] Sent {0}", message);
                        Thread.Sleep(1000);
                    }
                }


            Console.ReadLine();
        }
Esempio n. 37
0
        public async void UpdateInfobar()
        {
            try
            {
                StorageFile file = model.LoadedFiles[model.FileIndex].file;
                string      info = "(" + (model.FileIndex + 1) + "/" + model.LoadedFiles.Count + ")";

                BasicProperties basicProperties = await file.GetBasicPropertiesAsync();

                info += " - " + FilerModel.BytesToString((long)basicProperties.Size);

                view.window.Infobar.FontStyle  = FontStyle.Normal;
                view.window.Infobar.Foreground = new SolidColorBrush(Colors.White);

                if (FilerModel.IsImageExtension(file.Name) && file.FileType.ToLower() != ".gif")
                {
                    BitmapImage dimensions = (BitmapImage)view.window.imgMainContent.Source;
                    int         height     = dimensions.PixelHeight;
                    int         width      = dimensions.PixelWidth;
                    info += " - ( " + width + " x " + height + " )";

                    if (height < 1000)
                    {
                        view.window.Infobar.FontStyle  = FontStyle.Italic;
                        view.window.Infobar.Foreground = new SolidColorBrush(Colors.Coral);
                    }
                }

                string location = file.Path.Replace(model.RootFolder.folder.Path, model.RootFolder.folder.Name);
                view.window.SetInfobar(info + "\n" + location);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Esempio n. 38
0
        public static async Task <ulong> GetFolderSizeAsync(StorageFolder folder)
        {
            ulong size = 0;

            try
            {
                foreach (StorageFolder thisFolder in await folder.GetFoldersAsync())
                {
                    size += await GetFolderSizeAsync(thisFolder);
                }

                foreach (StorageFile thisFile in await folder.GetFilesAsync())
                {
                    BasicProperties props = await thisFile.GetBasicPropertiesAsync();

                    size += props.Size;
                }
            }
            catch (Exception ex)
            {
            }

            return(size);
        }
        public async Task SendMessage <T> (T messageBody) where T : class
        {
            var producerTopic = configuration.GetSection("ProducerTopic").Value;
            var activityName  = $"{producerTopic} send";
            var props         = new BasicProperties();

            using (var activity = ActivitySource.StartActivity(activityName, ActivityKind.Producer)) {
                if (activity != null)
                {
                    TextFormat.Inject(activity.Context, props, this.InjectTraceContextIntoBasicProperties);
                    AddMessagingTags(activity);

                    using (var producer = new ProducerBuilder <Null, T> (producerConfig).Build()) {
                        try {
                            var dr = await producer.ProduceAsync(producerTopic, new Message <Null, T> {
                                Value = messageBody, Headers = props.Headers
                            });
                        } catch (ProduceException <Null, string> e) {
                            Console.WriteLine($"Delivery failed: {e.Error.Reason}");
                        }
                    }
                }
            }
        }
Esempio n. 40
0
        public void SendResponse(MessageContext context, HttpResponsePacket response)
        {
            if (disposed)
            {
                throw new ObjectDisposedException("Subscriber has been disposed");
            }
            if (String.IsNullOrEmpty(context.ReplyToQueue))
            {
                return;
            }

            if (conn == null)
            {
                //TODO: Log this -- it technically shouldn't happen. Also translate to a HTTP Unreachable because it means StartCallbackQueueConsumer didn't create a connection
                throw new ApplicationException("This is Bad");
            }

            //TODO: Channel Pool this connection
            using (IModel channel = conn.CreateModel())
            {
                BasicProperties basicProperties = new BasicProperties {
                    CorrelationId = context.CorrelationId
                };

                try
                {
                    channel.BasicPublish(String.Empty,
                                         context.ReplyToQueue,
                                         basicProperties,
                                         response.Serialize());
                }
                catch {
                    //TODO: Log execption
                }
            }
        }
Esempio n. 41
0
        public async Task Issue90([Frozen] ISerializer serializer, [Frozen] IRabbitMqConfiguration configuration, RabbitMqBusEngine sut, string consumerTag, ulong headerDeliveryTag, ulong deliveryTag, bool redelivered, string exchange, string routingKey, string messageId, Guid correlationId, DateTimeOffset sentOn, FirstTestCommand testCommand)
        {
            Mock.Get(serializer).Setup(p => p.DeserializeObject(It.IsAny <byte[]>(), It.IsAny <Type>(), It.IsAny <Encoding>())).Returns(testCommand);

            sut.SubscribeToCommand <FirstTestCommand>();

            var sequence = await sut.StartAsync();

            var encoding = Encoding.UTF8;

            IBasicProperties properties = new BasicProperties
            {
                MessageId       = messageId,
                ContentEncoding = encoding.WebName,
                Headers         = new Dictionary <string, object>
                {
                    ["Nybus:MessageId"]      = encoding.GetBytes(messageId),
                    ["Nybus:MessageType"]    = encoding.GetBytes(DescriptorName(testCommand.GetType())),
                    ["Nybus:CorrelationId"]  = correlationId.ToByteArray(),
                    ["RabbitMq:DeliveryTag"] = headerDeliveryTag
                }
            };

            var body = configuration.Serializer.SerializeObject(testCommand, encoding);

            var incomingMessages = sequence.DumpInList();

            sut.Consumers.First().Value.HandleBasicDeliver(consumerTag, deliveryTag, redelivered, exchange, routingKey, properties, body);

            Assert.That(incomingMessages, Has.Exactly(1).InstanceOf <CommandMessage <FirstTestCommand> >());

            var message = incomingMessages[0] as CommandMessage <FirstTestCommand>;

            Assert.That(message.Headers, Contains.Key("RabbitMq:DeliveryTag"));
            Assert.That(message.Headers["RabbitMq:DeliveryTag"], Is.EqualTo(deliveryTag.ToString()));
        }
Esempio n. 42
0
        static void Main(string[] args)
        {
            var rand = new Random();

            var factory = new ConnectionFactory()
            {
                HostName = "localhost"
            };
            var properties = new BasicProperties();

            using (var connection = factory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    channel.QueueDeclare("hello", false, false, false, null);


                    var message = new List <int>
                    {
                        1, 2, 3, 4, 5
                    };

                    var binFormatter = new BinaryFormatter();
                    var mStream      = new MemoryStream();
                    binFormatter.Serialize(mStream, message);

                    channel.BasicPublish(string.Empty, "hello", null, mStream.ToArray());



                    Console.WriteLine(" Press Enter to continue");

                    Console.ReadLine();
                }
            }
        }
        private async void PopulateGridView(IReadOnlyList <StorageFile> files, ObservableCollection <FileItem> items)
        {
            foreach (StorageFile file in files.Where(file => file.FileType == ".xml"))
            {
                FileItem item = new FileItem();
                item.Name = file.DisplayName;
                item.Load = this.Load;
                BasicProperties properties = await file.GetBasicPropertiesAsync();

                item.LastUpdated = properties.DateModified;
                items.Add(item);
            }

            creator = new FileItem {
                Name = "Untitled", Create = Create, Cancel = Cancel
            };
            NewFile.DataContext  = creator;
            fileList.DataContext = items;
            checkName(items);
            Binding bin = new Binding();

            bin.Path = new PropertyPath("Name");
            textBox.SetBinding(TextBox.TextProperty, bin);
        }
Esempio n. 44
0
        public async Task Commands_can_be_received([Frozen] IRabbitMqConfiguration configuration, RabbitMqBusEngine sut, string consumerTag, ulong deliveryTag, bool redelivered, string exchange, string routingKey, string messageId, Guid correlationId, FirstTestCommand command)
        {
            sut.SubscribeToCommand <FirstTestCommand>();

            var sequence = await sut.StartAsync();

            var encoding = Encoding.UTF8;

            IBasicProperties properties = new BasicProperties
            {
                MessageId       = messageId,
                ContentEncoding = encoding.WebName,
                Headers         = new Dictionary <string, object>
                {
                    ["Nybus:MessageId"]     = encoding.GetBytes(messageId),
                    ["Nybus:MessageType"]   = encoding.GetBytes(DescriptorName(command.GetType())),
                    ["Nybus:CorrelationId"] = correlationId.ToByteArray()
                }
            };

            var body = configuration.Serializer.SerializeObject(command, encoding);

            var incomingMessages = sequence.DumpInList();

            sut.Consumers.First().Value.HandleBasicDeliver(consumerTag, deliveryTag, redelivered, exchange, routingKey, properties, body);

            Assert.That(incomingMessages, Has.Exactly(1).InstanceOf <CommandMessage <FirstTestCommand> >());

            var message = incomingMessages[0] as CommandMessage <FirstTestCommand>;

            Assert.That(message, Is.Not.Null);
            Assert.That(message.MessageId, Is.EqualTo(messageId));
            Assert.That(message.MessageType, Is.EqualTo(MessageType.Command));
            Assert.That(message.Type, Is.EqualTo(command.GetType()));
            Assert.That(message.Command, Is.Not.Null);
        }
        private static void WriteBasicPropertiesAsHeader(AmqpPrimitivesWriter writer, 
			ushort channel, ulong bodySize, BasicProperties properties)
        {
            if (properties.IsEmpty)
            {
                // short cut when it's empty

                uint payloadSize = 4 + 8 + 2;
                writer.WriteFrameStart(AmqpConstants.FrameHeader, channel, payloadSize, 60, 0);
                writer.WriteULong(bodySize);
                // no support for continuation. must be less than 15 bits used
                writer.WriteUShort(properties._presenceSWord);
                writer.WriteOctet(AmqpConstants.FrameEnd);
            }
            else
            {
                writer.WriteFrameHeader(channel, bodySize, properties);
            }
        }
Esempio n. 46
0
        private async Task <DateTime> LastModifiedDate()
        {
            BasicProperties properties = await Folder.GetBasicPropertiesAsync();

            return(properties.DateModified.DateTime);
        }
Esempio n. 47
0
        /// <summary>Send an HTTP request as an asynchronous operation.</summary>
        /// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns>
        /// <param name="request">The HTTP request message to send.</param>
        /// <param name="cancellationToken">The cancellation token to cancel operation.</param>
        /// <exception cref="T:System.ArgumentNullException">The <paramref name="request" /> was null.</exception>
        public override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            if (request.RequestUri == null && BaseAddress == null)
            {
                throw new InvalidOperationException("The request URI must either be set or BaseAddress must be set");
            }

            if (disposed)
            {
                throw new ObjectDisposedException(GetType().FullName);
            }
            hasKickStarted = true;
            PrepareMessage(request);

            //Get Request Options
            RequestOptions requestOptions    = GetRequestOptions(request);
            var            messageProperties = GetMessagingProperties(requestOptions);

            //Determine if message expects a response
            TimeSpan requestTimeout = GetRequestTimeout(requestOptions);
            //TODO: expectingResponse has a slightly different meaning in publisher confirms
            //where timespan may be longer than zero but MessageExpectsReply is false
            //in which case the timeout only applies to how long to wait for the publisher confirmation.
            bool expectingResponse = requestTimeout != TimeSpan.Zero && GetExpectsReply(request);

            //Declare messaging resources
            ExpectedResponse   arrival = null;
            AmqpModelContainer model   = null;
            bool   modelClosed         = false;
            string correlationId       = null;

            //Get channel pool and decide on RPC strategy
            var          pool        = connectionMgr.GetConnectedPool();
            IRPCStrategy rpcStrategy = pool.IsDirectReplyToCapable && !Settings.DisableDirectReplies ? directStrategy : callbackStrategy;

            try
            {
                #region Ensure CallbackQueue is started (If Using CallbackQueue Strategy)

                rpcStrategy.StartStrategy(pool, expectingResponse);

                #endregion

                #region Populate BasicProperties
                //Fill BasicProperties

                BasicProperties basicProperties = new BasicProperties();

                //Set message delivery mode -- Make message persistent if either:
                // 1. Properties.Persistent is true
                // 2. messagingConfig.PersistentMessages is true and Properties.Persistent is null
                // 3. messagingConfig.PersistentMessages is true and Properties.Persistent is true
                if (messageProperties.Persistent == true || (messagingConfig.PersistentMessages && messageProperties.Persistent != false))
                {
                    basicProperties.Persistent = true;
                }

                //Set Exchange Headers
                var exchangeHeaders = messageProperties.Headers ?? messageMapper.GetHeaders(request);
                if (exchangeHeaders != null)
                {
                    basicProperties.Headers = exchangeHeaders;
                }

                if (expectingResponse)
                {
                    //Set CorrelationId
                    correlationId = correlationIdGen.GetNextId();
                    basicProperties.CorrelationId = correlationId;

                    //Set Expiration if messageProperties doesn't override Client.Timeout, RequestOptions and MessageMapper.
                    if (!messageProperties.Expiration.HasValue && requestTimeout != System.Threading.Timeout.InfiniteTimeSpan &&
                        (messagingConfig.MessageExpires == null || messagingConfig.MessageExpires(request)))
                    {
                        if (requestTimeout.TotalMilliseconds > Int32.MaxValue)
                        {
                            basicProperties.Expiration = Int32.MaxValue.ToString();
                        }
                        else
                        {
                            basicProperties.Expiration = ((int)requestTimeout.TotalMilliseconds).ToString();
                        }
                    }
                }
                else if (!messageProperties.Expiration.HasValue && (messagingConfig.MessageExpires == null || messagingConfig.MessageExpires(request)))
                {
                    //Request has a zero timeout and the message mapper indicates it should expire and messageproperties expiration is not set:
                    //Set the expiration to zero which means RabbitMQ will only transmit if there is a consumer ready to receive it.
                    //If there is no ready consumer, RabbitMQ drops the message. See https://www.rabbitmq.com/ttl.html

                    basicProperties.Expiration = "0";
                }

                //Set expiration if set in message properties
                if (messageProperties.Expiration.HasValue)
                {
                    if (messageProperties.Expiration != System.Threading.Timeout.InfiniteTimeSpan)
                    {
                        var expiration = messageProperties.Expiration.Value.Duration();
                        if (expiration.TotalMilliseconds > Int32.MaxValue)
                        {
                            basicProperties.Expiration = Int32.MaxValue.ToString();
                        }
                        else
                        {
                            basicProperties.Expiration = ((int)expiration.TotalMilliseconds).ToString();
                        }
                    }
                    else
                    {
                        //Infinite Timespan indicates that message should never expire
                        basicProperties.ClearExpiration();
                    }
                }

                #endregion

                #region Get Ready to Send Message

                model = rpcStrategy.GetModel(pool, false);

                var serviceName =
                    (requestOptions == null || requestOptions.ServiceName == null)
                    ? (messageMapper.GetServiceName(request) ?? String.Empty).Trim()
                    : requestOptions.ServiceName.Trim();

                RedeclareExchangesAndQueues(model, serviceName);

                //TODO: Check if cancellation token was set before operation even began
                var taskSource = new TaskCompletionSource <HttpResponseMessage>();

                var exchangeKind = ExchangeKind.Direct;
                //TODO: Get ExchangeKind from CLient.Settings.ExchangeKind
                //TODO: Pull exchangeName from a concurrent dictionary that has a key of serviceName, exchangeKind
                //exchangeKind could be an index into arrays that have concurrentDictionaries.
                var exchangeName = AmqpUtils.GetExchangeName(messagingConfig, serviceName, exchangeKind);

                #endregion

                #region Start waiting for response
                //Start waiting for response if a request timeout is set.
                if (expectingResponse)
                {
                    //TODO: Better to just check if cancellationHasbeen requested instead of checking if it's None
                    if (!cancellationToken.Equals(System.Threading.CancellationToken.None))
                    {
                        //TODO: Have cancellationtokens cancel event trigger callbackHandle
                        //In fact turn this whole thing into an extension
                    }

                    arrival = rpcStrategy.PrepareForResponse(correlationId, basicProperties, model, request, requestTimeout, cancellationToken, taskSource);
                }

                #endregion

                #region Send Message
                //TODO: Implement routing to a different exchangeKind via substituting exchangeName
                //Send message
                model.Channel.BasicPublish(exchangeName,
                                           messageProperties.RoutingKey ?? messageMapper.GetRoutingKey(request, exchangeKind) ?? AmqpUtils.GetWorkQueueRoutingKey(),
                                           basicProperties,
                                           request.ToHttpRequestPacket().Serialize());

                //Close channel
                if (!expectingResponse || rpcStrategy.ReturnModelAfterSending)
                {
                    CloseAmqpModel(model);
                    modelClosed = true;
                }

                #endregion

                #region Cleanup if not expecting response
                //Exit with OK result if no request timeout was set.
                if (!expectingResponse)
                {
                    //TODO: Investigate adding a publisher confirm for zero timeout messages so we know that RabbitMQ did pick up the message before replying OK.
                    //Might add extra complexity to this class.

                    //Zero timespan means the client isn't interested in a response
                    taskSource.SetResult(new HttpResponseMessage(System.Net.HttpStatusCode.OK)
                    {
                        Content = _emptyByteArrayContent
                    });

                    rpcStrategy.CleanupMessagingResources(correlationId, arrival);
                }

                #endregion

                return(taskSource.Task);
            }
            catch (Exception ex)
            {
                //TODO: Log this

                if (model != null && !modelClosed)
                {
                    if (expectingResponse && model.Flags == ChannelFlags.RPC || model.Flags == ChannelFlags.RPCWithPublisherConfirms)
                    {
                        //Model might still be in use in waiting thread and so unsafe to be recycled
                        model.Discard = true;
                    }

                    CloseAmqpModel(model);
                }

                rpcStrategy.CleanupMessagingResources(correlationId, arrival);

                if (ex is HttpRequestException)
                {
                    throw;
                }
                else
                {
                    throw GetWrappedException("An error occurred while sending the request.", ex);
                }
            }
        }
Esempio n. 48
0
 public StorageMedia(StorageFile file, BasicProperties basic)
 {
     File  = file;
     Basic = basic;
 }
Esempio n. 49
0
 public void Return(BasicProperties properties)
 {
     _channel.Return(properties);
 }
Esempio n. 50
0
        public void BasicPublishFast(string exchange, string routingKey, bool mandatory, BasicProperties properties,
                                     ArraySegment <byte> buffer)
        {
            ThrowIfRecoveryInProcess();

            _channel.BasicPublishFast(exchange, routingKey, mandatory, properties, buffer);
        }
 public static IPortableFileBasicProperties AsPortableBasicProperties(this BasicProperties properties)
 {
     return(new WinRTFileBasicProperties(properties));
 }
 public TestBusCommandMessage(ICommandMessage message, BasicProperties props)
 {
     Message = message;
     Props   = props;
 }
Esempio n. 53
0
        private static async Task <DateTimeOffset> GetLastWriteTimeAsync(IStorageItem item)
        {
            BasicProperties properties = await item.GetBasicPropertiesAsync().TranslateWinRTTask(item.Path);

            return(properties.DateModified);
        }
Esempio n. 54
0
 public override async Task <BasicProperties> GetBasicPropertiesAsync(CancellationToken ct)
 => BasicProperties.FromFilePath(Owner.Path);
Esempio n. 55
0
        /// <summary>
        /// Gets a file's size.
        /// </summary>
        private async Task <long> GetSizeAsync(IStorageFile file)
        {
            BasicProperties fileProperties = await file.GetBasicPropertiesAsync().AsTask().ConfigureAwait(false);

            return((long)fileProperties.Size);
        }
		public async Task Read_BasicReturn(Func<ushort, string, string, string, int, BasicProperties, Stream, Task> continuation, 
										   BasicProperties properties)
		{
			ushort replyCode = _amqpReader.ReadShort();
			string replyText = _amqpReader.ReadShortStr();
			string exchange = _amqpReader.ReadShortStr();
			string routingKey = _amqpReader.ReadShortStr();

			byte frameEndMarker = _amqpReader.ReadOctet();
			if (frameEndMarker != AmqpConstants.FrameEnd) throw new Exception("Expecting frameend!");

			// Frame Header / Content header

			byte frameHeaderStart = _amqpReader.ReadOctet();
			if (frameHeaderStart != AmqpConstants.FrameHeader) throw new Exception("Expecting Frame Header");

			// await _reader.SkipBy(4 + 2 + 2 + 2);
			ushort channel = _reader.ReadUInt16();
			int payloadLength = _reader.ReadInt32();
			ushort classId = _reader.ReadUInt16();
			ushort weight = _reader.ReadUInt16();
			var bodySize = (long) _reader.ReadUInt64();

			// BasicProperties properties = ReadRestOfContentHeader();
			ReadRestOfContentHeader(properties, bodySize == 0);

			// Frame Body(s)
			if (bodySize != 0)
			{
				frameHeaderStart = _reader.ReadByte();
				if (frameHeaderStart != AmqpConstants.FrameBody) throw new Exception("Expecting Frame Body");

				await _reader.SkipBy(2); // channel = _reader.ReadUInt16();
				uint length = _reader.ReadUInt32();

				// must leave pending Frame end

				if (length == bodySize)
				{
					// continuation(replyCode, replyText, exchange, routingKey);

					var marker = new RingBufferPositionMarker(_reader._ringBufferStream._ringBuffer);

					await continuation(replyCode, replyText, exchange, routingKey, (int)length, properties, _reader._ringBufferStream);

					if (marker.LengthRead < length)
					{
						checked
						{
							int offset = (int)(length - marker.LengthRead);
							await _reader.SkipBy(offset);
						}
					}
				}
				else
				{
					throw new NotSupportedException("Multi body not supported yet. Total body size is " + bodySize + " and first body is " + length + " bytes");
				}
			}
			else
			{
				// no body

				await continuation(replyCode, replyText, exchange, routingKey, 0, properties, EmptyStream);
			}
		}
Esempio n. 57
0
        /// <summary>
        /// ログ書き込み・ログバッファ消去
        /// </summary>
        /// <param name="log">ログデータ</param>
        /// <param name="logName1">ログファイル名</param>
        /// <param name="logName2">ログファイル名(リネーム用)</param>
        private static async Task WriteLogBufferToFileAsync(LoggingData log, string logName1, string logName2)
        {
            StorageFolder logFolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync(Settings.Folder, CreationCollisionOption.OpenIfExists);

            if (Settings.LoggingMode == LoggingModes.Size)
            {
                // サイズチェック
                try
                {
                    StorageFile cf = await logFolder.GetFileAsync(logName1);

                    BasicProperties bprop = await cf.GetBasicPropertiesAsync();

                    if (bprop.Size > (ulong)Settings.MaxFileSizeKB * 1024)
                    {
                        // サイズオーバー
                        DebugWrite("]]>!! SIZE OVER !!");
                        try
                        {
                            StorageFile df = await logFolder.GetFileAsync(logName2);

                            await df.DeleteAsync();
                        }
                        catch (FileNotFoundException)
                        {
                            // ファイルなし
                        }
                        await cf.RenameAsync(logName2);
                    }
                }
                catch (FileNotFoundException)
                {
                    // ファイルなし
                }
            }
            else
            {
                // ファイル日付チェック
                try
                {
                    StorageFile cf = await logFolder.GetFileAsync(logName1);

                    BasicProperties bprop = await cf.GetBasicPropertiesAsync();

                    TimeSpan dtdiff    = bprop.DateModified.Subtract(log.DateTime);
                    bool     fileChear = false;
                    switch (Settings.LoggingMode)
                    {
                    case LoggingModes.Day:
                    case LoggingModes.Week:
                        // ログデータ日時とログファイル更新日時差が1日越で1周したとみなす
                        if (dtdiff.Days > 1)
                        {
                            fileChear = true;
                        }
                        break;

                    case LoggingModes.Month:
                        // ログデータ日時とログファイル更新日時差が31日越で1周したとみなす
                        if (dtdiff.Days > 31)
                        {
                            fileChear = true;
                        }
                        break;
                    }
                    if (fileChear)
                    {
                        DebugWrite("]]>!! FILE CLEAR !!");
                        StorageFile df = await logFolder.GetFileAsync(logName1);

                        await df.DeleteAsync();
                    }
                }
                catch (FileNotFoundException)
                {
                    // ファイルなし
                }
            }

            var sf = await logFolder.CreateFileAsync(logName1, Windows.Storage.CreationCollisionOption.OpenIfExists);

            DebugWrite("]]>", sf.Path, lastFilename);

            // 書き込み
            await FileIO.AppendLinesAsync(sf, new List <string>(log.ToStrings()));

            // タイムスタンプ変更
            if (Internal.DateTime.DifferenceNow.Ticks != 0)
            {
                // できません
            }

            lastFilename = sf.Path;

            WriteQueueCount--;
        }
Esempio n. 58
0
        private async void More_Tab_Click(object sender, RoutedEventArgs e)
        {
            if (infos_opened)
            {
                RemoveInfos.Begin(); infos_opened = false;

                if (current_tab.TabContentType == ContentType.Folder)
                {
                    current_tab.FolderOpened = false;
                    await TabsWriteManager.PushUpdateTabAsync(current_tab, current_list, false);
                }
            }
            else
            {
                enable_selection = false;

                switch (current_tab.TabContentType)
                {
                case ContentType.File:
                    try
                    {
                        list_types.SelectedItem = LanguagesHelper.GetLanguageNameViaType(current_tab.TabType);

                        bool ItemFound = false; int EncodingCodepage = Encoding.GetEncoding(current_tab.TabEncoding).CodePage;
                        for (int i = 0; i < (list_encodings.Items.Count - 1); i++)
                        {
                            if (((EncodingType)list_encodings.Items[i]).EncodingCodepage == EncodingCodepage && ((EncodingType)list_encodings.Items[i]).EncodingBOM == current_tab.TabEncodingWithBOM)
                            {
                                list_encodings.SelectedIndex = i;
                                ItemFound = true;
                                break;
                            }
                        }

                        if (!ItemFound)
                        {
                            list_encodings.Items.Insert(0, new EncodingType {
                                EncodingName = Encoding.GetEncoding(current_tab.TabEncoding).EncodingName, EncodingCodepage = Encoding.GetEncoding(current_tab.TabEncoding).CodePage
                            });
                            list_encodings.SelectedIndex = 0;
                        }

                        switch (current_tab.TabStorageMode)
                        {
                        case StorageListTypes.LocalStorage:
                            StorageFile file = await StorageFile.GetFileFromPathAsync(current_tab.TabOriginalPathContent);

                            BasicProperties properties = await file.GetBasicPropertiesAsync();

                            if (properties.Size != 0)
                            {
                                if (properties.Size > 1024f)         //Ko
                                {
                                    size_file.Text = string.Format("{0:0.00}", (properties.Size / 1024f)) + " Ko";

                                    if ((properties.Size / 1024f) > 1024f)         //Mo
                                    {
                                        size_file.Text = string.Format("{0:0.00}", ((properties.Size / 1024f) / 1024f)) + " Mo";
                                    }
                                }
                                else         //Octect
                                {
                                    size_file.Text = properties.Size + " Octect(s)";
                                }
                            }

                            modified_file.Text = properties.DateModified.ToString();
                            created_file.Text  = file.DateCreated.ToString();
                            break;

                        case StorageListTypes.OneDrive:
                            if (await OneDriveAuthHelper.OneDriveAuthentification())
                            {
                                var Item = await TabsDataCache.OneDriveClient.Drive.Items[current_tab.TabOriginalPathContent].Request().GetAsync();

                                if (Item.Size != 0)
                                {
                                    if (Item.Size > 1024f)         //Ko
                                    {
                                        size_file.Text = string.Format("{0:0.00}", (Item.Size / 1024f)) + " Ko";

                                        if ((Item.Size / 1024f) > 1024f)         //Mo
                                        {
                                            size_file.Text = string.Format("{0:0.00}", ((Item.Size / 1024f) / 1024f)) + " Mo";
                                        }
                                    }
                                    else         //Octect
                                    {
                                        size_file.Text = Item.Size + " Octect(s)";
                                    }
                                }

                                modified_file.Text = Item.LastModifiedDateTime.ToString();
                                created_file.Text  = Item.CreatedDateTime.ToString();

                                //path_tab.Text = System.Net.WebUtility.HtmlDecode(Item.ParentReference.Path);
                            }
                            break;
                        }
                    }
                    catch { }

                    break;

                case ContentType.Folder:
                    current_tab.FolderOpened = true;
                    await TabsWriteManager.PushUpdateTabAsync(current_tab, current_list, false);

                    break;
                }

                ShowInfos.Begin(); infos_opened = true; enable_selection = true;
            }
        }
Esempio n. 59
0
        public Task BasicPublishWithConfirmation(string exchange, string routingKey, bool mandatory, BasicProperties properties,
                                                 ArraySegment <byte> buffer)
        {
            ThrowIfRecoveryInProcess();

            return(_channel.BasicPublishWithConfirmation(exchange, routingKey, mandatory, properties, buffer));
        }
		public async Task Read_BasicDelivery(Func<string, ulong, bool, string, string, int, BasicProperties, Stream, Task> continuation, 
			BasicProperties properties)
		{
			string consumerTag = _amqpReader.ReadShortStr();
			ulong deliveryTag = _amqpReader.ReadULong();
			bool redelivered = _amqpReader.ReadBits() != 0;
			string exchange =  _amqpReader.ReadShortStr();
			string routingKey =  _amqpReader.ReadShortStr();

			byte frameEndMarker = _amqpReader.ReadOctet();
			if (frameEndMarker != AmqpConstants.FrameEnd) throw new Exception("Expecting frameend!");

			// Frame Header / Content header

			byte frameHeaderStart = _amqpReader.ReadOctet();
			if (frameHeaderStart != AmqpConstants.FrameHeader) throw new Exception("Expecting Frame Header");

			// await _reader.SkipBy(4 + 2 + 2 + 2);
			ushort channel = _reader.ReadUInt16();
			int payloadLength = _reader.ReadInt32();
			ushort classId = _reader.ReadUInt16();
			ushort weight = _reader.ReadUInt16();
			long bodySize = (long) _reader.ReadUInt64();

			// BasicProperties properties = ReadRestOfContentHeader();
			ReadRestOfContentHeader(properties, bodySize == 0);

			// Frame Body(s)

			if (bodySize != 0)
			{
				// Support just single body at this moment.

				frameHeaderStart = _reader.ReadByte();
				if (frameHeaderStart != AmqpConstants.FrameBody) throw new Exception("Expecting Frame Body");

				// await _reader.SkipBy(2);
				channel = _reader.ReadUInt16();
				uint length = _reader.ReadUInt32();

				// Pending Frame end

				if (length == bodySize)
				{
					var marker = new RingBufferPositionMarker(_reader._ringBufferStream._ringBuffer);

					await continuation(consumerTag, deliveryTag, redelivered, exchange,
						routingKey, (int) length, properties, (Stream) _reader._ringBufferStream);

					if (marker.LengthRead < length)
					{
						checked
						{
							int offset = (int) (length - marker.LengthRead);
							await _reader.SkipBy(offset);
						}
					}
				}
				else
				{
					throw new NotSupportedException("Multi body not supported yet. Total body size is " + bodySize +
					                                " and first body is " + length + " bytes");
				}
			}
			else
			{
				// Empty body size, which is OK

				await continuation(consumerTag, deliveryTag, redelivered, exchange, routingKey, 0, properties, EmptyStream);

			}
		}