Wrox Programmer Forums
|
ASP.NET 4 General Discussion For ASP.NET 4 discussions not relating to a specific Wrox book
Welcome to the p2p.wrox.com Forums.

You are currently viewing the ASP.NET 4 General Discussion section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
 
Old April 11th, 2013, 10:38 PM
Authorized User
 
Join Date: Dec 2011
Posts: 26
Thanks: 1
Thanked 4 Times in 3 Posts
Default Creating page to manage user roles

Hello all,
I have read the Beginning ASP.NET 4 book and I am using the aspnetdb and the user creation/management that comes with it. I have also set up one role and that role gets access to the management portion of the website.

With that said, here is what I need and I cannot find in the book. The book also references tinyurl.com/RolesAPI, but I still need some help getting started.

What I need is to build a page where I can list all the users and whether they belong to my one role (called "Board" like a board member).

Then I need to have a add or remove button next to the users name that allows the admin user to add or remove users from that Board role.

I have taken a look at the Roles class and see the AddUsersToRole and RemoveUserFromRole methods. So, that seems simple enough.

What I am not sure on is how to list out the users from the aspnetdb and then list next to them whether they belong to the Board role.

Is someone willing to offer some beginning steps?

At first I created a Model for the aspnetdb and it looked like that would work for me, but then I noticed my sign up page was broken until I deleted that model. So, I am assuming I will be required to use a regular SQL Data Source Connection? (I have been sticking to Entity Data Sources for this project, but at this point I'll do whatever is needed.)

I guess with a SQL connection I could build a query that looks at the user, users_in_role, and roles tables of the aspnetdb to get he user name and role name associated to each user...

Is there a easier or better way?
 
Old April 14th, 2013, 11:31 PM
Authorized User
 
Join Date: Dec 2011
Posts: 26
Thanks: 1
Thanked 4 Times in 3 Posts
Default my solution

Hello all,
Despite no replies to this thread, I was able to figure out a solution. I have noticed a number of views for this thread; so, I decided I'd show you how I ended up implementing the page I needed.

Here is the relevant ManageUsers.aspx code

Code:
    <center>
        <asp:Label ID="UpdatedMessage" runat="server" Text="UpdatedMessage Label text" 
                Visible="False" CssClass="updatedMessage" Width="750px"></asp:Label>
    </center>

    <!-- this listview is for users not on the board and allows the admin user viewing the page to delete the user
    or add said user to the Board role. -->
    <h2>Users not on the Board</h2>
    <asp:ListView ID="ListViewNonBoard" ItemPlaceholderID="IPHNonBoard" runat="server" > 
            <LayoutTemplate> 
                <asp:Literal runat="server" ID="IPHNonBoard"></asp:Literal> 
            </LayoutTemplate> 
            <ItemTemplate> 
                <asp:Literal ID="Literal1" runat="server" Text='<%# Eval("UserName") %>'></asp:Literal> 
                <asp:Button ID="Button1" runat="server" Text='Delete User' CommandArgument='<%# Eval("UserName") %>' 
                OnClientClick="return confirm('This will permanently delete this user and all of their service and directory entries. Are you sure you want to do this?');" />
                <asp:Button ID="Button2" runat="server" Text='Add To Board role' CommandArgument='<%# Eval("UserName") %>' />
                <br /> 
            </ItemTemplate> 
    </asp:ListView> 

    <!-- this listview is for users that are on the board and allows the admin user viewing the page to delete the user,
    remove the user from the Board role, or add or remove said user to the Admin role. -->
    <h2>Users on the Board</h2>
    <asp:ListView ID="ListViewBoard" ItemPlaceholderID="IPHBoard" runat="server"  > 
            <LayoutTemplate> 
                <asp:Literal runat="server" ID="IPHBoard"></asp:Literal> 
            </LayoutTemplate> 
            <ItemTemplate> 
                <!-- note that this listview's datasouce is just a string array so, we bind it directly instead of using eval -->
                <asp:Literal ID="Literal2" runat="server" Text='<%# Container.DataItem %>'></asp:Literal> 
                <asp:Button ID="Button1" runat="server" Text='Delete User' CommandArgument='<%# Container.DataItem %>' 
                OnClientClick="return confirm('This will permanently delete this user and all of their service and directory entries. Are you sure you want to do this?');" />
                <asp:Button ID="Button2" runat="server" Text='Remove From Board role' CommandArgument='<%# Container.DataItem %>' />
                <asp:Button ID="Button3" runat="server" Text='Add/Remove User Admin role' CommandArgument='<%# Container.DataItem %>' />
                <br /> 
            </ItemTemplate> 
    </asp:ListView>
Here is my code behind (ManageUsers.aspx.cs)
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

public partial class Manage_ManageUsers : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            // we need the listviews to have the appropriate group of users to display. We do that here.
            loadListViewNonBoard();
            loadListViewBoard();
        }

    }

    protected void Page_Init(object sender, EventArgs e) 
    { 
        // in the page init event, we need to add the event handler for ItemCommand
        ListViewNonBoard.ItemCommand += new EventHandler<ListViewCommandEventArgs>(ListViewNonBoard_ItemCommand);
        ListViewBoard.ItemCommand += new EventHandler<ListViewCommandEventArgs>(ListViewBoard_ItemCommand);
    }

    void ListViewNonBoard_ItemCommand(object sender, ListViewCommandEventArgs e) 
    {
        /* we button the commandSource and CommandArgument into local variables just to give them names that are 
         * obvious in terms of what they are and, thus, more easy to work with */
        Button localButton = (Button)e.CommandSource;
        string userNameFromRowButtonClicked = (String)e.CommandArgument;

        // If the user clicked the Delete user button, we delete the user of course.
        if (localButton.Text == "Delete User")
        {
            /* we delete the user from the aspnet db and delete the users directory entry and services
             * from the Association Database */
            Membership.DeleteUser(userNameFromRowButtonClicked);
            SharedMethods.deleteUsersDirectory(userNameFromRowButtonClicked);
            SharedMethods.deleteUsersServicesAll(userNameFromRowButtonClicked);
            // now we refresh the page so the user sees the change
            Response.Redirect("ManageUsers.aspx");
        }
        /* if they haven't clicked  the Delete button, they have clicked the 
         * Add to Board role button */
        else
        {
            Roles.AddUserToRole(userNameFromRowButtonClicked, "Board");
            // now we refresh the page so the user sees the change
            Response.Redirect("ManageUsers.aspx");
        }
    }

    void ListViewBoard_ItemCommand(object sender, ListViewCommandEventArgs e)
    {
        Button localButton = (Button)e.CommandSource;
        string userNameFromRowButtonClicked = (String)e.CommandArgument;

        if (localButton.Text == "Delete User")
        {
            /* we delete the user from the aspnet db and delete the users directory entry and services
             * from the Association Database */
            Membership.DeleteUser(userNameFromRowButtonClicked);
            SharedMethods.deleteUsersDirectory(userNameFromRowButtonClicked);
            SharedMethods.deleteUsersServicesAll(userNameFromRowButtonClicked);
            // now we refresh the page so the user sees the change
            Response.Redirect("ManageUsers.aspx");
        }
        else if (localButton.Text == "Add/Remove User Admin role")
        {
            /* if the FindUsersInRole.count method returns 0, then the user is not in the role.
             * In that case, we add the user to the role. */
            if (Roles.FindUsersInRole("UserAdmin", userNameFromRowButtonClicked).Count() <= 0)
            {
                Roles.AddUserToRole(userNameFromRowButtonClicked, "UserAdmin");
                UpdatedMessage.Text = "You have successfully added the user to the User Administration role.";
            }
            /* otherwise, the FindUsersInRole.count method found > 0 users, meaning the user is already in the role.
             * In that case, we remove the user from the role. */
            else
            {
                Roles.RemoveUserFromRole(userNameFromRowButtonClicked, "UserAdmin");
                UpdatedMessage.Text = "You have successfully removed the user from the User Administration role.";
            }
            // now these methods have updated the UpdatedMessage label so we need to make it visible
            UpdatedMessage.Visible = true;
        }
        /* if they haven't clicked  the Delete button or the 'Add/Remove User Admin role' button, they have clicked the 
         * 'Remove from Board role' button */
        else
        {
            Roles.RemoveUserFromRole(userNameFromRowButtonClicked, "Board");
            // now we refresh the page so the user sees the change
            Response.Redirect("ManageUsers.aspx");
        }
    }

    private void loadListViewNonBoard()
    {
        /* this block grabs the users in the board role, compares it against all the users,
         * and puts all the users NOT in the board role into the users var. */
        var usersInRole = Roles.GetUsersInRole("Board");
        var users = Membership.GetAllUsers()
            .Cast<MembershipUser>()
            .Where(u =>
                !usersInRole.Contains(u.UserName)
            );

        // now we just need to bind that group of users to the ListViewNonBoard
        ListViewNonBoard.DataSource = users;
        ListViewNonBoard.DataBind();
    }

    private void loadListViewBoard()
    {
        // first we grab the users with the Board roles
        var boardUsers = Roles.GetUsersInRole("Board");

        // now we bind that group of users to the ListViewBoard
        ListViewBoard.DataSource = boardUsers;
        ListViewBoard.DataBind();
    }
}
Hope this someday helps someone else who wants to do the same kind of thing.
The Following 2 Users Say Thank You to Notso For This Useful Post:
Imar (April 15th, 2013)





Similar Threads
Thread Thread Starter Forum Replies Last Post
Letting user manage content Gudni BOOK: Beginning ASP.NET Web Pages with WebMatrix 4 January 26th, 2013 11:25 AM
Multiple roles for a singe user ASP.NET saifsid9 ASP.NET 4 General Discussion 1 January 26th, 2012 06:58 AM
Query about the USER ROLES in INFOPATH anandhienator Infopath 1 May 2nd, 2007 12:51 PM
manage page PPGpilot Beginning PHP 2 January 21st, 2006 01:10 AM
Accessing User Roles in MS Access through Java sfali Java Databases 0 September 24th, 2003 08:12 AM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.