Question

I'm trying to send an activation email and have the user activate their account by clicking on the link provided. I have been tweaking it based on open source code I've been looking at online, however it has recently stopped sending the email without giving any errors. Here is the sign up form with the send email function:

Imports System.Data.SqlClient
Imports System.Data.Sql
Imports System.Data.SqlTypes
Imports System.Data
Imports System.Configuration
Imports System.Net.Mail
Imports System.Net
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls


Public Class WebForm1
Inherits System.Web.UI.Page

Dim boolCar As Object

Private Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
    If txtEmailAddress.Text.Trim.EndsWith("@umary.edu") Or txtPassword.Text.Trim = txtRetypePassword.Text.Trim Then
        Dim con As New SqlConnection
        Dim cmdEmail As New SqlCommand
        Dim cmdRegistration As New SqlCommand
        Dim EmailCount As Integer = 0

        Try
            con.ConnectionString = "Data Source=SERVERNAME;Initial Catalog=StudentGov;User ID=sa;Password=Password1"
            con.Open()

            cmdEmail = New SqlCommand("SELECT COUNT(UMaryEmail) As EmailCount FROM RegisteredUsers WHERE UMaryEmail='" & txtEmailAddress.Text.Trim & "'", con)
            EmailCount = cmdEmail.ExecuteScalar()

            If EmailCount = 0 Then
                ' Declare database input variables 
                Dim userId As Integer = 0
                Dim firstName As String = txtFirstName.Text
                Dim lastName As String = txtLastName.Text
                Dim hometown1 As String = txtHometown1.Text
                Dim state1 As String = txtState1.Text
                Dim zip1 As String = txtZipCode1.Text
                Dim hometown2 As String = txtHometown2.Text
                Dim state2 As String = txtState2.Text
                Dim zip2 As String = txtZipCode2.Text
                Dim phoneNum As String = txtPhoneNumber.Text
                Dim emailAddress As String = txtEmailAddress.Text
                Dim password As String = txtPassword.Text
                Dim boolCar As Boolean = False
                Dim boolUmary As Boolean = False

                If radYesNo.SelectedIndex = 0 Then
                    boolCar = True
                Else
                    boolCar = False
                End If

                ' Define the command using parameterized query 
                cmdRegistration = New SqlCommand("INSERT INTO RegisteredUsers(FirstName, LastName, Hometown1, State1, ZIP1, Hometown2, State2, ZIP2, PhoneNum, UMaryEmail, Password, Car) VALUES (@txtFirstName, @txtLastName, @txtHometown1, @txtState1, @txtZipCode1, @txtHometown2, @txtState2, @txtZipCode2, @txtPhoneNumber, @txtEmailAddress, @txtPassword, @RadYesNo)", con)

                ' Define the SQL parameter '
                cmdRegistration.Parameters.AddWithValue("@txtFirstName", txtFirstName.Text)
                cmdRegistration.Parameters.AddWithValue("@txtLastName", txtLastName.Text)
                cmdRegistration.Parameters.AddWithValue("@txtHometown1", txtHometown1.Text)
                cmdRegistration.Parameters.AddWithValue("@txtState1", txtState1.Text)
                cmdRegistration.Parameters.AddWithValue("@txtZipCode1", txtZipCode1.Text)
                cmdRegistration.Parameters.AddWithValue("@txtHometown2", txtHometown2.Text)
                cmdRegistration.Parameters.AddWithValue("@txtState2", txtState2.Text)
                cmdRegistration.Parameters.AddWithValue("@txtZipCode2", txtZipCode2.Text)
                cmdRegistration.Parameters.AddWithValue("@txtPhoneNumber", txtPhoneNumber.Text)
                cmdRegistration.Parameters.AddWithValue("@txtEmailAddress", txtEmailAddress.Text)
                cmdRegistration.Parameters.AddWithValue("@txtPassword", txtPassword.Text)
                cmdRegistration.Parameters.AddWithValue("@RadYesNo", boolCar)

                cmdRegistration.ExecuteNonQuery()
                SendActivationEmail(userId)
                Response.Redirect("RegistrationSuccess.aspx")
            Else
                ' Duplicate Email Exist Error Message
                MsgBox("Email address already supplied.")
            End If
            ' Catch ex As Exception (Not needed)
            ' Error Executing One Of The SQL Statements 
        Finally
            con.close()
        End Try
    Else
        ' Throw Error Message 
        MsgBox("Email input error")
    End If
End Sub

   Private Sub SendActivationEmail(userId As Integer)
    Dim sqlString As String = "Server=SERVERNAME;Database=StudentGov;UId=sa;Password=Password1;"
    Dim ActivationCode As String = Guid.NewGuid().ToString()
    Dim ActivationUrl As String = Server.HtmlEncode("http://localhost:63774/ActivateAccount.aspx?userId=" & FetchUserId(txtEmailAddress.ToString) & "&txtEmailAddress=" & txtEmailAddress.ToString & "&ActivationCode=" & ActivationCode.ToString)
    Using con As New SqlConnection(sqlString)
        Using sqlCmd As New SqlCommand("UPDATE RegisteredUsers SET UserId = '" + userId.ToString + "', ActivationCode = '" + ActivationCode.ToString + "' WHERE UMaryEmail='" + txtEmailAddress.Text + "';")
            Using sda As New SqlDataAdapter()
                sqlCmd.CommandType = CommandType.Text
                sqlCmd.Parameters.AddWithValue("@UserId", userId)
                sqlCmd.Parameters.AddWithValue("@ActivationCode", ActivationCode)
                sqlCmd.Connection = con
                con.Open()
                sqlCmd.ExecuteNonQuery()
                con.Close()
            End Using
        End Using
    End Using
    Using mm As New MailMessage("****@outlook.com", txtEmailAddress.Text)
        mm.Subject = "Account Activation"
        Dim body As String = "Hello " + txtFirstName.Text.Trim() + ","
        body += "<br /><br />Please click the following link to activate your account"
        body += "<br /><a href='" & ActivationUrl & "'>Click here to activate your account.</a>"
        body += "<br /><br />Thanks"
        mm.Body = body
        mm.IsBodyHtml = True
        Dim smtp As New SmtpClient()
        smtp.Host = "smtp.live.com"
        smtp.EnableSsl = True
        Dim NetworkCred As New NetworkCredential("****@outlook.com", "****")
        smtp.UseDefaultCredentials = True
        smtp.Credentials = NetworkCred
        smtp.Port = 587
        Try
            smtp.Send(mm)
        Catch ex As Exception
            MsgBox("Email was not sent")
        End Try
    End Using
End Sub

Private Function FetchUserId(emailAddress As String) As String
    Dim cmd As New SqlCommand()
    Dim con As New SqlConnection("Data Source=SERVERNAME;Initial Catalog=StudentGov;User ID=sa;Password=Password1")

    cmd = New SqlCommand("SELECT UserId FROM RegisteredUsers WHERE UMaryEmail=@txtEmailAddress", con)
    cmd.Parameters.AddWithValue("@txtEmailAddress", emailAddress)
    If con.State = ConnectionState.Closed Then
        con.Open()
    End If
    Dim userId As String = Convert.ToString(cmd.ExecuteScalar())
    con.Close()
    cmd.Dispose()
    Return userId
End Function
End Class

And here is the AccountActivation page:

Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration


Public Class ActivateAccount
Inherits System.Web.UI.Page

Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
    If Not Page.IsPostBack Then
        ActivateMyAccount()
    End If
End Sub


Private Sub ActivateMyAccount()
    Dim con As New SqlConnection()
    Dim cmd As New SqlCommand()

    Try
        con.ConnectionString = "Data Source=CISWEB\UMCISSQL2008;Initial Catalog=StudentGov;User ID=sa;Password=Password1"
        If (Not String.IsNullOrEmpty(Request.QueryString("UserId"))) And (Not String.IsNullOrEmpty(Request.QueryString("UMaryEmail"))) Then

            'approve account by setting Is_Approved to 1 i.e. True in the sql server table
            cmd = New SqlCommand("UPDATE RegisteredUsers SET AccountActivated=1 WHERE UserId=@UserId AND UMaryEmail=@txtEmailAddress", con)
            cmd.Parameters.AddWithValue("@UserId", Request.QueryString("UserId"))

            cmd.Parameters.AddWithValue("@txtEmailAddress", Request.QueryString("UMaryEmail"))
            If con.State = ConnectionState.Closed Then
                con.Open()

            End If
            cmd.ExecuteNonQuery()
            Response.Write("You account has been activated. You can <a href='SignIn.aspx'>Sign in</a> now! ")

        End If
    Catch ex As Exception
        ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('Error occured : " & ex.Message.ToString() & "');", True)
        Return
    Finally
        con.Close()
        cmd.Dispose()
    End Try
End Sub
End Class

As you may be able to tell already, I am flummoxed. With no error messages I'm receiving, I don't know why the SendActivationEmail function is no longer working. Someone help please! :(

Was it helpful?

Solution

Hi FlummoxedUser are you sure that have you checked your code as well ????

Take a look here :

 Dim ActivationUrl As String = Server.HtmlEncode("http://localhost:63774/ActivateAccount.aspx?userId=" & FetchUserId(txtEmailAddress.ToString) & "&txtEmailAddress=" & txtEmailAddress.ToString & "&ActivationCode=" & ActivationCode.ToString)

I think is better use httputility.urlEncode/Decode for this stuff where it use it to filter only the result of each function or single variable.

Second one take care at your code above

this is in your page :

  If (Not String.IsNullOrEmpty(Request.QueryString("UserId"))) And (Not String.IsNullOrEmpty(Request.QueryString("UMaryEmail"))) 

where have you found "UmaryEmail" key in your querystring parameters?????

Check it and you will solve your issue but check also in cmd and so on in activation page or you will make some issues :)

I hope it help you and if it solves your issue mark this as answer.

UPDATE :

>   Dim ActivationUrl As String = Server.HtmlEncode("http://localhost:63774/ActivateAccount.aspx?userId=" & FetchUserId(txtEmailAddress.ToString) & "&txtEmailAddress=" & txtEmailAddress.ToString & "&ActivationCode=" & ActivationCode.ToString)

with this task you create yout activation link which will be something like

http://localhost:63774/ActivateAccount.aspx?userId=1&txtEmailAddress=email@pippo&ActivationCode=123456

Now what's append when click on that link server handle request and create a collection data which include all the keys within your querystring

In effect you can use request.QueryString to check/retrieve values from each keys. So you can use as you did request.Querystring("keyname") to get the value for that particular parameter BUT in your case you check for a key which are not passed into the link. Pay attention that you have setup only 3 keys which are

UserID

txtEmailAddress

ActivationCode

there's no "UMaryEmail" key in request query string

Also another important stuff NEVER PASS IN QUERY STRING DATABASE FIELD :) use fantasy name or shortname which not reflect database field

example :

UserID => uid

ActivatioCode = token,acd,cd or anything you want

txtEmailAddress= email, em or any other name

Now activation page issue when you try to check your value use an if statement where check for userid key and UMaryEmail where userid could be matched coz it exist in query string but UmaryEmail is not into the request.querystring you have not provided it so if fails and nothing has been shown in page.

Here your Activation Sub revisited with some comments to better understand :

  Private Sub ActivateMyAccount()
    'Checking you keys in querystring

    If Request.QueryString.AllKeys.Contains("Userid") AndAlso Request.QueryString.AllKeys.Contains("txtEmailAddress") Then
        'here we assume that keys exist and so we can proceed with rest 
        If (Not String.IsNullOrEmpty(Request.QueryString("UserId"))) And (Not String.IsNullOrEmpty(Request.QueryString("txtEmailAddress"))) Then
            'no we can proceed to make other stuff 
            'Another stuff place you connection string within connection string section in webconfig in order to make a simple request like this one :

            'classic example for create a connection with web config file
            ' Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("yourconnectionstringname").ToString)
            Using con As New SqlConnection("Data Source=CISWEB\UMCISSQL2008;Initial Catalog=StudentGov;User ID=sa;Password=Password1")

                If con.State = ConnectionState.Closed Then con.Open()
                Dim sqlQuery As String = "UPDATE RegisteredUsers SET AccountActivated=1 WHERE UserId=@UserId AND UMaryEmail=@txtEmailAddress"
                Using cmd As New SqlCommand(sqlQuery, con)
                    Try
                        With cmd
                            .Parameters.AddWithValue("@UserId", Request.QueryString("UserId"))
                            .Parameters.AddWithValue("@txtEmailAddress", Request.QueryString("txtEmailAddress"))
                            .ExecuteNonQuery()
                            Response.Write("You account has been activated. You can <a href='SignIn.aspx'>Sign in</a> now! ")
                        End With
                    Catch ex As Exception
                        ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('We apologize but something is gone wrong;our techs are checking the issue.Best regards etc etc etc');", True)
                    End Try

                End Using
            End Using
        Else
            Response.Write("<h1>invalid activation links!!</h1>")
        End If
    Else
        Response.Write("<h1>invalid activation links!!</h1>")
    End If
End Sub

If your query is right it should work at first shot :) Take a try and let me know and if it solve your issue please mark it as answer

UPDATE 2:

Your actual code is :

    Dim ActivationUrl As String = Server.HtmlEncode("localhost:63774/ActivateAccount.aspx?userId=" & HttpUtility.UrlEncode(FetchUserId(txtEmailAddress.ToString)) & "&txtEmailAddress=" & HttpUtility.UrlEncode(txtEmailAddress.ToString) & "&ActivationCode=" & HttpUtility.UrlEncode(ActivationCode.ToString))

But is all wrong let me explain:

Declar your variable : Dim ActivationUrl as string it is ok Then built url so :

="http://localhost:63774/ActivateAccount.aspx?userId=" & HttpUtility.UrlEncode(FetchUserId(txtEmailAddress.text.tostring)) & "&txtEmailAddress=" & HttpUtility.UrlEncode(txtEmailAddress.text.tostring) & "&ActivationCode=" & HttpUtility.UrlEncode(ActivationCode.ToString))

Where take a look to piece of code which is your : 'HttpUtility.UrlEncode(txtEmailAddress.ToString)' in this manner you are passing a value system type object which is a textbox to pass textbox value you need to access to its .Text property like txtEmailAddress .Text

Change as per my code above and it will work (if your procedure is right)

**UPDATE CODE 3 **

Change your code with this.§be carefull don't change anything copy and paste all ActivateMyAccount Sub and delete your old one

Private Sub ActivateMyAccount()
    'Checking you keys in querystring

    If Request.QueryString.AllKeys.Contains("userId") And Request.QueryString.AllKeys.Contains("txtEmailAddress") Then
        'here we assume that keys exist and so we can proceed with rest 
        If (Not String.IsNullOrEmpty(Request.QueryString("userId"))) And (Not String.IsNullOrEmpty(Request.QueryString("txtEmailAddress"))) Then
            'no we can proceed to make other stuff 
            'Another stuff place you connection string within connection string section in webconfig in order to make a simple request like this one :

            'classic example for create a connection with web config file
            ' Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("yourconnectionstringname").ToString)
            Using con As New SqlConnection("Data Source=CISWEB\UMCISSQL2008;Initial Catalog=StudentGov;User ID=sa;Password=Password1")

                If con.State = ConnectionState.Closed Then con.Open()
                Dim sqlQuery As String = "UPDATE RegisteredUsers SET AccountActivated=1 WHERE UserId=@UserId AND UMaryEmail=@txtEmailAddress"
                Using cmd As New SqlCommand(sqlQuery, con)
                    Try
                        With cmd
                            cmd.Parameters.AddWithValue("@UserId", Request.QueryString("userId"))
                            cmd.Parameters.AddWithValue("@txtEmailAddress", Request.QueryString("txtEmailAddress"))
                            cmd.ExecuteNonQuery()
                            Response.Write("You account has been activated. You can <a href='SignIn.aspx'>Sign in</a> now! ")
                        End With
                    Catch ex As Exception
                        ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('We apologize but something is gone wrong;our techs are checking the issue.Best regards etc etc etc');", True)
                    End Try

                End Using
            End Using
        Else
            Response.Write("<h1>invalid activation links!! bad query string</h1>")
        End If
    Else
        Response.Write("<h1>invalid activation links!! bad not string</h1>")
    End If
End Sub
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top