Check if User already belonged to a Role (Problem)

Hello

I'm having a problem with checking if a user already has a Role before assigning a Role to them. Here is my partical code.

' Check if a User belonged to a Role

If (User.IsInRole(newUsers.ToString)) Then
Msg.Text = " User already has a Role "
Exit Sub

Else

' Add users to the selected role
Roles.AddUsersToRole(newUsers, RolesListBox.SelectedItem.Value)

End If

But it's not working at all. Everytime, I tried to assign a user who has a role aready, it gave me error instead of showing the text User already has a Role. I've got error like this" ProviderException was unhandled by user code " and then " the user ' Mike ' is already in a role ' teacher ' "

If you wanna have a look at my full code, see below :


Protected Sub AddUsers_OnClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddUsersToRole.Click


' A role must be selected


If RolesListBox.SelectedItem Is Nothing Then
Msg.Text = "Please select a role."
Exit Sub
End If


' At least one user must be selected

If UsersListBox.SelectedItem Is Nothing Then
Msg.Text = "Please select one or more users."
Exit Sub
End If

' Create list of users to be added to the selected role

Dim sizeOfArray As Integer = UsersListBox.GetSelectedIndices.Length
Dim newUsers(sizeOfArray - 1) As String


For i As Integer = 0 To newUsers.Length - 1

' get the array of selected indices from the (multiselect) list box
Dim selectedIndices As Integer() = UsersListBox.GetSelectedIndices()

' get the selectedIndex that corresponds to the counter (i)
Dim selectedIndex As Integer = selectedIndices(i)

' get the ListItem in the UserListBox Items collection at that offset
Dim myListItem As ListItem = UsersListBox.Items(selectedIndex)

' get the string that is that ListItem's value property
Dim newUser As String = myListItem.Value

' add that string to the newUsers collection of string
newUsers(i) = newUser
Next


' Check if a User belonged to a Role

If (User.IsInRole(newUsers.ToString)) Then
Msg.Text = " User already has a Role "
Exit Sub
Else
' Add users to the selected role
Roles.AddUsersToRole(newUsers, RolesListBox.SelectedItem.Value)

End If

usersInRole = Roles.GetUsersInRole(RolesListBox.SelectedItem.Value)
UsersInRoleGrid.DataSource = usersInRole
UsersInRoleGrid.DataBind()
End Sub
End Class


Thanks a lot for any suggestion.


0
Hyper
3/22/2007 1:01:53 PM
asp.net.security 27051 articles. 1 followers. Follow

2 Replies
480 Views

Similar Articles

[PageSpeed] 42

Hi Hyper Blade,

There is a problem in this line If (User.IsInRole(newUsers.ToString)) Then

The User.IsInRole method check whether the current user is in a role or not. The parameter of this method must be a role name. (newUsers.ToString is not a role name, it returns System.String[])

 

Hope this helps

 


www.stockbiz.vn
The Vietnamese Stock Market and Economy
0
spvlong
3/22/2007 2:22:31 PM
Hi, spvlong

Thanks a lot for your reply. It stopped giving error but I just couldn't fix the problem. When I clicked Add User to Role button to assign a new created user to an Instructor Role Msg Label appeared " User already has a Role ", and when I tried to sign in as that new user, I got the Admin role instead of Instructor Role. Would you mind modifying my code below to validate if the User is alreay in Role so that I can't assign a Role to them anymore.

Protected Sub AddUsers_OnClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddUsersToRole.Click


' A role must be selected


If RolesListBox.SelectedItem Is Nothing Then
Msg.Text = "Please select a role."
Exit Sub
End If


' At least one user must be selected

If UsersListBox.SelectedItem Is Nothing Then
Msg.Text = "Please select one or more users."
Exit Sub
End If

Dim SelectedRole As String = RolesListBox.SelectedItem.ToString

' Create list of users to be added to the selected role

Dim sizeOfArray As Integer = UsersListBox.GetSelectedIndices.Length
Dim newUsers(sizeOfArray - 1) As String


For i As Integer = 0 To newUsers.Length - 1

' get the array of selected indices from the (multiselect) list box
Dim selectedIndices As Integer() = UsersListBox.GetSelectedIndices()

' get the selectedIndex that corresponds to the counter (i)
Dim selectedIndex As Integer = selectedIndices(i)

' get the ListItem in the UserListBox Items collection at that offset
Dim myListItem As ListItem = UsersListBox.Items(selectedIndex)

' get the string that is that ListItem's value property
Dim newUser As String = myListItem.Value

' add that string to the newUsers collection of string
newUsers(i) = newUser
Next


' Check if a User belonged to a Role

If (User.IsInRole(SelectedRole)) Then
Msg.Text = " User already has a Role "

Else
' Add users to the selected role
Roles.AddUsersToRole(newUsers, RolesListBox.SelectedItem.Value)

End If



usersInRole = Roles.GetUsersInRole(RolesListBox.SelectedItem.Value)
UsersInRoleGrid.DataSource = usersInRole
UsersInRoleGrid.DataBind()
End Sub
End Class



0
Hyper
3/22/2007 7:57:24 PM
Reply:

Similar Artilces:

Problem : Get a list of user belonged to a role or to know if a user already has a role
What code can I write to know if a user belonged to a Role already ? and How can I get a list of a  user already in an existing role ? Please have a look at my code below : Protected Sub AddUsers_OnClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddUsersToRole.Click' I wanna add some code here to check if a user already belonged to a Role' Please insert your code here. Thanks a lot. ' A role must be selected If RolesListBox.SelectedItem Is Nothing Then Msg.Text = "Please select a role." Exit Sub End If ...

Creating User Account Without Default Security Role (Registered User Role)
  My DNN version is 3.1.1. The portal is set to Private Registration. Unauthenicated users have access to the basic pages of the site. We require my company's current customers to register and be approved to have access to all other pages that contain information restricted to them (the major part of the site). As you know, authorizing a user account applys the Registered User security role by default and this is how I control access to the customer areas.  We want to create a page that will be used by Marketing to allow potential customers by login to...

Problems implementing role security (.Net 1.1)
I'm having a problem implementing role based security.  Here's my code:   Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs) ' Fires upon attempting to authenticate the use If Not HttpContext.Current.User Is DBNull.Value Then If HttpContext.Current.User.Identity.AuthenticationType = "Forms" Then Dim id As Web.Security.FormsIdentity = CType(HttpContext.Current.User.Identity, Web.Security.FormsIdentity) Dim ticket As Web.Security.FormsAuthenticationTicket = id.Ticket Dim userData As String = ticket.User...

User based Security instead of Role based (The most common unanswered problem)
Problem: To check whether the user has permission to view some personal data, i need query by the UserId.Page.User only has UserName property.Solution used in TimeTracker starterkit: Create stored procs that take UserName as parameter and always use a select statement to lookup the userid. Other Solutions: Create a custom iprincipal object and store the userid in it during login.I read posts that suggest this is an ASP.NET 1.1 method but no one suggested what is the correct design for ASP.NET 2.0. Does this require event handling on the login control? So whats the best practice f...

problem redirecting user based on user role
Hi all, I have small problem redirecting  user based on user role how can i determine if  a user belong to a specific group of users then  redirect  to specific page to allow access to user on user role i'm using membership and bulit in aspnet data base generated by  ASP.NET configuartion tool heres a  fragment of what i'm trying to fulfill thanks in advance of your helpprotected void Login1_Authenticate(object sender, AuthenticateEventArgs e) {if (Membership.ValidateUser(Login1.UserName, Login1.Password)) {FormsAuthentication.SetAuthCookie(Login1...

How do I check whether a user is in a role when the user is not yet authenticated
My problem:  Users coming through a portal are automatically authenticated as guests, using a standard password that nobody ever sees.   However they can also register as normal users, in which chase they have their individual password which they know, and the usual functions to reset their password, handle a forgotten password, and so on.So, in my register-from-portal code, after recognizing that this is a returning user we need to authenticate the user: but we don't know whether to use the standard portal password, or request an individual password.  I would like to writ...

Problem with FreeTextBox on a Module with similar functionality to Editing Users and User Roles
  Hi,   I'm trying to design a module and I'm getting an error message when I open the page.  The error message is:-   Error: A Runtime error has occured. Do you wish to debug? Line: 39 Error: Expected ';'   The issue I have is:-   I have a normal module page that is displaying a list of clients.   I can then edit the clients details by moving to the edit page.   On the edit page, I can further edit some details of the client.  At the bottom of the page, I have an edit button, and it runs this code:-   Response.Redirect(Navig...

Membership and Role Management
Hello, I've configured SQL server 2005 as my back-end data store via aspnet_regsql.exe. I presume it was succesvol. Creating users en roles programmatically is no problem. When I start the Web Site Administration Tool I can see the created users and roles. But when I want to show them by code I get an empty result. ... ... Roles.GetAllRoles()...... membership.GetAllUsers() The roleManager is enabled in web.config.<roleManager defaultProvider="SqlProvider" enabled="true" cacheRolesInCookie="true" cookieName=".ASPROLES" cookieTimeout="30" cookiePath="/" cookieRequireSS...

Problem Adding users to Selected Role
Hey all, Below is my aspx.vb code and I am stumped as to why when I enter a user name then select a role the user is added to a role, but not the one I select in my dropdown. The user is always added to the first role in the list in the dropdown not the role I selected. As well the RemoveUserFromRole doesn't work, I have to go into my DB and remove them manually. Imports System.Web.Security Partial Class AddRemoveUserRoles Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load DataBind() End Sub Pub...

User Roles Problem
I have created an admin role allowing only the admin to be redirected to the admin page. It has worked out perfectly last week but no such luck today! I created an access rule that denies access to all users and another access rule to allow the admin to access the admin folder. Neither of these seem to be working somehow. I tried deleting everything and start all over bothe with the user roles and the access rules but still no success.  Any help would be greatly appreciated as no tutorials seem to solve the problem i have.. Thanks In the code behind use Page.User.Identity.IsAu...

How to check if some user is in the role
Hi,I want to build Administration panel in which I could controll which users are in selected role. I'm writing it in ASP MVC, but it doesn't matter. First I'm checking is edited/managed role exist (if no I'm writing message): if (Roles.RoleExists(roleName)){ ViewData["Title"] = "Manage users in role: " +roleName; ViewData["roleName"] = roleName; MembershipUserCollection users = Membership.GetAllUsers(); return View(users);}  and in the view I want to show list of all users with checkbox indicating if user is in selected role. ...

Security role problem
I work for Vancouver Port Authority and we are using the portal quite extensively. I have created a portal for our Canada Place Move and I have set up a security role that will allow certain individuals the ability to add files to our site. My problem is that when I enforce this role in a particular module giving it the right to edit/modify it I get a message that says the following: "Edit Access Denied" "Either you are not logged in, or you do not have access to modify the current portal module content" I don't want to set up these individuals with full admin r...

Check if user is in role
Hello,I need to check if a user with a certain username is in a specific role.This is not the current user which is logged on.How can I do this?Thanks,Miguel UserIsInRole();CheersAlMy BlogMapStats.NETPlease click on 'Mark as Answer' if this post answered your question! Visual Basic If User.IsInRole("members") Then buttonMembersArea.Visible = True End If C# if (User.IsInRole("members"))  { buttonMembersArea.Visible = True; You might want to have a look at this: http://msdn2.microsoft.com/en-us/library/5k850zwb.aspx...

How to check user role
I'm creating a module that I want to display certain things to specific roles. How do I check the roles of the currently logged in user? Sorry if this is a newb question but really not sure how this is done. ThanksCheersmidspot Hmm - you can use PortalSecurity.IsInRole to check if the logged on user is in a specific role or array of roles.. or                 RoleController roleController = new RoleController();                 roleController.GetUserRolesByUser...

Web resources about - Check if User already belonged to a Role (Problem) - asp.net.security

David Bowie fans celebrate the Brixton star’s life by dancing in the streets
Mourners gathered near the star's birthplace in Brixton, South London for a celebration that went on through the night, singing Bowie's hits ...

Apple denied a report that it's building an app to help iPhone users switch to Android
Sorry, unhappy iPhone customers: Apple isn't going to help you switch over to Android any time soon. The Cupertino company has denied reports ...

National Herald case: Court allows plea to summon govt documents
File the process fee for sending summons to the respective departments,” the magistrate ordered.

North Korea Is Now Faking Video Footage, Apparently
For years now, we’ve seen bad North Korean Photoshops . Now, according to Reuters , experts say the hermit kingdom is faking video clips. Read ...

‘Star Wars’ Spinoff: Who Will Be The Next Han Solo?
Star Wars has successfully found its way back to stardom, and a month after its latest film, The Force Awakens , was released, people are still ...

Jury Selection to Start in Real Estate Agent Killing Trial
Lawyer expects no trouble seating jury for man charged in Arkansas real estate agent's killing

Elon Musk says Apple's electric car will 'expand the industry'
Elon Musk has always said that competition is good for the electric car industry, and that apparently holds true even when the rivalry is with ...

Tonya Couch Posts Bond; Due for Release Tuesday
NBC 5 Dallas-Fort Worth Tonya Couch Posts Bond; Due for Release Tuesday NBC 5 Dallas-Fort Worth Tonya Couch has posted bond and will likely ...

Amazon reportedly developing a 'beer can' size Echo device
Amazon.com is reportedly working on a scaled-down version of its Echo voice-controlled speaker.

Buying Powerball Tickets Online: What To Know Before Looking Online For Tickets To Wednesday’s $1.4 Billion ...
Those who want to buy Powerball tickets online will find a host of companies offering to help them out, but in the sea of websites there is a ...

Resources last updated: 1/12/2016 11:49:33 AM