private HttpContent CreateAutoSizedBatch(IEnumerable <EventEntry> collection, out int publishedEventCount)
        {
            long       totalSerializedSizeInBytes = 0;
            const long maxMessageSizeInBytes      = 250000;
            var        messages = new List <BatchMessage>();

            foreach (var eventEntry in collection)
            {
                var batchMessage = eventEntry.ToBatchMessage();
                totalSerializedSizeInBytes += JsonConvert.SerializeObject(batchMessage.Body).Length;

                if (totalSerializedSizeInBytes > maxMessageSizeInBytes)
                {
                    break;
                }

                messages.Add(batchMessage);
            }

            var sendMessage = new ServiceBusHttpMessage
            {
                Body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(messages))
            };

            HttpContent postContent = new ByteArrayContent(sendMessage.Body);

            postContent.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.microsoft.servicebus.json");

            publishedEventCount = messages.Count;

            return(postContent);
        }
        public async Task ShouldWritePropertiesForBatchMessage()
        {
            var httpClient = HttpClientTestHelper.Create();

            httpClient.PostAsync(Arg.Any <string>(), Arg.Any <HttpContent>()).Returns(Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)));

            var entry = EventEntryTestHelper.Create();

            using (var sink = new EventHubHttpSink(httpClient, "eventHubNameNs", "eventhubName", "pubId", "token", Buffering.DefaultBufferingInterval, Buffering.DefaultBufferingCount, Buffering.DefaultMaxBufferSize, TimeSpan.Zero))
            {
                sink.OnNext(entry);
                sink.OnNext(entry);

                await sink.FlushAsync();
            }

            IList <EventEntry> entries = new List <EventEntry> {
                entry, entry
            };
            var messages    = entries.Select(c => c.ToBatchMessage());
            var sendMessage = new ServiceBusHttpMessage
            {
                Body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(messages))
            };

            var byteRepresentation = sendMessage.Body;

            await httpClient.Received().PostAsync(Arg.Any <string>(), Arg.Is <HttpContent>(c => byteRepresentation.SequenceEqual(c.ReadAsByteArrayAsync().Result)));
        }
Exemplo n.º 3
0
        private static void ProcessMessage(ServiceBusHttpMessage message)
        {
            Console.ForegroundColor = ConsoleColor.Yellow;
            if (message != null)
            {
                Console.WriteLine("Body           : " + Encoding.UTF8.GetString(message.Body));
                Console.WriteLine("Message ID     : " + message.BrokerProperties.MessageId);
                Console.WriteLine("Label          : " + message.BrokerProperties.Label);
                Console.WriteLine("SequenceNumber : " + message.BrokerProperties.SequenceNumber);
                Console.WriteLine("TTL            : " + message.BrokerProperties.TimeToLive + " seconds");
                Console.WriteLine("EnqueuedTime   : " + message.BrokerProperties.EnqueuedTimeUtcDateTime + " UTC");
                Console.WriteLine("Locked until   : " + (message.BrokerProperties.LockedUntilUtcDateTime == null ?
                                                         "unlocked" : message.BrokerProperties.LockedUntilUtcDateTime + " UTC"));

                foreach (var key in message.CustomProperties.AllKeys)
                {
                    Console.WriteLine("Custom property: " + key + " = " + message.CustomProperties[key]);
                }
            }
            else
            {
                Console.WriteLine("(No message)");
            }
            Console.ForegroundColor = ConsoleColor.Gray;
        }
Exemplo n.º 4
0
        private async void waitForMessage()
        {
            while (true)
            {
                m_msg = await hc.ReceiveMessage("https://[servicebusname].servicebus.windows.net/open/subscriptions/all");

                if (m_msg != null)
                {
                    await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() =>
                    {
                        if (m_msg.customProperties.ContainsKey("iothub-connection-device-id"))
                        {
                            string deviceId  = m_msg.customProperties["iothub-connection-device-id"]?.ToString().Replace("\"", String.Empty);
                            var deviceTwin   = await m_rm.GetTwinAsync(deviceId);
                            StringBuilder sb = new StringBuilder();
                            sb.AppendLine(deviceTwin.Tags["address"].ToString());
                            sb.AppendLine(deviceTwin.Tags["city"].ToString());
                            sb.AppendLine(deviceTwin.Tags["country"].ToString());
                            sb.AppendLine(deviceTwin.Tags["notes"].ToString());
                            txtInfo.Text = sb.ToString();
                        }
                        btnConfirm.IsEnabled = true;
                    });

                    return;
                }
            }
        }
        private HttpContent CreateManualSizedBatch(ICollection <EventEntry> collection, out int publishedEventCount)
        {
            var messages = collection.Select(c => c.ToBatchMessage());

            var sendMessage = new ServiceBusHttpMessage
            {
                Body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(messages))
            };

            HttpContent postContent = new ByteArrayContent(sendMessage.Body);

            postContent.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.microsoft.servicebus.json");

            publishedEventCount = collection.Count;

            return(postContent);
        }
Exemplo n.º 6
0
        static void Main(string[] args)
        {
            var baseAddressHttp = "https://" + ServiceBusNamespace + ".servicebus.windows.net/";
            var topicAddress    = baseAddressHttp + TopicName;

            HttpClientHelper.DisableServerCertificateValidation = true;
            HttpClientHelper httpClientHelper  = null;
            Timer            tokenRenewalTimer = null;
            var renewalInterval = TimeSpan.FromMinutes(AuthTokenExpirationMinutes) - TimeSpan.FromSeconds(30); // give ourselves a 30 second buffer

            if (!string.IsNullOrEmpty(SasKey))
            {
                // Create service bus http client and setup SAS token auto-renewal timer
                httpClientHelper  = new HttpClientHelper(ServiceBusNamespace, SasKeyName, SasKey, AuthTokenExpirationMinutes);
                tokenRenewalTimer = new Timer(x =>
                {
                    httpClientHelper.RenewSasToken(AuthTokenExpirationMinutes);
                    Console.WriteLine("SAS token renewed");
                }, null, renewalInterval, renewalInterval);
            }
            else if (!string.IsNullOrEmpty(AcsKey))
            {
                // Create service bus http client and setup ACS token auto-renewal timer
                httpClientHelper  = new HttpClientHelper(ServiceBusNamespace, AcsIdentity, AcsKey);
                tokenRenewalTimer = new Timer(x =>
                {
                    httpClientHelper.RenewAcsToken();
                    Console.WriteLine("ACS token renewed");
                }, null, renewalInterval, renewalInterval);
            }

            if (httpClientHelper == null)
            {
                throw new Exception("Failed to acquire authorization token");
            }

            // Create topic of size 1GB. Specify a default TTL of 10 minutes. Time durations
            // are formatted according to ISO 8610 (see http://en.wikipedia.org/wiki/ISO_8601#Durations).
            Console.WriteLine("Creating topic ...");
            var topicDescription = Encoding.UTF8.GetBytes(File.ReadAllText(".\\EntityDescriptions\\TopicDescription.xml"));

            httpClientHelper.CreateEntity(topicAddress, topicDescription, RequestTimeoutSeconds).Wait();

            // Optionally query the topic.
            Console.WriteLine("Query Topic ...");
            var queryTopicResponse = httpClientHelper.GetEntity(topicAddress, RequestTimeoutSeconds).Result;

            Console.WriteLine("Topic:\n" + Encoding.UTF8.GetString(queryTopicResponse));

            // start the message publishing loop
            var i = 0;

            while (true)
            {
                // Send message to the topic.
                Console.WriteLine("Sending message {0}...", ++i);
                var message = new ServiceBusHttpMessage
                {
                    Body             = Encoding.UTF8.GetBytes("This is message #" + i),
                    BrokerProperties =
                    {
                        Label     = "M1",
                        MessageId = i.ToString()
                    }
                };

                // adding custom properties effectively adds custom HTTP headers
                message.CustomProperties["Priority"]     = "High";
                message.CustomProperties["CustomerId"]   = "12345";
                message.CustomProperties["CustomerName"] = "ABC";
                message.CustomProperties["RecipientId"]  = Dns.GetHostName().ToLower();

                httpClientHelper.SendMessage(topicAddress, message, RequestTimeoutSeconds).Wait();
                Thread.Sleep(5000);
            }
        }