/// <summary>
        /// Request a responses from your service, this will invoke the request handler registered on your service as if it was called from another service.<br/>
        /// </summary>
        /// <param name="config">Request/Response Configuration</param>
        /// <param name="request">Request message</param>
        /// <typeparam name="TRequest">Type of Request Message</typeparam>
        /// <typeparam name="TResponse">Type of Response Message</typeparam>
        /// <returns>Response Message</returns>
        public TResponse Request <TRequest, TResponse>(RequestResponseConfig config, TRequest request)
        {
            var queue = _requestQueues.FirstOrDefault(q => q.Key == config.Name);

            var replyQueue = UniqueKeyUtility.Generate();

            if (queue.Value != null)
            {
                MockMessage(queue.Value, new RequestMessage
                {
                    MessageBody  = SerializeToJson(request),
                    RequestType  = typeof(TRequest).FullName,
                    ResponseType = typeof(TResponse).FullName,
                    Name         = config.Name,
                    ReplyQueue   = replyQueue
                }, true);

                // ReSharper disable once ImplicitlyCapturedClosure
                TimerUtility.WaitForIt(() => _responses.Any(r => r.ReplyQueue == replyQueue), Debugger.IsAttached ? 360000 : config.MillisecondsTimeout);
            }

            Thread.Sleep(100);

            var response = _responses.FirstOrDefault(r => r.ReplyQueue == replyQueue);

            return(JsonConvert.DeserializeObject <TResponse>(response?.MessageBody));
        }
        public void CanWaitForItWithoutTimeout()
        {
            const bool res = true;

            TimerUtility.WaitForIt(() => true);

            res.Should().BeTrue();
        }
예제 #3
0
        public void CanStartTask()
        {
            var i = 0;

            _cut.Start(() => ++ i, 10, new CancellationToken());
            TimerUtility.WaitForIt(() => i > 2, 100);
            _cut.Stop();
            i.Should().BeGreaterOrEqualTo(2);
        }
예제 #4
0
        public void CanStartWithCancellationTokenTask()
        {
            var i = 0;

            _cut.Start(() => ++ i, new CancellationToken());
            TimerUtility.WaitForIt(() => i > 0, 100);
            _cut.IsCompleted.Should().BeTrue();
            i.Should().Be(1);
        }
예제 #5
0
        public void CanStartTask()
        {
            var i = 0;

            _cut.Start(() => ++ i);
            TimerUtility.WaitForIt(() => i > 0, 100);
            _cut.IsCompleted.Should().BeTrue();
            i.Should().Be(1);
        }
        private void ExecuteHandler(Action <object, CancellationToken> messageHandler, bool multiThreadedHandler)
        {
            using (var cut = new QueueHandler(NullLogger.Instance, _queueFactory, _taskFactory))
            {
                cut.Start("MyQueue", true, LocaleQueueMode.TemporaryMaster, true, messageHandler, null, null, 100, multiThreadedHandler, false, _cancellationToken);

                // ReSharper disable once AccessToDisposedClosure
                TimerUtility.WaitForIt(() => cut.Idle, 6000);
            }
        }
예제 #7
0
        public override void OnExecute(IDialogueOwner dialogueOwner)
        {
            if (_timerHelper == null)
            {
                _timerHelper = TimerUtility.GetTimer();
            }

            _timerHelper.StartTimer(waitTime, null, OnTimerEnded);

//            Finish(true); // Finish once time is completed.
        }
예제 #8
0
        public void StartTimer()
        {
            if (timer == null)
            {
                timer = TimerUtility.GetTimer();
            }

            StopTimer();
            startTime = DateTime.Now;

            NotifyTimerStarted();
            timerID = timer.StartTimer(timeLimitInSeconds, NotifyTimerUpdated, NotifyReachedTimeLimit);
        }
예제 #9
0
        public static void TimerTick(object sender, ElapsedEventArgs e)
        {
            Logger.Write("Entering TimerTick.", Logger.LogType.ServiceLog);

            System.Threading.Tasks.Task.Run(() =>
            {
                try
                {
                    SchedulerId = (SchedulerId + 1) % 4;
                    Logger.Write($"SchedulerId: {SchedulerId}", Logger.LogType.ServiceLog);

                    var tls = new TaskLoopScheduler();
                    var eas = new EventActionScheduler();
                    switch (SchedulerId)
                    {
                    case 0:
                        tls.PollForTasksToStart();
                        tls.StartTasks();
                        break;

                    case 1:
                        eas.PollForEventActionsToStop();
                        eas.StopEventActions();
                        break;

                    case 2:
                        eas.PollForEventActionsToStart();
                        eas.StartEventActions();
                        break;

                    case 3:
                        tls.PollForTasksToStop();
                        tls.StopTasks();
                        break;
                    }

                    Logger.Write($"{new GlobalStateManager().GetCount()} TaskLoop(s) running: {new GlobalStateManager().ToString()}", Logger.LogType.ServiceLog);
                }
                catch (Exception exception)
                {
                    Logger.WriteException(exception);
                }
            });

            Logger.Write("Exiting TimerTick.", Logger.LogType.ServiceLog);

            TimerHelper.Timer.Interval = TimerUtility.GetAdjustedInterval(TimerHelper.TimerTickInterval);
            TimerHelper.Timer.Start();
        }
        public void DeleteLocaleQueueShouldDeleteQueue()
        {
            var name = $"IntegrationTest_{UniqueKeyUtility.Generate()}";

            try
            {
                _messageQueueManager.Create(name, true, true);
                _messageQueueManager.Delete(name, true);
                TimerUtility.WaitForIt(() => !_messageQueueManager.Exists(name, true), 10000);
                _messageQueueManager.Exists(name, true).Should().BeFalse();
            }
            finally
            {
                _messageQueueManager.Delete(name, true);
            }
        }
예제 #11
0
        protected override void SetText(string msg)
        {
            base.SetText(msg);

            var currentNodeTemp = currentNode;

            if (msg.Length > 0)
            {
                TimerUtility.GetTimer().StartTimer(msg.Length * waitTimePerLetter, () =>
                {
                    if (stopAtLeafNode && currentNodeTemp.isLeafNode)
                    {
                        return;
                    }

                    currentNodeTemp.Finish(true);
                });
            }
        }
        public void CanRestartHandler()
        {
            using (var cut = new QueueHandler(NullLogger.Instance, _queueFactory, _taskFactory))
            {
                cut.Start("MyQueue", true, LocaleQueueMode.TemporaryMaster, true, (m, c) => { c.WaitHandle.WaitOne(2000); }, null, null, 100, true, false, _cancellationToken);

                // ReSharper disable once AccessToDisposedClosure
                TimerUtility.WaitForIt(() => cut.Idle, 6000);

                cut.Stop();

                cut.Start("MyQueue", true, LocaleQueueMode.TemporaryMaster, true, (m, c) => { c.WaitHandle.WaitOne(2000); }, null, null, 100, true, false, _cancellationToken);

                // ReSharper disable once AccessToDisposedClosure
                TimerUtility.WaitForIt(() => cut.Idle, 6000);

                cut.Stop();
            }
        }
        private void GetMinuteUpdateInterval_TestHelper(
            string formattedDatetime,
            long expectedTicksUntilNextMinute)
        {
            ITimerUtility timerInTest = new TimerUtility(
                Substitute.For <ILocationDetailsService>(),
                string.Empty,
                string.Empty);

            var timeUntilNextMinute = timerInTest.GetMinuteUpdateInterval(
                DateTime.Parse(formattedDatetime));
            var ticksUntilNextMinute = timeUntilNextMinute.Ticks;

            Assert.IsTrue(ticksUntilNextMinute >= expectedTicksUntilNextMinute);

            const long acceptableDelta = 5 * TimeSpan.TicksPerMillisecond;

            Assert.IsTrue(ticksUntilNextMinute - expectedTicksUntilNextMinute <= acceptableDelta);
        }
예제 #14
0
        private void Navigate(int attempts = ScreenCapturePanel.DEFAULT_CAPTURE_MAX_RETRY_ATTEMPTS)
        {
            // this is needed for a weird case where this panel has never been made visible before and
            // the capture timer is asking for capture, without being made visible the WebView will start but
            // never completes, so we conditionally make this visible to allow the WebView to render which
            // will unblock its navigation.
            Action doNavigate = () =>
            {
                this.logger.Verbose("Navigating to {0} for {1}", this.Location.Text, this.Config.PrettyName);
                this.SafeViewport.Navigate(this.Location.Text);
            };

            if (!hasBeenVisible && !this.IsVisible)
            {
                this.logger.Info("Panel {0} is being asked to navigate, but it is not visible, forcing visibility", this.Config.PrettyName);
                if (this.requestFocus(this))
                {
                    this.hasBeenVisible = true;
                    TimerUtility.RunDelayedAction(() =>
                    {
                        this.releaseFocus(this);

                        // now we navigate as usual, navigate completion will acquire its own focus request.
                        doNavigate();
                    }, TimeSpan.FromMilliseconds(2000));
                }
                else if (attempts > 0)
                {
                    this.logger.Warn($"Tried to force visibility for Panel {this.Config.PrettyName} but another panel is visible, {attempts} retry attempts remaining...");
                    TimerUtility.RunDelayedAction(() => this.Navigate(attempts - 1), TimeSpan.FromMilliseconds(2000));
                }
                else
                {
                    this.logger.Warn($"Tried to force visibility for Panel {this.Config.PrettyName} but another panel is visible, aborting...");
                    this.CleanupCaptureRun(success: false);
                }
            }
            else
            {
                doNavigate();
            }
        }
예제 #15
0
        public void Execute()
        {
            if (this.isExecuting || !this.captureService.IsRecycleNeeded())
            {
                return;
            }

            this.isExecuting = true;
            TimerUtility.RunSafeDelayedAction(() =>
            {
                this.ExecuteUnsafe();
                this.isExecuting = false;
            },
                                              TimeSpan.FromMilliseconds(500),
                                              (error) =>
            {
                this.isExecuting = false;
                this.logger.Error("Got fatal error during Panel recycle {0}", error.ToString());
            });
        }
        /// <inheritdoc />
        public System.Messaging.MessageQueue Create(string name, bool privateQueue, bool transactional)
        {
            try
            {
                var queue = System.Messaging.MessageQueue.Create(Path(".", name, privateQueue), transactional);

                if (!TimerUtility.WaitForIt(() => Exists(".", name, privateQueue), privateQueue ? 1000 : 20000))
                {
                    throw new TimeoutException("Queue not created in time");
                }

                return(queue);
            }
            catch (Exception exception)
            {
                _logger.Information(exception, "Error Creating Message Queue {Name}", name);

                throw new QueueCreateException(name, privateQueue, exception);
            }
        }
예제 #17
0
        private void Viewport_NavigationCompletedImpl(int attempts = ScreenCapturePanel.DEFAULT_CAPTURE_MAX_RETRY_ATTEMPTS)
        {
            this.logger.Verbose($"running delayed capture with settle time of {this.appConfig.DefaultPageSettleDelay}...");

            // we introduce an artificial delay before processing the capture.
            // this is DUMB!, there's no definitive way to know if the page has "settled".
            TimerUtility.RunDelayedAction(() =>
            {
                // note: removed && this.IsVisible() check here, maybe that is necessary?
                if (this.requestFocus(this))
                {
                    // delay one more tick so we give the control time to render
                    TimerUtility.RunSafeDelayedAction(() =>
                    {
                        this.HandleScreenCapture();
                    },
                                                      TimeSpan.FromMilliseconds(2000),
                                                      (error) =>
                    {
                        // HandleScreenCapture should be safe.  no-op
                        if (this.IsCaptureInProgress)
                        {
                            this.CleanupCaptureRun(success: false);
                        }
                    });
                }
                else if (attempts > 0)
                {
                    this.logger.Warn($"Panel {this.Config.PrettyName} attempting to perform screen capture, but another panel already is visible, will retry {attempts} attempts...");

                    // TODO: randomize the retry time?
                    this.Viewport_NavigationCompletedImpl(attempts - 1);
                }
                else
                {
                    // could not get focus or we ran out of attempts
                    this.logger.Error($"Panel {this.Config.PrettyName} failed to get focus after {ScreenCapturePanel.DEFAULT_CAPTURE_MAX_RETRY_ATTEMPTS} attempts");
                    this.CleanupCaptureRun(success: false);
                }
            }, this.appConfig.DefaultPageSettleDelay);
        }
예제 #18
0
    protected override void Start()
    {
        base.Start();

        Debug.Log("who's there?????");

        this.Init();

        //Wait for range growtime amount of seconds, then grow if watered
        //If grow was called, stop the timer
        TimerUtility timer = gameObject.AddComponent <TimerUtility>();

        timer.OnTimeExpired.AddListener(delegate {
            Debug.Log("time has expired");
            //If the plant has been watered, grow
            Grow(plantTileToCreate.name);
        });

        //Start timer with range growtime
        growTime = Random.Range(minGrowTime, maxGrowTime);
        timer.StartIntervalConditionalTimer(growTime, delegate { return(hasBeenWatered); });
    }
예제 #19
0
        public override void OnExecute(IDialogueOwner dialogueOwner)
        {
            waitTime = 0; // Reset wait time incase the node is being replayed.

            if (_timerHelper == null)
            {
                _timerHelper = TimerUtility.GetTimer();
            }

            if (audioInfo.audioClip.val != null)
            {
                waitTime += audioInfo.audioClip.val.length;
            }
            else
            {
                DevdogLogger.LogError("[WaitForAudioNode] - Audio clip is missing from node: " + index + ". Dialogue: " + dialogueOwner.dialogue.name + ".");
            }

            waitTime += additionalWaitTime;

            _timerHelper.StartTimer(waitTime, null, OnTimerEnded);

            //            Finish(true); // Finish once time is completed.
        }
예제 #20
0
        public void CanWaitForExpression()
        {
            var i = 0;

            TimerUtility.WaitForIt(() => { ++i; return(i > 2); }, 100).Should().BeTrue();
        }
예제 #21
0
 public void CanWaitForItWithoutTimeout()
 {
     TimerUtility.WaitForIt(() => true);
 }
예제 #22
0
 public void CanWaitForItTimeout()
 {
     TimerUtility.WaitForIt(() => false, 100).Should().BeFalse();
 }
 private void WaitForIt()
 {
     TimerUtility.WaitForIt(() => _pendingMessages == 0, Debugger.IsAttached ? 3600000 : 6000);
 }
예제 #24
0
        public static void GatherTaskElapsed(object sender, string currencyPair, int interval, Timer t, List <EventAction> eventActions)
        {
            t.Interval = TimerUtility.GetAdjustedInterval(interval);
            t.Start();

            System.Threading.Tasks.Task.Run(() =>
            {
                try
                {
                    DateTime dateTimeNow  = DateTime.UtcNow;
                    DateTime dateTimePast = dateTimeNow.AddSeconds(-(60 * 4));

                    var result = PoloniexExchangeService.Instance.ReturnTradeHistory(currencyPair, dateTimePast, dateTimeNow);
                    result     = result.OrderBy(x => x.date).ToList();

                    var dataPoint = new CurrencyDataPoint
                    {
                        CurrencyPair    = currencyPair,
                        ClosingDateTime = dateTimeNow,
                    };

                    if (result.Any())
                    {
                        var curRate            = result.Last().rate;
                        dataPoint.ClosingValue = curRate;
                    }
                    else
                    {
                        using (var db = new PoloniexContext())
                        {
                            dataPoint.ClosingValue = db.CurrencyDataPoints
                                                     .Where(x => x.CurrencyPair == dataPoint.CurrencyPair)
                                                     .OrderByDescending(x => x.ClosingDateTime)
                                                     .First().ClosingValue;
                        }
                    }

                    using (var db = new PoloniexContext())
                    {
                        dataPoint.CreatedDateTime = DateTime.UtcNow;
                        db.CurrencyDataPoints.Add(dataPoint);
                        db.SaveChanges();
                    }

                    if (eventActions != null)
                    {
                        var sortedActions = eventActions.OrderBy(x => x.Priority).ToList();
                        for (int i = 0; i < sortedActions.Count(); i++)
                        {
                            Logger.Write($"{sortedActions[i].EventActionId}: Executing action {i + 1} of {sortedActions.Count()} - {sortedActions[i].EventActionType}", Logger.LogType.ServiceLog);
                            var threadEventAction = sortedActions[i];
                            threadEventAction.Action(threadEventAction.EventActionId);
                        }
                    }
                }
                catch (Exception exception)
                {
                    Logger.WriteException(exception);
                }
            });
        }
예제 #25
0
 private void Viewport_NewWindowRequested(object sender, WebViewControlNewWindowRequestedEventArgs e)
 {
     this.logger.Info($"New window requested... for {e.Uri}, navigating to location in the current view");
     TimerUtility.RunDelayedAction(() => this.SafeViewport.Navigate(e.Uri), TimeSpan.FromMilliseconds(2000));
 }