Exemple #1
0
    public void Update()
    {
        if (!IsEnabled)
        {
            return;
        }
        if (Input.GetKeyDown(_key))
        {
            Begin?.Invoke(this, _lastPosition = Input.mousePosition);
        }
        else if (Input.GetKey(_key))
        {
            Vector3 currentMousePosition = Input.mousePosition;
            if (_lastPosition != currentMousePosition)
            {
                Moved?.Invoke(this, currentMousePosition);
                _lastPosition = currentMousePosition;
            }

            Pressed?.Invoke(this, currentMousePosition);
        }
        else if (Input.GetKeyUp(_key))
        {
            Ended?.Invoke(this, Input.mousePosition);
            _lastPosition = Vector3.zero;
        }
    }
        public UploaderDemoForm(IHttpRequester httpRequester)
        {
            _view = new UploaderDemoFormView();
            _view.Attachments.SetImplementation(new ISomeService_OrderAttachment(httpRequester, () => 124, () => true));
            _attachments = LocalValueFieldBuilder.Build(new List <RemoteFileDescr>(), _view.Attachments,
                                                        (newValue, errors) => {
                errors.IfTrueAdd(newValue.Count > 10, "Maximum 10 files allowed");
            });

            //TODO this is experimental feature. It should be added by the above statement (if BeforeChange is supported in IView)
            _view.Attachments.BeforeChange += (newValue, isUser, preventProp) => {
                if (newValue.Count > 10)
                {
                    preventProp(new HashSet <string> {
                        "Maximum 10 files allowed"
                    });
                }
            };

            var mayConfirm = new AggregatedErrorsValue <bool>(
                false, self => !self.Errors.Any(), x => x.Observes(_attachments));

            var confirm = LocalActionBuilder.Build(_view.Confirm, () => Ended?.Invoke(this, Unit.Instance));

            confirm.BindEnableAndInitialize(mayConfirm);
        }
Exemple #3
0
        /// <summary>
        /// 获取是否存在指定远程文件
        /// </summary>
        /// <param name="edi"></param>
        /// <returns></returns>
        public bool ExistFile(ExistDataItem edi)
        {
            edi.Exist = false;
            try
            {
                string   filename = edi.Target.Replace(CurrentRemotePath + Path.AltDirectorySeparatorChar, "");
                string[] s        = List(filename);
                if (s.Length == 0)
                {
                    throw new IOException("not found " + filename);
                }

                edi.Success = true;
                edi.Exist   = true;
                if (edi.Replied)
                {
                    Ended?.Invoke(edi);
                }
            }
            catch (IOException ex)
            {
                edi.Message = ex.Message;
                edi.Success = false;
                edi.Exist   = false;
            }

            return(edi.Exist);
        }
Exemple #4
0
 protected virtual void StopInternal()
 {
     Ended.TrySetResult(true);
     State = PlayState.Stopped;
     AudioLayer.SourceStop(SoundInstance.Source);
     RestartInternal();
 }
Exemple #5
0
        public void Start()
        {
            if (_real.IsRunning)
            {
                return;
            }

            _real.Start();
            _updateTimer.Start();
            Task.Run(() =>
            {
                while (_real.IsRunning)
                {
                    if (Time - _real.Elapsed <= new TimeSpan(0, 0, 0, 0))
                    {
                        break;
                    }
                    Thread.Sleep(150);
                }

                if (Time - _real.Elapsed <= new TimeSpan(0, 0, 0, 0))
                {
                    Stop();
                    Reset();
                    Ended?.Invoke(this, null);
                }
            });
        }
Exemple #6
0
 protected void OnEnded()
 {
     if (Ended != null)
     {
         Ended.Invoke(this);
     }
 }
        public DataboundDatagridItemCreatorForm(ISomeService someService)
        {
            _view = new DataboundDatagridItemCreatorFormView();

            var someText   = LocalValueFieldBuilder.Build(_view.SomeText, Validator.IsNotNullRef);
            var someNumber = LocalValueFieldBuilder.BuildNullableInt(_view.SomeNumber, Validator.IsNotNull, Validator.MustBePositive <int>());
            var someBool   = LocalValueFieldBuilder.Build(_view.SomeBool);

            _view.SomeTrait.PermittedValues = EnumExtensions.GetEnumValues <SomeTraitType>().Select(x => (SomeTraitType?)x);
            var someTrait = LocalValueFieldBuilder.Build(_view.SomeTrait, Validator.IsNotNull);

            var createProduct = RemoteActionBuilder.Build(_view.CreateAction,
                                                          () => someService.Create(
                                                              new SomeDto {
                SomeNumber = someNumber.Value.GetValueOrDefault(),
                SomeText   = someText.Value,
                SomeBool   = someBool.Value,
                SomeTrait  = someTrait.Value.Value
            }),
                                                          x => {
                CreatedItem = x;
                Ended?.Invoke(this, Outcome.Created);
            });

            var isFormValid = new AggregatedErrorsValue <bool>(false, self => !self.Errors.Any(), x => {
                x.Observes(someText);
                x.Observes(someNumber);
                x.Observes(someBool);
                x.Observes(someTrait);
            });

            createProduct.BindEnableAndInitialize(isFormValid);
        }
Exemple #8
0
 internal void SetAsFinished()
 {
     if (!Ended.IsSet)
     {
         Ended.Set();
     }
 }
Exemple #9
0
        public async void Execute(object parameter)
        {
            IsExecuting = true;
            Started?.Invoke(this, EventArgs.Empty);

            await Task.Run(() =>
            {
                _execute(_cancelCommand.Token);
            }, _cancelCommand.Token)
            .ContinueWith(t =>
            {
                var error = t.Exception?.InnerException;

                if (_postAction != null)
                {
                    _postAction.Invoke(new RunWorkerCompletedEventArgs(null, error, t.IsCanceled));
                    error = null;
                }
                IsExecuting = false;
                Ended?.Invoke(this, EventArgs.Empty);

                if (_postAction == null && error != null)
                {
                    throw error;
                }
            }, TaskScheduler.FromCurrentSynchronizationContext());
        }
        public async Task RunAsync(CancellationToken ct)
        {
            this._CurrentCount = Seconds;
            Started?.Invoke(this, Seconds);
            timer.Start();
            int Counter = Seconds;
            await Task.Run(async() =>
            {
                while (!ct.IsCancellationRequested && timer.Enabled && Counter > 0)
                {
                    try
                    {
                        await Task.Delay(1000, ct);
                    }
                    catch (Exception ex)
                    {
                        timer.Stop();
                    }
                    Counter--;
                    Tick?.Invoke(this, Counter);
                }
            });

            Ended?.Invoke(this, new EventArgs());
        }
Exemple #11
0
        private void GenerateFlat(DataItem parent)
        {
            Beginning.Raise(this, EventArgs.Empty);

            var items = s_random.Next(5, 16);

            for (var i = 0; i < items; i++)
            {
                var data = CreateItem(parent);
                data.ItemChanged += DataItemChanged;

                if (parent != null)
                {
                    parent.Children.Add(data);
                }
                else
                {
                    m_data.Add(data);
                }

                ItemInserted.Raise(this, new ItemInsertedEventArgs <object>(-1, data, parent));
            }

            if (parent != null)
            {
                ItemChanged.Raise(this, new ItemChangedEventArgs <object>(parent));
            }

            Ending.Raise(this, EventArgs.Empty);
            Ended.Raise(this, EventArgs.Empty);
        }
        public async Task ServiceBusWaitAndCheckTrueTest()
        {
            const int TIMEOUT          = 10000;
            const int SHOULDBELESSTHAN = 2000;

            var topic        = Guid.NewGuid().ToString();
            var subscription = Guid.NewGuid().ToString();
            var filter       = "foobar";

            await EnsureTopicExists(_d.Settings.ServiceBusAccount, topic);

            Ended endedHow = Ended.Unknown;

            try
            {
                var sw = new Stopwatch();
                sw.Start();

                await using (var waitAndCheck = new ServiceBusWaitAndCheck(_d.Settings.ServiceBusAccount, topic, subscription, filter, () => { return(Task.FromResult(true)); }, TIMEOUT))
                {
                    await waitAndCheck.WaitAsync();

                    endedHow = waitAndCheck.EndedHow;
                }

                sw.Stop();

                Assert.IsTrue(sw.ElapsedMilliseconds <= SHOULDBELESSTHAN);
            }
            finally
            {
                await DeleteTopic(_d.Settings.ServiceBusAccount, topic);
            }
        }
Exemple #13
0
        private async Task Combatant_Death(IEntity deadCombatant)
        {
            deadCombatant.Died -= Combatant_Death;

            Dead.Add(deadCombatant);

            Debug.WriteLine("Combatant Died " + deadCombatant.Name);


            // figure out how many are alive per faction

            foreach (var faction in Factions.Keys.ToList())
            {
                // if a faction has no members alive then we are ending
                var aliveCount = Factions[faction].Count(e => !Dead.Contains(e));
                if (aliveCount == 0)
                {
                    _ended = true;
                    foreach (var combatant in Combatants.Keys.ToList())
                    {
                        combatant.Died -= Combatant_Death;
                    }


                    if (Ended != null)
                    {
                        await Ended.Invoke(this, EncounterEndings.Death);
                    }

                    //break;
                    return;
                }
            }
        }
Exemple #14
0
        private void ModifySelected(IEnumerable <object> selection)
        {
            Beginning.Raise(this, EventArgs.Empty);

            foreach (var obj in selection)
            {
                var data = obj.As <DataItem>();
                if (data == null)
                {
                    continue;
                }

                switch (data.Type)
                {
                case DataType.Integer:
                    data.Value = (int)data.Value + s_random.Next(2, 6);
                    break;

                case DataType.String:
                    data.Value = string.Format("{0}{1}", data.Value, Alphabet[s_random.Next(0, Alphabet.Length)]);
                    break;
                }

                ItemChanged.Raise(this, new ItemChangedEventArgs <object>(data));
            }

            Ending.Raise(this, EventArgs.Empty);
            Ended.Raise(this, EventArgs.Empty);
        }
Exemple #15
0
        /// <summary>
        /// Invoked when the post process script exits.
        /// </summary>
        private void OnPostProcessDlProcessExited(object sender, EventArgs e)
        {
            // Invoke the ended callback when the process exits.
            var exitCode = ((postProcess?.ExitCode ?? 1) == 0) ? 0 : (int)ExitCodes.Error;

            Ended?.Invoke(this, postProcess?.ExitCode ?? 1);
        }
Exemple #16
0
        public VerticalMenuForm(
            string title,
            IEnumerable <T> menuItems,
            Func <T, string> menuItemLabel,
            Func <string, IActionView <HTMLElement> > actionBuilder,
            bool isCancellable = true)
        {
            _title         = title;
            _isCancellable = isCancellable;

            _view = new VerticalMenuFormView(
                (act, lbl) => {
                var res        = actionBuilder(lbl);
                res.Triggered += () => act.Invoke();
                return(res);
            });

            _view.MenuItems = menuItems.Select(x => {
                var xCpy = x;
                return(Tuple.Create <Action, string>(() => {
                    Chosen = xCpy;
                    Ended?.Invoke(this, CompletedOrCanceled.Completed);
                }, menuItemLabel(x)));
            });
        }
Exemple #17
0
        /// <summary>
        /// Triggers the optimization job end event
        /// </summary>
        protected virtual void TriggerOnEndEvent()
        {
            if (_disposed)
            {
                return;
            }
            SetOptimizationStatus(OptimizationStatus.Completed);

            var result = Strategy.Solution;

            if (result != null)
            {
                var constraint = NodePacket.Constraints != null ? $"Constraints: ({string.Join(",", NodePacket.Constraints)})" : string.Empty;
                Log.Trace($"LeanOptimizer.TriggerOnEndEvent({GetLogDetails()}): Optimization has ended. " +
                          $"Result for {OptimizationTarget}: was reached using ParameterSet: ({result.ParameterSet}) backtestId '{result.BacktestId}'. " +
                          $"{constraint}");
            }
            else
            {
                Log.Trace($"LeanOptimizer.TriggerOnEndEvent({GetLogDetails()}): Optimization has ended. Result was not reached");
            }

            // we clean up before we send an update so that the runtime stats are updated
            CleanUpRunningInstance();
            ProcessUpdate(forceSend: true);

            Ended?.Invoke(this, result);
        }
Exemple #18
0
        public SomeChoicesForm()
        {
            _view = new SomeChoicesFormView();

            LocalActionBuilder.Build(_view.First, () => Ended?.Invoke(this, Outcome.FirstChoice));
            LocalActionBuilder.Build(_view.Second, () => Ended?.Invoke(this, Outcome.SecondChoice));
        }
        public PhotoTakerForm(PhotoTakerFormView view)
        {
            _view = view;
            LocalActionBuilder.Build(_view.TakePhoto, () => _view.InputFile.Click());
            LocalActionBuilder.Build(_view.AcceptPhoto, () => {
                _view.ResetPreviewStyle(true);
                Ended?.Invoke(this, CompletedOrCanceled.Completed);
            });
            LocalActionBuilder.Build(_view.RetryPhoto, () => {
                _view.ClearImage();
                _view.InputFile.Click();
            });

            _view.InputFile.OnChange += _ => {
                var files = _view.InputFile.Files;
                if (files == null || files.Length <= 0)
                {
                    Logger.Debug(GetType(), "got no files");
                    return;
                }
                Logger.Debug(GetType(), "got files {0}", files.Length);

                var fr = new FileReader();
                fr.OnLoad += ev => {
                    _view.SetImageFromDataUrl((string)fr.Result);
                };
                fr.ReadAsDataURL(files[0]);
            };
        }
Exemple #20
0
 private void Reload()
 {
     Beginning.Raise(this, EventArgs.Empty);
     Reloaded.Raise(this, EventArgs.Empty);
     Ending.Raise(this, EventArgs.Empty);
     Ended.Raise(this, EventArgs.Empty);
 }
 /// <summary>
 /// 结束构造(触发Ended事件。)
 /// </summary>
 protected virtual void OnEnd()
 {
     if (!_ended)
     {
         _ended = true;
         Ended?.Invoke(this, System.EventArgs.Empty);
     }
 }
Exemple #22
0
 private void MediaPlayer_MediaEnded(object sender, RoutedEventArgs e)
 {
     Ended?.Invoke(this, EventArgs.Empty);
     if (_active && IsLooped)
     {
         ResetAndPlay();
     }
 }
Exemple #23
0
 public IoTSoundPlayer(Context context)
 {
     this.context       = context;
     player             = new MediaPlayer();
     player.Completion += (sender, e) => {
         Ended?.Invoke(this, EventArgs.Empty);
     };
 }
Exemple #24
0
 public void Restart()
 {
     ElapsedTime = 0;
     if (!Repetitive)
     {
         Ended.Invoke(this, new AnimationEndedEventArgs());
     }
 }
Exemple #25
0
        private IEnumerator CooldownCoroutine()
        {
            Started?.Invoke();
            IsRunning = true;
            yield return(new WaitForSeconds(duration));

            Ended?.Invoke();
            IsRunning = false;
        }
        private void OnMediaEnded(object sender, EventArgs eventArgs)
        {
            if (Ended == null)
            {
                return;
            }

            Task.Factory.StartNew(() => Ended?.Invoke(this, EventArgs.Empty));
        }
Exemple #27
0
 /// <summary>
 /// Restarts streaming from the beginning.
 /// </summary>
 protected void Restart()
 {
     ReadyToPlay.TrySetResult(false);
     ReadyToPlay = new TaskCompletionSource <bool>();
     Ended.TrySetResult(false);
     Ended            = new TaskCompletionSource <bool>();
     readyToPlay      = false;
     prebufferedCount = 0;
 }
Exemple #28
0
        public Task NotifyEnded()
        {
            if (Ended != null)
            {
                return(Ended.Invoke());
            }

            return(Task.CompletedTask);
        }
Exemple #29
0
        /// <summary>
        /// Notifies the component that file upload has ended.
        /// </summary>
        /// <param name="fileEntry">Uploaded file entry.</param>
        /// <param name="success">True if the file upload was successful.</param>
        /// <returns>A task that represents the asynchronous operation.</returns>
        internal async Task UpdateFileEndedAsync(IFileEntry fileEntry, bool success)
        {
            if (AutoReset)
            {
                await Reset();
            }

            await Ended.InvokeAsync(new FileEndedEventArgs( fileEntry, success ));
        }
 /// <inheritdoc />
 public void Dispose()
 {
     Ended?.Invoke(this, null);
     Database?.Dispose();
     Replicator?.Stop();
     // Uncomment after DB019 (https://github.com/couchbase/couchbase-lite-net/issues/908)
     //_replicator?.Dispose();
     HttpClient.Dispose();
 }