canceling email send with asp.net custom validator - asp.net

I have a form that sends an email that includes 4 fields. One of the fields is validated by a custom validator against the database and if the value is found the email should send. If it is not found the email should cancel and there should be an error message. Everything is working except the email sends regardless of the validation. How can I keep the email from sending?
Imports System.Net.Mail
Imports System.Data.OleDb
Imports System.Data.SqlClient
Partial Class inforequest
Inherits System.Web.UI.Page
Protected Sub btnSend_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim mm As New MailMessage("sender#email.com", "receiver#email.com")
mm.Subject = txtSubject.Text
mm.Body = "Name: " & txtName.Text & "<br /><br />Email: " & txtEmail.Text & "<br />" & txtBody.Text & "<br /> Agent Code:" & AgentCode.Text
mm.IsBodyHtml = True
Dim smtp As New SmtpClient()
smtp.Host = "mailserver"
smtp.EnableSsl = False
Dim NetworkCred As New System.Net.NetworkCredential()
smtp.UseDefaultCredentials = False
NetworkCred.UserName = "username"
NetworkCred.Password = "password"
smtp.EnableSsl = False
smtp.Credentials = NetworkCred
smtp.Port = 587
smtp.Send(mm)
lblMessage.Text = "Email Sent SucessFully."
End Sub
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Dim dbconn As String
Dim qstring = Request.QueryString("ID")
Dim addressDR As System.Data.SqlClient.SqlDataReader
Dim sqlcommand As String = "SELECT * FROM listings WHERE ID=#qstring"
dbconn = ConfigurationManager.ConnectionStrings("houses").ToString
Dim connection As New System.Data.SqlClient.SqlConnection(dbconn)
connection.Open()
Dim addresscmd As New System.Data.SqlClient.SqlCommand(sqlcommand, connection)
addresscmd.Parameters.AddWithValue("#qstring", qstring)
addressDR = addresscmd.ExecuteReader()
If addressDR.HasRows Then
addressDR.Read()
Me.txtBody.Text = "I would like to request a showing of the home located at: " & addressDR("address") & " MLS#: " & addressDR("mlsnum")
addressDR.Close()
End If
connection.Close()
End Sub
Protected Sub CodeValidate_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles CodeValidate.ServerValidate
Dim AgentCode = Request.Form("AgentCode")
Dim sql As String = "SELECT agentcode FROM Codes WHERE agentcode = #AgentCode"
Using conn As New SqlConnection(ConfigurationManager.ConnectionStrings("Codes").ConnectionString)
Using cmd As New SqlCommand(sql, conn)
cmd.Parameters.AddWithValue("#AgentCode", AgentCode)
conn.Open()
Using rdr As SqlDataReader = cmd.ExecuteReader()
If (rdr.Read()) Then
'MsgBox("reader reading")
'If AgentCode = rdr("agentcode").ToString() Then
args.IsValid = True
'MsgBox("valid!")
Else
args.IsValid = False
'MsgBox("not valid")
End If
End Using
conn.Close()
End Using
End Using
End Sub
End Class

You need to call Page.Validate() and also check Page.IsValid

Related

Send email failed conversion from string "" to type 'Boolean' is not valid

Imports System.Net.Mail
Partial Class ch5_proj4_ch5_proj4
Inherits System.Web.UI.Page
Protected Sub EmailBtn_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles EmailBtn.Click
' insert code here
Dim MySmtpClient As New SmtpClient()
Dim MM As New MailMessage()
Try
MySmtpClient.Host = "stmp.gmail.com"
MySmtpClient.Port = 587
MySmtpClient.EnableSsl = True
MySmtpClient.UseDefaultCredentials = True
MySmtpClient.Credentials = New System.Net.NetworkCredential()
'mail message
MM.To.Add(New MailAddress(TextBox2.Text, TextBox1.Text))
Dim fromAddress As New MailAddress(TextBox4.Text, TextBox3.Text)
MM.From = fromAddress
MM.Subject = TextBox4.Text
MM.IsBodyHtml = RadioButtonList1.SelectedValue
MM.Body = txtMessage.Text
MySmtpClient.Send(MM)
Label5.Text = "Email successfully sent."
Catch exc As Exception
Label5.Text = "Send email failed" + exc.Message
End Try
MM = Nothing
MySmtpClient = Nothing
End Sub
End Class
What am I doing wrong? Every time I do it I have an error
"Send email failed Conversion from string "" to type 'Boolean' is not valid."
Please help.
Try to change this MM.IsBodyHtml = RadioButtonList1.SelectedValue to this MM.IsBodyHtml = If(RadioButtonList1.SelectedValue = "True",True,False)

Creating User twice in sql server for new registration

I'm trying to create a new user and everything works fine but it enters the same records twice to my db. I have already tried to kept some breakpoints but couldn't find where am I going wrong.
This is my Registration.aspx code:
Protected Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim msg As MailMessage
Dim UserID As String
Dim ActivationUrl As String = String.Empty
Dim emailId As String = String.Empty
UserID = Guid.NewGuid.ToString
'Create ConnectionString and Inser Statement
Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim insertSql As String = "INSERT INTO Users (UserID,UserName,Password,Email,Mobile,Address,CreatedDate)" & " values (#UserID,#UserName,#Password,#Email,#Mobile,#Address,#CreatedDate)"
'Create SQL connection
Dim con As New SqlConnection(connectionString)
'Create SQL Command And Sql Parameters
Dim cmd As New SqlCommand(insertSql, con)
Dim usernumber As New SqlParameter()
usernumber.ParameterName = "#UserID"
usernumber.Value = UserID
cmd.Parameters.Add(usernumber)
Dim username As New SqlParameter()
username.ParameterName = "#Username"
username.Value = txtUserName.Text.ToString()
cmd.Parameters.Add(username)
Dim password As New SqlParameter()
password.ParameterName = "#Password"
password.Value = txtPassword.Text.ToString()
cmd.Parameters.Add(password)
Dim email As New SqlParameter()
email.ParameterName = "#Email"
email.Value = txtEmail.Text.ToString()
cmd.Parameters.Add(email)
Dim mobile As New SqlParameter()
mobile.ParameterName = "#Mobile"
mobile.Value = txtMobile.Text.ToString()
cmd.Parameters.Add(mobile)
Dim address As New SqlParameter()
address.ParameterName = "#Address"
address.Value = txtAddress.Text.ToString()
cmd.Parameters.Add(address)
Dim createddate As New SqlParameter()
createddate.ParameterName = "#CreatedDate"
createddate.Value = Date.Now.ToString("MM/dd/yyyy hh:mm:ss tt")
cmd.Parameters.Add(createddate)
Try
con.Open()
cmd.ExecuteNonQuery()
lblMsg.Text = "User Registration successful"
Catch ex As SqlException
Dim errorMessage As String = "Error in registering user"
errorMessage += ex.Message
Throw New Exception(errorMessage)
Finally
con.Close()
End Try
Try
'Sending activation link in the email
msg = New MailMessage()
Dim smtp As New SmtpClient()
emailId = txtEmail.Text.Trim()
'sender email address
msg.From = New MailAddress("voletykiran#gmail.com")
'Receiver email address
msg.[To].Add(emailId)
msg.Subject = "Confirmation email for account activation"
'For testing replace the local host path with your lost host path and while making online replace with your website domain name
ActivationUrl = Server.HtmlEncode("http://localhost:8769/UserRegistration/ActivateAccount.aspx?UserID=" & FetchUserId(emailId) & "&Email=" & emailId)
msg.Body = "Hi " & txtUserName.Text.Trim() & "!" & vbLf & "Thanks for showing interest and registring in <a href='http://www.webcodeexpert.com'> webcodeexpert.com<a> " & " Please <a href='" & ActivationUrl & "'>click here to activate</a> your account and enjoy our services. " & vbLf & "Thanks!"
msg.IsBodyHtml = True
smtp.Credentials = New NetworkCredential("voletykiran#gmail.com", "india#1a")
smtp.Port = 587
smtp.Host = "smtp.gmail.com"
smtp.EnableSsl = True
smtp.Send(msg)
ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('Confirmation Link to activate account has been sent to your email address');", True)
Catch ex As Exception
ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('Error occured : " & ex.Message.ToString() & "');", True)
Return
Finally
ActivationUrl = String.Empty
emailId = String.Empty
con.Close()
End Try
End Sub
Private Function FetchUserId(emailId As String) As String
Dim cmd As New SqlCommand()
cmd = New SqlCommand("SELECT UserID FROM users WHERE Email=#Email", con)
cmd.Parameters.AddWithValue("#Email", emailId)
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
Private Sub clear_controls()
txtUserName.Text = String.Empty
txtPassword.Text = String.Empty
txtConfirmPassword.Text = String.Empty
txtEmail.Text = String.Empty
txtMobile.Text = String.Empty
txtAddress.Text = String.Empty
txtUserName.Focus()
End Sub
Can anyone say me where am I misleading?

Asp.net (SQL) Simple Login Form

I'm kinda new to asp.net but I'm learning fast, tho I cant find any good web forms tutorial for login page written in vb, I'm using the offline application tutorials to learn and I just change the commands,
So i've come to a simple error for you guys, the problem is with the dsc.sqlclient, probably there's not such command, but what should I use?
Thanks a lot anyway!
Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click
If Page.IsValid Then
' check for username & password in the database
Dim conn As New SqlConnection("Data Source=.\sqlexpress;Initial Catalog=LoginDB;Integrated Security=True")
' Get the row corresponding the given username and password
Dim strSQL As String = "Select * From Users Where Username='" + txtUname.Text + "' and Password = '" + txtPassword.Text + "'"
Dim dsc As New SqlClient.SqlCommand(strSQL, conn)
' Fill the dataset
Dim ds As New DataSet()
dsc.sqlclient.sqlcommand(ds, "Users")
' if there no entry then the user is invalid
If ds.Tables("Users").Rows.Count = 0 Then
Response.Redirect("Default.aspx")
Else
Response.Redirect("login.aspx")
End If
End If
End Sub
Thanks a lot guys, this is the correct answer tho, kbworkshop helped me a lot!
For anyone wanna know this is the code
Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click
If Page.IsValid Then
' check for username & password in the database
Dim conn As New SqlConnection("Data Source=.\sqlexpress;Initial Catalog=LoginDB;Integrated Security=True")
' Get the row corresponding the given username and password
Dim strSQL As String = "Select * From Users Where Username='" + txtUname.Text + "' and Password = '" + txtPassword.Text + "'"
'I recommend not to use * in querys
Dim dsc As New SqlClient.SqlCommand(strSQL, conn)
conn.Open()
Dim dr As SqlDataReader
dr = dsc.ExecuteReader()
If dr.HasRows = True Then
Response.Redirect("Default.aspx")
Else
Response.Redirect("login.aspx")
End If
conn.Close()
End If
End Sub
Your code should be something like this:
Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click
If Page.IsValid Then
' check for username & password in the database
Dim conn As New SqlConnection("Data Source=.\sqlexpress;Initial Catalog=LoginDB;Integrated Security=True")
' Get the row corresponding the given username and password
Dim strSQL As String = "Select * From Users Where Username='" + txtUname.Text + "' and Password = '" + txtPassword.Text + "'"
objConn.Open()
' Fill the dataset
Dim ds As New DataSet("Users")
Dim daExample As New SqlDataAdapter(strSQL, objConn)
daExample.Fill(ds, "Users2")
' if there no entry then the user is invalid
If ds.Tables("Users").Rows.Count = 0 Then
Response.Redirect("Default.aspx")
Else
Response.Redirect("login.aspx")
End If
objConn.close()
End If
End Sub
but you can also take this:
Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click
If Page.IsValid Then
' check for username & password in the database
Dim conn As New SqlConnection("Data Source=.\sqlexpress;Initial Catalog=LoginDB;Integrated Security=True")
' Get the row corresponding the given username and password
Dim strSQL As String = "Select * From Users Where Username='" + txtUname.Text + "' and Password = '" + txtPassword.Text + "'"
'I recommend not to use * in querys
Dim dsc As New SqlClient.SqlCommand(strSQL, conn)
Dim dr As SqlDataReader
dr = dsc.ExecuteReader()
If dr.HasRows = True Then
Response.Redirect("Default.aspx")
Else
Response.Redirect("login.aspx")
End If
End If
End Sub
PLEASE don't create your SELECT statement by pasting text together.
Ugh.
Never do that.
You just allow anyone to use "SQL Injection" to log in (and worse) without a
password.
Imports System.Data
Imports System.Data.SqlClient
Partial Class log
Inherits System.Web.UI.Page
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cn As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=F:\WebSite1\App_Data\Database.mdf;Integrated Security=True;User Instance=True")
Dim log As String = "SELECT * FROM login WHERE userid='" & TextBox1.Text & "' AND password='" & TextBox2.Text & "'"
Session("user") = TextBox1.Text
Dim cmd As New SqlCommand(log, cn)
Dim dr As SqlDataReader
cn.Open()
dr = cmd.ExecuteReader()
If dr.HasRows = True Then
Response.Redirect("showdata.aspx")
Else
Response.Redirect("log.aspx")
End If
End Sub
End Class
You can use SqlDataAdapter class to fill your dataset:
SqlConnection conn = new SqlConnection("My ConnectionString");
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = SQL;
da.SelectCommand = cmd;
DataSet ds = new DataSet();
conn.Open();
da.Fill(ds);
conn.Close();
VB.Net:
Dim conn As New SqlConnection("My ConnectionString")
Dim da As New SqlDataAdapter()
Dim cmd As SqlCommand = conn.CreateCommand()
cmd.CommandText = SQL
da.SelectCommand = cmd
Dim ds As New DataSet()
conn.Open()
da.Fill(ds)
conn.Close()

VB dot net session value set in text box not change

In one of my vb page i am setting the value of a textbox through the value coming from session. In the same page i want to perform an edit operation of the record. On the page load i displayed the variables in textboxes and after editing values when i submit and take the value from the textboxes, it still take the value i set through session. It do not take the value changed in the textbox rather it shows the value assigned at the time of page load. Please help.
Here is my code,
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.SessionState.HttpSessionState
Imports System.Drawing
Imports System.Drawing.Printing
Partial Class Default2
Inherits System.Web.UI.Page
Dim cn As New SqlConnection
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
cn = New SqlConnection("Data Source=nnn-PC;Initial Catalog=Faculty Housing;Persist Security Info=True;User ID=sa;Password=nnn;")
cn.Open()
Dim var As String
var = Session("S2").ToString()
TextBox1.Text = var
Session.Remove("S2")
cmd = New SqlCommand("select * from HouseDetails where OccupantName= '" & TextBox1.Text & "' ", cn)
dr = cmd.ExecuteReader
While (dr.Read)
Label1.Text = dr(1)
Label2.Text = dr(2)
Label3.Text = dr(3)
TextBox3.Text = dr(4)
DropDownList3.SelectedItem.Text = dr(5)
TextBox2.Text = dr(6)
TextBox4.Text = dr(7)
TextBox5.Text = dr(8)
DropDownList4.Text = dr(9)
End While
cn.Close()
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
cn = New SqlConnection("Data Source=nnn-PC;Initial Catalog=Faculty Housing;Persist Security Info=True;User ID=sa;Password=nnn;")
cn.Open()
Dim query As String = ("UPDATE HouseDetails SET OccupantName='" & TextBox1.Text & "' where HouseNum='" & Label3.Text & "'")
cmd = New SqlCommand(query, cn)
Dim x As Integer = cmd.ExecuteNonQuery()
cn.Close()
End Sub
Protected Sub TextBox1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
End Sub
End Class
Add postback prevention with the line "If (Page.IsPostBack = false) Then", for not assigning the same value again to the textbox,
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.SessionState.HttpSessionState
Imports System.Drawing
Imports System.Drawing.Printing
Partial Class Default2
Inherits System.Web.UI.Page
Dim cn As New SqlConnection
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If (Page.IsPostBack = false) Then
cn = New SqlConnection("Data Source=nnn-PC;Initial Catalog=Faculty Housing;Persist Security Info=True;User ID=sa;Password=nnn;")
cn.Open()
Dim var As String
var = Session("S2").ToString()
TextBox1.Text = var
Session.Remove("S2")
cmd = New SqlCommand("select * from HouseDetails where OccupantName= '" & TextBox1.Text & "' ", cn)
dr = cmd.ExecuteReader
While (dr.Read)
Label1.Text = dr(1)
Label2.Text = dr(2)
Label3.Text = dr(3)
TextBox3.Text = dr(4)
DropDownList3.SelectedItem.Text = dr(5)
TextBox2.Text = dr(6)
TextBox4.Text = dr(7)
TextBox5.Text = dr(8)
DropDownList4.Text = dr(9)
End While
cn.Close()
End If
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
cn = New SqlConnection("Data Source=nnn-PC;Initial Catalog=Faculty Housing;Persist Security Info=True;User ID=sa;Password=nnn;")
cn.Open()
Dim query As String = ("UPDATE HouseDetails SET OccupantName='" & TextBox1.Text & "' where HouseNum='" & Label3.Text & "'")
cmd = New SqlCommand(query, cn)
Dim x As Integer = cmd.ExecuteNonQuery()
cn.Close()
End Sub
Protected Sub TextBox1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
End Sub
End Class
I fancy you're missing a check for IsPostBack to see whether or not this is a new request or a submission.
If (Not IsPostBack) Then
' populate for first load
End If
You have to put your code in IsPostback property.
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.SessionState.HttpSessionState
Imports System.Drawing
Imports System.Drawing.Printing
Partial Class Default2
Inherits System.Web.UI.Page
Dim cn As New SqlConnection
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If (!IsPostBack) Then
cn = New SqlConnection("Data Source=nnn-PC;Initial Catalog=Faculty Housing;Persist Security Info=True;User ID=sa;Password=nnn;")
cn.Open()
Dim var As String
var = Session("S2").ToString()
TextBox1.Text = var
Session.Remove("S2")
cmd = New SqlCommand("select * from HouseDetails where OccupantName= '" & TextBox1.Text & "' ", cn)
dr = cmd.ExecuteReader
While (dr.Read)
Label1.Text = dr(1)
Label2.Text = dr(2)
Label3.Text = dr(3)
TextBox3.Text = dr(4)
DropDownList3.SelectedItem.Text = dr(5)
TextBox2.Text = dr(6)
TextBox4.Text = dr(7)
TextBox5.Text = dr(8)
DropDownList4.Text = dr(9)
End While
cn.Close()
End If
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
cn = New SqlConnection("Data Source=nnn-PC;Initial Catalog=Faculty Housing;Persist Security Info=True;User ID=sa;Password=nnn;")
cn.Open()
Dim query As String = ("UPDATE HouseDetails SET OccupantName='" & TextBox1.Text & "' where HouseNum='" & Label3.Text & "'")
cmd = New SqlCommand(query, cn)
Dim x As Integer = cmd.ExecuteNonQuery()
cn.Close()
End Sub
Protected Sub TextBox1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
End Sub
End Class

regarding repsone.redirect in asp.net

Protected Sub Login1_Authenticate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.AuthenticateEventArgs) Handles Login1.Authenticate
Dim Uname As String
Dim pwd As String
Dim pName As String
Dim reader As SqlDataReader
Uname = Login1.UserName
pwd = Login1.Password
pName = ""
Dim strConn As String
strConn = WebConfigurationManager.ConnectionStrings("ConnectionASPX").ConnectionString
Dim Conn As New SqlConnection(strConn)
Conn.Open()
Dim sqlUserName As String
sqlUserName = "SELECT UserName,Password FROM Customer"
sqlUserName &= " WHERE (UserName = #Uname"
sqlUserName &= " AND Password = #Pwd)"
Dim com As New SqlCommand(sqlUserName, Conn)
com.Parameters.AddWithValue("#Uname", Uname)
com.Parameters.AddWithValue("#Pwd", pwd)
reader = com.ExecuteReader()
If (reader.Read()) Then
Me.Response.Redirect("Faq.aspx")
Else
MsgBox("Invalid UserName-password")
End If
reader.Close()
Conn.Close()
'If CurrentName <> "" Then
' Session("UserAuthentication") = Uname
' Response.Redirect("Faq.aspx")
'Else
' Session("UserAuthentication") = ""
'End If
End Sub
the code kis working without any errors . It is not redirecting to another page.
Put a breakpoint (press F9) on the line If (reader.Read()) Then and then press F5 to run the app in debug mode and step through that line to see if it is skipping your Response.Redirect call. If it is, you will have to figure out why the Read() method is returning false.

Resources