Ejemplo n.º 1
0
        static void Main(string[] args)
        {
            string connectionString =
                @"<eventhub connection string without EntityPath>";
            NamespaceManager namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);
            string           eventHubName     = "lazhueventhub";
            EventHubClient   client           = EventHubClient.Create(eventHubName);
            int    i    = 0;
            Random rand = new Random();

            while (true)
            {
                CDRecord r = new CDRecord();
                r.id          = i;
                r.temperature = 20.1;
                r.humidity    = 68.6;
                r.createtime  = DateTime.Now;
                r.msgtype     = "thsensor";
                r.sensorID    = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xa1, 0x01, 0xd1, 0x17 };
                r.typeID      = rand.Next() % 4;

                var       serializedString = JsonConvert.SerializeObject(r);
                EventData data             = new EventData(Encoding.UTF8.GetBytes(serializedString));
                client.Send(data);

                Console.WriteLine("Send " + i + " message");
                System.Threading.Thread.Sleep(500);
                i++;
            }

            /*StreamReader sr = new StreamReader(@"C:\cases\117111317142938\request.json");
             * string json = sr.ReadToEnd();
             * EventData data = new EventData(Encoding.UTF8.GetBytes(json));
             * client.Send(data);*/
        }
        static async Task SendEventsAsync()
        {
            // Create EventHubClient
            EventHubClient client = EventHubClient.Create(eventHubName);

            while (true)
            {
                try
                {
                    // Send messages to Event Hub
                    Console.WriteLine("Sending messages to Event Hub {0}", client.Path);
                    string messageBody = Guid.NewGuid().ToString();

                    // Create the device/temperature metric
                    EventData data = new EventData(Encoding.UTF8.GetBytes(messageBody));

                    // Send the metric to Event Hub
                    await client.SendAsync(data);

                    Console.WriteLine("Sent message {0} ", messageBody);
                }
                catch (Exception exp)
                {
                    Console.WriteLine("Error on send: " + exp.Message);
                }

                Thread.Sleep(TimeSpan.FromSeconds(1));
            }
        }
        public async void SendVehicleAlerts()
        {
            var client = EventHubClient.Create(this.eventHubName);

            try
            {
                while (true)
                {
                    var alert = new SpeedCameraAlert()
                    {
                        DeviceID            = this.deviceID,
                        CameraID            = this.cameraName,
                        Time                = DateTime.UtcNow,
                        SpeedLimit          = this.speedLimitForLocation,
                        VehicleRegistration = getRegistration(),
                        Speed               = getSpeed()
                    };

                    var serializedAlert = JsonConvert.SerializeObject(alert);
                    var data            = new EventData(Encoding.UTF8.GetBytes(serializedAlert));
                    data.Properties.Add("Type", $"Telemetry_{DateTime.Now.ToLongTimeString()}");
                    Trace.TraceInformation($"Sending: {alert.ToString()}");
                    await client.SendAsync(data);

                    await Task.Delay(rnd.Next(10) * 500);
                }
            }
            catch (Exception e)
            {
                Trace.TraceError($"Error sending message: {e.Message}");
            }
            client.CloseAsync().Wait();
        }
Ejemplo n.º 4
0
            public IEventHubClient Create(string connectionString, TimeSpan receiveTimeout)
            {
                EventHubsConnectionStringBuilder csb = new EventHubsConnectionStringBuilder(connectionString);

                csb.OperationTimeout = receiveTimeout;
                return(new EventHubClientWrapper(EventHubClient.Create(csb)));
            }
Ejemplo n.º 5
0
        static void Main(string[] args)
        {
            if (args.Length < 3)
            {
                Usage();
            }

            eventHubName = ConfigurationManager.AppSettings["EventHubName"];
            client       = EventHubClient.Create(eventHubName);
            var engine = new TelcoGenerationEngine(client);

            // Show Usage information
            if (args.Length < 3)
            {
                Usage();
            }

            string           connectionString = engine.GetServiceBusConnectionString();
            NamespaceManager namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);

            partitionCurrent = 0;

            // Assumes you already have the Event Hub created.



            // Generate the data
            engine.GenerateData(args);

            Console.ReadKey();
        }
Ejemplo n.º 6
0
        public async void SendStockAlerts()
        {
            var client = EventHubClient.Create(this.eventHubName);

            try
            {
                while (true)
                {
                    var alert = new StockPriceChangeEvent()
                    {
                        Ticker    = this.ticker,
                        Price     = getPrice(),
                        QuoteTime = getQuoteTime()
                    };

                    var serializedAlert = JsonConvert.SerializeObject(alert);
                    var data            = new EventData(Encoding.UTF8.GetBytes(serializedAlert));
                    data.Properties.Add("Type", $"Telemetry_{DateTime.Now.ToLongTimeString()}");
                    Trace.TraceInformation($"Sending: {alert.ToString()}");
                    await client.SendAsync(data);

                    await Task.Delay(rnd.Next(10) * 500);
                }
            }
            catch (Exception e)
            {
                Trace.TraceError($"Error sending message: {e.Message}");
            }
            client.CloseAsync().Wait();
        }
Ejemplo n.º 7
0
        static void Main(string[] args)
        {
            // Show Usage information
            if (args.Length < 3)
            {
                Usage();
            }

            // Init
            _init();

            // Setup service bus
            string           connectionString = GetServiceBusConnectionString();
            NamespaceManager namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);

            eventHubName     = ConfigurationManager.AppSettings["EventHubName"];
            partitionCurrent = 0;

            // Assumes you already have the Event Hub created.
            client = EventHubClient.Create(eventHubName);


            // Generate the data
            GenerateData(args);

            Console.ReadKey();
        }
Ejemplo n.º 8
0
        private static EventHubSender CreatePartitionedSender()
        {
            // EventHubClient model (uses implicit factory instance, so all links on same connection)
            EventHubClient eventHubClient = EventHubClient.Create("contoso-trucks");

            // return sender for partition '1'
            return(eventHubClient.CreatePartitionedSender("1"));
        }
Ejemplo n.º 9
0
        static void ClientCredentialsScenario()
        {
            ClientCredential clientCredential = new ClientCredential(ClientId, ConfigurationManager.AppSettings["clientSecret"]);
            TokenProvider    tp = TokenProvider.CreateAadTokenProvider(new AuthenticationContext($"https://login.windows.net/{TenantId}"), clientCredential);

            var ehClient = EventHubClient.Create(new Uri($"sb://{EventHubNamespace}/"), EventHubName, tp);

            SendReceiveAsync(ehClient).Wait();
        }
Ejemplo n.º 10
0
        static void ClientAssertionCertScenario()
        {
            X509Certificate2           certificate = GetCertificate();
            ClientAssertionCertificate clientAssertionCertificate = new ClientAssertionCertificate(ClientId, certificate);
            TokenProvider tp = TokenProvider.CreateAadTokenProvider(new AuthenticationContext($"https://login.windows.net/{TenantId}"), clientAssertionCertificate);

            var ehClient = EventHubClient.Create(new Uri($"sb://{EventHubNamespace}/"), EventHubName, tp);

            SendReceiveAsync(ehClient).Wait();
        }
Ejemplo n.º 11
0
        static void UserInteractiveLoginScenario()
        {
            TokenProvider tp = TokenProvider.CreateAadTokenProvider(
                new AuthenticationContext($"https://login.windows.net/{TenantId}"),
                ClientId,
                new Uri("http://eventhubs.microsoft.com"),
                new PlatformParameters(PromptBehavior.Auto),
                UserIdentifier.AnyUser
                );

            var ehClient = EventHubClient.Create(new Uri($"sb://{EventHubNamespace}/"), EventHubName, tp);

            SendReceiveAsync(ehClient).Wait();
        }
Ejemplo n.º 12
0
        public ServiceBus()
        {
            ServiceBusEnvironment.SystemConnectivity.Mode = Microsoft.ServiceBus.ConnectivityMode.Http;

            // Setup service bus
            string           connectionString = GetServiceBusConnectionString();
            NamespaceManager namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);

            eventHubName = ConfigurationManager.AppSettings["EventHubName"];

            registryManager = RegistryManager.CreateFromConnectionString(connectionString);

            client = EventHubClient.Create(eventHubName);
        }
Ejemplo n.º 13
0
        static void Main(string[] args)
        {
            GenConfig config = new GenConfig(args);

            // Setup service bus
            string           connectionString = GetServiceBusConnectionString();
            NamespaceManager namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);

            eventHubName = ConfigurationManager.AppSettings["EventHubName"];
            client       = EventHubClient.Create(eventHubName);

            GenerateData(config);
            Console.ReadKey();
        }
Ejemplo n.º 14
0
        public AppModel()
        {
            Position = ObservableProperty.CreateSettable(new Point());

            var client = EventHubClient.Create("sakapon-event-201508");

            var index = 0;

            Position
            .Select(p => new { index = index++, position = p.ToString() })
            .Select(o => JsonConvert.SerializeObject(o))
            .Do(m => Debug.WriteLine("Sending message. {0}", new[] { m }))
            .Select(m => new EventData(Encoding.UTF8.GetBytes(m)))
            .Subscribe(d => client.SendAsync(d));
        }
Ejemplo n.º 15
0
        public async Task SendEventHubsMessage()
        {
            string hubNamespace = _settings.EventHubNamespace;
            var    endpoint     = new Uri($"sb://{hubNamespace}.servicebus.windows.net/");
            string hubName      = _settings.EventHubName;
            var    client       = EventHubClient.Create(
                endpoint,
                hubName,
                new ManagedIdentityEventHubsTokenProvider(_settings.ManagedIdentityTenantId));

            // You can also do this:
            // var client = EventHubClient.CreateWithManagedServiceIdentity(endpoint, hubName);
            byte[] bytes = Encoding.UTF8.GetBytes($"Test message {Guid.NewGuid()} ({DateTime.UtcNow:HH:mm:ss})");
            await client.SendAsync(new EventData(bytes));
        }
Ejemplo n.º 16
0
        private static EventHubReceiver GetEventHubReceiver(SiteState state)
        {
            // Create the EventHubClient and retrieve the default consumer group
            EventHubClient        eventHubClient        = EventHubClient.Create("contoso-trucks");
            EventHubConsumerGroup defaultConsumberGroup = eventHubClient.GetDefaultConsumerGroup();

            // if state ontains an offset, then use it; otherwise use the default (beginning of stream)
            if (string.IsNullOrEmpty(state.Offset))
            {
                return(defaultConsumberGroup.CreateReceiver("1"));
            }
            else
            {
                return(defaultConsumberGroup.CreateReceiver("1", state.Offset));
            }
        }
 internal EventHubClient CreateEventHubClient()
 {
     // Token provider already provided?
     if (this.tokenProvider == null)
     {
         return(EventHubClient.CreateFromConnectionString(this.eventHubConnectionString));
     }
     else
     {
         return(EventHubClient.Create(
                    this.EndpointAddress,
                    this.EventHubPath,
                    this.tokenProvider,
                    this.OperationTimeout,
                    this.TransportType));
     }
 }
Ejemplo n.º 18
0
        public bool SendEvents(string homeHubId, DateTime dt, string sensorName, string sensorRole, string sensorData)
        {
            // Create EventHubClient
            EventHubClient client = EventHubClient.Create(this.eventHubName);

            bool bEventSent = false;


            try
            {
                List <Task> tasks = new List <Task>();
                // Send messages to Event Hub
                Console.WriteLine("Sending messages to Event Hub {0}", client.Path);


                // Create the device/temperature metric
                MetricEvent info = new MetricEvent()
                {
                    HomeHubId     = homeHubId, SensorName = sensorName, SensorData = sensorData, SensorRole = sensorRole,
                    EntryDateTime = dt
                };
                var       serializedString = JsonConvert.SerializeObject(info);
                EventData data             = new EventData(Encoding.UTF8.GetBytes(serializedString))
                {
                    PartitionKey = info.HomeHubId.ToString()
                };

                // Set user properties if needed
                data.Properties.Add("Type", "Telemetry_" + DateTime.Now.ToLongTimeString());
                OutputMessageInfo(DateTime.Now.ToString() + " SENDING: ", data, info);

                // Send the metric to Event Hub
                tasks.Add(client.SendAsync(data));


                Task.WaitAll(tasks.ToArray());
                bEventSent = true;
            }
            catch (Exception exp)
            {
                Console.WriteLine("Error on send: " + exp.Message);
            }

            client.CloseAsync().Wait();
            return(bEventSent);
        }
Ejemplo n.º 19
0
        public void SendEvents()
        {
            // Create EventHubClient
            EventHubClient client = EventHubClient.Create(this.eventHubName);

            try
            {
                List <Task> tasks = new List <Task>();
                // Send messages to Event Hub
                Console.WriteLine("Sending messages to Event Hub {0}", client.Path);
                Random random = new Random();
                for (int i = 0; i < this.numberOfMessages; ++i)
                {
                    // Create the device/temperature metric
                    MetricEvent info = new MetricEvent()
                    {
                        DeviceId = random.Next(numberOfDevices), Temperature = random.Next(100)
                    };
                    var serializedString = JsonConvert.SerializeObject(info);



                    EventData data = new EventData(Encoding.UTF8.GetBytes(serializedString))
                    {
                        PartitionKey = info.DeviceId.ToString()
                    };

                    // Set user properties if needed
                    data.Properties.Add("Type", "Telemetry_" + DateTime.Now.ToLongTimeString());
                    OutputMessageInfo("SENDING: ", data, info);

                    // Send the metric to Event Hub
                    tasks.Add(client.SendAsync(data));
                }
                ;

                Task.WaitAll(tasks.ToArray());
            }
            catch (Exception exp)
            {
                Console.WriteLine("Error on send: " + exp.Message);
            }

            client.CloseAsync().Wait();
        }
Ejemplo n.º 20
0
        static void Main(string[] args)
        {
            // Show Usage information
            if (args.Length < 3)
            {
                Usage();
            }

            // Setup service bus
            string           connectionString = GetServiceBusConnectionString();
            NamespaceManager namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);

            eventHubName = ConfigurationManager.AppSettings["EventHubName"];
            client       = EventHubClient.Create(eventHubName);

            GenerateData(args);
            Console.ReadKey();
        }
Ejemplo n.º 21
0
        public async Task UseITokenProviderWithSas()
        {
            // Generate SAS token provider.
            var csb           = new EventHubsConnectionStringBuilder(TestUtility.EventHubsConnectionString);
            var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(csb.SasKeyName, csb.SasKey);

            // Create new client with updated connection string.
            var ehClient = EventHubClient.Create(csb.Endpoint, csb.EntityPath, tokenProvider);

            // Send one event
            TestUtility.Log($"Sending one message.");
            var ehSender  = ehClient.CreatePartitionSender("0");
            var eventData = new EventData(Encoding.UTF8.GetBytes("Hello EventHub!"));
            await ehSender.SendAsync(eventData);

            // Receive event.
            PartitionReceiver ehReceiver = null;

            try
            {
                TestUtility.Log($"Receiving one message.");
                ehReceiver = ehClient.CreateReceiver(PartitionReceiver.DefaultConsumerGroupName, "0", EventPosition.FromStart());
                var msg = await ehReceiver.ReceiveAsync(1);

                Assert.True(msg != null, "Failed to receive message.");
            }
            finally
            {
                await ehReceiver?.CloseAsync();
            }

            // Get EH runtime information.
            TestUtility.Log($"Getting Event Hub runtime information.");
            var ehInfo = await ehClient.GetRuntimeInformationAsync();

            Assert.True(ehInfo != null, "Failed to get runtime information.");

            // Get EH partition runtime information.
            TestUtility.Log($"Getting Event Hub partition '0' runtime information.");
            var partitionInfo = await ehClient.GetPartitionRuntimeInformationAsync("0");

            Assert.True(ehInfo != null, "Failed to get runtime partition information.");
        }
Ejemplo n.º 22
0
        public async Task UseITokenProviderWithAad()
        {
            var tenantId     = "";
            var aadAppId     = "";
            var aadAppSecret = "";

            if (string.IsNullOrEmpty(tenantId))
            {
                TestUtility.Log($"Skipping test during scheduled runs.");
                return;
            }

            var authContext   = new AuthenticationContext($"https://login.windows.net/{tenantId}");
            var cc            = new ClientCredential(aadAppId, aadAppSecret);
            var tokenProvider = TokenProvider.CreateAadTokenProvider(authContext, cc);

            // Create new client with updated connection string.
            var csb      = new EventHubsConnectionStringBuilder(TestUtility.EventHubsConnectionString);
            var ehClient = EventHubClient.Create(csb.Endpoint, csb.EntityPath, tokenProvider);

            // Send one event
            TestUtility.Log($"Sending one message.");
            var ehSender  = ehClient.CreatePartitionSender("0");
            var eventData = new EventData(Encoding.UTF8.GetBytes("Hello EventHub!"));
            await ehSender.SendAsync(eventData);

            // Receive event.
            PartitionReceiver ehReceiver = null;

            try
            {
                TestUtility.Log($"Receiving one message.");
                ehReceiver = ehClient.CreateReceiver(PartitionReceiver.DefaultConsumerGroupName, "0", EventPosition.FromStart());
                var msg = await ehReceiver.ReceiveAsync(1);

                Assert.True(msg != null, "Failed to receive message.");
            }
            finally
            {
                await ehReceiver?.CloseAsync();
            }
        }
Ejemplo n.º 23
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("Start receiver...");
            _listenerThread = new Thread(Receiver);
            _listenerThread.Start();

            Console.WriteLine("Start forwarder...");
            var ehConnection = new EventHubsConnectionStringBuilder(_forwarder.EventHub.ConnectionString)
            {
                EntityPath = _forwarder.EventHub.EventHubName
            };
            var ehClient = EventHubClient.Create(ehConnection);

            var events = new List <EventData>(2048);

            while (true)
            {
                while (!_waitHandles.IsEmpty)
                {
                    if (ehClient.IsClosed)
                    {
                        ehClient = EventHubClient.Create(ehConnection);
                    }

                    Console.WriteLine($"Preparing forwarding batch...");

                    events.Clear();
                    while (_waitHandles.TryDequeue(out var eventData))
                    {
                        events.Add(eventData);
                    }

                    if (events.Any())
                    {
                        Console.WriteLine($"Forward {events.Count} event(s)...");
                        await ehClient.SendAsync(events);
                    }
                }

                await Task.Delay(_forwarder.IterationInterval);
            }
        }
Ejemplo n.º 24
0
        static void Produce(CancellationToken cancellationToken)
        {
            var hub = EventHubClient.Create("unaigab2016");

            while (true)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    return;
                }

                var sensor = new Sensor()
                {
                    Value = _next.NextDouble(),
                    Name  = ((DateTime.UtcNow.Second & 1) == 1) ? "Sensor-A" : "Sensor-B"
                };

                hub.SendAsync(new EventData(
                                  UTF8Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(sensor)))).Wait();
            }
        }
        private bool InitializeHubClient(string eventHubname)
        {
            if (_isInitialized)
            {
                return(true);
            }

            string hubname = (string.IsNullOrEmpty(eventHubname)) ? ConfigurationManager.AppSettings["Microsoft.Eventhub.Name"] : eventHubname;

            if (!string.IsNullOrEmpty(hubname))
            {
                // Creates a new instance of the EventHubClient instance, using a connection string from the application configuration settings
                if ((_hubClient = EventHubClient.Create(hubname)) != null)
                {
                    return(_isInitialized = true);
                }
            }

            // Failed condition
            return(false);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Instantiate publishing on this bus by
        /// calling <see cref="CheckPrivateHubExists"/> and <see cref="CheckPublicHubExists"/>
        /// then calling <see cref="AzureBus{TAuthenticationToken}.StartSettingsChecking"/>
        /// </summary>
        protected override void InstantiatePublishing()
        {
#if NET452
            Manager manager = Manager.CreateFromConnectionString(ConnectionString);
#endif
#if NETSTANDARD2_0
            var manager = new Manager(ConnectionString);
#endif
            CheckPrivateHubExists(manager);
            CheckPublicHubExists(manager);

#if NET452
            EventHubPublisher = EventHubClient.CreateFromConnectionString(ConnectionString, PublicEventHubName);
#endif
#if NETSTANDARD2_0
            var connectionStringBuilder = new EventHubsConnectionStringBuilder(ConnectionString)
            {
                EntityPath = PublicEventHubName
            };
            EventHubPublisher = EventHubClient.Create(connectionStringBuilder);
#endif
            StartSettingsChecking();
        }
Ejemplo n.º 27
0
        static void Main(string[] args)
        {
            //Create the event hub
            var manager  = Microsoft.ServiceBus.NamespaceManager.CreateFromConnectionString(ConfigurationManager.AppSettings["Microsoft.ServiceBus.ConnectionString"]);
            var tweethub = manager.CreateEventHubIfNotExists("TweetHubSimple");

            tweetHubClient = EventHubClient.Create(tweethub.Path);

            var oauth = CredentialsCreator_CreateFromRedirectedCallbackURL_SingleStep(ConfigurationManager.AppSettings["twitterkey"], ConfigurationManager.AppSettings["twittersecret"]);

            // Setup your credentials
            TwitterCredentials.SetCredentials(oauth.AccessToken, oauth.AccessTokenSecret, oauth.ConsumerKey, oauth.ConsumerSecret);


            // Access the filtered stream
            var filteredStream = Tweetinvi.Stream.CreateFilteredStream();

            filteredStream.AddTrack("globalazurebootcamp");
            filteredStream.AddTrack("azure");
            filteredStream.AddTrack("microsoft");
            filteredStream.MatchingTweetReceived += (sender, a) => {
                Console.WriteLine(a.Tweet.Text);
                var str = JsonConvert.SerializeObject(new
                {
                    Tweet      = a.Tweet.Text,
                    Lang       = a.Tweet.Language,
                    Created_At = a.Tweet.CreatedAt
                });
                tweetHubClient.Send(new EventData(System.Text.Encoding.UTF8.GetBytes(str)));
            };
            //filteredStream.JsonObjectReceived += (sender, json) =>
            //{
            //    ProcessTweet(json.Json);
            //};
            filteredStream.StartStreamMatchingAllConditions();
        }
 public EventHubReceiver(EventHubsConnectionStringBuilder connectionString)
 {
     _connectionString = connectionString;
     _eventHubClient   = EventHubClient.Create(connectionString);
 }
 public EventHubSender(EventHubsConnectionStringBuilder connectionString)
 {
     _eventHubClient = EventHubClient.Create(connectionString);
 }