Passing array into table - asp.net

I'm creating multiple choice question system.
So far i create these 4 tables and 1 view.
The tables are tblQuestion, tblAnswer, tblQuiz, tblResult and tblResultDetail.
tblQuestion is to store the questions, tblAnswer to store the answers of the question,tblResult is to record for every user that answers the quiz, and store the users answers in TblResultDetails.
Based on the code below, the data is read from view. (questiondr.Read). I use 1 , 2 , 3, 4 as it is the column name of the view. I did this to randomize the answers.
Dim MyArray(3) As String
Dim commd As New SqlCommand("Select * From view_Question Where =QuestionID=#IdQuestion", conn)
commd.Parameters.AddWithValue("#IdQuestion", count)
Dim questiondr As SqlDataReader
questiondr = commd.ExecuteReader
If questiondr.Read() Then
Me.lblTitle.Text = questiondr("txtQuestion")
Me.ansrb1.Text = questiondr("1")
MyArray(0) = questiondr("1")
Me.ansrb2.Text = questiondr("2")
MyArray(1) = questiondr("2")
Me.ansrb3.Text = questiondr("3")
MyArray(2) = questiondr("3")
Me.ansrb4.Text = questiondr("4")
MyArray(3) = questiondr("4")
Dim userAns As String
If Me.ansrb1.Checked = True Then
userAns = MyArray(0)
ElseIf Me.ansrb2.Checked = True Then
answerId = MyArray(1)
ElseIf Me.ansrb3.Checked = True Then
userAns = MyArray(2)
ElseIf Me.ansrb4.Checked = True Then
userAns = MyArray(3)
End If
End If
conn.Close()
End Sub
And the problem is, how to pass the users answers into table tblResultDetails?

Supposing that tblResultDetails contains a field for the userid, a field for the questionid and a field for the answer given by that particular user to that particular question then you need something like this
Dim cmdText = "INSERT INTO tblResultDetails VALUES (#userid, #questionid, #answerid)"
Dim cmd = new SqlCommand(cmdText, connection)
cmd.Parameters.AddWithValue("#userid", yourCurrentUserIDValue)
cmd.Parameters.AddWithValue("#questionid", yourCurrentQuestionIDValue)
cmd.Parameters.AddWithValue("#answerid", userAns)
cmd.ExecuteNonQuery()
As you can see it is pretty straightforward if you have stored somewhere the two missing informations (userid and questionid)

Related

How can I calculate number of days between 2 dates?

I have a reservation page and a reservation table which contains reservationstart column, reservationend column and numofdays column.
I have determined the number of days between the two dates which a client will select but nothing was stored in the table when I update.
The data type of numofdays was datatime but I have changed this to int.
I used this first, to declare the start and end date:
DayPilotScheduler1.Scale = TimeScale.Manual
Dim start As New Date(Date.Today.Year, 1, 1, 12, 0, 0)
Dim [end] As Date = start.AddYears(1)
This is the code for the update:
Protected Sub DayPilotScheduler1_EventMove(ByVal sender As Object, ByVal e As DayPilot.Web.Ui.Events.EventMoveEventArgs)
Dim id_Renamed As String = e.Value
Dim start As Date = e.NewStart
Dim [end] As Date = e.NewEnd
Dim resource As String = e.NewResource
Dim message As String = Nothing
If Not dbIsFree(id_Renamed, start, [end], resource) Then
message = "The reservation cannot overlap with an existing reservation."
ElseIf e.OldEnd <= Date.Today Then
message = "This reservation cannot be changed anymore."
ElseIf e.OldStart < Date.Today Then
If e.OldResource <> e.NewResource Then
message = "The room cannot be changed anymore."
Else
message = "The reservation start cannot be changed anymore."
End If
ElseIf e.NewStart < Date.Today Then
message = "The reservation cannot be moved to the past."
Else
dbUpdateEvent(id_Renamed, start, [end], resource)
'message = "Reservation moved.";
End If
LoadResourcesAndEvents()
DayPilotScheduler1.UpdateWithMessage(message)
End Sub
Private Sub dbUpdateEvent(ByVal id As String, ByVal start As Date, ByVal [end] As Date, ByVal resource As String)
Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("connectionStringLocal").ConnectionString)
con.Open()
Dim numOfDay As Integer = CInt(([end] - start).TotalDays())
Dim cmd As New SqlCommand("UPDATE [Reservation] SET ReservationStart = #start, ReservationEnd = #end, RoomId = #resource,numofday=#numofday WHERE ReservationId = #id", con)
cmd.Parameters.AddWithValue("id", id)
cmd.Parameters.AddWithValue("start", start)
cmd.Parameters.AddWithValue("end", [end])
cmd.Parameters.AddWithValue("resource", resource)
cmd.Parameters.Add("numofday", SqlDbType.Int).Value = numOfDay
cmd.ExecuteNonQuery()
End Using
End Sub
Screenshot of database table structure:
Math.floor(Math.abs(new Date(timestringone) - new Date(timestringtwo))/(1000*60*60*24))
Simply subtracting the dates returns the time in Milliseconds inbetween them. If the first time was before the second time the value is negative, so i used Math.abs to make it absolute. Then we divide trough 1000Milliseconds=1second, 60seconds=1minute, 60minutes=1hour, 24hours=1 day, and floor it to whole days. Requires two valid timestrings (timestringone and timestringtwo) to be given.
This is a javascript solution as youve included the js tag...
I am not sure about the VB.Net but you can easily accomplished it in C# using an object of Type "TimeSpan". For example: let's assume that we want to know the number of days between the start and end. values for the DateTime Type and show it in a Console window, then I may write something like:
DateTime start=DateTime.MinValue;
DateTime end=DateTime.MaxValue;
TimeSpan span=end-start;
Console.WriteLine( "There're {0} days between {1} and {2}" , span.TotalDays, start.ToString(), end.ToString() );
OP is having problems using the .Days property on the TimeSpan structure. I think this may help:
Dim numOfDay As Integer = CInt(([end] - start).TotalDays())
The output is:
365
Moving onto the use of your parameters, I think you would benefit from using .Add and specifying the data type:
cmd.Parameters.Add("#id", SqlDbType.Int).Value = id
cmd.Parameters.Add("#start", SqlDbType.Date).Value = start
cmd.Parameters.Add("#end", SqlDbType.Date).Value = [end]
cmd.Parameters.Add("#resource", SqlDbType.Int).Value = CInt(resource)
cmd.Parameters.Add("#numofday", SqlDbType.Int).Value = numOfDay
Note that you may have to change the SqlDbType. I've taken an assumption.
I would also implement Using for both the SqlConnection and SqlCommand. This for me is just good practice and the code does read better. I would also use the .Add overload for all parameters.
Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("connectionStringLocal").ConnectionString),
cmd As New SqlCommand("UPDATE [Reservation] SET ReservationStart = #start, ReservationEnd = #end, RoomId = #resource, numofday = #numofday WHERE ReservationId = #id", con)
con.Open()
cmd.Parameters.Add("#id", SqlDbType.Int).Value = id
cmd.Parameters.Add("#start", SqlDbType.Date).Value = start
cmd.Parameters.Add("#end", SqlDbType.Date).Value = [end]
cmd.Parameters.Add("#resource", SqlDbType.Int).Value = CInt(resource)
cmd.Parameters.Add("#numofday", SqlDbType.Int).Value = CInt(([end] - start).TotalDays())
Dim rowsAffected As Integer = cmd.ExecuteNonQuery()
If rowsAffected = 0 Then
'nothing updated
Else
'something updated
End If
End Using

Validate that textbox has numeric value in vb.net and compare value with database

enter image description hereI'm trying to validate a textbox where users will put an ID. The ID has to be numeric and at the same time compare to a valid ID in the database. When I was just validating for numeric, I didn't have any problems. But now that I have two conditions, my code doesn't work properly. Whenever I type in letters in the textbox and click a button, it gives me an error. The boolean is throwing me off lol. Below is my code:
Thank you in advance.
Protected Sub btnGo_Click(sender As Object, e As EventArgs) Handles btnGo.Click
Dim dt As DataTable
Dim dr As DataRow
Dim Conn As New SqlConnection("Data Source=Computer;Initial Catalog=Catalog;Persist Security Info=True;User ID=userid;Password=password")
Dim cmd As New SqlCommand("SELECT COUNT(*) FROM [tbl] WHERE [ID]=#Value", Conn)
cmd.Parameters.Add("#Value", SqlDbType.NVarChar).Value = txtId.Text
Conn.Open()
Dim valueExistsInDB As Boolean = CBool(CInt(cmd.ExecuteScalar()) > 0)
Conn.Close()
If (IsNumeric(txtId.Text)) AndAlso valueExistsInDB = True AndAlso txtId.Text IsNot Nothing Then
dt = GetDataTable("SELECT ID, LEFT(SANZ_ID, PATINDEX('%.%', SANZ_ID) -1) AS City, CASE WHEN ST_DIR_ID = 1 THEN 'NB' WHEN ST_DIR_ID = 2 THEN 'SB' WHEN ST_DIR_ID = 3 THEN 'EB' WHEN ST_DIR_ID = 4 THEN 'WB' END AS ST_DIR, STREET_OF_TRAVEL, CROSS_STREET, (SELECT TOP 1 CASE WHEN STATUS_ID = 1 THEN 'F' WHEN STATUS_ID = 2 THEN 'P' WHEN STATUS_ID = 3 THEN 'I' WHEN STATUS_ID = 4 THEN 'N' WHEN STATUS_ID = 5 THEN 'A' END FROM tbl where dbo.tbl.ID=ID) AS STATUS FROM tbl WHERE ID=" & txtId.Text)
dr = dt.Rows(0)
labelStreet.Text = dr("street_of_travel")
labelCrossStreet.Text = dr("cross_street")
labelCity.Text = dr("city")
labelDir.Text = dr("st_dir")
labelAda.Text = dr("STATUS")
'dropdownStatus.SelectedValue=
dropdownStatus.Visible = True
txtNotes.Visible = True
btnSave.Visible = True
Else
MessageBox.Show("ID not found! Please input a valid ID.")
End If
End Sub
If ID is a numeric field then you should pass a numeric parameter not an NVarChar one
' First try to convert the input text to an integer '
' this should be done here before acting on the db '
Dim id As Integer
if Not Int32.TryParse(txtId.Text, id) Then
MessageBox.Show("Error, not a valid number")
return
End If
Dim cmdText = "SELECT COUNT(*) FROM [tbl] WHERE [ID]=#Value"
Using Conn = New SqlConnection(....)
Using cmd As New SqlCommand(cmdText, Conn)
cmd.Parameters.Add("#Value", SqlDbType.Int).Value = id
Conn.Open()
Dim valueExistsInDB = CBool(CInt(cmd.ExecuteScalar()) > 0)
' At this point you don't need anymore to check if the input value'
' is numeric and your if is more simple.....'
if valueExistsInDB Then
......
... continue with your code ....
Else
MessageBox.Show("ID not found! Please input a valid ID.")
End if
End Using
End Using

Populate List box with LDAP cn and name from a specific group

I'm having some trouble figuring this out and this is what I'm trying to do. I'm trying to populate a list box with the "name" as the text displayed and the "cn" as the value from a specific group in Active Directory. My code is below and it's not throwing any errors it's just not populating the list box with anything. My guess is I'm not adding each result properly but I'm stumped.
Dim search As DirectorySearcher = New DirectorySearcher(entry)
search.PropertiesToLoad.Add("cn")
search.PropertiesToLoad.Add("name")
search.PropertiesToLoad.Add("memberOf")
search.Filter = "(memberOf=SAO Computer Grp)"
Dim result As SearchResultCollection = search.FindAll()
Dim ct As Integer = result.Count
For i = 0 To ct
lstEmail.DataTextField = result.PropertiesLoaded("name")
lstEmail.DataValueField = result.PropertiesLoaded("cn")
lstEmail.DataSource = result.Item(i)
lstEmail.DataBind()
Next
Try the following:
Dim search As DirectorySearcher = New DirectorySearcher(entry)
search.PropertiesToLoad.Add("cn")
search.PropertiesToLoad.Add("name")
search.PropertiesToLoad.Add("memberOf")
search.Filter = "(memberOf=SAO Computer Grp))"
Dim result As SearchResultCollection = search.FindAll()
Dim de As DirectoryEntry
Dim firstName, lastName As String
For Each ADUsers As SearchResult In result
de = ADUsers.GetDirectoryEntry()
firstName = "NA"
lastName = "NA"
If de.Properties("name") IsNot Nothing
AndAlso de.Properties("name").Count > 0 Then
firstName = de.Properties("name")(0).ToString()
End If
If de.Properties("cn") IsNot Nothing
AndAlso de.Properties("cn").Count > 0 Then
lastName = de.Properties("cn")(0).ToString()
End If
lstEmail.Items.Add(New ListItem(firstName, lastName))
Next

Conversion failed when converting the varchar value 'table' to data type int

I'm creating multiple choice question system. So far i create these 4 tables and 1 view.
The tables are tblQuestion, tblAnswer, tblQuiz, tblResult and tblResultDetail. tblQuestion is to store the questions, tblAnswer to store the answers of the question,tblResult is to record for every user that answers the quiz, and store the users answers in TblResultDetails.
Based on the code below, the data is read from view. I use 1 , 2 , 3, 4 as it is the column name of the view. I did this to randomize the answers.
Sub soalan()
conn.Open()
Dim myArr(3) As String
Dim cmd As New SqlCommand("Select * From view_Soalan Where QuestionID=#IdSoalan", conn)
cmd.Parameters.AddWithValue("#IdSoalan", Counter)
Dim dr1 As SqlDataReader
dr1 = cmd.ExecuteReader
If dr1.Read() Then
Me.lblSoalan.Text = dr1("QuestionTxt")
Me.RadioButton1.Text = dr1("1")
myArr(0) = dr1("1")
Me.RadioButton2.Text = dr1("2")
myArr(1) = dr1("2")
Me.RadioButton3.Text = dr1("3")
myArr(2) = dr1("3")
Me.RadioButton4.Text = dr1("4")
myArr(3) = dr1("4")
Dim answerId As String
If Me.RadioButton1.Checked = True Then
answerId = dr1("1")
ElseIf Me.RadioButton2.Checked = True Then
answerId = dr1("2")
ElseIf Me.RadioButton3.Checked = True Then
answerId = dr1("3")
ElseIf Me.RadioButton4.Checked = True Then
answerId = dr1("4")
End If
'Dim jawapan As Integer = CInt(answerId)
Session("jaw") = answerId
Else
conn.Close()
Counter += 1
soalan()
End If
conn.Close()
End Sub
Sub bersih()
RadioButton1.Checked = False
RadioButton2.Checked = False
RadioButton3.Checked = False
RadioButton4.Checked = False
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
soalan()
End Sub
Sub masuk()
conn.Open()
Dim cmdGetId As New SqlCommand("Select MAX(ResultId) From TblResult", conn)
cmdGetId.ExecuteNonQuery()
Dim drBaca As SqlDataReader
drBaca = cmdGetId.ExecuteReader
While drBaca.Read
Dim maxID As Integer = drBaca(0)
Session("maximum") = maxID
End While
conn.Close()
conn.Open()
Dim cmdInsert As New SqlCommand("Insert into TblResultDetail (ResultDetail_Result_Id,ResultDetail_Answer_Id) values ('" & Session("maximum") & "','" & Session("jaw") & "')", conn)
cmdInsert.ExecuteNonQuery()
conn.Close()
End Sub
End Class
I got error
Conversion failed when converting the varchar value 'table' to data
type int.
at the cmdInsert command. I know that i cant insert the session("jaw") into table directly. So how to replace it?
In your query you are quoting integers:
... values ('" & Session("maximum") & "','"
Simply remove the quotes. Also you should user Parameters instead to prevent SQL Injection.
I.e.
Dim cmdInsert As New SqlCommand("Insert into TblResultDetail (ResultDetail_Result_Id,ResultDetail_Answer_Id) values (#max, #jaw)", conn)
cmdInsert.Parameters.AddWithValue("#max", Session("maximum"))
cmdInsert.Parameters.AddWithValue("#jaw", Session("jaw"))
I think that you have store in some of this fields a wrong value.
use this
Public Module MyExtensions
<System.Runtime.CompilerServices.Extension()> _
Public Function IsInteger(ByVal value As String) As Boolean
If String.IsNullOrEmpty(value) Then
Return False
Else
Return Integer.TryParse(value, Nothing)
End If
End Function
<System.Runtime.CompilerServices.Extension()> _
Public Function ToInteger(ByVal value As String) As Integer
If value.IsInteger() Then
Return Integer.Parse(value)
Else
Return 0
End If
End Function
End Module
and then
value.ToInteger() <-- returns 0 if it is not an integer
There is another error in your code. You should use ExecuteScalar instead of ExecuteNonQuery in the query that starts with
"Select MAX(ResultId)...."
Dim cmdGetId As New SqlCommand("Select MAX(ResultId) From TblResult", conn)
Dim maxID As Integer= cmdGetId.ExecuteScalar
Session("maximum") = maxID
ExecuteScalar is typically used when your query returns a single value.
ExecuteNonQuery is typically used for SQL statements without results (UPDATE, INSERT, etc.).
Refer this

The parameterized query '(#Physical_Address_Street varchar(50),#Physical_Address_Local va' expects the parameter '#Physical_Address_Street'

I am very very new to sql server and I am creating a webservice and with the code below I am getting the error above and I am wondering what it is I am doing wrong?
<WebMethod()> _
Public Function GetAddresses(ByVal skip As Integer, ByVal take As Integer) As FuelStop()
Dim resultList = New List(Of FuelStop)()
Using sqlCon As New SqlConnection()
sqlCon.ConnectionString = "Data Source=(local);Initial Catalog=DEV_DB;User ID=*****;Password=**********"
Dim command As New SqlCommand("SELECT * FROM Gas_Stations WHERE Location_Type = 1 AND [ Physical_Address_Street] = #Physical_Address_Street AND [ Physical_Address_Local] = #Physical_Address_Local AND [Physical_Address_State] = #Physical_Address_State AND [ Physical_Address_Zip] = #Physical_Address_Zip AND [ Phone_Number] = #Phone_Number")
command.Parameters.Add("#Physical_Address_Street", SqlDbType.VarChar, 50, "Physical_Address_Street")
command.Parameters.Add("#Physical_Address_Local", SqlDbType.VarChar, 50, "Physical_Address_Local")
command.Parameters.Add("#Physical_Address_State", SqlDbType.VarChar, 50, "Physical_Address_State")
command.Parameters.Add("#Physical_Address_Zip", SqlDbType.VarChar, 50, "Physical_Address_Zip")
command.Parameters.Add("#Phone_Number", SqlDbType.VarChar, 50, "Phone_Number")
command.Connection = sqlCon
sqlCon.Open()
Using reader = command.ExecuteReader()
While reader.Read()
Dim addr = New FuelStop()
addr.Physical_Address_Street = reader.GetString(0)
addr.Physical_Address_Local = reader.GetString(1)
addr.Physical_Address_State = reader.GetString(2)
addr.Physical_Address_Zip = reader.GetString(3)
addr.Phone_Number = reader.GetString(4)
resultList.Add(addr)
End While
End Using
End Using
Return resultList.Skip(skip).Take(take).ToArray()
End Function
I am looking to just pull values for the columns listed in the query straight from the database. I need all the address info for display in a android app. This would be a read only situation.
The column names in your database probably don't start with spaces, so...
Dim command As New SqlCommand("SELECT * FROM Gas_Stations WHERE Location_Type = 1 AND [Physical_Address_Street] = #Physical_Address_Street AND [Physical_Address_Local] = #Physical_Address_Local AND [Physical_Address_State] = #Physical_Address_State AND [Physical_Address_Zip] = #Physical_Address_Zip AND [Phone_Number] = #Phone_Number")
But you can make it easier to read by taking advantage of VB.NET XML literals:
Dim sql = <sql>
SELECT
[Physical_Address_Street]
, [Physical_Address_Local]
, [Physical_Address_State]
, [Physical_Address_Zip]
, [Phone_Number]
FROM Gas_Stations
WHERE Location_Type = 1
AND [Physical_Address_Street] = #Physical_Address_Street
AND [Physical_Address_Local] = #Physical_Address_Local
AND [Physical_Address_State] = #Physical_Address_State
AND [Physical_Address_Zip] = #Physical_Address_Zip
AND [Phone_Number] = #Phone_Number
</sql>
Dim command As New SqlCommand()
command.CommandText = CStr(sql)
Please note that I explicity named the columns to select. This is to make sure that the columns you want back are the columns you get and in the order you want them.
As to the expected parameter error message, you have not assigned a value to any of the parameters. You can do that like this:
command.Parameters.Add("#Physical_Address_Street", SqlDbType.VarChar, 50).Value = physAddrStreet
or like this:
command.Parameters.Add("#Physical_Address_Street", SqlDbType.VarChar, 50)
command.Parameters("#Physical_Address_Street").Value = physAddrStreet
EDIT: as you don't need all those parameters,
Dim sql = <sql>
SELECT
[Physical_Address_Street]
, [Physical_Address_Local]
, [Physical_Address_State]
, [Physical_Address_Zip]
, [Phone_Number]
FROM Gas_Stations
WHERE Location_Type = 1
</sql>
and don't do all the command.Parameters.Add(...).
Looking at your query above, it appears you want to display a dynamic set of properties (sometimes Street, sometimes Zip code, etc.) for a fixed location type.
Parameterized queries within SQL Server are designed to work with input parameters, not with columns you want to see in the results.
If you are truly looking to have a dynamic column set in the results, then check out this question on how to do this.
If instead, you are looking for the user to input the address, zip, etc. for the query, then you have your query slightly backwards. It should look like this:
Dim command As New SqlCommand
("SELECT * FROM Gas_Stations
WHERE Location_Type = 1
AND
Physical_Address_Street = #Physical_Address_Street
AND
Physical_Address_Local = #Physical_Address_Local
AND
Physical_Address_State = #Physical_Address_State
AND
Physical_Address_Zip = #Physical_Address_Zip
AND
Phone_Number = #Phone_Number
)
Note: You'll want to clean up your formatting above for VB.Net, I just did it this way for more readability. There are also other questions out there if you want to make those fields optionally searchable

Resources