Пример #1
0
 public static bool VerifyHashedPassword(TblUsers user, string password)
 {
     //byte[] buffer4;
     //if (hashedPassword == null)
     //{
     //    return false;
     //}
     //if (password == null)
     //{
     //    throw new ArgumentNullException("password");
     //}
     //byte[] src = Convert.FromBase64String(hashedPassword);
     //if ((src.Length != 0x31) || (src[0] != 0))
     //{
     //    return false;
     //}
     //byte[] dst = new byte[0x10];
     //Buffer.BlockCopy(src, 1, dst, 0, 0x10);
     //byte[] buffer3 = new byte[0x20];
     //Buffer.BlockCopy(src, 0x11, buffer3, 0, 0x20);
     //using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, dst, 0x3e8))
     //{
     //    buffer4 = bytes.GetBytes(0x20);
     //}
     ////return ByteArraysEqual(buffer3, buffer4);
     //return buffer3.ToString().Equals(buffer4);
     return(user.PasswordHash.Equals(CreatePasswordHash(password, user.PasswordSalt)));
 }
Пример #2
0
        public static bool SendConfirmEmail(TblUsers user)
        {
            var message = new MimeMessage();

            message.From.Add(new MailboxAddress("Shop Gear", "*****@*****.**"));
            message.To.Add(new MailboxAddress(user.DisplayName, user.Email));
            message.Subject = "cc";

            message.Body = new TextPart("plain")
            {
                Text = user.CodeConfirm
            };

            using (var client = new SmtpClient())
            {
                client.Connect("smtp.gmail.com", 587);


                // Note: since we don't have an OAuth2 token, disable
                // the XOAUTH2 authentication mechanism.
                client.AuthenticationMechanisms.Remove("XOAUTH2");

                // Note: only needed if the SMTP server requires authentication
                client.Authenticate("*****@*****.**", "Xuanbac771998");

                client.Send(message);
                client.Disconnect(true);
            }

            return(false);
        }
Пример #3
0
        // GET: UsersControler/Details/5
        public async Task <ActionResult> Details(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            //List<TblUsers> users = new List<TblUsers>();
            //SerializeObject
            TblUsers users = new TblUsers();

            var response = await _services.Client.GetAsync($"api/TblUsers/{id}");

            if (response.Content == null)
            {
                return(NotFound());
            }

            if (response.IsSuccessStatusCode)
            {
                var loadedUsers = response.Content.ReadAsStringAsync().Result;
                users = JsonConvert.DeserializeObject <TblUsers>(loadedUsers);
            }
            return(View(users));
        }
Пример #4
0
        public async Task <ActionResult <TblUsers> > setStatus(UsernameDTO usernameDTO)
        {
            TblUsers userEntity = _context.TblUsers
                                  .FromSqlRaw("select * from tblUsers where Username = {0}", usernameDTO.Username).First();

            if (userEntity != null)
            {
                if (userEntity.Status.Equals("active"))
                {
                    userEntity.Status = "banned";
                    _context.Entry(userEntity).State = EntityState.Modified;
                    await _context.SaveChangesAsync();
                }
                else if (userEntity.Status.Equals("banned"))
                {
                    userEntity.Status = "active";
                    _context.Entry(userEntity).State = EntityState.Modified;
                    await _context.SaveChangesAsync();
                }
            }
            else
            {
                return(NotFound());
            }
            return(userEntity);
        }
Пример #5
0
        public async Task <IActionResult> Edit(int id, [Bind("UserId,Username,Password,ContactName,Email,Phone,Company,Isadmin")] TblUsers tblUsers)
        {
            AddPageHeader("Edit customer information", "");
            if (id != tblUsers.UserId)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(tblUsers);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!TblUsersExists(tblUsers.UserId))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(tblUsers));
        }
Пример #6
0
        public async Task <ActionResult <TblUsers> > PostTblUsers(TblUsers tblUsers)
        {
            try
            {
                validator.ValidateUserFields(tblUsers);
            }
            catch (ArgumentException e)
            {
                return(BadRequest(e.Message));
            }

            _context.TblUsers.Add(tblUsers);
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (TblUsersExists(tblUsers.Username))
                {
                    return(Conflict());
                }
                else
                {
                    throw;
                }
            }

            return(CreatedAtAction("GetTblUsers", new { id = tblUsers.Username }, tblUsers));
        }
Пример #7
0
        public void Update(TblUsers obj)
        {
            //throw new NotImplementedException();

            TblUsers user = GetById(obj.Id);

            if (user != null)
            {
                user.UpdateBy = obj.UpdateBy;

                if (obj.locked && !user.locked)
                {
                    //user.LockTime = DateTime.Now;
                    user.LockedBy = obj.UpdateBy;
                    user.LockTime = obj.LockTime;
                }
                else if (!obj.locked && user.locked)
                {
                    user.LastunlockedBy = obj.UpdateBy;
                    //user.LastunlockTime = obj.UpdateTime.Value;
                    user.LockedBy = null;
                    user.LockTime = null;
                }

                user.Userrole = obj.Userrole;

                Save(user);
            }
        }
Пример #8
0
        public int AddUser(TblUsers TblUsers)
        {
            _context.TblUsers.Add(TblUsers);
            _context.SaveChanges();

            return(TblUsers.Id);
        }
Пример #9
0
 public ActionResult CreateUser(RegisterViewModel register)
 {
     if (!ModelState.IsValid)
     {
         return(View(register));
     }
     if (!_iUser.IsMobileNumberExist(register.Mobile))
     {
         TblUsers users1 = new TblUsers();
         users1.IsActive = true;
         users1.Mobile   = register.Mobile;
         users1.Name     = register.Name;
         users1.Code     = CodeGenerators.ActiveCode();
         users1.Password = HashGenerators.EncodingPassWithMd5(register.Password);
         users1.RoleId   = 1;
         TblUsers user = users1;
         this._iUser.AddUser(user);
         return(base.RedirectToAction("Index"));
     }
     else
     {
         ModelState.AddModelError("Mobile", "شما قبلا ثبت نام کرده اید");
         return(View(register));
     }
 }
Пример #10
0
 public static void tryLogout()
 {
     loggedUser = null;
     GlobalMethods.changeLoginStatus();
     GlobalMethods.main.tabLogin.IsSelected = true;
     MessageBox.Show("You have successfully logged-out");
 }
Пример #11
0
        public static bool AreParentAndChildByCurriculum(TblUsers parent, TblUsers child, TblCurriculums curriculum)
        {
            IList <TblPermissions> parentPermissions =
                ServerModel.DB.Query <TblPermissions>(
                    new AndCondition(
                        new CompareCondition <int>(
                            DataObject.Schema.OwnerUserRef,
                            new ValueCondition <int>(parent.ID), COMPARE_KIND.EQUAL),
                        new CompareCondition <int>(
                            DataObject.Schema.CourseRef,
                            new ValueCondition <int>(curriculum.ID), COMPARE_KIND.EQUAL)));

            IList <TblPermissions> childPermissions =
                ServerModel.DB.Query <TblPermissions>(
                    new AndCondition(
                        new CompareCondition <int>(
                            DataObject.Schema.OwnerUserRef,
                            new ValueCondition <int>(child.ID), COMPARE_KIND.EQUAL),
                        new CompareCondition <int>(
                            DataObject.Schema.CourseRef,
                            new ValueCondition <int>(curriculum.ID), COMPARE_KIND.EQUAL)));

            foreach (TblPermissions parentPermission in parentPermissions)
            {
                foreach (TblPermissions childPermission in childPermissions)
                {
                    if (childPermission.ParentPermitionRef.HasValue &&
                        childPermission.ParentPermitionRef.Value == parentPermission.ID)
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }
Пример #12
0
        public static TblUsers CreateUser(string email, string phoneNumber, string password, string fullname, int provinceId, int districtId, int wardId, string place)
        {
            using (ComputerAccessoriesContext db = new ComputerAccessoriesContext())
            {
                try
                {
                    var checkUser = db.TblUsers.Where(x => x.UserName.Equals(email)).FirstOrDefault();
                    if (checkUser != null)
                    {
                        return(null);
                    }
                    TblUsers user = new TblUsers();
                    user.Email                = email;
                    user.DisplayName          = fullname;
                    user.PasswordSalt         = CreateSalt();
                    user.PasswordHash         = CreatePasswordHash(password, user.PasswordSalt);
                    user.CreatedDate          = DateTime.Now;
                    user.IsActivated          = true;
                    user.LockoutEnabled       = false;
                    user.UserName             = email;
                    user.PhoneNumber          = phoneNumber;
                    user.EmailConfirmed       = false;
                    user.PhoneNumberConfirmed = false;
                    user.TwoFactorEnabled     = false;
                    user.LockoutEnabled       = false;
                    user.AccessFailedCount    = 0;
                    Random rand = new Random();
                    var    code = rand.Next(100000, 999999).ToString();

                    user.CodeConfirm = code;

                    user.SecurityStamp = Guid.NewGuid().ToString();

                    db.TblUsers.Add(user);
                    db.SaveChanges();
                    var result = GetUser(user.Email);
                    if (result == null)
                    {
                        return(null);
                    }

                    TblUserAddress tblUserAddress = new TblUserAddress();
                    tblUserAddress.UserId      = result.Id;
                    tblUserAddress.ProvinceId  = provinceId;
                    tblUserAddress.DistrictId  = districtId;
                    tblUserAddress.WardId      = wardId;
                    tblUserAddress.PlaceDetail = place;

                    db.TblUserAddress.Add(tblUserAddress);
                    db.SaveChanges();
                    return(user);
                }
                catch (Exception e)
                {
                    return(null);

                    throw;
                }
            }
        }
Пример #13
0
        public async Task <ActionResult <TransactionHistory> > createTransactionHistory(TransactionHistoryDTO dto)
        {
            TransactionHistory transactionHistory = new TransactionHistory(); //truyền xuống dto có 4 field: postid, giver, receiver, transactiondate

            transactionHistory.PostId          = dto.PostId;
            transactionHistory.Giver           = dto.Giver;
            transactionHistory.Receiver        = dto.Receiver;
            transactionHistory.TransactionDate = DateTime.Now;
            TblUsersHavingPosts usersHavingPosts = _context.TblUsersHavingPosts.FromSqlRaw("select * from TblUsersHavingPosts where " +
                                                                                           "Username = {0} and PostId = {1}", dto.Receiver, dto.PostId).First(); //tìm bài post của freelancer đã hoàn thành

            usersHavingPosts.Status = "finished";                                                                                                                //set status = finished
            _context.Entry(usersHavingPosts).State = EntityState.Modified;
            TblPosts post = _context.TblPosts.FromSqlRaw("select * from TblPosts where " +
                                                         "Id = {0}", dto.PostId).First(); //tìm bài post trong TblPosts

            post.IsPublic = false;                                                        //ko public bài post nữa
            _context.Entry(post).State = EntityState.Modified;
            Int64 postAmount = _context.TblPosts.Find(dto.PostId).Amount;                 //lấy ra amount của bài post

            transactionHistory.Amount = postAmount;                                       //lưu vào transaction history
            _context.TransactionHistory.Add(transactionHistory);                          //add transaction dto vào table TransactionHistory
            TblUsers company = _context.TblUsers.Find(dto.Giver);                         //tìm ra company

            company.Amount -= postAmount;                                                 //lấy amount hiện tại của company - amount của bài post đã finished
            _context.Entry(company).State = EntityState.Modified;
            TblUsers freelancer = _context.TblUsers.Find(dto.Receiver);                   //tìm ra freelancer

            freelancer.Amount += postAmount;                                              //lấy amount hiện tại của freelancer + amount của bài post đã finished
            _context.Entry(freelancer).State = EntityState.Modified;
            await _context.SaveChangesAsync();

            return(transactionHistory);
        }
Пример #14
0
        public override void Loaded()
        {
            base.Loaded();
            teacher = ServerModel.DB.Load <TblUsers>(TeacherId);
            if (CourseId != -1)
            {
                course        = ServerModel.DB.Load <TblCourses>(CourseId);
                Caption.Value = pageCaption.
                                Replace("{0}", courseStr).
                                Replace("{1}", course.Name).
                                Replace("{2}", teacher.DisplayName);
                Description.Value = pageDescription.
                                    Replace("{0}", courseStr).
                                    Replace("{1}", course.Name).
                                    Replace("{2}", teacher.DisplayName);

                fillCourseOperationsTable();
            }
            if (CurriculumId != -1)
            {
                curriculum    = ServerModel.DB.Load <TblCurriculums>(CurriculumId);
                Caption.Value = pageCaption.
                                Replace("{0}", curriculumStr).
                                Replace("{1}", curriculum.Name).
                                Replace("{2}", teacher.DisplayName);
                Description.Value = pageDescription.
                                    Replace("{0}", curriculumStr).
                                    Replace("{1}", curriculum.Name).
                                    Replace("{2}", teacher.DisplayName);

                fillCurriculumOperationsTable();
            }

            Title.Value = Caption.Value;
        }
Пример #15
0
        public Task <ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
        {
            //throw new NotImplementedException();
            var clone    = principal.Clone();
            var identity = (ClaimsIdentity)clone.Identity;
            var userName = identity.Name;

            var user = Context.TblUsers
                       .FirstOrDefault(u => u.Username == userName);

            if (user == null)
            {
                user = new TblUsers {
                    Username = userName, UpdateBy = userName
                };
                //user.InsertTime = DateTime.Now;
                Context.TblUsers.Add(user);
                Context.SaveChanges();
            }

            var role = user == null?0:user.Userrole;

            var roles = Context.TblRoles;

            foreach (var r in roles)
            {
                if (role >= r.Id)
                {
                    var claim = new Claim(identity.RoleClaimType, r.Rolename);
                    identity.AddClaim(claim);
                }
            }
            return(Task.FromResult(clone));
        }
        public async Task <IActionResult> PutUsers(int id, TblUsers users)
        {
            if (id != users.Id)
            {
                return(BadRequest());
            }

            _context.Entry(users).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!UsersExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Пример #17
0
        public async Task <ActionResult <TblUsers> > PostTblUsers(TblUsers tblUsers)
        {
            _context.TblUsers.Add(tblUsers);
            await _context.SaveChangesAsync();

            return(CreatedAtAction(nameof(GetTblUsers), new { id = tblUsers.UsersId }, tblUsers));
        }
Пример #18
0
        private static CustomUser CreateUser(TblUsers user)
        {
            var roleIDs = ServerModel.DB.LookupMany2ManyIds <FxRoles>(user, null);
            var roles   = new List <string>(ServerModel.DB.Load <FxRoles>(roleIDs).Select(r => r.Name));

            return(new CustomUser(user.ID, user.FirstName, user.LastName, user.Login, user.PasswordHash, user.Email, roles));
        }
Пример #19
0
        public static TblUserAnswers GetUserAnswerForQuestion(TblUsers user, TblQuestions question)
        {
            IList <TblUserAnswers> answers = ServerModel.DB.Query <TblUserAnswers>(new AndCondition(
                                                                                       new CompareCondition <int>(
                                                                                           DataObject.Schema.UserRef,
                                                                                           new ValueCondition <int>(user.ID), COMPARE_KIND.EQUAL),
                                                                                       new CompareCondition <int>(
                                                                                           DataObject.Schema.QuestionRef,
                                                                                           new ValueCondition <int>(question.ID), COMPARE_KIND.EQUAL)));

            TblUserAnswers lastAnswer = null;

            foreach (TblUserAnswers answer in answers)
            {
                if (lastAnswer == null)
                {
                    lastAnswer = answer;
                }
                else
                {
                    if (lastAnswer.Date < answer.Date)
                    {
                        lastAnswer = answer;
                    }
                }
            }

            return(lastAnswer);
        }
Пример #20
0
        /// <summary>
        /// Function set isDelete of user = true when delete Organization
        /// CreatedBy: HaiHM
        /// CreatedDate: 2019/6/3
        /// </summary>
        /// <param name="authoritys"></param>
        /// <param name="userId"></param>
        private void DeleteUser(int organizationId)
        {
            try
            {
                using (var ts = new TransactionScope())
                {
                    // Update tblUsers
                    List <TblOrganizationUser> data = db.TblOrganizationUser.Where(x => x.OrganizationId == organizationId).ToList();
                    if (data != null)
                    {
                        foreach (var item in data)
                        {
                            TblUsers user = db.TblUsers.Where(u => u.IsDelete == false && u.Id == item.UserId).FirstOrDefault();
                            if (user != null)
                            {
                                user.IsDelete        = true;
                                db.Entry(user).State = EntityState.Modified;
                                db.SaveChanges();
                            }
                        }
                    }

                    ts.Complete();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Пример #21
0
        public async Task <ActionResult <TblUsers> > CheckLoginUser([FromBody] LoginUserDTO loginUserDTO)
        {
            TblUsers userEntity = _context.TblUsers.Find(loginUserDTO.Username);

            if (userEntity != null)
            {
                if (userEntity.RoleId == 2 && userEntity.Status.Equals("active"))
                {
                    return(userEntity);
                }
                else if (userEntity.RoleId == 2 && userEntity.Status.Equals("banned"))
                {
                    return(NotFound());
                }
            }
            else
            {
                TblUsers dto = new TblUsers();
                dto.Username = loginUserDTO.Username;
                dto.Password = "******";
                dto.RoleId   = 2;
                dto.Fullname = loginUserDTO.Fullname;
                dto.Rating   = 0;
                dto.Avatar   = loginUserDTO.Avatar;
                dto.Status   = "active";
                _context.TblUsers.Add(dto);
                await _context.SaveChangesAsync();

                return(dto);
            }
            return(Unauthorized());
        }
Пример #22
0
        public virtual async Task <UserInfoModel> PrepareUserInfoModelAsync(TblUsers user)
        {
            var result = user.Adapt <UserInfoModel>();

            result.ShowUserSubscriptionInfo = (await _userGroupsService.GetAsEnumerableAsync()).Any();

            if (user.UserCountry != null)
            {
                result.Country = user.UserCountry.GetLocalized(x => x.CountryName);
            }

            if (user.UserGroup != null && user.SubscriptionExpireDate > DateTime.Now)
            {
                var textColor       = string.IsNullOrWhiteSpace(user.UserGroup.GetLocalized(x => x.GroupTextColor)) ? "inherit" : user.UserGroup.GetLocalized(x => x.GroupTextColor);
                var backgroundColor = string.IsNullOrWhiteSpace(user.UserGroup.GetLocalized(x => x.GroupBackgroundColor)) ? "inherit" : user.UserGroup.GetLocalized(x => x.GroupBackgroundColor);
                var groupImage      = string.IsNullOrWhiteSpace(user.UserGroup.GetLocalized(x => x.GroupSmallIcon))
                    ? ""
                    : $@"<img style=""max-height: 18px;"" src=""{
                            user.UserGroup.GetLocalized(x => x.GroupSmallIcon)
                        }""/>";

                result.UserGroup =
                    $@"<span class=""badge"" style=""color: {textColor}; background-color:{backgroundColor}"">{
                            groupImage
                        } {user.UserGroup.GetLocalized(x => x.GroupName)}</span>";

                var highestGroup = await _userGroupsService.GetHighestUserGroupAsync();

                result.UserSubscribedToHighestPlan   = user.UserGroup.GroupPriority >= highestGroup.GroupPriority;
                result.WhenExtendCurrentPlanBtnShown = user.UserGroup.WhenExtendCurrentPlanBtnShown;

                if (user.UserGroup.MaxDownloadCount > 0)
                {
                    var maxDownloadPeriodTypeStr = _localizationService.GetResource(user.UserGroup.MaxDownloadPeriodType.ToString());
                    result.UserGroupDownloadLimit = user.UserGroup.MaxDownloadCount + _localizationService.GetResource("Per") + maxDownloadPeriodTypeStr;
                }
                else
                {
                    result.UserGroupDownloadLimit = _localizationService.GetResource("Unlimited");
                }
            }
            else
            {
                result.UserGroup              = $"<small>({_localizationService.GetResource("YouNotSubscribedToPlan")})</small>";
                result.SubscriptionDate       = null;
                result.SubscriptionExpireDate = null;
            }

            if (user.MaxDownloadCount > 0)
            {
                var maxDownloadPeriodTypeStr = _localizationService.GetResource(user.MaxDownloadPeriodType.ToString());
                result.DownloadLimit = user.MaxDownloadCount + _localizationService.GetResource("Per") + maxDownloadPeriodTypeStr;
            }
            else
            {
                result.DownloadLimit = _localizationService.GetResource("Unlimited");
            }

            return(result);
        }
Пример #23
0
        /// <summary>
        /// List User Test
        /// </summary>
        /// <param name="idTest"></param>
        /// <returns></returns>
        TblUsers GetUser(int idTest)
        {
            List <TblUsers> lstUser = new List <TblUsers>();

            TblUsers userAdd = new TblUsers
            {
                //Id =
                UserName           = "******",
                Password           = "******",
                FullName           = "Hoang Manh Hai",
                Email              = "*****@*****.**",
                PhoneNumber        = "1234567890",
                CreateBy           = "Admin",
                CreateDate         = Convert.ToDateTime("2018-12-26"),
                UpdateBy           = "",
                UpdateDate         = Convert.ToDateTime("2019-03-29"),
                IsDelete           = false,
                IsLock             = false,
                Avatar             = null,
                Address            = null,
                LastLogin          = null,
                Position           = null,
                EmailConfirmed     = true,
                Gender             = 1,
                LoginFail          = 0,
                HistoryPassword    = "******",
                DateUpdatePassword = Convert.ToDateTime("2019-04-01")
            };

            TblUsers userLock = new TblUsers
            {
                Id                 = 18,
                UserName           = "******",
                Password           = "******",
                FullName           = "Hoang Manh Hai",
                Email              = "*****@*****.**",
                PhoneNumber        = "1234567890",
                CreateBy           = "Admin",
                CreateDate         = Convert.ToDateTime("2018-12-26"),
                UpdateBy           = "",
                UpdateDate         = Convert.ToDateTime("2019-03-29"),
                IsDelete           = false,
                IsLock             = false,
                Avatar             = null,
                Address            = null,
                LastLogin          = null,
                Position           = null,
                EmailConfirmed     = true,
                Gender             = 1,
                LoginFail          = 0,
                HistoryPassword    = "******",
                DateUpdatePassword = Convert.ToDateTime("2019-04-01")
            };

            lstUser.Add(userAdd);
            lstUser.Add(userLock);

            return(lstUser.Find(u => u.Id == idTest));
        }
        public ActionResult DeleteConfirmed(int id)
        {
            TblUsers tblUsers = db.TblUsers.Find(id);

            db.TblUsers.Remove(tblUsers);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Пример #25
0
        //Create [email protected] with password=Admin@123456 in the Admin role
        public virtual void Initialize(AppDbContext db)
        {
            ApplicationUserManager userManager;
            ApplicationRoleManager roleManager;

            try
            {
                userManager = HttpContext.Current.GetOwinContext().GetUserManager <ApplicationUserManager>();
                roleManager = HttpContext.Current.GetOwinContext().Get <ApplicationRoleManager>();
                if (userManager == null || roleManager == null)
                {
                    throw new Exception();
                }
            }
            catch
            {
                userManager = new ApplicationUserManager(new UserStore <TblUsers>(db));
                roleManager = new ApplicationRoleManager(new RoleStore <IdentityRole>(db));
            }

            const string name     = "*****@*****.**";
            const string password = "******";
            const string roleName = "Admin";

            //Create Admin Role if it does not exist
            var role = roleManager.FindByName(roleName);

            if (role == null)
            {
                role = new IdentityRole(roleName);
                roleManager.Create(role);

                var user = userManager.FindByName(name);
                if (user == null)
                {
                    user = new TblUsers()
                    {
                        UserName         = name,
                        Email            = name,
                        RegisterDate     = DateTime.Now,
                        EmailConfirmed   = true,
                        FirstName        = "Admin",
                        MaxDownloadCount = 0,
                    };
                    userManager.Create(user, password);
                    userManager.SetLockoutEnabled(user.Id, false);
                }

                // Add user admin to Role Admin if not already added
                var rolesForUser = userManager.GetRoles(user.Id);
                if (!rolesForUser.Contains(role.Name))
                {
                    userManager.AddToRole(user.Id, role.Name);
                }

                db.SaveChanges();
            }
        }
Пример #26
0
        //[Test]
        public void TestEditUser()
        {
            UserAndOrgViewModel model = new UserAndOrgViewModel();

            TblUsers user = new TblUsers
            {
                //Id =
                UserName           = "******",
                Password           = "******",
                FullName           = "Hoang Manh Hai",
                Email              = "*****@*****.**",
                PhoneNumber        = "1234567890",
                CreateBy           = "Admin",
                CreateDate         = Convert.ToDateTime("2018-12-26T11 =53 =47.327"),
                UpdateBy           = "",
                UpdateDate         = Convert.ToDateTime("2019-03-29T11 =53 =00.263"),
                IsDelete           = false,
                IsLock             = false,
                Avatar             = null,
                Address            = null,
                LastLogin          = null,
                Position           = null,
                EmailConfirmed     = true,
                Gender             = 1,
                LoginFail          = 0,
                HistoryPassword    = "******",
                DateUpdatePassword = Convert.ToDateTime("2019-04-01T00 =00 =00")
            };

            TblOrganization org = new TblOrganization()
            {
                OrganizationId         = 2,
                OrganizationCode       = "MP",
                OrganizationParentCode = null,
                OrganizationName       = "CT TNHH Minh Phúc",
                OrganizationAddress    = "Mễ Trì, Nam Từ Liêm",
                OrganizationEmail      = "*****@*****.**",
                OrganizationPhone      = null,
                OrganizationTaxCode    = null,
                OrganizationRemark     = null,
                OrganizationFrom       = null,
                CreateBy             = null,
                CreateDate           = null,
                UpdateBy             = null,
                UpdateDate           = Convert.ToDateTime("2019-03-03 00:00:00.000"),
                IsActive             = false,
                IsLock               = null,
                IsDelete             = false,
                OrganizationTo       = null,
                OrganizationHomePage = null
            };

            // Add model
            model.tblUsers        = user;
            model.tblOrganization = org;

            //Assert.AreEqual(save, _ac.Compare(2, 1));
        }
Пример #27
0
        void Initialize()
        {
            TblCourses course = new TblCourses
            {
                Name = "course"
            };

            ServerModel.DB.Insert(course);

            TblOrganizations organisation = new TblOrganizations
            {
                CourseRef = course.ID,
                Title     = "organisation"
            };

            ServerModel.DB.Insert(organisation);

            TblResources resource = new TblResources
            {
                CourseRef  = course.ID,
                Type       = "bob",
                Identifier = "resource"
            };

            ServerModel.DB.Insert(resource);

            TblItems item = new TblItems
            {
                OrganizationRef = organisation.ID,
                ResourceRef     = resource.ID,
                Title           = "item"
            };

            ServerModel.DB.Insert(item);

            TblLearnerAttempts attempt = new TblLearnerAttempts
            {
                //bug with foreign keys!
            };

            ServerModel.DB.Insert(attempt);

            TblLearnerSessions session = new TblLearnerSessions
            {
                ItemRef           = item.ID,
                LearnerAttemptRef = attempt.ID
            };

            ServerModel.DB.Insert(session);
            currentSession = session;

            TblUsers user = GetUniqueUserForTesting();

            ServerModel.DB.Insert(user);

            sessionID = session.ID;
            userID    = user.ID;
        }
Пример #28
0
        public ResponseModel AddUser(UserDto userNew, string password, string UserIDLogin)
        {
            var           context = _httpContextAccessor.HttpContext;
            ResponseModel res     = (new ResponseModel
            {
                Data = "",
                Status = "200",
                Message = ""
            });
            var tbluser = new TblUsers
            {
                UserName         = userNew.UserName,
                FamilyName       = userNew.FamilyName,
                GivenName        = userNew.GivenName,
                TypeOfAccount    = userNew.TypeOfAccount,
                Email            = userNew.Email,
                ContactByEmail   = userNew.ContactByEmail,
                EncryptionActive = userNew.EncryptionActive,
                DeletedOn        = null,
                Cid    = GetCID(context.User.Identity.Name),
                RoleId = userNew.RoleID
            };

            try
            {
                if (string.IsNullOrWhiteSpace(password))
                {
                    res.Data    = "";
                    res.Status  = "500";
                    res.Message = "Password is required";
                    return(res);
                }
                if (_context.TblUsers.Any(x => x.UserName == userNew.UserName && x.DeletedOn == null))
                {
                    res.Data    = "";
                    res.Status  = "500";
                    res.Message = "Username \"" + userNew.UserName + "\" is already taken";
                    return(res);
                }
                byte[] passwordHash, passwordSalt;
                CreatePasswordHash(password, out passwordHash, out passwordSalt);

                tbluser.PasswordHash = passwordHash;
                tbluser.PasswordSalt = passwordSalt;

                _context.TblUsers.Add(tbluser);
                _context.SaveChanges();
                res.Data = tbluser;
            }
            catch (Exception ex)
            {
                res.Data    = "";
                res.Status  = "500";
                res.Message = ex.Message;
            }
            return(res);
        }
Пример #29
0
 private string UserList_ActionUrl(TblUsers user)
 {
     return(ServerModel.Forms.BuildRedirectUrl(new Admin_RemoveUserFromGroupController
     {
         BackUrl = Request.RawUrl,
         GroupID = Controller.GroupID,
         UserID = user.ID
     }));
 }
Пример #30
0
        public void UpdateButton_Click()
        {
            TblUsers currentUser = ServerModel.DB.Load <TblUsers>(ServerModel.User.Current.ID);

            currentUser.FirstName = FirstName.Value;
            currentUser.LastName  = SecondName.Value;
            currentUser.Email     = Email.Value;

            ServerModel.DB.Update(currentUser);
        }
Пример #31
0
        public override void Loaded()
        {
            base.Loaded();

            course = ServerModel.DB.Load<TblCourses>(CourseId);
            teacher = ServerModel.DB.Load<TblUsers>(TeacherId);

            Caption.Value = pageCaption.
                Replace("{0}", course.Name).
                Replace("{1}", teacher.DisplayName);
            Description.Value = pageDescription.
                Replace("{0}", course.Name).
                Replace("{1}", teacher.DisplayName);
            Title.Value = Caption.Value;

            fillOperationsTable();
        }
Пример #32
0
        public override void Loaded()
        {
            base.Loaded();
            teacher = ServerModel.DB.Load<TblUsers>(TeacherId);
            if (CourseId != -1)
            {
                course = ServerModel.DB.Load<TblCourses>(CourseId);
                Caption.Value = pageCaption.
                    Replace("{0}", courseStr).
                    Replace("{1}", course.Name).
                    Replace("{2}", teacher.DisplayName);
                Description.Value = pageDescription.
                    Replace("{0}", courseStr).
                    Replace("{1}", course.Name).
                    Replace("{2}", teacher.DisplayName);

                fillCourseOperationsTable();
            }
            if (CurriculumId != -1)
            {
                curriculum = ServerModel.DB.Load<TblCurriculums>(CurriculumId);
                Caption.Value = pageCaption.
                    Replace("{0}", curriculumStr).
                    Replace("{1}", curriculum.Name).
                    Replace("{2}", teacher.DisplayName);
                Description.Value = pageDescription.
                    Replace("{0}", curriculumStr).
                    Replace("{1}", curriculum.Name).
                    Replace("{2}", teacher.DisplayName);

                fillCurriculumOperationsTable();
            }

            Title.Value = Caption.Value;

        }
Пример #33
0
        public static TblUserAnswers GetUserAnswerForQuestion(TblUsers user, TblQuestions question)
        {
            IList<TblUserAnswers> answers = ServerModel.DB.Query<TblUserAnswers>(new AndCondition(
                new CompareCondition<int>(
                                     DataObject.Schema.UserRef,
                                     new ValueCondition<int>(user.ID), COMPARE_KIND.EQUAL),
                new CompareCondition<int>(
                                     DataObject.Schema.QuestionRef,
                                     new ValueCondition<int>(question.ID), COMPARE_KIND.EQUAL)));

            TblUserAnswers lastAnswer = null;
            foreach (TblUserAnswers answer in answers)
            {
                if (lastAnswer == null)
                {
                    lastAnswer = answer;
                }
                else
                {
                    if (lastAnswer.Date < answer.Date)
                    {
                        lastAnswer = answer;
                    }
                }
            }

            return lastAnswer;
        }
Пример #34
0
 public static IList<TblGroups> GetUserGroups(TblUsers user)
 {
     IList<int> groupIDs = ServerModel.DB.LookupMany2ManyIds<TblGroups>(user, null);
     return ServerModel.DB.Load<TblGroups>(groupIDs);
 }
Пример #35
0
        public static bool CanChildDelegateCourse(TblPermissions parentPermission, TblUsers child, TblCourses course)
        {
            IList<TblPermissions> childPermissions =
                ServerModel.DB.Query<TblPermissions>(
                      new AndCondition(
                         new CompareCondition<int>(
                            DataObject.Schema.OwnerUserRef,
                            new ValueCondition<int>(child.ID), COMPARE_KIND.EQUAL),
                         new CompareCondition<int>(
                            DataObject.Schema.CourseRef,
                            new ValueCondition<int>(course.ID), COMPARE_KIND.EQUAL)));

            foreach (TblPermissions childPermission in childPermissions)
            {
                if (childPermission.ParentPermitionRef.HasValue
                    && childPermission.ParentPermitionRef.Value == parentPermission.ID)
                {
                    return childPermission.CanBeDelagated;
                }
            }

            return false;
        }
Пример #36
0
        public static bool AreParentAndChildByCurriculum(TblPermissions parentPermission, TblUsers child, TblCurriculums curriculum)
        {
            IList<TblPermissions> childPermissions =
                ServerModel.DB.Query<TblPermissions>(
                      new AndCondition(
                         new CompareCondition<int>(
                            DataObject.Schema.OwnerUserRef,
                            new ValueCondition<int>(child.ID), COMPARE_KIND.EQUAL),
                         new CompareCondition<int>(
                            DataObject.Schema.CurriculumRef,
                            new ValueCondition<int>(curriculum.ID), COMPARE_KIND.EQUAL)));

            foreach (TblPermissions childPermission in childPermissions)
            {
                if (childPermission.ParentPermitionRef.HasValue
                    && childPermission.ParentPermitionRef.Value == parentPermission.ID)
                {
                    return true;
                }
            }

            return false;
        }
Пример #37
0
        public static TblPermissions GetPermissionForCurriculum(TblPermissions parentPermission, TblUsers user, TblCurriculums curriculum, FxCurriculumOperations operation)
        {
            IList<TblPermissions> permissions = ServerModel.DB.Query<TblPermissions>(
                           new AndCondition(
                              new CompareCondition<int>(
                                 DataObject.Schema.OwnerUserRef,
                                 new ValueCondition<int>(user.ID), COMPARE_KIND.EQUAL),
                              new CompareCondition<int>(
                                 DataObject.Schema.CurriculumOperationRef,
                                 new ValueCondition<int>(operation.ID), COMPARE_KIND.EQUAL),
                              new CompareCondition<int>(
                                 DataObject.Schema.CurriculumRef,
                                 new ValueCondition<int>(curriculum.ID), COMPARE_KIND.EQUAL),
                              new CompareCondition<int>(
                                 DataObject.Schema.ParentPermitionRef,
                                 new ValueCondition<int>(parentPermission.ID), COMPARE_KIND.EQUAL)));

            if (permissions.Count == 0)
            {
                return null;
            }

            return permissions[0];
        }
        public void fillStatistic()
        {
            double totalstudntresoult = 0;
            double totalstagerank = 0;
            user = ServerModel.DB.Load<TblUsers>(UserId);
            curriculum = ServerModel.DB.Load<TblCurriculums>(CurriculumID);
            foreach (TblStages stage in TeacherHelper.StagesOfCurriculum(curriculum))
            {

                foreach (TblThemes theme in TeacherHelper.ThemesOfStage(stage))
                {
                    double result = 0; Name_Stage.Add(theme.Name);
                    double totalresult = 0;
                    int learnercount = TeacherHelper.GetLastIndexOfAttempts(user.ID, theme.ID);
                    TblOrganizations organization;
                    organization = ServerModel.DB.Load<TblOrganizations>(theme.OrganizationRef);
                    foreach (TblItems items in TeacherHelper.ItemsOfOrganization(organization))
                    {
                        totalresult += Convert.ToDouble(items.Rank);
                    }

                    foreach (TblLearnerAttempts attempt in TeacherHelper.AttemptsOfTheme(theme))
                    {
                        if (attempt.ID == TeacherHelper.GetLastLearnerAttempt(user.ID, theme.ID))

                            foreach (TblLearnerSessions session in TeacherHelper.SessionsOfAttempt(attempt))
                            {
                                CmiDataModel cmiDataModel = new CmiDataModel(session.ID, user.ID, false);
                                List<TblVarsInteractions> interactionsCollection = cmiDataModel.GetCollection<TblVarsInteractions>("interactions.*.*");

                                for (int i = 0, j = 0; i < int.Parse(cmiDataModel.GetValue("interactions._count")); i++)
                                {
                                    for (; j < interactionsCollection.Count && i == interactionsCollection[j].Number; j++)
                                    {
                                        if (interactionsCollection[j].Name == "result")
                                        {
                                            TblItems itm = ServerModel.DB.Load<TblItems>(session.ItemRef);
                                            if (interactionsCollection[j].Value == "correct") result += Convert.ToDouble(itm.Rank);
                                        }
                                    }

                                }

                            }
                    }
                    totalstudntresoult += result;
                    totalstagerank += totalresult;
                    Student_Stage_Count.Add(result);
                    Total_Stage_Count.Add(totalresult);
                }
            }

            Name_Stage.Add("Total");
            Student_Stage_Count.Add(totalstudntresoult);
            Total_Stage_Count.Add(totalstagerank);


            Saveto_Excel_Click();
        }
Пример #39
0
        private void fillStatisticTable()
        {
            IList<TblUsers> ilistusers;
            ilistusers = TeacherHelper.GetStudentsOfGroup(group);
            if (UserId > 0)
            {
                user = ServerModel.DB.Load<TblUsers>(UserId);
                ilistusers.Clear();
                ilistusers.Add(user);
            }
            StatisticTable.Rows.Clear();

            TableHeaderRow headerRow = new TableHeaderRow();

            TableHeaderCell headerCell = new TableHeaderCell();
            headerCell.Text = studentStr;
            headerRow.Cells.Add(headerCell);

            foreach (TblStages stage in TeacherHelper.StagesOfCurriculum(curriculum))
            {
                foreach (TblThemes theme in TeacherHelper.ThemesOfStage(stage))
                {
                    headerCell = new TableHeaderCell();
                    headerCell.Text = theme.Name;
                    headerRow.Cells.Add(headerCell);
                }
            }
            headerCell = new TableHeaderCell();
            headerCell.Text = totalStr;
            headerRow.Cells.Add(headerCell);

            headerCell = new TableHeaderCell();
            headerCell.Text = Translations.StatisticShowController_fillStatisticTable_Percent;
            headerRow.Cells.Add(headerCell);

            headerCell = new TableHeaderCell();
            headerCell.Text = "ECTS";
            headerRow.Cells.Add(headerCell);

            StatisticTable.Rows.Add(headerRow);
            foreach (TblUsers student in ilistusers)
            {
                var studentRow = new TableRow();
                TableCell studentCell = new TableHeaderCell { HorizontalAlign = HorizontalAlign.Center };
                studentCell.Controls.Add(new HyperLink
                {
                    Text = student.DisplayName,
                    NavigateUrl = ServerModel.Forms.BuildRedirectUrl(new StatisticShowGraphController
                    {
                        GroupID = GroupID,
                        CurriculumID = curriculum.ID,
                        UserId = student.ID,
                        BackUrl = RawUrl
                    })
                });


                studentRow.Cells.Add(studentCell);

                double pasedCurriculum = 0;
                double totalCurriculum = 0;
                foreach (TblStages stage in TeacherHelper.StagesOfCurriculum(curriculum))
                {
                    foreach (TblThemes theme in TeacherHelper.ThemesOfStage(stage))
                    {
                        double result = 0;
                        double totalresult = 0;
                        int learnercount = TeacherHelper.GetLastIndexOfAttempts(student.ID, theme.ID);
                        TblOrganizations organization;
                        organization = ServerModel.DB.Load<TblOrganizations>(theme.OrganizationRef);
                        foreach (TblItems items in TeacherHelper.ItemsOfOrganization(organization))
                        {
                            totalresult += Convert.ToDouble(items.Rank);
                        }

                        foreach (TblLearnerAttempts attempt in TeacherHelper.AttemptsOfTheme(theme))
                        {
                            if (attempt.ID == TeacherHelper.GetLastLearnerAttempt(student.ID, theme.ID))

                                foreach (TblLearnerSessions session in TeacherHelper.SessionsOfAttempt(attempt))
                                {
                                    CmiDataModel cmiDataModel = new CmiDataModel(session.ID, student.ID, false);
                                    List<TblVarsInteractions> interactionsCollection = cmiDataModel.GetCollection<TblVarsInteractions>("interactions.*.*");

                                    for (int i = 0, j = 0; i < int.Parse(cmiDataModel.GetValue("interactions._count")); i++)
                                    {
                                        for (; j < interactionsCollection.Count && i == interactionsCollection[j].Number; j++)
                                        {
                                            if (interactionsCollection[j].Name == "result")
                                            {
                                                TblItems itm = ServerModel.DB.Load<TblItems>(session.ItemRef);
                                                if (interactionsCollection[j].Value == "correct") result += Convert.ToDouble(itm.Rank);
                                            }
                                        }

                                    }

                                }
                        }



                        string attmpt = "";
                        if (learnercount > 0)
                        {
                            attmpt = "(" + learnercount.ToString() + " attempt )";
                        }
                        else if (learnercount == 0)
                        {
                            attmpt = "";
                        }

                        studentCell = new TableCell { HorizontalAlign = HorizontalAlign.Center };
                        studentCell.Controls.Add(new HyperLink
                        {
                            Text = result + "/" + totalresult + attmpt,
                            NavigateUrl = ServerModel.Forms.BuildRedirectUrl(new ThemeResultController
                            {
                                BackUrl = string.Empty,
                                LearnerAttemptId = TeacherHelper.GetLastLearnerAttempt(student.ID, theme.ID),

                            })
                        });

                        if (learnercount == 0)
                        {
                            studentCell.Enabled = false;
                            studentCell.BackColor = Color.Yellow;
                        }
                        else if (learnercount > 0) studentCell.BackColor = Color.YellowGreen;

                        pasedCurriculum += result;
                        totalCurriculum += totalresult;
                        studentRow.Cells.Add(studentCell);

                    }
                }

                studentCell = new TableCell
                {
                    HorizontalAlign = HorizontalAlign.Center,
                    Text = pasedCurriculum + "/" + totalCurriculum
                };
                studentRow.Cells.Add(studentCell);
                studentCell = new TableCell { HorizontalAlign = HorizontalAlign.Center };
                double temp_total;
                if (totalCurriculum != 0)
                    temp_total = pasedCurriculum / totalCurriculum * 100;
                else temp_total = 0;
                studentCell.Text = (temp_total).ToString("F2");
                studentRow.Cells.Add(studentCell);
                studentCell = new TableCell { HorizontalAlign = HorizontalAlign.Center };
                studentCell.Text = TeacherHelper.ECTS_code(temp_total);

                studentRow.Cells.Add(studentCell);
                StatisticTable.Rows.Add(studentRow);
            }

            if (StatisticTable.Rows.Count == 1)
            {
                StatisticTable.Visible = false;
                Message.Value = noStudents;
            }



        }
Пример #40
0
        private static TblUserAnswers GetLastUserAnswerForCompiledQuestion(TblQuestions q, TblUsers u)
        {
            var userAnswers = StudentRecordFinder.GetUserAnswersForQuestion(q, u.ID);

            var compiledAnswers = StudentRecordFinder.ExtractCompiledAnswers(userAnswers);

            return StatisticManager.FindLatestUserAnswer(compiledAnswers);
        }