Membership API: Adding user's role while creating user.

Hi All,

I'm trying to create a new user. I want to add the user's role while creating the user. So I need it to be somehow in some sort of a transaction. Also I require to save some extra information in a separate table. I don't seem to have any option of doing such a thing with SqlMembershipProvider. I just want to find out various ways I could do this. My code's attached below.

MembershipCreateStatus membershipCreateStatus;

MembershipUser membershipUser;

// Create user record

membershipUser = Membership.CreateUser(userName, password, email, securityQuestion, answer, false, out membershipCreateStatus);

if (membershipCreateStatus != MembershipCreateStatus.Success)


switch (membershipCreateStatus)


case MembershipCreateStatus.DuplicateEmail:

throw new RegistrationFailedException(Resources.RegistrationDuplicateEmailError);

case MembershipCreateStatus.DuplicateProviderUserKey:

throw new RegistrationFailedException(Resources.RegistrationDuplicateProviderUserKeyError);

case MembershipCreateStatus.DuplicateUserName:

throw new RegistrationFailedException(Resources.RegistrationDuplicateUserNameError);

case MembershipCreateStatus.InvalidAnswer:

throw new RegistrationFailedException(Resources.RegistrationInvalidAnswerError);

case MembershipCreateStatus.InvalidEmail:

throw new RegistrationFailedException(Resources.RegistrationInvalidEmailError);

case MembershipCreateStatus.InvalidPassword:

throw new RegistrationFailedException(Resources.RegistrationInvalidPasswordError);

case MembershipCreateStatus.InvalidProviderUserKey:

throw new RegistrationFailedException(Resources.RegistrationInvalidProviderUserKeyError);

case MembershipCreateStatus.InvalidQuestion:

throw new RegistrationFailedException(Resources.RegistrationInvalidQuestionError);

case MembershipCreateStatus.InvalidUserName:

throw new RegistrationFailedException(Resources.RegistrationInvaildUserNameError);

case MembershipCreateStatus.ProviderError:

throw new RegistrationFailedException(Resources.RegistrationProviderError);

case MembershipCreateStatus.UserRejected:

throw new RegistrationFailedException(Resources.RegistrationUserRejectedError);


throw new RegistrationFailedException(Resources.RegistrationUnknownError);





Roles.AddUserToRole(userName, role);


catch (ProviderException exception)


//TODO: Handle






6/14/2007 10:09:54 AM 27051 articles. 1 followers. Follow

4 Replies

Similar Articles

[PageSpeed] 50
Get it on Google Play
Get it on Apple App Store

You've already created the user so the only thing you need to woory about is if the new user was added to his/her role. After adding the user to the role, check to see if they were in fact added to the role. As far as extra information goes, I'd simply use the Profile Provider as long as the information was rather simple. Otherwise, I'd create my own database schema for this info. 

<profile defaultProvider="AspNetSqlProfileProvider" enabled="true">
			type="System.Web.Profile.SqlProfileProvider, System.Web, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
		<add name="FirstName" />
		<add name="LastName" />

Thanks, Ed

Microsoft MVP - ASP/ASP.NET

6/14/2007 12:32:43 PM

Thanks for your reply. But this doesn't solve my problem.  

Consider this scenario:

 - User registers with your website, you create a user, you try adding the user to a role, somehow it fails, you check role's not added, you try n delete the user, you fail again. You tell the user registration failed. The user tries again and finds out his/her beloved username's already taken. Make sense???

Now consider this:

- User registers with your website, you create a user, you add the user to a role. Now you update his FirstName in profile, and when you try n update his last name, you fail. So you try n delete the first name and role and user itself but fail again. So aren't you stuck again?

Any ideas how to get around that?

6/14/2007 1:55:22 PM

The only thing I can think of would be to create your own Custom Provider. I don't think the current provider allows for any transactional items.

Thanks, Ed

Microsoft MVP - ASP/ASP.NET

6/14/2007 1:58:30 PM

How about using System.Transactions.TransactionScope object (.net framework 3.0)? I just tried it. It seemed to have worked. Hope this helped. 

using (TransactionScope transactionScope = new TransactionScope())


UsersBC usersBC = new UsersBC();

Guid userIdentifier = usersBC.AddUser(userName, password, securityQuestion, answer, email, role);


AddressBC addressBC = new AddressBC();

AddressBE addressBE;

addressBE = addressBC.AddAddress(addressLine1, addressLine2, postcode, city, county, null);

UserDetailBC userDetailBC = new UserDetailBC();

UserDetailBE userDetailBE = new UserDetailBE();userDetailBE = userDetailBC.AddUserDetail(company, contactFirstName, contactLastName, phoneNo, addressBE.addressId, null);




6/19/2007 12:44:11 PM

Similar Artilces:

Creating a "user's page"
I would like to create a page in my intranet portal that would be for each specific user, sort of a personalized home page where they could add content and modules and order them according to their liking. I thought that I could just add a new tab for each user under the home tab and give them admin access to it, but I want it only available to them (ie. the user can only access the tab with their name on it: username = tabname). The only way I can figure out how to do this is to create a role for each user and then limit their tab to their role. However, I have too many users to crea...

how to create AD users in 'Users' section of "Active Directory Users and Computers" window.
 I can create new AD users but not in 'Users' section in "Active Directory Users and Computers" window of windows server 2003.Here is the related part of my code: System.DirectoryServices.DirectoryEntry myAD = new DirectoryEntry("LDAP://" + xxx + "/Users"); //If I put "/Users" then it throws exception, otherwise it works. But, users are not created in 'Users' folder. DirectoryEntry newUser = myAD.Children.Add("CN=" + username, "user"); newUser.Properties["d...

Cannot open user default database. Login failed. Login failed for user 'DOMAIN\User'. (.Net SqlClient Data Provider)
Hi when i try and open a database in sql server management studio i get the error "Cannot open user default database. Login failed. Login failed for user 'DOMAIN\User'. (.Net SqlClient Data Provider)", what can i do to rectify this, i have googled around and still havent found no answers. Which authentication mode is your Sql Server configured - MixedMode, Windows Authentication or Sql Server Authentication? Please refer to and    Ple...

Setting User's Initials in AD using .net
Hi All,   Is there any property which can be used to set User's Initials in Active Directory like we have "givenname" for first name and "sn" for last name?   Thanks in Advance, Anitha  ...

changes made from one user's webpart's page, effects all user's
 I am just doing this offline right now in Visual Web Developer Express 2008I created the login inonce in the memberpage area, people can modify their webpart page. I created several users to test this out.  I loaded it in a browser.When I make changes as logged in user "A" .  Then logout and login as user "B", user "B,s" webpart page has been changed to user "A".This goes true for whomever I log in as.  It changes for everyone.Is there something specific I need to do in order to get everyone's changes to be unique for them...

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...

Unable to access user control's user control's function\property from another user control
Hi, I used to call an user control's user control function as stated below from my user control in ASP.Net 1.1 wucCompany.wucEmployee.GetEmployeeSomething() After migrating to ASP.Net 2.0, I am unable to use any properties/functions(even the public ones) of the user control's User control's from another user control.  The way I have to do is create property\function in wucCompany which calls the wucEmployee's property\function and call the wucDepartment.GetEmployeeSomething().Since I need to do this change in too many places, I can...

DNN 3.0.5
Dear DNN Community, How do you locate every Security Role associated with a User Account? One would think that you can find out Role Memberships simply by viewing the particular User Account that you are interested in and having a list presented to you of all roles they participate in. Unfortunately, this appears to not be the case. From what I can tell, you can only veiew Security Role membership by clicking every Security Role group and looking. Isn't this a bit tedious for those of who have DNN sites with 100+ security roles? Why not display the Security Roles when viewing the...

How do i enable the 'Create User Wizard' to automatically select a role. (eg. USER)
Hi, Im using VWD. Im making a site  Im made a login, create acc.... but when i test it and make a account on my site, when i go to the pages ive restricted to Users only, i cant access it althouh im logged in. Is there a way to automatically enable the wizard to select my role i made on the admin site? Thanks Guys, MattyMaTTy231 Add you user to the required role within the CreateUserWizard.CreatedUser event. This will ensure that your user has been successfully created, and is the perfect place for any other type of personalization.Thanks, EdMi...

Login controls
HiI'm building a web app in visual studio 2005 and I'm setting up a 'create user' page for the admin part of the app. I'm creating a customised CreateUserWizard so that I can add a user to the membership list (in database on my server) and also add some info to one of my tables (user first name, faculty they work for etc).  I want to be able to let the admin user allocate roles (those already defined in my config) from a drop down list. I want to inculde this in my create user wizard, and have an 'update user' section where I can change their role the...

Login failed for user 'Bachelorplace'. The user is not associated with a trusted SQL Server connection. (.Net SqlClient Data Provider)
please tellme how to resolve this error, i m using server studio management tool. and trying to connect using sql server authentication. my pc is over a domain.   Login failed for user 'Bachelorplace'. The user is not associated with a trusted SQL Server connection. (.Net SqlClient Data Provider)  check whether that sql server is allowing sqlauthentication or that server -> right click it-> select  properties  -> in the window, select security -> check what is the server authentication. it should be  sqlserver and windows authentica...

Unable to cast object of type '' to type ''
I don't know if i post this in the rigth forum but it is related to database call. this is my code: public DataSet CustomerDetails_Select(Int32 ID)    {      DataSet ds = new DataSet();      WIMConnect wimcon = new WIMConnect();      WIMConnection cnnwim = new WIMConnection();      ConvertDataReaderToDataTable DrToDs = new ConvertDataReaderToDataTable();      GridViewHeadersDao gvh = new GridViewHeadersDao();       &nb...

Convert Existing User DB to Net .net MemberShip DB
Hey, Im looking to take my current Users DB and put those records into the new .net membership DB. I looked at the Membership Create User SP but im not sure if that sp is the only procedure that gets called when creating a user. I was wondering if any one else has had to do this and how should i go about it. I have about 100 users that i need to copy over. Thanks. This article has a bunch of links to Membership and security information in ASP.NET: For migrating 100 users over, you might just find it easiest to create a ...

Creating user interfaces -- newbie to .net -- HELP!!
I hope this isnt a stupid question, but I am pretty confused. I currently design/build interfaces for webapps that use coldfusion. I use html/css to build everything and then turn all this over to the programmers who make it all work. Well, we are going to be migrating over to .net/c# and I am confused as to whether or not I can continue with the same process, mainly, designing/building the sites in html/css, all interfaces, all visual pages, and then hand over to programmers to add code. I know that .net has some built in display controls, so how does that affect the interface design proces...

how to change a user's mailbox but keep the user's GW id
We have a user whose email has a space between her first name and middle name, which cause the problem in sending out email or receive email from the outside the network. Can someone advise how and where I suppose to change her email name to a valid name like from firstname Thank you very much! On Tue, 23 Oct 2007 15:27:51 +0000, April wrote: Duplicate. -- Joe Marton Novell Support Forum SysOp Novell does not officially monitor these forums! Use the Internet override - in ConsoleOne, GroupWise Tab, Inte...

Web resources about - Membership API: Adding user's role while creating user. -

Polish European Union membership referendum, 2003 - Wikipedia, the free encyclopedia
Text is available under the Creative Commons Attribution-ShareAlike License ;additional terms may apply. By using this site, you agree to the ...

Drivers of Facebook Shuttle Buses Eye Teamsters Membership
Facebook and several other tech companies in Silicon Valley provide shuttle buses to transport their employees, and according to The New York ...

NJ Membership (@NJMembership) on Twitter
Sign in Sign up To bring you Twitter, we and our partners use cookies on our and other websites. Cookies help personalize Twitter content, tailor ...

Membership Has Its Privileges
Right now, crossing one of the magical rep borders happens more or less unnoticed. People just gain the particular powers. Now, of course they ...

Membership Cards - a set on Flickr
... home Sign Up Explore Recent Photos The Commons Getty Collection Galleries World Map App Garden Camera Finder Flickr Blog Upload Sign In Membership ...

Calgary Public Library: New Look. New Library. Free Membership. - YouTube
CREATING THE WORLD’S BEST PUBLIC LIBRARY: NEW LOOK. NEW LIBRARY. FREE MEMBERSHIP. For Immediate Release: In a bold move to become the world’s ...

The benefits of private club membership in the UAE
Lifestyle membership clubs can offer cardholders exclusive leisure discounts across the Emirates. But there can be a big catch - you need to ...

New Brisbane Broncos CEO Paul White Flags Membership Drive
The coal executive taking over at the helm of the Brisbane Broncos has his eyes set on the thousands of fans who regularly turn up to home games ...

Joe Tripodi's ALP membership suspended
NSW ALP has suspended membership of Joe Tripodi amid a corruption inquiry.

Invite-only memberships expand at Canberra's sky-high lounge
... club &ndash; if they have been lucky enough to get an invite The 15th floor lounge billed as Canberra's most exclusive has quadrupled its membership ...

Resources last updated: 1/8/2016 6:55:38 PM