public static IWorkerApplicationBuilder UseSkipPollingMiddleware(this IWorkerApplicationBuilder app, ILoggerFactory loggerFactory)
        {
            // establish logger
            var logger = loggerFactory.CreateLogger("SkipPollingMiddleware");

            // get the polling service
            var pollingService = app.ApplicationServices.GetService <IPollingService>();

            // register the middleware
            app.Use(async(WorkerApplicationOperation operation, IWorkerApplicationMiddlewareExecutionController context) =>
            {
                // log
                logger.LogInformation("Skipping next polling...");

                // done
                pollingService.SkipNextPolling();

                // done
                await context.Invoke();
            });

            app.UseOnError(async(WorkerApplicationOperation operation, Exception error) => {
                // log
                logger.LogInformation("Skipping next polling...");

                // done
                pollingService.SkipNextPolling();

                // done
                await Task.CompletedTask;
            });

            return(app);
        }
Example #2
0
        public void Configure(IWorkerApplicationBuilder app, IWorkerHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            // get the right section
            var configSection = Configuration.GetSection("DemoAccount");
            var queueConfig1  = new AzureQueueClientPriorityConfiguration(configSection.GetValue <string>("Queue"), 1, configSection.GetValue <string>("Account"), configSection.GetValue <string>("Key"));
            var queueConfig2  = new AzureQueueClientPriorityConfiguration(configSection.GetValue <string>("Queue1"), 2, configSection.GetValue <string>("Account"), configSection.GetValue <string>("Key"));

            // Use our middle ware which checks the queue for a new task
            app.UseStorageQueueProcessor(loggerFactory, new List <AzureQueueClientPriorityConfiguration>()
            {
                queueConfig1, queueConfig2
            }, async(operation, message, next) => {
                // get a logger
                var logger = loggerFactory.CreateLogger("Processor");

                // log the message
                logger.LogInformation("Received Message: {0}", message);

                // delay
                Thread.Sleep(5000);

                // jump to the next middleware
                await next.Invoke();
            });

            // When executing this middleware we are skipping the polling because we don't wnat to wait. This works
            // well together witht he job queue message processor which skips all middle ware execution when
            // no job is arrived
            app.UseSkipPollingMiddleware(loggerFactory);
        }
Example #3
0
        public static IWorkerApplicationBuilder UseStorageQueueProcessor(this IWorkerApplicationBuilder app, ILoggerFactory loggerFactory, IEnumerable <IAzureQueueClientPriorityConfiguration> queuesConfiguration, Func <WorkerApplicationOperation, String, IWorkerApplicationMiddlewareExecutionController, Task> queueMessageProcessor)
        {
            Task.Run(async() =>
            {
                // generate a logger
                var logger = loggerFactory.CreateLogger("StorageQueueMiddleware");

                // initialize the queues
                var initializedQueues = await InitializeQueues(queuesConfiguration, logger);

                // some state of our function
                bool processedJobSinceLastMessage = true;

                // register our middleware
                logger.LogInformation("Registering StorageQueueMiddleware");
                return(app.Use(async(operation, next) =>
                {
                    // check the next queue task
                    if (processedJobSinceLastMessage)
                    {
                        logger.LogInformation("Waiting for new messages to process...");
                        processedJobSinceLastMessage = false;
                    }

                    // retrieve the message
                    var retrievedMessage = await GetMessageFromQueues(initializedQueues);
                    if (retrievedMessage != null)
                    {
                        // log
                        logger.LogInformation($"Received new message from queue {retrievedMessage.Item2.PriorityDisplayName} ({retrievedMessage.Item1.AsBytes.Length} bytes)");

                        // set the state
                        processedJobSinceLastMessage = true;

                        // process the next message as task
                        logger.LogInformation("Processing message...");
                        await queueMessageProcessor(operation, retrievedMessage.Item1.AsString, next);

                        // log
                        logger.LogInformation("Processing message finished...");
                    }
                    else
                    {
                        // Let the next middleware finish our job
                        await next.Skip();
                    }
                }));
            }).Wait();

            return(app);
        }
Example #4
0
        public void Configure(IWorkerApplicationBuilder app)
        {
            try
            {
                _methods.ConfigureDelegate(app);
            }
            catch (Exception ex)
            {
                if (ex is TargetInvocationException)
                {
                    ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
                }

                throw;
            }
        }
Example #5
0
 private void Invoke(object instance, IWorkerApplicationBuilder builder)
 {
     // Create a scope for Configure, this allows creating scoped dependencies
     // without the hassle of manually creating a scope.
     using (var scope = builder.ApplicationServices.CreateScope())
     {
         var serviceProvider = scope.ServiceProvider;
         var parameterInfos  = MethodInfo.GetParameters();
         var parameters      = new object[parameterInfos.Length];
         for (var index = 0; index < parameterInfos.Length; index++)
         {
             var parameterInfo = parameterInfos[index];
             if (parameterInfo.ParameterType == typeof(IWorkerApplicationBuilder))
             {
                 parameters[index] = builder;
             }
             else
             {
                 try
                 {
                     parameters[index] = serviceProvider.GetRequiredService(parameterInfo.ParameterType);
                 }
                 catch (Exception ex)
                 {
                     throw new Exception(string.Format(
                                             "Could not resolve a service of type '{0}' for the parameter '{1}' of method '{2}' on type '{3}'.",
                                             parameterInfo.ParameterType.FullName,
                                             parameterInfo.Name,
                                             MethodInfo.Name,
                                             MethodInfo.DeclaringType.FullName), ex);
                 }
             }
         }
         MethodInfo.Invoke(instance, parameters);
     }
 }
Example #6
0
        public void Configure(IWorkerApplicationBuilder app, IWorkerHostingEnvironment env, ILoggerFactory loggerFactory, IShutdownNotificationService shutdownService, IPollingService pollingService, ITimeoutService timeoutService)
        {
            shutdownService.OnShutdownNotification(async() =>
            {
                // get a logger
                var logger = loggerFactory.CreateLogger("ShutdownHandler");

                // delay
                logger.LogInformation("Delaying shutdown by 10 seconds");
                await Task.Delay(5000);

                // done
                logger.LogInformation("Finished delay");
            });

            app.Use((WorkerApplicationOperation operation, IWorkerApplicationMiddlewareExecutionController next) =>
            {
                // get a logger
                var logger = loggerFactory.CreateLogger("Processor");

                // lookup a scoped service
                var scopedService = operation.Services.GetService <IScopedService>();

                // log the message
                logger.LogInformation("MW01 - InstanceId: {0}", scopedService.InstanceId);

                return(next.Invoke());
            });

            app.Use((WorkerApplicationOperation operation, IWorkerApplicationMiddlewareExecutionController next) =>
            {
                // get a logger
                var logger = loggerFactory.CreateLogger("Processor");

                // lookup a scoped service
                var scopedService = operation.Services.GetService <IScopedService>();

                // log the message
                logger.LogInformation("MW02 - InstanceId: {0}", scopedService.InstanceId);

                return(next.Invoke());
            });

            /*app.Use((WorkerApplicationOperation operation, IWorkerApplicationMiddlewareExecutionController next) =>
             * {
             * // get a logger
             * var logger = loggerFactory.CreateLogger("AbortNextPolling");
             *
             * logger.LogInformation("Abort...");
             * pollingService.AbortDuringNextPolling();
             *
             * return next.Invoke();
             * });*/

            app.Use(async(WorkerApplicationOperation operation, IWorkerApplicationMiddlewareExecutionController next) =>
            {
                // get a logger
                var logger = loggerFactory.CreateLogger("Processor");
                logger.LogInformation("Delaying Job");

                // delay
                logger.LogInformation($"Delay 5sec - {DateTime.Now}");
                await Task.Delay(5000);

                // reset the timeout
                await timeoutService.ResetExecutionTimeout();

                // delay
                logger.LogInformation($"Delay 5sec - {DateTime.Now}");
                await Task.Delay(5000);

                // reset the timeout
                await timeoutService.ResetExecutionTimeout();

                // delay
                logger.LogInformation($"Delay 5sec - {DateTime.Now}");
                await Task.Delay(5000);

                // reset the timeout
                await timeoutService.ResetExecutionTimeout();

                // delay
                logger.LogInformation($"Delay 5sec - {DateTime.Now}");
                await Task.Delay(5000);

                // delay
                logger.LogInformation($"Delay 5sec - {DateTime.Now}");
                await Task.Delay(5000);

                // delay
                logger.LogInformation($"Delay 5sec - {DateTime.Now}");
                await Task.Delay(5000);

                // next
                await next.Invoke();
            });

            app.UseOnTimeout(async(WorkerApplicationOperation operation) =>
            {
                Console.WriteLine("Timeout Exceeded");
                await Task.CompletedTask;

                // abort
                Console.WriteLine("Aborting Worker");
                pollingService.AbortDuringNextPolling();
            });
        }