Example #1
0
        private void BtnAddUser_Click(object sender, RoutedEventArgs e)
        {
            tUser userbll = new tUser();

            formcheck();
            if (userManager.Any(s => s.user_name == username.Text.Trim()))
            {
                MessageBox.Show($"用户名【{username.Text.Trim()}】已经存在,请修改后点击添加!");
                return;
            }
            tUser usermodel = new tUser();

            usermodel.user_name  = username.Text.Trim();
            usermodel.password   = userpwd.Text.Trim();
            usermodel.true_name  = usertrue.Text.Trim();
            usermodel.type_name  = usertype.Text.Trim();
            usermodel.createtime = DateTime.Now;

            userManager.Add(usermodel);
            if (usermodel.ID > 0)
            {
                MessageBox.Show("用户添加成功!");
                LoadData();
            }
            else
            {
                MessageBox.Show("用户添加失败!");
            }
        }
Example #2
0
        public User Create(User user, string password)
        {
            // validation
            if (string.IsNullOrWhiteSpace(password))
            {
                throw new AppException("Password is required");
            }

            if (_dbContext.tUsers.Any(x => x.Username == user.Username))
            {
                throw new AppException("Username \"" + user.Username + "\" is already taken");
            }

            byte[] passwordHash, passwordSalt;
            CreatePasswordHash(password, out passwordHash, out passwordSalt);

            user.PasswordHash = passwordHash;
            user.PasswordSalt = passwordSalt;

            tUser dbUser = new tUser();

            MapEntityToDb(user, dbUser);

            _dbContext.tUsers.Add(dbUser);
            _dbContext.SaveChanges();

            return(user);
        }
        public ActionResult LogIn(tUser u)
        {
            if (!db.tUsers.Any(a => a.Username == u.Username && a.Password == u.Password))
            {
                ViewBag.Err = "Invalid username or password.";
                return(View());
            }
            var user = db.tUsers.SingleOrDefault(a => a.Username == u.Username && a.Password == u.Password);

            Session["userID"]      = user.UserId;
            Session["accountType"] = user.AccountTypeId;
            Session["entityID"]    = "0";
            if (db.tBusinessEntities.Any(b => b.UserId == user.UserId))
            {
                var entity = db.tBusinessEntities.SingleOrDefault(b => b.UserId == user.UserId);
                Session["entityID"] = entity.EntityId;
            }
            if (user.AccountTypeId == "1" || user.AccountTypeId == "3")
            {
                var info = db.tBusinessEntities.FirstOrDefault(f => f.UserId == user.UserId).BusinessEntityName;
                Session["name"] = info;
            }
            if (user.AccountTypeId == "2" || user.AccountTypeId == "4")
            {
                var info = db.tPersonInfoes.FirstOrDefault(f => f.UserId == user.UserId);
                var name = info.Lastname + ", " + info.Firstname + (info.Middlename != null ? " " + info.Middlename.Substring(0, 1) + "." : "");
                Session["name"] = name;
            }
            return(RedirectToAction("Feed", "Jobs"));
        }
Example #4
0
        public override string[] GetRolesForUser(string username)
        {
            _UserRep = BootStrapper.GetCurrentUserRepository();
            _RoleRep = BootStrapper.GetCurrentRoleRepository();
            // throw new NotImplementedException();
            tUser user = _UserRep.GetSingleByUserName(username);

            if (user == null)
            {
                return new string[1] {
                           "NotFoundRole"
                }
            }
            ;
            //List<USER_ROLE> uroles = _UserRoleRep.GetListByUserID(user.UserID);
            string[] roles = new string[1];//new string[uroles.Count];
            int      i     = 0;
            //foreach (USER_ROLE item in uroles)
            //{
            //    ROLE role = _RoleRep.GetSingle(item.RoleID);
            //    roles[i] = role.RoleName;
            //    i++;
            //}
            tRole role = _RoleRep.Find(user.IDRole);

            roles[0] = role.Name;
            return(roles);
            // throw new NotImplementedException();
        }
        public static bool InsertUser(tUser userToInsert)
        {
            try
            {
                using (IDbConnection connection = Helper.DbConnectionHelper.GetConnection())
                {
                    string sql = "INSERT INTO [OfficeFinancial].[dbo].[tUser]([ID],[Password],[Notes] ,[LanguageCode] ,[Theme] ,[FontName]   ,[FontSize])";
                    sql += " VALUES(@ID,@Password, @Notes,@LanguageCode, @Theme,@FontName ,@FontSize)";

                    connection.Execute(sql, userToInsert);
                }
            }
            catch (SqlException ex)
            {
                //LoggerHelper.Write(TraceEventType.Error, "Error in InsertUser. " + ex,
                //    new string[] { Constants.LOGGING_CATEGORY_DEV, Constants.LOGGING_CATEGORY_PRODUCTION });
                throw;
            }
            catch (InvalidOperationException ex)
            {
                //LoggerHelper.Write(TraceEventType.Error, "Error in InsertUser. " + ex,
                //    new string[] { Constants.LOGGING_CATEGORY_DEV, Constants.LOGGING_CATEGORY_PRODUCTION });
                throw;
            }
            return(true);
        }
Example #6
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            ReturnUrl = returnUrl;
            tUser user = new tUser();

            //if (!ModelState.IsValid)
            //{
            //    return Page();
            //}
            user = await _context.tUser.SingleOrDefaultAsync(m => m.user_id == users.user_id);

            if (user is null)
            {
                if (users.user_id.ToUpper() == "SYSTEM" && users.password == "Password1!")
                {
                    return(RedirectToPage("./Index"));
                }
                else
                {
                    return(Page());
                }
            }
            else
            {
                var isValid = (user.user_id == users.user_id && user.password == users.password);
                if (isValid == true)
                {
                    return(RedirectToPage("./Index"));
                }
                else
                {
                    return(Page());
                }
            }
        }
Example #7
0
        /// <summary>
        /// Returns true if user has write access right for document.
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="documentId"></param>
        /// <returns></returns>
        public bool CheckIfUserHasWriteAccess(int userId, int documentId)
        {
            using (DMSDataBaseEntities context = new DMSDataBaseEntities())
            {
                tUser user = context.tUsers.Find(userId);
                if (user.AuthorizationRoleId == (int)AuthorizationRoleCodes.Administrator)
                {
                    return(true);
                }

                tUserDocument ud = context.tUserDocuments.Where(u => u.UserId == userId && u.DocumentId == documentId).SingleOrDefault();
                if (ud == null)
                {
                    return(false);
                }
                if (ud.DocumentAccessRightId == (int)DocumentAccessRightCodes.Owner)
                {
                    return(true);
                }
                if (ud.DocumentAccessRightId == (int)DocumentAccessRightCodes.Modify)
                {
                    return(true);
                }
                return(false);
            }
        }
        public IHttpActionResult UpdateUserLanguageLocation(tUser tUser)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var user  = db.tUsers.Include(u => u.tUsersAddressHistories).FirstOrDefault(x => x.ID == tUser.ID);
            var state = tUser.tUsersAddressHistories.FirstOrDefault().StateID;

            if (user == null)
            {
                return(NotFound());
            }
            user.LanguageID = tUser.LanguageID;

            if (user.tUsersAddressHistories.Count > 0)
            {
                user.tUsersAddressHistories.FirstOrDefault().StateID = tUser.tUsersAddressHistories.FirstOrDefault().StateID;
            }
            else
            {
                user.tUsersAddressHistories.Add(new tUsersAddressHistory {
                    UserID = user.ID, StateID = state
                });
            }

            db.SaveChanges();
            return(Ok(user));
        }
Example #9
0
        // PUT: api/tUsers/5

        public IHttpActionResult PuttUser(int id, tUser tUser)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != tUser.recNo)
            {
                return(BadRequest());
            }

            db.Entry(tUser).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!tUserExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Example #10
0
 public void InsertOrUpdate(tUser user)
 {
     if (user.IDUser == default(int))
     {
         // New entity
         context.tUsers.InsertOnSubmit(user);
     }
     else
     {
         // Existing entity
         //context.USERs.Attach(user);
         //context.Entry(user).State = EntityState.Modified;
         tUser userToUpdate = Find(user.IDUser);
         if (userToUpdate != null && userToUpdate.IDUser > 0)
         {
             userToUpdate.IDRole            = user.IDRole;
             userToUpdate.Password          = user.Password;
             userToUpdate.LastLoginDate     = user.LastLoginDate;
             userToUpdate.Approved          = user.Approved;
             userToUpdate.IDPartnerCategory = user.IDPartnerCategory;
             userToUpdate.IDCity            = user.IDCity;
         }
     }
     context.SubmitChanges();
 }
Example #11
0
        public async Task <ServiceResult> AddAsync(AddUserContract user)
        {
            ServiceResult result = new ServiceResult();

            try
            {
                var check = await userRepository.GetCountAsync(userRepository.GetTable.Where(d => d.UserID.Equals(user.UserID)).AsQueryable());

                if (check == 0)
                {
                    tUser data = new tUser
                    {
                        UserID     = Guid.Parse(user.UserID.ToString()),
                        Password   = HelperMethod.encrypt(user.Password),
                        FirstName  = user.FirstName,
                        LastName   = user.LastName,
                        CreateDate = DateTime.Now,
                        UpdateDate = DateTime.Now
                    };
                    var save = await userRepository.AddAsync(data);

                    result = save.status;
                }
                else
                {
                    result.BadRequest("REGISTERED_ALREADY");
                }
                return(result);
            }
            catch (Exception ex)
            {
                result.Error("ERROR", ex.Message);
            }
            return(result);
        }
Example #12
0
 private void MapEntityToDb(User domain, tUser db)
 {
     db.FirstName    = domain.FirstName;
     db.Id           = domain.Id;
     db.LastName     = domain.LastName;
     db.PasswordHash = domain.PasswordHash;
     db.PasswordSalt = domain.PasswordSalt;
     db.Username     = domain.Username;
 }
        public async Task <IHttpActionResult> UpdateUser(int id, tUser tUser)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != tUser.ID)
            {
                return(BadRequest());
            }
            var user = await db.tUsers.FindAsync(id);

            user.PasswordHash = tUser.PasswordHash;

            if (user.PasswordHash != null)
            {
                PasswordStorage oPassUtil = new PasswordStorage();
                //oPassUtil.Hashstring = ;
                oPassUtil.CreateHash(user.PasswordHash);
                //oPassUtil.VerifyPassword
                user.PasswordHash = oPassUtil.Hashstring;

                tSalt salt = new tSalt {
                    Salt = oPassUtil.Saltstring
                };

                SaltsController sl = new SaltsController();
                user.tSalt = await sl.EditSalt(salt.Id, salt);

                if (user.tSalt != null)
                {
                    user.PHSaltID = tUser.tSalt.Id;
                }
            }
            db.Entry(user).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                if (!tUserExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            //return StatusCode(HttpStatusCode.NoContent);
            return(StatusCode(HttpStatusCode.OK));
        }
Example #14
0
        private MembershipUser MakeMembershipUser(tUser user)
        {
            object userID   = user.IDUser;
            string username = user.UserName;
            string email    = user.UserName;

            string passwordQuestion = String.Empty;
            //if (sqlDataReader.GetValue(3) != DBNull.Value)
            //{
            //    passwordQuestion = sqlDataReader.GetString(3);
            //}

            string comment = String.Empty;
            //if (sqlDataReader.GetValue(4) != DBNull.Value)
            //{
            //    comment = sqlDataReader.GetString(4);
            //}

            bool     isApproved   = (bool)user.Approved;
            bool     isLockedOut  = false;
            DateTime creationDate = (DateTime)user.DateAdded;

            DateTime lastLoginDate = new DateTime();

            if (user.LastLoginDate != null)
            {
                lastLoginDate = (DateTime)user.LastLoginDate;
            }

            DateTime lastActivityDate        = DateTime.Now; //sqlDataReader.GetDateTime(9);
            DateTime lastPasswordChangedDate = DateTime.Now; // sqlDataReader.GetDateTime(10);

            DateTime lastLockedOutDate = new DateTime();
            //if (sqlDataReader.GetValue(11) != DBNull.Value)
            //{
            //    lastLockedOutDate = sqlDataReader.GetDateTime(11);
            //}

            MembershipUser membershipUser = new MembershipUser(
                this.Name,
                username,
                userID,
                email,
                passwordQuestion,
                comment,
                isApproved,
                isLockedOut,
                creationDate,
                lastLoginDate,
                lastActivityDate,
                lastPasswordChangedDate,
                lastLockedOutDate
                );

            return(membershipUser);
        }
Example #15
0
 public bool Update(tUser entity)
 {
     if (entity == null)
     {
         return(false);
     }
     context.Users.Update(entity);
     context.SaveChanges();
     return(true);
 }
Example #16
0
 public bool Insert(tUser entity)
 {
     if (entity == null)
     {
         return(false);
     }
     context.Users.Add(entity);
     context.SaveChanges();
     return(true);
 }
Example #17
0
        public void Delete(int id)
        {
            tUser user = Find(id);

            if (user != null && user.IDUser > 0)
            {
                context.tUsers.DeleteOnSubmit(user);
            }
            context.SubmitChanges();
        }
Example #18
0
 private MiniProfile GetUserData(tUser d)
 {
     return(new MiniProfile
     {
         UserName = d.Username,
         FirstName = d.FirstName,
         LastName = d.LastName,
         UserID = d.UserID.ToString()
     });
 }
        public IHttpActionResult GetUserByEID(System.Guid ExternalId)
        {
            tUser tUser = db.tUsers.SingleOrDefault(x => x.ExternalID == ExternalId);;

            if (tUser == null)
            {
                return(NotFound());
            }

            return(Ok(tUser));
        }
Example #20
0
        public ActionResult Details(int?id)
        {
            if (id == null)
            {
                id = 0;
            }
            tUser userData = _userRepository.Find((int)id);

            ViewBag.DealsByPartner = _dealRepository.GetListByIDPartner((int)id);
            return(View(userData));
        }
Example #21
0
        public IHttpActionResult GettUser(int id)
        {
            tUser tUser = db.tUsers.Find(id);

            if (tUser == null)
            {
                return(NotFound());
            }

            return(Ok(tUser));
        }
        public IHttpActionResult PosttUser(tUser tUser)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            db.tUsers.Add(tUser);
            db.SaveChanges();

            return(CreatedAtRoute("DefaultApi", new { id = tUser.recNo }, tUser));
        }
Example #23
0
        static void SQLDeleteTest()
        {
            var user = new tUser()
            {
                ID = 1
            };

            using (var con = new SqlConnection(""))
            {
                var EfectedRowsCount = con.Delete(user);
            }
        }
Example #24
0
        /// <summary>
        /// Returns user dto specified by user name.
        /// </summary>
        /// <param name="userName">The name of the user.</param>
        /// <returns></returns>
        public UserDTO LoadUserByName(string userName)
        {
            BeginTransaction();
            tUser result = Context.tUsers.Where(u => u.UserName.Equals(userName) && u.IsValid).SingleOrDefault();

            EndTransaction();
            if (result == null)
            {
                throw new UserNotFoundException();
            }
            return(Mapper.Map <UserDTO>(result));
        }
Example #25
0
        public IHttpActionResult LogIn(tUser tUser)
        {
            var t = db.tUsers.Where(x => x.Username == tUser.Username && x.Password == tUser.Password).FirstOrDefault();

            if (t == null)
            {
                t = null;
                return(Ok(t));
            }

            return(Ok(t.Status));
        }
Example #26
0
        /// <summary>
        /// Returns user dto specified by id.
        /// </summary>
        /// <param name="id">The id of the user.</param>
        /// <returns></returns>
        public UserDTO LoadUserById(int id)
        {
            BeginTransaction();
            tUser result = Context.tUsers.Find(id);

            EndTransaction();
            if (result == null)
            {
                throw new UserNotFoundException();
            }
            return(Mapper.Map <UserDTO>(result));
        }
Example #27
0
 // GET: Upload
 public ActionResult Upload()
 {
     tUser user = Session[CDictionary.LOGIN_USER] as tUser;
     if (user == null)
     {
         return View("../Login/Login");//Login
     }
     else
     {
         ViewBag.User = "******" + user.fUserName + "[" + user.fMail + "]";
         return View();//Upload
     }
 }
Example #28
0
        public override bool ValidateUser(string username, string password)
        {
            bool isValid = false;

            _UserRep = BootStrapper.GetCurrentUserRepository();
            tUser user = _UserRep.GetSingleByUsernamePassword(username, password);

            if (user != null)
            {
                isValid = (bool)user.Approved;// && user.UserStatus == (int)B2B.Core.Enums.enmUserStatus.Active;
            }
            return(isValid);
        }
Example #29
0
        public void ResetUserPassword(int id)
        {
            BeginTransaction();
            tUser result = Context.tUsers.Find(id);

            if (result == null)
            {
                throw new UserNotFoundException();
            }
            result.HasEmptyPassword = true;
            Context.SaveChanges();
            EndTransaction();
        }
        public ActionResult Edit(int id)
        {
            List <tRole>     roleData            = _roleRepository.All.ToList();
            List <tCategory> partnerCategoryData = _categoryRepository.GetListByIDCategoryType((int)Enums.enmCategoryTypes.PartnersCategory);
            List <tCategory> cityData            = _categoryRepository.GetListByIDCategoryType((int)Enums.enmCategoryTypes.City);

            ViewBag.roleData     = roleData;
            ViewBag.categoryData = partnerCategoryData;
            ViewBag.cityData     = cityData;
            tUser currentUser = _userRepository.Find(id);

            return(View(currentUser));
        }