コード例 #1
0
        private static DataTable GetColumnsCollection(string?[]?restrictions, OdbcConnection connection)
        {
            OdbcCommand?   command     = null;
            OdbcDataReader?dataReader  = null;
            DataTable?     resultTable = null;
            const int      columnsRestrictionsCount = 4;

            try
            {
                command = GetCommand(connection);
                string[] allRestrictions = new string[columnsRestrictionsCount];
                FillOutRestrictions(columnsRestrictionsCount, restrictions, allRestrictions, OdbcMetaDataCollectionNames.Columns);

                dataReader = command.ExecuteReaderFromSQLMethod(allRestrictions, ODBC32.SQL_API.SQLCOLUMNS);

                resultTable = DataTableFromDataReader(dataReader, OdbcMetaDataCollectionNames.Columns);
            }

            finally
            {
                dataReader?.Dispose();;
                command?.Dispose();;
            }
            return(resultTable);
        }
コード例 #2
0
ファイル: DataAdapter.cs プロジェクト: layomia/dotnet_runtime
        internal int FillFromReader(DataSet?dataset, DataTable?datatable, string?srcTable, DataReaderContainer dataReader, int startRecord, int maxRecords, DataColumn?parentChapterColumn, object?parentChapterValue)
        {
            int rowsAddedToDataSet = 0;
            int schemaCount        = 0;

            do
            {
                AssertReaderHandleFieldCount(dataReader);
                if (0 >= dataReader.FieldCount)
                {
                    continue; // loop to next result
                }

                SchemaMapping?mapping = FillMapping(dataset, datatable, srcTable, dataReader, schemaCount, parentChapterColumn, parentChapterValue);
                schemaCount++; // don't increment if no SchemaTable ( a non-row returning result )

                if (null == mapping)
                {
                    continue; // loop to next result
                }
                if (null == mapping.DataValues)
                {
                    continue; // loop to next result
                }
                if (null == mapping.DataTable)
                {
                    continue; // loop to next result
                }
                mapping.DataTable.BeginLoadData();
                try
                {
                    // startRecord and maxRecords only apply to the first resultset
                    if ((1 == schemaCount) && ((0 < startRecord) || (0 < maxRecords)))
                    {
                        rowsAddedToDataSet = FillLoadDataRowChunk(mapping, startRecord, maxRecords);
                    }
                    else
                    {
                        int count = FillLoadDataRow(mapping);

                        if (1 == schemaCount)
                        {
                            // only return LoadDataRow count for first resultset
                            // not secondary or chaptered results
                            rowsAddedToDataSet = count;
                        }
                    }
                }
                finally
                {
                    mapping.DataTable.EndLoadData();
                }
                if (null != datatable)
                {
                    break; // do not read remaining results in single DataTable case
                }
            } while (FillNextResult(dataReader));

            return(rowsAddedToDataSet);
        }
コード例 #3
0
        private static DataTable GetProceduresCollection(string?[]?restrictions, OdbcConnection connection)
        {
            OdbcCommand?   command     = null;
            OdbcDataReader?dataReader  = null;
            DataTable?     resultTable = null;
            const int      columnsRestrictionsCount = 4;
            const int      indexOfProcedureType     = 3;

            try
            {
                command = GetCommand(connection);
                string?[] allRestrictions = new string[columnsRestrictionsCount];
                FillOutRestrictions(columnsRestrictionsCount, restrictions, allRestrictions, OdbcMetaDataCollectionNames.Procedures);


                dataReader = command.ExecuteReaderFromSQLMethod(allRestrictions, ODBC32.SQL_API.SQLPROCEDURES);

                if (allRestrictions[indexOfProcedureType] == null)
                {
                    resultTable = DataTableFromDataReader(dataReader, OdbcMetaDataCollectionNames.Procedures);
                }
                else
                {
                    short procedureType;
                    if ((restrictions ![indexOfProcedureType] == "SQL_PT_UNKNOWN") ||
コード例 #4
0
        public override bool NextResult()
        {
            // next result set; reset everything
            ValidateOpen(nameof(NextResult));

            if ((_tableCounter == _tables.Length - 1))
            {
                return(false);
            }

            _currentDataTable = _tables[++_tableCounter];

            if (_listener != null)
            {
                _listener.UpdataTable(_currentDataTable); // it will unsubscribe from preveous tables events and subscribe to new table's events
            }

            _schemaTable       = null;
            _rowCounter        = -1;
            _currentRowRemoved = false;
            _reachEORows       = false;
            _schemaIsChanged   = false;
            _started           = false;
            ReaderIsInvalid    = false;
            _tableCleared      = false;

            _hasRows = (_currentDataTable.Rows.Count > 0);

            return(true);
        }
コード例 #5
0
 internal void SetDataTable(DataTable table)
 {
     if (_table != table)
     {
         _table = table;
     }
 }
コード例 #6
0
        internal DataExpression(DataTable?table, string?expression, Type?type)
        {
            ExpressionParser parser = new ExpressionParser(table);

            parser.LoadExpression(expression);

            _originalExpression = expression;
            _expr = null;

            // Note: nobody seems to pass a null expression in the codebase
            if (expression != null)
            {
                _storageType = DataStorage.GetStorageType(type);
                if (_storageType == StorageType.BigInteger)
                {
                    throw ExprException.UnsupportedDataType(type !);
                }

                _dataType = type;
                _expr     = parser.Parse();
                _parsed   = true;
                if (_expr != null && table != null)
                {
                    Bind(table);
                }
                else
                {
                    _bound = false;
                }
            }
        }
コード例 #7
0
        private void UnregisterMetaDataEvents(bool updateListeners)
        {
            DataTable?table = _table;

            _table = null;

            if (table != null)
            {
                CollectionChangeEventHandler handlerCollection = new CollectionChangeEventHandler(ColumnCollectionChanged);
                table.Columns.ColumnPropertyChanged -= handlerCollection;
                table.Columns.CollectionChanged     -= handlerCollection;

                CollectionChangeEventHandler handlerChildRelation = new CollectionChangeEventHandler(ChildRelationCollectionChanged);
                ((DataRelationCollection.DataTableRelationCollection)(table.ChildRelations)).RelationPropertyChanged -= handlerChildRelation;
                table.ChildRelations.CollectionChanged -= handlerChildRelation;

                CollectionChangeEventHandler handlerParentRelation = new CollectionChangeEventHandler(ParentRelationCollectionChanged);
                ((DataRelationCollection.DataTableRelationCollection)(table.ParentRelations)).RelationPropertyChanged -= handlerParentRelation;
                table.ParentRelations.CollectionChanged -= handlerParentRelation;

                if (updateListeners)
                {
                    List <DataViewListener> listeners = table.GetListeners();
                    lock (listeners)
                    {
                        listeners.Remove(this);
                    }
                }
            }
        }
コード例 #8
0
        protected override async Task <ExchangeRateRecord[]> DownloadExchangeRatesForDayAsync(DateTime dt)
        {
            using (var cbr = new cbrwebservice.DailyInfoSoapClient())
            {
                var dtsResult = await cbr.GetCursOnDateAsync(dt);

                if (dtsResult == null)
                {
                    logger.Error("async await cbr.GetCursOnDateAsync(dt) return NULL with no errors!");
                    throw new Exception(UIStrings.CurrencyExchangeRates_Error_Network);
                }

                rawDataTable = dtsResult.Tables.Cast <DataTable>().FirstOrDefault();
                if (rawDataTable == default)
                {
                    logger.Error($"Failed to get frist DataTable from web dstaset ('{dtsResult.GetType()}'). Dataset does not containt any Tables!");
                    throw new Exception(UIStrings.CurrencyExchangeRates_Error_Network);
                }

                var dataTableRows = rawDataTable.RowsAsEnumerable().ToArray();
                logger.Debug($"dataTableRows.Count = {dataTableRows.Count()}");
                try
                {
                    var rows = dataTableRows.Select(row => new ExchangeRateRecord(row, dt)).ToArray();
                    return(rows);
                }
                catch (Exception ex)
                {
                    logger.Error(ex, $"Failed to convert '{dataTableRows.GetType()}' to '{typeof(ExchangeRateRecord)}'!");
                    throw new Exception(UIStrings.CurrencyExchangeRates_Error_ParseError);
                }
            };
        }
コード例 #9
0
ファイル: CsvUtilityTest.cs プロジェクト: menees/Libraries
        private static void TestReadTable(DataTable oldTable, DataTable?newTable, bool treatAsStrings = true)
        {
            int columnCount = oldTable.Columns.Count;

            newTable.ShouldNotBeNull();
            columnCount.ShouldBe(newTable.Columns.Count);

            int rowCount = oldTable.Rows.Count;

            rowCount.ShouldBe(newTable.Rows.Count);

            for (int rowIndex = 0; rowIndex < rowCount; rowIndex++)
            {
                DataRow originalRow = oldTable.Rows[rowIndex];
                DataRow newRow      = newTable.Rows[rowIndex];
                for (int columnIndex = 0; columnIndex < columnCount; columnIndex++)
                {
                    object?originalValue = originalRow[columnIndex];
                    object?newValue      = newRow[columnIndex];

                    if (treatAsStrings)
                    {
                        originalValue = originalValue.ToString();
                        newValue      = newValue.ToString();
                    }

                    originalValue.ShouldBe(newValue);
                }
            }
        }
コード例 #10
0
        public override void WriteJson(JsonWriter writer, DataTable?dt, JsonSerializer serializer)
        {
            if (dt == null)
            {
                return;
            }

            if (dt.ColumnLabels != null && dt.Columns.Count != dt.ColumnLabels.Count)
            {
                throw new Exception("Number of column labels does not equal number of columns");
            }


            var columnsMeta = dt.Columns;

            writer.WriteStartObject();

            //write cols
            writer.WritePropertyName("cols");
            WriteCols(writer, columnsMeta, serializer);


            //write rows
            writer.WritePropertyName("rows");
            WriteRows(writer, dt.Values, columnsMeta, dt.ColumnLabels);


            writer.WriteEndObject();
        }
コード例 #11
0
ファイル: DataTableCollection.cs プロジェクト: zouql/runtime
 /// <summary>
 /// Does verification on the table and it's name, and clears the table's dataSet pointer.
 /// An ArgumentNullException is thrown if this table is null.  An ArgumentException is thrown
 /// if this table doesn't belong to this collection or if this table is part of a relationship.
 /// </summary>
 private void BaseRemove(DataTable?table)
 {
     if (CanRemove(table, true))
     {
         UnregisterName(table.TableName);
         table.SetDataSet(null);
     }
     _list.Remove(table);
     _dataSet.OnRemovedTable(table !);
 }
コード例 #12
0
        public static DataRow Row(this DataTable?table, int index)
        {
            var row = table?.Rows[index];

            if (row is null)
            {
                throw new InvalidOperationException($"Could not find row at index {index} in table {table?.TableName}.");
            }
            return(row);
        }
コード例 #13
0
        public static DataColumn Column(this DataTable?table, string name)
        {
            var col = table?.Columns[name];

            if (col is null)
            {
                throw new InvalidOperationException($"Could not find column {name} in table {table?.TableName}.");
            }
            return(col);
        }
コード例 #14
0
ファイル: CsvUtilityTest.cs プロジェクト: menees/Libraries
        public void ReadTableReaderTest()
        {
            DataTable table = CreateTestTableAndText(out string tableText);

            using (StringReader reader = new(tableText))
            {
                DataTable?newTable = CsvUtility.ReadTable(reader);
                TestReadTable(table, newTable);
            }
        }
コード例 #15
0
ファイル: DataAdapter.cs プロジェクト: layomia/dotnet_runtime
        private SchemaMapping FillMappingInternal(DataSet?dataset, DataTable?datatable, string?srcTable, DataReaderContainer dataReader, int schemaCount, DataColumn?parentChapterColumn, object?parentChapterValue)
        {
            bool   withKeyInfo = (Data.MissingSchemaAction.AddWithKey == MissingSchemaAction);
            string?tmp         = null;

            if (null != dataset)
            {
                tmp = DataAdapter.GetSourceTableName(srcTable !, schemaCount);
            }
            return(new SchemaMapping(this, dataset, datatable, dataReader, withKeyInfo, SchemaType.Mapped, tmp, true, parentChapterColumn, parentChapterValue));
        }
コード例 #16
0
        internal void UpdataTable(DataTable datatable)
        {
            if (datatable == null)
            {
                throw ExceptionBuilder.ArgumentNull(nameof(DataTable));
            }

            UnSubscribeEvents();
            _currentDataTable = datatable;
            SubscribeEvents();
        }
コード例 #17
0
        private DataTable?GetTable(int index)
        {
            DataTable?dt = null;
            DataSet?  ds = _dataViewManager.DataSet;

            if (ds != null)
            {
                dt = ds.Tables[index];
            }
            return(dt);
        }
コード例 #18
0
ファイル: Merger.cs プロジェクト: layomia/dotnet_runtime
        internal Merger(DataTable dataTable, bool preserveChanges, MissingSchemaAction missingSchemaAction)
        {
            _isStandAlonetable = true;
            _dataTable         = dataTable;
            _preserveChanges   = preserveChanges;

            // map AddWithKey -> Add
            _missingSchemaAction = missingSchemaAction == MissingSchemaAction.AddWithKey ?
                                   MissingSchemaAction.Add :
                                   missingSchemaAction;
        }
コード例 #19
0
        private DataTable?GetTable(string tableName)
        {
            DataTable?dt = null;
            DataSet?  ds = _dataViewManager.DataSet;

            if (ds != null)
            {
                dt = ds.Tables[tableName];
            }
            return(dt);
        }
コード例 #20
0
 public virtual DataViewSetting?this[string tableName]
 {
     get
     {
         DataTable?dt = GetTable(tableName);
         if (dt != null)
         {
             return(this[dt]);
         }
         return(null);
     }
 }
コード例 #21
0
ファイル: DataTableCollection.cs プロジェクト: zouql/runtime
        /// <summary>
        /// Returns the index of a specified <see cref='System.Data.DataTable'/>.
        /// </summary>
        public int IndexOf(DataTable?table)
        {
            int tableCount = _list.Count;

            for (int i = 0; i < tableCount; ++i)
            {
                if (table == (DataTable)_list[i] !)
                {
                    return(i);
                }
            }
            return(-1);
        }
コード例 #22
0
ファイル: DataAdapter.cs プロジェクト: layomia/dotnet_runtime
        internal object?FillSchemaFromReader(DataSet?dataset, DataTable?datatable, SchemaType schemaType, string?srcTable, IDataReader dataReader)
        {
            DataTable[]? dataTables = null;
            int schemaCount = 0;

            do
            {
                DataReaderContainer readerHandler = DataReaderContainer.Create(dataReader, ReturnProviderSpecificTypes);

                AssertReaderHandleFieldCount(readerHandler);
                if (0 >= readerHandler.FieldCount)
                {
                    continue;
                }
                string?tmp = null;
                if (null != dataset)
                {
                    tmp = DataAdapter.GetSourceTableName(srcTable !, schemaCount);
                    schemaCount++; // don't increment if no SchemaTable ( a non-row returning result )
                }

                SchemaMapping mapping = new SchemaMapping(this, dataset, datatable, readerHandler, true, schemaType, tmp, false, null, null);

                if (null != datatable)
                {
                    // do not read remaining results in single DataTable case
                    return(mapping.DataTable);
                }
                else if (null != mapping.DataTable)
                {
                    if (null == dataTables)
                    {
                        dataTables = new DataTable[1] {
                            mapping.DataTable
                        };
                    }
                    else
                    {
                        dataTables = DataAdapter.AddDataTableToArray(dataTables, mapping.DataTable);
                    }
                }
            } while (dataReader.NextResult()); // FillSchema does not capture errors for FillError event

            object?value = dataTables;

            if ((null == value) && (null == datatable))
            {
                value = Array.Empty <DataTable>();
            }
            return(value); // null if datatable had no results
        }
コード例 #23
0
        public override void Close()
        {
            if (!_isOpen)
            {
                return;
            }

            // no need to listen to events after close
            _listener?.CleanUp();

            _listener    = null !;
            _schemaTable = null;
            _isOpen      = false;
        }
コード例 #24
0
        public override DataTable GetSchemaTable()
        {
            ValidateOpen(nameof(GetSchemaTable));
            ValidateReader();

            // each time, we just get schema table of current table for once, no need to recreate each time, if schema is changed, reader is already
            // is invalid
            if (_schemaTable == null)
            {
                _schemaTable = GetSchemaTableFromDataTable(_currentDataTable);
            }

            return(_schemaTable);
        }
コード例 #25
0
ファイル: ConstNode.cs プロジェクト: z77ma/runtime
        internal ConstNode(DataTable?table, ValueType type, object constant, bool fParseQuotes) : base(table)
        {
            switch (type)
            {
            case ValueType.Null:
                _val = DBNull.Value;
                break;

            case ValueType.Numeric:
                _val = SmallestNumeric(constant);
                break;

            case ValueType.Decimal:
                _val = SmallestDecimal(constant);
                break;

            case ValueType.Float:
                _val = Convert.ToDouble(constant, NumberFormatInfo.InvariantInfo);
                break;

            case ValueType.Bool:
                _val = Convert.ToBoolean(constant, CultureInfo.InvariantCulture);
                break;

            case ValueType.Str:
                if (fParseQuotes)
                {
                    // replace '' with one '
                    _val = ((string)constant).Replace("''", "'");
                }
                else
                {
                    _val = (string)constant;
                }
                break;

            case ValueType.Date:
                _val = DateTime.Parse((string)constant, CultureInfo.InvariantCulture);
                break;

            case ValueType.Object:
                _val = constant;
                break;

            default:
                Debug.Fail("NYI");
                goto case ValueType.Object;
            }
        }
コード例 #26
0
        private string GetParameterName(string neededCollectionName, int neededRestrictionNumber)
        {
            DataTable?           restrictionsTable  = null;
            DataColumnCollection?restrictionColumns = null;
            DataColumn?          collectionName     = null;
            DataColumn?          parameterName      = null;
            DataColumn?          restrictionName    = null;
            DataColumn?          restrictionNumber  = null;

            ;
            string?result = null;

            restrictionsTable = _metaDataCollectionsDataSet.Tables[DbMetaDataCollectionNames.Restrictions];
            if (restrictionsTable != null)
            {
                restrictionColumns = restrictionsTable.Columns;
                if (restrictionColumns != null)
                {
                    collectionName    = restrictionColumns[_collectionName];
                    parameterName     = restrictionColumns[_parameterName];
                    restrictionName   = restrictionColumns[_restrictionName];
                    restrictionNumber = restrictionColumns[_restrictionNumber];
                }
            }

            if ((parameterName == null) || (collectionName == null) || (restrictionName == null) || (restrictionNumber == null))
            {
                throw ADP.MissingRestrictionColumn();
            }

            foreach (DataRow restriction in restrictionsTable !.Rows)
            {
                if (((string)restriction[collectionName] == neededCollectionName) &&
                    ((int)restriction[restrictionNumber] == neededRestrictionNumber) &&
                    (SupportedByCurrentVersion(restriction)))
                {
                    result = (string)restriction[parameterName];
                    break;
                }
            }

            if (result == null)
            {
                throw ADP.MissingRestrictionRow();
            }

            return(result);
        }
コード例 #27
0
ファイル: ChainState.cs プロジェクト: thehoglet/RVis
 internal ChainState(
     int no,
     Arr <ModelParameter> modelParameters,
     Arr <ModelOutput> modelOutputs,
     DataTable?chainData,
     DataTable?errorData,
     IDictionary <string, DataTable>?posteriorData
     )
 {
     No = no;
     ModelParameters = modelParameters;
     ModelOutputs    = modelOutputs;
     ChainData       = chainData;
     ErrorData       = errorData;
     PosteriorData   = posteriorData;
 }
コード例 #28
0
ファイル: CsvUtilityTest.cs プロジェクト: menees/Libraries
        public void ReadTableFileTest()
        {
            string tableFileName = FileUtility.GetTempFileName(".csv");

            try
            {
                DataTable table = CreateTestTable();
                CsvUtility.WriteTable(tableFileName, table);
                DataTable?newTable = CsvUtility.ReadTable(tableFileName);
                TestReadTable(table, newTable);
            }
            finally
            {
                FileUtility.DeleteFile(tableFileName);
            }
        }
コード例 #29
0
        private static ReadOnlyCollection <DbColumn> GetColumnSchemaCompatibility(DbDataReader reader)
        {
            var       columnSchema = new List <DbColumn>();
            DataTable?schemaTable  = reader.GetSchemaTable();

            if (schemaTable != null)
            {
                DataColumnCollection schemaTableColumns = schemaTable.Columns;
                foreach (DataRow row in schemaTable.Rows)
                {
                    Debug.Assert(row != null);
                    columnSchema.Add(new DataRowDbColumn(row, schemaTableColumns));
                }
            }
            return(new ReadOnlyCollection <DbColumn>(columnSchema));
        }
コード例 #30
0
ファイル: DataAdapter.cs プロジェクト: layomia/dotnet_runtime
        private void OnFillErrorHandler(Exception e, DataTable?dataTable, object?[]?dataValues)
        {
            FillErrorEventArgs fillErrorEvent = new FillErrorEventArgs(dataTable, dataValues);

            fillErrorEvent.Errors = e;
            OnFillError(fillErrorEvent);

            if (!fillErrorEvent.Continue)
            {
                if (null != fillErrorEvent.Errors)
                {
                    throw fillErrorEvent.Errors;
                }
                throw e;
            }
        }