コード例 #1
0
ファイル: Program.cs プロジェクト: y10e/EventHubsClient
        static async Task Main()
        {
            DisplayAbstract();

            //Load configration from ./receiver.config.json
            Config config = new Config();

            config.ReadConfigFile();

            // Create a blob container client that the event processor will use
            BlobContainerClient storageClient = new BlobContainerClient(config.blobStorageConnectionString, config.blobContainerName);

            storageClient.CreateIfNotExists();

            // Create an event processor client to process events in the event hub
            EventProcessorClient processor = new EventProcessorClient(storageClient, config.consumergroup, config.eventHubConnectionString, config.eventHubName);

            // Register handlers for processing events and handling errors
            processor.ProcessEventAsync += ProcessEventHandler;
            processor.ProcessErrorAsync += ProcessErrorHandler;

            // Start the processing
            Console.WriteLine("Starting to receive messages from Eventhub. Press any key to stop this application.");
            Console.WriteLine("");

            await processor.StartProcessingAsync();

            // Wait for 10 seconds for the events to be processed
            //await Task.Delay(TimeSpan.FromSeconds(60));
            Console.ReadLine();

            // Stop the processing
            Console.WriteLine("Stopping. please wait a minute.");
            await processor.StopProcessingAsync();
        }
        protected override async Task ExecuteAsync(CancellationToken cancellationToken)
        {
            _eventProcessorClient.ProcessEventAsync += ProcessEventAsync;
            _eventProcessorClient.ProcessErrorAsync += ProcessErrorAsync;

            await _eventProcessorClient.StartProcessingAsync(cancellationToken);

            try
            {
                await Task.Delay(Timeout.Infinite, cancellationToken);
            }
            catch (TaskCanceledException)
            {
            }

            try
            {
                await _eventProcessorClient.StopProcessingAsync();
            }
            finally
            {
                _eventProcessorClient.ProcessEventAsync -= ProcessEventAsync;
                _eventProcessorClient.ProcessErrorAsync -= ProcessErrorAsync;
            }
        }
コード例 #3
0
        static async Task MainAsync(string[] args)
        {
            BlobContainerClient  storageClient = new BlobContainerClient(storageConnectionString, storageContainerName);
            EventProcessorClient processor     = new EventProcessorClient(storageClient, EventHubConsumerClient.DefaultConsumerGroupName, connectionString);

            processor.ProcessEventAsync += Processor_ProcessEventAsync;
            processor.ProcessErrorAsync += Processor_ProcessErrorAsync;

            try
            {
                Console.WriteLine("Starting to listen for 2 minutes.");
                await processor.StartProcessingAsync();

                Console.WriteLine("Started to listen for 2 minutes.");

                await Task.Delay(TimeSpan.FromMinutes(2));

                Console.WriteLine("Stopping the process");
                await processor.StopProcessingAsync();

                Console.WriteLine("Processing stopped");
            }
            finally
            {
                processor.ProcessEventAsync -= Processor_ProcessEventAsync;
                processor.ProcessErrorAsync -= Processor_ProcessErrorAsync;
            }
        }
コード例 #4
0
        public async Task Start()
        {
            _processor.ProcessEventAsync += Handle;
            _processor.ProcessErrorAsync += Handle;

            await _processor.StartProcessingAsync();
        }
コード例 #5
0
        public async Task ProcessUntilCanceled()
        {
            await using var eventHubScope = await EventHubScope.CreateAsync(2);

            await using var storageScope = await StorageScope.CreateAsync();

            #region Snippet:EventHubs_Processor_ReadMe_ProcessUntilCanceled

            var cancellationSource = new CancellationTokenSource();
            cancellationSource.CancelAfter(TimeSpan.FromSeconds(45));

            var storageConnectionString = "<< CONNECTION STRING FOR THE STORAGE ACCOUNT >>";
            var blobContainerName       = "<< NAME OF THE BLOB CONTAINER >>";
            /*@@*/
            /*@@*/ storageConnectionString = StorageTestEnvironment.Instance.StorageConnectionString;
            /*@@*/ blobContainerName       = storageScope.ContainerName;

            var eventHubsConnectionString = "<< CONNECTION STRING FOR THE EVENT HUBS NAMESPACE >>";
            var eventHubName  = "<< NAME OF THE EVENT HUB >>";
            var consumerGroup = "<< NAME OF THE EVENT HUB CONSUMER GROUP >>";
            /*@@*/
            /*@@*/ eventHubsConnectionString = EventHubsTestEnvironment.Instance.EventHubsConnectionString;
            /*@@*/ eventHubName  = eventHubScope.EventHubName;
            /*@@*/ consumerGroup = eventHubScope.ConsumerGroups.First();

            Task processEventHandler(ProcessEventArgs eventArgs) => Task.CompletedTask;
            Task processErrorHandler(ProcessErrorEventArgs eventArgs) => Task.CompletedTask;

            var storageClient = new BlobContainerClient(storageConnectionString, blobContainerName);
            var processor     = new EventProcessorClient(storageClient, consumerGroup, eventHubsConnectionString, eventHubName);

            processor.ProcessEventAsync += processEventHandler;
            processor.ProcessErrorAsync += processErrorHandler;

            await processor.StartProcessingAsync();

            try
            {
                // The processor performs its work in the background; block until cancellation
                // to allow processing to take place.
                await Task.Delay(Timeout.Infinite, cancellationSource.Token);
            }
            catch (TaskCanceledException)
            {
                // This is expected when the delay is canceled.
            }

            try
            {
                await processor.StopProcessingAsync();
            }
            finally
            {
                // To prevent leaks, the handlers should be removed when processing is complete.
                processor.ProcessEventAsync -= processEventHandler;
                processor.ProcessErrorAsync -= processErrorHandler;
            }

            #endregion
        }
コード例 #6
0
        static async Task Main()
        {
            // Read from the default consumer group: $Default
            string consumerGroup = EventHubConsumerClient.DefaultConsumerGroupName;

            // Create a blob container client that the event processor will use
            BlobContainerClient storageClient = new BlobContainerClient(blobStorageConnectionString, blobContainerName);

            var options = new EventProcessorClientOptions();

            options.ConnectionOptions.TransportType = EventHubsTransportType.AmqpWebSockets;

            // Create an event processor client to process events in the event hub
            EventProcessorClient processor = new EventProcessorClient(storageClient, consumerGroup, ehubNamespaceConnectionString, eventHubName, options);

            // Register handlers for processing events and handling errors
            processor.ProcessEventAsync += ProcessEventHandler;
            processor.ProcessErrorAsync += ProcessErrorHandler;

            // Start the processing
            await processor.StartProcessingAsync();

            // Wait for 10 seconds for the events to be processed
            await Task.Delay(TimeSpan.FromSeconds(10));

            // Stop the processing
            await processor.StopProcessingAsync();
        }
コード例 #7
0
        static async Task Main(string[] args)
        {
            // Read from the default consumer group: $Default
            string consumerGroup = EventHubConsumerClient.DefaultConsumerGroupName;

            // Create a blob container client that the event processor will use
            BlobContainerClient storageClient = new BlobContainerClient(blobStorageConnectionString, blobContainerName);

            // Create an event processor client to process events in the event hub
            EventProcessorClient processorClinet = new EventProcessorClient(storageClient, consumerGroup, ehubNamespaceConnectionString, eventHubName);

            // Register handlers for processing events and handling errors
            processorClinet.ProcessEventAsync += ProcessEventHandler;
            processorClinet.ProcessErrorAsync += ProcessErrorHandler;

            // Start processing
            await processorClinet.StartProcessingAsync();

            // Processing time
            DateTime finishProcessing = DateTime.Now.AddMinutes(10);

            while (DateTime.Now < finishProcessing)
            {
                // Wait for 10 seconds for the events to be processed
                await Task.Delay(TimeSpan.FromSeconds(10));
            }

            // Stop processing
            await processorClinet.StopProcessingAsync();
        }
コード例 #8
0
        static async Task Main()
        {
            Console.WriteLine("Receving the events from event hub...");

            // Read the default consumer group
            string consumerGroup = EventHubConsumerClient.DefaultConsumerGroupName;

            //Create blob container client that event will use
            BlobContainerClient storageClient = new BlobContainerClient(storageAccountConnectionString, containerName);

            //Create event processor client to process events in event hub

            while (true)
            {
                EventProcessorClient processor = new EventProcessorClient(storageClient, consumerGroup, eventHubsNamespaceConnetionString, eventHubName);

                processor.ProcessEventAsync += ProcessEventHandler;
                processor.ProcessErrorAsync += ProcessErrorHandler;

                // Start the processing

                await processor.StartProcessingAsync();

                // Wait for 10 seconds for the events to be processed
                await Task.Delay(TimeSpan.FromSeconds(10));

                await processor.StopProcessingAsync();
            }
        }
コード例 #9
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("Event Hubs Receiver");
            // Read from the default consumer group: $Default
            string consumerGroup = EventHubConsumerClient.DefaultConsumerGroupName;

            // Create a blob container client that the event processor will use
            BlobContainerClient storageClient = new BlobContainerClient(BlobStorageConnectionString, BlobContainerName);

            // Create an event processor client to process events in the event hub
            EventProcessorClient processor = new EventProcessorClient(storageClient, consumerGroup, EhubNamespaceConnectionString, EventHubName);

            // Register handlers for processing events and handling errors
            processor.ProcessEventAsync += Handlers.ProcessorHandlers.ProcessEventHandler;
            processor.ProcessErrorAsync += Handlers.ProcessorHandlers.ProcessErrorHandler;

            // Start the processing
            await processor.StartProcessingAsync();

            // Wait for 10 seconds for the events to be processed
            await Task.Delay(TimeSpan.FromSeconds(10));

            // Stop the processing
            await processor.StopProcessingAsync();

            Console.WriteLine("Event Received");
        }
コード例 #10
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            var storageConnectionString = Configuration["Storage:ConnectionString"];
            var storageContainer        = Configuration["Storage:Container"];

            var storageClient = new BlobContainerClient(storageConnectionString, storageContainer);

            var eventHubConnectionString  = Configuration["EventHubs:ConnectionString"];
            var eventHubName              = Configuration["EventHubs:EventHub"];
            var eventHubConsumerGroupName = EventHubConsumerClient.DefaultConsumerGroupName; // Configuration["EventHubs:ConsumerGroup"];

            var processor = new EventProcessorClient(storageClient, eventHubConsumerGroupName, eventHubConnectionString, eventHubName);

            processor.ProcessEventAsync += ProcessEventHandler;
            processor.ProcessErrorAsync += ProcessErrorHandler;

            EventsProcessed = 0;

            await processor.StartProcessingAsync();

            try
            {
                while (!stoppingToken.IsCancellationRequested)
                {
                    await Task.Delay(1000);
                }

                await processor.StopProcessingAsync();
            }
            finally
            {
                processor.ProcessEventAsync -= ProcessEventHandler;
                processor.ProcessErrorAsync -= ProcessErrorHandler;
            }
        }
コード例 #11
0
ファイル: Program.cs プロジェクト: caiquedias/EventHubApp
        static async Task Main()
        {
            try
            {
                // Read from the default consumer group: $Default
                string consumerGroup = EventHubConsumerClient.DefaultConsumerGroupName;

                // Create a blob container client that the event processor will use
                BlobContainerClient storageClient = new BlobContainerClient(blobStorageConnectionString, blobContainerName);

                // Create an event processor client to process events in the event hub
                EventProcessorClient processor = new EventProcessorClient(storageClient, consumerGroup, ehubNamespaceConnectionString, eventHubName);


                // Register handlers for processing events and handling errors
                processor.ProcessEventAsync += ProcessEventHandler;
                processor.ProcessErrorAsync += ProcessErrorHandler;

                // Start the processing
                await processor.StartProcessingAsync();

                // Wait for 10 seconds for the events to be processed
                await Task.Delay(TimeSpan.FromMinutes(3));

                // Stop the processing
                await processor.StopProcessingAsync();
            }
            catch (Exception e)
            {
                throw e;
            }
        }
コード例 #12
0
        /// <summary>
        /// Start processing of events. If the method was called previously, then it will only
        /// re-enable processing.
        /// </summary>
        public async Task StartProcessingAsync(CancellationToken ct)
        {
            if (_client == null)
            {
                throw new InvalidOperationException("EventProcessorWrapper has not been initialized.");
            }

            // If processing is active for all partitions then we only need to enable message propagation.
            await _lockInitializedPartitions.WaitAsync(ct).ConfigureAwait(false);

            try {
                if (_initializedPartitions.Count(kvp => kvp.Value) == _initializedPartitions.Count)
                {
                    _logger.LogInformation("Enabling monitoring of events...");
                    _monitoringEnabled = true;
                    return;
                }
            }
            finally {
                _lockInitializedPartitions.Release();
            }

            if (!_client.IsRunning)
            {
                _logger.LogInformation("Starting monitoring of events...");
                await _client.StartProcessingAsync(ct).ConfigureAwait(false);
            }

            await WaitForPartitionInitialization(ct).ConfigureAwait(false);

            _monitoringEnabled = true;
        }
コード例 #13
0
        public override async Task RunAsync(CancellationToken ct)
        {
            // Reset previous checkpoints corresponding to an older source event hub (i.e. applicable if the source event hub changes)
            await CheckpointClient.ResetCheckpointsAsync(ct);

            EventProcessorClient.ProcessEventAsync          += ProcessEventHandler;
            EventProcessorClient.ProcessErrorAsync          += ProcessErrorHandler;
            EventProcessorClient.PartitionInitializingAsync += ProcessInitializingHandler;

            try
            {
                Console.WriteLine($"Starting event hub processor at {DateTime.UtcNow}");
                await EventProcessorClient.StartProcessingAsync(ct);

                // Wait indefinitely until cancellation is requested
                ct.WaitHandle.WaitOne();

                await EventProcessorClient.StopProcessingAsync();
            }
            finally
            {
                EventProcessorClient.ProcessEventAsync          -= ProcessEventHandler;
                EventProcessorClient.ProcessErrorAsync          -= ProcessErrorHandler;
                EventProcessorClient.PartitionInitializingAsync -= ProcessInitializingHandler;
            }
        }
コード例 #14
0
        static async Task Main()
        {
            string eventHubConnectionString    = ConfigurationManager.AppSettings["EventHubConnectionString"];
            string eventHubName                = ConfigurationManager.AppSettings["EventHubName"];
            string blobContainerName           = ConfigurationManager.AppSettings["BlobContainerName"];
            string blobStorageConnectionString = ConfigurationManager.AppSettings["BlockStorageConnectionString"];

            // Read from the default consumer group: $Default
            string consumerGroup = EventHubConsumerClient.DefaultConsumerGroupName;

            // Create a blob container client that the event processor will use
            BlobContainerClient storageClient = new BlobContainerClient(blobStorageConnectionString, blobContainerName);

            // Create an event processor client to process events in the event hub
            EventProcessorClient processor = new EventProcessorClient(storageClient, consumerGroup, eventHubConnectionString, eventHubName);

            // Register handlers for processing events and handling errors
            processor.ProcessEventAsync += ProcessEventHandler;
            processor.ProcessErrorAsync += ProcessErrorHandler;

            // Start the processing
            await processor.StartProcessingAsync();

            // Wait for 10 seconds for the events to be processed
            await Task.Delay(TimeSpan.FromSeconds(60));

            // Stop the processing
            await processor.StopProcessingAsync();
        }
コード例 #15
0
        // This approach uses an EventPRocessorClient to maintain state of events read and to process new events.
        // To read more on this, see: https://docs.microsoft.com/en-us/dotnet/api/overview/azure/messaging.eventhubs.processor-readme
        public async static Task <string> processEvents(string ehConnectionString, string blobConnectionString)
        {
            string ehName            = "telemetryhub";
            string blobContainerName = "sample-container";
            // For now, read as the default consumer group: $Default
            // Change this to match certain consumer types/permissions you establish
            // in the EventHub properties.
            string consumerGroup = EventHubConsumerClient.DefaultConsumerGroupName;


            // Create a blob container client that the event processor will use to keep track of what has been
            // historically read or processed already and what events are new.
            BlobContainerClient storageClient = new BlobContainerClient(blobConnectionString, blobContainerName);

            // Create an event processor client to process events in the event hub
            EventProcessorClient processor = new EventProcessorClient(storageClient, consumerGroup, ehConnectionString, ehName);

            // Register handlers for processing events and handling errors (see static Task definitions later in this class)
            processor.ProcessEventAsync += ProcessEventHandler;
            processor.ProcessErrorAsync += ProcessErrorHandler;

            // By its nature, this approach runs continuously to process events as they're added to the queue
            // Therefore, for this sample code, we will start it and stop it after 15 seconds just to see how
            // it works.
            //
            // In the real world, you will likely have a dedicated processor class/function running
            // in perpetuity so that new events can be processed as they're recieved.
            await processor.StartProcessingAsync();

            await Task.Delay(TimeSpan.FromSeconds(15));

            await processor.StopProcessingAsync();

            return("Complete");
        }
コード例 #16
0
        private async Task Process(CancellationToken cancellationToken)
        {
            var processor = new EventProcessorClient(BlobContainerClient, EventHubConsumerClient.DefaultConsumerGroupName,
                                                     EventHubsConnectionString, EventHubName);

            processor.PartitionInitializingAsync += PartitionInitializingHandler;
            processor.ProcessEventAsync          += ProcessEventHandler;
            processor.ProcessErrorAsync          += ProcessErrorHandler;

            try
            {
                Console.WriteLine("await processor.StartProcessingAsync(cancellationToken)");
                await processor.StartProcessingAsync(cancellationToken);

                Console.WriteLine("await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken)");
                await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken);
            }
            catch (OperationCanceledException)
            {
            }
            finally
            {
                Console.WriteLine("await processor.StopProcessingAsync();");

                // TODO: Set timeout and log exceptions if cannot be cancelled
                await processor.StopProcessingAsync();
            }

            processor.PartitionInitializingAsync -= PartitionInitializingHandler;
            processor.ProcessEventAsync          -= ProcessEventHandler;
            processor.ProcessErrorAsync          -= ProcessErrorHandler;
        }
コード例 #17
0
ファイル: Program.cs プロジェクト: pigullino1975/lil-az-204
        static async Task Main(string[] args)
        {
            var eventHubConnectionString    = "Endpoint=sb://cursoaz204.servicebus.windows.net/;SharedAccessKeyName=receive;SharedAccessKey=EYXBssyaDJtp6sktCY+GAO2DcCiJhTymcSwPN58ByAc=;EntityPath=curso-az204";
            var eventHubName                = "curso-az204";
            var blobStorageConnectionString = "DefaultEndpointsProtocol=https;AccountName=cursoaz204storageaccount;AccountKey=/4aRjlAKzLAEYIHGVBYPc2k5CrrvAdCw6Q8d+CyePg8CrG3NXVs0MRkb35TGpPeagpC17431ceOklB97W1Lp1A==;EndpointSuffix=core.windows.net";
            var blobStorageContainerName    = "eventhub-checkpoints";

            var blobContainerClient  = new BlobContainerClient(blobStorageConnectionString, blobStorageContainerName);
            var eventProcessorClient = new EventProcessorClient(blobContainerClient,
                                                                EventHubConsumerClient.DefaultConsumerGroupName,
                                                                eventHubConnectionString, eventHubName);

            eventProcessorClient.ProcessEventAsync += async(a) => {
                Console.WriteLine("Recibido: {0}", Encoding.UTF8.GetString(a.Data.Body.ToArray()));
                await a.UpdateCheckpointAsync(a.CancellationToken);
            };
            eventProcessorClient.ProcessErrorAsync += (a) => {
                Console.WriteLine(a.Exception.Message);
                return(Task.CompletedTask);
            };

            await eventProcessorClient.StartProcessingAsync();

            Console.ReadLine();
            Console.WriteLine("Fin");
            await eventProcessorClient.StopProcessingAsync();
        }
コード例 #18
0
        public async void Listen(Action <string> eventHandler, Action <string> errorHandler)
        {
            _eventHandler = eventHandler;
            _errorHandler = errorHandler;

            // Read from the default consumer group: $Default
            string consumerGroup = EventHubConsumerClient.DefaultConsumerGroupName;

            // Create a blob container client that the event processor will use
            BlobContainerClient storageClient = new BlobContainerClient("DefaultEndpointsProtocol=https;AccountName=testblobstorage2021;AccountKey=hN77k/JHnRt+lGysIHJHuP2U9dvbIrYkPuwWrBN0O7ouj6mbQ47syeBxzmjvnPNugzVCXVancO8mVMXL8E0G8Q==;EndpointSuffix=core.windows.net", "blobcontainer");

            // Create an event processor client to process events in the event hub
            EventProcessorClient processor = new EventProcessorClient(storageClient, consumerGroup, "Endpoint=sb://testeventhub2021.servicebus.windows.net/;SharedAccessKeyName=eventhub;SharedAccessKey=dpDp+H+RKbIkqsLhzYmqlCSzJY9SI/WNm/e3vFk+1Ys=;EntityPath=eventhubdemo", "eventhubdemo");

            // Register handlers for processing events and handling errors
            processor.ProcessEventAsync += ProcessEventHandler;
            processor.ProcessErrorAsync += ProcessErrorHandler;

            // Start the processing
            await processor.StartProcessingAsync();

            // Wait for 10 seconds for the events to be processed
            await Task.Delay(Timeout.InfiniteTimeSpan);

            // Stop the processing
            await processor.StopProcessingAsync();
        }
コード例 #19
0
        static async Task Main()
        {
            // Read all environment variables
            // Event Hub processor needs its own blob container (to store checkpoints, etc.)
            string ehubNamespaceConnStr = Environment.GetEnvironmentVariable("EHUB_NS_CONNSTR");
            string eventProcBlobConnStr = Environment.GetEnvironmentVariable("EHUB_BLOB_CONNSTR");
            string eHub = Environment.GetEnvironmentVariable("EHUB");
            string eventProcContainer = Environment.GetEnvironmentVariable("EHUB_CONTAINER");

            // Read from the default consumer group: $Default
            string consumerGroup = EventHubConsumerClient.DefaultConsumerGroupName;

            // Create a blob container client that the event processor will use
            BlobContainerClient eventProcStorageClient = new BlobContainerClient(eventProcBlobConnStr, eventProcContainer);

            // Create an event processor client to process events in the event hub
            EventProcessorClient processor = new EventProcessorClient(eventProcStorageClient, consumerGroup, ehubNamespaceConnStr, eHub);

            // Register handlers for processing events and handling errors
            processor.ProcessEventAsync += ProcessEventHandler;
            processor.ProcessErrorAsync += ProcessErrorHandler;

            // Start the processing
            await processor.StartProcessingAsync();

            // Wait for 10 seconds for the events to be processed
            await Task.Delay(TimeSpan.FromSeconds(1000));

            // Stop the processing
            await processor.StopProcessingAsync();
        }
コード例 #20
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            /* create the blob */
            await _storageClient.CreateIfNotExistsAsync();

            /* Start the processing */
            await _processor.StartProcessingAsync();
        }
コード例 #21
0
 public async Task StartReadAsync(Func <ProcessEventArgs, Task> onMessage, Func <ProcessErrorEventArgs, Task> onError, CancellationToken cancellationToken = default)
 {
     OnMessage = onMessage;
     OnError   = onError;
     ClientReader.ProcessEventAsync += OnMessage;
     ClientReader.ProcessErrorAsync += OnError;
     await Task.WhenAll(BlobContainerClient.CreateIfNotExistsAsync(),
                        ClientReader.StartProcessingAsync(cancellationToken)).NoContext();
 }
コード例 #22
0
        /// <summary>
        ///   Performs the tasks needed to initialize and set up the environment for the test scenario.
        ///   This setup will take place once for each instance, running after the global setup has
        ///   completed.
        /// </summary>
        ///
        public override async Task SetupAsync()
        {
            await base.SetupAsync();

            EventProcessorClient.ProcessEventAsync += ProcessEventAsync;
            EventProcessorClient.ProcessErrorAsync += ProcessErrorAsync;

            await EventProcessorClient.StartProcessingAsync();
        }
コード例 #23
0
        public override async Task Bind()
        {
            // Register handlers for processing events and handling errors
            EventProcessorClient.ProcessEventAsync += async(args) =>
            {
                Console.WriteLine("ProcessEventAsync");

                if (args.CancellationToken.IsCancellationRequested)
                {
                    return;
                }

                try
                {
                    await _container.CreateItemAsync(
                        await Run(
                            _context,
                            JsonSerializer.Deserialize <TInput>(Encoding.UTF8.GetString(args.Data.Body.ToArray())), args.CancellationToken));

                    await args.UpdateCheckpointAsync(args.CancellationToken);

                    _context.PostHealth(FunHealth.Normal());
                }
                catch (OutOfMemoryException ex)
                {
                    // TODO: Fix Logging
                    //_context.LogError(ex);
                    _context.ScaleUp(ex);
                    _context.PostHealth(FunHealth.Degraded(ex));
                }
                catch (Exception ex)
                {
                    // TODO: retry, etc
                    Console.WriteLine(ex.Message);
                    _context.PostHealth(FunHealth.Failure(ex));
                }
            };

            EventProcessorClient.ProcessErrorAsync += (args) =>
            {
                Console.WriteLine($"ProcessErrorAsync: {args.Exception.Message}");

                //_context.Logger.LogError(eventArgs.Exception);
                // Circuit breaker
                //if (attempts > 3) Health.Error(ex);
                //else Health.Warning(ex);
                _context.PostHealth(FunHealth.Failure(args.Exception));

                return(Task.CompletedTask);
            };

            // Start the processor
            await EventProcessorClient.StartProcessingAsync();

            return;
        }
コード例 #24
0
        public async Task Connect(CancellationToken cancellationToken)
        {
            var logContext   = _context.LogContext;
            var inputAddress = _context.InputAddress;

            LogContext.SetCurrentIfNull(logContext);

            _cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);

            async Task ProcessEventAsync(ProcessEventArgs arg)
            {
                LogContext.SetCurrentIfNull(logContext);

                try
                {
                    await _executor.Push(() => _transport.Handle(arg, cancellationToken), _cancellationTokenSource.Token).ConfigureAwait(false);
                }
                catch (OperationCanceledException e) when(e.CancellationToken == _cancellationTokenSource.Token)
                {
                }
            }

            async Task ProcessErrorAsync(ProcessErrorEventArgs arg)
            {
                var faultedEvent = new ReceiveTransportFaultedEvent(inputAddress, arg.Exception);

                await _context.TransportObservers.Faulted(faultedEvent).ConfigureAwait(false);

                await _context.EndpointObservers.Faulted(new ReceiveEndpointFaultedEvent(faultedEvent, this)).ConfigureAwait(false);
            }

            _processor.ProcessEventAsync += ProcessEventAsync;
            _processor.ProcessErrorAsync += ProcessErrorAsync;

            try
            {
                await _blobContainerClient.CreateIfNotExistsAsync(cancellationToken : cancellationToken).ConfigureAwait(false);
            }
            catch (RequestFailedException exception)
            {
                LogContext.Warning?.Log(exception, "Azure Blob Container does not exist: {Address}", _blobContainerClient.Uri);
            }

            LogContext.Debug?.Log("EventHub processor starting: {EventHubName}", _processor.EventHubName);

            await _processor.StartProcessingAsync(cancellationToken).ConfigureAwait(false);

            await _context.TransportObservers.Ready(new ReceiveTransportReadyEvent(inputAddress)).ConfigureAwait(false);

            var endpointReadyEvent = new ReceiveEndpointReadyEvent(_context.InputAddress, this, true);

            _started.TrySetResult(endpointReadyEvent);

            await _context.EndpointObservers.Ready(endpointReadyEvent).ConfigureAwait(false);
        }
コード例 #25
0
        public async Task Start(CancellationToken token)
        {
            string consumerGroup = EventHubConsumerClient.DefaultConsumerGroupName;
            BlobContainerClient storageClient = new BlobContainerClient(eventHubWorkloadConfig.StorageAccountConnectionString, eventHubWorkloadConfig.StorageAccountContainer);

            processor = new EventProcessorClient(storageClient, consumerGroup, eventHubWorkloadConfig.EventHubsNamespaceConnectionString, eventHubWorkloadConfig.EventHub);

            processor.ProcessEventAsync += processEventHandler;
            processor.ProcessErrorAsync += processErrorHandler;
            await processor.StartProcessingAsync(token);
        }
コード例 #26
0
        private async Task StartEventProcessing()
        {
            string consumerGroup = EventHubConsumerClient.DefaultConsumerGroupName;
            var    storageClient = new BlobContainerClient(blobConnectionString, blobContainerName);

            eventProcessorClient = new EventProcessorClient(storageClient, consumerGroup, eventHubConnectionString, eventHubName);

            eventProcessorClient.ProcessEventAsync += processEventHandler;
            eventProcessorClient.ProcessErrorAsync += processErrorHandler;

            await eventProcessorClient.StartProcessingAsync();
        }
        public Task StartAsync(CancellationToken cancellationToken)
        {
            Console.WriteLine("StartAsync called...");

            Console.WriteLine("Created Clients. Registering handler...");

            _processor.ProcessEventAsync          += ProcessEventHandler;
            _processor.PartitionInitializingAsync += ProcessorOnPartitionInitializingAsync;
            _processor.ProcessErrorAsync          += ProcessorOnProcessErrorAsync;
            _processor.PartitionClosingAsync      += ProcessorOnPartitionClosingAsync;

            return(_processor.StartProcessingAsync(cancellationToken));
        }
コード例 #28
0
ファイル: Program.cs プロジェクト: vigneshvp/Optum-AZ204
        static async Task ReceiveMessagesAsync()
        {
            // Read from the default consumer group: $Default
            string consumerGroup = EventHubConsumerClient.DefaultConsumerGroupName;

            BlobContainerClient storageClient = new BlobContainerClient(blobStorageConnectionString, blobContainerName);

            EventProcessorClient processor = new EventProcessorClient(storageClient, consumerGroup, connectionString, eventHubName);

            processor.ProcessEventAsync += ProcessEventHandler;
            processor.ProcessErrorAsync += ProcessErrorHandler;

            await processor.StartProcessingAsync();
        }
コード例 #29
0
ファイル: Program.cs プロジェクト: mail4hafij/Azure-EventHub
        static async Task Main()
        {
            string consumerGroup = EventHubConsumerClient.DefaultConsumerGroupName;

            // Event client uses a blob storage to save the checkpoint.
            BlobContainerClient  storageClient   = new BlobContainerClient(StorageAccountConnectionString, BlobContainerName);
            EventProcessorClient processorClient = new EventProcessorClient(storageClient, consumerGroup, ConnectionString, EventHubName);

            // Registering the handlers
            processorClient.ProcessEventAsync += ProcessEventHandler;
            processorClient.ProcessErrorAsync += ProcessErrorHandler;

            await processorClient.StartProcessingAsync();

            await processorClient.StopProcessingAsync();
        }
コード例 #30
0
ファイル: Program.cs プロジェクト: dariiai/AzureEventHubsApp
        private static async Task <EventProcessorClient> RegisterEventReciever(string eventHubConnectionString,
                                                                               string eventHubName,
                                                                               string blobStorageConnectionString,
                                                                               string blobContainerName)
        {
            string consumerGroup = EventHubConsumerClient.DefaultConsumerGroupName;
            BlobContainerClient  storageClient = new BlobContainerClient(blobStorageConnectionString, blobContainerName);
            EventProcessorClient processor     = new EventProcessorClient(storageClient, consumerGroup, eventHubConnectionString, eventHubName);

            processor.ProcessEventAsync += ProcessEventHubMessageHandler;
            processor.ProcessErrorAsync += ProcessEventHubMessageErrorHandler;

            await processor.StartProcessingAsync();

            return(processor);
        }