Ejemplo n.º 1
0
        public Session(
            Application app, MessageStoreFactory storeFactory, SessionID sessID, DataDictionaryProvider dataDictProvider,
            SessionSchedule sessionSchedule, int heartBtInt, LogFactory logFactory, IMessageFactory msgFactory, string senderDefaultApplVerID)
        {
            this.Application = app;
            this.SessionID = sessID;
            this.DataDictionaryProvider = new DataDictionaryProvider(dataDictProvider);
            this.schedule_ = sessionSchedule;
            this.msgFactory_ = msgFactory;

            this.SenderDefaultApplVerID = senderDefaultApplVerID;

            this.SessionDataDictionary = this.DataDictionaryProvider.GetSessionDataDictionary(this.SessionID.BeginString);
            if (this.SessionID.IsFIXT)
                this.ApplicationDataDictionary = this.DataDictionaryProvider.GetApplicationDataDictionary(this.SenderDefaultApplVerID);
            else
                this.ApplicationDataDictionary = this.SessionDataDictionary;

            Log log;
            if (null != logFactory)
                log = logFactory.Create(sessID);
            else
                log = new NullLog();

            state_ = new SessionState(log, heartBtInt)
            {
                MessageStore = storeFactory.Create(sessID)
            };

            this.PersistMessages = true;
            this.ResetOnDisconnect = false;
            this.SendRedundantResendRequests = false;
            this.ValidateLengthAndChecksum = true;
            this.CheckCompID = true;
            this.MillisecondsInTimeStamp = true;
            this.EnableLastMsgSeqNumProcessed = false;
            this.MaxMessagesInResendRequest = 0;
            this.SendLogoutBeforeTimeoutDisconnect = false;
            this.IgnorePossDupResendRequests = false;

            if (!IsSessionTime)
                Reset("Out of SessionTime at construction");
            else if (IsNewSession)
                Reset("New session");

            lock (sessions_)
            {
                sessions_[this.SessionID] = this;
            }

            this.Application.OnCreate(this.SessionID);
            this.Log.OnEvent("Created session");
        }
Ejemplo n.º 2
0
        /// FIXME
        public Session(
            Application app, MessageStoreFactory storeFactory, SessionID sessID, DataDictionaryProvider dataDictProvider,
            SessionSchedule sessionSchedule, int heartBtInt, LogFactory logFactory, IMessageFactory msgFactory)
        {
            this.Application = app;
            this.SessionID = sessID;
            this.DataDictionaryProvider = new DataDictionaryProvider(dataDictProvider);
            this.schedule_ = sessionSchedule;
            this.msgFactory_ = msgFactory;

            this.SessionDataDictionary = this.DataDictionaryProvider.GetSessionDataDictionary(this.SessionID.BeginString);
            if (this.SessionID.IsFIXT)
                this.ApplicationDataDictionary = this.DataDictionaryProvider.GetApplicationDataDictionary(this.SenderDefaultApplVerID);
            else
                this.ApplicationDataDictionary = this.SessionDataDictionary;

            Log log;
            if (null != logFactory)
                log = logFactory.Create(sessID);
            else
                log = new NullLog();

            state_ = new SessionState(log, heartBtInt);
            state_.MessageStore = storeFactory.Create(sessID);

            this.PersistMessages = true;
            this.ResetOnDisconnect = false;
            this.SendRedundantResendRequests = false;
            this.ValidateLengthAndChecksum = true;
            this.CheckCompID = true;

            if (!CheckSessionTime())
                Reset();

            lock (sessions_)
            {
                sessions_[this.SessionID] = this;
            }

            this.Application.OnCreate(this.SessionID);
            this.Log.OnEvent("Created session");
        }
Ejemplo n.º 3
0
        public static IContainer CreateIntegrationContainer()
        {
            var builder     = new ContainerBuilder();
            var appSettings = LoadAppSettings();

            builder.RegisterInstance(LogFactory.Create().AddUnbufferedConsole())
            .As <ILogFactory>()
            .As <LogFactory>()
            .SingleInstance();

            builder.RegisterModule(new JobModule(appSettings));
            builder.RegisterModule(new RepositoriesModule(appSettings));
            builder.RegisterModule(new BlockchainsModule(appSettings));
            builder.RegisterModule(new CqrsTestModule(
                                       appSettings.CurrentValue.BlockchainCashinDetectorJob.Cqrs, "test"));

            var testContainer = builder.Build();

            return(testContainer);
        }
Ejemplo n.º 4
0
        public async Task TryToInitServiceTwice_InvalidOperation_ExceptionIsThrown()
        {
            var snapshotRepo = Mock.Of <ITokensSnapshotRepository>();
            var lastTokensTotalAmountRepo = Mock.Of <ILastKnownStatsRepository>();
            var pbfClient = Mock.Of <IPrivateBlockchainFacadeClient>();

            TokensStatisticsService tokensStatisticsService;

            using (var logFactory = LogFactory.Create().AddUnbufferedConsole())
            {
                tokensStatisticsService = new TokensStatisticsService(logFactory,
                                                                      pbfClient,
                                                                      snapshotRepo,
                                                                      lastTokensTotalAmountRepo);
            }

            await tokensStatisticsService.Initialize();

            await Assert.ThrowsAsync <InvalidOperationException>(() => tokensStatisticsService.Initialize());
        }
Ejemplo n.º 5
0
        public async Task Handle(SimDirectiveResult result)
        {
            if (result.IsExecOk && result.Status)
            {
                SuccessHandler?.Invoke(result);
            }

            else if (_retryTimes < 5)
            {
                LogFactory.Create().Info("sim resend times:" + _retryTimes);
                this._retryTimes++;
                await Task.Delay(500);

                SimWorker.Instance.Enqueue(this);
            }
            else
            {
                LogFactory.Create().Info("sim resend failed");
            }
        }
        private ILogFactory InitLogFactory(LoggerBuilderSettings settings)
        {
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }
            if (string.IsNullOrEmpty(settings.AppName))
            {
                throw new ArgumentNullException(nameof(settings.AppName));
            }
            if (string.IsNullOrEmpty(settings.TableName))
            {
                throw new ArgumentNullException(nameof(settings.TableName));
            }

            return(LogFactory.Create()
                   .AddConsole()
                   .AddAzureTable(settings.ConnectionString, settings.TableName)
                   .AddEssentialSlackChannels(settings.SlackNotificationsConnectionString, settings.SlackNotificationsQueueName));
        }
Ejemplo n.º 7
0
        public IntegrationTestBase(
            ITestOutputHelper outputHelper,
            WebApplicationFactory <Startup> factory)
        {
            var loggerFactory = LogFactory.Create(outputHelper);

            loggerFactory.AddProvider(new TestOutputLoggerProvider(outputHelper));

            var httpClient = factory.CreateClient();

            RequestService = new TestRequestService(httpClient, loggerFactory);

            var configuration = new ConfigurationBuilder()
                                .SetBasePath(Directory.GetCurrentDirectory())
                                .AddJsonFile("appsettings.json")
                                .AddJsonFile("appsettings.Development.json", optional: true)
                                .Build();

            MicroserviceSettings = configuration.GetSection(nameof(MicroserviceSettings)).Get <MicroserviceSettings>();
        }
Ejemplo n.º 8
0
        private static void Restore()
        {
            var files = new DirectoryInfo(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)).GetFiles("*.zip");

            foreach (var file in files)
            {
                try
                {
                    var task = new RestorePortalTask(LogFactory.Create("ASC"), ToAbsolute("TeamLabSvc.exe.config"), file.FullName);
                    task.ProgressChanged            += (sender, args) => log.Info(args.Progress);
                    task.UnblockPortalAfterCompleted = true;
                    task.ReplaceDate = true;
                    task.RunJob();
                }
                catch (Exception error)
                {
                    log.Error(error);
                }
            }
        }
        public async Task UserTriesToConfirmEmail_WithVerificationCodeThatNotExistsInTheSrorage_VerificationCodeMismatchReturned()
        {
            var verificationEmailRepository = new Mock <IEmailVerificationCodeRepository>();

            var verificationEmailGetResponse = GetMockedVerificationCode();

            var confirmEmailResponse = new ConfirmVerificationCodeResultModel
            {
                Error      = VerificationCodeError.VerificationCodeMismatch,
                IsVerified = true
            };

            verificationEmailRepository
            .Setup(x => x.GetByValueAsync(It.IsAny <string>()))
            .ReturnsAsync(verificationEmailGetResponse.Object);

            verificationEmailRepository
            .Setup(x => x.CreateOrUpdateAsync(It.IsAny <string>(), It.IsAny <string>()))
            .ReturnsAsync(verificationEmailGetResponse.Object);

            var publisherCodeVerified = new Mock <IRabbitPublisher <AdminEmailVerifiedEvent> >();

            EmailVerificationService emailVerificationService;

            using (var logFactory = LogFactory.Create().AddUnbufferedConsole())
            {
                emailVerificationService = new EmailVerificationService(
                    verificationEmailRepository.Object,
                    publisherCodeVerified.Object,
                    _notificationsServiceMock.Object,
                    _adminUserServiceMock.Object,
                    logFactory
                    );
            }

            var result =
                await emailVerificationService.ConfirmCodeAsync("123456".ToBase64());

            Assert.Equal(confirmEmailResponse.Error.ToString(), result.Error.ToString());
            Assert.False(result.IsVerified);
        }
Ejemplo n.º 10
0
        public async Task UserTriesToLogIn_WithInvalidFormatEmail_InvalidEmailOrPasswordFormatErrorReturned()
        {
            var sessionsServiceClient = new Mock <ISessionsServiceClient>();
            var credentialsClient     = new Mock <ICredentialsClient>();
            var adminUsersService     = new Mock <IAdminUserService>();

            var exception = new ClientApiException(HttpStatusCode.BadRequest, new ErrorResponse());
            var adminUsersServiceResponse = new AdminUserResult
            {
                Error   = AdminUserErrorCodes.None,
                Profile = new AdminUser
                {
                    IsActive = true
                }
            };

            credentialsClient
            .Setup(x => x.Admins.ValidateAsync(It.IsAny <CredentialsValidationRequest>()))
            .Throws(exception);

            adminUsersService
            .Setup(x => x.GetByEmailAsync(It.IsAny <string>(), null))
            .ReturnsAsync(adminUsersServiceResponse);

            AuthService authService;

            using (var logFactory = LogFactory.Create().AddUnbufferedConsole())
            {
                authService = new AuthService(
                    sessionsServiceClient.Object,
                    credentialsClient.Object,
                    adminUsersService.Object,
                    logFactory);
            }

            var result = await authService.AuthAsync("email", "password");

            Assert.Equal(ServicesError.InvalidEmailOrPasswordFormat.ToString(), result.Error.ToString());
            Assert.Null(result.CustomerId);
            Assert.Null(result.Token);
        }
        public void Simple_Test()
        {
            InitializeDependencies();

            _indexCalculator = new IndexCalculator(
                LyCi,
                ShortLyCi,
                true,
                _timerInterval,
                _settingsService,
                _indexStateRepository,
                _indexHistoryRepository,
                _tickPricesService,
                _coinMarketCapService,
                _tickPricePublisher,
                _warningRepository,
                _firstStateAfterResetTimeRepository,
                _indexHandler,
                LogFactory.Create());

            _indexCalculator.Start();

            _indexCalculator.Rebuild();

            var stepsCount = GetPrices(0).Count - 1; // without header

            var counter = 0;

            while (_step != stepsCount)
            {
                counter++;
                Thread.Sleep(1000);

                if (counter > 10)
                {
                    throw new TimeoutException("Debug IndexCalculator.CalculateThenSaveAndPublishAsync() to find exception.");
                }
            }

            _indexCalculator.Stop();
        }
Ejemplo n.º 12
0
        public async Task LogsDeleted_When_TwoLogsExist()
        {
            // Arrange
            var logs = LogFactory.Create(2);

            _logRepositoryMock.Setup(x => x.GetAllAsync()).Returns(Task.FromResult(logs));
            var exceptionLogDumpCreator = new DistributeLogDumpCreator(
                _logRepositoryMock.Object,
                _dateTimeProvider.Object,
                _fileProvider.Object,
                _directoryProvider.Object,
                _pathProvider.Object,
                _consoleProvider.Object,
                _reflectionProvider.Object);

            // Act
            await exceptionLogDumpCreator.DeleteAllDumpsAsync();

            // Assert
            _logRepositoryMock.Verify(x => x.DeleteAsync(logs), Times.AtLeastOnce());
        }
        public async Task TryingToDeleteProfileContactByLocationId_ValidLocationId_SuccessfullyDeleted()
        {
            var partnerContactRepository = new Mock <IPartnerContactRepository>();

            partnerContactRepository
            .Setup(x => x.DeleteIfExistsAsync(It.IsAny <string>()))
            .Verifiable();

            PartnerContactService partnerContactService;

            using (var logFactory = LogFactory.Create().AddUnbufferedConsole())
            {
                partnerContactService = new PartnerContactService(
                    partnerContactRepository.Object,
                    logFactory);
            }

            await partnerContactService.RemoveIfExistsAsync("testContactId");

            partnerContactRepository.Verify();
        }
Ejemplo n.º 14
0
        protected ISignServiceApi CreateClientApi <TStartup>(string integrationName, string localhost, TimeSpan?timeout = null) where TStartup : class
        {
            IServiceCollection collection = new ServiceCollection();
            var testServer = CreateTestServer <TStartup>();
            var client     = testServer.CreateClient();

            collection.AddSingleton(LogFactory.Create().AddConsole());
            collection.AddSignServiceClient(options =>
            {
                options.Timeout = timeout;
                options.AddDelegatingHandler(new RedirectToTestHostMessageHandler(client));
                options.AddIntegration(integrationName, integrationOptions =>
                {
                    integrationOptions.Url = localhost;
                });
            });
            var provider = collection.BuildServiceProvider();
            var api      = provider.GetRequiredService <ISignServiceApiProvider>().GetApi(integrationName);

            return(api);
        }
Ejemplo n.º 15
0
        private void ReceiveCallback(IAsyncResult result)
        {
            try
            {
                var ts  = (Socket)result.AsyncState;
                var len = ts.EndReceive(result);
                result.AsyncWaitHandle.Close();
                if (len > 0)
                {
                    byte[] bufferTemp = new byte[len];
                    ByteMencpy(bufferTemp, buffer, len);
                    LogFactory.Create().Info("receive ->" + Common.Utility.Common.BytesToString(bufferTemp) + "<- receive end");
                }

                ts.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), ts);
            }
            catch (SocketException e)
            {
                LogFactory.Create().Info("接收异常:" + e.Message);
            }
        }
Ejemplo n.º 16
0
 private async Task StartNextLoop(Tuple <DateTime, double, double> next)
 {
     if (next != null)
     {
         var interval = (int)((DateTime)next.Item1 - DateTime.Now).TotalMilliseconds;
         LogFactory.Create().Info($"StartNextLoop pump{PumpCultivation.Device.DeviceId} starttime{next.Item1:yyyy-MM-dd HH:mm:ss}, interval{interval}");
         if (interval < 0)
         {
             interval = 0;
         }
         try
         {
             await Task.Delay(interval, CancellationTokenSource.Token);
             await ExecStart(next.Item2, next.Item3);
         }
         catch (Exception)
         {
             LogFactory.Create().Info($"DEVICE{Device.DeviceId} StartNextLoop is cancel");
         }
     }
 }
Ejemplo n.º 17
0
        public async Task UserTriesToConfirmEmail_WithVerificationCodeThatHasAlreadyExpired_VerificationCodeExpiredReturned()
        {
            var verificationEmailRepository = new Mock <IEmailVerificationCodeRepository>();

            var verificationEmailGetResponse = GetMockedVerificationCode();

            verificationEmailGetResponse.SetupProperty(_ => _.ExpireDate, DateTime.UtcNow.AddYears(-1000));

            var confirmEmailResponse = new ConfirmVerificationCodeResultModel
            {
                Error      = VerificationCodeError.VerificationCodeExpired,
                IsVerified = true
            };

            verificationEmailRepository
            .Setup(x => x.GetByValueAsync(It.IsAny <string>()))
            .ReturnsAsync(verificationEmailGetResponse.Object);

            verificationEmailRepository
            .Setup(x => x.CreateOrUpdateAsync(It.IsAny <string>(), It.IsAny <string>()))
            .ReturnsAsync((IVerificationCode)null);

            var publisherCodeVerified = new Mock <IRabbitPublisher <AdminEmailVerifiedEvent> >();

            EmailVerificationService emailVerificationService;

            using (var logFactory = LogFactory.Create().AddUnbufferedConsole())
            {
                emailVerificationService = new EmailVerificationService(
                    verificationEmailRepository.Object,
                    publisherCodeVerified.Object,
                    logFactory
                    );
            }

            var result = await emailVerificationService.ConfirmCodeAsync("DDD666".ToBase64());

            Assert.Equal(confirmEmailResponse.Error.ToString(), result.Error.ToString());
            Assert.False(result.IsVerified);
        }
        public async Task Session_Should_Be_Refreshed_WithGet()
        {
            _client = new RedisSessionsClient(
                _connectionMultiplexer,
                "Sessions",
                TimeSpan.FromSeconds(1),
                TimeSpan.FromMinutes(5),
                LogFactory.Create(),
                _startedPublisher,
                _endedPublisher);
            var session = await _client.Authenticate(Guid.NewGuid().ToString(), "SomeInfo");

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

            await _client.GetAsync(session.SessionToken);

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

            var result = await _client.GetAsync(session.SessionToken);

            Assert.NotNull(result);
        }
        public async Task UserTriesToLogIn_WithInvalidFormatEmail_InvalidPasswordFormatErrorReturned()
        {
            var sessionsServiceClient = new Mock <ISessionsServiceClient>();
            var credentialsClient     = new Mock <ICredentialsClient>();
            var customerProfileClient = new Mock <ICustomerProfileClient>();

            var modelError = new ErrorResponse
            {
                ModelErrors = new Dictionary <string, List <string> >
                {
                    { nameof(CredentialsValidationRequest.Password), new List <string>() }
                }
            };
            var exception = new ClientApiException(HttpStatusCode.BadRequest, modelError);

            credentialsClient
            .Setup(x => x.Api.ValidateCredentialsAsync(It.IsAny <CredentialsValidationRequest>()))
            .Throws(exception);

            var customerService = new Mock <ICustomersService>();

            AuthService authService;

            using (var logFactory = LogFactory.Create().AddUnbufferedConsole())
            {
                authService = new AuthService(
                    sessionsServiceClient.Object,
                    credentialsClient.Object,
                    customerProfileClient.Object,
                    customerService.Object,
                    logFactory);
            }

            var result = await authService.AuthAsync("email", "password");

            Assert.Equal(CustomerManagementError.InvalidPasswordFormat.ToString(), result.Error.ToString());
            Assert.Null(result.CustomerId);
            Assert.Null(result.Token);
        }
Ejemplo n.º 20
0
        public void Send(byte[] buffer, CancellationToken token)
        {
            //运行过程中串口异常
            try
            {
                LogFactory.Create().Info($"send ->{Shunxi.Common.Utility.Common.BytesToString(buffer)}<- send end");
                SerialPort.Write(buffer, 0, buffer.Length);
            }
            catch (Exception ex)
            {
                if (SerialPort != null)
                {
                    SerialPort.DataReceived  -= SerialPort_DataReceived;
                    SerialPort.ErrorReceived -= SerialPort_ErrorReceived;
                }

                Status = SerialPortStatus.Initialled;
                SerialPort?.Close();
                SerialPort?.Dispose();
                LogFactory.Create().Error("usb serial port send msg error" + ex.Message);
            }
        }
        public async Task Should_Not_Return_UserIds()
        {
            _client = new RedisSessionsClient(
                _connectionMultiplexer,
                "Sessions",
                TimeSpan.FromSeconds(1),
                TimeSpan.FromMinutes(5),
                LogFactory.Create(),
                _startedPublisher,
                _endedPublisher);
            var user1 = Guid.NewGuid().ToString();
            var user2 = Guid.NewGuid().ToString();
            await _client.Authenticate(user1, "SomeInfo");

            await _client.Authenticate(user2, "SomeInfo");

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

            var result = await _client.GetActiveClientIdsAsync();

            Assert.Empty(result);
        }
Ejemplo n.º 22
0
        public static void RunIt(RabbitMqSubscriptionSettings settingsAssetsInfo, RabbitMqSubscriptionSettings settingsThresholds)
        {
            var logFactory = LogFactory.Create();

            logFactory.AddProvider(new ConsoleLoggerProvider((itm1, itm2) => true, true));



            _connector = new RabbitMqSubscriber <string>(logFactory, settingsAssetsInfo, new DefaultErrorHandlingStrategy(logFactory, settingsAssetsInfo))
                         .SetMessageDeserializer(new DefaultStringDeserializer())
                         .SetMessageReadStrategy(new MessageReadWithTemporaryQueueStrategy())
                         .CreateDefaultBinding()
                         .Subscribe(HandleMessage)
                         .Start();

            _thresholds = new RabbitMqSubscriber <string>(logFactory, settingsThresholds, new DefaultErrorHandlingStrategy(logFactory, settingsThresholds))
                          .SetMessageDeserializer(new DefaultStringDeserializer())
                          .SetMessageReadStrategy(new MessageReadWithTemporaryQueueStrategy())
                          .CreateDefaultBinding()
                          .Subscribe(HandleThresholdsMessage)
                          .Start();
        }
Ejemplo n.º 23
0
        public async Task GetBatchOfCustomerBlockStatuses_InvalidInputParameter_ErrorReturned()
        {
            var customerProfileClient = new Mock <ICustomerProfileClient>();

            var credentialsClient = new Mock <ICredentialsClient>();

            var postProcessService = new Mock <IPostProcessService>();

            var customerFlagsRepository = new Mock <ICustomerFlagsRepository>();

            var sessionsServiceClient = new Mock <ISessionsServiceClient>();

            CustomersService customersService;

            using (var logFactory = LogFactory.Create().AddUnbufferedConsole())
            {
                customersService = new CustomersService(
                    credentialsClient.Object,
                    postProcessService.Object,
                    customerProfileClient.Object,
                    customerFlagsRepository.Object,
                    sessionsServiceClient.Object,
                    _passwordSuccessfulChangeEmailTemplateId,
                    _passwordSuccessfulChangeEmailSubjectTemplateId,
                    logFactory,
                    MaxBatchValue,
                    _publisher.Object,
                    _customerBlockEmailTemplateId,
                    _customerUnBlockEmailTemplateId,
                    _customerBlockSubjectTemplateId,
                    _customerUnBlockSubjectTemplateId,
                    _customerSupportPhoneNumber);
            }

            var result =
                await customersService.GetBatchOfCustomersBlockStatusAsync(Enumerable.Repeat("a", 101).ToArray());

            Assert.Equal(BatchCustomerStatusesErrorCode.InvalidCustomerIdsCount, result.Error);
        }
Ejemplo n.º 24
0
        private static async Task SendByHttp(string url, CnetScan cnetScans, Action <string> cb)
        {
            using (HttpClient client = new HttpClient())
            {
                try
                {
                    var uri = new Uri($"http://{Config.SERVER_ADDR}:{Config.SERVER_PORT}/api/sim/location?mcc={cnetScans.MCC}&mnc={cnetScans.MNC}&lac={cnetScans.Lac}&ci={cnetScans.Cellid}&deviceid={Common.Utility.Common.GetUniqueId()}");
                    HttpResponseMessage response = await client.GetAsync(uri);

                    if (response.EnsureSuccessStatusCode().StatusCode.ToString().ToLower() == "ok")
                    {
                        string responseBody = await response.Content.ReadAsStringAsync();

                        cb?.Invoke(responseBody);
                    }
                }
                catch (HttpRequestException ex)
                {
                    LogFactory.Create().Info(ex.Message);
                }
            }
        }
Ejemplo n.º 25
0
        public async Task UserTriesToLogIn_UnexpectedErrorInValidation_InvalidOperationIsThrown()
        {
            var sessionsServiceClient = new Mock <ISessionsServiceClient>();
            var credentialsClient     = new Mock <ICredentialsClient>();
            var adminUsersService     = new Mock <IAdminUserService>();

            var response = new AdminCredentialsValidationResponse {
                Error = CredentialsError.LoginAlreadyExists
            };
            var adminUsersServiceResponse = new AdminUserResult
            {
                Error   = AdminUserErrorCodes.None,
                Profile = new AdminUser
                {
                    IsActive = true
                }
            };

            credentialsClient
            .Setup(x => x.Admins.ValidateAsync(It.IsAny <CredentialsValidationRequest>()))
            .ReturnsAsync(response);

            adminUsersService
            .Setup(x => x.GetByEmailAsync(It.IsAny <string>(), null))
            .ReturnsAsync(adminUsersServiceResponse);

            AuthService authService;

            using (var logFactory = LogFactory.Create().AddUnbufferedConsole())
            {
                authService = new AuthService(
                    sessionsServiceClient.Object,
                    credentialsClient.Object,
                    adminUsersService.Object,
                    logFactory);
            }

            await Assert.ThrowsAsync <InvalidOperationException>(() => authService.AuthAsync("email", "password"));
        }
Ejemplo n.º 26
0
        public void InstanceSystemStatusChangeEvent(object sender, RunStatusChangeEventArgs e)
        {
            LogFactory.Create().Info($"==================sys->{e.SysStatus}==================");

            Dispatcher.Invoke(() =>
            {
                SwitchCommandStatus(e.SysStatus);

                txtStatus.Text = e.SysStatus.ToString().ToLower();
                if (e.SysStatus == SysStatusEnum.Starting)
                {
                    UpdatePumpIn();
                    UpdatePumpOut();
                }
                else if (e.SysStatus == SysStatusEnum.Completed)
                {
                    //new ModalDialog().Show("细胞培养流程已完成");
                    LogFactory.Create().Info("细胞培养流程已完成");
                    //await ReStart();
                }
            });
        }
        public async Task TryingToGetProfileContactByLocationId_InvalidLocationId_ErrorCodeIsReturned()
        {
            var partnerContactRepository = new Mock <IPartnerContactRepository>();

            partnerContactRepository
            .Setup(x => x.GetByLocationIdAsync(It.IsAny <string>()))
            .ReturnsAsync((IPartnerContact)null);

            PartnerContactService partnerContactService;

            using (var logFactory = LogFactory.Create().AddUnbufferedConsole())
            {
                partnerContactService = new PartnerContactService(
                    partnerContactRepository.Object,
                    logFactory);
            }

            var actual = await partnerContactService.GetByLocationIdAsync("testContactId");

            Assert.Equal(PartnerContactErrorCodes.PartnerContactDoesNotExist, actual.ErrorCode);
            Assert.Null(actual.PartnerContact);
        }
Ejemplo n.º 28
0
        public async Task UserTriesToConfirmEmail_WithNewAdmin_Successfully()
        {
            var verificationEmailRepository = new Mock <IEmailVerificationCodeRepository>();

            var verificationEmailGetResponse = GetMockedVerificationCode();

            var confirmEmailResponse = new ConfirmVerificationCodeResultModel
            {
                Error      = VerificationCodeError.None,
                IsVerified = true
            };

            verificationEmailRepository
            .Setup(x => x.GetByValueAsync(It.IsAny <string>()))
            .ReturnsAsync(verificationEmailGetResponse.Object);

            verificationEmailRepository
            .Setup(x => x.CreateOrUpdateAsync(It.IsAny <string>(), It.IsAny <string>()))
            .ReturnsAsync((IVerificationCode)null);

            var publisherCodeVerified = new Mock <IRabbitPublisher <AdminEmailVerifiedEvent> >();

            EmailVerificationService emailVerificationService;

            using (var logFactory = LogFactory.Create().AddUnbufferedConsole())
            {
                emailVerificationService = new EmailVerificationService(
                    verificationEmailRepository.Object,
                    publisherCodeVerified.Object,
                    logFactory
                    );
            }

            var result = await emailVerificationService.ConfirmCodeAsync("DDD666".ToBase64());

            Assert.Equal(confirmEmailResponse.Error.ToString(), result.Error.ToString());
            Assert.True(result.IsVerified);
        }
        public (IContainer resolver, ILog logToConsole) GetResolver(string horizonUrl, string passPhrase)
        {
            ContainerBuilder   containerBuilder = new ContainerBuilder();
            IServiceCollection collection       = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            var consoleLogger = LogFactory.Create();

            consoleLogger.AddConsole(options => { options.IncludeScopes = true; });
            var log = consoleLogger.CreateLog(this);

            collection.AddSingleton <ILog>(log);
            collection.AddHttpClient();
            containerBuilder.RegisterType <HorizonService>()
            .As <IHorizonService>()
            .WithParameter("network", passPhrase)
            .WithParameter("horizonUrl", horizonUrl)
            .SingleInstance();
            containerBuilder.Populate(collection);

            var resolver = containerBuilder.Build();

            return(resolver, log);
        }
Ejemplo n.º 30
0
        public async Task TryToGetTokensSnapshot_SnapshotDoesNotExists_ResultWithBusinessError()
        {
            var lastTokensTotalAmountRepo = Mock.Of <ILastKnownStatsRepository>();
            var pbfClient    = Mock.Of <IPrivateBlockchainFacadeClient>();
            var snapshotRepo = new Mock <ITokensSnapshotRepository>();

            snapshotRepo.Setup(x => x.GetTokensSnapshotByDate(It.IsAny <string>()))
            .ReturnsAsync((DailyTokensSnapshot)null);

            TokensStatisticsService tokensStatisticsService;

            using (var logFactory = LogFactory.Create().AddUnbufferedConsole())
            {
                tokensStatisticsService = new TokensStatisticsService(logFactory,
                                                                      pbfClient,
                                                                      snapshotRepo.Object,
                                                                      lastTokensTotalAmountRepo);
            }

            var result = await tokensStatisticsService.GetTokensSnapshotForDate(DateTime.UtcNow.AddDays(-1));

            Assert.Equal(TokensErrorCodes.StatisticsNotFound, result.ErrorCode);
        }
Ejemplo n.º 31
0
        public override void ProcessPausingResult(DirectiveData data, CommunicationEventArgs comEventArgs)
        {
            var ret = data as PumpDirectiveData;

            if (ret != null && ret.FlowRate <= 0)
            {
                comEventArgs.DeviceStatus = DeviceStatusEnum.Idle;
                comEventArgs.Description  = IdleDesc.Paused.ToString();;

                this.SetStatus(DeviceStatusEnum.Idle);

                StopEvent.TrySetResult(new DeviceIOResult(true));
                StopTime            = DateTime.Now;
                PreUnfinishedVolume = CalcPreUnfinishedVolume();
                LogFactory.Create().Info($"device{Device.DeviceId} PreUnfinishedVolume is {PreUnfinishedVolume}");
                OnCommunicationChange(comEventArgs);
            }
            else
            {
                comEventArgs.DeviceStatus = DeviceStatusEnum.Pausing;
                StartPauseLoop();
            }
        }
Ejemplo n.º 32
0
        public async Task Open(SerialEnum serialType)
        {
            await Task.Yield();

            if (Status == SerialPortStatus.Initialled)
            {
                try
                {
                    Status = SerialPortStatus.Opening;
                    client.Connect(ADDR, PORT);

                    Status = SerialPortStatus.Opened;

                    _readCancellationTokenSource = new CancellationTokenSource();
                    Listen().IgnorCompletion();
                }
                catch (Exception e)
                {
                    LogFactory.Create().Info("net serial open error" + e.Message);
                    Status = SerialPortStatus.Initialled;
                }
            }
        }