Example #1
0
File: test.cs Project: nobled/mono
	static void dump_list (MembershipUserCollection users)
	{
		Console.WriteLine ("{0} users", users.Count);
		foreach (MembershipUser u in users) {
			Console.WriteLine ("{0} {1} {2}", u.UserName, u.Email, u.IsLockedOut ? "lockedout" : "notlockedout");
		}
	}
Example #2
0
    public MembershipUserCollection GetMembers(int maximumRows, int startRowIndex)
    {
        int totalRecords = 0;

        MembershipUserCollection users = null;

        if (!string.IsNullOrEmpty(_rolenameToMatch))
        {
            users = new MembershipUserCollection();

            foreach (string usr in Roles.GetUsersInRole(_rolenameToMatch))
                users.Add(Membership.GetUser(usr));

            totalRecords = users.Count;
        }
        else if (!string.IsNullOrEmpty(_usernameToMatch))
            users = Membership.FindUsersByName(_usernameToMatch, maximumRows > 0 ? startRowIndex / maximumRows : 0, maximumRows > 0 ? maximumRows : int.MaxValue, out totalRecords);
        else if (!string.IsNullOrEmpty(_emailToMatch))
            users = Membership.FindUsersByEmail(_emailToMatch, maximumRows > 0 ? startRowIndex / maximumRows : 0, maximumRows > 0 ? maximumRows : int.MaxValue, out totalRecords);
        else
            users = Membership.GetAllUsers(maximumRows > 0 ? startRowIndex / maximumRows : 0, maximumRows, out totalRecords);

        HttpContext.Current.Items["MembershipUsers_TotalCount"] = totalRecords;

        return users;
    }
Example #3
0
    // create datasource for user gridview
    private void BindUserAccounts()
    {
        int totalRecords;
        MembershipUserCollection allUsers = Membership.GetAllUsers(this.PageIndex, this.PageSize, out totalRecords);
        MembershipUserCollection filteredUsers = new MembershipUserCollection();

        bool isOnline = true;
        foreach (MembershipUser user in allUsers)
        {
            // if user is currently online, add to gridview list
            if (user.IsOnline == isOnline)
            {
                filteredUsers.Add(user);
            }
        }

        // Enable/disable the pager buttons based on which page we're on
        bool visitingFirstPage = (this.PageIndex == 0);
        lnkFirst.Enabled = !visitingFirstPage;
        lnkPrev.Enabled = !visitingFirstPage;

        int lastPageIndex = (totalRecords - 1) / this.PageSize;
        bool visitingLastPage = (this.PageIndex >= lastPageIndex);
        lnkNext.Enabled = !visitingLastPage;
        lnkLast.Enabled = !visitingLastPage;

        UsersGridView.DataSource = filteredUsers;
        UsersGridView.DataBind();
    }
Example #4
0
    protected void Page_Load(object sender, EventArgs e)
    {
        _MyUsers = Membership.GetAllUsers();
        UsersGridView.DataSource = _MyUsers;

        if (!this.IsPostBack)
        {
            UsersGridView.DataBind();
        }
    }
 protected void Page_Load(object sender, EventArgs e)
 {
     //调用GetAllUsers获取所有的用户信息
     UsersList = Membership.GetAllUsers();
     if (!this.IsPostBack)
     {
         UsersGridView.DataSource = UsersList;
         UsersGridView.DataBind();
     }
 }
Example #6
0
    public static MembershipUserCollection FindUsersByRole(string[] roles)
    {
        MembershipUserCollection msc = new MembershipUserCollection();

        roles.Select(role => Roles.GetUsersInRole(role))
        .Aggregate((a, b) => a.Union(b).ToArray())
        .Distinct()
        .Select(user => Membership.GetUser(user))
        .ToList().ForEach(user => msc.Add(user));

        return msc;
    }
 protected void UsersGridView_RowCommand(object sender, GridViewCommandEventArgs e)
 {
     if (e.CommandName == "DeleteUser")
     {
         string userName = (string)UsersGridView.DataKeys[0].Value;
         //调用Membership的DeleteUser方法删除用户
         Membership.DeleteUser(userName);
         //下面的代码用于刷新 GridView控件的显示
         UsersList = Membership.GetAllUsers();
         UsersGridView.DataSource = UsersList;
         UsersGridView.DataBind();
     }
 }
Example #8
0
    public DataSet CustomGetUsersOnline()
    {
        DataSet ds = new DataSet();
        DataTable dt = new DataTable();
        dt = ds.Tables.Add("Users");

        MembershipUserCollection muc = Membership.GetAllUsers();
        MembershipUserCollection OnlineUsers = new MembershipUserCollection();

        bool isOnline = true;

        dt.Columns.Add("UserName", Type.GetType("System.String"));
        dt.Columns.Add("Email", Type.GetType("System.String"));
        //dt.Columns.Add("PasswordQuestion", Type.GetType("System.String"));
        //dt.Columns.Add("Comment", Type.GetType("System.String"));
        //dt.Columns.Add("ProviderName", Type.GetType("System.String"));
        dt.Columns.Add("CreationDate", Type.GetType("System.DateTime"));
        dt.Columns.Add("LastLoginDate", Type.GetType("System.DateTime"));
        dt.Columns.Add("LastActivityDate", Type.GetType("System.DateTime"));
        //dt.Columns.Add("LastPasswordChangedDate", Type.GetType("System.DateTime"));
        //dt.Columns.Add("LastLockoutDate", Type.GetType("System.DateTime"));
        dt.Columns.Add("IsApproved", Type.GetType("System.Boolean"));
        dt.Columns.Add("IsLockedOut", Type.GetType("System.Boolean"));
        dt.Columns.Add("IsOnline", Type.GetType("System.Boolean"));

        foreach (MembershipUser mu in muc)
        {
            // if user is currently online, add to gridview list
            if (mu.IsOnline == isOnline)
            {
                OnlineUsers.Add(mu);

            DataRow dr;
            dr = dt.NewRow();
            dr["UserName"] = mu.UserName;
            dr["Email"] = mu.Email;
            dr["CreationDate"] = mu.CreationDate;
            dr["LastLoginDate"] = mu.LastLoginDate;
            dr["LastActivityDate"] = mu.LastActivityDate;
            dr["IsApproved"] = mu.IsApproved;
            dr["IsLockedOut"] = mu.IsLockedOut;
            dr["IsOnline"] = mu.IsOnline;
            // you can add the other columns that you want to include in your return value
            dt.Rows.Add(dr);

            }
        }
        return ds;
    }
Example #9
0
        public static MembershipUserCollection FindUsersByPredicate(this Expression <Func <DataAccess.Login, bool> > predicate, int pageIndex, int pageSize, out int totalRecords)
        {
            MembershipUserCollection returnValue = new MembershipUserCollection();

            totalRecords = 0;

            using (var db = new DataAccess.CSSDataContext())
            {
                var logins = db.Logins.Where(predicate);

                totalRecords = logins.Count();

                foreach (var login in logins.Skip(pageIndex * pageSize).Take(pageSize))
                {
                    returnValue.Add(MembershipUserUtility.CreateMembershipUserFromLogin(login));
                }
            }

            return(returnValue);
        }
        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            MembershipUserCollection col = new MembershipUserCollection();

            var dataObjects = RF.Service <IUserService>().GetUsers();

            if (dataObjects != null)
            {
                totalRecords = dataObjects.Count;
                foreach (var dataObject in dataObjects)
                {
                    col.Add(this.ConvertFrom(dataObject));
                }
            }
            else
            {
                totalRecords = 0;
            }
            return(col);
        }
Example #11
0
        private static MembershipUserCollection GetMembershipUsers(int pageIndex, int pageSize, UserCollection users, out int totalRecords)
        {
            totalRecords   = users.Count;
            users.PageSize = pageSize;
            int pageNumber = pageIndex + 1;

            MembershipUserCollection results = new MembershipUserCollection();

            if (users.PageCount <= pageNumber)
            {
                List <User> userPage = users.GetPage(pageNumber);
                for (int i = 0; i < userPage.Count; i++)
                {
                    User current = userPage[i];
                    results.Add(User.GetMembershipUser(current));
                }
            }

            return(results);
        }
Example #12
0
        /// <summary>
        /// Builds a membership collection full of mocked users
        /// </summary>
        /// <returns></returns>
        private static MembershipUserCollection GetDummyUsers()
        {
            MembershipUserCollection users = new MembershipUserCollection();
            var now = DateTime.Now;

            var start = DateTime.Now.Second;

            for (int i = 0; i < 500; i++)
            {
                string name             = "Dummy User " + i;
                string email            = "just@a-dummy" + i + ".com";
                var    registrationDate = now.AddMinutes(i * (-1));
                var    isLockedOut      = (i % 10) == 1;
                var    dummyUser        = CreateDummyUser(i, name, email, registrationDate, isLockedOut);
                users.Add(dummyUser);
            }
            var end = DateTime.Now.Second;

            return(users);
        }
        public override MembershipUserCollection GetAllUsers(int pageIndex,
                                                             int pageSize, out int totalRecords)
        {
            // Note: This implementation ignores pageIndex and pageSize,
            // and it doesn't sort the MembershipUser objects returned

            // Make sure the data source has been loaded
            ReadMembershipDataStore();

            MembershipUserCollection users =
                new MembershipUserCollection();

            foreach (KeyValuePair <string, MembershipUser> pair in _Users)
            {
                users.Add(pair.Value);
            }

            totalRecords = users.Count;
            return(users);
        }
Example #14
0
    private void PopulateControls()
    {
        ClearInputField();

        if (CurrentAdminID != null &&
            int.Parse(CurrentAdminID) >= 0)
        {
            Admin admin = DataAccessContext.AdminRepository.GetOne(CurrentAdminID);
            uxUserName.Text = admin.UserName;

            if (AdminConfig.CurrentTestMode == AdminConfig.TestMode.Normal)
            {
                uxRegisterDateCalendarPopup.SelectedDate = admin.RegisterDate;
            }

            MembershipUserCollection memberShip = Membership.FindUsersByName(uxUserName.Text);

            uxEmail.Text = admin.Email;
        }
    }
Example #15
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //绑定所有角色到 IsRoles
            string[] roles = Roles.GetAllRoles();
            lstRoles.DataSource = roles;
            lstRoles.DataBind();

            //绑定所有用户到 lsUsers
            MembershipUserCollection users = Membership.GetAllUsers();
            lstUsers.DataSource();
            lstUsers.DataBind();
        }

        if (lstRoles.SelectedItem != null)
        {
            GetUsersInRoles();
        }
    }
Example #16
0
        public override System.Web.Security.MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            using (var db = new NotificatorEntities())
            {
                var query = from user in db.Users
                            where user.Username.Contains(usernameToMatch) && user.Application.Id == applicationId
                            orderby user.Id
                            select user;

                totalRecords = query.Count();
                var col = new MembershipUserCollection();

                foreach (var item in query.Skip(pageSize * pageIndex).Take(pageSize))
                {
                    col.Add(UserMapper.Map(this.Name, item));
                }

                return(col);
            }
        }
        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            MembershipUserCollection muc = new MembershipUserCollection();

            using (RedisClient rClient = new RedisClient(DatabaseConfig.Host, DatabaseConfig.Port, db: DatabaseConfig.Database))
            {
                var client = rClient.As <RedisMember>();
                var users  = client.GetAll();

                totalRecords = users.Count;
                var pageItems = users.Skip(pageIndex * pageSize).Take(pageSize);

                foreach (var rm in pageItems)
                {
                    muc.Add(new MembershipUser(this.Name, rm.UserName, rm.Id, rm.EmailAddress, "", "", rm.IsApproved, rm.IsLockedOut, rm.CreationDate, rm.LastLoginDate, rm.LastActivityDate, DateTime.MinValue, rm.LastLockoutDate));
                }
            }

            return(muc);
        }
Example #18
0
        public void FindUsers()
        {
            MembershipCreateStatus status;

            for (int i = 0; i < 100; i++)
            {
                Membership.CreateUser(String.Format("boo{0}", i), "barbar!", null,
                                      "question", "answer", true, out status);
            }
            for (int i = 0; i < 100; i++)
            {
                Membership.CreateUser(String.Format("foo{0}", i), "barbar!", null,
                                      "question", "answer", true, out status);
            }
            for (int i = 0; i < 100; i++)
            {
                Membership.CreateUser(String.Format("schmoo{0}", i), "barbar!", null,
                                      "question", "answer", true, out status);
            }


            MembershipUserCollection users = Membership.FindUsersByName("fo%");

            Assert.Equal(100, users.Count);

            int total;

            users = Membership.FindUsersByName("fo%", 2, 10, out total);
            Assert.Equal(10, users.Count);
            Assert.Equal(100, total);
            int index = 0;

            foreach (MembershipUser user in users)
            {
                Assert.Equal(String.Format("foo2{0}", index++), user.UserName);
            }

            //Cleanup
            MySqlHelper.ExecuteScalar(Connection, "DELETE FROM my_aspnet_users");
            MySqlHelper.ExecuteScalar(Connection, "DELETE FROM my_aspnet_membership");
        }
Example #19
0
        /// <summary>Returns a collection of membership users for which the e-mail address field contains the specified e-mail address.</summary>
        /// <returns>A <see cref="T:System.Web.Security.MembershipUserCollection"></see> that contains a page of pageSize<see cref="T:System.Web.Security.MembershipUser"></see> objects beginning at the page specified by pageIndex.</returns>
        /// <param name="totalRecords">The total number of matched users.</param>
        /// <param name="pageIndex">The index of the page of results to return. pageIndex is zero-based.</param>
        /// <param name="emailToMatch">The e-mail address to search for.</param>
        /// <param name="pageSize">The size of the page of results to return.</param>
        /// <exception cref="T:System.ArgumentException">emailToMatch is longer than 256 characters.- or -pageIndex is less than zero.- or -pageSize is less than one.- or -pageIndex multiplied by pageSize plus pageSize minus one exceeds <see cref="F:System.Int32.MaxValue"></see>.</exception>
        public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            //
            // Calculate the first and last records
            //
            int firstUserIndex = pageIndex * pageSize;
            int lastUserIndex  = ((pageIndex * pageSize) + pageSize) - 1;

            if (pageIndex < 0)
            {
                throw new ArgumentException(Properties.Resources.PageIndex_bad, "pageIndex");
            }
            if (pageSize < 1)
            {
                throw new ArgumentException(Properties.Resources.PageSize_bad, "pageSize");
            }
            if (lastUserIndex > 0x7fffffff)
            {
                throw new ArgumentException(Properties.Resources.PageIndex_PageSize_bad, "pageIndex and pageSize");
            }

            //
            // Retrieve a users collection
            //
            MembershipDataContext membership = new MembershipDataContext(connectionString);

            System.Collections.Generic.IList <User> users = membership.Users.Where(us => us.Email == emailToMatch).ToList();
            totalRecords = users.Count;

            //
            // Enumerate the Membership.User and convert to MembershipUserCollection
            //
            MembershipUserCollection list = new MembershipUserCollection();

            for (int idx = firstUserIndex; idx <= lastUserIndex; idx++)
            {
                list.Add(new VivinaMembershipUser(users[idx]));
            }

            return(list);
        }
        //con esta funcion obtenemos la lista de destinatarios
        public void obtenerListaDestinatarios()
        {
            MembershipUserCollection users = Membership.GetAllUsers();
            IEnumerator lista_usuarios     = users.GetEnumerator();

            while (lista_usuarios.MoveNext())
            {
                try
                {
                    //optenemos el usuario actual
                    string d_usuario = lista_usuarios.Current.ToString();

                    MembershipUser d_ms_user = Membership.GetUser(d_usuario);

                    string d_email = d_ms_user.Email;

                    string d_nombre           = "";
                    string d_apellido_paterno = "";
                    string d_apellido_materno = "";
                    string d_enviar_email     = "";

                    this.control_db.obtenerDatosUsuario(d_usuario, ref d_nombre, ref d_apellido_paterno, ref d_apellido_materno, ref d_enviar_email);

                    //si esta activado el envio de notificaciones
                    if (bool.Parse(d_enviar_email))
                    {
                        this.lista_emails_destinatarios.Add(d_email);
                        this.lista_envio += d_email + ",";
                    }
                }
                catch (Exception e)
                {
                    Debug.WriteLine("ERROR: " + e.ToString());
                }
            }

            if (this.lista_envio.Length > 0)
            {
                this.lista_envio = this.lista_envio.Substring(0, this.lista_envio.Length - 1);
            }
        }
Example #21
0
    // create datasource for user gridview
    private void BindUserAccounts()
    {
        int totalRecords;
        MembershipUserCollection allUsers = Membership.GetAllUsers(this.PageIndex, this.PageSize, out totalRecords);
        MembershipUserCollection filteredUsers = new MembershipUserCollection();

        if (UserRoles.SelectedIndex > 0)
        {
            string[] usersInRole = Roles.GetUsersInRole(UserRoles.SelectedValue);
            foreach (MembershipUser user in allUsers)
            {
                foreach (string userInRole in usersInRole)
                {
                    if (userInRole == user.UserName)
                    {
                        filteredUsers.Add(user);

                        // Break out of the inner foreach loop to avoid unneeded checking.
                        break;
                    }
                }
            }
        }
        else
        {
            filteredUsers = allUsers;
        }

        // Enable/disable the pager buttons based on which page we're on
        bool visitingFirstPage = (this.PageIndex == 0);
        lnkFirst.Enabled = !visitingFirstPage;
        lnkPrev.Enabled = !visitingFirstPage;

        int lastPageIndex = (totalRecords - 1) / this.PageSize;
        bool visitingLastPage = (this.PageIndex >= lastPageIndex);
        lnkNext.Enabled = !visitingLastPage;
        lnkLast.Enabled = !visitingLastPage;

        UsersGridView.DataSource = filteredUsers;
        UsersGridView.DataBind();
    }
        public override MembershipUserCollection FindUsersByName(string usernameToMatch,
                                                                 int pageIndex, int pageSize, out int totalRecords)
        {
            var membershipUsers = new MembershipUserCollection();

            using (var transaction = new TransactionScope(_mConfiguration))
            {
                var dataStore = new UserDataStore(transaction);

                var          paging = new PagingInfo(pageSize, pageIndex);
                IList <User> users  = dataStore.FindByNameLike(ApplicationName, usernameToMatch, paging);
                totalRecords = (int)paging.RowCount;

                foreach (User u in users)
                {
                    membershipUsers.Add(UserToMembershipUser(u));
                }
            }

            return(membershipUsers);
        }
        public List <MembershipUserInfo> GetAllUsers()
        {
            try
            {
                MembershipUserCollection  membershipUserCollection = new MembershipUserCollection();
                List <MembershipUserInfo> membershipUserInfo       = new List <MembershipUserInfo>();

                membershipUserCollection = Membership.GetAllUsers();
                foreach (MembershipUser user in membershipUserCollection)
                {
                    membershipUserInfo.Add(ConvertMembershipUser(user));
                }
                return(membershipUserInfo);
            }
            catch (Exception ex)
            {
                ExceptionTrace.LogException(ex);
                string networkFaultMessage = ServiceFaultResourceManager.GetString("NetworkFault").ToString();
                throw new FaultException <ServiceFault>(new ServiceFault(networkFaultMessage), new FaultReason(ex.Message));
            }
        }
Example #24
0
        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            var portal = PortalProviderManager.Provider.GetCurrentPortal();

            if (portal == null)
            {
                throw new ProviderException("Failed to retrieve users. Unknown portal.");
            }

            Tenant tenant = portal.Tenant;

            var users = _userRepository.GetAllUsers(tenant.Id, pageIndex, pageSize);

            totalRecords = users.Count;

            MembershipUserCollection result = new MembershipUserCollection();

            users.ForEach(u => result.Add(UserToMembershipUser(u)));

            return(result);
        }
        public void ShouldFindUsersByName()
        {
            // arrange
            var users = new MembershipUserCollection();
            int totalRecords;

            this.localProvider
            .FindUsersByName(UserName, 5, 20, out totalRecords)
            .Returns(x =>
            {
                x[3] = 200;
                return(users);
            });

            // act
            var result = this.provider.FindUsersByName(UserName, 5, 20, out totalRecords);

            // assert
            result.Should().BeSameAs(users);
            totalRecords.Should().Be(200);
        }
        void sendMail(string subject, string body)
        {
            MembershipUserCollection x = Membership.FindUsersByName(User.Identity.Name);
            MembershipUser           y;


            foreach (MembershipUser user in x)
            {
                y = user;



                MailMessage message     = new MailMessage("*****@*****.**", y.Email, subject, body);
                SmtpClient  emailClient = new SmtpClient("smtp.gmail.com", 587);
                System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential("*****@*****.**", "ailiaili");
                emailClient.UseDefaultCredentials = false;
                emailClient.Credentials           = SMTPUserInfo;
                emailClient.EnableSsl             = true;
                emailClient.Send(message);
            }
        }
        public void ShouldGetAllUsers()
        {
            // arrange
              var users = new MembershipUserCollection();
              int totalRecords;

              this.localProvider
            .GetAllUsers(5, 20, out totalRecords)
            .Returns(x =>
            {
              x[2] = 200;
              return users;
            });

              // act
              var result = this.provider.GetAllUsers(5, 20, out totalRecords);

              // assert
              result.Should().BeSameAs(users);
              totalRecords.Should().Be(200);
        }
Example #28
0
        public IPagedList <MembershipUser> Find(int pageIndex, int pageSize, string searchText, bool isAppoved, bool isLockedOut, int membershipAppId)
        {
            // get one page of users
            var    usersCollection = new MembershipUserCollection();
            string query           = string.Format("call uspFindMembershipUsers({0},{1},{2},{3});", "'" + searchText + "'", Convert.ToInt16(isLockedOut),
                                                   Convert.ToInt16(isAppoved), membershipAppId);
            IQuery q   = NHibernateSession.Current.CreateSQLQuery(query);
            IList  lst = q.List();

            foreach (int userId in lst)
            {
                usersCollection.Add(Membership.GetUser(userId));
            }

            // convert from MembershipUserColletion to PagedList<MembershipUser> and return
            var converter      = new EnumerableToEnumerableTConverter <MembershipUserCollection, MembershipUser>();
            var usersList      = converter.ConvertTo <IEnumerable <MembershipUser> >(usersCollection);
            var usersPagedList = new StaticPagedList <MembershipUser>(usersList, pageIndex, pageSize, lst.Count);

            return(usersPagedList);
        }
        public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            MembershipUserCollection membershipUsers = new MembershipUserCollection();

            IQueryable <User> users = from u in _db.Users
                                      where u.Email.Contains(emailToMatch) && u.ApplicationName == applicationName
                                      select u;

            totalRecords = users.Count();
            if (users.Count() <= 0)
            {
                return(membershipUsers);
            }

            foreach (User user in users.Skip(pageIndex * pageSize).Take(pageSize))
            {
                membershipUsers.Add(GetMembershipUserFromPersitentObject(user));
            }

            return(membershipUsers);
        }
Example #30
0
        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            MembershipUserCollection MembershipUsers = new MembershipUserCollection();

            using (DataContext Context = new DataContext())
            {
                totalRecords = Context.Users.Count();
                IQueryable <User> Users =
                    Context.Users.OrderBy(Usrn => Usrn.Username).Skip(pageIndex * pageSize).Take(pageSize);
                foreach (User user in Users)
                {
                    MembershipUsers.Add(new MembershipUser(Membership.Provider.Name, user.Username, user.Id,
                                                           user.Email, null, null, user.IsApproved, user.IsLockedOut,
                                                           user.CreateDate.Value, user.LastLoginDate.Value,
                                                           user.LastActivityDate.Value,
                                                           user.LastPasswordChangedDate.Value,
                                                           user.LastLockoutDate.Value));
                }
            }
            return(MembershipUsers);
        }
Example #31
0
        internal List <MWAAuthor> GetAuthors(string blogID, string userName, string password)
        {
            ValidateRequest(userName, password);

            var authors = new List <MWAAuthor>();

            //if (Roles.IsUserInRole(userName, BlogSettings.Instance.AdministratorRole))
            //TODO: Adjust to actual admin role name
            if (Roles.IsUserInRole("Admin"))
            {
                int total = 0;
                int count = 0;
                MembershipUserCollection users = Membership.Provider.GetAllUsers(0, 999, out total);

                foreach (MembershipUser user in users)
                {
                    count++;
                    MWAAuthor author = new MWAAuthor();
                    author.user_id      = user.UserName;
                    author.user_login   = user.UserName;
                    author.display_name = user.UserName;
                    author.user_email   = user.Email;
                    author.meta_value   = "";
                    authors.Add(author);
                }
            }
            else
            {
                // If not admin, just add that user to the options.
                MembershipUser single = Membership.GetUser(userName);
                MWAAuthor      author = new MWAAuthor();
                author.user_id      = single.UserName;
                author.user_login   = single.UserName;
                author.display_name = single.UserName;
                author.user_email   = single.Email;
                author.meta_value   = "";
                authors.Add(author);
            }
            return(authors);
        }
        public IList <RegisterModel> GetAllUsers(MembershipUserCollection muc)
        {
            var roleService = new RoleService();
            IList <RegisterModel> registerModels = new List <RegisterModel>();

            foreach (var m in muc)
            {
                var roles = roleService.GetUserRole(m.ToString());
                if (roles.Count > 0)
                {
                    foreach (var role in roles)
                    {
                        var registerModel = new RegisterModel
                        {
                            UserName      = role.UserName,
                            RoleModelName = role.RoleModelName,
                            Email         = role.Email
                        };
                        var membershipUser = GetUser(role.UserName);
                        registerModel.Approved  = membershipUser.IsApproved;
                        registerModel.LockedOut = membershipUser.IsLockedOut;
                        registerModels.Add(registerModel);
                    }
                }
                else
                {
                    var registerModel = new RegisterModel
                    {
                        UserName      = m.ToString(),
                        RoleModelName = ""
                    };
                    var membershipUser = GetUser(m.ToString());
                    registerModel.Approved  = membershipUser.IsApproved;
                    registerModel.LockedOut = membershipUser.IsLockedOut;
                    registerModels.Add(registerModel);
                }
            }

            return(registerModels);
        }
Example #33
0
        public static MembershipUserCollection GetAllUserWithSelectUser()
        {
            MembershipUserCollection misUsuariosConOtro = new MembershipUserCollection();
            MembershipUserCollection misUsuarios        = Membership.GetAllUsers();

            if (misUsuarios == null)
            {
                return(null);
            }

            MembershipUser miOtroUsuario = null;

            foreach (MembershipUser miUsuario in misUsuarios)
            {
                miOtroUsuario = new MembershipUser(
                    miUsuario.ProviderName,
                    "[Seleccione un usuario...]",
                    miUsuario.ProviderUserKey,
                    miUsuario.Email,
                    miUsuario.PasswordQuestion,
                    miUsuario.Comment,
                    miUsuario.IsApproved,
                    miUsuario.IsLockedOut,
                    miUsuario.CreationDate,
                    miUsuario.LastLoginDate,
                    miUsuario.LastActivityDate,
                    miUsuario.LastPasswordChangedDate,
                    miUsuario.LastLockoutDate);
                break;
            }

            misUsuariosConOtro.Add(miOtroUsuario);

            foreach (MembershipUser miUsuario in misUsuarios)
            {
                misUsuariosConOtro.Add(miUsuario);
            }

            return(misUsuariosConOtro);
        }
Example #34
0
        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            AuthenticationSection authSection =
                (AuthenticationSection)WebConfigurationManager.GetWebApplicationSection("system.web/authentication");

            NameValueCollection emailsSection =
                (NameValueCollection)System.Configuration.ConfigurationManager.GetSection("emails");

            totalRecords = authSection.Forms.Credentials.Users.Count;
            MembershipUserCollection users = new MembershipUserCollection();


            for (int i = pageIndex * pageSize;
                 i < Math.Min(totalRecords, pageIndex * pageSize + pageSize);
                 i++)
            {
                FormsAuthenticationUser user = authSection.Forms.Credentials.Users[i];
                string email = null;
                email = emailsSection[user.Name];

                users.Add(new MembershipUser(
                              "FormsProvider",
                              user.Name,
                              null,
                              email,
                              null,
                              null,
                              true,
                              false,
                              // do not use DateTime.MinValue because some WebDAV clients may not properly parse it.
                              new DateTime(2000, 1, 1),
                              new DateTime(2000, 1, 1),
                              new DateTime(2000, 1, 1),
                              new DateTime(2000, 1, 1),
                              new DateTime(2000, 1, 1))
                          );
            }

            return(users);
        }
        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            MembershipUserCollection users = new MembershipUserCollection();

            totalRecords = 0;
            IEnumerable <User> allUsers = null;
            int counter    = 0;
            int startIndex = pageSize * pageIndex;
            int endIndex   = startIndex + pageSize - 1;

            using (ISession session = _sessionFactory.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    totalRecords = (Int32)session.CreateCriteria(typeof(User))
                                   .SetProjection(NHibernate.Criterion.Projections.Count("Id")).UniqueResult();

                    if (totalRecords <= 0)
                    {
                        return(users);
                    }

                    allUsers = session.CreateCriteria(typeof(User)).List <User>();
                    foreach (User user in allUsers)
                    {
                        if (counter >= endIndex)
                        {
                            break;
                        }
                        if (counter >= startIndex)
                        {
                            MembershipUser mu = GetMembershipUserFromUser(user);
                            users.Add(mu);
                        }
                        counter++;
                    }
                }
                return(users);
            }
        }
Example #36
0
        private void Bind()
        {
            List <UserRoleInfo> list = new List <UserRoleInfo>();

            if (!string.IsNullOrEmpty(userName))
            {
                MembershipUserCollection users = Membership.FindUsersByName(userName, pageIndex - 1, pageSize, out totalRecords);
                foreach (MembershipUser user in users)
                {
                    UserRoleInfo rModel = new UserRoleInfo();
                    rModel.UserName = user.UserName;
                    string[] currRoles = Roles.GetRolesForUser(user.UserName);
                    rModel.IsInRole = currRoles.Contains(roleName);

                    list.Add(rModel);
                }
            }
            else
            {
                string[] usersInRole = Roles.GetUsersInRole(roleName);

                foreach (var item in usersInRole)
                {
                    list.Add(new UserRoleInfo {
                        UserName = item, IsInRole = true
                    });
                }

                list = list.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList <UserRoleInfo>();

                totalRecords = usersInRole.Length;
            }

            rpData.DataSource = list;
            rpData.DataBind();

            myDataAppend.Append("<div id=\"myDataForPage\" style=\"display:none;\">{\"PageIndex\":\"" + pageIndex + "\",\"PageSize\":\"" + pageSize + "\",\"TotalRecord\":\"" + totalRecords + "\",\"QueryStr\":\"" + queryStr + "\"}</div>");
            myDataAppend.Append("<div id=\"myDataForModel\" style=\"display:none;\">{\"Keyword\":\"" + userName + "\"}</div>");
            ltrMyData.Text = myDataAppend.ToString();
        }
Example #37
0
        internal static void CreateUserRecords(MembershipProvider provider)
        {
            Users = new List <UserCreateStub>();
            int totalRecords;
            MembershipUserCollection users = provider.GetAllUsers(0, int.MaxValue - 1, out totalRecords);

            foreach (MembershipUser user in users)
            {
                if (
                    (user.UserName != null && user.UserName.ToLower().Contains("test_")) ||
                    (user.Email != null && user.Email.ToLower().Contains("test_")) ||
                    (user.PasswordQuestion != null && user.PasswordQuestion.ToLower().Contains("test_")))
                {
                    provider.DeleteUser(user.UserName, true);
                }
            }

            for (int x = 0; x < 50; x++)
            {
                string username    = "******" + x.ToString("000");
                string email       = "TEST_EMAIL_" + x.ToString("000") + "@test.com";
                string question    = "TEST_QUESTION:" + x.ToString("000");
                string answer      = "TEST_ANSWER:" + x.ToString("000");
                string password    = "******" + x.ToString("000");
                bool   isActive    = (x % 2) == 0; //only even numbers are active
                Guid   providerKey = Guid.NewGuid();
                MembershipCreateStatus status;

                var response = provider.CreateUser(username, password, email, question, answer, isActive, providerKey, out status);
                response.IsApproved = x != 19;
                response.Comment    = "";
                provider.UpdateUser(response);
                if (x != 19)
                {
                    provider.UnlockUser(username);  //record 19 is in 'Locked' status
                }
                Assert.AreEqual <MembershipCreateStatus>(MembershipCreateStatus.Success, status);
                Users.Add(new UserCreateStub(username, email, password, question, answer, response.IsApproved, providerKey, provider.Name));
            }
        }
        public void TestCreateUserOverrides()
        {
            try
            {
                MembershipCreateStatus status;
                Membership.CreateUser("foo", "barbar!", null, "question", "answer", true, out status);
                int records;
                MembershipUserCollection users = Membership.FindUsersByName("F%", 0, 10, out records);
                Assert.AreEqual(1, records);
                Assert.AreEqual("foo", users["foo"].UserName);

                Membership.CreateUser("test", "barbar!", "*****@*****.**",
                                      "question", "answer", true, out status);
                users = Membership.FindUsersByName("T%", 0, 10, out records);
                Assert.AreEqual(1, records);
                Assert.AreEqual("test", users["test"].UserName);
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }
        }
Example #39
0
    // create datasource for user gridview
    private void BindUserAccounts()
    {
        int totalRecords;
        MembershipUserCollection allUsers = Membership.GetAllUsers(this.PageIndex, this.PageSize, out totalRecords);
        MembershipUserCollection filteredUsers = new MembershipUserCollection();

        // create boolean for dropdown control list
        bool isActive;
        if (active.SelectedValue == "Active Accounts")
        {
            isActive = true;
        }
        else
        {
            isActive = false;
        }

        // create boolean Values for dropdown list
        foreach (MembershipUser user in allUsers)
        {
            if (user.IsApproved == isActive)
            {
                filteredUsers.Add(user);
            }
        }

        // Enable/disable the pager buttons based on which page we're on
        bool visitingFirstPage = (this.PageIndex == 0);
        lnkFirst.Enabled = !visitingFirstPage;
        lnkPrev.Enabled = !visitingFirstPage;

        int lastPageIndex = (totalRecords - 1) / this.PageSize;
        bool visitingLastPage = (this.PageIndex >= lastPageIndex);
        lnkNext.Enabled = !visitingLastPage;
        lnkLast.Enabled = !visitingLastPage;

        UsersGridView.DataSource = filteredUsers;
        UsersGridView.DataBind();
    }
Example #40
0
    protected void OnLogin(object sender, EventArgs e)
    {
        //Event handler for login request
        string username = this.txtUserID.Text.Trim();
        string pwd      = this.txtPassword.Text;

        try {
            //Validate login
            MembershipUserCollection users = Membership.FindUsersByName(username);
            if (users.Count == 0)
            {
                rfvUserID.IsValid = false; rfvUserID.ErrorMessage = USER_LOGIN_NOACCOUNT; return;
            }
            if (users[username].IsLockedOut)
            {
                rfvUserID.IsValid = false; rfvUserID.ErrorMessage = USER_ACCOUNT_LOCKEDOUT; return;
            }
            if (!users[username].IsApproved)
            {
                rfvUserID.IsValid = false; rfvUserID.ErrorMessage = USER_ACCOUNT_INACTIVE; return;
            }
            if (Page.IsValid)
            {
                //Validate userid/password
                if (Membership.ValidateUser(username, this.txtPassword.Text))
                {
                    //?
                    FormsAuthentication.SetAuthCookie(username, false);
                    string url = Request.QueryString["ReturnUrl"];
                    Response.Redirect((url != null ? url : "~/Default.aspx"), false);
                }
                else
                {
                    rfvUserID.IsValid = false; rfvUserID.ErrorMessage = USER_LOGIN_FAILED;
                }
            }
        }
        catch (Exception ex) { rfvUserID.IsValid = false; rfvUserID.ErrorMessage = ex.Message; }
    }
Example #41
0
 public static MembershipUserCollection GetUsersList(string name_part, int group_id)
 {
     string sErr = "";
     DBManager db = new DBManager(ConfigurationManager.AppSettings["SYS_DSN"]);
     MembershipUserCollection result = new MembershipUserCollection();
     try
     {
         string sql = string.Concat("exec spSysGetUsers @SearchString='", name_part, "',@GroupId=", group_id.ToString());
         DataTable dt = db.getDataTable(sql, out sErr);
         db.CloseOleDB();
         for (int i = 0; i < dt.Rows.Count; i++)
         {
             MembershipUser oUser = Membership.GetUser(dt.Rows[i]["UserName"].ToString());
             if (oUser != null)
             {
                 result.Add(oUser);
             }
         }
     }
     catch (Exception exception)
     {
         HttpContext.Current.Response.Write(exception.Message);
     }
     return result;
 }
    public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
    {
        List<MembershipUserCollection> mucs = new List<MembershipUserCollection>();
        foreach (string providerName in m_ProviderList)
        {
            MembershipProvider mp = Membership.Providers[providerName];
            mucs.Add(mp.GetAllUsers(pageIndex, pageSize, out totalRecords));
        }
        MembershipUserCollection allUsers = new MembershipUserCollection();
        totalRecords = 0;

        List<string> userNames = new List<string>();

        foreach (MembershipUserCollection muc in mucs)
        {
            foreach (MembershipUser mu in muc)
            {
                if (!(userNames.Contains(mu.UserName)))
                {
                    userNames.Add(mu.UserName);
                    allUsers.Add(mu);
                    totalRecords++;
                }
            }
        }
        return allUsers;
    }
    /// <summary>
    /// Retrieves a collection of all the users.
    /// This implementation ignores pageIndex and pageSize,
    /// and it doesn't sort the MembershipUser objects returned.
    /// </summary>
    public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
    {
        //ReadMembershipDataStore();
        MembershipUserCollection users = new MembershipUserCollection();

        List<Usuario> usuarios = UsuarioDal.GetAllUsuarios();

        if (usuarios != null)
        {
            foreach (Usuario usr in usuarios)
            {
                MembershipUser newuser = GetUser(usr.UserName, true);
                users.Add(newuser);
            }
        }

        totalRecords = users.Count;
        return users;
    }
    /// <summary>
    /// Retrieves a collection of all the users.
    /// This implementation ignores pageIndex and pageSize,
    /// and it doesn't sort the MembershipUser objects returned.
    /// </summary>
    public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
    {
        ReadMembershipDataStore();
        MembershipUserCollection users = new MembershipUserCollection();

        foreach (KeyValuePair<string, MembershipUser> pair in _Users)
        {
          users.Add(pair.Value);
        }

        totalRecords = users.Count;
        return users;
    }
 public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
 {
     MembershipUserCollection MembershipUsers = new MembershipUserCollection();
     using (DataContext Context = new DataContext())
     {
         totalRecords = Context.Users.Where(Usr => Usr.Username == usernameToMatch).Count();
         IQueryable<User> Users = Context.Users.Where(Usr => Usr.Username == usernameToMatch).OrderBy(Usrn => Usrn.Username).Skip(pageIndex * pageSize).Take(pageSize);
         foreach (User user in Users)
         {
             MembershipUsers.Add(new MembershipUser(Membership.Provider.Name, user.Username, user.UserId, user.Email, null, null, user.IsApproved, user.IsLockedOut, user.CreateDate.Value, user.LastLoginDate.Value, user.LastActivityDate.Value, user.LastPasswordChangedDate.Value, user.LastLockoutDate.Value));
         }
     }
     return MembershipUsers;
 }
    public override MembershipUserCollection GetAllUsers(int pageIndex, 
        int pageSize, out int totalRecords)
    {
        // Note: This implementation ignores pageIndex and pageSize,
        // and it doesn't sort the MembershipUser objects returned
        // Make sure the data source has been loaded

        ReadMembershipDataStore();

        MembershipUserCollection users =
        new MembershipUserCollection();

        foreach (KeyValuePair<string, MembershipUser> pair in _Users)
        users.Add(pair.Value);

        totalRecords = users.Count;

        return users;
    }
 public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
 {
     SqlConnection conn = new SqlConnection(connectionString);
         SqlCommand cmd = new SqlCommand("SELECT Count(*) FROM Users", conn);
         MembershipUserCollection users = new MembershipUserCollection();
         SqlDataReader reader = null;
         totalRecords = 0;
         try
         {
             conn.Open();
             totalRecords = (int)cmd.ExecuteScalar();
             if (totalRecords <= 0)
             {
                 return users;
             }
             cmd.CommandText = "SELECT User_Id, User_Name, User_Family, User_Email, User_Phone, User_Password, User_CreateDate, User_LastLogInDate, User_Area " +
                              " FROM T_Users " +
                              " ORDER BY Username Asc";
             reader = cmd.ExecuteReader();
             int counter = 0;
             int startIndex = pageSize * pageIndex;
             int endIndex = startIndex + pageSize - 1;
             while (reader.Read())
             {
                 if (counter >= startIndex)
                 {
                     MembershipUser u = GetUserFromReader(reader);
                     users.Add(u);
                 }
                 if (counter >= endIndex) { cmd.Cancel(); }
                 counter++;
             }
         }
         catch (SqlException e)
         {
             if (WriteExceptionsToEventLog)
             {
                 WriteToEventLog(e, "GetAllUsers ");
                 throw new ProviderException(exceptionMessage);
             }
             else
             {
                 throw e;
             }
         }
         finally
         {
             if (reader != null) { reader.Close(); }
             conn.Close();
         }
         return users;
 }
 public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
 {
     List<Person> list = PersonModel.ListPerson();
     totalRecords = list.Count;
     MembershipUserCollection ret = new MembershipUserCollection();
     foreach (Person p in list)
         ret.Add(p);
     return ret;
 }
    protected void Page_Load(object sender, EventArgs e)
    {
        Repeater repeater;
        Panel panel;
        ProfileCommon profilecommon;
        string[] user;
        string operation;

        if (!IsPostBack)
        {
            operation = Request.QueryString["operation"];

            if (operation != null)
            {
                if (operation.Equals("edit"))
                {
                    repeater = (Repeater)LoginView1.FindControl("Repeater1");
                    if (repeater != null)
                    {
                        repeater.Visible = false;
                    }

                    panel = (Panel)LoginView1.FindControl("Panel1");
                    if (panel != null)
                    {
                        panel.Visible = true;
                    }

                    ((DropDownList)LoginView1.FindControl("DateOfBirth1")).DataSource = GlobalVariable.day;
                    ((DropDownList)LoginView1.FindControl("DateOfBirth1")).DataBind();
                    ((DropDownList)LoginView1.FindControl("DateOfBirth2")).DataSource = GlobalVariable.month;
                    ((DropDownList)LoginView1.FindControl("DateOfBirth2")).DataBind();
                    ((DropDownList)LoginView1.FindControl("DateOfBirth3")).DataSource = GlobalVariable.year;
                    ((DropDownList)LoginView1.FindControl("DateOfBirth3")).DataBind();
                    ((DropDownList)LoginView1.FindControl("Nationality")).DataSource = GlobalVariable.nationality;
                    ((DropDownList)LoginView1.FindControl("Nationality")).DataBind();
                    ((DropDownList)LoginView1.FindControl("Country")).DataSource = GlobalVariable.country;
                    ((DropDownList)LoginView1.FindControl("Country")).DataBind();

                    profilecommon = Profile.GetProfile(Request.QueryString["username"]);

                    ((TextBox)LoginView1.FindControl("FirstName")).Text = profilecommon.User.FirstName;
                    ((TextBox)LoginView1.FindControl("LastName")).Text = profilecommon.User.LastName;
                    dateofbirth = profilecommon.User.DateOfBirth.Split('/');
                    ((DropDownList)LoginView1.FindControl("DateOfBirth1")).SelectedIndex = Array.IndexOf(GlobalVariable.day, dateofbirth.ElementAt(0));
                    if (dateofbirth.Count() > 1)
                    {
                        ((DropDownList)LoginView1.FindControl("DateOfBirth2")).SelectedIndex = Array.IndexOf(GlobalVariable.month, dateofbirth.ElementAt(1));
                    }
                    if (dateofbirth.Count() > 2)
                    {
                        ((DropDownList)LoginView1.FindControl("DateOfBirth3")).SelectedIndex = Array.IndexOf(GlobalVariable.year, dateofbirth.ElementAt(2));
                    }
                    if (profilecommon.User.Gender.Equals("Male"))
                    {
                        ((RadioButton)LoginView1.FindControl("Gender1")).Checked = true;
                    }
                    else
                    {
                        ((RadioButton)LoginView1.FindControl("Gender2")).Checked = true;
                    }
                    ((DropDownList)LoginView1.FindControl("Nationality")).SelectedIndex = Array.IndexOf(GlobalVariable.nationality, profilecommon.User.Nationality);
                    ((TextBox)LoginView1.FindControl("Street")).Text = profilecommon.User.Street;
                    ((TextBox)LoginView1.FindControl("HouseNumber")).Text = profilecommon.User.HouseNumber;
                    ((TextBox)LoginView1.FindControl("City")).Text = profilecommon.User.City;
                    ((DropDownList)LoginView1.FindControl("Country")).SelectedIndex = Array.IndexOf(GlobalVariable.country, profilecommon.User.Country);
                    ((TextBox)LoginView1.FindControl("PostalCode")).Text = profilecommon.User.PostalCode;
                    ((Label)LoginView1.FindControl("EmailAddress")).Text = Request.QueryString["username"];
                    if (Membership.GetUser(Request.QueryString["username"]).IsApproved)
                    {
                        ((RadioButton)LoginView1.FindControl("Status1")).Checked = true;
                    }
                    else
                    {
                        ((RadioButton)LoginView1.FindControl("Status2")).Checked = true;
                    }
                }
                else if (operation.Equals("delete"))
                {
                    Membership.DeleteUser(Request.QueryString["username"]);

                    Response.Redirect("./managestudent.aspx");
                }
            }
            else
            {
                user = Roles.GetUsersInRole("User");
                membershipusercollection = new MembershipUserCollection();

                foreach (string username in user)
                {
                    membershipusercollection.Add(Membership.GetUser(username));
                }

                repeater = (Repeater)LoginView1.FindControl("Repeater1");
                if (repeater != null)
                {
                    repeater.DataSource = membershipusercollection;
                    repeater.DataBind();
                    repeater.Visible = true;
                }

                panel = (Panel)LoginView1.FindControl("Panel1");
                if (panel != null)
                {
                    panel.Visible = false;
                }
            }
        }
        else
        {
            operation = Request.QueryString["operation"];

            if (operation == null)
            {
                user = Roles.GetUsersInRole("User");
                membershipusercollection = new MembershipUserCollection();

                foreach (string username in user)
                {
                    membershipusercollection.Add(Membership.GetUser(username));
                }

                repeater = (Repeater)LoginView1.FindControl("Repeater1");
                if (repeater != null)
                {
                    repeater.DataSource = membershipusercollection;
                    repeater.DataBind();
                    repeater.Visible = true;
                }

                panel = (Panel)LoginView1.FindControl("Panel1");
                if (panel != null)
                {
                    panel.Visible = false;
                }
            }
        }
    }
    //receives as input a page index and page size of type integer and the total records of type out integer
    //returns a collection containing all the users in the CRM account
    //returns NULL if there are no users to return
    public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
    {
        //MAS
        using (OrganizationService service = new OrganizationService(OurConnect()))
        {

            ConditionExpression deleteCondition = new ConditionExpression();
            ConditionExpression appCondition = new ConditionExpression();//creates a new condition.

            deleteCondition.AttributeName = consts.deleteduser;
            deleteCondition.Operator = ConditionOperator.Equal;
            deleteCondition.Values.Add(false);

            appCondition.AttributeName = consts.appname;
            appCondition.Operator = ConditionOperator.Equal;
            appCondition.Values.Add(_ApplicationName);

            FilterExpression filter = new FilterExpression(); //create new filter for the condition
            filter.Conditions.Add(deleteCondition);
            filter.Conditions.Add(appCondition);

            QueryExpression query = new QueryExpression(consts.useraccount); //create new query
            query.Criteria.AddFilter(filter);
            EntityCollection collection = service.RetrieveMultiple(query); //retrieve all records with same email

            totalRecords = collection.TotalRecordCount;

            if (totalRecords != 0 && totalRecords >= ((pageSize * pageIndex) + 1))
            {
                MembershipUserCollection usersToReturn = new MembershipUserCollection();
                var start = pageSize * pageIndex;
                var end = (pageSize * pageIndex) + pageSize;
                for (int i = start; i < end; i++)
                {
                    MembershipUser TempUser = GetUser((string)collection.Entities[i][consts.username]);
                    usersToReturn.Add(TempUser);

                }
                return usersToReturn;
            }
            else
            {
                return null;
            }
        }
    }
    //receives a username of type string, and page index and page size of type integer and total records of type out integer
    //returns a collection of users that match the given username
    //returns NULL if no users match the given username
    public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
    {
        //MAS
        using (OrganizationService service = new OrganizationService(OurConnect()))
        {

            ConditionExpression usernameCondition = new ConditionExpression();
            ConditionExpression deleteCondition = new ConditionExpression();
            ConditionExpression appCondition = new ConditionExpression();//creates a new condition.

            usernameCondition.AttributeName = consts.username; //column we want to check against
            usernameCondition.Operator = ConditionOperator.Equal; //checking against equal values
            usernameCondition.Values.Add(usernameToMatch); //checks email against rosetta_email in CRM

            deleteCondition.AttributeName = consts.deleteduser;
            deleteCondition.Operator = ConditionOperator.Equal;
            deleteCondition.Values.Add(false);

            appCondition.AttributeName = consts.appname;
            appCondition.Operator = ConditionOperator.Equal;
            appCondition.Values.Add(_ApplicationName);

            FilterExpression filter = new FilterExpression(); //create new filter for the condition
            filter.Conditions.Add(usernameCondition);
            filter.Conditions.Add(deleteCondition);
            filter.Conditions.Add(appCondition);//add condition to the filter

            QueryExpression query = new QueryExpression(consts.useraccount); //create new query
            query.Criteria.AddFilter(filter); //query CRM with the new filter for email
            EntityCollection collection = service.RetrieveMultiple(query); //retrieve all records with same email

            totalRecords = collection.TotalRecordCount;

            if (totalRecords != 0 && totalRecords >= ((pageSize * pageIndex) + 1))
            {
                MembershipUserCollection usersToReturn = new MembershipUserCollection();
                var start = pageSize * pageIndex;
                var end = (pageSize * pageIndex) + pageSize;
                for (int i = start; i < end; i++)//gets all the records out of ec assigns them to userstoreturn.
                {
                    MembershipUser TempUser = GetUser((string)collection.Entities[i][consts.username]);
                    usersToReturn.Add(TempUser);

                }
                return usersToReturn;
            }
            else
            {
                return null;
            }
        }
    }
Example #52
0
 public static MembershipUserCollection GetUsers(string name_part)
 {
     MembershipUserCollection allUsers;
     if (!(name_part == ""))
     {
         MembershipUserCollection users = new MembershipUserCollection();
         MembershipUserCollection result = new MembershipUserCollection();
         foreach (MembershipUser u in Membership.GetAllUsers())
         {
             if ((u == null ? false : u.UserName.Contains(name_part)))
             {
                 result.Add(u);
             }
         }
         allUsers = result;
     }
     else
     {
         allUsers = Membership.GetAllUsers();
     }
     return allUsers;
 }
 public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
 {
     MembershipUserCollection MembershipUsers = new MembershipUserCollection();
     using (PMToolContext Context = new PMToolContext())
     {
         totalRecords = Context.UserProfiles.Count();
         IQueryable<UserProfile> Users = Context.UserProfiles.OrderBy(Usrn => Usrn.UserName).Skip(pageIndex * pageSize).Take(pageSize);
         foreach (UserProfile user in Users)
         {
             MembershipUsers.Add(new MembershipUser(Membership.Provider.Name, user.UserName, user.UserId, user.Email, null, null, user.IsApproved, user.IsLockedOut, user.CreateDate.Value, user.LastLoginDate.Value, user.LastActivityDate.Value, user.LastPasswordChangedDate.Value, user.LastLockoutDate.Value));
         }
     }
     return MembershipUsers;
 }
 public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
 {
     MembershipUserCollection MembershipUsers = new MembershipUserCollection();
     using (StudentContext Context = new StudentContext())
     {
         totalRecords = Context.Users.Count();
         IQueryable<User> Users = Context.Users.OrderBy(Usrn => Usrn.Username).Skip(pageIndex * pageSize).Take(pageSize);
         foreach (User user in Users)
         {
             MembershipUsers.Add(new MembershipUser(Membership.Provider.Name, user.Username, user.UserId, user.Email, null, null, user.StatusId == (int)UserStatus.Active, user.IsLockedOut, user.InsertedOn, user.LastLoginDate.Value, user.LastActivityDate.Value, user.LastPasswordChangedDate.Value, user.LastLockoutDate.Value));
         }
     }
     return MembershipUsers;
 }