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;
33 private DataTable table;
34 //Don't allow public instantiation
35 //Will be instantianted from DataTable
36 internal ConstraintCollection(DataTable table){
40 internal DataTable Table{
46 public virtual Constraint this[string name] {
48 //If the name is not found we just return null
49 int index = IndexOf(name); //case insensitive
50 if (-1 == index) return null;
55 public virtual Constraint this[int index] {
57 if (index < 0 || index >= List.Count)
58 throw new IndexOutOfRangeException();
59 return (Constraint)List[index];
63 private void _handleBeforeConstraintNameChange(object sender, string newName)
66 if (newName == null || newName == "")
67 throw new ArgumentException("ConstraintName cannot be set to null or empty " +
68 " after it has been added to a ConstraintCollection.");
70 if (_isDuplicateConstraintName(newName,(Constraint)sender))
71 throw new DuplicateNameException("Constraint name already exists.");
74 private bool _isDuplicateConstraintName(string constraintName, Constraint excludeFromComparison)
76 string cmpr = constraintName.ToUpper();
77 foreach (Constraint cst in List)
79 //Case insensitive comparision
80 if ( cmpr.CompareTo(cst.ConstraintName.ToUpper()) == 0 &&
81 cst != excludeFromComparison)
90 //finds an open name slot of ConstraintXX
91 //where XX is a number
92 private string _createNewConstraintName()
94 bool loopAgain = false;
100 foreach (Constraint cst in List)
103 if (cst.ConstraintName.ToUpper().CompareTo("CONSTRAINT" +
104 index.ToString()) == 0 )
112 return "Constraint" + index.ToString();
117 // Overloaded Add method (5 of them)
118 // to add Constraint object to the collection
120 public void Add(Constraint constraint)
123 if (null == constraint) throw new ArgumentNullException("Can not add null.");
125 //check constraint membership
126 //can't already exist in this collection or any other
127 if (this == constraint.ConstraintCollection)
128 throw new ArgumentException("Constraint already belongs to this collection.");
129 if (null != constraint.ConstraintCollection)
130 throw new ArgumentException("Constraint already belongs to another collection.");
132 //check for duplicate name
133 if (_isDuplicateConstraintName(constraint.ConstraintName,null) )
134 throw new DuplicateNameException("Constraint name already exists.");
136 //Allow constraint to run validation rules and setup
137 constraint.AddToConstraintCollectionSetup(this); //may throw if it can't setup
139 //Run Constraint to check existing data in table
140 constraint.AssertConstraint();
142 //if name is null or empty give it a name
143 if (constraint.ConstraintName == null ||
144 constraint.ConstraintName == "" )
146 constraint.ConstraintName = _createNewConstraintName();
149 //Add event handler for ConstraintName change
150 constraint.BeforeConstraintNameChange += new DelegateConstraintNameChange(
151 _handleBeforeConstraintNameChange);
153 constraint.ConstraintCollection = this;
154 List.Add(constraint);
156 if (constraint is UniqueConstraint)
157 ((UniqueConstraint)constraint).UpdatePrimaryKey();
159 OnCollectionChanged( new CollectionChangeEventArgs( CollectionChangeAction.Add, this) );
164 public virtual Constraint Add(string name, DataColumn column, bool primaryKey)
167 UniqueConstraint uc = new UniqueConstraint(name, column, primaryKey);
173 public virtual Constraint Add(string name, DataColumn primaryKeyColumn,
174 DataColumn foreignKeyColumn)
176 ForeignKeyConstraint fc = new ForeignKeyConstraint(name, primaryKeyColumn,
183 public virtual Constraint Add(string name, DataColumn[] columns, bool primaryKey)
185 UniqueConstraint uc = new UniqueConstraint(name, columns, primaryKey);
191 public virtual Constraint Add(string name, DataColumn[] primaryKeyColumns,
192 DataColumn[] foreignKeyColumns)
194 ForeignKeyConstraint fc = new ForeignKeyConstraint(name, primaryKeyColumns,
202 public void AddRange(Constraint[] constraints) {
204 throw new NotImplementedException ();
207 public bool CanRemove(Constraint constraint)
210 //Rule A UniqueConstraint can't be removed if there is
211 //a foreign key relationship to that column
214 //LAMESPEC: MSFT implementation throws and exception here
215 //spec says nothing about this
216 if (null == constraint) throw new ArgumentNullException("Constraint can't be null.");
218 //LAMESPEC: spec says return false (which makes sense) and throw exception for False case (?).
219 //TODO: I may want to change how this is done
220 //maybe put a CanRemove on the Constraint class
221 //and have the Constraint fire this event
223 //discover if there is a related ForeignKey
224 string failReason ="";
225 return _canRemoveConstraint(constraint, ref failReason);
233 //CanRemove? See Lamespec below.
235 //the Constraints have a reference to us
236 //and we listen to name change events
237 //we should remove these before clearing
238 foreach (Constraint con in List)
240 con.ConstraintCollection = null;
241 con.BeforeConstraintNameChange -= new DelegateConstraintNameChange(
242 _handleBeforeConstraintNameChange);
245 //LAMESPEC: MSFT implementation allows this
246 //even when a ForeignKeyConstraint exist for a UniqueConstraint
247 //thus violating the CanRemove logic
248 List.Clear(); //Will violate CanRemove rule
249 OnCollectionChanged( new CollectionChangeEventArgs(CollectionChangeAction.Refresh, this) );
252 public bool Contains(string name)
254 return (-1 != IndexOf(name));
257 public int IndexOf(Constraint constraint)
259 return List.IndexOf(constraint);
262 public virtual int IndexOf(string constraintName)
264 //LAMESPEC: Spec doesn't say case insensitive
265 //it should to be consistant with the other
266 //case insensitive comparisons in this class
269 foreach (Constraint con in List)
271 if (constraintName.ToUpper().CompareTo( con.ConstraintName.ToUpper() ) == 0)
278 return -1; //not found
281 public void Remove(Constraint constraint) {
282 //LAMESPEC: spec doesn't document the ArgumentException the
283 //will be thrown if the CanRemove rule is violated
285 //LAMESPEC: spec says an exception will be thrown
286 //if the element is not in the collection. The implementation
287 //doesn't throw an exception. ArrayList.Remove doesn't throw if the
288 //element doesn't exist
289 //ALSO the overloaded remove in the spec doesn't say it throws any exceptions
292 if (null == constraint) throw new ArgumentNullException();
294 string failReason = "";
295 if (! _canRemoveConstraint(constraint, ref failReason) )
297 if (failReason != null || failReason != "")
298 throw new ArgumentException(failReason);
300 throw new ArgumentException("Can't remove constraint.");
303 constraint.RemoveFromConstraintCollectionCleanup(this);
304 List.Remove(constraint);
305 OnCollectionChanged( new CollectionChangeEventArgs(CollectionChangeAction.Remove,this));
308 public void Remove(string name)
310 //if doesn't exist fail quietly
311 int index = IndexOf(name);
312 if (-1 == index) return;
317 public void RemoveAt(int index)
319 if (index < 0 || index + 1 > List.Count)
320 throw new IndexOutOfRangeException("Index out of range, index = "
321 + index.ToString() + ".");
323 this[index].RemoveFromConstraintCollectionCleanup(this);
324 List.RemoveAt(index);
325 OnCollectionChanged( new CollectionChangeEventArgs(CollectionChangeAction.Remove,this));
328 protected override ArrayList List {
334 protected virtual void OnCollectionChanged( CollectionChangeEventArgs ccevent)
336 if (null != CollectionChanged)
338 CollectionChanged(this, ccevent);
342 private bool _canRemoveConstraint(Constraint constraint, ref string failReason )
346 if (null != ValidateRemoveConstraint)
348 ValidateRemoveConstraint(this, constraint, ref cancel, ref tmp);