public void ActivateAccountSuccessTest_ChecksIfTheAccountIsActivatedSuccessfully_VeririesThroughTheReturnedValue() { IUserRepository userRepository = new MockUserRepository(); ISecurityKeysRepository securityKeysRepository = new MockSecurityKeysRepository(); IPasswordEncryptionService passwordEncryptionService = new PasswordEncryptionService(); IIdentityAccessPersistenceRepository persistenceRepository = new MockPersistenceRepository(false); UserApplicationService userApplicationService = new UserApplicationService(userRepository, securityKeysRepository, passwordEncryptionService, persistenceRepository, new MockEmailService(), new PasswordCodeGenerationService()); // Store the Securiyty Keys with the Username of the User at hand (securityKeysRepository as MockSecurityKeysRepository).AddSecurityKeysPair(new SecurityKeysPair( new ApiKey("123456789").Value, new SecretKey("987654321").Value, "desc", 0, true)); string activationKey = "123456789"; string username = "******"; string password = "******"; User user = new User("*****@*****.**", username, passwordEncryptionService.EncryptPassword(password), "USA", TimeZone.CurrentTimeZone, "", activationKey); user.AddTierStatus(Status.NonVerified, new Tier(TierLevelConstant.Tier0, TierLevelConstant.Tier0)); // We need to encrypt the password in the test case ourselves, as we are not registering the user through // the proper service here (userRepository as MockUserRepository).AddUser(user); bool changeSuccessful = userApplicationService.ActivateAccount(new ActivationCommand(activationKey, username, password)); Assert.IsTrue(changeSuccessful); User user1 = (persistenceRepository as MockPersistenceRepository).GetUser(username); Assert.IsNotNull(user1); Assert.IsTrue(user1.IsActivationKeyUsed.Value); Assert.IsFalse(user1.IsUserBlocked.Value); }
public void ActivateAccountFailDueToBlankPasswordTest_MakesSureThatTheAccountIsNotActivatedWhenBlankPasswordIsGiven_VeririesThroughTheReturnedValue() { IUserRepository userRepository = new MockUserRepository(); ISecurityKeysRepository securityKeysRepository = new MockSecurityKeysRepository(); IPasswordEncryptionService passwordEncryptionService = new PasswordEncryptionService(); IIdentityAccessPersistenceRepository persistenceRepository = new MockPersistenceRepository(false); UserApplicationService userApplicationService = new UserApplicationService(userRepository, securityKeysRepository, passwordEncryptionService, persistenceRepository, new MockEmailService(), new PasswordCodeGenerationService()); // Store the Securiyty Keys with the Username of the User at hand (securityKeysRepository as MockSecurityKeysRepository).AddSecurityKeysPair(new SecurityKeysPair( new ApiKey("123456789").Value, new SecretKey("987654321").Value, "desc", 0, true)); string activationKey = "123456789"; string username = "******"; string password = "******"; User user = new User("*****@*****.**", username, passwordEncryptionService.EncryptPassword(password), "USA", TimeZone.CurrentTimeZone, "", activationKey); user.AddTierStatus(Status.NonVerified, new Tier(TierLevelConstant.Tier0, TierLevelConstant.Tier0)); // We need to encrypt the password in the test case ourselves, as we are not registering the user through // the proper service here (userRepository as MockUserRepository).AddUser(user); userApplicationService.ActivateAccount(new ActivationCommand(activationKey, username, password + "pass")); }
public void CancelAccountActivationSuccessfulTest_MakesSureAccountActivationGetsCancelledWhenEverythingIsGivenAsExpected_VerifiesByReturnedValueAndQueryingRepository() { IUserRepository userRepository = new MockUserRepository(); ISecurityKeysRepository securityKeysRepository = new MockSecurityKeysRepository(); IPasswordEncryptionService passwordEncryptionService = new PasswordEncryptionService(); IIdentityAccessPersistenceRepository persistenceRepository = new MockPersistenceRepository(false); UserApplicationService userApplicationService = new UserApplicationService(userRepository, securityKeysRepository, passwordEncryptionService, persistenceRepository, new MockEmailService(), new PasswordCodeGenerationService()); string activationKey = "123456789"; string username = "******"; string password = "******"; User user = new User("*****@*****.**", username, passwordEncryptionService.EncryptPassword(password), "USA", TimeZone.CurrentTimeZone, "", activationKey); user.AddTierStatus(Status.NonVerified, new Tier(TierLevelConstant.Tier0, TierLevelConstant.Tier0)); // We need to encrypt the password in the test case ourselves, as we are not registering the user through // the proper service here (userRepository as MockUserRepository).AddUser(user); bool accountActivationCancelled = userApplicationService.CancelAccountActivation(new CancelActivationCommand(activationKey)); Assert.IsTrue(accountActivationCancelled); User userByUserName = userRepository.GetUserByUserName(username); Assert.IsNull(userByUserName); }
public void TestAlreadyExists() { var userFactory = new InMemoryUserFactory(); var userRepository = new InMemoryUserRepository(); var userService = new UserService(userRepository); var userApplicationService = new UserApplicationService(userFactory, userRepository, userService); var userName = "******"; userRepository.Save(new User( new UserId("test-id"), new UserName(userName), UserType.Normal )); bool exceptionOccured = false; try { var command = new UserRegisterCommand(userName); userApplicationService.Register(command); } catch { exceptionOccured = true; } Assert.IsTrue(exceptionOccured); }
public void ChangePasswordSuccessTest_ChecksIfThePasswordIsChangedSuccessfully_VeririesThroughTheReturnedValue() { IUserRepository userRepository = new MockUserRepository(); ISecurityKeysRepository securityKeysRepository = new MockSecurityKeysRepository(); IPasswordEncryptionService passwordEncryptionService = new PasswordEncryptionService(); IIdentityAccessPersistenceRepository persistenceRepository = new MockPersistenceRepository(false); UserApplicationService userApplicationService = new UserApplicationService(userRepository, securityKeysRepository, passwordEncryptionService, persistenceRepository, new MockEmailService(), new PasswordCodeGenerationService()); // Store the Securiyty Keys with the Username of the User at hand (securityKeysRepository as MockSecurityKeysRepository).AddSecurityKeysPair(new SecurityKeysPair( new ApiKey("123456789").Value, new SecretKey("987654321").Value, "desc", 0, true)); // We need to encrypt the password in the test case ourselves, as we are not registering the user through // the proper service here (userRepository as MockUserRepository).AddUser(new User("*****@*****.**", "linkinpark", passwordEncryptionService.EncryptPassword("burnitdown"), "USA", TimeZone.CurrentTimeZone, "", "")); User userBeforePasswordChange = userRepository.GetUserByUserName("linkinpark"); string passwordBeforeChange = userBeforePasswordChange.Password; // Give the API key that is already stored in the Security keys repository mentioned with the User Name //UserValidationEssentials userValidationEssentials = new UserValidationEssentials(new Tuple<ApiKey, SecretKey>( // new ApiKey("123456789"), new SecretKey("987654321")), new TimeSpan(0,0,10,0)); ChangePasswordResponse changePasswordResponse = userApplicationService.ChangePassword(new ChangePasswordCommand( "123456789", "burnitdown", "burnitdowntwice")); Assert.IsTrue(changePasswordResponse.ChangeSuccessful); User userAfterPasswordChange = userRepository.GetUserByUserName("linkinpark"); string passwordAfterChange = userAfterPasswordChange.Password; // Verify the old and new password do not match Assert.AreNotEqual(passwordBeforeChange, passwordAfterChange); }
public UserApplicationService(SqlConnection connection, UserApplicationService userService, IUserFactory userFactory, IUserRepository userRepository) { this.connection = connection; this.userService = userService; this.userFactory = userFactory; this.userRepository = userRepository; }
public async void ShouldGetAllUsers() { var users = this.CreateUsers(NumberOfUsersToCreate); var usersOutput = this.CreateUsersDto(NumberOfUsersToCreate); using (this.Repository.Record()) { Expect.Call(this.DbContextScopeFactory.CreateReadOnly()); Expect.Call(this.UserRepository.GetAllListAsync()).Return(Task.FromResult(users)); Expect.Call(this.Mapper.Map <List <UserDto> >(null)).Constraints(Is.Equal(users)).Return(usersOutput).Repeat.Once(); Expect.Call(() => this.Logger.Info(Arg.Text.Contains("Getting Users"))).Repeat.Once(); Expect.Call(() => this.Logger.Info(Arg.Text.Contains("Got Users"))).Repeat.Once(); } using (this.Repository.Playback()) { var userApplicationService = new UserApplicationService( this.UserRepository, this.DbContextScopeFactory, this.Mapper, this.Logger); var output = await userApplicationService.GetAllUsers(); Assert.IsTrue(output.Users.Any()); Assert.AreEqual(usersOutput.Count, output.Users.Count); } }
static void Main(string[] args) { var repository = new InMemoryUserRepository(); var userService = new UserService(repository); var userApplicationService = new UserApplicationService(repository, userService); var id = "test-id"; var user = new User(new UserId(id), new UserName("test-user")); repository.Save(user); // ユーザ名変更だけを行うように var updateNameCommand = new UserUpdateCommand(id) { Name = "naruse" }; userApplicationService.Update(updateNameCommand); // メールアドレス変更だけを行うように var updateMailAddressCommand = new UserUpdateCommand(id) { MailAddress = "*****@*****.**" }; userApplicationService.Update(updateMailAddressCommand); }
public UserPresentationService( IMapper <AuthenticationInfo, AuthenticationViewModel> authenticationInfoToViewModelMapper, IMapper <UserInfo, UserViewModel> userInfoToViewModelMapper, UserApplicationService userApplicationService) { _authenticationInfoToViewModelMapper = authenticationInfoToViewModelMapper; _userInfoToViewModelMapper = userInfoToViewModelMapper; _userApplicationService = userApplicationService; }
public void CancelAccountActivationFailedBecasueNoSuchAccountExists_MakesSureTHisDoesntCreateAnyBreach_VerifiesByExpectingException() { IUserRepository userRepository = new MockUserRepository(); ISecurityKeysRepository securityKeysRepository = new MockSecurityKeysRepository(); IPasswordEncryptionService passwordEncryptionService = new PasswordEncryptionService(); IIdentityAccessPersistenceRepository persistenceRepository = new MockPersistenceRepository(false); UserApplicationService userApplicationService = new UserApplicationService(userRepository, securityKeysRepository, passwordEncryptionService, persistenceRepository, new MockEmailService(), new PasswordCodeGenerationService()); userApplicationService.CancelAccountActivation(new CancelActivationCommand("123ffdsdsaewr43212")); }
public void TestRegister() { var repository = new InMemoryUserRepository(); var app = new UserApplicationService(repository); app.RegisterUser("ttaro", "taro", "tanaka"); var user = repository.Find(new UserName("ttaro")); Assert.IsNotNull(user); Assert.IsFalse(user.Id.Value == "1"); }
public IActionResult Post(string email, string name) { var service = new UserApplicationService(_userRepository); var result = service.Create(email, name); if (result) { return(Ok()); } else { return(BadRequest()); } }
public ActionResult Index(string u, string p) { UserApplicationService = new UserApplicationService(); bool isValid = UserApplicationService.ValidateUser(u, p); if (isValid) { return(View("~/Views/Home/Opciones.cshtml")); } else { ViewBag.Error = "Usuario o contraseña incorrecto."; return(View("~/Views/Home/Index.cshtml")); } }
public ActionResult Register(string u, string p) { UserApplicationService = new UserApplicationService(); long userId = UserApplicationService.CreateUser(u, p); if (userId > 0) { return(View("~/Views/Home/Opciones.cshtml")); } else { ViewBag.Error = "Usuario no pudo ser creado."; return(View("~/Views/Home/Register.cshtml")); } }
public void Initialize() { // Configuration Parameters var eventDatabaseConnectionString = "Data Source=localhost;Initial Catalog=eventway-sample-db;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"; var projectionMetadataDatabaseConnectionString = eventDatabaseConnectionString; var cosmosDbEndpoint = "https://localhost:8081"; // This is the default endpoint for local emulator-instances of the Cosmos DB var cosmosDbAuthKey = "<REPLACE WITH YOUR COSMOS DB AUTH KEY>"; var cosmosDbDatabaseId = "eventway-sample-db"; var cosmosDbCollectionId = "projections"; var offerThroughput = 10000; var noOfPartitions = 1000; // Event Repository var eventRepository = new SqlServerEventRepository(eventDatabaseConnectionString); // Projection Metadata Repository var projectionMetadataRepository = new SqlServerProjectionMetadataRepository(projectionMetadataDatabaseConnectionString); // Query Model Repository var queryModelRepository = new DocumentDbQueryModelRepository(cosmosDbDatabaseId, cosmosDbCollectionId, offerThroughput, noOfPartitions, cosmosDbEndpoint, cosmosDbAuthKey); queryModelRepository.Initialize(); // Event Listener var eventListener = new BasicEventListener(); // Aggregate services var aggregateFactory = new DefaultAggregateFactory(); var aggregateRepository = new AggregateRepository(eventRepository, aggregateFactory); var aggregateStore = new AggregateStore(aggregateRepository, eventListener); // PROJECTIONS UserProjection = new UserProjection( eventRepository, eventListener, queryModelRepository, projectionMetadataRepository); // APPLICATION SERVICES UserApplicationService = new UserApplicationService( aggregateStore, queryModelRepository); // Start listening for events UserProjection.Listen(); }
public void Initialize() { // Configuration Parameters var eventDatabaseConnectionString = "Data Source=localhost;Initial Catalog=eventway;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"; var projectionMetadataDatabaseConnectionString = eventDatabaseConnectionString; var cosmosDbEndpoint = "https://localhost:8081"; // This is the default endpoint for local emulator-instances of the Cosmos DB var cosmosDbAuthKey = "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=="; var cosmosDbDatabaseId = "eventway"; var cosmosDbCollectionId = "projections"; var offerThroughput = 10000; var noOfPartitions = 1000; // Event Repository var eventRepository = new SqlServerEventRepository(eventDatabaseConnectionString); // Projection Metadata Repository var projectionMetadataRepository = new SqlServerProjectionMetadataRepository(projectionMetadataDatabaseConnectionString); // Query Model Repository var queryModelRepository = new CosmosDbQueryModelRepository(cosmosDbDatabaseId, cosmosDbCollectionId, offerThroughput, noOfPartitions, cosmosDbEndpoint, cosmosDbAuthKey); queryModelRepository.Initialize(); // Event Listener var eventListener = new BasicEventListener(); // Aggregate services var aggregateFactory = new DefaultAggregateFactory(); var aggregateRepository = new AggregateRepository(eventRepository, aggregateFactory); var aggregateStore = new AggregateStore(aggregateRepository, eventListener); // PROJECTIONS UserProjection = new UserProjection( eventRepository, eventListener, queryModelRepository, projectionMetadataRepository); // APPLICATION SERVICES UserApplicationService = new UserApplicationService( aggregateStore, queryModelRepository); // Start listening for events UserProjection.Listen(); }
public async Task IShouldCanCreateOrUpdateAUserAddress() { string email = "*****@*****.**"; var user = new User { Email = email, Id = "jkl34lk435-klj2342" }; var viewModel = new CreateOrEditAddressViewModel { City = "SP" }; var address = new Address { City = "SP" }; var mockForDomainService = new Mock <IUserService>(); mockForDomainService.Setup(service => service.GetUserByEmail(It.IsAny <string>())) .ReturnsAsync(user) .Verifiable(); mockForDomainService.Setup(service => service.CreateOrEditAddress(It.IsAny <User>(), It.IsAny <Address>())) .Returns(user) .Verifiable(); var mockForMapper = new Mock <IMapper>(); mockForMapper.Setup(m => m.Map <Address>(It.IsAny <CreateOrEditAddressViewModel>())) .Returns(address) .Verifiable(); mockForMapper.Setup(m => m.Map <CreateOrEditAddressViewModel>(It.IsAny <Address>())) .Returns(viewModel) .Verifiable(); var service = new UserApplicationService(mockForMapper.Object, mockForDomainService.Object); var result = await service.CreateOrEditAddress(email, viewModel); Assert.AreEqual(viewModel, result); mockForDomainService.VerifyAll(); mockForMapper.VerifyAll(); }
public void TestSuccessMinUserName_8_15() { var userRepository = new InMemoryUserRepository(); var userService = new UserService(userRepository); var userApplicationService = new UserApplicationService(userRepository, userService); // 사용자명의 최소 길이(3글자)를 만족하는 사용자 등록이 정상적으로 완료되는지 확인 var userName = "******"; var minUserNameInputData = new UserRegisterCommand(userName); userApplicationService.Register(minUserNameInputData); // 사용자 정보가 잘 저장됐는지 확인 var createdUser = userRepository.Store.Values .FirstOrDefault(user => user.Name.Value == userName); Assert.IsNotNull(createdUser); }
public void TestSuccessMaxUserName() { var userRepository = new InMemoryUserRepository(); var userService = new UserService(userRepository); var userApplicationService = new UserApplicationService(userRepository, userService); // 사용자명의 최장 길이(20글자)를 만족하는 사용자 등록이 정상적으로 완료되는지 확인 var userName = "******"; var maxUserNameInputData = new UserRegisterCommand(userName); userApplicationService.Register(maxUserNameInputData); // 사용자 정보가 잘 저장됐는지 확인 var createdUserName = new UserName(userName); var maxUserNameUser = userRepository.Find(createdUserName); Assert.IsNotNull(maxUserNameUser); }
public void TestSuccessMaxUserName() { var userRepository = new InMemoryUserRepository(); var userService = new UserService(userRepository); var userApplicationService = new UserApplicationService(userRepository, userService); // 最長のユーザ名(20文字)のユーザが正常に生成できるか var userName = "******"; var maxUserNameInputData = new UserRegisterCommand(userName); userApplicationService.Register(maxUserNameInputData); // ユーザが正しく保存されているか var createdUserName = new UserName(userName); var maxUserNameUser = userRepository.Find(createdUserName); Assert.IsNotNull(maxUserNameUser); }
public void TestSuccessMinUserName_8_15() { var userRepository = new InMemoryUserRepository(); var userService = new UserService(userRepository); var userApplicationService = new UserApplicationService(userRepository, userService); // 最短のユーザ名(3文字)のユーザが正常に生成できるか var userName = "******"; var minUserNameInputData = new UserRegisterCommand(userName); userApplicationService.Register(minUserNameInputData); // ユーザが正しく保存されているか var createdUser = userRepository.Store.Values .FirstOrDefault(user => user.Name.Value == userName); Assert.IsNotNull(createdUser); }
public void TestUserIsAtomic() { var factory = new UserFactory(); var throwedException = false; try { Parallel.For(0, 2, _ => { var context = new BottomUpDddDbContext(); context.Database.AutoTransactionsEnabled = false; var repository = new EFUserRepository(context); var app = new UserApplicationService(factory, repository); app.RegisterUser("ataro", "taro", "tanaka"); }); } catch (AggregateException e) { throwedException = true; } Assert.IsTrue(throwedException); }
public void TestInvalidUserNameLengthMax() { var userRepository = new InMemoryUserRepository(); var userService = new UserService(userRepository); var userApplicationService = new UserApplicationService(userRepository, userService); bool exceptionOccured = false; try { var command = new UserRegisterCommand("123456789012345678901"); userApplicationService.Register(command); } catch { exceptionOccured = true; } Assert.IsTrue(exceptionOccured); }
public void TestSuccessMinUserName() { var userFactory = new InMemoryUserFactory(); var userRepository = new InMemoryUserRepository(); var userService = new UserService(userRepository); var userApplicationService = new UserApplicationService(userFactory, userRepository, userService); // 사용자명의 최소 길이(3글자)를 만족하는 사용자 등록이 정상적으로 완료되는지 확인 var userName = "******"; var minUserNameInputData = new UserRegisterCommand(userName); var outputData = userApplicationService.Register(minUserNameInputData); Assert.IsNotNull(outputData.CreatedUserId); // 사용자 정보가 잘 저장됐는지 확인 var createdUserName = new UserName(userName); var createdUser = userRepository.Find(createdUserName); Assert.IsNotNull(createdUser); }
public void TestDuplicateFail() { var repository = new InMemoryUserRepository(); var username = new UserName("ttaro"); var fullname = new FullName("taro", "tanaka"); repository.Save(new User(username, fullname)); var app = new UserApplicationService(repository); bool isOk = false; try { app.RegisterUser("ttaro", "taro", "tanaka"); } catch (Exception e) { if (e.Message.StartsWith("重複")) { isOk = true; } } Assert.IsTrue(isOk); }
public void TestSuccessMinUserName() { var userFactory = new InMemoryUserFactory(); var userRepository = new InMemoryUserRepository(); var userService = new UserService(userRepository); var userApplicationService = new UserApplicationService(userFactory, userRepository, userService); // 最短のユーザ名(3文字)のユーザが正常に生成できるか var userName = "******"; var minUserNameInputData = new UserRegisterCommand(userName); var outputData = userApplicationService.Register(minUserNameInputData); Assert.IsNotNull(outputData.CreatedUserId); // ユーザが正しく保存されているか var createdUserName = new UserName(userName); var createdUser = userRepository.Find(createdUserName); Assert.IsNotNull(createdUser); }
public async Task Run() { // Create sample application command var registerUser = new Application.Commands.RegisterUser(firstName: "Donald", lastName: "Duck"); // Invoke sample application service var userId = await UserApplicationService.RegisterUser(registerUser); // Wait one second for the Read model to be updated. // This is much, much more than usually needed. Thread.Sleep(1000); // Get the query model UserQueryModel queryModel = await UserProjection.QueryById(userId); Console.WriteLine($"Query models Display Name: {queryModel.DisplayName}"); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); }
public async Task IShouldCanCreateAUser() { var userToCreate = new User { Id = "asdf798asdfas-asjkdhrjkwer8", Email = "*****@*****.**" }; var viewModel = new SignupViewModel { Email = "*****@*****.**" }; var viewModelResult = new SignupViewModel { Email = "*****@*****.**" }; var mockForDomainService = new Mock <IUserService>(); mockForDomainService.Setup(service => service.CreateUser(It.IsAny <User>(), It.IsAny <string>())) .ReturnsAsync(userToCreate) .Verifiable(); var mockForMapper = new Mock <IMapper>(); mockForMapper.Setup(m => m.Map <User>(It.IsAny <SignupViewModel>())) .Returns(userToCreate) .Verifiable(); mockForMapper.Setup(m => m.Map <SignupViewModel>(It.IsAny <User>())) .Returns(viewModelResult) .Verifiable(); var service = new UserApplicationService(mockForMapper.Object, mockForDomainService.Object); var result = await service.CreateUser(viewModel); Assert.AreEqual(viewModelResult, result); mockForDomainService.VerifyAll(); mockForMapper.VerifyAll(); }
public async Task CreateAsync_ShouldExecuteCreateMethod_WhenInboundDtoHasCollectionAtributes() { //arrange var applicationDTO = new UserApplicationModel { FirstName = "Андрій", SecondName = "Слижук", AverageMark = 200, PhoneNumber = 0661234567, Regions = new List <RegionModel> { new RegionModel { Name = "Схід" }, new RegionModel { Name = "Захід" } }, ProfessionalDirections = new List <ProfessionalDirectionModel> { new ProfessionalDirectionModel { Name = "Програмування" }, new ProfessionalDirectionModel { Name = "Медицина" }, new ProfessionalDirectionModel { Name = "Фінанси" } } }; _uowMock.Setup(e => e.RegionRepository.GetByAsync(It.IsAny <Expression <Func <Region, bool> > >()).Result); _uowMock.Setup(e => e.ProfessionalDirectionRepository.GetByAsync(It.IsAny <Expression <Func <ProfessionalDirection, bool> > >()).Result); _uowMock.Setup(e => e.UserApplicationRepository.CreateAsync(It.IsAny <UserApplication>())); //Act _sut = new UserApplicationService(_uowMock.Object, UTestHelper.CreateMapper()); await _sut.CreateAsync(applicationDTO); //Assert _uowMock.Verify(m => m.UserApplicationRepository.CreateAsync(It.IsAny <UserApplication>()), Times.Once); }
public void CancelAccountActivationFailedDueToBlankActivationKey_MakesSureAccountActivationDoesNotGetCancelledWhenBlankActivationKeyIsGiven_VerifiesByExpectingException() { IUserRepository userRepository = new MockUserRepository(); ISecurityKeysRepository securityKeysRepository = new MockSecurityKeysRepository(); IPasswordEncryptionService passwordEncryptionService = new PasswordEncryptionService(); IIdentityAccessPersistenceRepository persistenceRepository = new MockPersistenceRepository(false); UserApplicationService userApplicationService = new UserApplicationService(userRepository, securityKeysRepository, passwordEncryptionService, persistenceRepository, new MockEmailService(), new PasswordCodeGenerationService()); string activationKey = "123456789"; string username = "******"; string password = "******"; User user = new User("*****@*****.**", username, passwordEncryptionService.EncryptPassword(password), "USA", TimeZone.CurrentTimeZone, "", activationKey); user.AddTierStatus(Status.NonVerified, new Tier(TierLevelConstant.Tier0, TierLevelConstant.Tier0)); // We need to encrypt the password in the test case ourselves, as we are not registering the user through // the proper service here (userRepository as MockUserRepository).AddUser(user); userApplicationService.CancelAccountActivation(new CancelActivationCommand("")); }
static void Main(string[] args) { string usersFilePath = null; var options = new OptionSet { {"i|input:", "Path to file that contains names and SIDs of users to be imported.", value => usersFilePath = value} }; try { options.Parse(args); if (usersFilePath != null) { var watch = Stopwatch.StartNew(); var identity = WindowsIdentity.GetCurrent(); Log.Info("Importing {0} at {1} as {2}.", usersFilePath, XmlConvert.ToString(DateTime.Now, XmlDateTimeSerializationMode.Local), identity != null ? identity.Name : "<unknown>"); using (var connection = EventStoreConnection.Create()) { connection.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1113)); using (var file = File.OpenText(usersFilePath)) { string row; while ((row = file.ReadLine()) != null) { Record record; if (Record.TryParse(row, out record)) { var unitOfWork = new UnitOfWork(); IRepository<User> userRepository = new Repository<User>(User.Factory, unitOfWork, connection); IRepository<Role> roleRepository = new Repository<Role>(Role.Factory, unitOfWork, connection); var service = new UserApplicationService(userRepository, roleRepository); var command = record.ToCommand(); Console.WriteLine("Start handling command: {0} - {1}", command.GetType().Name, command.Identifier); service.Handle(command); if (unitOfWork.HasChanges()) { const int sliceEventCount = 500; var aggregate = unitOfWork.GetChanges().Single(); var eventIndex = 0; var slices = from eventData in aggregate.Root. GetChanges(). Select(change => new EventData( Guid.NewGuid(), change.GetType().AssemblyQualifiedName, false, SerializeEvent(change), new byte[0])) group eventData by eventIndex++%sliceEventCount into slice select slice.AsEnumerable(); using (var transaction = connection.StartTransaction( aggregate.Identifier, aggregate.ExpectedVersion)) { foreach (var slice in slices) { transaction.Write(slice); } transaction.Commit(); Console.WriteLine("Committed events for command"); } } } else { Log.Error("Could not import the following row. Please make sure it's well formed: {0}", row); } } } } Log.Info("Completed import at {0} (took {1}ms).", XmlConvert.ToString(DateTime.Now, XmlDateTimeSerializationMode.Local), watch.ElapsedMilliseconds); } else { options.WriteOptionDescriptions(Console.Out); } } catch (OptionException exception) { Console.WriteLine(exception.Message); } }