Trouble getting date value - asp.net

I am modifying a webpage. Webpage is using visual basic and my database is a SQL database.
The webpage gives me the total Sick, Comp, and Vacation time off. Right now, I get the logon name of whoever's logged onto the computer, and I look up the EmployeeID in a tblEmployees so I can search tblTimeAvailable by the EmployeeID, and then add up the different times.
I want to also get the StartDate from tblEmployees so I can also search by anniversary date (after I calculate it from the Start Date). I'm getting an error "Value of type 'Integer' cannot be converted to 'Date' on the rvsd=command2.ExecuteNonQuery line. Here's my code:
Dim rve As Object
Dim rvsd As Date
Dim dt As Date = Today
'Get network login name (name only)
split = windowsLoginName.Split("\".ToCharArray)
vname = split(1)
'Get employeeid from table that matches login name
Dim Connection As String = "Data Source=WillSQL\ict2;Initial Catalog=timesql_testing;Integrated Security=SSPI"
Using con As New SqlConnection(Connection)
Dim sqlemp As String = "SELECT EmployeeID FROM tblEmployees where login = #loginname"
Dim sqlstdt As String = "SELECT StartDate FROM tblEmployees where login = #loginname"
Dim command As New SqlCommand(sqlemp, con)
Dim command2 As New SqlCommand(sqlstdt, con)
con.Open()
command.Parameters.Add(New SqlParameter With {.ParameterName = "#loginname", .SqlDbType = SqlDbType.NVarChar, .Value = vname})
command2.Parameters.Add(New SqlParameter With {.ParameterName = "#loginname", .SqlDbType = SqlDbType.NVarChar, .Value = vname})
rve = command.ExecuteScalar
rvsd = command2.ExecuteNonQuery
End Using
Dim theDateThisYear As Date
theDateThisYear = DateSerial(Year(Now), Month(rvsd), Day(rvsd))
If theDateThisYear < Now() Then
theDateThisYear = DateAdd("yyyy", 1, theDateThisYear)
End If
Dim NextAnniversary As Date = theDateThisYear
MsgBox(NextAnniversary)
'Get Sick Time - DOES NOT INCLUDE CHECKING TO MAKE SURE LESS THAN ANNIV DATE YET
Using con As New SqlConnection(Connection)
Dim sqls1 As String = "Select SUM(NoofHours) as Total from tblTimeAvailable where workcode = 1 and EmployeeID = #emp"
Dim command As New SqlCommand(sqls1, con)
con.Open()
command.Parameters.Add(New SqlParameter With {.ParameterName = "#emp", .SqlDbType = SqlDbType.NVarChar, .Value = rve})
rvsa = command.ExecuteScalar
End Using
Thanks in advance for any help you can give me!

Assuming that the column [StartDate] in the database has a type of DateTime then all you need to do is
rvsd = CDate(command2.ExecuteScalar)
Although you could have retrieved both values with one query:
SELECT [EmployeeID], [StartDate] FROM [tblEmployees] where [login] = #loginname"
and so
Dim rve As String
Dim rvsd As Date
Dim connStr As String = "Data Source=WillSQL\ict2;Initial Catalog=timesql_testing;Integrated Security=SSPI"
Dim sql = "SELECT [EmployeeID], [StartDate] FROM [tblEmployees] where [login] = #loginname"
Using conn As New SqlConnection(connStr)
Using cmd As New SqlCommand(Sql, conn)
cmd.Parameters.Add(New SqlParameter With {.ParameterName = "#loginname", .SqlDbType = SqlDbType.NVarChar, .Value = vname})
conn.Open()
Dim rdr = cmd.ExecuteReader()
If rdr.HasRows Then
rdr.Read()
rve = rdr.GetString(0)
rvsd = rdr.GetDateTime(1)
End If
End Using
End Using

Related

How to store a value from a database as a variable with VB.net

I am trying to store DoctorId from the patient table as a variable that I can then add to an insert statement (to be inserted into the Order_pres table). I am also trying to do this with PharmacyId from the pharmacy table.
The pharmacy name displays on the dropdown, however I dont know how to store the PharmacyId, as shown below:
<asp:SqlDataSource ID="SqlPharm" runat="server" ConnectionString="<%$ ConnectionStrings:SurgeryConnectionString %>" SelectCommand="SELECT DISTINCT Pharmname FROM Pharmacy "></asp:SqlDataSource>
<asp:DropDownList ID="DropPharm" runat="server" DataSourceID="SqlPharm" DataTextField="Pharmname" DataValueField="Pharmname"></asp:DropDownList>
How I am storing my variables and adding Ids to the insert query
Protected Sub btnconfirm_Click(sender As Object, e As EventArgs) Handles btnconfirm.Click
' Dropdown for pharmacy someVariable = DropPharm.SelectedItem.Value
Dim PatientId As Integer = Session("PatientId")
Dim PharmacyId As Integer = Session("PharmacyId")
Dim MedicineId As Integer = Session("MedicineID")
Dim DateOrdered As Date
' Get DoctorId from the patient table
Dim DoctorId As Integer = "SELECT DoctorId FROM Patient "
'.Value = CInt(Session("DoctorId").ToString())
Dim query As String = String.Empty
query &= "INSERT INTO Order_pres (PatientId, PharmacyId, "
query &= " DoctorId, [Date Ordered]) "
query &= "VALUES (#PatientId,#MedicineId, #PharmacyId, #DoctorId, #DateOrdered)"
Dim sqlCs As String = ConfigurationManager.ConnectionStrings("SurgeryConnectionString").ConnectionString
Using conn As New SqlConnection(sqlCs),
comm As New SqlCommand(query, conn)
With comm.Parameters
.Add("#PatientId", SqlDbType.Int).Value = Session("PatientId")
.Add("#DoctorId", SqlDbType.Int).Value = Session("DoctorId")
.Add("#MedicineId", SqlDbType.Int).Value = Session("MedicineID")
.Add("#PharmacyId", SqlDbType.Int).Value = Session("PharmacyId")
.Add("#DateOrdered", SqlDbType.DateTime).Value = DateTime.Parse(DateOrdered)
End With
I have stored some of the sessions in the login.aspx page i.e when the user logs in:
Public Function CheckUser(username As String, password As String) As Integer
Dim cmdstring As String = "SELECT * FROM Patient Where Username=#USERNAME AND Password=#PASSWORD"
Dim found = 0
Using conn As New SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\surgerydb.mdf;Integrated Security=True;Integrated Security=True;Connect Timeout=30")
Dim cmd = New SqlCommand(cmdstring, conn)
cmd.Parameters.Add("#USERNAME", SqlDbType.NChar).Value = username
cmd.Parameters.Add("#PASSWORD", SqlDbType.NChar).Value = password
conn.Open()
Dim reader = cmd.ExecuteReader()
While reader.Read()
Session("PatientId") = CInt(reader.Item("PatientId"))
Session("Username") = CStr(reader.Item("Username"))
Session("DoctorId") = CStr(reader.Item("DoctorId"))
found = CInt(reader.Item("PatientId"))
End While
reader.Close()
End Using
Return (found)
End Function
enter code here
If I have been vague or any more information is needed a for the question is needed please let me know.
Kind regards :)

What's wrong with my Count Query asp.net

Public state_name as String
state_name = Textbox1.Text
Dim constr As String = ConfigurationManager.ConnectionStrings("ApplicationServices").ConnectionString
Dim query As String = "SELECT Count(cities) FROM state_table WHERE state_name=" & state_name
Using conn As New SqlConnection(constr)
Using comm As New SqlCommand()
conn.Open()
With comm
.Connection = conn
.CommandText = query
.CommandType = CommandType.Text
End With
Dim count As Int16 = Convert.ToInt16(comm.ExecuteScalar())
Label1.Text = count
End Using
End Using
The code shows an error
Invalid column name 'California'.
But California is already present in my State table, I want to count all the cities comes under state_name= california which I have entered in my State table.
I want the output as
California (3)
You want to use Parameterized Query to avoid SQL Injection.
Dim constr As String = ConfigurationManager.ConnectionStrings("ApplicationServices").ConnectionString
Dim query As String = "SELECT Count(cities) FROM state_table WHERE state_name=#State_Name"
Using conn As New SqlConnection(constr)
Using comm As New SqlCommand()
conn.Open()
With comm
.Connection = conn
.CommandText = query
.CommandType = CommandType.Text
.Parameters.AddWithValue("#State_Name", state_name)
End With
Dim count As Int16 = Convert.ToInt16(comm.ExecuteScalar())
Label1.Text = count
End Using
End Using
Because you didn't surround your variable with quotes. "state_name = '" + state_name + "'"
But, you should use a parameter instead.

Want DropDownlist value to get stored by ID

I am working on asp.net using VB and SQL database
I have two tables mst_Emp & mst_dept
mst_dept got following columns (dpt_ID(PK),dpt_name,dpt_descrip)
mst_Emp got following columns (Emp_ID,Emp_FirstName,Emp_LastName,Emp_Address,Emp_ContactNo,Dept_ID(Foreign key),Marital_Status,Gender)
Now I have a Employee Detail Form in that I have Department Name label(DataBind from mst_Dept) and I have DropDownList for that to select. If some choose value from DropDownList I want it to get stored by Dept_ID in database. How can I do that ?
Try binding your Department Dropdownlist like
Using sqlconn As New SqlConnection(ConfigurationManager.ConnectionStrings("Conn").ConnectionString)
If sqlconn.State = ConnectionState.Closed Then
sqlconn.Open()
End If
Dim ds As New DataSet()
Dim qry As String = "Select dpt_ID,dpt_name from mst_Dept"
Using cmd As New SqlCommand(qry, sqlconn)
Dim sda As New SqlDataAdapter(cmd)
sda.Fill(ds)
D_ddlDepartment.DataSource = ds
D_ddlDepartment.DataValueField = "dpt_ID"
D_ddlDepartment.DataTextField = "dpt_name"
D_ddlDepartment.DataBind()
D_ddlDepartment.Items.Insert(0, "-- Select Department --")
If sqlconn.State = ConnectionState.Open Then
sqlconn.Close()
End If
End Using
End Using
and you can access the Dept_id like
Dim Deptid As Integer = Convert.ToInt32(D_ddlDepartment.SelectedValue)
FINALLY GOT IT THANKS :-)
Dim ds As New DataSet
Dim cmd1 As SqlCommand = New SqlCommand()
Dim sqlconn As SqlConnection = New SqlConnection()
sqlconn.ConnectionString = "Data Source=PRGM\SQLEXPRESS;Initial Catalog=HRMS;Integrated Security=True"
sqlconn.Open()
cmd1 = New SqlCommand("select Dpt_ID,Dpt_Name from mst_Dept", sqlconn)
'Dim qry As String = "select Dpt_ID,Dpt_Name from mst_Dept"
'cmd1 As New SqlCommand(qry, sqlconn)
Dim sda As New SqlDataAdapter(cmd1)
sda.Fill(ds)
DropDownList1.DataSource = ds.Tables(0)
DropDownList1.DataValueField = ds.Tables(0).Columns("Dpt_ID").ColumnName
DropDownList1.DataTextField = ds.Tables(0).Columns("Dpt_Name").ColumnName
DropDownList1.DataBind()
DropDownList1.Items.Insert(0, "-- Select Department --")
sqlconn.Close()
End If

Invalid attempt to read when no data is present error

I have a function whose sole purpose is to fetch some data when a button is pressed and it's called multiple times. This is the function code:
Function GetData2(ByVal clientNo As Integer) As List(Of SocioInfo)
Dim theResults2 = New List(Of SocioInfo)
Dim connStr = "Data Source=localhost;Initial Catalog=testdb;Integrated Security=True;MultipleActiveResultSets=true"
Using conn = New SqlConnection(connStr)
Dim sql = "SELECT [FirstName], [LastName] FROM [CustInfo] Where ([NumCuenta] = #SocioNum)"
Dim sql2 = "SELECT [AcctName], [AcctNum], [NewAcct], [Balance] From [ACCT_NEW] Where ([AcctNum] = #SocioNum)"
Dim sqlCmd = New SqlCommand(sql, conn)
Dim sqlCmd2 = New SqlCommand(sql2, conn)
sqlCmd.Parameters.AddWithValue("#SocioNum", CDbl(txtInput.Text))
sqlCmd2.Parameters.AddWithValue("#SocioNum", CDbl(txtInput.Text))
conn.Open()
Dim rdr = sqlCmd.ExecuteReader
Dim rdr2 = sqlCmd2.ExecuteReader
While rdr.Read
theResults2.Add(New SocioInfo With {
.Nombre = rdr.GetString(0),
.LastName = rdr.GetString(1)
})
End While
While rdr2.Read
theResults2.Add(New SocioInfo With {
.CuentaName = rdr.GetString(0),
.AcctNum = rdr.GetValue(1),
.AcctFull = rdr2.GetValue(2),
.Balance = rdr2.GetValue(3)
})
End While
End Using
Return theResults2
End Function
I am not 100% sure if this is the best way to do this (basically need to get data from two different tables). Thing is, while Rdr shows me no error, Rdr2 just blows in the face. The exception is this:
Invalid attempt to read when no data is present.
In the second loop you are trying to use the first SqlDataReader but this is not possible because the first loop has already reached the end of the input data.
If you need joined data between the two tables a better approach is to use just one query using the JOIN operator. This query works assuming that each customer in the CustInfo table has one account in the ACCT_NEW table
Dim sql = "SELECT c.FirstName, c.LastName, a.AcctName, a.AcctNum, a.NewAcct, a.Balance " & _
"FROM CustInfo c INNER JOIN ACCT_NEW a ON a.AcctNum = c.NumCuenta " & _
"WHERE NumCuenta = #SocioNum "
Using conn = New SqlConnection(connStr)
Dim sqlCmd = New SqlCommand(sql, conn)
sqlCmd.Parameters.AddWithValue("#SocioNum", CDbl(txtInput.Text))
conn.Open()
Dim rdr = sqlCmd.ExecuteReader
While rdr.Read
theResults2.Add(New SocioInfo
With {
.Nombre = rdr.GetString(0),
.LastName = rdr.GetString(1)
.CuentaName = rdr.GetString(2),
.AcctNum = rdr.GetValue(3),
.AcctFull = rdr.GetValue(4),
.Balance = rdr.GetValue(5)
})
End While
End Using

ASP.NET/VB.NET/SQL Server 2012 - Page keeps loading

I'm trying to run this code, and whenever I press the 'Register' button, nothing is happening (the page is like loading but stays on the same page)
Code:
Public Sub register()
Dim Username As String = txtUsername.Text
Dim Surname As String = txtSurname.Text
Dim Password As String = txtPassword.Text
Dim Name As String = txtName.Text
Dim Address1 As String = txtAddress1.Text
Dim Address2 As String = txtAddress2.Text
Dim City As String = txtCity.Text
Dim Email As String = txtEmail.Text
Dim Country As String = drpCountry.Text
Dim DOB As Date = calDOB.SelectedDate
Dim Occupation As String = txtOccupation.Text
Dim WorkLocation As String = txtWorkLocation.Text
Dim Age As Integer = Date.Today.Year - calDOB.SelectedDate.Year
Dim ProjectManager As String = "N/A"
Dim TeamLeader As String = "N/A"
Dim TeamLeaderID As Integer = "1"
Dim ProjectManagerID As Integer = "1"
Dim RegistrationDate As Date = DateTime.Today
Dim ContractType As String = "N/A"
Dim ContractDuration As Integer = 6
Dim Department As String = "N/A"
Dim conn As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True")
Dim registerSQL As SqlCommand
Dim sqlComm As String
Dim validateSQL As SqlCommand
Dim sqlValidate As String
sqlValidate = "SELECT * FROM users where username=" + txtUsername.Text.ToString
sqlComm = "INSERT INTO users(Username, Password, Name, Surname, Address1, Address2, " +
"City, Country, date_of_birth, age, Occupation, department, work_location, " +
"project_manager,team_leader, team_leader_id, project_manager_id, " +
"date_registration, contract_type, contract_duration) " +
"VALUES(#p1, #p2,#p3,#p4,#p5,#p6,#p7,#p8,#p9,#p10,#p11,#p12,#p13,#p14,#p15," +
"#p16,#p17,#p18,#p19,#p20)"
conn.Open()
validateSQL = New SqlCommand(sqlValidate, conn)
Dim dr As SqlDataReader = validateSQL.ExecuteReader()
If dr.HasRows = False Then
validateSQL = New SqlCommand(sqlValidate, conn)
validateSQL.CommandText = sqlValidate
Dim reader As SqlDataReader = validateSQL.ExecuteReader()
reader.Read()
registerSQL = New SqlCommand(sqlComm, conn)
registerSQL.Parameters.AddWithValue("#p1", Username)
registerSQL.Parameters.AddWithValue("#p2", Password)
registerSQL.Parameters.AddWithValue("#p3", Name)
registerSQL.Parameters.AddWithValue("#p4", Surname)
registerSQL.Parameters.AddWithValue("#p5", Address1)
registerSQL.Parameters.AddWithValue("#p6", Address2)
registerSQL.Parameters.AddWithValue("#p7", City)
registerSQL.Parameters.AddWithValue("#p8", Country)
registerSQL.Parameters.AddWithValue("#p9", DOB)
registerSQL.Parameters.AddWithValue("#p10", Age)
registerSQL.Parameters.AddWithValue("#p11", Occupation)
registerSQL.Parameters.AddWithValue("#p12", Department)
registerSQL.Parameters.AddWithValue("#p13", WorkLocation)
registerSQL.Parameters.AddWithValue("#p14", ProjectManager)
registerSQL.Parameters.AddWithValue("#p15", TeamLeader)
registerSQL.Parameters.AddWithValue("#p16", TeamLeaderID)
registerSQL.Parameters.AddWithValue("#p17", ProjectManagerID)
registerSQL.Parameters.AddWithValue("#p18", RegistrationDate)
registerSQL.Parameters.AddWithValue("#p19", ContractType)
registerSQL.Parameters.AddWithValue("#p20", ContractDuration)
registerSQL.ExecuteNonQuery()
conn.Close()
ElseIf dr.HasRows = True Then
lblUsername.Text = "That Username (" + txtUsername.Text + ") is already registered/taken."
lblUsername.Visible = True
conn.Close()
End If
End Sub
Button event handler:
Protected Sub btnRegister_Click(sender As Object, e As EventArgs) Handles btnRegister.Click
register()
End Sub
Is something wrong with the code?
From MSDN
While the SqlDataReader is being used, the associated SqlConnection is
busy serving the SqlDataReader, and no other operations can be
performed on the SqlConnection other than closing it. This is the case
until the Close method of the SqlDataReader is called. For example,
you cannot retrieve output parameters until after you call Close.
It appears that you have the SqlDataReader open when you try to execute the insert command.
I will try to close it before using the insert command
If dr.HasRows = False Then
dr.Close()
' The following lines are probably a remainder of a copy/paste operation'
' They are not needed and you should remove them'
'validateSQL = New SqlCommand(sqlValidate, conn)'
'validateSQL.CommandText = sqlValidate'
'Dim reader As SqlDataReader = validateSQL.ExecuteReader()'
'reader.Read()'
' Now execute the insert command
Also your command to check for the user presence, apart from perfomance arguments, is wrong because introduces Sql Injection possibilities.
Summarizing try with these changes....
sqlValidate = "SELECT * FROM users where username=#uname"
validateSQL = New SqlCommand(sqlValidate, conn)
validateSQL.Parameters.AddWithValue("#uname", txtUserName.Text)
Dim dr As SqlDataReader = validateSQL.ExecuteReader()
Dim userFound = dr.HasRows
dr.Close()
if userFound = False then
......

Resources