1 //------------------------------------------------------------------------------
2 // <copyright file="DataRelationCollection.cs" company="Microsoft">
3 // Copyright (c) Microsoft Corporation. All rights reserved.
5 // <owner current="true" primary="true">Microsoft</owner>
6 // <owner current="true" primary="false">Microsoft</owner>
7 // <owner current="false" primary="false">Microsoft</owner>
8 //------------------------------------------------------------------------------
10 namespace System.Data {
12 using System.Collections;
13 using System.ComponentModel;
14 using System.Diagnostics;
15 using System.Globalization;
19 /// Represents the collection of relations,
20 /// each of which allows navigation between related parent/child tables.
24 DefaultEvent("CollectionChanged"),
25 Editor("Microsoft.VSDesigner.Data.Design.DataRelationCollectionEditor, " + AssemblyRef.MicrosoftVSDesigner, "System.Drawing.Design.UITypeEditor, " + AssemblyRef.SystemDrawing),
26 DefaultProperty("Table"),
28 public abstract class DataRelationCollection : InternalDataCollectionBase {
30 private DataRelation inTransition = null;
32 private int defaultNameIndex = 1;
34 private CollectionChangeEventHandler onCollectionChangedDelegate;
35 private CollectionChangeEventHandler onCollectionChangingDelegate;
37 private static int _objectTypeCount; // Bid counter
38 private readonly int _objectID = System.Threading.Interlocked.Increment(ref _objectTypeCount);
40 internal int ObjectID {
47 /// <para>Gets the relation specified by index.</para>
49 public abstract DataRelation this[int index] {
54 /// <para>Gets the relation specified by name.</para>
56 public abstract DataRelation this[string name] {
62 /// Adds the relation to the collection.</para>
64 public void Add(DataRelation relation) {
66 Bid.ScopeEnter(out hscp, "<ds.DataRelationCollection.Add|API> %d#, relation=%d\n", ObjectID, (relation != null) ? relation.ObjectID : 0);
68 if (inTransition == relation)
70 inTransition = relation;
72 OnCollectionChanging(new CollectionChangeEventArgs(CollectionChangeAction.Add, relation));
74 OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Add, relation));
81 Bid.ScopeLeave(ref hscp);
86 /// <para>[To be supplied.]</para>
88 public virtual void AddRange(DataRelation[] relations) {
89 if (relations != null) {
90 foreach(DataRelation relation in relations) {
91 if (relation != null) {
100 /// Creates a <see cref='System.Data.DataRelation'/> with the
101 /// specified name, parent columns,
102 /// child columns, and adds it to the collection.</para>
104 public virtual DataRelation Add(string name, DataColumn[] parentColumns, DataColumn[] childColumns) {
105 DataRelation relation = new DataRelation(name, parentColumns, childColumns);
111 /// Creates a relation given the parameters and adds it to the collection. An ArgumentNullException is
112 /// thrown if this relation is null. An ArgumentException is thrown if this relation already belongs to
113 /// this collection, belongs to another collection, or if this collection already has a relation with the
114 /// same name (case insensitive).
115 /// An InvalidRelationException is thrown if the relation can't be created based on the parameters.
116 /// The CollectionChanged event is fired if it succeeds.
118 public virtual DataRelation Add(string name, DataColumn[] parentColumns, DataColumn[] childColumns, bool createConstraints) {
119 DataRelation relation = new DataRelation(name, parentColumns, childColumns, createConstraints);
125 /// Creates a relation given the parameters and adds it to the collection. The name is defaulted.
126 /// An ArgumentException is thrown if
127 /// this relation already belongs to this collection or belongs to another collection.
128 /// An InvalidConstraintException is thrown if the relation can't be created based on the parameters.
129 /// The CollectionChanged event is fired if it succeeds.
131 public virtual DataRelation Add(DataColumn[] parentColumns, DataColumn[] childColumns) {
132 DataRelation relation = new DataRelation(null, parentColumns, childColumns);
138 /// Creates a relation given the parameters and adds it to the collection.
139 /// An ArgumentException is thrown if this relation already belongs to
140 /// this collection or belongs to another collection.
141 /// A DuplicateNameException is thrown if this collection already has a relation with the same
142 /// name (case insensitive).
143 /// An InvalidConstraintException is thrown if the relation can't be created based on the parameters.
144 /// The CollectionChanged event is fired if it succeeds.
146 public virtual DataRelation Add(string name, DataColumn parentColumn, DataColumn childColumn) {
147 DataRelation relation = new DataRelation(name, parentColumn, childColumn);
153 /// Creates a relation given the parameters and adds it to the collection.
154 /// An ArgumentException is thrown if this relation already belongs to
155 /// this collection or belongs to another collection.
156 /// A DuplicateNameException is thrown if this collection already has a relation with the same
157 /// name (case insensitive).
158 /// An InvalidConstraintException is thrown if the relation can't be created based on the parameters.
159 /// The CollectionChanged event is fired if it succeeds.
161 public virtual DataRelation Add(string name, DataColumn parentColumn, DataColumn childColumn, bool createConstraints) {
162 DataRelation relation = new DataRelation(name, parentColumn, childColumn, createConstraints);
168 /// Creates a relation given the parameters and adds it to the collection. The name is defaulted.
169 /// An ArgumentException is thrown if
170 /// this relation already belongs to this collection or belongs to another collection.
171 /// An InvalidConstraintException is thrown if the relation can't be created based on the parameters.
172 /// The CollectionChanged event is fired if it succeeds.
174 public virtual DataRelation Add(DataColumn parentColumn, DataColumn childColumn) {
175 DataRelation relation = new DataRelation(null, parentColumn, childColumn);
181 /// Does verification on the table.
182 /// An ArgumentNullException is thrown if this relation is null. An ArgumentException is thrown if this relation
183 /// already belongs to this collection, belongs to another collection.
184 /// A DuplicateNameException is thrown if this collection already has a relation with the same
185 /// name (case insensitive).
187 protected virtual void AddCore(DataRelation relation) {
188 Bid.Trace("<ds.DataRelationCollection.AddCore|INFO> %d#, relation=%d\n", ObjectID, (relation != null) ? relation.ObjectID : 0);
189 if (relation == null)
190 throw ExceptionBuilder.ArgumentNull("relation");
191 relation.CheckState();
192 DataSet dataSet = GetDataSet();
193 if (relation.DataSet == dataSet)
194 throw ExceptionBuilder.RelationAlreadyInTheDataSet();
195 if (relation.DataSet != null)
196 throw ExceptionBuilder.RelationAlreadyInOtherDataSet();
197 if (relation.ChildTable.Locale.LCID != relation.ParentTable.Locale.LCID ||
198 relation.ChildTable.CaseSensitive != relation.ParentTable.CaseSensitive)
199 throw ExceptionBuilder.CaseLocaleMismatch();
200 if (relation.Nested) {
201 relation.CheckNamespaceValidityForNestedRelations(relation.ParentTable.Namespace);
202 relation.ValidateMultipleNestedRelations();
203 relation.ParentTable.ElementColumnCount++;
208 /// <para>[To be supplied.]</para>
210 [ResDescriptionAttribute(Res.collectionChangedEventDescr)]
211 public event CollectionChangeEventHandler CollectionChanged {
213 Bid.Trace("<ds.DataRelationCollection.add_CollectionChanged|API> %d#\n", ObjectID);
214 onCollectionChangedDelegate += value;
217 Bid.Trace("<ds.DataRelationCollection.remove_CollectionChanged|API> %d#\n", ObjectID);
218 onCollectionChangedDelegate -= value;
222 internal event CollectionChangeEventHandler CollectionChanging {
224 Bid.Trace("<ds.DataRelationCollection.add_CollectionChanging|INFO> %d#\n", ObjectID);
225 onCollectionChangingDelegate += value;
228 Bid.Trace("<ds.DataRelationCollection.remove_CollectionChanging|INFO> %d#\n", ObjectID);
229 onCollectionChangingDelegate -= value;
234 /// Creates a new default name.
236 internal string AssignName() {
237 string newName = MakeName(defaultNameIndex);
243 /// Clears the collection of any relations.
245 public virtual void Clear() {
247 Bid.ScopeEnter(out hscp, "<ds.DataRelationCollection.Clear|API> %d#\n", ObjectID);
250 OnCollectionChanging(RefreshEventArgs);
251 for (int i = count - 1; i >= 0; i--) {
252 inTransition = this[i];
253 RemoveCore(inTransition); // Microsoft : No need to go for try catch here and this will surely not throw any exception
255 OnCollectionChanged(RefreshEventArgs);
259 Bid.ScopeLeave(ref hscp);
264 /// Returns true if this collection has a relation with the given name (case insensitive), false otherwise.
266 public virtual bool Contains(string name) {
267 return(InternalIndexOf(name) >= 0);
270 public void CopyTo(DataRelation[] array, int index) {
272 throw ExceptionBuilder.ArgumentNull("array");
274 throw ExceptionBuilder.ArgumentOutOfRange("index");
275 ArrayList alist = List;
276 if (array.Length - index < alist.Count)
277 throw ExceptionBuilder.InvalidOffsetLength();
278 for(int i = 0; i < alist.Count; ++i) {
279 array[index + i] = (DataRelation)alist[i];
285 /// Returns the index of a specified <see cref='System.Data.DataRelation'/>.
288 public virtual int IndexOf(DataRelation relation) {
289 int relationCount = List.Count;
290 for (int i = 0; i < relationCount; ++i) {
291 if (relation == (DataRelation) List[i]) {
300 /// Returns the index of the
301 /// relation with the given name (case insensitive), or -1 if the relation
302 /// doesn't exist in the collection.
305 public virtual int IndexOf(string relationName) {
306 int index = InternalIndexOf(relationName);
307 return (index < 0) ? -1 : index;
310 internal int InternalIndexOf(string name) {
312 if ((null != name) && (0 < name.Length)) {
313 int count = List.Count;
315 for (int i = 0; i < count; i++) {
316 DataRelation relation = (DataRelation) List[i];
317 result = NamesEqual(relation.RelationName, name, false, GetDataSet().Locale);
322 cachedI = (cachedI == -1) ? i : -2;
329 /// Gets the dataSet for this collection.
331 protected abstract DataSet GetDataSet();
334 /// Makes a default name with the given index. e.g. Relation1, Relation2, ... Relationi
336 private string MakeName(int index) {
340 return "Relation" + index.ToString(System.Globalization.CultureInfo.InvariantCulture);
344 /// This method is called whenever the collection changes. Overriders
345 /// of this method should call the base implementation of this method.
347 protected virtual void OnCollectionChanged(CollectionChangeEventArgs ccevent) {
348 if (onCollectionChangedDelegate != null) {
349 Bid.Trace("<ds.DataRelationCollection.OnCollectionChanged|INFO> %d#\n", ObjectID);
350 onCollectionChangedDelegate(this, ccevent);
355 /// <para>[To be supplied.]</para>
357 protected virtual void OnCollectionChanging(CollectionChangeEventArgs ccevent) {
358 if (onCollectionChangingDelegate != null) {
359 Bid.Trace("<ds.DataRelationCollection.OnCollectionChanging|INFO> %d#\n", ObjectID);
360 onCollectionChangingDelegate(this, ccevent);
365 /// Registers this name as being used in the collection. Will throw an ArgumentException
366 /// if the name is already being used. Called by Add, All property, and Relation.RelationName property.
367 /// if the name is equivalent to the next default name to hand out, we increment our defaultNameIndex.
369 internal void RegisterName(string name) {
370 Bid.Trace("<ds.DataRelationCollection.RegisterName|INFO> %d#, name='%ls'\n", ObjectID, name);
371 Debug.Assert (name != null);
373 CultureInfo locale = GetDataSet().Locale;
374 int relationCount = Count;
375 for (int i = 0; i < relationCount; i++) {
376 if (NamesEqual(name, this[i].RelationName, true, locale) != 0) {
377 throw ExceptionBuilder.DuplicateRelation(this[i].RelationName);
380 if (NamesEqual(name, MakeName(defaultNameIndex), true, locale) != 0) {
387 /// Verifies if a given relation can be removed from the collection.
390 public virtual bool CanRemove(DataRelation relation) {
391 if (relation == null)
394 if (relation.DataSet != GetDataSet())
401 /// Removes the given relation from the collection.
402 /// An ArgumentNullException is thrown if this relation is null. An ArgumentException is thrown
403 /// if this relation doesn't belong to this collection.
404 /// The CollectionChanged event is fired if it succeeds.
406 public void Remove(DataRelation relation) {
407 Bid.Trace("<ds.DataRelationCollection.Remove|API> %d#, relation=%d\n", ObjectID, (relation != null) ? relation.ObjectID : 0);
408 if (inTransition == relation)
410 inTransition = relation;
412 OnCollectionChanging(new CollectionChangeEventArgs(CollectionChangeAction.Remove, relation));
413 RemoveCore(relation);
414 OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Remove, relation));
422 /// Removes the relation at the given index from the collection. An IndexOutOfRangeException is
423 /// thrown if this collection doesn't have a relation at this index.
424 /// The CollectionChanged event is fired if it succeeds.
426 public void RemoveAt(int index) {
427 DataRelation dr = this[index];
429 throw ExceptionBuilder.RelationOutOfRange(index);
437 /// Removes the relation with the given name from the collection. An IndexOutOfRangeException is
438 /// thrown if this collection doesn't have a relation with that name
439 /// The CollectionChanged event is fired if it succeeds.
441 public void Remove(string name) {
442 DataRelation dr = this[name];
444 throw ExceptionBuilder.RelationNotInTheDataSet(name);
451 /// Does verification on the relation.
452 /// An ArgumentNullException is thrown if this relation is null. An ArgumentException is thrown
453 /// if this relation doesn't belong to this collection.
455 protected virtual void RemoveCore(DataRelation relation) {
456 Bid.Trace("<ds.DataRelationCollection.RemoveCore|INFO> %d#, relation=%d\n", ObjectID, (relation != null) ? relation.ObjectID : 0);
457 if (relation == null)
458 throw ExceptionBuilder.ArgumentNull("relation");
459 DataSet dataSet = GetDataSet();
460 if (relation.DataSet != dataSet)
461 throw ExceptionBuilder.RelationNotInTheDataSet(relation.RelationName);
462 if (relation.Nested) {
463 relation.ParentTable.ElementColumnCount--;
465 // why we were not unregistering the table when removing the relation
466 relation.ParentTable.Columns.UnregisterName(relation.ChildTable.TableName);
471 /// Unregisters this name as no longer being used in the collection. Called by Remove, All property, and
472 /// Relation.RelationName property. If the name is equivalent to the last proposed default name, we walk backwards
473 /// to find the next proper default name to use.
475 internal void UnregisterName(string name) {
476 Bid.Trace("<ds.DataRelationCollection.UnregisterName|INFO> %d#, name='%ls'\n", ObjectID, name);
477 if (NamesEqual(name, MakeName(defaultNameIndex - 1), true, GetDataSet().Locale) != 0) {
480 } while (defaultNameIndex > 1 &&
481 !Contains(MakeName(defaultNameIndex - 1)));
485 internal sealed class DataTableRelationCollection : DataRelationCollection {
487 private readonly DataTable table;
488 private readonly ArrayList relations; // For caching purpose only to improve performance
489 private readonly bool fParentCollection;
491 private CollectionChangeEventHandler onRelationPropertyChangedDelegate;
493 internal DataTableRelationCollection(DataTable table, bool fParentCollection) {
495 throw ExceptionBuilder.RelationTableNull();
497 this.fParentCollection = fParentCollection;
498 relations = new ArrayList();
501 protected override ArrayList List {
507 private void EnsureDataSet() {
508 if (table.DataSet == null) {
509 throw ExceptionBuilder.RelationTableWasRemoved();
513 protected override DataSet GetDataSet() {
515 return table.DataSet;
518 public override DataRelation this[int index] {
520 if (index >= 0 && index < relations.Count)
521 return (DataRelation)relations[index];
523 throw ExceptionBuilder.RelationOutOfRange(index);
527 public override DataRelation this[string name] {
529 int index = InternalIndexOf(name);
531 throw ExceptionBuilder.CaseInsensitiveNameConflict(name);
533 return (index < 0) ? null : (DataRelation)List[index];
537 internal event CollectionChangeEventHandler RelationPropertyChanged {
539 onRelationPropertyChangedDelegate += value;
542 onRelationPropertyChangedDelegate -= value;
546 internal void OnRelationPropertyChanged(CollectionChangeEventArgs ccevent) {
547 if (!fParentCollection) {
548 table.UpdatePropertyDescriptorCollectionCache();
550 if (onRelationPropertyChangedDelegate != null) {
551 onRelationPropertyChangedDelegate(this, ccevent);
555 private void AddCache(DataRelation relation) {
556 relations.Add(relation);
557 if (!fParentCollection) {
558 table.UpdatePropertyDescriptorCollectionCache();
562 protected override void AddCore(DataRelation relation) {
563 if (fParentCollection) {
564 if (relation.ChildTable != table)
565 throw ExceptionBuilder.ChildTableMismatch();
568 if (relation.ParentTable != table)
569 throw ExceptionBuilder.ParentTableMismatch();
572 // base.AddCore(relation); // Will be called from DataSet.Relations.AddCore
573 GetDataSet().Relations.Add(relation);
577 public override bool CanRemove(DataRelation relation) {
578 if (!base.CanRemove(relation))
581 if (fParentCollection) {
582 if (relation.ChildTable != table)
586 if (relation.ParentTable != table)
593 private void RemoveCache(DataRelation relation) {
594 for (int i = 0; i < relations.Count; i++) {
595 if (relation == relations[i]) {
596 relations.RemoveAt(i);
597 if (!fParentCollection) {
598 table.UpdatePropertyDescriptorCollectionCache();
603 throw ExceptionBuilder.RelationDoesNotExist();
606 protected override void RemoveCore(DataRelation relation) {
607 if (fParentCollection) {
608 if (relation.ChildTable != table)
609 throw ExceptionBuilder.ChildTableMismatch();
612 if (relation.ParentTable != table)
613 throw ExceptionBuilder.ParentTableMismatch();
616 // base.RemoveCore(relation); // Will be called from DataSet.Relations.RemoveCore
617 GetDataSet().Relations.Remove(relation);
618 RemoveCache(relation);
622 internal sealed class DataSetRelationCollection : DataRelationCollection {
624 private readonly DataSet dataSet;
625 private readonly ArrayList relations;
626 private DataRelation[] delayLoadingRelations = null;
628 internal DataSetRelationCollection(DataSet dataSet) {
630 throw ExceptionBuilder.RelationDataSetNull();
631 this.dataSet = dataSet;
632 relations = new ArrayList();
635 protected override ArrayList List {
641 public override void AddRange(DataRelation[] relations) {
642 if (dataSet.fInitInProgress) {
643 delayLoadingRelations = relations;
647 if (relations != null) {
648 foreach(DataRelation relation in relations) {
649 if (relation != null) {
656 public override void Clear() {
658 if (dataSet.fInitInProgress && delayLoadingRelations != null) {
659 delayLoadingRelations = null;
663 protected override DataSet GetDataSet() {
667 public override DataRelation this[int index] {
669 if (index >= 0 && index < relations.Count)
670 return (DataRelation)relations[index];
672 throw ExceptionBuilder.RelationOutOfRange(index);
676 public override DataRelation this[string name] {
678 int index = InternalIndexOf(name);
680 throw ExceptionBuilder.CaseInsensitiveNameConflict(name);
682 return (index < 0) ? null : (DataRelation)List[index];
686 protected override void AddCore(DataRelation relation) {
687 base.AddCore(relation);
688 if (relation.ChildTable.DataSet != dataSet || relation.ParentTable.DataSet != dataSet)
689 throw ExceptionBuilder.ForeignRelation();
691 relation.CheckState();
692 if(relation.Nested) {
693 relation.CheckNestedRelations();
696 if (relation.relationName.Length == 0)
697 relation.relationName = AssignName();
699 RegisterName(relation.relationName);
701 DataKey childKey = relation.ChildKey;
703 for (int i = 0; i < relations.Count; i++) {
704 if (childKey.ColumnsEqual(((DataRelation)relations[i]).ChildKey)) {
705 if (relation.ParentKey.ColumnsEqual(((DataRelation)relations[i]).ParentKey))
706 throw ExceptionBuilder.RelationAlreadyExists();
710 relations.Add(relation);
711 ((DataRelationCollection.DataTableRelationCollection)(relation.ParentTable.ChildRelations)).Add(relation); // Caching in ParentTable -> ChildRelations
712 ((DataRelationCollection.DataTableRelationCollection)(relation.ChildTable.ParentRelations)).Add(relation); // Caching in ChildTable -> ParentRelations
714 relation.SetDataSet(dataSet);
715 relation.ChildKey.GetSortIndex().AddRef();
716 if (relation.Nested) {
717 relation.ChildTable.CacheNestedParent();
720 ForeignKeyConstraint foreignKey = relation.ChildTable.Constraints.FindForeignKeyConstraint(relation.ParentColumnsReference, relation.ChildColumnsReference);
721 if (relation.createConstraints) {
722 if (foreignKey == null) {
723 relation.ChildTable.Constraints.Add(foreignKey = new ForeignKeyConstraint(relation.ParentColumnsReference, relation.ChildColumnsReference));
725 // try to name the fk constraint the same as the parent relation:
727 foreignKey.ConstraintName = relation.RelationName;
729 catch (Exception e) {
731 if (!Common.ADP.IsCatchableExceptionType(e)) {
734 ExceptionBuilder.TraceExceptionWithoutRethrow(e);
735 // ignore the exception
739 UniqueConstraint key = relation.ParentTable.Constraints.FindKeyConstraint(relation.ParentColumnsReference);
740 relation.SetParentKeyConstraint(key);
741 relation.SetChildKeyConstraint(foreignKey);
744 protected override void RemoveCore(DataRelation relation) {
745 base.RemoveCore(relation);
747 dataSet.OnRemoveRelationHack(relation);
749 relation.SetDataSet(null);
750 relation.ChildKey.GetSortIndex().RemoveRef();
751 if (relation.Nested) {
752 relation.ChildTable.CacheNestedParent();
755 for (int i = 0; i < relations.Count; i++) {
756 if (relation == relations[i]) {
757 relations.RemoveAt(i);
758 ((DataRelationCollection.DataTableRelationCollection)(relation.ParentTable.ChildRelations)).Remove(relation); // Remove Cache from ParentTable -> ChildRelations
759 ((DataRelationCollection.DataTableRelationCollection)(relation.ChildTable.ParentRelations)).Remove(relation); // Removing Cache from ChildTable -> ParentRelations
761 relation.ChildTable.CacheNestedParent();
763 UnregisterName(relation.RelationName);
765 relation.SetParentKeyConstraint(null);
766 relation.SetChildKeyConstraint(null);
771 throw ExceptionBuilder.RelationDoesNotExist();
774 internal void FinishInitRelations() {
775 if (delayLoadingRelations == null)
780 DataColumn[] parents, childs;
781 for (int i = 0; i < delayLoadingRelations.Length; i++) {
782 rel = delayLoadingRelations[i];
783 if (rel.parentColumnNames == null || rel.childColumnNames == null) {
788 colCount = rel.parentColumnNames.Length;
789 parents = new DataColumn[colCount];
790 childs = new DataColumn[colCount];
792 for (int j = 0; j < colCount; j++) {
793 if (rel.parentTableNamespace == null)
794 parents[j] = dataSet.Tables[rel.parentTableName].Columns[rel.parentColumnNames[j]];
796 parents[j] = dataSet.Tables[rel.parentTableName, rel.parentTableNamespace].Columns[rel.parentColumnNames[j]];
798 if (rel.childTableNamespace == null)
799 childs[j] = dataSet.Tables[rel.childTableName].Columns[rel.childColumnNames[j]];
801 childs[j] = dataSet.Tables[rel.childTableName, rel.childTableNamespace].Columns[rel.childColumnNames[j]];
804 DataRelation newRelation = new DataRelation(rel.relationName, parents, childs, false);
805 newRelation.Nested = rel.nested;
806 this.Add(newRelation);
809 delayLoadingRelations = null;