Esempio n. 1
0
        private object CopyDirectory(ICommandState state, string source)
        {
            var folder         = source;
            var folderName     = new DirectoryInfo(source).Name;
            var copyFolderName = $"Copy of {folderName}";

            var destination = _fileSystem.PathCombine(
                _fileSystem.PathCombine(new NPath(folder), new NPath(state.Target.Raw)),
                new NPath(copyFolderName));

            while (_fileSystem.DirectoryExists(destination))
            {
                folderName     = new DirectoryInfo(destination.Raw).Name;
                copyFolderName = $"Copy of {folderName}";
                destination    = _fileSystem.PathCombine(
                    _fileSystem.PathCombine(new NPath(folder), new NPath(state.Target.Raw)),
                    new NPath(copyFolderName));
            }

            CopyAll(new DirectoryInfo(source), new DirectoryInfo(destination.Raw));

            var folderResult = new
            {
                id    = destination.Raw,
                value = copyFolderName
            };

            return(folderResult);
        }
        public void StartProposing(ICommandState cmd)
        {
            ProposalState state;

            do
            {
                state = new ProposalState
                {
                    InitialValue   = cmd,
                    BallotNumber   = BallotStep + ballotBase,
                    ProposalNumber = GenerateNextProposalNumber(),
                    LastMessage    = DateTime.Now
                };
            } while (proposalsState.TryAdd(state.ProposalNumber, state) == false);

            foreach (var uri in allAcceptors)
            {
                SendAsync(uri, new Propose
                {
                    BallotNumber   = state.BallotNumber,
                    Originator     = orignatorUri,
                    ProposalNumber = state.ProposalNumber
                });
            }
        }
Esempio n. 3
0
        private object CopyFile(ICommandState state, string source)
        {
            // TODO: Run some tests on methods equivalency
            // to possibly remove code duplication.
            var folder       = Path.GetDirectoryName(source);
            var fileName     = Path.GetFileName(source);
            var copyFileName = $"Copy of {fileName}";
            var destination  = _fileSystem.PathCombine(
                _fileSystem.PathCombine(new NPath(folder), new NPath(state.Target.Raw)),
                new NPath(copyFileName));

            while (_fileSystem.FileExists(destination))
            {
                fileName     = Path.GetFileName(destination.Raw);
                copyFileName = $"Copy of {fileName}";
                destination  = _fileSystem.PathCombine(
                    _fileSystem.PathCombine(new NPath(folder), new NPath(state.Target.Raw)),
                    new NPath(copyFileName));
            }

            _fileSystem.CopyFile(new NPath(source), destination, true);
            var fileResult = new
            {
                id    = destination.Raw,
                value = copyFileName
            };

            return(fileResult);
        }
		public int CompareTo(ICommandState other)
		{
			var switchMasterCommand = other as SwitchMasterCommand;
			if (switchMasterCommand == null)
				return 1;
			return NewMaster.AbsoluteUri.CompareTo(switchMasterCommand.NewMaster.AbsoluteUri);
		}
        private ICommand ProcessCommand(CommandDto command, ICommandState state)
        {
            ICommand          typedCommand = null;
            ICommandProcessor processor    = null;
            // either take existing name from state, or construct from dto
            // the replace is a bit hacky, should probably clean the commandstore
            var commandName    = state == null ? command.Name  : state.CommandTypeId.Replace(command.Entity + "Command", "");
            var parametersJson = state == null ? command.ParametersJson : state.ParametersJson;

            if (_commandConfigs.TryGetValue(commandName + command.Entity + "Command", out ICommandConfig commandConfig))
            {
                typedCommand = commandConfig.GetCommand(parametersJson);
                processor    = commandConfig.Processor;
            }
            else if (_configs.TryGetValue(command.Entity, out IProcessorConfig config))
            {
                typedCommand = config.GetCommand(commandName, command.Entity, parametersJson);
                processor    = config.Processor;
            }
            if (typedCommand != null)
            {
                CopyCommandDtoIntoCommand(command, _repo, processor, typedCommand, state);

                typedCommand.Execute();
                typedCommand.ExecutedOn = _dateTimeProvider.GetUtcDateTime();

                return(typedCommand);
            }

            throw new CommandNotConfiguredException($"The command named '{command.Name}' for entity '{command.Entity}' does not have a matching configuration.");
        }
 public void ChangeState <T>(List <SceneObj> objs = null) where T : ICommandState, new()
 {
     _currentEvent?.OnStateExit();
     _currentEvent = new T {
         SceneObjs = objs
     };
     _currentEvent.OnStateStart();
 }
        private static void OnUpdatePropertyCommand(ICommandSource src, ICommandState state, object target)
        {
            string sourcePropertyName = state.GetValueOrDefault <string>(stateSourcePropertyName);

            if (sourcePropertyName == null)
            {
                Throw.InvalidOperationException(Res.ComponentModelMissingState(stateSourcePropertyName));
            }
            string targetPropertyName = state.GetValueOrDefault <string>(stateTargetPropertyName);

            if (targetPropertyName == null)
            {
                Throw.InvalidOperationException(Res.ComponentModelMissingState(stateTargetPropertyName));
            }

            object propertyValue         = null;
            bool   propertyValueObtained = false;

            if (src.EventArgs is PropertyChangedEventArgs e)
            {
                if (e.PropertyName != sourcePropertyName)
                {
                    return;
                }
                propertyValueObtained = e.TryGetNewPropertyValue(out propertyValue);
            }

            if (!propertyValueObtained)
            {
                object source = src.Source;
                propertyValue = source is IPersistableObject persistableSource && persistableSource.TryGetPropertyValue(sourcePropertyName, out propertyValue) ||
                                source is ICommandState stateSource && stateSource.TryGetValue(sourcePropertyName, out propertyValue)
                    ? propertyValue : Reflector.GetProperty(source, sourcePropertyName);
            }

            var formatValue = state.GetValueOrDefault <Func <object, object> >(stateFormatValue);

            if (formatValue != null)
            {
                propertyValue = formatValue.Invoke(propertyValue);
            }

            switch (target)
            {
            case IPersistableObject persistableTarget:
                persistableTarget.SetProperty(targetPropertyName, propertyValue);
                break;

            case ICommandState stateTarget:
                stateTarget[targetPropertyName] = propertyValue;
                break;

            default:
                Reflector.SetProperty(target, targetPropertyName, propertyValue);
                break;
            }
        }
        void ICommand.Execute(ICommandSource source, ICommandState state, object target, object parameter)
        {
            Action <ICommandSource <TEventArgs>, ICommandState> copy = callback;

            if (copy == null)
            {
                Throw.ObjectDisposedException();
            }
            copy.Invoke(source.Cast <TEventArgs>(), state);
        }
Esempio n. 9
0
        public int CompareTo(ICommandState other)
        {
            var switchMasterCommand = other as SwitchMasterCommand;

            if (switchMasterCommand == null)
            {
                return(1);
            }
            return(NewMaster.AbsoluteUri.CompareTo(switchMasterCommand.NewMaster.AbsoluteUri));
        }
Esempio n. 10
0
        void ICommand <TEventArgs> .Execute(ICommandSource <TEventArgs> source, ICommandState state, object target, object parameter)
        {
            Action <ICommandSource <TEventArgs>, ICommandState, TParam> copy = callback;

            if (copy == null)
            {
                Throw.ObjectDisposedException();
            }
            copy.Invoke(source, state, (TParam)parameter);
        }
        void ICommand.Execute(ICommandSource source, ICommandState state, object target)
        {
            Action <ICommandState> copy = callback;

            if (copy == null)
            {
                Throw.ObjectDisposedException();
            }
            copy.Invoke(state);
        }
Esempio n. 12
0
 public SubscriptionInfo(EventToKGyCommandExtension owner, object source, string eventName, ICommandState state)
 {
     this.owner     = owner;
     this.source    = source;
     this.eventName = eventName;
     commandState   = owner.State == null ? new CommandState() : state; // can be null even if there is a binding but the view is not loaded yet
     InitEnabledSync();
     if (source is FrameworkElement element)
     {
         element.RegisterOnDisposed((s, e) => syncEnabledBinding?.Dispose());
     }
 }
        public KGyCommandAdapter(ICommand command, CommandState state = null)
        {
            wrappedCommand = command;
            if (state == null)
            {
                return;
            }

            // if a state was passed to the constructor, then we sync its Enabled state with CanExecute
            this.state = state;
            state.CreatePropertyBinding(nameof(state.Enabled), nameof(CanExecute), this);
        }
Esempio n. 14
0
 private void InitState()
 {
     if (_state == null && _repository != null)
     {
         this._state = _repository.CreateCommandState();
         if (_state.Guid == null || _state.Guid == Guid.Empty)
         {
             _state.Guid = Guid.NewGuid();
         }
     }
     if (_state != null)
     {
         this._state.CommandTypeId = this.GetType().Name;
     }
 }
Esempio n. 15
0
            // This will be the actual handler method of the event.
            internal void Execute(object sender, TEventArgs e)
            {
                var src     = source as DependencyObject;
                var command = (ICommand)owner.Command.Evaluate(src);

                if (command == null)
                {
                    return;
                }
                ICommandState state     = State; // now it will not be null even if binding could not be resolved in constructor
                object        parameter = owner.Parameter?.Evaluate(src);

                if (state.Enabled)
                {
                    command.Execute(new CommandSource {
                        EventArgs = e, Source = source, TriggeringEvent = eventName
                    }, state, null, parameter);
                }
            }
Esempio n. 16
0
        private void LearnerOnOnAcceptedValue(ICommandState commandState)
        {
            var switchMasterCommand = commandState as SwitchMasterCommand;

            if (switchMasterCommand == null)
            {
                return;
            }
            if (switchMasterCommand.NewMaster == MasterSelectedByQuorum)
            {
                return;                 // nothing changed
            }
            IDictionary <string, string> value;

            lock (this)
            {
                if (switchMasterCommand.NewMaster == MasterSelectedByQuorum)
                {
                    return;                     // nothing changed
                }
                if (topologyState.TryGetValue(switchMasterCommand.NewMaster, out value) == false)
                {
                    // we got a master that we don't know of, let's discover the master
                    // which will initiate another master selection round
                    FindNewEndpointMetadata(switchMasterCommand.NewMaster);
                    return;
                }
                MasterSelectedByQuorum = switchMasterCommand.NewMaster;
            }

            TopologyChanged(this, new NodeMetadata
            {
                ChangeType  = TopologyChangeType.MasterSelected,
                ClusterName = clusterName,
                Metadata    = value,
                Uri         = MasterSelectedByQuorum
            });
        }
		public void StartProposing(ICommandState cmd)
		{
			ProposalState state;
			do
			{
				state = new ProposalState
				{
					InitialValue = cmd,
					BallotNumber = BallotStep + ballotBase,
					ProposalNumber = GenerateNextProposalNumber(),
					LastMessage = DateTime.Now
				};
			} while (proposalsState.TryAdd(state.ProposalNumber, state) == false);

			foreach (var uri in allAcceptors)
			{
				SendAsync(uri, new Propose
				{
					BallotNumber = state.BallotNumber,
					Originator = orignatorUri,
					ProposalNumber = state.ProposalNumber
				});
			}
		}
Esempio n. 18
0
        private bool Expects(Verb verb, Object obj, ICommandState commandState)
        {
            var call    = new DynamicCall(parsed.Expects, obj, preposition, indirectObject);
            var expects = new DynamicExpects(verb, parsed.Expects, call);

            var handled = false;
            var success = false;

            var before = CurrentRoom.Location.Before(verb.GetType());

            if (before != null)
            {
                commandState.State = CommandState.Before;
                handled            = before();
            }

            if (!handled)
            {
                commandState.State = CommandState.During;
                success            = expects.Invoke();

                if (success)
                {
                    var after = CurrentRoom.Location.After(verb.GetType());

                    if (after != null)
                    {
                        commandState.State = CommandState.After;
                        after();
                    }
                }
            }


            return(success);
        }
Esempio n. 19
0
 public QuizCommand()
 {
     CurrentState = new BeginGameState(this);
 }
Esempio n. 20
0
 public ExecutedEventArgs(ICommandState commandState, Exception exception)
 {
     CommandState = commandState;
     Exception    = exception;
 }
Esempio n. 21
0
 public void ChangeState(ICommandState newState)
 {
     _currentEvent?.OnStateExit();
     _currentEvent = newState;
     _currentEvent.OnStateStart();
 }
Esempio n. 22
0
 public void SetProcessed(ICommandState state)
 {
     throw new NotImplementedException();
 }
Esempio n. 23
0
        public MainForm(MainViewModel viewModel)
        {
            InitializeComponent();

            this.viewModel           = viewModel;
            grid.AutoGenerateColumns = true;

            errorProvider.Icon   = Images.Error;
            warningProvider.Icon = Images.Warning;
            infoProvider.Icon    = Images.Information;

            // For the better overview even the standard WinForms bindings are set here instead of the designer.

            // listBindingSource -> grid/listBox/errorProvider/tbIntPropList/tbStringPropList/editMenuStrip
            tbIntPropList.DataBindings.Add(nameof(TextBox.Text), listBindingSource, nameof(ITestObject.IntProp));
            tbStringPropList.DataBindings.Add(nameof(TextBox.Text), listBindingSource, nameof(ITestObject.StringProp));
            editMenuStrip.DataBindings.Add(nameof(editMenuStrip.DataSource), listBindingSource, String.Empty);

            // itemBindingSource -> tbIntPropCurrent/tbStringPropCurrent
            tbIntPropCurrent.DataBindings.Add(nameof(TextBox.Text), itemBindingSource, nameof(ITestObject.IntProp));
            tbStringPropCurrent.DataBindings.Add(nameof(TextBox.Text), itemBindingSource, nameof(ITestObject.StringProp));

            // A ToolStripButton does not support regular WinForms binding. But as it has a CheckedChanged event, KGy SOFT's command binding can be used for it.
            // btnChangeInner.Checked -> viewModel.ChangeUnderlyingCollection - AddPropertyBinding will use an internal command for the change event.
            commandBindings.AddPropertyBinding(btnChangeInner, nameof(btnChangeInner.Checked), nameof(viewModel.ChangeUnderlyingCollection), viewModel);

            // Binding radio buttons by KGy SOFT's command binding, too (regular WinForms binding behaves strangely for radio buttons).
            commandBindings.AddTwoWayPropertyBinding(viewModel, nameof(viewModel.UseList), rbList, nameof(RadioButton.Checked));
            commandBindings.AddTwoWayPropertyBinding(viewModel, nameof(viewModel.UseBindingList), rbBindingList, nameof(RadioButton.Checked));
            commandBindings.AddTwoWayPropertyBinding(viewModel, nameof(viewModel.UseSortableBindingList), rbSortableBindingList, nameof(RadioButton.Checked));
            commandBindings.AddTwoWayPropertyBinding(viewModel, nameof(viewModel.UseSortableBindingListSortOnChange), rbSortableBindingListSortOnChange, nameof(RadioButton.Checked));
            commandBindings.AddTwoWayPropertyBinding(viewModel, nameof(viewModel.UseObservableCollection), rbObservableCollection, nameof(RadioButton.Checked));
            commandBindings.AddTwoWayPropertyBinding(viewModel, nameof(viewModel.UseObservableBindingList), rbObservableBindingList, nameof(RadioButton.Checked));

            commandBindings.AddTwoWayPropertyBinding(viewModel, nameof(viewModel.NoInnerList), rbNoInnerList, nameof(RadioButton.Checked));
            commandBindings.AddTwoWayPropertyBinding(viewModel, nameof(viewModel.InnerList), rbInnerList, nameof(RadioButton.Checked));
            commandBindings.AddTwoWayPropertyBinding(viewModel, nameof(viewModel.InnerBindingList), rbInnerBindingList, nameof(RadioButton.Checked));
            commandBindings.AddTwoWayPropertyBinding(viewModel, nameof(viewModel.InnerSortableBindingList), rbInnerSortableBindingList, nameof(RadioButton.Checked));
            commandBindings.AddTwoWayPropertyBinding(viewModel, nameof(viewModel.InnerObservableCollection), rbInnerObservableCollection, nameof(RadioButton.Checked));
            commandBindings.AddTwoWayPropertyBinding(viewModel, nameof(viewModel.InnerObservableBindingList), rbInnerObservableBindingList, nameof(RadioButton.Checked));

            commandBindings.AddTwoWayPropertyBinding(viewModel, nameof(viewModel.UsePlainTestObject), rbObject, nameof(RadioButton.Checked));
            commandBindings.AddTwoWayPropertyBinding(viewModel, nameof(viewModel.UseObservableTestObject), rbObservableObject, nameof(RadioButton.Checked));
            commandBindings.AddTwoWayPropertyBinding(viewModel, nameof(viewModel.UseUndoableTestObject), rbUndoable, nameof(RadioButton.Checked));
            commandBindings.AddTwoWayPropertyBinding(viewModel, nameof(viewModel.UseEditableTestObject), rbEditable, nameof(RadioButton.Checked));
            commandBindings.AddTwoWayPropertyBinding(viewModel, nameof(viewModel.UseValidatingTestObject), rbValidating, nameof(RadioButton.Checked));
            commandBindings.AddTwoWayPropertyBinding(viewModel, nameof(viewModel.UseAllInOneTestObject), rbModel, nameof(RadioButton.Checked));

            // Binding to ViewModel Commands. Using a shared state for the indexing commands so we can set their Enabled status at once.
            // Adding PropertyCommandStateUpdater.Updater to them so their source buttons will reflect the Enabled state.
            commandsWithCurrentItemState = new CommandState {
                Enabled = false
            };
            commandBindings.Add(viewModel.AddItemCommand, btnAdd, nameof(btnAdd.Click));   // btnAdd.Click -> viewModel.AddItemCommand
            commandBindings.Add(viewModel.RemoveItemCommand, commandsWithCurrentItemState) // btnRemove.Click -> viewModel.RemoveItemCommand
            .WithParameter(() => listBindingSource.Current)
            .AddStateUpdater(PropertyCommandStateUpdater.Updater)
            .AddSource(btnRemove, nameof(btnRemove.Click));
            commandBindings.Add(viewModel.SetItemCommand, commandsWithCurrentItemState) // btnSetItem.Click -> viewModel.SetItemCommand
            .WithParameter(() => listBindingSource.Current)
            .AddStateUpdater(PropertyCommandStateUpdater.Updater)
            .AddSource(btnSetItem, nameof(btnSetItem.Click));
            commandBindings.Add(viewModel.SetItemPropertyCommand, commandsWithCurrentItemState) // btnSetProp.Click -> viewModel.SetItemPropertyCommand
            .WithParameter(() => listBindingSource.Current)
            .AddStateUpdater(PropertyCommandStateUpdater.Updater)
            .AddSource(btnSetProp, nameof(btnSetProp.Click));

            // Note that the following bindings don't reference any explicitly defined ICommands instances. We can do this for private commands not used by anyone else.
            commandBindings.Add <CommandErrorEventArgs>(OnCommandErrorHandler) // viewModel.CommandError -> OnCommandErrorHandler
            .AddSource(viewModel, nameof(viewModel.CommandError));
            commandBindings.Add <EventArgs>(OnRebindCommand)                   // this.Load/viewModel.PropertyChanged -> OnRebindCommand
            .AddSource(this, nameof(Load))
            .AddSource(viewModel, nameof(MainViewModel.PropertyChanged));
            commandBindings.Add(() => { }).AddSource(grid, nameof(grid.DataError));                 // grid.DataError: adding an empty handler so no dialogs will be popped up endlessly on errors
            commandBindings.Add <EventArgs>(OnListBindingSourceCurrentItemChangedCommand)           // listBindingSource.CurrentItemChanged -> OnListBindingSourceCurrentItemChangedCommand
            .AddSource(listBindingSource, nameof(listBindingSource.CurrentItemChanged));
            commandBindings.Add(OnResetBindingCommand).AddSource(btnReset, nameof(btnReset.Click)); // btnReset.Click -> OnResetBindingCommand

            // even static events are supported, provide a type as source:
            commandBindings.Add <ThreadExceptionEventArgs>(OnApplicationThreadExceptionCommand) // Application.ThreadException -> OnApplicationThreadExceptionCommand
            .AddSource(typeof(Application), nameof(Application.ThreadException));
        }
Esempio n. 24
0
 internal ExecuteCommandEventArgs(ICommandSource source, ICommandState state)
 {
     Source = source;
     State  = state;
 }
 public bool SaveState(ITelegramUser user, ICommandState state)
 {
     userState[user] = state;
     return(true);
 }
Esempio n. 26
0
 public void SetState(ICommandState state)
 {
     _state = state;
 }
Esempio n. 27
0
 public CommandBase(ICommandStateRepository repo, ICommandState state) : this(repo)
 {
     this._state = state;
 }
Esempio n. 28
0
 private static void OnPropertyChangedCommand(ICommandSource <PropertyChangedEventArgs> source, ICommandState state)
 {
     if (!source.EventArgs.PropertyName.In(state.GetValueOrDefault <string[]>(statePropertyNames)))
     {
         return;
     }
     state.GetValueOrDefault <Action>(stateHandler)?.Invoke();
 }
Esempio n. 29
0
 public void SetProcessed(ICommandState state)
 {
     //            state.UserName =
     //throw new NotImplementedException();
 }
Esempio n. 30
0
 public void AddCommandState(ICommandState state)
 {
     throw new NotImplementedException();
 }
Esempio n. 31
0
 void ICommand.Execute(ICommandSource source, ICommandState state, object target) => Throw.InternalError("Should never be invoked");
Esempio n. 32
0
 void ICommand <TEventArgs> .Execute(ICommandSource <TEventArgs> source, ICommandState state, object target) => command.Execute(source, state, target);
		private void LearnerOnOnAcceptedValue(ICommandState commandState)
		{
			var switchMasterCommand = commandState as SwitchMasterCommand;
			if (switchMasterCommand == null)
				return;
			if (switchMasterCommand.NewMaster == MasterSelectedByQuorum)
				return; // nothing changed

			IDictionary<string, string> value;
			lock (this)
			{
				if (switchMasterCommand.NewMaster == MasterSelectedByQuorum)
					return; // nothing changed


				if (topologyState.TryGetValue(switchMasterCommand.NewMaster, out value) == false)
				{
					// we got a master that we don't know of, let's discover the master
					// which will initiate another master selection round
					FindNewEndpointMetadata(switchMasterCommand.NewMaster);
					return;
				}
				MasterSelectedByQuorum = switchMasterCommand.NewMaster;
			}

			TopologyChanged(this, new NodeMetadata
			{
				ChangeType = TopologyChangeType.MasterSelected,
				ClusterName = clusterName,
				Metadata = value,
				Uri = MasterSelectedByQuorum
			});
		}