public void AddUserToGroup_DoesNotCallCRUD_AddUserToGroup_WhenCalled_IfUserIsAlreadyInTheGroup() { //Arrange int TestUserID = 1; int TestAccessGroupID = 1; User TestUser = new User { UserID = TestUserID }; UserAccessGroup TestAccessGroup = new UserAccessGroup { UserAccessGroupID = TestAccessGroupID, Users = new List <User> { TestUser } }; List <UserAccessGroup> TestAccessGroups = new List <UserAccessGroup> { TestAccessGroup }; Mock <ICRUD_Operations> MockCRUD = new Mock <ICRUD_Operations>(); MockCRUD.Setup(x => x.GetAllAccessGroups()).Returns(TestAccessGroups); UserManagementService UserMgmtService = new UserManagementService(MockCRUD.Object); //Act UserMgmtService.AddUserToGroup(TestUserID, TestAccessGroupID); //Assert MockCRUD.Verify(x => x.AddUserToGroup(It.IsAny <int>(), It.IsAny <int>()), Times.Never()); }
public AccountController(SignInManager <ApplicationUser> signInManager, UserManagementService userService, UserManager <ApplicationUser> userManager, LdapService ldapService) { _signInManager = signInManager; _userService = userService; _userManager = userManager; _ldapService = ldapService; }
public void DeleteUser_Calls_RemoveUserFromGroup_ExactlyTwice_WhenCalled_IfUserIsInTwoAccessGroups() { //Arrange int TestUserID = 1; User TestUser = new User { UserID = TestUserID, AccessGroups = new List <UserAccessGroup>() }; UserAccessGroup TestGroup = new UserAccessGroup { UserAccessGroupID = 1 }; UserAccessGroup TestGroup2 = new UserAccessGroup { UserAccessGroupID = 2 }; TestUser.AccessGroups.Add(TestGroup); TestUser.AccessGroups.Add(TestGroup2); Mock <ICRUD_Operations> MockCRUD = new Mock <ICRUD_Operations>(); MockCRUD.Setup(x => x.GetAllUsers()).Returns(new List <User> { TestUser }); UserManagementService UserMgmtService = new UserManagementService(MockCRUD.Object); //Act UserMgmtService.DeleteUser(TestUserID); //Assert MockCRUD.Verify(x => x.RemoveUserFromGroup(It.IsAny <int>(), It.IsAny <int>()), Times.Exactly(2)); }
public void AddUserToGroup_CallsGetAllAccessGroups_ExactlyOnce_WhenCalled() { //Arrange int TestUserID = 1; int TestAccessGroupID = 1; User TestUser = new User { UserID = TestUserID }; UserAccessGroup TestAccessGroup = new UserAccessGroup { UserAccessGroupID = TestAccessGroupID, Users = new List <User> { TestUser } }; List <UserAccessGroup> TestAccessGroups = new List <UserAccessGroup> { TestAccessGroup }; Mock <ICRUD_Operations> MockCRUD = new Mock <ICRUD_Operations>(); MockCRUD.Setup(x => x.GetAllAccessGroups()).Returns(TestAccessGroups); UserManagementService UserMgmtService = new UserManagementService(MockCRUD.Object); //Act UserMgmtService.AddUserToGroup(TestUserID, TestAccessGroupID); //Assert MockCRUD.Verify(x => x.GetAllAccessGroups(), Times.Once); }
public IHttpActionResult DisableUser([FromBody] UserManagementDTO obj) { // Filter if no username was passed if (obj.UserName == null || !ModelState.IsValid) { return(Content(HttpStatusCode.BadRequest, "Failure: Bad Request")); } // Pass input through business rules to see if a valid username was passed RegInfoValidator validator = new RegInfoValidator(); if (!validator.ValidateUserName(obj.UserName)) { return(Content(HttpStatusCode.BadRequest, "Failure: No valid data.")); } // Implement the actual status change of that user UserManagementService service = new UserManagementService(); var response = service.DisableUser(obj); if (!response.IsSuccessful) { return(Content(HttpStatusCode.BadRequest, response.Messages)); } // Everything was successful, returning message return(Content(HttpStatusCode.OK, "Success: Account was disabled for " + obj.UserName)); }
public void UserCreation_UserAlreadyExists_Fail() { var user = new UserAccount { Username = "******", IsActive = true, IsFirstTimeUser = false, RoleType = "standard" }; var claims = new List <Claim>() { new Claim("User", "*****@*****.**") }; var expected = false; var actual = false; using (_userGateway = new UserGateway()) { UserManagementService _userManagementService = new UserManagementService(_userGateway); // Act actual = _userManagementService.CreateUser(user, claims).Data; } //Assert Assert.AreEqual(expected, actual); }
public async Task GetUserAsync_UserExists_ReturnsUser() { using (var dbContext = TestHelpers.CreateDbContext()) using (var userManager = TestHelpers.CreateUserManager(dbContext)) using (var roleManager = TestHelpers.CreateRoleManager(dbContext)) { // Arrange var userManagementService = new UserManagementService(dbContext, userManager, roleManager); var testUsers = TestHelpers.GetTestUsers(); ApplicationUser user1 = testUsers[0]; await userManager.CreateAsync(user1, ACCEPTABLE_PASSWORD); var claims = new[] { new Claim(ClaimTypes.NameIdentifier, user1.Id) }; var identity = new ClaimsIdentity(claims, "Test"); var principal = new ClaimsPrincipal(identity); // Act var actualUser = await userManagementService.GetUserAsync(principal); // Assert actualUser.Should().BeEquivalentTo(user1); } }
public static void UserInfo() { UserManagementService service = new UserManagementService(); UserInfoVm user = service.UserInfo(1); Console.WriteLine($"{user.Adress}\n{user.Email}\n{user.FirstName}\n{user.LastName}\n{user.PositionId}"); }
public async Task UpdateUserAsync_EmailUnique_UpdatesUserProperties() { using (var dbContext = TestHelpers.CreateDbContext()) using (var userManager = TestHelpers.CreateUserManager(dbContext)) using (var roleManager = TestHelpers.CreateRoleManager(dbContext)) { // Arrange var userManagementService = new UserManagementService(dbContext, userManager, roleManager); const string ROLE_NAME = "administrator"; var testRole = new IdentityRole(ROLE_NAME); await roleManager.CreateAsync(testRole); var testUsers = TestHelpers.GetTestUsers(); ApplicationUser user1 = testUsers[0]; await userManager.CreateAsync(user1, ACCEPTABLE_PASSWORD); await userManager.AddToRoleAsync(user1, ROLE_NAME); user1.FirstName = "ADifferentFirstName"; user1.LastName = "ADifferentFirstName"; user1.Email = "*****@*****.**"; user1.UserName = "******"; // Act await userManagementService.UpdateUserAsync(user1, ROLE_NAME, user1.RowVersion); var actualUser = await dbContext.Users.AsNoTracking() // Retrieve fresh entity rather than through the Change Tracker .FirstOrDefaultAsync(user => user.Id == user1.Id); // Assert actualUser.Should().BeEquivalentTo(user1); } }
public async Task UpdateUserAsync_EmailUnique_UpdatesUserRole() { using (var dbContext = TestHelpers.CreateDbContext()) using (var userManager = TestHelpers.CreateUserManager(dbContext)) using (var roleManager = TestHelpers.CreateRoleManager(dbContext)) { // Arrange var userManagementService = new UserManagementService(dbContext, userManager, roleManager); const string ROLE_NAME1 = "administrator"; const string ROLE_NAME2 = "supervisor"; await roleManager.CreateAsync(new IdentityRole(ROLE_NAME1)); await roleManager.CreateAsync(new IdentityRole(ROLE_NAME2)); var testUsers = TestHelpers.GetTestUsers(); ApplicationUser user1 = testUsers[0]; await userManager.CreateAsync(user1, ACCEPTABLE_PASSWORD); await userManager.AddToRoleAsync(user1, ROLE_NAME1); // Act await userManagementService.UpdateUserAsync(user1, ROLE_NAME2, user1.RowVersion); // Assert Assert.True(await userManager.IsInRoleAsync(user1, ROLE_NAME2) && !await userManager.IsInRoleAsync(user1, ROLE_NAME1)); } }
public async Task UpdateUserAsync_EmailExists_ReturnsError() { using (var dbContext = TestHelpers.CreateDbContext()) using (var userManager = TestHelpers.CreateUserManager(dbContext)) using (var roleManager = TestHelpers.CreateRoleManager(dbContext)) { // Arrange var userManagementService = new UserManagementService(dbContext, userManager, roleManager); const string ROLE_NAME = "administrator"; const string NEW_EMAIL = "*****@*****.**"; var testRole = new IdentityRole(ROLE_NAME); await roleManager.CreateAsync(testRole); var testUsers = TestHelpers.GetTestUsers(); ApplicationUser user1 = testUsers[0]; await userManager.CreateAsync(user1, ACCEPTABLE_PASSWORD); await userManager.AddToRoleAsync(user1, ROLE_NAME); ApplicationUser user2 = testUsers[1]; await userManager.CreateAsync(user2, ACCEPTABLE_PASSWORD); await userManager.AddToRoleAsync(user2, ROLE_NAME); user2.Email = NEW_EMAIL; // Act var identityResult = await userManagementService.UpdateUserAsync(user2, ROLE_NAME, user2.RowVersion); // Assert Assert.False(identityResult.Succeeded); } }
public async Task GetUserRoleAsync_UserWithEmailAndRole_ReturnsRole() { using (var dbContext = TestHelpers.CreateDbContext()) using (var userManager = TestHelpers.CreateUserManager(dbContext)) using (var roleManager = TestHelpers.CreateRoleManager(dbContext)) { // Arrange var userManagementService = new UserManagementService(dbContext, userManager, roleManager); const string ROLE_NAME = "administrator"; var testRole = new IdentityRole(ROLE_NAME); await roleManager.CreateAsync(testRole); var testUsers = TestHelpers.GetTestUsers(); ApplicationUser user = testUsers[0]; await userManager.CreateAsync(user, ACCEPTABLE_PASSWORD); await userManager.AddToRoleAsync(user, ROLE_NAME); // Act string actualRoleName = await userManagementService.GetUserRoleAsync(user.Email); // Assert Assert.Equal(ROLE_NAME, actualRoleName); } }
public async Task GetUserRoleAsync_UserWithIdAndRole_ReturnsRole(string roleName, string expectedString, bool returnName) { using (var dbContext = TestHelpers.CreateDbContext()) using (var userManager = TestHelpers.CreateUserManager(dbContext)) using (var roleManager = TestHelpers.CreateRoleManager(dbContext)) { // Arrange var userManagementService = new UserManagementService(dbContext, userManager, roleManager); var testRole = new IdentityRole(roleName); await roleManager.CreateAsync(testRole); var testUsers = TestHelpers.GetTestUsers(); ApplicationUser user = testUsers[0]; await userManager.CreateAsync(user, ACCEPTABLE_PASSWORD); await userManager.AddToRoleAsync(user, roleName); // Act string actualString = await userManagementService.GetUserRoleAsync(user.Id, returnName); // Assert Assert.Equal(expectedString, actualString); } }
public void GetAllUsers() { UserManagementService ums = new UserManagementService(); Result <List <UsersList> > result = ums.GetAllUsers(); Console.WriteLine(result.message); }
/// <summary> /// Constructor /// </summary> /// <param name="commitData">Commit data</param> /// <param name="userManagementService">User management service</param> /// <param name="localizationService">Localization service</param> public RaidCommitDialogElement(LocalizationService localizationService, UserManagementService userManagementService, RaidCommitContainer commitData) : base(localizationService) { _localizationService = localizationService; _userManagementService = userManagementService; _commitData = commitData; }
public EndpointsController(ApplicationDbContext context, StateService stateService, UserManagementService userService, AggregateNotificationService notifier) { _context = context; _stateService = stateService; _userService = userService; _notifier = notifier; }
protected void btn_AddUser_Click(object sender, EventArgs e) { if (txtPassword.Text == txtRePassword.Text && txtPassword.Text != null) { UserBo.Username = txtUsername.Text; UserBo.NameEng = txtNameEng.Text; UserBo.NameNep = txtNameNep.Text; UserBo.Password = txtPassword.Text; UserBo.Office = Convert.ToInt32(ddlOffice.SelectedValue); UserBo.Role = ddlRole.SelectedValue; UserBo.UserType = Convert.ToInt32(ddlUserType.SelectedValue); UserBo.Mobile = txtMobile.Text; UserBo.Email = txtEmail.Text; UserBo.Organizarion = null; UserBo.EnableDisable = (chkIsEnable.Checked) ? 1 : 0; UserBo.RequestStatus = null; UserBo.RequestedBy = 0; if (Session["id"] != null && Session["id"].ToInt32() > 0) { UserBo.UserId = Session["id"].ToInt32(); UserBo.IsLocked = 0; objServiceUser = new UserManagementService(); objServiceUser.AuthSoapHdValue = ServiceAuth.ServiceAuthenticationUser(); int i = objServiceUser.UpdateUserById(UserBo); if (i > 0) { Response.Write("<script>alert('User Details Updated Successfully!');</script>"); Response.Redirect(Constants.ConstantAppPath + "/Modules/UserManagement/UsersList.aspx"); } else { //not inserted Response.Write("<script>alert('User Details Update Failed!');</script>"); } } else { objServiceUser = new UserManagementService(); objServiceUser.AuthSoapHdValue = ServiceAuth.ServiceAuthenticationUser(); int i = objServiceUser.InsertUser(UserBo); if (i > 0) { Response.Write("<script>alert('User Added Successfully!');</script>"); Response.Redirect(Constants.ConstantAppPath + "/Modules/UserManagement/UsersList.aspx"); } else { //not inserted Response.Write("<script>alert('User Addition Failed');</script>"); } } } else { //password mismatch Response.Write("<script>alert('Password Mismatched');</script>"); } }
/// <summary> /// Constructor /// </summary> /// <param name="localizationService">Localization service</param> /// <param name="userManagementService">User management service</param> /// <param name="messageBuilder">Message builder</param> public RaidCommitService(LocalizationService localizationService, UserManagementService userManagementService, RaidMessageBuilder messageBuilder) : base(localizationService) { _localizationService = localizationService; _userManagementService = userManagementService; _messageBuilder = messageBuilder; }
private void loadUserDetails(string id) { objServiceUser = new UserManagementService(); objServiceUser.AuthSoapHdValue = ServiceAuth.ServiceAuthenticationUser(); DataTable dtud = objServiceUser.FetchUserDetailsById(id); if (dtud != null && dtud.Rows.Count > 0) { txtUsername.Text = dtud.Rows[0]["LOGIN_ID"].ToString(); txtNameEng.Text = dtud.Rows[0]["USER_ENG_NAME"].ToString(); txtNameNep.Text = dtud.Rows[0]["USER_NEP_NAME"].ToString(); //txtPassword.Text = dtud.Rows[0][""].ToString(); ddlOffice.SelectedValue = dtud.Rows[0]["OFFICE_ID"].ToString(); ddlRole.SelectedValue = dtud.Rows[0]["ROLE_ID"].ToString(); ddlUserType.SelectedValue = dtud.Rows[0]["TYPE_ID"].ToString(); txtMobile.Text = dtud.Rows[0]["MOBILE_NO"].ToString(); txtEmail.Text = dtud.Rows[0]["EMAIL_ID"].ToString(); if (dtud.Rows[0]["enable_disable"].ToString() == "1") { chkIsEnable.Checked = true; } else { chkIsEnable.Checked = false; } } }
public void GetUserClaims_UserExists_Pass() { string username = "******"; List <ClaimDTO> expected = new List <ClaimDTO> { new ClaimDTO("User", "*****@*****.**"), new ClaimDTO("Action", "DisabledAction"), new ClaimDTO("Action", "CreateOtherUser"), new ClaimDTO("Action", "Logout"), new ClaimDTO("Parent", "*****@*****.**") }; List <ClaimDTO> actual = null; using (_userGateway = new UserGateway()) { UserManagementService _userManagementService = new UserManagementService(_userGateway); // Act actual = _userManagementService.GetAllUserClaims(username).Data; } //Assert foreach (ClaimDTO claim in expected) { CollectionAssert.Contains(actual, claim); } }
public void Should_Return_True_When_User_Is_Authenticated() { // Given: string username = "******"; // And: string password = "******"; // And: var userRepository = new Mock <IUserRepository>(); // And: userRepository .Setup(r => r.GetUser(It.IsAny <User>())) .Returns(new User()); // And: UserManagementService sut = new UserManagementService(userRepository.Object); // When: bool isLoggedIn = sut.Login(username, password); // Then: Assert.Equal(true, isLoggedIn); }
public void UserDeletion_UserExists_Pass() { var user = new UserAccount { Username = "******", Id = new Guid("88888888-4444-3333-2222-111111111111"), IsActive = true, IsFirstTimeUser = false, RoleType = "standard" }; var expected = true; var actual = false; using (_userGateway = new UserGateway()) { UserManagementService _userManagementService = new UserManagementService(_userGateway); // Act actual = _userManagementService.DeleteUser(user).Data; } //Assert Assert.AreEqual(expected, actual); }
public void Should_Throw_Exception_When_User_Is_Not_Authenticated() { // Given: string username = "******"; // And: string password = "******"; // And: var userRepository = new Mock <IUserRepository>(); // And: userRepository .Setup(r => r.GetUser(It.IsAny <User>())) .Returns(() => null); // And: UserManagementService sut = new UserManagementService(userRepository.Object); // When: Action action = () => sut.Login(username, password); // Then: Assert.Throws <Exception>(action); }
public void DeleteUser_Calls_RemoveUserFromGroup_ExactlyOnce_WhenCalled_IfUserIsInOneAccessGroup_PassingInTheCorrectIDs() { //Arrange int TestUserID = 1; User TestUser = new User { UserID = TestUserID, AccessGroups = new List <UserAccessGroup>() }; UserAccessGroup TestGroup = new UserAccessGroup { UserAccessGroupID = 1 }; TestUser.AccessGroups.Add(TestGroup); Mock <ICRUD_Operations> MockCRUD = new Mock <ICRUD_Operations>(); MockCRUD.Setup(x => x.GetAllUsers()).Returns(new List <User> { TestUser }); UserManagementService UserMgmtService = new UserManagementService(MockCRUD.Object); //Act UserMgmtService.DeleteUser(TestUserID); //Assert MockCRUD.Verify(x => x.RemoveUserFromGroup(TestUser.UserID, TestGroup.UserAccessGroupID), Times.Once); }
public void DeactivateUser() { UserManagementService ums = new UserManagementService(); Result <OlescUser> result = ums.Deactivate("*****@*****.**", "The Master"); Console.WriteLine(result.message); }
public void AddUser_ReturnsFalse_WhenCalled_IfEmailProvidedBelongsToAUserOnTheSystem() { //Arrange string TestFirstName = "Joe"; string TestLastName = "Bloggs"; string TestEmail = "*****@*****.**"; string TestPassword = "******"; bool expected = false; User TestUser = new User { Email = TestEmail }; List <User> TestUsers = new List <User> { TestUser }; Mock <ICRUD_Operations> MockCRUD = new Mock <ICRUD_Operations>(); MockCRUD.Setup(x => x.GetAllUsers()).Returns(TestUsers); UserManagementService UserMgmtService = new UserManagementService(MockCRUD.Object); //Act bool actual = UserMgmtService.AddUser(TestFirstName, TestLastName, TestEmail, TestPassword); //Assert Assert.AreEqual(expected, actual); }
public void ResetPassword() { UserManagementService ums = new UserManagementService(); Result <OlescUser> result = ums.ResetPassword("*****@*****.**"); Console.WriteLine(result.message); }
public void AddUserToGroup_CallsCRUD_AddUserToGroup_PassingTheCorrectIDs_ExactlyOnce_WhenCalled_IfUserIsNotAlreadyInTheGroup() { //Arrange int TestUserID = 1; int TestAccessGroupID = 1; User TestUser = new User { UserID = 2 }; UserAccessGroup TestAccessGroup = new UserAccessGroup { UserAccessGroupID = TestAccessGroupID, Users = new List <User> { TestUser } }; List <UserAccessGroup> TestAccessGroups = new List <UserAccessGroup> { TestAccessGroup }; Mock <ICRUD_Operations> MockCRUD = new Mock <ICRUD_Operations>(); MockCRUD.Setup(x => x.GetAllAccessGroups()).Returns(TestAccessGroups); MockCRUD.Setup(x => x.AddUserToGroup(It.IsAny <int>(), It.IsAny <int>())).Verifiable(); UserManagementService UserMgmtService = new UserManagementService(MockCRUD.Object); //Act UserMgmtService.AddUserToGroup(TestUserID, TestAccessGroupID); //Assert MockCRUD.Verify(x => x.AddUserToGroup(TestUserID, TestAccessGroupID), Times.Once); }
public void DeAssignRole() { UserManagementService ums = new UserManagementService(); Result <object> result = ums.DeAssignRole("*****@*****.**", 1); Console.WriteLine(result.message); }
public static int createUserPosition() { UserManagementService service = new UserManagementService(); //service.CreateUserPosition("Director"); return(service.CreateUserPosition("Director")); }
public IAuthenticationProvider BuildAuthenticationProvider(IPublisher mainQueue, IBus mainBus, IPublisher workersQueue, InMemoryBus[] workerBusses) { var passwordHashAlgorithm = new Rfc2898PasswordHashAlgorithm(); var dispatcher = new IODispatcher(mainQueue, new PublishEnvelope(workersQueue, crossThread: true)); foreach (var bus in workerBusses) { bus.Subscribe(dispatcher.ForwardReader); bus.Subscribe(dispatcher.BackwardReader); bus.Subscribe(dispatcher.Writer); bus.Subscribe(dispatcher.StreamDeleter); bus.Subscribe(dispatcher); } // USER MANAGEMENT var ioDispatcher = new IODispatcher(mainQueue, new PublishEnvelope(mainQueue)); mainBus.Subscribe(ioDispatcher.BackwardReader); mainBus.Subscribe(ioDispatcher.ForwardReader); mainBus.Subscribe(ioDispatcher.Writer); mainBus.Subscribe(ioDispatcher.StreamDeleter); mainBus.Subscribe(ioDispatcher); var userManagement = new UserManagementService(mainQueue, ioDispatcher, passwordHashAlgorithm, skipInitializeStandardUsersCheck: false); mainBus.Subscribe<UserManagementMessage.Create>(userManagement); mainBus.Subscribe<UserManagementMessage.Update>(userManagement); mainBus.Subscribe<UserManagementMessage.Enable>(userManagement); mainBus.Subscribe<UserManagementMessage.Disable>(userManagement); mainBus.Subscribe<UserManagementMessage.Delete>(userManagement); mainBus.Subscribe<UserManagementMessage.ResetPassword>(userManagement); mainBus.Subscribe<UserManagementMessage.ChangePassword>(userManagement); mainBus.Subscribe<UserManagementMessage.Get>(userManagement); mainBus.Subscribe<UserManagementMessage.GetAll>(userManagement); mainBus.Subscribe<SystemMessage.BecomeMaster>(userManagement); return new InternalAuthenticationProvider(dispatcher, passwordHashAlgorithm, ESConsts.CachedPrincipalCount); }
public SingleVNode(TFChunkDb db, SingleVNodeSettings vNodeSettings, bool dbVerifyHashes, int memTableEntryCount, params ISubsystem[] subsystems) { Ensure.NotNull(db, "db"); Ensure.NotNull(vNodeSettings, "vNodeSettings"); _settings = vNodeSettings; _mainBus = new InMemoryBus("MainBus"); _controller = new SingleVNodeController(_mainBus, _settings.ExternalHttpEndPoint, db, this); _mainQueue = new QueuedHandler(_controller, "MainQueue"); _controller.SetMainQueue(_mainQueue); _subsystems = subsystems; // MONITORING var monitoringInnerBus = new InMemoryBus("MonitoringInnerBus", watchSlowMsg: false); var monitoringRequestBus = new InMemoryBus("MonitoringRequestBus", watchSlowMsg: false); var monitoringQueue = new QueuedHandlerThreadPool(monitoringInnerBus, "MonitoringQueue", true, TimeSpan.FromMilliseconds(100)); var monitoring = new MonitoringService(monitoringQueue, monitoringRequestBus, _mainQueue, db.Config.WriterCheckpoint, db.Config.Path, vNodeSettings.StatsPeriod, _settings.ExternalHttpEndPoint, vNodeSettings.StatsStorage); _mainBus.Subscribe(monitoringQueue.WidenFrom<SystemMessage.SystemInit, Message>()); _mainBus.Subscribe(monitoringQueue.WidenFrom<SystemMessage.StateChangeMessage, Message>()); _mainBus.Subscribe(monitoringQueue.WidenFrom<SystemMessage.BecomeShuttingDown, Message>()); _mainBus.Subscribe(monitoringQueue.WidenFrom<SystemMessage.BecomeShutdown, Message>()); _mainBus.Subscribe(monitoringQueue.WidenFrom<ClientMessage.WriteEventsCompleted, Message>()); monitoringInnerBus.Subscribe<SystemMessage.SystemInit>(monitoring); monitoringInnerBus.Subscribe<SystemMessage.StateChangeMessage>(monitoring); monitoringInnerBus.Subscribe<SystemMessage.BecomeShuttingDown>(monitoring); monitoringInnerBus.Subscribe<SystemMessage.BecomeShutdown>(monitoring); monitoringInnerBus.Subscribe<ClientMessage.WriteEventsCompleted>(monitoring); monitoringInnerBus.Subscribe<MonitoringMessage.GetFreshStats>(monitoring); var truncPos = db.Config.TruncateCheckpoint.Read(); if (truncPos != -1) { Log.Info("Truncate checkpoint is present. Truncate: {0} (0x{0:X}), Writer: {1} (0x{1:X}), Chaser: {2} (0x{2:X}), Epoch: {3} (0x{3:X})", truncPos, db.Config.WriterCheckpoint.Read(), db.Config.ChaserCheckpoint.Read(), db.Config.EpochCheckpoint.Read()); var truncator = new TFChunkDbTruncator(db.Config); truncator.TruncateDb(truncPos); } db.Open(dbVerifyHashes); // STORAGE SUBSYSTEM var indexPath = Path.Combine(db.Config.Path, "index"); var readerPool = new ObjectPool<ITransactionFileReader>( "ReadIndex readers pool", ESConsts.PTableInitialReaderCount, ESConsts.PTableMaxReaderCount, () => new TFChunkReader(db, db.Config.WriterCheckpoint)); var tableIndex = new TableIndex(indexPath, () => new HashListMemTable(maxSize: memTableEntryCount * 2), () => new TFReaderLease(readerPool), maxSizeForMemory: memTableEntryCount, maxTablesPerLevel: 2, inMem: db.Config.InMemDb); var hasher = new XXHashUnsafe(); var readIndex = new ReadIndex(_mainQueue, readerPool, tableIndex, hasher, ESConsts.StreamInfoCacheCapacity, Application.IsDefined(Application.AdditionalCommitChecks), Application.IsDefined(Application.InfiniteMetastreams) ? int.MaxValue : 1); var writer = new TFChunkWriter(db); var epochManager = new EpochManager(ESConsts.CachedEpochCount, db.Config.EpochCheckpoint, writer, initialReaderCount: 1, maxReaderCount: 5, readerFactory: () => new TFChunkReader(db, db.Config.WriterCheckpoint)); epochManager.Init(); var storageWriter = new StorageWriterService(_mainQueue, _mainBus, _settings.MinFlushDelay, db, writer, readIndex.IndexWriter, epochManager); // subscribes internally monitoringRequestBus.Subscribe<MonitoringMessage.InternalStatsRequest>(storageWriter); var storageReader = new StorageReaderService(_mainQueue, _mainBus, readIndex, ESConsts.StorageReaderThreadCount, db.Config.WriterCheckpoint); _mainBus.Subscribe<SystemMessage.SystemInit>(storageReader); _mainBus.Subscribe<SystemMessage.BecomeShuttingDown>(storageReader); _mainBus.Subscribe<SystemMessage.BecomeShutdown>(storageReader); monitoringRequestBus.Subscribe<MonitoringMessage.InternalStatsRequest>(storageReader); var chaser = new TFChunkChaser(db, db.Config.WriterCheckpoint, db.Config.ChaserCheckpoint); var storageChaser = new StorageChaser(_mainQueue, db.Config.WriterCheckpoint, chaser, readIndex.IndexCommitter, epochManager); _mainBus.Subscribe<SystemMessage.SystemInit>(storageChaser); _mainBus.Subscribe<SystemMessage.SystemStart>(storageChaser); _mainBus.Subscribe<SystemMessage.BecomeShuttingDown>(storageChaser); var storageScavenger = new StorageScavenger(db, tableIndex, hasher, readIndex, Application.IsDefined(Application.AlwaysKeepScavenged), mergeChunks: false /*!Application.IsDefined(Application.DisableMergeChunks)*/); // ReSharper disable RedundantTypeArgumentsOfMethod _mainBus.Subscribe<ClientMessage.ScavengeDatabase>(storageScavenger); // ReSharper restore RedundantTypeArgumentsOfMethod // MISC WORKERS _workerBuses = Enumerable.Range(0, vNodeSettings.WorkerThreads).Select(queueNum => new InMemoryBus(string.Format("Worker #{0} Bus", queueNum + 1), watchSlowMsg: true, slowMsgThreshold: TimeSpan.FromMilliseconds(200))).ToArray(); _workersHandler = new MultiQueuedHandler( vNodeSettings.WorkerThreads, queueNum => new QueuedHandlerThreadPool(_workerBuses[queueNum], string.Format("Worker #{0}", queueNum + 1), groupName: "Workers", watchSlowMsg: true, slowMsgThreshold: TimeSpan.FromMilliseconds(200))); // AUTHENTICATION INFRASTRUCTURE var passwordHashAlgorithm = new Rfc2898PasswordHashAlgorithm(); var dispatcher = new IODispatcher(_mainQueue, new PublishEnvelope(_workersHandler, crossThread: true)); var internalAuthenticationProvider = new InternalAuthenticationProvider(dispatcher, passwordHashAlgorithm, ESConsts.CachedPrincipalCount); var passwordChangeNotificationReader = new PasswordChangeNotificationReader(_mainQueue, dispatcher); _mainBus.Subscribe<SystemMessage.SystemStart>(passwordChangeNotificationReader); _mainBus.Subscribe<SystemMessage.BecomeShutdown>(passwordChangeNotificationReader); _mainBus.Subscribe(internalAuthenticationProvider); SubscribeWorkers(bus => { bus.Subscribe(dispatcher.ForwardReader); bus.Subscribe(dispatcher.BackwardReader); bus.Subscribe(dispatcher.Writer); bus.Subscribe(dispatcher.StreamDeleter); bus.Subscribe(dispatcher); }); // TCP { var tcpService = new TcpService(_mainQueue, _settings.ExternalTcpEndPoint, _workersHandler, TcpServiceType.External, TcpSecurityType.Normal, new ClientTcpDispatcher(), ESConsts.ExternalHeartbeatInterval, ESConsts.ExternalHeartbeatTimeout, internalAuthenticationProvider, null); _mainBus.Subscribe<SystemMessage.SystemInit>(tcpService); _mainBus.Subscribe<SystemMessage.SystemStart>(tcpService); _mainBus.Subscribe<SystemMessage.BecomeShuttingDown>(tcpService); } // SECURE TCP if (vNodeSettings.ExternalSecureTcpEndPoint != null) { var secureTcpService = new TcpService(_mainQueue, _settings.ExternalSecureTcpEndPoint, _workersHandler, TcpServiceType.External, TcpSecurityType.Secure, new ClientTcpDispatcher(), ESConsts.ExternalHeartbeatInterval, ESConsts.ExternalHeartbeatTimeout, internalAuthenticationProvider, _settings.Certificate); _mainBus.Subscribe<SystemMessage.SystemInit>(secureTcpService); _mainBus.Subscribe<SystemMessage.SystemStart>(secureTcpService); _mainBus.Subscribe<SystemMessage.BecomeShuttingDown>(secureTcpService); } SubscribeWorkers(bus => { var tcpSendService = new TcpSendService(); // ReSharper disable RedundantTypeArgumentsOfMethod bus.Subscribe<TcpMessage.TcpSend>(tcpSendService); // ReSharper restore RedundantTypeArgumentsOfMethod }); // HTTP var httpAuthenticationProviders = new List<HttpAuthenticationProvider> { new BasicHttpAuthenticationProvider(internalAuthenticationProvider), }; if (_settings.EnableTrustedAuth) httpAuthenticationProviders.Add(new TrustedHttpAuthenticationProvider()); httpAuthenticationProviders.Add(new AnonymousHttpAuthenticationProvider()); var httpPipe = new HttpMessagePipe(); var httpSendService = new HttpSendService(httpPipe, forwardRequests: false); _mainBus.Subscribe<SystemMessage.StateChangeMessage>(httpSendService); _mainBus.Subscribe(new WideningHandler<HttpMessage.SendOverHttp, Message>(_workersHandler)); SubscribeWorkers(bus => { bus.Subscribe<HttpMessage.HttpSend>(httpSendService); bus.Subscribe<HttpMessage.HttpSendPart>(httpSendService); bus.Subscribe<HttpMessage.HttpBeginSend>(httpSendService); bus.Subscribe<HttpMessage.HttpEndSend>(httpSendService); bus.Subscribe<HttpMessage.SendOverHttp>(httpSendService); }); _httpService = new HttpService(ServiceAccessibility.Public, _mainQueue, new TrieUriRouter(), _workersHandler, vNodeSettings.HttpPrefixes); _httpService.SetupController(new AdminController(_mainQueue)); _httpService.SetupController(new PingController()); _httpService.SetupController(new StatController(monitoringQueue, _workersHandler)); _httpService.SetupController(new AtomController(httpSendService, _mainQueue, _workersHandler)); _httpService.SetupController(new GuidController(_mainQueue)); _httpService.SetupController(new UsersController(httpSendService, _mainQueue, _workersHandler)); _mainBus.Subscribe<SystemMessage.SystemInit>(_httpService); _mainBus.Subscribe<SystemMessage.BecomeShuttingDown>(_httpService); _mainBus.Subscribe<HttpMessage.PurgeTimedOutRequests>(_httpService); SubscribeWorkers(bus => { HttpService.CreateAndSubscribePipeline(bus, httpAuthenticationProviders.ToArray()); }); // REQUEST MANAGEMENT var requestManagement = new RequestManagementService(_mainQueue, 1, 1, vNodeSettings.PrepareTimeout, vNodeSettings.CommitTimeout); _mainBus.Subscribe<SystemMessage.SystemInit>(requestManagement); _mainBus.Subscribe<ClientMessage.WriteEvents>(requestManagement); _mainBus.Subscribe<ClientMessage.TransactionStart>(requestManagement); _mainBus.Subscribe<ClientMessage.TransactionWrite>(requestManagement); _mainBus.Subscribe<ClientMessage.TransactionCommit>(requestManagement); _mainBus.Subscribe<ClientMessage.DeleteStream>(requestManagement); _mainBus.Subscribe<StorageMessage.RequestCompleted>(requestManagement); _mainBus.Subscribe<StorageMessage.CheckStreamAccessCompleted>(requestManagement); _mainBus.Subscribe<StorageMessage.AlreadyCommitted>(requestManagement); _mainBus.Subscribe<StorageMessage.CommitAck>(requestManagement); _mainBus.Subscribe<StorageMessage.PrepareAck>(requestManagement); _mainBus.Subscribe<StorageMessage.WrongExpectedVersion>(requestManagement); _mainBus.Subscribe<StorageMessage.InvalidTransaction>(requestManagement); _mainBus.Subscribe<StorageMessage.StreamDeleted>(requestManagement); _mainBus.Subscribe<StorageMessage.RequestManagerTimerTick>(requestManagement); // SUBSCRIPTIONS var subscrBus = new InMemoryBus("SubscriptionsBus", true, TimeSpan.FromMilliseconds(50)); var subscrQueue = new QueuedHandlerThreadPool(subscrBus, "Subscriptions", false); _mainBus.Subscribe(subscrQueue.WidenFrom<SystemMessage.SystemStart, Message>()); _mainBus.Subscribe(subscrQueue.WidenFrom<SystemMessage.BecomeShuttingDown, Message>()); _mainBus.Subscribe(subscrQueue.WidenFrom<TcpMessage.ConnectionClosed, Message>()); _mainBus.Subscribe(subscrQueue.WidenFrom<ClientMessage.SubscribeToStream, Message>()); _mainBus.Subscribe(subscrQueue.WidenFrom<ClientMessage.UnsubscribeFromStream, Message>()); _mainBus.Subscribe(subscrQueue.WidenFrom<SubscriptionMessage.PollStream, Message>()); _mainBus.Subscribe(subscrQueue.WidenFrom<SubscriptionMessage.CheckPollTimeout, Message>()); _mainBus.Subscribe(subscrQueue.WidenFrom<StorageMessage.EventCommited, Message>()); var subscription = new SubscriptionsService(_mainQueue, subscrQueue, readIndex); subscrBus.Subscribe<SystemMessage.SystemStart>(subscription); subscrBus.Subscribe<SystemMessage.BecomeShuttingDown>(subscription); subscrBus.Subscribe<TcpMessage.ConnectionClosed>(subscription); subscrBus.Subscribe<ClientMessage.SubscribeToStream>(subscription); subscrBus.Subscribe<ClientMessage.UnsubscribeFromStream>(subscription); subscrBus.Subscribe<SubscriptionMessage.PollStream>(subscription); subscrBus.Subscribe<SubscriptionMessage.CheckPollTimeout>(subscription); subscrBus.Subscribe<StorageMessage.EventCommited>(subscription); // USER MANAGEMENT var ioDispatcher = new IODispatcher(_mainQueue, new PublishEnvelope(_mainQueue)); _mainBus.Subscribe(ioDispatcher.BackwardReader); _mainBus.Subscribe(ioDispatcher.ForwardReader); _mainBus.Subscribe(ioDispatcher.Writer); _mainBus.Subscribe(ioDispatcher.StreamDeleter); _mainBus.Subscribe(ioDispatcher); var userManagement = new UserManagementService( _mainQueue, ioDispatcher, passwordHashAlgorithm, vNodeSettings.SkipInitializeStandardUsersCheck); _mainBus.Subscribe<UserManagementMessage.Create>(userManagement); _mainBus.Subscribe<UserManagementMessage.Update>(userManagement); _mainBus.Subscribe<UserManagementMessage.Enable>(userManagement); _mainBus.Subscribe<UserManagementMessage.Disable>(userManagement); _mainBus.Subscribe<UserManagementMessage.Delete>(userManagement); _mainBus.Subscribe<UserManagementMessage.ResetPassword>(userManagement); _mainBus.Subscribe<UserManagementMessage.ChangePassword>(userManagement); _mainBus.Subscribe<UserManagementMessage.Get>(userManagement); _mainBus.Subscribe<UserManagementMessage.GetAll>(userManagement); _mainBus.Subscribe<SystemMessage.BecomeMaster>(userManagement); // TIMER _timeProvider = new RealTimeProvider(); _timerService = new TimerService(new ThreadBasedScheduler(_timeProvider)); _mainBus.Subscribe<SystemMessage.BecomeShutdown>(_timerService); _mainBus.Subscribe<TimerMessage.Schedule>(_timerService); _workersHandler.Start(); _mainQueue.Start(); monitoringQueue.Start(); subscrQueue.Start(); if (subsystems != null) foreach (var subsystem in subsystems) subsystem.Register(db, _mainQueue, _mainBus, _timerService, _timeProvider, httpSendService, new[]{_httpService}, _workersHandler); }