Friday, 8 March 2013

How to Approve New Users With Confirmation Email Using CreateUserWizard Control in ASP.Net


How to Approve New Users With Confirmation Email Using CreateUserWizard Control in ASP.Net


Description: http://www.c-sharpcorner.com/Images/Articles/ButtonImages/download.gifDownload Files:
·         EmailConfirmation.zip

In this article I will explain how to approve new users created using CreateUserWizard with a confirmation email in ASP.NET.

Introduction

In this article first we will configure a CreateUserWizard control using SQLMembersipProvider. Then an SMTP mail setting is configured to send a confirmation email to new users registered using this CreateUserWizard control. A user is approved when he clicks the confirmation email sent to his given email address.

Step 1

Configure a database using SQLMembershipProvider to store user details.

Step 2

Add a new ASP.NET Web Application using Visual Studio. And add a new Web page "Regester.aspx". Drag a CreateUserWizard control and set its DisableCreatedUser to "true" to disable any newly created user. He will be activated by sending an activation email to his email. Write the following in the Web.config file:
  • Write connection string inside <configuration> tag
     
<connectionStrings>
      <add name="ConString" connectionString="Data source=DEEPAK\SQLSERVER2005; Initial Catalog=Employee; User ID=sa; Password=********;"/>
</connectionStrings>
I have configured an "Employee" database using the aspnet_regsql command as in Step 1 and stored its connection string in ConString.
  • Write the following inside the <system.web> tag:
     
<authentication mode="Forms"/>
<membership defaultProvider="MyMembershipProvider">
      <providers>
            <add name="MyMembershipProvider"
         type="System.Web.Security.SqlMembershipProvider"
         connectionStringName="ConString"/>
      </providers>
</membership>
Here I have configured Forms authentication using SqlMembershipProvider with the above connection string.
  • Write the following inside the <system.net> tag:
     
<connectionStrings>
      <add name="ConString" connectionString="Data source=DEEPAK\SQLSERVER2005; Initial Catalog=Employee; User ID=sa; Password=********;"/>
</connectionStrings>
Here I have set up an SMTP account for sending email. I am using my Gmail account to send a confirmation email to new users.

Step 3

Import the following namespaces in the Regester.aspx.cs code view:
using System.Net;
using System.Net.Mail;
using System.Configuration;
using System.Data.SqlClient;
Declare the following variables inside the class declaration:

string Email, ConString, ActivationUrl;
MailMessage message;
SmtpClient smtp;

Write the following code in the SendingMail event of CreateUserWizard:

protected void CreateUserWizard1_SendingMail(object sender, MailMessageEventArgs e)
{
    e.Cancel = 
true;
    message = 
new MailMessage();
    Email = CreateUserWizard1.Email;
    message.To.Add(Email.Trim());
    message.Subject = 
"Email confirmation!";
    ActivationUrl=Server.HtmlEncode(
"http://localhost:49161/ActivateUsers.aspx?UserID="+GetUserID(CreateUserWizard1.Email)+"&Email="+CreateUserWizard1.Email);
    message.Body = 
"Hi "+CreateUserWizard1.UserName+"!\n"+
                   
"Welcome to deepak-sharma.net!"+
                   
"Please <a href='"+ActivationUrl+"'>click</a> here to activate your account. \nThanks!";
    message.IsBodyHtml = 
true;
    
SmtpClient smtpClient = new SmtpClient();
    smtpClient.EnableSsl = 
true;
    smtpClient.Send(message);
}

The SendingMail event of CreateUserWizard is fired before an email is sent to the new regestered user. The e.Cancel property is set to true to override the default SendingMail event and set our own properties to send email. Then a MailMessage object is created and the To, Subject, and Body properties are set to send email to the regiesered user.

The SmtpClient object is created for enabling the SSL connection because Gmail SMTP uses SSL encryption. If this property is not set you will get a System.Net.Mail.SmtpException exception. The SmtpClient.Send method is used to send the mail which takes MailMessage as a parameter.

An actication URL is created by adding two query strings to the ActivateUsers.aspx page. The first query string is UserID which is a Guid that is inserted in the "aspnet_Membership" table as its UserID and the second query string is the user's email. This URL is sent to the user in an email. When the user clicks on this URL, he redirects to the "ActicateUsers.aspx" page. On the load event of the "ActivateUsers.aspx" page the UserID and Email is validated and its IsApproved field is set to true to activate the user if the UserID and Email matches.

The user receives an email confirmation in the following format:

Hi deepak! 
Welcome to deepak-sharma.net! Please click here to activate your account.

Write function to get the user id of a given email 

private string GetUserID(string Email)
{
    
string ConString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
    
SqlConnection con = new SqlConnection(ConString);
    
    
SqlCommand cmd=new SqlCommand("SELECT UserId FROM aspnet_Membership WHERE email=@Email", con); 
    cmd.Parameters.AddWithValue(
"@Email", Email);
    con.Open();
    
string UserID = cmd.ExecuteScalar().ToString();
    con.Close();
    
return UserID;
}
Step 4

Create a new Web page "ActivateUsers.aspx" and write following code in its load event:
string ConString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
string Email, UserID;
int i=0;

if ((Request.QueryString["UserID"] != null) & (Request.QueryString["Email"] != null))
{
    UserID = Request.QueryString["UserID"];
    Email = Request.QueryString["Email"];
    SqlConnection con = new SqlConnection(ConString);
    SqlCommand cmd = new SqlCommand("UPDATE aspnet_Membership SET IsApproved=1 WHERE UserID=@UserID AND Email=@Email", con);
    cmd.Parameters.AddWithValue("@UserID", UserID);
    cmd.Parameters.AddWithValue("@Email", Email);
    con.Open();
    i = cmd.ExecuteNonQuery();
    con.Close();
}
if (i > 0)
{
    Response.Write("Thanks for activation. You can login now!");
    Response.Write("<a href='Login.aspx'>Login</a>");
}
This page is called when the user clicks on the activation mail. When the DisableCreatedUser property of CreateUserWizard is set to true, the IsApproved field is set to 0 to disable the user. When UserID and Email of the query strings is matched in the load event of this page, the IsApproved field is set to 1 to enable the user.
 

ContactUs page with Capctcha in ASP.NET using C#

Description: http://www.c-sharpcorner.com/Images/Articles/ButtonImages/download.gifDownload Files:
·         ContactUsCaptchaDemo.zip
Using a contact form on your website is very useful as it helps your web site visitors to communicate with you in an easy and simple way. But, there are spammers and hackers who are looking for exploitable web forms. It is essential to secure your form against all 'holes' that those hackers are searching for .

If you are not validating your form fields (on the serve side) before sending the emails, then hackers can alter your email headers to send the bulk unsolicited emails.

 In this article will give tutorial how to create contact Us page with below key features

Key features:
1.      Contact Us form
2.      Validations
3.      Send Email
4.      Use of Captcha to avoid Spam
Contact Us Form

<div style="padding: 5px 0px 10px 150px">
        <div id="ContentTitle">
            <h1>
                Contact Us</h1>
        </div>
        <div id="ContentBody">
            <table cellpadding="2">
                <tr>
                    <td class="fieldname">
                        Email:
                    
</td>
                    <td>
                          <asp:TextBox runat="server" ID="txtEmail" Width="100%" />
                    </td>
                    <td>
                      <asp:RequiredFieldValidator runat="server" Display="dynamic"ID="RequiredFieldValidator1"
                            SetFocusOnError="true" ControlToValidate="txtEmail" ErrorMessage="Your Email is required">*</asp:RequiredFieldValidator>
                    </td>
                </tr>            
                <tr>
                    <td class="fieldname">
                        <asp:Label runat="server" ID="lblName" AssociatedControlID="txtName" Text="Full name:" />
                    </td>
                    <td>
                        <asp:TextBox runat="server" ID="txtName" Width="100%" />
                    </td>
                    <td>
                        <asp:RequiredFieldValidator runat="server" Display="dynamic"ID="valRequireName"
                            SetFocusOnError="true" ControlToValidate="txtName" ErrorMessage="Your name is required">*</asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <td class="fieldname">
                        <asp:Label runat="server" ID="lblBody" AssociatedControlID="txtBody"Text="Message:" />
                    </td>
                    <td>
                        <asp:TextBox runat="server" ID="txtBody" Width="100%" TextMode="MultiLine"Rows="8" />
                    </td>
                    <td>
                        <asp:RequiredFieldValidator runat="server" Display="dynamic" ID="valRequireBody"
                            SetFocusOnError="true" ControlToValidate="txtBody" ErrorMessage="The Message is required">*</asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <td colspan="3" class="fieldname" align="center">
                        <img src="CaptchaPage.aspx" alt="Catcha" /><br />
                        <p>
                            <strong>Enter the code shown above:</strong><br />
                            <asp:TextBox ID="CodeNumberTextBox" runat="server"></asp:TextBox>
                        </p>
                        <p>
                            <em class="notice">(Note: If you cannot read the numbers in the above<br>
                                image, reload the page to generate a new one.)</em>
                        </p>
                        <p>
                            <asp:Label ID="MessageLabel" runat="server" ForeColor="#CC0000"></asp:Label></p>
                    </td>
                </tr>
                <tr>
                    <td colspan="3" align="right">
                        <asp:Label runat="server" ID="lblFeedbackOK" Text="Your message has been successfully sent."
                            SkinID="FeedbackOK" Visible="false" ForeColor="#006600" Font-Bold="True" />
                        <asp:Label runat="server" ID="lblFeedbackKO" Text="Sorry, there was a problem sending your message."
                            SkinID="FeedbackKO" Visible="false" ForeColor="#CC0000" />
                        <asp:Button runat="server" ID="txtSubmit" Text="Send"
                            
onclick="txtSubmit_Click" />
                        <asp:ValidationSummary runat="server" ID="valSummary" ShowSummary="false"ShowMessageBox="true" />
                    </td>
                </tr>
            </table>
        </div>
    </div>

Validating Captcha Image and Send Email

Below example will show you how to validate captcha Image before sending an Email to avoid spam mails

            MailMessage Message = 
new MailMessage();
            Message.From = 
new MailAddress(txtEmail.Text, txtName.Text + Page.User.Identity.Name);
            Message.To.Add(
new MailAddress("contact@yourdomain.com"));
            Message.Body = txtBody.Text;
            Message.Subject = 
"Contact Us";
            Message.IsBodyHtml = 
true;
            
try
            {
                
if (this.CodeNumberTextBox.Text == this.Session["CaptchaImageText"].ToString())
                {
                    
this.MessageLabel.Text = "";
                    SmtpClient mailClient = 
new SmtpClient();
                    mailClient.Send(Message);
                    lblFeedbackOK.Visible = 
true;

                }
                
else
                {
                    
// Display an error message.
                    this.MessageLabel.Text = "ERROR: Incorrect, try again.";
                    
// Clear the input and create a new random code.
                    this.CodeNumberTextBox.Text = "";
                    lblFeedbackOK.Visible = 
false;
                    
this.Session["CaptchaImageText"] = GenerateRandomCode();
                }

            }
            
catch (Exception ex)
            {
                lblFeedbackKO.Visible = 
true;
            }

first off you must import using System.Net.Mail; namespace. Then define new SMTP email and collect all the information user entered in your webpage. Finally send all the information to recipient as an email.

     
<system.net>
    <mailSettings>
      <smtp from="yourdomain.com">
        <network host="mail.yourdomain.com" port="25" userName="xxx" password="xxx"/>
      </smtp>
    </mailSettings>
  </system.net>
 
Download the source code for more details.

CreateUserWizard Account Activation Email Verification Confirmation

This example code is for CreateUserWizard Account Activation Through Email Verification Confirmation Or Validation In Asp.NET.

I am explaining how to create new signup using createnewuserwizard with membership provider and sending link to activate account using C# or VB.

Description: CreateUserWizard Email Confirmation or verification
Read Create Log in Page Using Login Control to know how to setup membership provider.

I have created one NewUser.aspx pagefor signups. 

One EmailVerification.aspx page to open when user clicks on the link in email sent to his emailid at the time of creating account.

Newly created accounts are deactivatedby default and user won't be able to login untill he clicks on the link sent to his email id to validate, verify and activate.


First of all create a template which you want to send to users who sign up on the site. for this create a text file and write the text mentioned below and name it mail.txt. 
Hello <%UserName%>!.

You or someone with your id signed up at this site, Your new account is almost ready, but before you can login you need to confirm your email id by visitng the link below:
<%VerificationUrl%>

Once you have visited the verification URL, your account will be activated.

If you have any problems or questions, please reply to this email.

Thanks!

Open NewUser.aspx page in design view and palce a CreateUserWizard control on it.

Set DisableCreatedUser property to true to deactivate new accounts untill user activate it by clicking the link.


Set MailDefinition property as mentioned below for wizard to send cenfirmation emails.
<MailDefinition From="YourGmailID@gmail.com" 
                Subject="Confirmation mail" 
                BodyFileName="~/mail.txt">
</MailDefinition>

HTML source of NewUser.aspx will look like
<form id="form1" runat="server">
<asp:CreateUserWizard ID="CreateUserWizard1" 
                      runat="server" 
                      DisableCreatedUser="True" 
        ContinueDestinationPageUrl="~/Login.aspx" 
        onsendingmail="CreateUserWizard1_SendingMail">
<MailDefinition From="YourGmailID@gmail.com" 
                Subject="Confirmation mail" 
                BodyFileName="~/mail.txt">
</MailDefinition>
<WizardSteps>
<asp:CreateUserWizardStep runat="server" />
<asp:CompleteWizardStep runat="server" />
</WizardSteps>
</asp:CreateUserWizard>
</form>

Write code mentioned below in SendingMail event of CreateUserWizard control in code behind of page.
C# CODE
01using System.Net.Mail;
02using System.Web.Security;
03 
04protected void CreateUserWizard1_SendingMail(object sender, MailMessageEventArgs e)
05    {
06        MembershipUser newUserAccount = Membership.GetUser(CreateUserWizard1.UserName);
07        Guid newUserAccountId = (Guid)newUserAccount.ProviderUserKey;
08        string domainName = Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath;
09        string confirmationPage = "/EmailConfirmation.aspx?ID=" + newUserAccountId.ToString();
10        string url = domainName + confirmationPage;
11        e.Message.Body = e.Message.Body.Replace("<%VerificationUrl%>", url);
12        SmtpClient smtp = new SmtpClient();
13        smtp.Host = "smtp.gmail.com";
14        smtp.Port = 587;
15        smtp.UseDefaultCredentials = false;
16        smtp.Credentials = new System.Net.NetworkCredential("YourGmailUserName@gmail.com", "YourGmailPassword");
17        smtp.EnableSsl = true;
18        smtp.Send(e.Message);
19        e.Cancel = true;
20    }

VB.NET CODE
01Protected Sub CreateUserWizard1_SendingMail(sender As Object, e As MailMessageEventArgs)
02 Dim newUserAccount As MembershipUser = Membership.GetUser(CreateUserWizard1.UserName)
03 Dim newUserAccountId As Guid = DirectCast(newUserAccount.ProviderUserKey, Guid)
04 Dim domainName As String = Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath
05 Dim confirmationPage As String = "/EmailConfirmation.aspx?ID=" & newUserAccountId.ToString()
06 Dim url As String = domainName & confirmationPage
07 e.Message.Body = e.Message.Body.Replace("<%VerificationUrl%>", url)
08 Dim smtp As New SmtpClient()
09 smtp.Host = "smtp.gmail.com"
10 smtp.Port = 587
11 smtp.UseDefaultCredentials = False
12 smtp.Credentials = New System.Net.NetworkCredential("YourGmailUserName@gmail.com", "YourGmailPassword")
13 smtp.EnableSsl = True
14 smtp.Send(e.Message)
15 e.Cancel = True
16End Sub

Mail sent will look like shown below. 
Description: Createuserwizard verification email

To activate user through EmailConfirmation.aspx page Place a label control on the page and write below mentioned code in Page_Load Event.
C# CODE
01protected void Page_Load(object sender, EventArgs e)
02    {
03        Guid newUserId = new Guid(Request.QueryString["ID"]);
04        MembershipUser newUser = Membership.GetUser(newUserId);
05        if (newUser == null)
06        {
07            lblMessage.Text = "User Account not found";
08        }
09        else
10        {
11            newUser.IsApproved = true;
12            Membership.UpdateUser(newUser);
13            lblMessage.Text = "Account Approved, please <a href="\"Login.aspx\""> Login</a> to continue";
14        }
15    }

VB.NET CODE
01Protected Sub Page_Load(sender As Object, e As EventArgs)
02 Dim newUserId As New Guid(Request.QueryString("ID"))
03 Dim newUser As MembershipUser = Membership.GetUser(newUserId)
04 If newUser Is Nothing Then
05  lblMessage.Text = "User Account not found"
06 Else
07  newUser.IsApproved = True
08  Membership.UpdateUser(newUser)
09  lblMessage.Text = "Account Approved, please <a href="" login.aspx""=""> Login</a> to continue"
10 End If
11End Sub


Build and run the application.



No comments:

Post a Comment