WorldofASP.NET : ASP.NET Tutorial, Hosting, and Source Code
You are 1 of 81 users

WorldofASP.NET >> ASP.NET >> Unedited ASP.NET

Activate User Registration by Email in ASP.NET

How to activate registered user using System.Net.Mail.SMTPClient class

Published Date : 13 Jun 2008

Author : Hans Candra
Language : C#
Platform : .NET
 
Technology : ASP.NET,Web Forms
Views : 1659
Rating : (0 votes so far)
Email to a Friend | Print this Article | Add to Favourites | Report Error

Introduction

Many of you have gone to websites where you needed to create a 'membership' form, for future logging in, which in turn sent an email to you, with a link back to the site, which 'activated' your account/membership for that website. This tutorial will attempt to lay the groundwork for the basics of that particular scenario.

Main

First off - there needs to be a database with a table that gathers the information from the form you will design. In this case, we'll just add a few fields - UserID, UserName, Password, Email, Name and Verified, calling the table 'tblUsers'.

Next, we need a form to gather the data and insert it into the table. The code for that is here:

<table cellpadding="3" width="550">
    <tbody><tr>
        <td colspan="3" class="style1">
            <img src="images/businessman.png"><b>Fill in Your Details</b>
        </td>
    </tr>
    <tr>
        <td>
             
        </td>
    </tr>
    <tr align="center">
        <td class="style1">
            Your Name :
        </td>
        <td align="left">
            <asp:textbox id="txtName" runat="server"></asp:textbox>
        </td>
    </tr>
    <tr align="center">
        <td class="style1">
            User Name :
        </td>
        <td align="left">
            <asp:textbox id="txtUserName" runat="server"></asp:textbox>
        </td>
    </tr>
    <tr align="center">
        <td class="style1">
            Email Address :
        </td>
        <td align="left">
            <asp:textbox id="txtEmail" runat="server"></asp:textbox>
        </td>
    </tr>
    <tr align="center">
        <td class="style1">
            Password :
        </td>
        <td align="left">
        </td>
    </tr>
    <tr align="center">
        <td class="style1">
            Confirm Password :
        </td>
        <td align="left">
            <asp:textbox id="txtConfirmPassword" textmode="Password"
 runat="server"></asp:textbox>
            <asp:comparevalidator id="CompareValidator1" 
runat="server" controltocompare="txtPassword" controltovalidate="txtConfirmPassword" 
errormessage="Password not match">
</asp:comparevalidator>
        </td>
    </tr>
</tbody></table>



And, of course, we need the code to insert the data into the database. The first example will be for SQL Server:

    protected void btnRegister_Click(object sender, EventArgs e)
    {
        if (Users.IsEmailExists(txtEmail.Text.Trim()))
        {
            lblMsg.Text = "Email address already exists on our system<br><br>";
        }
        else if (Users.IsUserExists(txtUserName.Text.Trim()))
        {
            lblMsg.Text = "UserName already exists on our system<br><br>";
        }
        else
        {

            int iUserID = Users.RegisterUser(txtUserName.Text.Trim(), 
txtEmail.Text.Trim(),
                txtPassword.Text.Trim(), txtName.Text.Trim());
            string iUserID = iUserID.ToString();
            string sData = Resources.Resource.NewMemberEmail;
            sData = sData.Replace("[Name]", txtName.Text.Trim());
            sData = sData.Replace("[LINK]", YourURL + "/Activate.aspx?UserID=" + 
iUserID + "&amp;UN=" + txtUserName.Text.Trim());
            sData = sData.Replace("[UserName]", txtUserName.Text.Trim());
            sData = sData.Replace("[Pwd]", txtPassword.Text.Trim());
            SMTPManager.SendEmail("mail@yourmail.com", "Your Name", 
txtEmail.Text.Trim(), sData, "New Member Activation", false);
            Response.Redirect("Login.aspx");
        }
    }

Create Users Class to Connect to the Database:

public class Users
{
public static int RegisterClient(string UserName, string EmailAddress, string 
Password, string Name)
        {
            SqlConnection conn = new SqlConnection(“your Database Connection Parameter”);
            conn.Open();
            SqlCommand cmd = conn.CreateCommand();
            cmd.CommandText = "Insert into tblUsers (UserName, Email, Password, 
Name) Values (@UserName, @EmailAddress, @ Password, @Name)";
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.Add("@UserName", SqlDbType.VarChar, 50);
            cmd.Parameters["@UserName"].Value = UserName;
            cmd.Parameters.Add("@EmailAddress", SqlDbType.VarChar, 100);
            cmd.Parameters["@EmailAddress"].Value = EmailAddress;
            cmd.Parameters.Add("@Password", SqlDbType.VarChar, 50);
            cmd.Parameters["@Password"].Value = Password;
            cmd.Parameters.Add("@Name", SqlDbType.VarChar, 100);
            cmd.Parameters["@Name"].Value = Name;
cmd.ExecuteNonQuery();
conn.Close();
	}
}

You will probably notice, that, in the Insert statement, there's no mention of the 'verified' field. That's because we set the default for that field, so that, whenever a new record gets inserted, it automatically fills that field with 0 value.

Next, we will need 2 things - an activation page, and an email subroutine. If you noticed in the Insert subroutine, there was a line with SMTPManager.SendEmail. That will call the email subroutine we will create next.

What we need to do is send an email to the person signing up for an account, dynamically, using his email address and his user id. The name of our activation page, for our example will be 'Activate.aspx'. In the body of the outgoing email message, we will be using this page as a url, along with addding a querystring, built from the UserID the person entered in the form.

public class SMTPManager
{
    public SMTPManager()
    {
    }
    public static void SendEmail(string FROM, string FromDisplayName, string TO, 
string BODY, string SUBJECT, bool bIsHtml)
    {
        MailMessage m = new MailMessage();
        m.From = new MailAddress(FROM, FromDisplayName);
        m.To.Add(TO);
        m.Subject = SUBJECT;
        m.Body = BODY;
        m.IsBodyHtml = bIsHtml;
        m.ReplyTo = new MailAddress(FROM);

        SmtpClient smtp = new SmtpClient("mail.yoursmtpserver.com");
        smtp.Credentials = new NetworkCredential("YourSMTPUserName", "YourSMTPPassword");
        smtp.Send(m);
    }
}





The last step in this scenario, is creating the 'Activate.aspx' page. It will be receiving/requesting a querystring, based on the UserID and UN, sent from the email subroutine in the email sub in the original page. Using that querystring, we will search the database for the UserID, and when it is found, we will Update the table (with an Update SQL statement), changing the verify field for that user to 1, from the default 0.


public partial class Activate : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string sID = Request.QueryString["UserID"].Trim();
        string sUserName = Request.QueryString["UN"].Trim().ToString();

        SqlConnection conn = new SqlConnection("Your Database Connection String");
        conn.Open();
        SqlCommand cmd = conn.CreateCommand();
        cmd.CommandText = "Select UserID from tblUser where UserName = '" + sUserName + "'";
        string sUserID = cmd.ExecuteScalar().ToString().Trim();
        conn.Close();

        if (String.Compare(sID, sUserID) == 0)
        {
            conn.Open();
            SqlCommand cmd = conn.CreateCommand();
            cmd.CommandText = "Update tblUser set Verified = 1 where UserName = '" + sUserName + "'";
            string sUserID = cmd.ExecuteNonQuery();
            conn.Close();
            Response.Redirect("Login.aspx");
        }
        else
        {
            lblMsg.Text = "Failed to activate your account. Please contact 
mail@yoursite.com<br>";
        }
    }
}

Conclusion

That actually wasn't too complicated. Just create a few little parts, in two short pages, and you have a complete registration/verification process.




            Other Related and Popular Articles :

            Simple asp2 feedback form
            A simple way to get user feedback via webpage email.
            Designing a Membership Sign-Up and Login Page in ASP.NET
            How to design user interface for registration and login in ASP.NET
            Validate Email and Domain in a Web Form
            Simple method to validate using javascript and ASP.NET validation control
            Basics of XHTML-MP
            Basics of XHTML-MP
            Implement captcha control library for ASP.NET
            a captcha control, image, image handler, and supression class for form validation

            Author Profile : Hans Candra

            Click here to view Author Profile


            How would you rate the quality of this content?
            Poor Excellent

            Comments

            Leave New Comments


            Article Content copyright by Hans Candra
            Everything else Copyright © by WorldofASP.NET 2008
             
            Announcements
            Earn Cash by writing an article or review
            For more info Click here







            Legend : - Within 3 Days - Within 6 Days - Within 9 Days

            Home | Add Resources | Sponsored Listings | Advertise with Us | SiteMap 1 | SiteMap 2 Link To Us | Contact Us
            © 2002-2008 Worldofasp.net ASP.NET Directory, Hosting and Tutorials | All rights reserved
            Our Partners : ASP.NET Web Hosting | Windows Web Hosting | FREE ASP.NET CMS | Phone Card | PHP Directory | Bangkok Hotels |Calling Card