示例#1
0
        /// <summary>
        /// Try to call CompareTo on 2 objects - do type conversion if necessary
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="other"></param>
        /// <param name="throwOnUncomparable">Throw an exception if the objects can't be compared?</param>
        /// <returns>null if only one arg is null, or if objects aren't comparable. Else the value of obj.CompareTo(other)</returns>
        public static int? LazyCompare(this object obj, object other, bool throwOnUncomparable = false)
        {
            // Handle nulls
            if (obj == null && other == null)
                return 0;

            if (other == null || obj == null)
                return null;

            var typeObj = obj.GetType();
            var typeOther = other.GetType();

            // This is a bit involved.
            // We want to find an implementation of IComparable on one of the objects that we can use to
            // do the comparison. We'll take anything we can get, but we'd prefer to NOT use string.CompareTo
            // if possible - everything can be converted to string, but not always in a meaningful way, so that
            // means that doing a string compare on the objects is not ideal.
            if (typeObj == typeOther && obj is IComparable)
                return (obj as IComparable).CompareTo(other);
            else if (!(obj is string) && obj is IComparable && other.CanConvertTo(typeObj))
                return (obj as IComparable).CompareTo(other.ConvertTo(typeObj));
            else if (!(other is string) && other is IComparable && obj.CanConvertTo(typeOther))
                return -1 * (other as IComparable).CompareTo(obj.ConvertTo(typeOther));
            else if (obj is IComparable && other.CanConvertTo(typeObj))
                return (obj as IComparable).CompareTo(other.ConvertTo(typeObj));
            else if (other is IComparable && obj.CanConvertTo(typeOther))
                return -1 * (other as IComparable).CompareTo(obj.ConvertTo(typeOther));

            if (throwOnUncomparable)
                throw new InvalidOperationException("Could not compare the two objects: " + obj + " and " + other);

            return null;
        }
        public static DeploymentDto ToDto(this Deployment_Latest.ReducedResult from, Environment environment)
        {
            var to = from.ConvertTo<DeploymentDto>();
            to.Environment = environment.ToDto();

            return to;
        }
        public static DeploymentDto ToDto(this Deployment from, Environment environment)
        {
            var to = from.ConvertTo<DeploymentDto>();
            to.Environment = environment.ToDto();
            to.Package = from.Package.ToDto();

            //var to = from.ConvertTo<MyDto>();
            //to.Items = from.Items.ConvertAll(x => x.ToDto());
            //to.CalculatedProperty = Calculate(from.Seed);
            return to;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="quantity"></param>
        /// <returns></returns>
        public static TimeSpan ToTimeSpan(this IQuantity quantity)
        {
            quantity.VerifyNotNull().VerifyTimeQuantity();

            var dimension = quantity.Dimensions.SingleOrDefault();

            // ReSharper disable once PossibleNullReferenceException
            if (dimension.Equals(T.Microsecond))
            {
                var millisecondQty = quantity.ConvertTo(T.Millisecond);
                millisecondQty.Value = Math.Min(millisecondQty.Value, TimeSpan.MaxValue.TotalMilliseconds - 1);
                millisecondQty.Value = Math.Max(millisecondQty.Value, TimeSpan.MinValue.TotalMilliseconds + 1);
                return TimeSpan.FromMilliseconds(millisecondQty.Value);
            }

            if (dimension.Equals(T.Millisecond))
                return TimeSpan.FromMilliseconds(quantity.Value);

            if (dimension.Equals(T.Second))
                return TimeSpan.FromSeconds(quantity.Value);

            if (dimension.Equals(T.Minute))
                return TimeSpan.FromMinutes(quantity.Value);

            if (dimension.Equals(T.Hour))
                return TimeSpan.FromHours(quantity.Value);

            if (dimension.Equals(T.Day))
                return TimeSpan.FromDays(quantity.Value);

            // ReSharper disable once ConvertIfStatementToReturnStatement
            if (dimension.Equals(T.Week))
                return TimeSpan.FromDays(quantity.ConvertTo(T.Day).Value);

            return TimeSpan.Zero;
        }
        public static bool LazyEq(this object obj, object other)
        {
            // Handle nulls
            if (obj == null)
                return (other == null);

            if (other == null)
                return false;

            var typeObj = obj.GetType();
            var typeOther = other.GetType();

            if (typeObj == typeOther)
                return obj.Eq(other);

            if (obj.CanConvertTo(typeOther))
                return obj.ConvertTo(typeOther).Eq(other);

            if (other.CanConvertTo(typeObj))
                return obj.Eq(other.ConvertTo(typeObj));

            throw new InvalidOperationException("Could not compare the two objects: " + obj + " and " + other);
        }
示例#6
0
 public static int? GetIntegerInParenthesis(this string source)
 {
     if (source != null)
     {
         Regex numberFinder = new Regex(@"(?:\()(?<number>\d+)(?:\))");
         Match m = numberFinder.Match(source);
         if (m.Success && m.Groups["number"].Success)
         {
             return m.Groups["number"].Captures[0].Value.ConvertTo<int?>();
         }
         else if (Regex.IsMatch(source, @"^\d+$"))
         {
             return source.ConvertTo<int?>();
         }
     }
     return null;
 }
        //private static bool IsDegree(this IQuantity angle, double expectedAngle)
        //{
        //    angle.VerifyAngular();
        //    // TODO: might be better if we had an actual IEquatable<IQuantiy> here ...
        //    return angle.ConvertTo(UsTheta.Degree).Value.Equals(expectedAngle);
        //}
        private static IQuantity CalculateDimensionless(this IQuantity angle, Func<double, double> trigonometry)
        {
            angle.VerifyAngular();

            var theta = angle.ConvertTo(SiTheta.Radian);

            var result = new Quantity(trigonometry(theta.Value));

            return result;
        }
        /// <summary>
        /// Returns the tangent of the specified <paramref name="angle"/>.
        /// </summary>
        /// <param name="angle"></param>
        /// <returns></returns>
        /// <see cref="SiTheta.Radian"/>
        /// <see cref="UsTheta.Degree"/>
        /// <a href="!:http://msdn.microsoft.com/en-us/library/system.math.tan.aspx" />
        /// <a href="!:http://www.quora.com/Is-tan-90%C2%B0-equal-to-infinity" />
        public static IQuantity Tan(this IQuantity angle)
        {
            /* These are a couple of corner cases that the Math library does not take into
             * account, or returned an "undefined" number, which is technically incorrect.
             * http://www.uwgb.edu/dutchs/structge/sl01.htm */

            const double max = 360d;

            angle.VerifyAngular();

            var angleDegreesValue = angle.ConvertTo(UsTheta.Degree).Value;

            if ((angleDegreesValue%max).Equals(90d))
                return new Quantity(double.PositiveInfinity);

            if ((angleDegreesValue%max).Equals(270d))
                return new Quantity(double.NegativeInfinity);

            return CalculateDimensionless(angle, Math.Tan);
        }
        /// <summary>
        /// Returns the cotangent of the specified <paramref name="angle"/>.
        /// </summary>
        /// <param name="angle"></param>
        /// <returns></returns>
        /// <see cref="SiTheta.Radian"/>
        /// <see cref="UsTheta.Degree"/>
        public static IQuantity Cot(this IQuantity angle)
        {
            const double max = 360d;

            angle.VerifyAngular();

            /* The operators are still a little bit of a work in progress, handling what to do
             * about converting to/from base approaching the core calculation. For purposes of
             * trig functions, however, we actually sometimes want these in terms of degrees,
             * not Radians, for purposes of evaluation. */

            var angleDegreesValue = angle.ConvertTo(UsTheta.Degree).Value;

            // This is likely not wholely correct, but it is close enough.
            if ((angleDegreesValue%max).Equals(0d))
                return new Quantity(double.PositiveInfinity);

            if ((angleDegreesValue%max).Equals(180d))
                return new Quantity(double.NegativeInfinity);

            var sine = CalculateDimensionless(angle, Math.Sin);
            var cosine = (Quantity) CalculateDimensionless(angle, Math.Cos);

            return cosine/sine;
        }
示例#10
0
 public static float ConvertTo(this Unit from, Unit to, float value)
 {
     if (from == to)
         return value;
     if (from == Unit.Gram)
         return value / to.InGrams();
     if (to == Unit.Gram)
         return value * from.InGrams();
     var valueInGrams = from.ConvertTo(Unit.Gram, value);
     return Unit.Gram.ConvertTo(to, valueInGrams);
 }
示例#11
0
 /// <summary>
 /// Converts a <see cref="Bitmap"/> image to the specified <see cref="ImageFormat"/>.
 /// </summary>
 /// <param name="originalImage">The <see cref="Bitmap"/> image to be converted.</param>
 /// <param name="newFormat">The new <see cref="ImageFormat"/> of the image.</param>
 /// <returns>A <see cref="Bitmap"/> instance.</returns>
 /// <example>
 /// This sample shows how to convert the format of an image:
 /// <code>
 /// using System;
 /// using System.Drawing;
 /// using System.Drawing.Imaging;
 /// using TVA.Drawing;
 ///
 /// class Program
 /// {
 ///     static void Main(string[] args)
 ///     {
 ///         // Load the original image.
 ///         Bitmap original = (Bitmap)Bitmap.FromFile("Original.jpg");
 ///         // Convert the original image.
 ///         Bitmap originalGif = original.ConvertTo(ImageFormat.Gif);
 ///         // Save the converted image to file.
 ///         originalGif.Save("OriginalGif.gif");
 ///
 ///         // Clean-up.
 ///         original.Dispose();
 ///         originalGif.Dispose();
 ///
 ///         Console.ReadLine();
 ///     }
 /// }
 /// </code>
 /// </example>
 public static Bitmap ConvertTo(this Bitmap originalImage, ImageFormat newFormat)
 {
     return originalImage.ConvertTo(newFormat, false);
 }
 public static DisplayResult ToDisplayResult(this TestResult from)
 {
     var to = from.ConvertTo<DisplayResult>();
     to.Host = from.Hostname;
     return to;
 }
		//Don't change the name or the signature of this, it's used by XamlC
		public static object ConvertTo(this object value, Type toType, Type convertertype, IServiceProvider serviceProvider)
		{
			if (convertertype == null)
				return value.ConvertTo(toType, (Func<object>)null, serviceProvider);
			Func<object> getConverter = () => Activator.CreateInstance(convertertype);
			;
			return value.ConvertTo(toType, getConverter, serviceProvider);
		}
        public static PackageDto ToDto(this Package from)
        {
            var to = from.ConvertTo<PackageDto>();

            return to;
        }
        public static EnvironmentDto ToDto(this Environment from)
        {
            var to = from.ConvertTo<EnvironmentDto>();

            return to;
        }
 public static object ConvertTo(this ITypeConverter converter, object value, Type to)
 {
     return converter.ConvertTo(CultureInfo.InvariantCulture, null, value, to);
 }
 public static TeamView ToViewModel(this Team team)
 {
     return team.ConvertTo<TeamView>();
 }