コード例 #1
0
        public IExecutable ManageCommand(string[] inputArgs)
        {
            IExecutable command = null;

            string commandType = inputArgs[0];

            switch (commandType)
            {
                case "create":
                    command = new CreateCommand(this.Engine, inputArgs[1], int.Parse(inputArgs[2]), int.Parse(inputArgs[3]),
                        (BehaviorTypes)Enum.Parse(typeof(BehaviorTypes), inputArgs[4]), (AttackTypes)Enum.Parse(typeof(AttackTypes), inputArgs[5]));
                    break;
                case "attack":
                    command = new AttackCommand(this.Engine, inputArgs[1], inputArgs[2]);
                    break;
                case "pass":
                    command = new PassCommand();
                    break;
                case "status":
                    command = new StatusCommand(this.Engine);
                    break;
                case "drop":
                    command = new DropCommand();
                    break;
            }

            return command;
        }
コード例 #2
0
        public IExecutable ManageCommand(string[] inputArgs)
        {
            IExecutable command = null;

            string commandType = inputArgs[0];

            switch (commandType)
            {
            case "create":
                command = new CreateCommand(this.Engine, inputArgs[1], int.Parse(inputArgs[2]), int.Parse(inputArgs[3]),
                                            (BehaviorTypes)Enum.Parse(typeof(BehaviorTypes), inputArgs[4]), (AttackTypes)Enum.Parse(typeof(AttackTypes), inputArgs[5]));
                break;

            case "attack":
                command = new AttackCommand(this.Engine, inputArgs[1], inputArgs[2]);
                break;

            case "pass":
                command = new PassCommand();
                break;

            case "status":
                command = new StatusCommand(this.Engine);
                break;

            case "drop":
                command = new DropCommand();
                break;
            }

            return(command);
        }
コード例 #3
0
        /// <summary>
        /// Ajouter un Status en base
        /// </summary>
        /// <param name="e">Status à ajouter</param>
        /// <returns></returns>
        public int AddStatus(Status s)
        {
            // TODO : ajouter des contrôles sur le produit (exemple : vérification de champ, etc.)
            StatusCommand sc = new StatusCommand(_context);

            return(sc.Add(s));
        }
コード例 #4
0
        internal GameController(EmailCommand emailService,
                                TimeLeftCommand timerService,
                                InsertCodeCommand codeService,
                                CheckRadioCommand checkRadioCommand,
                                DefragCommand defragCommand,
                                StatusCommand statusCommand,
                                CleanCacheCommand cleanCacheCommand)
        {
            SetupEmailService(emailService);
            _timerService      = timerService;
            _codeService       = codeService;
            _radioService      = checkRadioCommand;
            _defragCommand     = defragCommand;
            _statusCommand     = statusCommand;
            _cleanCacheCommand = cleanCacheCommand;
            _codeService.OnSuccesfullDelayCode += StartTimer;
            DeadHandSettings = new DeadHandSettings()
            {
                MotherboardTemperature      = 80,
                MemoryCacheUsedPercentage   = 20,
                DiskFragmentationPercentage = 10
            };

            _deadHandMaintenanceTimer          = new Timer(_rng.Next(2, 4) * 60 * 1000);
            _deadHandMaintenanceTimer.Elapsed += _deadHandMaintenanceTimer_Elapsed;
            _deadHandMaintenanceTimer.Start();
            _defragCommand.CurrentSettings     = DeadHandSettings;
            _statusCommand.CurrentSettings     = DeadHandSettings;
            _cleanCacheCommand.CurrentSettings = DeadHandSettings;

            CreateTimeline();
        }
コード例 #5
0
        /// <summary>
        /// Modifier un Status en base
        /// </summary>
        /// <param name="e">Status à modifier</param>
        public void UpdateStatus(Status s)
        {
            // TODO : ajouter des contrôles sur le produit (exemple : vérification de champ, etc.)
            StatusCommand sc = new StatusCommand(_context);

            sc.Update(s);
        }
コード例 #6
0
        public BasicMetaCommandResult ProcessResponce(BasicResponce rsp)
        {
            if (_step == 0)
            {
                _step = 1;
                var cmd = new StatusCommand(_degree, 1200);
                return(new BasicMetaCommandResult(MetaCommandAction.Command, cmd));
            }

            if (rsp == null)
            {
                return(new BasicMetaCommandResult(MetaCommandAction.Idle));
            }

            var scanResponce = rsp as StatusResponce;

            if (scanResponce != null)
            {
                _scanResult[scanResponce.Degree] = scanResponce.DistanceToObstacle;
            }

            if (_step == 1 && _degree < MaxDegree)
            {
                _degree += 1;
                var cmd = new StatusCommand(_degree, 50);
                return(new BasicMetaCommandResult(MetaCommandAction.Command, cmd));
            }

            return(new BasicMetaCommandResult(MetaCommandAction.Done));
        }
コード例 #7
0
        public static void Status(StatusCommand o)
        {
            // Check if the status window is already showing.
            foreach (Process existingProcess in Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Where(p => p.Id != Process.GetCurrentProcess().Id))
            {
                // Get the process's command-line args to see if it was run with the "status" flag.
                ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(@"root/cimv2", $"select CommandLine from Win32_Process where ProcessId = '{existingProcess.Id}'");
                foreach (var ws4wInstance in managementObjectSearcher.Get().OfType <ManagementObject>())
                {
                    if (ws4wInstance.GetPropertyValue("CommandLine")?.ToString() is { } commandLine)
                    {
                        int    substringIndex = commandLine.LastIndexOf('"') + 2;
                        string arguments      = substringIndex <= commandLine.Length ? commandLine.Substring(commandLine.LastIndexOf('"') + 2) : string.Empty;
                        if (arguments == typeof(StatusCommand).GetVerb())
                        {
                            SetForegroundWindow(existingProcess.MainWindowHandle);
                            Environment.Exit(0);
                        }
                    }
                }
            }

            // Otherwise, show the status window.
            new ServerStatusPrerequisite().Show();
        }
コード例 #8
0
        private async void buttonStatus_Click(object sender, EventArgs e)
        {
            var cardReader = new XFS4IoTClient.ClientConnection(new Uri($"{textBoxCardReader.Text}"));

            try
            {
                await cardReader.ConnectAsync();
            }
            catch (Exception)
            {
                return;
            }

            var statusCmd = new StatusCommand(Guid.NewGuid().ToString(), new StatusCommand.PayloadData(CommandTimeout));

            textBoxCommand.Text = statusCmd.Serialise();

            await cardReader.SendCommandAsync(statusCmd);

            textBoxResponse.Text = string.Empty;
            textBoxEvent.Text    = string.Empty;

            object cmdResponse = await cardReader.ReceiveMessageAsync();

            if (cmdResponse is StatusCompletion response)
            {
                textBoxResponse.Text = response.Serialise();
                textBoxStDevice.Text = response.Payload.Common.Device.ToString();
                textBoxStMedia.Text  = response.Payload.CardReader.Media.ToString();
            }
        }
コード例 #9
0
        public IExecutable ManageCommand(string inputArgs)
        {
            IExecutable command = null;

            string commandType = inputArgs;

            switch (commandType)
            {
                case "top":
                    command = new StatusCommand(this.Engine);
                    break;
                case "restart":
                    command = new RestartCommand(this.Engine);
                    break;
                case "turn":
                    command = new TurnCommand(this.Engine);
                    break;
                case "exit":
                    command = new EndCommand(this.Engine);
                    break;
                default:
                    this.Engine.Writer.WriteLine("\nError! Invalid command\n");
                    break;
            }

            return command;
        }
コード例 #10
0
        /// <summary>
        /// Create the command object that will be used to act on the repository.
        /// </summary>
        /// <returns>The command object that will be used to act on the
        ///     repository.</returns>
        /// <exception cref="Exception">TODO: Make a more specific exception</exception>
        /// <exception cref="NotImplementedException">If the command argument
        ///     is not implemented currently.  TODO: Implement the argument.</exception>
        public override ICommand CreateCommand()
        {
            DirectoryInfo dir =
                new DirectoryInfo(Path.Combine(Directory.GetCurrentDirectory(), "CVS"));
            StatusCommand statusCommand;

            this.localDirectory = Directory.GetCurrentDirectory();

            try {
                this.repository = Repository.Load(dir).FileContents;
                this.CvsRoot    = new CvsRoot(Root.Load(dir).FileContents);
            } catch (NullReferenceException) {
                this.InvalidRepository();
            } catch (CvsFileNotFoundException) {
                this.InvalidRepository();
            } catch (ICSharpCode.SharpCvsLib.Exceptions.CvsRootParseException) {
                this.InvalidRepository();
            }

            CurrentWorkingDirectory = new WorkingDirectory(this.CvsRoot,
                                                           localDirectory, this.repository);

            // Create new command object
            statusCommand         = new StatusCommand(CurrentWorkingDirectory);
            statusCommand.Folders = this.GetCurrentDirectory(new DirectoryInfo(localDirectory));
            this.ParseOptions(statusCommand, this.Args);

            return(statusCommand);
        }
コード例 #11
0
ファイル: BaseState.cs プロジェクト: fudanyi/MSGorilla
 public virtual void ProcessStatusCommand(StatusCommand cmd)
 {
     this.Session.AppendResponse(
         new ServerStatusResponse(cmd.Tag,
                                  ServerStatusResponseType.NO,
                                  "STATUS State Error")
         );
 }
コード例 #12
0
		public virtual void RetrieveServerStatus()
		{
			var command = new StatusCommand(_connection);
			command.Execute();
			Assert.IsTrue(command.Result.Success);
            Assert.IsTrue(command.Result.StatusInfo.Count > 0);
            Assert.IsNotNull(command.Result.StatusInfo[0].Name);
            Assert.IsNotNull(command.Result.StatusInfo[0].Value);
        }
コード例 #13
0
        private List <string> SensorCommands(int sensorId)
        {
            var commands = new List <string>();

            commands.Add(StreamReadingsCommand.Create(15000));
            commands.Add(SleepCommand.Create(1000));
            commands.Add(StatusCommand.Create());

            return(commands);
        }
コード例 #14
0
        public virtual void RetrieveServerStatus()
        {
            var command = new StatusCommand(_connection);

            command.Execute();
            Assert.IsTrue(command.Result.Success);
            Assert.IsTrue(command.Result.StatusInfo.Count > 0);
            Assert.IsNotNull(command.Result.StatusInfo[0].Name);
            Assert.IsNotNull(command.Result.StatusInfo[0].Value);
        }
コード例 #15
0
        public void Create()
        {
            var log    = A.Fake <ILogger>();
            var radio  = A.Fake <IRadio>();
            var output = A.Fake <Action <string> >();

            var command = new StatusCommand(log, output, radio);

            Assert.NotNull(command);
        }
コード例 #16
0
        public void CheckName()
        {
            var log    = A.Fake <ILogger>();
            var radio  = A.Fake <IRadio>();
            var output = A.Fake <Action <string> >();

            var command = new StatusCommand(log, output, radio);

            Assert.Contains(string.Empty, command.Name);
            Assert.Contains("Show status of radio", command.Description);
        }
コード例 #17
0
 public void senMessenger(StatusCommand command)
 {
     if (IO_COM_Port.IsOpen)
     {
         IO_COM_Port.WriteLine(command.ToString());
     }
     else
     {
         Global.ICOP_messenger("Serial port is not connected.");
     }
 }
コード例 #18
0
        public void Refresh()
        {
            var command = new StatusCommand();

            foreach (var portState in this.PortState.Values)
            {
                var output       = Wrapper.Run(command.Arguments(portState.Port));
                var statusOutput = command.Parse(output);

                PortState[portState.Port].Enabled = statusOutput.Enabled;
            }
        }
コード例 #19
0
        public async Task Execute()
        {
            var log    = A.Fake <ILogger>();
            var radio  = A.Fake <IRadio>();
            var output = A.Fake <Action <string> >();

            var command = new StatusCommand(log, output, radio);

            var result = await command.Execute(new string[0]);

            A.CallTo(() => radio.Status()).MustHaveHappened();
            Assert.Equal(CommandResult.OK, result);
        }
コード例 #20
0
        public string ExecuteCommand(string commandArguments)
        {
            var commandName = commandArguments.Substring(0, commandArguments.IndexOf(' '));

            var commandParameters = new JavaScriptSerializer()
                .Deserialize<Dictionary<string, string>>(
                    commandArguments.Substring(commandArguments.IndexOf(' ') + 1));

            if (commandName != "SetupPark" && this.VehiclePark == null)
            {
                return "The vehicle park has not been set up";
            }

            ICommand command = null;
            switch (commandName)
            {
                case "SetupPark":
                    command = new SetupParkCommand(commandName, commandParameters, this.VehiclePark);
                    break;
                case "Park":
                    command = new ParkCommand(commandName, commandParameters, this.VehiclePark);
                    break;
                case "Exit":
                    command = new ExitCommand(commandName, commandParameters, this.VehiclePark);
                    break;
                case "Status":
                    command = new StatusCommand(commandName, commandParameters, this.VehiclePark);
                    break;
                case "FindVehicle":
                    command = new FindVehicleCommand(commandName, commandParameters, this.VehiclePark);
                    break;
                case "VehiclesByOwner":
                    command = new VehiclesByOwner(commandName, commandParameters, this.VehiclePark);
                    break;
                default:
                    throw new InvalidOperationException("Invalid command.");
            }

            var commandOutput = string.Empty;
            if (commandName == "SetupPark")
            {
                this.VehiclePark = command.Execute() as IVehiclePark;
                commandOutput = "Vehicle park created";
            }
            else
            {
                commandOutput = command.Execute() as string;
            }

            return commandOutput;
        }
コード例 #21
0
        public async Task <int> Execute(string[] args)
        {
            var rootCommand = new RootCommand("Party: A Virt-A-Mate package manager")
            {
                HelpCommand.CreateCommand(_renderer, _config, _controllerFactory),
                SearchCommand.CreateCommand(_renderer, _config, _controllerFactory),
                GetCommand.CreateCommand(_renderer, _config, _controllerFactory),
                ShowCommand.CreateCommand(_renderer, _config, _controllerFactory),
                StatusCommand.CreateCommand(_renderer, _config, _controllerFactory),
                UpgradeCommand.CreateCommand(_renderer, _config, _controllerFactory),
                PublishCommand.CreateCommand(_renderer, _config, _controllerFactory),
                CleanCommand.CreateCommand(_renderer, _config, _controllerFactory),
            };

            // For CoreRT:
            rootCommand.Name = Path.GetFileName(Environment.GetCommandLineArgs().FirstOrDefault()) ?? "party.exe";

            Exception exc    = null;
            var       parser = new CommandLineBuilder(rootCommand)
                               .UseVersionOption()
                               .UseHelp()
#if DEBUG
                               .UseParseDirective()
                               .UseDebugDirective()
#endif
                               .UseSuggestDirective()
                               // .RegisterWithDotnetSuggest()
                               .UseTypoCorrections()
                               .UseParseErrorReporting()
                               .UseExceptionHandler((e, ctx) => exc = e)
                               .CancelOnProcessTermination()
                               .Build();

            _renderer.WriteLine("Party, a Virt-A-Mate package manager, is still in it's early stages. Please file any issue or ideas at https://github.com/vam-community/vam-party/issues", ConsoleColor.Green);

            try
            {
                await parser.InvokeAsync(args, _renderer);
            }
            catch (Exception e)
            {
                exc = e;
            }

            if (exc != null)
            {
                return(HandleError(exc));
            }

            return(0);
        }
コード例 #22
0
        /// <summary>
        /// Parse the command line options/ arguments and populate the command
        ///     object with the arguments.
        /// </summary>
        /// <param name="upOptions">A string value that holds the command
        ///     line options the user has selected.</param>
        /// <exception cref="NotImplementedException">If the command argument
        ///     is not implemented currently.  TODO: Implement the argument.</exception>
        private void ParseOptions(StatusCommand command, string[] options)
        {
            int currentOptionIndex = 0;

            while (currentOptionIndex < options.Length)
            {
                string currentOption = options[currentOptionIndex];
                switch (currentOption)
                {
                case "-v":
                    command.Verbose = true;
                    break;

                case "-l":
                    command.LocalOnly = true;
                    break;

                case "-R":
                    command.Recursive = true;
                    break;

                case "-q":
                    command.Terse = true;
                    break;

                case "-x":
                    command.CvsNt2Output = true;
                    break;

                case "-X":
                    command.Cvs1Output = true;
                    break;

                default:
                    // if a switch is passed in that we don't know about
                    //  then throw an exception
                    if (currentOption.StartsWith("-"))
                    {
                        throw new NotSupportedException(
                                  string.Format("Unknown option specified: {0}", currentOption));
                    }
                    // otherwise the parameter is probably a file or module name, ignore
                    break;
                }
            }

            this.ParseFiles(options);
        }
コード例 #23
0
        public void Execute_ShouldReturn_Success_WhenTraverseDependencies_Succeeds()
        {
            var algorithm = Container.Resolve <IDependencyVisitorAlgorithm>();

            algorithm.Arrange(a => a.TraverseDependencies(Arg.IsAny <IVisitor>(), Arg.AnyString))
            .DoInstead((IVisitor visitor, string directory) =>
            {
                visitor.ReturnCode = ReturnCode.Success;
            });

            var options  = new StatusSubOptions();
            var instance = new StatusCommand(options);
            var code     = instance.Execute();

            Assert.AreEqual(ReturnCode.Success, code, "Invalid Return Code");
        }
コード例 #24
0
        public void StatusCommandTest()
        {
            GameObject mockGo = new GameObject();

            Locator.Scheduler = mockGo.AddComponent <TurnScheduler>();
            Entity actor = new Entity(new Status())
            {
                Name = "TEST_ENTITY"
            };
            StatusDefinition momentum = StatusDefinition.statuses["Status_Momentum"];
            StatusCommand    cmd      = new StatusCommand(null, actor, momentum, 300, 1);
            CommandResult    result   = cmd.Execute();

            Assert.True(Status.IsAffectedBy(actor, momentum));
            Assert.True(result == CommandResult.Succeeded);
        }
コード例 #25
0
ファイル: BlobEngine.cs プロジェクト: bobosam/CSharpOOP
        public void Run()
        {
            IExecutable command = null;
            string line = reader.ReadLine();
            while (line != "drop")
            {
                string[] tokens = line.Split();

                switch (tokens[0])
                {
                    case "create":
                        command = new CreateCommand(
                            db,
                            tokens[1],
                            int.Parse(tokens[2]),
                            int.Parse(tokens[3]),
                            tokens[4],
                            tokens[5]);
                        break;
                    case "pass":
                        command = new PassCommand(db);
                        break;
                    case "status":
                        command = new StatusCommand(db);
                        break;
                    case "attack":

                    default:
                        throw new NotImplementedException("Uncnoun command.");
                }

                try
                {
                    this.writer.Print(command.Execute());
                }
                catch (Exception e)
                {
                    this.writer.Print(e.Message);
                }
                finally
                {
                    line = reader.ReadLine();
                }

            }
        }
コード例 #26
0
        public Task ChangeState(StatusCommand status)
        {
            if (_statusMatrix[this.Status] == status.Status)
            {
                Status = status.Status;
            }

            return(_asyncCollector.AddAsync(new SignalRMessage()
            {
                Target = "newStatus",
                Arguments = new[] { new
                                    {
                                        Name = Entity.Current.EntityKey,
                                        Status = (int)this.Status
                                    } }
            }));
        }
コード例 #27
0
        private string GetServerStatus()
        {
            StringBuilder sb = new StringBuilder();

            using (TcpConnection connection = new TcpConnection(Host, Port))
            {
                StatusCommand status = new StatusCommand(connection);
                status.Execute();

                sb.Append("<table border=1 style='border-collapse: collapse;' cellpadding='5'><tr><th>Name</th><th>Value</th></tr>");
                foreach (StatusInfo statusInfo in status.Result.StatusInfo)
                {
                    sb.AppendFormat("<tr><td>{0}</td><td>{1}</td></tr>", statusInfo.Name, statusInfo.Value);
                }
                sb.Append("</table>");
            }
            return(sb.ToString());
        }
コード例 #28
0
ファイル: GitHelper.cs プロジェクト: eliotcowley/UpdateDates
        private static void UpdateDatesInternal()
        {
            Console.WriteLine("Updating dates...");
            StatusCommand statusCommand = _git.Status();
            Status        status        = statusCommand.Call();

            _changedFiles = status.GetModified();

            if (_changedFiles.Count == 0)
            {
                Console.WriteLine("No files to commit");
                Environment.Exit(0);
            }

            foreach (string filename in _changedFiles)
            {
                StringBuilder stringBuilder = new StringBuilder();
                string        filePath      = _currentDirectory + @"\" + filename;

                using (StreamReader streamReader = new StreamReader(filePath))
                {
                    string currentLine;

                    while (streamReader.Peek() >= 0)
                    {
                        currentLine = streamReader.ReadLine();

                        if (currentLine.Contains(_dateText))
                        {
                            currentLine = _dateText + @": " + DateTime.Today.ToString("d");
                        }

                        stringBuilder.AppendLine(currentLine);
                    }
                }

                using (StreamWriter streamWriter = new StreamWriter(filePath))
                {
                    streamWriter.Write(stringBuilder.ToString());
                }
            }
        }
コード例 #29
0
        public StatusSubcommand()
        {
            Name        = "status";
            Description = "git status";

            OnExecute(() =>
            {
                var command  = new StatusCommand();
                bool isDirty = command.Execute(PathValueOrDefault);

                if (!Quiet)
                {
                    Console.WriteLine(isDirty ? "Repository has changes" : "Repository has no changes");
                }

                return(isDirty
                    ? 1
                    : 0);
            });
        }
    public ICommand ParseCommand(string input)
    {
        string[] data = input.Split();

        ICommand command = null;

        switch (data[0])
        {
        case "Job":
            string    jobName           = data[1];
            int       workHoursRequired = int.Parse(data[2]);
            string    employeeName      = data[3];
            IEmployee employee          = this.employeeRepository.GetEmployeeByName(employeeName);

            command = new CreateJobCommand(jobName, workHoursRequired, employee);
            break;

        case nameof(StandardEmployee):
        case nameof(PartTimeEmployee):
            string employeeToCreateName = data[1];

            command = new CreateEmployeeCommand(data[0], employeeToCreateName);
            break;

        case "Pass":
            command = new PassWeekCommand();
            break;

        case "Status":
            command = new StatusCommand();
            break;

        case "End":
            command = new EndCommand();
            break;
        }

        InjectFields(command);

        return(command);
    }
コード例 #31
0
ファイル: Status.cs プロジェクト: elendil-software/MountSend
        public static bool WaitForStatus(CommandSender sender, MountState stat, int timeout)
        {
            //Wait for a certain status to be obtained for a specified number of seconds
            int t = timeout * 4;

            while (t > 0)
            {
                var s = new StatusCommand(sender).Execute();
                if (s != stat)
                {
                    Thread.Sleep(250);
                    t -= 1;
                }
                else
                {
                    break;
                }
            }

            return(t > 0);
        }
コード例 #32
0
        public IExecutable ManageCommand(string[] inputArgs)
        {
            IExecutable command = null;

            switch (inputArgs[0])
            {
                case "build":
                    command = new BuildCommand(inputArgs[1], this.Engine);
                    break;
                case "skip":
                    command = new SkipCommand();
                    break;
                case "empire-status":
                    command = new StatusCommand(this.Engine);
                    break;
                case "armistice":
                    command = new EndCommand();
                    break;
            }

            return command;
        }
コード例 #33
0
        public BasicMetaCommandResult ProcessResponce(BasicResponce rsp)
        {
            if (rsp == null)
            {
                Console.WriteLine("Sending status");
                var cmd = new StatusCommand(Degree, 200);
                return(new BasicMetaCommandResult(MetaCommandAction.Command, cmd));
            }

            Console.WriteLine("Received command");
            var status = rsp as StatusResponce;

            if (status == null)
            {
                Console.WriteLine("Idle");
                return(new BasicMetaCommandResult(MetaCommandAction.Idle));
            }

            if (status.DistanceToObstacle < MinDistance && _direction == MoveDirection.Forward)
            {
                return(MoveBackward());
            }

            if (status.DistanceToObstacle >= MinDistance && _direction == MoveDirection.Backwards)
            {
                return(MoveForward());
            }

            if (_direction == MoveDirection.Stopped)
            {
                Console.WriteLine("Stopped.Moving forward");
                return(MoveForward());
            }

            return(new BasicMetaCommandResult(MetaCommandAction.Idle));
        }
コード例 #34
0
        public ICommand DispatchCommand(string commandName, string[] arguments)
        {
            ICommand command = null;

            switch (commandName)
            {
            case "CreateCore":
                command = new CreateCoreCommand(this.NuclearPowerPlant, (CoreType)Enum.Parse(typeof(CoreType), arguments[0]), this.NuclearPowerPlant.NextCoreName, int.Parse(arguments[1]));
                break;

            case "RemoveCore":
                command = new RemoveCoreCommand(this.NuclearPowerPlant, arguments[0]);
                break;

            case "SelectCore":
                command = new SelectCommand(this.NuclearPowerPlant, arguments[0]);
                break;

            case "AttachFragment":
                command = new AttachFragmentCommand(this.NuclearPowerPlant, (FragmentType)Enum.Parse(typeof(FragmentType), arguments[0]), arguments[1], int.Parse(arguments[2]));
                break;

            case "DetachFragment":
                command = new DetachFragmentCommand(this.NuclearPowerPlant);
                break;

            case "Status":
                command = new StatusCommand(this.NuclearPowerPlant);
                break;

            case "System Shutdown":
                break;
            }

            return(command);
        }
コード例 #35
0
ファイル: TermoPrinter.cs プロジェクト: kukareka/printbox
 public List<byte> CommandToByteList(StatusCommand cmd, byte n)
 {
     List<byte> result = new List<byte>();
     result.AddRange(GetCommandBytes(Convert.ToInt32(cmd)));
     result.Add(n);
     return result;
 }
コード例 #36
0
        VersionInfo[] GetDirectoryVersionInfo(FilePath localDirectory, IEnumerable<FilePath> localFileNames, bool getRemoteStatus, bool recursive)
        {
            List<VersionInfo> versions = new List<VersionInfo> ();
            HashSet<FilePath> existingFiles = new HashSet<FilePath> ();
            HashSet<FilePath> nonVersionedMissingFiles = new HashSet<FilePath> ();

            if (localFileNames != null) {
                var localFiles = new List<FilePath> ();
                var arev = new MercurialRevision (this, "");
                foreach (var p in localFileNames) {
                    if (Directory.Exists (p)) {
                        if (recursive)
                            versions.AddRange (GetDirectoryVersionInfo (p, getRemoteStatus, true));
                        else
                            versions.Add (new VersionInfo (p, "", true, VersionStatus.Versioned, arev, VersionStatus.Versioned, null));
                    }
                    else {
                        localFiles.Add (p);
                        if (File.Exists (p))
                            existingFiles.Add (p.CanonicalPath);
                        else
                            nonVersionedMissingFiles.Add (p.CanonicalPath);
                    }
                }
                // No files to check, we are done
                if (localFiles.Count == 0)
                    return versions.ToArray ();

                localFileNames = localFiles;
            } else {
                CollectFiles (existingFiles, localDirectory, recursive);
            }

            MercurialRevision rev;
            var headCommit = RootRepository.Tip ();
            if (headCommit != null)
                rev = new MercurialRevision (this, headCommit.Hash);
            else
                rev = null;

            IEnumerable<string> paths;
            if (localFileNames == null) {
                if (recursive)
                paths = new [] { (string) localDirectory };
                else
                    paths = Directory.GetFiles (localDirectory);
            } else {
                paths = localFileNames.Select (f => (string)f);
            }
            paths = paths.Select (f => ToMercurialPath (f));

            var statcmd = new StatusCommand ();
            foreach (var p in paths) statcmd.AddArgument (p);
            var status = RootRepository.Status (statcmd);
            HashSet<string> added = new HashSet<string> ();
            Action<IEnumerable<FileStatus>, VersionStatus> AddFiles = delegate(IEnumerable<FileStatus> files, VersionStatus fstatus) {
                foreach (FileStatus file in files) {
                    if (!added.Add (file.Path))
                        continue;
                    FilePath statFile = FromMercurialPath (file.Path);
                    existingFiles.Remove (statFile.CanonicalPath);
                    nonVersionedMissingFiles.Remove (statFile.CanonicalPath);
                    versions.Add (new VersionInfo (statFile, "", false, fstatus, rev, VersionStatus.Versioned, null));
                }
            };

            AddFiles (status.Where (fs => fs.State == FileState.Added), VersionStatus.Versioned | VersionStatus.ScheduledAdd);
            AddFiles (status.Where (fs => fs.State == FileState.Modified), VersionStatus.Versioned | VersionStatus.Modified);
            AddFiles (status.Where (fs => fs.State == FileState.Removed), VersionStatus.Versioned | VersionStatus.ScheduledDelete);
            AddFiles (status.Where (fs => fs.State == FileState.Missing), VersionStatus.Versioned | VersionStatus.ScheduledDelete);
            // mercurial-FIXME: how can I get conflicts?
            //AddFiles (status.GetConflicting (), VersionStatus.Versioned | VersionStatus.Conflicted);
            AddFiles (status.Where (fs => fs.State == FileState.Unknown), VersionStatus.Unversioned);

            // Existing files for which hg did not report an status are supposed to be tracked
            foreach (FilePath file in existingFiles) {
                VersionInfo vi = new VersionInfo (file, "", false, VersionStatus.Versioned, rev, VersionStatus.Versioned, null);
                versions.Add (vi);
            }

            // Non existing files for which hg did not report an status are unversioned
            foreach (FilePath file in nonVersionedMissingFiles)
                versions.Add (VersionInfo.CreateUnversioned (file, false));

            return versions.ToArray ();
        }
コード例 #37
0
ファイル: SearchForm.cs プロジェクト: ltbam/Sphinx.Client
 private string GetServerStatus()
 {
     StringBuilder sb = new StringBuilder();
     using (TcpConnection connection = new TcpConnection(Host, Port))
     {
         StatusCommand status = new StatusCommand(connection);
         status.Execute();
             
         sb.Append("<table border=1 style='border-collapse: collapse;' cellpadding='5'><tr><th>Name</th><th>Value</th></tr>");
         foreach (StatusInfo statusInfo in status.Result.StatusInfo)
         {
             sb.AppendFormat("<tr><td>{0}</td><td>{1}</td></tr>", statusInfo.Name, statusInfo.Value);
         }
         sb.Append("</table>");
     }
     return sb.ToString();
 }
コード例 #38
0
        public static Command Parse(string input)
        {
            string[] values = input.Split(' ');

            if (!values.Any())
            {
                throw new ArgumentException("No command specified.");
            }

            // command should be first
            if (!Enum.TryParse(values[0].ToPascalCase(), out CommandType type))
            {
                throw new ArgumentException($"Invalid command {values[0]}");
            }
            if (type == CommandType.Undefined)
            {
                throw new ArgumentException($"Invalid command {type}");
            }

            string[] args = values.Skip(1).ToArray();

            Command command = null;

            switch (type)
            {
            case CommandType.End:
            {
                command = new EndCommand();
                break;
            }

            case CommandType.Flag:
            {
                command = new FlagCommand();
                Dictionary <string, object> requiredArgs = command.GetRequiredArguments();

                if (args.Length != requiredArgs.Count)
                {
                    throw new ArgumentException($"Command type {type} requires {requiredArgs.Count} arguments.");
                }

                if (!int.TryParse(args[0], out int x))
                {
                    throw new ArgumentException($"Parameter {CommandKeys.XPosition} must be an integer.");
                }
                if (!int.TryParse(args[1], out int y))
                {
                    throw new ArgumentException($"Parameter {CommandKeys.YPosition} must be an integer.");
                }

                requiredArgs[CommandKeys.XPosition] = x;
                requiredArgs[CommandKeys.YPosition] = y;

                command.Build(requiredArgs);

                break;
            }

            case CommandType.Help:
            {
                command = new HelpCommand();
                Dictionary <string, object> requiredArgs = command.GetRequiredArguments();

                if (args.Length > 0)
                {
                    if (args.Length > 1)
                    {
                        throw new ArgumentException($"Command type {type} requires 1 or 0 arguments.");
                    }

                    if (!Enum.TryParse(args[0].ToPascalCase(), out CommandType commandType))
                    {
                        throw new ArgumentException($"Invalid command type {args[0]}");
                    }

                    requiredArgs[CommandKeys.CommandName] = commandType;

                    command.Build(requiredArgs);
                }

                break;
            }

            case CommandType.New:
            {
                command = new NewCommand();
                Dictionary <string, object> requiredArgs = command.GetRequiredArguments();

                if (args.Length != requiredArgs.Count)
                {
                    throw new ArgumentException($"Command type {type} requires {requiredArgs.Count} arguments.");
                }

                if (!int.TryParse(args[0], out int x))
                {
                    throw new ArgumentException($"Parameter {CommandKeys.XLength} must be an integer.");
                }
                if (!int.TryParse(args[1], out int y))
                {
                    throw new ArgumentException($"Parameter {CommandKeys.YLength} must be an integer.");
                }
                if (!int.TryParse(args[2], out int b))
                {
                    throw new ArgumentException($"Parameter {CommandKeys.Bombs} must be an integer.");
                }

                requiredArgs[CommandKeys.XLength] = x;
                requiredArgs[CommandKeys.YLength] = y;
                requiredArgs[CommandKeys.Bombs]   = b;

                command.Build(requiredArgs);

                break;
            }

            case CommandType.Open:
            {
                command = new OpenCommand();
                Dictionary <string, object> requiredArgs = command.GetRequiredArguments();

                if (args.Length != requiredArgs.Count)
                {
                    throw new ArgumentException($"Command type {type} requires {requiredArgs.Count} arguments.");
                }

                if (!int.TryParse(args[0], out int x))
                {
                    throw new ArgumentException($"Parameter {CommandKeys.XPosition} must be an integer.");
                }
                if (!int.TryParse(args[1], out int y))
                {
                    throw new ArgumentException($"Parameter {CommandKeys.YPosition} must be an integer.");
                }

                requiredArgs[CommandKeys.XPosition] = x;
                requiredArgs[CommandKeys.YPosition] = y;

                command.Build(requiredArgs);

                break;
            }

            case CommandType.Quit:
            {
                command = new QuitCommand();
                Dictionary <string, object> requiredArgs = command.GetRequiredArguments();
                break;
            }

            case CommandType.Unflag:
            {
                command = new UnflagCommand();
                Dictionary <string, object> requiredArgs = command.GetRequiredArguments();

                if (args.Length != requiredArgs.Count)
                {
                    throw new ArgumentException($"Command type {type} requires {requiredArgs.Count} arguments.");
                }

                if (!int.TryParse(args[0], out int x))
                {
                    throw new ArgumentException($"Parameter {CommandKeys.XPosition} must be an integer.");
                }
                if (!int.TryParse(args[1], out int y))
                {
                    throw new ArgumentException($"Parameter {CommandKeys.YPosition} must be an integer.");
                }

                requiredArgs[CommandKeys.XPosition] = x;
                requiredArgs[CommandKeys.YPosition] = y;

                command.Build(requiredArgs);

                break;
            }

            case CommandType.Status:
            {
                command = new StatusCommand();
                Dictionary <string, object> requiredArgs = command.GetRequiredArguments();

                if (args.Length != requiredArgs.Count)
                {
                    throw new ArgumentException($"Command type {type} requires {requiredArgs.Count} arguments.");
                }

                if (!int.TryParse(args[0], out int x))
                {
                    throw new ArgumentException($"Parameter {CommandKeys.XPosition} must be an integer.");
                }
                if (!int.TryParse(args[1], out int y))
                {
                    throw new ArgumentException($"Parameter {CommandKeys.YPosition} must be an integer.");
                }

                requiredArgs[CommandKeys.XPosition] = x;
                requiredArgs[CommandKeys.YPosition] = y;

                command.Build(requiredArgs);

                break;
            }
            }

            return(command);
        }
コード例 #39
0
        public override void ProcessStatusCommand(StatusCommand cmd)
        {
            MailBox mailbox = store.GetMailbox(cmd.MailBox);

            if (mailbox == null)
            {
                this.Session.AppendResponse(
                    new ServerStatusResponse(
                        cmd.Tag,
                        ServerStatusResponseType.NO,
                        "STATUS fail. Mailbox not found.")
                    );
                return;
            }

            StatusResponse response = new StatusResponse(mailbox.Path);

            foreach (var item in cmd.StatusDataItems)
            {
                switch (item)
                {
                case StatusCommand.StatusItem.MESSAGES:
                    response.StatusItems.Add(
                        new StatusResponseItem(
                            StatusCommand.StatusItem.MESSAGES, mailbox.Exist.ToString()
                            ));
                    break;

                case StatusCommand.StatusItem.RECENT:
                    response.StatusItems.Add(
                        new StatusResponseItem(
                            StatusCommand.StatusItem.RECENT, mailbox.Recent.ToString()
                            ));
                    break;

                case StatusCommand.StatusItem.UIDVALIDITY:
                    response.StatusItems.Add(
                        new StatusResponseItem(
                            StatusCommand.StatusItem.UIDVALIDITY, mailbox.UidValidity.ToString()
                            ));
                    break;

                case StatusCommand.StatusItem.UIDNEXT:
                    response.StatusItems.Add(
                        new StatusResponseItem(
                            StatusCommand.StatusItem.UIDNEXT, mailbox.UidNext.ToString()
                            ));
                    break;

                case StatusCommand.StatusItem.UNSEEN:
                    response.StatusItems.Add(
                        new StatusResponseItem(
                            StatusCommand.StatusItem.UNSEEN, store.GetUnseenMailCount(mailbox).ToString()
                            ));
                    break;

                default:
                    break;
                }
            }

            this.Session.AppendResponse(response);
            this.Session.AppendResponse(
                new ServerStatusResponse(cmd.Tag, ServerStatusResponseType.OK, "STATUS completed")
                );
        }