Пример #1
0
        public ThemeHelper(FrameworkElement element)
        {
            if (DesignMode.DesignModeEnabled)
            {
                return;
            }

            _element = element;
            ResourceHelper.TryResolveThemeStyle3(element);
            return;

            /*
             * For the current version of the application we are not using real-time
             * style changing, so this code path is temporarily ignored.
             */

#pragma warning disable CS0162 // Unreachable code detected
            _debouncer = new Debouncer();

            element.Loaded   += Element_Loaded;
            element.Unloaded += Element_Unloaded;

            Update();
#pragma warning restore CS0162 // Unreachable code detected
        }
Пример #2
0
        public void should_hold_the_call_while_paused()
        {
            var counter          = new Counter();
            var debounceFunction = new Debouncer(counter.Hit, TimeSpan.FromMilliseconds(50));

            debounceFunction.Pause();

            debounceFunction.Execute();
            debounceFunction.Execute();

            Thread.Sleep(100);

            counter.Count.Should().Be(0);

            debounceFunction.Execute();
            debounceFunction.Execute();

            Thread.Sleep(100);

            counter.Count.Should().Be(0);

            debounceFunction.Resume();

            Thread.Sleep(20);

            counter.Count.Should().Be(0);

            Thread.Sleep(100);

            counter.Count.Should().Be(1);
        }
Пример #3
0
 public void NullActionIsNotAllowedForSetInterval()
 {
     Assert.Throws <ArgumentNullException>(() =>
     {
         Debouncer.SetInterval(null, 10);
     });
 }
Пример #4
0
        public Combobox
        (
            IJSRuntime jsRuntime,
            OptionGetter optionGetter,
            IsDisabled?isDisabled   = null,
            IsRequired?isRequired   = null,
            Placeholder?placeholder = null
        )
        {
            _jsRuntime    = jsRuntime;
            _optionGetter = optionGetter;
            _isDisabled   = isDisabled;
            _isRequired   = isRequired;
            _placeholder  = placeholder;

            _debouncer = new Debouncer <string?>(s =>
            {
                SetSearchTerm(s);
                Show();
                Deselect();

                // TODO: keep this?
                _focused = null;

                _shouldRender = true;
                _stateHasChanged.Invoke();
            }, null);

            // Cache this so we find any selected option.
            Options();
        }
Пример #5
0
 public void NullActionIsNotAllowedForCancellableDebounce()
 {
     Assert.Throws <ArgumentNullException>(() =>
     {
         Debouncer.CancellableDebounce(null);
     });
 }
Пример #6
0
        public ServiceEditViewModel(INetworkProviderPrivate provider)
        {
            DeleteCommand = new RelayCommand(Delete);
            _debouncer    = new Debouncer();
            Service       = provider;
            Configuration = Service.GetApiConfiguration;

            if (Configuration == null)
            {
                throw new ArgumentException("No API Configuration object for " + Service.GetType());
            }

            UserKey = UserContext.Current.GetApiKey(Service);

            if (UserKey != null)
            {
                _apiKey    = UserKey.Key;
                _apiSecret = UserKey.Secret;
                _apiExtra1 = UserKey.Extra;
                _apiName   = UserKey.Name;
                DecideTest(1);
            }
            else
            {
                _apiName      = Service.Title;
                _initialCheck = false;
            }

            this.PropertyChanged += ServiceEditViewModel_PropertyChanged;
        }
Пример #7
0
        public QueueStatusController(IBroadcastSignalRMessage broadcastSignalRMessage, IQueueService queueService, IPendingReleaseService pendingReleaseService)
            : base(broadcastSignalRMessage)
        {
            _queueService          = queueService;
            _pendingReleaseService = pendingReleaseService;

            _broadcastDebounce = new Debouncer(BroadcastChange, TimeSpan.FromSeconds(5));
        }
Пример #8
0
 public MainWindow()
 {
     InitializeComponent();
     throttler         = Throttler.Throttle <string>(now => Dispatcher.Invoke(() => UpdateLabelContent(throttled, now)), TimeSpan.FromSeconds(1));
     debouncerTrailing = Debouncer.Debounce <string>(now => Dispatcher.Invoke(() => UpdateLabelContent(debouncedTrailing, now)), TimeSpan.FromSeconds(1), false, true);
     debouncerLeading  = Debouncer.Debounce <string>(now => Dispatcher.Invoke(() => UpdateLabelContent(debouncedLeading, now)), TimeSpan.FromSeconds(1), true, false);
     debouncerBoth     = Debouncer.Debounce <string>(now => Dispatcher.Invoke(() => UpdateLabelContent(debouncedBoth, now)), TimeSpan.FromSeconds(1), true, true);
 }
        /// <summary>
        /// Perform an action when configuration changes. Note this requires config sources to be added with
        /// `reloadOnChange` enabled
        /// </summary>
        /// <param name="config">Configuration to watch for changes</param>
        /// <param name="action">Action to perform when <paramref name="config"/> is changed</param>
        /// <param name="delayInMilliseconds">Delay In Milliseconds</param>
        public static void OnChange(this IConfiguration config, Action action, int delayInMilliseconds = 500)
        {
            // IConfiguration's change detection is based on FileSystemWatcher, which will fire multiple change
            // events for each change - Microsoft's code is buggy in that it doesn't bother to debounce/dedupe
            // https://github.com/aspnet/AspNetCore/issues/2542
            var debouncer = new Debouncer(TimeSpan.FromMilliseconds(delayInMilliseconds));

            ChangeToken.OnChange <object>(config.GetReloadToken, _ => debouncer.Debouce(action), null);
        }
Пример #10
0
 public AssetSelectorViewModel()
 {
     ListAssets         = new ObservableCollection <Asset>();
     AllAssetsViewModel = new AllAssetsViewModel();
     _debouncer         = new Debouncer();
     //M.RegisterAsync<AssetFoundMessage>(this, AssetFound);
     M.RegisterAsync <AssetAllResponseMessage>(this, RetreiveAllAssets);
     M.SendAsync(new AssetAllRequestMessage(RequesterTokenVm));
 }
Пример #11
0
        public void Init(PluginInitContext context)
        {
            _context   = context;
            _storage   = new PluginJsonStorage <Settings>();
            _settings  = _storage.Load();
            _debouncer = new Debouncer(_settings.Delay);

            LoadData();
        }
Пример #12
0
        public QueueStatusModule(IBroadcastSignalRMessage broadcastSignalRMessage, IQueueService queueService, IPendingReleaseService pendingReleaseService)
            : base(broadcastSignalRMessage, "queue/status")
        {
            _queueService          = queueService;
            _pendingReleaseService = pendingReleaseService;

            _broadcastDebounce = new Debouncer(BroadcastChange, TimeSpan.FromSeconds(5));

            Get("/", x => GetQueueStatusResponse());
        }
Пример #13
0
        public void MustDebounceCallWithTheSameValueWhenTheDelayBetweenCallIsLowerThanDebouncerDelay()
        {
            var debouncer = new Debouncer <string>(_ => _counter++, 20.Milliseconds());

            debouncer.DebouncedActionFor("a");
            debouncer.DebouncedActionFor("a");

            Thread.Sleep(50.Milliseconds());

            Check.That(_counter).IsEqualTo(1);
        }
Пример #14
0
 public PortfolioAggregator(UserContext context)
 {
     _id           = ObjectId.NewObjectId();
     TimerInterval = 15000;
     Context       = context;
     _scanners     = new List <PortfolioProvider>();
     M.Register <QuoteAssetChangedMessage>(this, BaseAssetChanged);
     _debouncer = new Debouncer();
     _timer     = new TimerIrregular(TimeSpan.FromSeconds(30), KeepPricesSubscriptionAlive);
     _keepAlive = new LatestPriceRequestSubscription(_id);
 }
Пример #15
0
        public void MustNotDebounceCallWithDifferentValues()
        {
            var debouncer = new Debouncer <string>(_ => _counter++, 20.Milliseconds());

            debouncer.DebouncedActionFor("a");
            debouncer.DebouncedActionFor("b");
            debouncer.DebouncedActionFor("c");

            Thread.Sleep(30.Milliseconds());
            Check.That(_counter).IsEqualTo(3);
        }
Пример #16
0
        public void SetTimeoutExecutesTheGivenActionAfterAnInterval()
        {
            // target function
            var    counter = 0;
            Action inc     = () => counter++;

            Debouncer.SetTimeout(inc, 10);
            Assert.AreEqual(0, counter);

            Thread.Sleep(50);
            Assert.AreEqual(1, counter);
        }
        public RootFolderWatchingService(IRootFolderService rootFolderService,
                                         IManageCommandQueue commandQueueManager,
                                         IConfigService configService,
                                         Logger logger)
        {
            _rootFolderService   = rootFolderService;
            _commandQueueManager = commandQueueManager;
            _configService       = configService;
            _logger = logger;

            _scanDebouncer = new Debouncer(ScanPending, TimeSpan.FromSeconds(DEBOUNCE_TIMEOUT_SECONDS), true);
        }
Пример #18
0
        public void SetIntervalExecutesTheGivenActionAtAGivenInterval()
        {
            // target function
            var    counter = 0;
            Action inc     = () => counter++;

            Debouncer.SetInterval(inc, 10);
            Assert.AreEqual(0, counter);

            Thread.Sleep(50);
            Assert.IsTrue(counter > 1);
        }
Пример #19
0
        private void SeekBarOnProgressChanged(object sender, SeekBar.ProgressChangedEventArgs e)
        {
            if (!e.FromUser)
            {
                return;
            }

            Debouncer.Debounce(nameof(AudioApplicationViewHolder) + nameof(SeekBarOnProgressChanged) + _id, () =>
            {
                _progress = e.Progress;
                RaiseDataUpdateRequired(AbsoluteAdapterPosition);
            }, TimeSpan.FromSeconds(1));
        }
Пример #20
0
        public CommandController(IManageCommandQueue commandQueueManager,
                                 IBroadcastSignalRMessage signalRBroadcaster,
                                 KnownTypes knownTypes)
            : base(signalRBroadcaster)
        {
            _commandQueueManager = commandQueueManager;
            _knownTypes          = knownTypes;

            _debouncer      = new Debouncer(SendUpdates, TimeSpan.FromSeconds(0.1));
            _pendingUpdates = new Dictionary <int, CommandResource>();

            PostValidator.RuleFor(c => c.Name).NotBlank();
        }
Пример #21
0
        static void Main(string[] args)
        {
            Debouncer debouncer = new Debouncer();

            for (int i = 0; i < 50; i++)
            {
                debouncer.Debounce("Scope", "UniqueSignature", "Requestor", () =>
                {
                    System.Console.WriteLine($"PASSED {i}");
                });
            }
            System.Console.ReadLine();
        }
Пример #22
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DocumentAnalyzerService"/> class.
        /// </summary>
        /// <param name="textView">The <see cref="IWpfTextView"/>.</param>
        /// <param name="syntaxWalkerProvider">The <see cref="ISyntaxWalkerProvider"/>.</param>
        public DocumentAnalyzerService(
            IWpfTextView textView,
            ISyntaxWalkerProvider syntaxWalkerProvider)
        {
            _textView             = textView ?? throw new ArgumentNullException(nameof(textView));
            _syntaxWalkerProvider = syntaxWalkerProvider ?? throw new ArgumentNullException(nameof(syntaxWalkerProvider));
            IsAnalyzeable         = _analyzeableContentTypes.Contains(textView.TextSnapshot.ContentType.TypeName);

            WeakEventManager <ITextBuffer, EventArgs> .AddHandler(_textView.TextBuffer, nameof(ITextBuffer.PostChanged), OnTextChanged);

            _structureDebouncer = new Debouncer(Analysis, TimeSpan.FromSeconds(1.5));
            _structureDebouncer.Start();
        }
Пример #23
0
        public void SetTimeoutCanBeCancelled()
        {
            // target function
            var    counter = 0;
            Action inc     = () => counter++;

            var timer = Debouncer.SetTimeout(inc, 10);

            Assert.AreEqual(0, counter);
            timer.Dispose();

            Thread.Sleep(50);
            Assert.AreEqual(0, counter);
        }
        public async Task given_data_is_debouncable_and_expired_then_Handle_relays(
            string id,
            IDebouncable debouncable,
            TracingProperties tracingProperties,
            Debouncer debouncer,
            IMessageHandler handler)
        {
            var sut     = new DebouncingMessageHandler(debouncer, handler);
            var message = new Message(id, debouncable, tracingProperties);

            await sut.Handle(message);

            Mock.Get(handler).Verify(x => x.Handle(message), Times.Never());
        }
Пример #25
0
        public async Task ActionsAreDebounced()
        {
            var executionCounter = 0;

            var debouncer = new Debouncer(TimeSpan.FromSeconds(.1));

            debouncer.Execute(() => executionCounter++);
            debouncer.Execute(() => executionCounter++);
            debouncer.Execute(() => executionCounter++);

            await Task.Delay(TimeSpan.FromSeconds(.5));

            Assert.Equal(1, executionCounter);
        }
Пример #26
0
        public void should_hold_the_call_for_debounce_duration()
        {
            var counter          = new Counter();
            var debounceFunction = new Debouncer(counter.Hit, TimeSpan.FromMilliseconds(50));

            debounceFunction.Execute();
            debounceFunction.Execute();
            debounceFunction.Execute();

            counter.Count.Should().Be(0);

            Thread.Sleep(100);

            counter.Count.Should().Be(1);
        }
Пример #27
0
 public StringDictionary(string dictPath)
 {
     this.dictPath = dictPath;
     saveDebouncer = new Debouncer(200 /* ms */, (Object src, ElapsedEventArgs e) => SaveDict());
     if (File.Exists(dictPath))
     {
         var json = File.ReadAllText(dictPath);
         lut = JsonSerializer.Deserialize <Dictionary <string, string> >(json);
         SaveDict(); // reformat
     }
     else
     {
         lut = new Dictionary <string, string>();
         SaveDict();
     }
 }
Пример #28
0
        public async Task OnlyLastActionIsInvoked()
        {
            string?invokedAction = null;

            var debouncer = new Debouncer(TimeSpan.FromSeconds(.1));

            foreach (var action in new[] { "a", "b", "c" })
            {
                debouncer.Execute(() => invokedAction = action);
            }

            await Task.Delay(TimeSpan.FromSeconds(.5));

            Assert.NotNull(invokedAction);
            Assert.Equal("c", invokedAction);
        }
Пример #29
0
        public CommandModule(IManageCommandQueue commandQueueManager,
                             IBroadcastSignalRMessage signalRBroadcaster,
                             IServiceFactory serviceFactory)
            : base(signalRBroadcaster)
        {
            _commandQueueManager = commandQueueManager;
            _serviceFactory      = serviceFactory;

            GetResourceById = GetCommand;
            CreateResource  = StartCommand;
            GetResourceAll  = GetStartedCommands;

            PostValidator.RuleFor(c => c.Name).NotBlank();

            _debouncer      = new Debouncer(SendUpdates, TimeSpan.FromSeconds(0.1));
            _pendingUpdates = new Dictionary <int, CommandResource>();
        }
Пример #30
0
        public AllAssetsViewModel()
        {
            if (IsInDesignMode)
            {
                return;
            }

            _debouncer = new Debouncer();

            Context       = UserContext.Current;
            SelectedAsset = Context.QuoteAsset;

            M.RegisterAsync <AssetFoundMessage>(this, AssetFound);

            M.RegisterAsync <AssetAllResponseMessage>(this, RetreiveAllAssets);

            M.SendAsync(new AssetAllRequestMessage(RequesterTokenVm));
        }