public void TestGet_InitializeValidUsers_PasswordsShouldMatch() { // Arrange var roomsRepo = new UserRepository(); roomsRepo.Add(new User("username1", "password123", Roles.User)); roomsRepo.Add(new User("username2", "password1234", Roles.VenueAdmin)); roomsRepo.Add(new User("username3", "password123", Roles.User)); // Act var user = roomsRepo.Get(2); // Assert Assert.AreEqual(HashUtilities.GetSha256Hash("password1234"), user.PasswordHash, "Passwords don't match."); }
public void TestGet_InitializeValidUsers_UsernamesShouldMatch() { // Arrange var roomsRepo = new UserRepository(); roomsRepo.Add(new User("username1", "password123", Roles.User)); roomsRepo.Add(new User("username2", "password123", Roles.VenueAdmin)); roomsRepo.Add(new User("username3", "password123", Roles.User)); // Act var user = roomsRepo.Get(2); // Assert Assert.AreEqual("username2", user.Username, "Usernames don't match."); }
public void TestGet_InitializeValidUsers_UserShouldNotBeNull() { // Arrange var roomsRepo = new UserRepository(); roomsRepo.Add(new User("username1", "password123", Roles.User)); roomsRepo.Add(new User("username2", "password123", Roles.VenueAdmin)); roomsRepo.Add(new User("username3", "password123", Roles.User)); // Act var user = roomsRepo.Get(2); // Assert Assert.IsNotNull(user, "User should not be null."); }
public void UserRepository() { IUserRepository userRepository = new UserRepository(new EntityFrameworkRepositoryContext()); User user1 = new User { Name = "小菜" }; User user2 = new User { Name = "大神" }; userRepository.Add(user1); userRepository.Add(user2); userRepository.Context.Commit(); //var user = URepository.GetUserByName("小菜"); //if (user != null) //{ // Console.WriteLine(user.Name); //} }
public void InsertUserCheckUnique() { var unitOfWork = new UnitOfWork<GenericRepositoryTestContext>(); var user = new User { Email = "*****@*****.**", Name = "Wim Pool" }; var userRepo = new UserRepository(unitOfWork); userRepo.Add(user); try { userRepo.SaveChanges(); } catch (DbEntityValidationException validationException) { foreach (var error in validationException.EntityValidationErrors) { Assert.IsTrue(error.ValidationErrors.Count == 1); Assert.AreEqual(error.ValidationErrors.First().ErrorMessage, "NotUnique"); Assert.AreEqual(error.ValidationErrors.First().PropertyName, "Email"); } } var users = userRepo.FindBy(u => u.Email == "*****@*****.**"); Assert.IsTrue(users.Count() == 1); }
public void AddUser() { using (CapriconContext context = new CapriconContext()) { var newUser = new User() { FirstName = "james", LastName = "kamau", OtherName = "", Gender = Gender.Female, MobilePhone = "0756 123 456", Email = "*****@*****.**", Town = "Nairobi", District = "Nairobi", DateOfBirth = DateTime.Now.AddYears(-40), }; var userRep = new UserRepository(context); userRep.Add(newUser); try { context.SaveChanges(); } catch (DbEntityValidationException ex) { //Retrieve validation errors ex.EntityValidationErrors.ToList().ForEach ( v => { v.ValidationErrors.ToList().ForEach ( e => { System.Diagnostics.Debug.WriteLine(e.ErrorMessage); } ); } ); Assert.Fail("Test failed"); } //retrieve saved object var context1 = new CapriconContext(); var repository = new UserRepository(context1); var savedUsers = repository.GetAll().ToList(); Assert.AreEqual(savedUsers.Count(), 1, "returns 20 records"); var savedUsersList = savedUsers; savedUsersList.ForEach ( s => { Debug.WriteLine(s.UserId +" - "+ s.FirstName +" "+ s.LastName); } ); }; }
public void TestAdd() { try { var userEntiry = new UserEntity() { Password = "******", CreatedAt = DateTime.UtcNow, UserName = "******", Emails = new List<string>() { "*****@*****.**", "*****@*****.**" }, Options = new Dictionary<string, string>() { {"city", "Zhuhai"}, {"language", "cn"} } }; var userRepo = new UserRepository(); var task = userRepo.Add(userEntiry); task.Wait(); Assert.IsNotNull(userEntiry.Id); Assert.IsFalse(string.IsNullOrWhiteSpace(task.Result)); } catch (Exception e) { Assert.Fail(e.Message); } }
public void Base_Inheritance_Save() { var repository = new UserRepository(); var user = new User {Name = "Base_Inheritance_Save"}; repository.Add(user); repository._collectionName.Should().Be("User"); }
public bool addUser(User user) { if (user != null) { UserRepository repository = new UserRepository(); repository.Add(user); return true; } return false; }
public void User_Add_ShouldSuccess() { // // TODO: 在此处添加测试逻辑 // User user = new User(); user.Username = "******"; IUserRepository r = new UserRepository(); r.Add(user); }
public void CanAddUser() { var repo = new UserRepository(); var user = new User { Username = "******", Password = "******", EmailAddress = "*****@*****.**", FirstName = "Matthew", MiddleName = "Scott", LastName = "Kimber", PhoneNumber = "222-1234567", IsActive = true, LicenseNumber = "ABCDEFG123", StaffType = StaffType.Physician, Address = new Address { Street1 = "939 E. 490 N.", Street2 = "Apt. 1B", City = "Ogden", Region = "Utah", //Country = "USA", IsActive = true }, DateCreated = DateTime.Now, IsApproved = true }; repo.Add(user); UnitOfWork.CurrentSession.Flush(); UnitOfWork.CurrentSession.Clear(); var retrievedUser = repo.Get("matthew.kimber"); Assert.AreEqual(user.Username, retrievedUser.Username); }
public ActionResult OpenId(string identifier, bool?rememberMe) { string errorMessage = null; string url = string.Concat(Settings.RootUrl, Url.Content("~/xrds.axd")); HttpContext.Response.Headers.Add("X-XRDS-Location", url); try { if (OpenIdRelyingParty.Response == null) { if (!string.IsNullOrEmpty(identifier)) { Identifier id; if (Identifier.TryParse(identifier, out id)) { var realm = new Realm(new Uri(string.Concat(Settings.RootUrl, Url.RouteUrl("OpenId")))); IAuthenticationRequest request = OpenIdRelyingParty.CreateRequest(identifier, realm); var fetch = new ClaimsRequest { Email = DemandLevel.Require }; request.AddExtension(fetch); OpenIdRememberMe = rememberMe ?? false; ReturnUrl = (HttpContext.Request.UrlReferrer != null) ? HttpContext.Request.UrlReferrer.ToString() : string.Empty; return(request.RedirectingResponse.AsActionResult()); //.RedirectToProvider(); } } return(new EmptyResult()); } if (OpenIdRelyingParty.Response.Status == AuthenticationStatus.Authenticated) { string userName = OpenIdRelyingParty.Response.ClaimedIdentifier; using (IUnitOfWork unitOfWork = UnitOfWork.Begin()) { IUser user = UserRepository.FindByUserName(userName); if ((user != null) && user.IsLockedOut) { errorMessage = "Twoje konto jest obecnie zablokowane. Skontaktuj się z nami w tej sprawie."; } else { var fetch = OpenIdRelyingParty.Response.GetExtension <ClaimsResponse>(); // Some of the Provider does not return Email // Such as Yahoo, Blogger, Bloglines etc, in that case we will assign a default // email string email = ((fetch == null) || string.IsNullOrEmpty(fetch.Email)) ? Settings.DefaultEmailOfOpenIdUser : fetch.Email; if (user == null) { user = _factory.CreateUser(userName, email, null); UserRepository.Add(user); _eventAggregator.GetEvent <UserActivateEvent>().Publish(new UserActivateEventArgs(user)); } else { //Sync the email from OpenID provider. if ((string.Compare(email, user.Email, StringComparison.OrdinalIgnoreCase) != 0) && (string.Compare(email, Settings.DefaultEmailOfOpenIdUser, StringComparison.OrdinalIgnoreCase) != 0)) { user.ChangeEmail(email); } } user.LastActivityAt = SystemTime.Now(); unitOfWork.Commit(); FormsAuthentication.SetAuthCookie(userName, OpenIdRememberMe); } } } else if ((OpenIdRelyingParty.Response.Status == AuthenticationStatus.Failed) || (OpenIdRelyingParty.Response.Status == AuthenticationStatus.Canceled)) { if (OpenIdRelyingParty.Response.Exception != null) { errorMessage = OpenIdRelyingParty.Response.Exception.Message; } if (String.IsNullOrEmpty(errorMessage)) { errorMessage = "Nie udało się zalogować przez wybranego dostawcę OpenID."; } } } catch (Exception oid) { errorMessage = oid.Message; } if (!string.IsNullOrEmpty(errorMessage)) { GenerateMessageCookie(errorMessage, true); } string returnUrl = ReturnUrl; if (!string.IsNullOrEmpty(returnUrl)) { return(Redirect(returnUrl)); } return(RedirectToRoute("Published")); }
public void ProcessRequest() { if (Request.QueryString["op"] == "login") { try { string email = Request.QueryString["username"]; string password = Request.QueryString["password"]; Registration regpage = new Registration(); password = regpage.MD5Hash(password); SocioBoard.Helper.SessionFactory.configfilepath = Server.MapPath("~/hibernate.cfg.xml"); UserRepository userrepo = new UserRepository(); LoginLogs objLoginLogs = new LoginLogs(); LoginLogsRepository objLoginLogsRepository = new LoginLogsRepository(); User user = userrepo.GetUserInfo(email, password); if (user == null) { Response.Write("Invalid Email or Password"); } else { if (user.UserStatus == 1) { Session["LoggedUser"] = user; // List<User> lstUser = new List<User>(); if (Session["LoggedUser"] != null) { //SocioBoard.Domain.User.lstUser.Add((User)Session["LoggedUser"]); //Application["OnlineUsers"] = SocioBoard.Domain.User.lstUser; //objLoginLogs.Id = new Guid(); //objLoginLogs.UserId = user.Id; //objLoginLogs.UserName = user.UserName; //objLoginLogs.LoginTime = DateTime.Now.AddHours(11.50); //objLoginLogsRepository.Add(objLoginLogs); Groups objGroups = new Groups(); GroupRepository objGroupRepository = new GroupRepository(); Team objteam = new Team(); TeamRepository objTeamRepository = new TeamRepository(); objGroups = objGroupRepository.getGroupDetail(user.Id); if (objGroups == null) { //================================================================================ //Insert into group try { objGroups = new Groups(); objGroups.Id = Guid.NewGuid(); objGroups.GroupName = ConfigurationManager.AppSettings["DefaultGroupName"]; objGroups.UserId = user.Id; objGroups.EntryDate = DateTime.Now; objGroupRepository.AddGroup(objGroups); objteam.Id = Guid.NewGuid(); objteam.GroupId = objGroups.Id; objteam.UserId = user.Id; objteam.EmailId = user.EmailId; // teams.FirstName = user.UserName; objTeamRepository.addNewTeam(objteam); SocialProfile objSocialProfile = new SocialProfile(); SocialProfilesRepository objSocialProfilesRepository = new SocialProfilesRepository(); List <SocialProfile> lstSocialProfile = objSocialProfilesRepository.getAllSocialProfilesOfUser(user.Id); if (lstSocialProfile != null) { if (lstSocialProfile.Count > 0) { foreach (SocialProfile item in lstSocialProfile) { try { TeamMemberProfile objTeamMemberProfile = new TeamMemberProfile(); TeamMemberProfileRepository objTeamMemberProfileRepository = new TeamMemberProfileRepository(); objTeamMemberProfile.Id = Guid.NewGuid(); objTeamMemberProfile.TeamId = objteam.Id; objTeamMemberProfile.ProfileId = item.ProfileId; objTeamMemberProfile.ProfileType = item.ProfileType; objTeamMemberProfile.Status = item.ProfileStatus; objTeamMemberProfile.StatusUpdateDate = DateTime.Now; objTeamMemberProfileRepository.addNewTeamMember(objTeamMemberProfile); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } } } catch (Exception ex) { Console.WriteLine(ex.Message); logger.Error("Error : " + ex.Message); logger.Error("Error : " + ex.StackTrace); } //========================================================================================================== } BusinessSetting objBusinessSetting = new BusinessSetting(); BusinessSettingRepository objBusinessSettingRepository = new BusinessSettingRepository(); List <BusinessSetting> lstBusinessSetting = objBusinessSettingRepository.GetBusinessSettingByUserId(user.Id); if (lstBusinessSetting.Count == 0) { try { List <Groups> lstGroups = objGroupRepository.getAllGroups(user.Id); foreach (Groups item in lstGroups) { objBusinessSetting = new BusinessSetting(); objBusinessSetting.Id = Guid.NewGuid(); objBusinessSetting.BusinessName = item.GroupName; //objbsnssetting.GroupId = team.GroupId; objBusinessSetting.GroupId = item.Id; objBusinessSetting.AssigningTasks = false; objBusinessSetting.AssigningTasks = false; objBusinessSetting.TaskNotification = false; objBusinessSetting.TaskNotification = false; objBusinessSetting.FbPhotoUpload = 0; objBusinessSetting.UserId = user.Id; objBusinessSetting.EntryDate = DateTime.Now; objBusinessSettingRepository.AddBusinessSetting(objBusinessSetting); } } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } } } Response.Write("user"); } else { Response.Write("You are Blocked by Admin Please contact Admin!"); } } } catch (Exception ex) { Response.Write("Error: " + ex.Message); Console.WriteLine(ex.StackTrace); logger.Error(ex.StackTrace); } } else if (Request.QueryString["op"] == "register") { User user = new User(); UserActivation objUserActivation = new UserActivation(); UserRepository userrepo = new UserRepository(); SocioBoard.Helper.SessionFactory.configfilepath = Server.MapPath("~/hibernate.cfg.xml"); Session["AjaxLogin"] = "******"; try { System.IO.StreamReader sr = new System.IO.StreamReader(Request.InputStream); string line = ""; line = sr.ReadToEnd(); JObject jo = JObject.Parse(line); user.PaymentStatus = "unpaid"; if (!string.IsNullOrEmpty(Request.QueryString["type"])) { user.AccountType = Request.QueryString["type"]; } else { user.AccountType = "deluxe"; } user.CreateDate = DateTime.Now; user.ExpiryDate = DateTime.Now.AddMonths(1); user.Id = Guid.NewGuid(); user.UserName = Server.UrlDecode((string)jo["firstname"]) + " " + Server.UrlDecode((string)jo["lastname"]); user.EmailId = Server.UrlDecode((string)jo["email"]); user.Password = Server.UrlDecode((string)jo["password"]); user.UserStatus = 1; if (!userrepo.IsUserExist(user.EmailId)) { UserRepository.Add(user); Session["LoggedUser"] = user; Response.Write("user"); objUserActivation.Id = Guid.NewGuid(); objUserActivation.UserId = user.Id; objUserActivation.ActivationStatus = "0"; UserActivationRepository.Add(objUserActivation); //add value in userpackage UserPackageRelation objUserPackageRelation = new UserPackageRelation(); UserPackageRelationRepository objUserPackageRelationRepository = new UserPackageRelationRepository(); PackageRepository objPackageRepository = new PackageRepository(); Package objPackage = objPackageRepository.getPackageDetails(user.AccountType); objUserPackageRelation.Id = new Guid(); objUserPackageRelation.PackageId = objPackage.Id; objUserPackageRelation.UserId = user.Id; objUserPackageRelation.PackageStatus = true; objUserPackageRelationRepository.AddUserPackageRelation(objUserPackageRelation); SocioBoard.Helper.MailSender.SendEMail(user.UserName, user.Password, user.EmailId, user.AccountType.ToString(), user.Id.ToString()); //MailSender.SendEMail(user.UserName, user.Password, user.EmailId); // lblerror.Text = "Registered Successfully !" + "<a href=\"login.aspx\">Login</a>"; } else { Response.Write("Email Already Exists !"); } } catch (Exception ex) { logger.Error(ex.StackTrace); Console.WriteLine(ex.StackTrace); } } else if (Request.QueryString["op"] == "facebooklogin") { SessionFactory.configfilepath = Server.MapPath("~/hibernate.cfg.xml"); string redi = "http://www.facebook.com/dialog/oauth/?scope=publish_stream,read_stream,read_insights,manage_pages,user_checkins,user_photos,read_mailbox,manage_notifications,read_page_mailboxes,email,user_videos,offline_access&client_id=" + ConfigurationManager.AppSettings["ClientId"] + "&redirect_uri=" + ConfigurationManager.AppSettings["RedirectUrl"] + "&response_type=code"; Session["login"] = "******"; Response.Write(redi); } else if (Request.QueryString["op"] == "googlepluslogin") { Session["login"] = "******"; oAuthToken objToken = new oAuthToken(); Response.Write(objToken.GetAutherizationLink("https://www.googleapis.com/auth/userinfo.email+https://www.googleapis.com/auth/userinfo.profile+https://www.googleapis.com/auth/plus.me+https://www.googleapis.com/auth/plus.login")); } else if (Request.QueryString["op"] == "removeuser") { try { if (Session["LoggedUser"] != null) { SocioBoard.Domain.User.lstUser.Remove((User)Session["LoggedUser"]); } } catch (Exception Err) { logger.Error(Err.StackTrace); Response.Write(Err.StackTrace); } } }
public void Should_Throw_Exception_When_User_Is_Assistant() { var options = new DbContextOptionsBuilder <RegistrationContext>() .UseInMemoryDatabase(databaseName: MethodBase.GetCurrentMethod().Name) .Options; using (var context = new RegistrationContext(options)) { IRSUserRepository userRepository = new UserRepository(context); IRSSessionRepository sessionRepository = new SessionRepository(context); IRSCourseRepository courseRepository = new CourseRepository(context); var Teacher = new UserTO() { //Id = 420, Name = "Christian", Email = "*****@*****.**", Role = UserRole.Teacher }; var Michou = new UserTO() { //Id = 45, Name = "Michou Miraisin", Email = "*****@*****.**", Role = UserRole.Attendee }; var Isabelle = new UserTO() { //Id = 45, Name = "Isabelle Balkany", Email = "*****@*****.**", Role = UserRole.Assistant }; var AddedTeacher = userRepository.Add(Teacher); var AddedAttendee = userRepository.Add(Michou); var AddedAttendee2 = userRepository.Add(Isabelle); context.SaveChanges(); var SQLCourse = new CourseTO() { //Id = 28, Name = "SQL" }; var AddedCourse = courseRepository.Add(SQLCourse); context.SaveChanges(); var SQLSession = new SessionTO() { //Id = 1, Attendees = new List <UserTO>() { AddedAttendee, AddedAttendee2 }, Course = AddedCourse, Teacher = AddedTeacher, }; var AddedSession = sessionRepository.Add(SQLSession); context.SaveChanges(); Assert.ThrowsException <ArgumentException>(() => sessionRepository.GetByUser(AddedAttendee2).Count()); } }
public void Add(SUser user) { UserRepository.Add(SUser.StoD(user)); }
/// <summary> /// The initialize fixture. /// </summary> private void InitializeFixture() { DatabaseTestUtility.DropCreateFirebrickDatabase(); this.defaultTestUser = new User { DisplayName = "name", Country = "United States", PostalCode = "a1b2c3", Password = "******", UserName = "******" }; var repository = new UserRepository(new DatabaseFactory()); repository.Add(this.defaultTestUser); }
public void Add_User(object s, EventArgs e) { Utility Util = new Utility(); if (!Page.IsValid) { UserRepository User = new UserRepository(); User.Username = Util.FormatTextForInput(Request.Form[Username.UniqueID]); User.Password = Encryption.Encrypt(Util.FormatTextForInput(Request.Form[Password1.UniqueID])); User.Email = Util.FormatTextForInput(Request.Form[Email.UniqueID]); User.FirstName = Util.FormatTextForInput(Request.Form[Firstname.UniqueID]); User.LastName = Util.FormatTextForInput(Request.Form[Lastname.UniqueID]); User.City = Util.FormatTextForInput(Request.Form[City.UniqueID]); User.State = Util.FormatTextForInput(Request.Form[State.UniqueID]); User.Country = Util.FormatTextForInput(Request.Form[Country.UniqueID]); User.DOB = DateTime.Parse(Date1.CalendarDateString); User.FavoriteFoods1 = Util.FormatTextForInput(Request.Form[FavoriteFoods1.UniqueID]); User.FavoriteFoods2 = Util.FormatTextForInput(Request.Form[FavoriteFoods2.UniqueID]); User.FavoriteFoods3 = Util.FormatTextForInput(Request.Form[FavoriteFoods3.UniqueID]); User.NewsLetter = Int32.Parse(Util.FormatTextForInput(Request.Form[Newsletter.UniqueID])); User.ContactMe = Int32.Parse(Util.FormatTextForInput(Request.Form[ContactMe.UniqueID])); User.Website = Util.FormatTextForInput(Request.Form[Website.UniqueID]); User.AboutMe = Util.FormatTextForInput(Request.Form[AboutMe.UniqueID]); User.GUID = Guid.NewGuid().ToString("N"); //Prevent username and email duplication. Ensure that all username and email in the database are unique. //This initialize the value. UserNameAndEmailValidation.Param(User.Username, User.Email); #region Form Input Validation //Handles validation of username and email. This prevent duplication. if (!UserNameAndEmailValidation.IsValid) { lbvalenght.Text = UserNameAndEmailValidation.ErrMsg; lbvalenght.Visible = true; txtsecfield.Text = ""; return; } if (!Validator.IsAlphaNumericOnly(User.Username)) { lbvalenght.Text = "<br> Lỗi: Tên đăng nhập phải có ít nhất 6 ký tự và lớn nhất 15 ký tự, và chỉ nên chứa chữ số. "; lbvalenght.Visible = true; txtsecfield.Text = ""; return; } //Let's decrypt the password for validation. if (!Validator.IsAlphaNumericOnly(Encryption.Decrypt(User.Password))) { lbvalenght.Text = "<br> Lỗi: Mật khẩu phải có ít nhất 6 ký tự và lớn nhất 12 ký tự, và chỉ nên chứa chữ số."; lbvalenght.Visible = true; txtsecfield.Text = ""; return; } //Let's decrypt the password for validation. if (Util.FormatTextForInput(Request.Form[Password1.UniqueID]) != Util.FormatTextForInput(Request.Form[Password2.UniqueID])) { lbvalenght.Text = "<br> Lỗi: Mật khẩu không giống nhau. Vui lòng. nhập một mật khẩu và đảm bảo rằng chúng phù hợp cả hai."; lbvalenght.Visible = true; txtsecfield.Text = ""; return; } if (!Validator.IsValidEmail(User.Email)) { lbvalenght.Text = "<br> Lỗi: Địa chỉ Email không hợp lệ. Địa chỉ email. phải là một định dạng hợp lệ."; lbvalenght.Visible = true; txtsecfield.Text = ""; return; } if (!Validator.IsValidName(User.FirstName)) { lbvalenght.Text = "<br> Lỗi: Tên của bạn nên được bảng chữ cái và không chứa các ký tự bất hợp pháp."; lbvalenght.Visible = true; txtsecfield.Text = ""; return; } if (!Validator.IsValidName(User.LastName)) { lbvalenght.Text = "<br> Lỗi: Tên họ và tên đệm của bạn nên được bảng chữ cái và không chứa các ký tự bất hợp pháp."; lbvalenght.Visible = true; txtsecfield.Text = ""; return; } if (User.FavoriteFoods1.Length > 25) { lbvalenght.Text = "<br> Lỗi: Bài hát yêu thích 1 là quá dài, tối đa là 25 ký tự.."; lbvalenght.Visible = true; txtsecfield.Text = ""; return; } if (User.FavoriteFoods2.Length > 25) { lbvalenght.Text = "<br> Lỗi: Bài hát yêu thích 2 là quá dài, tối đa là 25 ký tự.."; lbvalenght.Visible = true; txtsecfield.Text = ""; return; } if (User.FavoriteFoods3.Length > 25) { lbvalenght.Text = "<br> Lỗi: Bài hát yêu thích 3 là quá dài, tối đa là 25 ký tự.."; lbvalenght.Visible = true; txtsecfield.Text = ""; return; } if (User.Country == "none") { lbvalenght.Text = "<br> Lỗi: Bạn phải chọn một quốc gia."; lbvalenght.Visible = true; txtsecfield.Text = ""; return; } if (User.AboutMe.Length > 500) { lbvalenght.Text = "<br> Lỗi: Văn bản giới thiệu về bản thân quá dài. tối đa là 500 ký tự."; lbvalenght.Visible = true; txtsecfield.Text = ""; return; } if (User.Website.Length > 75) { lbvalenght.Text = "<br> Lỗi: Địa chỉ website quá dài tối đa là 75 ký tự.."; lbvalenght.Visible = true; txtsecfield.Text = ""; return; } #endregion if (UserImageFileUpload.HasFile) { int FileSize = UserImageFileUpload.PostedFile.ContentLength; string contentType = UserImageFileUpload.PostedFile.ContentType; //File type validation if (!contentType.Equals("image/gif") && !contentType.Equals("image/jpeg") && !contentType.Equals("image/jpg") && !contentType.Equals("image/png")) { lbvalenght.Text = "<br>Ảnh của bạn không đúng định dạng. chỉ cho phép những định dạng sau gif, jpg, jpeg or png."; lbvalenght.Visible = true; return; } // File size validation if (FileSize > constant.UserImageMaxSize) { lbvalenght.Text = "<br> Dung lượng vượt quá 60.000 byte cho phép"; lbvalenght.Visible = true; return; } } ImageUploadManager.UploadUserImage(User, PlaceHolder1, GetUserImage.ImagePathForUserPhoto, constant.UserImageMaxSize); if (User.Add(User) != 0) { JSLiteral.Text = "Có lỗi sảy ra trong quá trình sử lý yêu cầu của bạn."; return; } EmailAccountActivationLink(User); User = null; Response.Redirect("redirectionpage.aspx?email=" + Request.Form[Email.UniqueID]); } else { JSLiteral.Text = Util.JSAlert("Mã bảo mật không hợp lệ. Hãy chắc chắn rằng bạn nhập chính xác."); return; lblinvalidsecode.Text = "Mã bảo mât không đúng. Hãy chắc chắn bạn đã nhập đúng các ký tự của mã bảo vệ."; lblinvalidsecode.Visible = true; } Util = null; }
public string Save() { string result = ""; try { var repo = new UserRepository(); var userInput = JsonConvert.DeserializeObject<DAL.User>(Request["user"]); if (userInput != null) { if (repo.IsExist(userInput.ID, userInput.UserName)) return JsonResult(false, "1"); else { if (userInput.ID == 0) repo.Add(userInput); else { var user = repo.GetByID(userInput.ID); if (user != null) { user.UserName = userInput.UserName; user.RoleID = userInput.RoleID; user.RoleName = userInput.RoleName; if (userInput.Password + "" != "") user.Password = userInput.Password; repo.SaveChanges(); } } result = JsonResult(true, Resources.Messages.Save); } } else result = JsonResult(true, Resources.Messages.Save); } catch (Exception ex) { result = JsonResult(false, ex.Message); } return result; }
public string RegisterbyTwitter(string EmailId, string Password, string AccountType, string Username, string SocioLogin, string PictureUrl, string ActivationStatus = "0") { try { logger.Error("RegisterbyTwitter"); if (!userrepo.IsUserExist(EmailId)) { Domain.Socioboard.Domain.User user = new Domain.Socioboard.Domain.User(); user.AccountType = AccountType; user.EmailId = EmailId; user.CreateDate = DateTime.Now; user.ExpiryDate = DateTime.Now.AddMonths(1); user.Password = Utility.MD5Hash(Password); user.PaymentStatus = "unpaid"; user.ProfileUrl = string.Empty; user.TimeZone = string.Empty; user.UserName = Username;//FirstName + " " + LastName; user.UserStatus = 1; user.Ewallet = "0"; user.ActivationStatus = ActivationStatus;//"0"; user.Id = Guid.NewGuid(); user.UserCode = Utility.GenerateRandomUniqueString(); user.SocialLogin = SocioLogin; user.ProfileUrl = PictureUrl; UserRepository.Add(user); ////add value in UserActivation //UserActivation.AddUserActivation(user); //add value in userpackage // UserPackageRelation.AddUserPackageRelation(user); try { Domain.Socioboard.Domain.Groups groups = AddGroupByUserId(user.Id); BusinessSettingRepository busnrepo = new BusinessSettingRepository(); BusinessSetting.AddBusinessSetting(user.Id, groups.Id, groups.GroupName); Team.AddTeamByGroupIdUserId(user.Id, user.EmailId, groups.Id); UpdateTeam(EmailId, user.Id.ToString(), user.UserName); } catch (Exception ex) { Console.WriteLine(ex.Message); logger.Error("Error : " + ex.Message); logger.Error("Error : " + ex.StackTrace); } //MailSender.SendEMail(user.UserName, Password, EmailId); return(new JavaScriptSerializer().Serialize(user)); } else { return("Email Already Exists"); } } catch (Exception ex) { Console.WriteLine(ex.StackTrace); return("Something Went Wrong"); } }
public void Add(User user, string membershipUsername) { user.MemberShipUsername = membershipUsername; _repo.Add(user); }
public string Register(string EmailId, string Password, string AccountType, string Username, string ActivationStatus = "0") { try { //UserRepository userrepo = new UserRepository(); //Domain.Socioboard.Domain.UserActivation objUserActivation = new Domain.Socioboard.Domain.UserActivation(); //UserActivationRepository objUserActivation = new UserActivationRepository(); logger.Error("Register"); if (!userrepo.IsUserExist(EmailId)) { Domain.Socioboard.Domain.User user = new Domain.Socioboard.Domain.User(); user.AccountType = AccountType; user.EmailId = EmailId; user.CreateDate = DateTime.Now; try { if (ConfigurationManager.AppSettings["expiryindays"].ToString() != "") { double expiryindays = double.Parse(ConfigurationManager.AppSettings["expiryindays"].ToString(), CultureInfo.InvariantCulture.NumberFormat); user.ExpiryDate = DateTime.Now.AddDays(expiryindays); } else { user.ExpiryDate = DateTime.Now.AddDays(30); } } catch (Exception) { user.ExpiryDate = DateTime.Now.AddDays(30); } user.Password = Utility.MD5Hash(Password); user.PaymentStatus = "unpaid"; user.ProfileUrl = string.Empty; user.TimeZone = string.Empty; user.UserName = Username;//FirstName + " " + LastName; user.UserStatus = 1; user.Ewallet = "0"; user.ActivationStatus = ActivationStatus;//"0"; user.Id = Guid.NewGuid(); user.UserCode = Utility.GenerateRandomUniqueString(); user.LastLoginTime = DateTime.Now; UserRepository.Add(user); ////add value in UserActivation //UserActivation.AddUserActivation(user); //add value in userpackage // UserPackageRelation.AddUserPackageRelation(user); try { Domain.Socioboard.Domain.Groups groups = AddGroupByUserId(user.Id); BusinessSettingRepository busnrepo = new BusinessSettingRepository(); BusinessSetting.AddBusinessSetting(user.Id, groups.Id, groups.GroupName); Team.AddTeamByGroupIdUserId(user.Id, user.EmailId, groups.Id); UpdateTeam(EmailId, user.Id.ToString(), user.UserName); } catch (Exception ex) { Console.WriteLine(ex.Message); logger.Error("Error : " + ex.Message); logger.Error("Error : " + ex.StackTrace); } //MailSender.SendEMail(user.UserName, Password, EmailId); return(new JavaScriptSerializer().Serialize(user)); } else { return("Email Already Exists"); } } catch (Exception ex) { Console.WriteLine(ex.StackTrace); return("Something Went Wrong"); } }
/// <summary> /// 新增用户 /// </summary> /// <param name="user">用户</param> /// <returns>用户ID</returns> public OutputBase Add(User user) { var id = _userRepository.Add(user); return(_unitWork.Commit() ? OutputBase.Success("新增成功") : OutputBase.Fail("新增失败")); }
public override void Execute() { base.Execute(); User user; do { Console.WriteLine("Insert the new user's Username:"******"Username is already in use!"); } else { user = new User() { Username = username } }; }while (user.Id != 0); PrintSeparator(); Console.WriteLine("Insert the new user's Password:"******"======================= Users Roles ======================"); string[] allRoles = Enum.GetNames(typeof(User.Roles)).Where(r => r != User.Roles.Admin.ToString()).ToArray(); for (int i = 0; i < allRoles.Length; i++) { Console.WriteLine(allRoles[i]); } PrintSeparator(); string selectedRole; do { Console.WriteLine("Type the role you want to assign to the user from the roles above."); selectedRole = Console.ReadLine(); }while (!allRoles.Contains(selectedRole)); using (var userRepo = new UserRepository()) { user.Role = selectedRole; userRepo.Add(user); } PrintSuccess($"The user {user.Username} was created successfully"); Console.ReadLine(); new MainMenu(); } }
public void GetUserBySession_WhenValidNoTeacher() { //arrange var options = new DbContextOptionsBuilder <RegistrationContext>() .UseInMemoryDatabase(databaseName: MethodBase.GetCurrentMethod().Name) .Options; using var RSCxt = new RegistrationContext(options); IRSUserRepository userRepository = new UserRepository(RSCxt); IRSCourseRepository courseRepository = new CourseRepository(RSCxt); IRSSessionRepository sessionRepository = new SessionRepository(RSCxt); var Teacher = new UserTO() { Name = "Max", Email = "*****@*****.**", Role = UserRole.Teacher }; var Jack = new UserTO() { Name = "Jack Jack", Email = "*****@*****.**", Role = UserRole.Attendee }; var John = new UserTO() { Name = "John", Email = "*****@*****.**", Role = UserRole.Attendee }; var AddedUser0 = userRepository.Add(Teacher); var AddedUser1 = userRepository.Add(Jack); var AddedUser2 = userRepository.Add(John); RSCxt.SaveChanges(); var SQLCourse = new CourseTO() { Name = "SQL" }; var AddedCourse = courseRepository.Add(SQLCourse); RSCxt.SaveChanges(); var SQLSession = new SessionTO() { Attendees = new List <UserTO>() { AddedUser1, AddedUser0, AddedUser2 }, Course = AddedCourse, Teacher = null, }; var AddedSession = sessionRepository.Add(SQLSession); RSCxt.SaveChanges(); //act //assert Assert.AreEqual(3, userRepository.GetAll().Count()); Assert.AreEqual(3, userRepository.GetUsersBySession(AddedSession).Count()); }
public void Add(User item) { UserRepository.Add(item); }
public async Task<dynamic> Register([FromBody] JToken jsonbody) { //validate data if (jsonbody == null || jsonbody.Type != JTokenType.Object) throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid data.")); var email = jsonbody.SelectToken("email"); if (email == null || string.IsNullOrWhiteSpace(email.ToString())) throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "email is missed.")); var password = jsonbody.SelectToken("password"); if (password == null || string.IsNullOrWhiteSpace(password.ToString())) throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "password is missed.")); var displayName = jsonbody.SelectToken("displayname"); if (displayName == null || string.IsNullOrWhiteSpace(displayName.ToString())) throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "displayname is missed.")); //check if user exists or not var userRepo = new UserRepository(); var userEntity = await userRepo.GetByEmail(email.ToString()); if (userEntity != null) throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "User exists already.")); //save to db userEntity = new UserEntity { Password = Encryptor.GetInstance().Encrypt(password.ToString()), DisplayName = displayName.ToString(), Emails = new List<string> {email.ToString()} }; var options = (JObject)jsonbody.SelectToken("options"); if (options != null ) { userEntity.Options = new Dictionary<string, string>(); foreach (var jProperty in options.Properties()) { userEntity.Options.Add(jProperty.Name, jProperty.Value.ToString()); } } userRepo.Add(userEntity); return Ok(new { id = userEntity.ID }); }
public void Register(User user) { if (user == null) throw new ArgumentNullException("user"); using (UserRepository userRepository = new UserRepository()) { if (userRepository.CheckAccountExistByName(user.UserName)) { // throw account name exists exception throw new AccountIsExistException(string.Format(Resource.UserMessages.ex_AccountExist, user.UserName)); } var accounts = userRepository.GetFiltered(a => a.Email == user.Email); if (accounts.Count<User>() > 0) { // throw email exists exception throw new AccountEmailExistException(string.Format(Resource.UserMessages.ex_EmailExist, user.Email)); } userRepository.Add(user); userRepository.Commit(); } }
public void Should_Return_True_When_Item_Removed() { var options = new DbContextOptionsBuilder <RegistrationContext>() .UseInMemoryDatabase(databaseName: MethodBase.GetCurrentMethod().Name) .Options; using (var context = new RegistrationContext(options)) { IRSUserRepository userRepository = new UserRepository(context); IRSSessionRepository sessionRepository = new SessionRepository(context); IRSCourseRepository courseRepository = new CourseRepository(context); var Teacher = new UserTO() { //Id = 420, Name = "Christian", Email = "*****@*****.**", Role = UserRole.Teacher }; var Michou = new UserTO() { //Id = 45, Name = "Michou Miraisin", Email = "*****@*****.**", Role = UserRole.Attendee }; var AddedTeacher = userRepository.Add(Teacher); var AddedAttendee = userRepository.Add(Michou); context.SaveChanges(); var SQLCourse = new CourseTO() { //Id = 28, Name = "SQL" }; var AddedCourse = courseRepository.Add(SQLCourse); context.SaveChanges(); var SQLSession = new SessionTO() { //Id = 1, Attendees = new List <UserTO>() { AddedAttendee }, Course = AddedCourse, Teacher = AddedTeacher, }; var AddedSession = sessionRepository.Add(SQLSession); context.SaveChanges(); Assert.AreEqual(1, sessionRepository.GetAll().Count()); var RemovedSession = sessionRepository.Remove(1); context.SaveChanges(); Assert.AreEqual(0, sessionRepository.GetAll().Count()); } }
public User PostUser(User user) { UserRepository.Add(user); return(user); }
public static string Add(User user) { return(UserRepository.Add(user)); }
public void GetAllReservationsTestForMultipleReservations() { repoUser.Clear(); repoRooms.Clear(); DALFacade testDALFacade = new DALFacade(); string username1 = "matt2694"; string building1 = "C"; string floorNr1 = "4"; string nr1 = "1000"; string dateFrom1 = "2017-05-05 18:00:00.00"; string dateTo1 = "2017-05-05 19:00:00.00"; string peopleNr1 = "1"; string username2 = "matt2694"; string building2 = "C"; string floorNr2 = "4"; string nr2 = "1000"; string dateFrom2 = "2017-05-06 18:00:00.00"; string dateTo2 = "2017-05-06 19:00:00.00"; string peopleNr2 = "1"; string username3 = "matt2694"; string building3 = "C"; string floorNr3 = "4"; string nr3 = "1000"; string dateFrom3 = "2017-05-07 18:00:00.00"; string dateTo3 = "2017-05-07 19:00:00.00"; string peopleNr3 = "1"; List <Dictionary <string, string> > resultdReservationsInfo = new List <Dictionary <string, string> >(); Dictionary <string, string> oneReservation1 = new Dictionary <string, string>(); Dictionary <string, string> oneReservation2 = new Dictionary <string, string>(); Dictionary <string, string> oneReservation3 = new Dictionary <string, string>(); oneReservation1.Add("Username", username1); oneReservation1.Add("Building", building1); oneReservation1.Add("FloorNr", floorNr1); oneReservation1.Add("Nr", nr1); oneReservation1.Add("DateFrom", dateFrom1); oneReservation1.Add("DateTo", dateTo1); oneReservation1.Add("PeopleNr", peopleNr1); oneReservation2.Add("Username", username2); oneReservation2.Add("Building", building2); oneReservation2.Add("FloorNr", floorNr2); oneReservation2.Add("Nr", nr2); oneReservation2.Add("DateFrom", dateFrom2); oneReservation2.Add("DateTo", dateTo2); oneReservation2.Add("PeopleNr", peopleNr2); oneReservation3.Add("Username", username3); oneReservation3.Add("Building", building3); oneReservation3.Add("FloorNr", floorNr3); oneReservation3.Add("Nr", nr3); oneReservation3.Add("DateFrom", dateFrom3); oneReservation3.Add("DateTo", dateTo3); oneReservation3.Add("PeopleNr", peopleNr3); resultdReservationsInfo.Add(oneReservation1); resultdReservationsInfo.Add(oneReservation2); resultdReservationsInfo.Add(oneReservation3); DateTime testDateFrom1 = new DateTime(2017, 05, 05, 18, 00, 00, 00); DateTime testDateTo1 = new DateTime(2017, 05, 05, 19, 00, 00, 00); DateTime testDateFrom2 = new DateTime(2017, 05, 06, 18, 00, 00, 00); DateTime testDateTo2 = new DateTime(2017, 05, 06, 19, 00, 00, 00); DateTime testDateFrom3 = new DateTime(2017, 05, 07, 18, 00, 00, 00); DateTime testDateTo3 = new DateTime(2017, 05, 07, 19, 00, 00, 00); IUser testUser = new User(username1, "*****@*****.**", Permission.Student); IRoom testRoom = new Room('C', 4, 1000, 20, Permission.Student); repoUser.Add(testUser); repoRooms.Add(testRoom); Reservation expectedReservation1 = new Reservation(testUser, testRoom, 1, testDateFrom1, testDateTo1); Reservation expectedReservation2 = new Reservation(testUser, testRoom, 1, testDateFrom2, testDateTo2); Reservation expectedReservation3 = new Reservation(testUser, testRoom, 1, testDateFrom3, testDateTo3); var mock = new Mock <DAL.IReservationsForMocking>(); mock.Setup(reservationsMock => reservationsMock.GetAllReservationsFromDatabase()).Returns(() => resultdReservationsInfo); List <Reservation> returnedReservation = testDALFacade.ConvertFromStringsToReservationObjects(mock.Object.GetAllReservationsFromDatabase()); Assert.IsTrue(expectedReservation1.Equals(returnedReservation[0]) && expectedReservation2.Equals(returnedReservation[1]) && expectedReservation3.Equals(returnedReservation[2])); }
public void Add(User user) { _repo.Add(user); }
public void WhenUserAdded_ThenUpdatesRepository() { DatabaseTestUtility.DropCreateFirebrickDatabase(); var repository = new UserRepository(new DatabaseFactory()); var newUser = new User { DisplayName = "name", Country = "United States", PostalCode = "a1b2c3", Password = "******", UserName = "******" }; repository.Add(newUser); repository.Commit(); List<User> actualList = repository.GetAll().ToList(); Assert.Equal(1, actualList.Count); Assert.Equal(newUser.DisplayName, actualList[0].DisplayName); }
//public void Add(User user, Account account) //{ // _repoUser.Add(user, account); //MembershipCreateStatus status; //Membership.CreateUser( // user.Account.UserName, // user.Account.Password, // user.Email, // user.Account.Question, // user.Account.Answer, // true, // out status); //if (status == MembershipCreateStatus.Success) //{ // user.Account.User = user; // _repoUser.Add(user); // _accountRepo.Add(user.Account); // _userRepo.Update(user); // UserMap.MapDomainToDto(user, obj); // //} //} public void Add(User user) { //user.MembershipUsername = membershipUsername; _repoUser.Add(user); }
public async Task <ActionResult> Add(User user) { await userRepository.Add(user); return(RedirectToAction("User-List")); }
public async Task <IActionResult> Add(AddUserRequest model) { var record = await _userRepository.Add(model, UserRoleEnum.Salesman); return(Ok(new { userId = record })); }
public bool Add(User suser) { return(_userRepository.Add(suser)); }
public JsonResult AddUserRelation(User user) { try { //////// validation if (!Utilities.IsRequiredStringInputsValid(user.Name, user.Family, user.NationalCode, user.Username, user.Password)) { return(Json(new JsonData() { Success = false, Script = MessageBox.Show("فیلدهای ستاره دار را بدرستی وارد کنید", MessageType.Error).Script, Html = "" })); } user.Status = "فعال"; user.Password = user.Password.Encrypt(); user.ConfirmPassword = user.Password; user.Name = user.Name.ToFarsiString().Trim(); user.Family = user.Family.ToFarsiString().Trim(); user.FatherName = (string.IsNullOrEmpty(user.FatherName) ? null : user.FatherName.ToFarsiString().Trim()); user.NationalCode = user.NationalCode.ToFarsiString().Trim(); user.IdNo = (string.IsNullOrEmpty(user.IdNo) ? null : user.IdNo.ToFarsiString().Trim()); user.Mobile = (string.IsNullOrEmpty(user.Mobile) ? null : user.Mobile.ToFarsiString().Trim()); user.Tel = (string.IsNullOrEmpty(user.Tel) ? null : user.Tel.ToFarsiString().Trim()); user.Username = user.Username.ToFarsiString().Trim(); if (user.BirthDate != null) { user.BirthDate = Convert.ToDateTime(user.BirthDate).ToMiladiDate(); } ////////////// if (ModelState.IsValid) { string message = ""; if (blUser.Add(user, out message)) { return(Json(new { UserId = blUser.Where(p => p.Username == user.Username).Single().Id, Success = true, })); } else { if (message.Contains("Users(Username Must Unique)")) { return(Json(new JsonData() { Success = false, Script = MessageBox.Show("نام کاربری باید یکتا باشد", MessageType.Error).Script, Html = "" })); } return(Json(new JsonData() { Success = false, Script = MessageBox.Show("خطا رخ داده است. مجددا تلاش کنید", MessageType.Error).Script, Html = "" })); } } else { return(Json(new JsonData() { Success = false, Script = MessageBox.Show("خطا رخ داده است. مجددا تلاش کنید", MessageType.Error).Script, Html = "" })); } } catch { return(Json(new JsonData() { Success = false, Script = MessageBox.Show("خطا رخ داده است. مجددا تلاش کنید", MessageType.Error).Script, Html = "" })); } }
private void OnRegister(object obj) { if (string.IsNullOrWhiteSpace(Firstname)) { Error = "Enter a firstname."; ErrorVisibility = Visibility.Visible; return; } if (string.IsNullOrWhiteSpace(Lastname)) { Error = "Enter a lastname."; ErrorVisibility = Visibility.Visible; return; } if (string.IsNullOrWhiteSpace(Username)) { Error = "Enter a username."; ErrorVisibility = Visibility.Visible; return; } PasswordBox passwordBox = obj as PasswordBox; string password = passwordBox.Password; var salt = HashUtils.GetSalt(); var passwordHash = HashUtils.ComputeHashSha256( Encoding.UTF8.GetBytes( password + Convert.ToBase64String(salt) ) ); password = string.Empty; Guid gAddress = Guid.NewGuid(); User user = new User { Firstname = Firstname, Lastname = Lastname, Username = Username, Password = Convert.ToBase64String(passwordHash), Salt = Convert.ToBase64String(salt), Address = gAddress.ToString("N"), Timestamp = DateTime.Now }; userRepo.Add(user); DigitalSignatureUtils.AssignKeyPair(user.Address); dialogCoordinator.ShowMessageAsync( this, "Register Successful", "Your private key has been generated and you should keep it for yourself at ALL times." ); Firstname = string.Empty; Lastname = string.Empty; Username = string.Empty; ViewModelLocator.Main.CurrentViewModel = ViewModelLocator.Login; }
/// <summary> /// 创建一个新用户,此用户待审核 /// </summary> /// <param name="user"></param> /// <returns>是否成功创建</returns> public void NewUser(User user) { if (user == null) { throw new Exception("User对象不允许为空值"); } if (String.IsNullOrEmpty(user.NickName) || String.IsNullOrEmpty(user.RegisterName)|| String.IsNullOrEmpty(user.RealName)|| String.IsNullOrEmpty(user.Password)) { throw new Exception(@"User对象中,NickName,RegisterName,RealName, Password属性不允许为Null或者空字符串"); } bool hasExistRegisterName = Register.HasExistRegisterName(user.RegisterName); bool hasExistNickName = Register.HasExistNickName(user.NickName); if (hasExistRegisterName) { throw new Exception("注册名已存在"); } if (hasExistNickName) { throw new Exception("昵称已存在"); } user.Id = DateTimeHelper.ConvertToIDString(DateTime.Now); user.Createtime = DateTime.Now; //此用户待审核,并未通过审核 user.ApproveStatus = EnumUserApproveStatus.UnApproved; using (UserRepository userRepository = new UserRepository()) { userRepository.Add(user); } }
public void Should_Return_One_User_After_Removing_User() { var options = new DbContextOptionsBuilder <RegistrationContext>() .UseInMemoryDatabase(databaseName: MethodBase.GetCurrentMethod().Name) .Options; using (var context = new RegistrationContext(options)) { IRSUserRepository userRepository = new UserRepository(context); IRSSessionRepository sessionRepository = new SessionRepository(context); IRSCourseRepository courseRepository = new CourseRepository(context); var Teacher = new UserTO() { Name = "Christian", Email = "*****@*****.**", Role = UserRole.Teacher, }; var Michou = new UserTO() { Name = "Michou Miraisin", Email = "*****@*****.**", Role = UserRole.Attendee, }; var Isabelle = new UserTO() { Name = "Isabelle Balkany", Email = "*****@*****.**", Role = UserRole.Attendee, }; var AddedTeacher = userRepository.Add(Teacher); var AddedAttendee = userRepository.Add(Michou); var AddedAttendee2 = userRepository.Add(Isabelle); context.SaveChanges(); var SQLCourse = new CourseTO() { Name = "SQL" }; var AddedCourse = courseRepository.Add(SQLCourse); context.SaveChanges(); var SQLSession = new SessionTO() { Attendees = new List <UserTO>() { AddedAttendee, AddedAttendee2 }, Course = AddedCourse, Teacher = AddedTeacher, }; var AddedSession = sessionRepository.Add(SQLSession); context.SaveChanges(); Assert.AreEqual(2, sessionRepository.GetStudents(AddedSession).Count()); AddedSession.Attendees.Remove(AddedAttendee); Assert.AreEqual(1, AddedSession.Attendees.Count()); AddedSession = sessionRepository.Update(AddedSession); context.SaveChanges(); Assert.AreEqual(1, sessionRepository.GetStudents(AddedSession).Count()); } }
public static void Main(string[] args) { var newProduct1 = new Product { Name = "firstProduct" }; var newProduct2 = new Product() { Name = "secondProduct" }; var newCustomer1 = new Customer() { Name = "firstCustomer", Email = "*****@*****.**", Adress = "sadsaswwww", Id = Guid.NewGuid(), PhoneNumber = "0742757942" }; var newCustomer2 = new Customer() { Name = "secondCustomer", Email = "*****@*****.**", Adress = "sdsaswwww", Id = Guid.NewGuid(), PhoneNumber = "0742757942" }; var newCustomer3 = new Customer() { Name = "thirdCustomer", Email = "*****@*****.**", Adress = "sadsasww", Id = Guid.NewGuid(), PhoneNumber = "0742757942" }; using (var dbCtx1 = new DbEntities()) { var productRepo = new ProductRepository <Product>(dbCtx1); var customerRepo = new CustomerRepository <Customer>(dbCtx1); productRepo.Add(newProduct1); productRepo.Add(newProduct2); customerRepo.Add(newCustomer1); customerRepo.Add(newCustomer2); customerRepo.Add(newCustomer3); var numberOfProducts = dbCtx1.Products.Count(); var numberOfCustomers = dbCtx1.Customers.Count(); Console.WriteLine("Number of Customers: " + numberOfCustomers); Console.WriteLine("Number of Products: " + numberOfProducts); } using (var dbCtx2 = new DbEntities()) { var userRepo = new UserRepository <User>(dbCtx2); var organisationRepo = new OrganizationRepository <Organization>(dbCtx2); for (int i = 0; i < 10; ++i) { userRepo.Add(new User() { Id = Guid.NewGuid(), FirstName = "asda", LastName = "SdSDS" }); } for (int i = 0; i < 5; ++i) { organisationRepo.Add(new Organization() { Id = Guid.NewGuid(), Name = "dasxx", Description = "trololololoool" }); } } using (var dbCtx3 = new DbEntities()) { //var userRepo = new UserRepository<User>(dbCtx3); //var organisationRepo = new OrganizationRepository<Organization>(dbCtx3); foreach (var user in dbCtx3.Users) { Console.WriteLine(user.FirstName + " " + user.LastName); } foreach (var org in dbCtx3.Organizations) { Console.WriteLine(org.Name + " " + org.Description); } var lazyQuary = dbCtx3.Organizations; foreach (var item in lazyQuary) { Console.WriteLine($"{item.Name} has {item.AssignedUsers.Count} Assigned"); } var eagerQuary = dbCtx3.Organizations.Include("AssignedUsers"); foreach (var item in eagerQuary) { Console.WriteLine($"{item.Name} has {item.AssignedUsers.Count} Assigned"); } var explicitQuary = dbCtx3.Organizations.Include("AssignedUsers"); foreach (var item in explicitQuary) { var users = dbCtx3.Entry(item).Collection(c => c.AssignedUsers); if (!users.IsLoaded) { users.Load(); } Console.WriteLine($"{item.Name} has {item.AssignedUsers.Count} Assigned"); } Console.ReadLine(); } }
public ActionResult Register(UserRegister userReg) { userRsy = new UserRepository(); if (userRsy.Exists(userReg.UserName)) { ModelState.AddModelError("UserName", "用户名已存在"); return View(); } User _user = userReg.GetUser(); _user.RegTime = System.DateTime.Now; if (userRsy.Add(_user)) { Notice _n = new Notice { Title = "注册成功", Details = "您已经成功注册,用户为:" + _user.UserName + " ,请牢记您的密码!", DwellTime = 5, NavigationName = "登陆页面", NavigationUrl = Url.Action("Login", "User") }; return RedirectToAction("Notice", "Prompt", _n); } else { Error _e = new Error { Title = "注册失败", Details = "在用户注册时,发生了未知错误", Cause = "系统错误", Solution = Server.UrlEncode("<li>返回<a href='" + Url.Action("Register", "User") + "'>注册</a>页面,输入正确的信息后重新注册</li><li>联系网站管理员</li>") }; return RedirectToAction("Error", "Prompt", _e); } }
public void TestGet_InvalidPositiveId_ShouldReturnNull() { // Arrange var roomsRepo = new UserRepository(); roomsRepo.Add(new User("username1", "password123", Roles.User)); roomsRepo.Add(new User("username2", "password123", Roles.VenueAdmin)); roomsRepo.Add(new User("username3", "password123", Roles.User)); // Act var user = roomsRepo.Get(4); // Assert Assert.IsNull(user); }
public void Add_User(object s, EventArgs e) { Utility Util = new Utility(); if (Page.IsValid) { UserRepository User = new UserRepository(); User.UserName = Util.FormatTextForInput(Request.Form[Username.UniqueID]); User.Password = Encryption.Encrypt(Util.FormatTextForInput(Request.Form[Password1.UniqueID])); User.Email1 = Util.FormatTextForInput(Request.Form[Email.UniqueID]); User.FirstName = Util.FormatTextForInput(Request.Form[Firstname.UniqueID]); User.LastName = Util.FormatTextForInput(Request.Form[Lastname.UniqueID]); User.SetSex = Request.Form[RadioButtonSex.UniqueID]; User.CityID = 1; User.StateID = 8; User.CountryID = 18; /*User.CityID = Int16.Parse(Request.Form[City.UniqueID]); User.StateID = Int16.Parse(Request.Form[State.UniqueID]); User.CountryID = Int16.Parse(Request.Form[Cntry.UniqueID]);*/ User.DOB = DateTime.Parse(Date1.CalendarDateString); if (Int32.Parse(Request.Form[Newsletter.UniqueID]) == 1) { User.canEmailSend = true; } else User.canEmailSend = false; User.ECPreference = ""; for (int i = 0; i < ExamCategoryList.Items.Count; i++) { if (ExamCategoryList.Items[i].Selected) { if (User.ECPreference.Length > 0) User.ECPreference += ","; User.ECPreference += ExamCategoryList.Items[i].Value; } } User.Mobile = Util.FormatTextForInput(Request.Form[Mobile.UniqueID]); User.Address = Util.FormatTextForInput(Request.Form[Address.UniqueID]); //User.ContactMe = Int32.Parse(Util.FormatTextForInput(Request.Form[ContactMe.UniqueID])); User.Website = Util.FormatTextForInput(Request.Form[Website.UniqueID]); User.AboutMe = Util.FormatTextForInput(Request.Form[AboutMe.UniqueID]); //User.GUID = Guid.NewGuid().ToString("N"); //Prevent username and email duplication. Ensure that all username and email in the database are unique. //This initialize the value. UserNameAndEmailValidation.Param(User.UserName, User.Email1); #region Form Input Validation //Handles validation of username and email. This prevent duplication. if (!UserNameAndEmailValidation.IsValid) { lbvalenght.Text = UserNameAndEmailValidation.ErrMsg; lbvalenght.Visible = true; txtsecfield.Text = ""; return; } if (!Validator.IsValidUserName(User.UserName)) { lbvalenght.Text = "<br>Error: Username must be at least 6 characters long and 15 characters maximun, and should only contain AlphaNumeric."; lbvalenght.Visible = true; txtsecfield.Text = ""; return; } //Let's decrypt the password for validation. if (!Validator.IsValidPassword(Encryption.Decrypt(User.Password))) { lbvalenght.Text = "<br>Error: Password must be at least 6 characters long and 12 characters maximun, and should only contain AlphaNumeric."; lbvalenght.Visible = true; txtsecfield.Text = ""; return; } //Let's decrypt the password for validation. if (Util.FormatTextForInput(Request.Form[Password1.UniqueID]) != Util.FormatTextForInput(Request.Form[Password2.UniqueID])) { lbvalenght.Text = "<br>Error: Password did not matach. Please re-enter a password and make sure they both match."; lbvalenght.Visible = true; txtsecfield.Text = ""; return; } if (!Validator.IsValidEmail(User.Email1)) { lbvalenght.Text = "<br>Error: Invalid email address. Email address must be a valid format."; lbvalenght.Visible = true; txtsecfield.Text = ""; return; } if (!Validator.IsValidName(User.FirstName)) { lbvalenght.Text = "<br>Error: Firstname should be alphabet and not contain illegal characters."; lbvalenght.Visible = true; txtsecfield.Text = ""; return; } if (!Validator.IsValidName(User.LastName)) { lbvalenght.Text = "<br>Error: Firstname should be alphabet and not contain illegal characters."; lbvalenght.Visible = true; txtsecfield.Text = ""; return; } if (User.CountryID == null) { lbvalenght.Text = "<br>Error: You must select a country."; lbvalenght.Visible = true; txtsecfield.Text = ""; return; } if (User.AboutMe.Length > 500) { lbvalenght.Text = "<br>Error: About me text is too long. Maximum of 500 characters."; lbvalenght.Visible = true; txtsecfield.Text = ""; return; } if (User.Website.Length > 75) { lbvalenght.Text = "<br>Error: Website URL is too long. Maximum of 75 characters."; lbvalenght.Visible = true; txtsecfield.Text = ""; return; } if (Request.Form[txtsecfield.UniqueID] != this.securecode) { lbvalenght.Text = "<br>Error: Security Code Does not Match."; lbvalenght.Visible = true; txtsecfield.Text = ""; return; } #endregion if (UserImageFileUpload.HasFile) { int FileSize = UserImageFileUpload.PostedFile.ContentLength; string contentType = UserImageFileUpload.PostedFile.ContentType; //File type validation if (!contentType.Equals("image/gif") && !contentType.Equals("image/jpeg") && !contentType.Equals("image/jpg") && !contentType.Equals("image/png")) { lbvalenght.Text = "<br>File format is invalid. Only gif, jpg, jpeg or png files are allowed."; lbvalenght.Visible = true; return; } // File size validation if (FileSize > constant.UserImageMaxSize) { lbvalenght.Text = "<br>File size exceed the maximun allowed 60000 bytes"; lbvalenght.Visible = true; return; } } //ImageUploadManager.UploadUserImage(User, PlaceHolder1, GetUserImage.ImagePathForUserPhoto, constant.UserImageMaxSize); if (User.Add(User) != 0) { JSLiteral.Text = "Error occured while processing your submit."; return; } //EmailAccountActivationLink(User); //Create login session variable. During registration we never create login in cookies as we have not asked his permission CookieLoginHelper.CreateLoginSession(Util.FormatTextForInput(Request.Form[Username.UniqueID]), Util.FormatTextForInput(Request.Form[Password1.UniqueID])); User = null; Response.Redirect("/User/" + Util.FormatTextForInput(Request.Form[Username.UniqueID])); } else { JSLiteral.Text = Util.JSAlert("Invalid security code. Make sure you type it correctly."); return; lblinvalidsecode.Text = "Invalid security code. Make sure you type it correctly."; lblinvalidsecode.Visible = true; } Util = null; }
protected void txtSubmit_ServerClick(object sender, EventArgs e) { try { using (UserRepository repository = new UserRepository()) { if (!repository.CheckUserisExistOrNot(txtUserName.Value.Trim())) { if (!repository.IsEmailIsExists(txtUserName.Value.Trim())) { string activationCode = Guid.NewGuid().ToString(); Users newUsers = new Users { AlternateNumber = txtalNumber.Value.Trim(), EmailId = txtAddress.Value.Trim(), FirstName = txtfirstname.Value.Trim(), IsFollowUp = chkFollowUp.Checked, LastName = txtlastname.Value.Trim(), MobileNumber = txtMobileNumber.Value.Trim(), Password = txtpassword.Value.Trim(), RegistrationDate = System.DateTime.Now, RoleId = (int)EnumAccountType.User, Status = false, UserName = txtUserName.Value.Trim(), ActivationCode = activationCode }; newUsers = repository.Add(newUsers); if (chkAddress.Checked) { int type = rbtHome.Checked ? 1 : rbtOffice.Checked ? 2 : 3; EnumAddressType addressType = (EnumAddressType)type; AddressDetails newAddress = new AddressDetails(); newAddress.UserId = newUsers.UserId; newAddress.Address = txtAddress.Value.Trim(); newAddress.Landmark = txtLandmark.Value.Trim(); newAddress.Direction = txtDirection.Value.Trim(); newAddress.CityId = Convert.ToInt32(ddlCity.SelectedValue.Trim()); newAddress.AreaId = Convert.ToInt32(ddlArea.SelectedValue.Trim()); newAddress.CountryId = Convert.ToInt32(ddlCountry.SelectedValue.Trim()); newAddress.Pincode = txtPincode.Value.Trim(); newAddress.AddressTypeId = (int)addressType; if (rbtOffice.Checked || rbtOther.Checked) { newAddress.OtherAddress = txtOther.Value.Trim(); } else { newAddress.OtherAddress = "NA"; } newAddress.IsDefault = true; using (AddressRepository addressRepository = new AddressRepository()) addressRepository.Add(newAddress); } // Send varification email for registration. string url = string.Empty; url = Request.Url.AbsoluteUri.Replace("Register", "VerifyEmailAddress.aspx?ActivationCode=" + activationCode.ToString()); if (Request.Url.AbsoluteUri.Contains(".aspx")) { Request.Url.AbsoluteUri.Replace("Register.aspx", "VerifyEmailAddress.aspx?ActivationCode=" + activationCode.ToString()); } string sBody = string.Empty; sBody = "Hello " + newUsers.UserName.Trim() + ","; sBody += "<br /><br />Please click the following link to activate your account"; sBody += "<br /><a href = '" + url + "'>Click here to activate your account.</a>"; sBody += "<br /><br />Thanks"; EmailHelper.SendMail("", newUsers.EmailId, "Account Activation", sBody); this.ShowSuccessfulNotification("Your registration successful. Activation email has been sent to your register email address."); } else { this.ShowErrorNotification("Email address is already exists, Please register with another email address."); } } else { this.ShowErrorNotification("Username is already exists, Please select another username."); } } } catch (Exception ex) { this.ShowErrorNotification("Error in txtSubmit_ServerClick : " + ex.Message.ToString()); } }
private static void AddOrUpdateTheUser(User user, UserRepository userRepository) { var existingUser = userRepository.GetUserByGoogleId(user.GoogleId); if (existingUser == null) { user.CreateDate = DateTimeOffset.Now; userRepository.Add(user); } else { if (existingUser.DisplayName != user.DisplayName || existingUser.GivenName != user.GivenName || existingUser.FamilyName != user.FamilyName || existingUser.Link != user.Link || existingUser.Picture != user.Picture || existingUser.Gender != user.Gender || existingUser.Locale != user.Locale) { existingUser.DisplayName = user.DisplayName; existingUser.GivenName = user.GivenName; existingUser.FamilyName = user.FamilyName; existingUser.Link = user.Link; existingUser.Picture = user.Picture; existingUser.Gender = user.Gender; existingUser.Locale = user.Locale; existingUser.UpdateDate = DateTimeOffset.Now; userRepository.Update(existingUser); } } }
public void Should_Return_2_Session() { var options = new DbContextOptionsBuilder <RegistrationContext>() .UseInMemoryDatabase(databaseName: MethodBase.GetCurrentMethod().Name) .Options; using (var context = new RegistrationContext(options)) { IRSUserRepository userRepository = new UserRepository(context); IRSSessionRepository sessionRepository = new SessionRepository(context); IRSCourseRepository courseRepository = new CourseRepository(context); var Teacher = new UserTO() { //Id = 420, Name = "Christian", Email = "*****@*****.**", Role = UserRole.Teacher }; var Michou = new UserTO() { //Id = 45, Name = "Michou Miraisin", Email = "*****@*****.**", Role = UserRole.Attendee }; var Isabelle = new UserTO() { Name = "Isabelle Balkany", Email = "*****@*****.**", Role = UserRole.Attendee }; var AddedTeacher = userRepository.Add(Teacher); var AddedAttendee = userRepository.Add(Michou); var AddedAttendee2 = userRepository.Add(Isabelle); context.SaveChanges(); var SQLCourse = new CourseTO() { Name = "SQL" }; var MVCCourse = new CourseTO() { Name = "MVC" }; var AddedCourse = courseRepository.Add(SQLCourse); var AddedCourse2 = courseRepository.Add(MVCCourse); context.SaveChanges(); var SQLSession = new SessionTO() { Attendees = new List <UserTO>() { AddedAttendee }, Course = AddedCourse, Teacher = AddedTeacher, SessionDays = new List <SessionDayTO>() { new SessionDayTO() { Date = new DateTime(2020, 02, 20), PresenceType = SessionPresenceType.MorningAfternoon }, new SessionDayTO() { Date = new DateTime(2020, 02, 21), PresenceType = SessionPresenceType.MorningAfternoon } } }; var MVCSession = new SessionTO() { Attendees = new List <UserTO>() { AddedAttendee2 }, Course = AddedCourse, Teacher = AddedTeacher, SessionDays = new List <SessionDayTO>() { new SessionDayTO() { Date = new DateTime(2020, 03, 20), PresenceType = SessionPresenceType.MorningAfternoon }, new SessionDayTO() { Date = new DateTime(2020, 03, 21), PresenceType = SessionPresenceType.MorningAfternoon } } }; var AddedSession = sessionRepository.Add(SQLSession); context.SaveChanges(); Assert.AreEqual(0, sessionRepository.GetSessionsByDate(new DateTime(2020, 02, 20)).Count()); } }
private static void PerformInitialSetup(IDocumentSession session) { IUserService userService = new UserService(session); if (!userService.DoesUserExistWithUsername("robashton")) { User newUser = new User("robashton", "password"); IUserRepository userRepository = new UserRepository(session); userRepository.Add(newUser); } session.SaveChanges(); }
public async Task <IActionResult> HandleUserEvent(UserEvent evtUser) { try { _logger.LogInformation($"Received: {evtUser.EventType} {evtUser.Id} with version {evtUser.Version}"); // load eventstore version of user var ety = await GetByVersion(evtUser.Id, evtUser.Version); if (null == ety) { return(StatusCode((int)HttpStatusCode.NotFound)); } if (evtUser.EventType.ToLower() == "useradded") { var user = ety.Data; user.Version = ety.Version; await _repository.Add(user); } else if (evtUser.EventType.ToLower() == "userupdated") { // first load current user to check the version var savedUser = await _repository.GetUserById(ety.Data.Id); if (null == savedUser) { // concurrency problem? Maybe the user is still not added // Just return, the request which adds the user is responsible to requeue // newer version return(Ok()); } // check version if (savedUser.Item1.Version >= ety.Version) { // nothing todo, a new version is already available return(Ok()); } // try to update the user var user = ety.Data; user.Version = ety.Version; var result = await _repository.Save(user, savedUser.Item2); if (null == result) { // a changed was already made to the current user (Optimistic Offline Control) // The request that updated the user is responsible to reque newer versions if available return(Ok()); } } else { return(BadRequest("Unknown event type")); } // now check if a new version is available and if so push it // to the loopback queue var latestEty = await GetByLatestVersion(evtUser.Id); if (null == latestEty) { return(Ok()); } if (latestEty.Version > evtUser.Version) { // Todo, push it to the loopback queue var evt = new UserEvent { EventType = "UserUpdated", Version = latestEty.Version, Id = latestEty.ID }; await _daprClient.InvokeBindingAsync(_loopbackQueueOptions.UserOutputBindingName, evt); } return(Ok()); } catch (Exception e) { System.Console.WriteLine(e); return(StatusCode((int)HttpStatusCode.InternalServerError)); } }
public static void FillDb() { using (var context = new BankDbContext()) { Console.WriteLine("ConnectionString\n" + context.Database.Connection.ConnectionString); Console.WriteLine("DataSource\n" + context.Database.Connection.DataSource); Console.WriteLine("ConnectionString\n" + context.Database.Connection.Database); // CLEARS ALL DATA !!! Console.WriteLine("ALL DATA WILL BE DELETED FROM DB NOW!!! ([ENTER] TO PROCEED)"); Console.ReadLine(); //if (!context.Database.Exists()) //{ context.Database.Delete(); context.Database.Create(); //} context.Database.Initialize(true);// Console.WriteLine("Db initialized"); Console.ReadLine(); context.Accounts.RemoveRange(context.Accounts); ///Console.WriteLine("I've successfully completed first db action!"); ///Console.ReadLine(); context.Clients.RemoveRange(context.Clients); context.Credits.RemoveRange(context.Credits); context.CreditTypes.RemoveRange(context.CreditTypes); context.Payments.RemoveRange(context.Payments); context.Requests.RemoveRange(context.Requests); //context.RequestStatuses.RemoveRange(context.RequestStatuses); context.Users.RemoveRange(context.Users); context.SaveChanges(); // CLEARS ALL DATA !!! //var statusRepo = new RequestStatusRepository(context); //var statusCreated = new RequestStatus { Status = "Created" }; //var statusConfirmedByOperator = new RequestStatus { Status = "statusConfirmedByOperator" }; //var statusConfirmedBySse = new RequestStatus { Status = "statusConfirmedBySecurityServiceEmployee" }; ////var statusConfirmed = new RequestStatus { Status = "ConfirmedBy" }; //var statusCreditProvided = new RequestStatus { Status = "statusCreditProvided" }; //var statusDenied = new RequestStatus { Status = "Denied" }; //statusRepo.Add(statusCreated, statusConfirmedByOperator, statusConfirmedByOperator, statusCreditProvided,statusDenied); // context.SaveChanges(); // var confirmedByOperatorStatusId = statusCreditProvided.RequestStatusId; // var createdStatusId = statusCreated.RequestStatusId; // var deinedStatusId = statusDenied.RequestStatusId; var creditShort = new CreditType { Name = "Easy Money", //Type = "" WTF IS TYPE????? TimeMonths = 12, PercentPerYear = 20.0m, Currency = "USD", FinePercent = 40.0m, MinAmount = 200, MaxAmount = 2000, IsAvailable = true }; var creditMedium = new CreditType { Name = "Not So Easy Money", //Type = "" WTF IS TYPE????? TimeMonths = 12 * 2, PercentPerYear = 25.0m, Currency = "USD", FinePercent = 50.0m, MinAmount = 200, MaxAmount = 5000, IsAvailable = true }; var creditLong = new CreditType { Name = "Still Money", //Type = "" WTF IS TYPE????? TimeMonths = 12 * 4, PercentPerYear = 30.0m, Currency = "USD", FinePercent = 60.0m, MinAmount = 200, MaxAmount = 5000, IsAvailable = true }; var creditTypeRepo = new CreditTypeRepository(context); creditTypeRepo.Add(creditShort, creditLong, creditMedium); context.SaveChanges(); var creditEasyId = creditShort.CreditTypeId; var creditMediumId = creditMedium.CreditTypeId; var creditLongId = creditLong.CreditTypeId; var admin = new User { Login = "******", Password = "******", Role = UserRole.Admin, IsActive = true }; var ss = new User // security service employee { Login = "******", Password = "******", Role = UserRole.SecurityServiceEmployee, IsActive = true }; var operator1 = new User // { Login = "******", Password = "******", Role = UserRole.Operator, IsActive = true }; var operator2 = new User // { Login = "******", Password = "******", Role = UserRole.Operator, IsActive = true }; var client1 = new User { Login = "******", Password = "******", Role = UserRole.Client }; var client2 = new User { Login = "******", Password = "******", Role = UserRole.Client }; var client3 = new User { Login = "******", Password = "******", Role = UserRole.Client }; var userRepo = new UserRepository(context); userRepo.Add(admin, ss, operator1, operator2, client1, client2, client3); context.SaveChanges(); var client1Id = client1.UserId; var client2Id = client2.UserId; var client3Id = client3.UserId; var client1Info = new Client { UserId = client1.UserId, Name = "Clientone", LastName = "Clientov", Patronymic = "Clientovich", Birthday = new DateTime(1990, 1, 1), Mobile = "+375441234567", Email = "*****@*****.**", PassportNo = "AB1234567", PassportIdentificationNo = "4123456B124PB7", PassportAuthority = "Ministry of internal affairs", PassportExpirationDate = DateTime.Now.AddYears(6), PlaceOfResidence = "Pushkina st.1 app.18", RegistrationAddress = "Pushkina st.1 app.18" }; var client2Info = new Client { UserId = client2.UserId, Name = "Clienttwo", LastName = "Clientov", Patronymic = "Clientovich", Birthday = new DateTime(1982, 2, 2), Mobile = "+375251234567", Email = "*****@*****.**", PassportNo = "AB1234123", PassportIdentificationNo = "4125552B124PB7", PassportAuthority = "Ministry of internal affairs", PassportExpirationDate = DateTime.Now.AddYears(1), PlaceOfResidence = "Pushkina st.2 app.7", RegistrationAddress = "Pushkina st.2 app.7" }; var client3Info = new Client { UserId = client3.UserId, Name = "Clientthree", LastName = "Clientov", Patronymic = "Clientovich", Birthday = new DateTime(1973, 3, 3), Mobile = "+375291234567", Email = "*****@*****.**", PassportNo = "AB1223331", PassportIdentificationNo = "4129332B124PB3", PassportAuthority = "Ministry of internal affairs", PassportExpirationDate = DateTime.Now.AddYears(6), PlaceOfResidence = "Pushkina st.3 app.24", RegistrationAddress = "Pushkina st.3 app.24" }; var clientRepo = new ClientRepository(context); clientRepo.Add(client1Info, client2Info, client3Info); context.SaveChanges(); var request1client1 = new Request { ClientId = client1Info.ClientId, //RequestStatusId = createdStatusId, Status = RequestStatus.Created, CreditTypeId = creditEasyId, AmountOfCredit = 1000, Salary = 500 }; var request2client1 = new Request { ClientId = client1Info.ClientId, //RequestStatusId = createdStatusId, Status = RequestStatus.Created, OperatorId = operator1.UserId, CreditTypeId = creditMediumId, AmountOfCredit = 1200, Salary = 500 }; var request3client1 = new Request { ClientId = client1Info.ClientId, //RequestStatusId = confirmedByOperatorStatusId, Status = RequestStatus.ConfirmedByOperator, OperatorId = operator1.UserId, CreditTypeId = creditLongId, AmountOfCredit = 1000, Salary = 500 }; var request4client1 = new Request { ClientId = client1Info.ClientId, Status = RequestStatus.ConfirmedByOperator, // createdStatusId, OperatorId = operator1.UserId, CreditTypeId = creditMediumId, AmountOfCredit = 1100, Salary = 500 }; var request5client1 = new Request { ClientId = client1Info.ClientId, //RequestStatusId = createdStatusId, Status = RequestStatus.CreditProvided, OperatorId = operator1.UserId, CreditTypeId = creditLongId, AmountOfCredit = 1300, Salary = 500 }; var request6client1 = new Request { ClientId = client1Info.ClientId, //RequestStatusId = confirmedByOperatorStatusId, Status = RequestStatus.CreditProvided, OperatorId = operator1.UserId, CreditTypeId = creditLongId, AmountOfCredit = 900, Salary = 500 }; var request7client1 = new Request { ClientId = client1Info.ClientId, Status = RequestStatus.ConfirmedBySecurityOfficer, // createdStatusId, OperatorId = operator1.UserId, CreditTypeId = creditLongId, AmountOfCredit = 800, Salary = 500 }; var request8client1 = new Request { ClientId = client1Info.ClientId, //RequestStatusId = confirmedByOperatorStatusId, Status = RequestStatus.CreditProvided, OperatorId = operator1.UserId, CreditTypeId = creditMediumId, AmountOfCredit = 900, Salary = 500 }; var requestRepo = new RequestRepository(context); requestRepo.Add( request1client1, request2client1, request3client1, request4client1, request5client1, request6client1, request7client1, request8client1); context.SaveChanges(); //var acc1 = new Account //Bank Account //{ // ClientId = null, // Balance = 40*1000*1000 //}; var bankAccount = new BankAccount //Bank Account { Balance = 40 * 1000 * 1000, Currency = "USD" }; context.BankAccount = bankAccount; context.SaveChanges(); var acc2 = new Account { ClientId = client1Info.ClientId, Balance = request2client1.AmountOfCredit }; var accountRepo = new AccountRepository(context); accountRepo.Add( /*acc1,*/ acc2); context.SaveChanges(); DateTime dt1 = DateTime.Now.AddDays(-(30 * 4 + 5)); var credit1Client1 = new Credit { AccountId = acc2.AccountId, CreditTypeId = creditLong.CreditTypeId, //ContractNo = 123123, //random RequestId = request5client1.RequestId, //AllreadyPaid = 0, AmountOfPaymentPerMonth = (request5client1.AmountOfCredit / creditLong.TimeMonths) * (1 + creditLong.PercentPerYear / 100 * creditLong.TimeMonths / 12), StartDate = dt1, IsRepaid = false, HasDelays = false, CountFineFromThisDate = dt1.AddDays(30),//DateTime.UtcNow.AddDays(30), //!!! hard-coded!!! AmountToCountFineFromForFirstDelayedMonth = (request5client1.AmountOfCredit / creditLong.TimeMonths) * (1 + creditLong.PercentPerYear / 100 * creditLong.TimeMonths / 12), PaidForFine = 0 }; DateTime dt2 = DateTime.UtcNow.AddDays(-(30 * 50 + 7)); var credit2Client1 = new Credit { AccountId = acc2.AccountId, CreditTypeId = creditLong.CreditTypeId, //ContractNo = 123123, //random RequestId = request6client1.RequestId, //AllreadyPaid = 0, AmountOfPaymentPerMonth = (request6client1.AmountOfCredit / creditLong.TimeMonths) * (1 + creditLong.PercentPerYear / 100 * creditLong.TimeMonths/12), StartDate = dt2, IsRepaid = true, HasDelays = true, CountFineFromThisDate = dt2.AddDays(30), //!!! hard-coded!!! AmountToCountFineFromForFirstDelayedMonth = (request6client1.AmountOfCredit / creditLong.TimeMonths) * (1 + creditLong.PercentPerYear / 100 * creditLong.TimeMonths / 12), PaidForFine = 0 }; var credit3Client1 = new Credit { AccountId = acc2.AccountId, CreditTypeId = creditMedium.CreditTypeId, //ContractNo = 123123, //random RequestId = request8client1.RequestId, //AllreadyPaid = 0, AmountOfPaymentPerMonth = (request8client1.AmountOfCredit / creditMedium.TimeMonths) * (1 + creditMedium.PercentPerYear / 100 * creditMedium.TimeMonths / 12), StartDate = DateTime.Now, IsRepaid = false, HasDelays = true, CountFineFromThisDate = DateTime.Now.AddDays(30), //!!! hard-coded!!! AmountToCountFineFromForFirstDelayedMonth = (request8client1.AmountOfCredit / creditMedium.TimeMonths) * (1 + creditMedium.PercentPerYear / 100 * creditMedium.TimeMonths / 12), PaidForFine = 0 }; request5client1.Credit = credit1Client1; // IMPORTANT do this for 1-1 relationship (exception otherwise) request6client1.Credit = credit2Client1; // IMPORTANT do this for 1-1 relationship (exception otherwise) request8client1.Credit = credit3Client1; // IMPORTANT do this for 1-1 relationship (exception otherwise) var creditRepo = new CreditRepository(context); creditRepo.Add(credit1Client1, credit2Client1, credit3Client1); context.SaveChanges(); /* var payment = new Payment { OperatorId = operator1.UserId, CreditId = credit1Client1.CreditId, //ContractNo = credit1Client1.ContractNo, Amount = 75, Date = credit1Client1.StartDate.AddDays(15) }; //var credit var payRepo = new PaymentRepository(context); payRepo.Add(payment); */ var test = context.BankAccount; //context.RequestStatuses.Where(x => x.Status.Contains("Created")).FirstOrDefault(); //context.RequestStatuses.Add(new RequestStatus { Status = "Created" }); context.SaveChanges(); } }
public ActionResult Cadastro(User usuario) { userRepo.Add(usuario); return(RedirectToAction("Chat", "Home", new { id = userRepo.GetIdByEmail(usuario.Email) })); }
public void Add() { User user = new User { FirstName = "Test", LastName = "User", Username = "******", DateCreated = DateTime.UtcNow, Id = Guid.Parse("270e02a4-baf6-11e9-a2a3-2a2ae2dbcce4") }; Devices retrieveDevice = new Devices { Id = retrieveId, Name = "TestRetrieveDevice", Manufacturer = "RetrieveDevice", Model = "#1-InitialCreation", User = user }; Devices updateDevice = new Devices { Id = updateId, Name = "TestUpdateDevice", Manufacturer = "UpdateMethod", Model = "#1-InitialCreation", User = user }; Devices deleteDevice = new Devices { Id = deleteId, Name = "TestDeleteDevice", Manufacturer = "DeleteMethod", Model = "#1-InitialCreation", User = user }; List <Tasks> tasksList = new List <Tasks>(); tasksList.Add(new Tasks { Id = taskId, Status = Enums.Status.Waiting, TaskType = Enums.TaskType.GetDeviceInfo }); Devices deviceWithTask = new Devices { Id = deviceWithTaskId, Name = "TestDeviceWithTask", Manufacturer = "AddMetehod", Model = "#1-InitialCreation", Tasks = tasksList, User = user }; UserRepository.Add(user, "test"); DeviceRepository.Add(updateDevice); DeviceRepository.Add(retrieveDevice); DeviceRepository.Add(deleteDevice); DeviceRepository.Add(deviceWithTask); int changes = DeviceRepository.SaveChanges(); Assert.Greater(changes, 0); }
public BingoMutation(UserRepository userRepository, GameRepository gameRepository, IChat chat) { //USERS----------------------------------------- Field <UserType>("createUser", arguments: new QueryArguments(new QueryArgument <NonNullGraphType <UserInputType> > { Name = "input" }), resolve: context => { return(userRepository.Add(context.GetArgument <User>("input"))); }); Field <UserType>("updateUser", arguments: new QueryArguments( new QueryArgument <NonNullGraphType <IdGraphType> > { Name = "id" }, new QueryArgument <NonNullGraphType <UserInputType> > { Name = "input" } ), resolve: context => { var id = context.GetArgument <long>("id"); var user = context.GetArgument <User>("input"); return(userRepository.Update(id, user)); }); Field <UserType>("deleteUser", arguments: new QueryArguments(new QueryArgument <NonNullGraphType <IdGraphType> > { Name = "id" }), resolve: context => { return(userRepository.Remove(context.GetArgument <long>("id"))); }); //GAMES----------------------------------------- Field <GameType>("createGame", arguments: new QueryArguments(new QueryArgument <NonNullGraphType <GameInputType> > { Name = "input" }), resolve: context => { return(gameRepository.Add(context.GetArgument <Game>("input"))); }); Field <GameType>("updateGame", arguments: new QueryArguments( new QueryArgument <NonNullGraphType <IdGraphType> > { Name = "id" }, new QueryArgument <NonNullGraphType <GameInputType> > { Name = "input" } ), resolve: context => { var id = context.GetArgument <long>("id"); var game = context.GetArgument <Game>("input"); var updated = gameRepository.Update(id, game).Result; return(chat.AddGame(updated)); }); Field <GameType>("updateGameSync", arguments: new QueryArguments( new QueryArgument <NonNullGraphType <IdGraphType> > { Name = "id" }, new QueryArgument <NonNullGraphType <GameInputType> > { Name = "input" } ), resolve: context => { var id = context.GetArgument <long>("id"); var game = context.GetArgument <Game>("input"); game.Id = id; return(gameRepository.UpdateSync(id, game)); }); Field <GameType>("deleteGame", arguments: new QueryArguments(new QueryArgument <NonNullGraphType <IdGraphType> > { Name = "id" }), resolve: context => { return(gameRepository.Remove(context.GetArgument <long>("id"))); }); Field <GameType>("joinAGame", arguments: new QueryArguments(new QueryArgument <StringGraphType> { Name = "link" }), resolve: context => { var link = context.GetArgument <string>("link"); Game game = gameRepository.GameByLink(link); if (game != null) { game.PlayersNumber = game.PlayersNumber + 1; var updated = gameRepository.UpdateSync(game.Id, game); return(chat.AddGame(updated)); } return(null); }); Field <GameType>("quitTheGame", arguments: new QueryArguments(new QueryArgument <IdGraphType> { Name = "id" }), resolve: context => { var id = context.GetArgument <long>("id"); Game game = gameRepository.Find(id); if (game != null) { if (game.PlayersNumber > 0) { game.PlayersNumber = game.PlayersNumber - 1; } var updated = gameRepository.UpdateSync(game.Id, game); return(chat.AddGame(updated)); } return(null); }); //MESSAGES----------------------------------------- Field <GameType>("addGame", arguments: new QueryArguments(new QueryArgument <GameInputType> { Name = "game" }), resolve: context => { return(chat.AddGame(context.GetArgument <Game>("game"))); }); }
public static void TestAddUser() { var userRepository = new UserRepository(); User user = new User(); user.Id = "No.1"; user.RealName = "mr111"; user.AuthorityCategory = EnumUserCategory.Superman; user.RegisterName = "aswind"; user.NickName = "被惊呆的小伙伴"; user.Password = "******"; user.Createtime = DateTime.Now; UserGroupRepository repository = new UserGroupRepository(); UserGroup group=repository.FindByGroupTitle("R2Team"); // UserGroup group1 = new UserGroup { Id = group.Id }; // userRepository.db.Entry(group1).State = EntityState.Unchanged; // user.ContentGroup = group1; // user.ContentGroup = new UserGroup(); user.ContentGroupId = group.Id; userRepository.Add(user); }
public async Task<ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false); // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); IUserRepository userRepository = new UserRepository(); PlacePick.Model.EntityModel.User userToAdd = new PlacePick.Model.EntityModel.User(); userToAdd.AspNetUserId = user.Id; userRepository.Add(userToAdd); userRepository.Save(); return RedirectToAction("Index", "Home"); } AddErrors(result); } // If we got this far, something failed, redisplay form return View(model); }