/// <summary> /// /// </summary> private SqlContext() { try { DataSet = new System.Data.DataSet(); // Créer la table Person dans le DataSet PersonDataAdapter = CreateSqlDataAdapter(DataSet, "Person"); // Créer la table Operation dans le DataSet OperationDataAdapter = CreateSqlDataAdapter(DataSet, "Operation"); // Créer la relation Person/Operation dans le DataSet DataColumn personIdDataColumn = DataSet.Tables["Person"].Columns["ID"]; DataColumn operationIdDataColumn = DataSet.Tables["Operation"].Columns["Person_ID"]; DataRelation personOperationDataRelation = new DataRelation("Person_Operation", personIdDataColumn, operationIdDataColumn); DataSet.Relations.Add(personOperationDataRelation); // Modifier l'action du contriante DeleteRule à None ConstraintCollection constraintCollection = DataSet.Tables["Operation"].Constraints; IEnumerator enumerable = constraintCollection.GetEnumerator(); enumerable.MoveNext(); ForeignKeyConstraint foreignKeyConstraint = (ForeignKeyConstraint)enumerable.Current; foreignKeyConstraint.DeleteRule = Rule.None; } catch (Exception) { throw; } }
public List <T> Sort(List <T> inputList, ConstraintCollection constraints, params object[] conditions) { if (Shaked) { inputList = MiMFa_CollectionService.Shake(inputList); } List <KeyValuePair <T, InferenceCollection> > lold = new List <KeyValuePair <T, InferenceCollection> >(); for (int i = 0; i < inputList.Count; i++) { lold.Add(new KeyValuePair <T, InferenceCollection>(inputList[i], new InferenceCollection())); } constraints.Sort(); Constraint constraint = null; Type t = inputList.First().GetType(); FieldInfo[] fi = null; PropertyInfo[] pi = null; if (SendT) { for (int index = 0; index < constraints.Count; index++) { for (int i = 0; i < inputList.Count; i++) { lold[i].Value.Add(constraints[index].Solver(inputList[i], conditions)); } } } else { for (int index = 0; index < constraints.Count; index++) { constraint = constraints[index]; fi = MiMFa_GetDetail.GetFields(inputList.First(), constraint.Name, false); if (fi.Length > 0) { for (int i = 0; i < inputList.Count; i++) { lold[i].Value.Add(constraint.Solver(fi.First().GetValue(inputList[i]), conditions)); } } else { pi = MiMFa_GetDetail.GetProperties(inputList.First(), constraint.Name, false); if (pi.Length > 0) { for (int i = 0; i < inputList.Count; i++) { lold[i].Value.Add(constraint.Solver(pi.First().GetValue(inputList[i]), conditions)); } } } } } lold = Sort(lold); return(AllowanceMember(lold)); }
public void Add() { ConstraintCollection col = _table.Constraints; col.Add(_constraint1); col.Add(_constraint2); Assert.Equal(2, col.Count); }
public void Add() { ConstraintCollection col = _table.Constraints; col.Add(_constraint1); col.Add(_constraint2); Assert.That(col.Count, Is.EqualTo(2), "Count doesn't equal added."); }
public void Add() { ConstraintCollection col = _table.Constraints; col.Add(_constraint1); col.Add(_constraint2); AssertEquals("Count doesn't equal added.", 2, col.Count); }
public void AddExceptions() { ConstraintCollection col = _table.Constraints; Assert.Throws <ArgumentNullException>(() => col.Add(null)); _constraint1.ConstraintName = "Dog"; col.Add(_constraint1); Assert.Throws <DataException>(() => col.Add(_constraint1)); }
// <Snippet1> private void RemoveConstraint(ConstraintCollection constraints, Constraint constraint) { if (constraints.Contains(constraint.ConstraintName)) { if (constraints.CanRemove(constraint)) { constraints.Remove(constraint.ConstraintName); } } }
/// <summary> /// Initializes new instance of <see cref="IdentificationModel"/> /// </summary> public IdentificationModel() { IdentificationExperiments = new IdentificationExperimentCollection(); RealExperiments = new ExperimentCollection(); IdentificationParameters = new ParameterCollection(); OptimizationParameters = new ParameterCollection(); Criteria = new CriterionCollection(); FunctionalConstraints = new ConstraintCollection(); Properties = new PropertyCollection(); }
public override void Setup(Game game, Supply supply) { base.Setup(game, supply); IList <Card> availableCards = null; try { if (game.Settings.Preset != null) { availableCards = game.Settings.Preset.CardCards[game.Settings.Preset.Cards.First(c => c.CardType == typeof(BlackMarket))]; // Shuffle the preset cards -- these should definitely not be set up in a known order Utilities.Shuffler.Shuffle(availableCards); } else { int cardsToUse = 25; //Boolean errorOnNotEnoughCards = true; Boolean shouldUseGameConstraints = true; ConstraintCollection bmConstraints = new ConstraintCollection(); if (game.Settings.CardSettings.ContainsKey("Black Market")) { CardsSettings bmSettings = game.Settings.CardSettings["Black Market"]; cardsToUse = (int)bmSettings.CardSettingCollection[typeof(BlackMarket.BlackMarket_NumberOfCards)].Value; //errorOnNotEnoughCards = (Boolean)bmSettings.CardSettingCollection[typeof(BlackMarket.BlackMarket_ErrorOnNotEnoughCards)].Value; shouldUseGameConstraints = (Boolean)bmSettings.CardSettingCollection[typeof(BlackMarket.BlackMarket_UseGameConstraints)].Value; bmConstraints = (ConstraintCollection)bmSettings.CardSettingCollection[typeof(BlackMarket.BlackMarket_Constraints)].Value; } // need to set up a supply pile for Black Market; randomly pick an unused supply card and add it to the pile until we have the requisite number of cards availableCards = game.CardsAvailable; if (shouldUseGameConstraints) { // Skip all "Must Use" constraints ConstraintCollection constraints = new ConstraintCollection(game.Settings.Constraints.Where(c => c.ConstraintType != ConstraintType.CardMustUse)); availableCards = constraints.SelectCards(availableCards, cardsToUse); } else { availableCards = bmConstraints.SelectCards(availableCards, cardsToUse); } } } catch (DominionBase.Cards.ConstraintException ce) { throw new BlackMarketConstraintException(String.Format("Problem setting up Black Market constraints: {0}", ce.Message)); } foreach (Card cardToUse in availableCards) { game.CardsAvailable.Remove(cardToUse); supply.AddTo(cardToUse); } }
public ScopeConstraintProvider(string scope) { this.constraints = ConstraintCollection.CreateEmpty(); if (!scope.Equals("WorldWide", StringComparison.CurrentCultureIgnoreCase)) { this.constraints.Add(VariantType.Organization, "Microsoft"); if (!scope.Equals("Microsoft", StringComparison.CurrentCultureIgnoreCase)) { this.constraints.Add(scope, true); } } }
public void AdditionToConstraintCollectionTest() { DataTable myTable = new DataTable("myTable"); DataColumn idCol = new DataColumn("id", typeof(int)); idCol.Unique = true; myTable.Columns.Add(idCol); ConstraintCollection cc = myTable.Constraints; //cc just contains a single UniqueConstraint object. UniqueConstraint uc = cc[0] as UniqueConstraint; Assert.AreEqual("id", uc.Columns[0].ColumnName); }
public override void Setup(Game game, Supply supply) { base.Setup(game, supply); Card baneCard = null; try { if (game.Settings.Preset != null) { baneCard = game.Settings.Preset.CardCards[game.Settings.Preset.Cards.First(c => c.CardType == this.CardType)].ElementAt(0); } else { IList <Card> availableBaneCards = null; Boolean shouldUseGameConstraints = true; ConstraintCollection ywConstraints = new ConstraintCollection(); if (game.Settings.CardSettings.ContainsKey(this.Name)) { CardsSettings ywSettings = game.Settings.CardSettings[this.Name]; shouldUseGameConstraints = (Boolean)ywSettings.CardSettingCollection[typeof(YoungWitch_UseGameConstraints)].Value; ywConstraints = (ConstraintCollection)ywSettings.CardSettingCollection[typeof(YoungWitch_Constraints)].Value; } // need to setup a bane supply pile here; randomly pick an unused supply card type of cost $2 or $3 from // the Kingdom cards, create a new supply pile of it, and mark it with a Bane token availableBaneCards = game.CardsAvailable.Where(c => c.BaseCost == new Cost(2) || c.BaseCost == new Cost(3)).ToList(); if (shouldUseGameConstraints) { // Skip all "Must Use" constraints ConstraintCollection constraints = new ConstraintCollection(game.Settings.Constraints.Where(c => c.ConstraintType != ConstraintType.CardMustUse)); availableBaneCards = constraints.SelectCards(availableBaneCards, 1); } else { availableBaneCards = ywConstraints.SelectCards(availableBaneCards, 1); } baneCard = availableBaneCards[0]; } } catch (DominionBase.Cards.ConstraintException ce) { throw new YoungWitchConstraintException(String.Format("Problem setting up Young Witch constraints: {0}", ce.Message)); } game.CardsAvailable.Remove(baneCard); game.Table.AddKingdomSupply(game.Players, baneCard.CardType); game.Table.Supplies[baneCard].Setup(); game.Table.Supplies[baneCard].SnapshotSetup(); game.Table.Supplies[baneCard].AddToken(new BaneToken()); }
private void ConstraintCollection_IsSynchronized1() { DataTable dt = GHTUtils.DataProvider.CreateUniqueConstraint(); Compare(dt.Constraints.IsSynchronized, false); ConstraintCollection col = (ConstraintCollection)dt.Constraints.SyncRoot; // lock(dt.Constraints.SyncRoot) // { // Compare(col.IsSynchronized,true); //} }
[Test] public void IsSynchronized() { DataTable dt = DataProvider.CreateUniqueConstraint(); Assert.AreEqual(false, dt.Constraints.IsSynchronized, "CN25"); ConstraintCollection col = (ConstraintCollection)dt.Constraints.SyncRoot; // lock(dt.Constraints.SyncRoot) // { // Assert.AreEqual(true, col.IsSynchronized, "CN26"); //} }
public void AddExceptions() { ConstraintCollection col = _table.Constraints; //null try { col.Add(null); Assert.Fail("B1: Failed to throw ArgumentNullException."); } catch (ArgumentNullException) { } catch (AssertionException exc) { throw exc; } catch { Assert.Fail("A1: Wrong exception type"); } //duplicate name try { _constraint1.ConstraintName = "Dog"; _constraint2.ConstraintName = "dog"; //case insensitive col.Add(_constraint1); col.Add(_constraint2); col.Remove(_constraint2); // only for !1.0 col.Remove(_constraint1); } catch (AssertionException exc) { throw exc; } /* Don't use such catch. They cover our eyes from the exact exception location. * catch (Exception exc) * { * Assert.Fail("A2: Wrong exception type. " + exc.ToString()); * } */ //Constraint Already exists try { col.Add(_constraint1); col.Remove(_constraint1); } catch (ArgumentException) { } catch (AssertionException exc) { throw exc; } catch { Assert.Fail("A3: Wrong exception type"); } }
internal static VariantConfigurationSnapshot GetSnapshot(ADRawEntry executingUser, IEnumerable <KeyValuePair <string, string> > additionalConstraints) { if (executingUser == null) { return(null); } VariantConfigurationSnapshot variantConfigurationSnapshot = null; MiniRecipient miniRecipient = new MiniRecipient(); try { try { miniRecipient[MiniRecipientSchema.UserPrincipalName] = executingUser[ADUserSchema.UserPrincipalName]; miniRecipient[ADObjectSchema.OrganizationId] = executingUser[ADObjectSchema.OrganizationId]; miniRecipient[MiniRecipientSchema.ExternalDirectoryObjectId] = executingUser[ADRecipientSchema.ExternalDirectoryObjectId]; miniRecipient[MiniRecipientSchema.Languages] = executingUser[ADOrgPersonSchema.Languages]; } catch (DataValidationException ex) { AuthZLogger.SafeAppendColumn(RpsAuthZMetadata.VariantConfigurationSnapshot, "DataValidationException", ex.Message); } ConstraintCollection constraintCollection = null; if (additionalConstraints != null) { constraintCollection = ConstraintCollection.CreateEmpty(); foreach (KeyValuePair <string, string> keyValuePair in additionalConstraints) { constraintCollection.Add(keyValuePair.Key, keyValuePair.Value); } } variantConfigurationSnapshot = VariantConfiguration.GetSnapshot(miniRecipient.GetContext(null), constraintCollection, null); AuthZLogger.SafeAppendColumn(RpsAuthZMetadata.VariantConfigurationSnapshot, "Flights", string.Join(" ", variantConfigurationSnapshot.Flights)); } catch (Exception ex2) { AuthZLogger.SafeAppendGenericError("VariantConfigurationSnapshot.Exception", ex2.Message, false); } finally { AuthZLogger.SafeAppendColumn(RpsAuthZMetadata.VariantConfigurationSnapshot, "User", executingUser[ADUserSchema.UserPrincipalName].ToString()); AuthZLogger.SafeAppendColumn(RpsAuthZMetadata.VariantConfigurationSnapshot, "Org", executingUser[ADObjectSchema.OrganizationId].ToString()); } return(variantConfigurationSnapshot); }
// System.Data.ConstraintCollection internal static ForeignKeyConstraint FindForeignKeyConstraint(ConstraintCollection lst, ForeignKeyConstraint fk) { int count = lst.Count; for (int i = 0; i < count; i++) { // name? if (string.Equals(((Constraint)lst[i]).ConstraintName, fk.ConstraintName, StringComparison.OrdinalIgnoreCase)) { return((ForeignKeyConstraint)lst[i]); } // columns? if (((Constraint)lst[i]).Equals(fk)) { return((ForeignKeyConstraint)lst[i]); } } return(null); }
// <Snippet1> private void RemoveConstraint( ConstraintCollection constraints, Constraint constraint) { try { if (constraints.Contains(constraint.ConstraintName)) { if (constraints.CanRemove(constraint)) { constraints.RemoveAt(constraints.IndexOf(constraint)); } } } catch (Exception e) { // Process exception and return. Console.WriteLine("Exception of type {0} occurred.", e.GetType()); } }
protected internal Viewport2D(FrameworkElement host, Plotter2D plotter) { hostElement = host; host.ClipToBounds = true; host.SizeChanged += OnHostElementSizeChanged; this.plotter = plotter; plotter.Children.CollectionChanged += OnPlotterChildrenChanged; constraints = new ConstraintCollection(this); constraints.Add(new MinimalSizeConstraint()); constraints.CollectionChanged += constraints_CollectionChanged; fitToViewConstraints = new ConstraintCollection(this); fitToViewConstraints.CollectionChanged += fitToViewConstraints_CollectionChanged; readonlyContentBoundsHosts = new ReadOnlyObservableCollection <DependencyObject>(contentBoundsHosts); UpdateVisible(); UpdateTransform(); }
protected internal Viewport2D(FrameworkElement host, Plotter2D plotter) { hostElement = host; host.ClipToBounds = true; host.SizeChanged += OnHostElementSizeChanged; this.plotter = plotter; plotter.Children.CollectionChanged += OnPlotterChildrenChanged; constraints = new ConstraintCollection(this); constraints.Add(new MinimalSizeConstraint()); constraints.CollectionChanged += constraints_CollectionChanged; fitToViewConstraints = new ConstraintCollection(this); fitToViewConstraints.CollectionChanged += fitToViewConstraints_CollectionChanged; readonlyContentBoundsHosts = new ReadOnlyObservableCollection<DependencyObject>(contentBoundsHosts); UpdateVisible(); UpdateTransform(); }
public static void displayConstraint(DataTable dataTable) { Console.WriteLine("[제약 조건]"); DataColumn[] pkDataColumns = dataTable.PrimaryKey; foreach (DataColumn dataColumn in pkDataColumns) { Console.WriteLine("Prymary Key"); Console.WriteLine("\t" + dataColumn.ColumnName); } ConstraintCollection constraintCollection = dataTable.Constraints; foreach (Constraint constraint in constraintCollection) { Console.WriteLine(constraint.GetType()); if (constraint is UniqueConstraint) { UniqueConstraint uniqueConstraint = (UniqueConstraint)constraint; DataColumn[] dataColumns = uniqueConstraint.Columns; foreach (DataColumn dataColumn in dataColumns) { Console.WriteLine("\t" + uniqueConstraint.ConstraintName + ":\t" + dataColumn.ColumnName); } } else if (constraint is ForeignKeyConstraint) { ForeignKeyConstraint foreignKeyConstraint = (ForeignKeyConstraint)constraint; DataColumn[] dataColumns = foreignKeyConstraint.Columns; foreach (DataColumn dataColumn in dataColumns) { Console.WriteLine("\t" + foreignKeyConstraint.ConstraintName + ":\t" + dataColumn.ColumnName); } } } }
private void InitClass() { this.columnComputerID = new DataColumn("ComputerID", typeof(int), null, MappingType.Element); base.Columns.Add(this.columnComputerID); this.columnName = new DataColumn("Name", typeof(string), null, MappingType.Element); base.Columns.Add(this.columnName); this.columnflags = new DataColumn("flags", typeof(int), null, MappingType.Element); base.Columns.Add(this.columnflags); this.columnFeatureFlags = new DataColumn("FeatureFlags", typeof(int), null, MappingType.Element); base.Columns.Add(this.columnFeatureFlags); ConstraintCollection constraints = base.Constraints; DataColumn[] dataColumnArray = new DataColumn[] { this.columnComputerID }; constraints.Add(new UniqueConstraint("Constraint1", dataColumnArray, true)); this.columnComputerID.AutoIncrement = true; this.columnComputerID.AutoIncrementSeed = (long)-1; this.columnComputerID.AutoIncrementStep = (long)-1; this.columnComputerID.AllowDBNull = false; this.columnComputerID.Unique = true; this.columnName.AllowDBNull = false; this.columnName.MaxLength = 50; this.columnflags.AllowDBNull = false; this.columnFeatureFlags.AllowDBNull = false; }
//-------------------------------------------------------------- /// <summary> /// Initializes a new instance of the <see cref="Simulation"/> class. /// </summary> public Simulation() { Settings = new SimulationSettings(); var collisionDetection = new CollisionDetection { CollisionFilter = new CollisionFilter(), FullContactSetPerFrame = true }; CollisionDomain = new CollisionDomain(collisionDetection); ConstraintSolver = new SequentialImpulseBasedSolver(this); Constraints = new ConstraintCollection(); Constraints.CollectionChanged += OnConstraintsChanged; ForceEffects = new ForceEffectCollection(); ForceEffects.CollectionChanged += OnForceEffectsChanged; RigidBodies = new RigidBodyCollection(); RigidBodies.CollectionChanged += OnRigidBodiesChanged; ContactConstraintsInternal = new List<ContactConstraint>(); IslandManager = new SimulationIslandManager(this); // Define the "World" as a rigid body. // - World is an imaginary body that is used to define the space of the simulation. // - The user can use World in constraints e.g. to anchor objects in the world. // - No contacts are computed for World. World = new RigidBody(new BoxShape(20000, 20000, 20000)) { CollisionResponseEnabled = false, CollisionObject = { Type = CollisionObjectType.Trigger }, MotionType = MotionType.Static, Name = "World", Simulation = this, }; // Remove "World" from the collision domain. CollisionDomain.CollisionObjects.Remove(World.CollisionObject); #if STOPWATCH Diagnostics = new SimulationDiagnostics(); #endif // Store delegate methods to avoid garbage when multithreading. _updateVelocityMethod = i => { var body = RigidBodies[i]; body.UpdateVelocity(_fixedTimeStep); }; _solveIslandMethod = SolveIsland; _updatePoseMethod = i => { var body = RigidBodies[i]; body.UpdatePose(_fixedTimeStep); }; _computeTimeOfImpactMethod = ComputeTimeOfImpact_Multithreaded; _moveToTimeOfImpactMethod = MoveToTimeOfImpact; }
protected virtual void InitializeconstraintDataLookUp() { ConstrainedDataLookup = new Dictionary<string, ConstraintCollection<RecWrapper>>(); foreach (var property in typeof(RecWrapper).GetProperties(BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.SetProperty | BindingFlags.Public)) { if (typeof(string).IsAssignableFrom(property.PropertyType)) { var collection = new ConstraintCollection<RecWrapper>(); collection.AddConstraint(new TextSizeConstraint<RecWrapper> { Size = MaxTextLength, Property = new TextProperty { PropertyInfo = property } }); ConstrainedDataLookup[property.Name] = collection; } } }
private void TableSettings_Load(object sender, EventArgs e) { try { if (currentBaseWindow != null) { if (currentBaseWindow.TypeOfWindow.Equals(FormDesignerConstants.DataPattern)) { if (currentBaseWindow.CurrentControl != null && currentBaseWindow.CurrentControl.Count == 1) { if (currentBaseWindow.CurrentControl[0] is EIBTable) { childRelations.Items.Clear(); parentRelations.Items.Clear(); uniqueKeyList.Items.Clear(); foreignKeyList.Items.Clear(); childRelations.Text = ""; parentRelations.Text = ""; uniqueKeyList.Text = ""; foreignKeyList.Text = ""; currentDataSet = currentBaseWindow.DatabaseDataSet; EIBTable eibTable = (EIBTable)currentBaseWindow.CurrentControl[0]; DataTable currentTable = currentDataSet.Tables[eibTable.tableName.Text]; ConstraintCollection consRelation = currentTable.Constraints; foreach (Constraint constraint in consRelation) { //remove constraint if (constraint is ForeignKeyConstraint) { ForeignKeyConstraint uniqueCS = (ForeignKeyConstraint)constraint; foreignKeyList.Items.Add(uniqueCS.ConstraintName); } } consRelation = currentTable.Constraints; foreach (Constraint constraint in consRelation) { //remove constraint if (constraint is UniqueConstraint) { UniqueConstraint uniqueCS = (UniqueConstraint)constraint; // Get the Columns as an array. uniqueKeyList.Items.Add(uniqueCS.ConstraintName); } } DataRelationCollection relationCOllection = null; relationCOllection = currentTable.ParentRelations; foreach (DataRelation relation in relationCOllection) { parentRelations.Items.Add(relation.RelationName); } relationCOllection = currentTable.ChildRelations; foreach (DataRelation relation in relationCOllection) { childRelations.Items.Add(relation.RelationName); } this.tableName.Text = currentTable.TableName; } } } } } catch (Exception ex) { errorLabel.Text = ex.Message; } }
public override void Setup(Game game, Supply supply) { base.Setup(game, supply); IList<Card> availableCards = null; try { if (game.Settings.Preset != null) { availableCards = game.Settings.Preset.CardCards[game.Settings.Preset.Cards.First(c => c.CardType == typeof(BlackMarket))]; // Shuffle the preset cards -- these should definitely not be set up in a known order Utilities.Shuffler.Shuffle(availableCards); } else { int cardsToUse = 25; //Boolean errorOnNotEnoughCards = true; Boolean shouldUseGameConstraints = true; ConstraintCollection bmConstraints = new ConstraintCollection(); if (game.Settings.CardSettings.ContainsKey("Black Market")) { CardsSettings bmSettings = game.Settings.CardSettings["Black Market"]; cardsToUse = (int)bmSettings.CardSettingCollection[typeof(BlackMarket.BlackMarket_NumberOfCards)].Value; //errorOnNotEnoughCards = (Boolean)bmSettings.CardSettingCollection[typeof(BlackMarket.BlackMarket_ErrorOnNotEnoughCards)].Value; shouldUseGameConstraints = (Boolean)bmSettings.CardSettingCollection[typeof(BlackMarket.BlackMarket_UseGameConstraints)].Value; bmConstraints = (ConstraintCollection)bmSettings.CardSettingCollection[typeof(BlackMarket.BlackMarket_Constraints)].Value; } // need to set up a supply pile for Black Market; randomly pick an unused supply card and add it to the pile until we have the requisite number of cards availableCards = game.CardsAvailable; if (shouldUseGameConstraints) { // Skip all "Must Use" constraints ConstraintCollection constraints = new ConstraintCollection(game.Settings.Constraints.Where(c => c.ConstraintType != ConstraintType.CardMustUse)); availableCards = constraints.SelectCards(availableCards, cardsToUse); } else availableCards = bmConstraints.SelectCards(availableCards, cardsToUse); } } catch (DominionBase.Cards.ConstraintException ce) { throw new BlackMarketConstraintException(String.Format("Problem setting up Black Market constraints: {0}", ce.Message)); } foreach (Card cardToUse in availableCards) { game.CardsAvailable.Remove(cardToUse); supply.AddTo(cardToUse); } }
public void Set(List <T> inputList, ConstraintCollection constraints) { InputList = inputList; Constraints = constraints; }
private object[] SetupSchemaWithKeyInfo(MissingMappingAction mappingAction, MissingSchemaAction schemaAction, bool gettingData, DataColumn parentChapterColumn, object chapterValue) { DbSchemaRow[] sortedSchemaRows = DbSchemaRow.GetSortedSchemaRows(this._schemaTable, this._dataReader.ReturnProviderSpecificTypes); if (sortedSchemaRows.Length == 0) { this._dataTable = null; return(null); } bool flag3 = ((this._dataTable.PrimaryKey.Length == 0) && ((((LoadOption)4) <= this._loadOption) || (this._dataTable.Rows.Count == 0))) || (0 == this._dataTable.Columns.Count); DataColumn[] rgcol = null; int len = 0; bool flag2 = true; string str3 = null; string str2 = null; bool flag6 = false; bool flag = false; int[] numArray = null; bool[] flagArray = null; int num3 = 0; object[] objArray = null; List <object> items = null; DataColumnCollection columnCollection = this._dataTable.Columns; try { for (int i = 0; i < sortedSchemaRows.Length; i++) { DbSchemaRow row = sortedSchemaRows[i]; int unsortedIndex = row.UnsortedIndex; bool flag5 = false; Type dataType = row.DataType; if (null == dataType) { dataType = this._dataReader.GetFieldType(i); } if (null == dataType) { throw ADP.MissingDataReaderFieldType(i); } if (typeof(IDataReader).IsAssignableFrom(dataType)) { if (flagArray == null) { flagArray = new bool[sortedSchemaRows.Length]; } flagArray[unsortedIndex] = flag5 = true; dataType = typeof(int); } else if (typeof(System.Data.SqlTypes.SqlXml).IsAssignableFrom(dataType)) { if (this._xmlMap == null) { this._xmlMap = new int[sortedSchemaRows.Length]; } this._xmlMap[i] = 1; } else if (typeof(XmlReader).IsAssignableFrom(dataType)) { dataType = typeof(string); if (this._xmlMap == null) { this._xmlMap = new int[sortedSchemaRows.Length]; } this._xmlMap[i] = 2; } DataColumn targetColumn = null; if (!row.IsHidden) { targetColumn = this._tableMapping.GetDataColumn(this._fieldNames[i], dataType, this._dataTable, mappingAction, schemaAction); } string baseTableName = row.BaseTableName; if (targetColumn == null) { if (numArray == null) { numArray = this.CreateIndexMap(sortedSchemaRows.Length, unsortedIndex); } numArray[unsortedIndex] = -1; if (row.IsKey && (flag6 || (row.BaseTableName == str3))) { flag3 = false; rgcol = null; } } else { if ((this._xmlMap != null) && (this._xmlMap[i] != 0)) { if (typeof(System.Data.SqlTypes.SqlXml) == targetColumn.DataType) { this._xmlMap[i] = 1; } else if (typeof(System.Xml.XmlDocument) == targetColumn.DataType) { this._xmlMap[i] = 2; } else { this._xmlMap[i] = 0; int num7 = 0; for (int j = 0; j < this._xmlMap.Length; j++) { num7 += this._xmlMap[j]; } if (num7 == 0) { this._xmlMap = null; } } } if (row.IsKey && (baseTableName != str3)) { if (str3 == null) { str3 = baseTableName; } else { flag6 = true; } } if (flag5) { if (targetColumn.Table != null) { if (!targetColumn.AutoIncrement) { throw ADP.FillChapterAutoIncrement(); } } else { targetColumn.AllowDBNull = false; targetColumn.AutoIncrement = true; targetColumn.ReadOnly = true; } } else { if ((!flag && (baseTableName != str2)) && !ADP.IsEmpty(baseTableName)) { if (str2 == null) { str2 = baseTableName; } else { flag = true; } } if (((LoadOption)4) <= this._loadOption) { if (row.IsAutoIncrement && DataColumn.IsAutoIncrementType(dataType)) { targetColumn.AutoIncrement = true; if (!row.AllowDBNull) { targetColumn.AllowDBNull = false; } } if (dataType == typeof(string)) { targetColumn.MaxLength = (row.Size > 0) ? row.Size : -1; } if (row.IsReadOnly) { targetColumn.ReadOnly = true; } if (!row.AllowDBNull && (!row.IsReadOnly || row.IsKey)) { targetColumn.AllowDBNull = false; } if ((row.IsUnique && !row.IsKey) && !dataType.IsArray) { targetColumn.Unique = true; if (!row.AllowDBNull) { targetColumn.AllowDBNull = false; } } } else if (targetColumn.Table == null) { targetColumn.AutoIncrement = row.IsAutoIncrement; targetColumn.AllowDBNull = row.AllowDBNull; targetColumn.ReadOnly = row.IsReadOnly; targetColumn.Unique = row.IsUnique; if ((dataType == typeof(string)) || (dataType == typeof(SqlString))) { targetColumn.MaxLength = row.Size; } } } if (targetColumn.Table == null) { if (((LoadOption)4) > this._loadOption) { this.AddAdditionalProperties(targetColumn, row.DataRow); } this.AddItemToAllowRollback(ref items, targetColumn); columnCollection.Add(targetColumn); } if (flag3 && row.IsKey) { if (rgcol == null) { rgcol = new DataColumn[sortedSchemaRows.Length]; } rgcol[len++] = targetColumn; if (flag2 && targetColumn.AllowDBNull) { flag2 = false; } } if (numArray != null) { numArray[unsortedIndex] = targetColumn.Ordinal; } else if (unsortedIndex != targetColumn.Ordinal) { numArray = this.CreateIndexMap(sortedSchemaRows.Length, unsortedIndex); numArray[unsortedIndex] = targetColumn.Ordinal; } num3++; } } bool flag4 = false; DataColumn column2 = null; if (chapterValue != null) { Type type = chapterValue.GetType(); column2 = this._tableMapping.GetDataColumn(this._tableMapping.SourceTable, type, this._dataTable, mappingAction, schemaAction); if (column2 != null) { if (column2.Table == null) { column2.ReadOnly = true; column2.AllowDBNull = false; this.AddItemToAllowRollback(ref items, column2); columnCollection.Add(column2); flag4 = null != parentChapterColumn; } num3++; } } if (0 < num3) { if ((this._dataSet != null) && (this._dataTable.DataSet == null)) { this.AddItemToAllowRollback(ref items, this._dataTable); this._dataSet.Tables.Add(this._dataTable); } if (flag3 && (rgcol != null)) { if (len < rgcol.Length) { rgcol = this.ResizeColumnArray(rgcol, len); } if (flag2) { this._dataTable.PrimaryKey = rgcol; } else { UniqueConstraint constraint = new UniqueConstraint("", rgcol); ConstraintCollection constraints = this._dataTable.Constraints; int count = constraints.Count; for (int k = 0; k < count; k++) { if (constraint.Equals(constraints[k])) { constraint = null; break; } } if (constraint != null) { constraints.Add(constraint); } } } if ((!flag && !ADP.IsEmpty(str2)) && ADP.IsEmpty(this._dataTable.TableName)) { this._dataTable.TableName = str2; } if (gettingData) { this._indexMap = numArray; this._chapterMap = flagArray; objArray = this.SetupMapping(sortedSchemaRows.Length, columnCollection, column2, chapterValue); } else { this._mappedMode = -1; } } else { this._dataTable = null; } if (flag4) { this.AddRelation(parentChapterColumn, column2); } } catch (Exception exception) { if (ADP.IsCatchableOrSecurityExceptionType(exception)) { this.RollbackAddedItems(items); } throw; } return(objArray); }
private void insertRecursive(DataSet ds, DataTable dataTableSchema, IDbCommandBuilder dbCommandBuilder, IDbTransaction dbTransaction, Hashtable insertedTableColl, bool insertIdentity) { // Table has already been inserted into. if (insertedTableColl.ContainsKey(dataTableSchema.TableName)) { return; } // [20060724 - sdh] Move here (from end of method) to avoid infinite-loop when package has relation to itself // Table was inserted into in the database. insertedTableColl[dataTableSchema.TableName] = null; ConstraintCollection constraints = dataTableSchema.Constraints; if (null != constraints) { foreach (Constraint constraint in constraints) { // The table has a foreign key constraint. if (constraint.GetType() == typeof(ForeignKeyConstraint)) { ForeignKeyConstraint fkConstraint = (ForeignKeyConstraint)constraint; // Must insert parent table first. insertRecursive(ds, fkConstraint.RelatedTable, dbCommandBuilder, dbTransaction, insertedTableColl, insertIdentity); } } } // process parent tables first! DataRelationCollection parentRelations = dataTableSchema.ParentRelations; if (null != parentRelations) { foreach (DataRelation parentRelation in parentRelations) { // Must insert parent table first. insertRecursive(ds, parentRelation.ParentTable, dbCommandBuilder, dbTransaction, insertedTableColl, insertIdentity); } } DataRow dataRowClone = null; DataTable dataTable = ds.Tables[dataTableSchema.TableName]; DataTable dataTableClone = dataTableSchema.Clone(); foreach (DataRow dataRow in dataTable.Rows) { // Insert as a new row. dataRowClone = CloneDataRow(dataTableClone, dataRow); dataTableClone.Rows.Add(dataRowClone); } if (insertIdentity) { IDbCommand dbCommand = dbCommandBuilder.GetInsertIdentityCommand(dataTableSchema.TableName); OnInsertIdentity(dataTableClone, dbCommand, dbTransaction); } else { IDbCommand dbCommand = dbCommandBuilder.GetInsertCommand(dataTableSchema.TableName); OnInsert(dataTableClone, dbCommand, dbTransaction); } }
public static void SetViewConstraints(BindableObject view, ConstraintCollection value) { view.SetValue(ViewConstraintsProperty, value); }
public override void Setup(Game game, Supply supply) { base.Setup(game, supply); Card baneCard = null; try { if (game.Settings.Preset != null) { baneCard = game.Settings.Preset.CardCards[game.Settings.Preset.Cards.First(c => c.CardType == this.CardType)].ElementAt(0); } else { IList<Card> availableBaneCards = null; Boolean shouldUseGameConstraints = true; ConstraintCollection ywConstraints = new ConstraintCollection(); if (game.Settings.CardSettings.ContainsKey(this.Name)) { CardsSettings ywSettings = game.Settings.CardSettings[this.Name]; shouldUseGameConstraints = (Boolean)ywSettings.CardSettingCollection[typeof(YoungWitch_UseGameConstraints)].Value; ywConstraints = (ConstraintCollection)ywSettings.CardSettingCollection[typeof(YoungWitch_Constraints)].Value; } // need to setup a bane supply pile here; randomly pick an unused supply card type of cost $2 or $3 from // the Kingdom cards, create a new supply pile of it, and mark it with a Bane token availableBaneCards = game.CardsAvailable.Where(c => c.BaseCost == new Cost(2) || c.BaseCost == new Cost(3)).ToList(); if (shouldUseGameConstraints) { // Skip all "Must Use" constraints ConstraintCollection constraints = new ConstraintCollection(game.Settings.Constraints.Where(c => c.ConstraintType != ConstraintType.CardMustUse)); availableBaneCards = constraints.SelectCards(availableBaneCards, 1); } else availableBaneCards = ywConstraints.SelectCards(availableBaneCards, 1); baneCard = availableBaneCards[0]; } } catch (DominionBase.Cards.ConstraintException ce) { throw new YoungWitchConstraintException(String.Format("Problem setting up Young Witch constraints: {0}", ce.Message)); } game.CardsAvailable.Remove(baneCard); game.Table.AddKingdomSupply(game.Players, baneCard.CardType); game.Table.Supplies[baneCard].Setup(); game.Table.Supplies[baneCard].SnapshotSetup(); game.Table.Supplies[baneCard].AddToken(new BaneToken()); }
/// <summary> /// 复制表结构及主键、唯一键 /// </summary> /// <param name="srcTableName">源表</param> /// <param name="destTableName">新表名称,必须是不存在的</param> public void CopyTableStruct(string srcTableName, string destTableName) { if (srcTableName == destTableName) { throw new Exception("源表和目标表名称冲突"); } string sql = ""; try { ConstraintCollection ucList = GetTableConstraint(srcTableName); sql = "create table " + destTableName + " as select * from " + srcTableName + " where 1=2"; IDbOperation db = new OracleExecute(); db.ExecuteNonQuery(sql); // 添加主键、唯一键约束 foreach (UniqueConstraint uc in ucList) { if (uc == null || uc.Columns.Length <= 0) { continue; } string newConstraintName = uc.ConstraintName; if (newConstraintName.IndexOf(srcTableName) > -1) { newConstraintName = newConstraintName.Replace(srcTableName, destTableName); } else { newConstraintName += "_" + destTableName; } StringBuilder sb = new StringBuilder("alter table "); sb.Append(destTableName); sb.Append(" add constraint "); sb.Append(newConstraintName); if (uc.IsPrimaryKey) { sb.Append(" primary key ("); } else { sb.Append(" unique ("); } for (int i = 0; i < uc.Columns.Length; ++i) { if (i > 0) { sb.Append(", "); } sb.Append(uc.Columns[i].ColumnName); } sb.Append(")"); sql = sb.ToString(); IDbOperation dbOperation = new OracleExecute(); dbOperation.ExecuteNonQuery(sql); } } catch (CustomDataException exdb) { throw exdb; } catch (System.Exception ex) { throw new CustomDataException(ex, sql); } }
public void AutoUpdate(DbTransaction transaction, DataTable dataTable) { DataSet dsTable = GetTableInfo(dataTable.TableName); if (null == dsTable || dsTable.Tables.Count == 0 || dsTable.Tables[0].Rows.Count == 0) { throw new Exception("未找到 " + dataTable.TableName + " 表的信息"); } ConstraintCollection ucList = GetTableConstraint(dataTable.TableName); if (ucList.Count == 0) { throw new Exception("表 " + dataTable.TableName + " 没有主键,无法自动更新"); } Dictionary <string, bool> keyTable = new Dictionary <string, bool>(); foreach (UniqueConstraint uc in ucList) { if (uc == null || uc.Columns.Length == 0) { continue; } foreach (DataColumn dc in uc.Columns) { keyTable[dc.ColumnName] = true; } } StringBuilder sb = new StringBuilder(); sb.Append("update "); sb.Append(dataTable.TableName); int idx = 0; foreach (DataRow dataRow in dsTable.Tables[0].Rows) { string cName = dataRow["CNAME"].ToString(); if (dataTable.Columns.Contains(cName) && !keyTable.ContainsKey(cName)) { if (idx == 0) { sb.Append(" set "); } else { sb.Append(", "); } sb.Append(cName); sb.Append(" = :"); sb.Append(cName); ++idx; } } if (idx == 0) { return; } idx = 0; foreach (UniqueConstraint uc in ucList) { if (uc == null || uc.Columns.Length == 0) { continue; } foreach (DataColumn dc in uc.Columns) { if (idx == 0) { sb.Append(" where "); } else { sb.Append(" and "); } sb.Append(dc.ColumnName); sb.Append(" = :"); sb.Append(dc.ColumnName); ++idx; } } string sql = sb.ToString(); DbParameter[] parameters = null; try { foreach (DataRow dataRow in dataTable.Rows) { List <DbParameter> paramList = new List <DbParameter>(); foreach (DataRow drTable in dsTable.Tables[0].Rows) { string cName2 = drTable["cname"].ToString(); if (!dataTable.Columns.Contains(cName2)) { continue; } DbType dbt = OracleDbTypeWrapper.WrapDbType(drTable["coltype"].ToString()); object o = dataRow.IsNull(cName2) ? null : dataRow[cName2]; paramList.Add(DbFactory <OracleConn, OracleFactory <OracleConn> > .MakeInParam(":" + cName2, dbt, Convert.ToInt32(drTable["WIDTH"]), o)); } parameters = paramList.ToArray(); IDbOperation db = new OracleExecute(); if (transaction == null) { db.ExecuteNonQuery(sql, parameters); } else { db.ExecuteNonQuery(transaction, sql, parameters); } } } catch (System.Exception ex) { throw new CustomDataException(ex, sql, parameters); } }
public void AutoProcess(DbTransaction transaction, DataTable dataTable, ExistingItemProcessType processType) { if (dataTable.TableName.Length == 0) { throw new Exception("表名为空"); } if (dataTable.Rows.Count == 0) { return; } string sql = ""; bool owerConnection = transaction == null; DbConnection conn = null; DbTransaction tran = null; try { ConstraintCollection ucList = GetTableConstraint(dataTable.TableName); if (ucList.Count == 0) { AutoInsert(null, dataTable); return; } if (owerConnection) { conn = CreateConnection(); conn.Open(); tran = conn.BeginTransaction(); } else { conn = transaction.Connection; tran = transaction; } //sql = "select * from " + dt.TableName; //DataSet ds = ExecuteDataset(tran, sql); sql = "select count(*) from " + dataTable.TableName + " where "; Dictionary <string, bool> keyColumnList = new Dictionary <string, bool>(); foreach (UniqueConstraint uc in ucList) { if (uc == null || uc.Columns.Length == 0) { continue; } foreach (DataColumn dc in uc.Columns) { keyColumnList[dc.ColumnName] = true; } } int idx = 0; foreach (string columnName in keyColumnList.Keys) { if (idx > 0) { sql += " and "; } sql += columnName + "=:" + columnName; ++idx; } DataSet dsTable = GetTableInfo(dataTable.TableName); DataTable dtInsert = dataTable.Clone(); DataTable dtExist = dataTable.Clone(); foreach (DataRow dr in dataTable.Rows) { DbParameter[] pList = new DbParameter[keyColumnList.Keys.Count]; idx = 0; foreach (DataRow dr2 in dsTable.Tables[0].Rows) { if (keyColumnList.ContainsKey(dr2["cname"].ToString())) { pList[idx] = DbFactory <OracleConn, OracleFactory <OracleConn> > .MakeInParam(":" + dr2["cname"].ToString(), OracleDbTypeWrapper.WrapDbType(dr2["coltype"].ToString()), Convert.ToInt32(dr2["width"]), dr[dr2["cname"].ToString()]); ++idx; } } bool bContain = Convert.ToInt32(ExecuteScalar(tran, CommandType.Text, sql, pList)) > 0; if (!bContain) { dtInsert.ImportRow(dr); } else { dtExist.ImportRow(dr); } } if (dtInsert.Rows.Count > 0) { AutoInsert(tran, dtInsert); } if (processType == ExistingItemProcessType.Update && dtExist.Rows.Count > 0) { AutoUpdate(tran, dtExist); } if (owerConnection) { tran.Commit(); } } catch (System.Exception ex) { if (owerConnection) { tran.Rollback(); } throw new CustomDataException(ex, sql); } finally { if (owerConnection && conn != null) { conn.Close(); } } }
public MiMFa_DecisionMachine(List <T> inputList, ConstraintCollection constraints) { Set(inputList, constraints); }
public void SetUp() { _constraintCollection = new ConstraintCollection<RecWrapper>(); }
public void TearDown() { _constraintCollection = null; }