Ejemplo n.º 1
0
 public async Task OpenAsync(PartitionContext context)
 {
     if (!WebJobsHelper.RunAsWebJobs)
         Console.WriteLine(string.Format("EventProcessor initialization. Partition: '{0}', Offset: '{1}'",
             context.Lease.PartitionId, context.Lease.Offset));
     partitionContext = context;
     var retries = 3;
     while (retries > 0)
     {
         try
         {
             retries--;
             hubClient = EventHubClient.CreateFromConnectionString(
                 ConfigurationManager.ConnectionStrings["SigfoxDemoAlertSender"].ConnectionString,
                 "alert");
             cacheConnection = await ConnectionMultiplexer.ConnectAsync(ConfigurationManager.ConnectionStrings["SigfoxDemoCache"].ConnectionString);
             cacheDatabase = cacheConnection.GetDatabase();
             sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["SigfoxDemoDatabase"].ConnectionString);
             //sqlConnection.Open();
             //sqlCommand = new SqlCommand("InsertAlert", sqlConnection) { CommandType = CommandType.StoredProcedure };
             //sqlCommand.Parameters.Add(new SqlParameter("@Device", SqlDbType.VarChar));
             retries = 0;
         }
         catch (Exception e)
         {
             Console.Error.WriteLine("Error opening destination Event Hub: " + e.Message);
             if (retries == 0)
                 throw;
         }
     }
     checkpointStopWatch = new Stopwatch();
     checkpointStopWatch.Start();
 }
Ejemplo n.º 2
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();
        }
Ejemplo n.º 3
0
        //------------------------------------------------------------------------------------------------------------------------
        #endregion

        #region Constructor
        //------------------------------------------------------------------------------------------------------------------------
        public EventHubDev(string evhubname, string connectionstring)
        {
            this.eventHubName = evhubname;
            this.connectionName = connectionstring;
            //create eventhub client
            eventHubClient = EventHubClient.CreateFromConnectionString(this.connectionName, this.eventHubName);
        }
        /// <summary>
        /// A sink that puts log events into a provided Azure Event Hub.
        /// </summary>
        /// <param name="loggerConfiguration">The logger configuration.</param>
        /// <param name="eventHubClient">The Event Hub to use to insert the log entries to.</param>
        /// <param name="partitionKey">The partition key used to group log events in the Event Hub.</param>
        /// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param>
        /// <param name="outputTemplate">A message template describing the format used to write to the sink.
        /// the default is "{Timestamp} [{Level}] {Message}{NewLine}{Exception}".</param>
        /// <param name="restrictedToMinimumLevel">The minimum log event level required in order to write an event to the sink.</param>
        /// <param name="writeInBatches">Use a periodic batching sink, as opposed to a synchronous one-at-a-time sink; this alters the partition
        /// key used for the events so is not enabled by default.</param>
        /// <param name="batchPostingLimit">The maximum number of events to post in a single batch.</param>
        /// <param name="period">The time to wait between checking for event batches.</param>
        /// <returns>Logger configuration, allowing configuration to continue.</returns>
        /// <exception cref="ArgumentNullException">A required parameter is null.</exception>
        public static LoggerConfiguration AzureEventHub(
            this LoggerSinkConfiguration loggerConfiguration,
            EventHubClient eventHubClient,
            string partitionKey = null,
            string outputTemplate = DefaultOutputTemplate,
            IFormatProvider formatProvider = null,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            bool writeInBatches = false,
            TimeSpan? period = null,
            int? batchPostingLimit = null
            )
        {
            if (loggerConfiguration == null)
                throw new ArgumentNullException("loggerConfiguration");
            if (eventHubClient == null)
                throw new ArgumentNullException("eventHubClient");
            if (outputTemplate == null)
                throw new ArgumentNullException("outputTemplate");

            var formatter = new MessageTemplateTextFormatter(outputTemplate, formatProvider);

            var sink = writeInBatches ?
                (ILogEventSink) new AzureEventHubBatchingSink(
                    eventHubClient,
                    partitionKey ?? DefaultPartitionKey,
                    formatter,
                    batchPostingLimit ?? DefaultBatchPostingLimit,
                    period ?? DefaultPeriod) :
                new AzureEventHubSink(
                    eventHubClient,
                    partitionKey ?? DefaultPartitionKey,
                    formatter);

            return loggerConfiguration.Sink(sink, restrictedToMinimumLevel);
        }
Ejemplo n.º 5
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();
        }
        public override bool OnStart()
        {
            // Set the maximum number of concurrent connections
            ServicePointManager.DefaultConnectionLimit = 12;

            // For information on handling configuration changes
            // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.

            bool result = base.OnStart();

            Trace.TraceInformation("EventsForwarding OnStart()...\n");

            connectionString = ConfigurationManager.AppSettings["Microsoft.ServiceBus.ConnectionString"];
            eventHubName = ConfigurationManager.AppSettings["Microsoft.ServiceBus.EventHubName"];

            string storageAccountName = ConfigurationManager.AppSettings["AzureStorage.AccountName"];
            string storageAccountKey = ConfigurationManager.AppSettings["AzureStorage.Key"];
            string storageAccountString = string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}",
                storageAccountName, storageAccountKey);

            string iotHubConnectionString = ConfigurationManager.AppSettings["AzureIoTHub.ConnectionString"];
            iotHubServiceClient = ServiceClient.CreateFromConnectionString(iotHubConnectionString);
            eventHubClient = EventHubClient.CreateFromConnectionString(connectionString, eventHubName);

            var defaultConsumerGroup = eventHubClient.GetDefaultConsumerGroup();

            string eventProcessorHostName = "SensorEventProcessor";
            EventProcessorHost eventProcessorHost = new EventProcessorHost(eventProcessorHostName, eventHubName, defaultConsumerGroup.GroupName, connectionString, storageAccountString);
            eventProcessorHost.RegisterEventProcessorAsync<SensorEventProcessor>().Wait();

            Trace.TraceInformation("Receiving events...\n");

            return result;
        }
        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);
        }
Ejemplo n.º 8
0
        //------------------------------------------------------------------------------------------------------------------------
        #endregion

        #region Constructor
        //------------------------------------------------------------------------------------------------------------------------
        public EventHubDirectConsumer(EventHubClient client)
        {
            //create event hub direct consumer
            EventHubConsumerGroup group = client.GetDefaultConsumerGroup();
            var x = client.GetRuntimeInformation().PartitionIds[0];
            eventHubDirectReceiver = group.CreateReceiver(client.GetRuntimeInformation().PartitionIds[0]);
        }
Ejemplo n.º 9
0
 private void SendDeviceEventStream(EventHubClient eventHubClient)
 {
     var allEvents = new List<EventData>();
     for (int i = 0; i < DeviceSendingDetails.NumberOfDevices; i++)
     {
         string deviceName = "device" + i;
         var rand = new Random();
         // set up the modifier to enable 
         float modifier = 1.0F;
         if (DeviceSendingDetails.FailureConditions.Any(device => device.FailedDeviceId == i))
         {
             var deviceDetails = DeviceSendingDetails.FailureConditions.First(device => device.FailedDeviceId == i);
             modifier = modifier += deviceDetails.FailedDeviceGradient;
         }
         var deviceValue = rand.Next((int) ((DeviceSendingDetails.TemperatureMin * modifier)*100),
             (int) ((DeviceSendingDetails.TemperatureMax * modifier)*100));
         var deviceData = new DeviceData()
         {
             deviceid = deviceName,
             temperature = (deviceValue/100F),
             timestamp = DateTime.UtcNow
         };
         var jsonDeviceDetail = JsonConvert.SerializeObject(deviceData);
         var encodedPayload = Encoding.UTF8.GetBytes(jsonDeviceDetail);
         var eventData = new EventData(encodedPayload)
         {
             PartitionKey = "devices"
         };
         allEvents.Add(eventData);
     }
     eventHubClient.SendBatch(allEvents);
 }
Ejemplo n.º 10
0
        public static void Main()
        {
     //       string connectionString =
     //ConfigurationManager.ConnectionStrings["RootManageSharedAccessKey"].ConnectionString;
     //       Action<BrokeredMessage> callback = x =>
     //       {
                
     //       };
     //       var clients = new List<SubscriptionClient>();
     //       for (int i = 0; i < 5; i++)
     //       {
     //           var client = TopicClient.CreateFromConnectionString(connectionString, "signalr_topic_push_" + i);
     //           client.
     //           client.OnMessage(callback);
     //           clients.Add(client);
     //       }
     //       Console.ReadLine();
            //var ctx = GlobalHost.ConnectionManager.GetHubContext<yourhub>();
            //ctx.Clients.Client(connectionId).< your method >

            var cloudStorage = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["DataStorage"].ConnectionString);
            var tableClient = cloudStorage.CreateCloudTableClient();
            _tickEvents = tableClient.GetTableReference("tickevents");
            _tickEvents.CreateIfNotExists();
            var host = new JobHost();
            var cancelToken = new WebJobsShutdownWatcher().Token;
            _eventHubClient = EventHubClient.CreateFromConnectionString(ConfigurationManager.ConnectionStrings["IotHubConnection"].ConnectionString, iotHubD2cEndpoint);
            var d2CPartitions = _eventHubClient.GetRuntimeInformation().PartitionIds;
            Task.WaitAll(d2CPartitions.Select(partition => ListenForEvent(host, partition, cancelToken)).ToArray(), cancelToken);
            host.RunAndBlock();
        }
        public async Task StartAsync(EventHubClient client, CancellationToken token)
        {
            var groups = await _nsm.GetConsumerGroupsAsync(EventHubName);
            groups.ToList()
                .ForEach(g => ConsumerGroups.Add(g.Name));

            var defaultConsumerGroup = ConsumerGroups.First();

            var runtime = await client.GetRuntimeInformationAsync();
            runtime.PartitionIds
                .Select(partitionId =>
                {
                    Func<Task<PartitionDescription>> f = () => _nsm.GetEventHubPartitionAsync(EventHubName, defaultConsumerGroup, partitionId);
                    return new PartitionViewModel(partitionId, client, f);
                })
                .ToList()
                .ForEach(p => Partitions.Add(p));

            foreach (var partition in Partitions)
            {
                partition.WhenEventReceived.Subscribe(x => { _aggregatedEventCount.OnNext(x); });

                _listeners.Add(partition.StartAsync(CancellationToken.None));
            }

            _aggregatedEventCount
                .Buffer(TimeSpan.FromSeconds(5))
                .TimeInterval()
                .Select(x => x.Value.Sum() / x.Interval.TotalSeconds)
                .Subscribe(rate => RatePerSecond = rate);
        }
Ejemplo n.º 12
0
        internal EvalOperation(OnlineTrainerSettingsInternal settings)
        {
            this.telemetry = new TelemetryClient();

            // evaluation pipeline
            this.evalEventHubClient = EventHubClient.CreateFromConnectionString(settings.EvalEventHubConnectionString);

            this.evalBlock = new TransformManyBlock<object, EvalData>(
                (Func<object, IEnumerable<EvalData>>)this.OfflineEvaluate,
                new ExecutionDataflowBlockOptions
                {
                    MaxDegreeOfParallelism = 4,
                    BoundedCapacity = 1024
                });

            this.evalBlock.Completion.ContinueWith(t =>
            {
                this.telemetry.TrackTrace($"Stage 3 - Evaluation pipeline completed: {t.Status}");
                if (t.IsFaulted)
                    this.telemetry.TrackException(t.Exception);
            });

            // batch output together to match EventHub throughput by maintaining maximum latency of 5 seconds
            this.evalBlockDisposable = this.evalBlock.AsObservable()
                .GroupBy(k => k.PolicyName)
                   .Select(g =>
                        g.Window(TimeSpan.FromSeconds(5))
                         .Select(w => w.Buffer(245 * 1024, e => Encoding.UTF8.GetByteCount(e.JSON)))
                         .SelectMany(w => w)
                         .Subscribe(this.UploadEvaluation))
                   .Publish()
                   .Connect();
        }
Ejemplo n.º 13
0
        public void GenerateMessages()
        {
            if (DeviceSendingDetails.RedirectToLocalFile == false)
            {
                var connectionString =
                    String.Format(
                        "Endpoint=sb://{0}.servicebus.windows.net/;SharedAccessKeyName={1};SharedAccessKey={2};TransportType=Amqp",
                        EventHubConnectionDetails.ServiceBusNamespace,
                        EventHubConnectionDetails.SasPolicyName,
                        EventHubConnectionDetails.SasPolicyKey);

                var factory = MessagingFactory.CreateFromConnectionString(connectionString);
                EventHubClient = factory.CreateEventHubClient(EventHubConnectionDetails.EventHubName);
            }

            if (DeviceSendingDetails.RedirectToLocalFile)
                Console.WriteLine("Redirecting messages to file {0}", DeviceSendingDetails.RedirectFileName);

            var startTime = DateTime.UtcNow;
            for (var i = 0; i < DeviceSendingDetails.IterationSeconds; i++)
            {
                SendDeviceEventStream();
                Console.WriteLine("Messages fired onto the eventhub!");
                
                Thread.Sleep(DeviceSendingDetails.MillisecondDelay);
            }

            var duration = DateTime.UtcNow - startTime;
            Console.WriteLine("Total Time (ms) : {0}", duration.TotalMilliseconds);

        }
Ejemplo n.º 14
0
 public Task OpenAsync(PartitionContext context)
 {
     if (!WebJobsHelper.RunAsWebJobs)
         Console.WriteLine(string.Format("EventProcessor initialization. Partition: '{0}', Offset: '{1}'",
             context.Lease.PartitionId, context.Lease.Offset));
     partitionContext = context;
     var retries = 3;
     while (retries > 0)
     {
         try
         {
             retries--;
             hubClient = EventHubClient.CreateFromConnectionString(
                 ConfigurationManager.ConnectionStrings["SigfoxDemoDispatchSender"].ConnectionString,
                 "dispatch");
             retries = 0;
         }
         catch (Exception e)
         {
             Console.Error.WriteLine("Error opening destination Event Hub: " + e.Message);
             if (retries == 0)
                 throw;
         }
     }
     checkpointStopWatch = new Stopwatch();
     checkpointStopWatch.Start();
     return Task.FromResult<object>(null);
 }
Ejemplo n.º 15
0
        //------------------------------------------------------------------------------------------------------------------------
        #endregion

        #region Constructor
        public AzureIOTApplication(string connectionString)
        {
            //create an eventhubclient for receiving messages from the Azure IOT Hub
            eventHubClient = EventHubClient.CreateFromConnectionString(connectionString, "messages/events");
            //create a sericeclient, able to send messages to the Azure IOT Hub Devices
            serviceClient = ServiceClient.CreateFromConnectionString(connectionString);
        }
Ejemplo n.º 16
0
 private async Task Publish(EventHubClient client, QuickBlockTransferSegment segment)
 {
     try
     {
         await client.SendAsync(new EventData(segment.Content)
         {
             PartitionKey = segment.GetKey(),
             Properties =
             {
                 {nameof(segment.Header), segment.Header},
                 {nameof(segment.ReceivedAt), segment.ReceivedAt},
                 {nameof(segment.Filename), segment.Filename},
                 {nameof(segment.TimeStamp), segment.TimeStamp},
                 {nameof(segment.Checksum), segment.Checksum},
                 {nameof(segment.BlockNumber), segment.BlockNumber},
                 {nameof(segment.TotalBlocks), segment.TotalBlocks},
                 {nameof(segment.Version), segment.Version},
                 {nameof(segment.Source), segment.Source}
             }
         });
     }
     catch (Exception ex)
     {
         _log.Error(ex.ToString());
     }
 }
Ejemplo n.º 17
0
 /// <summary>
 /// Creates a new instance which consumes messages from iot hub.
 /// </summary>
 /// <param name="endpointId">Id of the <see cref="DeviceToCloudEndpoint"/> producing the messages.</param>
 /// <param name="iotHubConnectionString">Iot hub connection string.</param>
 public CloudToDeviceEndpoint(string endpointId, string iotHubConnectionString)
 {
     if (String.IsNullOrEmpty(iotHubConnectionString)) throw new ArgumentException($"Argument {nameof(iotHubConnectionString)} must be non empty string.");
     if (String.IsNullOrEmpty(endpointId)) throw new ArgumentException($"Argument {nameof(endpointId)} must be non empty string.");
     _endpointId = endpointId;
     _iotHubConnectionString = iotHubConnectionString;
     _eventHubClient = EventHubClient.CreateFromConnectionString(iotHubConnectionString, _iotHubDeviceToCloudEndpoint);
 }
Ejemplo n.º 18
0
        public EventPublisher(string connectionString, string eventHubName, string partitionKey, ILogger logger)
        {
            var builder = new ServiceBusConnectionStringBuilder(connectionString) { TransportType = TransportType.Amqp };

            _partitionKey = partitionKey;
            _client = EventHubClient.CreateFromConnectionString(builder.ToString(), eventHubName);
            _logger = logger;
        }
Ejemplo n.º 19
0
        protected void StartEH_Click(object sender, EventArgs e)
        {
            if (SendButton.Text.StartsWith("Start"))
            {
                Global.ifStart = true;
                SendButton.Text = "Stop Event Hub";

                //set Event Hub Client
                MessagingFactory factory = MessagingFactory.CreateFromConnectionString(Global.EventHubPars.ConnectionString + ";TransportType=Amqp");
                client = factory.CreateEventHubClient(Global.EventHubPars.EHname);

                //initialise sensors
                sensors = new List<ConnectSensor> {
                    new ConnectSensor("5eb6aaff-02de-40e9-a5e6-547f4b456360", sensortype1.Value, sensorunit1.Value),
                    new ConnectSensor("9e511c82-57a6-4608-ab39-b0226d2112ea", sensortype2.Value, sensorunit2.Value),
                    new ConnectSensor("5a15b803-cbc5-4ae6-a0e6-5ca4935469cc", sensortype3.Value, sensorunit3.Value)
                };

                SetSensorAttributes();

                //set min/max ranges
                min = new int[] {
                    Convert.ToInt32(minrange1.Value),
                    Convert.ToInt32(minrange2.Value),
                    Convert.ToInt32(minrange3.Value)
                };

                max = new int[]
                {
                    Convert.ToInt32(maxrange1.Value),
                    Convert.ToInt32(maxrange2.Value),
                    Convert.ToInt32(maxrange3.Value)
                };

                //initialise random int generator
                rand = new Random();

                //set Timer using the user-defined value
                double seconds = Convert.ToDouble(datafreq.Value) * 1000;
                Global.EventHubTimer = new System.Timers.Timer();
                SetTimer(Global.EventHubTimer, seconds);
            }
            else if (SendButton.Text.StartsWith("Stop"))
            {
                SendButton.Text = "Start Event Hub";

                try
                {
                    Global.EventHubTimer.Enabled = false;
                    Global.EventHubTimer.Close();
                }
                catch (NullReferenceException nullRef)
                {
                    System.Diagnostics.Debug.WriteLine(nullRef.Message);
                }

            }
        }
Ejemplo n.º 20
0
 // Please set the following connection strings in app.config for this WebJob to run:
 // AzureWebJobsDashboard and AzureWebJobsStorage
 static void Main()
 {
     _host = new JobHost();
     var connectionString = ConfigurationManager.ConnectionStrings["IoTHub"].ConnectionString;
     _eventHubClient = EventHubClient.CreateFromConnectionString(connectionString, "messages/events");
     _serviceClient = ServiceClient.CreateFromConnectionString(connectionString);
     Task.WaitAll(_eventHubClient.GetRuntimeInformation().PartitionIds.Select(Listen).ToArray());
     _host.RunAndBlock();
 }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="client">Event Hub Client</param>
        public HubClient(EventHubClient client)
        {
            if (null == client)
            {
                throw new ArgumentNullException("client");
            }

            this.client = client;
        }
Ejemplo n.º 22
0
        public EventSender(
            MessagingFactory messagingFactory,
            SimulatorConfiguration config,
            Func<object, byte[]> serializer)
        {
            this._serializer = serializer;

            this._eventHubClient = messagingFactory.CreateEventHubClient(config.EventHubPath);
        }
Ejemplo n.º 23
0
        static void Main(string[] args)
        {
            string eventHubConnectionString = ConfigurationManager.AppSettings["eventHubReceiveRuleConnectionString"];
            string eventHubName = ConfigurationManager.AppSettings["eventHubName"];

            _client = EventHubClient.CreateFromConnectionString(eventHubConnectionString, eventHubName);

            MonitorEventHub().Wait();
        }
 /// <summary>
 /// Add an existing client for sending messages to an event hub.  Infer the eventHub name from client.path
 /// </summary>
 /// <param name="client"></param>
 public void AddEventHubClient(EventHubClient client)
 {
     if (client == null)
     {
         throw new ArgumentNullException("client");
     }
     string eventHubName = client.Path;
     AddEventHubClient(eventHubName, client);
 }
 /// <summary>
 /// Construct a sink that saves log events to the specified EventHubClient.
 /// </summary>
 /// <param name="eventHubClient">The EventHubClient to use in this sink.</param>
 /// <param name="partitionKey">PartitionKey to group events by within the Event Hub.</param>
 /// <param name="formatter">Provides formatting for outputting log data</param>
 public AzureEventHubSink(
     EventHubClient eventHubClient,
     string partitionKey,
     ITextFormatter formatter)
 {
     _eventHubClient = eventHubClient;
     _partitionKey = partitionKey;
     _formatter = formatter;
 }
Ejemplo n.º 26
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);
        }
Ejemplo n.º 27
0
 /// <summary>
 /// Creates the event sender action block.
 /// </summary>
 /// <param name="hubClient">The hub client.</param>
 /// <param name="options">The options.</param>
 /// <returns>ActionBlock&lt;System.Byte[]&gt;.</returns>
 public static ActionBlock<byte[]> Create(EventHubClient hubClient, ExecutionDataflowBlockOptions options)
 {
     return new ActionBlock<byte[]>(data =>
     {
         //var index = Array.IndexOf(data, (byte)'>');
         //if (index < 0) return Task.FromResult(0);
         //var key = Encoding.UTF8.GetString(data, 0, index);
         var eventData = new EventData(data);
         return hubClient.SendAsync(eventData);
     }, options);
 }
Ejemplo n.º 28
0
        protected void Application_Start( object sender, EventArgs e )
        {
            ThreadPool.QueueUserWorkItem( _ =>
            {
                eventHubClient = EventHubClient.CreateFromConnectionString( connectionString, iotHubD2cEndpoint );

                var d2cPartitions = eventHubClient.GetRuntimeInformation( ).PartitionIds;

                foreach ( string partition in d2cPartitions )
                    ReceiveMessagesFromDeviceAsync( partition );
            } );
        }
 public async void ProcessEvents()
 {
     eventHubName = "azureguidanceevnthub";
     connectionString = GetServiceBusConnectionString();
     NamespaceManager namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);
     eventHubClient = EventHubClient.CreateFromConnectionString(connectionString, eventHubName);
     defaultConsumerGroup = eventHubClient.GetDefaultConsumerGroup();
     string blobConnectionString = ConfigurationManager.AppSettings["AzureStorageConnectionString"]; // Required for checkpoint/state
     eventProcessorHost = new EventProcessorHost("AzureGuidanceReceiver", eventHubClient.Path, defaultConsumerGroup.GroupName, connectionString, blobConnectionString);
     await eventProcessorHost.RegisterEventProcessorAsync<SimpleEventProcessor>();
                 
 }
        /// <summary>
        /// Add an existing client for sending messages to an event hub.  Infer the eventHub name from client.path
        /// </summary>
        /// <param name="eventHubName">name of the event hub</param>
        /// <param name="client"></param>
        public void AddEventHubClient(string eventHubName, EventHubClient client)
        {
            if (eventHubName == null)
            {
                throw new ArgumentNullException("eventHubName");
            }
            if (client == null)
            {
                throw new ArgumentNullException("client");
            }

            _senders[eventHubName] = client;
        }