Solved

I can't seem to connect to my database.

Posted on 2006-07-12
7
386 Views
Last Modified: 2008-03-17
I'm working in VB.NET creating a log in page and I can't seem to connect to my database. I keep getting the error:
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:


Line 75:             lblCheck.Text = s
Line 76:         End Try
Line 77:         gdrDR.Close()
Line 78:         gdcDataConnection.Close()
Line 79:
 

Source File: c:\inetpub\wwwroot\Bioness\admin\login.aspx.vb    Line: 77

Stack Trace:


[NullReferenceException: Object reference not set to an instance of an object.]
   Bioness.login.AttemptLogin(String sUserName, String sPassword) in c:\inetpub\wwwroot\Bioness\admin\login.aspx.vb:77
   Bioness.login.btnLogin_ServerClick(Object sender, ImageClickEventArgs e) in c:\inetpub\wwwroot\Bioness\admin\login.aspx.vb:46
   System.Web.UI.HtmlControls.HtmlInputImage.OnServerClick(ImageClickEventArgs e) +109
   System.Web.UI.HtmlControls.HtmlInputImage.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +67
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +18
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33
   System.Web.UI.Page.ProcessRequestMain() +1292

 Here is my code:

    Dim gdcDataConnection As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\db\users.mdb;")
    Dim gdcCMD As New OleDbCommand
    Dim gdrDR As OleDbDataReader
    Dim gsCnn As String
    Dim glID As Long

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here
    End Sub

    Private Sub btnLogin_ServerClick(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnLogin.ServerClick
        Dim sPassword As String
        Dim sUserName As String
        AttemptLogin(sUserName, sPassword)
    End Sub

    Private Function AttemptLogin(ByVal sUserName As String, ByVal sPassword As String) As Boolean
        Dim sSQL As String
        Dim s As String
        Try
            gdcDataConnection.Open()

            sSQL = "SELECT ID FROM [my_users] WHERE user = '" & Replace(sUserName, "'", "''") & "' and password = '" & Replace(sPassword, "'", "''") & "'"
            gdcCMD = New OleDbCommand(sSQL, gdcDataConnection)

            gdrDR = gdcCMD.ExecuteReader
            If gdrDR.Read() Then
                glID = gdrDR.Item(0)
                Session("login") = True
                AttemptLogin = True
                Response.Redirect("admin.aspx")
            Else
                Session("login") = False
                AttemptLogin = False
                s = "Log in Failed. Try again."
            End If

        Catch ex As Exception

            s = ex.ToString

        Finally
            lblCheck.Text = s
        End Try
        gdrDR.Close()
        gdcDataConnection.Close()

    End Function
0
Comment
Question by:Dalkalion
  • 2
  • 2
  • 2
  • +1
7 Comments
 
LVL 25

Expert Comment

by:Lee Savidge
ID: 17093335
Hi,

If you put a break point on the AttemptLogin function, I suspect that you'll find that in the try catch block the code is failing possibly because the database connection hasn't opened or something. I don't have VS in front of me to check the code. If it isn't open and you try to execute the reader, the try catch block will drop to the catch section, set the string value and then go into the Finally section, then drop out to the gdrDR.Close() function call, but but because it might not have an open DB connection it fails and errors. Step through the code and see where it occurs. If it is what I said, then either move the call to close the reader into the try catch block or check to see if the connection is open after you have told it to open the connection.

Regards,

Lee
0
 
LVL 25

Expert Comment

by:SStory
ID: 17094219
if it happens when you attempt a close, make sure the object isnot nothing before closing
0
 

Author Comment

by:Dalkalion
ID: 17095284
Ok I moved the gdrDR.Close() into the try catch block area and got this response for my lblCheck.Text label.
This is my line 58      gdrDR = gdcCMD.ExecuteReader
This might sound dumb but is this happening from not putting single quotes around my password and username in my database?

System.Data.OleDb.OleDbException: No value given for one or more required parameters. at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(Int32 hr) at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method) at System.Data.OleDb.OleDbCommand.ExecuteReader(CommandBehavior behavior) at System.Data.OleDb.OleDbCommand.ExecuteReader() at Bioness.login.AttemptLogin(String sUserName, String sPassword) in c:\inetpub\wwwroot\Bioness\admin\login.aspx.vb:line 58

As far as this comment "if it happens when you attempt a close, make sure the object isnot nothing before closing"
How and which object do I make not nothing to before closing?

I do appreciate the help.
0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
LVL 3

Expert Comment

by:mdg12
ID: 17096094
The problem is that "s" is never initialized if the login is successful.   The finally block is always called, so on a successful login, it tries to assign null to the lblCheck.

Try changing the first couple of lines to the following

Private Function AttemptLogin(ByVal sUserName As String, ByVal sPassword As String) As Boolean
        Dim sSQL As String
        Dim s As String = ""   'initialize to default value
        Try
...
0
 

Author Comment

by:Dalkalion
ID: 17097113
I tried it. Here's my errror:
System.Data.OleDb.OleDbException: No value given for one or more required parameters. at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(Int32 hr) at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method) at System.Data.OleDb.OleDbCommand.ExecuteReader(CommandBehavior behavior) at System.Data.OleDb.OleDbCommand.ExecuteReader() at Bioness.login.AttemptLogin(String sUserName, String sPassword) in c:\inetpub\wwwroot\Bioness\admin\login.aspx.vb:line 58
0
 
LVL 25

Expert Comment

by:SStory
ID: 17099079
I don't know, but you would be wiser to use a command object with parameters rather than ad-hoc SQL. I was told that command params protect again SQL Injects and handle the single quote issues.

Also why do you have [] around the table name?  In Access proper that is a single for a query parameter. Although I think in ASP.NET you use ? (would need to read up on that again to verify)

so I suggest you create OleDbParameters for user and password and add those to the parameters of the command. Make

gdcCMD.Text="SELECT ID FROM my_users WHERE user = ? and password = ?"

again you will need to verify syntax for ?

I'm not sure this will solve your problem but it is something that should be done.  

You don't want ' ' around the actual data in the fields in the database.

It sounds like your command object is expecting parameters anyway.. maybe the [] is a syntax for parameters for some database.  If this is Access investigate using ? ? and try without []

0
 
LVL 3

Accepted Solution

by:
mdg12 earned 500 total points
ID: 17099258
When SStory told you to check for nothing before close, he meant doing something like:
    If Not gdrDR Is Nothing Then  ' i think that's vb's syntax...   c# would be if (gdrDR!=null) {...}
        gdrDR.Close()
    End If
    If Not gdcDataConnection Is Nothing Then
        gdcDataConnection.Close()
    End If
And that should actually go in you Finally block so that the connection gets closed even if there is an error in your command

The single quotes are necessary around the data values in you SQL statement (unless they are numbers)... but those quotes do not need to be there in the actual data which is stored in the table...  
Another option to avoid having to escape the single quotes is to use "parameters"..  

Another thing you might try is to wrap the ID, user, and password in your SQL statement in []'s...  they could be reserved keywords in Access, which might cause a problem

So here's what I'm thinking you could try...
    Private Function AttemptLogin(ByVal sUserName As String, ByVal sPassword As String) As Boolean
        Dim sSQL As String
        Dim s As String = ""
        Try
            gdcDataConnection.Open()
            sSQL = "SELECT [ID] FROM [my_users] WHERE [user] = @user and [password] = @password"
            gdcCMD = New OleDbCommand(sSQL, gdcDataConnection)
            gdcCMD.Parameters.Add("@user", sUserName);
            gdcCMD.Parameters.Add("@password", sPassword);
            gdrDR = gdcCMD.ExecuteReader
            If gdrDR.Read() Then
                glID = gdrDR.Item(0)
                Session("login") = True
                AttemptLogin = True
                Response.Redirect("admin.aspx")
            Else
                Session("login") = False
                AttemptLogin = False
                s = "Log in Failed. Try again."
            End If
        Catch ex As Exception
            Session("login") = False
            s = ex.ToString
        Finally
            lblCheck.Text = s
            If Not gdrDR Is Nothing Then
                gdrDR.Close()
            End If
            If Not gdcDataConnection Is Nothing Then
                gdcDataConnection.Close()
            End If
        End Try
    End Function

0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
This article explains all about SQL Server Piecemeal Restore with examples in step by step manner.
Video by: Steve
Using examples as well as descriptions, step through each of the common simple join types, explaining differences in syntax, differences in expected outputs and showing how the queries run along with the actual outputs based upon a simple set of dem…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now