/// <summary>
		/// Initialize a new instance of the <see cref="ConfigurationUICommand"/> class.
		/// </summary>		
		/// <param name="serviceProvider">The a mechanism for retrieving a service object; that is, an object that provides custom support to other objects.</param>
		/// <param name="text">The text for the command.</param>
		/// <param name="longText">The text that will be in the status bar.</param>
		/// <param name="commandState">One of the <see cref="CommandState"/> values.</param>		
		/// <param name="command">The command to execute.</param>		
		/// <param name="shortcut">A short cut for the command.</param>
		/// <param name="insertionPoint">One of the <see cref="InsertionPoint"/> values.</param>
		/// <param name="icon">The icon for the command.</param>
		public ConfigurationUICommand(IServiceProvider serviceProvider, string text,
			string longText, CommandState commandState,
			ConfigurationNodeCommand command, Shortcut shortcut,
			InsertionPoint insertionPoint, Icon icon) 
			: this(serviceProvider,
			text, longText, commandState, NodeMultiplicity.Allow, command, null,
			shortcut, insertionPoint, icon)
		{			
		}
示例#2
0
        public static void DrawButtonCommand(Graphics g, 
                                             VisualStyle style, 
                                             Direction direction, 
                                             Rectangle drawRect,
                                             CommandState state,
                                             Color baseColor,
                                             Color trackLight,
                                             Color trackBorder)
        {
            Rectangle rect = new Rectangle(drawRect.Left, drawRect.Top, drawRect.Width - 1, drawRect.Height - 1);

            // Draw background according to style
            switch(style)
            {
                case VisualStyle.Plain:
                    // Draw background with back color
                    using(SolidBrush backBrush = new SolidBrush(baseColor))
                        g.FillRectangle(backBrush, rect);

                    // Modify according to state
                    switch(state)
                    {
                        case CommandState.HotTrack:
                            DrawPlainRaised(g, rect, baseColor);
                            break;
                        case CommandState.Pushed:
                            DrawPlainSunken(g, rect, baseColor);
                            break;
                    }
                    break;
                case VisualStyle.IDE:
                    // Draw according to state
                    switch(state)
                    {
                        case CommandState.Normal:
                            // Draw background with back color
                            using(SolidBrush backBrush = new SolidBrush(baseColor))
                                g.FillRectangle(backBrush, rect);
                            break;
                        case CommandState.HotTrack:
                            g.FillRectangle(Brushes.White, rect);

                            using(SolidBrush trackBrush = new SolidBrush(trackLight))
                                g.FillRectangle(trackBrush, rect);

                            using(Pen trackPen = new Pen(trackBorder))
                                g.DrawRectangle(trackPen, rect);
                            break;
                        case CommandState.Pushed:
                            //TODO: draw in a darker background color
                            break;
                    }
                    break;
            }
        }
示例#3
0
 public MainWindow()
 {
     state = new CommandSelectingState(this);
     InitializeComponent();
     HookEvents();
     timer = new Timer<string>(PresentInput);
     parameterStoryboard = (Storyboard) Resources["Parameter"];
     resetStoryboard = (Storyboard) Resources["Reset"];
     displayOptionsStoryboard = (Storyboard) Resources["DisplayOptions"];
     showOtherLaunchablesStoryboard = (Storyboard) Resources["ShowOtherLaunchables"];
 }
 /// <summary>
 /// Initialize a new instance of the <see cref="ConfigurationUICommand"/> class.
 /// </summary>
 /// <param name="serviceProvider">The a mechanism for retrieving a service object; that is, an object that provides custom support to other objects.</param>
 /// <param name="text">The text for the command.</param>
 /// <param name="longText">The text that will be in the status bar.</param>
 /// <param name="commandState">One of the <see cref="CommandState"/> values.</param>
 /// <param name="multiplicity">One of the <see cref="NodeMultiplicity"/> values.</param>
 /// <param name="command">The command to execute.</param>
 /// <param name="nodeType">The node type that will be created when the command is executed.</param>
 /// <param name="shortcut">A short cut for the command.</param>
 /// <param name="insertionPoint">One of the <see cref="InsertionPoint"/> values.</param>
 /// <param name="icon">The icon for the command.</param>
 public ConfigurationUICommand(IServiceProvider serviceProvider, string text,
                               string longText, CommandState commandState, NodeMultiplicity multiplicity,
                               ConfigurationNodeCommand command, Type nodeType, Shortcut shortcut,
                               InsertionPoint insertionPoint, Icon icon)
 {
     this.text            = text;
     this.longText        = longText;
     this.commandState    = commandState;
     this.command         = command;
     this.nodeType        = nodeType;
     this.insertionPoint  = insertionPoint;
     this.shortcut        = shortcut;
     this.icon            = icon;
     this.serviceProvider = serviceProvider;
     this.multiplicity    = multiplicity;
 }
示例#5
0
        /// <summary>
        /// Updates command state for given command</summary>
        /// <remarks>This is used e.g. to set the check next to a menu command or
        /// to show a toolbar button as pressed</remarks>
        /// <param name="commandTag">Command</param>
        /// <param name="commandState">Command info to update</param>
        public void UpdateCommand(object commandTag, CommandState commandState)
        {
            //GameDocument document = m_contextRegistry.GetActiveContext<GameDocument>();
            //if (document == null)
            //    return;

            //if (commandTag is Command)
            //{
            //    switch ((Command)commandTag)
            //    {
            //        case Command.ToggleSplitMode:
            //            commandState.Check = document.SplitManipulator.Active;
            //            break;
            //    }
            //}
        }
        public void UpdateCommand(object commandTag, CommandState state)
        {
            if (!(commandTag is Command))
            {
                return;
            }

            switch ((Command)commandTag)
            {
            case Command.Toggle:
            {
                state.Check = m_bMemoryTracerRunning;
            }
            break;
            }
        }
示例#7
0
        public void CannotGetRemovedCommand()
        {
            var commandState        = new CommandState();
            var isAddCommandSuccess = commandState.TryAddAvailableCommand(_commandName, _command);
            var isGetCommandAfterAdditionSuccess = commandState.TryGetCommand(_commandName, out var retrievedCommandAfterAdd);
            var isRemoveCommandSuccess           = commandState.TryRemoveAvailableCommand(_commandName);
            var isGetCommandAfterRemovalSuccess  = commandState.TryGetCommand(_commandName, out var retrievedCommandAfterRemoval);

            Assert.IsTrue(isAddCommandSuccess);
            Assert.IsTrue(isGetCommandAfterAdditionSuccess);
            Assert.IsNotNull(retrievedCommandAfterAdd);
            Assert.IsTrue(isRemoveCommandSuccess);
            Assert.IsFalse(isGetCommandAfterRemovalSuccess);
            Assert.IsNull(retrievedCommandAfterRemoval);
            Assert.AreNotEqual(retrievedCommandAfterAdd, retrievedCommandAfterRemoval);
        }
示例#8
0
        private void ExecuteThread(object obj)
        {
            try
            {
                CommandState state = (CommandState)obj;

                Entity                 entity  = state.Entity;
                TunnelComponent        tunnel  = entity.Get <TunnelComponent>();
                DownloadRequestCommand command = new DownloadRequestCommand(entity, tunnel.Connection);
                command.Execute(state.Id, state.Data, state.Chunk);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
示例#9
0
        bool ICommandHandler.OnUpdateCommand(string MenuId, CommandState CommandState)
        {
            // enabled ist immer OK
            switch (MenuId)
            {
            case "MenuId.HatchStyleList.NewSolid":
                return(true);

            case "MenuId.HatchStyleList.NewLines":
                return(true);

            case "MenuId.HatchStyleList.NewContour":
                return(true);
            }
            return(false);
        }
		/// <summary>
		/// Initialize a new instance of the <see cref="ConfigurationUICommand"/> class.
		/// </summary>		
		/// <param name="serviceProvider">The a mechanism for retrieving a service object; that is, an object that provides custom support to other objects.</param>
		/// <param name="text">The text for the command.</param>
		/// <param name="longText">The text that will be in the status bar.</param>
		/// <param name="commandState">One of the <see cref="CommandState"/> values.</param>		
		/// <param name="multiplicity">One of the <see cref="NodeMultiplicity"/> values.</param>
		/// <param name="command">The command to execute.</param>		
		/// <param name="nodeType">The node type that will be created when the command is executed.</param>
		/// <param name="shortcut">A short cut for the command.</param>
		/// <param name="insertionPoint">One of the <see cref="InsertionPoint"/> values.</param>
		/// <param name="icon">The icon for the command.</param>
		public ConfigurationUICommand(IServiceProvider serviceProvider, string text,
			string longText, CommandState commandState, NodeMultiplicity multiplicity,
			ConfigurationNodeCommand command, Type nodeType, Shortcut shortcut, 
			InsertionPoint insertionPoint, Icon icon)
		{
			this.text = text;
			this.longText = longText;
			this.commandState = commandState;
			this.command = command;
			this.nodeType = nodeType;
			this.insertionPoint = insertionPoint;
			this.shortcut = shortcut;
			this.icon = icon;
			this.serviceProvider = serviceProvider;
			this.multiplicity = multiplicity;
		}
示例#11
0
        /// <summary>
        /// Get command lifecycle event id based on command state
        /// </summary>
        /// <param name="commandState"></param>
        /// <returns></returns>
        private static int GetCommandLifecycleEventId(CommandState commandState)
        {
            switch (commandState)
            {
            case CommandState.Started:
                return(_baseCommandLifecycleEventId);

            case CommandState.Stopped:
                return(_baseCommandLifecycleEventId + 1);

            case CommandState.Terminated:
                return(_baseCommandLifecycleEventId + 2);
            }

            return(_invalidEventId);
        }
示例#12
0
 private async Task ChangeState(CommandContext context, CommandState commandState)
 {
     if (!string.IsNullOrEmpty(context.Parameters))
     {
         var command = (new Regex(@"^/\w+", RegexOptions.IgnoreCase)).Match(context.Parameters).Value;
         if (!string.IsNullOrEmpty(command))
         {
             context.RedirectToCommand(command, commandState, context.Parameters.Replace(command, string.Empty), true);
         }
     }
     else
     {
         context.ChangeState(commandState);
         await BotClient.SendTextMessageAsync(context.Message.Chat, Localizer["ChangeState"]);
     }
 }
示例#13
0
        public void Undo()
        {
            // Remove the money from the original "to" account,
            // and add it back to the original "from" account.
            if (_toAccount.Balance >= _amount)
            {
                _toAccount.Balance   -= _amount;
                _fromAccount.Balance += _amount;

                Status = CommandState.UndoSucceeded;
            }
            else
            {
                Status = CommandState.UndoFailed;
            }
        }
示例#14
0
        // Initialization
        public void Start()
        {
            _fileSystemState = new FileSystemState();
            _terminalState   = new TerminalState();
            _commandState    = new CommandState();

            _directoryController     = new DirectoryController();
            _fileController          = new FileController();
            _permissionController    = new PermissionController();
            _userInterfaceController = new UserInterfaceController();
            _commandController       = new CommandController();

            _terminalStateInitializer   = new TerminalStateInitializer();
            _fileSystemStateInitializer = new FileSystemStateInitializer();
            _commandStateInitializer    = new CommandStateInitializer();
            _userInterfaceInitializer   = new UserInterfaceInitializer();

            _userInputParser = new UserInputParser();

            // Initialize the state of each system piece for game start
            _terminalStateInitializer.InitializeTerminalState(_terminalState, InputLengthCharacterLimit, InputHistoryLimit);
            _terminalStateInitializer.ClearTerminalState(_terminalState);

            var commandsInitialized = _commandStateInitializer.InitializeCommandState(
                _commandState,
                _terminalState,
                _fileSystemState,
                _directoryController);

            _fileSystemStateInitializer.InitializeFileSystemState(
                _fileSystemState,
                _permissionController,
                _directoryController);
            _fileSystemStateInitializer.InitializeCommandsInFileSystemState(
                _fileSystemState,
                _permissionController,
                _directoryController,
                _fileController,
                commandsInitialized);

            _userInterfaceInitializer.InitializeConsoleText(
                _userInterfaceController,
                _fileSystemState,
                _directoryController,
                InputTextObject,
                OutputTextObject);
        }
示例#15
0
 internal void SetCommand(int userId, int chatId, string command)
 {
     var commandState = GetCommandState(userId, chatId);
     if (commandState == null)
     {
         commandState = new CommandState();
     }
     if (string.IsNullOrEmpty(commandState.commandText) ||
         !commandState.commandText.Equals(command, StringComparison.InvariantCultureIgnoreCase))
     {
         commandState.commandText = command;
         commandState.chatId = chatId;
         commandState.userId = userId;
         commandState.Parameters.Clear();
     }
     Store(commandState);
 }
示例#16
0
        public static CommandState GetDesignRightState(CommandState originalState, CommandContext commandContext)
        {
            if (commandContext.Items[0] == null)
            {
                return(originalState);
            }

            // We don't want to enable it if it's disabled
            if (originalState != CommandState.Enabled)
            {
                return(originalState);
            }

            return(DesignAccessRight.IsAllowed(commandContext.Items[0], Context.User)
                ? originalState
                : CommandState.Hidden);
        }
示例#17
0
        public async Task SetEnabled(ulong channelId, bool enabled)
        {
            using (var context = new IAContext())
            {
                CommandState state = await context.CommandStates.FindAsync(Name, channelId.ToDbLong());

                if (state == null)
                {
                    state = context.CommandStates.Add(new CommandState()
                    {
                        ChannelId = channelId.ToDbLong(), CommandName = Name, State = DefaultEnabled
                    });
                }
                state.State = enabled;
                await context.SaveChangesAsync();
            }
        }
        private void ProcessCommandReplyMessage(CommandState state, ReplyMessage <RawBsonDocument> replyMessage, ConnectionId connectionId)
        {
            BsonDocument reply = replyMessage.Documents[0];
            BsonValue    ok;

            if (!reply.TryGetValue("ok", out ok))
            {
                // this is a degenerate case with the server and
                // we don't really know what to do here...
                return;
            }

            if (__securitySensitiveCommands.Contains(state.CommandName))
            {
                reply = new BsonDocument();
            }

            if (!ok.ToBoolean())
            {
                if (_failedEvent != null)
                {
                    _failedEvent(new CommandFailedEvent(
                                     state.CommandName,
                                     new MongoCommandException(
                                         connectionId,
                                         string.Format("{0} command failed", state.CommandName),
                                         null,
                                         reply),
                                     state.OperationId,
                                     replyMessage.ResponseTo,
                                     connectionId,
                                     state.Stopwatch.Elapsed));
                }
            }
            else if (_succeededEvent != null)
            {
                _succeededEvent(new CommandSucceededEvent(
                                    state.CommandName,
                                    reply,
                                    state.OperationId,
                                    replyMessage.ResponseTo,
                                    connectionId,
                                    state.Stopwatch.Elapsed));
            }
        }
示例#19
0
    // Use this for initialization
    void Start()
    {
        gameObject.transform.position = StartingPosition;
        _commandMap           = new Dictionary <CommandType, List <KeyCode> >();
        _currentCommandStates = new Dictionary <CommandType, CommandState>();

        foreach (CommandType type in System.Enum.GetValues(typeof(CommandType)))
        {
            _currentCommandStates[type] = new CommandState();
        }

        _commandMap[CommandType.MoveForward] = new List <KeyCode>(new KeyCode[] { KeyCode.UpArrow, KeyCode.W });
        _commandMap[CommandType.MoveBack]    = new List <KeyCode>(new KeyCode[] { KeyCode.DownArrow, KeyCode.S });
        _commandMap[CommandType.MoveLeft]    = new List <KeyCode>(new KeyCode[] { KeyCode.A });
        _commandMap[CommandType.MoveRight]   = new List <KeyCode>(new KeyCode[] { KeyCode.D });
        _commandMap[CommandType.RotateLeft]  = new List <KeyCode>(new KeyCode[] { KeyCode.LeftArrow, KeyCode.Q });
        _commandMap[CommandType.RotateRight] = new List <KeyCode>(new KeyCode[] { KeyCode.RightArrow, KeyCode.E });
    }
 public void GetCommandState()
 {
     currentCommandState = 0;
     for (int c = 0; c < GameEngine.gameEngine.CurrentMoveList().commandStates.Count; c++)
     {
         CommandState s = GameEngine.gameEngine.CurrentMoveList().commandStates[c];
         if (s.aerial == aerialFlag)
         {
             currentCommandState = c;
             return;
         }
         //if (s.wall == wallFlag)
         //{
         //    currentCommandState = c;
         //    return;
         //}
     }
 }
示例#21
0
    public virtual void Cancel()
    {
        if (this._state == CommandState.Running)
        {
            this._state = CommandState.Canceled;
            if (FrameWorkConfig.Open_DEBUG)
            {
                LogMgr.LogFormat("********* Cmd Cancel :{0}", this);
            }

            RunningList.Remove(this);

            if (AutoPoolManger)
            {
                this.Release(true);
            }
        }
    }
示例#22
0
文件: Command.cs 项目: menees/RpnCalc
        internal void PushResults(CommandState state, params Value[] valuesToPush)
        {
            // Make sure we have no double or complex values that
            // use #INF or #NaN.  Also, do value type reduction if it
            // will cause no "significant" data loss.
            var actualValuesToPush = ValidateAndReduce(valuesToPush);

            ValueStack stack = this.calc.Stack;

            if (this.topValuesUsedCount > 0)
            {
                this.lastArgs = stack.PopRange(this.topValuesUsedCount);
            }

            stack.PushRange(actualValuesToPush);

            this.state = state;
        }
示例#23
0
        bool ICommandHandler.OnUpdateCommand(string MenuId, CommandState CommandState)
        {
            switch (MenuId)
            {
            case "MenuId.Schedule.NewPosition":
                return(true);

            case "MenuId.Schedule.Sort":
                return(true);

            case "MenuId.Schedule.MakeCurrent":
                return(true);

            case "MenuId.Schedule.Remove":
                return(true);
            }
            return(false);
        }
        public override void LoadSubtitle(Subtitle subtitle, List <string> lines, string fileName)
        {
            _errorCount = 0;
            subtitle.Paragraphs.Clear();
            var       timeCodeList = new List <TimeCode>();
            Paragraph p            = null;
            var       header       = new StringBuilder();
            var       state        = new CommandState();

            char[] splitChars = { ':', ';', ',' };
            for (var index = 0; index < lines.Count; index++)
            {
                var line = lines[index];
                var s    = line.Trim();
                if (string.IsNullOrEmpty(s) || s.StartsWith("//", StringComparison.Ordinal) || s.StartsWith("File Format=MacCaption_MCC", StringComparison.Ordinal) || s.StartsWith("UUID=", StringComparison.Ordinal) ||
                    s.StartsWith("Creation Program=") || s.StartsWith("Creation Date=") || s.StartsWith("Creation Time=") ||
                    s.StartsWith("Code Rate=", StringComparison.Ordinal) || s.StartsWith("Time Code Rate=", StringComparison.Ordinal))
                {
                    header.AppendLine(line);
                }
                else
                {
                    var match = RegexTimeCodes.Match(s);
                    if (!match.Success)
                    {
                        continue;
                    }

                    var startTime = DecodeTimeCodeFrames(s.Substring(0, match.Length - 1), splitChars);
                    var text      = GetText(timeCodeList.Count, s.Substring(match.Index + match.Length).Trim(), index == lines.Count - 1, state);
                    timeCodeList.Add(startTime);
                    if (string.IsNullOrEmpty(text))
                    {
                        continue;
                    }

                    p = new Paragraph(new TimeCode(timeCodeList[state.StartLineIndex].TotalMilliseconds), new TimeCode(startTime.TotalMilliseconds), text);
                    subtitle.Paragraphs.Add(p);
                }
            }

            subtitle.RemoveEmptyLines();
            subtitle.Renumber();
        }
示例#25
0
        private void LegacyUpdateCommand(ICommandItem item)
        {
            ICommandClient client = GetClient(item.CommandTag);

            if (client == null)
            {
                client = m_activeClient;
            }

            if (client != null)
            {
                var commandState = new CommandState {
                    Text = item.Text, Check = item.IsChecked
                };
                client.UpdateCommand(item.CommandTag, commandState);
                item.Text      = commandState.Text.Trim();
                item.IsChecked = commandState.Check;
            }
        }
示例#26
0
 public CommandStateActor()
 {
     State         = CommandState.New;
     PersistenceId = Self.Path.Name;
     Command <AcceptCommandExecution>(a =>
     {
         if (State != CommandState.Executed)
         {
             Sender.Tell(Accepted.Instance);
         }
         else
         {
             Sender.Tell(Rejected.Instance);
         }
     });
     Command <CommandSucceed>(s => Persist(CommandState.Executed, e => State = e));
     Command <CommandFailed>(s => Persist(CommandState.Failed, e => State    = e));
     Recover <CommandState>(s => State = s);
 }
示例#27
0
        public static void WriteGCodeFile(this LoadBase load, StreamWriter sw)
        {
            Command last  = null;
            var     state = new CommandState();

            foreach (var r in load.Commands)
            {
                string[] cmds = r.GetGCodeCommands(last?.CalculatedEndPosition, state);
                if (cmds != null)
                {
                    foreach (string str in cmds)
                    {
                        sw.WriteLine(str);
                    }
                }

                last = r;
            }
        }
示例#28
0
        /// <summary>
        /// Updates command state for given command</summary>
        /// <param name="commandTag">Command</param>
        /// <param name="commandState">Command info to update</param>
        public void UpdateCommand(object commandTag, CommandState commandState)
        {
            TimelineDocument document = m_contextRegistry.GetActiveContext <TimelineDocument>();

            if (document == null)
            {
                return;
            }

            if (commandTag is Command)
            {
                switch ((Command)commandTag)
                {
                case Command.ToggleSplitMode:
                    commandState.Check = document.SplitManipulator != null ? document.SplitManipulator.Active : false;
                    break;
                }
            }
        }
示例#29
0
        protected void DoPushToFilter(CommandBase command)
        {
            Exception exception = null;
            bool      result;

            try
            {
                result = _filterManager.Process(command);
            }
            catch (Exception ex)
            {
                result    = false;
                exception = ex;
            }
            CommandState nextState = result ? CommandState.Executing
                                            : command.ShouldFailIfFiltered ? CommandState.Failed
                                                                           : CommandState.Pending;

            command.StartRequest(nextState, exception);
        }
示例#30
0
 private void WriteGCodeFile(string filename)
 {
     using (var sw = new StreamWriter(Environment.ExpandEnvironmentVariables(filename)))
     {
         Command last  = null;
         var     state = new CommandState();
         foreach (var r in Commands)
         {
             string[] cmds = r.GetGCodeCommands(last?.CalculatedEndPosition, state);
             if (cmds != null)
             {
                 foreach (string str in cmds)
                 {
                     sw.WriteLine(str);
                 }
             }
             last = r;
         }
     }
 }
示例#31
0
        public async Task SetEnabled(ICacheClient client, ulong channelId, bool enabled)
        {
            using (var context = new IAContext())
            {
                CommandState state = await context.CommandStates.FindAsync(Name, channelId.ToDbLong());

                if (state == null)
                {
                    state = context.CommandStates.Add(new CommandState()
                    {
                        ChannelId = channelId.ToDbLong(), CommandName = Name, State = DefaultEnabled
                    }).Entity;
                }
                state.State = enabled;

                await client.UpsertAsync(GetCacheKey(channelId), enabled);

                await context.SaveChangesAsync();
            }
        }
示例#32
0
        public override bool Execute()
        {
            Log.LogMessage(MessageImportance.Low, $"Task {nameof (CheckAdbTarget)}");
            Log.LogMessage(MessageImportance.Low, $"  {nameof (AdbTarget)}: {AdbTarget}");
            Log.LogMessage(MessageImportance.Low, $"  {nameof (SdkVersion)}: {SdkVersion}");

            state = CommandState.CheckSdk;
            base.Execute();

            if (IsValidTarget)
            {
                state = CommandState.CheckPM;
                base.Execute();
            }

            Log.LogMessage(MessageImportance.Low, $"  [Output] {nameof (AdbTarget)}: {AdbTarget}");
            Log.LogMessage(MessageImportance.Low, $"  [Output] {nameof (IsValidTarget)}: {IsValidTarget}");

            return(true);
        }
示例#33
0
 private static void BeginReceive(this Socket socket)
 {
     socket.TryAndLog(
         handler =>
     {
         var commandState = new CommandState
         {
             Handler     = handler,
             CommandData = new byte[Command.Command.SizeOf]
         };
         handler.BeginReceive(
             commandState.CommandData,
             0,
             commandState.CommandData.Length,
             0,
             commandState.ReceiveCallback,
             null
             );
     }
         );
 }
示例#34
0
        public override void Draw(IOutputCommand output, CommandState state, object param)
        {
            double I, J, K;

            if (!TryGetVariable('I', out I))
            {
                I = 0;
            }
            if (!TryGetVariable('J', out J))
            {
                J = 0;
            }
            if (!TryGetVariable('K', out K))
            {
                K = 0;
            }

            output.DrawArc(this, param, Convert(Movetype, state), CalculatedStartPosition, CalculatedEndPosition, new Framework.Tools.Drawing.Point3D {
                X = I, Y = J, Z = K
            }, true, state.CurrentPane);
        }
示例#35
0
 public void UpdateCommand()
 {
     foreach (MenuItem mi in MenuItems)
     {
         MenuItemWithHandler miid = mi as MenuItemWithHandler;
         if (mi.Tag is MenuWithHandler menuWithHandler)
         {
             if (menuWithHandler.Target != null)
             {
                 CommandState commandState = new CommandState();
                 menuWithHandler.Target.OnUpdateCommand(menuWithHandler.ID, commandState);
                 miid.Enabled = commandState.Enabled;
                 miid.Checked = commandState.Checked;
                 if (miid.IsParent)
                 {
                     RecurseCommandState(miid);
                 }
             }
         }
     }
 }
示例#36
0
文件: Command.cs 项目: unfernojp/ux
        public void Cancel()
        {
            if ( _state != CommandState.Executing ) { return; }

            _state = CommandState.Canceling;

            if ( _executeCoroutine != null ) {
                UXBehaviour.StopCoroutine( _executeCoroutine );

                if ( _processCoroutine != null ) {
                    UXBehaviour.StopCoroutine( _processCoroutine );
                }
            }

            _executeCoroutine = null;
            _processCoroutine = null;

            cancelProcess();

            _state = CommandState.Idling;

            UXEventDelegate.Execute( new UXEventData( this, UXEventData.onCancel, false ) );
        }
示例#37
0
 public TestCommand(CommandState state, bool shouldFailIfFiltered = false,
     Action<CommandState, Exception> startRequestAction = null, bool blockCanExecute = false, Func<ProcessorInput, bool> interpretResponseAction = null,
     bool shouldExecuteForever = false, TimeSpan? pendingTimeout = null, TimeSpan? executionTimeout = null,
     Action executeAction = null, bool shouldFailIfBlocked = false, Action<IProcessedCommand> beforeExecuteAction = null, Action<IProcessedCommand, Exception> errorAction = null,
     Action<IProcessedCommand> fullfillmentAction = null, Action<IProcessedCommand> completeAction = null, bool shouldCompleteAfterExecute = false, string groupId = null)
 {
     _startRequestAction = startRequestAction;
     _blockCanExecute = blockCanExecute;
     _interpretResponseAction = interpretResponseAction;
     _executeAction = executeAction;
     CurrentState = state;
     ShouldFailIfFiltered = shouldFailIfFiltered;
     ShouldExecuteForever = shouldExecuteForever;
     ShouldFailIfBlocked = shouldFailIfBlocked;
     ShouldCompleteAfterExecute = shouldCompleteAfterExecute;
     CommandGroup = groupId;
     PendingTimeout = pendingTimeout;
     ExecutingTimeout = executionTimeout;
     BeforeExecuteAction = beforeExecuteAction;
     CompleteAction = completeAction;
     FullfillmentAction = fullfillmentAction;
     ErrorAction = errorAction;
 }
示例#38
0
 private static void WireCommand(FrameworkElement element, ICommand newValue)
 {
     Debug.Assert(GetCommandState(element) == null);
     if (newValue != null)
     {
         var state = new CommandState(element);
         element.SetValue(CommandStateProperty, state);
         state._owner.MouseLeftButtonDown += source_MouseLeftButtonDown;
         newValue.CanExecuteChanged += state.Command_CanExecuteChanged;
     }
 }
示例#39
0
		public void Reset ()
		{
			if (!dontReset) {
				dontReset = true;
				if (hasCache) {
					switch (reader.NodeType) {
					case XmlNodeType.Text:
					case XmlNodeType.CDATA:
					case XmlNodeType.SignificantWhitespace:
					case XmlNodeType.Whitespace:
						reader.Read ();
						break;
					}
					switch (state) {
					case CommandState.ReadElementContentAsBase64:
					case CommandState.ReadElementContentAsBinHex:
						reader.Read ();
						break;
					}
				}
				base64CacheStartsAt = -1;
				state = CommandState.None;
				hasCache = false;
				dontReset = false;
			}
		}
示例#40
0
		private void CheckState (bool element, CommandState action)
		{
			if (state == CommandState.None) {
				if (textCache == null)
					textCache = new StringBuilder ();
				else
					textCache.Length = 0;
				if (action == CommandState.None)
					return; // for ReadValueChunk()
				if (reader.ReadState != ReadState.Interactive)
					return;
				switch (reader.NodeType) {
				case XmlNodeType.Text:
				case XmlNodeType.CDATA:
				case XmlNodeType.SignificantWhitespace:
				case XmlNodeType.Whitespace:
					if (!element) {
						state = action;
						return;
					}
					break;
				case XmlNodeType.Element:
					if (element) {
						if (!reader.IsEmptyElement)
							reader.Read ();
						state = action;
						return;
					}
					break;
				}
				throw new XmlException ((element ? 
					"Reader is not positioned on an element."
					: "Reader is not positioned on a text node."));
			}
			if (state == action)
				return;
			throw StateError (action);
		}
示例#41
0
        NpgsqlDataReader Execute(CommandBehavior behavior = CommandBehavior.Default)
        {
            Validate();
            if (!IsPrepared)
                ProcessRawQuery();
            LogCommand();

            State = CommandState.InProgress;
            try
            {
                _connector = Connection.Connector;

                // If a cancellation is in progress, wait for it to "complete" before proceeding (#615)
                lock (_connector.CancelLock) { }

                // Send protocol messages for the command
                // Unless this is a prepared SchemaOnly command, in which case we already have the RowDescriptions
                // from the Prepare phase (no need to send anything).
                if (!IsPrepared || (behavior & CommandBehavior.SchemaOnly) == 0)
                {
                    _connector.UserTimeout = CommandTimeout * 1000;

                    _sendState = SendState.Start;
                    _writeStatementIndex = 0;

                    if (IsPrepared)
                        Send(PopulateExecutePrepared);
                    else if ((behavior & CommandBehavior.SchemaOnly) == 0)
                        Send(PopulateExecuteNonPrepared);
                    else
                        Send(PopulateExecuteSchemaOnly);
                }

                var reader = new NpgsqlDataReader(this, behavior, _statements);
                reader.NextResult();
                _connector.CurrentReader = reader;
                return reader;
            }
            catch
            {
                State = CommandState.Idle;
                throw;
            }
        }
示例#42
0
 internal override void LogCommandLifecycleEvent(Func<LogContext> getLogContext, CommandState newState)
 {
     LogContext logContext = getLogContext();
     int commandLifecycleEventId = GetCommandLifecycleEventId(newState);
     if (commandLifecycleEventId != -1)
     {
         Hashtable mapArgs = new Hashtable();
         mapArgs["NewCommandState"] = newState.ToString();
         FillEventArgs(mapArgs, logContext);
         EventInstance entry = new EventInstance((long) commandLifecycleEventId, 5) {
             EntryType = EventLogEntryType.Information
         };
         string eventDetail = this.GetEventDetail("CommandLifecycleContext", mapArgs);
         this.LogEvent(entry, new object[] { logContext.CommandName, newState, eventDetail });
     }
 }
示例#43
0
文件: MshLog.cs 项目: 40a/PowerShell
        /// <summary>
        /// LogCommandLifecycleEvent: Log a command lifecycle event.
        /// 
        /// This is a form of CommandLifecycleEvent which takes a commandName instead
        /// of invocationInfo. It is likely that invocationInfo is not available if 
        /// the command failed security check. 
        /// </summary>
        /// <param name="executionContext">Execution Context for the current running engine</param>
        /// <param name="commandState">new command state</param>
        /// <param name="commandName">current command that is running</param>
        internal static void LogCommandLifecycleEvent(ExecutionContext executionContext,
                                                CommandState commandState,
                                                string commandName)
        {
            if (executionContext == null)
            {
                PSTraceSource.NewArgumentNullException("executionContext");
                return;
            }

            LogContext logContext = null;
            foreach (LogProvider provider in GetLogProvider(executionContext))
            {
                if (NeedToLogCommandLifecycleEvent(provider, executionContext))
                {
                    provider.LogCommandLifecycleEvent(
                        () =>
                        {
                            if (logContext == null)
                            {
                                logContext = GetLogContext(executionContext, null);
                                logContext.CommandName = commandName;
                            }
                            return logContext;
                        }, commandState);
                }
            }
        }
示例#44
0
        /// <summary>
        /// Provider interface function for logging command lifecycle event
        /// </summary>
        /// <param name="getLogContext"></param>
        /// <param name="newState"></param>
        /// 
        internal override void LogCommandLifecycleEvent(Func<LogContext> getLogContext, CommandState newState)
        {
            if (IsEnabled(PSLevel.Informational, PSKeyword.Cmdlets | PSKeyword.UseAlwaysAnalytic))
            {
                LogContext logContext = getLogContext();
                StringBuilder payload = new StringBuilder();

                if (logContext.CommandType != null)
                {
                    if (logContext.CommandType.Equals(StringLiterals.Script, StringComparison.OrdinalIgnoreCase))
                    {
                        payload.AppendLine(StringUtil.Format(EtwLoggingStrings.ScriptStateChange, newState.ToString()));
                    }
                    else
                    {
                        payload.AppendLine(StringUtil.Format(EtwLoggingStrings.CommandStateChange, logContext.CommandName, newState.ToString()));
                    }
                }

                PSTask task = PSTask.CommandStart;

                if (newState == CommandState.Stopped ||
                    newState == CommandState.Terminated)
                {
                    task = PSTask.CommandStop;
                }

                WriteEvent(PSEventId.Command_Lifecycle, PSChannel.Analytic, PSOpcode.Method, task, logContext, payload.ToString());
            }
        }
示例#45
0
 internal override void LogCommandLifecycleEvent(Func<LogContext> getLogContext, CommandState newState)
 {
 }
示例#46
0
 /// <summary>
 /// Public constructor. Creates a new command.
 /// </summary>
 /// <param name="text">A description for the current command.</param>
 public Command(string text)
 {
     _text = text;
     _state = CommandState.Waiting;
 }
 public CommandTimeoutException(string message, CommandState state)
     : base(message)
 {
     State = state;
 }
示例#48
0
文件: MshLog.cs 项目: nickchal/pash
 internal static void LogCommandLifecycleEvent(System.Management.Automation.ExecutionContext executionContext, CommandState commandState, InvocationInfo invocationInfo)
 {
     Func<LogContext> getLogContext = null;
     LogContext logContext;
     if (executionContext == null)
     {
         PSTraceSource.NewArgumentNullException("executionContext");
     }
     else if (invocationInfo == null)
     {
         PSTraceSource.NewArgumentNullException("invocationInfo");
     }
     else if (!ignoredCommands.Contains(invocationInfo.MyCommand.Name))
     {
         logContext = null;
         foreach (LogProvider provider in GetLogProvider(executionContext))
         {
             if (NeedToLogCommandLifecycleEvent(provider, executionContext))
             {
                 if (getLogContext == null)
                 {
                     getLogContext = () => logContext ?? (logContext = GetLogContext(executionContext, invocationInfo));
                 }
                 provider.LogCommandLifecycleEvent(getLogContext, commandState);
             }
         }
     }
 }
示例#49
0
		public int ReadValueChunk (
			char [] buffer, int offset, int length)
		{
			CommandState backup = state;
			if (state == CommandState.None)
				CheckState (false, CommandState.None);

			if (offset < 0)
				throw CreateArgumentOutOfRangeException ("offset", offset, "Offset must be non-negative integer.");
			else if (length < 0)
				throw CreateArgumentOutOfRangeException ("length", length, "Length must be non-negative integer.");
			else if (buffer.Length < offset + length)
				throw new ArgumentOutOfRangeException ("buffer length is smaller than the sum of offset and length.");

			if (length == 0)
				return 0;

			if (!hasCache) {
				if (reader.IsEmptyElement)
					return 0;
			}

			bool loop = true;
			while (loop && textCache.Length < length) {
				switch (reader.NodeType) {
				case XmlNodeType.Text:
				case XmlNodeType.CDATA:
				case XmlNodeType.SignificantWhitespace:
				case XmlNodeType.Whitespace:
					if (hasCache) {
						switch (reader.NodeType) {
						case XmlNodeType.Text:
						case XmlNodeType.CDATA:
						case XmlNodeType.SignificantWhitespace:
						case XmlNodeType.Whitespace:
							Read ();
							break;
						default:
							loop = false;
							break;
						}
					}
					textCache.Append (reader.Value);
					hasCache = true;
					break;
				default:
					loop = false;
					break;
				}
			}
			state = backup;
			int min = textCache.Length;
			if (min > length)
				min = length;
			string str = textCache.ToString (0, min);
			textCache.Remove (0, str.Length);
			str.CopyTo (0, buffer, offset, str.Length);
			if (min < length && loop)
				return min + ReadValueChunk (buffer, offset + min, length - min);
			else
				return min;
		}
示例#50
0
文件: MshLog.cs 项目: nickchal/pash
 internal static void LogCommandLifecycleEvent(System.Management.Automation.ExecutionContext executionContext, CommandState commandState, string commandName)
 {
     Func<LogContext> getLogContext = null;
     LogContext logContext;
     if (executionContext == null)
     {
         PSTraceSource.NewArgumentNullException("executionContext");
     }
     else
     {
         logContext = null;
         foreach (LogProvider provider in GetLogProvider(executionContext))
         {
             if (NeedToLogCommandLifecycleEvent(provider, executionContext))
             {
                 if (getLogContext == null)
                 {
                     getLogContext = delegate {
                         if (logContext == null)
                         {
                             logContext = GetLogContext(executionContext, null);
                             logContext.CommandName = commandName;
                         }
                         return logContext;
                     };
                 }
                 provider.LogCommandLifecycleEvent(getLogContext, commandState);
             }
         }
     }
 }
示例#51
0
		InvalidOperationException StateError (CommandState action)
		{
			return new InvalidOperationException (
				String.Format ("Invalid attempt to read binary content by {0}, while once binary reading was started by {1}", action, state));
		}
示例#52
0
        public override void StartRequest(CommandState currentState, Exception exception)
        {
            base.StartRequest(currentState, exception);

            if (_startRequestAction != null) _startRequestAction(currentState, exception);
        }
示例#53
0
文件: MshLog.cs 项目: 40a/PowerShell
        /// <summary>
        /// LogCommandLifecycleEvent: Log a command lifecycle event.
        /// 
        /// This is the only form of CommandLifecycleEvent logging api.
        /// </summary>
        /// <param name="executionContext">Execution Context for the current running engine</param>
        /// <param name="commandState">new command state</param>
        /// <param name="invocationInfo">invocation data for current command that is running</param>
        internal static void LogCommandLifecycleEvent(ExecutionContext executionContext,
                                                CommandState commandState,
                                                InvocationInfo invocationInfo)
        {
            if (executionContext == null)
            {
                PSTraceSource.NewArgumentNullException("executionContext");
                return;
            }

            if (invocationInfo == null)
            {
                PSTraceSource.NewArgumentNullException("invocationInfo");
                return;
            }

            if (s_ignoredCommands.Contains(invocationInfo.MyCommand.Name))
            {
                return;
            }

            LogContext logContext = null;
            foreach (LogProvider provider in GetLogProvider(executionContext))
            {
                if (NeedToLogCommandLifecycleEvent(provider, executionContext))
                {
                    provider.LogCommandLifecycleEvent(
                        () => logContext ?? (logContext = GetLogContext(executionContext, invocationInfo)), commandState);
                }
            }
        }
        private void ProcessReplyMessage(CommandState state, ResponseMessage message, IByteBuffer buffer, ConnectionId connectionId, MessageEncoderSettings encoderSettings)
        {
            state.Stopwatch.Stop();
            bool disposeOfDocuments = false;
            var replyMessage = message as ReplyMessage<RawBsonDocument>;
            if (replyMessage == null)
            {
                // ReplyMessage is generic, which means that we can't use it here, so, we need to use a different one...
                using (var stream = new ByteBufferStream(buffer, ownsBuffer: false))
                {
                    var encoderFactory = new BinaryMessageEncoderFactory(stream, encoderSettings);
                    replyMessage = (ReplyMessage<RawBsonDocument>)encoderFactory
                        .GetReplyMessageEncoder(RawBsonDocumentSerializer.Instance)
                        .ReadMessage();
                    disposeOfDocuments = true;
                }
            }

            try
            {
                if (replyMessage.CursorNotFound ||
                    replyMessage.QueryFailure ||
                    (state.ExpectedResponseType != ExpectedResponseType.Query && replyMessage.Documents.Count == 0))
                {
                    var queryFailureDocument = replyMessage.QueryFailureDocument;
                    if (__securitySensitiveCommands.Contains(state.CommandName))
                    {
                        queryFailureDocument = new BsonDocument();
                    }
                    if (_failedEvent != null)
                    {
                        _failedEvent(new CommandFailedEvent(
                            state.CommandName,
                            new MongoCommandException(
                                connectionId,
                                string.Format("{0} command failed", state.CommandName),
                                null,
                                queryFailureDocument),
                            state.OperationId,
                            replyMessage.ResponseTo,
                            connectionId,
                            state.Stopwatch.Elapsed));
                    }
                }
                else
                {
                    switch (state.ExpectedResponseType)
                    {
                        case ExpectedResponseType.Command:
                            ProcessCommandReplyMessage(state, replyMessage, connectionId);
                            break;
                        case ExpectedResponseType.GLE:
                            ProcessGLEReplyMessage(state, replyMessage, connectionId);
                            break;
                        case ExpectedResponseType.Query:
                            ProcessQueryReplyMessage(state, replyMessage, connectionId);
                            break;
                    }
                }
            }
            finally
            {
                if (disposeOfDocuments && replyMessage.Documents != null)
                {
                    replyMessage.Documents.ForEach(d => d.Dispose());
                }
            }
        }
示例#55
0
 /// <summary>
 /// Updates command state for given command</summary>
 /// <param name="commandTag">Command</param>
 /// <param name="state">Command state to update</param>
 public void UpdateCommand(object commandTag, CommandState state)
 {
 }
        private void ProcessCommandReplyMessage(CommandState state, ReplyMessage<RawBsonDocument> replyMessage, ConnectionId connectionId)
        {
            BsonDocument reply = replyMessage.Documents[0];
            BsonValue ok;
            if (!reply.TryGetValue("ok", out ok))
            {
                // this is a degenerate case with the server and 
                // we don't really know what to do here...
                return;
            }

            if (__securitySensitiveCommands.Contains(state.CommandName))
            {
                reply = new BsonDocument();
            }

            if (!ok.ToBoolean())
            {
                if (_failedEvent != null)
                {
                    _failedEvent(new CommandFailedEvent(
                        state.CommandName,
                        new MongoCommandException(
                            connectionId,
                            string.Format("{0} command failed", state.CommandName),
                            null,
                            reply),
                        state.OperationId,
                        replyMessage.ResponseTo,
                        connectionId,
                        state.Stopwatch.Elapsed));
                }
            }
            else if (_succeededEvent != null)
            {
                _succeededEvent(new CommandSucceededEvent(
                    state.CommandName,
                    reply,
                    state.OperationId,
                    replyMessage.ResponseTo,
                    connectionId,
                    state.Stopwatch.Elapsed));
            }
        }
示例#57
0
        private static int GetCommandLifecycleEventId(CommandState commandState)
        {
            switch (commandState)
            {
                case CommandState.Started:
                    return 500;

                case CommandState.Stopped:
                    return 0x1f5;

                case CommandState.Terminated:
                    return 0x1f6;
            }
            return -1;
        }
        private void ProcessGLEReplyMessage(CommandState state, ReplyMessage<RawBsonDocument> replyMessage, ConnectionId connectionId)
        {
            var reply = replyMessage.Documents[0];
            BsonValue ok;
            if (!reply.TryGetValue("ok", out ok))
            {
                // this is a degenerate case with the server and 
                // we don't really know what to do here...
            }
            else if (!ok.ToBoolean())
            {
                if (_failedEvent != null)
                {
                    _failedEvent(new CommandFailedEvent(
                        state.CommandName,
                        new MongoCommandException(
                            connectionId,
                            string.Format("{0} command failed", state.CommandName),
                            null,
                            reply),
                        state.OperationId,
                        replyMessage.ResponseTo,
                        connectionId,
                        state.Stopwatch.Elapsed));
                }
            }
            else if (_succeededEvent != null)
            {
                var fakeReply = new BsonDocument("ok", 1);

                BsonValue n;
                if (reply.TryGetValue("n", out n))
                {
                    fakeReply["n"] = n;
                }

                BsonValue err;
                if (reply.TryGetValue("err", out err) && err != BsonNull.Value)
                {
                    var code = reply.GetValue("code", -1);
                    var errmsg = err.ToString();
                    var isWriteConcernError = __writeConcernIndicators.Any(x => errmsg.Contains(x));
                    if (isWriteConcernError)
                    {
                        fakeReply["writeConcernError"] = new BsonDocument
                        {
                            { "code", code },
                            { "errmsg", err }
                        };
                    }
                    else
                    {
                        fakeReply["writeErrors"] = new BsonArray(new[] { new BsonDocument
                        {
                            { "index", 0 },
                            { "code", code },
                            { "errmsg", err }
                        }});
                    }
                }
                else if (state.CommandName == "insert")
                {
                    fakeReply["n"] = state.NumberOfInsertedDocuments;
                }
                else if (state.CommandName == "update")
                {
                    // Unfortunately v2.4 GLE does not include the upserted field when
                    // the upserted _id is non-OID type.  We can detect this by the
                    // updatedExisting field + an n of 1
                    BsonValue upsertedValue;
                    var upserted = reply.TryGetValue("upserted", out upsertedValue) ||
                        (n == 1 && !reply.GetValue("updatedExisting", false).ToBoolean());

                    if (upserted)
                    {
                        fakeReply["upserted"] = new BsonArray(new[] { new BsonDocument
                        {
                            { "index", 0 },
                            { "_id", upsertedValue ?? state.UpsertedId ?? BsonUndefined.Value }
                        }});
                    }
                }

                _succeededEvent(new CommandSucceededEvent(
                    state.CommandName,
                    fakeReply,
                    state.OperationId,
                    replyMessage.ResponseTo,
                    connectionId,
                    state.Stopwatch.Elapsed));
            }
        }
示例#59
0
 /// <summary>
 /// Provider interface function for logging command lifecycle event
 /// </summary>
 /// <param name="logContext"></param>
 /// <param name="newState"></param>
 /// 
 internal static void LogCommandLifecycleEvent(LogContext logContext, CommandState newState)
 {
     provider.LogCommandLifecycleEvent(() => logContext, newState);
 }
        private void ProcessQueryReplyMessage(CommandState state, ReplyMessage<RawBsonDocument> replyMessage, ConnectionId connectionId)
        {
            if (_succeededEvent != null)
            {
                BsonDocument reply;
                if (state.CommandName == "explain")
                {
                    reply = new BsonDocument("ok", 1);
                    reply.Merge(replyMessage.Documents[0]);
                }
                else
                {
                    var batchName = state.CommandName == "find" ? "firstBatch" : "nextBatch";
                    reply = new BsonDocument
                    {
                        { "cursor", new BsonDocument
                                    {
                                        { "id", replyMessage.CursorId },
                                        { "ns", state.QueryNamespace.FullName },
                                        { batchName, new BsonArray(replyMessage.Documents) }
                                    }},
                        { "ok", 1 }
                    };
                }

                _succeededEvent(new CommandSucceededEvent(
                    state.CommandName,
                    reply,
                    state.OperationId,
                    replyMessage.ResponseTo,
                    connectionId,
                    state.Stopwatch.Elapsed));
            }
        }