I have created a web application that introduced me to something I haven’t really used before, classes. They are a great thing. This may be a 101 style post but I find it very interesting. What I have done is create a class of user. Inside the user.vb class I have all the methods/functions that has to do with the user. I have things like a function to find the user name, another to find user ID, and yet another to find the user roles. To use it all you have to do is create an instance of that class and you can call the methods directly on the caller page. For instance my class is named user.vb. To use it you have to reference it. This is how I reference it:
Dim iUser As New User
That’s it! Then to use the methods:
iUser.methodname()
How easy is that? I also have a sqlMethod.vb which houses all my sql methods used throughout my web application. I even use it in the User class. Again, the same way whether its in a class or another page is to use the:
Dim iSQL As New sqlMethods
And then you guessed it, to use any method just reference it like:
iSQL.methodname()
You can also pass in variables if you need to:
iSQL.Methodname(var1, var2)
One thing to remember is that the call has to be set to a variable. You have to have:
Dim roles As String
Roles = iSQL.roles(userID)
To create the class, if your using Visual Studio, you just have to right click on the project name and choose add new item and choose class, name it, and your good to go to use one. Make sure you Import anything that is needed at the top of the class. Below is a real world example of how I use it.
Here is my User.vb code:
Dim iSQL As New sqlMethods
Public Function GetUserID(ByVal userlogin As String, ByVal userpassword As String) As String
Dim userID As String
userID = iSQL.GetUserID(userlogin, userpassword).ToString
Return userID
End Function
Here is my sqlMethods.vb Code:
Public Function GetUserID(ByVal userlogin As String, ByVal userpassword As String) As String
Dim mySQLString As String = “SELECT tblUser.userID FROM tblUser WHERE tblUser.userLogin = ‘” & userlogin & “‘ AND tblUser.userPassword = ‘” & userpassword & “‘”
Dim myCommand As New SqlCommand(mySQLString, dsn)
Dim userID As String
Try
dsn.Open()
userID = Convert.ToString(myCommand.ExecuteScalar())
If userID = “” Then
Return 0
Else
Return userID
End If
Catch ex As Exception
‘Something went wrong
dsn.Close()
Throw ex
Finally
‘Cleanup
dsn.Close()
End Try
End Function
Hope this helped. Have fun coding and as always, if there are any questions or suggestions, they are welcome. Thank you.