Bug #51977 .NET Connector 6.2.2 is giving Object Reference is not set to an instance of an
Submitted: 12 Mar 2010 7:08 Modified: 18 Mar 2010 5:27
Reporter: D Srinivas Email Updates:
Status: Can't repeat Impact on me:
None 
Category:Connector / NET Severity:S2 (Serious)
Version:.NET Connector 6.2.2 OS:Microsoft Windows
Assigned to: CPU Architecture:Any

[12 Mar 2010 7:08] D Srinivas
Description:
As you advised we have installed .NET Connector 6.2.2. Now it is giving "Object Reference is not set to an instance of an Object" error when dbconnection.close(). Please help me in this regard. The following are set in web.config:

Respect Binary Flags=false;Pooling=False;Allow User Variables=True;

Let me know is there any thing I have to set in web.config. Please help me. This is urgent.

How to repeat:
Same opened connection is used for multiple datareaders by just closing datareader every time. Connection is opened once and closed in Finally block 

                If (dbConnection.State <> ConnectionState.Broken And dbConnection.State <> ConnectionState.Closed) Then
                    dbConnection.Close()
                End If

Error is comming in dbConnection.close()

Suggested fix:
No Comments
[15 Mar 2010 9:06] Tonci Grgin
Hi Srinivas and thanks for your report.

Alas, there is a little useful info provided. I do not have a code to reproduce the problem reliably, there is no stack trace of error and so on.

Based on info provided, I have two code snippets for you to try:
Taken from Bug#48007:
    string strCon = "server=xx;user id=xx;password=xx;persist security info=True;database=test";
    MySqlConnection con = new MySqlConnection(strCon);
    MySqlCommand cmd = new MySqlCommand("pbug48007", con);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@Param1", "Hello");
    cmd.Parameters.AddWithValue("@Param2", "World");
    try
    {
        con.Open();
        MySqlDataReader rd = cmd.ExecuteReader();
        rd.Read();
        this.Text = rd["Param1"] + " " + rd["Param2"];
    }
    catch (MySqlException exc)
    {
        MessageBox.Show(this, exc.Message);
    }
    finally
    {
        con.Close();
        con.Dispose();
    }

or something like:
    dr.Close();    //Get rid of anything holding to connection object
    cmd.Dispose(); //Get rid of anything holding to connection object
    if (c.State == ConnectionState.Closed)
    {
        Console.WriteLine("Conn closed");
    }
    else
    {
        c.Close();
    }
[17 Mar 2010 9:49] D Srinivas
Hi Tonci Grgin,

Thank you for your reply. The following is the error please go through it.

The following is the stack trace:

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 792:            End If
Line 793:            'Close DataReader of School
Line 794:            dtrData1.Close()
Line 795:
Line 796:            If RecordExits Then
 

Source File: hidden    Line: 794 

Stack Trace: 

[NullReferenceException: Object reference not set to an instance of an object.]
   MySql.Data.MySqlClient.MySqlCommand.Close(MySqlDataReader reader) +84
   MySql.Data.MySqlClient.MySqlDataReader.Close() +176
   manabadi.EditaSchool.PopulateRecord() in E:\Manabadi2.0Code\Institute\AdmEditaSchool.aspx.vb:794
   manabadi.EditaSchool.Page_Load(Object sender, EventArgs e) in hidden :139
   System.Web.UI.Control.OnLoad(EventArgs e) +88
   System.Web.UI.Control.LoadRecursive() +74
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +30
 

Initially I copied Mysql.Data.dll file then I got error in the finally block as I said before.

Once I copied the other two files( viz., MySql.Data.Entity.dll and MySql.Web.dll) then I am getting the error while closing datareader as mentioned above in the stack trace.
[17 Mar 2010 9:56] Tonci Grgin
Srinivas, it appears obvious from your trace what's happening:
Line 794:            dtrData1.Close() << you have closed the reader
Line 795:
Line 796:            If RecordExits Then << and then you check if record exists...

If you had attached your test case this would have become clear...
Please fix your code as this surely looks as !Bg.
[17 Mar 2010 12:49] D Srinivas
Hi Tonci Grgin,

Thanks for your quick response. Here is the code snippette that generating error. Hope this will help you to investigate the error. Please feel free to ask any more you want from me that I did not supply.

    Public Sub PopulateRecord()
            Dim dbConnection As New MySqlConnection(sConnStr)
            Dim RecordExits As Boolean
	    Dim i As Integer
            Dim crListItem As ListItem
            Dim dtrData1 As MySqlDataReader
	    Try
                dbConnection.Open()
                strSQL = "SELECT * FROM MBD_Schools WHERE SCH_SchoolId = " & iSchoolId
                cmdData.CommandText = strSQL
                cmdData.CommandType = CommandType.Text
                cmdData.Connection = dbConnection
                dtrData1 = cmdData.ExecuteReader

                RecordExits = False
                If dtrData1.Read() Then
                    RecordExits = True
		    'do whatever you want 
                End If
                'Close DataReader of School
                dtrData1.Close()
                If RecordExits Then
                    'Medium
                    strSQL = "SELECT MDM_MediumId FROM MBD_SchoolMedium WHERE MDM_SchoolId = " & iSchoolId
                    cmdData.CommandText = strSQL
                    cmdData.CommandType = CommandType.Text
                    cmdData.Connection = dbConnection
                    dtrData = cmdData.ExecuteReader
                    While dtrData.Read()
			'do whatever you want
                    End While
                    dtrData.Close()

                    'Like this many more datareaders
                    'dtrData.Close()
                End If
            Catch ex As Exception
                GlobalMethods.ShowMessage(Me, "Error:" & ex.Message)
            Finally
                If (dbConnection.State <> ConnectionState.Broken And dbConnection.State <> ConnectionState.Closed) Then
                    dbConnection.Close()
                End If
            End Try
    End Sub
[17 Mar 2010 13:29] Tonci Grgin
Srinivas, I am unable to repeat the problem described. There are plenty of test cases I attached to reports in BugsDB and not a single one raises the error. Also, your test case attached does not reproduce it! You are again hiding the real code used as well as the nature of project (I think it's web based).

Last test I used is:
            MySqlConnection conn = new MySqlConnection();
            conn.ConnectionString = "DataSource=xx;Database=test;UserID=xx;Password=xx;PORT=xx;logging=True;oldGuids = false;charset=utf8;";
            conn.Open();
            MySqlCommand cmd = conn.CreateCommand();
            cmd.CommandTimeout = 50;

            cmd.CommandText = "SELECT * FROM mysql.user"; //As I do not have your table structures nor data
            dr = cmd.ExecuteReader();
            while (dr.Read()) //Just some random reads
            {
                Console.WriteLine("V DataTypeName(1): " + dr.GetDataTypeName(1));
                Console.WriteLine("V GetFieldType(1): " + dr.GetFieldType(1));
                Console.WriteLine(dr.GetString(0));
            }
            dr.Close();

            cmd.CommandText = "SELECT * FROM mysql.proc";
            dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                Console.WriteLine("V DataTypeName(1): " + dr.GetDataTypeName(1));
                Console.WriteLine("V GetFieldType(1): " + dr.GetFieldType(1));
                Console.WriteLine(dr.GetString(0));
            }
            dr.Close();
                
            cmd.Dispose();
            conn.Close();
        }
        catch (Exception ex)
        {
            Console.Out.WriteLine(DateTime.UtcNow.ToLongTimeString() + "  " + "Exception: " + ex.Message);
            throw;
        }
This works as expected.

So, check your tables, connection, SQL, firewalls, application etc and see what is actually wrong. You definitely have a thread or service still fetching by the time connection's already closed.
[18 Mar 2010 5:25] D Srinivas
Hi Tonci Grgin,

How can I send the entire code file to you. It is confidential. Hope you understand. Please tell me.

Thanks.

Best regards,
D.Srinivas.
[18 Mar 2010 5:27] D Srinivas
More over the same code is working with .Net Connector/NET 5.2.6.0 as well as 6.0.2.0. Strangely it is not working with .Net Connector/Net 6.2.2.0.