Using LINQ to set up a login page from an access database - vb.net

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!

Related

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.

Find username from email address in active directory vb.net

Sorry, i checked the link "Find username from Active Directory using email id" but that's for C# i can't figure that out how to do in Vb.net.
In my gridview when i select the row to get the email id and pass it to AD to find the user name but so far i can't figure that out what command will give that details in VB.net
Protected Sub grdValidate_RowUpdating(sender As Object, e As EventArgs)
Dim strEmail As String = grdValidate.SelectedRow.Cells(2).Text
Dim ctx As New PrincipalContext(ContextType.Domain)
' find a user
Dim user As UserPrincipal = UserPrincipal.FindByIdentity(ctx, strEmail)
End Sub
i saw this property "UserPrincipal.EmailAddress" but VS is not even recognize the command. Obviously i imported
Imports System.DirectoryServices
Imports System.DirectoryServices.AccountManagement
I am trying to find a command to pass the email and match the email id in AD and get the user information.
Thanks in Advance
You need to add .NET references to System.DirectoryServices and System.DirectoryServices.AccountManagement and then...
Using context As New System.DirectoryServices.AccountManagement.PrincipalContext(DirectoryServices.AccountManagement.ContextType.Domain, strDomainName)
Dim yourUser As System.DirectoryServices.AccountManagement.UserPrincipal = System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(context, strEmailAddress)
If yourUser IsNot Nothing Then
strFirstName = yourUser.GivenName
strLastName = yourUser.Surname
End If
End Using
MsgBox(strFirstName & " " & strLastName)
I've used fully qualified names for clarity, but you can tidy things up with Imports System.DirectoryServices.AccountManagement at the beginning of the module

Get First & Last Name of All AD Accounts

I'm looking for the quickest and easiest way to retrieve all Active Directory account's first & last names. The intention is to have a string list which contains all names from the Active Directory, for the purpose of auto-completion in a textbox in a small Visual Basic application used for unlocking accounts.
Usage Scenario:
On form load the application generates the list of names from the AD. I'm expecting this to take around 10-15 seconds as there's 4,500 accounts on the AD. Each name is added to a string list for use with the auto completion.
The user types the name Garry into textbox1 and the auto complete suggests all Garry's in the AD, by using a string list. I know how to do this easily, I just dont know how to populate the list with user's names efficiently.
There's a lot of samples on accessing the AD, but none which show how to loop through it. I thought asking on here would help both myself and other users in a similar usage case.
The code I have so far for accessing a single account is shown below, however I need to loop through all AD accounts and retrieve their First & Last names.
Current Code to access single account:
'Domain is declared with the LDAP path
'UserName is declared with textbox1.text value
Dim ADEntry As New DirectoryServices.DirectoryEntry("LDAP://" & Domain)
Dim ADSearch As New System.DirectoryServices.DirectorySearcher(ADEntry)
ADSearch.Filter = ("(samAccountName=" & UserName & ")")
ADSearch.SearchScope = System.DirectoryServices.SearchScope.Subtree
Dim UserFound As System.DirectoryServices.SearchResult = ADSearch.FindOne()
If Not IsNothing(UserFound) Then
Log.AppendLine("Account found, loading checks...")
Dim Attrib As String = "msDS-User-Account-Control-Computed"
Dim User As System.DirectoryServices.DirectoryEntry
User = UserFound.GetDirectoryEntry()
User.RefreshCache(New String() {Attrib})
'Display user account details
txtLogin.Text = User.Properties("userPrincipalName").ToString
txtName.Text = User.Properties("givenName").ToString & " " & User.Properties("sn").ToString
else
'User not found
end if
Any help would be much appreciated, even in C#.
You can use the same ADEntry variable as above and do something like this. This only adds a user to the list if they have both a first and last name.
Dim listNames As New AutoCompleteStringCollection
Using ADSearch As New DirectoryServices.DirectorySearcher(ADEntry, "(&(objectCategory=person)(objectClass=user))", {"givenName", "sn"}, DirectoryServices.SearchScope.Subtree)
For Each user As DirectoryServices.SearchResult In ADSearch.FindAll
Try
listNames.Add(user.GetDirectoryEntry.Properties("givenName").Value.ToString + " " + user.GetDirectoryEntry.Properties("sn").Value.ToString)
Catch ex As Exception
End Try
Next
End Using
With TextBox1
.AutoCompleteCustomSource = listNames
.AutoCompleteMode = AutoCompleteMode.SuggestAppend
.AutoCompleteSource = AutoCompleteSource.CustomSource
End With

insert date to database using silverlight-enabled wcf service, visual basic

I have difficulties in inserting record from silverlight interface to database using silverlight-enabled wcf service, visual basic. I followed a few tutorials in this topic, but somehow I couldn't finish my project in inserting data into database.
I followed VBRocks' blog on "Silverlight 3: Displaying SQL Server data " (http://garylima.blogspot.com/2009/09/silverlight-3-displaying-sql-server.html)to display data from database but failed to write record to the database.
I have 6 textboxes to receive user input, and I want to submit the information from the 6 boxes to the database.
Here is the Operationcontract in the register.svc.vb page:
<OperationContract()>
Public Sub InsertData(registerid As Integer, firstname As String, emailid As String, phoneno As String, loginname As String, password As String)
Dim db As New SilverlightDataContext()
Dim record As New Registration With {.registerID = registerid, .FirstName = firstname, .EmailID = emailid,
.PhoneNo = phoneno, .LoginName = loginname, .Password = password}
db.Registrations.InsertOnSubmit(record)
Try
db.SubmitChanges()
Catch ex As Exception
End Try
Here are the subs in the Mainpage.xaml.vb, there is no error but no result too:
Private Sub SubmitRegister_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Button1.Click
Dim mbservice As New RegisterClient()
Dim registerid = Convert.ToInt32(BoxRegisterID.Text)
mService.InsertDataAsync(registerid, BoxFirstName.Text, BoxEmailID.Text, BoxPhoneNo.Text, BoxLoginName.Text, BoxPassword.Text)
End Sub
Those are the main things in the project. Any ideas will be greatly appreciated!
Thanks in advance!
For some reason, the code I have is right and I am able to insert a record into the database which I didn't notice by the time I posted this question. Hope this will help later.

Validating Login from checking sql table

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")