Esempio n. 1
0
 // <Snippet1>
 public void FindDataTableMapping()
 {
     // ...
     // create mappings and mapping
     // ...
     if (mappings.Contains("Categories"))
     {
         mapping = DataTableMappingCollection.GetTableMappingBySchemaAction
                       (mappings, "Categories", "", MissingMappingAction.Ignore);
     }
 }
Esempio n. 2
0
        public void CopyToArray()
        {
            var mapping    = new DataTableMapping("source", "dataSet");
            var collection = new DataTableMappingCollection
            {
                mapping,
            };
            Array array = new DataTableMapping[1];

            collection.CopyTo(array, 0);
            Assert.Same(mapping, array.GetValue(0));
        }
Esempio n. 3
0
        /// <summary>
        /// Form initialiation and load.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TableMapForm_Load(object sender, System.EventArgs e)
        {
            bool result = true;              // if all is well, enable the OK button

            //load the .gif image for the corner
            System.Reflection.Assembly assembly =
                GetType().Module.Assembly;
            Bitmap advanBitmap = new Bitmap(
                assembly.GetManifestResourceStream(bitmapName));

            this.pictureBox1.Image = advanBitmap;
            this.pictureBox1.Size  =
                new Size(advanBitmap.Width, advanBitmap.Height);
            this.pictureBox1.BorderStyle = BorderStyle.FixedSingle;

            // build a DataTable that can map the 2-column DataSource to the grid
            System.Data.DataTable dt = new System.Data.DataTable("mapping");
            dt.Columns.Add(TableMappings.SOURCE_COLUMNS);
            dt.Columns.Add(TableMappings.DATASET_COLUMNS);

            // safety check that IngresDataAdapter exists
            if (this.dbAdapter == null)
            {
                System.Windows.Forms.MessageBox.Show(
                    "Data Adapter is null; Table mappings is not available.",
                    "Table Mappings");
                return;
            }

            DataTableMappingCollection mapList = this.dbAdapter.TableMappings;

            // safety check that TableMappings exists; should never fail
            if (mapList == null)
            {
                System.Windows.Forms.MessageBox.Show(
                    "Data Adapter's Table mappings are null and are not available.",
                    "Table Mappings");
                return;
            }

            // if empty TableMappings, build new set from SELECT's column
            // else use the existing list.
            if (mapList.Count > 0)
            {
                result = BuildMapFromExistingMap(dt, mapList);
            }

            dt.AcceptChanges();
            this.dataGrid1.DataMember = dt.TableName;
            this.dataGrid1.DataSource = dt;

            this.buttonOK.Enabled = result;              // all went well
        }
Esempio n. 4
0
        public void GetTableMappingBySchemaAction()
        {
            var collection = new DataTableMappingCollection();

            Assert.Throws <ArgumentException>(() => DataTableMappingCollection.GetTableMappingBySchemaAction(collection, "", "", MissingMappingAction.Ignore));
            Assert.Throws <InvalidOperationException>(() => DataTableMappingCollection.GetTableMappingBySchemaAction(collection, "source", "", MissingMappingAction.Error));
            Assert.Null(DataTableMappingCollection.GetTableMappingBySchemaAction(collection, "source", "", MissingMappingAction.Ignore));
            Assert.Throws <ArgumentOutOfRangeException>(() => DataTableMappingCollection.GetTableMappingBySchemaAction(collection, "source", "", default(MissingMappingAction)));
            DataTableMapping mapping = DataTableMappingCollection.GetTableMappingBySchemaAction(collection, "source", "", MissingMappingAction.Passthrough);

            Assert.NotNull(mapping);
            Assert.Equal("source", mapping.SourceTable);
        }
Esempio n. 5
0
        public void Remove()
        {
            object mapping    = new DataTableMapping("source", "dataSet");
            var    collection = new DataTableMappingCollection
            {
                mapping,
            };

            Assert.Throws <ArgumentNullException>(() => collection.Remove(default(object)));
            Assert.Throws <ArgumentNullException>(() => collection.Remove(default(DataTableMapping)));
            Assert.Throws <ArgumentException>(() => collection.Remove(new DataTableMapping("a", "b")));
            collection.Remove(mapping);
            Assert.Empty(collection);
        }
Esempio n. 6
0
        public void IListIndexer()
        {
            IList list    = new DataTableMappingCollection();
            var   mapping = new DataTableMapping("source", "dataSet");

            Assert.Throws <IndexOutOfRangeException>(() => { var x = list[0]; });
            Assert.Throws <IndexOutOfRangeException>(() => { list[0] = mapping; });
            list.Add(mapping);
            Assert.Same(mapping, list[0]);
            Assert.Throws <ArgumentNullException>(() => { list[0] = null; });
            Assert.Throws <InvalidCastException>(() => { list[0] = "invalid"; });
            list[0] = new DataTableMapping("source2", "dataSet2");
            Assert.NotSame(mapping, list[0]);
        }
Esempio n. 7
0
        /// <summary>
        /// OK Button event handler.
        /// Copy the column mappings back the TableMapping collection.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonOK_Click(object sender, System.EventArgs e)
        {
            System.Data.DataTable dt =
                (System.Data.DataTable) this.dataGrid1.DataSource;
            if (dt == null)
            {
                return;
            }

            dt.AcceptChanges();

            string sourceTable  = comboBoxSourceTable.Text.Trim();
            string datasetTable = textBoxDatasetTable.Text.Trim();

            if (sourceTable.Length == 0)
            {
                System.Windows.Forms.MessageBox.Show(
                    "Source Table name is invalid.",
                    "Table Mappings");
                return;
            }
            if (datasetTable.Length == 0)
            {
                System.Windows.Forms.MessageBox.Show(
                    "DataSet Table name is invalid.",
                    "Table Mappings");
                return;
            }

            DataTableMappingCollection mapList = this.dbAdapter.TableMappings;

            mapList.Clear();
            DataTableMapping map = mapList.Add(sourceTable, datasetTable);

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                System.Data.DataRow datarow = dt.Rows[i];
                string sourceCol            =
                    ((string)datarow[TableMappings.SOURCE_COLUMNS]).Trim();
                string datasetCol =
                    ((string)datarow[TableMappings.DATASET_COLUMNS]).Trim();
                if (sourceCol.Length == 0 ||                   // drop empty mappings
                    datasetCol.Length == 0)
                {
                    continue;
                }
                map.ColumnMappings.Add(sourceCol, datasetCol);
            }
        }
Esempio n. 8
0
        /// <summary>
        /// 创建默认表列映射
        /// </summary>
        /// <param name="ds"></param>
        /// <returns></returns>
        public static System.Data.Common.DataTableMappingCollection CreateDefaultMapping(System.Data.DataSet ds)
        {
            DataTableMappingCollection rtn = new DataTableMappingCollection();

            foreach (System.Data.DataTable dt in ds.Tables)
            {
                DataTableMapping dtm = rtn.Add(dt.TableName, dt.TableName);
                foreach (DataColumn dc in dt.Columns)
                {
                    dtm.ColumnMappings.Add(dc.ColumnName, dc.ColumnName);
                }
            }

            return(rtn);
        }
Esempio n. 9
0
        public void Insert()
        {
            var collection = new DataTableMappingCollection();

            Assert.Throws <ArgumentNullException>(() => collection.Insert(0, default(object)));
            Assert.Throws <ArgumentNullException>(() => collection.Insert(0, default(DataTableMapping)));
            Assert.Throws <InvalidCastException>(() => collection.Insert(0, "invalid"));
            object mapping = new DataTableMapping("source", "dataSet");

            Assert.Throws <ArgumentOutOfRangeException>(() => collection.Insert(-1, mapping));
            Assert.Throws <ArgumentOutOfRangeException>(() => collection.Insert(1, mapping));
            collection.Insert(0, mapping);
            Assert.Single(collection);
            Assert.Same(mapping, collection[0]);
            Assert.Throws <ArgumentException>(() => collection.Insert(1, mapping));
        }
Esempio n. 10
0
    // <Snippet1>
    public void CreateTableMappings()
    {
        DataTableMappingCollection mappings =
            new DataTableMappingCollection();

        mappings.Add("Categories", "DataCategories");
        mappings.Add("Orders", "DataOrders");
        mappings.Add("Products", "DataProducts");
        string message = "TableMappings:\n";

        for (int i = 0; i < mappings.Count; i++)
        {
            message += i.ToString() + " "
                       + mappings[i].ToString() + "\n";
        }
        Console.WriteLine(message);
    }
Esempio n. 11
0
        internal string SetupSchema(SchemaType schemaType, string sourceTableName)
        {
            DataTableMapping tableMapping = null;

            if (schemaType == SchemaType.Mapped)
            {
                tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction(TableMappings, sourceTableName, sourceTableName, MissingMappingAction);
                if (tableMapping != null)
                {
                    return(tableMapping.DataSetTable);
                }
                return(null);
            }
            else
            {
                return(sourceTableName);
            }
        }
Esempio n. 12
0
        public void Replace()
        {
            var mapping1    = new DataTableMapping("source1", "dataSet1");
            var collection1 = new DataTableMappingCollection
            {
                mapping1,
            };

            Assert.Throws <ArgumentNullException>(() => collection1[0]         = null);
            Assert.Throws <ArgumentNullException>(() => collection1["source1"] = null);

            var mapping2    = new DataTableMapping("source2", "dataSet2");
            var collection2 = new DataTableMappingCollection
            {
                mapping2,
            };

            Assert.Throws <ArgumentException>(() => collection2[0] = mapping1);
        }
Esempio n. 13
0
        protected override int Fill(DataSet dataSet, string srcTable, IDataReader dataReader, int startRecord, int maxRecords)
        {
            if (!dataReader.IsClosed)
            {
                DataTableMapping tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction(TableMappings, srcTable, srcTable, MissingMappingAction);

                if (tableMapping != null)
                {
                    DataTable dataTable = tableMapping.GetDataTableBySchemaAction(dataSet, MissingSchemaAction);

                    if (dataTable != null)
                    {
                        return(Fill(dataTable, tableMapping, dataReader, startRecord, maxRecords));
                    }
                }
            }

            return(0);
        }
Esempio n. 14
0
        public void ITableMappingCollectionIndexer()
        {
            ITableMappingCollection collection = new DataTableMappingCollection();

            Assert.Throws <IndexOutOfRangeException>(() => { var x = collection["source"]; });
            Assert.Throws <IndexOutOfRangeException>(() => { collection["source"] = new DataTableMapping(); });
            ITableMapping mapping = collection.Add("source", "dataSet");

            Assert.Same(mapping, collection["source"]);
            Assert.Same(mapping, collection.GetByDataSetTable("dataSet"));
            Assert.Throws <ArgumentNullException>(() => { collection["source"] = null; });
            Assert.Throws <InvalidCastException>(() => { collection["source"] = "invalid"; });
            ITableMapping mapping2 = new DataTableMapping("source2", "dataSet2");

            collection["source"] = mapping2;
            Assert.Single(collection);
            Assert.Same(mapping2, collection["source2"]);
            Assert.Throws <IndexOutOfRangeException>(() => collection.GetByDataSetTable("dataSet"));
        }
Esempio n. 15
0
        private void CloneFrom(DataAdapter from)
        {
            _acceptChangesDuringUpdate            = from._acceptChangesDuringUpdate;
            _acceptChangesDuringUpdateAfterInsert = from._acceptChangesDuringUpdateAfterInsert;
            _continueUpdateOnError       = from._continueUpdateOnError;
            _returnProviderSpecificTypes = from._returnProviderSpecificTypes; // WebData 101795
            _acceptChangesDuringFill     = from._acceptChangesDuringFill;
            _fillLoadOption       = from._fillLoadOption;
            _missingMappingAction = from._missingMappingAction;
            _missingSchemaAction  = from._missingSchemaAction;

            if ((null != from._tableMappings) && (0 < from.TableMappings.Count))
            {
                DataTableMappingCollection parameters = this.TableMappings;
                foreach (object parameter in from.TableMappings)
                {
                    parameters.Add((parameter is ICloneable) ? ((ICloneable)parameter).Clone() : parameter);
                }
            }
        }
Esempio n. 16
0
        public void GetTableMappingBySchemaAction()
        {
            _tableMapCollection.AddRange(_tabs);
            bool             eq;
            DataTableMapping tab1;

            tab1 = DataTableMappingCollection.GetTableMappingBySchemaAction(_tableMapCollection, "sourceCustomers", "dataSetCustomers", MissingMappingAction.Passthrough);
            eq   = (tab1.DataSetTable.Equals("dataSetCustomers") && tab1.SourceTable.Equals("sourceCustomers"));
            Assert.True(eq);
            tab1 = DataTableMappingCollection.GetTableMappingBySchemaAction(_tableMapCollection, "sourceEmployees", "dataSetEmployees", MissingMappingAction.Passthrough);
            eq   = (tab1.DataSetTable.Equals("dataSetEmployees") && tab1.SourceTable.Equals("sourceEmployees"));
            Assert.True(eq);

            tab1 = DataTableMappingCollection.GetTableMappingBySchemaAction(_tableMapCollection, "sourceData", "dataSetData", MissingMappingAction.Passthrough);
            eq   = (tab1.DataSetTable.Equals("sourceData") && tab1.SourceTable.Equals("dataSetData"));
            Assert.False(eq);
            eq = _tableMapCollection.Contains(tab1);
            Assert.False(eq);
            tab1 = DataTableMappingCollection.GetTableMappingBySchemaAction(_tableMapCollection, "sourceData", "dataSetData", MissingMappingAction.Ignore);
            Assert.Null(tab1);
        }
        public void GetTableMappingBySchemaAction()
        {
            tableMapCollection.AddRange(tabs);
            bool             eq;
            DataTableMapping tab1;

            tab1 = DataTableMappingCollection.GetTableMappingBySchemaAction(tableMapCollection, "sourceCustomers", "dataSetCustomers", MissingMappingAction.Passthrough);
            eq   = (tab1.DataSetTable.Equals("dataSetCustomers") && tab1.SourceTable.Equals("sourceCustomers"));
            Assert.AreEqual(true, eq, "test1");
            tab1 = DataTableMappingCollection.GetTableMappingBySchemaAction(tableMapCollection, "sourceEmployees", "dataSetEmployees", MissingMappingAction.Passthrough);
            eq   = (tab1.DataSetTable.Equals("dataSetEmployees") && tab1.SourceTable.Equals("sourceEmployees"));
            Assert.AreEqual(true, eq, "test2");

            tab1 = DataTableMappingCollection.GetTableMappingBySchemaAction(tableMapCollection, "sourceData", "dataSetData", MissingMappingAction.Passthrough);
            eq   = (tab1.DataSetTable.Equals("sourceData") && tab1.SourceTable.Equals("dataSetData"));
            Assert.AreEqual(false, eq, "test3");
            eq = tableMapCollection.Contains(tab1);
            Assert.AreEqual(false, eq, "test4");
            tab1 = DataTableMappingCollection.GetTableMappingBySchemaAction(tableMapCollection, "sourceData", "dataSetData", MissingMappingAction.Ignore);
            Assert.AreEqual(null, tab1, "test5");
        }
Esempio n. 18
0
        /// <summary>
        /// Build a DataTable for the form's datagrid from the
        /// existing TableMappings.
        /// </summary>
        /// <param name="dt">2-column DataTable to hold the names.</param>
        /// <param name="mapList">TableMapping collection usually
        /// from the DataAdapter.</param>
        /// <returns></returns>
        private bool BuildMapFromExistingMap(
            System.Data.DataTable dt, DataTableMappingCollection mapList)
        {
            DataTableMapping map          = mapList[0];
            string           sourceTable  = map.SourceTable;
            string           datasetTable = map.DataSetTable;

            comboBoxSourceTable.Text = sourceTable;
            textBoxDatasetTable.Text = datasetTable;

            // copy the column mappings to the 2-column DataTable
            // that will be the DataSource for the datagrid
            foreach (DataColumnMapping colMap in map.ColumnMappings)
            {
                System.Data.DataRow datarow = dt.NewRow();
                datarow[TableMappings.SOURCE_COLUMNS]  = colMap.SourceColumn;
                datarow[TableMappings.DATASET_COLUMNS] = colMap.DataSetColumn;
                dt.Rows.Add(datarow);
            }

            return(true);
        }
Esempio n. 19
0
        /// <summary>
        /// Executes a stored procedure for select
        /// </summary>
        /// <param name="p_datatable">Data set</param>
        /// <param name="p_selectCmd">Select command</param>
        /// <param name="p_tableMappings">Table mappings</param>
        public static void ExecStoredProcForSelect(
            DataSet p_dataSet, SqlCommand p_selectCmd,
            DataTableMappingCollection p_tableMappings)
        {
            SqlConnection conn = NewDBConnection();

            //Add Connection to Commmands
            p_selectCmd.Connection = conn;

            //Set up Data Adapter
            SqlDataAdapter da = new SqlDataAdapter();

            da.SelectCommand = p_selectCmd;
            foreach (DataTableMapping m in p_tableMappings)
            {
                da.TableMappings.Add(m.SourceTable, m.DataSetTable);
            }


            //Open DB
            conn.Open();

            //Do Select
            try
            {
                da.Fill(p_dataSet);
            }
            catch (SqlException ex)
            {
                HandleSqlException(ex);
            }

            //Clean up
            conn.Close();
            da.Dispose();
            conn.Dispose();
        }
Esempio n. 20
0
        public static void DataAdapter()
        {
            SqlConnection  cn         = new SqlConnection();;
            SqlDataAdapter da         = new SqlDataAdapter(selectCommandText: "Select * from Aircraft", selectConnection: cn);
            var            sqlbuilder = new SqlCommandBuilder(da);
            bool           acceptChangesDuringFill   = da.AcceptChangesDuringFill;
            bool           acceptChangesDuringUpdate = da.AcceptChangesDuringUpdate;
            bool           continueUpdateOnError     = da.ContinueUpdateOnError;
            SqlCommand     sqlcmdDelete = da.DeleteCommand;
            SqlCommand     sqlcmdInsert = da.InsertCommand;
            SqlCommand     sqlcmdSelect = da.SelectCommand;
            SqlCommand     sqlcmdUpdate = da.UpdateCommand;
            LoadOption     loadOption   = da.FillLoadOption;

            MissingMappingAction mapingAction          = da.MissingMappingAction; //passthroug 1, ignore 2, error 3
            MissingSchemaAction  schemaAction          = da.MissingSchemaAction;  // add, ignore, error ,AddwithKey
            bool shouldReturnProvider                  = da.ReturnProviderSpecificTypes;
            DataTableMappingCollection dtMapCollection = da.TableMappings;

            //dtMapCollection[0].

            Console.WriteLine("*********DataAdapter**************");
            Console.WriteLine("");
            Console.WriteLine("   acceptChangesDuringFill {0,10}", acceptChangesDuringFill);
            Console.WriteLine("   acceptChangesDuringUpdate {0,10}", acceptChangesDuringUpdate);
            Console.WriteLine("   ContinueUpdateOnError {0,10}", continueUpdateOnError);
            Console.WriteLine("   DeleteCommand {0}", sqlcmdDelete);
            Console.WriteLine("   InsertCommand {0}", sqlcmdInsert);
            Console.WriteLine("   SelectCommand {0}", sqlcmdSelect);
            Console.WriteLine("   UpdateCommand {0}", sqlcmdUpdate);
            Console.WriteLine("   FillLoadOption {0}", loadOption);
            Console.WriteLine("   MissingMappingAction {0}", mapingAction);
            Console.WriteLine("   MissingSchemaAction {0}", schemaAction);
            Console.WriteLine("   ReturnProviderSpecificTypes {0}", shouldReturnProvider);
            Console.WriteLine("   TableMappings {0}", dtMapCollection);
        }
Esempio n. 21
0
 DataTableMapping IAdaSchemaMappingAdapter.GetTableMappingBySchemaAction(string sourceTableName, string dataSetTableName, MissingMappingAction mappingAction)
 {
     return(DataTableMappingCollection.GetTableMappingBySchemaAction(this.TableMappings, sourceTableName, dataSetTableName, mappingAction));
 }
        internal SchemaMapping(DataAdapter adapter, DataSet dataset, System.Data.DataTable datatable, DataReaderContainer dataReader, bool keyInfo, SchemaType schemaType, string sourceTableName, bool gettingData, DataColumn parentChapterColumn, object parentChapterValue)
        {
            MissingMappingAction missingMappingAction;
            MissingSchemaAction  missingSchemaAction;

            this._dataSet    = dataset;
            this._dataTable  = datatable;
            this._adapter    = adapter;
            this._dataReader = dataReader;
            if (keyInfo)
            {
                this._schemaTable = dataReader.GetSchemaTable();
            }
            if (adapter.ShouldSerializeFillLoadOption())
            {
                this._loadOption = adapter.FillLoadOption;
            }
            else if (adapter.AcceptChangesDuringFill)
            {
                this._loadOption = (LoadOption)4;
            }
            else
            {
                this._loadOption = (LoadOption)5;
            }
            if (SchemaType.Mapped == schemaType)
            {
                missingMappingAction = this._adapter.MissingMappingAction;
                missingSchemaAction  = this._adapter.MissingSchemaAction;
                if (ADP.IsEmpty(sourceTableName))
                {
                    if (this._dataTable != null)
                    {
                        int num2 = this._adapter.IndexOfDataSetTable(this._dataTable.TableName);
                        if (-1 == num2)
                        {
                            switch (missingMappingAction)
                            {
                            case MissingMappingAction.Passthrough:
                                this._tableMapping = new DataTableMapping(this._dataTable.TableName, this._dataTable.TableName);
                                goto Label_01DB;

                            case MissingMappingAction.Ignore:
                                this._tableMapping = null;
                                goto Label_01DB;

                            case MissingMappingAction.Error:
                                throw ADP.MissingTableMappingDestination(this._dataTable.TableName);
                            }
                            throw ADP.InvalidMissingMappingAction(missingMappingAction);
                        }
                        this._tableMapping = this._adapter.TableMappings[num2];
                    }
                }
                else
                {
                    this._tableMapping = this._adapter.GetTableMappingBySchemaAction(sourceTableName, sourceTableName, missingMappingAction);
                }
            }
            else
            {
                if (SchemaType.Source != schemaType)
                {
                    throw ADP.InvalidSchemaType(schemaType);
                }
                missingMappingAction = MissingMappingAction.Passthrough;
                missingSchemaAction  = MissingSchemaAction.Add;
                if (!ADP.IsEmpty(sourceTableName))
                {
                    this._tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction(null, sourceTableName, sourceTableName, missingMappingAction);
                }
                else if (this._dataTable != null)
                {
                    int num = this._adapter.IndexOfDataSetTable(this._dataTable.TableName);
                    if (-1 != num)
                    {
                        this._tableMapping = this._adapter.TableMappings[num];
                    }
                    else
                    {
                        this._tableMapping = new DataTableMapping(this._dataTable.TableName, this._dataTable.TableName);
                    }
                }
            }
Label_01DB:
            if (this._tableMapping != null)
            {
                if (this._dataTable == null)
                {
                    this._dataTable = this._tableMapping.GetDataTableBySchemaAction(this._dataSet, missingSchemaAction);
                }
                if (this._dataTable != null)
                {
                    this._fieldNames = GenerateFieldNames(dataReader);
                    if (this._schemaTable == null)
                    {
                        this._readerDataValues = this.SetupSchemaWithoutKeyInfo(missingMappingAction, missingSchemaAction, gettingData, parentChapterColumn, parentChapterValue);
                        return;
                    }
                    this._readerDataValues = this.SetupSchemaWithKeyInfo(missingMappingAction, missingSchemaAction, gettingData, parentChapterColumn, parentChapterValue);
                }
            }
        }
Esempio n. 23
0
        /// <summary>
        /// [Microsoft.Office.Interop.Excel]建立表列结构(保留不使用的页(Worksheet).(创建/覆盖文件)
        /// </summary>
        /// <param name="FileName">文件路径</param>
        /// <param name="dtmc">取其 Source 属性值建立空文件</param>
        public static void BuildSheets(string FileName, DataTableMappingCollection dtmc)
        {
            Application app = new Application();

            try
            {
                Workbook wb;
                if (File.Exists(FileName))
                {
                    wb = app.Workbooks.Open(FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing
                                            , true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                }
                else
                {
                    wb = app.Workbooks.Add(Type.Missing);
                }

                foreach (DataTableMapping dtm in dtmc)
                {
                    try
                    {
                        Worksheet ws;
                        try
                        {
                            ws = wb.Worksheets[dtm.SourceTable] as Worksheet;
                            // 清空表
                            ws.UsedRange.ClearContents();
                        }
                        catch
                        {
                            ws = wb.Worksheets.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing) as Worksheet;
                            // 表名
                            ws.Name = dtm.SourceTable;
                        }

                        ((_Worksheet)ws).Activate();
                        // 列名
                        for (int i = 1; i <= dtm.ColumnMappings.Count; i++)
                        {
                            DataColumnMapping dcm = dtm.ColumnMappings[i - 1];
                            ws.Cells[1, i] = dcm.SourceColumn;
                        }
                    }
                    catch (System.Exception ex)
                    {
                        Apq.GlobalObject.ApqLog.Warn(string.Format("构建文件结构[{0}]失败:", dtm.SourceTable), ex);
                    }
                }

                // 保存
                if (File.Exists(FileName))
                {
                    wb.Save();
                }
                else
                {
                    wb.SaveAs(FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing
                              , XlSaveAsAccessMode.xlNoChange, XlSaveConflictResolution.xlLocalSessionChanges, Type.Missing, Type.Missing, Type.Missing, true);
                }

                // 关闭
                wb.Close(XlSaveAction.xlDoNotSaveChanges, FileName, false);
                wb = null;
            }
            finally
            {
                try
                {
                    Int64  appID       = 0;
                    IntPtr hwnd        = new IntPtr(app.Hwnd);
                    int    appThreadID = Apq.DllImports.User32.GetWindowThreadProcessId(hwnd, ref appID);

                    // 退出 Excel
                    app.Quit();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(app);

                    if (appID > 0)
                    {
                        try
                        {
                            Process pr = Process.GetProcessById(System.Convert.ToInt32(appID));
                            pr.Kill();
                        }
                        catch { }
                    }
                    app = null;
                    GC.Collect();
                }
                catch (System.Exception ex)
                {
                    Apq.GlobalObject.ApqLog.Warn("关闭Excel失败", ex);
                }
            }
        }
Esempio n. 24
0
 internal DataTableMapping GetTableMappingBySchemaAction(string sourceTableName, string dataSetTableName, MissingMappingAction mappingAction)
 {
     return(DataTableMappingCollection.GetTableMappingBySchemaAction(_tableMappings, sourceTableName, dataSetTableName, mappingAction));
 }
        public void AddException1()
        {
            DataTableMappingCollection c = new DataTableMappingCollection();

            tableMapCollection.Add((Object)c);
        }
 public void GetTableMappingBySchemaActionException1()
 {
     DataTableMappingCollection.GetTableMappingBySchemaAction(tableMapCollection, "sourceCustomers", "dataSetCustomers", MissingMappingAction.Error);
 }
Esempio n. 27
0
        /// <summary>
        ///     Creates or Modifies the schema of the given DataTable based on the schema of
        ///     the reader and the arguments passed.
        /// </summary>
        internal static int[] BuildSchema(IDataReader reader, DataTable table,
                                          SchemaType schemaType,
                                          MissingSchemaAction missingSchAction,
                                          MissingMappingAction missingMapAction,
                                          DataTableMappingCollection dtMapping
                                          )
        {
            int readerIndex = 0;

            // FIXME : this fails if query has fewer columns than a table
            int[] mapping = new int[table.Columns.Count];             // mapping the reader indexes to the datatable indexes

            for (int i = 0; i < mapping.Length; i++)
            {
                mapping[i] = -1;
            }

            ArrayList primaryKey       = new ArrayList();
            ArrayList sourceColumns    = new ArrayList();
            bool      createPrimaryKey = true;

            DataTable schemaTable = reader.GetSchemaTable();

            DataColumn ColumnNameCol      = schemaTable.Columns["ColumnName"];
            DataColumn DataTypeCol        = schemaTable.Columns["DataType"];
            DataColumn IsAutoIncrementCol = schemaTable.Columns["IsAutoIncrement"];
            DataColumn AllowDBNullCol     = schemaTable.Columns["AllowDBNull"];
            DataColumn IsReadOnlyCol      = schemaTable.Columns["IsReadOnly"];
            DataColumn IsKeyCol           = schemaTable.Columns["IsKey"];
            DataColumn IsUniqueCol        = schemaTable.Columns["IsUnique"];
            DataColumn ColumnSizeCol      = schemaTable.Columns["ColumnSize"];

            foreach (DataRow schemaRow in schemaTable.Rows)
            {
                // generate a unique column name in the source table.
                string sourceColumnName;
                string realSourceColumnName;
                if (ColumnNameCol == null || schemaRow.IsNull(ColumnNameCol) ||
                    (string)schemaRow [ColumnNameCol] == String.Empty)
                {
                    sourceColumnName     = DefaultSourceColumnName;
                    realSourceColumnName = DefaultSourceColumnName + "1";
                }
                else
                {
                    sourceColumnName     = (string)schemaRow [ColumnNameCol];
                    realSourceColumnName = sourceColumnName;
                }

                for (int i = 1; sourceColumns.Contains(realSourceColumnName); i += 1)
                {
                    realSourceColumnName = String.Format("{0}{1}", sourceColumnName, i);
                }
                sourceColumns.Add(realSourceColumnName);

                // generate DataSetColumnName from DataTableMapping, if any
                DataTableMapping tableMapping = null;

                //FIXME : The sourcetable name shud get passed as a parameter..
                int    index    = dtMapping.IndexOfDataSetTable(table.TableName);
                string srcTable = (index != -1 ? dtMapping[index].SourceTable : table.TableName);
                tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction(dtMapping, ADP.IsEmpty(srcTable) ? " " : srcTable, table.TableName, missingMapAction);
                if (tableMapping != null)
                {
                    table.TableName = tableMapping.DataSetTable;
                    // check to see if the column mapping exists
                    DataColumnMapping columnMapping = DataColumnMappingCollection.GetColumnMappingBySchemaAction(tableMapping.ColumnMappings, realSourceColumnName, missingMapAction);
                    if (columnMapping != null)
                    {
                        Type       columnType = schemaRow[DataTypeCol] as Type;
                        DataColumn col        = columnType != null?columnMapping.GetDataColumnBySchemaAction(
                            table,
                            columnType,
                            missingSchAction) : null;

                        if (col != null)
                        {
                            // if the column is not in the table - add it.
                            if (table.Columns.IndexOf(col) == -1)
                            {
                                if (missingSchAction == MissingSchemaAction.Add ||
                                    missingSchAction == MissingSchemaAction.AddWithKey)
                                {
                                    table.Columns.Add(col);
                                }

                                int[] tmp = new int[mapping.Length + 1];
                                Array.Copy(mapping, 0, tmp, 0, col.Ordinal);
                                Array.Copy(mapping, col.Ordinal, tmp, col.Ordinal + 1, mapping.Length - col.Ordinal);
                                mapping = tmp;
                            }

                            if (missingSchAction == MissingSchemaAction.AddWithKey)
                            {
                                object value       = (AllowDBNullCol != null) ? schemaRow[AllowDBNullCol] : null;
                                bool   allowDBNull = value is bool?(bool)value : true;

                                value = (IsKeyCol != null) ? schemaRow[IsKeyCol] : null;
                                bool isKey = value is bool?(bool)value : false;

                                value = (IsAutoIncrementCol != null) ? schemaRow[IsAutoIncrementCol] : null;
                                bool isAutoIncrement = value is bool?(bool)value : false;

                                value = (IsReadOnlyCol != null) ? schemaRow[IsReadOnlyCol] : null;
                                bool isReadOnly = value is bool?(bool)value : false;

                                value = (IsUniqueCol != null) ? schemaRow[IsUniqueCol] : null;
                                bool isUnique = value is bool?(bool)value : false;

                                col.AllowDBNull = allowDBNull;
                                // fill woth key info
                                if (isAutoIncrement && CanAutoIncrement(columnType))
                                {
                                    col.AutoIncrement = true;
                                    if (!allowDBNull)
                                    {
                                        col.AllowDBNull = false;
                                    }
                                }

                                if (columnType == DbTypes.TypeOfString)
                                {
                                    col.MaxLength = (ColumnSizeCol != null) ? (int)schemaRow[ColumnSizeCol] : 0;
                                }

                                if (isReadOnly)
                                {
                                    col.ReadOnly = true;
                                }

                                if (!allowDBNull && (!isReadOnly || isKey))
                                {
                                    col.AllowDBNull = false;
                                }
                                if (isUnique && !isKey && !columnType.IsArray)
                                {
                                    col.Unique = true;
                                    if (!allowDBNull)
                                    {
                                        col.AllowDBNull = false;
                                    }
                                }

                                // This might not be set by all DataProviders
                                bool isHidden = false;
                                if (schemaTable.Columns.Contains("IsHidden"))
                                {
                                    value    = schemaRow["IsHidden"];
                                    isHidden = ((value is bool) ? (bool)value : false);
                                }

                                if (isKey && !isHidden)
                                {
                                    primaryKey.Add(col);
                                    if (allowDBNull)
                                    {
                                        createPrimaryKey = false;
                                    }
                                }
                            }
                            // add the ordinal of the column as a key and the index of the column in the datareader as a value.
                            mapping[col.Ordinal] = readerIndex++;
                        }
                    }
                }
            }
            if (primaryKey.Count > 0)
            {
                DataColumn[] colKey = (DataColumn[])(primaryKey.ToArray(typeof(DataColumn)));
                if (createPrimaryKey)
                {
                    table.PrimaryKey = colKey;
                }
                else
                {
                    UniqueConstraint uConstraint = new UniqueConstraint(colKey);
                    for (int i = 0; i < table.Constraints.Count; i++)
                    {
                        if (table.Constraints[i].Equals(uConstraint))
                        {
                            uConstraint = null;
                            break;
                        }
                    }

                    if (uConstraint != null)
                    {
                        table.Constraints.Add(uConstraint);
                    }
                }
            }
            return(mapping);
        }
Esempio n. 28
0
        /// <summary>
        /// [Microsoft.Office.Interop.Excel]建立表列结构(保留不使用的页(Worksheet).(创建/覆盖文件)
        /// </summary>
        /// <param name="FileName">文件路径</param>
        /// <param name="ds">数据集</param>
        public static void BuildSheets(string FileName, DataSet ds)
        {
            DataTableMappingCollection dtmc = Apq.Data.DataSet.CreateDefaultMapping(ds);

            BuildSheets(FileName, dtmc);
        }