Пример #1
0
        private static async Task AddUserRoleHistory(UsersInRole current, UserRoleOperations op)
        {
            UsersRoleHistoryServiceProxy hrhsvc = new UsersRoleHistoryServiceProxy();
            UsersRoleHistorySet          urhs   = new UsersRoleHistorySet();
            UsersRoleHistory             urh    = new UsersRoleHistory();

            urh.UserID      = current.UserID;
            urh.RoleID      = current.RoleID;
            urh.SubPriority = current.SubPriority;
            urh.OperatorID  = current.AdminID;
            urh.ChangeDate  = DateTime.UtcNow;
            switch (op)
            {
            case UserRoleOperations.Added:
                urh.Operation = urhs.OperationValues[0];
                break;

            case UserRoleOperations.Modified:
                urh.Operation = urhs.OperationValues[1];
                break;

            case UserRoleOperations.Deleted:
                urh.Operation = urhs.OperationValues[2];
                break;
            }
            await hrhsvc.AddOrUpdateEntitiesAsync(Cntx, urhs, new UsersRoleHistory[] { urh });
        }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (cboRoles.SelectedValue == "")
        {
            lblErr.Text = "Nao ha mais perfis disponiveis para este usuario";
            lblErr.Visible = true;
        }
        else
        {
            if (userId != 0)
            {
                // Create object
                UsersInRole userInRoles = new UsersInRole();
                userInRoles.UserId = userId;
                userInRoles.RoleId = Convert.ToInt16(cboRoles.SelectedValue);
                userInRoles.CompanyId = Company.CompanyId;

                // Fires Insert
                UsersInRolesManager uManager = new UsersInRolesManager(this);
                uManager.Insert(userInRoles);

                //Refresh the Combo and Grid
                cboRoles.DataBind();
                grdRolesByUser.DataBind();

                // Refresh the menu
                if (User.Identity.UserId == userId)
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "ResetMenu", "top.ResetMenu();", true);
            }
        }
    }
Пример #3
0
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                a.MembershipCreateStatus createStatus;

                a.Membership.CreateUser(model.UserName, model.Password, model.Email, passwordQuestion: null, passwordAnswer: null, isApproved: true, providerUserKey: null, status: out createStatus);

                if (createStatus == a.MembershipCreateStatus.Success)
                {
                    DataClasses1DataContext db    = new DataClasses1DataContext();
                    System.Guid             idus  = db.Users.Where(b => b.UserName == model.UserName).Select(b => b.UserId).ToArray()[0];
                    System.Guid             idrol = db.Roles.Where(b => b.RoleName == "usuario").Select(b => b.RoleId).ToArray()[0];
                    UsersInRole             r1    = new UsersInRole();
                    r1.UserId = idus;
                    r1.RoleId = idrol;
                    db.UsersInRoles.InsertOnSubmit(r1);
                    db.SubmitChanges();


                    a.FormsAuthentication.SetAuthCookie(model.UserName, createPersistentCookie: false);
                    return(RedirectToAction("Index", "Home"));
                }
                else
                {
                    //ModelState.AddModelError("", ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        public async Task <IActionResult> ListOfUsersInRole(string roleId)
        {
            //get the role by Id
            var role = await _roleManager.FindByIdAsync(roleId);

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

            //create a new list of role with users
            List <UsersInRole> usersInRoles = new List <UsersInRole>();
            UsersInRole        inRole       = new UsersInRole();

            foreach (var user in _userManager.Users.ToList())
            {
                if (await _userManager.IsInRoleAsync(user, role.Name))
                {
                    inRole.AppUserId = user.Id;
                    inRole.Username  = user.UserName;

                    //add the user to the list
                    usersInRoles.Add(inRole);
                }
            }

            var model = new RoleViewModel();

            model.Id        = role.Id;
            model.RoleName  = role.Name;
            model.RoleUsers = usersInRoles;

            return(Ok(model));
        }
Пример #5
0
 // This method deletes a record in the table.
 // Change this method to alter how records are deleted.
 public int Delete(UsersInRole x)
 {
     DbContext.UsersInRoles.Attach(x);
     DbContext.UsersInRoles.DeleteOnSubmit(x);
     DbContext.SubmitChanges();
     return(1);
 }
Пример #6
0
        public bool AddUserToRole(string userName, string roleName)
        {
            //NOTE:Why do we get a ShopgunMembershipUser instead of a user??
            var membershipUser = _membershipProviderApplicationService.GetUser(userName, false, "ShopgunMembershipProvider") as ShopgunMembershipUser;

            var role = _roleRepository.FindOne(r => r.RoleName == roleName);

            role = _usersInRoleRepository.FindDomainObject(role);

            if (membershipUser != null)
            {
                var user        = _usersInRoleRepository.FindDomainObject(membershipUser.ToUser());
                var usersInRole = new UsersInRole
                {
                    User = user,
                    Role = role
                };

                _usersInRoleRepository.Add(usersInRole);
                _usersInRoleRepository.Persist();
                return(true);
            }

            return(false);
        }
Пример #7
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (cboRoles.SelectedValue == "")
        {
            lblErr.Text    = "Nao ha mais perfis disponiveis para este usuario";
            lblErr.Visible = true;
        }
        else
        {
            if (userId != 0)
            {
                // Create object
                UsersInRole userInRoles = new UsersInRole();
                userInRoles.UserId    = userId;
                userInRoles.RoleId    = Convert.ToInt16(cboRoles.SelectedValue);
                userInRoles.CompanyId = Company.CompanyId;

                // Fires Insert
                UsersInRolesManager uManager = new UsersInRolesManager(this);
                uManager.Insert(userInRoles);

                //Refresh the Combo and Grid
                cboRoles.DataBind();
                grdRolesByUser.DataBind();

                // Refresh the menu
                if (User.Identity.UserId == userId)
                {
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "ResetMenu", "top.ResetMenu();", true);
                }
            }
        }
    }
        public IHttpActionResult AddOrUpdateEmployee(Employee employee, int type)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    using (MudarDBContext mdbContext = new MudarDBContext())
                    {
                        if (employee.EmployeeId == Guid.Empty)
                        {
                            employee.EmployeeId  = Guid.NewGuid();
                            employee.CreatedBy   = "superadmin";
                            employee.CreatedDate = DateTime.Now;

                            var userlogin = new UserLogin()
                            {
                                UserId       = employee.EmployeeId,
                                UserLoginId  = MudarCommon.GenerateULogin(employee.EmployeeFirstName),
                                UserPassword = MudarCommon.GeneratePassword(employee.EmployeeFirstName),
                                CreatedBy    = "superadmin",
                                CreatedDate  = DateTime.Now
                            };

                            var usrRole = new UsersInRole()
                            {
                                UserId      = employee.EmployeeId,
                                RoleId      = mdbContext.Roles.First(r => r.BranchRoleValue == type).RoleId,
                                CreatedBy   = "superadmin",
                                CreatedDate = DateTime.Now
                            };

                            mdbContext.UserLogins.Add(userlogin);
                            mdbContext.Employees.Add(employee);
                            mdbContext.UserRoles.Add(usrRole);
                        }
                        else
                        {
                            mdbContext.Employees.Attach(employee);
                            mdbContext.Entry <Employee>(employee).State = EntityState.Modified;
                            employee.ModifiedBy   = "superadmin";
                            employee.ModifiedDate = DateTime.Now;
                        }
                        mdbContext.SaveChanges();
                    }
                    return(Ok("success"));
                }
                else
                {
                    return(BadRequest("failed"));
                }
            }
            catch (Exception)
            {
                return(BadRequest("failed"));
            }
        }
Пример #9
0
        public async Task <IHttpActionResult> ManageUsersInRole(UsersInRole model)
        {
            var role = await this.AppRoleManager.FindByIdAsync(model.Id);

            if (role == null)
            {
                ModelState.AddModelError("", "Role does not exist");
                return(BadRequest(ModelState));
            }

            foreach (string user in model.EnrolledUsers)
            {
                var appUser = await this.AppUserManager.FindByIdAsync(user);

                if (appUser == null)
                {
                    ModelState.AddModelError("", String.Format("User: {0} does not exists", user));
                    continue;
                }

                if (!this.AppUserManager.IsInRole(user, role.Name))
                {
                    IdentityResult result = await this.AppUserManager.AddToRoleAsync(user, role.Name);

                    if (!result.Succeeded)
                    {
                        ModelState.AddModelError("", String.Format("User: {0} could not be added to role", user));
                    }
                }
            }

            foreach (string user in model.RemovedUsers)
            {
                var appUser = await this.AppUserManager.FindByIdAsync(user);

                if (appUser == null)
                {
                    ModelState.AddModelError("", String.Format("User: {0} does not exists", user));
                    continue;
                }

                IdentityResult result = await this.AppUserManager.RemoveFromRoleAsync(user, role.Name);

                if (!result.Succeeded)
                {
                    ModelState.AddModelError("", String.Format("User: {0} could not be removed from role", user));
                }
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            return(Ok());
        }
Пример #10
0
        public JsonResult DeleteRol(string idRol, string idUser)
        {
            Guid _idRol  = new Guid(idRol);
            Guid _idUser = new Guid(idUser);
            DataClasses1DataContext db  = new DataClasses1DataContext();
            UsersInRole             rol = db.UsersInRoles.Where(a => a.RoleId == _idRol && a.UserId == _idUser).First();

            db.UsersInRoles.DeleteOnSubmit(rol);
            db.SubmitChanges();
            return(Json(new { success = true }));
        }
Пример #11
0
        public async Task <IActionResult> ManageUsersInRole(UsersInRole usersInRole)
        {
            var role = await _roleManager.FindByIdAsync(usersInRole.RoleId);

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

            foreach (var user in usersInRole.EnrolledUsers)
            {
                var appUser = await _userManager.FindByIdAsync(user);

                if (appUser == null)
                {
                    AddError($"User: {user} does not exists");
                    continue;
                }

                if (await _userManager.IsInRoleAsync(appUser, role.Name))
                {
                    continue;
                }

                var result = await _userManager.AddToRoleAsync(appUser, role.Name);

                if (!result.Succeeded)
                {
                    AddError($"User: {user} could not be added to role");
                }
            }

            foreach (var user in usersInRole.RemovedUsers)
            {
                var appUser = await _userManager.FindByIdAsync(user);

                if (appUser == null)
                {
                    AddError($"User: {user} does not exists");
                    continue;
                }

                var result = await _userManager.RemoveFromRoleAsync(appUser, role.Name);

                if (!result.Succeeded)
                {
                    AddError($"User: {user} could not be removed from role");
                }
            }

            return(!IsOperationValid() ? CustomResponse() : Ok());
        }
 /// <summary>
 /// Fills current instance with data provided by users in role collection
 /// </summary>
 /// <param name="usersInRoles"> The users in roles. </param>
 public void SetFromUsers(IEnumerable <UserInRoleDto> usersInRoles)
 {
     foreach (var user in usersInRoles)
     {
         if (user.RoleIds.Contains(Id))
         {
             UsersInRole.Add(UserViewModel.From(user));
         }
         else
         {
             UsersOutsideRole.Add(UserViewModel.From(user));
         }
     }
 }
Пример #13
0
        public bool DeleteUserFromRole(string userName, string roleName)
        {
            ShopgunMembershipUser user = _membershipProviderApplicationService.GetUser(userName, false, "ShopgunMembershipProvider") as ShopgunMembershipUser;
            Role role = _roleRepository.FindOne(r => r.RoleName == roleName);

            if (user != null)
            {
                UsersInRole usersInRole = _usersInRoleRepository.FindOne(u => u.Role == role && u.User.Id == user.UserId);
                _usersInRoleRepository.Delete(usersInRole);
                _usersInRoleRepository.Persist();
                return(true);
            }
            return(false);
        }
 void IUserInRolesDAO.DeleteUserFromRole(String UserName)
 {
     using (var GiftEntity = new GiftEntities())
     {
         UsersInRole DBUserInRole = (from c in GiftEntity.UsersInRoles
                                     where c.Username == UserName
                                     select c).FirstOrDefault();
         if (DBUserInRole == null)
         {
             return;
         }
         GiftEntity.UsersInRoles.Remove(DBUserInRole);
         GiftEntity.SaveChanges();
     }
 }
Пример #15
0
        public async Task <UsersInRole> GetUsersInRole(string roleName)
        {
            UsersInRole usersInRole = null;

            usersInRole = await TryCatch <ArgumentNullException, UsersInRole>(async() =>
            {
                UsersInRole users = new UsersInRole()
                {
                    User = await _userManager.GetUsersInRoleAsync(roleName)
                };

                return(users);
            });

            return(usersInRole);
        }
Пример #16
0
        internal int PersonelEkle(PersonelModel model, string ilce, string cinsiyet)
        {
            try
            {
                Users users = new Users()
                {
                    UserName = model.UserName.Trim(), Password = model.Password.Trim(), Aktifmi = true
                };
                DigerBilgiler bilgi = new DigerBilgiler()
                {
                    Adres = model.Adres.Trim(), Cinsiyet = cinsiyet, Eposta = model.Eposta.Trim(), IlceID = Convert.ToInt32(ilce), PostaKod = model.PostaKod, TelefonNo = model.TelefonNo.Trim(), Yasi = model.Yasi
                };

                var kontrol = PersonelKontrol(users);
                if (kontrol == null)
                {
                    _db.Users.Add(users);
                    _db.SaveChanges();
                    _db.DigerBilgiler.Add(bilgi);
                    _db.SaveChanges();
                    int userId  = users.ID;
                    int bilgiId = bilgi.ID;

                    Personel personel = new Personel()
                    {
                        UserID = userId, BilgiID = bilgiId, Adi = model.Adi.Trim(), Soyadi = model.Soyadi.Trim(), Tarih = DateTime.Today
                    };
                    _db.Personel.Add(personel);
                    _db.SaveChanges();
                    UsersInRole rol = new UsersInRole()
                    {
                        RoleID = 8, UserID = userId
                    };
                    _db.UsersInRole.Add(rol);
                    _db.SaveChanges();
                    return(1); //Herşey tamam
                }
                else
                {
                    return(-1); // Users Var
                }
            }
            catch
            {
                return(-2); //Kayıt hatası
            }
        }
        public void AddUserToRole(String username, String RoleName, String ApplicationName)
        {
            if (IsUserInRole(username, RoleName, ApplicationName))
            {
                throw new Exception("User is already in role.");
            }

            using (var GiftEntity = new GiftEntities())
            {
                UsersInRole UR = new UsersInRole();
                UR.Username        = username;
                UR.Rolename        = RoleName;
                UR.ApplicationName = ApplicationName;
                GiftEntity.UsersInRoles.Add(UR);
                GiftEntity.SaveChanges();
            }
        }
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                a.MembershipCreateStatus createStatus;
                a.Membership.CreateUser(model.UserName, model.Password, model.Email, passwordQuestion: null, passwordAnswer: null, isApproved: true, providerUserKey: null, status: out createStatus);

                if (createStatus == a.MembershipCreateStatus.Success)
                {
                    DataClasses1DataContext db    = new DataClasses1DataContext();
                    System.Guid             idUs  = db.Users.Where(b => b.UserName == model.UserName).Select(b => b.UserId).ToArray()[0];
                    System.Guid             idRol = db.Roles.Where(b => b.RoleName == "Usuario").Select(b => b.RoleId).ToArray()[0];
                    UsersInRole             rel   = new UsersInRole()
                    {
                        RoleId = idRol, UserId = idUs
                    };
                    db.UsersInRoles.InsertOnSubmit(rel);
                    db.SubmitChanges();
                    a.FormsAuthentication.SetAuthCookie(model.UserName, createPersistentCookie: false);

                    usuario nuevo = new Models.usuario();
                    nuevo.id          = idUs;
                    nuevo.ciudad      = model.Ciudad;
                    nuevo.estado      = model.Estado;
                    nuevo.pais        = model.pais;
                    nuevo.nit         = model.nit;
                    nuevo.telefono    = model.telefono;
                    nuevo.direccion   = model.direccion;
                    nuevo.comentarios = model.comentarios;
                    db.usuarios.InsertOnSubmit(nuevo);
                    db.SubmitChanges();
                    return(RedirectToAction("Index", "Home"));
                }
                else
                {
                    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Пример #19
0
        private async Task populateList(string roleId)
        {
            var role = await roleManager.FindByIdAsync(roleId);

            RoleName = role.Name;
            RoleId   = role.Id;


            //Got error: There is already an open DataReader associated with this Command which must be closed first.
            foreach (var user in userManager.Users.ToList())
            {
                if (await userManager.IsInRoleAsync(user, RoleName))
                {
                    UsersInRole.Add(user);
                }
            }

            //Users to be added shouldn't be in the role already:
            UserList = new SelectList(userManager.Users.Where(u => !UsersInRole.Contains(u)).ToList(), "Id", "UserName");
        }
Пример #20
0
        private void SaveRoles(Guid userId, FormCollection collection)
        {
            UsersInRole role;
            var         roles = from x in db.Roles select x;
            var         exist = (from x in db.UsersInRoles
                                 where x.UserId == userId
                                 select x.RoleId).AsEnumerable <Guid>();
            var provider = collection.ToValueProvider();
            var selected = from x in roles.AsEnumerable()
                           where (bool)provider.GetValue(x.RoleName).ConvertTo(typeof(bool))
                           select x.RoleId;
            var forAdd = selected.Except(exist);
            var forDel = exist.Except(selected);

            using (IEnumerator <Guid> enumerator = forDel.GetEnumerator())
            {
                Guid guid;
                while (enumerator.MoveNext())
                {
                    guid = enumerator.Current;
                    role = (from x in db.UsersInRoles
                            where (x.UserId == userId) && (x.RoleId == guid)
                            select x).First();
                    db.UsersInRoles.DeleteOnSubmit(role);
                }
            }
            foreach (Guid guid in forAdd)
            {
                var usersInRole = new UsersInRole
                {
                    RoleId = guid,
                    UserId = userId
                };

                db.UsersInRoles.InsertOnSubmit(usersInRole);
            }
            db.SubmitChanges();
        }
Пример #21
0
        public JsonResult addrol(string idUs2, string idRol)
        {
            //string data = idUs + idRol;
            Guid _idUs  = new Guid(idUs2);
            Guid _idRol = new Guid(idRol);
            DataClasses1DataContext db  = new DataClasses1DataContext();
            UsersInRole             rol = new UsersInRole()
            {
                RoleId = _idRol,
                UserId = _idUs
            };
            int aa = db.UsersInRoles.Where(a => a.RoleId == _idRol && a.UserId == _idUs).Count();

            if (aa == 1)
            {
                return(Json(new { success = "Error Este Rol esta Asignado" }));
            }
            db.UsersInRoles.InsertOnSubmit(rol);
            db.SubmitChanges();
            string nombrerol = db.Roles.Where(a => a.RoleId == _idRol).First().RoleName;

            return(Json(new { success = "Rol Agregado", rol = nombrerol, idRol = _idRol, idUs = _idUs }));
        }
Пример #22
0
        public async Task <IActionResult> AddUserRoleMenuAsync(string roleId)
        {
            UsersInRole usersInRole = new UsersInRole();

            usersInRole.Users = new List <AppUser>();
            IdentityRole role = await _roleManager.FindByIdAsync(roleId);

            var result = _appUserRepository.GetAllAsync();
            var users  = result.Result;

            // get all users not in role
            foreach (var user in users)
            {
                if (await _userManager.IsInRoleAsync(user, role.Name) == false)
                {
                    usersInRole.Users.Add(user);
                }
            }

            usersInRole.RoleId = role.Id;


            return(View(usersInRole));
        }
Пример #23
0
        public ActionResult UsersInRoles(int _roleid, int _userid)
        {
            if (_roleid.ToString() == "" || _userid.ToString() == "")
            {
                return(Json(new ResultJson {
                    Success = false, Message = "Rol veya Kullanıcı seçiniz!"
                }));
            }
            try {
                var result = diyaPMContext.UsersInRoles.Where(x => x.user_id == _userid && x.role_id == _roleid).Any();
                if (result)
                {
                    return(Json(new ResultJson {
                        Success = false, Message = "Kullanıcı zaten bu role eklenmiş!"
                    }));
                }

                UsersInRole usersInRole = new UsersInRole();
                usersInRole.user_id = _userid;
                usersInRole.role_id = _roleid;

                diyaPMContext.UsersInRoles.Add(usersInRole);
                diyaPMContext.SaveChanges();

                return(Json(new ResultJson {
                    Success = true, Message = "Role ait kullanıcı eklendi.."
                }));
            }
            catch (Exception ex)
            {
                databaseLogger.Log(ex.ToString(), User.Identity.Name);
                return(Json(new ResultJson {
                    Success = false, Message = ex.ToString()
                }));
            }
        }
 /// <summary>
 /// Basic Delete method
 /// </summary>
 /// <param name="entity"></param>
 public void DeleteUserInRoles(UsersInRole entity)
 {
     DbContext.UsersInRoles.Attach(entity);
     DbContext.UsersInRoles.DeleteOnSubmit(entity);
     DbContext.SubmitChanges();
 }
        /// <summary>
        /// Method to add a USER in a determined ROLE
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="companyId"></param>
        /// <param name="roleId"></param>
        private void AddUserInRoles(int userId, int companyId, int roleId)
        {
            var newUserInRoles = new UsersInRole();
            var userInRolesManager = new UsersInRolesManager(this);

            newUserInRoles.UserId = userId;
            newUserInRoles.RoleId = roleId;
            newUserInRoles.CompanyId = companyId;
            userInRolesManager.Insert(newUserInRoles);
        }
Пример #26
0
        public ActionResult SignUp([Bind(Include = "UserID,UserFirstName,UserLastName,UserAddress1,UserAddress2,CountryID,UserStateList,UserCity,UserEmail, " +
                                                   " UserPassword,UserConfirmPassword,SecurityQuestionIDList,SecurityAnswer,UserPhone,CreatedOn,Gender,IsDeleted,UserRole")] SignUpViewModel suvm, string lga, string State, string terms, string txtState, string txtCity)
        {
            try
            {
                ViewBag.StateId = new SelectList(db.States, "StateID", "StateName");
                string termsAndCondition = (terms == "yes") ? "Agreed" : "Not Agreed";

                //var state = (txtState != "") ? txtState : State;
                string state = "";
                var    lga3  = (txtCity != "") ? txtCity : lga;

                if (txtState != "")
                {
                    state = txtState;
                }
                else
                {
                    int enteredStateID = Convert.ToInt32(State);
                    var stateID        = (from st in db.States where (st.StateID == enteredStateID) select st).FirstOrDefault();
                    state = stateID.StateName;
                }

                var activationID = Guid.NewGuid();
                var encriptPwd   = new PasswordHashing();
                if (termsAndCondition == "Agreed")
                {
                    // string sexGender = suvm.Gender;
                    int sqs             = suvm.SecurityQuestionIDList.Value;
                    var itemCollections = new User
                    {
                        UserLastName        = suvm.UserLastName,
                        UserFirstName       = suvm.UserFirstName,
                        UserAddress1        = suvm.UserAddress1,
                        UserAddress2        = suvm.UserAddress2,
                        UserState           = state.ToString(),
                        UserCity            = lga3,
                        UserEmail           = suvm.UserEmail,
                        UserPassword        = encriptPwd.Encrypt(suvm.UserPassword),
                        UserConfirmPassword = encriptPwd.Encrypt(suvm.UserConfirmPassword),
                        SecurityQuestionID  = Convert.ToInt16(suvm.SecurityQuestionIDList),
                        SecurityAnswer      = encriptPwd.Encrypt(suvm.SecurityAnswer),
                        UserPhone           = suvm.UserPhone,
                        CreatedOn           = DateTime.Now,
                        GenderID            = suvm.Gender.Value,
                        IsDeleted           = false,
                        CountryID           = suvm.CountryID,
                        UserRole            = suvm.UserRole,
                        IsActivated         = false,
                        ActivationID        = activationID,
                    };

                    var uir = new UsersInRole
                    {
                        UserID = suvm.UserID,
                        RoleID = Convert.ToInt32(suvm.UserRole)
                    };
                    LoadDropDownList();
                    var chkExistingEmail = (from l in db.Users
                                            where l.UserEmail == suvm.UserEmail
                                            select l).FirstOrDefault();
                    if (chkExistingEmail == null)
                    {
                        try
                        {
                            string newActivationID = activationID.ToString();
                            itemCollections.UsersInRoles.Add(uir);
                            db.Users.Add(itemCollections);
                            db.SaveChanges();
                            EmailNotification.ProcessEmailForAccountActivation(suvm.UserEmail, suvm.UserFirstName, suvm.UserLastName, newActivationID, suvm.UserEmail);
                            LoadDropDownList();
                            ViewBag.DisplayMessage = "success";
                            ModelState.AddModelError("", "Record Saved Successfully, an activation link has been sent to your inbox, kindly activate your account so you will be able to login!");
                        }
                        catch (Exception ex)
                        {
                            ViewBag.DisplayMessage = "Info";
                            ModelState.AddModelError("", ex.Message);
                        }
                    }
                    else
                    {
                        ViewBag.DisplayMessage = "Info";
                        ModelState.AddModelError("", "This email address has already been used, enter a different email address!");
                        LoadDropDownList();
                        return(View());
                    }
                }


                if (termsAndCondition == "Not Agreed")
                {
                    ViewBag.DisplayMessage = "Info";
                    ModelState.AddModelError("", "You must agree to our terms and conditions before submitting the form");

                    LoadDropDownList();
                    return(View());
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                return(View());
            }
            return(View());
        }
Пример #27
0
        internal int MusteriEkle(MusteriModel model)
        {
            int uId = 0, bId = 0, krediId = 0;

            try
            {
                var u = _db.Users.SingleOrDefault(x => x.UserName == model.UserName);
                if (u != null)
                {
                    return(-2); // username ve passs var ise
                }
                var eposta = _db.DigerBilgiler.SingleOrDefault(x => x.Eposta == model.Eposta);
                if (eposta != null)
                {
                    return(-3); // eposta var ise
                }
                var kredi = _db.KrediKartBilgileri.SingleOrDefault(x => x.KrediKartNo == model.KrediKartNo);
                if (kredi != null)
                {
                    return(-4); //kredi kart no var ise
                }
                var tc = _db.Musteriler.SingleOrDefault(x => x.TCNo == model.TCNo);
                if (tc != null)
                {
                    return(-5); // tc var ise
                }
                //Todo : Kredi Kart Kontrol - çalışırsa user'da aktif edilir çalışmaz ise hata verir.

                Users user = new Users()
                {
                    UserName = model.UserName.Trim(), Password = model.Password.Trim(), Aktifmi = true
                };
                _db.Users.Add(user);
                _db.SaveChanges();
                uId = user.ID;

                DigerBilgiler bilgi = new DigerBilgiler()
                {
                    Adres = model.Adres.Trim(), Cinsiyet = model.Cinsiyet, Eposta = model.Eposta.Trim(), IlceID = model.IlceID, PostaKod = model.PostaKod, TelefonNo = model.TelefonNo.Trim(), Yasi = model.Yasi
                };
                _db.DigerBilgiler.Add(bilgi);
                _db.SaveChanges();
                bId = bilgi.ID;

                KrediKartBilgileri krediKart = new KrediKartBilgileri()
                {
                    KrediKartCNRNo = model.KrediKartCNRNo, KrediKartNo = model.KrediKartNo, KrediKartSKT = model.KrediKartSKT, Aktifmi = true
                };
                _db.KrediKartBilgileri.Add(krediKart);
                _db.SaveChanges();
                krediId = krediKart.ID;

                Musteriler musteri = new Musteriler()
                {
                    KrediKartID = krediId, Adi = model.Adi.Trim(), Soyadi = model.Soyadi.Trim(), TCNo = model.TCNo, BilgiID = bId, UserID = uId, Tarih = DateTime.Today, PaketID = model.PaketID
                };
                _db.Musteriler.Add(musteri);
                _db.SaveChanges();
                //Todo: RoleId Musteri seçilmiştir eğer Musteri Id'si değişirse Burdakide Değişmeli.
                UsersInRole ur = new UsersInRole();
                ur.RoleID = 7;
                ur.UserID = user.ID;
                _db.UsersInRole.Add(ur);
                _db.SaveChanges();



                return(1); // tmm ise
            }
            catch
            {
                if (uId > 0)
                {
                    var userdel = _db.Users.SingleOrDefault(x => x.ID == uId);
                    _db.Users.Remove(userdel);
                }
                if (bId > 0)
                {
                    var bilgidel = _db.DigerBilgiler.SingleOrDefault(x => x.ID == bId);
                    _db.DigerBilgiler.Remove(bilgidel);
                }
                if (krediId > 0)
                {
                    var kredidel = _db.KrediKartBilgileri.SingleOrDefault(x => x.ID == krediId);
                    _db.KrediKartBilgileri.Remove(kredidel);
                }
                _db.SaveChanges();
                return(-1); //büyük Hatalarda
            }
        }
Пример #28
0
 /// <summary>
 /// This method inserts a new record in the table.
 /// Change this method to alter how records are inserted.
 /// </summary>
 /// <param name=entity>entity</param>
 public void Insert(UsersInRole entity)
 {
     DbContext.UsersInRoles.InsertOnSubmit(entity);
     DbContext.SubmitChanges();
 }
Пример #29
0
        public static async Task <OperationResult> AddUserToRole(string adminId, string uid, int rid)
        {
            OperationResult OpResult = new OperationResult();
            var             maxp     = await MemberAdminContext.GetMaxPriority(adminId);

            RoleServiceProxy rsvc = new RoleServiceProxy();
            UserServiceProxy usvc = new UserServiceProxy();
            var cntx = Cntx;
            var u    = await usvc.LoadEntityByKeyAsync(cntx, uid);

            if (u == null)
            {
                OpResult.Result = new { ok = false, msg = string.Format(ResourceUtils.GetString("b66098049404e4de1356242e8aa6444a", "User \"{0}\" is not found."), uid) };
                return(OpResult);
            }
            var uroles = await usvc.MaterializeAllRolesAsync(cntx, u);

            if (DBAutoCleanupRoles)
            {
                // prevent polution
                List <Role> higherroles = new List <Role>();
                foreach (var ur in uroles)
                {
                    var pr = ur;
                    if (pr.ID == rid)
                    {
                        higherroles.Add(ur);
                    }
                    while (pr.ParentID != null)
                    {
                        pr.UpperRef = await rsvc.MaterializeUpperRefAsync(cntx, pr);

                        pr = pr.UpperRef;
                        if (pr.ID == rid)
                        {
                            higherroles.Add(ur);
                            break;
                        }
                    }
                }
                if (higherroles.Count > 0)
                {
                    string rolesstr = "";
                    foreach (var hr in higherroles)
                    {
                        rolesstr += (rolesstr == "" ? "" : ", ") + hr.DistinctString;
                    }
                    string errorfmt = ResourceUtils.GetString("43558b5deaec392b9461d28d4e753687", "Operation denied: the user already has this or more specific roles: '{0}'! Try to remove them before adding present one.");
                    OpResult.Result = new { ok = false, msg = string.Format(errorfmt, rolesstr) };
                    return(OpResult);
                }
            }
            var r = await rsvc.LoadEntityByKeyAsync(cntx, rid);

            if (r == null)
            {
                OpResult.Result = new { ok = false, msg = ResourceUtils.GetString("db2a3d7bc44d36a9ebeaa0d562c4cd21", "The role is not found.") };
                return(OpResult);
            }
            else if (r.RolePriority > maxp.Major)
            {
                OpResult.Result = new { ok = false, msg = ResourceUtils.GetString("67729f0f407d1ea57f28b43235b3e5f6", "Adding more priviledged role is not authorized.") };
                return(OpResult);
            }
            List <SimpleMessage> notices = new List <SimpleMessage>();
            var         uir     = new UsersInRole();
            List <Role> removed = new List <Role>();

            if (DBAutoCleanupRoles)
            {
                // clean up: find more general roles to remove.
                var p = r;
                while (p.ParentID != null)
                {
                    p.UpperRef = await rsvc.MaterializeUpperRefAsync(cntx, p);

                    p = p.UpperRef;
                    foreach (var ur in uroles)
                    {
                        if (ur.ID == p.ID)
                        {
                            if (!(from d in removed where d.ID == p.ID select d).Any())
                            {
                                removed.Add(p);
                            }
                        }
                    }
                }
            }
            uir.IsPersisted  = false;
            uir.UserID       = u.ID;
            uir.RoleID       = rid;
            uir.SubPriority  = 0;
            uir.AssignDate   = DateTime.UtcNow;
            uir.LastModified = uir.AssignDate;
            uir.AdminID      = adminId;
            UsersInRoleServiceProxy uirsvc = new UsersInRoleServiceProxy();
            await uirsvc.AddOrUpdateEntitiesAsync(cntx, new UsersInRoleSet(), new UsersInRole[] { uir });

            UserAppMemberServiceProxy mbsvc = new UserAppMemberServiceProxy();
            var memb = await mbsvc.LoadEntityByKeyAsync(cntx, AppId, uid);

            notices.Add(new SimpleMessage
            {
                TypeId = 1,
                Title  = string.Format(ResourceUtils.GetString("38015f8af3e032dfd803758dd2bde917", "New role: [{0}] is added.", memb.AcceptLanguages), r.DistinctString),
                Data   = "{ id=\"" + r.ID + "\", type=\"role\", name=\"" + r.DistinctString + "\" }"
            });
            var            _r       = new { id = rid, uid = u.ID, name = r.RoleName, path = r.DistinctString, level = uir.SubPriority, op = true };
            List <dynamic> _removed = new List <dynamic>();

            if (removed.Count > 0)
            {
                List <UsersInRole> l = new List <UsersInRole>();
                foreach (var rmv in removed)
                {
                    var x = uirsvc.LoadEntityByKey(Cntx, rmv.ID, u.ID);
                    l.Add(x);
                    _removed.Add(new { id = rmv.ID, name = rmv.RoleName, path = rmv.DistinctString, op = maxp.Major >= rmv.RolePriority });
                }
                await uirsvc.DeleteEntitiesAsync(Cntx, new UsersInRoleSet(), l.ToArray());

                foreach (var _rrmv in removed)
                {
                    notices.Add(new SimpleMessage
                    {
                        TypeId = 1,
                        Title  = string.Format(ResourceUtils.GetString("9708d527fbbf0d9752fc2c741615fb58", "Your role: [{0}] is removed.", memb.AcceptLanguages), _rrmv.DistinctString),
                        Data   = "{ id=\"" + _rrmv.ID + "\", type=\"role\", name=\"" + _rrmv.DistinctString + "\" }"
                    });
                }
            }
            await AddUserRoleHistory(uir, UserRoleOperations.Added);

            OpResult.Result  = new { ok = true, msg = "", added = _r, removed = _removed.ToArray() };
            OpResult.notices = notices.ToArray();
            return(OpResult);
        }
Пример #30
0
 /// <summary>
 /// This method updates a record in the table.
 /// Change this method to alter how records are updated.
 /// </summary>
 /// <param name=original_entity>original_entity</param>
 /// <param name=entity>entity</param>
 public void Update(UsersInRole original_entity, UsersInRole entity)
 {
     DbContext.UsersInRoles.Attach(original_entity);
     DbContext.SubmitChanges();
 }
Пример #31
0
 /// <summary>
 /// Basic Delete method
 /// </summary>
 /// <param name="entity"></param>
 public void DeleteUserInRoles(UsersInRole entity)
 {
     DbContext.UsersInRoles.Attach(entity);
     DbContext.UsersInRoles.DeleteOnSubmit(entity);
     DbContext.SubmitChanges();
 }
Пример #32
0
 // This method inserts a new record in the table.
 // Change this method to alter how records are inserted.
 public int Insert(UsersInRole x)
 {
     DbContext.UsersInRoles.InsertOnSubmit(x);
     DbContext.SubmitChanges();
     return(1);
 }
Пример #33
0
 // This method updates a record in the table.
 // Change this method to alter how records are updated.
 public int Update(UsersInRole original_x, UsersInRole x)
 {
     DbContext.UsersInRoles.Attach(original_x);
     DbContext.SubmitChanges();
     return(1);
 }
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                a.MembershipCreateStatus createStatus;
                a.Membership.CreateUser(model.UserName, model.Password, model.Email, passwordQuestion: null, passwordAnswer: null, isApproved: true, providerUserKey: null, status: out createStatus);

                if (createStatus == a.MembershipCreateStatus.Success)
                {
                    DataClasses1DataContext db = new DataClasses1DataContext();
                    System.Guid idUs = db.Users.Where(b => b.UserName == model.UserName).Select(b => b.UserId).ToArray()[0];
                    System.Guid idRol = db.Roles.Where(b => b.RoleName == "Usuario").Select(b => b.RoleId).ToArray()[0];
                    UsersInRole rel = new UsersInRole() { RoleId = idRol, UserId = idUs };
                    db.UsersInRoles.InsertOnSubmit(rel);
                    db.SubmitChanges();
                    a.FormsAuthentication.SetAuthCookie(model.UserName, createPersistentCookie: false);

                    usuario nuevo = new Models.usuario();
                    nuevo.id = idUs;
                    nuevo.ciudad = model.Ciudad;
                    nuevo.estado=model.Estado;
                    nuevo.pais=model.pais;
                    nuevo.nit=model.nit;
                    nuevo.telefono = model.telefono;
                    nuevo.direccion=model.direccion;
                    nuevo.comentarios=model.comentarios;
                    db.usuarios.InsertOnSubmit(nuevo);
                    db.SubmitChanges();
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }