Example #1
0
 public virtual IConstraint And(IConstraint andWith)
 {
     lock (StreamLock())
     {
         return Join(andWith, true);
     }
 }
Example #2
0
 /// <summary>
 /// Formats a prefix constraint's description.
 /// </summary>
 internal static string FormatDescription(string descriptionPrefix, IConstraint baseConstraint)
 {
     return string.Format(
         baseConstraint is EqualConstraint ? "{0} equal to {1}" : "{0} {1}",
         descriptionPrefix,
         baseConstraint.Description);
 }
Example #3
0
        protected override void VisitGroup(ConstraintGroup node)
        {
            IConstraint where = null;

            for (int i = 0, c = node.Items.Count; i < c; i++)
            {
                this.Visit(node.Items[i]);

                if (i == 0)
                {
                    where = _whereResult;
                }
                else
                {
                    string op = node.Operators[i - 1];
                    if (op == Constraint.AndOperator)
                    {
                        where = f.And(where, _whereResult);
                    }
                    else if (op == Constraint.OrOperator)
                    {
                        where = f.Or(where, _whereResult);
                    }
                }
            }

            _whereResult = where;
        }
        protected override object GetRandomValueCore(Type type, IConstraint[] constraints)
        {
            var valueScaled = _random.NextDouble();

            if (type == typeof(float))
                return this.ApplyConstraints(
                    constraints, 0.0f, 1.0f,
                    (minValue, maxValue) => minValue + valueScaled * (maxValue - minValue)
                );

            if (type == typeof(double))
                return this.ApplyConstraints(
                    constraints, 0.0d, 1.0d,
                    (minValue, maxValue) => minValue + valueScaled * (maxValue - minValue)
                );

            if (type == typeof(decimal))
                return this.ApplyConstraints(
                    constraints, 0.0m, 1.0m,
                    (minValue, maxValue) => minValue + (decimal)valueScaled * (maxValue - minValue)
                );

            throw new InvalidOperationException(
                string.Format("{0} does not support generation of {1}", this.GetType(), type
            ));
        }
Example #5
0
        /// <summary>
        /// Construct given a base constraint
        /// </summary>
        /// <param name="baseConstraint"></param>
        protected PrefixConstraint(IResolveConstraint baseConstraint)
            : base(baseConstraint)
        {
            Guard.ArgumentNotNull(baseConstraint, "baseConstraint");

            this.baseConstraint = baseConstraint.Resolve();
        }
Example #6
0
			public virtual void Visit(OrExpression expression)
			{
				expression.Left().Accept(this);
				IConstraint left = _constraint;
				expression.Right().Accept(this);
				left.Or(_constraint);
				_constraint = left;
			}
Example #7
0
 public virtual void Visit(AndExpression expression)
 {
     expression.Left().Accept(this);
     var left = _constraint;
     expression.Right().Accept(this);
     left.And(_constraint);
     _constraint = left;
 }
        protected override object GetRandomValueCore(Type type, IConstraint[] constraints)
        {
            var randomNumber = _random.Next(Int32.MinValue, Int32.MaxValue);
            var valueScaled = (decimal)((long)randomNumber - Int32.MinValue) / ((long)Int32.MaxValue - Int32.MinValue);

            if (type == typeof(sbyte))
                return this.ApplyConstraints(
                    constraints, sbyte.MinValue, sbyte.MaxValue,
                    (minValue, maxValue) => minValue + valueScaled * (maxValue - minValue)
                );

            if (type == typeof(short))
                return this.ApplyConstraints(
                    constraints, short.MinValue, short.MaxValue,
                    (minValue, maxValue) => minValue + valueScaled * (maxValue - minValue)
                );

            if (type == typeof(int))
                return this.ApplyConstraints(
                    constraints, int.MinValue, int.MaxValue,
                    (minValue, maxValue) => minValue + valueScaled * ((long)maxValue - minValue)
                );

            if (type == typeof(long))
                return this.ApplyConstraints(
                    constraints, long.MinValue, long.MaxValue,
                    (minValue, maxValue) => this.ConstrictToRange(valueScaled, minValue, maxValue)
                );

            if (type == typeof(byte))
                return this.ApplyConstraints(
                    constraints, byte.MinValue, byte.MaxValue,
                    (minValue, maxValue) => minValue + valueScaled * (maxValue - minValue)
                );

            if (type == typeof(ushort))
                return this.ApplyConstraints(
                    constraints, ushort.MinValue, ushort.MaxValue,
                    (minValue, maxValue) => minValue + valueScaled * (maxValue - minValue)
                );

            if (type == typeof(uint))
                return this.ApplyConstraints(
                    constraints, uint.MinValue, uint.MaxValue,
                    (minValue, maxValue) => minValue + valueScaled * (maxValue - minValue)
                );

            if (type == typeof(ulong))
                return this.ApplyConstraints(
                    constraints, ulong.MinValue, ulong.MaxValue,
                    (minValue, maxValue) => minValue + valueScaled * (maxValue - minValue)
                );

            throw new InvalidOperationException(
                string.Format("{0} does not support generation of {1}", this.GetType(), type
            ));
        }
Example #9
0
        /// <summary>
        /// Writes the difference between the constraint and the actual value into a message.
        /// </summary>
        /// <param name="constraint">The constraint.</param>
        public string BuildMessage(IConstraint constraint)
        {
            this.Message = string.Format("Expected: '{0}' But was : '{1}'"
                , constraint.Description
                , this.GetString(constraint.Actual));

            this.BuildHeader(this.Message, constraint);
            return this.Message;
        }
Example #10
0
        /// <summary>
        /// Construct a BinaryConstraint from two other constraints
        /// </summary>
        /// <param name="left">The first constraint</param>
        /// <param name="right">The second constraint</param>
        protected BinaryConstraint(IConstraint left, IConstraint right)
            : base(left, right)
        {
            Guard.ArgumentNotNull(left, "left");
            this.Left = left;

            Guard.ArgumentNotNull(right, "right");
            this.Right = right;
        }
Example #11
0
		public void IsNull()
		{
			c = new IsNull();
			Assertion.Assert(c.Eval(null));
			Assertion.Assert(!c.Eval(new object()));
			Assertion.Assert(!c.Eval(1));
			Assertion.Assert(!c.Eval(true));
			Assertion.Assert(!c.Eval(false));
		}
Example #12
0
		public void IsEqualWhenArray()
		{
			object[] o1 = new object[] { 1, 2, 3 };
			object[] o2 = new object[] { 1, 2, 4 };

			c = new IsEqual(new object[] { 1, 2, 3 });
			Assertion.Assert("should be equal", c.Eval(o1));
			Assertion.Assert("shouldn't be equal", !c.Eval(o2));
			Assertion.Assert("it ain't null", !c.Eval(null));
		}
Example #13
0
        protected override void VisitAndOrConstraint(AndOrConstraint node)
        {
            this.Visit(node.Left);
            var leftWhere = _whereResult;

            this.Visit(node.Right);
            var rightWhere = _whereResult;

            _whereResult = f.Binary(leftWhere, node.IsAnd ? BinaryOperator.And : BinaryOperator.Or, rightWhere);
        }
Example #14
0
        public object GetRandomValue(Type type, IConstraint[] constraints)
        {
            Require.NotNull(type, "type");
            Require.That<InvalidOperationException>(
                this.IsTypeSupported(type),
                "{0} does not support generation of {1}.",
                this.GetType(), type
            );

            return this.GetRandomValueCore(type, constraints);
        }
        public InstanceRegistration(IConstraint constraint, ActionDescriptor actionDescriptor, ControllerDescriptor controllerDescriptor, FilterScope scope1)
            : base(actionDescriptor, controllerDescriptor, scope1)
        {
            if (constraint == null)
            {
                throw new ArgumentNullException("constraint", "Constraint instance can not be null.");
            }

            Constraint = constraint;
            ConstraintType = Constraint.GetType();
        }
Example #16
0
		public virtual IConstraints Constraints()
		{
			lock (_cluster)
			{
				IConstraint[] constraints = new IConstraint[_queries.Length];
				for (int i = 0; i < constraints.Length; i++)
				{
					constraints[i] = _queries[i].Constraints();
				}
				return new ClusterConstraints(_cluster, constraints);
			}
		}
Example #17
0
 public virtual IConstraint Constrain(object constraint)
 {
     lock (_cluster)
     {
         var constraints = new IConstraint[_queries.Length];
         for (var i = 0; i < constraints.Length; i++)
         {
             constraints[i] = _queries[i].Constrain(constraint);
         }
         return new ClusterConstraint(_cluster, constraints);
     }
 }
Example #18
0
		public void IsAnything()
		{
			c = new IsAnything();
			Assertion.Assert(c.Eval(null));
			Assertion.Assert(c.Eval(0));
			Assertion.Assert(c.Eval(99));
			Assertion.Assert(c.Eval(-2));
			Assertion.Assert(c.Eval(true));
			Assertion.Assert(c.Eval(false));
			Assertion.Assert(c.Eval(""));
			Assertion.Assert(c.Eval("hello"));
			Assertion.Assert(c.Eval(new object()));
		}
Example #19
0
        private Pendulum(Particle point_a_, Particle point_b_, Vector3f equilibrium_position_, Render callback_, params IConstraint[] constraints_)
        {
            point_a = point_a_;
            point_b = point_b_;
            callback = callback_;
            equilibrium_position = equilibrium_position_;

            constraints = new IConstraint[constraints_.Length];
            for(int i = 0; i < constraints_.Length; ++i)
            {
                constraints[i] = constraints_[i];
            }
        }
Example #20
0
		internal override IConstraint Join(IConstraint a_with, bool a_and)
		{
			lock (StreamLock())
			{
				if (!(a_with is QCon))
				{
					return null;
				}
				// resolving multiple constraints happens in QCon for
				// a_with, so we simply turn things around
				return ((QCon)a_with).Join1(this, a_and);
			}
		}
Example #21
0
		private IConstraint[] argsAsConstraints(object[] args)
		{
			if (null == args)
			{
				return new IConstraint[0];
			}

			IConstraint[] result = new IConstraint[args.Length];
			for (int i = 0; i < result.Length; ++i)
			{
				result[i] = argAsConstraint(args[i]);
			}
			return result;
		}
Example #22
0
		private IConstraint Join(IConstraint with, bool isAnd)
		{
			lock (_cluster)
			{
				Db4objects.Db4o.Internal.Cluster.ClusterConstraint other = Compatible(with);
				IConstraint[] newConstraints = new IConstraint[_constraints.Length];
				for (int i = 0; i < _constraints.Length; i++)
				{
					newConstraints[i] = isAnd ? _constraints[i].And(other._constraints[i]) : _constraints
						[i].Or(other._constraints[i]);
				}
				return new Db4objects.Db4o.Internal.Cluster.ClusterConstraint(_cluster, newConstraints
					);
			}
		}
Example #23
0
		private Db4objects.Db4o.Internal.Cluster.ClusterConstraint Compatible(IConstraint
			 with)
		{
			if (!(with is Db4objects.Db4o.Internal.Cluster.ClusterConstraint))
			{
				throw new ArgumentException();
			}
			Db4objects.Db4o.Internal.Cluster.ClusterConstraint other = (Db4objects.Db4o.Internal.Cluster.ClusterConstraint
				)with;
			if (other._constraints.Length != _constraints.Length)
			{
				throw new ArgumentException();
			}
			return other;
		}
		private static int GetIndexOfConstraintDimension(IConstraint constraint, ReadOnlyCollection<DimensionWithValues> dimensionValues,
			QualifiedDimension dimension)
		{
			int ret = 0;
			foreach (DimensionWithValues dv in dimensionValues)
			{
				if (IsSubset(dimension, dv.Dimension))
				{
					return ret;
				}
				ret++;
			}
			throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture,
				"Dimension {0} from constraint {1} was not found in the matrix (all dimensions: {2}).",
				dimension.FullyQualifiedName, constraint.GetType().Name, string.Join(",", dimensionValues.Select(dv => dv.Dimension.FullyQualifiedName))));
		}
Example #25
0
		public void NotEqual()
		{
			object o1 = new object();
			object o2 = new object();
			c = new NotEqual(o1);
			Assertion.Assert(!c.Eval(o1));
			Assertion.Assert(c.Eval(o2));
			Assertion.Assert(c.Eval(null));

			int i1 = 1;
			int i2 = 2;
			c = new NotEqual(i1);
			Assertion.Assert(!c.Eval(i1));
			Assertion.Assert(!c.Eval(1));
			Assertion.Assert(c.Eval(i2));
			Assertion.Assert(c.Eval(2));
		}
		public virtual IConstraint[] ToArray()
		{
			lock (_cluster)
			{
				Collection4 all = new Collection4();
				for (int i = 0; i < _constraints.Length; i++)
				{
					ClusterConstraint c = (ClusterConstraint)_constraints[i];
					for (int j = 0; j < c._constraints.Length; j++)
					{
						all.Add(c._constraints[j]);
					}
				}
				IConstraint[] res = new IConstraint[all.Size()];
				all.ToArray(res);
				return res;
			}
		}
Example #27
0
			public virtual void Visit(ComparisonExpression expression)
			{
				IQuery subQuery = Descend(expression.Left());
				ComparisonQueryGeneratingVisitor visitor = new ComparisonQueryGeneratingVisitor(_predicate
					, _classSource, _referenceResolver);
				expression.Right().Accept(visitor);
				_constraint = subQuery.Constrain(visitor.Value());
				ComparisonOperator op = expression.Op();
				if (op.Equals(ComparisonOperator.ValueEquality))
				{
					return;
				}
				if (op.Equals(ComparisonOperator.ReferenceEquality))
				{
					_constraint.Identity();
					return;
				}
				if (op.Equals(ComparisonOperator.Greater))
				{
					_constraint.Greater();
					return;
				}
				if (op.Equals(ComparisonOperator.Smaller))
				{
					_constraint.Smaller();
					return;
				}
				if (op.Equals(ComparisonOperator.Contains))
				{
					_constraint.Contains();
					return;
				}
				if (op.Equals(ComparisonOperator.StartsWith))
				{
					_constraint.StartsWith(true);
					return;
				}
				if (op.Equals(ComparisonOperator.EndsWith))
				{
					_constraint.EndsWith(true);
					return;
				}
				throw new Exception("Can't handle constraint: " + op);
			}
        protected override object GetRandomValueCore(Type type, IConstraint[] constraints)
        {
            if (type == typeof(char))
                return (char)_random.Next(Char.MinValue, Char.MaxValue);

            if (type == typeof(bool))
                return _random.NextDouble() > 0.5;

            if (type == typeof(string))
            #if !SILVERLIGHT
                return Path.GetRandomFileName();
            #else
                return Guid.NewGuid().ToString();
            #endif

            if (type == typeof(Guid))
                return Guid.NewGuid();

            throw new InvalidOperationException(
                string.Format("{0} does not support generation of {1}", this.GetType(), type
            ));
        }
Example #29
0
        public void Parse(string filter, IQuery query)
        {
            _query = query;
            _mainTable = query.MainTable;
            _column = null;
            _comparison = null;
            _concat = null;
            _current = null;
            _f = QueryFactory.Instance;
            _bracketStack = new Stack<StackItem>();

            using (_reader = new StringReader(filter))
            {
                while (true)
                {
                    var part = this.ReadPart();
                    if (part == string.Empty) break;
                    this.DealPart(part);
                }
            }

            query.Where = _current;
        }
Example #30
0
 public BinaryRandomGeneration(IConstraint <bool> constraint, int?seed = null)
     : base(constraint)
 {
     rng = new BoolRandom(seed);
 }
 public void DistributedTracePayload_OptionalAndRequired(string json, IConstraint constraint)
 {
     Assert.That(() => DistributedTracePayload.TryBuildIncomingPayloadFromJson(json), constraint);
 }
Example #32
0
 /// <summary>
 /// Returns a constraint that will apply the argument
 /// to the members of a collection, succeeding if
 /// none of them succeed.
 /// </summary>
 public override IConstraint ApplyPrefix(IConstraint constraint)
 {
     return(new NoItemConstraint(constraint));
 }
Example #33
0
        //private enum FailurePoint
        //{
        //    None,
        //    Left,
        //    Right
        //};

        //private FailurePoint failurePoint;

        /// <summary>
        /// Create an AndConstraint from two other constraints
        /// </summary>
        /// <param name="left">The first constraint</param>
        /// <param name="right">The second constraint</param>
        public AndConstraint(IConstraint left, IConstraint right) : base(left, right)
        {
        }
Example #34
0
 public AGenerator(IConstraint <Element> constraint)
 {
     pcConstraint = constraint;
 }
 /// <summary>
 /// Returns the constraint created by applying this
 /// prefix to another constraint.
 /// </summary>
 /// <param name="constraint"></param>
 /// <returns></returns>
 public abstract IConstraint ApplyPrefix(IConstraint constraint);
Example #36
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PropertyConstraint"/> class.
 /// </summary>
 /// <param name="name">The name.</param>
 /// <param name="baseConstraint">The constraint to apply to the property.</param>
 public PropertyConstraint(string name, IConstraint baseConstraint)
     : base(baseConstraint)
 {
     this.name = name;
     this.descriptionPrefix = "property " + name;
 }
        /// <summary>
        /// Constrains the specified constraint.
        /// </summary>
        /// <param name="constraint">The constraint.</param>
        /// <returns>A <see cref="IContextObjectProviderRuleBuilder{TContext,TSubject,TContextObject}"/></returns>
        public IContextObjectProviderRuleBuilder <TContext, TSubject, TContextObject> Constrain(IConstraint constraint)
        {
            Check.IsNotNull(constraint, "constraint is required.");

            _constraints.Add(constraint);

            CheckAddClauses();
            return(this);
        }
 /// <summary>
 /// Construct a SomeItemsConstraint on top of an existing constraint
 /// </summary>
 /// <param name="itemConstraint"></param>
 public SomeItemsConstraint(IConstraint itemConstraint)
     : base(itemConstraint)
 {
     _equalConstraint  = itemConstraint as EqualConstraint;
     DescriptionPrefix = "some item";
 }
Example #39
0
 /// <summary>
 /// Returns a IndexerConstraint applied to its argument.
 /// </summary>
 public override IConstraint ApplyPrefix(IConstraint constraint)
 {
     return(new IndexerConstraint(_indexArguments, constraint));
 }
Example #40
0
 /// <summary>
 /// Display Expected and Actual lines for a constraint. This
 /// is called by MessageWriter's default implementation of
 /// WriteMessageTo and provides the generic two-line display.
 /// </summary>
 /// <param name="constraint">The constraint that failed</param>
 public abstract void DisplayDifferences(IConstraint constraint);
Example #41
0
 /// <summary>
 /// Constructs a <see cref="ConstraintResult"/> for a <see cref="ExactCountConstraint"/>.
 /// </summary>
 /// <param name="constraint">The Constraint to which this result applies.</param>
 /// <param name="actualValue">The actual value to which the Constraint was applied.</param>
 /// <param name="isSuccess">If true, applies a status of Success to the result, otherwise Failure.</param>
 /// <param name="matchCount">Count of matched items of the <see cref="ExactCountConstraint"/></param>
 /// <param name="itemList">A list with maximum count (+1) of items of the <see cref="ExactCountConstraint"/></param>
 internal ExactCountConstraintResult(IConstraint constraint, object actualValue, bool isSuccess, int matchCount, ICollection <object> itemList)
     : base(constraint, actualValue, isSuccess)
 {
     _matchCount = matchCount;
     _itemList   = itemList;
 }
Example #42
0
 /// <summary>
 /// Construct a ReusableConstraint from a constraint expression
 /// </summary>
 /// <param name="c">The expression to be resolved and reused</param>
 public ReusableConstraint(IResolveConstraint c)
 {
     this.constraint = c.Resolve();
 }
        /// <summary>
        ///     Adds a table constraint.
        /// </summary>
        /// <param name="constraintFactory">
        ///     The constraint factory that instantiates a dedicated constraint instance for
        ///     this table.
        ///     </param>
        public void Add(IConstraintFactory <T> constraintFactory)
        {
            IConstraint <T> constraint = constraintFactory.Create();

            this.Add(constraint);
        }
Example #44
0
 public ComposedExpression Add(IConstraint constraint)
 {
     Constraints.Add(constraint);
     return(this);
 }
Example #45
0
 /// <summary>
 /// Initializes a new instance of the <see cref="StringType"/> class.
 /// </summary>
 /// <param name="primitive">The primitive type flag</param>
 /// <param name="constraint">The type constraint, or null</param>
 private StringType(bool primitive, IConstraint constraint)
     : base("OCTET STRING", primitive)
 {
     this.constraint = constraint;
 }
Example #46
0
 /// <summary>
 /// Construct an AllItemsConstraint on top of an existing constraint
 /// </summary>
 /// <param name="itemConstraint"></param>
 public AllItemsConstraint(IConstraint itemConstraint)
     : base(itemConstraint)
 {
     DescriptionPrefix = "all items";
 }
Example #47
0
 public Constraint(IConstraint impl)
 {
     impl_ = impl;
 }
 /// <summary>
 /// Constructs a <see cref="PropertyConstraintResult"/> for a particular <see cref="PropertyConstraint"/>.
 /// </summary>
 /// <param name="constraint">The Constraint to which this result applies.</param>
 /// <param name="baseResult">The base result with actual value to which the Constraint was applied.</param>
 public PropertyConstraintResult(IConstraint constraint, ConstraintResult baseResult) : base(constraint, baseResult.ActualValue, baseResult.Status)
 {
     _baseResult = baseResult;
 }
Example #49
0
 /// <summary>
 /// Returns a constraint that will apply the argument
 /// to the members of a collection, succeeding if
 /// none of them succeed.
 /// </summary>
 public override IConstraint ApplyPrefix(IConstraint constraint)
 {
     return(new ExactCountConstraint(expectedCount, constraint));
 }
Example #50
0
        /// <summary>
        /// <see cref="CommonQueryCriteria"/> 查询的数据层实现。
        /// </summary>
        /// <param name="criteria"></param>
        public virtual EntityList GetBy(CommonQueryCriteria criteria)
        {
            var table = f.Table(_repository);
            var q     = f.Query(table);

            var allProperties = _repository.EntityMeta.ManagedProperties.GetNonReadOnlyCompiledProperties();

            //拼装所有 Where 条件。
            bool ignoreNull = criteria.IgnoreNull;

            foreach (var group in criteria.Groups)
            {
                IConstraint groupRes = null;
                foreach (var pm in group)
                {
                    var property = allProperties.Find(pm.PropertyName);
                    if (property != null)
                    {
                        var  op      = pm.Operator;
                        var  value   = pm.Value;
                        bool ignored = false;
                        if (ignoreNull)
                        {
                            ignored = !DomainHelper.IsNotEmpty(value);
                        }
                        else
                        {
                            if (value is string || (value == null && property.PropertyType == typeof(string)))
                            {
                                #region 如果是对空字符串进行模糊匹配,那么这个条件需要被忽略。

                                var strValue = value as string;
                                if (string.IsNullOrEmpty(strValue))
                                {
                                    switch (op)
                                    {
                                    case PropertyOperator.Like:
                                    case PropertyOperator.Contains:
                                    case PropertyOperator.StartsWith:
                                    case PropertyOperator.EndsWith:
                                    case PropertyOperator.NotLike:
                                    case PropertyOperator.NotContains:
                                    case PropertyOperator.NotStartsWith:
                                    case PropertyOperator.NotEndsWith:
                                        ignored = true;
                                        break;

                                    default:
                                        break;
                                    }
                                }

                                #endregion
                            }
                        }
                        if (!ignored)
                        {
                            var propertyRes = f.Constraint(table.Column(property), op, value);
                            groupRes = f.Binary(groupRes, group.Concat, propertyRes);
                        }
                    }
                }

                q.Where = f.Binary(groupRes, criteria.Concat, q.Where);
            }

            //OrderBy
            if (!string.IsNullOrWhiteSpace(criteria.OrderBy))
            {
                var orderBy = allProperties.Find(criteria.OrderBy, true);
                if (orderBy == null)
                {
                    throw new InvalidProgramException(string.Format("在实体 {0} 中没有找到名为 {1} 的属性。", _repository.EntityType.FullName, criteria.OrderBy));
                }

                var dir = criteria.OrderByAscending ? OrderDirection.Ascending : OrderDirection.Descending;
                q.OrderBy.Add(table.Column(orderBy), dir);
            }

            return(this.QueryList(q, criteria.PagingInfo, criteria.EagerLoad));
        }
Example #51
0
 /// <summary>
 /// Initializes a new instance of the <see cref="StringType"/> class.
 /// </summary>
 /// <param name="constraint">The additional type constraint</param>
 public StringType(IConstraint constraint) : this(true, constraint)
 {
 }
Example #52
0
 /// <summary>
 /// Constructs a <see cref="ConstraintResult"/> for a particular <see cref="Constraint"/>.
 /// </summary>
 /// <param name="constraint">The Constraint to which this result applies.</param>
 /// <param name="actualValue">The actual value to which the Constraint was applied.</param>
 /// <param name="isSuccess">If true, applies a status of Success to the result, otherwise Failure.</param>
 public ConstraintResult(IConstraint constraint, object actualValue, bool isSuccess)
     : this(constraint, actualValue)
 {
     this.Status = isSuccess ? ConstraintStatus.Success : ConstraintStatus.Failure;
 }
Example #53
0
        public static void AlterTable(AlterPlan plan, ITableStructure oldTable, ITableStructure newTable, DbDiffOptions opts, DbObjectPairing pairing)
        {
            //plan.BeginFixedOrder();
            if (oldTable == null)
            {
                throw new ArgumentNullException("oldTable", "DAE-00240 oldTable is null");
            }
            if (newTable == null)
            {
                throw new ArgumentNullException("newTable", "DAE-00241 newTable is null");
            }

            //bool processed;
            //proc.AlterTable(oldTable, newTable, out processed);
            //if (processed) return;

            InMemoryTableOperation dataOps = null;

            if (oldTable.FixedData != null)
            {
                dataOps = new InMemoryTableOperation(oldTable.FixedData.Structure);
            }

            NameWithSchema newTableName = GenerateNewName(oldTable.FullName, newTable.FullName, opts);

            bool permuteColumns = false;
            bool insertColumns  = false;
            //bool renameColumns = false;

            List <int> columnMap     = new List <int>();
            List <int> constraintMap = new List <int>();

            foreach (var col in newTable.Columns)
            {
                columnMap.Add(oldTable.Columns.IndexOfIf(c => c.GroupId == col.GroupId));
            }
            foreach (var cnt in newTable.Constraints)
            {
                int cindex = oldTable.Constraints.IndexOfIf(c => c.GroupId == cnt.GroupId);
                if (cindex < 0 && cnt is IPrimaryKey)
                {
                    // primary keys for one table are equal
                    cindex = oldTable.Constraints.IndexOfIf(c => c is IPrimaryKey);
                }
                constraintMap.Add(cindex);
            }

            if (!opts.IgnoreColumnOrder)
            {
                // count alter requests
                int lastcol = -1;
                foreach (int col in columnMap)
                {
                    if (col < 0)
                    {
                        continue;
                    }
                    if (col < lastcol)
                    {
                        permuteColumns = true;
                    }
                    lastcol = col;
                }

                bool wasins = false;
                foreach (int col in columnMap)
                {
                    if (col < 0)
                    {
                        wasins = true;
                    }
                    if (col >= 0 && wasins)
                    {
                        insertColumns = true;
                    }
                }
            }

            int index;

            // drop constraints
            index = 0;

            foreach (IConstraint cnt in oldTable.Constraints)
            {
                if (constraintMap.IndexOf(index) < 0)
                {
                    plan.DropConstraint(cnt);
                }
                index++;
            }

            // drop columns
            index = 0;
            foreach (IColumnStructure col in oldTable.Columns)
            {
                if (columnMap.IndexOf(index) < 0)
                {
                    plan.DropColumn(col);
                    if (dataOps != null)
                    {
                        dataOps.DropColumn(col.ColumnName);
                    }
                }
                index++;
            }

            if (!DbDiffTool.EqualFullNames(oldTable.FullName, newTable.FullName, opts))
            {
                plan.RenameTable(oldTable, newTable.FullName);
            }

            // create columns
            index = 0;
            foreach (IColumnStructure col in newTable.Columns)
            {
                if (columnMap[index] < 0)
                {
                    ColumnStructure newcol = new ColumnStructure(col);
                    plan.CreateColumn(oldTable, newcol);
                    if (dataOps != null)
                    {
                        dataOps.CreateColumn(newcol);
                    }
                }
                index++;
            }

            // change columns
            index = 0;
            foreach (IColumnStructure col in newTable.Columns)
            {
                if (columnMap[index] >= 0)
                {
                    IColumnStructure src = oldTable.Columns[columnMap[index]];
                    if (!DbDiffTool.EqualsColumns(src, col, true, opts, pairing))
                    {
                        using (var ctx = new DbDiffChangeLoggerContext(opts, NopLogger.Instance, DbDiffOptsLogger.DiffLogger))
                        {
                            if (DbDiffTool.EqualsColumns(src, col, false, opts, pairing))
                            {
                                plan.RenameColumn(src, col.ColumnName);
                            }
                            else
                            {
                                plan.ChangeColumn(src, col);
                            }
                            if (dataOps != null && src.ColumnName != col.ColumnName)
                            {
                                dataOps.RenameColumn(src.ColumnName, col.ColumnName);
                            }
                        }
                    }
                }
                index++;
            }

            // create fixed data script
            var script = AlterFixedData(oldTable.FixedData, newTable.FixedData, dataOps, opts);

            if (script != null)
            {
                plan.UpdateData(oldTable.FullName, script);
            }

            // change constraints
            index = 0;
            foreach (IConstraint cnt in newTable.Constraints)
            {
                if (constraintMap[index] >= 0)
                {
                    IConstraint src = oldTable.Constraints[constraintMap[index]];
                    if (DbDiffTool.EqualsConstraints(src, cnt, opts, false, pairing) && src.Name != cnt.Name)
                    {
                        if (cnt is IPrimaryKey && (pairing.Source.Dialect.DialectCaps.AnonymousPrimaryKey || pairing.Target.Dialect.DialectCaps.AnonymousPrimaryKey))
                        {
                            // do nothing
                        }
                        else
                        {
                            plan.RenameConstraint(src, cnt.Name);
                        }
                    }
                    else
                    {
                        if (!DbDiffTool.EqualsConstraints(src, cnt, opts, true, pairing))
                        {
                            plan.ChangeConstraint(src, cnt);
                        }
                    }
                }
                index++;
            }

            // create constraints
            index = 0;
            foreach (IConstraint cnt in newTable.Constraints)
            {
                if (constraintMap[index] < 0)
                {
                    plan.CreateConstraint(oldTable, cnt);
                }
                index++;;
            }

            if (permuteColumns || insertColumns)
            {
                plan.ReorderColumns(oldTable, new List <string>((from c in newTable.Columns select c.ColumnName)));
            }

            var alteredOptions = GetTableAlteredOptions(oldTable, newTable, opts);

            if (alteredOptions.Count > 0)
            {
                plan.ChangeTableOptions(oldTable, alteredOptions);
            }
            //plan.EndFixedOrder();
        }
Example #54
0
 /// <summary>
 /// Constructs a <see cref="ConstraintResult"/> for a particular <see cref="Constraint"/>.
 /// </summary>
 /// <param name="constraint">The Constraint to which this result applies.</param>
 /// <param name="actualValue">The actual value to which the Constraint was applied.</param>
 /// <param name="status">The status of the new ConstraintResult.</param>
 public ConstraintResult(IConstraint constraint, object actualValue, ConstraintStatus status)
     : this(constraint, actualValue)
 {
     this.Status = status;
 }
Example #55
0
 public ValidationFailure(string message, IConstraint sender) : this(message)
 {
     SourceConstraint = sender;
 }
Example #56
0
 /// <summary>
 /// Constructs a <see cref="ConstraintResult"/> for a particular <see cref="Constraint"/>.
 /// </summary>
 /// <param name="constraint">The Constraint to which this result applies.</param>
 /// <param name="actualValue">The actual value to which the Constraint was applied.</param>
 public ConstraintResult(IConstraint constraint, object actualValue)
 {
     this.Name        = constraint.DisplayName;
     this.Description = constraint.Description;
     this.ActualValue = actualValue;
 }
Example #57
0
 public PlanConstraint(IConstraint con)
 {
     this.Constraint = con;
 }
Example #58
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ThrowsConstraint"/> class,
 /// using a constraint to be applied to the exception.
 /// </summary>
 /// <param name="baseConstraint">A constraint to apply to the caught exception.</param>
 public ThrowsConstraint(IConstraint baseConstraint)
     : base(baseConstraint)
 {
 }
Example #59
0
 public void PushConstraint(IConstraint constraint)
 {
     _constraints.Push(constraint);
 }
 /// <summary>Creates a new <see cref="IOneDimEquationSolverAlgorithm"/> object.
 /// </summary>
 /// <param name="constraint">A contraint for the root finder algorithm represented by the current instance, where the parameter has been created via property <see cref="OneDimEquationSolver.Constraint"/>; if
 /// <c>null</c> an unconstraint feasible region is assumed, i.e. identical to <see cref="OneDimEquationSolver.Create()"/>.</param>
 /// <returns>A new <see cref="IOneDimEquationSolverAlgorithm"/> object.</returns>
 /// <remarks>If <paramref name="constraint"/> is <c>null</c> this method returns the same value as <see cref="OneDimEquationSolver.Create()"/>.</remarks>
 public abstract IOneDimEquationSolverAlgorithm Create(IConstraint constraint);