示例#1
0
        public void Scenario4_EventHubSendToPublisherWithToken(string sbnamespace, string eventHubEntity, string publisher, string sharedAccessKeyName, string sharedAccessKey)
        {
            string token = SharedAccessSignatureTokenProvider.GetPublisherSharedAccessSignature(
                new Uri(sbnamespace),
                eventHubEntity,
                publisher,
                sharedAccessKeyName,
                sharedAccessKey,
                new TimeSpan(0, 20, 0));

            string connectionString = ServiceBusConnectionStringBuilder.CreateUsingSharedAccessSignature(
                new Uri(sbnamespace),
                eventHubEntity,
                publisher,
                token);

            MessagingFactory factory = MessagingFactory.CreateFromConnectionString(connectionString);

            EventHubClient client = factory.CreateEventHubClient(eventHubEntity);

            EventHubSender sender = client.CreateSender(publisher);

            EventData data = new EventData(Encoding.UTF8.GetBytes("Body"));

            data.Properties["time"] = DateTime.UtcNow;

            sender.Send(data);

            sender.Close();
            client.Close();
            factory.Close();
        }
示例#2
0
        public async Task ReceiveDataFromCloud()
        {
            startingDateTimeUtc = DateTime.UtcNow - TimeSpan.FromHours(24);

            factory = MessagingFactory.CreateFromConnectionString(ConnectionString);

            client   = factory.CreateEventHubClient(eventHubEntity);
            group    = client.GetDefaultConsumerGroup();
            receiver = group.CreateReceiver(partitionId.ToString(), startingDateTimeUtc);

            try
            {
                while (true)
                {
                    EventData data = receiver.Receive();

                    if (data != null)
                    {
                        var receiveddata = Encoding.UTF8.GetString(data.GetBytes());

                        Debug.WriteLine("{0} {1} {2}", data.SequenceNumber, data.EnqueuedTimeUtc.ToLocalTime(), receiveddata);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Exception {0}", ex);
            }

            receiver.Close();
            client.Close();
            factory.Close();
        }
        //code adapted from tutorial https://paolopatierno.wordpress.com/2015/11/02/azure-iot-hub-get-telemetry-data-using-amqp-stack-and-azure-sb-lite/
        public static string GetMessage(string partitionId)
        {
            string result = null;
            ServiceBusConnectionStringBuilder builder = new ServiceBusConnectionStringBuilder(ConnectionString);

            builder.TransportType = TransportType.Amqp;

            MessagingFactory factory = MessagingFactory.CreateFromConnectionString(ConnectionString);

            EventHubClient        client = factory.CreateEventHubClient(eventHubEntity);
            EventHubConsumerGroup group  = client.GetDefaultConsumerGroup();

            var startingDateTimeUtc = DateTime.Now;

            EventHubReceiver receiver = group.CreateReceiver(partitionId, startingDateTimeUtc);

            EventData data = receiver.Receive();

            receiver.Close();
            client.Close();
            factory.Close();
            if (data != null)
            {
                result = Encoding.UTF8.GetString(data.GetBytes());
                return(result);
            }
            else
            {
                return(null);
            }
        }
示例#4
0
        private static void EventHubReceive()
        {
            var ehName     = "davnaeventhub";
            var connection = "Endpoint=sb://alewife.servicebus.windows.net/;SharedAccessKeyName=Receiver;SharedAccessKey=3jaTeykwRu84x93OpW3DftRO1WSHt4oi7QB0FRyHoyg=;TransportType=Amqp";

            MessagingFactory factory = MessagingFactory.CreateFromConnectionString(connection);

            EventHubClient        ehub     = factory.CreateEventHubClient(ehName);
            EventHubConsumerGroup group    = ehub.GetDefaultConsumerGroup();
            EventHubReceiver      receiver = group.CreateReceiver("1");

            while (true)
            {
                EventData data = receiver.Receive();

                if (data != null)
                {
                    var message = Encoding.UTF8.GetString(data.GetBytes());

                    Console.WriteLine("PartitionKey: {0}", data.PartitionKey);
                    Console.WriteLine("SequenceNumber: {0}", data.SequenceNumber);
                    Console.WriteLine(message);
                }
            }
        }
        public async Task<string> OpenAsync(CancellationToken cancellationToken)
        {
            var builder = new ServiceBusConnectionStringBuilder(_connectionString)
            {
                TransportType = TransportType.Amqp
            };
            _messagingFactory = MessagingFactory.CreateFromConnectionString(builder.ToString());
            _eventHubClient = _messagingFactory.CreateEventHubClient(_eventHubName);
            _consumerGroup = !string.IsNullOrEmpty(_consumerGroupName)
                ? _eventHubClient.GetConsumerGroup(_consumerGroupName)
                : _eventHubClient.GetDefaultConsumerGroup();

            _eventProcessorFactory = new EventProcessorFactory();
            _leaseRepository = new ReliableStateLeaseRepository(_reliableStateManager);
            _checkpointManager = new CheckpointManager(_leaseRepository); 

            var allocatedPartitions = await new EventHubPartitionPartitionAllocationStrategy(_serviceName, _partitionId)
                .AllocateAsync(_eventHubClient, new FabricClient());

            foreach (var partition in allocatedPartitions)
            {
                var lease = await _leaseRepository.GetOrCreateAsync(_connectionString, _consumerGroupName, _eventHubName, partition);

                await _consumerGroup.RegisterProcessorFactoryAsync(lease, _checkpointManager, _eventProcessorFactory);
            }

            return string.Concat(_eventHubName, " @ ", _connectionString);
        }
示例#6
0
        static void Main(string[] args)
        {
            string                ehname     = "<eventhubname>";
            string                connection = "Endpoint=sb://<eventhubnamespace>.servicebus.windows.net/;SharedAccessKeyName=<policy>;SharedAccessKey=<key>;TransportType=Amqp";
            MessagingFactory      factory    = MessagingFactory.CreateFromConnectionString(connection);
            EventHubClient        ehub       = factory.CreateEventHubClient(ehname);
            EventHubConsumerGroup group      = ehub.GetDefaultConsumerGroup();
            EventHubReceiver      reciever   = group.CreateReceiver("0");

            while (true)
            {
                EventData data = reciever.Receive();
                if (data != null)
                {
                    try
                    {
                        string message = Encoding.UTF8.GetString(data.GetBytes());
                        Console.WriteLine(message + " " + DateTime.Now);
                        Console.WriteLine();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                    }
                }
            }
        }
示例#7
0
        static void Main(string[] args)
        {
            string                ehname     = "<eventhubname>";
            string                connection = "<eventhubconnectionstring>,TransportType=Amqp";
            MessagingFactory      factory    = MessagingFactory.CreateFromConnectionString(connection);
            EventHubClient        ehub       = factory.CreateEventHubClient(ehname);
            EventHubConsumerGroup group      = ehub.GetDefaultConsumerGroup();
            EventHubReceiver      reciever   = group.CreateReceiver("0");

            while (true)
            {
                EventData data = reciever.Receive();
                if (data != null)
                {
                    try
                    {
                        string message = Encoding.UTF8.GetString(data.GetBytes());
                        //Console.WriteLine("Partition Key: {0}", data.PartitionKey);
                        Console.WriteLine(message);
                        Console.WriteLine();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                    }
                }
            }
        }
        private EventHubClient CreateClient()
        {
            MessagingFactory factory = MessagingFactory.CreateFromConnectionString(ConfigurationManager.AppSettings["IoTHubConnectionString"] + ";TransportType=Amqp");

            factory.RetryPolicy = new RetryExponential(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(20), 3);

            return(factory.CreateEventHubClient(ConfigurationManager.AppSettings["IotHubD2CEndpoint"]));
        }
示例#9
0
        public EventSender(
            MessagingFactory messagingFactory,
            SimulatorConfiguration config,
            Func<object, byte[]> serializer)
        {
            this._serializer = serializer;

            this._eventHubClient = messagingFactory.CreateEventHubClient(config.EventHubPath);
        }
        public MessagingFacotryPoolItem(string _sbConnectionString, string eventHubName, int clientPoolSize)
        {
            _messagingFactory   = MessagingFactory.CreateFromConnectionString(_sbConnectionString);
            _eventHubClientPool = new List <EventHubClient>(clientPoolSize);

            for (int i = 0; i < clientPoolSize; i++)
            {
                _eventHubClientPool.Add(_messagingFactory.CreateEventHubClient(eventHubName));
            }
        }
        public AzureEventHubService()
        {
            ServiceBusConnectionStringBuilder builder = new ServiceBusConnectionStringBuilder(AppConfig.EventHubConnectionString);

            builder.TransportType = TransportType.Amqp;

            MessagingFactory factory = MessagingFactory.CreateFromConnectionString(AppConfig.EventHubConnectionString);

            _client = factory.CreateEventHubClient(AppConfig.EventHubName);
        }
示例#12
0
        public EventHubsTraceListener()
        {
            MessagingFactory factory = MessagingFactory.Create(ServiceBusEnvironment.CreateServiceUri("sb", ConfigurationSettings.AppSettings["ServiceBus.Namespace"], ""), new MessagingFactorySettings()
            {
                TokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(ConfigurationSettings.AppSettings["ServiceBus.KeyName"], ConfigurationSettings.AppSettings["ServiceBus.Key"]),
                TransportType = TransportType.Amqp
            });

            _client = factory.CreateEventHubClient("vehicletelemetry");
        }
示例#13
0
        public MessageSender(
            MessagingFactory messagingFactory,
            SimulatorConfiguration config,
            Func<object, byte[]> serializer,
            ISenderInstrumentationPublisher telemetryPublisher)
        {
            this._serializer = serializer;
            this._instrumentationTelemetryPublisher = telemetryPublisher;

            this._eventHubClient = messagingFactory.CreateEventHubClient(config.EventHubPath);
        }
        public MessageSender(
            MessagingFactory messagingFactory,
            SimulatorConfiguration config,
            Func <object, byte[]> serializer,
            ISenderInstrumentationPublisher telemetryPublisher)
        {
            this._serializer = serializer;
            this._instrumentationTelemetryPublisher = telemetryPublisher;

            this._eventHubClient = messagingFactory.CreateEventHubClient(config.EventHubPath);
        }
示例#15
0
        public EventHubsTraceListener()
        {
            MessagingFactory factory = MessagingFactory.Create(ServiceBusEnvironment.CreateServiceUri("sb", ConfigurationManager.AppSettings["ServiceBus.Namespace"], ""), new MessagingFactorySettings()
            {
                TokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(ConfigurationManager.AppSettings["ServiceBus.KeyName"], ConfigurationManager.AppSettings["ServiceBus.Key"]),
                TransportType = TransportType.Amqp
            });

            _client = factory.CreateEventHubClient("Logs");

            // Event information.
            _instanceId = Environment.GetEnvironmentVariable("WEBSITE_INSTANCE_ID") ?? DateTime.Now.Ticks.ToString(CultureInfo.InvariantCulture);
            _siteName   = Environment.GetEnvironmentVariable("WEBSITE_SITE_NAME") ?? "CorporateWebApp";
        }
示例#16
0
        public EventHubClient CreateEventHubClient()
        {
            if (string.IsNullOrWhiteSpace(this.serviceBusConnectionString) || string.IsNullOrWhiteSpace(this.eventHubName))
            {
                return(null);
            }
            MessagingFactory messagingFactory =
                MessagingFactory.CreateFromConnectionString(
                    new ServiceBusConnectionStringBuilder(this.serviceBusConnectionString)
            {
                TransportType = TransportType.Amqp
            }.ToString());

            return(messagingFactory.CreateEventHubClient(this.eventHubName));
        }
示例#17
0
 public EventHub(EventHubConfiguration configuration)
 {
     _configuration = configuration;
     try
     {
         _messagingFactory      = MessagingFactory.CreateFromConnectionString(_configuration.EventHubConnectionString + TransportType);
         _eventHubClient        = _messagingFactory.CreateEventHubClient(_configuration.EventHubName);
         _eventHubConsumerGroup = _eventHubClient.GetConsumerGroup(_configuration.EventHubConsumer);
     }
     catch (Exception e)
     {
         Console.WriteLine($"{DateTime.Now} > Exception: {e.Message}");
         Console.WriteLine("Press any key to exit.");
         Console.ReadLine();
         Environment.Exit(-1);
     }
 }
示例#18
0
        protected void btnSend_Click(object sender, EventArgs e)
        {
            MessagingFactorySettings messagingFactorySettings = new MessagingFactorySettings
            {
                TokenProvider = TokenProvider.CreateManagedServiceIdentityTokenProvider(ServiceAudience.EventHubsAudience),
                TransportType = TransportType.Amqp
            };

            MessagingFactory messagingFactory = MessagingFactory.Create($"sb://{txtNamespace.Text}.servicebus.windows.net/",
                                                                        messagingFactorySettings);

            EventHubClient ehClient = messagingFactory.CreateEventHubClient(txtEventHub.Text);

            ehClient.Send(new EventData(Encoding.UTF8.GetBytes(txtData.Text)));
            ehClient.Close();
            messagingFactory.Close();
        }
示例#19
0
        private bool Send(string partitionKey, AsyncLogEventInfo[] logEvents)
        {
            if (_messsagingFactory == null)
            {
                _messsagingFactory = MessagingFactory.CreateFromConnectionString(CloudConfigurationManager.GetSetting(EventHubConnectionStringKey));
            }

            if (_eventHubClient == null)
            {
                _eventHubClient = _messsagingFactory.CreateEventHubClient(CloudConfigurationManager.GetSetting(EventHubNameKey));
            }

            var payload = FormPayload(logEvents.Select(e => e.LogEvent), partitionKey);

            _eventHubClient.SendBatch(payload);

            return(true);
        }
示例#20
0
        public static async Task GetAll(Action <string> processEvent, CancellationTokenSource cts)
        {
            Action <string> eventAction = processEvent;

            factory = MessagingFactory.CreateFromConnectionString(ConnectionString);

            client = factory.CreateEventHubClient(eventHubEntity);
            group  = client.GetDefaultConsumerGroup();

            var tasks = new List <Task>();

            foreach (string partition in PartitionIds)
            {
                tasks.Add(Task.Run(() => ReceiveMessagesFromDeviceAsync(partition, eventAction, cts.Token)));
            }

            await Task.WhenAll(tasks.ToArray());
        }
        public async Task <string> OpenAsync(CancellationToken cancellationToken)
        {
            await mOptions.PrepareAsync();

            var useDefaultConsumerGroup = !string.IsNullOrEmpty(mOptions.EventHubConsumerGroupName);


            mMessagingFactory = MessagingFactory.CreateFromConnectionString(mOptions.EventHubConnectionString);
            mEventHubClient   = mMessagingFactory.CreateEventHubClient(mOptions.EventHubName);
            mConsumerGroup    = useDefaultConsumerGroup ?
                                mEventHubClient.GetConsumerGroup(mOptions.EventHubConsumerGroupName)
                              : mEventHubClient.GetDefaultConsumerGroup();



            return(string.Concat(mEventHubNamespace, "/",
                                 mOptions.EventHubName, "/",
                                 useDefaultConsumerGroup ? "<default group>" : mOptions.EventHubConsumerGroupName));
        }
示例#22
0
        public void Scenario1_EventHubSend(string eventHubEntity)
        {
            ServiceBusConnectionStringBuilder builder = new ServiceBusConnectionStringBuilder(this.ConnectionString);

            builder.TransportType = TransportType.Amqp;

            MessagingFactory factory = MessagingFactory.CreateFromConnectionString(this.ConnectionString);

            EventHubClient client = factory.CreateEventHubClient(eventHubEntity);

            EventData data = new EventData(Encoding.UTF8.GetBytes("Body"));

            data.Properties["time"] = DateTime.UtcNow;

            client.Send(data);

            client.Close();
            factory.Close();
        }
示例#23
0
        public Task OpenEventHubAsync(string eventHubConnectionString, string hubName)
        {
            return(Task.Factory.StartNew(async() => {
                if (string.IsNullOrWhiteSpace(eventHubConnectionString))
                {
                    throw new ArgumentException("invalid event hub connection string");
                }

                if (string.IsNullOrWhiteSpace(hubName))
                {
                    throw new ArgumentException("invalid hubname");
                }
                this.IsOpen = true;

                var builder = new ServiceBusConnectionStringBuilder(eventHubConnectionString)
                {
                    TransportType = TransportType.Amqp
                };
                var s = builder.ToString();
                _factory = MessagingFactory.CreateFromConnectionString(builder.ToString());

                _client = _factory.CreateEventHubClient(hubName);

                var runtimeInfo = await _client.GetRuntimeInformationAsync();

                _partitions.Clear();
                foreach (var p in runtimeInfo.PartitionIds)
                {
                    var partition = await _client.GetPartitionRuntimeInformationAsync(p);
                    var count = partition.LastEnqueuedSequenceNumber - partition.BeginSequenceNumber;
                    if (count != 0)
                    {
                        count++;
                    }
                    this.MessageCount = count;
                    _partitions.Add(new Partition(p, _messages));
                    _foundPartitions.OnNext(partition);
                }

                _foundPartitions.OnCompleted();
            }));
        }
示例#24
0
        private static void SendToEventHub()
        {
            var ehName     = "davnaeventhub";
            var connection = "Endpoint=sb://<yournamespacehere>.servicebus.windows.net/;SharedAccessKeyName=Sender;SharedAccessKey=<yourkeyhere>;TransportType=Amqp";

            MessagingFactory factory = MessagingFactory.CreateFromConnectionString(connection);

            EventHubClient client = factory.CreateEventHubClient(ehName);

            for (var i = 0; i < 10000; i++)
            {
                var message = i + " event hub message";

                EventData data = new EventData(Encoding.UTF8.GetBytes(message));

                client.Send(data);

                Console.WriteLine(message);
            }
        }
示例#25
0
        /// <summary>
        /// Creates an EventHubClient through AMQP protocol
        /// </summary>
        /// <param name="iotHubConnectionString"></param>
        private EventHubClient GetAmqpEventHubClient(string iotHubConnectionString)
        {
            // EventHubs doesn't support NetMessaging, so ensure the transport type is AMQP.
            ServiceBusConnectionStringBuilder connectionStringBuilder =
                new ServiceBusConnectionStringBuilder(iotHubConnectionString)
            {
                TransportType = TransportType.Amqp
            };

            ServiceEventSource.Current.ServiceMessage(
                this.Context,
                "RoutingService connecting to IoT Hub at {0}",
                new object[] { string.Join(",", connectionStringBuilder.Endpoints.Select(x => x.ToString())) });

            // A new MessagingFactory is created here so that each partition of this service will have its own MessagingFactory.
            // This gives each partition its own dedicated TCP connection to IoT Hub.
            MessagingFactory messagingFactory = MessagingFactory.CreateFromConnectionString(connectionStringBuilder.ToString());
            EventHubClient   eventHubClient   = messagingFactory.CreateEventHubClient("messages/events");

            return(eventHubClient);
        }
示例#26
0
        //    static string eventHubName = ConfigurationManager.AppSettings["eventHubName"];
        //    static string connectionString = ConfigurationManager.AppSettings["sbConnectionString"];



        static void Main(string[] args)
        {
            string eventHubName     = args[0];
            string connectionString = args[1];

            double mean         = 0;
            double stdDev       = 5 / 3;
            int    numRooms     = 2;
            int    plantsInRoom = 4;

            string[] plantTypes = { "Rose", "SugarCane", "Watermelon", "Wheat" };


            //Set up connections to Service Bus and create the client object
            ServiceBusConnectionStringBuilder builder = new ServiceBusConnectionStringBuilder(connectionString);

            builder.TransportType = TransportType.Amqp;
            MessagingFactory    factory     = MessagingFactory.CreateFromConnectionString(builder.ToString());
            NamespaceManager    manager     = NamespaceManager.CreateFromConnectionString(connectionString);
            EventHubDescription description = manager.CreateEventHubIfNotExists(eventHubName);
            EventHubClient      client      = factory.CreateEventHubClient(eventHubName);


            //Allows for number of threads to be specified
            try
            {
                numThreads = Convert.ToInt32(ConfigurationManager.AppSettings["numThreads"]);
            }
            catch { }

            List <Sensor> sensors = setupGreenhouse(numRooms, plantsInRoom, plantTypes);

            //This loop continues to run and has all of the sensors updated and events sent.

            while (true)
            {
                advanceTime(sensors, mean, stdDev, client);
                Thread.Sleep(10000);
            }
        }
示例#27
0
        public void TestMethod1()
        {
            dynamic factorySettings = new ServiceBus.ConnectionPool.DynamicDictionary();

            factorySettings.ConnectionString = "your_connection_string";
            SBMessagingFactoryWithConnectionString fws = new SBMessagingFactoryWithConnectionString(factorySettings.ConnectionString);
            ConnectionPool <MessagingFactory>      sbp = new ConnectionPool <MessagingFactory>(fws, 10);

            sbp.Initialize();
            MessagingFactory mf1 = sbp.GetNext();
            EventHubClient   ehc = mf1.CreateEventHubClient("your_eventhub_name");
            EventData        ed  = new EventData(Encoding.UTF8.GetBytes("Hello"));

            try
            {
                ehc.Send(ed);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
示例#28
0
        public void Scenario8_EventHubReceiveFromPartitionDateTimeOffset(string eventHubEntity, string partitionId, DateTime dateTimeOffset)
        {
            ServiceBusConnectionStringBuilder builder = new ServiceBusConnectionStringBuilder(this.ConnectionString);

            builder.TransportType = TransportType.Amqp;

            MessagingFactory factory = MessagingFactory.CreateFromConnectionString(this.ConnectionString);

            EventHubClient        client = factory.CreateEventHubClient(eventHubEntity);
            EventHubConsumerGroup group  = client.GetDefaultConsumerGroup();

            EventHubReceiver receiver = group.CreateReceiver(partitionId, dateTimeOffset);

            while (true)
            {
                EventData data = receiver.Receive();
            }

            receiver.Close();
            client.Close();
            factory.Close();
        }
示例#29
0
        static void SendReceive(MessagingFactorySettings messagingFactorySettings)
        {
            MessagingFactory messagingFactory = MessagingFactory.Create($"sb://{EventHubNamespace}/",
                                                                        messagingFactorySettings);

            EventHubClient        ehClient      = messagingFactory.CreateEventHubClient(EventHubName);
            EventHubConsumerGroup consumerGroup = ehClient.GetDefaultConsumerGroup();

            var receiveTask = Task.Factory.StartNew(() =>
            {
                string[] partitionIds = { "0", "1" };
                Parallel.ForEach(partitionIds, partitionId =>
                {
                    EventHubReceiver receiver = consumerGroup.CreateReceiver(partitionId, EventHubConsumerGroup.StartOfStream);
                    while (true)
                    {
                        EventData data = receiver.Receive(TimeSpan.FromSeconds(10));
                        if (data == null)
                        {
                            break;
                        }
                        Console.WriteLine($"Received from partition {partitionId} : " + Encoding.UTF8.GetString(data.GetBytes()));
                    }
                    receiver.Close();
                });
            });

            System.Threading.Thread.Sleep(5000);

            ehClient.Send(new EventData(Encoding.UTF8.GetBytes($"{DateTime.UtcNow}")));

            Task.WaitAll(receiveTask);

            ehClient.Close();
            messagingFactory.Close();
            Console.WriteLine("Send / Receive complete. Press enter to exit.");
            Console.ReadLine();
        }
示例#30
0
        private async Task SendEventsAsync(IEnumerable <EventData> events, long transmissionSequenceNumber, CancellationToken cancellationToken)
        {
            if (events == null)
            {
                return;
            }

            try
            {
                List <MessagingEventData> batch = new List <MessagingEventData>();

                foreach (EventData eventData in events)
                {
                    MessagingEventData messagingEventData = eventData.ToMessagingEventData();
                    batch.Add(messagingEventData);
                }

                if (cancellationToken.IsCancellationRequested)
                {
                    return;
                }

                MessagingFactory factory = this.connectionData.MessagingFactories[transmissionSequenceNumber % ConcurrentConnections];
                EventHubClient   hubClient;
                lock (factory)
                {
                    hubClient = factory.CreateEventHubClient(this.connectionData.EventHubName);
                }

                await hubClient.SendBatchAsync(batch);

                this.ReportListenerHealthy();
            }
            catch (Exception e)
            {
                this.ReportListenerProblem("Diagnostics data upload has failed." + Environment.NewLine + e.ToString());
            }
        }
示例#31
0
        protected void btnReceive_Click(object sender, EventArgs e)
        {
            MessagingFactorySettings messagingFactorySettings = new MessagingFactorySettings
            {
                TokenProvider = TokenProvider.CreateManagedServiceIdentityTokenProvider(ServiceAudience.EventHubsAudience),
                TransportType = TransportType.Amqp
            };

            messagingFactorySettings.AmqpTransportSettings.EnableLinkRedirect = false;

            MessagingFactory messagingFactory = MessagingFactory.Create($"sb://{txtNamespace.Text}.servicebus.windows.net/",
                                                                        messagingFactorySettings);

            EventHubClient        ehClient      = messagingFactory.CreateEventHubClient(txtEventHub.Text);
            EventHubConsumerGroup consumerGroup = ehClient.GetDefaultConsumerGroup();
            int partitions = int.Parse(txtPartitions.Text);

            string[] Offsets = new string[partitions];
            if (!string.IsNullOrEmpty(hiddenStartingOffset.Value))
            {
                Offsets = hiddenStartingOffset.Value.Split(',');
            }
            System.Threading.Tasks.Parallel.ForEach(Enumerable.Range(0, int.Parse(txtPartitions.Text)), partitionId =>
            {
                EventHubReceiver receiver = consumerGroup.CreateReceiver($"{partitionId}", Offsets[partitionId] == null ? "-1" : Offsets[partitionId]);
                EventData data            = receiver.Receive(TimeSpan.FromSeconds(1));
                if (data != null)
                {
                    Offsets[partitionId]  = data.Offset;
                    txtReceivedData.Text += $"PartitionId: {partitionId} Seq#:{data.SequenceNumber} data:{Encoding.UTF8.GetString(data.GetBytes())}{Environment.NewLine}";
                }
                receiver.Close();
            });

            hiddenStartingOffset.Value = string.Join(",", Offsets);
            ehClient.Close();
            messagingFactory.Close();
        }
示例#32
0
        static void SendingRandomMessages()
        {
            MessagingFactory factory = MessagingFactory.CreateFromConnectionString(connectionString);
            EventHubClient   client  = factory.CreateEventHubClient(eventHubName);

            while (true)
            {
                try
                {
                    var message = Guid.NewGuid().ToString();
                    Console.WriteLine("{0} > Sending message: {1}", DateTime.Now, message);
                    client.Send(new EventData(System.Text.Encoding.UTF8.GetBytes(message)));
                }
                catch (Exception exception)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("{0} > Exception: {1}", DateTime.Now, exception.Message);
                    Console.ResetColor();
                }

                Thread.Sleep(200);
            }
        }
        public  Task OpenEventHubAsync(string eventHubConnectionString, string hubName)
        {
            
            return Task.Factory.StartNew(async () => {
                if (string.IsNullOrWhiteSpace(eventHubConnectionString))
                    throw new ArgumentException("invalid event hub connection string");

                if (string.IsNullOrWhiteSpace(hubName))
                    throw new ArgumentException("invalid hubname");
                this.IsOpen = true;

                var builder = new ServiceBusConnectionStringBuilder(eventHubConnectionString) { TransportType = TransportType.Amqp };
                var s = builder.ToString();
                _factory = MessagingFactory.CreateFromConnectionString(builder.ToString());
       
                _client = _factory.CreateEventHubClient(hubName);
                
                var runtimeInfo = await _client.GetRuntimeInformationAsync();

                _partitions.Clear();
                foreach (var p in runtimeInfo.PartitionIds)
                {
                
                    var partition = await _client.GetPartitionRuntimeInformationAsync(p);
                    var count = partition.LastEnqueuedSequenceNumber - partition.BeginSequenceNumber;
                    if (count != 0)
                        count++;
                    this.MessageCount = count;
                    _partitions.Add(new Partition(p, _messages));
                    _foundPartitions.OnNext(partition);
                }

                _foundPartitions.OnCompleted();
                
            });

        }
示例#34
0
        // The Initialize method is not thread-safe. Please only call this on one thread and do so before the pipeline starts sending
        // data to this output
        private void Initialize(EventHubOutputConfiguration configuration)
        {
            Debug.Assert(configuration != null);
            Debug.Assert(this.healthReporter != null);

            if (string.IsNullOrWhiteSpace(configuration.ConnectionString))
            {
                var errorMessage = $"{nameof(EventHubOutput)}: '{nameof(EventHubOutputConfiguration.ConnectionString)}' configuration parameter must be set to a valid connection string";
                healthReporter.ReportProblem(errorMessage, EventFlowContextIdentifiers.Configuration);
                throw new Exception(errorMessage);
            }

            ServiceBusConnectionStringBuilder connStringBuilder = new ServiceBusConnectionStringBuilder(configuration.ConnectionString);

            connStringBuilder.TransportType = TransportType.Amqp;

            this.eventHubName = connStringBuilder.EntityPath ?? configuration.EventHubName;
            if (string.IsNullOrWhiteSpace(this.eventHubName))
            {
                var errorMessage = $"{nameof(EventHubOutput)}: Event Hub name must not be empty. It can be specified in the '{nameof(EventHubOutputConfiguration.ConnectionString)}' or '{nameof(EventHubOutputConfiguration.EventHubName)}' configuration parameter";

                healthReporter.ReportProblem(errorMessage, EventFlowContextIdentifiers.Configuration);
                throw new Exception(errorMessage);
            }

            this.connections = new EventHubConnection[ConcurrentConnections];

            // To create a MessageFactory, the connection string can't contain the EntityPath. So we set it to null here.
            connStringBuilder.EntityPath = null;
            for (uint i = 0; i < this.connections.Length; i++)
            {
                MessagingFactory factory = MessagingFactory.CreateFromConnectionString(connStringBuilder.ToString());
                this.connections[i] = new EventHubConnection();
                this.connections[i].MessagingFactory = factory;
                this.connections[i].HubClient        = factory.CreateEventHubClient(this.eventHubName);
            }
        }
        public async Task<string> OpenAsync(CancellationToken cancellationToken)
        {
            await mOptions.PrepareAsync();

            var useDefaultConsumerGroup = !string.IsNullOrEmpty(mOptions.EventHubConsumerGroupName);


            mMessagingFactory = MessagingFactory.CreateFromConnectionString(mOptions.EventHubConnectionString);
            mEventHubClient = mMessagingFactory.CreateEventHubClient(mOptions.EventHubName);
            mConsumerGroup = useDefaultConsumerGroup ?
                                mEventHubClient.GetConsumerGroup(mOptions.EventHubConsumerGroupName)
                              : mEventHubClient.GetDefaultConsumerGroup();

           


            return string.Concat(mEventHubNamespace, "/",
                                 mOptions.EventHubName, "/",
                                 useDefaultConsumerGroup ? "<default group>" : mOptions.EventHubConsumerGroupName);

        }