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

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.

Related

Error parsing - Insert value Textbox inside database

I have this form ASP.NET that have two textbox and a label, where the user enters only the expiration date in the last textbox, while the others are inserted automatically if the user clicks on another button inside the repeater where the customer code and company name are found.
The problem is that I created a class to do the insertion: I used a stored procedure for the insertion and I used the query parameterization.
When I parse the code and date it gives me 0 and a default date as a result, while my goal is to insert them into a table inside a db and then have it displayed inside the repeater.
P.S. I add that for reading the data I have another class with another stored procedure and that I have some values ​​that are inside another table (the code and the name of the company).
This is the method:
Public Sub INSERT_EXP_DATE_TABLE()
Dim id_customer As Integer
Dim exp_date As Date
Try
cmd.Connection = cn
cmd.CommandType = CommandType.StoredProcedure
MyParm = cmd.Parameters.Add("#COD_CUSTOMER", SqlDbType.Int)
If (Integer.TryParse(txt_COD_CUSTOMER.Text, id_customer)) Then
MyParm.Value = id_customer
Else
MsgBox("customer not found", vbCritical)
End If
MyParm = cmd.Parameters.Add("#COMPANY_NAME", SqlDbType.NVarChar)
MyParm.Value = lbl_COMPANY_NAME.Text.ToString
MyParm = cmd.Parameters.Add("#EXP_DATE", SqlDbType.Date)
If (Date.TryParse(txt_EXP_DATE.Text, exp_date)) Then
MyParm.Value = exp_date
Else
MsgBox("Exp Date not found", vbCritical)
End If
cmd.CommandText = "LST_INSERT_TABLE_01"
cmd.Connection.Open()
cmd.ExecuteNonQuery()
MsgBox("Date registred", vbInformation)
Catch ex As Exception
MsgBox(ex.Message)
Finally
cn.Close()
End Try
End Sub
And this is the stored procedure:
#ID_CUSTOMER int,
#COMPANY_NAME varchar(50),
#EXP_DATE date,
AS
BEGIN
INSERT INTO TABLE
(
ID_CUSTOMER,
COMPANY_NAME,
EXP_DATE,
)
VALUES(
#ID_CUSTOMER,
#COMPANY_NAME,
#EXP_DATE,
)
END
Keep your connection local to the method where it is used. Connections use unmanaged resources so they include a .Dispose method which releases these resources. To ensure that the database objects are closed and disposed use Using...End Using blocks.
Do you parsing before you start creating database objects. Exit the sub so the user has a chance to correct the problem.
Side note: I don't think a message box will work in an asp.net application.
You set up the company name parameter as an NVarChar but your stored procedure declares it as a VarChar. Which is correct?
It is not necessary to call .ToString on a .Text property. A .Text property is already a String.
You are providing a parameter called "#COD_CUSTOMER" but your stored procedure does not have such parameter.
Public Sub INSERT_EXP_DATE_TABLE()
Dim id_customer As Integer
If Not Integer.TryParse(txt_COD_CUSTOMER.Text, id_customer) Then
MsgBox("Please enter a valid number.", vbCritical)
Exit Sub
End If
Dim exp_date As Date
If Not Date.TryParse(txt_EXP_DATE.Text, exp_date) Then
MsgBox("Please enter a valid date.")
Exit Sub
End If
Using cn As New SqlConnection("Your connection string"),
cmd As New SqlCommand("LST_INSERT_TABLE_01", cn)
cmd.CommandType = CommandType.StoredProcedure
With cmd.Parameters
.Add("#ID_CUSTOMER", SqlDbType.Int).Value = id_customer
.Add("#COMPANY_NAME", SqlDbType.VarChar, 50).Value = lbl_COMPANY_NAME.Text
.Add("#EXP_DATE", SqlDbType.Date).Value = exp_date
End With
Try
cn.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Using
End Sub
{
string CN = Interaction.InputBox("Enter Company Name","Customer","",-1,-1);
string Cname = Interaction.InputBox("Enter Customer Name", "Customer", "", -1, -1);
SqlConnection con = new SqlConnection(#"Data Source=Adnan;Initial Catalog=Production;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO hello(Company_Name,Customer_name ) VALUES ( #Company_Name,#Customer_name )");
cmd.Connection = con;
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#Company_Name", CN.ToString() );
cmd.Parameters.AddWithValue("#Customer_name", Cname.ToString());
}

ASP.Net Login Page with MySQL

Can anyone spot the error in this? I'm trying to create a simple login page (asp.net vb) that does a count on a mysql table. When i type anything in it logs me in even if the details do not match. I believe it'll be the case statement that's wrong but any help would be appreciated!
Protected Sub ValidateUser(sender As Object, e As EventArgs)
Dim userId As Integer = -1
Dim constr As String = ConfigurationManager.ConnectionStrings("conn").ConnectionString
Using con As New MySqlConnection(constr)
Using uscmd As New MySqlCommand("SELECT COUNT(*) FROM tblUser WHERE UName = ?#Username AND Pword = ?#Password", con)
uscmd.Parameters.AddWithValue("#Username", Login1.UserName)
uscmd.Parameters.AddWithValue("#Password", Login1.Password)
Using uuda As New MySqlDataAdapter(uscmd)
Dim ds As New DataSet()
uuda.Fill(ds)
userId = ds.Tables(0).Rows.Count.ToString()
End Using
End Using
Select Case userId
Case -1
Login1.FailureText = "Username and/or password is incorrect."
Exit Select
Case -2
Login1.FailureText = "Account has not been activated."
Exit Select
Case Else
FormsAuthentication.RedirectFromLoginPage(Login1.UserName, Login1.RememberMeSet)
Exit Select
End Select
End Using
End Sub
Your query "SELECT COUNT()..." will always return 1 record. After execute the query, you make an assignment
userId = ds.Tables(0).Rows.Count.ToString()
So the value of userId will be always 1. So it always run into CASE ELSE of the CASE statement. That's why whatever you type, it logs you in even if the details do not match.
To check the username and password have been registered or not, you could update your code like following
Protected Sub ValidateUser(sender As Object, e As EventArgs)
Dim userCount As Integer = -1
Dim constr As String = ConfigurationManager.ConnectionStrings("conn").ConnectionString
Using con As New MySqlConnection(constr)
Using uscmd As New MySqlCommand("SELECT COUNT(*) FROM tblUser WHERE UName = ?#Username AND Pword = ?#Password", con)
uscmd.Parameters.AddWithValue("#Username", Login1.UserName)
uscmd.Parameters.AddWithValue("#Password", Login1.Password)
Using uuda As New MySqlDataAdapter(uscmd)
Dim ds As New DataSet()
uuda.Fill(ds)
Integer.TryParse(ds.Tables(0).Rows(0)(0), userCount)
End Using
End Using
If userCount > 0 Then
FormsAuthentication.RedirectFromLoginPage(Login1.UserName, Login1.RememberMeSet)
Else
Login1.FailureText = "Username and/or password is incorrect."
End If
End Using
End Sub

Comparing variables to SQL / Troubleshooting session

I am trying to send some variables, using a session, to the next page "ProcedureSelectionForm.aspx". As you can see, the sessions have been commented out. The code below will work (without sending the variable of course). However, when you remove the comments the .onclick function reloads the page rather than navigating to "ProcedureSelectionForm.aspx". For this reason, I believe this is where my problem is. The first two columns are "Account" and "Password" in the database. I have not misspelled anything. I am new to VB and ASP.net and would appreciate some explanation as to what is happening and why my desired functionality isn't materializing. Thank you for your help!
If IsValid Then
Try
Dim strSQL = "select * from CreatePatient where Account = #Account and Password = #Password"
Using CCSQL = New SqlConnection(ConfigurationManager.ConnectionStrings("CreatePatientConnectionString").ConnectionString)
Using CCUser = New SqlCommand(strSQL, CCSQL)
CCSQL.Open()
CCUser.Parameters.Add("#Account", Data.SqlDbType.VarChar).Value = PatientAccount.Text
CCUser.Parameters.Add("#Password", Data.SqlDbType.VarChar).Value = PatientPass.Text
CCUser.ExecuteNonQuery()
'Using reader As SqlDataReader = CCUser.ExecuteReader()
'If reader.HasRows Then
'reader.Read()
'Session("user") = reader("Account")
'Session("pass") = reader("Password")
Response.Redirect("ProcedureSelectionForm.aspx")
'End If
'End Using
End Using
End Using
Catch ex As Exception
Label1.Text = ex.Message
End Try
End If
My friend was able to make time to help me out. I am unsure of what he did differently besides closing connections
If IsValid Then
Dim CCSQL As New SqlConnection
Dim CCUser As New SqlCommand
Dim strSQL As String
Dim dtrUser As SqlDataReader
Try
CCSQL.ConnectionString = ConfigurationManager.ConnectionStrings("CreatePatientConnectionString").ConnectionString
strSQL = "Select * from CreatePatient where Account=#user and Password=#pwd"
CCUser.CommandType = Data.CommandType.Text
CCUser.CommandText = strSQL
CCUser.Parameters.Add("#user", Data.SqlDbType.VarChar).Value = PatientAccount.Text
CCUser.Parameters.Add("#pwd", Data.SqlDbType.VarChar).Value = PatientPass.Text
CCSQL.Open()
CCUser.Connection = CCSQL
dtrUser = CCUser.ExecuteReader()
If dtrUser.HasRows Then
dtrUser.Read()
Session("user") = dtrUser("Account")
Session("level") = dtrUser("Password")
Response.Redirect("ProcedureSelectionForm.aspx")
Else
Label1.Text = "Please check your user name and password"
End If
dtrUser.Close()
CCSQL.Close()
Catch ex As Exception
Label1.Text = ex.Message
End Try
End If
I am on a tight deadline but i will get back to those interested with an answer. Thank you for your effort.
You don't want to do .ExecuteNonQuery() when you are actually doing a query (i.e. a SQL "SELECT" statement. You can just do the .ExecuteReader() to read those two values.
Also, I presume you are trying to validate the Account and Password; otherwise you could just set Session("user") = PatientAccount.Text and set Session("pass") = PatientPass.Text.

Activation Email/Link Not Working

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

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