public void AddRemoveUser() { // arrange FakeUserRepo userRepo = new FakeUserRepo(); int id = ObjectIDBuilder.GetUserID(); const string username = "******"; const string password = "******"; const string gender = "male"; DateTime dateJoinedD = DateTime.Now; Thread ownedThread = null; StandardUser newUser = new StandardUser() { StandardUserID = id, Name = username, Password = password, Gender = gender, DateJoined = dateJoinedD, OwnedThread = ownedThread }; // act userRepo.AddUsertoRepo(newUser); StandardUser removedUser = userRepo.RemoveUserfromRepo(id); // assert Assert.Equal(newUser.Name, removedUser.Name); Assert.Equal(newUser.DateJoined, removedUser.DateJoined); Assert.Equal(newUser.StandardUserID, removedUser.StandardUserID); }
static void Main(string[] args) { Seed(); while (true) { Console.Clear(); int loginChoice = _uiService.LogInMenu(); Console.Clear(); if (loginChoice == 1) { int roleChoice = _uiService.RoleMenu(); UserRole role = (UserRole)roleChoice; Console.Clear(); Console.WriteLine("Enter username:"******"Enter password:"******"Enter first name:"); newUser.FirstName = Console.ReadLine(); Console.WriteLine("Enter last name:"); newUser.LastName = Console.ReadLine(); Console.WriteLine("Enter username:"******"Enter password:"); newUser.Password = Console.ReadLine(); User user = _standardUserSrvc.Register(newUser); if (user == null) { continue; } } } Console.Clear(); _uiService.Welcome(_currentUser); _uiService.MainMenu(_currentUser.Role); }
/// <summary> /// Import Users data from document of CSV format. /// </summary> /// <param name="fileName">The name of imported file.</param> public void ImportCsv(string fileName) { var basePath = AppDomain.CurrentDomain.BaseDirectory; var finalPath = Path.Combine(basePath, fileName + ".csv"); if (File.Exists(fileName + ".csv")) { using (StreamReader sr = new StreamReader(finalPath)) { string line; string test = ""; string[] headers = sr.ReadLine().Split(';'); foreach (string header in headers) { test += header; } string[] row = new string[4]; while ((line = sr.ReadLine()) != null) { row = line.Split(';'); User user = new StandardUser(); user.FirstName = row[0].Trim(); user.LastName = row[1].Trim(); user.DateOfBirth = row[2].Trim(); user.ID = int.Parse(row[3]); users.Add(user); } } } else { throw new FileNotFoundException("File was not found"); } }
public async Task <IActionResult> Edit(string id, [Bind("Id,ApplicationUserId,Bio,FirstName,LastName,Email,City,State,ZipCode")] StandardUser standardUser) { if (id != standardUser.Id) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(standardUser); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!StandardUserExists(standardUser.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } ViewData["ApplicationUserId"] = new SelectList(_context.Set <ApplicationUser>(), "Id", "Id", standardUser.ApplicationUserId); return(View(standardUser)); }
private static void BuildAndSendObjectsToRepos() { /* * Steps: * loop through the array of usernames * build user objects and a thread for each of them * add the thread to the threadRepo * add the user object to the user repo */ // loop to generate user objects for (int i = 0; i < usernames.Length; i++) { // build user object StandardUser user = new StandardUser() { StandardUserID = ObjectIDBuilder.GetUserID(), Name = usernames[i], Password = "******", DateJoined = DateTime.Now }; // call thread builder // pass creator username to thread // set owned thread property Thread thread = BuildThread(i); thread.CreatorName = user.Name; user.OwnedThread = thread; // set objects to object repos new FakeThreadRepo().AddThreadtoRepo(thread); new FakeUserRepo().AddUsertoRepo(user); } }
public IActionResult UpdateUserById([FromBody] CreateUserViewModel userViewModel, int id) { var deletedUser = userRepo.RemoveUserfromRepo(id); if (deletedUser != null) { var dateJoined = deletedUser.DateJoined; StandardUser user = new StandardUser() { Name = userViewModel.Name, Password = userViewModel.Password, ConfirmPassword = userViewModel.Password, DateJoined = dateJoined, }; userRepo.AddUsertoRepo(user); if (user != null) { return(Ok(user)); } else { return(NotFound()); } } else { return(Ok()); // means user is gone } }
public IActionResult MyBlogDashboard() { // no need to valid tempdata, only time this method gets called is if a valid username is passed string username = TempData["validUsername"].ToString(); StandardUser userObject = userRepo.GetUserByUsername(username); return(View("MyBlogMainPanel", userObject)); }
public async Task <IActionResult> OnPostConfirmationAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); // Get the information about the user from the external login provider var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { ErrorMessage = "Error loading external login information during confirmation."; return(RedirectToPage("./Login", new { ReturnUrl = returnUrl })); } if (ModelState.IsValid) { var user = new ApplicationUser { UserName = Input.Email, Email = Input.Email }; var result = await _userManager.CreateAsync(user); if (result.Succeeded) { if (!await _roleManager.RoleExistsAsync(StaticDetails.StandardEndUser)) { await _roleManager.CreateAsync(new IdentityRole(StaticDetails.StandardEndUser)); } await _userManager.AddToRoleAsync(user, StaticDetails.StandardEndUser); result = await _userManager.AddLoginAsync(user, info); if (result.Succeeded) { var standardUserEntry = _context.StandardUsers.Where(s => s.ApplicationUserId == user.Id).ToList(); if (standardUserEntry.Count() == 0) { var standardUser = new StandardUser() { Email = user.Email, ApplicationUserId = user.Id }; await _context.StandardUsers.AddAsync(standardUser); await _context.SaveChangesAsync(); } await _signInManager.SignInAsync(user, isPersistent : false); _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider); return(LocalRedirect(returnUrl)); } } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } LoginProvider = info.LoginProvider; ReturnUrl = returnUrl; return(Page()); }
// THESE METHODS REQUIRE A USER ID FOR ACCESS // ----------------------------------------------------------------------------------------------------> // ----------------------------------------------------------------------------------------------------> public IActionResult ReloadBlogDashboard() { // takes in userId from temp data entry // retrieves user object and then passes it into the dashboard view int userId = int.Parse(TempData["userId"].ToString()); StandardUser userObject = userRepo.GetUserById(userId); return(View("MyBlogMainPanel", userObject)); }
public ActionResult Edit([Bind(Include = "Id,Password,Name,Surname")] StandardUser standardUser) { if (ModelState.IsValid) { db.Entry(standardUser).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } return(View(standardUser)); }
public void AddUsertoRepo(StandardUser user) { if (IsUsernameTaken(user.Name) == false) { userList.Add(user); } else { throw new ArgumentException("Please make sure that the username is unique!"); } }
public ActionResult Create([Bind(Include = "Id,Password,Name,Surname")] StandardUser standardUser) { if (ModelState.IsValid) { db.standardUsers.Add(standardUser); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(standardUser)); }
static void Main(string[] args) { List <Phonebook> users = new List <Phonebook>(); string json = new WebClient().DownloadString("https://jsonplaceholder.typicode.com/users?_limit=5"); users = new JavaScriptSerializer().Deserialize <List <Phonebook> >(json); StandardMessages messages = new StandardMessages(); Console.WriteLine(messages.StartApp); Console.WriteLine(); Console.WriteLine(); bool keepGoing = true; do { Console.WriteLine("Select your user status\n\t1 - Standard User\n\t2 - Supervisor\n\t3 - Exit"); string input = Console.ReadLine(); switch (input) { case "1": Console.Clear(); StandardMessages.StandardUserViewTitle(); foreach (Phonebook phonebook in users) { IStandardUser user = new StandardUser(phonebook); Console.WriteLine(user.Display()); } //Console.WriteLine("Press any key to return to the main menu."); break; case "2": Console.Clear(); StandardMessages.SupervisorViewTitle(); foreach (Phonebook phonebook in users) { ISupervisor user = new Supervisor(phonebook); Console.WriteLine(user.Display()); } break; default: keepGoing = false; break; } } while (keepGoing == true); Console.WriteLine(messages.EndApp); Console.WriteLine("Press any key to exit"); Console.ReadLine(); }
public IActionResult PostDashboard(string userId) { // get user by id // pass user object into view int ID = int.Parse(userId); StandardUser userObject = userRepo.GetUserById(ID); // using viewbag because I need to use a post model for validation ViewBag.OwnedThread = userObject.OwnedThread; ViewBag.UserID = userObject.StandardUserID; return(View()); }
public async Task <IActionResult> Create([Bind("Id,ApplicationUserId,Bio,FirstName,LastName,Email,City,State,ZipCode")] StandardUser standardUser) { if (ModelState.IsValid) { _context.Add(standardUser); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } ViewData["ApplicationUserId"] = new SelectList(_context.Set <ApplicationUser>(), "Id", "Id", standardUser.ApplicationUserId); return(View(standardUser)); }
public void AddUsertoRepo(StandardUser user) { if (IsUsernameTaken(user.Name) == false) { context.StandardUsers.Add(user); context.SaveChanges(); } else { throw new ArgumentException("Please make sure that the username is unique!"); } }
public static StandardUser getCurrentUser() { if (HttpContext.Current.Session["user"] == null) { return(null); } else { StandardUser currentUser = (StandardUser)HttpContext.Current.Session["user"]; return(currentUser); } }
/// <summary> /// Edit User in the storage. /// </summary> /// <param name="user">User which would like to be changed.</param> /// <param name="newName">New User first name.</param> /// <param name="newLName">New User last name.</param> /// <param name="newDB">New User day of birth.</param> /// <returns>Operation success status.</returns> public bool EditUser(User user, string newName, string newLName, string newDB) { User newUser = new StandardUser(newName, newLName, newDB); users.Find(t => t.ID == user.ID).FirstName = newName; users.Find(t => t.ID == user.ID).LastName = newLName; users.Find(t => t.ID == user.ID).DateOfBirth = newDB; if (user.Equals(newUser)) { return(true); } return(false); }
public ActionResult Borrow(string id) { currentUser = db.standardUsers.Find(currentUser.Id); if (id == null) { ViewBag.error = "Isbn no girilmedi"; return(View("Error")); } Book book = db.books.Find(id); if (book == null) { ViewBag.error = "Kitap bulunamadı"; return(View("Error")); } if (book.userMap != null) { ViewBag.error = "Bu kitap teslim alınmış."; return(View("Error")); } List <Book> myBooks = db.books.Include(a => a.userMap).Where(x => x.userMap.userId == currentUser.Id).ToList(); if (myBooks.Count >= 3) { ViewBag.error = "Bir kullanıcı 3'ten fazla sayıda kitap alamaz."; return(View("Error")); } if (myBooks.Where(x => x.userMap.deliveryDate < Kutuphane.Date.Date.date).ToList().Count > 0) { ViewBag.error = "Teslim süren geçmiş kitapların var. Önce onları teslim et."; return(View("Error")); } UserBookMap willBeAdded = new UserBookMap(); willBeAdded.book = book; willBeAdded.deliveryDate = Kutuphane.Date.Date.date.AddDays(7); willBeAdded.Isbn = book.Isbn; willBeAdded.user = currentUser; willBeAdded.userId = currentUser.Id; db.userBookMaps.Add(willBeAdded); db.SaveChanges(); return(RedirectToAction("MyBooks")); }
public RedirectToActionResult BuildThread(string Name, string category, string Bio, string userId) { // validate input (not empty AND trim trailing white space) // search thread repo and determine if the threadname is in use // Build a thread object using the input parameters // Get reference to user by id // Set the user's owned thread property // Add thread to threadRepo // make a temp data entry containing the userId // redirect to ReloadBlogDashboard action method var trimmedThreadname = ""; var trimmedBio = ""; if (Name != null && category != null && Bio != null) { trimmedThreadname = Name.Trim(); trimmedBio = Bio.Trim(); } else { // create a tempdata entry that contains the message to be returned in the getting started view // return getting started view because the inputted data is empty TempData["ThreadCreationMessage"] = "No fields can be left blank"; TempData["userId"] = userId; return(RedirectToAction("GettingStarted")); } if (!(threadRepo.GetThreadnameEligibility(trimmedThreadname) == true)) { TempData["ThreadCreationMessage"] = "Unforunately, that thread name is already taken :("; TempData["userId"] = userId; return(RedirectToAction("GettingStarted")); } int USERID = int.Parse(userId); StandardUser user = userRepo.GetUserById(USERID); Thread newThread = new Thread() { Name = Name, Bio = Bio, Category = category, CreatorName = user.Name }; user.OwnedThread = newThread; threadRepo.AddThreadtoRepo(newThread); TempData["userId"] = userId; return(RedirectToAction("ReloadBlogDashboard")); }
public RedirectToActionResult SignUpRedirect(string Name, string Password, string ConfirmPassword) { // validate username and password (not empty AND trim trailing white space) // search repo to see if username is already taken // check to make sure password and confirmed password fields match // build user object // add user to repo // redirect to myblogpanel // else show signup with an invalid username and password error var trimmedUsername = ""; var trimmedPassword = ""; var trimmedConfirmPassword = ""; if (Name != null && Name != null && ConfirmPassword != null) { trimmedUsername = Name.Trim(); trimmedPassword = Password.Trim(); trimmedConfirmPassword = ConfirmPassword.Trim(); } else { // create a tempdata entry that contains the message to be returned in the sign up view // return signup view because the password/username combo is empty TempData["SignUpMessage"] = "Password and/or username fields cannot be empty"; return(RedirectToAction("SignUp")); } if (userRepo.GetUsernameEligibility(trimmedUsername) == false) { TempData["SignUpMessage"] = "That username is taken :("; return(RedirectToAction("SignUp")); } if (trimmedPassword != trimmedConfirmPassword) { TempData["SignUpMessage"] = "Password and/or username fields cannot be empty"; return(RedirectToAction("SignUp")); } StandardUser newUser = new StandardUser() { Name = trimmedUsername, Password = trimmedConfirmPassword, ConfirmPassword = trimmedConfirmPassword, DateJoined = DateTime.Now }; userRepo.AddUsertoRepo(newUser); TempData["validUsername"] = trimmedUsername; return(RedirectToAction("MyBlogDashboard")); }
// GET: Admin/StandardUsers/Details/5 public ActionResult Details(string id) { if (id == null) { ViewBag.error = "User id girilmedi."; return(View("Error")); } StandardUser standardUser = currentAdmin.GetUserDetail(id); if (standardUser == null) { ViewBag.error = "User bulunamadı"; return(View("Error")); } return(View(standardUser)); }
// GET: Admin/StandardUsers/Edit/5 public ActionResult Edit(string id) { if (id == null) { ViewBag.error = "User id girilmedi."; return(View("Error")); } StandardUser standardUser = db.standardUsers.Find(id); if (standardUser == null) { ViewBag.error = "User bulunamadı."; return(View("Error")); } return(View(standardUser)); }
private static void UpgradeStandardToPremium() { var standard = new StandardUser { ID = 1, FirstName = "Standard", LastName = "Standerson", UserName = "******", Password = "******" }; var premium = new PremiumUser(standard); var result = (premium is PremiumUser); Console.WriteLine(result); }
public StandardUser RemoveUserfromRepo(int userID) { // find user // then remove it StandardUser removedUser = null; foreach (StandardUser u in userList) { if (u.StandardUserID == userID) { removedUser = u; userList.Remove(u); return(removedUser); } } return(removedUser); }
public ActionResult DeleteConfirmed(string id) { if (id == null) { ViewBag.error = "User id girilmedi."; return(View("Error")); } StandardUser standardUser = db.standardUsers.Find(id); if (standardUser == null) { ViewBag.error = "User bulunamadı."; return(View("Error")); } db.standardUsers.Remove(standardUser); db.SaveChanges(); return(RedirectToAction("Index")); }
public StandardUser RemoveUserfromRepo(int userID) { // find user // then remove it StandardUser removedUser = null; List <StandardUser> userList = GetUsers(); foreach (StandardUser u in userList) { if (u.StandardUserID == userID) { removedUser = u; context.StandardUsers.Remove(u); context.SaveChanges(); } } return(removedUser); }
/// <summary> /// Import Users data from document of XML format. /// </summary> /// <param name="fileName">The name of imported file.</param> public void ImportXml(string fileName) { XmlDocument xDoc = new XmlDocument(); var basePath = AppDomain.CurrentDomain.BaseDirectory; var finalPath = Path.Combine(basePath, fileName + ".xml"); if (File.Exists(fileName + ".xml")) { xDoc.Load(finalPath); } else { throw new FileNotFoundException("File was not found"); } XmlElement xRoot = xDoc.DocumentElement; foreach (XmlElement xnode in xRoot) { User user = new StandardUser(); XmlNode attr = xnode.Attributes.GetNamedItem("UserID"); if (attr != null) { user.ID = int.Parse(attr.Value); } foreach (XmlNode childnode in xnode.ChildNodes) { if (childnode.Name == "FirstName") { user.FirstName = childnode.InnerText; } if (childnode.Name == "LastName") { user.LastName = childnode.InnerText; } if (childnode.Name == "DayOfBirth") { user.DateOfBirth = childnode.InnerText; } } users.Add(user); } }
public IActionResult AddUser([FromBody] CreateUserViewModel userViewModel) { if (userViewModel != null) { StandardUser user = new StandardUser() { Name = userViewModel.Name, Password = userViewModel.Password, ConfirmPassword = userViewModel.Password, DateJoined = DateTime.Now, }; userRepo.AddUsertoRepo(user); return(Ok(user)); } else { return(BadRequest()); } }
public StandardUser FillNewUserData() { StandardUser standardUser = new StandardUser(); Console.WriteLine("Enter first name"); string firstName = Console.ReadLine(); if (string.IsNullOrEmpty(firstName)) { throw new Exception("You must enter first name"); } Console.WriteLine("Enter last name"); string lastName = Console.ReadLine(); if (string.IsNullOrEmpty(lastName)) { throw new Exception("You must enter last name"); } Console.WriteLine("Enter username"); string username = Console.ReadLine(); if (string.IsNullOrEmpty(username)) { throw new Exception("You must enter username"); } Console.WriteLine("Enter password"); string password = Console.ReadLine(); if (string.IsNullOrEmpty(password)) { throw new Exception("You must enter password"); } standardUser.FirstName = firstName; standardUser.LastName = lastName; standardUser.Username = username; standardUser.Password = password; return(standardUser); }
/// <summary> /// Initializes a new instance of the <see cref="DelegateUser"/> class. /// </summary> /// <param name="standardUser">The standard delegate user.</param> public DelegateUser(StandardUser standardUser) : this() { this.userId.StandardUser = standardUser; }
/// <summary> /// Initializes a new instance of the <see cref="UserId"/> class. /// </summary> /// <param name="standardUser">The StandardUser value used to initialize the UserId.</param> public UserId(StandardUser standardUser) : this() { this.standardUser = standardUser; }
/// <summary> /// Initializes a new instance of the <see cref="FolderPermission"/> class. /// </summary> /// <param name="standardUser">The standard user the permission applies to.</param> /// <param name="permissionLevel">The level of the permission.</param> public FolderPermission(StandardUser standardUser, FolderPermissionLevel permissionLevel) { this.userId = new UserId(standardUser); this.PermissionLevel = permissionLevel; }