Add a session variable to a script string? - asp.net

I am using the code below to generate a popup box. Where is says "The information is ready to be submitted" I would like to add "Your reference number is 12345" I am getting that reference number using a session i.e. Session("ID"). Is there a way I can add this to the string?
Try
Dim msg As String = "Hello!"
Dim script As String = "if(confirm('The information is ready to be submitted')) {window.location.href ='frmMain.aspx'; }"
ScriptManager.RegisterClientScriptBlock(Me, Me.[GetType](), "Test", script, True)
Catch ex As Exception
End Try

Yep. Just add the information to your script string (I switched the string to stringbuilder for slight efficiency gain):
Dim sbScript As New System.Text.StringBuilder(200)
sbScript.Append("if(confirm('The information is ready to be submitted. Your reference number is ").Append(Session("ID"))
sbScript.Append("')) {window.location.href ='frmMain.aspx'; }")
ScriptManager.RegisterClientScriptBlock(Me, Me.[GetType](), "Test", sbScript.ToString(), True)

Try this:
Try
Dim msg As String = "Hello!"
Dim idValue As String = CType(Session("ID"), String)
Dim script As String = "if(confirm('The information is ready to be submitted. Your reference number is " & idValue & "')) {window.location.href ='frmMain.aspx'; }"
ScriptManager.RegisterClientScriptBlock(Me, Me.[GetType](), "Test", script, True)
Catch ex As Exception
End Try

Related

The code for my aspx signup page does not work

Hello the following code for my signup page does not work. when I execute it, it refreshes and stays in the same page. But it is supposed to redirect to a page called message.aspx. The register command works as follows the person trying to register writes in comboboxs their information and then once they finished, they click the button begin which will save all their information and then use it to personalize the message.aspx page and the person will receive an email.
here is the code:
Private Sub cmdRegister_Click(sender As Object, e As System.EventArgs) Handles cmdRegister.Click
Dim status As MembershipCreateStatus
Dim organization As New Org
Dim employee As New Employee
Dim description As New Description(25)
Dim userMembership As MembershipUser
Dim stringBuilder As New StringBuilder
Try
Membership.CreateUser( _
txtUserName.Text, _
txtPassword.Text, _
txtEmail.Text, _
"question", _
"answer", _
True, _
status)
If status.ToString = "Success" Then
organization.GSTRate = 1
organization.QSTRate = 1
organization.AccountStatus = 2
organization.Name = txtOrg.Text
organization.Active = 1
organization.OrgTypeID = cboType.SelectedValue
organization.Create()
organization = Nothing
organization = New Org(txtOrg.Text)
employee.Username = txtUserName.Text
employee.OrgID = organization.ID
employee.FirstName = txtFName.Text
employee.LastName = txtLName.Text
employee.Title = txtTitle.Text
employee.Username = txtUserName.Text
employee.IsAdmin = True
employee.IsSupervisor = True
employee.IsAccountant = False
employee.IsAdvalorem = True
employee.Email = txtEmail.Text
employee.Phone = ""
employee.Create()
Roles.AddUserToRole(employee.Username, "Admin")
userMembership = Membership.GetUser(txtUserName.Text)
stringBuilder.Append(description.EnglishDescription)
stringBuilder.Replace("(name)", employee.FirstName & " " & employee.LastName)
stringBuilder.Replace("(OrgName)", organization.Name)
stringBuilder.Replace("(username)", employee.Username)
stringBuilder.Replace("you must activate your account", "you must <a href='https://www.advataxes.ca/login.aspx?action=activate&id=" + userMembership.ProviderUserKey.ToString + "&username=" + userMembership.UserName + "'>activate your account</a>")
SendEmail(userMembership.Email, "Advataxes: Account created ", stringBuilder.ToString, Session("language"))
Session("NewUserEmail") = userMembership.Email
Response.Redirect("message.aspx?id=364")
Else
lblInvalidUserName.Visible = True
If status.ToString = "DuplicateUserName" Then lblInvalidUserName.Text = "Username already exists"
End If
Catch ex As MembershipCreateUserException
MsgBox(GetErrorMessage(ex.StatusCode))
Catch ex As HttpException
MsgBox(ex.Message)
Finally
userMembership = Nothing
organization = Nothing
employee = Nothing
description = Nothing
End Try
End Sub
Looking at your code, I suspect the code execution is not successfully reaching the Response.Redirect("message.aspx?id=364") line and due to an exception the flow jumps to catch block/
Two possibilities I can think of:
Exception is thrown inside SendEmail method if smtp is not configured
Membership.CreateUser is failing due to incorrect database connectionstring
I suggest you put a breakpoint inside the cmdRegister_Click method and step through the code.

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.

second ExecuteReader() doesn't work

I have a code which checks the validity of user and then, if a user is valid it inserts certain values in the database.
My problem is when After I query my database to check if a user is valid and after that i try to pass the additional value to its account the flow stops when I invoke ExecuteReader() for the second time.
There is no error, or anything like that. I tried to substitute ExecuteReader() with ExecuteNoneQuery but still it's not working. I tried all the query in mysql command prompt they are working perfectly. I really can't understand what am I doing wrong there. Can anyone help me please?
Here is the code:
Try
myconn.Open()
Dim stquery As String = "SELECT * from accountstbl WHERE SE_ID = " & Id.Text
Dim smd = New MySqlCommand(stquery, myconn)
Dim myreader = smd.ExecuteReader()
If Not myreader.HasRows Then
errorUser.Visible = True
Else
myreader.Read()
Dim name As String = myreader.Item("user_name").ToString()
Dim stquery2 = "INSERT into backup VALUES (" & name & ", '" & Info & "')"
Dim smd2 = New MySqlCommand(stquery2, myconn)
Dim Myreader2 As MySqlDataReader
'smd.ExecuteNonQuery()'
'THE CODE STOPS HERE'
Myreader2 = smd2.ExecuteReader()
'Myreader2.Read()'
MsgBox("The BACKUP INFORMATION HAS BEEN SAVED")
End If
myconn.Close()
Catch ex As Exception
Dim ErrorMessage As String = "alert('" & ex.Message.ToString() & "');"
Page.ClientScript.RegisterStartupScript(Me.GetType(), "ErrorAlert", ErrorMessage, True)
myconn.Close()
End Try
Because your second query is an update, not a select, you need to execute it using the ExecuteNonQuery method. Your commented-out code shows an attempt to call ExecuteNonQuery but on the wrong command object (smd when it should be smd2). Try something like this instead:
myreader.Read()
Dim name As String = myreader.Item("user_name").ToString()
Dim stquery2 = "INSERT into backup VALUES (" & name & ", '" & Info & "')"
Dim smd2 = New MySqlCommand(stquery2, myconn)
smd2.ExecuteNonQuery()
The ExecuteNonQuery method returns the number of rows updated as an int value, so you can capture it if it's valuable to you. In your case it's probably not, but here's how you'd check anyway:
int rowsAdded = smd2.ExecuteNonQuery();
if (rowsAdded == 1) {
// expected this
} else {
// didn't expect this
}
Finally, concatenating strings to build SQL commands can leave you vulnerable to SQL Injection attacks. Please take a look at using parameterized queries. There's a decent example here.
If you want to execute nested Reader, you have to create another connection. You need somethig like
smd2 = New MySqlCommand(stquery2, myconn2)' myconn2 is another connection
OR
Set "MultipleActiveResultSets=True in your connection string.
Also, use ExecuteNonQuery() for Inserting
Dim name As String = myreader("user_name").ToString()
Dim stquery2 = "INSERT into backup VALUES ('" & name & "', '" & Info & "')"
Dim smd2 = New MySqlCommand(stquery2, myconn)
smd.ExecuteNonQuery()
Please use Parameterized query to avoid SQL Injection
The logic is that you need to close your first reader (myreader) before executing another reader (MyReader2) on the same connection.

How to check if mysql query returns nothing?

I'm writing a project and at the some point i have to check if there is an entry in database which matches the content of id-textbox and password-textbox. But I don't know how to indicate in my backend code(VB) that the query returns nothing.
This is the code I am using. But it doesn't work somehow. Error messages Are not being prompt:
Try
myconn.Open()
Dim stquery As String = "SELECT * from accountstbl WHERE user_ID = " & IdNumb.Text
Dim smd As MySqlCommand
Dim myreader As MySqlDataReader
smd = New MySqlCommand(stquery, myconn)
myreader = smd.ExecuteReader()
If myreader.Read() = True Then
If myreader.Item("user_ID") = IdNumb.Text Then
If myreader.Item("password") = CurrPass.Text Then
'some code if the user input is valid
Else
errorPassID.Visible = True
End If
Else
errorPassC.Visible = True
End If
End If
myconn.Close()
Catch ex As Exception
Dim ErrorMessage As String = "alert('" & ex.Message.ToString() & "');"
Page.ClientScript.RegisterStartupScript(Me.GetType(), "ErrorAlert", ErrorMessage, True) myconn.Close()
End Try
Will appreciate any help or suggestion.
I will try to check if the reader return rows and if not, emit an error message.
Also, do not use string concatenation to build queries, use always parametrized queries
myconn.Open()
Dim stquery As String = "SELECT * from accountstbl WHERE user_ID = #id"
Dim smd = New MySqlCommand(stquery, myconn)
smd.Parameters.AddWithValue("#id", Convert.ToInt32(IdNumb.Text))
Dim myreader = smd.ExecuteReader()
if Not myreader.HasRows Then
Dim ErrorMessage As String = "alert('No user found');"
Page.ClientScript.RegisterStartupScript(Me.GetType(), "ErrorAlert", ErrorMessage, True)
myconn.Close()
return
else
myreder.Read()
' no need to check if id is equal, you pass it as parameter to a where clause'
If myreader.Item("password") = CurrPass.Text Then
'some code if the user input is valid '
Else
errorPassID.Visible = True
' or error message '
End If
End If
myconn.Close()
Catch ex As Exception
Dim ErrorMessage As String = "alert('" & ex.Message.ToString() & "');"
Page.ClientScript.RegisterStartupScript(Me.GetType(), "ErrorAlert", ErrorMessage, True)
myconn.Close()
End Try
Note also that passing a clear text password along the wire is a serious security hole. I hope you have stored an hash of the password and check on that instead.
By the way, why don't pass also the password hash in the query? Somthing like this:
Dim stquery As String = "SELECT * from accountstbl WHERE user_ID = #id AND password = #pwd"
In this way, if you have a record returned the user is validated and your client side code will be simple

Compare values from data source to string

I'm just stumped on what to do with this code, I'm just trying to implement a 'no duplicates' catch on my insert customer form, but it just slips through my if statement to the else everytime. This is the source. Also I tried a .Equals with the same results :(
Protected Sub srcAllClients_Inserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceCommandEventArgs) Handles srcAllClients.Inserting
'Establish Variables
Dim emailAddress As String
Dim srcUsers As SqlDataSource = New SqlDataSource()
srcUsers.ConnectionString = ConfigurationManager.ConnectionStrings("ISSD21ConnectionString").ConnectionString
Dim view As DataView
view = DirectCast(srcUsers.Select(DataSourceSelectArguments.Empty), DataView)
srcUsers.SelectCommand = "SELECT EmailAddress FROM ISSDClients"
srcUsers.DataSourceMode = SqlDataSourceMode.DataReader
Dim reader As IDataReader
reader = DirectCast(srcUsers.Select(DataSourceSelectArguments.Empty), IDataReader)
emailAddress = FormView1.FindControl("txtEmail").ToString
While reader.Read()
If reader("EmailAddress") = (emailAddress) Then
lblError.Text = "Your Email is NOT Unique!"
'this is where we cancel the update and return an error
Else
lblError.Text = "Your Email is Unique!"
'nothing needs to happen, maybe just tell them that it went through
End If
End While
reader.Close()
End Sub
emailAddress = FormView1.FindControl("txtEmail").ToString
is just going to return the string "System.Web.UI.WebControls.TextBox". You're not accessing the actual property of the control that would hold the text value, you're just calling ToString() on the control itself.
Try this:
Dim emailBox As TextBox = CType(FormView1.FindControl("txtEmail"), TextBox);
emailAddress = emailBox.Text
In addition to Womp's answer...
In the while loop that is running through the email records, you need to break out of the loop once you find a matching email and alert the user.
if reader("EmailAddress") = (emailAddress) then
'1. Break from the Loop
End if
I would recommend that you pass the emailAddress to the SQL Server as a parameter.
Select Count(EmailAddress) From ISSDClients
Where EmailAddress = #EmailAddress
Execute this statement using ExecuteScalar and cast the result as an integer. If the result is zero then you are ok, otherwise display an error.
Doing it this way avoids using the while loop and should be much quicker if your table has lots of rows.
You also need to get the Text property from the Email Text box.
emailAddress = FormView1.FindControl("txtEmail").Text.ToString
You may want to take a look at the String.Compare method, which will make it easier to compare without respect to things like case sensitivity and culture. It does consider whitespace to be part of your string, so you may wish to trim the string prior to calling it, to help normalize.
For example, the following strings would be considered equal:
var firstString = "some StrinG to Compare ";
var secondString = " somE string to COMPARE";
var equal = (String.Compare(firstString.Trim(), secondString.Trim(), StringComparison.InvariantCultureIgnoreCase) == 0);

Resources