示例#1
0
文件: Parser.cs 项目: vadian/Novus
        static public void ExecuteCommand(Character.Iactor actor, string command, string message = null)
        {
            User.User player = new User.User(true);
            player.UserID = actor.ID;
            player.Player = actor;
            bool commandFound = false;

            if (CombatCommands.ContainsKey(command.ToUpper()))    //check to see if player provided a combat related command
            {
                CombatCommands[command.ToUpper()](player, new List <string>(new string[] { command, message }));
                commandFound = true;
            }

            if (!commandFound)
            {
                foreach (Dictionary <string, CommandDelegate> AvailableCommands in CommandsList)
                {
                    if (AvailableCommands.ContainsKey(command.ToUpper()))
                    {
                        AvailableCommands[command.ToUpper()](player, new List <string>(new string[] { command + " " + message, command, message }));
                        break;
                    }
                }
            }
        }
示例#2
0
文件: Parser.cs 项目: vadian/Novus
        static public void ParseCommands(User.User player)
        {
            List <string> commands     = ParseCommandLine(player.InBufferPeek);
            bool          commandFound = false;

            foreach (Dictionary <string, CommandDelegate> AvailableCommands in CommandsList)
            {
                if (AvailableCommands.ContainsKey(commands[1].ToUpper()))
                {
                    AvailableCommands[commands[1].ToUpper()](player, commands);
                    commandFound = true;
                    break;
                }
            }

            //if all else fails auto-attack
            if (player.Player.InCombat && player.Player.CurrentTarget != null)
            {
                //auto attack! or we could remove this and let a player figure out on their own they're being attacked
                commands.Clear();
                commands.Add("KILL");
                commands.Add("target");
                commands.Insert(0, commands[0] + " " + commands[1]);
            }

            if (!commandFound && CombatCommands.ContainsKey(commands[1].ToUpper()))                //check to see if player provided a combat related command
            {
                CombatCommands[commands[1].ToUpper()](player, commands);
                commandFound = true;
                commands[0]  = player.InBuffer; //just removing the command from the queue now
                commands.Clear();
            }


            if (commands.Count == 0)
            {
                return;
            }

            //maybe this command shouldn't be a character method call...we'll see
            if (commands.Count >= 2 && commands[1].ToLower() == "save")
            {
                player.Player.Save();
                player.MessageHandler("Save succesful!\r\n");

                commandFound = true;
            }

            if (!commandFound && commands[0].Length > 0)
            {
                player.MessageHandler("I don't know what you're trying to do, but that's not going to happen.");
            }

            commands[0] = player.InBuffer;  //remove command from queue
        }
        /// <inheritdoc/>
        public override void VisitObjectMember(object container, ObjectDescriptor containerDescriptor, IMemberDescriptor member, object value)
        {
            // If this member should contains a reference, create it now.
            var containerNode = (IInitializingObjectNode)GetContextNode();
            var guid          = Guid.NewGuid();
            var content       = (MemberContent)ContentFactory.CreateMemberContent(this, guid, containerNode, member, IsPrimitiveType(member.Type), value);

            containerNode.AddMember(content);

            if (content.IsReference)
            {
                referenceContents.Add(content);
            }

            PushContextNode(content);
            if (content.TargetReference == null)
            {
                // For enumerable references, we visit the member to allow VisitCollection or VisitDictionary to enrich correctly the node.
                Visit(content.Value);
            }
            PopContextNode();

            AvailableCommands.Where(x => x.CanAttach(content.Descriptor, (MemberDescriptorBase)member)).ForEach(content.AddCommand);

            content.Seal();
        }
 //ncrunch: no coverage start
 public void ChangeExistingStateInList(string adding, string key)
 {
     foreach (var trigger in AvailableCommands.GetAllTriggers(SelectedCommand))
     {
         CheckWichTriggerTypeToChange(adding, key, trigger);
     }
 }
示例#5
0
        //private PanelCommandFileSystemSecurity command_security = new PanelCommandFileSystemSecurity();

        public DirectoryList(int sort_index, bool sort_reverse, string directory_path)
            : base(sort_index, sort_reverse)
        {
            this.directory_path = directory_path;
            internal_comparer   = new InternalComparer(sort_index, sort_reverse);
            internal_list       = new SortedList <WIN32_FIND_DATA, object>(internal_comparer);

            //set notification
            internal_watcher.IncludeSubdirectories = false;
            internal_watcher.NotifyFilter          =
                NotifyFilters.Attributes |
                NotifyFilters.DirectoryName |
                NotifyFilters.FileName |
                NotifyFilters.Size;
            internal_watcher.Changed += new FileSystemEventHandler(internal_watcher_Changed);
            internal_watcher.Renamed += new RenamedEventHandler(internal_watcher_Renamed);
            internal_watcher.Created += new FileSystemEventHandler(internal_watcher_Created);
            internal_watcher.Deleted += new FileSystemEventHandler(internal_watcher_Deleted);
            internal_watcher.Error   += new ErrorEventHandler(internal_watcher_Error);

            //add panel commands
            AvailableCommands.Add(command_show_afs);
            AvailableCommands.Add(command_touch);
            AvailableCommands.Add(command_attributes);
            AvailableCommands.Add(command_delete);
            AvailableCommands.Add(command_copy);
            AvailableCommands.Add(command_move);
            AvailableCommands.Add(command_create_dir);
            //AvailableCommands.Add(command_browse_streams);
            AvailableCommands.Add(command_fileinfo);
            //AvailableCommands.Add(command_security);
        }
示例#6
0
        /// <inheritdoc/>
        public override void VisitObjectMember(object container, ObjectDescriptor containerDescriptor, IMemberDescriptor member, object value)
        {
            bool shouldProcessReference;

            if (!NotifyNodeConstructing(containerDescriptor, member, out shouldProcessReference))
            {
                return;
            }

            // If this member should contains a reference, create it now.
            GraphNode containerNode = GetContextNode();
            IContent  content       = ContentFactory.CreateMemberContent(this, containerNode.Content, member, IsPrimitiveType(member.Type), value, shouldProcessReference);
            var       node          = (GraphNode)currentNodeFactory(member.Name, content, Guid.NewGuid());

            containerNode.AddChild(node);

            if (content.IsReference)
            {
                referenceContents.Add(content);
            }

            PushContextNode(node);
            if (!(content.Reference is ObjectReference))
            {
                // For enumerable references, we visit the member to allow VisitCollection or VisitDictionary to enrich correctly the node.
                Visit(content.Value);
            }
            PopContextNode();

            AvailableCommands.Where(x => x.CanAttach(node.Content.Descriptor, (MemberDescriptorBase)member)).ForEach(node.AddCommand);
            NotifyNodeConstructed(content);

            node.Seal();
        }
示例#7
0
        /// <inheritdoc/>
        public override void VisitObjectMember(object container, ObjectDescriptor containerDescriptor, IMemberDescriptor member, object value)
        {
            if (!NotifyNodeConstructing(containerDescriptor, member))
            {
                return;
            }

            // If this member should contains a reference, create it now.
            IReference      reference      = CreateReferenceForNode(member.Type, value);
            ModelNode       containerNode  = GetContextNode();
            ITypeDescriptor typeDescriptor = TypeDescriptorFactory.Find(member.Type);
            IContent        content        = new MemberContent(containerNode.Content, member, typeDescriptor, IsPrimitiveType(member.Type), reference);
            var             node           = new ModelNode(member.Name, content, Guid.NewGuid());

            containerNode.AddChild(node);

            if (reference != null)
            {
                referenceContents.Add(content);
            }

            if (!(reference is ObjectReference))
            {
                // For enumerable references, we visit the member to allow VisitCollection or VisitDictionary to enrich correctly the node.
                PushContextNode(node);
                Visit(value);
                PopContextNode();
            }

            AvailableCommands.Where(x => x.CanAttach(node.Content.Descriptor, (MemberDescriptorBase)member)).ForEach(node.AddCommand);
            NotifyNodeConstructed(content);

            node.Seal();
        }
示例#8
0
        /// <inheritdoc />
        public override void ExecuteCommand(ICommonSession?session, string command)
        {
            if (string.IsNullOrWhiteSpace(command))
            {
                return;
            }

            // echo the command locally
            WriteLine(null, "> " + command);

            //Commands are processed locally and then sent to the server to be processed there again.
            var args = new List <string>();

            CommandParsing.ParseArguments(command, args);

            var commandName = args[0];

            if (AvailableCommands.ContainsKey(commandName))
            {
                var command1 = AvailableCommands[commandName];
                args.RemoveAt(0);
                var shell   = new ConsoleShell(this, null);
                var cmdArgs = args.ToArray();

                AnyCommandExecuted?.Invoke(shell, commandName, command, cmdArgs);
                command1.Execute(shell, command, cmdArgs);
            }
            else
            {
                WriteError(null, "Unknown command: " + commandName);
            }
        }
示例#9
0
        public FileCollectionBase(int sort_criteria_index, bool sort_reverse)
        {
            sort_current      = sort_criteria_index;
            this.sort_reverse = sort_reverse;

            AvailableCommands.Add(command_add_short);
            AvailableCommands.Add(command_add_long);
        }
        /// <inheritdoc />
        public void Reset()
        {
            AvailableCommands.Clear();
            _requestedCommands    = false;
            NetManager.Connected += OnNetworkConnected;

            LoadConsoleCommands();
            SendServerCommandRequest();
        }
示例#11
0
        public ProcessList(int sort_index, bool sort_reverse, string computer_name)
            : base(sort_index, sort_reverse)
        {
            internal_comparer = new InternalComparer(sort_index, sort_reverse);
            intern_list       = new List <Process>();
            comp_name         = computer_name;

            AvailableCommands.Add(cmd_process_info);
            AvailableCommands.Add(cmd_terminate);
        }
 public CommerceState()
     : base()
 {
     AvailableCommands.Add("go", new MoveCommand());
     AvailableCommands.Add("buy", new BuyCommand());
     AvailableCommands.Add("sell", new SellCommand());
     AvailableCommands.Add("move", new MoveCommand());
     AvailableCommands.Add("look", new LookCommand());
     AvailableCommands.Add("list", new ListItemCommand());
 }
 public void AssignKey(Keys k, ICommand command)
 {
     if (AvailableCommands.Contains(command))
     {
         AssignedCommands[k] = command;
     }
     else
     {
         throw new CommandUnavailableException();
     }
 }
示例#14
0
        public void ChangeExistingKeyInList(string adding, string removing)
        {
            if (ListAlreadyHasTrigger(adding))
            {
                return;
            }

            foreach (var trigger in AvailableCommands.GetAllTriggers(SelectedCommand))
            {
                CheckWichTriggerToChange(adding, removing, trigger);
            }
        }
示例#15
0
        /// <inheritdoc/>
        public override void VisitObject(object obj, ObjectDescriptor descriptor, bool visitMembers)
        {
            ITypeDescriptor currentDescriptor = descriptor;

            bool isRootNode = contextStack.Count == 0;

            if (isRootNode)
            {
                bool shouldProcessReference;
                if (!NotifyNodeConstructing(descriptor, out shouldProcessReference))
                {
                    return;
                }

                // If we are in the case of a collection of collections, we might have a root node that is actually an enumerable reference
                // This would be the case for each collection within the base collection.
                IContent content = descriptor.Type.IsStruct() ? ContentFactory.CreateBoxedContent(this, obj, descriptor, IsPrimitiveType(descriptor.Type))
                                                : ContentFactory.CreateObjectContent(this, obj, descriptor, IsPrimitiveType(descriptor.Type), shouldProcessReference);
                currentDescriptor = content.Descriptor;
                rootNode          = (GraphNode)currentNodeFactory(currentDescriptor.Type.Name, content, rootGuid);
                if (content.IsReference && currentDescriptor.Type.IsStruct())
                {
                    throw new QuantumConsistencyException("A collection type", "A structure type", rootNode);
                }

                if (content.IsReference)
                {
                    referenceContents.Add(content);
                }

                AvailableCommands.Where(x => x.CanAttach(currentDescriptor, null)).ForEach(rootNode.AddCommand);
                NotifyNodeConstructed(content);

                if (obj == null)
                {
                    rootNode.Seal();
                    return;
                }
                PushContextNode(rootNode);
            }

            if (!IsPrimitiveType(currentDescriptor.Type))
            {
                base.VisitObject(obj, descriptor, true);
            }

            if (isRootNode)
            {
                PopContextNode();
                rootNode.Seal();
            }
        }
示例#16
0
        public HelpViewModel(IEnumerable <Framework.ModuleBase> modules)
        {
            CommandText = string.Empty;
            _modules    = new List <Framework.ModuleBase>(modules);

            AvailableCommands = modules
                                .Select(module => module.ModuleCommand)
                                .ToList();

            AvailableCommands.Add(back);

            SelectedIndex = 0;
        }
示例#17
0
        public FtpDirectoryList(int sort_criteria, bool sort_reverse, FtpConnection connection)
            : base(sort_criteria, sort_reverse)
        {
            internal_comparer       = new InternalComparer(sort_criteria, sort_reverse);
            internal_list           = new SortedList <FtpEntryInfo, object>(internal_comparer);
            internal_conection      = connection;
            internal_directory_path = string.Empty;

            AvailableCommands.Add(command_download);
            AvailableCommands.Add(command_delete);
            AvailableCommands.Add(command_create_dir);

            internal_conection.ForceUpdate += new EventHandler(internal_conection_ForceUpdate);
        }
示例#18
0
        /// <inheritdoc/>
        public override void VisitObject(object obj, ObjectDescriptor descriptor, bool visitMembers)
        {
            bool isRootNode = contextStack.Count == 0;

            if (isRootNode)
            {
                if (!NotifyNodeConstructing(descriptor))
                {
                    return;
                }

                // If we are in the case of a collection of collections, we might have a root node that is actually an enumerable reference
                // This would be the case for each collection within the base collection.
                IReference reference = CreateReferenceForNode(descriptor.Type, obj);
                reference = reference is ReferenceEnumerable ? reference : null;
                IContent content = descriptor.Type.IsStruct() ? new BoxedContent(obj, descriptor, IsPrimitiveType(descriptor.Type)) : new ObjectContent(obj, descriptor, IsPrimitiveType(descriptor.Type), reference);
                rootNode = new ModelNode(descriptor.Type.Name, content, rootGuid);
                if (reference != null && descriptor.Type.IsStruct())
                {
                    throw new QuantumConsistencyException("A collection type", "A structure type", rootNode);
                }

                if (reference != null)
                {
                    referenceContents.Add(content);
                }

                AvailableCommands.Where(x => x.CanAttach(rootNode.Content.Descriptor, null)).ForEach(rootNode.AddCommand);
                NotifyNodeConstructed(content);

                if (obj == null)
                {
                    rootNode.Seal();
                    return;
                }
                PushContextNode(rootNode);
            }

            if (!IsPrimitiveType(descriptor.Type))
            {
                base.VisitObject(obj, descriptor, true);
            }

            if (isRootNode)
            {
                PopContextNode();
                rootNode.Seal();
            }
        }
示例#19
0
        private void ExecuteInShell(IConsoleShell shell, string command)
        {
            try
            {
                var args = new List <string>();
                CommandParsing.ParseArguments(command, args);

                // missing cmdName
                if (args.Count == 0)
                {
                    return;
                }

                string?cmdName = args[0];

                if (AvailableCommands.TryGetValue(cmdName, out var conCmd)) // command registered
                {
                    args.RemoveAt(0);
                    var cmdArgs = args.ToArray();
                    if (shell.Player != null)                                                   // remote client
                    {
                        if (_groupController.CanCommand((IPlayerSession)shell.Player, cmdName)) // client has permission
                        {
                            AnyCommandExecuted?.Invoke(shell, cmdName, command, cmdArgs);
                            conCmd.Execute(shell, command, cmdArgs);
                        }
                        else
                        {
                            shell.WriteError($"Unknown command: '{cmdName}'");
                        }
                    }
                    else // system console
                    {
                        AnyCommandExecuted?.Invoke(shell, cmdName, command, cmdArgs);
                        conCmd.Execute(shell, command, cmdArgs);
                    }
                }
                else
                {
                    shell.WriteError($"Unknown command: '{cmdName}'");
                }
            }
            catch (Exception e)
            {
                LogManager.GetSawmill(SawmillName).Error($"{FormatPlayerString(shell.Player)}: ExecuteError - {command}:\n{e}");
                shell.WriteError($"There was an error while executing the command: {e}");
            }
        }
示例#20
0
        /// <summary>
        /// Assign A button to a command
        /// </summary>
        /// <param name="b">Button to assign</param>
        /// <param name="command">ICommand button is assigned to</param>
        public void AssignButton(Buttons b, ICommand command)
        {
            if (StickOneDown == command || StickOneUp == command || StickOneLeft == command || StickOneRight == command ||
                StickTwoDown == command || StickTwoUp == command || StickTwoLeft == command || StickTwoRight == command)
            {
                throw new UnchangeableCommandException();
            }

            if (AvailableCommands.Contains(command))
            {
                AssignedCommands[b] = command;
            }
            else
            {
                throw new CommandUnavailableException();
            }
        }
示例#21
0
        public ZipDirectory(string file_name, int sort_criteria, bool reverse)
            : base(sort_criteria, reverse)
        {
            zip_file_name   = file_name;
            zip_virtual_dir = string.Empty;
            if (zip_file == null)
            {
                zip_file = new ZipFile(zip_file_name);
                zip_file.KeysRequired = new ZipFile.KeysRequiredEventHandler(keys_required_callback);
            }
            internal_comparer = new InternalComparer(sort_criteria, reverse, zip_file);
            internal_list     = new SortedList <string, object>(internal_comparer);

            AvailableCommands.Add(command_extract);
            AvailableCommands.Add(command_create_dir);
            AvailableCommands.Add(command_del);
        }
示例#22
0
        private void HandleConCmdReg(MsgConCmdReg msg)
        {
            foreach (var cmd in msg.Commands)
            {
                string?commandName = cmd.Name;

                // Do not do duplicate commands.
                if (AvailableCommands.ContainsKey(commandName))
                {
                    Logger.DebugS("console", $"Server sent console command {commandName}, but we already have one with the same name. Ignoring.");
                    continue;
                }

                var command = new ServerDummyCommand(commandName, cmd.Help, cmd.Description);
                AvailableCommands[commandName] = command;
            }
        }
        /// <inheritdoc/>
        public override void VisitObject(object obj, ObjectDescriptor descriptor, bool visitMembers)
        {
            ITypeDescriptor currentDescriptor = descriptor;

            bool isRootNode = contextStack.Count == 0;

            if (isRootNode)
            {
                // If we're visiting a value type as "object" we need to use a special "boxed" node.
                var content = descriptor.Type.IsValueType ? ContentFactory.CreateBoxedContent(this, rootGuid, obj, descriptor, IsPrimitiveType(descriptor.Type))
                    : ContentFactory.CreateObjectContent(this, rootGuid, obj, descriptor, IsPrimitiveType(descriptor.Type));

                currentDescriptor = content.Descriptor;
                rootNode          = (IInitializingObjectNode)content;
                if (content.IsReference && currentDescriptor.Type.IsStruct())
                {
                    throw new QuantumConsistencyException("A collection type", "A structure type", rootNode);
                }

                if (content.IsReference)
                {
                    referenceContents.Add(content);
                }

                AvailableCommands.Where(x => x.CanAttach(currentDescriptor, null)).ForEach(rootNode.AddCommand);

                if (obj == null)
                {
                    rootNode.Seal();
                    return;
                }
                PushContextNode(rootNode);
            }

            if (!IsPrimitiveType(currentDescriptor.Type))
            {
                base.VisitObject(obj, descriptor, true);
            }

            if (isRootNode)
            {
                PopContextNode();
                rootNode.Seal();
            }
        }
 public MovementState() : base()
 {
     AvailableCommands.Add("go", new MoveCommand());
     AvailableCommands.Add("move", new MoveCommand());
     AvailableCommands.Add("quit", new QuitCommand());
     AvailableCommands.Add("look", new LookCommand());
     AvailableCommands.Add("unlock", new UnlockCommand());
     AvailableCommands.Add("attack", new AttackCommand());
     AvailableCommands.Add("list", new ListItemCommand());
     AvailableCommands.Add("inventory", new ListItemCommand());
     AvailableCommands.Add("grab", new PickUpCommand());
     AvailableCommands.Add("get", new PickUpCommand());
     AvailableCommands.Add("pickup", new PickUpCommand());
     AvailableCommands.Add("drop", new DropCommand());
     AvailableCommands.Add("flee", new FleeCommand());
     AvailableCommands.Add("equip", new EquipCommand());
     AvailableCommands.Add("unequip", new UnequipCommand());
 }
示例#25
0
        /// <inheritdoc />
        public override void ExecuteCommand(ICommonSession?session, string command)
        {
            if (string.IsNullOrWhiteSpace(command))
            {
                return;
            }

            // echo the command locally
            WriteLine(null, "> " + command);

            //Commands are processed locally and then sent to the server to be processed there again.
            var args = new List <string>();

            CommandParsing.ParseArguments(command, args);

            var commandName = args[0];

            if (AvailableCommands.ContainsKey(commandName))
            {
                var playerManager = IoCManager.Resolve <IPlayerManager>();
#if !DEBUG
                if (!_conGroup.CanCommand(commandName) && playerManager.LocalPlayer?.Session.Status > SessionStatus.Connecting)
                {
                    WriteError(null, $"Insufficient perms for command: {commandName}");
                    return;
                }
#endif
                var command1 = AvailableCommands[commandName];
                args.RemoveAt(0);
                var shell   = new ConsoleShell(this, null);
                var cmdArgs = args.ToArray();

                AnyCommandExecuted?.Invoke(shell, commandName, command, cmdArgs);
                command1.Execute(shell, command, cmdArgs);
            }
            else
            {
                WriteError(null, "Unknown command: " + commandName);
            }
        }
        /// <summary>
        /// Adds a command to the configured commands. This properly initializes the class, subscribes to the command topic and writes it to the config file.
        /// </summary>
        /// <param name="commandType"></param>
        /// <param name="json"></param>
        public void AddCommand(AvailableCommands commandType, string json)
        {
            var serializerOptions = new JsonSerializerOptions
            {
                Converters = { new DynamicJsonConverter() }
            };
            dynamic model = JsonSerializer.Deserialize <dynamic>(json, serializerOptions);

            AbstractCommand commandToCreate = null;

            switch (commandType)
            {
            case AvailableCommands.ShutdownCommand:
                commandToCreate = new ShutdownCommand(this._publisher, model.Name);
                break;

            case AvailableCommands.RestartCommand:
                commandToCreate = new RestartCommand(this._publisher, model.Name);
                break;

            case AvailableCommands.LogOffCommand:
                commandToCreate = new LogOffCommand(this._publisher, model.Name);
                break;

            case AvailableCommands.CustomCommand:
                commandToCreate = new CustomCommand(this._publisher, model.Command, model.Name);
                break;

            default:
                Log.Logger.Error("Unknown sensortype");
                break;
            }
            if (commandToCreate != null)
            {
                this._configurationService.AddConfiguredCommand(commandToCreate);
            }
        }
示例#27
0
    //add SlotScript

    // Use this for initialization
    void Start()
    {
        if (Net = FindObjectOfType <NetConnection>())
        {
            Net.transform.SetParent(FindObjectOfType <Canvas>().transform);
            ////Net.Sender("ARRRRRRR");
            Net.gameObject.SetActive(true);
            Debug.Log(Net);
            ObserverMode = Net.observerMode;
        }
        builderInterface   = FindObjectOfType <BuilderInterface>();
        telega             = FindObjectOfType <TelegaManager>();
        FanucSettingsPanel = FindObjectOfType <CommandFanucUI>();
        FanucSettingsPanel.gameObject.SetActive(false);
        CameraSettingsPanel = FindObjectOfType <CommandCameraUI>();
        CameraSettingsPanel.gameObject.SetActive(false);
        TelegaSettingsPanel = FindObjectOfType <CommandTelegaUI>();
        TelegaSettingsPanel.gameObject.SetActive(false);
        avalaibleCommands = FindObjectOfType <AvailableCommands>();
        Pull           = FindObjectOfType <PullManager>();
        ScenarioEditor = GameObject.Find("ScenarioEditor");
        ScenarioEditor.SetActive(false);
        dropdownSceneObjects = FindObjectOfType <DropdownSceneObjects>();
        dropdownSceneObjects.gameObject.SetActive(false);
        fanuc = FindObjectOfType <FanucScript>();
        SceneSynchronization = FindObjectOfType <InstantiateFromCam>();

        telega.telega.Type = telegaScript.MoveType.RotateBarsAndMove;
        if (ObserverMode)
        {
            CloseAllUI();
            UserControlLock    = true;
            fanuc.mode         = 0;
            telega.telega.Type = telegaScript.MoveType.RotateBarsAndMove;
        }
    }
示例#28
0
        public void Invoke(string[] args)
        {
            bool   showHelp    = false;
            string newAlias    = null;
            string deleteAlias = null;

            var options = new OptionSet();

            options.Add(
                "?|help",
                "Show help information.",
                x => showHelp = x != null
                );
            options.Add(
                "n|new=",
                "Create a new {alias}.",
                x => newAlias = x
                );
            options.Add(
                "d|delete=",
                "Delete an existing {alias}.",
                x => deleteAlias = x
                );

            if (args == null)
            {
                CommandResult.WriteLine(DisplayTemplates.InvalidArguments);
            }
            else
            {
                try
                {
                    var parsedArgs = options.Parse(args).ToArray();

                    if (parsedArgs.Length == args.Length)
                    {
                        CommandResult.WriteLine(DisplayTemplates.InvalidArguments);
                    }
                    else
                    {
                        if (showHelp)
                        {
                            HelpUtility.WriteHelpInformation(this, options);
                        }
                        else if (newAlias != null)
                        {
                            if (!newAlias.Is("HELP") && !AvailableCommands.Any(x => x.Name.Is(newAlias)))
                            {
                                var alias = _dataBucket.AliasRepository.GetAlias(CommandResult.CurrentUser.Username, newAlias);
                                if (alias == null)
                                {
                                    if (CommandResult.CommandContext.PromptData == null)
                                    {
                                        CommandResult.WriteLine("Type the value that should be sent to the terminal when you use your new alias.");
                                        CommandResult.SetPrompt(Name, args, string.Format("{0} VALUE", newAlias.ToUpper()));
                                    }
                                    else if (CommandResult.CommandContext.PromptData.Length == 1)
                                    {
                                        _dataBucket.AliasRepository.AddAlias(new Alias
                                        {
                                            Username = CommandResult.CurrentUser.Username,
                                            Shortcut = newAlias,
                                            Command  = CommandResult.CommandContext.PromptData[0]
                                        });
                                        _dataBucket.SaveChanges();
                                        CommandResult.WriteLine("Alias '{0}' was successfully defined.", newAlias.ToUpper());
                                        CommandResult.RestoreContext();
                                    }
                                }
                                else
                                {
                                    CommandResult.WriteLine("You have already defined an alias named '{0}'.", newAlias.ToUpper());
                                }
                            }
                            else
                            {
                                CommandResult.WriteLine("'{0}' is an existing command. You cannot create aliases with the same name as existing commands.", newAlias.ToUpper());
                            }
                        }
                        else if (deleteAlias != null)
                        {
                            var alias = _dataBucket.AliasRepository.GetAlias(CommandResult.CurrentUser.Username, deleteAlias);
                            if (alias != null)
                            {
                                _dataBucket.AliasRepository.DeleteAlias(alias);
                                _dataBucket.SaveChanges();
                                CommandResult.WriteLine("Alias '{0}' was successfully deleted.", deleteAlias.ToUpper());
                            }
                            else
                            {
                                CommandResult.WriteLine("You have not defined an alias named '{0}'.", deleteAlias.ToUpper());
                            }
                        }
                    }
                }
                catch (OptionException ex)
                {
                    CommandResult.WriteLine(ex.Message);
                }
            }
        }
示例#29
0
 /// <summary>
 /// Initializes an instance of ConsoleCommandFinder class.
 /// </summary>
 public ConsoleCommandFinder()
 {
     AvailableCommands.AddRange(GetCommandsFromMainAssembly());
     AvailableCommands.AddRange(GetCommandsFromReferencedAssemblies());
 }
示例#30
0
        public void Invoke(string[] args)
        {
            bool showHelp  = false;
            bool newTopic  = false;
            bool modTopic  = false;
            bool refresh   = false;
            bool?lockBoard = null;

            var options = new OptionSet();

            options.Add(
                "?|help",
                "Show help information.",
                x => showHelp = x != null
                );
            options.Add(
                "R|refresh",
                "Refresh the current board.",
                x => refresh = x != null
                );
            if (CommandResult.IsUserLoggedIn)
            {
                options.Add(
                    "nt|newTopic",
                    "Create new topic on the specified board.",
                    x => newTopic = x != null
                    );
            }
            if (CommandResult.UserLoggedAndModOrAdmin())
            {
                options.Add(
                    "mt|modTopic",
                    "Create a topic that only moderators can see.",
                    x =>
                {
                    newTopic = x != null;
                    modTopic = x != null;
                }
                    );
            }
            if (CommandResult.UserLoggedAndAdmin())
            {
                options.Add(
                    "l|lock",
                    "Lock the board to prevent creation of topics.",
                    x => lockBoard = x != null
                    );
            }

            if (args == null)
            {
                CommandResult.WriteLine(DisplayTemplates.InvalidArguments);
            }
            else
            {
                try
                {
                    var parsedArgs = options.Parse(args).ToArray();

                    if (parsedArgs.Length == args.Length)
                    {
                        if (parsedArgs.Length == 1)
                        {
                            if (parsedArgs[0].IsShort())
                            {
                                var boardId = parsedArgs[0].ToShort();
                                var page    = 1;
                                WriteTopics(boardId, page);
                            }
                            else
                            {
                                CommandResult.WriteLine("'{0}' is not a valid board ID.", parsedArgs[0]);
                            }
                        }
                        else if (parsedArgs.Length == 2)
                        {
                            if (parsedArgs[0].IsShort())
                            {
                                var boardId = parsedArgs[0].ToShort();
                                if (parsedArgs[1].IsInt())
                                {
                                    var page = parsedArgs[1].ToInt();
                                    WriteTopics(boardId, page);
                                }
                                else if (PagingUtility.Shortcuts.Any(x => parsedArgs[1].Is(x)))
                                {
                                    var page = PagingUtility.TranslateShortcut(parsedArgs[1], CommandResult.CommandContext.CurrentPage);
                                    WriteTopics(boardId, page);
                                    if (parsedArgs[1].Is("last") || parsedArgs[1].Is("prev"))
                                    {
                                        CommandResult.ScrollToBottom = false;
                                    }
                                }
                                else
                                {
                                    CommandResult.WriteLine("'{0}' is not a valid page number.", parsedArgs[1]);
                                }
                            }
                            else
                            {
                                CommandResult.WriteLine("'{0}' is not a valid board ID.", parsedArgs[0]);
                            }
                        }
                        else
                        {
                            CommandResult.WriteLine(DisplayTemplates.InvalidArguments);
                        }
                    }
                    else
                    {
                        if (showHelp)
                        {
                            HelpUtility.WriteHelpInformation(this, options);
                        }
                        else if (newTopic)
                        {
                            if (parsedArgs.Length >= 1)
                            {
                                if (parsedArgs[0].IsShort())
                                {
                                    var boardId = parsedArgs[0].ToShort();
                                    var board   = _dataBucket.BoardRepository.GetBoard(boardId);
                                    if (board != null)
                                    {
                                        if (!board.Locked || CommandResult.CurrentUser.IsModeratorOrAdministrator())
                                        {
                                            if (!board.ModsOnly || CommandResult.CurrentUser.IsModeratorOrAdministrator())
                                            {
                                                if (CommandResult.CommandContext.PromptData == null)
                                                {
                                                    CommandResult.WriteLine("Create a title for your topic.");
                                                    CommandResult.SetPrompt(Name, args, string.Format("{0} NEW TOPIC Title", boardId));
                                                }
                                                else if (CommandResult.CommandContext.PromptData.Length == 1)
                                                {
                                                    CommandResult.WriteLine("Create the body for your topic.");
                                                    CommandResult.SetPrompt(Name, args, string.Format("{0} NEW TOPIC Body", boardId));
                                                }
                                                else if (CommandResult.CommandContext.PromptData.Length == 2)
                                                {
                                                    var topic = new Topic
                                                    {
                                                        BoardID = boardId,
                                                        Title   = CommandResult.CommandContext.PromptData[0],
                                                        Body    = BBCodeUtility.SimplifyComplexTags(
                                                            CommandResult.CommandContext.PromptData[1],
                                                            _dataBucket.ReplyRepository,
                                                            CommandResult.CurrentUser.IsModeratorOrAdministrator()
                                                            ),
                                                        Username   = CommandResult.CurrentUser.Username,
                                                        PostedDate = DateTime.UtcNow,
                                                        LastEdit   = DateTime.UtcNow,
                                                        ModsOnly   = modTopic && !board.ModsOnly
                                                    };
                                                    _dataBucket.TopicRepository.AddTopic(topic);
                                                    _dataBucket.SaveChanges();
                                                    CommandResult.RestoreContext();
                                                    var TOPIC = AvailableCommands.SingleOrDefault(x => x.Name.Is("TOPIC"));
                                                    TOPIC.Invoke(new string[] { topic.TopicID.ToString() });
                                                    CommandResult.WriteLine("New topic succesfully posted.");
                                                }
                                            }
                                            else
                                            {
                                                CommandResult.WriteLine("Board '{0}' is for moderators only.", boardId);
                                            }
                                        }
                                        else
                                        {
                                            CommandResult.WriteLine("Board '{0}' is locked. You cannot create topics on this board.", boardId);
                                        }
                                    }
                                    else
                                    {
                                        CommandResult.WriteLine("There is no board with ID '{0}'.", boardId);
                                    }
                                }
                                else
                                {
                                    CommandResult.WriteLine("'{0}' is not a valid board ID.", parsedArgs[0]);
                                }
                            }
                            else
                            {
                                CommandResult.WriteLine("You must supply a board ID.");
                            }
                        }
                        else
                        {
                            if (lockBoard != null)
                            {
                                if (parsedArgs.Length > 0)
                                {
                                    if (parsedArgs[0].IsShort())
                                    {
                                        var boardId = parsedArgs[0].ToShort();
                                        var board   = _dataBucket.BoardRepository.GetBoard(boardId);
                                        if (board != null)
                                        {
                                            board.Locked = (bool)lockBoard;
                                            _dataBucket.BoardRepository.UpdateBoard(board);
                                            _dataBucket.SaveChanges();
                                            string status = (bool)lockBoard ? "locked" : "unlocked";
                                            CommandResult.WriteLine("Board '{0}' was successfully {1}.", boardId, status);
                                        }
                                        else
                                        {
                                            CommandResult.WriteLine("There is no board with ID '{0}'.", boardId);
                                        }
                                    }
                                    else
                                    {
                                        CommandResult.WriteLine("'{0}' is not a valid board ID.", parsedArgs[0]);
                                    }
                                }
                                else
                                {
                                    CommandResult.WriteLine("You must supply a board ID.");
                                }
                            }
                            if (refresh)
                            {
                                if (parsedArgs.Length > 0)
                                {
                                    if (parsedArgs[0].IsShort())
                                    {
                                        var boardId = parsedArgs[0].ToShort();
                                        WriteTopics(boardId, CommandResult.CommandContext.CurrentPage);
                                    }
                                    else
                                    {
                                        CommandResult.WriteLine("'{0}' is not a valid board ID.", parsedArgs[0]);
                                    }
                                }
                                else
                                {
                                    CommandResult.WriteLine("You must supply a board ID.");
                                }
                            }
                        }
                    }
                }
                catch (OptionException ex)
                {
                    CommandResult.WriteLine(ex.Message);
                }
            }
        }