Exemplo n.º 1
0
        private object ParseBoolValue()
        {
            object val = null;

            //If ValueType is bool, we must be serialize mode as in DeserializeMode we would have shortcut out of ParseValue
            //immediately due to PropertyType and ValueType both being bool
            if (ValueType == typeof(bool))
            {
                Type = TypeCategory.Boolean;

                val = Convert.ToInt32((bool)OriginalValue);
            }
            else
            {
                bool boolVal;

                //OriginalValue is implicitly not null because if it were ProcessNonNullable would have escaped
                //to ValueConversionWithNullCheck
                if (TryParseBool(OriginalValue.ToString(), out boolVal))
                {
                    Type = TypeCategory.Boolean;

                    if (Mode == SerializationMode.Deserialize)
                    {
                        val = boolVal;
                    }
                    else
                    {
                        val = Convert.ToInt32(boolVal);
                    }
                }
            }

            return(val);
        }
Exemplo n.º 2
0
 public override string ToString()
 {
     return(string.Format(CultureInfo.InvariantCulture, "error: {0}, value: {1}, process: {2}",
                          Message,
                          OriginalValue != null ? OriginalValue + " (" + OriginalValue.GetType().GetFriendlyTypeName() + ")" : "NULL",
                          Process?.Name ?? "unknown process").Replace("\n", @"\n", StringComparison.InvariantCultureIgnoreCase));
 }
Exemplo n.º 3
0
        private void CalculateCoefficentValues()
        {
            DiceCoefficentValue = OriginalValue.DiceCoefficient(ActualValue);

            var LevenshteinDistanceValue = OriginalValue.LevenshteinDistance(ActualValue);

            LevenshteinDistanceCoefficentValue = 1.0 / (1.0 * (LevenshteinDistanceValue + 0.2));
            LevenshteinDistanceCoefficentValue = LevenshteinDistanceCoefficentValue > .99 ? .99 : LevenshteinDistanceCoefficentValue;

            LongestCommonSubsequenceCoefficentValue = OriginalValue.LongestCommonSubsequence(ActualValue).Item2;
            LongestCommonSubsequenceCoefficentValue = LongestCommonSubsequenceCoefficentValue > .99 ? .99 : LongestCommonSubsequenceCoefficentValue;

            string originalValueDoubleMetaphone = OriginalValue.ToDoubleMetaphone();
            string ActualValueDoubleMetaphone   = ActualValue.ToDoubleMetaphone();

            int matchCount = 0;

            if (originalValueDoubleMetaphone.Length == 4 && ActualValueDoubleMetaphone.Length == 4)
            {
                for (int i = 0; i < originalValueDoubleMetaphone.Length; i++)
                {
                    if (originalValueDoubleMetaphone[i] == ActualValueDoubleMetaphone[i])
                    {
                        matchCount++;
                    }
                }
            }
            DoubleMetaphoneCoefficentValue = matchCount == 0 ? 0.0 : matchCount / 4.0;
            DoubleMetaphoneCoefficentValue = DoubleMetaphoneCoefficentValue == 1.0 ? .90 : DoubleMetaphoneCoefficentValue;

            AverageCoefficentValue = (DiceCoefficentValue + LongestCommonSubsequenceCoefficentValue + LevenshteinDistanceCoefficentValue + DoubleMetaphoneCoefficentValue) / 4.0;
        }
Exemplo n.º 4
0
 private void Print()
 {
     Console.WriteLine(Formatter.GetString(OriginalValue.ToString(), ORIGINAL_TYPE, nameof(Kilograms), Kilograms.ToString("#.######")));
     Console.WriteLine(Formatter.GetString(OriginalValue.ToString(), ORIGINAL_TYPE, nameof(Ounces), Ounces.ToString("#.######")));
     Console.WriteLine(Formatter.GetString(OriginalValue.ToString(), ORIGINAL_TYPE, nameof(Stone), Stone.ToString("#.######")));
     Console.WriteLine();
 }
Exemplo n.º 5
0
 private void Print()
 {
     Console.WriteLine(Formatter.GetString(OriginalValue.ToString(), ORIGINAL_TYPE, nameof(Feet), Feet.ToString("#.######")));
     Console.WriteLine(Formatter.GetString(OriginalValue.ToString(), ORIGINAL_TYPE, nameof(Meters), Meters.ToString("#.######")));
     Console.WriteLine(Formatter.GetString(OriginalValue.ToString(), ORIGINAL_TYPE, nameof(Miles), Miles.ToString("#.######")));
     Console.WriteLine(Formatter.GetString(OriginalValue.ToString(), ORIGINAL_TYPE, nameof(Kilometers), Kilometers));
     Console.WriteLine();
 }
Exemplo n.º 6
0
        public override int GetHashCode()
        {
            var hashCode = 33288;

            hashCode = hashCode * OriginalValue.GetHashCode();
            hashCode = hashCode * StartIndex;
            hashCode = hashCode * EndIndex;
            return(hashCode);
        }
Exemplo n.º 7
0
        private object ParseNumericValue()
        {
            object val = null;

            //If the value is convertable to a double, it is either an int or a double
            if (!string.IsNullOrEmpty(OriginalValue?.ToString()))
            {
                double doubleResult;

                //If the value is a double. Implicitly not null due to !string.IsNullOrEmpty check above
                if (double.TryParse(OriginalValue.ToString(), out doubleResult))
                {
                    //If we're actually looking for an int, see if this double is actually an integer
                    if (PropertyType == typeof(int))
                    {
                        if (Convert.ToInt32(doubleResult) == doubleResult)
                        {
                            //If so, that's cool. When we ToString, we'll get an integer value anyway
                            Type = TypeCategory.Number;

                            if (Mode == SerializationMode.Deserialize)
                            {
                                val = (int)doubleResult;
                            }
                            else
                            {
                                val = doubleResult.ToString(CultureInfo.CurrentCulture);
                            }
                        }

                        //Else: someone tried to assign an actual double to our integer. An exception will be thrown below
                    }
                    else
                    {
                        Type = TypeCategory.Number;

                        if (Mode == SerializationMode.Deserialize)
                        {
                            val = doubleResult;
                        }
                        else
                        {
                            val = doubleResult.ToString(CultureInfo.CurrentCulture);
                        }
                    }
                }

                //If we still don't have a value, since we already verified our value is not null or empty we must have a value of an invalid type
                if (val == null)
                {
                    throw GetInvalidTypeException();
                }
            }

            return(val);
        }
Exemplo n.º 8
0
 public override int GetHashCode()
 {
     unchecked
     {
         var hashCode = (Value != null ? Value.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (OriginalValue != null ? OriginalValue.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (Language != null ? Language.GetHashCode() : 0);
         return(hashCode);
     }
 }
Exemplo n.º 9
0
        /// <summary>
        /// Возвращает значение фильтра в виде целого числа.
        /// </summary>
        /// <returns>Число</returns>
        public int?GetValue()
        {
            int?v = null;

            if (OriginalValue != null)
            {
                int value = 0;
                Int32.TryParse(OriginalValue.ToString(), out value);
                v = value;
            }
            return(v);
        }
Exemplo n.º 10
0
 private void InitModeItems()
 {
     ModeItems = new Caliburn.Micro.BindableCollection <LookupItem>();
     ModeItems.Add(new LookupItem()
     {
         Text = "Auto", Value = ModeOptions.Auto
     });
     ModeItems.Add(new LookupItem()
     {
         Text = "Manual", Value = ModeOptions.Manual
     });
     SelectedMode = OriginalValue.IsNullOrEmpty() ? ModeItems.Last() : ModeItems.First();
 }
Exemplo n.º 11
0
 public override bool Equals(Object obj)
 {
     if ((obj == null) || !this.GetType().Equals(obj.GetType()))
     {
         return(false);
     }
     else
     {
         DateResult dr = (DateResult)obj;
         return(OriginalValue.Equals(dr.OriginalValue) &&
                StartIndex == dr.StartIndex &&
                EndIndex == dr.EndIndex);
     }
 }
Exemplo n.º 12
0
        public void SanitizePropertiesTrimsLeadingAndTraliningSpacesFromValues()
        {
            const string OriginalKey   = "test";
            const string OriginalValue = " name with spaces ";
            var          original      = new Dictionary <string, string> {
                { OriginalKey, OriginalValue }
            };

            original.SanitizeProperties();

            string sanitizedValue = OriginalValue.Trim();

            Assert.Equal(new[] { new KeyValuePair <string, string>(OriginalKey, sanitizedValue) }, original);
        }
Exemplo n.º 13
0
        private object ParseEnumValue <T>() where T : XmlEnumAttribute
        {
            object val = null;

            //If our value type was an enum, get its XmlEnumAttribute immediately
            if (PropertyType == ValueType)
            {
                //We must be serializing as if we were deserializing we would have fast-pathed out of ParseValue
                val = ((Enum)OriginalValue).GetEnumAttribute <T>(true).Name;
            }
            else
            {
                //Otherwise, our value may have been a string. See if any enum members are named after the specified value
                if (Enum.GetNames(PropertyType).Any(x => x.ToLower() == OriginalValue.ToString().ToLower()))
                {
                    var enumValue = ((Enum)Enum.Parse(PropertyType, OriginalValue.ToString(), true));

                    if (Mode == SerializationMode.Deserialize)
                    {
                        val = enumValue;
                    }
                    else
                    {
                        val = enumValue.GetEnumAttribute <T>(true).Name;
                    }
                }
                else
                {
                    //If the enum represents a set of numeric values and our value was an integer,
                    int result;

                    if (PropertyType.GetTypeCache().GetAttribute <NumericEnumAttribute>() != null && int.TryParse(OriginalValue.ToString(), out result))
                    {
                        var enumVal = Enum.Parse(PropertyType, OriginalValue.ToString());

                        if (Mode == SerializationMode.Deserialize)
                        {
                            val = enumVal;
                        }
                        else
                        {
                            val = ((Enum)enumVal).GetEnumAttribute <T>(true).Name;
                        }
                    }
                }
            }

            return(val);
        }
Exemplo n.º 14
0
        public string ToXML(string rootName)
        {
            XmlDocument xmlDocument = new XmlDocument();
            var         rootElement = xmlDocument.CreateElement(rootName);

            //var typeElement = xmlDocument.CreateElement("Type");
            //typeElement.InnerText = Type.ToString();

            //var originalValueElement = xmlDocument.CreateElement("OriginalValue");
            //originalValueElement.InnerText = OriginalValue;

            //var newValueElement = xmlDocument.CreateElement("NewValue");
            //newValueElement.InnerText = NewValue;

            //rootElement.AppendChild(typeElement);
            //rootElement.AppendChild(originalValueElement);
            //rootElement.AppendChild(newValueElement);

            if (Type == ChangeType.None)
            {
                rootElement.InnerText = OriginalValue;
            }
            else if (Type == ChangeType.Add)
            {
                rootElement.InnerText = "<div style='background:#00FF00'>" + NewValue + "<div style='background:#00FF00'>";
            }
            else if (Type == ChangeType.Delete)
            {
                rootElement.InnerText = "<s><div style='background:#FF0000'>" + OriginalValue + "</div></s>";
            }
            else
            {
                if (OriginalValue.Contains('\r') || NewValue.Contains('\r') ||
                    OriginalValue.Contains('\n') || NewValue.Contains('\n'))
                {
                    rootElement.InnerText = "<div>" + new LineDiff().CreateDiffHtml(OriginalValue, NewValue) + "</div>";
                }
                else
                {
                    rootElement.InnerText = "<div style='background:#DBDB70'>" + OriginalValue + "<br/> ==><br/>" + NewValue + "</div>";
                }
            }

            return(rootElement.OuterXml);
        }
Exemplo n.º 15
0
        private ConversionState ProcessNullable()
        {
            //String, Int and Double can be used as is
            if (PropertyType == typeof(string))
            {
                Type = TypeCategory.String;

                NewValue = OriginalValue?.ToString();

                return(ValueConversionWithMaybeNullCheck);
            }
            else if (PropertyType == typeof(double) || PropertyType == typeof(int))
            {
                NewValue = ParseNumericValue();

                return(ValueConversionWithMaybeNullCheck);
            }

            return(MoveNext());
        }
Exemplo n.º 16
0
        public override string GetStepParameters()
        {
            var parameters = new List <string>();

            parameters.Add(GlobalId != null ? GlobalId.ToStepValue() : "$");
            parameters.Add(OwnerHistory != null ? OwnerHistory.ToStepValue() : "$");
            parameters.Add(Name != null ? Name.ToStepValue() : "$");
            parameters.Add(Description != null ? Description.ToStepValue() : "$");
            parameters.Add(ObjectType != null ? ObjectType.ToStepValue() : "$");
            parameters.Add(Identification != null ? Identification.ToStepValue() : "$");
            parameters.Add(OriginalValue != null ? OriginalValue.ToStepValue() : "$");
            parameters.Add(CurrentValue != null ? CurrentValue.ToStepValue() : "$");
            parameters.Add(TotalReplacementCost != null ? TotalReplacementCost.ToStepValue() : "$");
            parameters.Add(Owner != null ? Owner.ToStepValue() : "$");
            parameters.Add(User != null ? User.ToStepValue() : "$");
            parameters.Add(ResponsiblePerson != null ? ResponsiblePerson.ToStepValue() : "$");
            parameters.Add(IncorporationDate != null ? IncorporationDate.ToStepValue() : "$");
            parameters.Add(DepreciatedValue != null ? DepreciatedValue.ToStepValue() : "$");

            return(string.Join(", ", parameters.ToArray()));
        }
Exemplo n.º 17
0
        private ConversionState DeserializeIEnumerable()
        {
            if (PropertyType.IsArray)
            {
                //If Value was string[] we would have shortcut out due to PropertyType == ValueType in ProcessCorrectType()

                if (OriginalValue == null)
                {
                    NewValue = null;
                    return(ConversionState.ValueConversion);
                }

                if (OriginalValue.IsIEnumerable())
                {
                    NewValue = OriginalValue.ToIEnumerable().Where(v => v != null).Select(v => v.ToString()).ToArray();
                    return(ConversionState.ValueConversion);
                }

                var characters = Cache.GetAttribute <SplittableStringAttribute>(true)?.Characters;

                if (characters != null)
                {
                    NewValue = OriginalValue.ToString().Split(characters);
                    return(ConversionState.ValueConversion);
                }

                NewValue = new[]
                {
                    OriginalValue.ToString()
                };

                return(ConversionState.ValueConversion);
            }

            return(MoveNext());
        }
Exemplo n.º 18
0
 private void Print()
 {
     Console.WriteLine(Formatter.GetString(OriginalValue.ToString(), ORIGINAL_TYPE, nameof(Celsius), Celsius.ToString("#.##")));
     Console.WriteLine(Formatter.GetString(OriginalValue.ToString(), ORIGINAL_TYPE, nameof(Kelvin), Kelvin.ToString("#.##")));
     Console.WriteLine();
 }
Exemplo n.º 19
0
        private ConversionState SerializeIEnumerable()
        {
            var supportedArrayTypes = new[]
            {
                typeof(object),
                typeof(string)
            };

            //We would like for our Value to be some type of IEnumerable so that we may serialize it
            //as a splittable string
            if (PropertyType.IsArray)
            {
                if (ValueType?.IsArray == true)
                {
                    var elementType = ValueType.GetElementType();

                    if (!supportedArrayTypes.Contains(elementType))
                    {
                        throw GetNotSupportedCollectionException(elementType);
                    }
                }

                //The serialized form of null is null. The serialized form of any list is a string
                if (OriginalValue == null || OriginalValue is string)
                {
                    NewValue = OriginalValue as string;
                    return(ConversionState.ValueConversion);
                }

                if (OriginalValue.IsIEnumerable())
                {
                    foreach (var @interface in ValueType.GetInterfaces())
                    {
                        if (@interface.IsGenericType && @interface.GetGenericTypeDefinition() == typeof(IEnumerable <>))
                        {
                            var genericTypeArg = @interface.GetGenericArguments()[0];

                            if (!supportedArrayTypes.Contains(genericTypeArg))
                            {
                                throw GetNotSupportedCollectionException(genericTypeArg);
                            }

                            break;
                        }
                    }

                    var enumerable = OriginalValue.ToIEnumerable().ToArray();

                    if (enumerable.Length == 0)
                    {
                        NewValue = null;
                        return(ConversionState.ValueConversion);
                    }

                    var illegalTypes = enumerable.Where(v => !(v is string)).ToList();

                    if (illegalTypes.Count > 0)
                    {
                        throw GetNotSupportedCollectionException(illegalTypes[0].GetType());
                    }

                    //The first character is considered canon. All subsequent characters are for alternate characters that
                    //could somehow get thrown into the mix
                    var splittableStringChar = Cache.GetAttribute <SplittableStringAttribute>(true)?.Characters[0].ToString();

                    if (splittableStringChar == null)
                    {
                        throw new NotSupportedException($"Cannot serialize value for array property {Property} as the property is missing a {nameof(SplittableStringAttribute)}.");
                    }

                    NewValue = string.Join(splittableStringChar, enumerable);
                    return(ConversionState.ValueConversion);
                }

                throw GetInvalidTypeException();
            }

            return(MoveNext());
        }
 public FilePath Replace(string oldValue, string newValue)
 {
     return(new FilePath(OriginalValue.Replace(oldValue, newValue)));
 }
        public FilePath SubPath(int start, int end)
        {
            var filePath = new FilePath(OriginalValue.Substring(start, end));

            return(filePath);
        }
        public FilePath SubPath(int index)
        {
            var filePath = new FilePath(OriginalValue.Substring(index));

            return(filePath);
        }
Exemplo n.º 23
0
 public T GetResultOrThrow()
 {
     if (Error == null)
     {
         return(ConvertedValue);
     }
     if (OriginalValue == null)
     {
         throw new InvalidCastException($"Failed to convert null to {TargetType.Type}.", Error);
     }
     else
     {
         throw new InvalidCastException($"Failed to convert {OriginalValue} from {OriginalValue.GetType()} to {TargetType.Type}.", Error);
     }
 }
 public bool Fail(string format, params object[] args)
 {
     if (args != null && args.Length > 0)
     {
         Message = String.Format("{0}.{1}: {3} ('{2}')", Field.Category, Field.DisplayName, OriginalValue.Truncate(30), string.Format(format, args));
     }
     else
     {
         Message = String.Format("{0}.{1}: {3} ('{2}')", Field.Category, Field.DisplayName, OriginalValue.Truncate(30), format);
     }
     IsValid        = false;
     ConvertedValue = null;
     return(false);
 }