Asp.net Button disable value from Sql field - sql

The title may not be the best description but i would like help with having the button be disabled depending on which user click on it.
I know I should put the connection string in the web.config and I will but I'm not getting this button to work.
The HasRows yest looks if there is a row but i might do this wrong.
I have 3 rows in the table and with only one row = 'reports' all 3 users can still click the Button?
Can anyone help me here?
Protected Sub LeftMenuBarReportsButton_Click(sender As Object, e As System.EventArgs) Handles LeftMenuBarReportsButton.Click
Dim sqlconn As New SqlConnection
Dim sqCmd As New SqlCommand
Dim sqlreader As SqlDataReader
sqlconn.ConnectionString = "server = ....;Database=......;User ID=......;Password=...." 'SQL Connection String
sqCmd.Connection = sqlconn
sqlconn.Open()
sqCmd.CommandText = "SELECT UserID,Password,Role FROM UserCredentials WHERE Role = 'Reports'"
sqlreader = sqCmd.ExecuteReader
If sqlreader.HasRows Then
Response.Redirect("Reports.aspx")
Else
Dim click As Button = sender
click.Enabled = False
LeftMenuBarReportsButton.BackColor = Drawing.Color.Red
LeftMenuBarReportsButton.Text = "Access Denied"
End If
sqlreader.Close()
sqlconn.Close()

Related

How to represent currently logged in user in vb.net

I am in desperate need of some help.
I'm using SQL Server and vb.net. On my personal info Windows form I'm trying to populate textboxes with user information based on the currently logged in user.
However I don't know how to represent the value of the current user. I'm trying to pass the value as a parameter. What should be put in place of: #idontknow ?
Code for form:
Private Sub PersonalInfo_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim connection As New SqlConnection("server=DESKTOP-PL1ATUA\DMV;Database=EHR;Integrated Security=True")
Dim dt As New DataTable
connection.Open()
Dim sqlcmd As New SqlCommand("SELECT * FROM PATIENT WHERE PATIENT_ID = #id", connection)
Dim sqlda As New SqlDataAdapter(sqlcmd)
Dim user_email As Object = Nothing
sqlcmd.Parameters.AddWithValue("#id", #idontknow)
Dim reader As SqlDataReader = sqlcmd.ExecuteReader()
While reader.Read()
fname.Text = reader("PATIENT_FNAME")
ComboBox1.Text = reader("patient_gender")
TextBox4.Text = reader("patient_street")
TextBox5.Text = reader("patient_city")
TextBox6.Text = reader("patient_state")
TextBox7.Text = reader("patient_zip")
TextBox8.Text = reader("patient_phone")
email.Text = reader("user_email")
End While
End Sub
Here I validate User credentials on a windows form by checking email and password, the primary key (patient_id) is generated upon insert when a new user registers (this code is on a separate form, which is not displayed below):
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connection As New SqlConnection("server=DESKTOP-PL1ATUA\DMV;Database=EHR;Integrated Security=True")
Dim command As New SqlCommand("select * from patient where user_email = #email and user_pass = #pass", connection)
command.Parameters.Add("#email", SqlDbType.VarChar).Value = email.Text
command.Parameters.Add("#pass", SqlDbType.VarChar).Value = pass.Text
Dim adapter As New SqlDataAdapter(command)
Dim table As New DataTable()
adapter.Fill(table)
If table.Rows.Count() <= 0 Then
MessageBox.Show(" Username or Password are Invalid")
Else
MessageBox.Show("Login Successful")
command.CommandType = CommandType.StoredProcedure
dashboard.Show()
End If
End Sub
Your login code queries for a record from the patient table that has the appropriate username and password. Right now it looks like all you're doing is checking for the existence of such a record. What you want to do is take that record's patient_id and store it somewhere that you can refer back to from elsewhere in your code. This could be something as simple as a shared property somewhere. This question discusses a few options that might suit. For instance, a module:
Module CurrentUser
Public Property PatientId As Integer
End Module
Or a class that can't be instantiated:
NotInheritable Class CurrentUser
Private Sub New()
End Sub
Public Shared Property PatientId As Integer
End Class
Review the answers to the question linked above for a discussion of the differences between the two approaches. In either case, you'd assign the value of CurrentUser.PatientId in your login code and then access its value where you've written #idontknow.
One last thing: it looks like your login code is taking the contents of a password box somewhere and comparing it directly to the contents of the password field in your database, which strongly implies that you're storing passwords as plain text. This is not secure. Review this question for a thorough overview of how to store passwords securely.
Well, I'm not sure if you're looking for a logged user in Windows, then it's a string (not Integer) as follows:
Dim UserNameStr As String = Environment.UserName
Same applies to the SQL Server:
SELECT CURRENT_USER;
...it's a string too.

Login always fails in my Sql based visual basic simple login application

I tried to create a login page in VISUAL BASIC. But the problem is that the login always fails . My program is connected to my sql database and though my password and username is correct through text boxes the output is always login fail!! and I don't know where is screwed up .
Imports System.Data.SqlClient
Public Class login
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connection1 As New SqlConnection With {.ConnectionString = "Server = VAIOO-PC ; Database = forum ; Integrated Security= true "}
Dim sqlcommand As New SqlCommand(" Select * from username where username= #username and password =#password", connection1)
sqlcommand.Parameters.Add("#username", SqlDbType.VarChar).Value = textboxuser.Text
sqlcommand.Parameters.Add("#password", SqlDbType.VarChar).Value = textboxpassword.Text
Dim sqldtaadpt As New SqlDataAdapter(sqlcommand) 'passes the command to via the adapter
Dim table As New DataTable()
If table.Rows.Count() <= 0 Then
MsgBox("USERNAME or THE PASSWORD IS INCORRECT")
Else
MsgBox("login successful")
End If
End Sub
End Class
You forgot to fill the datatable.
Use Fill method of DataAdapter.
sqlcommand.Open()
sqldtaadpt.Fill(table)
To get a full example, look at SqlCommand class help.
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand(v=vs.110).aspx

Select commannd in Visual Basic not working properly

I am new to Visual Basic for Applications. I have a login system in my current program. You will understand the system by reading below. I have an Access database whose table looks like following :-
Name : Cookies
----------------------------
ID | Nme | Val |
----------------------------
The table is cleared and all the contents of it is deleted when the form is closed. Now, when a user signs in, a row is added :-
----------------------------
(id) | "user" | username |
----------------------------
Now, the user enters his id and password in the form index.vb and the command to add the row in the access database is also there in the index.vb file. After the row is added, the index.vb file is hidden and the file userpage.vb is shown. Now, I have seen this that when the user logs in, the row is added properly in the access file (by refreshing the access file manually) and everything is deleted properly in the table when the window is closed. So, there is no problem in inserting and deletion of rows. So, obviously, the problem is with the displaying part. My code for displaying the username is as follows (the code is in the userpage.vb file) :-
Dim Username As String = ""
Dim Conn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Software\db.accdb")
Conn.Open()
Dim Cmd As New OleDb.OleDbCommand("Select Val From Cookies Where Nme='user'", Conn)
Dim Reader = Cmd.ExecuteReader
Do While Reader.Read
Username = Reader.Item("Val")
Loop
Label1.Text = "Welcome " & Username
Conn.Close()
The output that is given is "Welcome" and Username is "" even when the row has been added. Now, I have also seen this by experimenting that when I manually add a row in the access database with the same details that is going to be added in the database problematically, the program works fine. Any help, of course, will be appreciated and thanks for reading this long post.
UPDATE 1 ( as suggested by #Dimple)
My code for insertion is as follows(This code is in the index.vb page) :-
Dim usernameinput As String = TextBox1.Text
Dim Cmmd As New OleDb.OleDbCommand()
Cmmd.Connection = Conn
Cmmd.CommandText = "INSERT INTO Cookies (Nme, Val) Values('user','" & usernameinput & "')"
Cmmd.ExecuteNonQuery()
Dim Userpage As New User_page
Me.Hide()
Userpage.Show()
You said that Access displays row after manually refreshing Access file (database). Sometimes you need to Requery() the database after insertion. I had this problem while working with Access.
Form1
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim Conn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\db.accdb")
Conn.Open()
Dim usernameinput As String = "TextBox3.Text"
Dim Cmmd As New OleDb.OleDbCommand()
Cmmd.Connection = Conn
Cmmd.CommandText = "INSERT INTO Cookies (Nme, Val) Values('user','" & usernameinput & "')"
Cmmd.ExecuteNonQuery()
Conn.Close()
Me.Hide()
Form2.Show()
End Sub
End Class
Form2
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim Conn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\db.accdb")
Conn.Open()
Dim usernameinput As String = "TextBox3.Text"
Dim Cmmd As New OleDb.OleDbCommand()
Cmmd.Connection = Conn
Cmmd.CommandText = "INSERT INTO Cookies (Nme, Val) Values('user','" & usernameinput & "')"
Cmmd.ExecuteNonQuery()
Conn.Close()
Me.Hide()
Form2.Show()
End Sub
End Class
I didnt even change the variables you named. Just avoided form designing by using msgbox.
My brother instead of using,
Do While Reader.Read
Username = Reader.Item("Val")
Loop
try
Do While Reader.Read = True
Username = Reader.Item(0)
Loop
Let me Know if it works for you.

Database Connection is Not Ending

I have the following code to insert some data from a GridView to a oracle database.
Protected Sub btnInsert_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnInsert.Click
Dim con = New OleDbConnection("Data Source=sml2; User ID=sfpl; Password=a; provider=OraOLEDB.Oracle")
con.Open()
For Each gvRow As GridViewRow In GridView1.Rows
Dim trndate As Date = ddlTrnDte.SelectedValue
Dim ZoneNo As Integer = ddlZone.SelectedValue
Dim DocNo As TextBox = CType(gvRow.FindControl("txtDocNo"), TextBox)
Dim VehCod As DropDownList = CType(gvRow.FindControl("ddlVeh"), DropDownList)
Dim CircleNo As DropDownList = CType(gvRow.FindControl("ddlCircle"), DropDownList)
Dim Contractor As DropDownList = CType(gvRow.FindControl("ddlContractor"), DropDownList)
Dim Supplier As DropDownList = CType(gvRow.FindControl("ddlSupplier"), DropDownList)
Dim NetWt As TextBox = CType(gvRow.FindControl("txtNetWt"), TextBox)
Dim Rate As TextBox = CType(gvRow.FindControl("txtRate"), TextBox)
Dim SNF As TextBox = CType(gvRow.FindControl("txtSNF"), TextBox)
Dim FAT As TextBox = CType(gvRow.FindControl("txtFAT"), TextBox)
Dim LR As TextBox = CType(gvRow.FindControl("txtLR"), TextBox)
Dim TS As TextBox = CType(gvRow.FindControl("txtTS"), TextBox)
'Create Connection
Dim cmd As OleDbCommand = New OleDbCommand("Insert into MLK_02_01 (TRN_DTE,ZONE_NO,CIRCLE_NO,CNT_NO,DOC_NO,SUP_COD,VEH_NUM,NET_WEIGHT,Q_SNF,Q_FAT,Q_LR,Q_TS,RATE,veh_cod) VALUES (:TRN_DTE,:ZONE_NO,:CIRCLE_NO,:CNT_NO,:DOC_NO,:SUP_COD,:VEH_NUM,:NET_WEIGHT,:Q_SNF,:Q_FAT,:Q_LR,:Q_TS,:RATE,:veh_cod)", con)
cmd.Parameters.Clear()
'TrnDate
cmd.Parameters.Add(":trn_dte", (OleDb.OleDbType.Date))
cmd.Parameters(":trn_dte").Value = DateTime.Now()
cmd.Parameters(":trn_dte").Value = ddlTrnDte.SelectedValue
cmd.Parameters.AddWithValue(":ZONE_no", ZoneNo)
cmd.Parameters.AddWithValue(":CIRCLE_no", CircleNo.SelectedValue)
cmd.Parameters.AddWithValue(":CNT_no", Contractor.SelectedValue)
cmd.Parameters.AddWithValue(":Doc_No", DocNo.Text)
cmd.Parameters.AddWithValue(":sup_cod", Contractor.SelectedValue)
cmd.Parameters.AddWithValue(":Veh_num", VehCod.SelectedItem.Text)
cmd.Parameters.AddWithValue(":NET_WEIGHT", NetWt.Text)
cmd.Parameters.AddWithValue(":Q_SNF", SNF.Text)
cmd.Parameters.AddWithValue(":Q_FAT", FAT.Text)
cmd.Parameters.AddWithValue(":Q_LR", LR.Text)
cmd.Parameters.AddWithValue(":Q_TS", TS.Text)
cmd.Parameters.AddWithValue(":rate", Rate.Text)
cmd.Parameters.AddWithValue(":veh_cod", VehCod.SelectedValue)
cmd.ExecuteNonQuery()
Label1.Text = "All Records are Saved Successfully"
con.Close()
btnInsert.Enabled = False
Next
End Sub
Data is inserted into database fine but when the form is closed the database connection does not end. I need help in ending the database session to eliminate further communication errors.
You mention it's a page, so I'm assuming this is an ASP page.
IIS has database connection pooling enabled by default. This means that even though your code closed your connection, IIS maintains a connection in order to make the next query from the next request execute faster.
To disable connection pooling, in your database connection string add this:
Pooling=false
New OleDbConnection("Data Source=sml2; User ID=sfpl; Password=a; provider=OraOLEDB.Oracle; Pooling=false")
Also, after your execute change to this:
cmd.ExecuteNonQuery()
cmd.Dispose()
After the con.Close():
con.Close()
con.Dispose()
and that should dispose the command and connection objects.

having trouble disabling textbox in vb.net

How do I disable a textbox the second time?
here is my code, In form load the textbox is disabled, unless the user will input an idnumber that is in the database. But what if the user will input an idnumber that is in the database then, input again another that is not,
That is where this code comes in, but it has problems, it doesnt disable the textbox in the event of a mouse click, what would be the proper way of doing this?
Private Sub Button12_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Button12.MouseClick
Dim NoAcc As String
Dim NoAccmod2 As String
Dim NoPas As String
Dim sqlcon As New MySqlConnection("Server=localhost; Database=school;Uid=root;Pwd=nitoryolai123$%^;")
Dim sqlcom As MySqlCommand = New MySqlCommand("Select * from student where IDNO= '" & TextBox14.Text & "' ", sqlcon)
sqlcon.Open()
Dim rdr As MySqlDataReader
rdr = sqlcom.ExecuteReader
If rdr.HasRows Then
rdr.Read()
NoAcc = rdr("IDNO")
If (TextBox14.Text <> NoAcc) Then
MsgBox("ID Number is not yet registered!, please register first in the general information before trying to register parents information", MsgBoxStyle.Information)
TextBox7.Enabled = False
TextBox8.Enabled = False
TextBox9.Enabled = False
TextBox10.Enabled = False
TextBox11.Enabled = False
TextBox12.Enabled = False
TextBox13.Enabled = False
End If
End If
At the top of the routine ALWAYS disable the textboxes, then ENABLE them if ID NUMBER matches...
Depending upon what you're actually trying to achieve here, also in the mouse-click you may want to clear the textbox of interest if the ID matches or set it to FOCUS if it does not (to allow them to see what they entered and make changes ... maybe they just mistyped?)