Activation Email/Link Not Working - asp.net

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! :(

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

Related

<function> is not a member of <class> error when published to Azure

I'm working on an MVC app and I have built a function to handle my DB connections called DBConn. Within DBConn I have a function InsertSQL(qry, parr()) that is public and shared. When I test on my local machine it all works fine, but when I publish to Azure and view the live site I get the following:
BC30456: 'InsertSQL' is not a member of 'DBConn'.
The Function I have is below:
Imports Microsoft.VisualBasic
Imports System.Data.SqlClient
Imports System.Data
Public Class DBConn
Public Shared Connstr As String
Public Shared Querystr As String
Public Shared Function InsertSQL(qryStr As String, ByRef parr() As Object) As Integer
Dim connection As SqlConnection = New SqlConnection()
Dim cmd As New SqlCommand
Dim qry As String = ""
connection.ConnectionString = ConfigurationManager.ConnectionStrings(Connstr).ConnectionString
connection.Open()
cmd.Connection = connection
Select Case qryStr
Case "addForumPost"
qry = "INSERT INTO ForumPosts(CreatedBy, CreatedDate, Sticky, Message, ForumID) VALUES ('" & parr(1) & "','" & parr(3) & "'," & "0" & ",'" & parr(0) & "'," & parr(2) & ")"
End Select
If qry <> "" Then cmd.CommandText = qry
cmd.ExecuteNonQuery()
connection.Close()
Return 0
End Function
End Class
I've only included the InsertSQL function for brevity, but there are other functions set up exactly the same way that aren't having the same issue. Any ideas? I'm thinking it must be either an Azure thing, or an access/permission thing.
Here is how I am calling the function within my asp page:
#<form method = "post" action="#HttpContext.Current.Request.Url.AbsolutePath">
<fieldset>
<p>Add Comment</p>
<p><textarea style="width:100%" rows="10" name = "comment" ></textarea></p>
<p><input type = "submit" name="addPost" value="Post" /></p>
#If IsPost = True Then
Dim rtnCode As Integer
Dim cn As New DBConn
Dim arr(0 To 3) As Object
If Request.Form("comment") <> "" Then
cn.Connstr = "kbl"
arr(0) = Request.Form("comment")
arr(1) = Session("userObject").username
arr(2) = HttpContext.Current.Request.RequestContext.RouteData.Values("id")
arr(3) = Now().ToString("yyyyMMdd hh:mm:ss")
rtnCode = cn.InsertSQL("addForumPost", arr)
End If
#<meta http-equiv='refresh' content='0'>
End If
</fieldset>
</form>

error when trying to update column values in VB.net

Good day!
I just want to seek help from you guys, I'm again having problems with my UPDATE functionality, here's my code...
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
con = New SqlConnection("Server=localhost\SQLEXPRESS;Database=Vehicle;Trusted_Connection=True;")
con.Open()
Dim cmd As SqlCommand = con.CreateCommand
cmd.CommandText = String.Format("UPDATE trip SET ticketno, charge, driver, destination, passenger, purpose, tripdate", txtticket.Text, txtcharge.Text, txtdriver.Text, txtdestination.Text, txtpassenger.Text, txtpurpose.Text, dtptripdate1.Value)
Dim affectedRows As Integer = cmd.ExecuteNonQuery
If affectedRows > 0 Then
MsgBox("Succesfully Updated")
Else
MsgBox("Failed to update")
End If
con.Close()
End Sub
When I try to click the Button, an error would show:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Incorrect syntax near ','.
thanks for helping me out.
I'm really close to finishing this small-scale project for my office but I'm stuck with these kind of problems.
Try this,
Dim myCommand = New SqlCommand("UPDATE trip SET ticketno=#ticketno, charge=#charge, driver=#driver, destination=#destination, passenger=#passenger, purpose=#purpose, tripdate=#tripdate",con)
myCommand.Parameters.Add("#ticketno", txtticket.Text)
myCommand.Parameters.Add("#charge", txtcharge.Text)
myCommand.Parameters.Add("#driver", txtdriver.Text)
myCommand.Parameters.Add("#destination", txtdestination.Text)
myCommand.Parameters.Add("#passenger", txtpassenger.Text)
myCommand.Parameters.Add("#purpose", txtpurpose.Text)
myCommand.Parameters.Add("#tripdate", dtptripdate1.Text)
Dim affectedRows As Integer = cmd.ExecuteNonQuery
If affectedRows > 0 Then
MsgBox("Succesfully Updated")
Else
MsgBox("Failed to update")
End If
con.Close()
Your UPDATE statement is wrong, so your String.Format. and don't your missed out a WHERE condition?
cmd.CommandText = String.Format("UPDATE trip SET ticketno='{0}', charge='{1}', driver='{2}', destination='{3}', passenger='{4}', purpose='{5}', tripdate='{6}'", txtticket.Text, txtcharge.Text, txtdriver.Text, txtdestination.Text, txtpassenger.Text, txtpurpose.Text, dtptripdate1.Value)
OR try this to avoid SQL Injection.
Wrap your conn with a Using block to ensure the dispose of your SqlConnection
Using conn As New SqlConnection("Server=localhost\SQLEXPRESS;Database=Vehicle;Trusted_Connection=True;")
conn.Open()
Dim cmd As New SqlCommand
cmd.Connection = conn
cmd.CommandText = "UPDATE trip SET ticketno=#ticketno, charge=#charge, driver=#driver, destination=#destination, " & _
"passenger=#passenger, purpose=#purpose, tripdate=#tripdate " & _
"WHERE SomeCondition"
cmd.Parameters.AddWithValue("#ticketno", txtticket.Text)
cmd.Parameters.AddWithValue("#charge", txtcharge.Text)
cmd.Parameters.AddWithValue("#driver", txtdriver.Text)
cmd.Parameters.AddWithValue("#destination", txtdestination.Text)
cmd.Parameters.AddWithValue("#passenger", txtpassenger.Text)
cmd.Parameters.AddWithValue("#purpose", txtpurpose.Text)
cmd.Parameters.AddWithValue("#tripdate", dtptripdate1.Value)
Dim affectedRow As Integer = cmd.ExecuteNonQuery
IIf(affectedRow > 0, MsgBox("Succesfully Updated"), MsgBox("Failed to update"))
End Using

ASP.NET VB.NET -- SQL UPDATE Command Not Working

I have been working on this particular issue for a couple of days, and scouring over SO, MSDN and other google searches has not proven to be of any use. I am trying to make a simple update to a SQL table. My SELECT and INSERT statements all work fine, but for some reason, this update will not work. I have set breakpoints and stepped through, and the code seems to be working fine -- the Catch ex as Exception is never reached after the .ExecuteNonQuery() fires off.
Could anyone give me an idea of why I've been unable to get a SQL update?
Protected Sub SaveButton_Click(sender As Object, e As EventArgs) Handles SaveButton.Click
Dim currentUser = Membership.GetUser(User.Identity.Name)
Dim username As String = currentUser.UserName
Dim userId As Guid = currentUser.ProviderUserKey
UserNameTextBox.Text = username
' Get Root Web Config Connection String so you don't have to encrypt it
Dim rootWebConfig As System.Configuration.Configuration
rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~/")
Dim connString As System.Configuration.ConnectionStringSettings
connString = rootWebConfig.ConnectionStrings.ConnectionStrings("LocalSqlServer")
Dim conn As String = connString.ToString
Dim commandString As String = "UPDATE UserDetails SET FirstName ='" + FirstNameTextBox.Text + "' WHERE UserId ='" + userId.ToString + "'"
Dim fname As String = FirstNameTextBox.Text
Dim commandText As String = "UPDATE UserDetails SET FirstName=#firstname WHERE UserId=#UID;"
Using connection As New SqlConnection(conn)
Dim command As New SqlCommand(commandText, connection)
command.CommandType = CommandType.Text
' Add UserId parameter for WHERE clause.
command.Parameters.Add("#UID", SqlDbType.UniqueIdentifier).Value = userId
' command.Parameters("#UID").Value = userId
' command.Parameters.AddWithValue("#UID", userId)
' Use AddWithValue to assign Demographics.
command.Parameters.Add("#firstname", SqlDbType.VarChar, 255).Value = fname
'command.Parameters.AddWithValue("#firstname", fname)
' command.Parameters("#firstname").Value = FirstNameTextBox.Text.ToString
Try
connection.Open()
command.ExecuteNonQuery()
Dim rowsAffected As Integer = command.ExecuteNonQuery()
Console.WriteLine("RowsAffected: {0}", rowsAffected)
Catch ex As Exception
Console.WriteLine(ex.Message)
Finally
connection.Close()
End Try
End Using
End Sub
You're running "command.ExecuteNonQuery()" twice, meaning the second execution will likely return 0 rows affected since you already updated what you needed to update, and that's what you're assigning to rowsAffected. Are you sure the UPDATE isn't occurring?
Edit: Re your comment, did you check for IsPostBack when you LoadUser? If not, when you click SaveButton, you're going to reload the existing values, and then you'll be updating with those existing values.

I got a Object reference not set to an instance of an object

I got this error when I click on SAVE button inside the save button is
The error is
"Object reference not set to an instance of an object"
Protected Sub btnWizardFinish_Click(sender As Object, e As EventArgs)
If (rdoAprovalList.SelectedIndex = 1) Then
SaveConsideration(4)
Else
SaveConsideration(1)
End If
End Sub
and this is save sub that contain to save and update a value in DocumentStatusID field in Database
Private Sub SaveConsideration(ByVal DocumentStatusID As Integer)
Dim Conn As New SqlConnection(strConn)
Dim cmd As New SqlCommand
Try
If ((txtProducerID.Text.Trim.Length = 9)) Then
cmd.Connection = Conn
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "spConsiderationSaving"
cmd.Parameters.AddWithValue("#libDocumentID", txtProducerID.Text)
cmd.Parameters.AddWithValue("#ProducerComments", txtProducerComment.Text)
cmd.Parameters.AddWithValue("#DocumentStatusID", DocumentStatusID)
cmd.Parameters.AddWithValue("#ConProduceThai", chkConproduceThai.Checked)
cmd.Parameters.AddWithValue("#ConProducePolicy", chkConProducePolicy.Checked)
cmd.Parameters.AddWithValue("#ConProduceIP", chkConProduceIP.Checked)
cmd.Parameters.AddWithValue("#ConProduceDanger", chkConProduceDanger.Checked)
cmd.Parameters.AddWithValue("#ConProducePeople", chkConproducePeople.Checked)
cmd.Parameters.AddWithValue("#ConProduceManage", chkConProduceManage.Checked)
cmd.Parameters.AddWithValue("#ConProduceMade", chkConProduceMade.Checked)
Conn.Open()
Dim ResponseText As Integer = DirectCast(cmd.ExecuteScalar, Int32).ToString
If (ResponseText = 1) Then
lblResponseResult.Text = "<img src='../images/icons/message-boxes/confirmation.png' /> บันทึกลงฐานข้อมูลเรียบร้อยแล้ว"
If (DocumentStatusID = 3) Then 'Goto next step
AlertRedirects("redirect", pnlHint.ClientID, 3, "Verification.aspx")
Else
AlertBoxs("alert", pnlHint.ClientID, 2)
End If
End If
Else
Dim sb As New System.Text.StringBuilder()
sb.Append("<script type = 'text/javascript'>")
sb.Append("window.onload=function(){")
sb.Append("javascript:history.back();return false;")
sb.Append("};")
sb.Append("</script>")
ClientScript.RegisterClientScriptBlock(Me.GetType(), "back", sb.ToString())
End If
Catch ex As Exception
Response.Write("Error Save: " & ex.Message)
Finally
Conn.Close()
End Try
End Sub
I think it's a problem with reference to something
what is the error please specify that. the code which you posted in that is seems two syntax mistakes
Dim ResponseText As Integer = DirectCast(cmd.ExecuteScalar, Int32).ToString
If (ResponseText = 1)
you are assigning ResponseText a string value which is an integer
and second is if condition there should be double equals like If (ResponseText == 1) because it's not assignment single equals used for assignment

oRecordset in ASP.NET mySQL

I have this mySQL code that connects to my server. It connects just fine:
Dim MyConString As String = "DRIVER={MySQL ODBC 3.51 Driver};" & _
"SERVER=example.com;" & _
"DATABASE=xxx;" & _
"UID=xxx;" & _
"PASSWORD=xxx;" & _
"OPTION=3;"
Dim conn As OdbcConnection = New OdbcConnection(MyConString)
conn.Open()
Dim MyCommand As New OdbcCommand
MyCommand.Connection = conn
MyCommand.CommandText = "select * from userinfo WHERE emailAddress = '" & theUN & "'""
MyCommand.ExecuteNonQuery()
conn.Close()
However, i have an old Classic ASP page that uses "oRecordset" to get the data from the mySQL server:
Set oConnection = Server.CreateObject("ADODB.Connection")
Set oRecordset = Server.CreateObject("ADODB.Recordset")
oConnection.Open "DRIVER={MySQL ODBC 3.51 Driver}; SERVER=example.com; PORT=3306; DATABASE=xxx; USER=xxx; PASSWORD=xxx; OPTION=3;"
sqltemp = "select * from userinfo WHERE emailAddress = '" & theUN & "'"
oRecordset.Open sqltemp, oConnection,3,3
And i can use oRecordset as follows:
if oRecordset.EOF then....
or
strValue = oRecordset("Table_Name").value
or
oRecordset("Table_Name").value = "New Value"
oRecordset.update
etc...
However, for the life of me, i can not find any .net code that is similar to that of my Classic ASP page!!!!!
Any help would be great! :o)
David
This is what you have to do:
instead of MyCommand.ExecuteNonQuery you should use MyCommand.ExecuteQuery and assign it to DataReader.
Check out this sample:
Dim myConnection As SqlConnection
Dim myCommand As SqlCommand
Dim dr As New SqlDataReader()
'declaring the objects
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)_
Handles MyBase.Load
myConnection = New SqlConnection("server=localhost;uid=sa;pwd=;database=pubs")
'establishing connection. you need to provide password for sql server
Try
myConnection.Open()
'opening the connection
myCommand = New SqlCommand("Select * from discounts", myConnection)
'executing the command and assigning it to connection
dr = myCommand.ExecuteReader()
While dr.Read()
'reading from the datareader
MessageBox.Show("discounttype" & dr(0).ToString())
MessageBox.Show("stor_id" & dr(1).ToString())
MessageBox.Show("lowqty" & dr(2).ToString())
MessageBox.Show("highqty" & dr(3).ToString())
MessageBox.Show("discount" & dr(4).ToString())
'displaying the data from the table
End While
dr.Close()
myConnection.Close()
Catch e As Exception
End Try
HTH
Dim conn As OdbcConnection = New OdbcConnection("DRIVER={MySQL ODBC 3.51 Driver}; SERVER=xxx.com; DATABASE=xxx; UID=xxx; PASSWORD=xxx; OPTION=3;")
conn.Open()
Dim MyCommand As New OdbcCommand
MyCommand.Connection = conn
MyCommand.CommandText = "SELECT * FROM userinfo"
Dim rst = MyCommand.ExecuteReader()
While rst.Read()
response.write(rst("userID").ToString())
End While
conn.Close()
Dim email As String = "anyone#anywhere.com"
Dim stringValue As String
Using conn As OdbcConnection = New OdbcConnection(MyConString)
conn.Open()
Dim sql = "Select ... From userInfo Where emailAddress = #Email"
Using cmd As OdbcCommand = New OdbcCommand(sql, conn)
cmd.Parameters.AddWithValue("#Email", email)
Dim reader As OdbcDataReader = cmd.ExecuteReader()
While reader.Read()
stringValue = reader.GetString(0)
End While
End Using
conn.Close()
End Using
'To do an Update
Using conn As OdbcConnection = New OdbcConnection(MyConString)
conn.Open()
Dim sql As String = "Update userInfo Set Column = #Value Where PK = #PK"
Using cmd As OdbcCommand = New OdbcCommand(sql, conn)
cmd.Parameters.AddWithValue("#Email", email)
cmd.ExecuteNonQuery()
End Using
End Using
'To do an Insert
Using conn As OdbcConnection = New OdbcConnection(MyConString)
conn.Open()
Dim sql As String = "Insert userInfo(Col1,Col2,...) Values(#Value1,#Value2...)"
Using cmd As OdbcCommand = New OdbcCommand(sql, conn)
cmd.Parameters.AddWithValue("#Col1", value1)
cmd.Parameters.AddWithValue("#Col2", value2)
...
cmd.ExecuteNonQuery()
End Using
End Using
First, even in ASP Classic, it is an absolutely horrid approach to concatenate a value directly into a SQL statement. This is how SQL Injection vulnerabilities happen. You should always sanitize values that get concatenated into SQL statements. In .NET, you can use parametrized queries where you replace the values that go into your query with a variable that begins with an # sign. You then add a parameter to the command object and set your value that way. The Command object will sanitize the value for you.
ADDITION
You mentioned in a comment that your ASP Classic code is shorter. In fact, the .NET code is shorter because there are a host of things happening that you do not see and have not implemented in your ASP Classic code. I already mentioned one which is sanitizing the inputs. Another is logging. Out of the box, if an exception is thrown, it will log it in the Event Log with a call stack. To even get a call stack in ASP Classic is a chore much less any sort of decent logging. You would need to set On Error Resume Next and check for err.number <> 0 after each line. In addition, without On Error Resume Next, if an error is thrown, you have no guarantee that the connection will be closed. It should be closed, but the only way to know for sure is to use On Error Resume Next and try to close it.
Generally, I encapsulate all of my data access code into a set of methods so that I can simply pass the SQL statement and the parameter values and ensure that it is called properly each time. (This holds true for ASP Classic too).

Resources