public static void ReCreateRegistryAccounts(string path) { RegisteredUsers Registry = new RegisteredUsers(); Account toetag = new Account() { Email = "*****@*****.**", Administrator = true }; toetag.SetName("Toetag"); toetag.SetPassword("toetag"); Registry.List.Add(toetag); Account haystack = new Account() { Email = "*****@*****.**", Administrator = true }; haystack.SetName("Haystack"); haystack.SetPassword("haystack"); Registry.List.Add(haystack); Account bucky = new Account() { Email = "*****@*****.**", Administrator = false }; bucky.SetName("Bucky"); bucky.SetPassword("bucky"); Registry.List.Add(bucky); XML.ObjectToXml(Registry, path); }
private bool CheckIfUserDeletedOrModified(User user) { List <User> remoteUsers = ServerSystemController.GetRegisteredUsers(); List <User> filteredListed = remoteUsers.Where(p => p.Id == user.Id).ToList(); if (filteredListed.Count > 0) { User userInList = filteredListed[0]; if (userInList.NickName != user.NickName) { User userInServer = RegisteredUsers.FirstOrDefault(x => x.Value.NickName.Equals(user.NickName)).Value; TcpClient clientInServer = RegisteredUsers.FirstOrDefault(x => x.Value.NickName.Equals(user.NickName)).Key; RegisteredUsers.Remove(clientInServer); userInServer.NickName = userInList.NickName; RegisteredUsers.Add(clientInServer, userInServer); showRegisteredPlayers(); showConnectedPlayers(); } return(true); } else { return(false); } }
async void RegButton_Clicked(object sender, EventArgs e) { if ((string.IsNullOrWhiteSpace(userNameValue.Text)) || (string.IsNullOrEmpty(userNameValue.Text)) || (string.IsNullOrWhiteSpace(PasswordValue.Text)) || (string.IsNullOrEmpty(PasswordValue.Text)) || (string.IsNullOrWhiteSpace(EmailValue.Text)) || (string.IsNullOrEmpty(EmailValue.Text)) || (string.IsNullOrWhiteSpace(PhoneNumberValue.Text)) || (string.IsNullOrEmpty(PhoneNumberValue.Text)) ) { await DisplayAlert("Enter Data", "Enter Valid Data", "OK"); } else { var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "UserDatabase.db"); var db = new SQLiteConnection(dbpath); db.CreateTable <RegisteredUsers>(); var user_det = new RegisteredUsers() { Username = userNameValue.Text, Password = PasswordValue.Text, EmailId = EmailValue.Text, PhoneNumber = PhoneNumberValue.Text }; db.Insert(user_det); Device.BeginInvokeOnMainThread(async() => { var res = await this.DisplayAlert("Congrats", "User Details Registered Successfully", "Yes", "Cancel"); if (res) { await Navigation.PushAsync(new LoginPage()); } }); } }
public ActionResult UsersFiltering([FromForm] RegisteredUsers users) { var model = new List <RegisteredUsers>(); model = _saveData.UsersFiltering(users.NameORMobilOREmail); return(PartialView("_UsersList", model)); }
public RegisteredUserInfo GetRegisteredUserInfo(long accountId) { RegisteredUserInfo info = null; RegisteredUsers.TryGetValue(accountId, out info); return(info); }
public void RegisterUser() { GitLabWrapper gitLabWrapper = new GitLabWrapper(TestCredentials.GitServer, TestCredentials.GitLabToken); DXVcsWrapper vcsWrapper = new DXVcsWrapper(TestCredentials.VcsServer); RegisteredUsers users = new RegisteredUsers(gitLabWrapper, vcsWrapper); var user = users.GetUser("Barakhov"); }
public void can_apply_name_changes() { //given var user1 = new UserRegistered(Guid.NewGuid(), "Mike", "smith", "*****@*****.**"); var user2 = new UserRegistered(Guid.NewGuid(), "Robert", "Jones", "*****@*****.**"); var user3 = new UserRegistered(Guid.NewGuid(), "Ben", "smith", "*****@*****.**"); var nameChange = new NameChanged(user2.UserId, "John", "Doe"); var usersRM = new RegisteredUsers(() => null, null); //when usersRM.Apply(user1); usersRM.Apply(user2); usersRM.Apply(user3); usersRM.Apply(nameChange); //then var displayNames = usersRM.Current; Assert.Collection( displayNames, displayName => { Assert.Equal(user1.UserId, displayName.UserId); Assert.Equal($"{user1.LastName}, {user1.FirstName}", displayName.DisplayName); }, displayName => { Assert.Equal(user2.UserId, displayName.UserId); Assert.Equal($"{nameChange.LastName}, {nameChange.FirstName}", displayName.DisplayName); }, displayName => { Assert.Equal(user3.UserId, displayName.UserId); Assert.Equal($"{user3.LastName}, {user3.FirstName}", displayName.DisplayName); }); }
public ActionResult Save(RegisteredUsers registeredUser) { if (!ModelState.IsValid) { var viewModel = new NewUserViewModel { RegisteredUser = registeredUser, Biographies = _context.Biographies.ToList() }; return(View("UserForm", viewModel)); } if (registeredUser.Id == 0) { _context.RegisteredUsers.Add(registeredUser); } else { var registeredUserInDb = _context.RegisteredUsers.Single(c => c.Id == registeredUser.Id); registeredUserInDb.Name = registeredUser.Name; registeredUserInDb.Birthdate = registeredUser.Birthdate; registeredUserInDb.Gender = registeredUser.Gender; registeredUserInDb.Email = registeredUser.Email; registeredUserInDb.Address = registeredUser.Address; registeredUserInDb.Postcode = registeredUser.Postcode; registeredUserInDb.Phonenumber = registeredUser.Phonenumber; registeredUserInDb.BiographyId = registeredUser.BiographyId; } _context.SaveChanges(); return(RedirectToAction("Index", "User")); }
public Registration() { InitializeComponent(); //hide nav bar NavigationPage.SetHasNavigationBar(this, false); BindingContext = new RegisteredUsers(); }
public static void ConfigureApp(RegistrationApp app, string eventNamespace, string eventAssembly) { var settings = ConnectionSettings.Create() .SetDefaultUserCredentials(new UserCredentials("admin", "changeit")) .KeepReconnecting() .KeepRetrying() //.UseConsoleLogger() .Build(); var conn = EventStoreConnection.Create(settings, new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1113)); conn.ConnectAsync().Wait(); var repo = new SimpleRepo(conn, eventNamespace, eventAssembly); var userRm = new RegisteredUsers(() => conn, repo.Deserialize); var mainBus = new SimpleBus(); var userSvc = new UserSvc(repo); mainBus.Subscribe <RegisterUser>(userSvc); mainBus.Subscribe <ChangeName>(userSvc); //application wire up //app.CommandPublisher = mainBus; //userRm.Subscribe(app.DisplayUsers); //start userRm.Start(); }
/// public IInteractionHandler <T> CreateInteractionHandler(Update interaction, Action <T> configureContext) { int senderUserId = interaction.GetOwner().Id; var session = SessionDispatcher[senderUserId]; if (session == null) { var regInfo = RegisteredUsers.FirstOrDefault(registered => registered.Id == senderUserId); if (regInfo != null) //user registered but session not oppened yet { session = SessionDispatcher.StartSession(interaction.GetOwner().ToRegisteredUser(regInfo)); } else { //start registration procedure place it in RouteInteraction with check if session is null } } var context = new T(); context.Session = session; context.User = session.User; context.Interaction = interaction; context.Connection = Connection; configureContext(context); return(InteractionRouter.RouteInteraction(context)); }
private async void signin(RegisteredUsers user) { var claims = new List <Claim> { new Claim(ClaimTypes.Name, user.UserName), new Claim(ClaimTypes.Role, user.MemberType.ToString()), }; var claimsIdentity = new ClaimsIdentity( claims, CookieAuthenticationDefaults.AuthenticationScheme); var authProperties = new AuthenticationProperties { }; await HttpContext.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties); HttpContext.Session.SetInt32("userId", user.id); //return Redirect("/items/index"); /* moved this to check another kind of auth * var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); * var authproperties = new AuthenticationProperties { /* ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(10)* / }; * // var userPrincipal = new ClaimsPrincipal(new[] { claimsIdentity }); * await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authproperties); * // HttpContext.Session.SetString("Logged", "5"); * // RedirectToAction( "item","Items"); */ }
public async Task <IActionResult> Edit(int id, [Bind("id,UserName,Email,Password,MemberType")] RegisteredUsers registeredUsers) { if (id != registeredUsers.id) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(registeredUsers); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!RegisteredUsersExists(registeredUsers.id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(registeredUsers)); }
/// <summary> /// Register /// The client sends a request to register themselves /// with a username and password. If they are already registered /// the CustomValidation tries to validate their credentials /// </summary> /// <param name="username">(string) user name</param> /// <param name="password">(string) password</param> /// <returns>(boolean) if successful, false otherwise</returns> public bool Register(string username, string password) { // Registration Success Flag bool registered = false; // Obtain callback for the client IServiceCallback callback = OperationContext.Current.GetCallbackChannel <IServiceCallback>(); // First Verify User Does Not Already Exist in Registration if (!(RegisteredUsers.Any(x => x.UserName == username))) { // User is Not Registered, Register User // Create new user User user = new User(username, password, callback); /// Add to Registered Users RegisteredUsers.Add(user); // Set Return Value registered = true; Console.WriteLine($"User {username} registered..."); } else { DuplicateUserFault fault = new DuplicateUserFault() { Reason = "User '" + username + "' already registered." }; throw new FaultException <DuplicateUserFault>(fault, fault.Reason); } return(registered); } // end of Register method
public async Task <IActionResult> OnGetAsync(string documentid) { if (String.IsNullOrEmpty(documentid)) { return(new NotFoundResult()); } ReferencedCalenderItem = await _calendarRepository.GetDocument(documentid); CalendarItemId = ReferencedCalenderItem.Id; if (ReferencedCalenderItem == null) { return(new NotFoundResult()); } if (ReferencedCalenderItem.Members != null) { RegisteredUsers.AddRange(ReferencedCalenderItem.Members); } if (ReferencedCalenderItem.RegistrationKeys != null) { RegistrationKeys.AddRange(ReferencedCalenderItem.RegistrationKeys); } Random randomGen = new Random(); NewRegistrationKey = new RegistrationKey { UniqueId = Guid.NewGuid().ToString(), Key = randomGen.Next(1000, 1000000).ToString() }; return(Page()); }
private bool ValidateRegisteredUser(RegisteredUsers user) { if (user.BirthDate > DateTime.Now) { return(false); } return(true); }
public IActionResult SubmitDummydetails([FromForm] IFormCollection form, [FromForm] RegisteredUsers dummyuser) { var model = new UsercardDetailelements(); var savedummyuserdata = _saveData.saveDummyuserdetails(dummyuser); // return RedirectToAction("CardsPreview(dummyuser.Guid)"); model = _saveData.GetDummyuserdetails(dummyuser.Guid); return(View("CardsPreview", model)); }
public async System.Threading.Tasks.Task <int> PostAsync([FromForm] UserInformation user) { int departmentid = context.DepartmentInformation.Where(x => x.DepartmentName.Contains(user.DepartmentName)).FirstOrDefault().DepartmentId; int designationId = context.DesignationInformation.Where(x => x.Designation.Contains(user.Designation)).FirstOrDefault().DesignationId; int officeid = context.OfficeInformation.Where(x => x.OfficeName.Contains(user.Office)).FirstOrDefault().OfficeId; RegisteredUsers registeruser = new RegisteredUsers(); if (user.Profilepic != null) { using (var stream = new MemoryStream()) { await user.Profilepic.CopyToAsync(stream); registeruser.Profilepic = stream.ToArray(); } } else { registeruser.Profilepic = context.defaultImage.FirstOrDefault().image; } registeruser.EmployeeId = user.EmployeeId; registeruser.DisplayName = user.DisplayName; registeruser.EmployeeUsername = user.EmployeeUsername; registeruser.Email = user.Email; registeruser.DepartmentId = departmentid; registeruser.DesignationId = designationId; registeruser.OfficeId = officeid; registeruser.UserRegisteredOrNot = 1; registeruser.ReportingManagerUsername = user.ReportingManagerUsername; if (userPresentInRegistrationTableOrNot(user.ReportingManagerUsername) >= 1) { return(RegisterNewUser(registeruser)); } else { RegisteredUsers manager = new RegisteredUsers(); manager.EmployeeId = context.TempAd.Where(x => x.EmployeeUsername.Contains(user.ReportingManagerUsername)).FirstOrDefault().EmployeeId; // work on this//GetAD(user.ReportingManagerUsername).First().EmployeeId; manager.DisplayName = ""; manager.EmployeeUsername = user.ReportingManagerUsername; manager.UserRegisteredOrNot = 0; manager.Email = "null"; manager.OfficeId = 0; manager.DepartmentId = 0; manager.DesignationId = 0; manager.Profilepic = context.defaultImage.FirstOrDefault().image; manager.ReportingManagerUsername = "******"; context.RegisteredUsers.Add(manager); context.SaveChanges(); return(RegisterNewUser(registeruser)); } }
public async Task <IActionResult> Create([Bind("id,UserName,Email,Password,MemberType")] RegisteredUsers registeredUsers) { if (ModelState.IsValid) { _context.Add(registeredUsers); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(registeredUsers)); }
private Measurement GetMeasurement(App app, MeasurementType measurementType) { Measurement measurement = null; switch (measurementType) { case MeasurementType.RegisteredUsers: measurement = new RegisteredUsers(app, measurementType); break; case MeasurementType.TeamSize: measurement = new TeamSize(app, measurementType); break; case MeasurementType.DbSize: measurement = new DbSize(app, measurementType); break; case MeasurementType.XmlSize: measurement = new XmlSize(app, measurementType); break; case MeasurementType.Factor: measurement = new Factor(app, measurementType); break; case MeasurementType.TotalRows: measurement = new TotalRows(app, measurementType); break; case MeasurementType.MaxTableTotalRows: measurement = new MaxTableTotalRows(app, measurementType); break; case MeasurementType.S3FilesSize: measurement = new FilesS3Measurement(app, measurementType); break; case MeasurementType.S3HostingSize: measurement = new HostingS3Measurement(app, measurementType); break; case MeasurementType.S3NodeJsSize: measurement = new NodeJsS3Measurement(app, measurementType); break; default: break; } return(measurement); }
public ApplicationSettings(MessageQueue messageQueue, SystemEventQueue eventQueue) { InitializeDirectories(); SystemMessageQueue = messageQueue; SystemEventQueue = eventQueue; MapColors = new Dictionary<int, KnownColor>(); LoadColors(); Logins = new List<Connection>(); RegisteredUsers = new RegisteredUsers(); Players = new Players(); LoadRegistryAccounts(); }
public ApplicationSettings(MessageQueue messageQueue, SystemEventQueue eventQueue) { InitializeDirectories(); SystemMessageQueue = messageQueue; SystemEventQueue = eventQueue; MapColors = new Dictionary <int, KnownColor>(); LoadColors(); Logins = new List <Connection>(); RegisteredUsers = new RegisteredUsers(); Players = new Players(); LoadRegistryAccounts(); }
protected RegisteredUsers ConverToRegisteredUser(RegisteredUserModel model) { RegisteredUsers registeredUsers = new RegisteredUsers(); registeredUsers.UserName = model.UserName?.Trim(); registeredUsers.EmailAddress = model.EmailAddress?.Trim(); registeredUsers.Gender = model.Gender; registeredUsers.RegisterDate = model.RegisterDate; registeredUsers.AdditionalRequest = model.AdditionalRequest?.Trim(); return(registeredUsers); }
public PaletteViewModel() { //PieSeries this.FacebookStatistics = new ObservableCollection<PaletteModel>(); FacebookStatistics.Add(new PaletteModel { Country = "Finland", UsersCount = 12.68 }); FacebookStatistics.Add(new PaletteModel { Country = "Germany", UsersCount = 10.59 }); FacebookStatistics.Add(new PaletteModel { Country = "Poland", UsersCount = 11.16 }); FacebookStatistics.Add(new PaletteModel { Country = "France", UsersCount = 10.48 }); FacebookStatistics.Add(new PaletteModel { Country = "Australia", UsersCount = 10.13 }); FacebookStatistics.Add(new PaletteModel { Country = "Brazil", UsersCount = 7.99 }); if (AnalyticsInfo.VersionInfo.DeviceFamily != "Windows.Mobile") { FacebookStatistics.Add(new PaletteModel { Country = "Russia", UsersCount = 6.25 }); FacebookStatistics.Add(new PaletteModel { Country = "Israel", UsersCount = 10.50 }); } //Active User in Year of 2012,2014,2015 this.Users = new ObservableCollection<PaletteModel>(); Users.Add(new PaletteModel { SocialSite = "Facebook", Year2012 = 788, Year2014 = 1240, Year2015 = 1550 }); Users.Add(new PaletteModel { SocialSite = "QZone", Year2012 = 310, Year2014 = 632, Year2015 = 900 }); Users.Add(new PaletteModel { SocialSite = "Google+", Year2012 = 500, Year2014 = 743, Year2015 = 890 }); Users.Add(new PaletteModel { SocialSite = "Twitter", Year2012 = 250, Year2014 = 540, Year2015 = 784 }); Users.Add(new PaletteModel { SocialSite = "Skype", Year2012 = 120, Year2014 = 300, Year2015 = 520 }); Users.Add(new PaletteModel { SocialSite = "WeChat", Year2012 = 180, Year2014 = 390, Year2015 = 550 }); Users.Add(new PaletteModel { SocialSite = "Instagram", Year2012 = 120, Year2014 = 250, Year2015 = 850 }); Users.Add(new PaletteModel { SocialSite = "WhatsApp", Year2012 = 100, Year2014 = 300, Year2015 = 300 }); //Active Users this.ActiveUsers = new ObservableCollection<PaletteModel>(); ActiveUsers.Add(new PaletteModel { SocialSite = "Twitter", UsersCount = 302 }); ActiveUsers.Add(new PaletteModel { SocialSite = "Skype", UsersCount = 300 }); ActiveUsers.Add(new PaletteModel { SocialSite = "WeChat", UsersCount = 559 }); if (AnalyticsInfo.VersionInfo.DeviceFamily != "Windows.Mobile") { ActiveUsers.Add(new PaletteModel { SocialSite = "Google+", UsersCount = 650 }); ActiveUsers.Add(new PaletteModel { SocialSite = "WhatsApp", UsersCount = 800 }); } ActiveUsers.Add(new PaletteModel { SocialSite = "Facebook", UsersCount = 1184 }); // Registered users this.RegisteredUsers = new ObservableCollection<PaletteModel>(); RegisteredUsers.Add(new PaletteModel { SocialSite = "Twitter", UsersCount = 500 }); RegisteredUsers.Add(new PaletteModel { SocialSite = "Skype", UsersCount = 663 }); RegisteredUsers.Add(new PaletteModel { SocialSite = "WeChat", UsersCount = 1120 }); if (AnalyticsInfo.VersionInfo.DeviceFamily != "Windows.Mobile") { RegisteredUsers.Add(new PaletteModel { SocialSite = "Google+", UsersCount = 540 }); RegisteredUsers.Add(new PaletteModel { SocialSite = "WhatsApp", UsersCount = 920 }); } RegisteredUsers.Add(new PaletteModel { SocialSite = "Facebook", UsersCount = 1600 }); }
public Result UpdateUserLevel(RoomUser user) { var result = new Result(); var storedUser = RegisteredUsers.SingleOrDefault(u => u.OpenId == user.OpenId); if (storedUser != null) { storedUser.UserLevel = user.UserLevel; storedUser.Stars = user.Stars; result.Status = 200; result.Success = true; } return(result); }
public object Get(RegisteredUsers request) { var response = new { UserAuths = Db.Select <UserAuth>() }; //nulled out for security response.UserAuths.ForEach(x => x.PasswordHash = null); response.UserAuths.ForEach(x => x.Salt = null); response.UserAuths.ForEach(x => x.DigestHa1Hash = null); return(response); }
public void SearchRegisteredUser() { GitLabWrapper gitLabWrapper = new GitLabWrapper(TestCredentials.GitServer, TestCredentials.GitLabToken); DXVcsWrapper vcsWrapper = new DXVcsWrapper(TestCredentials.VcsServer); RegisteredUsers users = new RegisteredUsers(gitLabWrapper, vcsWrapper); var user = users.GetUser("litvinov"); Assert.IsNotNull(user); Assert.IsTrue(user.IsRegistered); var user2 = users.GetUser("Litvinov"); Assert.IsNotNull(user2); Assert.IsTrue(user2.IsRegistered); }
private void GoToPrevious() { int index = RegisteredUsers.IndexOf(SelectedUser); if (index == 0) { index = RegisteredUsers.Count - 1; } else { index--; } SelectedUser = RegisteredUsers[index]; }
private void GoToNext() { int index = RegisteredUsers.IndexOf(SelectedUser); if (index == (RegisteredUsers.Count - 1)) { index = 0; } else { index++; } SelectedUser = RegisteredUsers[index]; }
private void sendAuthorizatonData(string data, NetworkStream nws, TcpClient client, ref User user) { List <User> remoteUsers = ServerSystemController.GetRegisteredUsers(); byte[] responseStream; lock (registrationLock) { if (!remoteUsers.Contains(user)) { RegisteredUsers.Add(client, user); ServerSystemController.AddUserToSystem(user); showRegisteredPlayers(); showConnectedPlayers(); responseStream = Protocol.GenerateStream(ProtocolConstants.SendType.RESPONSE, ProtocolConstants.LOGIN, ProtocolConstants.OK_RESPONSE_CODE); } else { if (RegisteredUsers.ContainsValue(user)) { User userInServer = RegisteredUsers.FirstOrDefault(x => x.Value.NickName.Equals(data)).Value; TcpClient clientInServer = RegisteredUsers.FirstOrDefault(x => x.Value.NickName.Equals(data)).Key; if (userInServer.Connected) { responseStream = Protocol.GenerateStream(ProtocolConstants.SendType.RESPONSE, ProtocolConstants.LOGIN, "400"); } else { User userFromServer = ServerSystemController.GetUserInServer(user); RegisteredUsers.Remove(clientInServer); RegisteredUsers.Add(client, userFromServer); showRegisteredPlayers(); showConnectedPlayers(); responseStream = Protocol.GenerateStream(ProtocolConstants.SendType.RESPONSE, ProtocolConstants.LOGIN, ProtocolConstants.OK_RESPONSE_CODE); } } else { User userFromServer = ServerSystemController.GetUserInServer(user); RegisteredUsers.Add(client, userFromServer); showRegisteredPlayers(); showConnectedPlayers(); responseStream = Protocol.GenerateStream(ProtocolConstants.SendType.RESPONSE, ProtocolConstants.LOGIN, ProtocolConstants.OK_RESPONSE_CODE); } } nws.Write(responseStream, 0, responseStream.Length); } }
public bool UnRegisterUser(LoginUserInfo info) { if (RegisteredUsers.ContainsKey(info.AccountID)) { if (info.Status >= LoginStatus.在线) { KickUser(info.AccountID, 0, LogoutReason.系统踢出, null); } if (info.ParentGroup != null) { info.ParentGroup.RemoveUser(info.AccountID); } return(RegisteredUsers.Remove(info.AccountID)); } return(false); }
} // end of Greet Me /// <summary> /// Login /// Logs in a registered user. /// Throws faults (to client) if there are issues /// </summary> /// <param name="username">(string) username to login</param> /// <returns>(boolean) true if successful, false otherwise</returns> public bool Login(string username) { bool loggedin = false; // First Verify User Not Already Logged In if (!(LoggedInUsers.Any(x => x.UserName == username))) { // See if User is Registered if (RegisteredUsers.Any(x => x.UserName == username)) { // User is Already Authenticated Per Custom Validator LoggedInUsers.Add(RegisteredUsers.Find(x => x.UserName == username)); loggedin = true; Console.WriteLine($"User {username} logged in."); // Send message to callback SendMessageToUsers($"User {username} logged in."); } // User is Not Registered else { loggedin = false; // This will be sent to client as a generic fault throw new ArgumentException("User: "******" is not registered"); } } else { loggedin = false; // Send custom fault to client DuplicateUserFault fault = new DuplicateUserFault() { Reason = "User '" + username + "' already logged in!" }; throw new FaultException <DuplicateUserFault>(fault, fault.Reason); } return(loggedin); } // end of method
static int DoSyncWork(SyncOptions clo) { string localGitDir = clo.LocalFolder != null && Path.IsPathRooted(clo.LocalFolder) ? clo.LocalFolder : Path.Combine(Environment.CurrentDirectory, clo.LocalFolder ?? repoPath); EnsureGitDir(localGitDir); string gitRepoPath = clo.Repo; string username = clo.Login; string password = clo.Password; string gitlabauthtoken = clo.AuthToken; string branchName = clo.Branch; string trackerPath = clo.Tracker; string gitServer = clo.Server; DXVcsWrapper vcsWrapper = new DXVcsWrapper(vcsServer, username, password); TrackBranch branch = FindBranch(branchName, trackerPath, vcsWrapper); if (branch == null) return 1; string historyPath = GetVcsSyncHistory(vcsWrapper, branch.HistoryPath); if (historyPath == null) return 1; SyncHistory history = SyncHistory.Deserialize(historyPath); if (history == null) return 1; SyncHistoryWrapper syncHistory = new SyncHistoryWrapper(history, vcsWrapper, branch.HistoryPath, historyPath); var head = syncHistory.GetHistoryHead(); if (head == null) return 1; GitLabWrapper gitLabWrapper = new GitLabWrapper(gitServer, gitlabauthtoken); RegisteredUsers registeredUsers = new RegisteredUsers(gitLabWrapper, vcsWrapper); User defaultUser = registeredUsers.GetUser(username); if (!defaultUser.IsRegistered) { Log.Error($"default user {username} is not registered in the active directory."); return 1; } var checkMergeChangesResult = CheckChangesForMerging(gitLabWrapper, gitRepoPath, branchName, head, vcsWrapper, branch, syncHistory, defaultUser); if (checkMergeChangesResult == CheckMergeChangesResult.NoChanges) return 0; if (checkMergeChangesResult == CheckMergeChangesResult.Error) return 1; GitWrapper gitWrapper = CreateGitWrapper(gitRepoPath, localGitDir, branch.Name, username, password); if (gitWrapper == null) return 1; ProcessHistoryResult processHistoryResult = ProcessHistory(vcsWrapper, gitWrapper, registeredUsers, defaultUser, gitRepoPath, localGitDir, branch, clo.CommitsCount, syncHistory, true); if (processHistoryResult == ProcessHistoryResult.NotEnough) return 0; if (processHistoryResult == ProcessHistoryResult.Failed) return 1; int result = ProcessMergeRequests(vcsWrapper, gitWrapper, gitLabWrapper, registeredUsers, defaultUser, gitRepoPath, localGitDir, clo.Branch, clo.Tracker, syncHistory, username); if (result != 0) return result; return 0; }
static int ProcessMergeRequests(DXVcsWrapper vcsWrapper, GitWrapper gitWrapper, GitLabWrapper gitLabWrapper, RegisteredUsers users, User defaultUser, string gitRepoPath, string localGitDir, string branchName, string tracker, SyncHistoryWrapper syncHistory, string userName) { var project = gitLabWrapper.FindProject(gitRepoPath); TrackBranch branch = GetBranch(branchName, tracker, vcsWrapper); if (branch == null) { Log.Error($"Specified branch {branchName} not found in track file."); return 1; } var mergeRequests = GetMergeRequests(gitLabWrapper, branchName, userName, project); if (!mergeRequests.Any()) { Log.Message("Zero registered merge requests."); return 0; } int result = 0; foreach (var mergeRequest in mergeRequests) { var mergeRequestResult = ProcessMergeRequest(vcsWrapper, gitWrapper, gitLabWrapper, users, defaultUser, localGitDir, branch, mergeRequest, syncHistory); if (mergeRequestResult == MergeRequestResult.Failed) return 1; if (mergeRequestResult == MergeRequestResult.CheckoutFailed || mergeRequestResult == MergeRequestResult.Conflicts || mergeRequestResult == MergeRequestResult.InvalidState) result = 1; } return result; }
static void AssignBackConflictedMergeRequest(GitLabWrapper gitLabWrapper, RegisteredUsers users, MergeRequest mergeRequest, string comment) { User author = users.GetUser(mergeRequest.Author.Username); var mr = gitLabWrapper.UpdateMergeRequestAssignee(mergeRequest, author.UserName); gitLabWrapper.AddCommentToMergeRequest(mr, comment); }
static MergeRequestResult ProcessMergeRequest(DXVcsWrapper vcsWrapper, GitWrapper gitWrapper, GitLabWrapper gitLabWrapper, RegisteredUsers users, User defaultUser, string localGitDir, TrackBranch branch, MergeRequest mergeRequest, SyncHistoryWrapper syncHistory) { switch (mergeRequest.State) { case "reopened": case "opened": return ProcessOpenedMergeRequest(vcsWrapper, gitWrapper, gitLabWrapper, users, defaultUser, localGitDir, branch, mergeRequest, syncHistory); } return MergeRequestResult.InvalidState; }
static void ProcessHistoryInternal(DXVcsWrapper vcsWrapper, GitWrapper gitWrapper, RegisteredUsers users, User defaultUser, string localGitDir, TrackBranch branch, IList<CommitItem> commits, SyncHistoryWrapper syncHistory) { ProjectExtractor extractor = new ProjectExtractor(commits, (item) => { var localCommits = vcsWrapper.GetCommits(item.TimeStamp, item.Items).Where(x => !IsLabel(x)).ToList(); bool hasModifications = false; GitCommit last = null; string token = syncHistory.CreateNewToken(); foreach (var localCommit in localCommits) { string localProjectPath = Path.Combine(localGitDir, localCommit.Track.ProjectPath); DirectoryHelper.DeleteDirectory(localProjectPath); string trackPath = branch.GetTrackRoot(localCommit.Track); vcsWrapper.GetProject(vcsServer, trackPath, localProjectPath, item.TimeStamp); Log.Message($"git stage {localCommit.Track.ProjectPath}"); gitWrapper.Stage(localCommit.Track.ProjectPath); string author = CalcAuthor(localCommit, defaultUser); var comment = CalcComment(localCommit, author, token); User user = users.GetUser(author); try { gitWrapper.Commit(comment.ToString(), user, localCommit.TimeStamp, false); last = gitWrapper.FindCommit(x => true); hasModifications = true; } catch (Exception) { Log.Message($"Empty commit detected for {localCommit.Author} {localCommit.TimeStamp}."); } } if (hasModifications) { gitWrapper.PushEverything(); syncHistory.Add(last.Sha, item.TimeStamp.Ticks, token); } else { var head = syncHistory.GetHead(); syncHistory.Add(head.GitCommitSha, item.TimeStamp.Ticks, token); string author = CalcAuthor(item, defaultUser); Log.Message($"Push empty commits rejected for {author} {item.TimeStamp}."); } syncHistory.Save(); }); int i = 0; while (extractor.PerformExtraction()) Log.Message($"{++i} from {commits.Count} push to branch {branch.Name} completed."); }
static ProcessHistoryResult ProcessHistory(DXVcsWrapper vcsWrapper, GitWrapper gitWrapper, RegisteredUsers users, User defaultUser, string gitRepoPath, string localGitDir, TrackBranch branch, int commitsCount, SyncHistoryWrapper syncHistory, bool mergeCommits) { IList<CommitItem> commits = GenerateCommits(vcsWrapper, branch, syncHistory, mergeCommits); if (commits.Count > commitsCount) { Log.Message($"Commits generated. First {commitsCount} of {commits.Count} commits taken."); commits = commits.Take(commitsCount).ToList(); } else { Log.Message($"Commits generated. {commits.Count} commits taken."); } if (commits.Count > 0) ProcessHistoryInternal(vcsWrapper, gitWrapper, users, defaultUser, localGitDir, branch, commits, syncHistory); Log.Message($"Importing history from vcs completed."); return commits.Count > commitsCount ? ProcessHistoryResult.NotEnough : ProcessHistoryResult.Success; }
static MergeRequestResult ProcessOpenedMergeRequest(DXVcsWrapper vcsWrapper, GitWrapper gitWrapper, GitLabWrapper gitLabWrapper, RegisteredUsers users, User defaultUser, string localGitDir, TrackBranch branch, MergeRequest mergeRequest, SyncHistoryWrapper syncHistory) { string autoSyncToken = syncHistory.CreateNewToken(); var lastHistoryItem = syncHistory.GetHead(); Log.Message($"Start merging mergerequest {mergeRequest.Title}"); Log.ResetErrorsAccumulator(); var changes = gitLabWrapper.GetMergeRequestChanges(mergeRequest).ToList(); if (changes.Count >= MaxChangesCount) { Log.Error($"Merge request contains more than {MaxChangesCount} changes and cannot be processed. Split it into smaller merge requests"); AssignBackConflictedMergeRequest(gitLabWrapper, users, mergeRequest, CalcCommentForFailedCheckoutMergeRequest(null)); return MergeRequestResult.Failed; } var genericChange = changes .Where(x => branch.TrackItems.FirstOrDefault(track => CheckItemForChangeSet(x, track)) != null) .Select(x => ProcessMergeRequestChanges(mergeRequest, x, localGitDir, branch, autoSyncToken)).ToList(); bool ignoreValidation = gitLabWrapper.ShouldIgnoreSharedFiles(mergeRequest); if (!ValidateMergeRequestChanges(gitLabWrapper, mergeRequest, ignoreValidation) || !vcsWrapper.ProcessCheckout(genericChange, ignoreValidation, branch)) { Log.Error("Merging merge request failed because failed validation."); AssignBackConflictedMergeRequest(gitLabWrapper, users, mergeRequest, CalcCommentForFailedCheckoutMergeRequest(genericChange)); vcsWrapper.ProcessUndoCheckout(genericChange); return MergeRequestResult.CheckoutFailed; } CommentWrapper comment = CalcComment(mergeRequest, branch, autoSyncToken); mergeRequest = gitLabWrapper.ProcessMergeRequest(mergeRequest, comment.ToString()); if (mergeRequest.State == "merged") { Log.Message("Merge request merged successfully."); gitWrapper.Pull(); gitWrapper.LFSPull(); var gitCommit = gitWrapper.FindCommit(x => CommentWrapper.Parse(x.Message).Token == autoSyncToken); long timeStamp = lastHistoryItem.VcsCommitTimeStamp; if (gitCommit != null && vcsWrapper.ProcessCheckIn(genericChange, comment.ToString())) { var checkinHistory = vcsWrapper.GenerateHistory(branch, new DateTime(timeStamp)).Where(x => x.ActionDate.Ticks > timeStamp); var lastCommit = checkinHistory.OrderBy(x => x.ActionDate).LastOrDefault(); long newTimeStamp = lastCommit?.ActionDate.Ticks ?? timeStamp; var mergeRequestResult = MergeRequestResult.Success; if (!ValidateMergeRequest(vcsWrapper, branch, lastHistoryItem, defaultUser)) mergeRequestResult = MergeRequestResult.Mixed; if (!ValidateChangeSet(genericChange)) mergeRequestResult = MergeRequestResult.Mixed; syncHistory.Add(gitCommit.Sha, newTimeStamp, autoSyncToken, mergeRequestResult == MergeRequestResult.Success ? SyncHistoryStatus.Success : SyncHistoryStatus.Mixed); syncHistory.Save(); Log.Message("Merge request checkin successfully."); return mergeRequestResult; } Log.Error("Merge request checkin failed."); if (gitCommit == null) Log.Error($"Can`t find git commit with token {autoSyncToken}"); var failedHistory = vcsWrapper.GenerateHistory(branch, new DateTime(timeStamp)); var lastFailedCommit = failedHistory.OrderBy(x => x.ActionDate).LastOrDefault(); syncHistory.Add(gitCommit.Sha, lastFailedCommit?.ActionDate.Ticks ?? timeStamp, autoSyncToken, SyncHistoryStatus.Failed); syncHistory.Save(); return MergeRequestResult.Failed; } Log.Message($"Merge request merging failed due conflicts. Resolve conflicts manually."); vcsWrapper.ProcessUndoCheckout(genericChange); AssignBackConflictedMergeRequest(gitLabWrapper, users, mergeRequest, CalcCommentForFailedCheckoutMergeRequest(genericChange)); return MergeRequestResult.Conflicts; }