2 // System.Data.ConstraintCollection.cs
5 // Franklin Wise <gracenote@earthlink.net>
8 // (C) Ximian, Inc. 2002
9 // (C) 2002 Franklin Wise
10 // (C) 2002 Daniel Morgan
14 using System.Collections;
15 using System.ComponentModel;
17 namespace System.Data {
20 internal delegate void DelegateValidateRemoveConstraint(ConstraintCollection sender, Constraint constraintToRemove, ref bool fail,ref string failReason);
23 /// hold collection of constraints for data table
25 [DefaultEvent ("CollectionChanged")]
27 public class ConstraintCollection : InternalDataCollectionBase
29 //private bool beginInit = false;
31 public event CollectionChangeEventHandler CollectionChanged;
32 internal event DelegateValidateRemoveConstraint ValidateRemoveConstraint;
34 //Don't allow public instantiation
35 //Will be instantianted from DataTable
36 internal ConstraintCollection(){}
38 public virtual Constraint this[string name] {
40 //If the name is not found we just return null
41 int index = IndexOf(name); //case insensitive
42 if (-1 == index) return null;
47 public virtual Constraint this[int index] {
49 if (index < 0 || index >= List.Count)
50 throw new IndexOutOfRangeException();
51 return (Constraint)List[index];
55 private void _handleBeforeConstraintNameChange(object sender, string newName)
58 if (newName == null || newName == "")
59 throw new ArgumentException("ConstraintName cannot be set to null or empty " +
60 " after it has been added to a ConstraintCollection.");
62 if (_isDuplicateConstraintName(newName,(Constraint)sender))
63 throw new DuplicateNameException("Constraint name already exists.");
66 private bool _isDuplicateConstraintName(string constraintName, Constraint excludeFromComparison)
68 string cmpr = constraintName.ToUpper();
69 foreach (Constraint cst in List)
71 //Case insensitive comparision
72 if ( cmpr.CompareTo(cst.ConstraintName.ToUpper()) == 0 &&
73 cst != excludeFromComparison)
82 //finds an open name slot of ConstraintXX
83 //where XX is a number
84 private string _createNewConstraintName()
86 bool loopAgain = false;
92 foreach (Constraint cst in List)
95 if (cst.ConstraintName.ToUpper().CompareTo("CONSTRAINT" +
96 index.ToString()) == 0 )
104 return "Constraint" + index.ToString();
109 // Overloaded Add method (5 of them)
110 // to add Constraint object to the collection
112 public void Add(Constraint constraint)
115 if (null == constraint) throw new ArgumentNullException("Can not add null.");
117 //check constraint membership
118 //can't already exist in this collection or any other
119 if (this == constraint.ConstraintCollection)
120 throw new ArgumentException("Constraint already belongs to this collection.");
121 if (null != constraint.ConstraintCollection)
122 throw new ArgumentException("Constraint already belongs to another collection.");
124 //check for duplicate name
125 if (_isDuplicateConstraintName(constraint.ConstraintName,null) )
126 throw new DuplicateNameException("Constraint name already exists.");
128 //Allow constraint to run validation rules and setup
129 constraint.AddToConstraintCollectionSetup(this); //may throw if it can't setup
131 //Run Constraint to check existing data in table
132 constraint.AssertConstraint();
134 //if name is null or empty give it a name
135 if (constraint.ConstraintName == null ||
136 constraint.ConstraintName == "" )
138 constraint.ConstraintName = _createNewConstraintName();
141 //Add event handler for ConstraintName change
142 constraint.BeforeConstraintNameChange += new DelegateConstraintNameChange(
143 _handleBeforeConstraintNameChange);
145 constraint.ConstraintCollection = this;
146 List.Add(constraint);
148 if (constraint is UniqueConstraint)
149 ((UniqueConstraint)constraint).UpdatePrimaryKey();
151 OnCollectionChanged( new CollectionChangeEventArgs( CollectionChangeAction.Add, this) );
156 public virtual Constraint Add(string name, DataColumn column, bool primaryKey)
159 UniqueConstraint uc = new UniqueConstraint(name, column, primaryKey);
165 public virtual Constraint Add(string name, DataColumn primaryKeyColumn,
166 DataColumn foreignKeyColumn)
168 ForeignKeyConstraint fc = new ForeignKeyConstraint(name, primaryKeyColumn,
175 public virtual Constraint Add(string name, DataColumn[] columns, bool primaryKey)
177 UniqueConstraint uc = new UniqueConstraint(name, columns, primaryKey);
183 public virtual Constraint Add(string name, DataColumn[] primaryKeyColumns,
184 DataColumn[] foreignKeyColumns)
186 ForeignKeyConstraint fc = new ForeignKeyConstraint(name, primaryKeyColumns,
194 public void AddRange(Constraint[] constraints) {
196 throw new NotImplementedException ();
199 public bool CanRemove(Constraint constraint)
202 //Rule A UniqueConstraint can't be removed if there is
203 //a foreign key relationship to that column
206 //LAMESPEC: MSFT implementation throws and exception here
207 //spec says nothing about this
208 if (null == constraint) throw new ArgumentNullException("Constraint can't be null.");
210 //LAMESPEC: spec says return false (which makes sense) and throw exception for False case (?).
211 //TODO: I may want to change how this is done
212 //maybe put a CanRemove on the Constraint class
213 //and have the Constraint fire this event
215 //discover if there is a related ForeignKey
216 string failReason ="";
217 return _canRemoveConstraint(constraint, ref failReason);
225 //CanRemove? See Lamespec below.
227 //the Constraints have a reference to us
228 //and we listen to name change events
229 //we should remove these before clearing
230 foreach (Constraint con in List)
232 con.ConstraintCollection = null;
233 con.BeforeConstraintNameChange -= new DelegateConstraintNameChange(
234 _handleBeforeConstraintNameChange);
237 //LAMESPEC: MSFT implementation allows this
238 //even when a ForeignKeyConstraint exist for a UniqueConstraint
239 //thus violating the CanRemove logic
240 List.Clear(); //Will violate CanRemove rule
241 OnCollectionChanged( new CollectionChangeEventArgs(CollectionChangeAction.Refresh, this) );
244 public bool Contains(string name)
246 return (-1 != IndexOf(name));
249 public int IndexOf(Constraint constraint)
251 return List.IndexOf(constraint);
254 public virtual int IndexOf(string constraintName)
256 //LAMESPEC: Spec doesn't say case insensitive
257 //it should to be consistant with the other
258 //case insensitive comparisons in this class
261 foreach (Constraint con in List)
263 if (constraintName.ToUpper().CompareTo( con.ConstraintName.ToUpper() ) == 0)
270 return -1; //not found
273 public void Remove(Constraint constraint) {
274 //LAMESPEC: spec doesn't document the ArgumentException the
275 //will be thrown if the CanRemove rule is violated
277 //LAMESPEC: spec says an exception will be thrown
278 //if the element is not in the collection. The implementation
279 //doesn't throw an exception. ArrayList.Remove doesn't throw if the
280 //element doesn't exist
281 //ALSO the overloaded remove in the spec doesn't say it throws any exceptions
284 if (null == constraint) throw new ArgumentNullException();
286 string failReason = "";
287 if (! _canRemoveConstraint(constraint, ref failReason) )
289 if (failReason != null || failReason != "")
290 throw new ArgumentException(failReason);
292 throw new ArgumentException("Can't remove constraint.");
295 constraint.RemoveFromConstraintCollectionCleanup(this);
296 List.Remove(constraint);
297 OnCollectionChanged( new CollectionChangeEventArgs(CollectionChangeAction.Remove,this));
300 public void Remove(string name)
302 //if doesn't exist fail quietly
303 int index = IndexOf(name);
304 if (-1 == index) return;
309 public void RemoveAt(int index)
311 if (index < 0 || index + 1 > List.Count)
312 throw new IndexOutOfRangeException("Index out of range, index = "
313 + index.ToString() + ".");
315 this[index].RemoveFromConstraintCollectionCleanup(this);
316 List.RemoveAt(index);
317 OnCollectionChanged( new CollectionChangeEventArgs(CollectionChangeAction.Remove,this));
320 protected override ArrayList List {
326 protected virtual void OnCollectionChanged( CollectionChangeEventArgs ccevent)
328 if (null != CollectionChanged)
330 CollectionChanged(this, ccevent);
334 private bool _canRemoveConstraint(Constraint constraint, ref string failReason )
338 if (null != ValidateRemoveConstraint)
340 ValidateRemoveConstraint(this, constraint, ref cancel, ref tmp);