protected override void EndProcessing()
        {
            base.EndProcessing();

            if (!string.IsNullOrWhiteSpace(Header) && (Body == null || !Body.Any()))
            {
                throw new PSArgumentException("Header cannot be used without Body. Please specify a Body and try again.");
            }

            var hour = Now.Time().Hour;

            if (hour is >= 0 and <= 4)
            {
                var dayPrior = Date.Minus(Period.FromDays(1));
                var question = $"Edit entry for '{dayPrior}' or '{Date}'?";
                var result   = Choice("It's after midnight!", question, 0, dayPrior.DayOfWeek.ToChoiceString(), Date.DayOfWeek.ToChoiceString());
                if (result == 0)
                {
                    Date = dayPrior;
                }
            }

            var journal = OpenJournal();

            journal.AppendEntryContent(Date, Body, Header, Tags, Readme, out var warnings);

            foreach (var warning in warnings)
            {
                WriteWarning(warning.Wrap(WrapWidth));
            }
        }
Esempio n. 2
0
        private async Task <string> GetWeather(string cityname)
        {
            WeatherData weatherdata = await GetWeatherDataAsync(cityname);

            if (weatherdata == null || weatherdata.HeWeather5 == null)
            {
                return(string.Format("无法获取\"{0}\"的天气信息", cityname));
            }
            else
            {
                Heweather5[] weatherServices = weatherdata.HeWeather5;
                if (weatherServices.Length <= 0)
                {
                    return(string.Format("无法获取\"{0}\"的天气信息", cityname));
                }
                Basic cityInfo = weatherServices[0].basic;
                if (cityInfo == null)
                {
                    return(string.Format("\"{0}\"应该不是城市的名字", cityname));
                }
                string cityInfoString    = "城市:" + cityInfo.city + "\r\n";
                Now    cityNowInfo       = weatherServices[0].now;
                string cityNowInfoString = "现在天气:" + cityNowInfo.cond.txt + "\r\n"
                                           + "现在温度:" + cityNowInfo.tmp;
                Suggestion citySuggestionInfo       = weatherServices[0].suggestion;
                string     citySuggestionInfoString = "舒适指数:" + citySuggestionInfo.comf.brf + "\r\n"
                                                      + "穿衣建议:" + citySuggestionInfo.drsg.txt + "\r\n"
                                                      + "运动建议:" + citySuggestionInfo.sport.txt + "\r\n";
                Aqi    cityAqiInfo       = weatherServices[0].aqi;
                string cityAqiInfoString = "空气质量指数:" + cityAqiInfo.city.aqi + "\r\n"
                                           + "PM2.5:" + cityAqiInfo.city.pm25;
                return(string.Format("现在{0}的天气:\r\n{1}", cityname, cityInfoString + cityNowInfoString + cityAqiInfoString + citySuggestionInfoString));
            }
        }
Esempio n. 3
0
        private static IEnumerable <Schedule> CalculateNextRun(IEnumerable <Schedule> schedules)
        {
            foreach (var schedule in schedules)
            {
                if (schedule.CalculateNextRun == null)
                {
                    if (schedule.DelayRunFor > TimeSpan.Zero)
                    {
                        // delayed job
                        schedule.NextRun = Now.Add(schedule.DelayRunFor);
                        _schedules.Add(schedule);
                    }
                    else
                    {
                        // run immediately
                        yield return(schedule);
                    }
                    var hasAdded = false;
                    foreach (var child in schedule.AdditionalSchedules.Where(x => x.CalculateNextRun != null))
                    {
                        var nextRun = child.CalculateNextRun(Now.Add(child.DelayRunFor).AddMilliseconds(1));
                        if (!hasAdded || schedule.NextRun > nextRun)
                        {
                            schedule.NextRun = nextRun;
                            hasAdded         = true;
                        }
                    }
                }
                else
                {
                    schedule.NextRun = schedule.CalculateNextRun(Now.Add(schedule.DelayRunFor));
                    _schedules.Add(schedule);
                }

                foreach (var childSchedule in schedule.AdditionalSchedules)
                {
                    if (childSchedule.CalculateNextRun == null)
                    {
                        if (childSchedule.DelayRunFor > TimeSpan.Zero)
                        {
                            // delayed job
                            childSchedule.NextRun = Now.Add(childSchedule.DelayRunFor);
                            _schedules.Add(childSchedule);
                        }
                        else
                        {
                            // run immediately
                            yield return(childSchedule);

                            continue;
                        }
                    }
                    else
                    {
                        childSchedule.NextRun = childSchedule.CalculateNextRun(Now.Add(childSchedule.DelayRunFor));
                        _schedules.Add(childSchedule);
                    }
                }
            }
        }
            public async Task ItShouldRenewTheLeaseWithRateLimiter()
            {
                this.SetupAquireMocks();
                await this.target.AcquireLeaseAsync();

                this.blob.Setup(v => v.RenewLeaseAsync(It.IsAny <AccessCondition>(), this.cancellationToken))
                .Returns(Task.FromResult(0)).Verifiable();

                await this.target.KeepAliveAsync();

                this.blob.Verify(v => v.RenewLeaseAsync(It.IsAny <AccessCondition>(), this.cancellationToken), Times.Exactly(0));

                this.timestampCreator.Setup(v => v.Now()).Returns(Now.AddSeconds(BlobLease.RenewRateLimitSeconds - 1));
                await this.target.KeepAliveAsync();

                this.blob.Verify(v => v.RenewLeaseAsync(It.IsAny <AccessCondition>(), this.cancellationToken), Times.Exactly(0));

                this.timestampCreator.Setup(v => v.Now()).Returns(Now.AddSeconds(BlobLease.RenewRateLimitSeconds));
                await this.target.KeepAliveAsync();

                this.blob.Verify(v => v.RenewLeaseAsync(It.IsAny <AccessCondition>(), this.cancellationToken), Times.Exactly(1));

                this.timestampCreator.Setup(v => v.Now()).Returns(Now.AddSeconds((BlobLease.RenewRateLimitSeconds * 2) - 1));
                await this.target.KeepAliveAsync();

                this.blob.Verify(v => v.RenewLeaseAsync(It.IsAny <AccessCondition>(), this.cancellationToken), Times.Exactly(1));

                this.timestampCreator.Setup(v => v.Now()).Returns(Now.AddSeconds(BlobLease.RenewRateLimitSeconds * 2));
                await this.target.KeepAliveAsync();

                this.blob.Verify(v => v.RenewLeaseAsync(It.IsAny <AccessCondition>(), this.cancellationToken), Times.Exactly(2));

                this.blob.Verify();
            }
            public async Task ItShouldUpdateTheTimestamps()
            {
                this.SetupAquireMocks();
                await this.target.AcquireLeaseAsync();

                await this.target.RenewLeaseAsync();

                await this.target.KeepAliveAsync();

                await this.target.RenewLeaseAsync();

                var end = Now.AddDays(1);

                this.timestampCreator.Setup(v => v.Now()).Returns(end);

                this.blob.Setup(v => v.FetchAttributesAsync(this.cancellationToken)).Returns(Task.FromResult(0)).Verifiable();

                var metadata = new Dictionary <string, string>();

                this.blob.SetupGet(v => v.Metadata).Returns(metadata);

                this.blob.Setup(v => v.SetMetadataAsync(It.IsAny <AccessCondition>(), null, null, this.cancellationToken)).Returns(Task.FromResult(0)).Verifiable();

                await this.target.UpdateTimestampsAsync();

                this.blob.Verify();

                Assert.AreEqual <DateTime>(Now, metadata[Azure.Constants.LeaseStartTimestampMetadataKey].FromIso8601String());
                Assert.AreEqual <DateTime>(end, metadata[Azure.Constants.LeaseEndTimestampMetadataKey].FromIso8601String());
                Assert.AreEqual(3, int.Parse(metadata[Azure.Constants.LeaseRenewCountMetadataKey]));
            }
Esempio n. 6
0
        public void Configure(IApplicationBuilder app)
        {
            app.Run(context => {
                var requestPath = context.Request.Path;
                switch (requestPath)
                {
                case "/log-time.html":
                    if (context.Request.Method == "POST")
                    {
                        var date = ParseExact(context.Request.Form["date"], "yyyy-MM-dd",
                                              CultureInfo.InvariantCulture);
                        var loggedTimeEvent = new LoggedTimeEvent(
                            date,
                            context.Request.Form["hour"],
                            context.Request.Form["minute"],
                            context.Request.Form["total-hours"],
                            context.Request.Form["project"]);
                        File.WriteAllText("events/" + Now.ToUniversalTime() + "-LoggedTime.json", JsonSerializer.Serialize(loggedTimeEvent));
                    }
                    return(context.Response.WriteAsync(FillTemplate("layout/log-time.html",
                                                                    GetTodayAndYesterday())));

                default:
                    return(context.Response.WriteAsync("Unknown path: " + requestPath));
                }
            });
        }
Esempio n. 7
0
        }         // CalculateRollovers

        private int CalculateSeniority()
        {
            if (this.customer == null)
            {
                this.log.Debug("CalculateSeniority: 0 because customer is null.");
                return(-1);
            }             // if

            DateTime oMpOriginationDate = this.db.ExecuteScalar <DateTime?>(
                "LoadCustomerFirstTransactionTime",
                CommandSpecies.StoredProcedure,
                new QueryParameter("CustomerID", this.customer.Id)
                ) ?? Now;

            this.log.Debug("CalculateSeniority: mp origination date is {0}.", oMpOriginationDate.MomentStr());

            DateTime oIncorporationDate = GetCustomerIncorporationDate();

            this.log.Debug("CalculateSeniority: incorporation date is {0}.", oIncorporationDate.MomentStr());

            DateTime oDate = (oMpOriginationDate < oIncorporationDate) ? oMpOriginationDate : oIncorporationDate;

            this.log.Debug("CalculateSeniority: chosen date is {0}.", oDate.MomentStr());

            this.log.Debug("CalculateSeniority: current date is {0}.", Now.MomentStr());

            int seniority = (int)(Now - oDate).TotalDays;

            this.log.Debug("CalculateSeniority: result is {0} days.", seniority);

            return(seniority);
        }         // CalculateSeniority
        public void Comparer()
        {
            var v1 = Type.Seed(null);
            var v2 = Now.Subtract(TimeSpan.FromTicks(DateAccuracyInTicks));

            Assert.That(() => Type.Comparator.Compare(v1, v2), Throws.Nothing);
        }
Esempio n. 9
0
        public async Task ShouldKeepCurrentTokenParamsAndOptionsEvenIfCurrentTokenIsValidAndNoNewTokenIsRequested()
        {
            var client = GetRestClient(
                null,
                opts => opts.TokenDetails = new TokenDetails("boo")
            {
                Expires = Now.AddHours(10)
            });

            var testAblyAuth      = new TestAblyAuth(client.Options, client);
            var customTokenParams = TokenParams.WithDefaultsApplied();

            customTokenParams.Ttl       = TimeSpan.FromHours(2);
            customTokenParams.Timestamp = Now.AddHours(1);

            var customAuthOptions = AuthOptions.FromExisting(testAblyAuth.Options);

            customAuthOptions.UseTokenAuth = true;

            await testAblyAuth.AuthorizeAsync(customTokenParams, customAuthOptions);

            var expectedTokenParams = customTokenParams.Clone();

            expectedTokenParams.Timestamp = null;
            testAblyAuth.CurrentTokenParams.Should().BeEquivalentTo(expectedTokenParams);
            testAblyAuth.CurrentAuthOptions.Should().BeSameAs(customAuthOptions);
        }
Esempio n. 10
0
 public async Task WithStartBeforeEnd_Throws()
 {
     _ = await Assert.ThrowsAsync <AblyException>(() =>
                                                  _channel.HistoryAsync(new PaginatedRequestParams {
         Start = Now, End = Now.AddHours(-1)
     }));
 }
Esempio n. 11
0
        public async Task single_should_load_aggregate()
        {
            // arrange
            var id          = NewGuid();
            var birthday    = Now.AddYears(-3);
            var anniversary = Now;
            var person      = new Person(id, "Jane", "Smith", birthday);
            var spouse      = new Person(NewGuid(), "John", "Doe", Now);

            person.Marry(spouse, anniversary);
            person.ChangeLastName("Doe");

            var events = new IEvent[]
            {
                new Born(id, "Jane", "Smith", birthday),
                new Married(id, spouse.Id, anniversary),
                new LastNameChanged(id, "Doe")
            };
            var eventStore = new SimpleEventStore(new Dictionary <Guid, IEnumerable <IEvent> >()
            {
                [id] = events
            });
            var repository = new Repository <Person>(eventStore);

            // act
            var twin = await repository.Single(id, CancellationToken.None);

            // assert
            twin.Equals(person).Should().BeTrue();
        }
Esempio n. 12
0
 public void StartCount(int stage)
 {
     IsStartCount[stage] = true;
     NowSec[stage]       = Now.Second;
     GoalTimes[stage]    = Now.AddHours(ResourceDatas[stage].hour);
     GoalTimes[stage]    = GoalTimes[stage].AddMinutes(ResourceDatas[stage].min);
 }
Esempio n. 13
0
        public void CountDownToStringIsHHMM()
        {
            var startedTimer = _countDownTimer.Start();

            Now = Now.AddSeconds(30);
            Assert.Equal($"14:30", startedTimer.ToString());
        }
Esempio n. 14
0
 public ProductCommandHandlers(
     GetStreamName getStreamName,
     AsyncRepository <Product> repository,
     AsyncSnapshotableRepository <Product> snapshotableRepository,
     Now now) : base(getStreamName, repository, snapshotableRepository, now)
 {
 }
Esempio n. 15
0
        private void SendClientNames(Socket thisClient)
        {
            try
            {
                string names = "ClientsNameList:";

                foreach (Socket otherClient in _clientSockets)
                {
                    if (thisClient != otherClient)
                    {
                        lock (this)
                        {
                            names += _clientsName[otherClient.RemoteEndPoint.ToString()] != string.Empty
                                ? _clientsName[otherClient.RemoteEndPoint.ToString()] + ";" : "";
                        }
                    }
                }
                thisClient.Send(Encoding.GetEncoding(1251).GetBytes(names));
                Application.Current.Dispatcher.Invoke(() =>
                {
                    _logsTextBox.Text += $"[{Now.ToLongTimeString()}] Отправки списка клиентов клиенту {_clientsName[thisClient.RemoteEndPoint.ToString()]}\r\n";
                });
            }
            catch
            {
                // ignored
            }
        }
        public ProcessClientOutboxMessageCommandV2HandlerTestsFixture()
        {
            Now          = DateTime.UtcNow;
            EndpointName = "SFA.DAS.NServiceBus";

            Events = new List <object>
            {
                new FooEvent(Now.AddDays(-1)),
                new BarEvent(Now)
            };

            TransportOperations        = Events.Select(e => new TransportOperation(Guid.NewGuid(), e)).ToList();
            ClientOutboxMessage        = new ClientOutboxMessageV2(GuidComb.NewGuidComb(), EndpointName, TransportOperations);
            SynchronizedStorageSession = new Mock <SynchronizedStorageSession>();

            Context = new TestableMessageHandlerContext
            {
                MessageId = ClientOutboxMessage.MessageId.ToString(),
                SynchronizedStorageSession = SynchronizedStorageSession.Object
            };

            Command             = new ProcessClientOutboxMessageCommandV2();
            ClientOutboxStorage = new Mock <IClientOutboxStorageV2>();

            ClientOutboxStorage.Setup(o => o.GetAsync(ClientOutboxMessage.MessageId, SynchronizedStorageSession.Object)).ReturnsAsync(ClientOutboxMessage);

            Handler = new ProcessClientOutboxMessageCommandV2Handler(ClientOutboxStorage.Object);
        }
Esempio n. 17
0
        public void replay_all_should_load_aggregate_from_history()
        {
            // arrange
            var id       = NewGuid();
            var birthday = Now.AddYears(-3);
            var person   = new Person(id, "Jane", "Smith", birthday);
            var spouse   = new Person(NewGuid(), "John", "Doe", Now);
            var version  = 0;

            person.Marry(spouse, Now);
            person.ChangeLastName("Doe");

            foreach (var @event in person.UncommittedEvents)
            {
                @event.Version = version++;
            }

            var lifeExperiences = person.UncommittedEvents.ToArray();
            var twin            = new Person();

            person.AcceptChanges();

            // act
            twin.ReplayAll(lifeExperiences);

            // assert
            twin.Equals(person).Should().BeTrue();
            twin.Version.Should().Be(2);
        }
Esempio n. 18
0
        public async Task save_should_throw_exception_when_concurrency_is_violated()
        {
            // arrange
            var id          = NewGuid();
            var birthday    = Now.AddYears(-21);
            var newEvents   = new IEvent[] { new Married(id, NewGuid(), Now) };
            var persistence = new SimplePersistence();
            var eventStore  = new SimpleEventStore(persistence);

            await persistence.Persist(new Commit()
            {
                Id = id, Version = 0, Events = { new Born(id, "John", "Doe", birthday) }
            }, CancellationToken.None);

            await persistence.Persist(new Commit()
            {
                Id = id, Version = 1, Events = { new Married(id, NewGuid(), Now) }
            }, CancellationToken.None);

            // act
            Func <Task> save = () => eventStore.Save(id, newEvents, 0, CancellationToken.None);

            // assert
            save.Should().Throw <ConcurrencyException>();
        }
Esempio n. 19
0
        public async Task WithDefaultTokenParamsAndTokenParamsSpecified_ShouldUseOnlyParamsPassedIntoTheMethod()
        {
            var client = GetRestClient(
                null,
                options => options.DefaultTokenParams = new TokenParams
            {
                ClientId = "123", Ttl = TimeSpan.FromHours(2)
            });

            var capability = new Capability();

            capability.AddResource("a").AllowAll();
            var methodParams = new TokenParams
            {
                Capability = capability,
                ClientId   = "999",
                Ttl        = TimeSpan.FromMinutes(1),
                Nonce      = "123",
                Timestamp  = Now.AddHours(1)
            };

            await client.Auth.RequestTokenAsync(methodParams);

            var data = LastRequest.PostData as TokenRequest;

            data.Capability.Should().Be(capability);
            data.ClientId.Should().Be(methodParams.ClientId);
            data.Ttl.Should().Be(methodParams.Ttl);
            data.Nonce.Should().Be(methodParams.Nonce);
            data.Timestamp.Should().Be(methodParams.Timestamp);
        }
        protected async Task <bool> HasSubscriptionDayBeenInitialized(DateTime?date = null)
        {
            var dateStr = !date.HasValue ? Now.AddDays(1).Date.ToString("yyyy-MM-dd") : date.Value.ToString("yyyy-MM-dd");
            var item    = await SubscriptionDayRepository.GetSingleAsync(x => x.Date == dateStr);

            return(item != null && item.Initialized);
        }
        public async void SavesRefreshTokenReturnsTokenPair(string uid, bool shouldPersist)
        {
            var user = new User {
                Id = uid, UserName = "******"
            };
            var expected = new TokenPair
            {
                AccessToken  = "axessToken" + uid,
                RefreshToken = "refreshToken" + uid,
                User         = user,
                Persistent   = shouldPersist
            };
            var refreshToken = new RefreshToken
            {
                Token      = expected.RefreshToken,
                UID        = uid,
                ExpiresAt  = Now.AddDays(30),
                Persistent = shouldPersist
            };

            tokenService.Setup(x => x.CreateAccessToken(uid)).Returns(expected.AccessToken);
            tokenService.Setup(x => x.CreateRefreshToken()).Returns(expected.RefreshToken);
            refreshTokenRepo.Setup(x => x.Create(refreshToken)).ReturnsAsync(refreshToken);

            var actual = await userService.CreateAuthTokens(user, shouldPersist);

            Assert.Equal(expected, actual);
            refreshTokenRepo.Verify(x => x.Create(It.IsAny <RefreshToken>()), Times.Once);
        }
Esempio n. 22
0
        // 락이 없는 함수로 푸시 말고는 쓰기 동작이 없어야 한다.
        // Stop이 불리고 나서도 로그가 푸시될 수 있는 것을 감안한다(이런 로그는 Stop에서 처리).
        private Int64 PushImpl(String type, Object log, Boolean doSerialize)
        {
            try
            {
                if (CheckAvailablePush(type, log) == false)
                {
                    return(INVALID_SEQUENCE);
                }

                DateTime now         = Now.NowDateTime();
                Int64    sequence    = _sequenceGenerator.Generate();
                Boolean  successPush = _logQueue.Push(new Log()
                {
                    Sequence    = sequence,
                    LogType     = type,
                    LogObject   = log,
                    TimeStamp   = Now.TimestampSec(now),
                    TimeStampNS = Now.TimestampNS(now),
                    IsRawString = doSerialize
                });

                if (successPush)
                {
                    Watcher.IncrementPushLogCount();
                    return(sequence);
                }

                return(INVALID_SEQUENCE);
            }
            catch (Exception exception)
            {
                ErrorCounter.RaiseError($"Fail Push: {exception.Message}");
                return(INVALID_SEQUENCE);
            }
        }
        public ProcessOutboxMessageCommandHandlerTestsFixture()
        {
            Now = DateTime.UtcNow;

            EndpointName = "SFA.DAS.NServiceBus";

            Events = new List <Event>
            {
                new FooEvent {
                    Created = Now.AddDays(-1)
                },
                new BarEvent {
                    Created = Now
                }
            };

            OutboxMessage = new OutboxMessage(GuidComb.NewGuidComb(), EndpointName, Events);

            Context = new TestableMessageHandlerContext
            {
                MessageId = OutboxMessage.MessageId.ToString()
            };

            Command = new ProcessOutboxMessageCommand();
            Outbox  = new Mock <IOutbox>();

            Outbox.Setup(o => o.GetAsync(OutboxMessage.MessageId)).ReturnsAsync(OutboxMessage);

            Handler = new ProcessOutboxMessageCommandHandler(Outbox.Object);
        }
        public async void RetriesOnceOnDocumentConflictError(string uid, bool shouldPersist)
        {
            var duplicateToken1 = new RefreshToken
            {
                UID        = uid,
                Token      = "tokenthatsalreadyinuse",
                ExpiresAt  = Now.AddDays(30),
                Persistent = shouldPersist
            };
            var duplicateToken2 = new RefreshToken
            {
                UID        = uid,
                Token      = "anothertokenthatsalreadyinuse",
                ExpiresAt  = Now.AddDays(30),
                Persistent = shouldPersist
            };

            tokenService.SetupSequence(x => x.CreateRefreshToken())
            .Returns(duplicateToken1.Token)
            .Returns(duplicateToken2.Token);
            refreshTokenRepo.SetupSequence(x => x.Create(duplicateToken1))
            .ThrowsAsync(new DocumentConflictException());
            refreshTokenRepo.SetupSequence(x => x.Create(duplicateToken2))
            .ThrowsAsync(new DocumentConflictException());

            await Assert.ThrowsAsync <DocumentConflictException>(
                () => userService.CreateAuthTokens(new User {
                Id = uid
            }, shouldPersist)
                );

            refreshTokenRepo.Verify(x => x.Create(It.IsNotNull <RefreshToken>()), Times.Exactly(2));
        }
Esempio n. 25
0
        public async void Run()
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                _logsTextBox.Text += $"[{Now.ToLongTimeString()}] Сервер слушает порт #{_port}\r\n";
            });


            while (true)
            {
                _logsTextBox.Text += $"[{Now.ToLongTimeString()}] Ждем подключения нового клиента...\r\n";

                Socket newClient = await Task.Factory.FromAsync(_serverSocket.BeginAccept, _serverSocket.EndAccept, true);

                _logsTextBox.Text += $"[{Now.ToLongTimeString()}] Клиент пришел {newClient.RemoteEndPoint}\r\n";

                lock (this)
                {
                    _clientSockets.Add(newClient);
                    _clientsName.Add(newClient.RemoteEndPoint.ToString(), string.Empty);
                }

                ConversationStart(newClient);
            }
        }
Esempio n. 26
0
        public void CountDownTimerStopsAt0()
        {
            var inProgressTimer = _countDownTimer.Start();

            Now = Now.AddMinutes(_defaultTimerLength.Minutes + 5);
            Assert.Equal(TimeSpan.Zero, inProgressTimer.TimeLeft);
        }
        public async Task WithTokenErrorAndNonRenewableToken_ShouldRaiseErrorAndTransitionToFailed()
        {
            var tokenDetails = new TokenDetails("id")
            {
                Expires = Now.AddHours(1)
            };
            bool renewTokenCalled = false;
            var  client           = GetClientWithFakeTransport(opts =>
            {
                opts.Key               = "";
                opts.TokenDetails      = tokenDetails;
                opts.UseBinaryProtocol = false;
            }, request =>
            {
                if (request.Url.Contains("/keys"))
                {
                    renewTokenCalled = true;
                    return(_returnedDummyTokenDetails.ToJson().ToAblyResponse());
                }

                return(AblyResponse.EmptyResponse.ToTask());
            });

            await client.FakeProtocolMessageReceived(new ProtocolMessage(ProtocolMessage.MessageAction.Error) { Error = new ErrorInfo("Unauthorised", _tokenErrorCode, HttpStatusCode.Unauthorized) });

            renewTokenCalled.Should().BeFalse();
            client.Connection.State.Should().Be(ConnectionState.Failed);
            client.Connection.ErrorReason.Should().NotBeNull();
            client.Connection.ErrorReason.Code.Should().Be(_tokenErrorCode);
        }
        public async Task WhenInSuspendedStateAfterRetrying_ShouldGoBackToSuspendedState()
        {
            Now = DateTimeOffset.UtcNow;

            _fakeTransportFactory.initialiseFakeTransport =
                transport => transport.OnConnectChangeStateToConnected = false;
            //this will keep it in connecting state

            var client = GetClientWithFakeTransport(opts =>
            {
                opts.AutoConnect = false;
                opts.DisconnectedRetryTimeout = TimeSpan.FromMilliseconds(10);
                opts.SuspendedRetryTimeout    = TimeSpan.FromMilliseconds(10);
                opts.RealtimeRequestTimeout   = TimeSpan.FromMilliseconds(100);
            });

            client.Connect();
            do
            {
                LastCreatedTransport.Listener?.OnTransportEvent(TransportState.Closing, new Exception());
                await WaitForConnectingOrSuspended(client);

                Now = Now.AddSeconds(30);
            } while (client.Connection.State != ConnectionState.Suspended);

            await new ConnectionAwaiter(client.Connection, ConnectionState.Connecting).Wait();
            await new ConnectionAwaiter(client.Connection, ConnectionState.Suspended).Wait();
        }
        public async Task WhenInSuspendedState_ShouldTryAndReconnectAfterSuspendRetryTimeoutIsReached()
        {
            Now = DateTimeOffset.UtcNow;

            _fakeTransportFactory.initialiseFakeTransport =
                transport => transport.OnConnectChangeStateToConnected = false;
            //this will keep it in connecting state

            var client = GetClientWithFakeTransport(opts =>
            {
                opts.AutoConnect = false;
                opts.DisconnectedRetryTimeout = TimeSpan.FromMilliseconds(10);
                opts.SuspendedRetryTimeout    = TimeSpan.FromMilliseconds(100);
            });

            client.Connect();
            do
            {
                LastCreatedTransport.Listener?.OnTransportEvent(TransportState.Closing, new Exception());

                await WaitForConnectingOrSuspended(client);

                Now = Now.AddSeconds(30);
            } while (client.Connection.State != ConnectionState.Suspended);

            var awaiter = new ConnectionAwaiter(client.Connection, ConnectionState.Connecting);
            var elapsed = await awaiter.Wait();

            elapsed.Should().BeCloseTo(client.Options.SuspendedRetryTimeout, 100);
        }
        public async Task WithTokenErrorAndTokenRenewalFails_ShouldRaiseErrorAndTransitionToFailed()
        {
            var tokenDetails = new TokenDetails("id")
            {
                Expires = Now.AddHours(1)
            };
            var client = GetClientWithFakeTransport(opts =>
            {
                opts.TokenDetails      = tokenDetails;
                opts.UseBinaryProtocol = false;
            }, request =>
            {
                if (request.Url.Contains("/keys"))
                {
                    throw new AblyException(new ErrorInfo()
                    {
                        Code = 123
                    });
                }

                return(AblyResponse.EmptyResponse.ToTask());
            });

            await client.FakeProtocolMessageReceived(new ProtocolMessage(ProtocolMessage.MessageAction.Error) { Error = new ErrorInfo("Unauthorised", _tokenErrorCode, HttpStatusCode.Unauthorized) });

            client.Connection.State.Should().Be(ConnectionState.Failed);
            client.Connection.ErrorReason.Should().NotBeNull();
            client.Connection.ErrorReason.Code.Should().Be(123);
        }
Esempio n. 31
0
 public PaymentService(IAccountRepository accountRepository, IBus bus, Now now)
 {
     this.accountRepository = accountRepository;
     this.bus = bus;
     this.now = now;
 }
 public StockControlController(IStockItemService stockItemService, Now now, CurrentUser currentUser)
 {
     this.stockItemService = stockItemService;
     this.now = now;
     this.currentUser = currentUser;
 }
Esempio n. 33
0
 public ChronoMap(Now now)
 {
     _now = now;
 }