Exemple #1
0
        private void Connect_Read_Template_Raw(ref DataSet products)
        {
            // When reading raw data from the database (DatabaseReadTechnology.eRbRead_DataSet, using IDbDataAdapter)
            int recordsRead = 0;

            Console.WriteLine("\t{0}{1}{2}",
                              Northwind_Products.colProductID.PadRight(Northwind_Products.colProductIDWidth),
                              Northwind_Products.colUnitPrice.PadRight(Northwind_Products.colUnitPriceWidth),
                              Northwind_Products.colProductName);

            foreach (DataRow p in products.Tables[0].Rows)
            {
                try
                {
                    recordsRead++;
                    Console.WriteLine("\t{0}{1}{2}",
                                      ((int)p[Northwind_Products.colProductID]).ToString().PadRight(Northwind_Products.colProductIDWidth),
                                      ((decimal)p[Northwind_Products.colUnitPrice]).ToString("0.00").PadRight(Northwind_Products.colUnitPriceWidth),
                                      (string)p[Northwind_Products.colProductName]);
                }
                catch (Exception ex)
                {
                    //throw;
                    // Consider handling exception (instead of re-throwing) if graceful recovery is possible
                    Console.WriteLine(UtilitiesGeneral.FormatException(
                                          this.ToString(), System.Reflection.MethodBase.GetCurrentMethod().Name, ex.Message));
                }
            }
            Console.WriteLine("    ({0} records)", recordsRead);

            // Demonstrating searching for a specific record
        }
Exemple #2
0
        private string GetFieldTypeAsString(DAO.Field fd)
        {
            // Convert DAO.Type to a human-readable string. This can be converted like this:
            //       ((DAO.DataTypeEnum)DAO.Field .Type).ToString())
            // but returns something like "dbText", when we want to display "Text" (or similar).

            // Alternatively, use a giant switch:

            /*  switch (type)
             *  {
             *      case (short)DAO.DataTypeEnum.dbBoolean:
             *      strType = "Boolean";
             *          break;
             *      // etc...
             */
            string strType = "Unknown";

            try
            {
                strType = ((DAO.DataTypeEnum)fd.Type).ToString().Replace("db", "");
            }
            catch (Exception ex)
            {
                Console.WriteLine(UtilitiesGeneral.FormatException(
                                      this.ToString(), System.Reflection.MethodBase.GetCurrentMethod().Name, ex.Message));
            }
            return(strType);
        }
Exemple #3
0
        public List <string> GetFields(string strConnection, string strTable)
        {
            // Return a list of the columns in the supplied table
            List <string> columns = new List <string>();

            DAO.DBEngine dbEngine = new DAO.DBEngine();
            dbEngine.Idle(DAO.IdleEnum.dbRefreshCache);
            DAO.Database db = dbEngine.OpenDatabase(strConnection, false, false);
            if (db.TableDefs.Count > 0)
            {
                try
                {
                    if (db.TableDefs[strTable].Fields.Count > 0)
                    {
                        columns.Add(m_fieldHeader);
                        foreach (DAO.Field fd in db.TableDefs[strTable].Fields)
                        {
                            columns.Add(string.Format(Schema_Header_Column_Formatting,
                                                      fd.Name,
                                                      fd.Type,
                                                      GetFieldTypeAsString(fd),
                                                      fd.Size,
                                                      fd.Required));
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(UtilitiesGeneral.FormatException(
                                          this.ToString(), System.Reflection.MethodBase.GetCurrentMethod().Name, ex.Message));
                }
            }
            db.Close();
            return(columns);
        }
Exemple #4
0
        private void Connect_Read_Raw(string strConnection)
        {
            // Create and open the connection in a using block. This ensures that all resources will be
            // closed and disposed when the code exits.
            if (m_eDbReadTechnology == DatabaseReadTechnology.eRbRead_DataReader)
            {
                Console.WriteLine("(raw)");
                using (OdbcConnection connection = new OdbcConnection(strConnection))
                {
                    // Create the Command and Parameter objects
                    OdbcCommand command = new OdbcCommand(m_cfgDatabase.querySELECT, connection);
                    command.Parameters.AddWithValue("@pricePoint", m_cfgDatabase.paramValue);

                    // Open the connection in a try/catch block
                    try
                    {
                        // Create and execute the DataReader, writing the result to the console window
                        Northwind_Products rsTmp = new Northwind_Products();
                        Console.WriteLine("\t{0}{1}{2}",
                                          Northwind_Products.colProductID.PadRight(Northwind_Products.colProductIDWidth),
                                          Northwind_Products.colUnitPrice.PadRight(Northwind_Products.colUnitPriceWidth),
                                          Northwind_Products.colProductName);

                        int recordsRead = 0;
                        connection.Open();
                        OdbcDataReader reader = command.ExecuteReader();
                        while (reader.Read())
                        {
                            recordsRead++;
                            Console.WriteLine("\t{0}{1}{2}",
                                              ((int)reader[Northwind_Products.colProductID]).ToString().PadRight(Northwind_Products.colProductIDWidth),
                                              ((decimal)reader[Northwind_Products.colUnitPrice]).ToString("0.00").PadRight(Northwind_Products.colUnitPriceWidth),
                                              (string)reader[Northwind_Products.colProductName]);
                            // Note: The reader returns 3 items (since the query was for three fields). You can access them
                            // with reader[0], reader[1], and so on. Using the field name is preferable, though, because
                            // then we are less dependent on the order of fields in the SQL query.
                        }
                        reader.Close();
                        Console.WriteLine("    ({0} records)", recordsRead);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(UtilitiesGeneral.FormatException(
                                              this.ToString(), System.Reflection.MethodBase.GetCurrentMethod().Name, ex.Message));
                    }
                }
                Console.WriteLine();
            }
            // Do nothing for DatabaseReadTechnology.eRbRead_DataAdapter
        }
Exemple #5
0
        protected override void Connect_Read(string strConnection)
        {
            // Use the DAO::DBEngine to open an Access database and read recordsets

            // Note: On one machine running Windows 10 and Office 365, the DBEngine had these details:
            // * TypeLib = {4AC9E1DA-5BAD-4AC7-86E3-24F4CDCECA28}
            // * Name = Microsoft Office 16.0 Access Database Engine Object Library
            // * Assembly = Microsoft.Office.Interop.Access.Dao, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71E9BCE111E9429C
            // * Path = C:\Program Files\Microsoft Office\root\VFS\ProgramFilesCommonX64\Microsoft Shared\Office16\ACEDAO.DLL
            DAO.DBEngine dbEngine = new DAO.DBEngine();
            dbEngine.Idle(DAO.IdleEnum.dbRefreshCache);

            DAO.Database db = dbEngine.OpenDatabase(strConnection, false, false);
            DAO.Recordset rs = db.OpenRecordset(
                m_cfgDatabase.querySELECT,
                DAO.RecordsetTypeEnum.dbOpenDynaset,
                DAO.RecordsetOptionEnum.dbReadOnly);
            if (!(rs.BOF && rs.EOF))
            {
                // Go through each record in the RecordSet, writing the result to the console window
                Simple_Members rsMember = new Simple_Members();
                Console.WriteLine(rsMember.GetRecordHeader());

                int recordsRead = 0;
                rs.MoveFirst();
                dbEngine.Idle(DAO.IdleEnum.dbFreeLocks);
                while (!rs.EOF)
                {
                    recordsRead++;
                    try
                    {
                        ConvertRecordset(in rs, ref rsMember);
                        Console.WriteLine(rsMember.GetRecordAsString());
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(UtilitiesGeneral.FormatException(
                            this.ToString(), System.Reflection.MethodBase.GetCurrentMethod().Name, ex.Message));
                    }
                    rs.MoveNext();
                    dbEngine.Idle(DAO.IdleEnum.dbFreeLocks);
                }
                rs.Close();
                Console.WriteLine("    ({0} records)", recordsRead);
            }

            db.Close();
            Console.WriteLine();
        }
Exemple #6
0
 public bool DoesFieldExist(DAO.Database db, string strTable, string strField)
 {
     // DAO: HelperBoolFieldToString function to determine if a field exists
     try
     {
         DAO.Field ThisField = db.TableDefs[strTable].Fields[strField];
         return(true);
     }
     catch (Exception ex)
     {
         Console.WriteLine(UtilitiesGeneral.FormatException(
                               this.ToString(), System.Reflection.MethodBase.GetCurrentMethod().Name, ex.Message));
     }
     return(false);
 }
Exemple #7
0
        public DAO.Field SafeGetField(DAO.Recordset rs, string strField)
        {
            // DAO: Helper function for recordset fields
            object objField = null;

            try
            {
                objField = rs.Fields[strField];
            }
            catch (Exception ex)
            {
                Console.WriteLine(UtilitiesGeneral.FormatException(
                                      this.ToString(), System.Reflection.MethodBase.GetCurrentMethod().Name, ex.Message));
            }
            return((DAO.Field)objField);
        }
Exemple #8
0
        public object SafeGetFieldValue(DAO.Recordset rs, string strField)
        {
            // DAO: Helper function for recordsets which may contain a null value
            object objResult = null;

            try
            {
                if (rs.Fields[strField].Value != null)
                {
                    objResult = rs.Fields[strField].Value;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(UtilitiesGeneral.FormatException(
                                      this.ToString(), System.Reflection.MethodBase.GetCurrentMethod().Name, ex.Message));
            }
            return(objResult);
        }
Exemple #9
0
        public override string GetDbName(string strConnection)
        {
            // Get the name of the database associated with the connection string
            string dbName = string.Empty;

            try
            {
                DAO.DBEngine dbEngine = new DAO.DBEngine();
                dbEngine.Idle(DAO.IdleEnum.dbRefreshCache);
                DAO.Database db = dbEngine.OpenDatabase(strConnection, false, false);
                dbName = db.Name;
                db.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(UtilitiesGeneral.FormatException(
                                      this.ToString(), System.Reflection.MethodBase.GetCurrentMethod().Name, ex.Message));
            }
            return(dbName);
        }
Exemple #10
0
        private void Connect_Read_Raw(string strConnection)
        {
            // Create and open the connection in a using block. This ensures that all resources
            // will be closed and disposed when the code exits.
            Console.WriteLine("(raw)");
            using (OdbcConnection connection = new OdbcConnection(strConnection))
            {
                // Create the Command and Parameter objects
                OdbcCommand command = new OdbcCommand(m_cfgDatabase.querySELECT, connection);
                command.Parameters.AddWithValue("@pricePoint", m_cfgDatabase.paramValue);

                // Open the connection in a try/catch block
                try
                {
                    // Create and execute the DataReader, writing the result to the console window
                    Simple_Members rsMember = new Simple_Members();
                    Console.WriteLine(rsMember.GetRecordHeader());

                    int recordsRead = 0;
                    connection.Open();
                    OdbcDataReader reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        recordsRead++;
                        ConvertRecordset(in reader, ref rsMember);
                        Console.WriteLine(rsMember.GetRecordAsString());
                    }
                    reader.Close();
                    Console.WriteLine("    ({0} records)", recordsRead);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(UtilitiesGeneral.FormatException(
                                          this.ToString(), System.Reflection.MethodBase.GetCurrentMethod().Name, ex.Message));
                }
            }

            Console.WriteLine();
        }
Exemple #11
0
 protected override void Connect_Insert(string strConnection)
 {
     // Run a command against the database
     // Note: You may want to back up the database before running this code!
     using (OdbcConnection connection = new OdbcConnection(strConnection))
     {
         OdbcCommand command = new OdbcCommand(m_cfgDatabase.queryINSERT, connection);
         connection.Open();
         try
         {
             int    rowsAffected = command.ExecuteNonQuery();
             string dbName       = m_utilsDbConnection.GetDbName(connection);
             Console.WriteLine("{0} rows inserted into {1}", rowsAffected, m_utilsDbConnection.GetDbName(connection));
         }
         catch (Exception ex)
         {
             string dbName = m_utilsDbConnection.GetDbName(connection);
             Console.WriteLine(UtilitiesGeneral.FormatException(
                                   this.ToString(),
                                   System.Reflection.MethodBase.GetCurrentMethod().Name,
                                   ex.Message + m_utilsDbConnection.GetDbName(connection)));
         }
     }
 }
Exemple #12
0
        private void ConvertRowToSchemaColumns(ref SchemaFieldDefinition fd, DataRow row, DbConnection connection)
        {
            // Helper function to convert schema information (in a DataRow variable) into our own format
            if (connection is OdbcConnection)
            {
                // ODBC
                try
                {
                    fd.name = (string)row[m_utilsODBC.Schema_Columns_ODBC_Name];

                    // For ODBC data types, preferentially use "TYPE_NAME" to determine the field type. ODBC must work
                    // across multiple data sources and the mappings from underlying SQL data types to ODBC type
                    // identifiers are only approximate.
                    // Note: The "DATA_TYPE" column for ODBC data sources is actually an Int16
                    fd.type = Convert.ToInt32(row[m_utilsODBC.Schema_Columns_ODBC_Type]);

                    fd.typeName = (string)row[m_utilsODBC.Schema_Columns_ODBC_TypeName];
                    fd.size     = (int)row[m_utilsODBC.Schema_Columns_ODBC_Size];
                    fd.nullable = (string)row[m_utilsODBC.Schema_Columns_ODBC_Nullable];
                }
                catch (Exception ex)
                {
                    Console.WriteLine(UtilitiesGeneral.FormatException(
                                          this.ToString(), System.Reflection.MethodBase.GetCurrentMethod().Name, ex.Message));
                    fd.name = "(name)";

                    // The value contained in COUNTER or INTEGER columns is "4", but the value of "4" in
                    // System.Data.Odbc.OdbcType is "Char" (and the "Int" type is "10"). These appear to be different
                    // types...to be investigated.
                    fd.type = (int)OdbcType.Int;

                    fd.typeName = "(type)";
                    fd.size     = -1;
                    fd.nullable = "(nullable)";
                }
            }
            else if (connection is OleDbConnection)
            {
                // OleDB
                try
                {
                    fd.name = (string)row[m_utilsOleDB.Schema_Columns_OleDB_Name];
                    fd.type = (int)row[m_utilsOleDB.Schema_Columns_OleDB_Type];
                    if (Enum.IsDefined(typeof(OleDbType), fd.type))
                    {
                        fd.typeName = ((OleDbType)fd.type).ToString();
                    }

                    // Note:
                    // NUMERIC_PRECISION            => Int32
                    // CHARACTER_MAXIMUM_LENGTH     => Int64
                    // DATETIME_PRECISION           => Int64
                    fd.size     = Convert.ToInt32(row[m_utilsOleDB.GetOleDBTypeSchemaSizeColumn(fd.type)]);
                    fd.nullable = Convert.ToString(row[m_utilsOleDB.Schema_Columns_OleDB_Nullable]);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(UtilitiesGeneral.FormatException(
                                          this.ToString(), System.Reflection.MethodBase.GetCurrentMethod().Name, ex.Message));
                    fd.name     = "(name)";
                    fd.type     = (int)OleDbType.Integer;
                    fd.typeName = "(type)";
                    fd.size     = -1;
                    fd.nullable = "(nullable)";
                }
            }
        }
Exemple #13
0
        private void GetSchemaTables(ref List <string> tables, DbConnection connection, bool stdTablesOnly = false)
        {
            // Retrieve "Tables" schema information, which differs between connection types. To see all columns,
            // use "GetSchemaTablesFull".

            #region Schema details

            /* ### OdbcConnection ###
             * See https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/odbc-schema-collections
             * ColumnName          DataType    Description
             * TABLE_CAT           String      Name of database (eg. C:\Apps\Data\Northwind 2000)
             * TABLE_SCHEM         String      ?
             * TABLE_NAME          String      Name of table (eg. Customers)
             * TABLE_TYPE          String      Type of table ("SYSTEM TABLE" or "TABLE") [the ODBC "Tables" schema does not include Views]
             * REMARKS             String      Description of table
             * Note, 1: Schema information may differ between ODBC drivers
             * Note, 2: The above schema applies to Views as well */

            /* ### OleDbConnection ###
             * See https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/ole-db-schema-collections
             * ColumnName          DataType    Description
             * TABLE_CATALOG       String      ?
             * TABLE_SCHEMA        String      ?
             * TABLE_NAME          String      Name of table (eg. Customers)
             * TABLE_TYPE          String      Type of table or view ("ACCESS TABLE", "TABLE" or "VIEW")
             * TABLE_GUID          Guid        ?
             * DESCRIPTION         String      Description of table
             * TABLE_PROPID        Int64       ?
             * DATE_CREATED        DateTime    Date created (eg. 13/09/1995 10:51:45)
             * DATE_MODIFIED       DateTime    Date modified (eg. 12/03/2003 05:09:58) */
            #endregion // Schema details

            DataTable schemaTables = connection.GetSchema(Schema_Tables);
            bool      addTable     = true;
            foreach (DataRow row in schemaTables.Rows)
            {
                addTable = true;
                if (stdTablesOnly)
                {
                    try
                    {
                        if (connection is OdbcConnection)
                        {
                            // ODBC
                            addTable = (!row[Schema_Tables_Column_TableType].Equals(m_utilsODBC.Schema_Tables_ODBC_SystemTable));
                        }
                        else if (connection is OleDbConnection)
                        {
                            // OleDB
                            addTable = (
                                (!row[Schema_Tables_Column_TableType].Equals(m_utilsOleDB.Schema_Tables_OleDB_SystemTable)) &&
                                (!row[Schema_Tables_Column_TableType].Equals(m_utilsOleDB.Schema_Tables_OleDB_ViewTable)));
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(UtilitiesGeneral.FormatException(
                                              this.ToString(), System.Reflection.MethodBase.GetCurrentMethod().Name, ex.Message));
                    }
                }

                if (addTable)
                {
                    foreach (DataColumn col in schemaTables.Columns)
                    {
                        // Add the tables names. These are held in the "TABLE_NAME" column.
                        if (col.ColumnName.Equals(Schema_Tables_Column_TableName))
                        {
                            tables.Add((string)row[col]);
                        }
                    }
                }
            }
        }
Exemple #14
0
        protected override Simple_Members Map(DataRow row, UInt64 uRecordsToRead)
        {
            // Mapper working with DataRow objects
            string         error = string.Empty;
            Simple_Members m     = new Simple_Members();

            m.DefaultRecord();
            try
            {
                m.MemberID = (DBNull.Value == row[Simple_Members.colMemberID])
                    ? Simple_Members.cDefaultMemberID
                    : (int)row[Simple_Members.colMemberID];
            }
            catch (Exception ex) { error = ex.Message; }

            try
            {
                m.Surname = (DBNull.Value == row[Simple_Members.colSurname])
                    ? Simple_Members.cDefaultSurname
                    : (string)row[Simple_Members.colSurname];
            }
            catch (Exception ex) { error = ex.Message; }

            try
            {
                m.FirstName = (DBNull.Value == row[Simple_Members.colFirstName])
                    ? Simple_Members.cDefaultFirstName
                    : (string)row[Simple_Members.colFirstName];
            }
            catch (Exception ex) { error = ex.Message; }

            try
            {
                m.DOB = (DBNull.Value == row[Simple_Members.colDOB])
                    ? Simple_Members.cDefaultDOB
                    : (DateTime)row[Simple_Members.colDOB];
            }
            catch (Exception ex) { error = ex.Message; }

            try
            {
                m.Fee = (DBNull.Value == row[Simple_Members.colFee])
                    ? Simple_Members.cDefaultFee
                    : (decimal)row[Simple_Members.colFee];
            }
            catch (Exception ex) { error = ex.Message; }

            try
            {
                m.Accepted = (DBNull.Value == row[Simple_Members.colAccepted])
                    ? Simple_Members.cDefaultAccepted
                    : (bool)row[Simple_Members.colAccepted];
            }
            catch (Exception ex) { error = ex.Message; }

            try
            {
                m.Points = (DBNull.Value == row[Simple_Members.colPoints])
                    ? Simple_Members.cDefaultPoints
                    : (int)row[Simple_Members.colPoints];
            }
            catch (Exception ex) { error = ex.Message; }

            if (!string.IsNullOrEmpty(error))
            {
                Console.WriteLine(UtilitiesGeneral.FormatException(
                                      this.ToString(), System.Reflection.MethodBase.GetCurrentMethod().Name, error));
            }

            return(m);
        }
Exemple #15
0
        protected override Northwind_Products Map(DataRow row, UInt64 uRecordsToRead)
        {
            // Mapper working with DataRow objects
            string             error = string.Empty;
            Northwind_Products p     = new Northwind_Products();

            p.DefaultRecord();
            if ((uRecordsToRead & Northwind_Products.colToReadProductID) != 0)
            {
                try
                {
                    p.ProductID = (DBNull.Value == row[Northwind_Products.colProductID])
                        ? Northwind_Products.cDefaultProductID
                        : (int)row[Northwind_Products.colProductID];
                }
                catch (Exception ex) { error = ex.Message; }
            }

            if ((uRecordsToRead & Northwind_Products.colToReadProductName) != 0)
            {
                try
                {
                    p.ProductName = (DBNull.Value == row[Northwind_Products.colProductName])
                        ? Northwind_Products.cDefaultProductName
                        : (string)row[Northwind_Products.colProductName];
                }
                catch (Exception ex) { error = ex.Message; }
            }

            if ((uRecordsToRead & Northwind_Products.colToReadSupplierID) != 0)
            {
                try
                {
                    p.SupplierID = (DBNull.Value == row[Northwind_Products.colSupplierID])
                        ? Northwind_Products.cDefaultSupplierID
                        : (int)row[Northwind_Products.colSupplierID];
                }
                catch (Exception ex) { error = ex.Message; }
            }

            if ((uRecordsToRead & Northwind_Products.colToReadCategoryID) != 0)
            {
                try
                {
                    p.CategoryID = (DBNull.Value == row[Northwind_Products.colCategoryID])
                        ? Northwind_Products.cDefaultCategoryID
                        : (int)row[Northwind_Products.colCategoryID];
                }
                catch (Exception ex) { error = ex.Message; }
            }

            if ((uRecordsToRead & Northwind_Products.colToReadQuantityPerUnit) != 0)
            {
                try
                {
                    p.QuantityPerUnit = (DBNull.Value == row[Northwind_Products.colQuantityPerUnit])
                        ? Northwind_Products.cDefaultQuantityPerUnit
                        : (string)row[Northwind_Products.colQuantityPerUnit];
                }
                catch (Exception ex) { error = ex.Message; }
            }

            if ((uRecordsToRead & Northwind_Products.colToReadUnitPrice) != 0)
            {
                try
                {
                    p.UnitPrice = (DBNull.Value == row[Northwind_Products.colUnitPrice])
                        ? Northwind_Products.cDefaultUnitPrice
                        : (decimal)row[Northwind_Products.colUnitPrice];
                }
                catch (Exception ex) { error = ex.Message; }
            }

            if ((uRecordsToRead & Northwind_Products.colToReadUnitsInStock) != 0)
            {
                try
                {
                    p.UnitsInStock = (DBNull.Value == row[Northwind_Products.colUnitsInStock])
                        ? Northwind_Products.cDefaultUnitsInStock
                        : (int)row[Northwind_Products.colUnitsInStock];
                }
                catch (Exception ex) { error = ex.Message; }
            }

            if ((uRecordsToRead & Northwind_Products.colToReadUnitsOnOrder) != 0)
            {
                try
                {
                    p.UnitsOnOrder = (DBNull.Value == row[Northwind_Products.colUnitsOnOrder])
                        ? Northwind_Products.cDefaultUnitsOnOrder
                        : (int)row[Northwind_Products.colUnitsOnOrder];
                }
                catch (Exception ex) { error = ex.Message; }
            }

            if ((uRecordsToRead & Northwind_Products.colToReadReorderLevel) != 0)
            {
                try
                {
                    p.ReorderLevel = (DBNull.Value == row[Northwind_Products.colReorderLevel])
                        ? Northwind_Products.cDefaultReorderLevel
                        : (int)row[Northwind_Products.colReorderLevel];
                }
                catch (Exception ex) { error = ex.Message; }
            }

            if ((uRecordsToRead & Northwind_Products.colToReadDiscontinued) != 0)
            {
                try
                {
                    p.Discontinued = (DBNull.Value == row[Northwind_Products.colDiscontinued])
                        ? Northwind_Products.cDefaultDiscontinued
                        : (bool)row[Northwind_Products.colDiscontinued];
                }
                catch (Exception ex) { error = ex.Message; }
            }

            if (!string.IsNullOrEmpty(error))
            {
                Console.WriteLine(UtilitiesGeneral.FormatException(
                                      this.ToString(), System.Reflection.MethodBase.GetCurrentMethod().Name, error));
            }

            return(p);
        }
Exemple #16
0
        private void Connect_Read_Raw(string strConnection)
        {
            // Create and open the connection in a using block. This ensures that all resources
            // will be closed and disposed when the code exits.
            Console.WriteLine("(raw)");
            using (OleDbConnection connection = new OleDbConnection(strConnection))
            {
                // Open the connection in a try/catch block
                try
                {
                    if (m_eDbReadTechnology == DatabaseReadTechnology.eRbRead_DataReader)
                    {
                        // Using System.Data.OleDb.OleDbDataReader : IDataReader
                        Console.WriteLine("(OleDb.OleDbDataReader)");

                        // Create and open the connection in a using block. This ensures that all resources
                        // will be closed and disposed when the code exits.

                        // Note:
                        // * "DbConnection" is the base class for OleDbConnection, OdbcConnection
                        // * "DbCommand" is the base class for OleDbCommand, OdbcCommand
                        // * "DbParameterCollection" is the base class for OleDbParameterCollection, OdbcParameterCollection
                        // * "DbDataReader" is the base class for OleDbDataReader, OdbcDataReader
                        // We could write a generic function to access the database with OleDB or ODBC, but it
                        // is simpler to write an unique method for each technology.

                        // Create and execute the DataReader, writing the result to the console window
                        int recordsRead = 0;
                        Console.WriteLine("\t{0}{1}{2}",
                                          Northwind_Products.colProductID.PadRight(Northwind_Products.colProductIDWidth),
                                          Northwind_Products.colUnitPrice.PadRight(Northwind_Products.colUnitPriceWidth),
                                          Northwind_Products.colProductName);

                        connection.Open();
                        OleDbCommand command = new OleDbCommand(m_cfgDatabase.querySELECT, connection);
                        command.Parameters.AddWithValue("@pricePoint", m_cfgDatabase.paramValue);
                        // This also works: command.Parameters.AddWithValue(string.Empty, paramValue);

                        OleDbDataReader reader = command.ExecuteReader();
                        while (reader.Read())
                        {
                            recordsRead++;
                            Console.WriteLine("\t{0}{1}{2}",
                                              ((int)reader[Northwind_Products.colProductID]).ToString().PadRight(Northwind_Products.colProductIDWidth),
                                              ((decimal)reader[Northwind_Products.colUnitPrice]).ToString("0.00").PadRight(Northwind_Products.colUnitPriceWidth),
                                              (string)reader[Northwind_Products.colProductName]);
                        }
                        reader.Close();
                        Console.WriteLine("    ({0} records)", recordsRead);
                    }
                    else if (m_eDbReadTechnology == DatabaseReadTechnology.eRbRead_DataAdapter)
                    {
                        // This version uses:
                        // * System.Data.DataSet
                        // * System.Data.OleDb.OleDbDataAdapter : IDbDataAdapter
                        // * System.Data.DataRow
                        Console.WriteLine("(DataSet, OleDb.OleDbDataAdapter and DataRow)");

                        // Create and fill the DataSet, writing the result to the console window
                        int recordsRead = 0;
                        Console.WriteLine("\t{0}{1}{2}",
                                          Northwind_Products.colProductID.PadRight(Northwind_Products.colProductIDWidth),
                                          Northwind_Products.colUnitPrice.PadRight(Northwind_Products.colUnitPriceWidth),
                                          Northwind_Products.colProductName);

                        connection.Open();
                        DataSet          ds      = new DataSet();
                        OleDbDataAdapter adapter = new OleDbDataAdapter(m_cfgDatabase.querySELECT, connection);
                        adapter.SelectCommand.Parameters.Add("@pricePoint", OleDbType.Integer).Value = m_cfgDatabase.paramValue;
                        adapter.Fill(ds);
                        foreach (DataRow row in ds.Tables[0].Rows)
                        {
                            recordsRead++;
                            Console.WriteLine("\t{0}{1}{2}",
                                              ((int)row[Northwind_Products.colProductID]).ToString().PadRight(Northwind_Products.colProductIDWidth),
                                              ((decimal)row[Northwind_Products.colUnitPrice]).ToString("0.00").PadRight(Northwind_Products.colUnitPriceWidth),
                                              (string)row[Northwind_Products.colProductName]);
                        }
                        Console.WriteLine("    ({0} records)", recordsRead);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(UtilitiesGeneral.FormatException(
                                          this.ToString(), System.Reflection.MethodBase.GetCurrentMethod().Name, ex.Message));
                }
            }

            Console.WriteLine();
        }