public ActionResult Delete(Commands.DeleteUserCommand command)
        {
            var service = new Commanding.SimpleTwitterCommandServiceClient();
            service.DeleteUser(command);

            return RedirectToAction("Index");
        }
        internal void QueueCommand(Commands.BaseCommand command)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

            // check whether a new command can be queued at this timing
            if (RunningCommand != null)
            {
                Debug.Assert(RunningCommand.ExecutionPhase != Commands.CommandPhase.Pending);

                if (RunningCommand.ExecutionPhase == Commands.CommandPhase.Prerequisite)
                {
                    throw new InvalidOperationException("Command can't be queued in Prerequisite phase.");
                }
            }

            InitializeCommand(command);
            command.ValidateOnIssue();

            if (RunningCommand != null && RunningCommand.ExecutionPhase == Commands.CommandPhase.Prolog)
            {
                Debug.Assert(m_timingGroupHead != null && m_timingGroupTail != null);
                command.Next = m_timingGroupTail.Next;
                m_timingGroupTail.Next = command;
                m_timingGroupTail = command;
            }
            else
            {
                CommandQueue.PushTail(command, ref m_commandQueueHead, ref m_commandQueueTail);
            }
        }
 private void RunCommand(Commands cmd)
 {
     if (CurrentNode.DataItem is ProjectFile) {
         ProjectFile file = (ProjectFile)CurrentNode.DataItem;
         Project prj = file.Project;
         ProjectFileCollection pfc = prj.Files;
         int currIndex = pfc.IndexOf(file);
         try {
             switch (cmd) {
                 case Commands.MoveUp:
                     if (currIndex > 0) {
                         pfc.RemoveAt(currIndex);
                         pfc.Insert(currIndex-1, file);
                     }
                     break;
                 case Commands.MoveDown:
                     if (currIndex < pfc.Count-1 ) {
                         pfc.RemoveAt(currIndex);
                         pfc.Insert(currIndex+1, file);
                     }
                     break;
                 }
             using (IProgressMonitor monitor = GetStatusMonitor()){
                 prj.Save(monitor);
             }
         }
         catch (Exception ex) {
             LoggingService.LogError (ex.ToString ());
         }
     }
 }
Example #4
0
 public AudioChangedEventArgs(Commands command, string audioFile, double? leftVolume = null, double? rightVolume = null)
 {
     this.Command = command;
     this.AudioFile = audioFile;
     this.LeftVolume = leftVolume;
     this.RightVolume = rightVolume;
 }
Example #5
0
        private static void ParseCommand(string str, out Commands command, out Range range)
        {
            const string turnOffStr = "turn off";
            const string turnOnStr = "turn on";
            const string toggleStr = "toggle";
            if (str.StartsWith(turnOffStr))
            {
                command = Commands.TurnOff;
            }
            else if (str.StartsWith(turnOnStr))
            {
                command = Commands.TurnOn;
            }
            else if (str.StartsWith(toggleStr))
            {
                command = Commands.Toggle;
            }
            else
            {
                throw new ArgumentException("unknown command");
            }

            var regex = new Regex(@"(\d+)\,(\d+)");
            var matches = regex.Matches(str);
            var x1 = int.Parse(matches[0].Groups[1].Value);
            var y1 = int.Parse(matches[0].Groups[2].Value);
            var x2 = int.Parse(matches[1].Groups[1].Value);
            var y2 = int.Parse(matches[1].Groups[2].Value);
            range = new Range(new Point(x1, y1), new Point(x2, y2));
        }
Example #6
0
 /// <summary>
 /// Simple constructor that initializes all
 /// the fields.
 /// </summary>
 /// <param name="command"></param>
 /// <param name="key"></param>
 /// <param name="argument"></param>
 public Query(Commands command, string key, string argument)
 {
     this.Command = command;
     this.Key = key;
     this.Argument = argument;
     ExecutionDate = DateTime.Now;
 }
        //xls���ǂݍ��ݎ�
        public void BuildCommandsXls(string xlsSchemaFile)
        {
            NDbUnit.Core.CreateXlsDs createXls = CreateXlsDs.GetInstance();
            //_dataSet.ReadXmlSchema(xmlSchema);
            // DataSet table rows RowState property is set to Added
            // when read in from an xml file.
            //_dataSet.AcceptChanges();

            _dataSet = createXls.CreateDataSetToXls(xlsSchemaFile);

            Hashtable ht = new Hashtable();

            Commands commands;
            foreach (DataTable dataTable in _dataSet.Tables)
            {
                // Virtual overrides.
                commands = new Commands();
                commands.SelectCommand = CreateSelectCommand(_dataSet, dataTable.TableName);
                commands.InsertCommand = CreateInsertCommand(commands.SelectCommand, dataTable.TableName);
                commands.InsertIdentityCommand = CreateInsertIdentityCommand(commands.SelectCommand, dataTable.TableName);
                commands.DeleteCommand = CreateDeleteCommand(commands.SelectCommand, dataTable.TableName);
                commands.DeleteAllCommand = CreateDeleteAllCommand(dataTable.TableName);
                commands.UpdateCommand = CreateUpdateCommand(commands.SelectCommand, dataTable.TableName);

                ht[dataTable.TableName] = commands;
            }

            _dbCommandColl = ht;
            _initialized = true;
        }
        public async Task<Response> Send(Commands.Command command)
        {
            
            int id = commandsSent;
            var mes = command.GetMessage(id);
            commandsSent++;
            bool hasResponse = false;
            if (socket.State != WebSocketState.Open)
            {
                if (socket.State == WebSocketState.None || socket.State == WebSocketState.Closed)
                {
                    socket.Open();
                    while (socket.State == WebSocketState.Connecting)
                        await Task.Delay(100);

                    if (socket.State != WebSocketState.Open)
                        throw new Exception("Socket could not be opened.");
                }
            }
            socket.Send(mes);
            while (!hasResponse)
            {
                await Task.Delay(10).ConfigureAwait(false);
                lock (responses)
                {
                    hasResponse = responses.ContainsKey(id);
                }
            }
            var response = responses[id];
            removeResponse(id);
            return response;
        }
 public void sendData(Commands cmd)
 {
     if (port.IsOpen)
     {
         port.Write(new byte[] { (byte)cmd }, 0, 1);
     }
 }
        internal void OnCommandCanceled(Commands.BaseCommand command, string reason)
        {
            if (!m_sendNotifications)
            {
                return;
            }

            var castSpell = command as Commands.CastSpell;
            if (castSpell != null)
            {
                new Interactions.NotifySpellEvent(Game, "OnSpellCastCanceled", castSpell.Spell as Behaviors.ICastableSpell, reason).Run();
            }

            var moveCard = command as Commands.InitiativeMoveCard;
            if (moveCard != null && moveCard.FromZone == SystemZone.Hand && moveCard.ToZone == SystemZone.Battlefield
                && moveCard.Cause is Game)
            {
                new Interactions.NotifyCardEvent(Game, "OnCardPlayCanceled", moveCard.Subject, reason).Run();
            }

            if (command is Commands.IInitiativeCommand)
            {
                new Interactions.NotifyGameEvent(Game, "OnInitiativeCommandCanceled", null).Run();
            }
        }
        void CreateNavigationCommands(Commands commands)
        {
            var previousCmd = commands.AddNamedCommand(
                m_addIn,
                "GotoPrevious",
                "goto previous location",
                "Goto the previous location in the current navigation list.",
                false,
                0,
                vsCommandDisabledFlagsValue:
                    (int) vsCommandStatus.vsCommandStatusEnabled 
                    | (int) vsCommandStatus.vsCommandStatusSupported
            );

            previousCmd.Bindings = "Global::Alt+Left Arrow";
            
            var nextCmd = commands.AddNamedCommand(
                m_addIn,
                "GotoNext",
                "goto next location",
                "Goto the next location in the current navigation list.",
                false,
                0,
                vsCommandDisabledFlagsValue:
                    (int) vsCommandStatus.vsCommandStatusEnabled 
                    | (int) vsCommandStatus.vsCommandStatusSupported
            );

            nextCmd.Bindings = "Global::Alt+Right Arrow";
        }
        public static void RegisterAll(Commands system)
        {
            // Entity Events
            system.RegisterEvent(new AnimalDamagedScriptEvent(system));
            system.RegisterEvent(new AnimalDeathScriptEvent(system));
            system.RegisterEvent(new BarricadeDamagedScriptEvent(system));
            system.RegisterEvent(new BarricadeDestroyedScriptEvent(system));
            system.RegisterEvent(new EntityDamagedScriptEvent(system));
            system.RegisterEvent(new EntityDeathScriptEvent(system));
            system.RegisterEvent(new EntityDestroyedScriptEvent(system));
            system.RegisterEvent(new ResourceDamagedScriptEvent(system));
            system.RegisterEvent(new ResourceDestroyedScriptEvent(system));
            system.RegisterEvent(new StructureDamagedScriptEvent(system));
            system.RegisterEvent(new StructureDestroyedScriptEvent(system));
            system.RegisterEvent(new VehicleDamagedScriptEvent(system));
            system.RegisterEvent(new VehicleDestroyedScriptEvent(system));
            system.RegisterEvent(new ZombieDamagedScriptEvent(system));
            system.RegisterEvent(new ZombieDeathScriptEvent(system));

            // Player Events
            system.RegisterEvent(new PlayerChatScriptEvent(system));
            system.RegisterEvent(new PlayerConnectingScriptEvent(system));
            system.RegisterEvent(new PlayerConnectedScriptEvent(system));
            system.RegisterEvent(new PlayerDamagedScriptEvent(system));
            system.RegisterEvent(new PlayerDeathScriptEvent(system));
            system.RegisterEvent(new PlayerDisconnectedScriptEvent(system));
            system.RegisterEvent(new PlayerShootScriptEvent(system));
        }
        public BinaryPacketFormatter(Commands command, params object[] args)
            : this()
        {
            this.Add(command);
            foreach (var obj in args)
            {
                if (obj is Byte) this.Add((Byte)obj);

                if (obj is Int16) this.Add((Int16)obj);
                if (obj is UInt16) this.Add((UInt16)obj);

                if (obj is Int32) this.Add((Int32)obj);
                if (obj is UInt32) this.Add((UInt32)obj);

                if (obj is Int64) this.Add((Int64)obj);
                if (obj is UInt64) this.Add((UInt64)obj);

                if (obj is byte[]) this.Add((byte[])obj);
                if (obj is List<byte>) this.Add((List<byte>)obj);
                if (obj is string) this.Add((string)obj);
                if (obj is float) this.Add((float)obj);
                if (obj is Vector3) this.Add((Vector3)obj);
                if (obj is Vector4) this.Add((Vector4)obj);
                if (obj is Quaternion) this.Add((Quaternion)obj);
            }
        }
        public static Usuario Create(Commands.NovoUsuarioCompletoCommand cmd)
        {
            var telefone = new AparelhoTelefone(cmd.Numero, cmd.UUID, cmd.SistemaOperacional);
            var usuarioCompleto = new Usuario(cmd.Nome, cmd.Email, cmd.AceitoMkt, telefone);

            return usuarioCompleto;
        }
Example #15
0
        /// <summary>
        /// Prepares the command system, registering all base commands.
        /// </summary>
        public void Init(Outputter _output, Client tclient)
        {
            // General Init
            TheClient = tclient;
            CommandSystem = new Commands();
            Output = _output;
            CommandSystem.Output = Output;
            CommandSystem.Init();

            // UI Commands
            CommandSystem.RegisterCommand(new AttackCommand(TheClient));
            CommandSystem.RegisterCommand(new BackwardCommand(TheClient));
            CommandSystem.RegisterCommand(new BindblockCommand(TheClient));
            CommandSystem.RegisterCommand(new BindCommand(TheClient));
            CommandSystem.RegisterCommand(new ForwardCommand(TheClient));
            CommandSystem.RegisterCommand(new ItemdownCommand(TheClient));
            CommandSystem.RegisterCommand(new ItemleftCommand(TheClient));
            CommandSystem.RegisterCommand(new ItemrightCommand(TheClient));
            CommandSystem.RegisterCommand(new ItemupCommand(TheClient));
            CommandSystem.RegisterCommand(new LeftwardCommand(TheClient));
            CommandSystem.RegisterCommand(new MovedownCommand(TheClient));
            CommandSystem.RegisterCommand(new RightwardCommand(TheClient));
            CommandSystem.RegisterCommand(new SecondaryCommand(TheClient));
            CommandSystem.RegisterCommand(new SprintCommand(TheClient));
            CommandSystem.RegisterCommand(new TalkCommand(TheClient));
            CommandSystem.RegisterCommand(new UnbindCommand(TheClient));
            CommandSystem.RegisterCommand(new UpwardCommand(TheClient));
            CommandSystem.RegisterCommand(new UseCommand(TheClient));
            CommandSystem.RegisterCommand(new WalkCommand(TheClient));

            // Common Commands
            CommandSystem.RegisterCommand(new CdevelCommand(TheClient));
            CommandSystem.RegisterCommand(new ItemnextCommand(TheClient));
            CommandSystem.RegisterCommand(new ItemprevCommand(TheClient));
            CommandSystem.RegisterCommand(new ItemselCommand(TheClient));
            CommandSystem.RegisterCommand(new PlayCommand(TheClient));
            CommandSystem.RegisterCommand(new QuickItemCommand(TheClient));
            CommandSystem.RegisterCommand(new QuitCommand(TheClient));
            CommandSystem.RegisterCommand(new ReloadGameCommand(TheClient));

            // Network Commands
            CommandSystem.RegisterCommand(new ConnectCommand(TheClient));
            CommandSystem.RegisterCommand(new DisconnectCommand(TheClient));
            CommandSystem.RegisterCommand(new NetusageCommand(TheClient));
            CommandSystem.RegisterCommand(new PingCommand(TheClient));
            CommandSystem.RegisterCommand(new StartlocalserverCommand(TheClient));

            // Game Commands
            CommandSystem.RegisterCommand(new InventoryCommand(TheClient));
            CommandSystem.RegisterCommand(new TesteffectCommand(TheClient));

            // General Tags
            CommandSystem.TagSystem.Register(new AudioTagBase(TheClient));

            // Entity Tags
            CommandSystem.TagSystem.Register(new PlayerTagBase(TheClient));

            CommandSystem.PostInit();
        }
Example #16
0
        public MainPage()
        {
            this.InitializeComponent();
            CurrentCmd = null;
            GetCommands("Commands");
            NavLinksList.DataContext = Commands.CommandsList;

        }
Example #17
0
 public static byte[] ToBytes(Commands command)
 {
     int intValue = (int)command;
     byte[] intBytes = BitConverter.GetBytes(intValue);
     if (BitConverter.IsLittleEndian)
         Array.Reverse(intBytes);
     return intBytes;
 }
Example #18
0
 public MidiMessage(uint channel, Commands command, uint param1, uint param2, uint timeStamp)
 {
     TimeStamp = timeStamp;
     Channel = channel;
     Command = command;
     Param1 = param1;
     Param2 = param2;
 }
Example #19
0
 public Command(Commands command, string data)
 {
     CurrentCommand = Enum.GetName(typeof(Commands), command);
     Data = data;
     ValuesList = new List<List<object>>();
     ColumnsList = new List<string>();
     TypesList = new List<string>();
 }
Example #20
0
 public void SendCommand(Commands cmd, Channel chan, bool repeat)
 {
     sendBuffer[0] = (byte) chan;
     sendBuffer[1] = (byte) cmd;
     sendBuffer[2] = (byte) (repeat ? 0x1 : 0x0);
     sendBuffer[3] = GetChecksum(sendBuffer[0], sendBuffer[1], sendBuffer[2]);
     port.Write(sendBuffer, 0, 4);
 }
Example #21
0
 public ChatMessage(Commands command, string sender, string body, byte[] icon)
     : this()
 {
     Command = command;
     Sender = sender;
     Body = body;
     Icon = icon;
 }
Example #22
0
 public MidiMessage(uint message, uint timestamp)
 {
     this.TimeStamp = timestamp;
     this.Channel = message & 0xf;
     this.Command = (Commands)((message >> 4) & 0xf);
     this.Param1 = (message >> 8) & 0xff;
     this.Param2 = (message >> 16) & 0xff;
 }
Example #23
0
 public AgentConsole()
 {
     m_commands = new Commands("AgentConsole");
     m_commands.Register(new AgentCommands());
     m_commands.Register(new DnsCommands());
     m_commands.Register(new SmtpAgentCommands());
     m_commands.Register(new CertificateCommands());
     m_commands.Register(new MailCommands());
 }
        // POST: /<controller>/Create
        public IActionResult Create(Commands.Product.Create.Command command)
        {
            if (!ModelState.IsValid)
            {
                return this.View("Create", command);
            }

            return this.View("Create");
        }
        public IActionResult Edit(Commands.Product.Create.Command model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            return View("Index");
        }
        private void QueueResourceCommand(Commands.BaseCommand command)
        {
            // can only queue command at head when issueing resource consuming commands
            Debug.Assert(RunningCommand != null && RunningCommand.ExecutionPhase == Commands.CommandPhase.Condition);
            InitializeCommand(command);
            command.ValidateOnIssue();

            CommandQueue.PushTail(command, ref m_resourceCommandQueueHead, ref m_resourceCommandQueueTail);
        }
        public CommandConsole(string defaultPrompt)
            : base(defaultPrompt)
        {
            Commands = new Commands();

            Commands.AddCommand(
                "Help", false, "help", "help [<item>]",
                "Display help on a particular command or on a list of commands in a category", Help);
        }
Example #28
0
        /// <summary>
        /// Prepares the command system, registering all base commands.
        /// </summary>
        public void Init(Outputter _output, Server tserver)
        {
            // General Init
            TheServer = tserver;
            CommandSystem = new Commands();
            Output = _output;
            CommandSystem.Output = Output;
            CommandSystem.Init();

            // Common Commands
            CommandSystem.RegisterCommand(new MeminfoCommand(TheServer));
            CommandSystem.RegisterCommand(new QuitCommand(TheServer));
            CommandSystem.RegisterCommand(new SayCommand(TheServer));

            // File Commands
            CommandSystem.RegisterCommand(new AddpathCommand(TheServer));

            // World Commands
            // ...

            // Item Commands
            CommandSystem.RegisterCommand(new AddrecipeCommand(TheServer));
            CommandSystem.RegisterCommand(new GiveCommand(TheServer));

            // Player Management Commands
            CommandSystem.RegisterCommand(new KickCommand(TheServer));

            // Tag Bases
            CommandSystem.TagSystem.Register(new ArrowEntityTagBase(TheServer));
            CommandSystem.TagSystem.Register(new BlockGroupEntityTagBase(TheServer));
            CommandSystem.TagSystem.Register(new BlockItemEntityTagBase(TheServer));
            CommandSystem.TagSystem.Register(new BulletEntityTagBase(TheServer));
            CommandSystem.TagSystem.Register(new ColorTagBase());
            CommandSystem.TagSystem.Register(new EntityTagBase(TheServer));
            CommandSystem.TagSystem.Register(new GlowstickEntityTagBase(TheServer));
            CommandSystem.TagSystem.Register(new GrenadeEntityTagBase(TheServer));
            CommandSystem.TagSystem.Register(new ItemEntityTagBase(TheServer));
            CommandSystem.TagSystem.Register(new ItemTagBase(TheServer));
            CommandSystem.TagSystem.Register(new LivingEntityTagBase(TheServer));
            CommandSystem.TagSystem.Register(new LocationTagBase(TheServer));
            CommandSystem.TagSystem.Register(new MaterialTagBase());
            CommandSystem.TagSystem.Register(new ModelEntityTagBase(TheServer));
            CommandSystem.TagSystem.Register(new PhysicsEntityTagBase(TheServer));
            CommandSystem.TagSystem.Register(new PlayerTagBase(TheServer));
            CommandSystem.TagSystem.Register(new PrimitiveEntityTagBase(TheServer));
            CommandSystem.TagSystem.Register(new RecipeResultTagBase(TheServer));
            CommandSystem.TagSystem.Register(new RecipeTagBase(TheServer));
            CommandSystem.TagSystem.Register(new WorldTagBase(TheServer));
            CommandSystem.TagSystem.Register(new ServerTagBase(TheServer));
            CommandSystem.TagSystem.Register(new SmokeGrenadeEntityTagBase(TheServer));
            CommandSystem.TagSystem.Register(new VehicleEntityTagBase(TheServer));
            CommandSystem.TagSystem.Register(new VehiclePartEntityTagBase(TheServer));

            // Wrap up
            CommandSystem.PostInit();
        }
Example #29
0
 public ConsumerStatus RegisterCommand(Commands.AbstractCommand command)
 {
     lock (this)
     {
         _responseQueue.Enqueue(command);
         if (_alive)
             return ConsumerStatus.Running;
         return ConsumerStatus.Idle;
     }
 }
        private dynamic findCommand(Commands commands, string commandName)
        {
            foreach (var command in commands)
            {
                if (((dynamic)command).Name == commandName)
                    return command;
            }

            return null;
        }
Example #31
0
        private string appHelpText()
        {
            StringBuilder sb = new StringBuilder();

            // NAME
            sb.Append($"Name: \n");
            sb.Append($"\t{Name} {(string.IsNullOrWhiteSpace(Usage) ? "" : "- " + Usage)}");
            sb.Append($"\n");

            // USAGE
            sb.Append($"Usage: \n");
            sb.Append($"\t{ProcessName}");
            if (Flags.Count() > 0)
            {
                sb.Append(" [global options]");
            }
            if (Commands.Count() > 0)
            {
                sb.Append(" command [command options]");
            }
            if (string.IsNullOrEmpty(ArgsUsage))
            {
                sb.Append(" [arguments...]");
            }
            else
            {
                sb.Append(" ").Append(ArgsUsage);
            }
            sb.Append($"\n");

            // VERSION
            if (!string.IsNullOrWhiteSpace(Version))
            {
                sb.Append($"Version: \n");
                sb.Append($"\t{Version}");
                sb.Append($"\n");
            }

            // DESCRIPTION
            if (!string.IsNullOrWhiteSpace(Description))
            {
                sb.Append($"Description: \n");
                sb.Append($"\t{Description}");
                sb.Append($"\n");
            }

            // AUTHOR(S)
            if (Authors.Count() > 0)
            {
                if (Authors.Count() > 1)
                {
                    sb.Append($"Authors: \n").Append("\t");
                }
                else
                {
                    sb.Append($"Author: \n").Append("\t");
                }
                sb.Append(String.Join(", ", Authors));
                sb.Append($"\n");
            }

            // COMMANDS
            if (Commands.Count() > 0)
            {
                sb.Append($"Commands: \n");

                int maxLength = Commands.Select(x => String.Join(", ", x.Names()).Length).Max();
                foreach (var command in Commands)
                {
                    string n = String.Join(", ", command.Names());
                    sb.Append("\t").Append(n).Append(new string(' ', maxLength - n.Length + 1)).Append($" {command.Usage}");
                    sb.Append($"\n");
                }
            }

            // GLOBAL OPTIONS
            if (Flags.Count() > 0)
            {
                sb.Append($"Global Options: \n");

                int maxLength = Flags.Select(x => String.Join(", ", x.NamesAppendHyphen()).Length).Max();
                foreach (var flag in Flags)
                {
                    string n = String.Join(", ", flag.NamesAppendHyphen());
                    sb.Append("\t").Append(n).Append(new string(' ', maxLength - n.Length + 1)).Append($" {flag.Usage}");
                    if (flag.Value is not null)
                    {
                        sb.Append($" (default: \"{flag.Value}\")");
                    }
                    sb.Append($"\n");
                    // TODO Value
                }
            }

            // COPYLIGHT
            if (!string.IsNullOrWhiteSpace(CopyRight))
            {
                sb.Append($"Copyright: \n");
                sb.Append($"\t{CopyRight}");
                sb.Append($"\n");
            }

            return(sb.ToString());
        }
Example #32
0
        void ReceiveCallback(object state)
        {
            var peer       = (NetPeer)state;
            var message    = peer.ReadMessage();
            var connection = message.SenderConnection;
            var user       = (connection != null) ? connection.Tag as User : null;

            try
            {
                //Console.Write ("Server {0}", message.MessageType);

                switch (message.MessageType)
                {
                                        #if DEBUG
                case NetIncomingMessageType.VerboseDebugMessage:
                case NetIncomingMessageType.DebugMessage:
                    Client.OnMessage(new ClientMessageArgs("SERVER:" + message.ReadString(), null));
                    break;
                                        #endif
                case NetIncomingMessageType.WarningMessage:
                case NetIncomingMessageType.ErrorMessage:
                    Client.OnMessage(new ClientMessageArgs(message.ReadString(), null));
                    break;

                case NetIncomingMessageType.StatusChanged:
                    //Console.Write (" Status: Peer:{0}, Connection:{1}", peer.Status, message.SenderConnection.Status);
                    switch (message.SenderConnection.Status)
                    {
                    case NetConnectionStatus.Connected:
                        if (user != null)
                        {
                            bool   isCurrentUser = user.Key == Client.CurrentUser.Key;
                            User[] usersArray;

                            lock (Users)
                            {
                                if (!isCurrentUser || !Client.Headless)
                                {
                                    Users.Add(user);
                                }
                                usersArray = Users.ToArray();
                            }
                            if (!isCurrentUser)
                            {
                                SendCommand(new UserStatusChanged {
                                    User = user, Status = UserStatus.Initialize
                                }, connection);
                                SendCommand(new LoadDocument {
                                    Document = Delegate != null ? Delegate.Document : null
                                }, connection);
                            }
                            SendCommand(new UserList(this)
                            {
                                Users = usersArray
                            }, connection);
                            SendCommand(new UserStatusChanged {
                                User = user, Status = UserStatus.Connected
                            }, null, connection);
                        }
                        break;

                    case NetConnectionStatus.Disconnected:
                        if (user != null)
                        {
                            var users = Users;
                            lock (users)
                                users.Remove(user);
                            if (user.KickedBy != null)
                            {
                                SendCommand(new UserStatusChanged {
                                    User = user, Status = UserStatus.Kicked
                                }, null, connection, user.KickedBy);
                            }
                            else
                            {
                                SendCommand(new UserStatusChanged {
                                    User = user, Status = UserStatus.Disconnected
                                }, null, connection);
                            }
                        }
                        break;
                    }
                    break;

                case NetIncomingMessageType.ConnectionApproval:
                    var version       = message.ReadVariableInt32();
                    var clientVersion = message.ReadString();
                    var password      = message.ReadString();
                    if (version != Server.VERSION)
                    {
                        var serverVersion = Assembly.GetEntryAssembly().GetName().Version;
                        connection.Deny(string.Format("Server is running version {0} (protocol v{1}), which is not the same as your client version {2} (protocol v{3})", serverVersion, Server.VERSION, clientVersion, version));
                    }
                    else
                    {
                        try
                        {
                            var requiresPassword = !string.IsNullOrEmpty(Password);
                            var hasUserPassword  = (!string.IsNullOrEmpty(Password) && password == Password);
                            var hasAdminPassword = (!string.IsNullOrEmpty(OperatorPassword) && password == OperatorPassword);
                            var hasPassword      = hasUserPassword || hasAdminPassword;
                            if (requiresPassword && !hasPassword)
                            {
                                if (string.IsNullOrEmpty(password))
                                {
                                    connection.Deny("A password is required to join this server");
                                }
                                else
                                {
                                    connection.Deny("Password is incorrect");
                                }
                            }
                            else
                            {
                                IPHostEntry host = null;
                                try
                                {
                                    host = Dns.GetHostEntry(message.SenderEndPoint.Address);
                                }
                                catch
                                {
                                }

                                user           = new User();
                                user.Connected = true;
                                user.Receive(new ReceiveCommandArgs(message, this, null));
                                user.IPAddress = message.SenderEndPoint.Address;
                                if (host != null)
                                {
                                    user.HostName = host.HostName;
                                }
                                user.Level = hasAdminPassword ? UserLevel.Operator : DefaultUserLevel;
                                bool isCurrentUser = user.Key == Client.CurrentUser.Key;
                                if (isCurrentUser)
                                {
                                    user = Client.CurrentUser;
                                }
                                connection.Tag = user;

                                if (!isCurrentUser)
                                {
                                    var users = Users;

                                    lock (users)
                                    {
                                        if (users.Any(r => r.Alias == user.Alias))
                                        {
                                            connection.Deny("Alias is currently in use");
                                            return;
                                        }
                                    }
                                }
                                connection.Approve();
                            }
                        }
                        catch
                        {
                            connection.Deny("There was a problem connecting to this server");
#if DEBUG
                            throw;
#endif
                        }
                    }
                    break;

                case NetIncomingMessageType.Data:

                    int      messageId = message.ReadVariableInt32();
                    ICommand command;
                    if (Commands.TryGetValue(messageId, out command))
                    {
                        command.Receive(new ReceiveCommandArgs(message, this, user));
                    }
                    else
                    {
                        // send to all clients
                        ResendMessage(message, user);
                    }
                    break;
                }
            }
            catch (Exception ex)
            {
                Client.OnMessage(new ClientMessageArgs(string.Format("Server Error: {0}", ex), null));
#if DEBUG
                throw;
#endif
            }
            finally
            {
                server.Recycle(message);
            }
            //Console.WriteLine ();
        }
Example #33
0
 public virtual void Append(ISqlCommand command)
 {
     Commands.Add(command);
     sqlString = sqlString.Append(command.Query).Append(";").Append(Environment.NewLine);
 }
 private static void Fetch(ILog log, AuthenticationInfo authentication, Remote remote, Repository repo)
 {
     log.Info($"Fetching from remote '{remote.Name}' using the following refspecs: {string.Join(", ", remote.FetchRefSpecs.Select(r => r.Specification))}.");
     Commands.Fetch(repo, remote.Name, new string[0], authentication.ToFetchOptions(), null);
 }
Example #35
0
 protected Command(Commands name, CommandType type, bool requireConnection)
 {
     this._comm = name;
     this._type = type;
     this._requireConnection = requireConnection;
 }
 private void performBinarySampling(Commands cmd, string param)
 {
     cmd.performOneCommand(ConfigurationBuilder.COMMAND_BINARY_SAMPLING + " " + param);
 }
Example #37
0
        public async Task RunBotAsync()
        {
            var cfg = new DiscordConfiguration
            {
                Token           = BotSettings.Token,
                AutoReconnect   = true,
                TokenType       = TokenType.Bot,
                Intents         = DiscordIntents.All,
                MinimumLogLevel = BotSettings.Debug ? LogLevel.Debug : LogLevel.Information
            };

            Client = new DiscordClient(cfg);

            var ccfg = new CommandsNextConfiguration
            {
                StringPrefixes      = new[] { BotSettings.Prefix },
                EnableDms           = true,
                CaseSensitive       = false,
                EnableMentionPrefix = true
            };

            Commands = Client.UseCommandsNext(ccfg);

            var icfg = new InteractivityConfiguration
            {
                PaginationBehaviour = PaginationBehaviour.WrapAround,
                PaginationDeletion  = PaginationDeletion.DeleteEmojis,
                Timeout             = TimeSpan.FromMinutes(2)
            };

            Interactivity = Client.UseInteractivity(icfg);

            //Команды
            Commands.RegisterCommands(Assembly.GetExecutingAssembly());

            //Кастомная справка команд
            Commands.SetHelpFormatter <HelpFormatter>();

            //Ивенты
            AsyncListenerHandler.InstallListeners(Client, this);

            ConnectionString =
                $"Server={Bot.BotSettings.DatabaseHost}; Port=3306; Database={Bot.BotSettings.DatabaseName}; Uid={Bot.BotSettings.DatabaseUser}; Pwd={Bot.BotSettings.DatabasePassword}; CharSet=utf8mb4;";

            await Client.ConnectAsync();

            if (!Directory.Exists("generated"))
            {
                Directory.CreateDirectory("generated");
            }
            if (!File.Exists("generated/attachments_messages.csv"))
            {
                File.Create("generated/attachments_messages.csv");
            }
            if (!File.Exists("generated/find_channel_invites.csv"))
            {
                File.Create("generated/find_channel_invites.csv");
            }
            if (!File.Exists("generated/top_inviters.xml"))
            {
                File.Create("generated/top_inviters.xml");
            }
            if (!Directory.Exists("generated/stats"))
            {
                Directory.CreateDirectory("generated/stats");
            }
            if (!File.Exists("generated/stats/ship_names.csv"))
            {
                File.Create("generated/stats/ship_names.csv");
            }

            await Task.Delay(-1);
        }
        // Show full help
        public void ShowHelp(string commandName = null)
        {
            var headerBuilder     = new StringBuilder("Usage:");
            var usagePrefixLength = headerBuilder.Length;

            for (var cmd = this; cmd != null; cmd = cmd.Parent)
            {
                cmd.IsShowingInformation = true;
                if (cmd != this && cmd.Arguments.Any())
                {
                    var args = string.Join(" ", cmd.Arguments.Select(arg => arg.Name));
                    headerBuilder.Insert(usagePrefixLength, string.Format(" {0} {1}", cmd.Name, args));
                }
                else
                {
                    headerBuilder.Insert(usagePrefixLength, string.Format(" {0}", cmd.Name));
                }
            }

            CommandLineApplication target;

            if (commandName == null || string.Equals(Name, commandName, StringComparison.OrdinalIgnoreCase))
            {
                target = this;
            }
            else
            {
                target = Commands.SingleOrDefault(cmd => string.Equals(cmd.Name, commandName, StringComparison.OrdinalIgnoreCase));

                if (target != null)
                {
                    headerBuilder.AppendFormat(" {0}", commandName);
                }
                else
                {
                    // The command name is invalid so don't try to show help for something that doesn't exist
                    target = this;
                }
            }

            var optionsBuilder           = new StringBuilder();
            var commandsBuilder          = new StringBuilder();
            var argumentsBuilder         = new StringBuilder();
            var argumentSeparatorBuilder = new StringBuilder();

            int maxArgLen = 0;

            for (var cmd = target; cmd != null; cmd = cmd.Parent)
            {
                if (cmd.Arguments.Any())
                {
                    if (cmd == target)
                    {
                        headerBuilder.Append(" [arguments]");
                    }

                    if (argumentsBuilder.Length == 0)
                    {
                        argumentsBuilder.AppendLine();
                        argumentsBuilder.AppendLine("Arguments:");
                    }

                    maxArgLen = Math.Max(maxArgLen, MaxArgumentLength(cmd.Arguments));
                }
            }

            for (var cmd = target; cmd != null; cmd = cmd.Parent)
            {
                if (cmd.Arguments.Any())
                {
                    var outputFormat = "  {0}{1}";
                    foreach (var arg in cmd.Arguments)
                    {
                        argumentsBuilder.AppendFormat(
                            outputFormat,
                            arg.Name.PadRight(maxArgLen + 2),
                            arg.Description);
                        argumentsBuilder.AppendLine();
                    }
                }
            }

            if (target.Options.Any())
            {
                headerBuilder.Append(" [options]");

                optionsBuilder.AppendLine();
                optionsBuilder.AppendLine("Options:");
                var maxOptLen    = MaxOptionTemplateLength(target.Options);
                var outputFormat = string.Format("  {{0, -{0}}}{{1}}", maxOptLen + 2);
                foreach (var opt in target.Options)
                {
                    optionsBuilder.AppendFormat(outputFormat, opt.Template, opt.Description);
                    optionsBuilder.AppendLine();
                }
            }

            if (target.Commands.Any())
            {
                headerBuilder.Append(" [command]");

                commandsBuilder.AppendLine();
                commandsBuilder.AppendLine("Commands:");
                var maxCmdLen    = MaxCommandLength(target.Commands);
                var outputFormat = string.Format("  {{0, -{0}}}{{1}}", maxCmdLen + 2);
                foreach (var cmd in target.Commands.OrderBy(c => c.Name))
                {
                    commandsBuilder.AppendFormat(outputFormat, cmd.Name, cmd.Description);
                    commandsBuilder.AppendLine();
                }

                if (OptionHelp != null)
                {
                    commandsBuilder.AppendLine();
                    commandsBuilder.AppendFormat("Use \"{0} [command] --help\" for more information about a command.", Name);
                    commandsBuilder.AppendLine();
                }
            }

            if (target.AllowArgumentSeparator || target.HandleRemainingArguments)
            {
                if (target.AllowArgumentSeparator)
                {
                    headerBuilder.Append(" [[--] <arg>...]]");
                }
                else
                {
                    headerBuilder.Append(" [args]");
                }

                if (!string.IsNullOrEmpty(target.ArgumentSeparatorHelpText))
                {
                    argumentSeparatorBuilder.AppendLine();
                    argumentSeparatorBuilder.AppendLine("Args:");
                    argumentSeparatorBuilder.AppendLine($"  {target.ArgumentSeparatorHelpText}");
                    argumentSeparatorBuilder.AppendLine();
                }
            }

            headerBuilder.AppendLine();

            var nameAndVersion = new StringBuilder();

            nameAndVersion.AppendLine(GetFullNameAndVersion());
            nameAndVersion.AppendLine();

            Console.Write("{0}{1}{2}{3}{4}{5}", nameAndVersion, headerBuilder, argumentsBuilder, optionsBuilder, commandsBuilder, argumentSeparatorBuilder);
        }
Example #39
0
        public Dictionary <int, string> GetPrescriptionsMedications()
        {
            query = Commands.SelectPrescriptionsMedications();
            ConnectedData.SetCommand(query);
            Dictionary <int, string> list = new Dictionary <int, string>();

            if (connectionType == ConnectionTypes.Connected)
            {
                int[] size = new int[2];
                size = ConnectedData.GetRowAndColumnCount();
                int row    = size[0];
                int column = size[1];

                string[,] data = new string[row, column];
                data           = ConnectedData.GetTableData();

                int    key = Convert.ToInt32(data[0, 0]);
                string str = "";

                for (int i = 0; i < row; i++)
                {
                    if (Convert.ToInt32(data[i, 0]) == key)
                    {
                        str += data[i, 1] + " " + data[i, 2] + "шт, ";
                    }
                    else
                    {
                        str = str.Remove(str.Length - 2);
                        list.Add(key, str);
                        str  = "";
                        key  = Convert.ToInt32(data[i, 0]);
                        str += data[i, 1] + " " + data[i, 2] + "шт, ";
                    }
                }
                str = str.Remove(str.Length - 2);
                list.Add(key, str);
            }

            else
            {
                dataSet = DisconnectedData.GetTableData(query);
                DataTable dataTable = dataSet.Tables[0];
                DataRow   dataRow   = dataTable.Rows[0];
                int       key       = Convert.ToInt32(dataRow[0]);
                string    str       = "";
                for (int i = 0; i < dataTable.Rows.Count; i++)
                {
                    dataRow = dataTable.Rows[i];
                    if (Convert.ToInt32(dataRow[0]) == key)
                    {
                        str += dataRow[1] + " " + dataRow[2] + "шт, ";
                    }
                    else
                    {
                        str = str.Remove(str.Length - 2);
                        list.Add(key, str);
                        str  = "";
                        key  = Convert.ToInt32(dataRow[0]);
                        str += dataRow[1] + " " + dataRow[2] + "шт, ";
                    }
                }
                str = str.Remove(str.Length - 2);
                list.Add(key, str);
            }
            return(list);
        }
Example #40
0
        public void MedicationsPrint(SortTypes sort, string name = "")
        {
            double sum          = 0;
            int    countPills   = 0;
            int    countSolutes = 0;

            MedicationsListView.Items.Clear();
            if (name != "")
            {
                query = Commands.SelectMedications(sort, name);
            }
            else
            {
                query = Commands.SelectMedications(sort);
            }
            ListViewItem item;

            if (connectionType == ConnectionTypes.Connected)
            {
                ConnectedData.SetCommand(query);
                int[] size = new int[2];
                size = ConnectedData.GetRowAndColumnCount();
                int row    = size[0];
                int column = size[1];

                string[,] data = new string[row, column];
                data           = ConnectedData.GetTableData();

                for (int i = 0; i < row; i++)
                {
                    item = new ListViewItem(data[i, 0]);
                    for (int j = 1; j < column; j++)
                    {
                        if (j == 2)
                        {
                            double value = Convert.ToDouble(data[i, j]);
                            item.SubItems.Add(Math.Round(value, 2).ToString() + " грн");
                            sum += value;
                        }

                        else
                        {
                            item.SubItems.Add(data[i, j]);
                        }
                        if (j == 5 && data[i, j] == "Таблетки")
                        {
                            countPills++;
                        }
                        else if (j == 5 && data[i, j] == "Раствор")
                        {
                            countSolutes++;
                        }
                    }
                    MedicationsListView.Items.Add(item);
                }
            }

            else
            {
                dataSet = DisconnectedData.GetTableData(query);
                DataTable dataTable = dataSet.Tables[0];
                for (int i = 0; i < dataTable.Rows.Count; i++)
                {
                    DataRow dataRow = dataTable.Rows[i];
                    item = new ListViewItem(dataRow[0].ToString());
                    for (int j = 1; j < dataTable.Columns.Count; j++)
                    {
                        if (j == 2)
                        {
                            double value = Convert.ToDouble(dataRow[j]);
                            item.SubItems.Add(Math.Round(value, 2).ToString() + " грн");
                            sum += value;
                        }

                        else
                        {
                            item.SubItems.Add(dataRow[j].ToString());
                        }
                        if (j == 5 && dataRow[j].ToString() == "Таблетки")
                        {
                            countPills++;
                        }
                        else if (j == 5 && dataRow[j].ToString() == "Раствор")
                        {
                            countSolutes++;
                        }
                    }
                    MedicationsListView.Items.Add(item);
                }
            }


            LabelMedicationsSumPriceValue.Text   = Math.Round(sum, 2).ToString() + " грн";
            LabelMedicationsSumPillsValue.Text   = countPills.ToString();
            LabelMedicationsSumSolutesValue.Text = countSolutes.ToString();
        }
Example #41
0
        public void PrescriptionsPrint(SortTypes sort, string name = "")
        {
            PrescriptionsListView.Items.Clear();
            if (name != "")
            {
                query = Commands.SelectPrescriptions(sort, name);
            }
            else
            {
                query = Commands.SelectPrescriptions(sort);
            }
            ListViewItem item;

            if (connectionType == ConnectionTypes.Connected)
            {
                ConnectedData.SetCommand(query);
                int[] size = new int[2];
                size = ConnectedData.GetRowAndColumnCount();
                int row    = size[0];
                int column = size[1];
                string[,] data = new string[row, column];
                data           = ConnectedData.GetTableData();
                Dictionary <int, string> list  = GetPrescriptionsDiagnoses();
                Dictionary <int, string> list2 = GetPrescriptionsMedications();
                for (int i = 0; i < row; i++)
                {
                    item = new ListViewItem(data[i, 0]);
                    for (int j = 1; j < column; j++)
                    {
                        if (j == 4 || j == 5)
                        {
                            bool value = Convert.ToBoolean(data[i, j]);
                            if (value == true)
                            {
                                item.SubItems.Add("+");
                            }
                            else
                            {
                                item.SubItems.Add("-");
                            }
                        }

                        else
                        {
                            item.SubItems.Add(data[i, j]);
                        }
                    }

                    if (list.ContainsKey(Convert.ToInt32(data[i, 0])))
                    {
                        item.SubItems.Add(list[Convert.ToInt32(data[i, 0])]);
                    }
                    else
                    {
                        item.SubItems.Add("-");
                    }

                    if (list2.ContainsKey(Convert.ToInt32(data[i, 0])))
                    {
                        item.SubItems.Add(list2[Convert.ToInt32(data[i, 0])]);
                    }
                    else
                    {
                        item.SubItems.Add("-");
                    }

                    PrescriptionsListView.Items.Add(item);
                }
            }
            else
            {
                dataSet = DisconnectedData.GetTableData(query);
                DataTable dataTable = dataSet.Tables[0];
                for (int i = 0; i < dataTable.Rows.Count; i++)
                {
                    DataRow dataRow = dataTable.Rows[i];
                    item = new ListViewItem(dataRow[0].ToString());
                    for (int j = 1; j < dataTable.Columns.Count; j++)
                    {
                        if (j == 4 || j == 5)
                        {
                            bool value = Convert.ToBoolean(dataRow[j]);
                            if (value == true)
                            {
                                item.SubItems.Add("+");
                            }
                            else
                            {
                                item.SubItems.Add("-");
                            }
                        }

                        else
                        {
                            item.SubItems.Add(dataRow[j].ToString());
                        }
                    }
                    Dictionary <int, string> list  = GetPrescriptionsDiagnoses();
                    Dictionary <int, string> list2 = GetPrescriptionsMedications();
                    if (list.ContainsKey(Convert.ToInt32(dataRow[0])))
                    {
                        item.SubItems.Add(list[Convert.ToInt32(dataRow[0])]);
                    }
                    else
                    {
                        item.SubItems.Add("-");
                    }

                    if (list2.ContainsKey(Convert.ToInt32(dataRow[0])))
                    {
                        item.SubItems.Add(list2[Convert.ToInt32(dataRow[0])]);
                    }
                    else
                    {
                        item.SubItems.Add("-");
                    }
                    PrescriptionsListView.Items.Add(item);
                }
            }
        }
Example #42
0
        public void StorehouseFPrint(SortTypes sort, string name = "")
        {
            StorehouseFListView.Items.Clear();
            if (name != "")
            {
                query = Commands.SelectStorehouseF(sort, name);
            }
            else
            {
                query = Commands.SelectStorehouseF(sort);
            }
            ListViewItem item;

            if (connectionType == ConnectionTypes.Connected)
            {
                ConnectedData.SetCommand(query);
                int[] size = new int[2];
                size = ConnectedData.GetRowAndColumnCount();
                int row    = size[0];
                int column = size[1];
                string[,] data = new string[row, column];
                data           = ConnectedData.GetTableData();

                for (int i = 0; i < row; i++)
                {
                    item = new ListViewItem(data[i, 0]);

                    for (int j = 1; j < column; j++)
                    {
                        if (j == 5 || j == 6)
                        {
                            DateTime value = Convert.ToDateTime(data[i, j]);
                            item.SubItems.Add(value.ToShortDateString());
                        }

                        else
                        {
                            item.SubItems.Add(data[i, j]);
                        }
                    }
                    StorehouseFListView.Items.Add(item);
                }
            }
            else
            {
                dataSet = DisconnectedData.GetTableData(query);
                DataTable dataTable = dataSet.Tables[0];
                for (int i = 0; i < dataTable.Rows.Count; i++)
                {
                    DataRow dataRow = dataTable.Rows[i];
                    item = new ListViewItem(dataRow[0].ToString());
                    for (int j = 1; j < dataTable.Columns.Count; j++)
                    {
                        if (j == 5 || j == 6)
                        {
                            DateTime value = Convert.ToDateTime(dataRow[j]);
                            item.SubItems.Add(value.ToShortDateString());
                        }

                        else
                        {
                            item.SubItems.Add(dataRow[j].ToString());
                        }
                    }
                    StorehouseFListView.Items.Add(item);
                }
            }
        }
Example #43
0
 public AppViewModel(IMediator mediator, IAppContext context)
 {
     Commands.Add("Refresh", new Command(async _ => await mediator.Send(new Refresh.Request(context.Session?.Widget))));
 }
Example #44
0
 public Message(Commands command) : this()
 {
     Command = command;
 }
Example #45
0
        public static Command GetCommand(String commS)
        {
            Commands commE = GetEnumCommand(commS);

            return(GetCommand(commE));
        }
Example #46
0
 public void RemoveCommand(string commandName)
 {
     Commands.Remove(commandName);
 }
 private void performNumericSampling(Commands cmd, string param)
 {
     cmd.performOneCommand(ConfigurationBuilder.COMMAND_NUMERIC_SAMPLING + " " + param);
 }
Example #48
0
        /// <summary>
        /// Gives the number of bytes a message should have when coming back from scribbler.
        /// This includes the command type byte.
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        public int ReturnSize(Commands cmd)
        {
            switch (cmd)
            {
            case Commands.GET_STATE:
                return(3);

                break;

            case Commands.GET_IR_LEFT:
                return(2);

                break;

            case Commands.GET_IR_RIGHT:
                return(2);

                break;

            case Commands.GET_STALL:
                return(2);

                break;

            case Commands.GET_LIGHT_LEFT:
                return(3);

                break;

            case Commands.GET_LIGHT_CENTER:
                return(3);

                break;

            case Commands.GET_LIGHT_RIGHT:
                return(3);

                break;

            case Commands.GET_LINE_RIGHT:
                return(2);

                break;

            case Commands.GET_LINE_LEFT:
                return(2);

                break;

            case Commands.GET_NAME:
                return(9);

                break;

            case Commands.GET_LIGHT_ALL:
                return(7);

                break;

            case Commands.GET_IR_ALL:
                return(3);

                break;

            case Commands.GET_LINE_ALL:
                return(3);

                break;

            case Commands.GET_ALL:
                return(12);

                break;

            case Commands.GET_ALL_BINARY:
                return(2);

                break;

            case Commands.GET_INFO:
                return(37);

                break;

            case Commands.GET_DATA:
                return(9);

                break;

            case Commands.SET_MOTORS_OFF:
            case Commands.SET_MOTORS:
            case Commands.SET_LED_LEFT_ON:
            case Commands.SET_LED_LEFT_OFF:
            case Commands.SET_LED_CENTER_ON:
            case Commands.SET_LED_CENTER_OFF:
            case Commands.SET_LED_RIGHT_ON:
            case Commands.SET_LED_RIGHT_OFF:
            case Commands.SET_SPEAKER:
            case Commands.SET_SPEAKER_2:
            case Commands.SET_NAME:
            case Commands.SET_LED_ALL_ON:
            case Commands.SET_LED_ALL_OFF:
            case Commands.SET_LOUD:
            case Commands.SET_QUIET:
            case Commands.SET_LED_ALL:
            case Commands.SET_DATA:
            case Commands.SET_ECHO_MODE:
                return(SetMessageReturnLength);

                break;

            case Commands.SOFT_RESET:
                return(0);

                break;

            default:
                Console.WriteLine("Command missmatch");
                return(1);

                break;
            }
        }
Example #49
0
    private void OutputThreadMethod(TextWriter output)
    {
        Stopwatch stopWatch = new Stopwatch();

        stopWatch.Start();
        _messageDelay = 0;

        while (ThreadAlive)
        {
            try
            {
                Thread.Sleep(25);
                Commands command;
                if (stopWatch.ElapsedMilliseconds <= _messageDelay && _state == IRCConnectionState.Connected)
                {
                    continue;
                }
                lock (_commandQueue)
                {
                    if (_commandQueue.Count == 0)
                    {
                        continue;
                    }
                    command = _commandQueue.Dequeue();
                }

                if (command.CommandIsColor() &&
                    CurrentColor.Equals(command.GetColor(), StringComparison.InvariantCultureIgnoreCase))
                {
                    continue;
                }

                output.WriteLine(command.Command);
                output.Flush();

                stopWatch.Reset();
                stopWatch.Start();

                _messageDelay  = _isModerator ? MessageDelayMod : MessageDelayUser;
                _messageDelay += (command.CommandIsColor() && _isModerator) ? 700 : 0;
            }
            catch
            {
                AddTextToHoldable("[IRC:Disconnect] Connection failed.");
                _state = IRCConnectionState.Disconnected;
            }
        }
        TwitchGame.EnableDisableInput();

        try
        {
            if (_state == IRCConnectionState.Disconnecting)
            {
                Commands setColor = new Commands($"PRIVMSG #{_settings.channelName} :.color {ColorOnDisconnect}");
                if (setColor.CommandIsColor())
                {
                    AddTextToHoldable("[IRC:Disconnect] Color {0} was requested, setting it now.", ColorOnDisconnect);
                    while (stopWatch.ElapsedMilliseconds < _messageDelay)
                    {
                        Thread.Sleep(25);
                    }
                    output.WriteLine(setColor.Command);
                    output.Flush();

                    stopWatch.Reset();
                    stopWatch.Start();
                    while (stopWatch.ElapsedMilliseconds < 1200)
                    {
                        Thread.Sleep(25);
                    }
                }
                _state = IRCConnectionState.Disconnected;
                AddTextToHoldable("[IRC:Disconnect] Disconnected from chat IRC.");
            }

            lock (_commandQueue)
                _commandQueue.Clear();
        }
        catch
        {
            _state = IRCConnectionState.Disconnected;
        }
        if (!gameObject.activeInHierarchy)
        {
            AddTextToHoldable("[IRC:Disconnect] Twitch Plays disabled.");
        }
    }
Example #50
0
 public StatusMessage(Commands command) : base(command)
 {
 }
        /// <summary>
        /// Normalization of a git directory turns all remote branches into local branches, turns pull request refs into a real branch and a few other things. This is designed to be run *only on the build server* which checks out repositories in different ways.
        /// It is not recommended to run normalization against a local repository
        /// </summary>
        public static void NormalizeGitDirectory(ILog log, IEnvironment environment, string gitDirectory, AuthenticationInfo authentication,
                                                 bool noFetch, string currentBranch, bool isDynamicRepository)
        {
            using var repo = new Repository(gitDirectory);
            // Need to ensure the HEAD does not move, this is essentially a BugCheck
            var expectedSha        = repo.Head.Tip.Sha;
            var expectedBranchName = repo.Head.CanonicalName;

            try
            {
                var remote = EnsureOnlyOneRemoteIsDefined(log, repo);

                AddMissingRefSpecs(log, repo, remote);

                //If noFetch is enabled, then GitVersion will assume that the git repository is normalized before execution, so that fetching from remotes is not required.
                if (noFetch)
                {
                    log.Info("Skipping fetching, if GitVersion does not calculate your version as expected you might need to allow fetching or use dynamic repositories");
                }
                else
                {
                    Fetch(log, authentication, remote, repo);
                }

                EnsureLocalBranchExistsForCurrentBranch(log, repo, remote, currentBranch);
                CreateOrUpdateLocalBranchesFromRemoteTrackingOnes(log, repo, remote.Name);

                // Bug fix for https://github.com/GitTools/GitVersion/issues/1754, head maybe have been changed
                // if this is a dynamic repository. But only allow this in case the branches are different (branch switch)
                if (expectedSha != repo.Head.Tip.Sha &&
                    (isDynamicRepository || !expectedBranchName.IsBranch(currentBranch)))
                {
                    var newExpectedSha        = repo.Head.Tip.Sha;
                    var newExpectedBranchName = repo.Head.CanonicalName;

                    log.Info($"Head has moved from '{expectedBranchName} | {expectedSha}' => '{newExpectedBranchName} | {newExpectedSha}', allowed since this is a dynamic repository");

                    expectedSha = newExpectedSha;
                }

                var headSha = repo.Refs.Head.TargetIdentifier;

                if (!repo.Info.IsHeadDetached)
                {
                    log.Info($"HEAD points at branch '{headSha}'.");
                    return;
                }

                log.Info($"HEAD is detached and points at commit '{headSha}'.");
                log.Info(string.Format("Local Refs:\r\n" + string.Join(System.Environment.NewLine, repo.Refs.FromGlob("*").Select(r => $"{r.CanonicalName} ({r.TargetIdentifier})"))));

                // In order to decide whether a fake branch is required or not, first check to see if any local branches have the same commit SHA of the head SHA.
                // If they do, go ahead and checkout that branch
                // If no, go ahead and check out a new branch, using the known commit SHA as the pointer
                var localBranchesWhereCommitShaIsHead = repo.Branches.Where(b => !b.IsRemote && b.Tip.Sha == headSha).ToList();

                var matchingCurrentBranch = !string.IsNullOrEmpty(currentBranch)
                    ? localBranchesWhereCommitShaIsHead.SingleOrDefault(b => b.CanonicalName.Replace("/heads/", "/") == currentBranch.Replace("/heads/", "/"))
                    : null;
                if (matchingCurrentBranch != null)
                {
                    log.Info($"Checking out local branch '{currentBranch}'.");
                    Commands.Checkout(repo, matchingCurrentBranch);
                }
                else if (localBranchesWhereCommitShaIsHead.Count > 1)
                {
                    var          branchNames   = localBranchesWhereCommitShaIsHead.Select(r => r.CanonicalName);
                    var          csvNames      = string.Join(", ", branchNames);
                    const string moveBranchMsg = "Move one of the branches along a commit to remove warning";

                    log.Warning($"Found more than one local branch pointing at the commit '{headSha}' ({csvNames}).");
                    var master = localBranchesWhereCommitShaIsHead.SingleOrDefault(n => n.FriendlyName == "master");
                    if (master != null)
                    {
                        log.Warning("Because one of the branches is 'master', will build master." + moveBranchMsg);
                        Commands.Checkout(repo, master);
                    }
                    else
                    {
                        var branchesWithoutSeparators = localBranchesWhereCommitShaIsHead.Where(b => !b.FriendlyName.Contains('/') && !b.FriendlyName.Contains('-')).ToList();
                        if (branchesWithoutSeparators.Count == 1)
                        {
                            var branchWithoutSeparator = branchesWithoutSeparators[0];
                            log.Warning($"Choosing {branchWithoutSeparator.CanonicalName} as it is the only branch without / or - in it. " + moveBranchMsg);
                            Commands.Checkout(repo, branchWithoutSeparator);
                        }
                        else
                        {
                            throw new WarningException("Failed to try and guess branch to use. " + moveBranchMsg);
                        }
                    }
                }
                else if (localBranchesWhereCommitShaIsHead.Count == 0)
                {
                    log.Info($"No local branch pointing at the commit '{headSha}'. Fake branch needs to be created.");
                    CreateFakeBranchPointingAtThePullRequestTip(log, repo, authentication);
                }
                else
                {
                    log.Info($"Checking out local branch 'refs/heads/{localBranchesWhereCommitShaIsHead[0].FriendlyName}'.");
                    Commands.Checkout(repo, repo.Branches[localBranchesWhereCommitShaIsHead[0].FriendlyName]);
                }
            }
            finally
            {
                if (repo.Head.Tip.Sha != expectedSha)
                {
                    if (environment.GetEnvironmentVariable("IGNORE_NORMALISATION_GIT_HEAD_MOVE") != "1")
                    {
                        // Whoa, HEAD has moved, it shouldn't have. We need to blow up because there is a bug in normalisation
                        throw new BugException($@"GitVersion has a bug, your HEAD has moved after repo normalisation.

To disable this error set an environmental variable called IGNORE_NORMALISATION_GIT_HEAD_MOVE to 1

Please run `git {CreateGitLogArgs(100)}` and submit it along with your build log (with personal info removed) in a new issue at https://github.com/GitTools/GitVersion");
                    }
                }
            }
        }
Example #52
0
 /// <summary>
 /// Initializes a new instance of the class.
 /// </summary>
 /// <param name="panel">the scanner object</param>
 public Dispatcher(IScannerPanel panel)
     : base(panel)
 {
     Commands.Add(new CommandHandler("CmdGoBack"));
 }
Example #53
0
 public static void Execute()
 {
     Commands.HelpCommandCommon();
 }
Example #54
0
        public void Run(string[] args)
        {
            var ctx = new Context();

            // 初期値設定
            foreach (var flag in Flags)
            {
                ctx.GlobalFlagValues.Add(flag.Name, flag.Value);
            }

            Action <Context> action = Action == null ? writeHelpText: Action;

            // ContextのFlag、Args設定
            Command command = null;

            for (int i = 0; i < args.Length; i++)
            {
                var arg = args[i];
                // Option
                if (arg.Substring(0, 1) == "-")
                {
                    string optionName = arg.Substring(0, 2) == "--" ? arg.Substring(2) : arg.Substring(1);

                    if (command is null)
                    {
                        // Global Options
                        if (!Flags.Any(x => x.Names().Any(x => x == optionName)))
                        {
                            continue;
                        }
                        Flag flag = Flags.First(x => x.Names().Any(x => x == optionName));
                        if (flag is BoolFlag)
                        {
                            ctx.GlobalFlagValues[flag.Name] = true;
                        }
                        else
                        {
                            if (i + 1 < args.Length)
                            {
                                ctx.GlobalFlagValues[flag.Name] = args[++i];
                            }
                        }
                    }
                    else
                    {
                        // Command Options
                        Flag flag;
                        if (command.Flags.Any(x => x.Names().Any(x => x == optionName)))
                        {
                            flag = command.Flags.First(x => x.Names().Any(x => x == optionName));
                        }
                        else if (Flags.Any(x => x.Names().Any(x => x == optionName)))
                        {
                            flag = Flags.First(x => x.Names().Any(x => x == optionName));
                        }
                        else
                        {
                            continue;
                        }

                        if (flag is BoolFlag)
                        {
                            ctx.FlagValues[flag.Name] = true;
                        }
                        else
                        {
                            if (i + 1 < args.Length)
                            {
                                ctx.FlagValues[flag.Name] = args[++i];
                            }
                        }
                    }
                }
                else
                {
                    // Command or args
                    if (command is null)
                    {
                        if (Commands.Any(x => x.Names().Any(x => x == arg)))
                        {
                            command = Commands.First(x => x.Names().Any(x => x == arg));
                        }
                        else
                        {
                            ctx.Args = args.Skip(i).ToArray();
                            break;
                        }
                    }
                    else
                    {
                        if (command.SubCommands.Any(x => x.Names().Any(x => x == arg)))
                        {
                            command = command.SubCommands.First(x => x.Names().Any(x => x == arg));
                        }
                        else
                        {
                            ctx.Args = args.Skip(i).ToArray();
                            break;
                        }
                    }
                }
            }

            if (command is not null)
            {
                action = command.Action;
            }

            action.Invoke(ctx);
        }
Example #55
0
    public SemanticVersion Versionize(VersionizeOptions options)
    {
        var workingDirectory = _directory.FullName;

        using var repo = new Repository(workingDirectory);

        var isDirty = repo.RetrieveStatus(new StatusOptions()).IsDirty;

        if (!options.SkipDirty && isDirty)
        {
            Exit($"Repository {workingDirectory} is dirty. Please commit your changes.", 1);
        }

        var projects = Projects.Discover(workingDirectory);

        if (projects.IsEmpty())
        {
            Exit($"Could not find any projects files in {workingDirectory} that have a <Version> defined in their csproj file.", 1);
        }

        if (projects.HasInconsistentVersioning())
        {
            Exit($"Some projects in {workingDirectory} have an inconsistent <Version> defined in their csproj file. Please update all versions to be consistent or remove the <Version> elements from projects that should not be versioned", 1);
        }

        Information($"Discovered {projects.GetProjectFiles().Count()} versionable projects");
        foreach (var project in projects.GetProjectFiles())
        {
            Information($"  * {project}");
        }

        var versionTag       = repo.SelectVersionTag(projects.Version);
        var isInitialRelease = versionTag == null;
        var commitsInVersion = repo.GetCommitsSinceLastVersion(versionTag);

        var conventionalCommits = ConventionalCommitParser.Parse(commitsInVersion);

        var versionIncrement = new VersionIncrementStrategy(conventionalCommits);

        var nextVersion = isInitialRelease ? projects.Version : versionIncrement.NextVersion(projects.Version, options.Prerelease);

        // For non initial releases: for insignificant commits such as chore increment the patch version if IgnoreInsignificantCommits is not set
        if (!isInitialRelease && nextVersion == projects.Version)
        {
            if (options.IgnoreInsignificantCommits || options.ExitInsignificantCommits)
            {
                var exitCode = options.ExitInsignificantCommits ? 1 : 0;
                Exit($"Version was not affected by commits since last release ({projects.Version})", exitCode);
            }
            else
            {
                nextVersion = nextVersion.IncrementPatchVersion();
            }
        }

        if (!string.IsNullOrWhiteSpace(options.ReleaseAs))
        {
            try
            {
                nextVersion = SemanticVersion.Parse(options.ReleaseAs);
            }
            catch (Exception)
            {
                Exit($"Could not parse the specified release version {options.ReleaseAs} as valid version", 1);
            }
        }

        if (nextVersion < projects.Version)
        {
            Exit($"Semantic versioning conflict: the next version {nextVersion} would be lower than the current version {projects.Version}. This can be caused by using a wrong pre-release label or release as version", 1);
        }

        if (!options.DryRun && !options.SkipCommit && repo.VersionTagsExists(nextVersion))
        {
            Exit($"Version {nextVersion} already exists. Please use a different version.", 1);
        }

        var versionTime = DateTimeOffset.Now;

        // Commit changelog and version source
        if (!options.DryRun && (nextVersion != projects.Version))
        {
            projects.WriteVersion(nextVersion);

            foreach (var projectFile in projects.GetProjectFiles())
            {
                Commands.Stage(repo, projectFile);
            }
        }

        Step($"bumping version from {projects.Version} to {nextVersion} in projects");

        var changelog            = ChangelogBuilder.CreateForPath(workingDirectory);
        var changelogLinkBuilder = LinkBuilderFactory.CreateFor(repo);

        if (options.DryRun)
        {
            string markdown = ChangelogBuilder.GenerateMarkdown(nextVersion, versionTime, changelogLinkBuilder, conventionalCommits, options.Changelog);
            DryRun(markdown.TrimEnd('\n'));
        }
        else
        {
            changelog.Write(nextVersion, versionTime, changelogLinkBuilder, conventionalCommits, options.Changelog);
        }

        Step("updated CHANGELOG.md");

        if (!options.DryRun && !options.SkipCommit)
        {
            if (!repo.IsConfiguredForCommits())
            {
                Exit(@"Warning: Git configuration is missing. Please configure git before running versionize:
git config --global user.name ""John Doe""
$ git config --global user.email [email protected]", 1);
            }

            Commands.Stage(repo, changelog.FilePath);

            foreach (var projectFile in projects.GetProjectFiles())
            {
                Commands.Stage(repo, projectFile);
            }

            var author    = repo.Config.BuildSignature(versionTime);
            var committer = author;

            var releaseCommitMessage = $"chore(release): {nextVersion} {options.CommitSuffix}".TrimEnd();
            var versionCommit        = repo.Commit(releaseCommitMessage, author, committer);
            Step("committed changes in projects and CHANGELOG.md");

            repo.Tags.Add($"v{nextVersion}", versionCommit, author, $"{nextVersion}");
            Step($"tagged release as {nextVersion}");

            Information("");
            Information("i Run `git push --follow-tags origin master` to push all changes including tags");
        }
        else if (options.SkipCommit)
        {
            Information("");
            Information($"i Commit and tagging of release was skipped. Tag this release as `v{nextVersion}` to make versionize detect the release");
        }

        return(nextVersion);
    }
        public void ShowHelp(string commandName = null)
        {
            var headerBuilder = new StringBuilder("Usage:");

            for (var cmd = this; cmd != null; cmd = cmd.Parent)
            {
                cmd.IsShowingInformation = true;
                headerBuilder.Insert(6, $" {cmd.Name}");
            }

            CommandLineApplication target;

            if (commandName == null || string.Equals(Name, commandName, StringComparison.OrdinalIgnoreCase))
            {
                target = this;
            }
            else
            {
                target = Commands.SingleOrDefault(cmd => string.Equals(cmd.Name, commandName, StringComparison.OrdinalIgnoreCase));

                if (target != null)
                {
                    headerBuilder.AppendFormat(" {0}", commandName);
                }
                else
                {
                    target = this;
                }
            }

            var optionsBuilder   = new StringBuilder();
            var commandsBuilder  = new StringBuilder();
            var argumentsBuilder = new StringBuilder();

            if (target.Arguments.Any())
            {
                headerBuilder.Append(" [arguments]");

                argumentsBuilder.AppendLine();
                argumentsBuilder.AppendLine("Arguments:");
                var maxArgLen    = MaxArgumentLength(target.Arguments);
                var outputFormat = $"  {{0, -{maxArgLen + 2}}}{{1}}";
                foreach (var arg in target.Arguments)
                {
                    argumentsBuilder.AppendFormat(outputFormat, arg.Name, arg.Description);
                    argumentsBuilder.AppendLine();
                }
            }

            if (target.Options.Any())
            {
                headerBuilder.Append(" [options]");

                optionsBuilder.AppendLine();
                optionsBuilder.AppendLine("Options:");
                var maxOptLen    = MaxOptionTemplateLength(target.Options);
                var outputFormat = $"  {{0, -{maxOptLen + 2}}}{{1}}";
                foreach (var opt in target.Options)
                {
                    optionsBuilder.AppendFormat(outputFormat, opt.Template, opt.Description);
                    optionsBuilder.AppendLine();
                }
            }

            if (target.Commands.Any())
            {
                headerBuilder.Append(" [command]");

                commandsBuilder.AppendLine();
                commandsBuilder.AppendLine("Commands:");
                var maxCmdLen    = MaxCommandLength(target.Commands);
                var outputFormat = $"  {{0, -{maxCmdLen + 2}}}{{1}}";
                foreach (var cmd in target.Commands.OrderBy(c => c.Name))
                {
                    commandsBuilder.AppendFormat(outputFormat, cmd.Name, cmd.Description);
                    commandsBuilder.AppendLine();
                }

                if (OptionHelp != null)
                {
                    commandsBuilder.AppendLine();
                    commandsBuilder.AppendFormat("Use \"{0} [command] --help\" for more information about a command.", Name);
                    commandsBuilder.AppendLine();
                }
            }

            if (target.AllowArgumentSeparator)
            {
                headerBuilder.Append(" [[--] <arg>...]]");
            }

            headerBuilder.AppendLine();

            var nameAndVersion = new StringBuilder();

            nameAndVersion.AppendLine(GetFullNameAndVersion());
            nameAndVersion.AppendLine();

            Console.Write("{0}{1}{2}{3}{4}", nameAndVersion, headerBuilder, argumentsBuilder, optionsBuilder, commandsBuilder);
        }
 public override string ToString()
 {
     return(Commands.FirstOrDefault());
 }
        private TestResult RunCommand(Commands cmd, bool test, bool projRecurse = true)
        {
            VersionControlItemList items = GetItems(projRecurse);

            foreach (VersionControlItem it in items)
            {
                if (it.Repository == null)
                {
                    if (cmd != Commands.Publish)
                    {
                        return(TestResult.NoVersionControl);
                    }
                }
                else if (it.Repository.VersionControlSystem != null && !it.Repository.VersionControlSystem.IsInstalled)
                {
                    return(TestResult.Disable);
                }
            }

            bool res = false;

            try {
                switch (cmd)
                {
                case Commands.Update:
                    res = UpdateCommand.Update(items, test);
                    break;

                case Commands.Diff:
                    res = DiffCommand.Show(items, test);
                    break;

                case Commands.Log:
                    res = LogCommand.Show(items, test);
                    break;

                case Commands.Status:
                    res = StatusView.Show(items, test, false);
                    break;

                case Commands.Add:
                    res = AddCommand.Add(items, test);
                    break;

                case Commands.Remove:
                    res = RemoveCommand.Remove(items, test);
                    break;

                case Commands.Revert:
                    res = RevertCommand.Revert(items, test);
                    break;

                case Commands.Lock:
                    res = LockCommand.Lock(items, test);
                    break;

                case Commands.Unlock:
                    res = UnlockCommand.Unlock(items, test);
                    break;

                case Commands.Publish:
                    VersionControlItem it = items [0];
                    if (items.Count == 1 && it.IsDirectory && it.WorkspaceObject != null)
                    {
                        res = PublishCommand.Publish(it.WorkspaceObject, it.Path, test);
                    }
                    break;

                case Commands.Annotate:
                    res = BlameCommand.Show(items, test);
                    break;

                case Commands.CreatePatch:
                    res = CreatePatchCommand.CreatePatch(items, test);
                    break;

                case Commands.Ignore:
                    res = IgnoreCommand.Ignore(items, test);
                    break;

                case Commands.Unignore:
                    res = UnignoreCommand.Unignore(items, test);
                    break;

                case Commands.ResolveConflicts:
                    res = ResolveConflictsCommand.ResolveConflicts(items, test);
                    break;
                }
            }
            catch (Exception ex) {
                if (test)
                {
                    LoggingService.LogError(ex.ToString());
                }
                else
                {
                    MessageService.ShowException(ex, GettextCatalog.GetString("Version control command failed."));
                }
                return(TestResult.Disable);
            }

            return(res ? TestResult.Enable : TestResult.Disable);
        }
Example #59
0
 /// <summary>
 /// Constructs the PlayerDeath script event.
 /// </summary>
 /// <param name="system">The relevant command system.</param>
 public PlayerDeathScriptEvent(Commands system)
     : base(system, "playerdeathevent", true)
 {
 }
Example #60
0
 protected override void OnCommandsUpdated(EventArgs e)
 {
     base.OnCommandsUpdated(e);
     Commands.Add(new UserStatusChanged());
 }