public void TestUserManagerIntegrationGetAllUsers() { UserDTO userDTO2 = new UserDTO() { Id = 2, Name = "Bob2" }; userManager.CreateUser(userDTO); userManager.CreateUser(userDTO2); Assert.AreEqual(2, userManager.GetAllUsers().Count()); }
public WorkerStatusDTO ChangeStatus(UserDTO Driver, DriverWorkingStatusEnum newStatus, DateTime? blockTime = null, string message = null) { var driver = Mapper.Map<User>(Driver); var driverStatus = uOW.WorkerStatusRepo.All.Where(o => o.WorkerId == Driver.Id).FirstOrDefault(); if (driverStatus != null) { driverStatus.WorkingStatus = newStatus; if (blockTime != null) driverStatus.BlockTime = blockTime; if (message != null) driverStatus.BlockMessage = message; uOW.WorkerStatusRepo.Update(driverStatus); } else { driverStatus = new WorkerStatus(); driverStatus.WorkerId = Driver.Id; driverStatus.WorkingStatus = newStatus; if (blockTime != null) driverStatus.BlockTime = blockTime; if (message != null) driverStatus.BlockMessage = message; uOW.WorkerStatusRepo.Insert(driverStatus); } uOW.Save(); return Mapper.Map<WorkerStatusDTO>(driverStatus); }
public UserDTO find(string userName, string id) { var obj = (from p in ctx.Users where p.userName == @userName && p.id == @id select p).Single(); UserDTO add = new UserDTO(); add.userName = obj.userName; add.id = obj.id; add.fullName = obj.fullName; add.nickName = obj.nickName; add.gender = obj.gender; add.race = obj.race; add.disabled = obj.disabled; add.citizenship = obj.citizenship; add.idType = obj.idType; add.license = obj.license; add.basicEducation = obj.basicEducation; add.higherEducation = obj.higherEducation; add.language = obj.language; add.residentialAddress = obj.residentialAddress; add.postalAddress = obj.postalAddress; add.employed = obj.employed; add.employmentHistory = obj.employmentHistory; return add; }
public bool AuthenticateUser(string username, string password) { bool ret = false; try { UserDTO user = new UserDTO(username, password); string authenticationMessage = null; UserDTO systemUser = UserDTO.Authenticate(user, out authenticationMessage); if (systemUser != null) { _loginView.ClientSession[Constants.SESSION_KEY_USER] = systemUser; _loginView.ClientSession[Constants.SESSION_KEY_USERNAME] = systemUser.Id; ret = true; } else { ret = false; _loginView.ClientSession[Constants.SESSION_KEY_USER] = null; _loginView.ClientSession[Constants.SESSION_KEY_USERNAME] = null; if (authenticationMessage != null) _loginView.MessageText = authenticationMessage; } } catch (Exception ex) { throw ex; } return ret; }
public WorkerStatusDTO GetStatus(UserDTO Driver) { var driver = Mapper.Map<User>(Driver); var driverStatus = uOW.WorkerStatusRepo.All.Where(o => o.WorkerId == Driver.Id).FirstOrDefault(); return Mapper.Map<WorkerStatusDTO>(driverStatus); }
public List<UserDTO> findAll() { var objs = (from p in ctx.Users select p); UserDTO add = null; List<UserDTO> addList = new List<UserDTO>(); foreach (User obj in objs) { add = new UserDTO(); add.userName = obj.userName; add.id = obj.id; add.fullName = obj.fullName; add.nickName = obj.nickName; add.gender = obj.gender; add.race = obj.race; add.disabled = obj.disabled; add.citizenship = obj.citizenship; add.idType = obj.idType; add.license = obj.license; add.basicEducation = obj.basicEducation; add.higherEducation = obj.higherEducation; add.language = obj.language; add.residentialAddress = obj.residentialAddress; add.postalAddress = obj.postalAddress; add.employed = obj.employed; add.employmentHistory = obj.employmentHistory; addList.Add(add); } return addList; }
public void ChangeUserParameters(UserDTO user) { var role = GerRoleForUser(user); user.Role = role; user.RoleId = role.Id; UpdateUser(user); }
public static User MapFromDTO(UserDTO dto) { User user = new User(); user.UserID = dto.UserID; user.UserName = dto.UserName; user.Department = dto.DepartmentID == null? null:ManagerFactory.DepartmentManager.GetDepartment(dto.DepartmentID); user.Role = dto.RoleId == null ? null : ManagerFactory.RoleManager.GetRole(dto.RoleId); return user; }
private static User UserDtoToUser(UserDTO userDTO) { User user = null; if (userDTO != null) { user = new User(userDTO.UserID, userDTO.UserLogin); } return user; }
public static UserDTO UserToUserDTO(User user) { UserDTO userDAO = null; if (user != null) { userDAO = new UserDTO(user.UserID, user.UserLogin); } return userDAO; }
private void singin_btn_Click(object sender, EventArgs e) { UsersDAL user = new UsersDAL(); UserDTO dto = new UserDTO(); dto = user.GetUserByLoginPassword(dto.login, dto.password); if (dto.id_user != 0) { MagorPage m = new MagorPage(); m.Show(); } }
public static UserDTO MapToDTO(User model ) { UserDTO dto = new UserDTO(); dto.UserID = model.UserID; dto.UserName = model.UserName; dto.DepartmentID = model.Department == null ? "" : model.Department.DepartmentID; dto.DepartmentName = model.Department == null ? "" : model.Department.DepartmentName; dto.RoleId = model.Role == null ? "" : model.Role.RoleId; dto.RoleName = model.Role == null ? "" : model.Role.RoleName; return dto; }
public static UserDTO UpdateUser([NotNull] UserDTOUpdater uu, [NotNull] List<UserRoleDTO> roles, UserDTO updater) { if (uu.UserId == 1 && !roles.Exists(r => r.UserRoleId == 1)) throw new MyException(string.Format("Нельзя у пользователя с UserId=1 убрать роль Суперадмин")); if (uu.UserId == 1 && !uu.IsActive) throw new MyException(string.Format("Нельзя пользователя с UserId=1 сделать неактивным")); if (!updater.Roles.Exists(r => r.UserRoleId == 1) && roles.Exists(r => r.UserRoleId == 1)) throw new MyException(string.Format("Нельзя делать пользователя суперадминистратором, не являясь таким")); Logger.Info("updating user: " + uu.ChangedAsString); return Db.UpdateUser(uu, roles, updater); }
public HttpResponseMessage SaveUser(UserDTO user) { return SafeAction(() => { IDelightServices service = new DelightServices(); int id = service.SaveUser(user); if (id <= 0) { return Request.CreateResponse(HttpStatusCode.NoContent); } var response = Request.CreateResponse<int>(HttpStatusCode.OK, id); return response; }, user); }
void OnGUI() { //On button S press, the game data will be saved if (GUIKeyDown(KeyCode.S)) { //Sample JSON - to be deleted UserDTO user1 = new UserDTO("Test1", 2); UserDTO user2 = new UserDTO("Test2", 65); users.Add(user1); users.Add(user2); gameUtils.saveUsersDetails(users, scoreFileName); } }
public void UserDAO_Test() { /*Context*/ AccountDAO acc_context = new AccountDAO(); UserDAO user_context = new UserDAO(); /*Insert*/ AccountDTO acc = new AccountDTO(); acc.userName = "******"; acc.password = "******"; acc.accountType = "administrator"; acc.status = "active"; acc_context.presist(acc); UserDTO user = new UserDTO(); user.basicEducation = true; user.citizenship = true; user.disabled = true; user.employed = true; user.employmentHistory = true; user.fullName = "Andre"; user.gender = "male"; user.higherEducation = true; user.id = "8630302930"; user.idType = "SA"; user.language = true; user.license = true; user.nickName = "WIlliem"; user.postalAddress = true; user.race = "white"; user.residentialAddress = true; user.surname = "Pretorious"; user.userName = "******"; // user_context.presist(user); //Assert.AreEqual(user.race, user_context.find("griddy","8630302930").race); ///*Update*/ //user.nickName = "willi"; //user_context.merge(user); //Assert.AreEqual(user.nickName, user_context.find("griddy", "8630302930").nickName); ///*Delete*/ //user_context.removeByUserId("griddy", "8630302930"); //Assert.AreEqual(user_context.isFound("griddy", "8630302930"), false); acc_context.removeByUserId("griddy"); }
public void Save( UserDTO packet ) { Validate ( packet ); Contact contact = FormateContact ( packet ); User user = FormateUser ( packet, contact ); if ( UserDAO.isLoginExists (user) == false ) { ContactDAO.Save ( contact ); UserDAO.Save ( user ); } else { MessageBox.Show ( "This Login exists in DB already." ); } }
public ActionResult Index(UserModel model) { if (ModelState.IsValid) { UsersDAL u = new UsersDAL(); UserDTO dto1 = new UserDTO(); UserDTO dto2 = new UserDTO(); dto1 = u.GetUserByLogin(model.login); dto2 = u.GetUserByPassword(model.password); if ((dto1 != null) && (dto2 != null)) { if (dto1.id_user == dto2.id_user) { //FormsAuthentication.SetAuthCookie(model.login,false); return RedirectToAction("Index","MagorPage"); } else ModelState.AddModelError("", "Invalid login or password"); } else { ModelState.AddModelError("", "Invalid login or password"); } } return View(); }
protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e) { // Determine the currently logged on user's UserId //MembershipUser currentUser = Membership.GetUser(); //Guid currentUserId = (Guid)currentUser.ProviderUserKey; //Create user in Account table DAO_Account_Interface acc_ctx = new AccountDAO(); AccountDTO newAccount = new AccountDTO(); newAccount.userName = CreateUserWizard1.UserName.ToLower(); newAccount.password = "******"; newAccount.status = "active"; newAccount.accountType = "user"; acc_ctx.presist(newAccount); //Add User Email to COntact Info DAO_ContactInfo_Interface info_ctx = new ContactInfoDAO(); ContactInfoDTO mail_info = new ContactInfoDTO(); mail_info.userName = newAccount.userName; mail_info.contactType = "e-mail"; mail_info.data = CreateUserWizard1.Email; info_ctx.presist(mail_info); //Add User information to User Table DAO_User_Interface user_ctx = new UserDAO(); UserDTO user_info = new UserDTO(); user_info.userName = newAccount.userName; user_info.id = txtID.Text; user_info.fullName = txtName.Text; user_info.surname = txtSurname.Text; user_info.nickName = txtNickname.Text; user_info.idType = RadioIdType.SelectedValue; user_info.race = RadioRace.SelectedValue; user_info.gender = RadioGender.SelectedValue; user_ctx.presist(user_info); Roles.AddUserToRole(newAccount.userName, "User"); }
private void buttonOk_Click( object sender, System.EventArgs e ) { UserDTO newPacket = new UserDTO { Id = -1, ContactId = -1, Login = textBoxLogin.Text, Password = textBoxPassword.Text.GetHashCode(), ////// GetHashCode() Address = textBoxAddress.Text, Phone = textBoxPhone.Text, IsAdmin = checkBoxAdmin.Checked }; if ( user == null ) { try { servis.Save ( newPacket ); } catch ( Exception ex) { MessageBox.Show ( ex.Message ); } listBoxUsers.Items.Clear (); servis.FindAll ( listBoxUsers, true, false ); Close (); } else { newPacket.Id = user.Id; newPacket.ContactId = user.ContactId; servis.Update ( newPacket ); listBoxUsers.Items.Clear (); servis.FindAll ( listBoxUsers, true, false ); Close (); } }
public ActionResult Create(CommentModel comment) { try { var commentDto = Mapper.Map <CommentModel, CommentDTO>(comment); UserDTO userDto = userService.FindUserByLogin(User.Identity.Name); commentDto.User = userDto; if (User.IsInRole(Role.Admin) || User.IsInRole(Role.Moderator)) { commentDto.IsPublished = true; } else { TempData["message"] = string.Format("Ваш комментарий успешно добавлен и отправлен модератору."); } commentService.Add(commentDto); //return RedirectToAction("Show", "Post", comment.PostId); } catch (ValidationException ex) { ModelState.AddModelError(ex.Property, ex.Message); } return(RedirectToAction("Show", "Post", new { id = comment.PostId })); }
public IHttpActionResult PostEmail(UserDTO usuarioDTO) { using (uowUser) { try { var usuario = uowUser.UserRepository.GetByLoginAndEmail(usuarioDTO.Login, usuarioDTO.Email); appUser.ValidarInfos(usuario); string mailBodyhtml = "<p>Sua senha é:</p>" + usuario.Password; var msg = new MailMessage("*****@*****.**", usuario.Email, "Esqueci a senha!", mailBodyhtml); msg.IsBodyHtml = true; var smtpClient = new SmtpClient("smtp.gmail.com", 587); //if your from email address is "*****@*****.**" then host should be "smtp.hotmail.com"** smtpClient.UseDefaultCredentials = true; smtpClient.Credentials = new NetworkCredential("*****@*****.**", "projetofatecribeiraopreto"); smtpClient.EnableSsl = true; smtpClient.Send(msg); return(Ok()); } catch (Exception ex) { return(BadRequest(ex.Message)); } } }
public async Task CreateUser_WhenParamsAreValid() { //Arrange var mockDatetimeProvider = new Mock <IDateTimeProvider>(); var mockIUserMapper = new Mock <IUserMapper>(); mockIUserMapper .Setup(x => x.MapToUserDTO(It.IsAny <User>())) .Returns <User>(x => new UserDTO { UserName = x.UserName, Email = x.Email, PhoneNumber = x.PhoneNumber }); mockIUserMapper .Setup(x => x.MapToUser(It.IsAny <UserDTO>())) .Returns <UserDTO>(x => new User { UserName = x.UserName, Email = x.Email, PhoneNumber = x.PhoneNumber }); var options = Utils.GetOptions(nameof(CreateUser_WhenParamsAreValid)); var userDTO = new UserDTO { UserName = "******", Email = "*****@*****.**", PhoneNumber = "0899 899 899" }; //Act & Assert using (var assertContext = new CocktailMagicianContext(options)) { var sut = new UserService(mockDatetimeProvider.Object, assertContext, mockIUserMapper.Object); var result = await sut.CreateUserAsync(userDTO); Assert.AreEqual(1, assertContext.Users.Count()); } }
public bool Update(UserDTO oUserData) { string sProcName; DatabaseManager oDB; try { oDB = new DatabaseManager(); sProcName = "up_Upd_UserMaster"; oDB.DbCmd = oDB.GetStoredProcCommand(sProcName); oDB.DbDatabase.AddInParameter(oDB.DbCmd, "@UserId", DbType.String, oUserData.UserId); oDB.DbDatabase.AddInParameter(oDB.DbCmd, "@sUserName", DbType.String, DataSecurityManager.Encrypt(oUserData.UserName)); oDB.DbDatabase.AddInParameter(oDB.DbCmd, "@Password", DbType.String, DataSecurityManager.Encrypt(oUserData.Password)); oDB.DbDatabase.AddInParameter(oDB.DbCmd, "@Active", DbType.Boolean, oUserData.Active); oDB.DbDatabase.AddInParameter(oDB.DbCmd, "@Administrator", DbType.Boolean, oUserData.Administrator); oDB.DbDatabase.AddInParameter(oDB.DbCmd, "@userRoleId", DbType.Int32, oUserData.UserRoleData.UserRoleId); oDB.DbDatabase.AddInParameter(oDB.DbCmd, "@UserEmailId", DbType.String, DataSecurityManager.Encrypt(oUserData.EmailId)); oDB.ExecuteNonQuery(oDB.DbCmd); } catch (Exception exp) { oDB = null; oUserData = null; GF.LogError("clsUserMaster.Update", exp.Message); return(false); } finally { oDB = null; oUserData = null; } return(true); }
public JsonResult GetQuestions(FilterModel filterModel) { JsonModel model = new JsonModel(); try { FilterDTO filterDTO = Mapper.Map <FilterDTO>(filterModel); UserDTO userDTO = this.Business.GetUser(filterDTO); if (userDTO == null) { model = new JsonModel() { Result = false, Message = "Vui lòng kiểm tra mật khẩu" }; return(Json(model, JsonRequestBehavior.AllowGet)); } UserContext = userDTO; List <QuestionModel> questionModels = new List <QuestionModel>(); IList <QuestionDTO> questionDTOs = new List <QuestionDTO>(); questionDTOs = this.Business.GetQuestionByServiceID(filterDTO); questionModels = Mapper.Map <List <QuestionModel> >(questionDTOs); model = new JsonModel() { Result = true, Data = questionModels }; } catch (Exception ex) { Logging.LogError("HomeController - GetQuestions: ", ex); } return(Json(model, JsonRequestBehavior.AllowGet)); }
public ActionResult UserNavPartial() { // Get username string username = User.Identity.Name; // declare model UserNavPartialVM model; using (Db db = new Db()) { // Get the user UserDTO dto = db.Users.FirstOrDefault(x => x.Username == username); // Build the model model = new UserNavPartialVM() { Firstname = dto.FirstName, Lasttname = dto.LastName }; } // return partial view with model return(PartialView(model)); }
public async Task <IActionResult> Authenticate([FromBody] UserDTO model) { if (ModelState.IsValid) { var user = _userService.Authenticate(model.user_name, model.password); if (user == null) { return(Unauthorized(new { message = "Invalid_Credentials" })); } var tokenString = await GenerateJwtToken(user); // return basic user info and authentication token return(Ok(new { Id = user.id, Username = user.user_name, Token = tokenString })); } else { return(ValidationProblem("User name and password are required feilds")); } }
public object GenerateJwtToken(string email, int id, UserDTO user, IConfiguration _config) { var claims = new [] { new Claim(JwtRegisteredClaimNames.Sub, user.Username), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), }; var jwtkey = _config["Jwt:Key"]; var issuer = _config["Jwt:JwtIssuer"]; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"])); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( _config["Jwt:JwtIssuer"], _config["Jwt:JwtIssuer"], claims, expires: DateTime.Now.AddMinutes(30), signingCredentials: creds); var tokenString = new JwtSecurityTokenHandler().WriteToken(token); return(tokenString); }
public bool Insert(UserDTO user) { using (var connection = new SQLiteConnection(_connectionString)) { SQLiteCommand command = new SQLiteCommand(null, connection); int res = -1; try { connection.Open(); command.CommandText = $"INSERT INTO {UsersTableName} ({UserDTO.EmailColumnName},{UserDTO.NickNameColumnName},{UserDTO.PassColumnName},{UserDTO.boardIDColumnName}) " + $"VALUES (@Email,@Nickname,@Password,@boardID);"; SQLiteParameter EmailParam = new SQLiteParameter(@"Email", user.Email); SQLiteParameter NicknameParam = new SQLiteParameter(@"Nickname", user.Nickname); SQLiteParameter PasswordParam = new SQLiteParameter(@"Password", user.Password); SQLiteParameter boardidParam = new SQLiteParameter(@"boardID", user.boardID); command.Parameters.Add(EmailParam); command.Parameters.Add(NicknameParam); command.Parameters.Add(PasswordParam); command.Parameters.Add(boardidParam); command.Prepare(); res = command.ExecuteNonQuery(); } catch (Exception ex) { log.Error("Error accured!"); log.Debug(ex.Message); } finally { command.Dispose(); connection.Close(); } return(res > 0); } }
public async Task <IActionResult> PostAsync([FromHeader] string authToken, [FromBody] UserDTO model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (!await _tokenService.HasTokenAsync(authToken)) { return(Unauthorized()); } User user = UserMapper.Map(model); UserValidator validator = new UserValidator(); ValidationResult result = await validator.ValidateAsync(user); if (result.IsValid) { _context.Users.Update(user); await _context.SaveChangesAsync(); } else { foreach (ValidationFailure error in result.Errors) { ModelState.AddModelError(error.PropertyName, error.ErrorMessage); } } if (ModelState.ErrorCount != 0) { return(BadRequest(ModelState)); } return(Ok()); }
/// <summary> /// Monitor SanPham information to fields and show UI as privilege /// </summary> /// <param name="item"></param> public SanPhamDetail(int index, ItemDTO item, UserDTO user, InitPage parent) { this.parent = parent; this.itemIndex = index; this.OpenMode = MODE_EDIT; this.InitializeComponent(); this.lbName.Text = item.name; this.txtID.Text = item.ID.ToString(); this.txtName.Text = item.name; this.txtType.Text = item.type; this.txtAmount.Text = item.amount.ToString(); this.txtMinimum.Text = item.minimum.ToString(); this.txtProvider.Text = item.provider; if (user.role == DTO.Helper.Constants.USERTYPE_MANAGER) { this.btnConfirm.Visible = true; this.txtAmount.Enabled = true; this.txtID.Enabled = false; this.txtMinimum.Enabled = true; this.txtName.Enabled = true; this.txtType.Enabled = true; this.txtProvider.Enabled = true; } else { this.btnConfirm.Visible = false; this.txtAmount.Enabled = false; this.txtID.Enabled = false; this.txtMinimum.Enabled = false; this.txtName.Enabled = false; this.txtType.Enabled = false; this.txtProvider.Enabled = false; } }
public ActionResult Login(UserViewModel userViewModel) { UserDTO UserDTO = UserMapper.UserViewModel2userDTO(userViewModel); UserDTO LoggedInUserDTO; try { LoggedInUserDTO = UserService.Login(UserDTO); } catch (InvalidUserException ex) { ModelState.AddModelError(string.Empty, ex.Message); return(View(userViewModel)); } UserViewModel LoggedInUser = UserMapper.UserDTO2UserViewModel(LoggedInUserDTO); Session["User"] = LoggedInUser; if (LoggedInUser.isAdmin) { Session["Admin"] = true; } return(RedirectToAction("Home", "Event")); }
private OperationDetails Create(UserDTO userDto) { ApplicationUser user = FindByEmail(userDto.Email); if (user == null) { user = new ApplicationUser { Email = userDto.Email, UserName = userDto.Email }; CreateUser(user, userDto.Password); AddToRole(user.Id, userDto.Role); ClientProfile clientProfile = new ClientProfile { Id = user.Id, Name = userDto.Name, DateOfBirth = userDto.DateOfBirth, Surname = userDto.Surname, Role = userDto.Role }; Database.ClientManager.Create(clientProfile); Database.Save(); userDto.Id = user.Id; return(new OperationDetails(true, "Registration is successful", "")); } else { return(new OperationDetails(false, "User with such login already exists", "Email")); } }
public async Task <ActionResult> Get(string userId) { var currentPlayer = Player; if (currentPlayer is null) { _logger.LogWarning("Unable to get current player for host '{host}'", Request.Host); return(Unauthorized()); } UserProfile userProfile; // Is it self? if (currentPlayer?.Data?.PSNUserId?.Equals(userId) is true) { userProfile = UserProfile.FromDatabaseObject(currentPlayer.Data); } else { // Possible friend - Check if they're a friend before allowing to get their profile UserDTO userData = await _userDb.GetByPSNUserIdAsync(userId); if (!await _friendsDb.IsFriendedToUser(currentPlayer.Data.Id, userData.Id)) { return(Forbid()); } userProfile = UserProfile.FromDatabaseObject(userData); } userProfile.BandUp = 1024; userProfile.BandDown = 1024; userProfile.BandUpdateTime = DateTime.Now.ToRfc3339String(); userProfile.BandTest = 1024; return(Ok(userProfile)); }
public void CreateUser(UserDTO userDTO) { User user = new User(); if (string.IsNullOrWhiteSpace(userDTO.Password) && userDTO.ChatId == null) { throw new Exception("Password or ChatId is Required"); } if (db.Users.Find(u => u.Username == userDTO.Username).Count() != 0) { throw new Exception($"Username {userDTO.Username} is already taken"); } user.ChatId = userDTO.ChatId; user.Username = userDTO.Username; byte[] passwordHash; byte[] passwordSalt; CreatePasswordHash(userDTO.Password, out passwordHash, out passwordSalt); user.PasswordHash = passwordHash; user.PasswordSalt = passwordSalt; db.Users.Create(user); db.Save(); }
public async Task <HttpResponseMessage> Create([FromBody] UserDTO userDTO) { if (!ModelState.IsValid) { string errorMessage = string.Empty; foreach (ModelState keyValuePairs in ModelState.Values) { foreach (ModelError modelError in keyValuePairs.Errors) { errorMessage += " - " + modelError.ErrorMessage; } } return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, errorMessage)); } if (await UserService.AddAsync(userDTO) != null) { return(Request.CreateResponse(HttpStatusCode.OK, new { message = "User was succesfully created" })); } return(Request.CreateResponse(HttpStatusCode.InternalServerError, new { message = "Something horrible went wrong." })); }
public ActionResult Orders() { List <OrdersForAdminVM> ordersForAdmin = new List <OrdersForAdminVM>(); using (Db db = new Db()) { List <OrderVM> orders = db.Orders.ToArray().Select(m => new OrderVM(m)).ToList(); foreach (var order in orders) { Dictionary <string, int> productsAndQty = new Dictionary <string, int>(); decimal total = 0m; List <OrderDetailsDTO> orderDetailsList = db.OrderDetails.Where(m => m.OrderId == order.OrderId).ToList(); UserDTO user = db.Users.FirstOrDefault(m => m.Id == order.UserId); string username = user.Username; foreach (var orderDetails in orderDetailsList) { ProductDTO product = db.Products.Where(m => m.Id == orderDetails.ProductId).FirstOrDefault(); decimal price = product.Price; string productName = product.Name; productsAndQty.Add(productName, orderDetails.Quantity); total += price * orderDetails.Quantity; } ordersForAdmin.Add(new OrdersForAdminVM { OrderNumber = order.OrderId, Username = username, Total = total, ProductsAndQty = productsAndQty, CreatedAt = order.CreatedAt }); } } return(View(ordersForAdmin)); }
public async Task <BaseResult <UserEntity> > Updata(UserDTO modal) { BaseResult <UserEntity> userinfo = await userRepository.Detail(modal.userId); int isManager = modal.isManager; if (userinfo.code != "0" || userinfo.data.total <= 0) { throw new Exception("用户不存在"); } if (!string.IsNullOrEmpty(modal.oldPassWord)) { if (modal.comfirPassword != modal.newPassword) { throw new Exception("两次密码输入不一致"); } if (userinfo.data.list[0].passWord != modal.oldPassWord) { throw new Exception("原密码输入错误"); } } else { modal.newPassword = userinfo.data.list[0].passWord; modal.isManager = userinfo.data.list[0].isManager; } if (userinfo.data.list[0].isManager == 1) { modal.isManager = 1; } if (!string.IsNullOrEmpty(modal.editManager)) { modal.isManager = isManager; } return(await userRepository.Update(modal)); }
public ActionResult UserProfile() { // Get user name string username = User.Identity.Name; // Declare model UserProfileVM model; using (Db db = new Db()) { if (!db.Users.Any(x => x.UserName == username)) { FormsAuthentication.SignOut(); // Set TempData message TempData["SM"] = "You have edited your username please login again!"; return(Redirect("~/account/login")); } // Get user UserDTO dto = db.Users.FirstOrDefault(x => x.UserName == username); // Build model model = new UserProfileVM(dto); } // Return view with model return(View("UserProfile", model)); }
public UserDTO UpdateUser(UserDTO user) { try { var client = new MongoClient(connectionString); var db = client.GetDatabase("social-network"); var users = db.GetCollection <UserDTO>("users"); int id = user.UserId; var oldUser = GetUserById(id); oldUser.LastName = user.LastName; oldUser.FirstName = user.FirstName; oldUser.Email = user.Email; oldUser.Friends = user.Friends; oldUser.Interests = user.Interests; oldUser.Login = user.Login; oldUser.Password = user.Password; var res = users.Find(p => p.UserId == user.UserId).Single(); return(res); } catch (Exception e) { throw e; } }
public RegisterOperationDetails Create(UserDTO userDto) { ApplicationUser user = repository.UserManager.FindByEmail(userDto.Email); if (user == null) { user = new ApplicationUser { Email = userDto.Email, UserName = userDto.Email, RegistrationDateTime = DateTime.UtcNow }; var result = repository.UserManager.Create(user, userDto.Password); if (result.Errors.Count() > 0) { return(new RegisterOperationDetails(false, ErrorType.IdentityErrorWhileCreating)); } repository.UserManager.AddToRole(user.Id, userDto.Role); repository.Save(); return(new RegisterOperationDetails(true, ErrorType.None)); } else { return(new RegisterOperationDetails(false, ErrorType.UserWithSuchEmailAlreadyExists)); } }
public async Task <ActionResult> Register(RegisterModel model) { if (ModelState.IsValid) { UserDTO userDto = new UserDTO { UserName = model.UserName, Email = model.Email, Password = model.Password, Role = "User" }; OperationDetails operationDetails = await userService.Create(userDto); if (operationDetails.Succeeded) { return(RedirectToAction("Index", "Home")); } else { ModelState.AddModelError(operationDetails.Property, operationDetails.Message); } } return(View(model)); }
public ActionResult Login([FromBody] UserDTO request) { if (!ModelState.IsValid) { return(BadRequest()); } if (!_userService.GetUser(request.UserName, request.Password)) { return(Unauthorized()); } //var role = _userService.GetUserRole(request.UserName); //var claims = new[] //{ // new Claim(ClaimTypes.Name,request.UserName), // new Claim(ClaimTypes.Role, role) //}; var claims = new[] { new Claim(ClaimTypes.Name, request.UserName), new Claim(ClaimTypes.Role, "Admin") }; var jwtResult = _jwtAuthManager.GenerateTokens(request.UserName, claims, DateTime.Now); _logger.LogInformation($"User [{request.UserName}] logged in the system."); return(Ok(new LoginResult { UserName = request.UserName, Role = "Admin", AccessToken = jwtResult.AccessToken, RefreshToken = jwtResult.RefreshToken.TokenString, ExpireIn = string.Format("Token Expires in {0}", jwtResult.ExpireIn) })); }
public async Task <ActionResult> Register(UserRegisterViewModel model) { await _identityService.SetInitialData(); if (ModelState.IsValid) { UserDTO userDto = _mapper.Map <UserRegisterViewModel, UserDTO>(model); userDto.RoleByDefault = roleByDefault; OperationDetails operationDetails = await _identityService.Create(userDto); if (operationDetails.Succedeed) { if (await TryToSignInAsync(userDto, false)) { return(RedirectToAction("Index", "Home")); } } else { ModelState.AddModelError(operationDetails.Property, operationDetails.Message); } } return(View(model)); }
public OperationDetails CreateTeacher(UserDTO userDto) { var userManager = _database.UserManager; ApplicationUser user = userManager.FindByEmail(userDto.Email); if (user != null) { return(new OperationDetails(false, "User with such an email already exists", "Email")); } user = new ApplicationUser { Email = userDto.Email, UserName = userDto.Email, FirstName = userDto.FirstName, SecondName = userDto.SecondName, Patronymic = userDto.Patronymic, PhoneNumber = userDto.PhoneNumber, DateOfBirth = userDto.DateOfBirth, Photo = userDto.Photo }; var result = _database.UserManager.Create(user, userDto.Password); if (result.Errors.Count() > 0) { return(new OperationDetails(false, result.Errors.FirstOrDefault(), "")); } _database.UserManager.AddToRole(user.Id, RoleDistributer.GetTeacherRole()); _database.Save(); _database.TeacherRepository.Create(new Teacher() { ApplicationUser = user }); _database.Save(); return(new OperationDetails(true, "", "")); }
public IHttpActionResult UpdateProfile(string id, UserDTO userDto) { if (!ModelState.IsValid) { return(BadRequest()); } var selectedUser = UOW.UserRepository.FindAsNoTracking(u => u.Id == id) .SingleOrDefault(); if (selectedUser == null) { return(NotFound()); } ObjectMapper.Mapper.Map(userDto, selectedUser); selectedUser.Id = id; UOW.UserRepository.Update(selectedUser); UOW.Complete(); UOW.Dispose(); return(Ok()); }
// POST api/<controller> public string Post([FromBody] UserDTO user) { // Account account = new Account( //"dmxrlqiij", //"536862683394679", //"GAo3FcR_C7D6lj_Q_isWwyosCDc"); //Cloudinary cloudinary = new Cloudinary(account); //var uploadParams = new ImageUploadParams() //{ // File = new FileDescription(@user.image) //}; //var uploadResult = cloudinary.Upload(uploadParams); //var x=uploadResult.SecureUri; //user.image = x.ToString(); if (ModelState.IsValid) { return(serviceCall.ServiceCreateUser(user)); } else { return("valid"); } }
public async Task <string> SignIn(UserDTO userDTO) { userDTO.Username = userDTO.Username.ToLower(); userDTO.Password = Constants.EncryptPwd(userDTO.Password); var result = await _userSearcher.GetBy(x => x.Username == userDTO.Username && x.Password == userDTO.Password); if (result != null) { var secretBytes = Encoding.UTF8.GetBytes(Constants.Secret); var key = new SymmetricSecurityKey(secretBytes); var algorithm = SecurityAlgorithms.HmacSha256; var signingCredentials = new SigningCredentials(key, algorithm); var token = new JwtSecurityToken( Constants.Issuer, Constants.Audiance, claims: new Claim[] { new Claim("userId", result.Id) }, notBefore: DateTime.Now, expires: DateTime.Now.AddDays(1), signingCredentials ); var tokenJson = new JwtSecurityTokenHandler().WriteToken(token); return(tokenJson); } else { return(null); } }
public async Task AddAsync([FromBody] UserDTO item) { await _userService.Add(item); }
public FriendLoggedOutResponse(UserDTO friend) { this.friend = friend; }
private static string GetSingleValue(UserDTO[][] values) { string singleValue = new SuperTask().multipleValuesMessage; if (ValuesAreTheSame(values)) { singleValue = null; foreach (UserDTO[] usersDTO in values) { if (usersDTO.Length > 0) { string[] userLogins = new string[usersDTO.Length]; for (int i = 0; i < usersDTO.Length; i++) { userLogins[i] = usersDTO[i].UserLogin; } singleValue = string.Join(", ", userLogins); break; } } } return singleValue; }
public JsonResult RegisterAction(UserDTO userDTO) { var msg= _userServices.SaveUser(userDTO); return Json(msg, JsonRequestBehavior.DenyGet); }
public JsonResult LoginAction(UserDTO userDTO) { var msg = _userServices.Login(userDTO); return Json(msg, JsonRequestBehavior.DenyGet); }
public bool presist(UserDTO entity) { try { model.User obj = new User(); obj.userName = entity.userName; obj.id = entity.id; obj.fullName = entity.fullName; obj.nickName = entity.nickName; obj.gender = entity.gender; obj.race = entity.race; obj.disabled = entity.disabled; obj.citizenship = entity.citizenship; obj.idType = entity.idType; obj.license = entity.license; obj.basicEducation = entity.basicEducation; obj.higherEducation = entity.higherEducation; obj.language = entity.language; obj.residentialAddress = entity.residentialAddress; obj.postalAddress = entity.postalAddress; obj.employed = entity.employed; obj.employmentHistory = entity.employmentHistory; ctx.Users.InsertOnSubmit(obj); ctx.SubmitChanges(); return true; } catch (Exception) { ctx.Dispose(); ctx = new ModelDataContext(); return false; } }
public bool remove(UserDTO entity) { return this.removeByUserId(entity.userName,entity.id); }
public bool merge(UserDTO entity) { try { var addObj = (from p in ctx.Users where p.userName == @entity.userName && p.id == @entity.id select p).Single(); model.User obj = (User)addObj; /*Update*/ obj.userName = entity.userName; obj.id = entity.id; obj.fullName = entity.fullName; obj.nickName = entity.nickName; obj.gender = entity.gender; obj.race = entity.race; obj.disabled = entity.disabled; obj.citizenship = entity.citizenship; obj.idType = entity.idType; obj.license = entity.license; obj.basicEducation = entity.basicEducation; obj.higherEducation = entity.higherEducation; obj.language = entity.language; obj.residentialAddress = entity.residentialAddress; obj.postalAddress = entity.postalAddress; obj.employed = entity.employed; obj.employmentHistory = entity.employmentHistory; ctx.SubmitChanges(); return true; } catch (Exception e) { model.Log log = new Log(); log.message = "User Merge: " + " ["+entity.userName+" , "+entity.id+"] " + e.Message; ctx.SubmitChanges(); ctx.Dispose(); ctx = new ModelDataContext(); return false; } }
private void CheckPerson(UserDTO user) { var currentUser = userManager.GetByUserName(user.UserName, user.Password); var currentPerson = personManager.GetPersonByUserId(currentUser.Id); if (currentPerson == null) { currentPerson = personManager.InsertPerson(new PersonDTO() { UserId = currentUser.Id, ImageName = "item_0_profile.jpg" }); currentPerson.User = currentUser; } if (!System.IO.File.Exists(Server.MapPath(@"~\Images\") + currentPerson.ImageName)) { personManager.DefaultImage(user.Id); } }
public void CreateTestMethod() { UserDTO user = new UserDTO() { Name = "dragon.luo", Password = "******", Email = "*****@*****.**", Mobile = "15913135166", EffectiveDate = DateTime.Now, ExpiryDate = DateTime.Now.AddYears(5), }; user.Roles = new List<RoleDTO>() { new RoleDTO() { Name = "Administrator" } }; response = InvokeOperation("userOperation", "Create", new object[] { user }); user = new UserDTO() { Name = "diana.wu", Password = "******", Email = "*****@*****.**", Mobile = "13570497968", EffectiveDate = DateTime.Now, ExpiryDate = DateTime.Now.AddYears(5), }; user.Roles = new List<RoleDTO>() { new RoleDTO() { Name = "General User" }, new RoleDTO() { Name = "System Configuration Management" } }; response = InvokeOperation("userOperation", "Create", new object[] { user }); response = InvokeOperation("roleOperation", "Retrieve", new object[] { 100003 }); ; RoleDTO role = response.Result.Value as RoleDTO; user = new UserDTO() { Name = "admin", Password = "******", Email = "*****@*****.**", Mobile = "1234567890A", EffectiveDate = DateTime.Now, ExpiryDate = DateTime.Now.AddYears(5), }; role.Remark = "testing reamrk"; user.Roles = new List<RoleDTO>() { role }; JsonConfigDTO jsonConfig = new JsonConfigDTO() { DefaultModuleId = 2, WindowTheme = "Office2010Blue" }; UserProfileDTO profile = new UserProfileDTO() { JsonConfig = JsonUtils.SerializeObject(jsonConfig), Owner = user, ProfileType = "Personal", StartDate = DateTime.Now }; user.Profiles.Add(profile); response = InvokeOperation("userOperation", "Create", new object[] { user }); }
public IList<OrderExDTO> GetDriversTodayOrders(UserDTO Driver) { var driver = Mapper.Map<User>(Driver); var orders = uOW.OrderExRepo.All .Where(o => o.Driver.Id == driver.Id && o.OrderTime.Day == DateTime.Now.Day && o.OrderTime.Month == DateTime.Now.Month && o.OrderTime.Year == DateTime.Now.Year) .ToList(); return Mapper.Map<List<OrderExDTO>>(orders); }
public IEnumerable<OrderExDTO> GetOrdersByDriver(UserDTO Driver) { var driver = Mapper.Map<User>(Driver); var orders = uOW.OrderExRepo.All.Include(o => o.AddressFrom) .Where(o => o.Driver.Id == driver.Id) .ToList(); return Mapper.Map<List<OrderExDTO>>(orders); }