I trying to figure out why my code in inserting two records into the database when it executes? the CreateEnrollment Sub executes fine, however the results insert 2 sometimes 3 records ranging from 1-10 seconds apart, depending on remote server load. I first thought it might be the IsPostBack problem but adding the If Not Page.IsPostBack Then did not resolve.
Dim FailedMessage As String = "This COPDI (On-Line) user failed: "
Dim PassedMessage As String = "This COPDI (On-Line) user passes: "
Dim ClassName As String = "COPDI (FAILED)"
Dim SendMailAddress As String = "myEmailAddress.com"
Dim SubsiteConnString As String = "Subsite_appSettings"
Dim MainsiteConnString As String = "SubsiteConn"
Dim RecordsReturned As Integer = 0
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim UserName As String = User.Identity.Name()
Dim userID As Integer = GetUID(UserName)
Dim ClassDate As Date = DateTime.Now.AddHours(3).ToShortDateString
Dim ClassTime As String = DateTime.Now.AddHours(3). ToShortTimeString
If Not Page.IsPostBack Then
If Request.QueryString("code") = 1111 Then
RecordsReturned = RecordExist(UserName)
CreateEnrollment(UserName, ClassDate, ClassTime, ClassName, userID)
UpdateLastActivityDate(UserName)
If RecordsReturned < 3 Then
Response.Redirect("~/transcript.aspx" & "?code=" & RecordsReturned)
Else
Response.Redirect("~/transcript.aspx" & "?code=" & "more_than_three")
End If
End If
End If
End Sub
Public Sub CreateEnrollment(ByVal UserName As String, ByVal ClassDate As Date, ByVal ClassTime As String, ByVal ClassName As String, ByVal UID As Integer)
Dim connStr As String = ConfigurationManager.AppSettings.Get(SubsiteConnString)
Dim conn As New Data.OleDb.OleDbConnection(connStr)
Try
conn.Open()
Dim sql As String = "INSERT INTO EnrollmentsTbl (" & _
"[UserName],[SubmitTime],[ClassTime],[ClassDate],[Enrolled],[ClassName],[Instructor],[DateCompleted],[Completed],[WaitListed],[UID]) " & _
"VALUES (#UserName, #SubmitTime, #ClassTime, #ClassDate, #Enrolled, #ClassName, #Instructor, #DateCompleted, #Completed, #WaitListed, #UID) "
Dim comm As New Data.OleDb.OleDbCommand(sql, conn)
comm.Parameters.AddWithValue("#UserName", UserName)
comm.Parameters.AddWithValue("#SubmitTime", DateTime.Now.AddHours(3).ToString())
comm.Parameters.AddWithValue("#ClassTime", ClassTime)
comm.Parameters.AddWithValue("#ClassDate", ClassDate)
comm.Parameters.AddWithValue("#Enrolled", True)
comm.Parameters.AddWithValue("#ClassName", ClassName)
comm.Parameters.AddWithValue("#Instructor", "On-line")
comm.Parameters.AddWithValue("#DateCompleted", DateTime.Now.AddHours(3).ToString)
comm.Parameters.AddWithValue("#Completed", False)
comm.Parameters.AddWithValue("#WaitListed", False)
comm.Parameters.AddWithValue("#UID", UID)
Dim result As Integer = comm.ExecuteNonQuery()
Catch ex As Exception
Response.Write(ex)
Finally
conn.Close()
End Try
End Sub
Public Function RecordExist(ByVal username As String) As Integer
Dim connStr As String = ConfigurationManager.AppSettings.Get(SubsiteConnString)
Dim conn As New Data.OleDb.OleDbConnection(connStr)
Dim sql As String = "SELECT COUNT(*) FROM EnrollmentsTbl " & _
"WHERE [UserName] = """ & username & """ AND ClassName LIKE """ & ClassName & """ AND [Completed] = 0 AND [Enrolled] = -1"
Dim DBCommand As New Data.OleDb.OleDbCommand(sql, conn)
Try
conn.Open()
Dim RecordCount As Integer = CInt(DBCommand.ExecuteScalar())
conn.Close()
Return RecordCount
Catch ex As Exception
Response.Write(ex)
Finally
conn.Close()
End Try
End Function
Public Function GetUID(ByVal username As String) As Integer
Dim xUserName As String = User.Identity.Name()
If (Not xUserName="") Then
Dim objConn As Data.OleDb.OleDbConnection
Dim objCmd As Data.OleDb.OleDbCommand
Dim objRdr As Data.OleDb.OleDbDataReader
Dim userAN As String
Dim strConnection As String = ConfigurationManager.ConnectionStrings("TechTrainingConn").ToString
objConn = New Data.OleDb.OleDbConnection(strConnection)
objCmd = New Data.OleDb.OleDbCommand("SELECT * FROM UsersDataTbl WHERE [UserName] = """ & xUserName & """", objConn)
Try
objConn.Open()
objRdr = objCmd.ExecuteReader()
While objRdr.Read()
userAN = objRdr.Item("UID")
End While
objRdr.Close()
objConn.Close()
Session("userID") = userAN
Return userAN
'Response.Write(Session("userAN") & " - " & xUserName)
Catch ex As Exception
Response.Write(ex)
Finally
objConn.Close()
End Try
End If
End Function
What aspx page is this supporting? I noticed you have a redirect to transcript.aspx, is this code for that page? If so that would explain the multiple page loads. Response.Redirect is not a postback so it's going to fall into recordReturned and CreateEnrollment methods again, especially if you are passing the &code=1111 in the URL querystring
Related
Here's my code:
Partial Class VideoPlayer
Inherits System.Web.UI.Page
Protected strFileName As String
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Dim con As New OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim vidID As Integer = Integer.Parse(Request.QueryString("ID"))
dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
dbSource = "Data Source = |DataDirectory|/webvideos.mdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
Dim strSQL As String = "SELECT * FROM Videos WHERE ID=" & vidID
strFileName = "videos/TrainingVideos/" & Eval("Filename")
con.Close()
End Sub
End Class
So when I run the code, it tells me it can't run Eval on my string. What am I missing?
Eval will work in your .aspx code with a DataBoundControl.
When in code-behind, you are setting up the connectionstring, sql query and other variables but you are not actually executing the query.
So your code should be something like below:
Dim con As New OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim vidID As Integer = Integer.Parse(Request.QueryString("ID"))
dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
dbSource = "Data Source = |DataDirectory|/webvideos.mdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
Dim strSQL As String = "SELECT * FROM Videos WHERE ID=" & vidID
//Create an OleDbCommand object.
//Pass in the SQL query and the OleDbConnection object
Dim cmd As OleDbCommand = New OleDbCommand(strSQL, con)
//Execute the command
Dim reader As OleDbDataReader = cmd.ExecuteReader
//Read the first record from the reader
reader.Read()
strFileName = "videos\TrainingVideos\" & reader(1)
con.Close()
First the most important, you are open for sql-injection here:
"SELECT * FROM Videos WHERE ID=" & vidID
Use sql-parameters instead.
You can use Eval only in a databinding context. So you need to call Me.DataBind before.
Me.DataBind()
Dim fileName = Me.Eval("Filename").ToString()
strFileName = System.IO.Path.Combine("videos/TrainingVideos", fileName)
However, i don't know what you're actually trying to achieve here. Why do you need it at all?
Global variable, forgot to add it up there.
Then access it directly.
Here is whats happening , If the user is logged in - this is called directly from Page_Load
Protected Sub EnterNewTransInDb()
Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("connstring").ConnectionString)
Dim comm As New SqlCommand("INSERT INTO tblRegisterRedirect (RegID , UserID, EventID, TimeStamp) VALUES (#RegID, #UserID, #EventID , getdate()) ;", conn)
Dim RegID As Guid
RegID = Guid.NewGuid()
Dim GIUDuserid As Guid
GIUDuserid = New Guid(HttpContext.Current.Request.Cookies("UserID").Value.ToString())
Dim GIUDevnetid As New Guid(HttpContext.Current.Request.QueryString("id").ToString())
comm.Parameters.AddWithValue("#RegID", RegID)
comm.Parameters.AddWithValue("#UserID", GIUDuserid)
comm.Parameters.AddWithValue("#EventID", GIUDevnetid)
Try
conn.Open()
Dim i As Integer = comm.ExecuteNonQuery()
conn.Close()
Catch ex As Exception
Dim errors As String = ex.ToString()
End Try
Dim URL As String = Request.QueryString("url").ToString()
Response.Redirect(URL + "?aid=854&rid=" + RegID.ToString())
End Sub
This works great, but if their not logged in , then they enter their log-in credentials - this happens on Button_Click event, in the click event I call this function EnterNewTransInDb() , When I run it this time , after logging in - SAME CODE , it throws an exception - Object reference is null - referring to the querystring
Protected Sub btnLogin_Click(sender As Object, e As System.EventArgs) Handles btnLogin.Click
'took out code SqlConnection onnection and SqlDataReader Code
dbCon.Open()
'If Email and PW are found
If dr.Read Then
Dim appCookie As New HttpCookie("UserID")
appCookie.Value = dr("GUID").ToString()
appCookie.Expires = DateTime.Now.AddDays(30)
HttpContext.Current.Response.Cookies.Add(appCookie)
Dim appCookie1 As New HttpCookie("UserName")
appCookie1.Value = dr("UserName").ToString
appCookie1.Expires = DateTime.Now.AddDays(30)
HttpContext.Current.Response.Cookies.Add(appCookie1)
Dim appCookie2 As New HttpCookie("UserEmail")
appCookie2.Value = txtEmail.Text.ToLower()
appCookie2.Expires = DateTime.Now.AddDays(30)
HttpContext.Current.Response.Cookies.Add(appCookie2)
Dim appCookie3 As New HttpCookie("Lat")
appCookie3.Value = dr("GeoLat").ToString()
appCookie3.Expires = DateTime.Now.AddDays(30)
HttpContext.Current.Response.Cookies.Add(appCookie3)
Dim appCookie4 As New HttpCookie("Long")
appCookie4.Value = dr("GeoLong").ToString()
appCookie4.Expires = DateTime.Now.AddDays(30)
HttpContext.Current.Response.Cookies.Add(appCookie4)
Dim appCookie5 As New HttpCookie("City")
appCookie5.Value = dr("City").ToString()
appCookie5.Expires = DateTime.Now.AddDays(30)
HttpContext.Current.Response.Cookies.Add(appCookie5)
Dim appCookie6 As New HttpCookie("State")
appCookie6.Value = dr("State").ToString
appCookie6.Expires = DateTime.Now.AddDays(30)
HttpContext.Current.Response.Cookies.Add(appCookie6)
HttpContext.Current.Response.Cookies("EO_Login").Expires = Now.AddDays(30)
HttpContext.Current.Response.Cookies("EO_Login")("EMail") = txtEmail.Text.ToLower()
Dim sUserData As String = HttpContext.Current.Server.HtmlEncode(HttpContext.Current.Request.Cookies("UserID").Value) & "|" & HttpContext.Current.Server.HtmlEncode(HttpContext.Current.Request.Cookies("UserName").Value) & "|" & HttpContext.Current.Server.HtmlEncode(HttpContext.Current.Request.Cookies("UserEmail").Value)
' Dim sUserData As String = "dbcf586f-82ac-4aef-8cd0-0809d20c70db|scott selby|scottselby#live.com"
Dim fat As FormsAuthenticationTicket = New FormsAuthenticationTicket(1, _
dr("UserName").ToString, DateTime.Now, _
DateTime.Now.AddDays(6), True, sUserData, _
FormsAuthentication.FormsCookiePath)
Dim encTicket As String = FormsAuthentication.Encrypt(fat)
HttpContext.Current.Response.Cookies.Add(New HttpCookie(FormsAuthentication.FormsCookieName, encTicket))
'If Email and Pw are not found
Else
dr.Close()
dbCon.Close()
End If
'Always do this
dr.Close()
sSql = "UPDATE eo_Users SET LastLogin=GETUTCDATE() WHERE GUID=#GUID; "
cmd = New SqlCommand(sSql, dbCon)
cmd.Parameters.AddWithValue("#GUID", HttpContext.Current.Session("UserID"))
cmd.ExecuteNonQuery()
dbCon.Close()
EnterNewTransInDb()
'Dim URL As String = Request.QueryString("url").ToString()
'Response.Redirect(URL + "?aid=854&rid=" + RegID.ToString())
End Sub
Assuming you only want this code to run if there is a valid QueryString, you could put a guard clause at the beginning of the method to simply check if QueryString is null and then perform some other action if this page is called without a QueryString.
Try setting the breakpoints before the call and make sure the variables are assigned values.
Have you tried putting a breakpoint on Dim URL As String = Request.QueryString("url").ToString() line in your code? Maybe you just need to evaluate first the querystring for the 'url' parameter, if it exists; before converting it to a string.
This is the code I try
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim ds As New DataSet
Dim strSQL As String = "SELECT * FROM Client WHERE UserName = '" & TextBox1.Text & "'"
Dim da As New OleDbDataAdapter(strSQL, con)
Try
con.Open()
Dim builder As New OleDbCommandBuilder(da)
da.Fill(da)
If ds.Tables.Count > 0 Then
MsgBox("exist")
Else
MsgBox("not exist")
End If
con.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
The ds.table.count its every time = 1 whatever the TextBox1.Text.
Thanks for helping me to Check if the string from a textBox exist in my access table.
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.
I am trying to insert an array into SQL with no luck. I get the string from a GPRS device that looks like this:
/WeightBridge.aspx?ReadeID=A1B5A0F5C4E4A1B5A0F5C4E4&TagID=45B6C56A90B645B6C56A90B6,A47B1256A45F0843,B49B1256A45F08FF,30 SEP 2010 21:33:59,I,&Custom=Vehicle Num
All I want to do is to split the TagID array and insert it with the rest of the string into a SQL table. The TagID array must inserted into the following colomns in the DB. TagID, TID, UserMemory, DateTime and Direction. After the insert I just give a response that the insert was successfull or failed. Thank you
My code this far:
Imports System.Data.Sql
Imports System.Data.SqlClient
Partial Class WeightBridge
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
insertValue()
End Sub
Private Sub insertValue()
Dim sqlConn As New SqlConnection
Dim strConnection As String
Dim MyTagID As String
Dim MyReaderID As String
Dim MyCustom As String
Dim MyTagArray As Array
Dim i As Integer
'Request TagID Array
MyTagID = Request("TagID")
If MyTagID.Length > 0 Then
'Response.Write(MyTagID)
'Split TagID Array
MyTagArray = Split(MyTagID, ",")
For i = 0 To UBound(MyTagArray) - 1
Next
End If
Try
strConnection = "My Connection String"
sqlConn = New SqlConnection(strConnection)
Dim InsertCommand As New SqlCommand("INSERT INTO WeightBridge(ReaderID, TagID, TID, UserMemory, DateTime, Direction, Custom) VALUES ( '" & Request("ReaderID") & "', '0','0','0','0','0', '" & Request("Custom") & "')", sqlConn)
sqlConn.Open()
InsertCommand.ExecuteNonQuery()
sqlConn.Close()
Catch ex As Exception
Response.Write("FailedNo")
End Try
Response.Write("Success")
End Sub
End Class
There is a comma at the end of your TagID QueryString.
Besides, have a look at following code:
Dim allCols() As String = Request("TagID").Split(","c)
Dim tagID As String = allCols(0)
Dim tID As String = allCols(1)
Dim usermemory As String = allCols(2)
Dim dateTime As String = allCols(3)
Dim direction As String = allCols(4)
'........
You should read this article because you are widely open for sql-injection attacks.