Login Form - Not working - vb.net

Struggling with creating a login from a text file database. The information needs to be manually entered into the text file before it works... see my code below for the form. Its not letting me login.
Public Class UserLogin
Private PWD As String
Public User As User
Public Users As List(Of User) = New List(Of User)
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Me.Close()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
If isValidData() Then
If isValidUser() Then
MessageBox.Show("Login Successful")
Form2.Show()
Me.Hide()
Else
MessageBox.Show("Incorrect Username or password")
End If
End If
Catch ex As Exception
MessageBox.Show(ex.Message & vbCrLf & vbCrLf & ex.GetType.ToString & vbCrLf & vbCrLf & ex.StackTrace, "User Does not Exist")
End Try
End Sub
Private Function isValidData() As Boolean
Return Validator.IsPresent(TextBox1, "Username") AndAlso
Validator.IsPresent(TextBox2, "Password")
End Function
Private Function isValidUser() As Boolean
Return UserDB.ValidateUser("Username", "Password")
End Function
Public Sub setPath(cwd As String)
PWD = cwd
End Sub
End Class
User class below :
Public Class User
Public Sub New()
End Sub
Public Sub New(Username As String, Password As String)
Me.Username = Username
Me.Password = Password
End Sub
Public Property Username As String
Public Property Password As String
Public Function GetDisplayText(sep As String) As String
Dim text As String = Username & sep & Password
Return text
End Function
End Class
UserDB class Below
Imports System.IO
Public Class UserDB
Private Const Databasename = "C:\Depreciate\Users.txt"
Public User As New User
Public Shared Users As List(Of User) = New List(Of User)
Public Shared Function GetUsers(Dir As String) As List(Of User)
Dim Users As New List(Of User)
Dim textIn As New StreamReader(
New FileStream(Databasename, FileMode.OpenOrCreate, FileAccess.Read))
Do While textIn.Peek <> -1
Dim row As String = textIn.ReadLine
Dim columns As String() = row.Split(CChar(","))
Dim User As New User
User.Username = columns(0)
User.Password = columns(1)
Users.Add(User)
Loop
textIn.Close()
Return Users
End Function
Public Shared Function ValidateUser(username As String, password As String) As Boolean
Dim Validated = False
For Each userEntry As User In Users
If username = userEntry.Username AndAlso password = userEntry.Password Then
Validated = True
Exit For
End If
Next
Return Validated
End Function
End Class

looks like you compare all user names and passwords to the strings "Username" and "Password" by calling:
Return UserDB.ValidateUser("Username", "Password")
in isValidUser.Probably you should better pass the actual username and the password which the user has typed instead?

There are a couple of problems in your code:
First I can't see anywhere the call to UserDB.GetUsers that should initialize the list of users from the file. But also assuming that you have made the call in some other place, there is another problem in that method.
This line inside the GetUsers method creates a new variable of type List(Of User) and name it with the same name of the Shared one effectively hiding the one declared at the global class level
Dim Users As New List(Of User)
Then your code continue and fills a variable named Users but this variable is not the shared one declared at the class global level. Of course, when you search your username and password in the shared variable you don't find anything.
Just remove that line and let the call To GetUsers fill the same variable used in the check
(Of course I also assume that when you call UserDB.ValidateUser you will pass an actual Username and a password and not the placeholders string that you are using in the code above)

Related

VB.NET connection to MySQL Add Model

I'm very new to .NET. I am trying to use a code example from the first person that posted a response, here: Connect to remote MySQL database using VB.NET 2010
I would like to instantiate the MySqlVB model object but when I add the following code into the controller, I get a not found error. I don't know how to resolve this.
The error is: Warning 1 Namespace or type specified in the Imports 'MySql.Data.MySqlClient' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases.
What I need is to run a MySQL query and to return the dataset to the controller. Can someone show me how to do this, please?
I'm using VB 2010 Express to do this.
This is the controller
Public Class Form1
Private Sub PrintBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PrintBtn.Click
Dim data As New MySqlVB
With data
If .Connection Then
MessageBox.Show("Database Conneted.")
Else
MessageBox.Show(.ErrorMessage)
End If
End With
End Sub
End Class
And this is my model object
Imports MySql.Data.MySqlClient
Public Class MySqlVB
Private _connection As New MySqlConnection
Private _errormessge As String
Private _servername As String = "xxx.xxx.xxx.xxx"
Private _databasename As String = "testdb"
Private _userid As String = "theuser"
Private _password As String = "thepass"
Public WriteOnly Property ServerName() As String
Set(ByVal value As String)
_servername = value
End Set
End Property
Public WriteOnly Property DatabaseName() As String
Set(ByVal value As String)
_databasename = value
End Set
End Property
Public WriteOnly Property UserID() As String
Set(ByVal value As String)
_userid = value
End Set
End Property
Public WriteOnly Property Password() As String
Set(ByVal value As String)
_password = value
End Set
End Property
Public ReadOnly Property ErrorMessage() As String
Get
Return _errormessge
End Get
End Property
Public Function Connection() As Boolean
Try
_connection.ConnectionString = "Server=" & _servername & ";Port=3306;Database=" & _databasename & ";User ID=" & _userid & ";Password=" & _password & ""
_connection.Open()
If _connection.State = ConnectionState.Open Then
_connection.Close()
Return True
End If
Catch ex As Exception
_errormessge = ex.Message
Return False
End Try
End Function
End Class
Assuming you have fixed your reference to MySql.Data.MySqlClient I think your class could use some work.
Public Class DataAccess
Private ConnectionString As String
Public Sub New(UserName As String, Password As String)
Dim builder As New MySqlConnectionStringBuilder With {
.Server = "xxx.xxx.xxx.xxx",
.Database = "testdb",
.UserID = UserName,
.Password = Password
}
ConnectionString = builder.ConnectionString
Debug.Print(ConnectionString) 'just to see what the builder created
End Sub
Public Function TestConnecion() As Boolean
Using cn As New MySqlConnection(ConnectionString)
Try
cn.Open()
Catch ex As Exception
Debug.Print(ex.Message) 'just to see what is wrong with connection
Return False
End Try
End Using
Return True
End Function
Public Function GetData() As DataTable
Dim dt As New DataTable
Using cn As New MySqlConnection(ConnectionString)
Using cmd As New MySqlCommand("Select * From SomeTable")
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
Return dt
End Function
End Class
Assuming you have a DataGridView to display data and 2 text boxes for user id and password, you can use your class in your form like this.
Private Sub FillGrid()
Dim daClass As New DataAccess(txtUser.Text, txtPassword.Text)
Dim dt = daClass.GetData
DataGridView1.DataSource = dt
End Sub
Of course you will need to add error handling. Also you need to salt and hash passwords. Plain text passwords should never be stored.

Me.Close not working and a Break Mode window appears

I have a class where I will get the value of username and password of my login form and pass it to admin form.
Public Property getUsername() As String
Get
Return Login.username.Text
End Get
Set(value As String)
uname = value
End Set
End Property
Public Property getPassword() As String
Get
Return Login.password.Text
End Get
Set(value As String)
pword = value
End Set
End Property
A function getName()
Public Function getName()
con.Open()
Dim sd As New SqlDataAdapter("select * from AdminAcc where Username = '" & getUsername() & "'", con)
Dim dt As New DataTable
sd.Fill(dt)
con.Close()
getName = dt.Rows(0)(1).ToString()
End Function
I want to display the name of that user in my form so I tried this one:
Private Sub AdminM_Load(sender As Object, e As EventArgs) Handles MyBase.Load
admingreeting.Text = "Hi, " + queryclass.getName()
End Sub
It is actually working, but when I try to sign out the application stops and a break mode window appears.
Private Sub btnsignout_Click(sender As Object, e As EventArgs) Handles btnsignout.Click
If MsgBox("Are you sure you want to sign out?", vbQuestion + vbYesNo) = vbYes Then
Login.Show()
Me.Close()
End If
End Sub
I tried using the me.hide() and it worked, but when I tried to login another acc, the value in the previous getName() did not change.
I'm not sure based on what you've said whether this will solve your problem, but try changing the Shutdown Mode:
If you bring up the Properties window for the project, on the Applications Tab you can set the 'Shutdown mode'. The default is when the 'Startup Form Closes'. Change it to 'When the last form closes'.

VB.NET - Cannot bind to the new display member

I'm trying to assign the DataSource for a ComboBox that will allow the user to select a member. I'm receiving this error when run my application:
Cannot bind to the new display member.
Parameter name: newDisplayMember.
Here's my code:
Private Sub StartScreen_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'GetAllELData()
ddlMember.DataSource = GetMemberList()
ddlMember.DisplayMember = "DisplayName"
ddlMember.ValueMember = "ID"
End Sub
Private Function GetMemberList() As List(Of Member)
Dim rval = New List(Of Member)
Dim dv As DataView = New DataView
Dim myConnString = ConfigurationSettings.AppSettings("ConnString")
Try
dv = SqlHelper.ExecuteDataset(myConnString, CommandType.StoredProcedure, "spGetData").Tables(0).DefaultView
Catch ex As Exception
MessageBox.Show(ex.Message, "Database Error", MessageBoxButtons.OK)
End Try
For Each row As DataRowView In dv
Dim mbrNum As String = row.Item("IMMBR_CD").ToString()
Dim mbrName As String = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(row.Item("IMMBR_NM20").ToLower())
Dim mbrState As String = row.Item("IMMBR_ST").ToString()
'assigns the member data to the list of members
rval.Add(New Member(mbrNum, mbrName, mbrState))
Next
Return rval
End Function
And then my class definition:
Public Class Member
Public ID As String
Public Name As String
Public State As String
Public DisplayName As String
Public Sub New(ByVal i As String, ByVal n As String, ByVal s As String)
ID = i
Name = n
State = s
DisplayName = ID & " - " & Name & ", " & State
End Sub
Public Overrides Function ToString() As String
Dim rval As String = ID & " - " & Name & ", " & State
Return rval
End Function
Public Function GetID() As String
Return ID
End Function
Public Function GetName() As String
Return Name
End Function
Public Function GetState() As String
Return State
End Function
End Class
I don't know why I'm getting the error. The application correctly loads the member as intended and works just fine once I click "Continue" on the error popup. Everything I've found about the error is for people passing a table as their DataSource instead of a custom class like me and the answers contain only code snippets rather than an explanation of the why there's a problem.
Can anyone help me figure out what's wrong here?
Thanks a bunch!
The errors were caused by binding directly to the fields. Defining those as properties and binding to the properties solved the issue.
Public ReadOnly Property GetID() As String
Get
Return Me.ID
End Get
End Property
Public ReadOnly Property GetName() As String
Get
Return Me.Name
End Get
End Property
Public ReadOnly Property GetState() As String
Get
Return Me.State
End Get
End Property
Public ReadOnly Property GetDisplayName() As String
Get
Return Me.DisplayName
End Get
End Property
And:
Private Sub StartScreen_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'GetAllELData()
ddlMember.DataSource = GetMemberList()
ddlMember.DisplayMember = "GetDisplayName"
ddlMember.ValueMember = "GetID"
End Sub

How check if a windows account is an administrator of pc in vb 2013?

I need to check if the current Logon Windows account is an Administrator of the PC.
If My.User.IsInRole(ApplicationServices.BuiltInRole.Administrator) Then
'Is Admin
Else
'Isn't Admin
End If
This code work fine but if i lunch the code with RUN AS "another account" the code dont do the right job becouse take the account that lunch the code not the Windows account that is logged in.
With this code i can see the current Windows User logged in:
Dim Coll As ManagementObjectCollection
Dim LogonName As String
Dim GetName As New ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem")
Coll = GetName.[Get]()
LogonName = DirectCast(Coll.Cast(Of ManagementBaseObject)().First()("UserName"), String)
Dim CleanName() As String = Split(LogonName, "\")
So in the string LogonName i'll have the Windows user name account that is logged in but how can i check if is an Administrator?
Public Function UserIsAdmin(ByVal userName As String) As Boolean
Dim groupName As String = "administrators" '<--You can localize this'
Dim isAdmin As Boolean
Using context As PrincipalContext = New PrincipalContext(ContextType.Machine)
Dim gfilter As GroupPrincipal = GroupPrincipal.FindByIdentity(context, groupName)
If gfilter IsNot Nothing Then
Dim members = gfilter.GetMembers
For Each member In members
If String.Compare(member.Name, userName, True) = 0 Then
isAdmin = True
End If
Next
End If
End Using
Return isAdmin
End Function
You can use System.Security.Principle namespace for this task. I wrote a function in a separate class you can use if you would like or move the function...
This is the class...
Option Strict On
Option Explicit On
Imports System.Security.Principal
Public Class SecurityClass
#Region "Functions"
Public Shared Function IsAdministrator() As Boolean
Dim isAdmin As Boolean = False
Try
Dim user As IIdentity = WindowsIdentity.GetCurrent()
Dim principal As New WindowsPrincipal(CType(user, WindowsIdentity))
isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator)
Return isAdmin
Catch ex As Exception
Return isAdmin
End Try
End Function
#End Region
End Class
To use the class and function, just simply call it where ever needed. I used a messagebox to show it for my test using a button click event.
Private Sub btnIsAdmin_Click(sender As Object, e As EventArgs) Handles btnIsAdmin.Click
If SecurityClass.IsAdministrator Then
MessageBox.Show("Current user is an Administrator")
Else
MessageBox.Show("Current user is not Administrator")
End If
End Sub

update value of a variable outside a class in VB.NET

I have a class derived from a Form, it has textbox for username and password and an OK button. I want it to behave like an InputBox so I can use it like this:
Dim Username As String = ""
Dim Password As String = ""
Dim authorization As New Authorization(Username, Password)
authorization.ShowDialog()
'The user will click OK and I will expect the Username and Password to change based on the user input
MsgBox(Username & " " & Password)
The Authorization class:
Public Class Authorization
Dim RefUsername As String
Dim RefPassword As String
Public Sub New(ByRef Username As String, ByRef Password As String)
InitializeComponent()
RefUsername = Username 'I'm trying to pass reference instead of value
RefPassword = Password 'I'm trying to pass reference instead of value
End Sub
Private Sub OKButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AuthorizeButton.Click
RefUsername = Username.Text 'I'm trying to change value of variable outside the class
RefPassword = Password.Text 'I'm trying to change value of variable outside the class
Me.Close()
End Sub
End Class
In short, I want to change the value of variables outside the class when the user clicks the OK, how am I going to accomplish that?
You can just add properties to the class to modify it from outside like any other class:
Public Class Authorization
Friend Property RefUsername As String
Friend Property RefPassword As String
'this constructor isn't really necessary with this new approach,
'but I'll leave it as-is.
Public Sub New(ByRef Username As String, ByRef Password As String)
InitializeComponent()
RefUsername = Username '
RefPassword = Password
End Sub
Private Sub OKButton_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles AuthorizeButton.Click
Me.DialogResult = DialogResult.OK
End Sub
End Class
From the outside you then get username and password:
Dim Username As String = ""
Dim Password As String = ""
Dim authorization As New Authorization(Username, Password)
'this constructor isn't really necessary with this new approach,
'but I'll leave it as-is.
If authorization.ShowDialog() = DialogResult.OK Then
MsgBox(authorization.RefUsername & " " & authorization.RefPassword)
End If
Public Class Authorization
Dim RefUsername As String
Dim RefPassword As String
Public Sub New(ByRef Username As String, ByRef Password As String)
InitializeComponent()
RefUsername = Username 'I'm trying to pass reference instead of value
RefPassword = Password 'I'm trying to pass reference instead of value
End Sub
Private Shared Function PromptUser() As ReturnClass
Dim currentReturnClass as ReturnClass
// Dialog Goes Here
currentReturnClass.UserName = Username.Text
currentReturnClass.Password = Password.Text
Me.Close()
End Sub
End Class
private class ReturnClass
Dim userName as String
Dim password as String
Dim userAcceptedDialog as Boolean
' Setters and Getters
End Class
Your calling code:
Dim Username As String = "Default User"
Dim Password As String = "Default Password"
Dim authorization As New Authorization(Username, Password)
Dim myReturnClass as ReturnClass
myReturnClass = authorization.PromptUser()
MsgBox(myReturnClass.Username & " " & myReturnClass.Password)