예제 #1
0
        public void RegisterTheSameCommandTwice()
        {
            var registry = new CommandRegistry();
            registry.Register(new HelpCommand());

            Assert.Throws<ArgumentException>(() => registry.Register(new HelpCommand()));
        }
예제 #2
0
 public void FindShouldReturnTheSameCommandJustOnce()
 {
     var registry = new CommandRegistry();
     registry.Register(new HelpCommand());
     registry.Register(new HelpCommand(), "hlp");
     Assert.AreEqual(1, registry.Find("h").Count);
 }
예제 #3
0
 public void AmbiguousMatchCommand()
 {
     var registry = new CommandRegistry();
     registry.Register(new BarCommand());
     registry.Register(new BazCommand());
     var factory = new CommandFactory(registry);
     var command = factory.Create(new[] {"ba"});
     Assert.That(command, Is.InstanceOf(typeof(AmbiguousMatchCommand)));
 }
예제 #4
0
 public void RegisterBothCommandAndAliasAndFindWithPrefix()
 {
     var registry = new CommandRegistry();
     registry.Register(new HelpCommand());
     registry.Register(new HelpCommand(), "h");
     // Only finds the alias, because the prefix and the name of the
     // command are the same in this case.
     Assert.AreEqual(1, registry.Find("h").Count);
 }
예제 #5
0
 public void RegisterBothCommandAndAlias()
 {
     var registry = new CommandRegistry();
     registry.Register(new HelpCommand());
     registry.Register(new HelpCommand(), "h");
     Assert.AreEqual(2, registry.Commands.Count);
     Assert.IsTrue(registry.Contains("help"));
     Assert.IsTrue(registry.Contains("h"));
 }
예제 #6
0
 public void OutputForAmbiguousMatchCommand()
 {
     var registry = new CommandRegistry();
     registry.Register(new BarCommand());
     registry.Register(new BazCommand());
     var factory = new CommandFactory(registry);
     var command = factory.Create(new[] {"ba"});
     var output = OutputFor(command);
     Assert.That(output, Is.StringContaining("Multiple commands start with 'ba':"));
     Assert.That(output, Is.StringContaining("  bar"));
     Assert.That(output, Is.StringContaining("  baz"));
 }
예제 #7
0
 public void RegisterOne()
 {
     var registry = new CommandRegistry();
     registry.Register(new HelpCommand());
     Assert.AreEqual(1, registry.Commands.Count);
     Assert.IsTrue(registry.Contains("help"));
 }
예제 #8
0
        static void Main(string[] args)
        {
            ICommandRegistry commandRegistry = new CommandRegistry();
            commandRegistry.Register<SayHelloQuery, SayHelloQueryHandler>();
            commandRegistry.Register<SayHelloCommand, SayHelloCommandHandler>();

            ContainerBuilder container = new ContainerBuilder();
            RegisterHandlers(container);

            AutofacCommandHandlerFactory autofacCommandHandlerFactory = new AutofacCommandHandlerFactory(container.Build());

            _commandProcessor = new CommandProcessor(commandRegistry, autofacCommandHandlerFactory);

            ExecuteCommand(_commandProcessor);
            ExecuteCommand(_commandProcessor);
            ExecuteQuery(_commandProcessor);

            Console.ReadLine();
        }
예제 #9
0
 /// <summary>
 /// Initialises a new instance of the ServerCommands class.
 /// </summary>
 /// <param name="server">The instance of the Server running.</param>
 /// <param name="registry">A CommandRegistry to register commands to.</param>
 public ServerCommands(Server server, CommandRegistry<ServerCommand> registry)
 {
     _server = server;
     _registry = registry;
     _registry.Register(new ServerCommand("broadcast", false, Broadcast, "Broadcasts a message to every connected client."));
     _registry.Register(new ServerCommand("help", false, Help, "Provides help for the command utility."));
     _registry.Register(new ServerCommand("ban", true, BanUser, "Bans a user from the server, never to return!"));
     _registry.Register(new ServerCommand("kick", true, KickUser, "Kicks a user from their session. They may reconnect, but their sessions will be read-only until the server is restarted."));
     _registry.Register(new ServerCommand("restart", true, Restart, "Restarts the server, notifying clients that it's happening."));
     _registry.Register(new ServerCommand("privileged", false, ListPrivileged, "Gives a list of all the privileged users."));
     _registry.Register(new ServerCommand("banned", false, ListBanned, "Gives a list of all the banned users."));
 }
예제 #10
0
        public void Execute_NoDescriptionOnCommand_DoesNotError()
        {
            // arrange
            var nameValidator       = new NameValidator();
            var descriptorGenerator = new CommandAttributeInspector();
            var registry            = new CommandRegistry(nameValidator, descriptorGenerator);

            registry.Register(typeof(SampleCommand2));

            var sut = new Help(registry, new PhraseDictionary());

            // act
            var result = sut.Execute() as ValueResult;

            // assert
            Assert.Contains("sample2", result.Value);
        }
예제 #11
0
        public static void RebuildCreateImportedTypeMenu()
        {
            var menus = new[] { customNodes.Menu, GenericCommands.NewTanWithCustomRoot.Menu, create };

            foreach (var menu in menus)
            {
                foreach (var command in menu)
                {
                    CommandHandlerList.Global.Disconnect(command);
                }
            }
            CreateNodeCommands.Clear();
            customNodes.Menu.Clear();
            GenericCommands.NewTanWithCustomRoot.Menu.Clear();
            create.Clear();
            create.Add(customNodes = new Command("Custom Nodes", new Menu()));

            foreach (var type in Project.Current.RegisteredNodeTypes)
            {
                var cmd = new Command("Create " + type.Name)
                {
                    Icon = NodeIconPool.GetIcon(type)
                };
                CommandRegistry.Register(cmd, "CreateCommands", "Create" + type.Name, @override: true);
                CommandHandlerList.Global.Connect(cmd, new CreateNode(type, cmd));
                if (type.Namespace == "Lime")
                {
                    create.Add(cmd);
                    CreateNodeCommands.Add(cmd);
                }
                else
                {
                    customNodes.Menu.Add(cmd);
                }
                if (IsNodeTypeCanBeRoot(type))
                {
                    var newFileCmd = new Command(type.Name);
                    var format     = typeof(Node3D).IsAssignableFrom(type) ? DocumentFormat.T3D : DocumentFormat.Tan;
                    CommandHandlerList.Global.Connect(newFileCmd, new FileNew(format, type));
                    GenericCommands.NewTanWithCustomRoot.Menu.Add(newFileCmd);
                }
            }
            customNodes.Enabled = customNodes.Menu.Count > 0;
            GenericCommands.NewTanWithCustomRoot.Enabled = GenericCommands.NewTanWithCustomRoot.Menu.Count > 0;
            TangerineApp.Instance?.RefreshCreateNodeCommands();
        }
예제 #12
0
        public static void Initialize()
        {
            if (_hasInit)
            {
                throw new InvalidOperationException();
            }

            _container = new Container();
            _container.Options.LifestyleSelectionBehavior = new SingletonLifestyleSelectionBehavior(); // Lazy hack to force all plugins to be singleton.

            // Register registries
            _container.RegisterSingleton <ClientRegistry>();
            _container.RegisterSingleton <CommandRegistry>();
            _container.RegisterSingleton <ICredentialStorage, JsonCredentialStorage>();

            // Register services
            _container.RegisterSingleton <IMessageBus, MessageBus>();
            _container.RegisterSingleton <ICommandHandler, CommandHandler>();

            AssemblyLoader loader = new AssemblyLoader();

            // Scan for clients
            var clientAssemblies =
                from file in new DirectoryInfo(PlatformServices.Default.Application.ApplicationBasePath).GetFiles()
                where file.Extension.ToLower() == ".dll" && file.Name.StartsWith("Coremero.Client.")
                select loader.LoadFromAssemblyPath(file.FullName);

            _container.RegisterCollection <IClient>(clientAssemblies);

            // Scan for plugins
            if (Directory.Exists(PathExtensions.PluginDir))
            {
                var pluginAssemblies =
                    from file in new DirectoryInfo(PathExtensions.PluginDir).GetFiles()
                    where file.Extension.ToLower() == ".dll" && file.Name.StartsWith("Coremero.Plugin.")
                    select loader.LoadFromAssemblyPath(file.FullName);

                _container.RegisterCollection <IPlugin>(pluginAssemblies);
            }

            _container.Verify();

            // TODO: Allow host application to control this.
            Debug.WriteLine("Connecting all clients.");
            foreach (IClient client in _container.GetAllInstances <IClient>())
            {
                client.Connect();
            }

            Debug.WriteLine("Loading all plugins.");
            CommandRegistry cmdRegistry = _container.GetInstance <CommandRegistry>();

            try
            {
                foreach (IPlugin plugin in _container.GetAllInstances <IPlugin>())
                {
                    cmdRegistry.Register(plugin);
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
            }

            cmdRegistry.Register(_container.GetInstance <CorePlugin>());


            _hasInit = true;
        }
예제 #13
0
 public CommandMapTest()
 {
     Registry = new CommandRegistry();
     Registry.Register(new MockPlugin());
 }
예제 #14
0
        public static async Task Main(string[] args)
        {
            // Log init.
            var loggingConfig = new LoggingConfiguration();

            var consoleTarget = new ColoredConsoleTarget
            {
                Name   = "console",
                Layout = @"[${date:format=HH\:mm\:ss}] ${message}"
            };

            var fileTarget = new FileTarget()
            {
                Name     = "file",
                FileName = "${basedir}/coremero.log",
                Layout   = @"[${date:format=yyyy-MM-dd HH\:mm\:ss}] ${message}",
            };

            loggingConfig.AddTarget(fileTarget);
            loggingConfig.AddTarget(consoleTarget);

#if DEBUG
            loggingConfig.AddRule(LogLevel.Trace, LogLevel.Fatal, consoleTarget);
#else
            loggingConfig.AddRule(LogLevel.Info, LogLevel.Fatal, consoleTarget);
#endif
            loggingConfig.AddRule(LogLevel.Info, LogLevel.Fatal, fileTarget);
            LogManager.Configuration = loggingConfig;

            Log.Info("Coremero initializing.");

            // IoC setup
            _container = new Container
            {
                Options =
                {
                    LifestyleSelectionBehavior = new SingletonLifestyleSelectionBehavior()
                }
            };

            _container.ExpressionBuilt += (sender, arg) =>
            {
                Log.Trace($"Type {arg.RegisteredServiceType} registered.");
            };

            // Register registries
            _container.RegisterSingleton <ClientRegistry>();
            _container.RegisterSingleton <CommandRegistry>();
            _container.RegisterSingleton <ICredentialStorage, JsonCredentialStorage>();

            // Register services
            _container.RegisterSingleton <IMessageBus, MessageBus>();
            _container.RegisterSingleton <ICommandHandler, CommandHandler>();
            var loader = System.Runtime.Loader.AssemblyLoadContext.Default;
            // Scan for clients
            var clientAssemblies =
                new DirectoryInfo(PlatformServices.Default.Application.ApplicationBasePath).GetFiles()
                .Where(file => file.Extension.ToLower() == ".dll" && file.Name.StartsWith("Coremero.Client."))
                .Select(file => loader.LoadFromAssemblyPath(file.FullName));
            _container.RegisterCollection <IClient>(clientAssemblies);

            // Scan for plugins
            if (Directory.Exists(PathExtensions.PluginDir))
            {
                var pluginAssemblies =
                    new DirectoryInfo(PathExtensions.PluginDir).GetFiles()
                    .Where(file => file.Extension.ToLower() == ".dll" && file.Name.StartsWith("Coremero.Plugin."))
                    .Select(file => loader.LoadFromAssemblyPath(file.FullName));

                if (pluginAssemblies?.Any() == true)
                {
                    _container.RegisterCollection <IPlugin>(pluginAssemblies);
                }
            }

            _container.Verify();

            Log.Info("Connecting all clients.");
            foreach (IClient client in _container.GetAllInstances <IClient>())
            {
                try
                {
                    await client.Connect();

                    Log.Info($"Connected {client.Name}.");
                }
                catch (Exception e)
                {
                    Log.Exception(e.GetBaseException(), $"Failed to connect to {client.Name}");
                }
            }

            Log.Info("Loading all plugins.");
            CommandRegistry cmdRegistry = _container.GetInstance <CommandRegistry>();

            try
            {
                foreach (IPlugin plugin in _container.GetAllInstances <IPlugin>())
                {
                    try
                    {
                        cmdRegistry.Register(plugin);
                    }
                    catch (Exception e)
                    {
                        Log.Exception(e, $"Failed to register ${plugin.GetType()} in to the command registry.");
                    }
                }
            }
            catch
            {
                // No plugins registered.
                Log.Warn("No plugins were registered.");
            }

            cmdRegistry.Register(_container.GetInstance <CorePlugin>());
            System.Console.CancelKeyPress += Console_CancelKeyPress;
            await _cancelSemaphore.WaitAsync();
        }