In this article I will explain with an example, how to generate and verify
OTP in
ASP.Net using C# and VB.Net.
Database
The following Table UserOTP is used in this article.
Note: You can download the database table SQL by clicking the download link below.
Registration Page
Inside the RegisterUser event handler, the stored procedure first checks whether the username and email address already exists.
If yes then, the SendActivationEmail method is executed and user is redirected to Activation page.
C#
protected void RegisterUser(object sender, EventArgs e)
{
int userId = 0;
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Insert_User"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Username", txtUsername.Text.Trim());
cmd.Parameters.AddWithValue("@Password", txtPassword.Text.Trim());
cmd.Parameters.AddWithValue("@Email", txtEmail.Text.Trim());
cmd.Connection = con;
con.Open();
userId = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
}
}
string message = string.Empty;
switch (userId)
{
case -1:
message = "Username already exists.\\nPlease choose a different username.";
break;
case -2:
message = "Supplied email address has already been used.";
break;
default:
this.SendActivationEmail(userId);
Response.Redirect("~/CS_Activation.aspx");
break;
}
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('" + message + "');", true);
}
}
VB.Net
Protected Sub RegisterUser(sender As Object, e As EventArgs)
Dim userId As Integer = 0
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand("Insert_User")
Using sda As New SqlDataAdapter()
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("@Username", txtUsername.Text.Trim())
cmd.Parameters.AddWithValue("@Password", txtPassword.Text.Trim())
cmd.Parameters.AddWithValue("@Email", txtEmail.Text.Trim())
cmd.Connection = con
con.Open()
userId = Convert.ToInt32(cmd.ExecuteScalar())
con.Close()
End Using
End Using
Dim message As String = String.Empty
Select Case userId
Case -1
message = "Username already exists.\nPlease choose a different username."
Exit Select
Case -2
message = "Supplied email address has already been used."
Exit Select
Case Else
message = "Registration successful. Activation email has been sent."
Me.SendActivationEmail(userId)
Response.Redirect("~/VB_Activation.aspx")
Exit Select
End Select
ClientScript.RegisterStartupScript(Me.GetType(), "alert", "alert('" & message & "');", True)
End Using
End Sub
Mail Server Settings in Web.Config file
The following Mail Server settings need to be saved in the
Web.Config file.
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="sender@gmail.com">
<network
host="smtp.gmail.com"
port="587"
enableSsl="true"
userName="sender@gmail.com"
password="SenderGmailPassword"
defaultCredentials="true"/>
</smtp>
</mailSettings>
</system.net>
MailMessage Class Properties
Following are the required properties of the MailMessage class.
From – Sender’s email address.
To – Recipient(s) Email Address.
CC – Carbon Copies. (If any)
BCC – Blind Carbon Copies. (If any)
Subject – Subject of the Email.
Body – Body of the Email.
IsBodyHtml – Specify whether body contains text or
HTML mark up.
Attachments – Attachments. (If any)
ReplyTo – ReplyTo Email address.
SMTP Class Properties
Following are the properties of the SMTP class.
Host – SMTP Server URL. (Gmail: smtp.gmail.com)
EnableSsl – Specify whether your host accepts SSL Connections. (Gmail: True)
UseDefaultCredentials – Set to True in order to allow authentication based on the Credentials of the Account used to send emails.
Credentials – Valid login credentials for the SMTP server. (Gmail: email address and password)
Port – Port Number of the SMTP server. (Gmail: 587)
SendActivationEmail Method
Inside the
SendActivationEmail method, a random
OTP is generated using
GenerateOTP method and it is inserted in the
UserOTP table.
Then, an email is sent to the user’s email address with the
OTP.
C#
private void SendActivationEmail(int userId)
{
string activationCode = this.GenerateOTP();
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO UserOTP VALUES(@UserId, @ActivationCode)"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Parameters.AddWithValue("@UserId", userId);
cmd.Parameters.AddWithValue("@ActivationCode", activationCode);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
SmtpSection smtpSection = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
using (MailMessage mm = new MailMessage(smtpSection.From, "admin@aspsnippets.com"))
{
string body = "Hello " + txtUsername.Text.Trim() + ",";
body += "<br /><br />Following is your OTP.";
body += "<br /><b>" + activationCode + "</b>";
body += "<br /><br />Thanks";
mm.Subject = "Account Activation";
mm.Body = body;
mm.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = smtpSection.Network.Host;
smtp.EnableSsl = smtpSection.Network.EnableSsl;
NetworkCredential networkCred = new NetworkCredential(smtpSection.Network.UserName, smtpSection.Network.Password);
smtp.UseDefaultCredentials = smtpSection.Network.DefaultCredentials;
smtp.Credentials = networkCred;
smtp.Port = smtpSection.Network.Port;
smtp.Send(mm);
}
}
protected string GenerateOTP()
{
string characters = "1234567890";
string otp = string.Empty;
for (int i = 0; i < 5; i++)
{
string character = string.Empty;
do
{
int index = new Random().Next(0,characters.Length);
character = characters.ToCharArray()[index].ToString();
} while (otp.IndexOf(character) != -1);
otp += character;
}
return otp;
}
VB.Net
Private Sub SendActivationEmail(userId As Integer)
Dim activationCode As String = Me.GenerateOTP()
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand("INSERT INTO UserActivation VALUES(@UserId, @ActivationCode)")
Using sda As New SqlDataAdapter()
cmd.Parameters.AddWithValue("@UserId", userId)
cmd.Parameters.AddWithValue("@ActivationCode", activationCode)
cmd.Connection = con
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
End Using
Dim smtpSection As SmtpSection = CType(ConfigurationManager.GetSection("system.net/mailSettings/smtp"), SmtpSection)
Using mm As MailMessage = New MailMessage(smtpSection.From, "admin@aspsnippets.com")
Dim body As String = "Hello " & txtUsername.Text.Trim() & ","
body += "<br /><br />Following is your OTP."
body += "<br /><b>" & activationCode & "</b>"
body += "<br /><br />Thanks"
mm.Subject = "Account Activation"
mm.Body = body
mm.IsBodyHtml = True
Dim smtp As SmtpClient = New SmtpClient()
smtp.Host = smtpSection.Network.Host
smtp.EnableSsl = smtpSection.Network.EnableSsl
Dim networkCred As NetworkCredential = New NetworkCredential(smtpSection.Network.UserName, smtpSection.Network.Password)
smtp.UseDefaultCredentials = smtpSection.Network.DefaultCredentials
smtp.Credentials = networkCred
smtp.Port = smtpSection.Network.Port
smtp.Send(mm)
End Using
End Sub
Protected Function GenerateOTP() As String
Dim characters As String = "1234567890"
Dim otp As String = String.Empty
For i As Integer = 0 To 4
Dim character As String = String.Empty
Do
Dim index As Integer = New Random().Next(0, characters.Length)
character = characters.ToCharArray()(index).ToString()
Loop While otp.IndexOf(character) <> -1
otp += character
Next
Return otp
End Function
Activation Page
HTML Markup
The
HTML markup consists of:
TextBox – For entering
OTP.
Button – For activating the User Account.
Label – For displaying the Activation status message.
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>OTP</td>
<td><asp:TextBox ID="txtOTP" runat="server" /></td>
</tr>
<tr>
<td></td>
<td><asp:Button Text="Submit" runat="server" OnClick="OnVerify" /></td>
</tr>
</table>
<hr />
<h3> <asp:Label ID="lblMessage" runat="server" /></h3>
Namespaces
You will need to import the following namespaces.
C#
using System.Data.SqlClient;
using System.Configuration;
using System.Drawing;
VB.Net
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Drawing
Validating the OTP and activating the User Account
Inside the
Button click event handler, the entered
OTP received in the
Email is validated on the
UserOTP table.
Finally, if the
OTP is valid, the record is deleted from
UserOTP table user will be displayed an Activation success message, else Invalid message is displayed in the
Label control.
C#
protected void OnVerify(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("DELETE FROM UserOTP WHERE ActivationCode = @ActivationCode"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Parameters.AddWithValue("@ActivationCode", txtOTP.Text.Trim());
cmd.Connection = con;
con.Open();
int rowsAffected = cmd.ExecuteNonQuery();
con.Close();
if (rowsAffected == 1)
{
lblMessage.Text = "Activation successful.";
lblMessage.ForeColor = Color.Green;
}
else
{
lblMessage.Text = "Invalid OTP.";
lblMessage.ForeColor = Color.Red;
}
}
}
}
}
VB.Net
Protected Sub OnVerify(sender As Object, e As EventArgs)
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand("DELETE FROM UserOTP WHERE ActivationCode = @ActivationCode")
Using sda As SqlDataAdapter = New SqlDataAdapter()
cmd.Parameters.AddWithValue("@ActivationCode", txtOTP.Text.Trim())
cmd.Connection = con
con.Open()
Dim rowsAffected As Integer = cmd.ExecuteNonQuery()
con.Close()
If rowsAffected = 1 Then
lblMessage.Text = "Activation successful."
lblMessage.ForeColor = Color.Green
Else
lblMessage.Text = "Invalid OTP."
lblMessage.ForeColor = Color.Red
End If
End Using
End Using
End Using
End Sub
Screenshots
Inserted record in the UserOTP table
Activation email sent to the user
Message displayed when Activation is successful
Downloads