protected override void RegisterMiscHandlersImpl(ICommandRegistry commandRegistry, Func <IServiceProvider> serviceProviderFactory)
        {
            commandRegistry.Register <BatchMapDataCommand>(() => serviceProviderFactory().GetService <QueueCommandDispatcher>());
            commandRegistry.Register <WriteMappedDataCommand>(() => serviceProviderFactory().GetService <QueueCommandDispatcher>());

            commandRegistry.Register <BatchReduceDataCommand>(() => serviceProviderFactory().GetService <QueueCommandDispatcher>());
            commandRegistry.Register <WriteReducedDataCommand>(() => serviceProviderFactory().GetService <QueueCommandDispatcher>());
        }
Example #2
0
        public static IServiceCollection UseShoppingCart(this IServiceCollection serviceCollection,
                                                         ICommandRegistry commandRegistry)
        {
            serviceCollection.AddSingleton <IShoppingCartRepository, ShoppingCartRepository>();

            commandRegistry.Register <GetCartQueryHandler>();
            commandRegistry.Register <AddToCartCommandHandler>();

            return(serviceCollection);
        }
Example #3
0
        public static IServiceCollection UseCheckout(this IServiceCollection serviceCollection,
                                                     ICommandRegistry registry)
        {
            serviceCollection.AddSingleton <IOrderRepository, OrderRepository>();

            registry.Register <CreateOrderCommandHandler>();
            registry.Register <MakePaymentCommandHandler>();

            return(serviceCollection);
        }
        public IRegisterFireAndForgetHandler RegisterFireAndForgetFunctionImpl <TFunction, TCommand>()
            where TFunction : class, IFireAndForgetFunction
            where TCommand : ICommand
        {
            _serviceCollection.AddTransient <TFunction>();

            var commandHandlerType = _functionHandlerType.MakeGenericType(typeof(TFunction), typeof(TCommand));

            _commandRegistry.Register(commandHandlerType);
            if (_customCommandDispatcher != null)
            {
                _commandRegistry.Register <TCommand>(() => _customCommandDispatcher);
            }
            return(this);
        }
        private void RegisterCommandHandlersForCommandsWithNoAssociatedHandler(FunctionHostBuilder builder, ICommandRegistry commandRegistry)
        {
            // IN PROGRESS: This looks from the loaded set of assemblies and looks for a command handler for each command associated with a function.
            // If the handler is not already registered in the command registry then this registers it.
            IRegistrationCatalogue registrationCatalogue  = (IRegistrationCatalogue)commandRegistry;
            HashSet <Type>         registeredCommandTypes = new HashSet <Type>(registrationCatalogue.GetRegisteredCommands());

            Dictionary <Type, List <Type> > commandTypesToHandlerTypes = null;

            foreach (AbstractFunctionDefinition functionDefinition in builder.FunctionDefinitions)
            {
                if (registeredCommandTypes.Contains(functionDefinition.CommandType))
                {
                    continue;
                }

                if (commandTypesToHandlerTypes == null)
                {
                    commandTypesToHandlerTypes = HarvestCommandHandlers();
                }

                if (commandTypesToHandlerTypes.TryGetValue(functionDefinition.CommandType, out List <Type> handlerTypes))
                {
                    foreach (Type handlerType in handlerTypes)
                    {
                        commandRegistry.Register(handlerType);
                    }
                }
            }
        }
Example #6
0
 public static ICommandRegistry RegisterAmazonS3ObjectStore(this ICommandRegistry commandRegistry)
 {
     return(commandRegistry
            .Register <AmazonS3StoreObjectCommandHandler>()
            .Register <AmazonS3RetrieveObjectCommandHandler>()
            .Register <AmazonS3ListObjectKeysCommandHandler>());
 }
Example #7
0
 public static ICommandRegistry RegisterFileSystemObjectStore(this ICommandRegistry commandRegistry)
 {
     return(commandRegistry
            .Register <FileSystemStoreObjectCommandHandler>()
            .Register <FileSystemRetrieveObjectCommandHandler>()
            .Register <FileSystemListObjectKeysCommandHandler>());
 }
Example #8
0
 public static ICommandRegistry RegisterMemoryObjectStore(this ICommandRegistry commandRegistry)
 {
     return(commandRegistry
            .Register <MemoryStoreObjectCommandHandler>()
            .Register <MemoryRetrieveObjectCommandHandler>()
            .Register <MemoryListObjectKeysCommandHandler>());
 }
Example #9
0
        private static void ConfigureCommanding(CloudQueue queue, out ICommandDispatcher dispatcher, out IAzureStorageCommandQueueProcessorFactory listenerFactory)
        {
            ServiceCollection serviceCollection = new ServiceCollection();
            CommandingDependencyResolverAdapter dependencyResolver = serviceCollection.GetCommandingDependencyResolver(() => _serviceProvider);
            ICommandRegistry registry = dependencyResolver.AddCommanding();

            dependencyResolver.AddQueues(
                (msg, cmd, ex) =>
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(msg);
            },
                (msg, cmd, ex) =>
            {
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine(msg);
            },
                (msg, cmd, ex) =>
            {
                Console.ForegroundColor = ConsoleColor.Blue;
                Console.WriteLine(msg);
            })
            .AddAzureStorageCommanding();

            registry
            .Register <OutputWorldToConsoleCommandHandler>(1000, dispatcherFactoryFunc: queue.CreateCommandDispatcherFactory())
            .Register <OutputBigglesToConsoleCommandHandler>();

            _serviceProvider = serviceCollection.BuildServiceProvider();
            dispatcher       = _serviceProvider.GetService <ICommandDispatcher>();
            listenerFactory  = _serviceProvider.GetService <IAzureStorageCommandQueueProcessorFactory>();
        }
        public static ICommandRegistry AddNotificationClient(this ICommandRegistry commandRegistry, string serviceBusConnectionString)
        {
            // Configure the SendEmailCommand to be dispatched to a service bus queue
            QueueClient queueClient = new QueueClient(serviceBusConnectionString, "sendEmailQueue");

            commandRegistry.Register <SendEmailCommand>(queueClient.CreateCommandDispatcherFactory());
            return(commandRegistry);
        }
Example #11
0
        /// <summary>
        /// Registers a command so that it can be inspected.
        /// </summary>
        /// <param name="commandType">The type of the command to register.</param>
        public void Register(Type commandType)
        {
            if (commandType == null)
            {
                throw new ArgumentNullException("commandType");
            }

            commandRegistry.Register(commandType);
        }
Example #12
0
        /// <summary>
        /// Register a command type.
        /// </summary>
        /// <param name="commandType">The <see cref="Type" /> implementing the command.</param>
        public void RegisterCommandType(Type commandType)
        {
            if (commandType == null)
            {
                throw new ArgumentNullException(nameof(commandType));
            }

            _commandRegistry.Register(commandType);
        }
        public static IServiceCollection UseStore(this IServiceCollection serviceCollection,
                                                  ICommandRegistry commandRegistry)
        {
            serviceCollection.AddSingleton <IStoreProductRepository, StoreProductRepository>();

            commandRegistry.Register <GetStoreProductQueryHandler>();

            return(serviceCollection);
        }
Example #14
0
        public void RegisterHostingEnvironment(ICommandRegistry commandRegistry, IServiceCollection serviceCollection, Func <IServiceProvider> serviceProviderFactory, Action <IRegisterFireAndForgetHandler> registerFireAndForgetHandlers)
        {
            commandRegistry.Register(TerminatorHandlerTypeFactory());
            RegisterMiscHandlersImpl(commandRegistry, serviceProviderFactory);
            RegisterObjectStoreImpl(commandRegistry);
            registerFireAndForgetHandlers(new RegisterFireAndForgetHandler(commandRegistry, serviceCollection, FireAndForgetHandlerType(), CustomCommandDispatcherFactory()));

            serviceCollection.AddSingleton(QueueClientFactory);
            serviceCollection.AddSingleton(x => ConfigFactory());
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            CommandingDependencyResolverAdapter resolver = new CommandingDependencyResolverAdapter(
                (fromType, toInstance) => services.AddSingleton(fromType, toInstance),
                (fromType, toType) => services.AddTransient(fromType, toType),
                (resolveTo) => _serviceProvider.GetService(resolveTo));

            ICommandRegistry registry = resolver.AddCommanding();

            registry.Register <UpdatePropertyValueCommandHandler>();
            registry.Register <GetPropertyValueQueryHandler>();
            registry.Register <GetMessageQueryHandler>();

            services
            .AddMvc(cfg => cfg.Filters.Add <ClaimsInjectionFilter>())
            .AddAspNetCoreCommanding(cfg =>
            {
                cfg
                // Define RESTful controllers and actions based on commands
                .Controller("PropertyValue",
                            attributes => attributes.Attribute <AuthorizeAttribute>(),
                            actions => actions
                            .Action <GetPropertyValueQuery>(HttpMethod.Get)
                            .Action <UpdatePropertyValueCommand>(HttpMethod.Put))
                .Controller("Message", actions => { actions.Action <GetMessageQuery>(HttpMethod.Get); })
                // Configure claims to automatically populate properties on commands
                .Claims(mapping =>
                {
                    mapping
                    .MapClaimToCommandProperty <GetPropertyValueQuery>("UserId", cmd => cmd.MisspelledUserId)
                    .MapClaimToPropertyName("UserId", "UserId");
                });
            });

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "My API", Version = "v1"
                });
                c.AddAspNetCoreCommanding();
            });
        }
Example #16
0
        /// <summary>
        /// Create a new instance.
        /// </summary>
        public Runtime()
        {
            var nameValidator = new NameValidator();
            var commandDescriptorGenerator = new CommandAttributeInspector();

            _commandRegistry = new CommandRegistry(nameValidator, commandDescriptorGenerator);

            _commandServices  = new CommandServices();
            _parser           = new Parser();
            _variableReplacer = new VariableReplacer();

            _sessionObjectTypes = new ScopedObjectRegistry();
            _sessionObjectTypes.Register <VariableCollection>();

            _commandRegistry.Register(typeof(Help));
            _commandRegistry.Register(typeof(Var));

            _commandServices.Register(_commandRegistry);
            _commandServices.Register <IPhraseDictionary>(new PhraseDictionary());
        }
        public Form1()
        {
            InitializeComponent();
            IServiceCollection            serviceCollection = new ServiceCollection();
            ICommandingDependencyResolver resolver          = new CommandingDependencyResolver((type, instance) => serviceCollection.AddSingleton(type, instance),
                                                                                               (type, impl) => serviceCollection.AddTransient(type, impl),
                                                                                               type => _serviceProvider.GetService(type));
            ICommandRegistry registry = resolver.UseCommanding();

            registry.Register <GetTextCommandHandler>();
            _serviceProvider = serviceCollection.BuildServiceProvider();
            _dispatcher      = _serviceProvider.GetService <ICommandDispatcher>();
        }
 public static void RegisterHttpCommand <TCommand, TResult>(this ICommandRegistry registry,
                                                            Uri uri,
                                                            HttpMethod httpMethod = null,
                                                            Func <string> authenticationHeaderContent      = null,
                                                            IHttpCommandSerializer httpCommandSerializer   = null,
                                                            IUriCommandQueryBuilder uriCommandQueryBuilder = null) where TCommand : ICommand <TResult>
 {
     registry.Register <TCommand, TResult>(() => new HttpCommandDispatcher(new HttpCommandExecuter(
                                                                               uri,
                                                                               httpMethod, authenticationHeaderContent, httpCommandSerializer ?? new JsonCommandSerializer(),
                                                                               uriCommandQueryBuilder ?? new UriCommandQueryBuilder(),
                                                                               HttpCommandingDependencies.HttpClientProvider)));
 }
        public static IServiceCollection UseStore(this IServiceCollection serviceCollection,
                                                  Func <IServiceProvider> serviceProvider,
                                                  ICommandRegistry commandRegistry, ApplicationModeEnum applicationMode = ApplicationModeEnum.InProcess)
        {
            serviceCollection.AddSingleton <IStoreProductRepository, StoreProductRepository>();
            if (applicationMode == ApplicationModeEnum.InProcess || applicationMode == ApplicationModeEnum.Server)
            {
                commandRegistry.Register <GetStoreProductQueryHandler>();
            }
            else if (applicationMode == ApplicationModeEnum.Client)
            {
                // this configures the command dispatcher to send the command over HTTP and wait for the result
                Uri functionUri = new Uri("http://localhost:7071/api/GetStoreProduct");
                commandRegistry.Register <GetStoreProductQuery, CommandResponse <StoreProduct> >(() =>
                {
                    IHttpCommandDispatcherFactory httpCommandDispatcherFactory = serviceProvider().GetService <IHttpCommandDispatcherFactory>();
                    return(httpCommandDispatcherFactory.Create(functionUri, HttpMethod.Get));
                });
            }

            serviceCollection.RegisterValidators();

            return(serviceCollection);
        }
Example #20
0
        static ICommandDispatcher Configure()
        {
            Uri uri = new Uri("http://localhost:52933/api/personalDetails");
            ServiceCollection serviceCollection = new ServiceCollection();
            CommandingDependencyResolverAdapter dependencyResolver = serviceCollection.GetCommandingDependencyResolver(() => _serviceProvider);

            ICommandRegistry registry = dependencyResolver.AddCommanding();

            dependencyResolver.AddHttpCommanding();
            _serviceProvider = serviceCollection.BuildServiceProvider();

            registry.Register <UpdatePersonalDetailsCommand, UpdateResult>(HttpCommandDispatcherFactory.Create(uri, HttpMethod.Put));

            ICommandDispatcher dispatcher = _serviceProvider.GetService <ICommandDispatcher>();

            return(dispatcher);
        }
        public static IServiceCollection UseServiceBusScheduler <TCommandDispatcherType>(
            this IServiceCollection serviceCollection,
            ICommandRegistry commandRegistry,
            Options options) where TCommandDispatcherType : IFrameworkCommandDispatcher
        {
            serviceCollection
            .AddSingleton <IQueueClientProvider>(new QueueClientProvider(options.ServiceBusConnectionString, options.QueueName))
            .AddTransient <ICommandRescheduler, CommandRescheduler>()
            .AddTransient <ICommandScheduler, CommandScheduler>()
            .AddTransient <IScheduledDateCalculator, ScheduledDateCalculator>()
            ;

            if (serviceCollection.All(x => x.ServiceType != typeof(ICancelledCommandRepository)))
            {
                serviceCollection.AddTransient <ICancelledCommandRepository, CancellationUnsupportedCommandRepository>();
            }

            commandRegistry.Register <ScheduledMessageHandler <TCommandDispatcherType> >();
            return(serviceCollection);
        }
        private static IServiceBusCommandQueueProcessorFactory ConfigureForDequeue()
        {
            if (_dequeueServiceProvider == null)
            {
                IServiceCollection serviceCollection         = new ServiceCollection();
                CommandingDependencyResolverAdapter resolver = new CommandingDependencyResolverAdapter(
                    (fromType, toInstance) => serviceCollection.AddSingleton(fromType, toInstance),
                    (fromType, toType) => serviceCollection.AddTransient(fromType, toType),
                    (resolveType) => _dispatchServiceProvider.GetService(resolveType));
                ICommandRegistry commandRegistry = resolver.AddCommanding();
                resolver.AddQueues().AddAzureServiceBus();

                // register our command to dispatch to a servie bus queue
                commandRegistry.Register <SimpleCommandHandler>();

                _dequeueServiceProvider = serviceCollection.BuildServiceProvider();
            }

            IServiceBusCommandQueueProcessorFactory serviceBusCommandQueueProcessorFactory = _dispatchServiceProvider.GetService <IServiceBusCommandQueueProcessorFactory>();

            return(serviceBusCommandQueueProcessorFactory);
        }
        private static ICommandDispatcher ConfigureForDispatchToQueue()
        {
            if (_dispatchServiceProvider == null)
            {
                IServiceCollection serviceCollection         = new ServiceCollection();
                CommandingDependencyResolverAdapter resolver = new CommandingDependencyResolverAdapter(
                    (fromType, toInstance) => serviceCollection.AddSingleton(fromType, toInstance),
                    (fromType, toType) => serviceCollection.AddTransient(fromType, toType),
                    (resolveType) => _dispatchServiceProvider.GetService(resolveType));
                ICommandRegistry commandRegistry = resolver.AddCommanding();
                resolver.AddAzureServiceBus();

                // register our command to dispatch to a servie bus queue
                QueueClient client = new QueueClient(ServiceBusConnectionString, "myqueue");
                commandRegistry.Register <SimpleCommand>(client.CreateCommandDispatcherFactory());

                _dispatchServiceProvider = serviceCollection.BuildServiceProvider();
            }


            ICommandDispatcher dispatcher = _dispatchServiceProvider.GetService <ICommandDispatcher>();

            return(dispatcher);
        }
Example #24
0
        private void RegisterCommandHandlersForCommandsWithNoAssociatedHandler(FunctionHostBuilder builder, ICommandRegistry commandRegistry)
        {
            // TODO: We can improve this so that auto-registration is decoupled and can be provided by a mediator package
            if (builder.MediatorType != typeof(DefaultMediatorDecorator))
            {
                return;
            }

            // IN PROGRESS: This looks from the loaded set of assemblies and looks for a command handler for each command associated with a function.
            // If the handler is not already registered in the command registry then this registers it.
            IRegistrationCatalogue registrationCatalogue  = (IRegistrationCatalogue)commandRegistry;
            HashSet <Type>         registeredCommandTypes = new HashSet <Type>(registrationCatalogue.GetRegisteredCommands());

            Dictionary <Type, List <Type> > commandTypesToHandlerTypes = null;

            foreach (AbstractFunctionDefinition functionDefinition in builder.FunctionDefinitions)
            {
                if (registeredCommandTypes.Contains(functionDefinition.CommandType))
                {
                    continue;
                }

                if (commandTypesToHandlerTypes == null)
                {
                    commandTypesToHandlerTypes = HarvestCommandHandlers();
                }

                if (commandTypesToHandlerTypes.TryGetValue(functionDefinition.CommandType, out List <Type> handlerTypes))
                {
                    foreach (Type handlerType in handlerTypes)
                    {
                        commandRegistry.Register(handlerType);
                    }
                }
            }
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public virtual void ConfigureServices(IServiceCollection services)
        {
            string storageAccountConnectionString = Configuration["storage:connectionstring"];
            string expensiveOperationQueueName    = Configuration["storage:queuename"];

            CommandingDependencyResolverAdapter resolver = new CommandingDependencyResolverAdapter(
                (fromType, toInstance) => services.AddSingleton(fromType, toInstance),
                (fromType, toType) => services.AddTransient(fromType, toType),
                (resolveTo) => _serviceProvider.GetService(resolveTo));

            // Using an instance of CommandingRuntime rather than the static helpers isolates
            // this commanding infrastructure to this startup class / instance of the web app
            // which means that acceptance tests can be run in parallel with multiple instances
            // of the ASP.Net Core test server.
            ICommandRegistry registry = _commandingRuntime.AddCommanding(resolver);

            //ICommandRegistry registry = resolver.AddCommanding();
            resolver.AddQueues().AddAzureStorageCommanding();

            // Register our command handlers using the discovery approach. Our handlers are in this assembly
            // so we just pass through our assembly
            registry.Discover(typeof(Startup).Assembly);

            // Register our expensive operation command to be sent to a queue
            registry.Register <ExpensiveOperationCommand>(
                CloudQueueDispatcherFactory.Create(storageAccountConnectionString, expensiveOperationQueueName));

            // Register our commands as REST endpoints. This results in an API where the AddCommand, GetPostsQuery,
            // GetPostsForCurrentUserQuery and GetPostQuery are handled as GET requests and executed immediately
            // in process by the registered handlers while the ExpensiveOperationCommand is exposed as a POST operation
            // and results in the command being placed on a queue
            services
            .AddMvc(ConfigureMvcOptions)
            // this block configures our commands to be exposed on endpoints
            .AddAspNetCoreCommanding(cfg => cfg
                                     .Controller("Post", controller => controller
                                                 .Action <GetPostsQuery>(HttpMethod.Get)
                                                 .Action <GetPostQuery, FromRouteAttribute>(HttpMethod.Get, "{PostId}")
                                                 .Action <AddNewPostCommand>(HttpMethod.Post)
                                                 .Action <DeletePostCommand>(HttpMethod.Delete, "{PostId}")
                                                 )
                                     .Controller("Profile", controller => controller
                                                 .Action <GetPostsForCurrentUserQuery>(HttpMethod.Get, "Posts"))
                                     .Controller("ExpensiveOperation", controller => controller
                                                 .Action <ExpensiveOperationCommand>(HttpMethod.Post))
                                     .Controller("SecurityTest", controller => controller
                                                 .Action <SecurityTestCommand>(HttpMethod.Post)
                                                 // we wire this one up with an ActionDefinition model to cover that test path
                                                 .Action(new ActionDefinition
            {
                BindingAttributeType = typeof(FromQueryAttribute),
                CommandType          = typeof(SecurityTestCommand),
                ResultType           = null,
                Route = "asQueryParam",
                Verb  = HttpMethod.Get
            }))
                                     .Claims(ConfigureClaimsMapping)
                                     .LogControllerCode(code =>
            {
                // this will output the code that is compiled for each controller to the debug window
                Debug.WriteLine(code);
            })
                                     );

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "Acceptance Test API", Version = "v1"
                });
                c.AddAspNetCoreCommanding();
            });
        }
Example #26
0
 public static ICommandRegistry AddProductClient(this ICommandRegistry commandRegistry, Uri endpoint)
 {
     commandRegistry.Register <GetProductQuery>(HttpCommandDispatcherFactory.Create(endpoint, HttpMethod.Get));
     return(commandRegistry);
 }