Search code examples
excelexceptionoledb

OleDb Object Invalid or No Longer Set


I'm trying to read an excel file using an OleDb Reader, I couldn't debug the code because this error only comes out on a production server. It really doesn't make sense to me, could anyone help me?

From the logs the error comes out as:

System.Data.OleDb.OleDbException: Object invalid or no longer set. at System.Data.OleDb.OleDbConnectionInternal.ProcessResults(OleDbHResult hr) at System.Data.OleDb.OleDbConnectionInternal.GetSchemaRowset(Guid schema, Object[] restrictions) at System.Data.OleDb.OleDbConnection.GetOleDbSchemaTable(Guid schema, Object[] restrictions) at System.Data.OleDb.OleDbMetaDataFactory.PrepareCollection(String collectionName, String[] restrictions, DbConnection connection) at System.Data.ProviderBase.DbMetaDataFactory.GetSchema(DbConnection connection, String collectionName, String[] restrictions) at System.Data.ProviderBase.DbConnectionInternal.GetSchema(DbConnectionFactory factory, DbConnectionPoolGroup poolGroup, DbConnection outerConnection, String collectionName, String[] restrictions) at System.Data.OleDb.OleDbConnection.GetSchema(String collectionName, String[] restrictionValues) at System.Data.OleDb.OleDbConnection.GetSchema(String collectionName)

Also, a little while before this error appeared, I had a

System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. at System.Data.Common.UnsafeNativeMethods.IDBSchemaRowset.GetRowset(IntPtr pUnkOuter, Guid& rguidSchema, Int32 cRestrictions, Object[] rgRestrictions, Guid& riid, Int32 cPropertySets, IntPtr rgPropertySets, IRowset& ppRowset) at System.Data.OleDb.OleDbConnectionInternal.GetSchemaRowset(Guid schema, Object[] restrictions) at System.Data.OleDb.OleDbConnection.GetOleDbSchemaTable(Guid schema, Object[] restrictions) at System.Data.OleDb.OleDbMetaDataFactory.PrepareCollection(String collectionName, String[] restrictions, DbConnection connection) at System.Data.ProviderBase.DbMetaDataFactory.GetSchema(DbConnection connection, String collectionName, String[] restrictions) at System.Data.ProviderBase.DbConnectionInternal.GetSchema(DbConnectionFactory factory, DbConnectionPoolGroup poolGroup, DbConnection outerConnection, String collectionName, String[] restrictions) at System.Data.OleDb.OleDbConnection.GetSchema(String collectionName, String[] restrictionValues) at System.Data.OleDb.OleDbConnection.GetSchema(String collectionName)

exception as well. I don't know if they are related. Can anyone point me in the right direction?

The code I'm using to read the file is

            DateTime start = DateTime.Now;
            IEnumerable<string> worksheetNames = GetWorkbookWorksheetNames( connString );
            using ( OleDbConnection connection = new OleDbConnection( connString ) )
            {
                connection.Open();
                foreach ( string worksheetName in worksheetNames )
                {
                    using ( OleDbCommand command = 
                        new OleDbCommand( "SELECT * FROM [" + worksheetName + "]", connection ) )
                    {
                        TEntity entity;
                        using ( OleDbDataReader dataReader = command.ExecuteReader() )
                        {
                            while ( dataReader.Read() )
                            {
                                entity = GetDataFromDataTable( dataReader );

                                if ( entity != null )
                                {
                                    entityList.Add( entity );
                                }
                            }
                        }
                    }
                }
                connection.Close();

GetWorkbookWorksheetNames contains

private IEnumerable<string> GetWorkbookWorksheetNames( string connString )
    {
        LogUtil.Info( "Getting workbook worksheet names" );
        OleDbConnection _connection = new OleDbConnection( connString );
        List<string> _tableNames = new List<string>();
        try
        {
            // Error Handle
            _connection.Open();
            // Gets the worksheet names
            DataTable _excelSchema = _connection.GetSchema( "Tables" );

            if ( _excelSchema.Rows.Count < 1 )
            {
                throw new FormatException( "The file is in an invalid format. No worksheets were found." );
            }

            foreach ( DataRow _excelSchemaRow in _excelSchema.Rows )
            {
                _tableNames.Add( Regex.Replace( (string)_excelSchemaRow["TABLE_NAME"], "_$", "" ) );
            }
        }
        catch ( OleDbException ex )
        {
            LogUtil.Error( "Could not get Workbook Worksheet names." );
            LogUtil.Error( ex );
            throw ex;
        }
        finally
        {
            _connection.Close();
        }
        return _tableNames;
    }

And I'm sure the error doesn't get to GetDataFromDataTable()

EDIT: The connection string I'm using is:

        string connString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
                        "Data Source=" + filePath + ";" +
                        "Extended Properties=\"Excel 8.0;HDR=No;IMEX=1\";";

I also found out, further back in my logs, another error that made no sense to me at all. I didn't notice this before but it took place just before the AccessViolationException.

No error message available, result code: E_UNEXPECTED(0x8000FFFF). at System.Data.OleDb.OleDbConnectionInternal..ctor(OleDbConnectionString constr, OleDbConnection connection) at System.Data.OleDb.OleDbConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningObject) at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup) at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) at System.Data.OleDb.OleDbConnection.Open() at REMEC.Library.WatcherServiceCommon.ExcelParserService`1.GetWorkbookWorksheetNames(String connString) in

And while simulating this error under a test, the thread never stops, making me assume that said error does not actually close the connection even after explicitly closing it on my finally clause.

Sorry for the long blocks of code/text


Solution

  • Possibly - ConnStr Value Problem;
    Try this:

    private String[] GetExcelSheetNames(string excelFile) { OleDbConnection objConn = null; System.Data.DataTable dt = null;

      try
      {
        // Connection String. Change the excel file to the file you
        // will search.
    
        String connString = "Provider=Microsoft.Jet.OLEDB.4.0;" + 
            "Data Source=" + excelFile + ";Extended Properties=Excel 8.0;";
        // Create connection object by using the preceding connection string.
    
        objConn = new OleDbConnection(connString);
        // Open connection with the database.
    
        objConn.Open();
    
        // Get the data table containg the schema guid.    
        dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
    
        if(dt == null)
        {
          return null;
        }
    
        String[] excelSheets = new String[dt.Rows.Count];
        int i = 0;
    
        // Add the sheet name to the string array.
    
        foreach(DataRow row in dt.Rows)
        {
          excelSheets[i] = row["TABLE_NAME"].ToString();
          i++;
        }
    
        // Loop through all of the sheets if you want too...
    
        for(int j=0; j < excelSheets.Length; j++)
        {
          // Query each excel sheet.
    
        }
    
        return excelSheets;
      }
      catch(Exception ex)
      {
        return null;
      }
      finally
      {
        // Clean up.
    
        if(objConn != null)
        {
          objConn.Close();
          objConn.Dispose();
        }
        if(dt != null)
        {
          dt.Dispose();
        }
      }
    }