Introduction:
In this article, we discussed in-depth how to send user confirmation or account activation links after registration in ASP.NET using C# programming. After confirmation mail is received by the user, click on that link to activate the user account. We will see all this programmatically.
Creating Registration Table:
For demonstration purposes, I created a database table i.e registration table which is used to store user registration details.
CREATE TABLE [dbo].[Registration](
[username] [nvarchar](50) NULL,
[password] [nvarchar](50) NULL,
[emailid] [nvarchar](50) NULL,
[activation_code] [uniqueidentifier] NULL,
[account_status] [nvarchar](15) NULL
) ON [PRIMARY]
GO
HTML Markup for Registration Page:
The registration page is designed according to the below image.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Registration.aspx.cs" Inherits="Registration" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="StyleSheet.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form id="form1" runat="server">
<div>
<table class="table">
<tr>
<th class="table_th" colspan="2">Registration</th>
</tr>
<tr>
<td colspan="2"></td>
</tr>
<tr>
<td style="width:200px; text-align:center;">Username :</td>
<td><asp:TextBox ID="txtusername" runat="server" CssClass="txtbox"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
ControlToValidate="txtusername" >enter username</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td style="width:200px; text-align:center;">Password :</td>
<td><asp:TextBox ID="txtpassword" runat="server" CssClass="txtbox" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="txtpassword">enter password</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td style="width:200px; text-align:center;">Email ID :</td>
<td><asp:TextBox ID="txtemailid" runat="server" CssClass="txtbox"></asp:TextBox><asp:RegularExpressionValidator
ID="RegularExpressionValidator1" runat="server"
ControlToValidate="txtemailid"
ValidationExpression="\w+undefined[-+.']\w+)*@\w+undefined[-.]\w+)*\.\w+undefined[-.]\w+)*">please enter valid email addressundefinedabc@xyz.com)</asp:RegularExpressionValidator></td>
</tr>
<tr>
<td colspan="2" align="center">
<asp:Button ID="Btn_Register" runat="server" Text="Register"
onclick="Btn_Register_Click"/>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
In the Registration.aspx page I designed as per requirement which is shown in the above image. I also used validation control to perform validation on controls i.e the fields need to check correct format data otherwise it will show an error message.
I have used two validation controls in this task to perform validation i.e RequiredFieldValidator and RegularExpressionValidator.
RequiredFieldValidator is used to validate that the textbox does not allow null or empty it should contain some value.
RegularExpressionValidator is used to check whether the data is in the correct email format or not, this control will check data with validation expression pattern.
Adding Namespace
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Security.Cryptography;
using System.Text;
using System.Net.Mail;
Establishing SQL Connection
If we need to perform any operation on a database we need to open a connection with that database, below code does this work.
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RCCon"].ToString());
C# Coding
Today, we performed three tasks.
public partial class Registration : System.Web.UI.Page
{
--add database connection here
SqlCommand cmd;
private string Encrypt_Password(string password)
{
// logic
}
// Send Email to user email address
public void Send_Account_Activation_Link(string emailaddress, string act_code)
{
// logic
}
protected void Btn_Register_Click(object sender, EventArgs e)
{
// logic
}
}
For encrypting the user's password, I defined a private method with a string return type called Encrypt_Password. This method accepts the string parameter and returns the encrypted password as a string.
private string Encrypt_Password(string password)
{
string pwdstring = string.Empty;
byte[] pwd_encode = new byte[password.Length];
pwd_encode = Encoding.UTF8.GetBytes(password);
pwdstring = Convert.ToBase64String(pwd_encode);
return pwdstring;
}
Sending an activation link through the mail: for this, I also defined a private method with two arguments (email address and activation code), which constructs the mail body as a string type and sends that message to our email address.
public void Send_Account_Activation_Link(string emailaddress, string act_code)
{
MailMessage mm = new MailMessage("Your EMail ID", emailaddress);
mm.Subject = "Account Activation";
string body = "Hello " + txtusername.Text + ",";
body += "<br/><br/>Please click the following link to activate your account<br/>";
body += "<br/><br/><a style='background:#000000; color:#fafafa; padding:10px 100px 10px 100px; width:350px; text-decoration:none; font-weight:bold; font-size:20px;' href = '"+ Request.Url.AbsoluteUri.Replaceundefined"Registration.aspx", "Account_Activation.aspx?ActivationCode=" + act_code) + "'>Click here to activate your account.</a>";
body += "<br /><br />Thanks";
mm.Body = body;
mm.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.Credentials = new System.Net.NetworkCredential("Your Email ID", "<your email password>");
smtp.EnableSsl = true;
smtp.Send(mm);
}
When the Registration Button Click event executes first, it is used to get the activation code and convert the string password into an encrypted password by simply calling the encrypt_password method. Next, it stores the user's information in the database successfully. It will call the Send_Account_Activation_Link method and pass an email address and activation code as arguments to that method. After that, it will redirect to the Account_Activation.aspx page.
protected void Btn_Register_Click(object sender, EventArgs e)
{
string activationCode = Guid.NewGuid().ToString();
string encry_password = Encrypt_Password(txtpassword.Text);
cmd = new SqlCommand("insert into Registration values('" + txtusername.Text.ToLower() + "','" + encry_password + "','" + txtemailid.Text + "','" + activationCode + "','inactive')");
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
Send_Account_Activation_Link(txtemailid.Text, activationCode);
con.Close();
Session["user"] = txtusername.Text;
Response.Redirect("Account_Activation.aspx");
}
HTML Markup: Login Page
Create a login page for users to access their accounts.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="login.aspx.cs" Inherits="login" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<link href="StyleSheet.css" rel="stylesheet" type="text/css" />
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table class="table">
<tr>
<th colspan="2" class="table_th">Login Page</th>
</tr>
<tr >
<td>Username :</td>
<td><asp:TextBox ID="txtusername" runat='server' CssClass="txtbox"></asp:TextBox></td>
</tr>
<tr>
<td >Password :</td>
<td><asp:TextBox id="txtpassword" runat="server" CssClass="txtbox" TextMode="Password"></asp:TextBox></td>
</tr>
<tr>
<td colspan="2" align="center">
<asp:Button ID="Btn_Login" runat="server" onclick="Btn_Login_Click" Text="Login" />
</td>
</tr>
<tr>
<td colspan="2">
Create a New Account : <a href="Registration.aspx">SignUp</a>
</td>
</tr>
<tr>
<td colspan="2" align="left">
<label id="lblerror" runat="server"></label>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
C# Coding:
Implement the logic to validate user credentials during login.
Adding Namespace
---
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.Text;
using System.IO;
In the c# login operation we are performing 2 tasks, i.e Decrypt_Passoword and Btn_Login, Let's see in-depth logic performance further.
public partial class login : System.Web.UI.Page
{
-- sql connection logic here
protected void Btn_Login_Click(object sender, EventArgs e)
{
// logic
}
private string Decrypt_Password(string encryptpassword)
{
// logic
}
}
Password Decrypted C#
Decrypt_Password method and return type of this method is string, because this method is used to convert encrypted data back to the string.
private string Decrypt_Password(string encryptpassword)
{
string pwdstring = string.Empty;
UTF8Encoding encode_pwd = new UTF8Encoding();
Decoder Decode = encode_pwd.GetDecoder();
byte[] todecode_byte = Convert.FromBase64String(encryptpassword);
int charCount = Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
char[] decoded_char = new char[charCount];
Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
pwdstring = new String(decoded_char);
return pwdstring;
}
The Btn_Login_Click is used to fetch complete user records based on username and bind that data into the dataset. Now, that dataset contains all user records along with an encrypted user password. In this method, we used a loop condition to iterate each column one by one and check those column data with our username and password. If the condition is true, then it will navigate to the Default.aspx page; otherwise, it will give an error, i.e., an invalid username and password.
protected void Btn_Login_Click(object sender, EventArgs e)
{
SqlDataAdapter da = new SqlDataAdapter("select * from Registration where username="+txtusername.Text, con);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
string userid = ds.Tables[0].Rows[i]["username"].ToString();
string pwd = Decrypt_Password(ds.Tables[0].Rows[i]["password"].ToString());
string status = "active";
if (status == ds.Tables[0].Rows[i]["account_status"].ToString())
{
if (userid == txtusername.Text.ToLower() && pwd == txtpassword.Text)
{
Response.Redirect("Default.aspx?Username=" + txtusername.Text);
}
}
lblerror.InnerText = "Invalid Username and Password";
}
}
}
Acknowledgement for Activation Link Sent
The acknowledgement simply indicates that your account was created successfully and you'll receive an email with an attached link.
Activation Link in Email Address
Below is proof that your account was created successfully, but the account was in inactive mode, so you are unable to login into the account or access the features of the application. To overcome this problem, we need to activate our account by clicking on the below activation link.
After clicking the activation link in the email, if it is activated, then it will show the message "Account Activated Message Appears," as shown in the below image.
Conclusion:
In this article, we've explained how to send a link for activating an account to users after they sign up in ASP.NET using C# programming. This method is safe and easy for users, making sure only real email addresses can register, which gives a smooth experience for your users.
Next Tutorials:
Explore more tutorials, including how to resolve SMTPException in email sending processes.
9 Comments
Does this code will also run at on that website which is hosted on webserver
ReplyDeleteyes, it will work
Deleteplease help me Im getting error as nullreferenceexception was unhandled by user code
ReplyDeletewhat should I do????
you have to give your gmail Id and password otherwise its give error
Deletestill not working :( :(
ReplyDeletedid you done any modification in code....
Deleteno..its working now...but how can I add a link for my login page in email body?
ReplyDeletehey everything is working fine but only one problem is there........after filling the login username and password it is showing invalid username and password also after filling the correct username and password...please help me...otherwise everything is working
ReplyDeleteyou have to do some setting in your gmail account, for that just check this article how to do gmail setting to send emails
ReplyDeletehttp://allittechnologies.blogspot.in/2015/04/the-smtp-server-requires-secure-connection-or-the-client-was-not-authenticated-the-server-response-was-5.5.1-authentication-required.html