private static void ReadXmlSerializable (DataTable dt, XmlReader xr) { XmlSerializer serializer = new XmlSerializer (dt.GetType ()); IXmlSerializable idt = dt; idt.ReadXml (xr); xr.Close (); }
// ReSharper disable InconsistentNaming public void DataTableInterrogator_CreateMapper_WhenDataTable_ExpectDataTableInterrogator() // ReSharper restore InconsistentNaming { //------------Setup for test-------------------------- DataTable obj = new DataTable(); //------------Execute Test--------------------------- IInterrogator interrogator = InterrogatorFactory.CreateInteregator(obj.GetType()); //------------Assert Results------------------------- Assert.AreEqual(typeof(DataTableInterrogator), interrogator.GetType()); }
public void DataTableInterrogator_CreateMapper_WhenDataTable_ExpectDataTableNavigator() { //------------Setup for test-------------------------- DataTable obj = new DataTable(); //------------Execute Test--------------------------- IInterrogator interrogator = InterrogatorFactory.CreateInteregator(obj.GetType()); var nav = interrogator.CreateNavigator(obj, typeof(DataTable)); //------------Assert Results------------------------- Assert.AreEqual(typeof(DataTableNavigator), nav.GetType()); }
public void DataTableInterrogator_CreateMapper_WhenNull_ExpectDataTableMapper() { //------------Setup for test-------------------------- DataTable obj = new DataTable(); //------------Execute Test--------------------------- IInterrogator interrogator = InterrogatorFactory.CreateInteregator(obj.GetType()); var mapper = interrogator.CreateMapper(null); //------------Assert Results------------------------- Assert.AreEqual(typeof(DataTableMapper), mapper.GetType()); }
public async void TableDataIsEqual(OBData.DataTable dt1, OBData.DataTable dt2, string schema) { _engine = new AutomationEngineInstance(null); _mergeDataTable = new MergeDataTableCommand(); VariableMethods.CreateTestVariable(dt1, _engine, "dt1", typeof(OBData.DataTable)); VariableMethods.CreateTestVariable(dt2, _engine, "dt2", typeof(OBData.DataTable)); switch (schema) { case "Add": dt2.Merge(dt1, false, MissingSchemaAction.Add); break; case "AddWithKey": dt2.Merge(dt1, false, MissingSchemaAction.AddWithKey); break; case "Error": dt2.Merge(dt1, false, MissingSchemaAction.Error); break; case "Ignore": dt2.Merge(dt1, false, MissingSchemaAction.Ignore); break; default: throw new NotImplementedException("Test for schema '" + schema + "' not implemented"); } _mergeDataTable.v_SourceDataTable = "{dt1}"; _mergeDataTable.v_DestinationDataTable = "{dt2}"; _mergeDataTable.v_MissingSchemaAction = schema; _mergeDataTable.RunCommand(_engine); OBData.DataTable resultDataTable = (OBData.DataTable) await _mergeDataTable.v_DestinationDataTable.EvaluateCode(_engine); Assert.Equal(dt2.GetType(), resultDataTable.GetType()); // Check each row / column pair and assert equivalence for (int row = 0; row < dt2.Rows.Count; row++) { for (int col = 0; col < dt2.Columns.Count; col++) { Assert.Equal(dt2.Rows[row][dt2.Columns[col]], resultDataTable.Rows[row][resultDataTable.Columns[col]]); } } }
public void AddTest_Pattern3() { var table = new DataTable(); table.Columns.Add("param1"); table.Columns.Add("param2"); table.Columns.Add("param3"); table.Rows.Add(1, "test", "row"); table.Rows.Add(2, "test", "row2"); var p = new SqlParamCreator(); p.Add("@table", table); Assert.AreEqual(1, p.SqlParameters.Length); table = p.SqlParameters[0].Value as DataTable; Assert.AreEqual(typeof(DataTable), table.GetType()); }
/// <summary> /// Call the FastReport method of the same name /// This should only be called from the "DataGetter" method. It can only succeed if FastReports initialised correctly. /// </summary> /// <param name="data"></param> /// <param name="name"></param> public void RegisterData(DataTable data, string name) { FFastReportType.GetMethod("RegisterData", new Type[] { data.GetType(), name.GetType() }).Invoke(FfastReportInstance, new object[] { data, name }); FClientDataTable = data; }
// 将DataTable 数据序列化成xml文本数据 /// <summary> /// 将DataTable 数据序列化成xml文本数据 /// </summary> /// <param name="table"></param> /// <param name="tablename"></param> /// <param name="ci"></param> /// <returns></returns> public static string TableToXMLString(DataTable table, CultureInfo ci) { if (string.IsNullOrEmpty(table.TableName)) { table.TableName = "tmp_table"; } if (ci == null) { ci = new CultureInfo("zh-CHS"); } using (StringWriter sw = new StringWriter(ci)) { XmlSerializer xmls = new XmlSerializer(table.GetType()); xmls.Serialize(sw, table); sw.Flush(); return sw.GetStringBuilder().ToString(); } }
/// <summary> /// Returns a DataTable from the Cache. /// /// </summary> /// <param name="ACacheableTableName">Name of the DataTable</param> /// <param name="AType"></param> /// <returns>DataTable from the Cache</returns> /// <exception cref="ECacheableTablesMgrTableNotUpToDateException">if the Cacheable /// DataTable isn't in an up-to-date state. This means it needs to be retrieved /// anew before it can be used /// </exception> public DataTable GetCachedDataTable(String ACacheableTableName, out System.Type AType) { CacheableTablesTDSContentsRow ContentsEntryDR; DataTable TmpTable; System.Type CachedDataTableType; LockCookie UpgradeLockCookie = new LockCookie(); // Variable initialisation (just to prevent compiler warnings) TmpTable = new DataTable(); CachedDataTableType = new System.Data.DataTable().GetType(); try { TLogging.LogAtLevel(10, "TCacheableTablesManager.GetCachedDataTable waiting for a ReaderLock..."); // Try to get a read lock [We don't specify a timeout because reading the DB tables into the cached table should be fairly quick] FReadWriteLock.AcquireReaderLock(SharedConstants.THREADING_WAIT_INFINITE); TLogging.LogAtLevel(10, "TCacheableTablesManager.GetCachedDataTable grabbed a ReaderLock."); if (!UDataCacheDataSet.Tables.Contains(ACacheableTableName)) { throw new ECacheableTablesMgrException( "TCacheableTablesManager.GetCachedDataTable: Cacheable DataTable '" + ACacheableTableName + "' does not exist in Cache"); } ContentsEntryDR = GetContentsEntry(ACacheableTableName); // GetContentsEntry reuses the ReaderLock if (ContentsEntryDR != null) { if (ContentsEntryDR.DataUpToDate) { try { TLogging.LogAtLevel(10, "TCacheableTablesManager.GetCachedDataTable waiting for upgrading to a WriterLock..."); // Need to temporarily upgrade to a write lock to prevent other threads from obtaining a read lock on the cache table while we are modifying the Cache Contents table! UpgradeLockCookie = FReadWriteLock.UpgradeToWriterLock(SharedConstants.THREADING_WAIT_INFINITE); TLogging.LogAtLevel(10, "TCacheableTablesManager.GetCachedDataTable upgraded to a WriterLock."); ContentsEntryDR.LastAccessed = DateTime.Now; } finally { TLogging.LogAtLevel(10, "TCacheableTablesManager.GetCachedDataTable waiting for downgrading to a ReaderLock..."); // Downgrade from a WriterLock to a ReaderLock again! FReadWriteLock.DowngradeFromWriterLock(ref UpgradeLockCookie); TLogging.LogAtLevel(10, "TCacheableTablesManager.GetCachedDataTable downgraded to a ReaderLock."); } } else { throw new ECacheableTablesMgrTableNotUpToDateException(ACacheableTableName); } } /* * To get around multi-threading reading/writing issues that might occur * when the caller of this function performs read or write operations on the * DataTable, we must return only a *copy* of the DataTable, not a reference * to the DataTable! */ TmpTable = UDataCacheDataSet.Tables[ACacheableTableName].Copy(); CachedDataTableType = UDataCacheDataSet.Tables[ACacheableTableName].GetType(); } finally { // Release read lock FReadWriteLock.ReleaseReaderLock(); TLogging.LogAtLevel(10, "TCacheableTablesManager.GetCachedDataTable released the ReaderLock."); } if (TmpTable is TTypedDataTable) { // The Copy needs to be a typed DataTable, so we need to type it DataUtilities.ChangeDataTableToTypedDataTable(ref TmpTable, CachedDataTableType, ""); } TLogging.LogAtLevel(7, "TCacheableTablesManager.GetCachedDataTable: Returned Type: " + TmpTable.GetType().FullName); AType = TmpTable.GetType(); return TmpTable; }
/// <summary> /// Adds the passed in DataTable to the Cache. If it is already there, a Merge /// operation is done. /// /// </summary> /// <param name="ACacheableTableName">Name of the DataTable</param> /// <param name="ACacheableTable">DataTable that should be added to the Cache/merged /// with an already existing DataTable in the Cache with the same TableName</param> /// <param name="AClientID">The ClientID that should be exempt from getting a ClientTask /// queued for updating of the Cached DataTable (only if a Merge operation is /// done). This would be the ClientID of the Client that performed the call /// to this procedure</param> /// <param name="AFilterCriteria">Filter Criteria (eg. Ledger Number for the Finance /// Module) that will be needed by the Clients that receive the ClientTask to /// be able to request the update of the filtered Cached DataTable /// </param> /// <returns>void</returns> public void AddOrMergeCachedTable(String ACacheableTableName, DataTable ACacheableTable, System.Int32 AClientID, object AFilterCriteria) { CacheableTablesTDSContentsRow ContentsEntryDR; DataTable TmpDT; ContentsEntryDR = GetContentsEntry(ACacheableTableName); if (ContentsEntryDR != null) { try { TLogging.LogAtLevel(10, "TCacheableTablesManager.AddOrMergeCachedTable waiting for a WriterLock..."); // Prevent other threads from obtaining a read lock on the cache table while we are merging the cache table! FReadWriteLock.AcquireWriterLock(SharedConstants.THREADING_WAIT_INFINITE); TLogging.LogAtLevel(10, "TCacheableTablesManager.AddOrMergeCachedTable grabbed a WriterLock."); int rowCount = UDataCacheDataSet.Tables[ACacheableTableName].Rows.Count; TLogging.LogAtLevel(7, "TCacheableTablesManager.AddOrMergeCachedTable: merging DataTable " + ACacheableTableName + ". Rows before merging: " + rowCount.ToString()); Type cacheableTableType = ACacheableTable.GetType(); if ((UDataCacheDataSet.Tables[ACacheableTableName].GetType() == typeof(System.Data.DataTable)) && cacheableTableType.IsSubclassOf(typeof(TTypedDataTable))) { TLogging.LogAtLevel(7, "TCacheableTablesManager.AddOrMergeCachedTable: An attempt was made to merge a Typed Table into a plain DataTable"); if (rowCount == 0) { // This can happen if the cache did not contain this table when it was marked as needing refreshing. // In that case the cache will contain an empty plain DataTable, which we are now trying to populate. TLogging.LogAtLevel(7, "TCacheableTablesManager.AddOrMergeCachedTable: Creating new Typed table (" + ACacheableTableName + ") in preparation for data merge"); DataTable dt = new DataTable(); DataUtilities.ChangeDataTableToTypedDataTable(ref dt, cacheableTableType, ACacheableTableName); UDataCacheDataSet.Tables.Remove(ACacheableTableName); UDataCacheDataSet.Tables.Add(dt); } else { // This should never happen. The cache should only contain Typed tables or a dummy untyped table that contains no data // that was only used so that the Contents DataSet could mark it as needing refreshing. throw new ECacheableTablesMgrException( "TCacheableTablesManager.AddOrMergeCachedTable: " + "An unexpected attempt was made to merge a typed data table into an untyped data table that already contains data"); } } TmpDT = ACacheableTable.Copy(); TmpDT.TableName = ACacheableTableName; try { UDataCacheDataSet.Merge(TmpDT); } catch (Exception) { // if the column names change, we cannot merge anymore with the table that was loaded from an old cache file UDataCacheDataSet.RemoveTable(TmpDT.TableName); UDataCacheDataSet.Merge(TmpDT); } // Remove rows from the cached DT that are no longer present in the DB Table (DataSet.Merge doesn't do this!). // Note: The Cacheable DataTable must have a Primary Key for this Method to be able to perform this! DataUtilities.RemoveRowsNotPresentInDT(TmpDT, UDataCacheDataSet.Tables[ACacheableTableName], true); ContentsEntryDR.DataUpToDate = true; TLogging.LogAtLevel(7, "TCacheableTablesManager.AddOrMergeCachedTable: merged DataTable " + ACacheableTableName + ". Rows after merging: " + UDataCacheDataSet.Tables[ACacheableTableName].Rows.Count.ToString()); } finally { // Other threads are now free to obtain a read lock on the cache table. FReadWriteLock.ReleaseWriterLock(); TLogging.LogAtLevel(10, "TCacheableTablesManager.AddOrMergeCachedTable released the WriterLock."); } // Inform all Clients (except the one that calls this function) that they // need to refresh their Clientside cached DataTable! UpdateCacheOnClients(ACacheableTableName, AClientID, AFilterCriteria); } else { AddCachedTableInternal(ACacheableTableName, ACacheableTable, false); } }
/// <summary> /// Serializes a Typed DataTable to a byte[] containing only the data (ie no infrastructure) /// </summary> /// <param name="dataTable">The Typed DataTable to serialize.</param> /// <returns>A byte[] containing the serialized data.</returns> /// <remarks>The DataTable must be Typed and not a plain DataTable. It must also not have had any /// new columns added to it. In either of these cases, use SerializeDataTable instead.</remarks> public static byte[] SerializeTypedDataTable(DataTable dataTable) { if (dataTable == null) throw new ArgumentNullException("dataTable"); if (dataTable.GetType() == typeof(DataTable)) throw new ArgumentException("Is not a typed DataTable", "dataTable"); if (dataTable.GetType().GetConstructor(Type.EmptyTypes) == null) throw new ArgumentException("Does not have a public, empty constructor", "dataTable"); return new FastSerializer().SerializeDataOnly(dataTable); }
/// <summary> /// Serializes a simple Typed DataTable to a byte[] containing only data. /// </summary> /// <param name="dataTable">The Typed DataTable to serialize.</param> /// <returns>A byte[] containing the serialized data.</returns> /// <remarks>A simple Typed DataTable will have no Errors associated with the rows /// or columns and all rows should be Unchanged/Added (deserialized /// rows will always be Unchanged). Deleted rows will throw an exception. /// Designed for read-only tables which need to be serialized to a minumum size. </remarks> public static byte[] SerializeSimpleTypedDataTable(DataTable dataTable) { if (dataTable == null) throw new ArgumentNullException("dataTable"); if (dataTable.HasErrors) throw new ArgumentException("Table has errors so is not a simple table", "dataTable"); if (dataTable.GetType().GetConstructor(Type.EmptyTypes) == null) throw new ArgumentException("Does not have a public, empty constructor", "dataTable"); return new FastSerializer().SerializeSimpleDataOnly(dataTable); }
/// <summary> /// Deserializes a Typed DataTable from a byte[] containing serialized data only. /// </summary> /// <param name="dataTable">The Typed DataTable to deserialize into.</param> /// <param name="serializedData">A byte[] containing the serialized data.</param> /// <returns>The same DataTable passed in.</returns> /// <remarks>The DataTable must be of the same type from which the serialized data was originally obtained.</remarks> public static DataTable DeserializeTypedDataTable(DataTable dataTable, byte[] serializedData) { if (dataTable == null) throw new ArgumentNullException("dataTable"); if (serializedData == null) throw new ArgumentNullException("serializedData"); if (dataTable.GetType() == typeof(DataTable)) throw new ArgumentException("Is not a typed DataTable", "dataTable"); return new FastDeserializer().DeserializeDataTableDataOnly(dataTable, serializedData); }
/// <summary> /// 打印 DataTable . /// </summary> /// <param name="sb">输出缓冲区.</param> /// <param name="indent">缩进.</param> /// <param name="obj">对象.</param> public static void PrintDataTable(StringBuilder sb, int indent, DataTable obj) { int indentnext = indent + 1; String indentstr = GetIndentStr(indent); sb.AppendLine(string.Format("{0}# <{1}>", indentstr, obj.GetType().FullName)); sb.AppendLine(string.Format("{0}CaseSensitive:\t{1}", indentstr, obj.CaseSensitive)); sb.AppendLine(string.Format("{0}DisplayExpression:\t{1}", indentstr, obj.DisplayExpression)); sb.AppendLine(string.Format("{0}HasErrors:\t{1}", indentstr, obj.HasErrors)); sb.AppendLine(string.Format("{0}Locale:\t{1}", indentstr, obj.Locale)); sb.AppendLine(string.Format("{0}MinimumCapacity:\t{1}", indentstr, obj.MinimumCapacity)); sb.AppendLine(string.Format("{0}Namespace:\t{1}", indentstr, obj.Namespace)); sb.AppendLine(string.Format("{0}Prefix:\t{1}", indentstr, obj.Prefix)); sb.AppendLine(string.Format("{0}TableName:\t{1}", indentstr, obj.TableName)); sb.AppendLine(string.Format("{0}PrimaryKey:\t// Length={1}", indentstr, obj.PrimaryKey.Length)); foreach (DataColumn dc in obj.PrimaryKey) { sb.AppendLine(string.Format("{0}\t{1}", indentstr, dc)); } sb.AppendLine(string.Format("{0}ExtendedProperties:\t{1}", indentstr, obj.ExtendedProperties)); PrintPropertyCollection(sb, indentnext, obj.ExtendedProperties); sb.AppendLine(string.Format("{0}Rows:\t{1}", indentstr, obj.Rows)); PrintDataRowCollection(sb, indentnext, obj.Rows); sb.AppendLine(string.Format("{0}Columns:\t{1}", indentstr, obj.Columns)); PrintDataColumnCollection(sb, indentnext, obj.Columns); sb.AppendLine(string.Format("{0}Constraints:\t{1}", indentstr, obj.Constraints)); PrintConstraintCollection(sb, indentnext, obj.Constraints); sb.AppendLine(string.Format("{0}ChildRelations:\t{1}", indentstr, obj.ChildRelations)); PrintDataRelationCollection(sb, indentnext, obj.ChildRelations); sb.AppendLine(string.Format("{0}ParentRelations:\t{1}", indentstr, obj.ParentRelations)); PrintDataRelationCollection(sb, indentnext, obj.ParentRelations); }
public bool RefreshData(DataTable source) { if (source.Rows.Count == 0) { FillTable(source.TableName); return true; } //обновить справочники //нужен у все метод FillNew с параметром дата foreach (DataRelation relation in source.ParentRelations) {if (relation.ChildKeyConstraint!=null) RefreshData(relation.ParentTable); } Object[] parameters = new Object[0]; Object _newTable; Object[] args = new Object[1]; try { // создать пустую таблицу Type _typeTable = source.GetType(); ConstructorInfo constructorInfoObj = _typeTable.GetConstructor(Type.EmptyTypes); _newTable = constructorInfoObj.Invoke(parameters); args[0] = _newTable; } catch (SecurityException err) { Log("RefreshData : " + source.TableName + err.Message + " " + err.Source + err.InnerException.Message); return false; } catch (Exception err) { Log("RefreshData : " + source.TableName + err.Message + " " + err.Source + err.InnerException.Message); return false; } // Merge try { Type tp = this.components.Components[source.TableName + "TableAdapter"].GetType(); tp.GetMethod("FillNew").Invoke(this.components.Components[source.TableName + "TableAdapter"], args); source.Merge(_newTable as DataTable, false); } catch (Exception err) { MessageBox.Show(err.Message); Log("RefreshData : " + source.TableName + err.Message + " " + err.Source + err.InnerException.Message); return false; } return true; }
private static void Chapter8CodeBlock8() { DataTable myDataTable = new DataTable(); Type myDataTableType = myDataTable.GetType(); ConstructorInfo[] myDataTableConstructors = myDataTableType.GetConstructors(); for(int i = 0; i <= myDataTableConstructors.Length - 1; i++) { ConstructorInfo constructorInfo = myDataTableConstructors[i]; Debug.Print(string.Format("\nConstructor #{0}", i + 1)); ParameterInfo[] parameters = constructorInfo.GetParameters(); Debug.Print(string.Format("Number Of Parameters: {0}", parameters.Length)); foreach (ParameterInfo parameter in parameters) { Debug.Print(string.Format("Parameter Name: {0}", parameter.Name)); Debug.Print(string.Format("Parameter Type: {0}", parameter.ParameterType.Name)); } } }