// ReSharper disable once SuggestBaseTypeForParameter
        public PendingDirectory(InstallationDirectory installationDirectory, SystemClock clock)
        {
            _pendingLocation = installationDirectory.GetChildDirectory(LocationExtensions.Pending);
            _pendingLocation.EnsureExists();

            _clock = clock;
        }
 public TuckerRockyGatherShipmentsHandler(IDropShipper dropShipper, ITuckerRockyClient client, SystemClock clock, TuckerRockyConfig config)
 {
     _dropShipper = dropShipper;
     _client = client;
     _clock = clock;
     _config = config;
 }
 /// <summary>
 /// The full and original text of the command.
 /// </summary>
 /// <param name="commandText">The command text.</param>
 /// <param name="transactionList">The transaction list.</param>
 /// <param name="siteList"></param>
 /// <param name="systemClock"></param>
 public BaseAction(string commandText, TransactionList transactionList, SiteList siteList, SystemClock systemClock)
 {
     CommandText = commandText;
     TransactionList = transactionList;
     SiteList = siteList;
     systemClock = systemClock;
 }
Exemple #4
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Site"/> class.
 /// </summary>
 /// <param name='siteId'>
 /// Site identifier.
 /// </param>
 public Site(int siteId, SiteList siteList, SystemClock systemClock)
 {
     Id = siteId;
     VariableList = new List<Variable>();
     SiteList = siteList;
     FailTimes = new List<FailureRecoverPair>();
     SystemClock = systemClock;
     IsFailed = false;
 }
Exemple #5
0
        public Dump(string commandText, TransactionList transactionList, SiteList siteList, SystemClock systemClock)
            : base(commandText, transactionList, siteList, systemClock)
        {
            string[] info = commandText.Split(new[] { '(', ')' });

            DumpFull = info[1].Trim().Equals(String.Empty);

            if (info.Count() == 3)
                DumpObject = info[1];
        }
        static void Main()
        {
            // set the clock and mailing component to be used
            IClock clock = new SystemClock();
            IMailer mailer = new MailerStub();

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new AdminForm(clock, mailer));
        }
 /// <summary>
 /// Creates an instance of bearer authentication options with default values.
 /// </summary>
 public OAuthBearerAuthenticationOptions() : base()
 {
     AuthenticationScheme = OAuthBearerAuthenticationDefaults.AuthenticationScheme;
     BackchannelTimeout = TimeSpan.FromMinutes(1);
     Challenge = OAuthBearerAuthenticationDefaults.AuthenticationScheme;
     Notifications = new OAuthBearerAuthenticationNotifications();
     RefreshOnIssuerKeyNotFound = true;
     SystemClock = new SystemClock();
     TokenValidationParameters = new TokenValidationParameters();
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="Transaction"/> class.
 /// </summary>
 /// <param name="transactionId">The transaction id.</param>
 /// <param name="systemClock">The system clock.</param>
 public Transaction(string transactionId, SystemClock systemClock)
 {
     Id = transactionId;
     Status = TransactionStatus.Created;
     LocksHeld = new List<Site>();
     QueuedCommands = new Queue<BaseAction>();
     AwaitingReReplication = new List<ValueSitePair>();
     SiteUsedList= new List<SiteAccessRecord>();
     SystemClock = systemClock;
 }
        static void Main()
        {
            // define the clock, database, and mailing component to be used
            IClock clock = new SystemClock();
            IMailer mailer = new MailerStub();
            ParkingDatabase database = new ParkingDatabase(clock, mailer);

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new UserForm(clock, mailer, database, false));
        }
 /// <summary>
 /// Create an instance of the options initialized with the default values
 /// </summary>
 public CookieAuthenticationOptions()
 {
     AuthenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme;
     ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
     ExpireTimeSpan = TimeSpan.FromDays(14);
     SlidingExpiration = true;
     CookieHttpOnly = true;
     CookieSecure = CookieSecureOption.SameAsRequest;
     SystemClock = new SystemClock();
     Notifications = new CookieAuthenticationNotifications();
 }
Exemple #11
0
 public Variable(int id, Site site, SystemClock systemClock)
 {
     ReadLockHolders = new List<Transaction>();
     WriteLockHolder = null;
     SystemClock = systemClock;
     Site = site;
     VariableHistory = new List<VariableValue>();
     UncomittedValue = string.Empty;
     IsReadable = true;
     Id = id;
 }
        public BeginTransaction(string commandText, TransactionList transactionList, SiteList siteList,
                                SystemClock systemClock)
            : base(commandText, transactionList, siteList, systemClock)
        {
            string[] info = commandText.Split(new[] {'(', ')'});

            if (info.Length != 3)
                throw new Exception("Invalid command format: " + commandText);

            Transaction = new Transaction(info[1], systemClock) {IsReadOnly = info[0].ToLower().Equals("beginro")};
            transactionList.AddTransaction(Transaction);
        }
        public EndTransaction(string commandText, TransactionList transactionList, SiteList siteList, SystemClock systemClock)
            : base(commandText, transactionList, siteList, systemClock)
        {
            string[] info = commandText.Split(new[] {'(', ')'});

            if (info.Length != 3)
                throw new Exception("Invalid command format: " + commandText);

            Transaction = transactionList.GetTransaction(info[1]);

            if (Transaction == null)
                throw new Exception("Transaction not found: " + commandText);
        }
Exemple #14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Fail"/> class.
        /// </summary>
        /// <param name="commandText">The command text.</param>
        /// <param name="transactionList">The transaction list.</param>
        /// <param name="siteList"></param>
        /// <param name="systemClock"></param>
        public Fail(string commandText, TransactionList transactionList, SiteList siteList, SystemClock systemClock)
            : base(commandText, transactionList, siteList, systemClock)
        {
            string[] info = commandText.Split(new[] { '(', ')' });

            if (info.Length != 3)
                throw new Exception("Invalid command format: " + commandText);

            Site = siteList.GetSite(int.Parse(info[1]));

            if (Site == null)
                throw new Exception("Site not found:" + info[1]);
        }
 public VendorPusher(
     Lazy<IItemUpdates<UpdateQuantityHeader, VendorQtyEntry>> inventoryUpdater,
     IItemUpdates<PriceHeader, VendorPriceEntry> costsUpdater,
     IReadyDirectory readyDirectory,
     IFileHelpersCache fileHelpersCache,
     IArchiveDirectory archiveDirectory,
     SystemClock systemClock,
     ILogger logger)
 {
     _inventoryUpdater = inventoryUpdater;
     _readyDirectory = readyDirectory;
     _fileHelpersCache = fileHelpersCache;
     _archiveDirectory = archiveDirectory;
     _systemClock = systemClock;
     _logger = logger;
     _costsUpdater = costsUpdater;
 }
Exemple #16
0
        private void When_changing_directory_last_write_time_in_local_zone_it_must_refresh_automatically()
        {
            // Arrange
            const string path = @"c:\some\folder";

            var clock = new SystemClock(() => DefaultTimeUtc);

            IFileSystem fileSystem = new FakeFileSystemBuilder(clock)
                                     .IncludingDirectory(path)
                                     .Build();

            IDirectoryInfo dirInfo = fileSystem.ConstructDirectoryInfo(path);

            DateTime beforeTime = dirInfo.LastWriteTime;

            // Act
            dirInfo.LastWriteTime = AlternateTime;

            // Assert
            DateTime afterTime = dirInfo.LastWriteTime;

            beforeTime.Should().Be(DefaultTime);
            afterTime.Should().Be(AlternateTime);
        }
        public virtual async Task CanGetBufferedQueueMetricsAsync()
        {
            using var metrics = GetMetricsClient(true) as IBufferedMetricsClient;

            if (metrics is not IMetricsClientStats stats)
            {
                return;
            }

            using var behavior = new MetricsQueueBehavior <SimpleWorkItem>(metrics, reportCountsInterval: TimeSpan.FromMilliseconds(25), loggerFactory: Log);
            using var queue    = new InMemoryQueue <SimpleWorkItem>(new InMemoryQueueOptions <SimpleWorkItem> { Behaviors = new[] { behavior }, LoggerFactory = Log });

            await queue.EnqueueAsync(new SimpleWorkItem { Id = 1, Data = "1" });

            await SystemClock.SleepAsync(50);

            var entry = await queue.DequeueAsync(TimeSpan.Zero);

            await SystemClock.SleepAsync(15);

            await entry.CompleteAsync();

            await SystemClock.SleepAsync(100); // give queue metrics time

            await metrics.FlushAsync();

            var queueStats = await stats.GetQueueStatsAsync("simpleworkitem");

            Assert.Equal(1, queueStats.Count.Max);
            Assert.Equal(0, queueStats.Count.Last);
            Assert.Equal(1, queueStats.Enqueued.Count);
            Assert.Equal(1, queueStats.Dequeued.Count);
            Assert.Equal(1, queueStats.Completed.Count);
            Assert.InRange(queueStats.QueueTime.AverageDuration, 45, 250);
            Assert.InRange(queueStats.ProcessTime.AverageDuration, 10, 250);
        }
Exemple #18
0
        public void Should_call_ontimeout_with_timeout_supplied_different_for_each_execution_by_evaluating_func_influenced_by_context__optimistic(int programaticallyControlledDelay)
        {
            Func <Context, TimeSpan> timeoutProvider = ctx => (TimeSpan)ctx["timeout"];

            TimeSpan?timeoutPassedToOnTimeout          = null;
            Action <Context, TimeSpan, Task> onTimeout = (ctx, span, task) => { timeoutPassedToOnTimeout = span; };
            var policy = Policy.Timeout <ResultPrimitive>(timeoutProvider, TimeoutStrategy.Optimistic, onTimeout);
            var userCancellationToken = CancellationToken.None;

            // Supply a programatically-controlled timeout, via the execution context.
            Context context = new Context("SomeOperationKey")
            {
                ["timeout"] = TimeSpan.FromMilliseconds(25 * programaticallyControlledDelay)
            };

            policy.Invoking(p => p.Execute((ctx, ct) =>
            {
                SystemClock.Sleep(TimeSpan.FromSeconds(3), ct);
                return(ResultPrimitive.WhateverButTooLate);
            }, context, userCancellationToken))
            .ShouldThrow <TimeoutRejectedException>();

            timeoutPassedToOnTimeout.Should().Be(timeoutProvider(context));
        }
Exemple #19
0
        public virtual async Task CanRunQueueJobWithLockFailAsync()
        {
            const int workItemCount    = 10;
            const int allowedLockCount = 5;

            Log.SetLogLevel <ThrottlingLockProvider>(LogLevel.Trace);

            using (var queue = GetSampleWorkItemQueue(retries: 3, retryDelay: TimeSpan.Zero)) {
                await queue.DeleteQueueAsync();

                var enqueueTask = Run.InParallelAsync(workItemCount, index => {
                    _logger.LogInformation($"Enqueue #{index}");
                    return(queue.EnqueueAsync(new SampleQueueWorkItem {
                        Created = SystemClock.UtcNow,
                        Path = "somepath" + index
                    }));
                });

                var lockProvider = new ThrottlingLockProvider(new InMemoryCacheClient(new InMemoryCacheClientOptions()), allowedLockCount, TimeSpan.FromDays(1), Log);
                var job          = new SampleQueueJobWithLocking(queue, null, lockProvider, Log);
                await SystemClock.SleepAsync(10);

                _logger.LogInformation("Starting RunUntilEmptyAsync");
                await Task.WhenAll(job.RunUntilEmptyAsync(), enqueueTask);

                _logger.LogInformation("Done RunUntilEmptyAsync");

                var stats = await queue.GetQueueStatsAsync();

                Assert.Equal(0, stats.Queued);
                Assert.Equal(workItemCount, stats.Enqueued);
                Assert.Equal(allowedLockCount, stats.Completed);
                Assert.Equal(allowedLockCount * 4, stats.Abandoned);
                Assert.Equal(allowedLockCount, stats.Deadletter);
            }
        }
Exemple #20
0
        private void When_changing_file_creation_time_in_UTC_it_must_refresh_automatically()
        {
            // Arrange
            const string path = @"c:\some\file.txt";

            var clock = new SystemClock(() => DefaultTimeUtc);

            IFileSystem fileSystem = new FakeFileSystemBuilder(clock)
                                     .IncludingEmptyFile(path)
                                     .Build();

            IFileInfo fileInfo = fileSystem.ConstructFileInfo(path);

            DateTime beforeTime = fileInfo.CreationTimeUtc;

            // Act
            fileInfo.CreationTimeUtc = AlternateTimeUtc;

            // Assert
            DateTime afterTime = fileInfo.CreationTimeUtc;

            beforeTime.Should().Be(DefaultTimeUtc);
            afterTime.Should().Be(AlternateTimeUtc);
        }
Exemple #21
0
        private async Task CleanupSoftDeletedOrganizationsAsync(JobContext context)
        {
            var organizationResults = await _organizationRepository.GetAllAsync(q => q.SoftDeleteMode(SoftDeleteQueryMode.DeletedOnly).SnapshotPaging().PageLimit(5)).AnyContext();

            _logger.CleanupOrganizationSoftDeletes(organizationResults.Total);

            while (organizationResults.Documents.Count > 0 && !context.CancellationToken.IsCancellationRequested)
            {
                foreach (var organization in organizationResults.Documents)
                {
                    using (_logger.BeginScope(new ExceptionlessState().Organization(organization.Id))) {
                        await RemoveOrganizationAsync(organization, context).AnyContext();

                        // Sleep so we are not hammering the backend.
                        await SystemClock.SleepAsync(TimeSpan.FromSeconds(5)).AnyContext();
                    }
                }

                if (context.CancellationToken.IsCancellationRequested || !await organizationResults.NextPageAsync().AnyContext())
                {
                    break;
                }
            }
        }
Exemple #22
0
        public void Should_be_able_to_cancel_with_user_cancellation_token_before_timeout__optimistic()
        {
            Stopwatch watch = new Stopwatch();

            int timeout = 10;
            var policy  = Policy.Timeout(timeout, TimeoutStrategy.Optimistic);

            TimeSpan tolerance = TimeSpan.FromSeconds(3);       // Consider increasing tolerance, if test fails transiently in different test/build environments.

            TimeSpan userTokenExpiry = TimeSpan.FromSeconds(1); // Use of time-based token irrelevant to timeout policy; we just need some user token that cancels independently of policy's internal token.

            using (CancellationTokenSource userTokenSource = new CancellationTokenSource(userTokenExpiry))
            {
                watch.Start();
                policy.Invoking(p => p.Execute(
                                    ct => SystemClock.Sleep(TimeSpan.FromSeconds(timeout), ct) // Simulate cancel in the middle of execution
                                    , userTokenSource.Token)                                   // ... with user token.
                                ).ShouldThrow <OperationCanceledException>();
                watch.Stop();
            }

            watch.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(timeout * 0.8));
            watch.Elapsed.Should().BeCloseTo(userTokenExpiry, ((int)tolerance.TotalMilliseconds));
        }
Exemple #23
0
        private void When_updating_directory_attributes_it_must_not_update_directory_timings()
        {
            // Arrange
            const string path = @"C:\folder";

            DateTime creationTimeUtc = 17.March(2006).At(14, 03, 53).AsUtc();
            var      clock           = new SystemClock(() => creationTimeUtc);

            IFileSystem fileSystem = new FakeFileSystemBuilder(clock)
                                     .IncludingDirectory(path)
                                     .Build();

            DateTime updateTimeUtc = 18.March(2006).At(14, 03, 53).AsUtc();

            clock.UtcNow = () => updateTimeUtc;

            // Act
            fileSystem.File.SetAttributes(path, FileAttributes.Directory | FileAttributes.Hidden);

            // Assert
            fileSystem.Directory.GetCreationTimeUtc(path).Should().Be(creationTimeUtc);
            fileSystem.Directory.GetLastWriteTimeUtc(path).Should().Be(creationTimeUtc);
            fileSystem.Directory.GetLastAccessTimeUtc(path).Should().Be(creationTimeUtc);
        }
Exemple #24
0
        public virtual async Task WorkItemsWillTimeoutAsync()
        {
            var queue = GetQueue(retryDelay: TimeSpan.Zero, workItemTimeout: TimeSpan.FromMilliseconds(50));

            if (queue == null)
            {
                return;
            }

            using (queue) {
                await queue.DeleteQueueAsync();
                await AssertEmptyQueueAsync(queue);

                await queue.EnqueueAsync(new SimpleWorkItem {
                    Data = "Hello"
                });

                var workItem = await queue.DequeueAsync(TimeSpan.Zero);

                Assert.NotNull(workItem);
                Assert.Equal("Hello", workItem.Value.Data);
                await SystemClock.SleepAsync(TimeSpan.FromSeconds(1));

                // wait for the task to be auto abandoned

                var sw = Stopwatch.StartNew();
                workItem = await queue.DequeueAsync(TimeSpan.FromSeconds(5));

                sw.Stop();
                _logger.Trace("Time {0}", sw.Elapsed);
                Assert.NotNull(workItem);
                await workItem.CompleteAsync();

                Assert.Equal(0, (await queue.GetQueueStatsAsync()).Queued);
            }
        }
        public virtual async Task CanRunQueueJobAsync()
        {
            const int workItemCount = 100;

            using (var queue = GetSampleWorkItemQueue(retries: 0, retryDelay: TimeSpan.Zero)) {
                await queue.DeleteQueueAsync();

                var enqueueTask = Run.InParallelAsync(workItemCount, index => queue.EnqueueAsync(new SampleQueueWorkItem {
                    Created = SystemClock.UtcNow,
                    Path    = "somepath" + index
                }));

                var job = new SampleQueueJob(queue, null, Log);
                await SystemClock.SleepAsync(10);

                await Task.WhenAll(Task.Run(() => job.RunUntilEmpty()), enqueueTask);

                var stats = await queue.GetQueueStatsAsync();

                Assert.Equal(0, stats.Queued);
                Assert.Equal(workItemCount, stats.Enqueued);
                Assert.Equal(workItemCount, stats.Dequeued);
            }
        }
Exemple #26
0
        private void When_creating_file_it_must_update_file_timings()
        {
            // Arrange
            const string path = @"C:\some\file.txt";

            DateTime creationTimeUtc = 17.March(2006).At(14, 03, 53).AsUtc();
            var      clock           = new SystemClock {
                UtcNow = () => creationTimeUtc
            };

            IFileSystem fileSystem = new FakeFileSystemBuilder(clock)
                                     .IncludingDirectory(@"c:\some")
                                     .Build();

            // Act
            using (fileSystem.File.Create(path))
            {
            }

            // Assert
            fileSystem.File.GetCreationTimeUtc(path).Should().Be(creationTimeUtc);
            fileSystem.File.GetLastWriteTimeUtc(path).Should().Be(creationTimeUtc);
            fileSystem.File.GetLastAccessTimeUtc(path).Should().Be(creationTimeUtc);
        }
        public void Should_call_ontimeout_with_timing_out_exception__optimistic()
        {
            TimeSpan timeoutPassedToConfiguration = TimeSpan.FromMilliseconds(250);

            Exception exceptionPassedToOnTimeout = null;
            Func <Context, TimeSpan, Task, Exception, Task> onTimeoutAsync = (ctx, span, task, exception) =>
            {
                exceptionPassedToOnTimeout = exception;
                return(TaskHelper.EmptyTask);
            };

            var policy = Policy.TimeoutAsync <ResultPrimitive>(timeoutPassedToConfiguration, TimeoutStrategy.Optimistic, onTimeoutAsync);
            var userCancellationToken = CancellationToken.None;

            policy.Awaiting(async p => await p.ExecuteAsync(async ct =>
            {
                await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), ct).ConfigureAwait(false);
                return(ResultPrimitive.WhateverButTooLate);
            }, userCancellationToken).ConfigureAwait(false))
            .Should().Throw <TimeoutRejectedException>();

            exceptionPassedToOnTimeout.Should().NotBeNull();
            exceptionPassedToOnTimeout.Should().BeOfType(typeof(OperationCanceledException));
        }
Exemple #28
0
        public void stop(NumberPicker picker, long elapsedTime)
        {
            // Execute dummy touch to adjust the position of the picker
            long      now          = SystemClock.UptimeMillis();
            int       touchX       = picker.Width / 2;
            int       topTouchY    = picker.Height / 5;
            int       bottomTouchY = picker.Height * 4 / 5;
            const int metaState    = 0;

            // Dummy touch of upper side of the picker
            MotionEvent e = MotionEvent.Obtain(
                now,
                now,
                MotionEventActions.Down,
                touchX,
                topTouchY,
                metaState);

            picker.DispatchTouchEvent(e);

            e.Action = MotionEventActions.Up;
            picker.DispatchTouchEvent(e);

            // Dummy touch of bottom side of the picker
            e = MotionEvent.Obtain(
                now,
                now,
                MotionEventActions.Down,
                touchX,
                bottomTouchY,
                metaState);
            picker.DispatchTouchEvent(e);

            e.Action = MotionEventActions.Up;
            picker.DispatchTouchEvent(e);
        }
Exemple #29
0
        public void AddCategoryToPost([FromBody] AdminCategoryModel model)
        {
            var existing = this.db.Categories.Single(c => c.Title == model.Title);

            if (existing == null)
            {
                var newCategory = new Category
                {
                    ProfileId   = GetProfile().Id,
                    Title       = model.Title,
                    Description = model.Title,
                    Slug        = model.Title.ToSlug(),
                    LastUpdated = SystemClock.Now()
                };
                this.db.Categories.Add(newCategory);
                this.db.Complete();

                existing = this.db.Categories.Single(c => c.Title == model.Title);
            }

            this.db.Categories.AddCategoryToPost(int.Parse(model.PostId),
                                                 existing.Id);
            this.db.Complete();
        }
Exemple #30
0
        public void CanSendMultiple()
        {
            const int iterations = 100000;

            StartListening(iterations);

            var sw = Stopwatch.StartNew();

            for (int index = 0; index < iterations; index++)
            {
                if (index % (iterations / 10) == 0)
                {
                    StopListening();
                }

                _client.Counter("counter");

                if (index % (iterations / 10) == 0)
                {
                    StartListening(iterations - index);
                }
            }

            sw.Stop();
            // Require at least 10,000 operations/s
            Assert.InRange(sw.ElapsedMilliseconds, 0, (iterations / 10000.0) * 1000);

            SystemClock.Sleep(250);
            var messages = GetMessages();

            Assert.InRange(messages.Count, iterations - (iterations / 10), iterations);
            foreach (string message in messages)
            {
                Assert.Equal("test.counter:1|c", message);
            }
        }
        public async Task CanSleepAsync()
        {
            using (TestSystemClock.Install()) {
                var sw = Stopwatch.StartNew();
                await SystemClock.SleepAsync(250);

                sw.Stop();

                Assert.InRange(sw.ElapsedMilliseconds, 225, 3000);

                SystemClock.Test.UseFakeSleep();

                var now = SystemClock.UtcNow;
                sw.Restart();
                await SystemClock.SleepAsync(1000);

                sw.Stop();
                var afterSleepNow = SystemClock.UtcNow;

                Assert.InRange(sw.ElapsedMilliseconds, 0, 30);
                Assert.True(afterSleepNow > now);
                Assert.InRange(afterSleepNow.Subtract(now).TotalMilliseconds, 950, 5000);
            }
        }
Exemple #32
0
        private void When_creating_file_it_must_update_directory_timings()
        {
            // Arrange
            const string containerPath = @"C:\folder";

            DateTime creationTimeUtc = 17.March(2006).At(14, 03, 53).AsUtc();
            var      clock           = new SystemClock(() => creationTimeUtc);

            IFileSystem fileSystem = new FakeFileSystemBuilder(clock)
                                     .IncludingDirectory(containerPath)
                                     .Build();

            DateTime updateTimeUtc = 18.March(2006).At(14, 03, 53).AsUtc();

            clock.UtcNow = () => updateTimeUtc;

            // Act
            fileSystem.File.WriteAllText(@"c:\folder\file.txt", "X");

            // Assert
            fileSystem.Directory.GetCreationTimeUtc(containerPath).Should().Be(creationTimeUtc);
            fileSystem.Directory.GetLastWriteTimeUtc(containerPath).Should().Be(updateTimeUtc);
            fileSystem.Directory.GetLastAccessTimeUtc(containerPath).Should().Be(updateTimeUtc);
        }
Exemple #33
0
        private void prepareTracking(int position)
        {
            mTracking        = true;
            mVelocityTracker = VelocityTracker.Obtain();
            Boolean opening = !mExpanded;

            if (opening)
            {
                mAnimatedAcceleration = mMaximumAcceleration;
                mAnimatedVelocity     = mMaximumMajorVelocity;
                if (mInvert)
                {
                    mAnimationPosition = mTopOffset;
                }
                else
                {
                    mAnimationPosition = mBottomOffset + (mVertical ? Height - mHandleHeight : Width - mHandleWidth);
                }
                moveHandle((int)mAnimationPosition);
                mAnimating = true;
                mHandler.RemoveMessages(MSG_ANIMATE);
                long now = SystemClock.UptimeMillis();
                mAnimationLastTime    = now;
                mCurrentAnimationTime = now + ANIMATION_FRAME_DURATION;
                mAnimating            = true;
            }
            else
            {
                if (mAnimating)
                {
                    mAnimating = false;
                    mHandler.RemoveMessages(MSG_ANIMATE);
                }
                moveHandle(position);
            }
        }
Exemple #34
0
        public void Should_not_be_able_to_cancel_with_user_cancellation_token_before_timeout__pessimistic()
        {
            Stopwatch watch = new Stopwatch();

            int timeout = 5;
            var policy  = Policy.TimeoutAsync(timeout, TimeoutStrategy.Pessimistic);

            TimeSpan tolerance = TimeSpan.FromSeconds(3);       // Consider increasing tolerance, if test fails transiently in different test/build environments.

            TimeSpan userTokenExpiry = TimeSpan.FromSeconds(1); // Use of time-based token irrelevant to timeout policy; we just need some user token that cancels independently of policy's internal token.

            using (CancellationTokenSource userTokenSource = new CancellationTokenSource(userTokenExpiry))
            {
                watch.Start();
                policy.Awaiting(async p => await p.ExecuteAsync(async
                                                                _ => {
                    await SystemClock.SleepAsync(TimeSpan.FromSeconds(timeout * 2), CancellationToken.None).ConfigureAwait(false); // Do not observe any cancellation in the middle of execution
                }, userTokenSource.Token)                                                                                          // ... with user token.
                                ).ShouldThrow <TimeoutRejectedException>();
                watch.Stop();
            }

            watch.Elapsed.Should().BeCloseTo(TimeSpan.FromSeconds(timeout), ((int)tolerance.TotalMilliseconds));
        }
    static void Main(string[] args)
    {
        SystemClock         oncePerSecond   = new SystemClock();
        VariableSystemClock oncePerInterval = new VariableSystemClock(TimeSpan.FromSeconds(2));

        Console.WriteLine("Start:");
        Console.WriteLine("  oncePerSecond:   {0}", oncePerSecond.getSystemTime());
        Console.WriteLine("  oncePerInterval: {0}", oncePerInterval.getSystemTime());
        Console.WriteLine();
        for (Int32 i = 0; i < 10; i++)
        {
            // sleep three seconds
            System.Threading.Thread.Sleep(TimeSpan.FromSeconds(2));
            // display output
            Console.WriteLine("Interval {0}:", i);
            Console.WriteLine("  oncePerSecond:   {0}", oncePerSecond.getSystemTime());
            Console.WriteLine("  oncePerInterval: {0}", oncePerInterval.getSystemTime());
            Console.WriteLine();
        }
        Console.WriteLine("End:");
        Console.WriteLine("  oncePerSecond:   {0}", oncePerSecond.getSystemTime());
        Console.WriteLine("  oncePerInterval: {0}", oncePerInterval.getSystemTime());
        Console.WriteLine();
    }
Exemple #36
0
        async Task SaveStatsTotals(int postId)
        {
            try
            {
                var existentTotal = _db.StatsTotals.Where(s => s.PostId == postId &&
                                                          s.DateCreated == SystemClock.Now().Date).FirstOrDefault();

                if (existentTotal == null)
                {
                    await _db.StatsTotals.AddAsync(new StatsTotal
                    {
                        PostId      = postId,
                        Total       = 1,
                        DateCreated = SystemClock.Now().Date
                    });
                }
                else
                {
                    existentTotal.Total = existentTotal.Total + 1;
                }
                await _db.SaveChangesAsync();
            }
            catch { }
        }
Exemple #37
0
        public string receive()
        {
            try {
                string s = "";
                int    x = 10;
                while (!s.Contains('\n') && !s.Contains(">"))
                {
#if !disablebluetooth
                    x = _socket.InputStream.Read(buffer, 0, buffer.Length);
                    if (recieveTime < SystemClock.ElapsedRealtime())
                    {
                        s = "";
                    }
                    recieveTime = SystemClock.ElapsedRealtime() + 50;
                    s          += System.Text.Encoding.ASCII.GetString(buffer, 0, x).Replace('\r', '\n');
                }
#else
                    /*if (!inputStream.IsDataAvailable())
                     * inputStream.Seek(0, SeekOrigin.Begin );*/
                    s += (char)inputStream.ReadByte();
                    if (createHangup)
                    {
                        while (true)
                        {
                            ;
                        }
                    }
                }
                //Thread.Sleep(1);
#endif

/*#if DEBUG
 *      Console.WriteLine(s);
 #endif*/
                return(s);
            } catch (Exception) { return(""); }
Exemple #38
0
        public void Should_call_ontimeout_with_timeout_supplied_different_for_each_execution_by_evaluating_func__pessimistic()
        {
            for (int i = 1; i <= 3; i++)
            {
                Func <TimeSpan> timeoutFunc = () => TimeSpan.FromMilliseconds(25 * i);

                TimeSpan?timeoutPassedToOnTimeout = null;
                Func <Context, TimeSpan, Task, Task> onTimeoutAsync = (ctx, span, task) =>
                {
                    timeoutPassedToOnTimeout = span;
                    return(TaskHelper.EmptyTask);
                };

                var policy = Policy.TimeoutAsync(timeoutFunc, TimeoutStrategy.Pessimistic, onTimeoutAsync);

                policy.Awaiting(async p => await p.ExecuteAsync(async() =>
                {
                    await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), CancellationToken.None).ConfigureAwait(false);
                }))
                .ShouldThrow <TimeoutRejectedException>();

                timeoutPassedToOnTimeout.Should().Be(timeoutFunc());
            }
        }
        public virtual async Task CanGetBufferedQueueMetrics()
        {
            using (var metrics = GetMetricsClient(true) as IBufferedMetricsClient) {
                var stats = metrics as IMetricsClientStats;
                if (stats == null)
                {
                    return;
                }

                using (var queue = new InMemoryQueue <SimpleWorkItem>(behaviors: new[] { new MetricsQueueBehavior <SimpleWorkItem>(metrics, loggerFactory: Log) }, loggerFactory: Log)) {
                    await queue.EnqueueAsync(new SimpleWorkItem { Id = 1, Data = "1" });

                    await SystemClock.SleepAsync(50);

                    var entry = await queue.DequeueAsync(TimeSpan.Zero);

                    await SystemClock.SleepAsync(30);

                    await entry.CompleteAsync();

                    await SystemClock.SleepAsync(500);  // give queue metrics time

                    await metrics.FlushAsync();

                    var queueStats = await stats.GetQueueStatsAsync("simpleworkitem");

                    Assert.Equal(1, queueStats.Count.Max);
                    Assert.Equal(0, queueStats.Count.Last);
                    Assert.Equal(1, queueStats.Enqueued.Count);
                    Assert.Equal(1, queueStats.Dequeued.Count);
                    Assert.Equal(1, queueStats.Completed.Count);
                    Assert.InRange(queueStats.QueueTime.AverageDuration, 50, 200);
                    Assert.InRange(queueStats.ProcessTime.AverageDuration, 30, 200);
                }
            }
        }
Exemple #40
0
        public NES()
        {
            //clock = new SystemClock(200000);
            clock = new SystemClock(5369318); // 1/4 speed of real system, but emulate-able
            //clock = new SystemClock(21477272); // True speed

            bus = new SystemBus(0xFFFF);
            RAM ram = new RAM(2048);

            ppu            = new PPU(clock, bus);
            cpu            = new CPU_2A03(new ClockDivider(clock, 3), bus); // 3x slower than PPU
            apu            = new APU(new ClockDivider(clock, 6));           // 6x slower than PPU
            controllers[0] = new Controller(0x4016);
            controllers[1] = new Controller(0x4017);

            bus.AddComponent(ram, new BusAddressRange(0x0000, 0x1FFF));
            bus.AddComponent(ppu, new BusAddressRange(0x2000, 0x3FFF));
            bus.AddComponent(apu, new BusAddressRange(0x4000, 0x4013));
            bus.AddComponent(cpu, new BusAddressRange(0x4014, 0x4014));
            bus.AddComponent(apu, new BusAddressRange(0x4015, 0x4015));
            bus.AddComponent((Controller)controllers[0], new BusAddressRange(0x4016, 0x4016));
            bus.AddComponent((Controller)controllers[1], new BusAddressRange(0x4017, 0x4017));
            bus.AddComponent(apu, new BusAddressRange(0x4017, 0x4017));
        }
        public void CanSleep()
        {
            SystemClock.UseTestClock();

            var sw = Stopwatch.StartNew();

            SystemClock.Sleep(250);
            sw.Stop();

            Assert.InRange(sw.ElapsedMilliseconds, 225, 400);

            SystemClock.Test.UseFakeSleep();

            var now = SystemClock.UtcNow;

            sw.Restart();
            SystemClock.Sleep(1000);
            sw.Stop();
            var afterSleepNow = SystemClock.UtcNow;

            Assert.InRange(sw.ElapsedMilliseconds, 0, 25);
            Assert.True(afterSleepNow > now);
            Assert.InRange(afterSleepNow.Subtract(now).TotalMilliseconds, 950, 1100);
        }
    protected override async Task <JobResult> RunInternalAsync(JobContext context)
    {
        const int LIMIT = 100;

        _lastRun = SystemClock.UtcNow;
        _logger.LogTrace("Start save stack event counts.");

        // Get list of stacks where snooze has expired
        var results = await _stackRepository.GetExpiredSnoozedStatuses(SystemClock.UtcNow, o => o.PageLimit(LIMIT)).AnyContext();

        while (results.Documents.Count > 0 && !context.CancellationToken.IsCancellationRequested)
        {
            foreach (var stack in results.Documents)
            {
                stack.MarkOpen();
            }

            await _stackRepository.SaveAsync(results.Documents).AnyContext();

            // Sleep so we are not hammering the backend.
            await SystemClock.SleepAsync(TimeSpan.FromSeconds(2.5)).AnyContext();

            if (context.CancellationToken.IsCancellationRequested || !await results.NextPageAsync().AnyContext())
            {
                break;
            }

            if (results.Documents.Count > 0)
            {
                await context.RenewLockAsync().AnyContext();
            }
        }

        _logger.LogTrace("Finished save stack event counts.");
        return(JobResult.Success);
    }
        private async Task CanRunConcurrentlyAsync(TimeSpan?minimumIntervalTime = null)
        {
            var countdown = new AsyncCountdownEvent(2);

            Func <Task <DateTime?> > callback = async() => {
                _logger.LogInformation("Starting work.");
                countdown.Signal();
                await SystemClock.SleepAsync(500);

                _logger.LogInformation("Finished work.");
                return(null);
            };

            using (var timer = new ScheduledTimer(callback, minimumIntervalTime: minimumIntervalTime, loggerFactory: Log)) {
                timer.ScheduleNext();
                var t = Task.Run(async() => {
                    for (int i = 0; i < 3; i++)
                    {
                        await SystemClock.SleepAsync(10);
                        timer.ScheduleNext();
                    }
                });

                _logger.LogInformation("Waiting for 300ms");
                await countdown.WaitAsync(TimeSpan.FromMilliseconds(300));

                _logger.LogInformation("Finished waiting for 300ms");
                Assert.Equal(1, countdown.CurrentCount);

                _logger.LogInformation("Waiting for 1.5 seconds");
                await countdown.WaitAsync(TimeSpan.FromSeconds(1.5));

                _logger.LogInformation("Finished waiting for 1.5 seconds");
                Assert.Equal(0, countdown.CurrentCount);
            }
        }
Exemple #44
0
        private void When_getting_file_creation_time_in_UTC_it_must_cache()
        {
            // Arrange
            const string path = @"c:\some\file.txt";

            var clock = new SystemClock(() => DefaultTimeUtc);

            IFileSystem fileSystem = new FakeFileSystemBuilder(clock)
                                     .IncludingEmptyFile(path)
                                     .Build();

            IFileInfo fileInfo = fileSystem.ConstructFileInfo(path);

            DateTime beforeTime = fileInfo.CreationTimeUtc;

            fileSystem.File.SetCreationTimeUtc(path, AlternateTimeUtc);

            // Act
            DateTime afterTime = fileInfo.CreationTimeUtc;

            // Assert
            beforeTime.Should().Be(DefaultTimeUtc);
            afterTime.Should().Be(DefaultTimeUtc);
        }
Exemple #45
0
        public void StatsIncr()
        {
            stats.Increment("cats");
            stats.Increment("dogs", 3);

            collector.Periodic(null);

            stats.Increment("dogs", 60000);
            SystemClock.Advance(TimeSpan.FromMinutes(1));

            collector.Periodic(null);

            var series = collector.Get("counter:dogs", null);

            series.ShouldNotBe(null);
            series.Count().ShouldBe(60);

            var seconds = SystemClock.Minus(TimeSpan.FromMinutes(2d)).MillisFromEpoch() / 1000;

            AssertClose(new List <long>(new[] { seconds, 0 }), series.ElementAt(57));
            seconds = SystemClock.Minus(TimeSpan.FromMinutes(1d)).MillisFromEpoch() / 1000;
            AssertClose(new List <long>(new[] { seconds, 3 }), series.ElementAt(58));
            AssertClose(new List <long>(new[] { SystemClock.Seconds(), 60000 }), series.ElementAt(59));
        }
 public TuckerRockyDropShipper(ITuckerRockyClient client, SystemClock clock, ITextFileReader fileReader)
 {
     _client = client;
     _clock = clock;
     _fileReader = fileReader;
 }
Exemple #47
0
	static SystemClock()
	{
		Instance = new SystemClock();
	}
 public ReadyDirectory(InstallationDirectory installationDirectory, SystemClock clock)
 {
     _readyLocation = installationDirectory.GetChildDirectory(LocationExtensions.Ready);
     _readyLocation.EnsureExists();
     _clock = clock;
 }
 public TuckerRockyVendor(ITextFileReader fileReader, IFileHelpersCache fileHelpersCache, SystemClock clock)
 {
     _fileReader = fileReader;
     _fileHelpersCache = fileHelpersCache;
     _clock = clock;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="TransactionList"/> class.
 /// </summary>
 /// <param name="systemClock">The system clock.</param>
 public TransactionList(SystemClock systemClock)
 {
     Transactions = new List<Transaction>();
 }
Exemple #51
0
 public SiteList(SystemClock systemClock)
 {
     Sites = new List<Site>();
     Clock = systemClock;
 }
 public VendorDirectory(Directory vendorLocation, IVendor vendor, SystemClock clock)
 {
     _vendorLocation = vendorLocation;
     _vendor = vendor;
     _clock = clock;
 }
 public DropShipperDirectory(Directory dropShipperLocation, IDropShipper dropShipper, SystemClock clock)
 {
     _dropShipperLocation = dropShipperLocation;
     _dropShipper = dropShipper;
     _clock = clock;
 }