Introduction:
In this article I will explain how to create users programmatically using asp.net membership concept.
Description:
In previous post I explained clearly how to install asp.net membership database schema in SQL Server and create users using CreateUserWizard . In this post I will explain how to create users programmatically using asp.net membership concept.
In this article I will explain how to create users programmatically using asp.net membership concept.
Description:
In previous post I explained clearly how to install asp.net membership database schema in SQL Server and create users using CreateUserWizard . In this post I will explain how to create users programmatically using asp.net membership concept.
To create new user account programmatically with asp.net membership concept we need to use CreateUser method for that first design your aspx page like this
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Programmatically Create Users in asp.net Membership</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td></td>
<td colspan="2"><b>Sign Up for New User Account</b></td>
</tr>
<tr>
<td>UserName:</td>
<td><asp:TextBox ID="txtUserName" runat="server"/></td>
<td><asp:RequiredFieldValidator ID="rqfUserName" runat="server" ControlToValidate="txtUserName" Display="Dynamic" ErrorMessage="Required" ForeColor="Red"/></td>
</tr>
<tr>
<td>Password:</td>
<td><asp:TextBox ID="txtPwd" runat="server" TextMode="Password"/></td>
<td><asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtPwd" Display="Dynamic" ErrorMessage="Required" ForeColor="Red"/></td>
</tr>
<tr>
<td>Confirm Password:</td>
<td><asp:TextBox ID="txtCnfPwd" runat="server" TextMode="Password"/></td>
<td><asp:RequiredFieldValidator id="PasswordConfirmRequiredValidator" runat="server" ControlToValidate="txtCnfPwd" ForeColor="red" Display="Dynamic" ErrorMessage="Required" />
<asp:CompareValidator id="PasswordConfirmCompareValidator" runat="server" ControlToValidate="txtCnfPwd" ForeColor="red" Display="Dynamic" ControlToCompare="txtPwd" ErrorMessage="Confirm password must match password." /></td>
</tr>
<tr>
<td>Email:</td>
<td><asp:TextBox ID="txtEmail" runat="server"/></td>
<td><asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="txtEmail" Display="Static" ErrorMessage="Required" ForeColor="Red"/></td>
</tr>
<tr>
<td>Security Question:</td>
<td><asp:TextBox ID="txtQuestion" runat="server"/></td>
<td><asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="txtQuestion" Display="Static" ErrorMessage="Required" ForeColor="Red"/></td>
</tr>
<tr>
<td>Security Answer:</td>
<td><asp:TextBox ID="txtAnswer" runat="server"/></td>
<td><asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ControlToValidate="txtAnswer" Display="Static" ErrorMessage="Required" ForeColor="Red"/></td>
</tr>
<tr>
<td></td>
<td><asp:Button ID="btnSubmit" runat="server" Text="Create User" onclick="btnSubmit_Click" /></td>
</tr>
<tr>
<td colspan="3"><asp:Label ID="lblResult" runat="server" Font-Bold="true"/></td>
</tr>
</table>
</div>
</form>
</body>
</html>
|
After that in code behind add the following namespaces
C# Code
using System;
using System.Drawing;
using System.Web.Security;
|
Now write the following code in code behind
protected void btnSubmit_Click(object sender, EventArgs e)
{
MembershipCreateStatus createStatus;
MembershipUser user = Membership.CreateUser(txtUserName.Text,txtPwd.Text,txtEmail.Text,txtQuestion.Text,txtAnswer.Text,true,out createStatus);
switch (createStatus)
{
//This Case Occured whenver User Created Successfully in database
case MembershipCreateStatus.Success:
lblResult.ForeColor = Color.Green;
lblResult.Text = "The user account was successfully created";
txtUserName.Text = string.Empty;
txtEmail.Text = string.Empty;
txtQuestion.Text = string.Empty;
txtAnswer.Text = string.Empty;
break;
// This Case Occured whenver we send duplicate UserName
case MembershipCreateStatus.DuplicateUserName:
lblResult.ForeColor = Color.Red;
lblResult.Text = "The user with the same UserName already exists!";
break;
//This Case Occured whenver we give duplicate mail id
case MembershipCreateStatus.DuplicateEmail:
lblResult.ForeColor = Color.Red;
lblResult.Text = "The user with the same email address already exists!";
break;
//This Case Occured whenver we send invalid mail format
case MembershipCreateStatus.InvalidEmail:
lblResult.ForeColor = Color.Red;
lblResult.Text = "The email address you provided is invalid.";
break;
//This Case Occured whenver we send empty data or Invalid Data
case MembershipCreateStatus.InvalidAnswer:
lblResult.ForeColor = Color.Red;
lblResult.Text = "The security answer was invalid.";
break;
// This Case Occured whenver we supplied weak password
case MembershipCreateStatus.InvalidPassword:
lblResult.ForeColor = Color.Red;
lblResult.Text = "The password you provided is invalid. It must be 7 characters long and have at least 1 special character.";
break;
default:
lblResult.ForeColor = Color.Red;
lblResult.Text = "There was an unknown error; the user account was NOT created.";
break;
}
}
|
VB.NET Code
Imports System.Drawing
Partial Class Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim createStatus As MembershipCreateStatus
Dim user As MembershipUser = Membership.CreateUser(txtUserName.Text, txtPwd.Text, txtEmail.Text, txtQuestion.Text, txtAnswer.Text, True, _
createStatus)
Select Case createStatus
'This Case Occured whenver User Created Successfully in database
Case MembershipCreateStatus.Success
lblResult.ForeColor = Color.Green
lblResult.Text = "The user account was successfully created"
txtUserName.Text = String.Empty
txtEmail.Text = String.Empty
txtQuestion.Text = String.Empty
txtAnswer.Text = String.Empty
Exit Select
' This Case Occured whenver we send duplicate UserName
Case MembershipCreateStatus.DuplicateUserName
lblResult.ForeColor = Color.Red
lblResult.Text = "The user with the same UserName already exists!"
Exit Select
'This Case Occured whenver we give duplicate mail id
Case MembershipCreateStatus.DuplicateEmail
lblResult.ForeColor = Color.Red
lblResult.Text = "The user with the same email address already exists!"
Exit Select
'This Case Occured whenver we send invalid mail format
Case MembershipCreateStatus.InvalidEmail
lblResult.ForeColor = Color.Red
lblResult.Text = "The email address you provided is invalid."
Exit Select
'This Case Occured whenver we send empty data or Invalid Data
Case MembershipCreateStatus.InvalidAnswer
lblResult.ForeColor = Color.Red
lblResult.Text = "The security answer was invalid."
Exit Select
' This Case Occured whenver we supplied weak password
Case MembershipCreateStatus.InvalidPassword
lblResult.ForeColor = Color.Red
lblResult.Text = "The password you provided is invalid. It must be 7 characters long and have at least 1 special character."
Exit Select
Case Else
lblResult.ForeColor = Color.Red
lblResult.Text = "There was an unknown error; the user account was NOT created."
Exit Select
End Select
End Sub
End Class
|
Here don’t forgot to set database connection settings in web.config file
First set the connectionstring like this
<connectionStrings>
<add name="dbconnection" connectionString="Data Source=SureshDasari;Initial Catalog=AspMembership;Integrated Security=true" providerName="System.Data.SqlClient"/>
</connectionStrings>
|
After that write the following code in system.web section
<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="dbconnection" applicationName="SampleApplication"/>
</providers>
</membership>
<profile>
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="dbconnection" applicationName="SampleApplication"/>
</providers>
</profile>
<roleManager enabled="false">
<providers>
<clear/>
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="dbconnection" applicationName="SampleApplication"/>
</providers>
</roleManager>
|
After that run your application and create users using our own registration form
Demo
|
In above demo if you observe we are passing parameters like Username, password, Email, security question and security answer.
If we don’t want security question and answer options and we need to allow users to enter his own password without any restrictions for that we need to configure some properties in web.config file like requiresQuestionAndAnswer="false", minRequiredPasswordLength="6" and minRequiredNonalphanumericCharacters="0" to set those properties check this post solve password length problem.
If we remove Security Question and answer options then we need to use different CreateUser method that contains different types of overloaded methods those are
If you enjoyed this post, please support the blog below. It's FREE! Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email. |
|||
|
|||
12 comments :
thnaks dude it has help me lot
Is there any way to accept mobile numbers during registration?
i need this sample project.ple send this email id watmurgan@gmail.com
hey can we add more fields in createuserwizard control and add in database???please help me
Thank you Suresh. For such a nice article.
I read your first article - [Create asp.net membership database schema in SQL Server | Create User using CreateUserWizard control in asp.net]
Its quite helpful. Now I request you can you please explain how can we add additional fields like Address or Contact no information in create user wizard? I have gone through some article on msdn about customizing the MembershipUser class.
[ http://msdn.microsoft.com/en-us/library/ms366730.aspx#CreateDataSourceAnchor ]
and
[http://msdn.microsoft.com/en-us/library/ms178342.aspx]
but I liked the way you describe. I think you can make it easy.Please help.
Thanks in advance.
m getting this error....
Object reference not set to an instance of an object.
this is my code..please help
protected void regButton_Click(object sender, EventArgs e)
{
try
{
MembershipCreateStatus status;
MembershipUser newUser = Membership.CreateUser(txtUserName.Text.Trim(), txtPassword.Text.Trim(), txtEmail.Text, txtQuestion.Text.Trim(), txtAnswer.Text.Trim(),true, out status);
status = MembershipCreateStatus.Success;
if (status == MembershipCreateStatus.Success)
{
MembershipUser currentUser = Membership.GetUser();
Guid currentUserId = (Guid)currentUser.ProviderUserKey;
ApplicationAccess.InsertProfile(currentUserId, txtFirstName.Text.Trim(), txtMiddleName.Text.Trim(), txtLastName.Text.Trim(), txtVoterID.Text.Trim(), AreaList.SelectedValue.Trim(), GenderList.SelectedValue.Trim(), txtMobile.Text.Trim(), txtLandline.Text.Trim(), Convert.ToDateTime(txtDob.Text), txtAddress.Text.Trim());
ErrorMessage.Text = "User Created Sucessfully";
Response.Redirect("default.aspx");
}
else
{
switch (status)
{
case MembershipCreateStatus.DuplicateUserName:
ErrorMessage.Text = "user name is already exist!";
break;
case MembershipCreateStatus.DuplicateEmail:
ErrorMessage.Text = "Email is already registered with us! please try another";
break;
case MembershipCreateStatus.InvalidEmail:
ErrorMessage.Text = "Please enter valid email address";
break;
case MembershipCreateStatus.UserRejected:
ErrorMessage.Text = "try creating different user name, as it is rejected!";
break;
case MembershipCreateStatus.ProviderError:
ErrorMessage.Text = "Error occured during user creation";
break;
case MembershipCreateStatus.InvalidPassword:
ErrorMessage.Text = "please enter minimum 8 digit password contains atleast one special character";
break;
case MembershipCreateStatus.InvalidUserName:
ErrorMessage.Text = "Please enter valid user name";
break;
}
}
}
catch (Exception ex)
{
ErrorMessage.Text = ex.Message;
MembershipUser user = Membership.GetUser(txtUserName.Text);
if (user != null)
{
Membership.DeleteUser(txtUserName.Text);
}
}
}
Could not find stored procedure 'dbo.aspnet_CheckSchemaVersion'. sir I'm workin in MNC I couldnt use the aspnet_regsql.exe so pls tel me the code for writing the checkSchemaVersion stored procedure code
WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive).
showing this erroe ,pls help me
Can i add new label and text box and save it to database in aspnet_Membership table
Hi Suresh
Can we implement ASP.NET membership with SHA256.
We are doing development for security auditing . Auditing company requires hased password(SHA256) using javascript at client side. We have save password in SHA256 format but not able to access the same password using login form.
One more thing , initially we were using the ASP.NET membership. But we were unable to find the password format whether it is in SHA256 format or in other format. That's why we have stored password in new tables other than Membership table.
Hi,
Getting time out error in membership.CreateUser(username,password) when creating mutiple user same time
Note: Only a member of this blog may post a comment.