Insert array from query string into SQL 2005 - asp.net

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.

Related

Duplicate records created on page load vb.net

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

Cannot refer to an instance member of a class from a shared method

How you get a public shared function outside of a Protected Sub, use the values from within a protected sub to postBack to the same webpage. The postback reply works, but the query of the function fails at (Line 44 Char 17 "fqdom = dom & ".forest.local")
Imports System
Imports System.IO
Imports System.DirectoryServices
Imports System.DirectoryServices.AccountManagement
Imports System.DirectoryServices.ActiveDirectory
Partial Class _Default
Inherits System.Web.UI.Page
Dim dom As String
Dim Group1 As String
Dim Group2 As String
Dim usrname As String
Dim fqdom As String
Dim netdom As String
Private Function GetDataFromArrayList() As ArrayList
Dim DomainList As New ArrayList()
DomainList.Add(New ListItem("d1", "dom1"))
DomainList.Add(New ListItem("d2", "dom2"))
Return DomainList
End Function
Protected Sub Selection_Changed(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
For Each item As ListItem In GetDataFromArrayList()
DropDownList1.Items.Add(item)
Next
End If
End Sub
Public Shared Function GetGroups() As ArrayList
Dim groupList As New ArrayList()
Dim usrname As String
Dim fqdom As String
'Dim netdom As String
Dim groupCheck As String
fqdom = dom & ".forest.local"
Dim entry As System.DirectoryServices.DirectoryEntry
Dim searcher As System.DirectoryServices.DirectorySearcher
Dim result As System.DirectoryServices.SearchResult
Try
entry = New System.DirectoryServices.DirectoryEntry("LDAP://" & fqdom)
searcher = New DirectorySearcher()
searcher.SearchRoot = entry
searcher.Filter = "(samAccountName=" & usrname & ")"
searcher.PropertiesToLoad.Add("memberOf")
result = searcher.FindOne()
Dim groupCount As Integer = result.Properties("memberOf").Count
For groupCounter As Integer = 0 To groupCount - 1
groupCheck = CStr(result.Properties("memberOf")(groupCounter))
groupCheck = groupCheck.Remove(groupCheck.LastIndexOf(",CN="))
groupCheck = groupCheck.Replace("CN=", "")
groupList.Add(groupCheck)
Next groupCounter
Catch ex As Exception
End Try
Return groupList
End Function
Protected Sub Button1_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load
If IsPostBack Then
Dim name As Boolean = False
If Not TextBox1.Text = String.Empty Then
name = True
End If
If name = False Then
StatusLabel.Text = "Update Status: Please Enter Name"
ElseIf name = True Then
Group1 = "groupb1"
Group2 = "groupb2"
Try
form1.Visible = False
Dim groups As New ArrayList()
groups = GetGroups()
Dim group As String
For Each group In groups
'NameLabel.Text = group
If (group.Contains(Group1)) Then
Group1.Text = "User: " & usrname & " is in group1"
End If
If (group.Contains(Group2)) Then
Group1.Text = "User: " & usrname & " is in group2"
End If
Next
fqdn.Text = "Domain: " & dom & ".forest.local"
NameLabel.Text = "User: " & usrname
Catch ex As Exception
End Try
Else
StatusLabel.Text = "Upload status: Error Please Retry later"
End If
End If
End Sub
End Class
Remove the Shared keyword from the method, so replace
Public Shared Function GetGroups() As ArrayList
with
Public Function GetGroups() As ArrayList
You cannot use instance variables like dom from within a Shared method.
You could also make those fields Shared. But that's not a good idea in ASP.NET since it could cause locks and concurrency issues and every request shared the same values(even of different users).
It's also not necessary since you want to use that method from a page method(button-click), so you need an instance of the page anyway.
If you need to persist a value across postback you can use a different way like using ViewState, Session or a HiddenField.

Using Eval function in my code behind?

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.

use connectionstring from webconfig rather than dataset properties

I built a dataset using the wizzard and added a connection in there.
I now want to use a connection string which is defined in my web config instead of whats set in the dataset.
I have the following code (i've taken a lot of stuff out you don't need to see)
Partial Public Class downloaditems
Inherits System.Web.UI.Page
Private dtmboFeed As dsmbo.mboFeedDataTable
Private tamboFeed As New dsmboTableAdapters.mboFeedTableAdapter
Private itemCount As Integer = 0
Private changedItem As Boolean = False
Private headSource As String
Private footSource As String
Private sideSource As String
Private lastHead As String
Private lastFoot As String
Private lastSide As String
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
feedChecks()
If changedItem = True Then
If itemCount = "3" Then
savetodatabase(headSource, footSource, sideSource)
End If
End If
End Sub
Private Sub checkSite(ByVal URL As String, ByVal Type As String)
Dim request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create(URL)
request.UserAgent = ".NET Framework Test Client"
Dim response As System.Net.HttpWebResponse = request.GetResponse()
Dim sr As System.IO.StreamReader = New System.IO.StreamReader(response.GetResponseStream())
Dim sourcecode As String = sr.ReadToEnd()
Dim compareHead As Integer
Dim compareFoot As Integer
Dim compareSide As Integer
Select Case Type
Case "headSource"
headSource = sourcecode
compareHead = String.Compare(headSource, lastHead)
Case "footSource"
footSource = sourcecode
compareFoot = String.Compare(footSource, lastFoot)
Case "sideSource"
sideSource = sourcecode
compareSide = String.Compare(sideSource, lastSide)
End Select
If Not compareHead = "0" Then
changedItem = True
End If
If Not compareFoot = "0" Then
changedItem = True
End If
If Not compareSide = "0" Then
changedItem = True
End If
itemCount = itemCount + 1
End Sub
Private Sub feedChecks()
Dim lastImport As DateTime
dtmboFeed = New dsmbo.mboFeedDataTable
dtmboFeed = tamboFeed.GetCode()
For Each rFeed As dsmbo.mboFeedRow In dtmboFeed
lastImport = rFeed.LastImport
lastHead = rFeed.HeaderCode
lastFoot = rFeed.FooterCode
lastSide = rFeed.SideCode
Next
If lastImport > System.DateTime.Now.AddDays(1) Then
checkSite("http://www.xxx.me/sss/header.html", "headSource")
checkSite("http://www.xxx.me/sss/footer.html", "footSource")
checkSite("http://www.xxx.me/sss/sidenav.html", "sideSource")
Else
Exit Sub
End If
End Sub
Private Sub savetodatabase(ByVal HeaderCode As String, ByVal FooterCode As String, ByVal SideCode As String)
dtmboFeed = tamboFeed.GetData()
Dim rFeed As dsmbo.mboFeedRow
rFeed = dtmboFeed.NewmboFeedRow
rFeed.HeaderCode = HeaderCode
rFeed.FooterCode = FooterCode
rFeed.SideCode = SideCode
rFeed.LastImport = System.DateTime.Now
rFeed.Verified = "True"
dtmboFeed.AddmboFeedRow(rFeed)
tamboFeed.Update(dtmboFeed)
lblCode.Text = lblCode.Text & "All downloaded"
End Sub End Class
EDIT:
Heres my updated code below as requested. I'm getting an error saying
Error 53 Value of type 'String' cannot be converted to 'System.Data.SqlClient.SqlConnection'.
Code:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim constring As String
constring = ConfigurationManager.ConnectionStrings("ConnectString").ToString()
tamboFeed.Connection = constring
feedChecks()
If changedItem = True Then
If itemCount = "3" Then
savetodatabase(headSource, footSource, sideSource)
End If
End If
End Sub
You can get the connection string as
Dim constring as String
constring = ConfigurationManager.ConnectionStrings("YouconnectionStringNameinWebConfig").ConnectionString
Now first go to your DataSet Design View, Select the table,right click on tableAdapter and Change it's Connection modifier to Public ( see below picture ), now you can access adapter connection property in the codebehind.
tamboFeed.Connection = constring
See the below picture for changing access modifier.
Picture Reference: Link
Updated answer:
The problem is that you have placed you connection string in the AppSettings section in the webconfig, add your connection string to ConnectionString Section. See below code
<connectionStrings>
<add name="ConnectString" connectionString="data source=server;initial catalog=database;persist security info=False;user id=adsadasda;password=asdsadasd;packet size=4096" />
</connectionStrings>
tamboFeed.Connection is of type System.data.SqlClient.SqlConnection so cannot accept a string assignment. So long as the dataset connection modifier is set to Public, you can assign the connection string from the web.config in one line, as follows:
tamboFeed.Connection.ConnectionString = ConfigurationManager.ConnectionStrings("YouconnectionStringNameinWebConfig").ConnectionString

Using VariantType in ASP.net

Hoping for a quick answer here.
OK, since I do a lot of single value lookups from the DB, I created a function to handle the lookup for me. It's designed to get any type of data type (string, integer, date, ...).
It works when I want to retrieve a number, but gives me an error when I want a string (InvalidCastException trying to convert a string to an integer on the line: GetValue = DR(0)).
I can't do a ctype or directcast because the datatype is unknown and varies.
Haven't tested any other data types yet.
Code is below. I'd like to find out how to make this function work, or pointed to another function that will serve the same purpose.
Public Shared Function GetValue(Optional ByVal SQL As String = "", Optional ByVal FieldName As String = "", Optional ByVal TableName As String = "", Optional ByVal WhereClause As String = "") As VariantType?
Dim myConnection As SqlConnection
Dim myCommand As SqlCommand
Dim strSQL As New SQLStringBuilder
Dim DR As SqlDataReader
myConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("ConnAFRAMSSQL").ConnectionString)
strSQL.Add(SQL)
If FieldName > "" Then
strSQL.Add("SELECT " & FieldName)
End If
If TableName > "" Then
strSQL.Add("FROM " & TableName)
End If
If WhereClause > "" Then
strSQL.Add("WHERE " & WhereClause)
End If
myConnection.Open()
myCommand = New SqlCommand(strSQL.ToString, myConnection)
DR = myCommand.ExecuteReader()
If DR.HasRows Then
DR.Read()
GetValue = DR(0)
Else
GetValue = Nothing
End If
End Function
Thanks.
You may specify the System.Object (System.Object is the ultimate base class of all types) return type of your method.
Public Shared Function GetValue(Optional ByVal SQL As String = "", Optional ByVal FieldName As String = "", Optional ByVal TableName As String = "", Optional ByVal WhereClause As String = "") As Object
Dim myConnection As SqlConnection
....
Dim obj as Object=Nothing
If DR.Read()
obj=DR(0)
End If
DR.Close()
myConnection.Close()
return obj
End Function

Resources