Validating Login from checking sql table - sql

I'm trying to check username and password by using a For Each Statement. If it validates then messagebox saying welcome appears, if it doesn't a message box saying "incorrect" will keep popping up over and over until it's done looping through the table. How can i correct this and just make it display one time. Also when it does validate a new window will show up with users First and Last name in a textbox, How can I edit users info and then save to db. Thanks for any help.
Private Sub Button1_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Button1.Click
Dim data As New datalinq1DataContext
For Each row In data.Users
If Not row.username = TextBox1.Text And Not row.password = TextBox2.Text Then
Messagebox.Show("Incorrect")
Else
MessageBox.Show("Welcome " + row.fname + " " + row.lname)
Dim window As New Window1
window.TextBox1.Text = row.fname
window.TextBox2.Text = row.lname
window.TextBox3.Text = row.username
window.Show()
Exit For
End If
Next
End Sub

You could add an EXIT FOR after the msg box, but why are there multiple records being checked in the user table. You should filter the user table to just the username entered.

Looping over each and every user in the table will give you performance issues in no time.
Instead of using a foreach, try figuring out why you can't access the proper LINQ extension methods. Have you references System.Linq and System.Data.Linq?
The proper way of checking for a user with corresponding username and password would be:
var potentialUser = data.Users
.SingleOrDefault(user =>
user.Username == userName &&
user.Password = passWord
);
if(potentialUser != null)
Messagebox.Show("Welcome")
else
Messagebox.Show("Incorrect")

Related

Using LINQ to set up a login page from an access database

I currently have a small table of 4 records of people in an Access Database each with just three fields, Role, Username and Password. Im trying to set up a login page where I'm using LINQ to read the Username and Password fields and then if they are both correct then to login to one of 4 possible roles depending on what role that person is allocated to on database. I currently have this.
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
Dim strUsername As String
Dim strPassword As String
Dim strRole As String
Dim query1 = From loginUsername In database1.tblStaff
Where loginUsername.FirstName = txtUsername.Text
Select loginUsername.FirstName
Dim query2 = From loginPassword In database1.tblStaff
Where loginPassword.Password = txtPassword.Text
Select loginPassword.Password
End Sub
End Class
As you can see, I'm trying to take what the user enters in each text box and match it to the database and then somehow set up an if statement checking if it's right but I'm not sure if I'm even on the right track.
Any help is great, thanks.
I guess it should be something like this (disclaimer: I'm not familiar with VB)
Dim role = (From entry In database1.tblStaff
Where entry .FirstName = txtUsername.Text
AndAlso entry.Password = txtPassword.Text
Select entry.Role)
.FirstOrDefault() 'execute query explicitly
'if a role is null, then login or password incorrect
If role Is Nothing Then
'No match
Else
'Use role here
End If
There is no point to separate queries. You can merge them in a single query
Thank you sm Chris this has been a lifesaver for Yvonne's project! Our group was really struggling with this. You probably already have you answer by now, that code works really well. You just have to add your If statements after:
If query1.Count = 1 And query2.Count = 1 Then
Me.Hide()
FrmExample.Show()
Else
MessageBox.Show("Incorrect username or password", "Warning")
End If
Idk if that's any help, thank you!

Show/Hide text box for email input based on AD user result

I'm still a bit of a VB Noob and I am having some trouble getting this to work correctly. The code looks like it should work, but I am obviously missing something...
What I'm trying to do is to get the users email address from DirectoryServices when the form loads & If there is no AD user email available, show (unhide) a text box to allow the user to enter their email address. What I have will pull the users email from AD, but will not show the textbox if Directy services is not available. I have tried moving UserEmailAdd.Visible = False and lblEmail.Visible = False to the Form Load and the setting the value to True, but I'm not having much luck
Here is what I have so far:
Private Sub FormTicket_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.CenterToScreen()
BtnSCR.Hide()
LblScreenshot.Hide()
'Get current users email address from AD or input
Dim currentADUser As System.DirectoryServices.AccountManagement.UserPrincipal
currentADUser = System.DirectoryServices.AccountManagement.UserPrincipal.Current
Dim userEmail = currentADUser.EmailAddress
If currentADUser IsNot Nothing Then
' user exists
LblEmail.Visible = False
UserEmailAdd.Visible = False
txtSummary.Focus()
MailUser = userEmail
'Catch ex As Exception
Else
' user does *not* exist
UserEmailAdd.Visible = True
LblEmail.Visible = True
UserEmailAdd.Focus()
MailUser = UserEmailAdd.Text
'End Try
End If
So after some testing (trial & error), I was able to make this work. This may not be the best way, but it suits my purpose for now and I will continue to work on cleaning it up.
I determined if there was a local domain and if the user had an account & email address. If so, I populated the UserEmailAdd textbox with this value and made the label and field hidden. If no local domain/user was found, the label and textbox were then unhidden and the user was now able to enter their email address which in both cases provided the users mail.From address.
Here is what I did:
Try
' check if domain user exists
Dim currentADUser As System.DirectoryServices.AccountManagement.UserPrincipal
currentADUser = System.DirectoryServices.AccountManagement.UserPrincipal.Current
Dim userEmail = currentADUser.EmailAddress
If currentADUser.EmailAddress IsNot Nothing Then
LblEmail.Hide()
UserEmailAdd.Hide()
UserEmailAdd.Text = userEmail
txtSummary.Focus()
End If
' local domain user does not exist
Catch ex As Exception
UserEmailAdd.Show()
LblEmail.Show()
UserEmailAdd.Focus()
End Try
...
mail.From = New MailAddress(UserEmailAdd.Text)
jmcilhinney, thank you for prompting some more thought on my part. I'm obviously not any sort of programmer and I have A LOT to learn yet. But your comments helped me to take another look at this and figure out a different way.

Label Text Changes During Code but Won't Say Changed

I have code in my program that updates a database. When the database has been updated, I change the text of a label to say "Last Update" and then the actual time when the update occurred. This part works perfectly.
My problem occurs when I close the program and re-open it. I want to code to check the date in the label and if the date in the label is less than the current date I want to update my database. But when I close my program and re-open it the label in the text doesn't stay.
Here is my code:
Public Sub Screen_Shown(sender As Object, e As EventArgs) Handles Me.Shown
Dim Time_of_Update = CDate(Label_Time_of_Update.Text.Split(" "c)(2).Trim())
Debug.WriteLine(Time_of_Update)
If Time_of_Update < Today Then
Update_Data()
Else
End If
End Sub
Private Sub Update_Data()
Update_Daily()
Ready_Update_Quarterly_and_Annualy()
Dim Time_of_Update = DateTime.Now
Label_Time_of_Update.Text = "Last Updated " & Time_of_Update & ""
End Sub
How can I fix this?
Go to Settings in Project properties and create a LastUpdatedDate setting:
Name == "LastUpdatedDate" basically a variable name
Type == Date
Scope == User (Application scope makes them Read Only)
Value == a valid date
This defines the setting name and data type. in code:
Dim Time_of_Update = DateTime.Now
Label_Time_of_Update.Text = "Last Updated " & Time_of_Update & ""
My.Settings.LastUpdatedDate = Time_of_Update
My.Settings.Save
next time you run:
Label_Time_of_Update.Text = My.Settings.LastUpdatedDate
Saving it as a DateTime type will make it easy to date comparison in code rather than converting it back from a String.

Saving user input in VB

At the start of my VB application I am asking user to type his email and password into two text boxes. If login will be successful, I would like to save entered email and password as a Login.txt file into relative directory. I would like to overwrite all old info in the file.
I would like that every time the application starts; it will read this Login.txt file and displays email and password back in same two text boxes, so user do not need to type it every time he is doing Login.
What is the right code for this?
Thank you for help.
First of all you need to follow #Plutonix comment steps,
you can create two new settings as string type and select "user" scope (not application), and also ensure to keep empty the default values.
So in your code to save the values everytime when you want you can do this:
My.Settings.Email = EmailTextBox.text
My.Settings.Pass = PassTextBox.text
And to load the values:
EmailTextBox.text = My.Settings.Email
PassTextBox.text = My.Settings.Pass
I have been using this method for along time and i think it would help you.
When you open up VB double click in the soloution explorer "My Project"
It will come up with tabs along the side of the window you need to click the settings tab. It will come up with a table and one of the rows will have the name "settings" in it. In your case you want to name it "email" then press enter. Another row will appear again change the name from "settings" to "Password" then press enter. When you have done this part this is the coding part:
CODING:
Textbox1.text = my.settings.email
Textbox2.text = my.settings.password
My.settings.save
Ok so that is the coding out of the way
All you need to do now is insert the coding from above into the coding of the button you want to click to remember the details.
Then after you have done that step click debug or the play button or the (f5) key.
Hope this works for you i will edit it if it doesn't
thanks
hope that the following reference will give solution for your problem
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
pth = "d:\user_login"
If Directory.Exists(pth) = False Then
Directory.CreateDirectory(pth) 'create a folder in the path is no such folder is existing
End If
End Sub
this will create a directory in your D: drive at first run
Private Sub login_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles login.Click
' works like session veriables
uname = username.Text ' store user name to a public verible for future reference till the application restarted
pwd = pasword.Text ' store password to a public verible for future reference till the application restarted
'save user name and password as small text file for future reference
'Dim rtc As New RichTextBox
rtc.Clear() ' clear the rtc content
rtc.Text = "Username :" & username.Text & Chr(13) & "Password :" & pasword.Text 'create a text document and write values on it
rtc.SaveFile(pth & "\" & Now.Month.ToString & Now.Day & "_" & Now.Hour.ToString & "_" & Now.Minute.ToString & ".txt") 'save the document in the above path with current date and time as name
End Sub

VB.NET - Combobox goes blank when a button is clicked, databind doesn't update

Please forgive me, it has been some time since I've used VB.Net so this may be easy.
I have a simple login form with a text box, combobox and a button. The combobox is binded to a SQL database and displays the user names from Users table. The idea is that you select a name, type in a password, and you logon to a new form (This part works Great!). If you type a wrong password, the form pops up a message that says "invalid." For some reason at this stage, the combobox goes blank. The drop down now has empty spaces where names once were. Typing in a name with a password here results in object reference errors. I have tried everything to get the combo box to reset and searched the web but nothing works!!!
(I know this is not a secure login, this is just an easy example of binding data to a combo box and checking it against SQL table). Thanks for your help!
enter code here
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles BTN_Logon.Click
Try
Dim STR_User As String = Users_nameComboBox.SelectedValue
Dim STR_Pwd As String = TB_Pwd.Text
STR_User = STR_User.Trim
'MessageBox.Show(STR_User & "|" & STR_Pwd)'Used to verify this stage works
Dim numRecords As Int16 = UsersTableAdapter.FillByLogin(Me.Login_testDataSet.users, STR_User, STR_Pwd)
'MessageBox.Show(numRecords) 'Used to verify this stage works
If (numRecords > 0) Then
Dim DB_User As String = Me.Login_testDataSet.users(0).users_name.Trim
Dim DB_Pwd As String = Me.Login_testDataSet.users(0).users_pwd.Trim
'MessageBox.Show(DB_User & "|" & DB_Pwd)'Used to verify this stage works
If DB_User.Equals(STR_User) And DB_Pwd.Equals(STR_Pwd) Then
'User is authenticated for application
'This section works (removed to cleanup code)
Else
MessageBox.Show("ERROR" & STR_User & "|" & STR_Pwd) 'Shows that this stage works
'Need to figure out why combobox doesn't refill, using restart for now
'Application.Restart()
End If
End If
MessageBox.Show("ERROR" & STR_User & "|" & STR_Pwd) 'Shows that this stage works
'Need to figure out why combobox doesn't refill, using restart for now
'Application.Restart()
Catch ex As Exception
MessageBox.Show(ex.Message)
'Need to figure out why combobox doesn't refill, using restart for now
'Application.Restart()
End Try
End Sub
InitializeComponent
'Users_nameComboBox
Me.Users_nameComboBox.DataBindings.Add(New System.Windows.Forms.Binding("Text",
Me.UsersBindingSource, "users_name", True))
Me.Users_nameComboBox.DataBindings.Add(New System.Windows.Forms.Binding("SelectedValue", Me.UsersBindingSource, "users_name", True))
Me.Users_nameComboBox.DataSource = Me.UsersBindingSource
Me.Users_nameComboBox.DisplayMember = "users_name"
Me.Users_nameComboBox.Name = "Users_nameComboBox"
Me.Users_nameComboBox.ValueMember = "users_name"