예제 #1
0
		internal static int Compare (IComparable o1, IComparable o2, bool caseSensitive)
		{
			//TODO: turn this "conversion pipeline" into something nicer

			try {
				if (o1 is string && Numeric.IsNumeric (o2))
					o1 = (IComparable) Convert.ChangeType (o1, o2.GetType ());
				else if (o2 is string && Numeric.IsNumeric (o1))
					o2 = (IComparable) Convert.ChangeType (o2, o1.GetType ());
				else if (o1 is string && o2 is Guid)
					o2 = o2.ToString ();
				else if (o2 is string && o1 is Guid)
					o1 = o1.ToString ();
			} catch (FormatException) {
				throw new EvaluateException (String.Format ("Cannot perform compare operation on {0} and {1}.", o1.GetType(), o2.GetType()));
			}

			if (o1 is string && o2 is string && !caseSensitive) {
				o1 = ((string)o1).ToLower();
				o2 = ((string)o2).ToLower();
			}
			
			if (o1.GetType () != o2.GetType ())
				o2 = (IComparable)Convert.ChangeType (o2, o1.GetType ());

			return o1.CompareTo (o2);
		}
예제 #2
0
        internal static int Compare(IComparable o1, IComparable o2, bool caseSensitive)
        {
            //TODO: turn this "conversion pipeline" into something nicer

            try {
                if (o1 is string && Numeric.IsNumeric(o2))
                {
                    o1 = (IComparable)Convert.ChangeType(o1, o2.GetType());
                }
                else if (o2 is string && Numeric.IsNumeric(o1))
                {
                    o2 = (IComparable)Convert.ChangeType(o2, o1.GetType());
                }
                else if (o1 is string && o2 is Guid)
                {
                    o2 = o2.ToString();
                }
                else if (o2 is string && o1 is Guid)
                {
                    o1 = o1.ToString();
                }
            } catch (FormatException) {
                throw new EvaluateException(String.Format("Cannot perform compare operation on {0} and {1}.", o1.GetType(), o2.GetType()));
            }

            if (o1 is string && o2 is string)
            {
                o1 = ((string)o1).TrimEnd(IgnoredTrailingChars);
                o2 = ((string)o2).TrimEnd(IgnoredTrailingChars);
                if (!caseSensitive)
                {
                    o1 = ((string)o1).ToLower();
                    o2 = ((string)o2).ToLower();
                }
            }

            if (o1 is DateTime && o2 is string && Thread.CurrentThread.CurrentCulture != CultureInfo.InvariantCulture)
            {
                // DateTime is always CultureInfo.InvariantCulture
                o2 = (IComparable)DateTime.Parse((string)o2, CultureInfo.InvariantCulture);
            }
            else if (o2 is DateTime && o1 is string &&
                     Thread.CurrentThread.CurrentCulture != CultureInfo.InvariantCulture)
            {
                // DateTime is always CultureInfo.InvariantCulture
                o1 = (IComparable)DateTime.Parse((string)o1, CultureInfo.InvariantCulture);
            }
            else if (o2 is DateTime && o1 is string && Thread.CurrentThread.CurrentCulture != CultureInfo.InvariantCulture)
            {
                // DateTime is always CultureInfo.InvariantCulture
                o1 = (IComparable)DateTime.Parse((string)o1, CultureInfo.InvariantCulture);
            }

            if (o1.GetType() != o2.GetType())
            {
                o2 = (IComparable)Convert.ChangeType(o2, o1.GetType());
            }

            return(o1.CompareTo(o2));
        }
        private bool CompareOperands(ASTNodeType op, IComparable lhs, IComparable rhs)
        {
            if (lhs.GetType() != rhs.GetType())
            {
                // Different types. Try to convert one to match the other.

                if (rhs is double)
                {
                    // Special case for rhs doubles because we don't want to lose precision.
                    lhs = (double)lhs;
                }
                else if (rhs is bool)
                {
                    // Special case for rhs bools because we want to down-convert the lhs.
                    var tmp = Convert.ChangeType(lhs, typeof(bool));
                    lhs = (IComparable)tmp;
                }
                else
                {
                    var tmp = Convert.ChangeType(rhs, lhs.GetType());
                    rhs = (IComparable)tmp;
                }
            }

            try
            {
                // Evaluate the whole expression
                switch (op)
                {
                case ASTNodeType.EQUAL:
                    return(lhs.CompareTo(rhs) == 0);

                case ASTNodeType.NOT_EQUAL:
                    return(lhs.CompareTo(rhs) != 0);

                case ASTNodeType.LESS_THAN:
                    return(lhs.CompareTo(rhs) < 0);

                case ASTNodeType.LESS_THAN_OR_EQUAL:
                    return(lhs.CompareTo(rhs) <= 0);

                case ASTNodeType.GREATER_THAN:
                    return(lhs.CompareTo(rhs) > 0);

                case ASTNodeType.GREATER_THAN_OR_EQUAL:
                    return(lhs.CompareTo(rhs) >= 0);
                }
            }
            catch (ArgumentException e)
            {
                throw new RunTimeError(null, e.Message);
            }

            throw new RunTimeError(null, "Unknown operator in expression");
        }
예제 #4
0
        private static bool ParseCompare(object[] values, IEnumerator <Token <ExpTokens> > tokens, CultureInfo culture)
        {
            IComparable val1 = ParseNot(values, tokens, culture);
            bool?       ret  = null;

            while (tokens.Current.Symbol >= ExpTokens.Op_Equals && tokens.Current.Symbol <= ExpTokens.Op_GreaterThanEquals)
            {
                var cmptoken = tokens.Current;

                tokens.MoveNext();
                IComparable val2 = ParseNot(values, tokens, culture);

                if (val2.GetType() != val1.GetType())
                {
                    val2 = (IComparable)System.Convert.ChangeType(val2, val1.GetType());
                }

                int cmp = val1.CompareTo(val2);

                switch (cmptoken.Symbol)
                {
                case ExpTokens.Op_Equals:
                    ret = (cmp == 0);
                    break;

                case ExpTokens.Op_NotEquals:
                    ret = (cmp != 0);
                    break;

                case ExpTokens.Op_LessThan:
                    ret = (cmp < 0);
                    break;

                case ExpTokens.Op_GreaterThan:
                    ret = (cmp > 0);
                    break;

                case ExpTokens.Op_LessThanEquals:
                    ret = (cmp <= 0);
                    break;

                case ExpTokens.Op_GreaterThanEquals:
                    ret = (cmp >= 0);
                    break;
                }
                val1 = ret.Value;
            }

            if (!ret.HasValue)
            {
                ret = System.Convert.ToBoolean(val1, culture);
            }

            return(ret.Value);
        }
예제 #5
0
 protected static void CheckPropertyType(String myVertexTypeName,
                                         IComparable myValue,
                                         IPropertyDefinition propertyDef)
 {
     //Assign safty should be suffice.
     if (!propertyDef.BaseType.IsAssignableFrom(myValue.GetType()) && !propertyDef.BaseType.IsSubclassOf(typeof(AUserdefinedDataType)))
     {
         throw new PropertyHasWrongTypeException(myVertexTypeName,
                                                 propertyDef.Name,
                                                 propertyDef.BaseType.Name,
                                                 myValue.GetType().Name);
     }
 }
        // @SuppressWarnings("unchecked")
        public int compare(object o1, object o2)
        {
            logger.debug("compare({},{})", o1, o2);
            if (o1 == null && o2 == null)
            {
                return(0);
            }
            if (o1 == null)
            {
                return(-1);
            }
            if (o2 == null)
            {
                return(1);
            }
            if (o1 is CsNumber && o1 is CsNumber)
            {
                return(NumberComparator.getComparator().Compare(o1, o2));
            }
            if (TimeComparator.isTimeBased(o1) && TimeComparator.isTimeBased(o2))
            {
                return(TimeComparator.getComparator().Compare(o1, o2));
            }
            if (BooleanComparator.isBoolean(o1) && BooleanComparator.isBoolean(o2))
            {
                return(BooleanComparator.getComparator().Compare(o1, o2));
            }
            if (o1 is IComparable && o2 is IComparable)
            {
                //@SuppressWarnings("rawtypes")

                IComparable c1 = (IComparable)o1;
                //@SuppressWarnings("rawtypes")

                IComparable c2 = (IComparable)o2;
                // We can only count on using the comparable interface if o1 and o2
                // are within of the same class or if one is a subclass of the other
                if (c1.GetType().IsAssignableFrom(c2.GetType()))
                {
                    return(c1.CompareTo(o2));
                }
                if (o2.GetType().IsAssignableFrom(c1.GetType()))
                {
                    return(-1 * c2.CompareTo(o1));
                }
            }
            logger.debug("Using ToStringComparator because no apparent better comparison method could be found");
            return(ToStringComparator.getComparator().Compare(o1, o2));
        } // compare()
예제 #7
0
 internal static void ValidateRangeValidator(IComparable lowerBound, RangeBoundaryType lowerBoundaryType, IComparable upperBound, RangeBoundaryType upperBoundaryType)
 {
     if (lowerBoundaryType != 0 && lowerBound == null)
     {
         throw new ArgumentNullException("lowerBound");
     }
     if (upperBoundaryType != 0 && upperBound == null)
     {
         throw new ArgumentNullException("upperBound");
     }
     if (lowerBoundaryType == RangeBoundaryType.Ignore && upperBoundaryType == RangeBoundaryType.Ignore)
     {
         throw new ArgumentException(Resources.ExceptionCannotIgnoreBothBoundariesInRange, "lowerBound");
     }
     if (lowerBound == null)
     {
         return;
     }
     if (upperBound == null)
     {
         return;
     }
     if (lowerBound.GetType() == upperBound.GetType())
     {
         return;
     }
     throw new ArgumentException(Resources.ExceptionTypeOfBoundsMustMatch, "upperBound");
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="BetweenValidator"/> class.
        /// </summary>
        /// <param name="from">From.</param>
        /// <param name="to">The automatic.</param>
        public BetweenValidator(IComparable @from, IComparable to)
        {
            if (@from == null)
            {
                throw new ArgumentNullException("from");
            }

            if (to == null)
            {
                throw new ArgumentNullException("to");
            }

            if (!to.GetType().IsInstanceOfType(@from))
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "'To' value should be type of '{0}'", @from.GetType().FullName));
            }

            if (to.CompareTo(@from) == -1)
            {
                throw new ArgumentOutOfRangeException("to", "'To' should be larger than 'from'.");
            }

            m_From = @from;
            m_To = to;

            m_ValidatorProperties = new ValidatorProperties
                                        {
                                            { Constants.ValidationMessageParameterNames.FROM_VALUE, FromValue },
                                            { Constants.ValidationMessageParameterNames.TO_VALUE, ToValue }
                                        };
        }
예제 #9
0
        public virtual bool Validate(DataRow dataRow, int columnIndex)
        {
            IComparable comparable = dataRow[columnIndex] as IComparable;

            if (this.Operand == null || comparable == null)
            {
                return(false);
            }
            if (comparable.GetType() != this.Operand.GetType())
            {
                if (OperationComparer.IsNumeric(comparable) && OperationComparer.IsNumeric(this.Operand))
                {
                    return(true);
                }
                SharedObject.Instance.Output(SharedObject.enOutputType.Error, "FilterTypeWarning operand:" + this.Operand.GetType() + "comparable:" + comparable.GetType());
                return(false);
            }
            else
            {
                if (comparable is string)
                {
                    SharedObject.Instance.Output(SharedObject.enOutputType.Error, "FilterTypeWarning operand:" + this.Operand.GetType() + "comparable:" + comparable.GetType());
                    return(false);
                }
                return(true);
            }
        }
예제 #10
0
        /// <summary>
        /// Creates a Sql In clause for filters
        /// </summary>
        /// <typeparam name="listType">
        /// Type of the items in the list of values
        /// </typeparam>
        /// <param name="valuesList">
        /// List of values for create the In sentence
        /// </param>
        /// <returns>
        /// Sql In clause for filters
        /// </returns>
        protected virtual Command InClause(List <IComparable> valuesList)
        {
            //Initializing In clause
            Command command = new Command();

            command.Script = " IN (";
            string randomPrefix = new Random().Next(0, 999999).ToString();

            //Crossing the elements of the list
            for (int i = 0; i < valuesList.Count; i++)
            {
                IComparable item      = valuesList[i];
                string      paramName = randomPrefix + "_" + i;

                command.Script += paramName + ", ";
                command.Parameters.Add(new CommandParameter()
                {
                    Name = paramName, DbType = DbTypeMapper.Parse(item.GetType()), Value = item
                });
            }

            //Removing last ", "
            command.Script = command.Script.TrimEnd(',', ' ');

            //Closing the clause
            command.Script += ")";

            //Returning the filter
            return(command);
        }
예제 #11
0
        protected override string OverrideError(object value)
        {
            if (value == null)
            {
                return(null);
            }

            IComparable val = (IComparable)value;

            if (number.GetType() != value.GetType())
            {
                number = (IComparable)Convert.ChangeType(number, value.GetType()); // made just once
            }
            bool ok = (ComparisonType == ComparisonType.EqualTo && val.CompareTo(number) == 0) ||
                      (ComparisonType == ComparisonType.DistinctTo && val.CompareTo(number) != 0) ||
                      (ComparisonType == ComparisonType.GreaterThan && val.CompareTo(number) > 0) ||
                      (ComparisonType == ComparisonType.GreaterThanOrEqualTo && val.CompareTo(number) >= 0) ||
                      (ComparisonType == ComparisonType.LessThan && val.CompareTo(number) < 0) ||
                      (ComparisonType == ComparisonType.LessThanOrEqualTo && val.CompareTo(number) <= 0);

            if (ok)
            {
                return(null);
            }

            return(ValidationMessage._0ShouldBe12.NiceToString().FormatWith("{0}", ComparisonType.NiceToString(), number.ToString()));
        }
예제 #12
0
 /// <summary>
 /// Converts the reference value to a <see cref="Enum"/> of type <typeparamref name="T"/>.
 /// </summary>
 /// <typeparam name="T">The enum type.</typeparam>
 /// <param name="value">The value of enum.</param>
 /// <returns>The enum value.</returns>
 public static T ToEnum <T>(this IComparable value) where T : struct, IComparable, IFormattable, IConvertible
 {
     if (value.GetType() == typeof(string))
     {
         return(Enum.TryParse(value.ToString(), out T result)
             ? result
             : default);
예제 #13
0
        static void Main(string[] args)
        {
            Point p1 = new Point(10, 10);
            Point p2 = new Point(20, 20);

            // p1 не пакуется тк этот метод перекрыт(вызывает невиртуально)
            Console.WriteLine(p1.ToString());

            // p1 пакуется тк getType метод базового класса (нужна ссылка this)
            Console.WriteLine(p1.GetType()); // "Point"

            // p1 не пакуется тк в структуре есть метод compareTo требующий аргумент Point(те не метод реализованный от интерфейса)
            // p2 не пакуется тк требуется аргумент как раз типа Point
            Console.WriteLine(p1.CompareTo(p2));

            // p1 пакуется, тк Интерфейсы - это ссылочный тип
            IComparable c = p1;

            Console.WriteLine(c.GetType()); // "Point"

            //p1 не пакуется тк вызвана версия реализованная от интерфейса
            //c не пкауется тк это и есть ссылочный тип
            Console.WriteLine(p1.CompareTo(c));

            // c - ссылочный тип
            // p2 пакуется тк c интерфейс и вызывает версию реализованную от интерфейса (compareTo(object o))
            Console.WriteLine(c.CompareTo(p2));

            // Распаковка C из кучи и копирование полей в p2
            p2 = (Point)c;
        }
예제 #14
0
        static void Main(string[] args)
        {
            // Два инстанца в стеке
            Point p1 = new Point(10, 10);
            Point p2 = new Point(20, 20);

            // Нет boxing, потому что метод виртуальный (переопределен нами)
            Console.WriteLine(p1.ToString()); // "(10, 10)"

            // Есть boxing, потому что GetType - невиртуальный метод от родителя
            Console.WriteLine(p1.GetType());// "Point"

            // Нет боксинга для р1 - потому что CompareTo - наш невиртуальный метод
            // Нет боксинга для р2, потому что CompareTo принимает Point
            Console.WriteLine(p1.CompareTo(p2));// "-1"

            // Происходит боксинг, потому что интерфейс - ссылочный тип
            IComparable c = p1;

            Console.WriteLine(c.GetType());// "Point"

            // Нет боксинга для р1
            // Нет для с, потому что вызвался CompareTo(object), а с - уже является ссылкой
            Console.WriteLine(p1.CompareTo(c));//"0"

            // с - уже ссылка, поэтому боксинга нет
            // А для p2 есть боксинг, потому что вызвался CompareTo(object)
            Console.WriteLine(c.CompareTo(p2)); //"-1"

            p2 = (Point)c;                      // с - unboxed, поля копируются в р2

            Console.WriteLine(p2.ToString());   //"(10, 10)"
        }
예제 #15
0
 public override void AssertValidValue(IComparable value)
 {
     if (this.IsValidValue(value) == false)
     {
         throw new ArgumentException("Invalid type for String facet: " + value.GetType().Name);
     }
 }
예제 #16
0
        /// <summary>
        /// Test whether the constraint is satisfied by a given value
        /// </summary>
        /// <param name="actual">The value to be tested</param>
        /// <returns>True for success, false for failure</returns>
        public override bool Matches(object actual)
        {
            Actual = actual;

            if (actual == null)
            {
                return(false);
            }

            Type actualType = actual.GetType();

            if (actualType != _low.GetType() || actualType != _high.GetType())
            {
                return(false);
            }

            int lowCompare = _low.CompareTo(actual);

            if (lowCompare > 0 || !_includeLow && lowCompare == 0)
            {
                return(false);
            }

            int highCompare = _high.CompareTo(actual);

            return(highCompare > 0 || _includeHigh && highCompare == 0);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="BetweenValidator"/> class.
        /// </summary>
        /// <param name="from">From.</param>
        /// <param name="to">The automatic.</param>
        public BetweenValidator(IComparable @from, IComparable to)
        {
            if (@from == null)
            {
                throw new ArgumentNullException("from");
            }

            if (to == null)
            {
                throw new ArgumentNullException("to");
            }

            if (!to.GetType().IsInstanceOfType(@from))
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "'To' value should be type of '{0}'", @from.GetType().FullName));
            }

            if (to.CompareTo(@from) == -1)
            {
                throw new ArgumentOutOfRangeException("to", "'To' should be larger than 'from'.");
            }

            m_From = @from;
            m_To   = to;

            m_ValidatorProperties = new ValidatorProperties
            {
                { Constants.ValidationMessageParameterNames.FROM_VALUE, FromValue },
                { Constants.ValidationMessageParameterNames.TO_VALUE, ToValue }
            };
        }
예제 #18
0
        /// <summary>
        /// Détermine l'égalité entre deux éléments.
        /// </summary>
        /// <param name="left">Opérande de gauche.</param>
        /// <param name="right">Opérande de droite.</param>
        /// <returns><c>true</c> si les éléments sont considérés comme égaux.</returns>
        private bool AreEqual(object left, object right)
        {
            IComparable comparableLeft  = left as IComparable;
            IComparable comparableRight = right as IComparable;

            if (comparableLeft != null && comparableRight != null)
            {
                object rightConverted = null;
                try
                {
                    rightConverted = Convert.ChangeType(comparableRight, comparableLeft.GetType(), CultureInfo.CurrentCulture);
                }
                catch (FormatException) { }
                catch (InvalidCastException) { }

                if (rightConverted == null)
                {
                    return(false);
                }

                return(comparableLeft.CompareTo((IComparable)rightConverted) == 0);
            }

            return(object.Equals(left, right));
        }
예제 #19
0
        public int Compare(object x, object y)
        {
            ListViewItem xi = (ListViewItem)x;
            ListViewItem yi = (ListViewItem)y;

            if (xi.SubItems.Count <= Column)
            {
                throw new ArgumentException("Invalid item for comparer", "x");
            }

            if (yi.SubItems.Count <= Column)
            {
                throw new ArgumentException("Invalid item for comparer", "y");
            }

            IComparable left  = GetComparableItem(xi.SubItems[Column].Text);
            IComparable right = GetComparableItem(yi.SubItems[Column].Text);

            if (left.GetType() != right.GetType())
            {
                left  = left.ToString();
                right = right.ToString();
            }

            if (Ascending)
            {
                return(left.CompareTo(right));
            }
            else
            {
                return(right.CompareTo(left));
            }
        }
예제 #20
0
        /// <summary>
        /// Compara a instancia informadas.
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        private static int Compare(IComparable x, IComparable y)
        {
            if (x is bool && y is int)
            {
                y = (int)y != 0;
            }
            var yIsNull = CacheNull.IsNull(y);
            var xIsNull = CacheNull.IsNull(x);

            if (xIsNull || yIsNull)
            {
                if (!xIsNull && yIsNull)
                {
                    return(1);
                }
                else if (!yIsNull && xIsNull)
                {
                    return(-1);
                }
                return(0);
            }
            if (x is string || y is string)
            {
                return(Culture.StringComparer.Compare(x is string?(string)x: (x != null ? x.ToString() : null), y is string?(string)y: (y != null ? y.ToString() : null)));
            }
            if ((x is int || x is short || x is long) && y != null && y.GetType().IsEnum)
            {
                y = Convert.ToInt32(y);
            }
            return(x.CompareTo(y));
        }
예제 #21
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ArithmeticCriteria"/> class.
        /// </summary>
        /// <param name="fieldName">Name of the field.</param>
        /// <param name="value">The value.</param>
        /// <param name="operand">The operand.</param>
        public ArithmeticCriteria(string fieldName, IComparable value, ArithmeticOperandEnum operand)
            : base(fieldName)
        {
            if (value == null)
            {
                ThrowHelper.ThrowArgumentNullException("value");
            }

            Type valueType = value.GetType();

            if (valueType.IsGenericType && valueType.GetGenericTypeDefinition().Equals(typeof(EntityBaseGenericId <>)))
            {
                dynamic dynValue = value;
                if (dynValue.Id == null)
                {
                    ThrowHelper.ThrowArgumentException(String.Format("Provided entity has not got identifier. Entity type: '{0}'.", valueType.FullName), "value");
                }
                if (fieldName.ToLower().Equals("id"))
                {
                    this.FieldName = fieldName;
                }
                else
                {
                    this.FieldName = fieldName.ToLower().EndsWith(".id") ? fieldName : String.Format("{0}.id", fieldName);
                }
                this.mValue = dynValue.Id;
            }
            else
            {
                this.mValue = value;
            }
            this.mOperand = operand;
        }
예제 #22
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ArithmeticCriteria"/> class.
        /// </summary>
        /// <param name="fieldName">Name of the field.</param>
        /// <param name="value">The value.</param>
        /// <param name="operand">The operand.</param>
        public ArithmeticCriteria(string fieldName, IComparable value, ArithmeticOperandEnum operand)
            : base(fieldName)
        {
            if (value == null)
            {
                ThrowHelper.ThrowArgumentNullException("value");
            }

            Type valueType = value.GetType();
            if (valueType.IsGenericType && valueType.GetGenericTypeDefinition().Equals(typeof(EntityBaseGenericId<>)))
            {
                dynamic dynValue = value;
                if (dynValue.Id == null)
                {
                    ThrowHelper.ThrowArgumentException(String.Format("Provided entity has not got identifier. Entity type: '{0}'.", valueType.FullName), "value");
                }
                if (fieldName.ToLower().Equals("id"))
                {
                    this.FieldName = fieldName;
                }
                else
                {
                    this.FieldName = fieldName.ToLower().EndsWith(".id") ? fieldName : String.Format("{0}.id", fieldName);
                }
                this.mValue = dynValue.Id;
            }
            else
            {
                this.mValue = value;
            }
            this.mOperand = operand;
        }
예제 #23
0
        /// <summary>
        /// Determines the appropriate facet type based upon the Type of a given instance.
        /// </summary>
        /// <remarks>
        /// This method will inspect the given object's type and attempt to match it to the expected Type(s) for each
        /// supported Pivot facet category type. For strings, it will automatically differentiate between the LongString
        /// and String types based upon the actual length of the given text.
        /// </remarks>
        /// <param name="value">the object to use in inferring the facet category type</param>
        /// <returns>the appropriate constant for the type most closely matching the given object</returns>
        /// <exception cref="ArgumentException">
        /// if no suitable type could be determined for the given object
        /// </exception>
        public static PivotFacetType IdentifyType(IComparable value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("Cannot determine the type of a null value");
            }

            if (DateTime.IsValidValue(value))
            {
                return(DateTime);
            }
            if (Link.IsValidValue(value))
            {
                return(Link);
            }
            if (Number.IsValidValue(value))
            {
                return(Number);
            }

            if (String.IsValidValue(value))
            {
                String testString = (String)value;
                if (testString.Length > LongStringThreshold)
                {
                    return(LongString);
                }
                return(String);
            }

            throw new ArgumentException("No facet type matches Type: " + value.GetType().Name);
        }
예제 #24
0
        /// <summary>
        /// IComparable.CompareTo implementation
        /// </summary>
        /// <param name="arg"></param>
        /// <returns></returns>
        public override int CompareTo(object arg)
        {
            int i;

            ComparableValue comparableValue = arg as ComparableValue;

            if (obj.GetType() == comparableValue.obj.GetType())
            {
                i = obj.CompareTo(comparableValue.obj);
            }
            else
            {
                i = obj.GetType().FullName.CompareTo(comparableValue.obj.GetType().FullName);
            }
            return(i);
        }
예제 #25
0
        // Override method for ContainsValue, which accomodates for strings
        // partial matches will return true, case-insensitive
        public override bool ContainsValue(IComparable value)
        {
            if (value.GetType() != typeof(string))
            {
                return(false);
            }

            string val = value.ToString().ToLower();

            for (int i = 0; i < Values.Count; ++i)
            {
                if (((string)Values[i]).ToLower().Contains(val))
                {
                    return(true);
                }
            }

            // Also search through formatted values, as user may search in this format
            // (ie. "lewis, c.s." vs. "C.S. Lewis")
            string[] formattedValues = FormattedValues;
            for (int i = 0; i < formattedValues.Length; ++i)
            {
                if (formattedValues[i].ToLower().Contains(val))
                {
                    return(true);
                }
            }

            return(false);
        }
예제 #26
0
        static bool EvaluateComparable(IComparable leftOperand, ComparisonCondition operatorType, IComparable rightOperand)
        {
            object convertedOperand = null;

            try
            {
                convertedOperand = Convert.ChangeType(rightOperand, leftOperand.GetType(), CultureInfo.CurrentCulture);
            }
            catch (FormatException)
            {
            }
            catch (InvalidCastException)
            {
            }

            if (convertedOperand == null)
            {
                return(operatorType == ComparisonCondition.NotEqual);
            }

            int comparison = leftOperand.CompareTo((IComparable)convertedOperand);

            return(operatorType switch
            {
                ComparisonCondition.Equal => comparison == 0,
                ComparisonCondition.NotEqual => comparison != 0,
                ComparisonCondition.LessThan => comparison < 0,
                ComparisonCondition.LessThanOrEqual => comparison <= 0,
                ComparisonCondition.GreaterThan => comparison > 0,
                ComparisonCondition.GreaterThanOrEqual => comparison >= 0,
                _ => false,
            });
예제 #27
0
        public static Term GetTerm(IComparable /*?*/ value)
        {
            // Case 1: null value
            if (value == null)
            {
                return(nullSymbol);
            }

            // Case 2: Literal value (int, string, bool, etc.)
            Type t = value.GetType();

            if (GetLiteralTypes().ContainsKey(t))
            {
                return(new Literal(value));
            }

            // Case 3: enum value-- encode as sort applied to string arg
            else if (value is System.Enum)
            {
                Symbol sort = TypeSort(value.GetType());

                // to do: also handle Flags attribute for enums by encoding value as a set of strings
                string label = value.ToString();
                return(new CompoundTerm(sort, new Literal(label)));
            }

            // Case 4: Term value-- return quoted term
            else if (value is Term)
            {
                return(new CompoundTerm(quoteSymbol, (Term)value));
            }

            // Case 5: value is of type IAbstractValue-- invoke property to get term
            else
            {
                IAbstractValue av = value as IAbstractValue;
                if (av != null)
                {
                    return(av.AsTerm);
                }
                else
                {
                    // Case 6: fail
                    throw new ArgumentException("AbstractValue.GetTerm(): No term can be produced for value " + value.ToString() + ". Type must implement IAbstractValue interface.");
                }
            }
        }
예제 #28
0
 /// <summary>
 /// Set ImplicitDefault to the default value of <paramref name="explicitDefault"/>'s type,
 /// and ExplicitDefault to <paramref name="explicitDefault"/>.
 /// </summary>
 /// <param name="explicitDefault"></param>
 /// <param name="storeInBase"></param>
 /// <param name="nativeToString"></param>
 internal ValueDescription(IComparable explicitDefault, bool storeInBase = true, ValueNativeToString nativeToString = null)
 {
     ImplicitDefault = GetImplicitDefault(explicitDefault.GetType());
     ExplicitDefault = explicitDefault;
     DefaultsDiffer  = (ImplicitDefault.CompareTo(ExplicitDefault) != 0);
     StoreInBase     = storeInBase;
     NativeToString  = nativeToString;
 }
 /// <summary>
 /// Set ImplicitDefault to the default value of <paramref name="explicitDefault"/>'s type,
 /// and ExplicitDefault to <paramref name="explicitDefault"/>.
 /// </summary>
 /// <param name="explicitDefault"></param>
 /// <param name="storeInBase"></param>
 /// <param name="nativeToString"></param>
 internal ValueDescription(IComparable explicitDefault, bool storeInBase = true, ValueNativeToString nativeToString = null)
 {
     ImplicitDefault = GetImplicitDefault(explicitDefault.GetType());
     ExplicitDefault = explicitDefault;
     DefaultsDiffer = (ImplicitDefault.CompareTo(ExplicitDefault) != 0);
     StoreInBase = storeInBase;
     NativeToString = nativeToString;
 }
예제 #30
0
        static void Main(string[] args)
        {
            SomeRef r1 = new SomeRef(); //在堆上分配
            SomeVal v1 = new SomeVal(); //在栈上分配

            r1.x = 5;                   //提领指针
            v1.x = 5;                   //在栈上修改

            SomeRef r2 = r1;            //只复制了引用
            SomeVal v2 = v1;;           //在栈上分配并复制成员

            r1.x = 8;                   //r1,r2都会改变
            v1.x = 8;                   //v1会改变
            Console.WriteLine(r1.x);
            Console.WriteLine(r2.x);
            Console.WriteLine(v1.x);
            Console.WriteLine(v2.x);


            Int32 v = 5;

#if INEFFICIENT
            Console.WriteLine("{0}, {1}, {2}", v, v, v); //会造成3次装箱,浪费内存
#else
            Object o = v;                                //手动装箱
            Console.WriteLine("{0},{1},{2}", o, o, o);   //不发生装箱
#endif


            //在栈上创建两个Point实例
            Point p1 = new Point(10, 10);
            Point p2 = new Point(20, 20);
            //调用ToString()虚方法,不装箱
            Console.WriteLine(p1.ToString());

            //调用CompareTo,不装箱p1
            Console.WriteLine(p1.CompareTo(p2));
            //调用GetType,装箱
            Console.WriteLine(p1.GetType());
            //装箱到C中
            IComparable c = p1;
            Console.WriteLine(c.GetType());
            //调用CompareTo不装箱p1
            Console.WriteLine(p1.CompareTo(o));
            //这里要装箱p2
            Console.WriteLine(c.CompareTo(p2));
            p2 = (Point)c; //拆箱


            uint invalid = unchecked ((uint)-1); //不会造成异常
            Byte b       = 100;
            b = checked ((Byte)(b + 200));       //抛出溢出异常

            checked
            {
                //对内部所有的内容进行检查
            }
        }
예제 #31
0
        private static bool EvaluateComparable(ComparisonConditionType comparisonType, IComparable leftOperand, IComparable rightOperand)
        {
            object right;

            try
            {
                right = Convert.ChangeType(rightOperand, leftOperand.GetType(), CultureInfo.CurrentCulture);
            }
            catch (Exception)
            {
                return(false);
            }

            if (null == right)
            {
                return(ComparisonConditionType.NotEqual == comparisonType);
            }

            var op = leftOperand.CompareTo(right);

            switch (comparisonType)
            {
            case ComparisonConditionType.Equal:
            {
                return(0 == op);
            }

            case ComparisonConditionType.NotEqual:
            {
                return(0 != op);
            }

            case ComparisonConditionType.LessThan:
            {
                return(0 > op);
            }

            case ComparisonConditionType.LessThanOrEqual:
            {
                return(0 >= op);
            }

            case ComparisonConditionType.GreaterThan:
            {
                return(0 < op);
            }

            case ComparisonConditionType.GreaterThanOrEqual:
            {
                return(0 <= op);
            }

            default:
            {
                return(false);
            }
            }
        }
예제 #32
0
        protected int Compare(IComparable lhs, IComparable rhs)
        {
            if (lhs == null || rhs == null)
            {
                return(lhs?.CompareTo(rhs) ?? (-1 * rhs?.CompareTo(lhs) ?? 0));
            }

            if (TypeConverter.IsNumeric(lhs) && TypeConverter.IsNumeric(rhs))
            {
                lhs = (decimal)TypeConverter.To(lhs, typeof(decimal));
                rhs = (decimal)TypeConverter.To(rhs, typeof(decimal));
            }
            if (!Equals(lhs.GetType(), rhs.GetType()))
            {
                throw ComparisionException.UnComparable(lhs.GetType(), rhs.GetType()).Decorate(Token);
            }
            return(lhs.CompareTo(rhs));
        }
예제 #33
0
        /// <summary>
        /// Returns an array of attributes of the specified type applied to the given enum value.
        /// </summary>
        public static T[] GetAttributes <T>(this IComparable input) where T : Attribute
        {
            var attributes = (T[])input.GetType()
                             .GetTypeInfo()
                             .GetDeclaredField(input.ToString())
                             .GetCustomAttributes(typeof(T), false);

            return(attributes);
        }
예제 #34
0
        protected void setLimits(IComparable min, IComparable max)
        {
            if (min != null && max != null && !min.GetType().Equals((max.GetType())))
            {
                Logger.getLogger(Log.DATATABLE).error("'min' and 'max' Limits Validator parameters should be the same type");
            }

            this.min = min;
            this.max = max;
        }
예제 #35
0
파일: Comparison.cs 프로젝트: nlhepler/mono
		internal static int Compare (IComparable o1, IComparable o2, bool caseSensitive)
		{
			//TODO: turn this "conversion pipeline" into something nicer

			try {
				if (o1 is string && Numeric.IsNumeric (o2))
					o1 = (IComparable) Convert.ChangeType (o1, o2.GetType ());
				else if (o2 is string && Numeric.IsNumeric (o1))
					o2 = (IComparable) Convert.ChangeType (o2, o1.GetType ());
				else if (o1 is string && o2 is Guid)
					o2 = o2.ToString ();
				else if (o2 is string && o1 is Guid)
					o1 = o1.ToString ();
			} catch (FormatException) {
				throw new EvaluateException (String.Format ("Cannot perform compare operation on {0} and {1}.", o1.GetType(), o2.GetType()));
			}

			if (o1 is string && o2 is string) {
				o1 = ((string) o1).TrimEnd (IgnoredTrailingChars);
				o2 = ((string) o2).TrimEnd (IgnoredTrailingChars);
				if (!caseSensitive) {
					o1 = ((string) o1).ToLower ();
					o2 = ((string) o2).ToLower ();
				}
			}

			if (o1 is DateTime && o2 is string && Thread.CurrentThread.CurrentCulture != CultureInfo.InvariantCulture) {
				// DateTime is always CultureInfo.InvariantCulture
				o2 = (IComparable) DateTime.Parse ((string)o2, CultureInfo.InvariantCulture);
			} else if (o2 is DateTime && o1 is string && 
			           Thread.CurrentThread.CurrentCulture != CultureInfo.InvariantCulture) {
				// DateTime is always CultureInfo.InvariantCulture
                o1 = (IComparable) DateTime.Parse ((string)o1, CultureInfo.InvariantCulture);
			}
			else if (o2 is DateTime && o1 is string && Thread.CurrentThread.CurrentCulture != CultureInfo.InvariantCulture) {
				// DateTime is always CultureInfo.InvariantCulture
				o1 = (IComparable) DateTime.Parse ((string)o1, CultureInfo.InvariantCulture);
			}

			if (o1.GetType () != o2.GetType ())
				o2 = (IComparable)Convert.ChangeType (o2, o1.GetType ());

			return o1.CompareTo (o2);
		}
 internal static void ValidateRangeValidator(IComparable lowerBound, RangeBoundaryType lowerBoundaryType, IComparable upperBound, RangeBoundaryType upperBoundaryType)
 {
     if ((lowerBoundaryType != RangeBoundaryType.Ignore) && (lowerBound == null))
     {
         throw new ArgumentNullException("lowerBound");
     }
     if ((upperBoundaryType != RangeBoundaryType.Ignore) && (upperBound == null))
     {
         throw new ArgumentNullException("upperBound");
     }
     if ((lowerBoundaryType == RangeBoundaryType.Ignore) && (upperBoundaryType == RangeBoundaryType.Ignore))
     {
         throw new ArgumentException(Resources.ExceptionCannotIgnoreBothBoundariesInRange, "lowerBound");
     }
     if (((lowerBound != null) && (upperBound != null)) && (lowerBound.GetType() != upperBound.GetType()))
     {
         throw new ArgumentException(Resources.ExceptionTypeOfBoundsMustMatch, "upperBound");
     }
 }
        /// <summary>
        /// Compares the specified value with from value.
        /// </summary>
        /// <param name="sourceValue">The source value.</param>
        /// <param name="targetValue">The target value.</param>
        /// <param name="result">A value that indicates the relative order of the objects being compared.</param>
        /// <returns><c>true</c> if two values could be compared, otherwise <c>false</c>.</returns>
        public static bool TryCompareTo(IComparable sourceValue, IComparable targetValue, out int result)
        {
            if (sourceValue == null)
            {
                throw new ArgumentNullException("sourceValue");
            }

            if (targetValue == null)
            {
                throw new ArgumentNullException("targetValue");
            }

            if (!sourceValue.GetType().IsInstanceOfType(targetValue))
            {
                result = 0;
                return false;
            }

            result = sourceValue.CompareTo(targetValue);
            return true;
        }
        /// <summary>
        /// Evaluates both operands that implement the IComparable interface.
        /// </summary>
        /// <param name="leftOperand">Left operand from the LeftOperand property.</param>
        /// <param name="operatorType">Operator from Operator property.</param>
        /// <param name="rightOperand">Right operand from the RightOperand property.</param>
        /// <returns>Returns true if the condition is met; otherwise, returns false.</returns>
        private static bool EvaluateComparable(IComparable leftOperand, ComparisonConditionType operatorType, IComparable rightOperand)
        {
            object obj2 = null;
            try
            {
                obj2 = Convert.ChangeType(rightOperand, leftOperand.GetType(), CultureInfo.CurrentCulture);
            }
            catch (FormatException)
            {
            }
            catch (InvalidCastException)
            {
            }
            if (obj2 == null)
            {
                return (operatorType == ComparisonConditionType.NotEqual);
            }
            int num = leftOperand.CompareTo((IComparable)obj2);
            switch (operatorType)
            {
                case ComparisonConditionType.Equal:
                    return (num == 0);

                case ComparisonConditionType.NotEqual:
                    return (num != 0);

                case ComparisonConditionType.LessThan:
                    return (num < 0);

                case ComparisonConditionType.LessThanOrEqual:
                    return (num <= 0);

                case ComparisonConditionType.GreaterThan:
                    return (num > 0);

                case ComparisonConditionType.GreaterThanOrEqual:
                    return (num >= 0);
            }
            return false;
        }
예제 #39
0
 /// <summary>
 /// Determines if this value has an object id (that is, is of type <see cref="LabeledInstance"/>),
 /// or has a subvalue that has an object id (for example, a set of instances).
 /// </summary>
 /// <returns>True if this value has an object id or contains a value with an object id.</returns>
 /// <remarks> This method is invoked by the modeling library when determining whether two states are isomorphic.
 /// </remarks>
 public static bool ContainsObjectIds(IComparable obj)
 {
     if (null == obj) return false;
     Type t = obj.GetType();
     if (GetLiteralTypes().ContainsKey(t) || t.IsEnum) return false;
     IAbstractValue av = obj as IAbstractValue;
     if (null == av) return false;  // maybe throw exception?
     else return av.ContainsObjectIds();
 }
예제 #40
0
 public override void AssertValidValue(IComparable value)
 {
     if (this.IsValidValue(value) == false)
     {
         throw new ArgumentException("Invalid type for String facet: " + value.GetType().Name);
     }
 }
예제 #41
0
        /// <summary>
        /// Determines the appropriate facet type based upon the Type of a given instance.
        /// </summary>
        /// <remarks>
        /// This method will inspect the given object's type and attempt to match it to the expected Type(s) for each
        /// supported Pivot facet category type. For strings, it will automatically differentiate between the LongString
        /// and String types based upon the actual length of the given text.
        /// </remarks>
        /// <param name="value">the object to use in inferring the facet category type</param>
        /// <returns>the appropriate constant for the type most closely matching the given object</returns>
        /// <exception cref="ArgumentException">
        /// if no suitable type could be determined for the given object
        /// </exception>
        public static PivotFacetType IdentifyType(IComparable value)
        {
            if (value == null) throw new ArgumentNullException("Cannot determine the type of a null value");

            if (DateTime.IsValidValue(value)) return DateTime;
            if (Link.IsValidValue(value)) return Link;
            if (Number.IsValidValue(value)) return Number;

            if (String.IsValidValue(value))
            {
                String testString = (String)value;
                if (testString.Length > LongStringThreshold) return LongString;
                return String;
            }

            throw new ArgumentException("No facet type matches Type: " + value.GetType().Name);
        }
 public bool IsCompatible(IComparable value)
 {
     return value.GetType() == typeof (int);
 }
예제 #43
0
 private static object CastOtherValue(string right, IComparable leftValue)
 {
     return Convert.ChangeType(right, leftValue.GetType());
 }
예제 #44
0
        public static Term GetTerm(IComparable/*?*/ value)
        {
            // Case 1: null value
            if (value == null)
                return nullSymbol;

            // Case 2: Literal value (int, string, bool, etc.)
            Type t = value.GetType();
            if (GetLiteralTypes().ContainsKey(t))
                return new Literal(value);

            // Case 3: enum value-- encode as sort applied to string arg
            else if (value is System.Enum)
            {
                Symbol sort = TypeSort(value.GetType());

                // to do: also handle Flags attribute for enums by encoding value as a set of strings
                string label = value.ToString();
                return new CompoundTerm(sort, new Literal(label));
            }

            // Case 4: Term value-- return quoted term
            else if (value is Term)
            {
                return new CompoundTerm(quoteSymbol, (Term)value);
            }

            // Case 5: value is of type IAbstractValue-- invoke property to get term
            else
            {
                IAbstractValue av = value as IAbstractValue;
                if (av != null)
                    return av.AsTerm;
                else
                {
                    // Case 6: fail
                    throw new ArgumentException("AbstractValue.GetTerm(): No term can be produced for value " + value.ToString() + ". Type must implement IAbstractValue interface.");
                }
            }
        }
예제 #45
0
 protected static void CheckPropertyType(String myVertexTypeName,
                                         IComparable myValue,
                                         IPropertyDefinition propertyDef)
 {
     //Assign safty should be suffice.
     if (!propertyDef.BaseType.IsAssignableFrom(myValue.GetType()))
         throw new PropertyHasWrongTypeException(myVertexTypeName,
                                                 propertyDef.Name,
                                                 propertyDef.BaseType.Name,
                                                 myValue.GetType().Name);
 }
예제 #46
0
        protected int Compare(IComparable lhs, IComparable rhs)
        {
            if (lhs == null || rhs == null)
                return lhs?.CompareTo(rhs) ?? (-1*rhs?.CompareTo(lhs) ?? 0);

            if(TypeConverter.IsNumeric(lhs) && TypeConverter.IsNumeric(rhs))
            {
                lhs = (decimal) TypeConverter.To(lhs, typeof(decimal));
                rhs = (decimal) TypeConverter.To(rhs, typeof(decimal));
            }
            if (!Equals(lhs.GetType(), rhs.GetType()))
            {
                throw ComparisionException.UnComparable(lhs.GetType(), rhs.GetType()).Decorate(Token);
            }
            return lhs.CompareTo(rhs);
        }
예제 #47
0
        /// <summary>
        /// Evaluates both operands that implement the IComparable interface.
        /// </summary>
        private static bool EvaluateComparable(IComparable leftOperand, ComparisonConditionType operatorType, IComparable rightOperand)
        {
            object convertedOperand = null;
            try
            {
                convertedOperand = Convert.ChangeType(rightOperand, leftOperand.GetType(), CultureInfo.CurrentCulture);
            }
            catch (FormatException)
            {
                // FormatException: Convert.ChangeType("hello", typeof(double), ...);
            }
            catch (InvalidCastException)
            {
                // InvalidCastException: Convert.ChangeType(4.0d, typeof(Rectangle), ...);
            }

            if (convertedOperand == null)
            {
                return operatorType == ComparisonConditionType.NotEqual;
            }

            int comparison = leftOperand.CompareTo((IComparable)convertedOperand);
            switch (operatorType)
            {
                case ComparisonConditionType.Equal:
                    return comparison == 0;

                case ComparisonConditionType.NotEqual:
                    return comparison != 0;

                case ComparisonConditionType.LessThan:
                    return comparison < 0;

                case ComparisonConditionType.LessThanOrEqual:
                    return comparison <= 0;

                case ComparisonConditionType.GreaterThan:
                    return comparison > 0;

                case ComparisonConditionType.GreaterThanOrEqual:
                    return comparison >= 0;
            }

            return false;
        }