internal bool CanRemove(DataColumn column, bool fThrowException) { if (column == null) { if (!fThrowException) { return(false); } else { throw ExceptionBuilder.ArgumentNull(nameof(column)); } } if (column._table != _table) { if (!fThrowException) { return(false); } else { throw ExceptionBuilder.CannotRemoveColumn(); } } // allow subclasses to complain first. _table.OnRemoveColumnInternal(column); // We need to make sure the column is not involved in any Relations or Constriants if (_table._primaryKey != null && _table._primaryKey.Key.ContainsColumn(column)) { if (!fThrowException) { return(false); } else { throw ExceptionBuilder.CannotRemovePrimaryKey(); } } for (int i = 0; i < _table.ParentRelations.Count; i++) { if (_table.ParentRelations[i].ChildKey.ContainsColumn(column)) { if (!fThrowException) { return(false); } else { throw ExceptionBuilder.CannotRemoveChildKey(_table.ParentRelations[i].RelationName); } } } for (int i = 0; i < _table.ChildRelations.Count; i++) { if (_table.ChildRelations[i].ParentKey.ContainsColumn(column)) { if (!fThrowException) { return(false); } else { throw ExceptionBuilder.CannotRemoveChildKey(_table.ChildRelations[i].RelationName); } } } for (int i = 0; i < _table.Constraints.Count; i++) { if (_table.Constraints[i].ContainsColumn(column)) { if (!fThrowException) { return(false); } else { throw ExceptionBuilder.CannotRemoveConstraint(_table.Constraints[i].ConstraintName, _table.Constraints[i].Table.TableName); } } } if (_table.DataSet != null) { for (ParentForeignKeyConstraintEnumerator en = new ParentForeignKeyConstraintEnumerator(_table.DataSet, _table); en.GetNext();) { Constraint constraint = en.GetConstraint(); if (((ForeignKeyConstraint)constraint).ParentKey.ContainsColumn(column)) { if (!fThrowException) { return(false); } else { throw ExceptionBuilder.CannotRemoveConstraint(constraint.ConstraintName, constraint.Table.TableName); } } } } if (column._dependentColumns != null) { for (int i = 0; i < column._dependentColumns.Count; i++) { DataColumn col = column._dependentColumns[i]; if (_fInClear && (col.Table == _table || col.Table == null)) { continue; } if (col.Table == null) { continue; } Debug.Assert(col.Computed, "invalid (non an expression) column in the expression dependent columns"); DataExpression expr = col.DataExpression; if ((expr != null) && (expr.DependsOn(column))) { if (!fThrowException) { return(false); } else { throw ExceptionBuilder.CannotRemoveExpression(col.ColumnName, col.Expression); } } } } // you can't remove a column participating in an index, // while index events are suspended else the indexes won't be properly maintained. // However, all the above checks should catch those participating columns. // except when a column is in a DataView RowFilter or Sort clause foreach (Index index in _table.LiveIndexes) { } return(true); }
internal bool CanRemove(DataColumn column, bool fThrowException) { if (column == null) { if (fThrowException) { throw ExceptionBuilder.ArgumentNull("column"); } return(false); } if (column.table != this.table) { if (fThrowException) { throw ExceptionBuilder.CannotRemoveColumn(); } return(false); } this.table.OnRemoveColumnInternal(column); if ((this.table.primaryKey != null) && this.table.primaryKey.Key.ContainsColumn(column)) { if (fThrowException) { throw ExceptionBuilder.CannotRemovePrimaryKey(); } return(false); } for (int i = 0; i < this.table.ParentRelations.Count; i++) { if (this.table.ParentRelations[i].ChildKey.ContainsColumn(column)) { if (fThrowException) { throw ExceptionBuilder.CannotRemoveChildKey(this.table.ParentRelations[i].RelationName); } return(false); } } for (int j = 0; j < this.table.ChildRelations.Count; j++) { if (this.table.ChildRelations[j].ParentKey.ContainsColumn(column)) { if (fThrowException) { throw ExceptionBuilder.CannotRemoveChildKey(this.table.ChildRelations[j].RelationName); } return(false); } } for (int k = 0; k < this.table.Constraints.Count; k++) { if (this.table.Constraints[k].ContainsColumn(column)) { if (fThrowException) { throw ExceptionBuilder.CannotRemoveConstraint(this.table.Constraints[k].ConstraintName, this.table.Constraints[k].Table.TableName); } return(false); } } if (this.table.DataSet != null) { ParentForeignKeyConstraintEnumerator enumerator = new ParentForeignKeyConstraintEnumerator(this.table.DataSet, this.table); while (enumerator.GetNext()) { Constraint constraint = enumerator.GetConstraint(); if (((ForeignKeyConstraint)constraint).ParentKey.ContainsColumn(column)) { if (fThrowException) { throw ExceptionBuilder.CannotRemoveConstraint(constraint.ConstraintName, constraint.Table.TableName); } return(false); } } } if (column.dependentColumns != null) { for (int m = 0; m < column.dependentColumns.Count; m++) { DataColumn column2 = column.dependentColumns[m]; if ((!this.fInClear || ((column2.Table != this.table) && (column2.Table != null))) && (column2.Table != null)) { DataExpression dataExpression = column2.DataExpression; if ((dataExpression != null) && dataExpression.DependsOn(column)) { if (fThrowException) { throw ExceptionBuilder.CannotRemoveExpression(column2.ColumnName, column2.Expression); } return(false); } } } } using (List <Index> .Enumerator enumerator2 = this.table.LiveIndexes.GetEnumerator()) { while (enumerator2.MoveNext()) { Index current = enumerator2.Current; } } return(true); }
private DataTable?MergeSchema(DataTable table) { DataTable?targetTable = null; if (!_isStandAlonetable) { if (_dataSet !.Tables.Contains(table.TableName, true)) { if (_IgnoreNSforTableLookup) { targetTable = _dataSet.Tables[table.TableName]; } else { targetTable = _dataSet.Tables[table.TableName, table.Namespace]; } } } else { targetTable = _dataTable; } if (targetTable == null) { // in case of standalone table, we make sure that targetTable is not null, so if this check passes, it will be when it is called via detaset if (MissingSchemaAction.Add == _missingSchemaAction) { targetTable = table.Clone(table.DataSet); // if we are here mainly we are called from DataSet.Merge at this point we don't set //expression columns, since it might have refer to other columns via relation, so it won't find the table and we get exception; // do it after adding relations. _dataSet !.Tables.Add(targetTable); } else if (MissingSchemaAction.Error == _missingSchemaAction) { throw ExceptionBuilder.MergeMissingDefinition(table.TableName); } } else { if (MissingSchemaAction.Ignore != _missingSchemaAction) { // Do the columns int oldCount = targetTable.Columns.Count; for (int i = 0; i < table.Columns.Count; i++) { DataColumn src = table.Columns[i]; DataColumn?dest = (targetTable.Columns.Contains(src.ColumnName, true)) ? targetTable.Columns[src.ColumnName] : null; if (dest == null) { if (MissingSchemaAction.Add == _missingSchemaAction) { dest = src.Clone(); targetTable.Columns.Add(dest); } else { if (!_isStandAlonetable) { _dataSet !.RaiseMergeFailed(targetTable, SR.Format(SR.DataMerge_MissingColumnDefinition, table.TableName, src.ColumnName), _missingSchemaAction); } else { throw ExceptionBuilder.MergeFailed(SR.Format(SR.DataMerge_MissingColumnDefinition, table.TableName, src.ColumnName)); } } } else { if (dest.DataType != src.DataType || ((dest.DataType == typeof(DateTime)) && (dest.DateTimeMode != src.DateTimeMode) && ((dest.DateTimeMode & src.DateTimeMode) != DataSetDateTime.Unspecified))) { if (!_isStandAlonetable) { _dataSet !.RaiseMergeFailed(targetTable, SR.Format(SR.DataMerge_DataTypeMismatch, src.ColumnName), MissingSchemaAction.Error); } else { throw ExceptionBuilder.MergeFailed(SR.Format(SR.DataMerge_DataTypeMismatch, src.ColumnName)); } } MergeExtendedProperties(src.ExtendedProperties, dest.ExtendedProperties); } } // Set DataExpression if (_isStandAlonetable) { for (int i = oldCount; i < targetTable.Columns.Count; i++) { targetTable.Columns[i].CopyExpressionFrom(table.Columns[targetTable.Columns[i].ColumnName] !); } } // check the PrimaryKey DataColumn[] targetPKey = targetTable.PrimaryKey; DataColumn[] tablePKey = table.PrimaryKey; if (targetPKey.Length != tablePKey.Length) { // special case when the target table does not have the PrimaryKey if (targetPKey.Length == 0) { DataColumn[] key = new DataColumn[tablePKey.Length]; for (int i = 0; i < tablePKey.Length; i++) { key[i] = targetTable.Columns[tablePKey[i].ColumnName] !; } targetTable.PrimaryKey = key; } else if (tablePKey.Length != 0) { _dataSet !.RaiseMergeFailed(targetTable, SR.DataMerge_PrimaryKeyMismatch, _missingSchemaAction); } } else { for (int i = 0; i < targetPKey.Length; i++) { if (string.Compare(targetPKey[i].ColumnName, tablePKey[i].ColumnName, false, targetTable.Locale) != 0) { _dataSet !.RaiseMergeFailed(table, SR.Format(SR.DataMerge_PrimaryKeyColumnsMismatch, targetPKey[i].ColumnName, tablePKey[i].ColumnName), _missingSchemaAction); } } } } MergeExtendedProperties(table.ExtendedProperties, targetTable.ExtendedProperties); } return(targetTable); }
void IList.Clear() { throw ExceptionBuilder.CannotModifyCollection(); }
void IList.Remove(object?value) { throw ExceptionBuilder.CannotModifyCollection(); }
internal void HandleColumn(XmlElement node, DataTable table) { Debug.Assert(FEqualIdentity(node, Keywords.XDR_ELEMENT, Keywords.XDRNS) || FEqualIdentity(node, Keywords.XDR_ATTRIBUTE, Keywords.XDRNS), "Illegal node type"); string instanceName; string strName; Type type; string strType; string strValues; int minOccurs = 0; int maxOccurs = 1; string strDefault; DataColumn column; // Get the name if (node.Attributes.Count > 0) { string strRef = node.GetAttribute(Keywords.REF); if (strRef != null && strRef.Length > 0) { return; //skip ref nodes. B2 item } strName = instanceName = GetInstanceName(node); column = table.Columns[instanceName, _schemaUri]; if (column != null) { if (column.ColumnMapping == MappingType.Attribute) { if (FEqualIdentity(node, Keywords.XDR_ATTRIBUTE, Keywords.XDRNS)) { throw ExceptionBuilder.DuplicateDeclaration(strName); } } else { if (FEqualIdentity(node, Keywords.XDR_ELEMENT, Keywords.XDRNS)) { throw ExceptionBuilder.DuplicateDeclaration(strName); } } instanceName = GenUniqueColumnName(strName, table); } } else { strName = instanceName = string.Empty; } // Now get the type XmlElement typeNode = FindTypeNode(node); SimpleType xsdType = null; if (typeNode == null) { strType = node.GetAttribute(Keywords.TYPE); throw ExceptionBuilder.UndefinedDatatype(strType); } strType = typeNode.GetAttribute(Keywords.DT_TYPE, Keywords.DTNS); strValues = typeNode.GetAttribute(Keywords.DT_VALUES, Keywords.DTNS); if (strType == null || strType.Length == 0) { strType = string.Empty; type = typeof(string); } else { type = ParseDataType(strType, strValues); // HACK: temp work around special types if (strType == "float") { strType = string.Empty; } if (strType == "char") { strType = string.Empty; xsdType = SimpleType.CreateSimpleType(StorageType.Char, type); } if (strType == "enumeration") { strType = string.Empty; xsdType = SimpleType.CreateEnumeratedType(strValues); } if (strType == "bin.base64") { strType = string.Empty; xsdType = SimpleType.CreateByteArrayType("base64"); } if (strType == "bin.hex") { strType = string.Empty; xsdType = SimpleType.CreateByteArrayType("hex"); } } bool isAttribute = FEqualIdentity(node, Keywords.XDR_ATTRIBUTE, Keywords.XDRNS); GetMinMax(node, isAttribute, ref minOccurs, ref maxOccurs); strDefault = null; // Does XDR has default? strDefault = node.GetAttribute(Keywords.DEFAULT); bool bNullable = false; column = new DataColumn(XmlConvert.DecodeName(instanceName), type, null, isAttribute ? MappingType.Attribute : MappingType.Element); SetProperties(column, node.Attributes); // xmlschema.SetProperties will skipp setting expressions column.XmlDataType = strType; column.SimpleType = xsdType; column.AllowDBNull = (minOccurs == 0) || bNullable; column.Namespace = (isAttribute) ? string.Empty : _schemaUri; // We will skip handling expression columns in SetProperties, so we need set the expressions here if (node.Attributes != null) { for (int i = 0; i < node.Attributes.Count; i++) { if (node.Attributes[i].NamespaceURI == Keywords.MSDNS) { if (node.Attributes[i].LocalName == "Expression") { column.Expression = node.Attributes[i].Value; break; } } } } string targetNamespace = node.GetAttribute(Keywords.TARGETNAMESPACE); if (targetNamespace != null && targetNamespace.Length > 0) { column.Namespace = targetNamespace; } table.Columns.Add(column); if (strDefault != null && strDefault.Length != 0) { try { column.DefaultValue = SqlConvert.ChangeTypeForXML(strDefault, type); } catch (System.FormatException) { throw ExceptionBuilder.CannotConvert(strDefault, type.FullName); } } }
object?IList.this[int index] { get { return(_item); } set { throw ExceptionBuilder.CannotModifyCollection(); } }
private object SmallestNumeric(object constant) { if (null == constant) { return((int)0); } else { string sval = (constant as string); if (null != sval) { int i4; if (Int32.TryParse(sval, NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out i4)) { return(i4); } long i8; if (Int64.TryParse(sval, NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out i8)) { return(i8); } double r8; if (Double.TryParse(sval, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.InvariantInfo, out r8)) { return(r8); } } else { IConvertible convertible = (constant as IConvertible); if (null != convertible) { try { return(convertible.ToInt32(NumberFormatInfo.InvariantInfo)); } catch (System.ArgumentException e) { ExceptionBuilder.TraceExceptionWithoutRethrow(e); } catch (System.FormatException e) { ExceptionBuilder.TraceExceptionWithoutRethrow(e); } catch (System.InvalidCastException e) { ExceptionBuilder.TraceExceptionWithoutRethrow(e); } catch (System.OverflowException e) { ExceptionBuilder.TraceExceptionWithoutRethrow(e); } try { return(convertible.ToInt64(NumberFormatInfo.InvariantInfo)); } catch (System.ArgumentException e) { ExceptionBuilder.TraceExceptionWithoutRethrow(e); } catch (System.FormatException e) { ExceptionBuilder.TraceExceptionWithoutRethrow(e); } catch (System.InvalidCastException e) { ExceptionBuilder.TraceExceptionWithoutRethrow(e); } catch (System.OverflowException e) { ExceptionBuilder.TraceExceptionWithoutRethrow(e); } try { return(convertible.ToDouble(NumberFormatInfo.InvariantInfo)); } catch (System.ArgumentException e) { ExceptionBuilder.TraceExceptionWithoutRethrow(e); } catch (System.FormatException e) { ExceptionBuilder.TraceExceptionWithoutRethrow(e); } catch (System.InvalidCastException e) { ExceptionBuilder.TraceExceptionWithoutRethrow(e); } catch (System.OverflowException e) { ExceptionBuilder.TraceExceptionWithoutRethrow(e); } } } } return(constant); }
internal void MergeRows(DataRow[] rows) { DataTable src = null; DataTable dst = null; DataKey key = null; Index ndxSearch = null; bool fEnforce = dataSet.EnforceConstraints; dataSet.EnforceConstraints = false; Hashtable saveTableIndexes = new Hashtable(); for (int i = 0; i < rows.Length; i++) { DataRow row = rows[i]; if (row == null) { throw ExceptionBuilder.ArgumentNull("rows[" + i + "]"); } if (row.Table == null) { throw ExceptionBuilder.ArgumentNull("rows[" + i + "].Table"); } //somebody is doing an 'automerge' if (row.Table.DataSet == dataSet) { continue; } if (src != row.Table) // row.Table changed from prev. row. { src = row.Table; dst = MergeSchema(row.Table); if (dst == null) { Debug.Assert(MissingSchemaAction.Ignore == missingSchemaAction, "MergeSchema failed"); dataSet.EnforceConstraints = fEnforce; return; } if (dst.primaryKey != null) { key = GetSrcKey(src, dst); } if (key != null) { ndxSearch = new Index(dst, dst.primaryKey.Key.GetIndexDesc(), DataViewRowState.OriginalRows | DataViewRowState.Added, (IFilter)null); } // Getting our own copy instead. ndxSearch = dst.primaryKey.Key.GetSortIndex(); } if (row.newRecord == -1 && row.oldRecord == -1) { continue; } DataRow targetRow = null; if (0 < dst.Rows.Count && ndxSearch != null) { targetRow = dst.FindMergeTarget(row, key, ndxSearch); } if (!saveTableIndexes.Contains(dst)) { saveTableIndexes[dst] = dst.LiveIndexes; saveTableIndexes[dst] = new ArrayList(); } dst.MergeRow(row, targetRow, preserveChanges, ndxSearch); } dataSet.EnforceConstraints = fEnforce; foreach (DataTable tab in saveTableIndexes.Keys) { tab.indexes = (ArrayList)saveTableIndexes[tab]; tab.ResetIndexes(); } }
private int ReadOldRowData(DataSet ds, ref DataTable table, ref int pos, XmlReader row) { // read table information if (ds != null) { table = ds.Tables.GetTable(XmlConvert.DecodeName(row.LocalName), row.NamespaceURI); } else { table = GetTable(XmlConvert.DecodeName(row.LocalName), row.NamespaceURI); } if (table == null) { row.Skip(); // need to skip this element if we dont know about it, before returning -1 return(-1); } int iRowDepth = row.Depth; string value = null; if (table == null) { throw ExceptionBuilder.DiffgramMissingTable(XmlConvert.DecodeName(row.LocalName)); } value = row.GetAttribute(Keywords.ROWORDER, Keywords.MSDNS); if (!Common.ADP.IsEmpty(value)) { pos = (Int32)Convert.ChangeType(value, typeof(Int32), null); } int record = table.NewRecord(); foreach (DataColumn col in table.Columns) { col[record] = DBNull.Value; } foreach (DataColumn col in table.Columns) { if ((col.ColumnMapping == MappingType.Element) || (col.ColumnMapping == MappingType.SimpleContent)) { continue; } if (col.ColumnMapping == MappingType.Hidden) { value = row.GetAttribute("hidden" + col.EncodedColumnName, Keywords.MSDNS); } else { value = row.GetAttribute(col.EncodedColumnName, col.Namespace); } if (value == null) { continue; } col[record] = col.ConvertXmlToObject(value); } row.Read(); SkipWhitespaces(row); int currentDepth = row.Depth; if (currentDepth <= iRowDepth) { // the node is empty if (currentDepth == iRowDepth && row.NodeType == XmlNodeType.EndElement) { // VSTFDEVDIV 764390: read past the EndElement of the current row // note: (currentDepth == iRowDepth) check is needed so we do not skip elements on parent rows. row.Read(); SkipWhitespaces(row); } return(record); } if (table.XmlText != null) { DataColumn col = table.XmlText; col[record] = col.ConvertXmlToObject(row.ReadString()); } else { while (row.Depth > iRowDepth) { String ln = XmlConvert.DecodeName(row.LocalName); String ns = row.NamespaceURI; DataColumn column = table.Columns[ln, ns]; if (column == null) { while ((row.NodeType != XmlNodeType.EndElement) && (row.LocalName != ln) && (row.NamespaceURI != ns)) { row.Read(); // consume the current node } row.Read(); // now points to the next column //SkipWhitespaces(row); seems no need, just in case if we see other issue , this will be here as hint continue; // add a read here! } if (column.IsCustomType) { // if column's type is object or column type does not implement IXmlSerializable bool isPolymorphism = (column.DataType == typeof(Object) || (row.GetAttribute(Keywords.MSD_INSTANCETYPE, Keywords.MSDNS) != null) || (row.GetAttribute(Keywords.TYPE, Keywords.XSINS) != null)); bool skipped = false; if (column.Table.DataSet != null && column.Table.DataSet.UdtIsWrapped) { row.Read(); // if UDT is wrapped, skip the wrapper skipped = true; } XmlRootAttribute xmlAttrib = null; if (!isPolymorphism && !column.ImplementsIXMLSerializable) // THIS // if does not implement IXLSerializable, need to go with XmlSerializer: pass XmlRootAttribute { if (skipped) { xmlAttrib = new XmlRootAttribute(row.LocalName); xmlAttrib.Namespace = row.NamespaceURI; } else { xmlAttrib = new XmlRootAttribute(column.EncodedColumnName); xmlAttrib.Namespace = column.Namespace; } } // for else case xmlAttrib MUST be null column[record] = column.ConvertXmlToObject(row, xmlAttrib); // you need to pass null XmlAttib here if (skipped) { row.Read(); // if Wrapper is skipped, skip its end tag } } else { int iColumnDepth = row.Depth; row.Read(); // SkipWhitespaces(row);seems no need, just in case if we see other issue , this will be here as hint if (row.Depth > iColumnDepth) //we are inside the column { if (row.NodeType == XmlNodeType.Text || row.NodeType == XmlNodeType.Whitespace || row.NodeType == XmlNodeType.SignificantWhitespace) { String text = row.ReadString(); column[record] = column.ConvertXmlToObject(text); row.Read(); // now points to the next column } } else { // <element></element> case if (column.DataType == typeof(string)) { column[record] = string.Empty; } } } } } row.Read(); //now it should point to next row SkipWhitespaces(row); return(record); }
private object SmallestDecimal(object constant) { if (null == constant) { return(0d); } else { string sval = (constant as string); if (null != sval) { decimal r12; if (Decimal.TryParse(sval, NumberStyles.Number, NumberFormatInfo.InvariantInfo, out r12)) { return(r12); } double r8; if (Double.TryParse(sval, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.InvariantInfo, out r8)) { return(r8); } } else { IConvertible convertible = (constant as IConvertible); if (null != convertible) { try { return(convertible.ToDecimal(NumberFormatInfo.InvariantInfo)); } catch (System.ArgumentException e) { ExceptionBuilder.TraceExceptionWithoutRethrow(e); } catch (System.FormatException e) { ExceptionBuilder.TraceExceptionWithoutRethrow(e); } catch (System.InvalidCastException e) { ExceptionBuilder.TraceExceptionWithoutRethrow(e); } catch (System.OverflowException e) { ExceptionBuilder.TraceExceptionWithoutRethrow(e); } try { return(convertible.ToDouble(NumberFormatInfo.InvariantInfo)); } catch (System.ArgumentException e) { ExceptionBuilder.TraceExceptionWithoutRethrow(e); } catch (System.FormatException e) { ExceptionBuilder.TraceExceptionWithoutRethrow(e); } catch (System.InvalidCastException e) { ExceptionBuilder.TraceExceptionWithoutRethrow(e); } catch (System.OverflowException e) { ExceptionBuilder.TraceExceptionWithoutRethrow(e); } } } } return(constant); }
internal void ProcessDiffs(ArrayList tableList, XmlReader ssync) { DataTable tableBefore; DataRow row; int oldRowRecord; int pos = -1; int iSsyncDepth = ssync.Depth; ssync.Read(); // pass the before node. //SkipWhitespaces(ssync); for given scenario does not require this change, but in fact we should do it. while (iSsyncDepth < ssync.Depth) { tableBefore = null; string diffId = null; oldRowRecord = -1; // the diffgramm always contains sql:before and sql:after pairs int iTempDepth = ssync.Depth; diffId = ssync.GetAttribute(Keywords.DIFFID, Keywords.DFFNS); bool hasErrors = (bool)(ssync.GetAttribute(Keywords.HASERRORS, Keywords.DFFNS) == Keywords.TRUE); oldRowRecord = ReadOldRowData(dataSet, ref tableBefore, ref pos, ssync); if (oldRowRecord == -1) { continue; } if (tableBefore == null) { throw ExceptionBuilder.DiffgramMissingSQL(); } row = (DataRow)tableBefore.RowDiffId[diffId]; if (row != null) { row.oldRecord = oldRowRecord; tableBefore.recordManager[oldRowRecord] = row; } else { row = tableBefore.NewEmptyRow(); tableBefore.recordManager[oldRowRecord] = row; row.oldRecord = oldRowRecord; row.newRecord = oldRowRecord; tableBefore.Rows.DiffInsertAt(row, pos); row.Delete(); if (hasErrors) { tableBefore.RowDiffId[diffId] = row; } } } return; }
internal DataTable InstantiateTable(DataSet dataSet, XmlElement node, XmlElement typeNode) { DataTable table; string name = ""; XmlAttributeCollection attrs = node.Attributes; int minOccurs = 1; int maxOccurs = 1; string str2 = null; ArrayList tableChildren = new ArrayList(); if (attrs.Count > 0) { name = this.GetInstanceName(node); table = dataSet.Tables.GetTable(name, this._schemaUri); if (table != null) { return(table); } } table = new DataTable(XmlConvert.DecodeName(name)) { Namespace = this._schemaUri }; this.GetMinMax(node, ref minOccurs, ref maxOccurs); table.MinOccurs = minOccurs; table.MaxOccurs = maxOccurs; this._ds.Tables.Add(table); this.HandleTypeNode(typeNode, table, tableChildren); XMLSchema.SetProperties(table, attrs); if (str2 != null) { string[] strArray = str2.TrimEnd(null).Split(null); int length = strArray.Length; DataColumn[] columnArray = new DataColumn[length]; for (int i = 0; i < length; i++) { DataColumn column2 = table.Columns[strArray[i], this._schemaUri]; if (column2 == null) { throw ExceptionBuilder.ElementTypeNotFound(strArray[i]); } columnArray[i] = column2; } table.PrimaryKey = columnArray; } foreach (DataTable table2 in tableChildren) { DataRelation relation = null; DataRelationCollection childRelations = table.ChildRelations; for (int j = 0; j < childRelations.Count; j++) { if (childRelations[j].Nested && (table2 == childRelations[j].ChildTable)) { relation = childRelations[j]; } } if (relation == null) { DataColumn parentKey = table.AddUniqueKey(); DataColumn childColumn = table2.AddForeignKey(parentKey); relation = new DataRelation(table.TableName + "_" + table2.TableName, parentKey, childColumn, true) { CheckMultipleNested = false, Nested = true }; table2.DataSet.Relations.Add(relation); relation.CheckMultipleNested = true; } } return(table); }
internal void HandleColumn(XmlElement node, DataTable table) { DataColumn column; Type type; string str3; string str4; int minOccurs = 0; int maxOccurs = 1; node.GetAttribute("use"); if (node.Attributes.Count > 0) { string str7 = node.GetAttribute("ref"); if ((str7 != null) && (str7.Length > 0)) { return; } str3 = str4 = this.GetInstanceName(node); column = table.Columns[str4, this._schemaUri]; if (column != null) { if (column.ColumnMapping == MappingType.Attribute) { if (XMLSchema.FEqualIdentity(node, "attribute", "urn:schemas-microsoft-com:xml-data")) { throw ExceptionBuilder.DuplicateDeclaration(str3); } } else if (XMLSchema.FEqualIdentity(node, "element", "urn:schemas-microsoft-com:xml-data")) { throw ExceptionBuilder.DuplicateDeclaration(str3); } str4 = XMLSchema.GenUniqueColumnName(str3, table); } } else { str3 = str4 = ""; } XmlElement element = this.FindTypeNode(node); SimpleType type2 = null; if (element == null) { throw ExceptionBuilder.UndefinedDatatype(node.GetAttribute("type")); } string attribute = element.GetAttribute("type", "urn:schemas-microsoft-com:datatypes"); string dtValues = element.GetAttribute("values", "urn:schemas-microsoft-com:datatypes"); if ((attribute == null) || (attribute.Length == 0)) { attribute = ""; type = typeof(string); } else { type = this.ParseDataType(attribute, dtValues); if (attribute == "float") { attribute = ""; } if (attribute == "char") { attribute = ""; type2 = SimpleType.CreateSimpleType(type); } if (attribute == "enumeration") { attribute = ""; type2 = SimpleType.CreateEnumeratedType(dtValues); } if (attribute == "bin.base64") { attribute = ""; type2 = SimpleType.CreateByteArrayType("base64"); } if (attribute == "bin.hex") { attribute = ""; type2 = SimpleType.CreateByteArrayType("hex"); } } bool isAttribute = XMLSchema.FEqualIdentity(node, "attribute", "urn:schemas-microsoft-com:xml-data"); this.GetMinMax(node, isAttribute, ref minOccurs, ref maxOccurs); string str2 = null; str2 = node.GetAttribute("default"); bool flag2 = false; column = new DataColumn(XmlConvert.DecodeName(str4), type, null, isAttribute ? MappingType.Attribute : MappingType.Element); XMLSchema.SetProperties(column, node.Attributes); column.XmlDataType = attribute; column.SimpleType = type2; column.AllowDBNull = (minOccurs == 0) || flag2; column.Namespace = isAttribute ? string.Empty : this._schemaUri; if (node.Attributes != null) { for (int i = 0; i < node.Attributes.Count; i++) { if ((node.Attributes[i].NamespaceURI == "urn:schemas-microsoft-com:xml-msdata") && (node.Attributes[i].LocalName == "Expression")) { column.Expression = node.Attributes[i].Value; break; } } } string str5 = node.GetAttribute("targetNamespace"); if ((str5 != null) && (str5.Length > 0)) { column.Namespace = str5; } table.Columns.Add(column); if ((str2 != null) && (str2.Length != 0)) { try { column.DefaultValue = SqlConvert.ChangeTypeForXML(str2, type); } catch (FormatException) { throw ExceptionBuilder.CannotConvert(str2, type.FullName); } } for (XmlNode node2 = node.FirstChild; node2 != null; node2 = node2.NextSibling) { if (XMLSchema.FEqualIdentity(node2, "description", "urn:schemas-microsoft-com:xml-data")) { column.Description(((XmlElement)node2).InnerText); } } }
internal void LoadTypeValues(XmlSchemaSimpleType node) { if ((node.Content is XmlSchemaSimpleTypeList) || (node.Content is XmlSchemaSimpleTypeUnion)) { throw ExceptionBuilder.SimpleTypeNotSupported(); } if (node.Content is XmlSchemaSimpleTypeRestriction) { XmlSchemaSimpleTypeRestriction content = (XmlSchemaSimpleTypeRestriction)node.Content; XmlSchemaSimpleType ancestor = node.BaseXmlSchemaType as XmlSchemaSimpleType; if ((ancestor != null) && (ancestor.QualifiedName.Namespace != Keywords.XSDNS)) { _baseSimpleType = new SimpleType(node.BaseXmlSchemaType as XmlSchemaSimpleType); } // do we need to put qualified name? // for user defined simpletype, always go with qname if (content.BaseTypeName.Namespace == Keywords.XSDNS) { _baseType = content.BaseTypeName.Name; } else { _baseType = content.BaseTypeName.ToString(); } if (_baseSimpleType != null && _baseSimpleType.Name != null && _baseSimpleType.Name.Length > 0) { _xmlBaseType = _baseSimpleType.XmlBaseType; // SimpleTypeQualifiedName; } else { _xmlBaseType = content.BaseTypeName; } if (_baseType == null || _baseType.Length == 0) { _baseType = content.BaseType.Name; _xmlBaseType = null; } if (_baseType == "NOTATION") { _baseType = "string"; } foreach (XmlSchemaFacet facet in content.Facets) { if (facet is XmlSchemaLengthFacet) { _length = Convert.ToInt32(facet.Value, null); } if (facet is XmlSchemaMinLengthFacet) { _minLength = Convert.ToInt32(facet.Value, null); } if (facet is XmlSchemaMaxLengthFacet) { _maxLength = Convert.ToInt32(facet.Value, null); } if (facet is XmlSchemaPatternFacet) { _pattern = facet.Value; } if (facet is XmlSchemaEnumerationFacet) { _enumeration = !string.IsNullOrEmpty(_enumeration) ? _enumeration + " " + facet.Value : facet.Value; } if (facet is XmlSchemaMinExclusiveFacet) { _minExclusive = facet.Value; } if (facet is XmlSchemaMinInclusiveFacet) { _minInclusive = facet.Value; } if (facet is XmlSchemaMaxExclusiveFacet) { _maxExclusive = facet.Value; } if (facet is XmlSchemaMaxInclusiveFacet) { _maxInclusive = facet.Value; } } } string tempStr = XSDSchema.GetMsdataAttribute(node, Keywords.TARGETNAMESPACE); if (tempStr != null) { _ns = tempStr; } }
private DataTable MergeSchema(DataTable table) { DataTable targetTable = null; if (dataSet.Tables.Contains(table.TableName, true)) { targetTable = dataSet.Tables[table.TableName]; } if (targetTable == null) { if (MissingSchemaAction.Add == missingSchemaAction) { targetTable = table.Clone(); dataSet.Tables.Add(targetTable); } else if (MissingSchemaAction.Error == missingSchemaAction) { throw ExceptionBuilder.MergeMissingDefinition(table.TableName); } } else { if (MissingSchemaAction.Ignore != missingSchemaAction) { // Do the columns int oldCount = targetTable.Columns.Count; for (int i = 0; i < table.Columns.Count; i++) { DataColumn src = table.Columns[i]; DataColumn dest = (targetTable.Columns.Contains(src.ColumnName, true)) ? targetTable.Columns[src.ColumnName] : null; if (dest == null) { if (MissingSchemaAction.Add == missingSchemaAction) { dest = src.Clone(); targetTable.Columns.Add(dest); } else { dataSet.RaiseMergeFailed(targetTable, Res.GetString(Res.DataMerge_MissingColumnDefinition, table.TableName, src.ColumnName), missingSchemaAction); } } else { if (dest.DataType != src.DataType) { dataSet.RaiseMergeFailed(targetTable, Res.GetString(Res.DataMerge_DataTypeMismatch, src.ColumnName), MissingSchemaAction.Error); } // CONSIDER: check all other properties; // CONSIDER: if property has default value, change it or not? MergeExtendedProperties(src.ExtendedProperties, dest.ExtendedProperties); } } // Set DataExpression for (int i = oldCount; i < targetTable.Columns.Count; i++) { targetTable.Columns[i].Expression = table.Columns[targetTable.Columns[i].ColumnName].Expression; } // check the PrimaryKey if (targetTable.PrimaryKey.Length != table.PrimaryKey.Length) { // special case when the target table does not have the PrimaryKey if (targetTable.PrimaryKey.Length == 0) { int keyLength = table.PrimaryKey.Length; DataColumn[] key = new DataColumn[keyLength]; for (int i = 0; i < keyLength; i++) { key[i] = targetTable.Columns[table.PrimaryKey[i].ColumnName]; } targetTable.PrimaryKey = key; } else if (table.PrimaryKey.Length != 0) { dataSet.RaiseMergeFailed(targetTable, Res.GetString(Res.DataMerge_PrimaryKeyMismatch), missingSchemaAction); } } else { for (int i = 0; i < targetTable.PrimaryKey.Length; i++) { if (String.Compare(targetTable.PrimaryKey[i].ColumnName, table.PrimaryKey[i].ColumnName, false, targetTable.Locale) != 0) { dataSet.RaiseMergeFailed(table, Res.GetString(Res.DataMerge_PrimaryKeyColumnsMismatch, targetTable.PrimaryKey[i].ColumnName, table.PrimaryKey[i].ColumnName), missingSchemaAction ); } } } } MergeExtendedProperties(table.ExtendedProperties, targetTable.ExtendedProperties); } return(targetTable); }
internal bool CanRemove([NotNullWhen(true)] DataTable?table, bool fThrowException) { long logScopeId = DataCommonEventSource.Log.EnterScope("<ds.DataTableCollection.CanRemove|INFO> {0}, table={1}, fThrowException={2}", ObjectID, (table != null) ? table.ObjectID : 0, fThrowException); try { if (table == null) { if (!fThrowException) { return(false); } throw ExceptionBuilder.ArgumentNull(nameof(table)); } if (table.DataSet != _dataSet) { if (!fThrowException) { return(false); } throw ExceptionBuilder.TableNotInTheDataSet(table.TableName); } // allow subclasses to throw. _dataSet.OnRemoveTable(table); if (table.ChildRelations.Count != 0 || table.ParentRelations.Count != 0) { if (!fThrowException) { return(false); } throw ExceptionBuilder.TableInRelation(); } for (ParentForeignKeyConstraintEnumerator constraints = new ParentForeignKeyConstraintEnumerator(_dataSet, table); constraints.GetNext();) { ForeignKeyConstraint constraint = constraints.GetForeignKeyConstraint(); if (constraint.Table == table && constraint.RelatedTable == table) // we can go with (constraint.Table == constraint.RelatedTable) { continue; } if (!fThrowException) { return(false); } else { throw ExceptionBuilder.TableInConstraint(table, constraint); } } for (ChildForeignKeyConstraintEnumerator constraints = new ChildForeignKeyConstraintEnumerator(_dataSet, table); constraints.GetNext();) { ForeignKeyConstraint constraint = constraints.GetForeignKeyConstraint(); if (constraint.Table == table && constraint.RelatedTable == table) { continue; } if (!fThrowException) { return(false); } else { throw ExceptionBuilder.TableInConstraint(table, constraint); } } return(true); } finally { DataCommonEventSource.Log.ExitScope(logScopeId); } }
private void MergeRelation(DataRelation relation) { Debug.Assert(MissingSchemaAction.Error == missingSchemaAction || MissingSchemaAction.Add == missingSchemaAction, "Unexpected value of MissingSchemaAction parameter : " + ((Enum)missingSchemaAction).ToString()); DataRelation destRelation = null; // try to find given relation in this dataSet int iDest = dataSet.Relations.InternalIndexOf(relation.RelationName); if (iDest >= 0) { // check the columns and Relation properties.. destRelation = dataSet.Relations[iDest]; if (relation.ParentKey.Columns.Length != destRelation.ParentKey.Columns.Length) { dataSet.RaiseMergeFailed(null, Res.GetString(Res.DataMerge_MissingDefinition, relation.RelationName), missingSchemaAction ); } for (int i = 0; i < relation.ParentKey.Columns.Length; i++) { DataColumn dest = destRelation.ParentKey.Columns[i]; DataColumn src = relation.ParentKey.Columns[i]; if (0 != string.Compare(dest.ColumnName, src.ColumnName, false, dest.Table.Locale)) { dataSet.RaiseMergeFailed(null, Res.GetString(Res.DataMerge_ReltionKeyColumnsMismatch, relation.RelationName), missingSchemaAction ); } dest = destRelation.ChildKey.Columns[i]; src = relation.ChildKey.Columns[i]; if (0 != string.Compare(dest.ColumnName, src.ColumnName, false, dest.Table.Locale)) { dataSet.RaiseMergeFailed(null, Res.GetString(Res.DataMerge_ReltionKeyColumnsMismatch, relation.RelationName), missingSchemaAction ); } } } else { if (MissingSchemaAction.Add == missingSchemaAction) { // create identical realtion in the current dataset DataTable parent = dataSet.Tables[relation.ParentTable.TableName]; DataTable child = dataSet.Tables[relation.ChildTable.TableName]; DataColumn[] parentColumns = new DataColumn[relation.ParentKey.Columns.Length]; DataColumn[] childColumns = new DataColumn[relation.ParentKey.Columns.Length]; for (int i = 0; i < relation.ParentKey.Columns.Length; i++) { parentColumns[i] = parent.Columns[relation.ParentKey.Columns[i].ColumnName]; childColumns[i] = child.Columns[relation.ChildKey.Columns[i].ColumnName]; } try { destRelation = new DataRelation(relation.RelationName, parentColumns, childColumns, relation.createConstraints); destRelation.Nested = relation.Nested; dataSet.Relations.Add(destRelation); } catch (Exception e) { dataSet.RaiseMergeFailed(null, e.Message, missingSchemaAction); } } else { Debug.Assert(MissingSchemaAction.Error == missingSchemaAction, "Unexpected value of MissingSchemaAction parameter : " + ((Enum)missingSchemaAction).ToString()); throw ExceptionBuilder.MergeMissingDefinition(relation.RelationName); } } MergeExtendedProperties(relation.ExtendedProperties, destRelation.ExtendedProperties); return; }
internal DataTable InstantiateTable(DataSet dataSet, XmlElement node, XmlElement typeNode) { string typeName = string.Empty; XmlAttributeCollection attrs = node.Attributes; DataTable table; int minOccurs = 1; int maxOccurs = 1; string keys = null; ArrayList tableChildren = new ArrayList(); if (attrs.Count > 0) { typeName = GetInstanceName(node); table = dataSet.Tables.GetTable(typeName, _schemaUri); if (table != null) { return(table); } } table = new DataTable(XmlConvert.DecodeName(typeName)); // fxcop: new DataTable should inherit the CaseSensitive, Locale from DataSet and possibly updating during SetProperties table.Namespace = _schemaUri; GetMinMax(node, ref minOccurs, ref maxOccurs); table.MinOccurs = minOccurs; table.MaxOccurs = maxOccurs; _ds.Tables.Add(table); HandleTypeNode(typeNode, table, tableChildren); SetProperties(table, attrs); // check to see if we fave unique constraint if (keys != null) { string[] list = keys.TrimEnd(null).Split(null); int keyLength = list.Length; var cols = new DataColumn[keyLength]; for (int i = 0; i < keyLength; i++) { DataColumn col = table.Columns[list[i], _schemaUri]; if (col == null) { throw ExceptionBuilder.ElementTypeNotFound(list[i]); } cols[i] = col; } table.PrimaryKey = cols; } foreach (DataTable _tableChild in tableChildren) { DataRelation relation = null; DataRelationCollection childRelations = table.ChildRelations; for (int j = 0; j < childRelations.Count; j++) { if (!childRelations[j].Nested) { continue; } if (_tableChild == childRelations[j].ChildTable) { relation = childRelations[j]; } } if (relation != null) { continue; } DataColumn parentKey = table.AddUniqueKey(); // foreign key in the child table DataColumn childKey = _tableChild.AddForeignKey(parentKey); // create relationship // setup relationship between parent and this table relation = new DataRelation(table.TableName + "_" + _tableChild.TableName, parentKey, childKey, true); relation.CheckMultipleNested = false; // disable the check for multiple nested parent relation.Nested = true; _tableChild.DataSet.Relations.Add(relation); relation.CheckMultipleNested = true; // enable the check for multiple nested parent } return(table); }
internal void CascadeDelete(DataRow row) { if (-1 == row.newRecord) { return; } object[] currentKey = row.GetKeyValues(parentKey, DataRowVersion.Current); if (IsKeyNull(currentKey)) { return; } Index childIndex = childKey.GetSortIndex(); switch (DeleteRule) { case Rule.None: { if (row.Table.DataSet.EnforceConstraints) { // if we're not cascading deletes, we should throw if we're going to strand a child row under enforceConstraints. Range range = childIndex.FindRecords(currentKey); if (!range.IsNull) { if (range.Count == 1 && childIndex.GetRow(range.Min) == row) { return; } throw ExceptionBuilder.FailedCascadeDelete(ConstraintName); } } break; } case Rule.Cascade: { object[] key = row.GetKeyValues(parentKey, DataRowVersion.Default); Range range = childIndex.FindRecords(key); if (!range.IsNull) { DataRow[] rows = childIndex.GetRows(range); for (int j = 0; j < rows.Length; j++) { DataRow r = rows[j]; if (r.inCascade) { continue; } r.Table.DeleteRow(r); } } break; } case Rule.SetNull: { object[] proposedKey = new object[childKey.ColumnsReference.Length]; for (int i = 0; i < childKey.ColumnsReference.Length; i++) { proposedKey[i] = DBNull.Value; } Range range = childIndex.FindRecords(currentKey); if (!range.IsNull) { DataRow[] rows = childIndex.GetRows(range); for (int j = 0; j < rows.Length; j++) { // if (rows[j].inCascade) // continue; if (row != rows[j]) { rows[j].SetKeyValues(childKey, proposedKey); } } } break; } case Rule.SetDefault: { object[] proposedKey = new object[childKey.ColumnsReference.Length]; for (int i = 0; i < childKey.ColumnsReference.Length; i++) { proposedKey[i] = childKey.ColumnsReference[i].DefaultValue; } Range range = childIndex.FindRecords(currentKey); if (!range.IsNull) { DataRow[] rows = childIndex.GetRows(range); for (int j = 0; j < rows.Length; j++) { // if (rows[j].inCascade) // continue; if (row != rows[j]) { rows[j].SetKeyValues(childKey, proposedKey); } } } break; } default: { Debug.Assert(false, "Unknown Rule value"); break; } } }
int IList.Add(object?value) { throw ExceptionBuilder.CannotModifyCollection(); }
internal override bool IsConstraintViolated() { Index childIndex = _childKey.GetSortIndex(); object[] uniqueChildKeys = childIndex.GetUniqueKeyValues(); bool errors = false; Index parentIndex = _parentKey.GetSortIndex(); for (int i = 0; i < uniqueChildKeys.Length; i++) { object[] childValues = (object[])uniqueChildKeys[i]; if (!IsKeyNull(childValues)) { if (!parentIndex.IsKeyInIndex(childValues)) { DataRow[] rows = childIndex.GetRows(childIndex.FindRecords(childValues)); string error = SR.Format(SR.DataConstraint_ForeignKeyViolation, ConstraintName, ExceptionBuilder.KeysToString(childValues)); for (int j = 0; j < rows.Length; j++) { rows[j].RowError = error; } errors = true; } } } return(errors); }
void IList.Insert(int index, object?value) { throw ExceptionBuilder.CannotModifyCollection(); }
internal void CascadeUpdate(DataRow row) { Debug.Assert(Table?.DataSet != null && row.Table.DataSet != null); if (-1 == row._newRecord) { return; } object[] currentKey = row.GetKeyValues(_parentKey, DataRowVersion.Current); if (!Table.DataSet._fInReadXml && IsKeyNull(currentKey)) { return; } Index childIndex = _childKey.GetSortIndex(); switch (UpdateRule) { case Rule.None: { if (row.Table.DataSet.EnforceConstraints) { // if we're not cascading deletes, we should throw if we're going to strand a child row under enforceConstraints. Range range = childIndex.FindRecords(currentKey); if (!range.IsNull) { throw ExceptionBuilder.FailedCascadeUpdate(ConstraintName); } } break; } case Rule.Cascade: { Range range = childIndex.FindRecords(currentKey); if (!range.IsNull) { object[] proposedKey = row.GetKeyValues(_parentKey, DataRowVersion.Proposed); DataRow[] rows = childIndex.GetRows(range); for (int j = 0; j < rows.Length; j++) { // if (rows[j].inCascade) // continue; rows[j].SetKeyValues(_childKey, proposedKey); } } break; } case Rule.SetNull: { object[] proposedKey = new object[_childKey.ColumnsReference.Length]; for (int i = 0; i < _childKey.ColumnsReference.Length; i++) { proposedKey[i] = DBNull.Value; } Range range = childIndex.FindRecords(currentKey); if (!range.IsNull) { DataRow[] rows = childIndex.GetRows(range); for (int j = 0; j < rows.Length; j++) { // if (rows[j].inCascade) // continue; rows[j].SetKeyValues(_childKey, proposedKey); } } break; } case Rule.SetDefault: { object[] proposedKey = new object[_childKey.ColumnsReference.Length]; for (int i = 0; i < _childKey.ColumnsReference.Length; i++) { proposedKey[i] = _childKey.ColumnsReference[i].DefaultValue; } Range range = childIndex.FindRecords(currentKey); if (!range.IsNull) { DataRow[] rows = childIndex.GetRows(range); for (int j = 0; j < rows.Length; j++) { // if (rows[j].inCascade) // continue; rows[j].SetKeyValues(_childKey, proposedKey); } } break; } default: { Debug.Fail("Unknown Rule value"); break; } } }
void IList.RemoveAt(int index) { throw ExceptionBuilder.CannotModifyCollection(); }
internal void FinishInitConstraints() { if (delayLoadingConstraints == null) { return; } int colCount; DataColumn[] parents, childs; for (int i = 0; i < delayLoadingConstraints.Length; i++) { if (delayLoadingConstraints[i] is UniqueConstraint) { if (fLoadForeignKeyConstraintsOnly) { continue; } UniqueConstraint constr = (UniqueConstraint)delayLoadingConstraints[i]; if (constr.columnNames == null) { this.Add(constr); continue; } colCount = constr.columnNames.Length; parents = new DataColumn[colCount]; for (int j = 0; j < colCount; j++) { parents[j] = table.Columns[constr.columnNames[j]]; } if (constr.bPrimaryKey) { if (table.primaryKey != null) { throw ExceptionBuilder.AddPrimaryKeyConstraint(); } else { Add(constr.ConstraintName, parents, true); } continue; } UniqueConstraint newConstraint = new UniqueConstraint(constr.constraintName, parents); if (FindConstraint(newConstraint) == null) { this.Add(newConstraint); } } else { ForeignKeyConstraint constr = (ForeignKeyConstraint)delayLoadingConstraints[i]; if (constr.parentColumnNames == null || constr.childColumnNames == null) { this.Add(constr); continue; } if (table.DataSet == null) { fLoadForeignKeyConstraintsOnly = true; continue; } colCount = constr.parentColumnNames.Length; parents = new DataColumn[colCount]; childs = new DataColumn[colCount]; for (int j = 0; j < colCount; j++) { if (constr.parentTableNamespace == null) { parents[j] = table.DataSet.Tables[constr.parentTableName].Columns[constr.parentColumnNames[j]]; } else { parents[j] = table.DataSet.Tables[constr.parentTableName, constr.parentTableNamespace].Columns[constr.parentColumnNames[j]]; } childs[j] = table.Columns[constr.childColumnNames[j]]; } ForeignKeyConstraint newConstraint = new ForeignKeyConstraint(constr.constraintName, parents, childs); newConstraint.AcceptRejectRule = constr.acceptRejectRule; newConstraint.DeleteRule = constr.deleteRule; newConstraint.UpdateRule = constr.updateRule; this.Add(newConstraint); } } if (!fLoadForeignKeyConstraintsOnly) { delayLoadingConstraints = null; } }
internal void MergeRows(DataRow[] rows) { Debug.Assert(_dataSet != null); DataTable?src = null; DataTable?dst = null; DataKey key = default(DataKey); Index? ndxSearch = null; bool fEnforce = _dataSet.EnforceConstraints; _dataSet.EnforceConstraints = false; for (int i = 0; i < rows.Length; i++) { DataRow row = rows[i]; if (row == null) { throw ExceptionBuilder.ArgumentNull($"{nameof(rows)}[{i}]"); } if (row.Table == null) { throw ExceptionBuilder.ArgumentNull($"{nameof(rows)}[{i}].{nameof(DataRow.Table)}"); } //somebody is doing an 'automerge' if (row.Table.DataSet == _dataSet) { continue; } if (src != row.Table) { // row.Table changed from prev. row. src = row.Table; dst = MergeSchema(row.Table); if (dst == null) { Debug.Assert(MissingSchemaAction.Ignore == _missingSchemaAction, "MergeSchema failed"); _dataSet.EnforceConstraints = fEnforce; return; } if (dst._primaryKey != null) { key = GetSrcKey(src, dst); } if (key.HasValue) { // Getting our own copy instead. ndxSearch = dst.primaryKey.Key.GetSortIndex(); // IMO, Better would be to reuse index // ndxSearch = dst.primaryKey.Key.GetSortIndex(DataViewRowState.OriginalRows | DataViewRowState.Added ); if (null != ndxSearch) { ndxSearch.RemoveRef(); ndxSearch = null; } ndxSearch = new Index(dst, dst._primaryKey !.Key.GetIndexDesc(), DataViewRowState.OriginalRows | DataViewRowState.Added, null); ndxSearch.AddRef(); // need to addref twice, otherwise it will be collected ndxSearch.AddRef(); // in past first adref was done in const } } if (row._newRecord == -1 && row._oldRecord == -1) { continue; } DataRow?targetRow = null; if (0 < dst !.Rows.Count && ndxSearch != null) { targetRow = dst.FindMergeTarget(row, key, ndxSearch); } targetRow = dst.MergeRow(row, targetRow, _preserveChanges, ndxSearch); if (targetRow.Table._dependentColumns != null && targetRow.Table._dependentColumns.Count > 0) { targetRow.Table.EvaluateExpressions(targetRow, DataRowAction.Change, null); } } if (null != ndxSearch) { ndxSearch.RemoveRef(); ndxSearch = null; } _dataSet.EnforceConstraints = fEnforce; }
// To add foreign key constraint without adding any unique constraint for internal use. Main purpose : Binary Remoting internal void Add(Constraint constraint, bool addUniqueWhenAddingForeign) { if (constraint == null) { throw ExceptionBuilder.ArgumentNull("constraint"); } // It is an error if we find an equivalent constraint already in collection if (FindConstraint(constraint) != null) { throw ExceptionBuilder.DuplicateConstraint(FindConstraint(constraint).ConstraintName); } if (1 < table.NestedParentRelations.Length) { if (!AutoGenerated(constraint)) { throw ExceptionBuilder.CantAddConstraintToMultipleNestedTable(table.TableName); } } if (constraint is UniqueConstraint) { if (((UniqueConstraint)constraint).bPrimaryKey) { if (Table.primaryKey != null) { throw ExceptionBuilder.AddPrimaryKeyConstraint(); } } AddUniqueConstraint((UniqueConstraint)constraint); } else if (constraint is ForeignKeyConstraint) { ForeignKeyConstraint fk = (ForeignKeyConstraint)constraint; if (addUniqueWhenAddingForeign) { UniqueConstraint key = fk.RelatedTable.Constraints.FindKeyConstraint(fk.RelatedColumnsReference); if (key == null) { if (constraint.ConstraintName.Length == 0) { constraint.ConstraintName = AssignName(); } else { RegisterName(constraint.ConstraintName); } key = new UniqueConstraint(fk.RelatedColumnsReference); fk.RelatedTable.Constraints.Add(key); } } AddForeignKeyConstraint((ForeignKeyConstraint)constraint); } BaseAdd(constraint); ArrayAdd(constraint); OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Add, constraint)); if (constraint is UniqueConstraint) { if (((UniqueConstraint)constraint).bPrimaryKey) { Table.PrimaryKey = ((UniqueConstraint)constraint).ColumnsReference; } } }
private void MergeRelation(DataRelation relation) { Debug.Assert(_dataSet != null); Debug.Assert(MissingSchemaAction.Error == _missingSchemaAction || MissingSchemaAction.Add == _missingSchemaAction, "Unexpected value of MissingSchemaAction parameter : " + _missingSchemaAction.ToString()); DataRelation?destRelation = null; // try to find given relation in this dataSet int iDest = _dataSet.Relations.InternalIndexOf(relation.RelationName); if (iDest >= 0) { // check the columns and Relation properties.. destRelation = _dataSet.Relations[iDest]; if (relation.ParentKey.ColumnsReference.Length != destRelation.ParentKey.ColumnsReference.Length) { _dataSet.RaiseMergeFailed(null, SR.Format(SR.DataMerge_MissingDefinition, relation.RelationName), _missingSchemaAction); } for (int i = 0; i < relation.ParentKey.ColumnsReference.Length; i++) { DataColumn dest = destRelation.ParentKey.ColumnsReference[i]; DataColumn src = relation.ParentKey.ColumnsReference[i]; if (0 != string.Compare(dest.ColumnName, src.ColumnName, false, dest.Table !.Locale)) { _dataSet.RaiseMergeFailed(null, SR.Format(SR.DataMerge_ReltionKeyColumnsMismatch, relation.RelationName), _missingSchemaAction); } dest = destRelation.ChildKey.ColumnsReference[i]; src = relation.ChildKey.ColumnsReference[i]; if (0 != string.Compare(dest.ColumnName, src.ColumnName, false, dest.Table !.Locale)) { _dataSet.RaiseMergeFailed(null, SR.Format(SR.DataMerge_ReltionKeyColumnsMismatch, relation.RelationName), _missingSchemaAction); } } } else { if (MissingSchemaAction.Add == _missingSchemaAction) { // create identical realtion in the current dataset DataTable parent = _IgnoreNSforTableLookup ? _dataSet.Tables[relation.ParentTable.TableName] ! : _dataSet.Tables[relation.ParentTable.TableName, relation.ParentTable.Namespace] !; DataTable child = _IgnoreNSforTableLookup ? _dataSet.Tables[relation.ChildTable.TableName] ! : _dataSet.Tables[relation.ChildTable.TableName, relation.ChildTable.Namespace] !; DataColumn[] parentColumns = new DataColumn[relation.ParentKey.ColumnsReference.Length]; DataColumn[] childColumns = new DataColumn[relation.ParentKey.ColumnsReference.Length]; for (int i = 0; i < relation.ParentKey.ColumnsReference.Length; i++) { parentColumns[i] = parent.Columns[relation.ParentKey.ColumnsReference[i].ColumnName] !; childColumns[i] = child.Columns[relation.ChildKey.ColumnsReference[i].ColumnName] !; } try { destRelation = new DataRelation(relation.RelationName, parentColumns, childColumns, relation._createConstraints); destRelation.Nested = relation.Nested; _dataSet.Relations.Add(destRelation); } catch (Exception e) when(Common.ADP.IsCatchableExceptionType(e)) { ExceptionBuilder.TraceExceptionForCapture(e); _dataSet.RaiseMergeFailed(null, e.Message, _missingSchemaAction); // TODO: destRelation may be null, causing an NRE below } } else { Debug.Assert(MissingSchemaAction.Error == _missingSchemaAction, "Unexpected value of MissingSchemaAction parameter : " + _missingSchemaAction.ToString()); throw ExceptionBuilder.MergeMissingDefinition(relation.RelationName); } } // TODO: destRelation may be null, see comment above MergeExtendedProperties(relation.ExtendedProperties, destRelation !.ExtendedProperties); }
internal void XmlDataRowWriter(DataRow row, string encodedTableName) { object obj2; string prefix = (row.Table.Namespace.Length == 0) ? "" : row.Table.Prefix; this._xmlw.WriteStartElement(prefix, encodedTableName, row.Table.Namespace); if (this.isDiffgram) { this._xmlw.WriteAttributeString("diffgr", "id", "urn:schemas-microsoft-com:xml-diffgram-v1", row.Table.TableName + row.rowID.ToString(CultureInfo.InvariantCulture)); this._xmlw.WriteAttributeString("msdata", "rowOrder", "urn:schemas-microsoft-com:xml-msdata", this.rowsOrder[row].ToString()); if (row.RowState == DataRowState.Added) { this._xmlw.WriteAttributeString("diffgr", "hasChanges", "urn:schemas-microsoft-com:xml-diffgram-v1", "inserted"); } if (row.RowState == DataRowState.Modified) { this._xmlw.WriteAttributeString("diffgr", "hasChanges", "urn:schemas-microsoft-com:xml-diffgram-v1", "modified"); } if (RowHasErrors(row)) { this._xmlw.WriteAttributeString("diffgr", "hasErrors", "urn:schemas-microsoft-com:xml-diffgram-v1", "true"); } } foreach (DataColumn column2 in row.Table.Columns) { if (column2.columnMapping == MappingType.Attribute) { obj2 = row[column2]; string str3 = (column2.Namespace.Length == 0) ? "" : column2.Prefix; if ((obj2 != DBNull.Value) && (!column2.ImplementsINullable || !DataStorage.IsObjectSqlNull(obj2))) { XmlTreeGen.ValidateColumnMapping(column2.DataType); this._xmlw.WriteAttributeString(str3, column2.EncodedColumnName, column2.Namespace, column2.ConvertObjectToXml(obj2)); } } if (this.isDiffgram && (column2.columnMapping == MappingType.Hidden)) { obj2 = row[column2]; if ((obj2 != DBNull.Value) && (!column2.ImplementsINullable || !DataStorage.IsObjectSqlNull(obj2))) { XmlTreeGen.ValidateColumnMapping(column2.DataType); this._xmlw.WriteAttributeString("msdata", "hidden" + column2.EncodedColumnName, "urn:schemas-microsoft-com:xml-msdata", column2.ConvertObjectToXml(obj2)); } } } foreach (DataColumn column in row.Table.Columns) { if (column.columnMapping != MappingType.Hidden) { obj2 = row[column]; string str2 = (column.Namespace.Length == 0) ? "" : column.Prefix; bool flag = true; if (((obj2 == DBNull.Value) || (column.ImplementsINullable && DataStorage.IsObjectSqlNull(obj2))) && (column.ColumnMapping == MappingType.SimpleContent)) { this._xmlw.WriteAttributeString("xsi", "nil", "http://www.w3.org/2001/XMLSchema-instance", "true"); } if (((obj2 != DBNull.Value) && (!column.ImplementsINullable || !DataStorage.IsObjectSqlNull(obj2))) && (column.columnMapping != MappingType.Attribute)) { if ((column.columnMapping != MappingType.SimpleContent) && ((!column.IsCustomType || !column.IsValueCustomTypeInstance(obj2)) || typeof(IXmlSerializable).IsAssignableFrom(obj2.GetType()))) { this._xmlw.WriteStartElement(str2, column.EncodedColumnName, column.Namespace); flag = false; } Type type = obj2.GetType(); if (!column.IsCustomType) { if (((type == typeof(char)) || (type == typeof(string))) && PreserveSpace(obj2)) { this._xmlw.WriteAttributeString("xml", "space", "http://www.w3.org/XML/1998/namespace", "preserve"); } this._xmlw.WriteString(column.ConvertObjectToXml(obj2)); } else if (column.IsValueCustomTypeInstance(obj2)) { if (!flag && (type != column.DataType)) { this._xmlw.WriteAttributeString("msdata", "InstanceType", "urn:schemas-microsoft-com:xml-msdata", DataStorage.GetQualifiedName(type)); } if (!flag) { column.ConvertObjectToXml(obj2, this._xmlw, null); } else { if (obj2.GetType() != column.DataType) { throw ExceptionBuilder.PolymorphismNotSupported(type.AssemblyQualifiedName); } XmlRootAttribute xmlAttrib = new XmlRootAttribute(column.EncodedColumnName) { Namespace = column.Namespace }; column.ConvertObjectToXml(obj2, this._xmlw, xmlAttrib); } } else { if (((type == typeof(Type)) || (type == typeof(Guid))) || ((type == typeof(char)) || DataStorage.IsSqlType(type))) { this._xmlw.WriteAttributeString("msdata", "InstanceType", "urn:schemas-microsoft-com:xml-msdata", type.FullName); } else if (obj2 is Type) { this._xmlw.WriteAttributeString("msdata", "InstanceType", "urn:schemas-microsoft-com:xml-msdata", "Type"); } else { string str = "xs:" + XmlTreeGen.XmlDataTypeName(type); this._xmlw.WriteAttributeString("xsi", "type", "http://www.w3.org/2001/XMLSchema-instance", str); this._xmlw.WriteAttributeString("xmlns:xs", "http://www.w3.org/2001/XMLSchema"); } if (!DataStorage.IsSqlType(type)) { this._xmlw.WriteString(column.ConvertObjectToXml(obj2)); } else { column.ConvertObjectToXml(obj2, this._xmlw, null); } } if ((column.columnMapping != MappingType.SimpleContent) && !flag) { this._xmlw.WriteEndElement(); } } } } if (this._ds != null) { foreach (DataRelation relation in this.GetNestedChildRelations(row)) { foreach (DataRow row2 in row.GetChildRows(relation)) { this.XmlDataRowWriter(row2, relation.ChildTable.EncodedTableName); } } } this._xmlw.WriteEndElement(); }