diff --git a/Src/Newtonsoft.Json.Tests/Properties/AssemblyInfo.cs b/Src/Newtonsoft.Json.Tests/Properties/AssemblyInfo.cs index 91e51fdf..ff6fcb59 100644 --- a/Src/Newtonsoft.Json.Tests/Properties/AssemblyInfo.cs +++ b/Src/Newtonsoft.Json.Tests/Properties/AssemblyInfo.cs @@ -66,5 +66,5 @@ using System.Runtime.InteropServices; // by using the '*' as shown below: [assembly: AssemblyVersion("4.0.5.0")] #if !PocketPC -[assembly: AssemblyFileVersion("4.0.5.14516")] +[assembly: AssemblyFileVersion("4.0.5.14518")] #endif diff --git a/Src/Newtonsoft.Json/Bson/BsonBinaryWriter.cs b/Src/Newtonsoft.Json/Bson/BsonBinaryWriter.cs index fdd0abec..e51294c5 100644 --- a/Src/Newtonsoft.Json/Bson/BsonBinaryWriter.cs +++ b/Src/Newtonsoft.Json/Bson/BsonBinaryWriter.cs @@ -15,7 +15,6 @@ namespace Newtonsoft.Json.Bson private readonly BinaryWriter _writer; private byte[] _largeByteBuffer; - private int _maxChars; public DateTimeKind DateTimeKindHandling { get; set; } @@ -181,7 +180,6 @@ namespace Newtonsoft.Json.Bson if (_largeByteBuffer == null) { _largeByteBuffer = new byte[256]; - _maxChars = 256 / Encoding.GetMaxByteCount(1); } if (byteCount <= 256) { diff --git a/Src/Newtonsoft.Json/Bson/BsonToken.cs b/Src/Newtonsoft.Json/Bson/BsonToken.cs index ff4b21da..24d4c16a 100644 --- a/Src/Newtonsoft.Json/Bson/BsonToken.cs +++ b/Src/Newtonsoft.Json/Bson/BsonToken.cs @@ -64,8 +64,8 @@ namespace Newtonsoft.Json.Bson internal class BsonValue : BsonToken { - private object _value; - private BsonType _type; + private readonly object _value; + private readonly BsonType _type; public BsonValue(object value, BsonType type) { diff --git a/Src/Newtonsoft.Json/Bson/BsonWriter.cs b/Src/Newtonsoft.Json/Bson/BsonWriter.cs index 3d2d6ebc..1502ad8b 100644 --- a/Src/Newtonsoft.Json/Bson/BsonWriter.cs +++ b/Src/Newtonsoft.Json/Bson/BsonWriter.cs @@ -345,7 +345,7 @@ namespace Newtonsoft.Json.Bson public override void WriteValue(char value) { base.WriteValue(value); - AddToken(new BsonString(value.ToString(), true)); + AddToken(new BsonString(value.ToString(CultureInfo.InvariantCulture), true)); } /// diff --git a/Src/Newtonsoft.Json/Converters/JavaScriptDateTimeConverter.cs b/Src/Newtonsoft.Json/Converters/JavaScriptDateTimeConverter.cs index 4d709db4..9b27c453 100644 --- a/Src/Newtonsoft.Json/Converters/JavaScriptDateTimeConverter.cs +++ b/Src/Newtonsoft.Json/Converters/JavaScriptDateTimeConverter.cs @@ -65,7 +65,7 @@ namespace Newtonsoft.Json.Converters return null; } - if (reader.TokenType != JsonToken.StartConstructor || string.Compare(reader.Value.ToString(), "Date", StringComparison.Ordinal) != 0) + if (reader.TokenType != JsonToken.StartConstructor || !string.Equals(reader.Value.ToString(), "Date", StringComparison.Ordinal)) throw new Exception("Unexpected token or value when parsing date. Token: {0}, Value: {1}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType, reader.Value)); reader.Read(); diff --git a/Src/Newtonsoft.Json/Converters/XmlNodeConverter.cs b/Src/Newtonsoft.Json/Converters/XmlNodeConverter.cs index d7469e6d..65dcba70 100644 --- a/Src/Newtonsoft.Json/Converters/XmlNodeConverter.cs +++ b/Src/Newtonsoft.Json/Converters/XmlNodeConverter.cs @@ -40,7 +40,7 @@ namespace Newtonsoft.Json.Converters #if !SILVERLIGHT internal class XmlDocumentWrapper : XmlNodeWrapper, IXmlDocument { - private XmlDocument _document; + private readonly XmlDocument _document; public XmlDocumentWrapper(XmlDocument document) : base(document) @@ -123,7 +123,7 @@ namespace Newtonsoft.Json.Converters internal class XmlElementWrapper : XmlNodeWrapper, IXmlElement { - private XmlElement _element; + private readonly XmlElement _element; public XmlElementWrapper(XmlElement element) : base(element) @@ -146,7 +146,7 @@ namespace Newtonsoft.Json.Converters internal class XmlDeclarationWrapper : XmlNodeWrapper, IXmlDeclaration { - private XmlDeclaration _declaration; + private readonly XmlDeclaration _declaration; public XmlDeclarationWrapper(XmlDeclaration declaration) : base(declaration) @@ -983,7 +983,7 @@ namespace Newtonsoft.Json.Converters if (writePropertyName) writer.WritePropertyName(GetPropertyName(node, manager)); - if (ValueAttributes(node.Attributes).Count() == 0 && node.ChildNodes.Count == 1 + if (!ValueAttributes(node.Attributes).Any() && node.ChildNodes.Count == 1 && node.ChildNodes[0].NodeType == XmlNodeType.Text) { // write elements with a single text child as a name value pair @@ -1319,11 +1319,11 @@ namespace Newtonsoft.Json.Converters { case JsonToken.PropertyName: string attributeName = reader.Value.ToString(); - string attributeValue; if (!string.IsNullOrEmpty(attributeName)) { char firstChar = attributeName[0]; + string attributeValue; switch (firstChar) { diff --git a/Src/Newtonsoft.Json/JsonSerializerSettings.cs b/Src/Newtonsoft.Json/JsonSerializerSettings.cs index 6537c66d..1d18e033 100644 --- a/Src/Newtonsoft.Json/JsonSerializerSettings.cs +++ b/Src/Newtonsoft.Json/JsonSerializerSettings.cs @@ -23,7 +23,7 @@ namespace Newtonsoft.Json internal const ConstructorHandling DefaultConstructorHandling = ConstructorHandling.Default; internal const TypeNameHandling DefaultTypeNameHandling = TypeNameHandling.None; internal const FormatterAssemblyStyle DefaultTypeNameAssemblyFormat = FormatterAssemblyStyle.Simple; - internal static readonly StreamingContext DefaultContext = new StreamingContext(); + internal static readonly StreamingContext DefaultContext; /// /// Gets or sets how reference loops (e.g. a class referencing itself) is handled. @@ -116,6 +116,11 @@ namespace Newtonsoft.Json /// The context. public StreamingContext Context { get; set; } + static JsonSerializerSettings() + { + DefaultContext = new StreamingContext(); + } + /// /// Initializes a new instance of the class. /// diff --git a/Src/Newtonsoft.Json/JsonValidatingReader.cs b/Src/Newtonsoft.Json/JsonValidatingReader.cs index 785de5b7..a6e199b9 100644 --- a/Src/Newtonsoft.Json/JsonValidatingReader.cs +++ b/Src/Newtonsoft.Json/JsonValidatingReader.cs @@ -658,7 +658,7 @@ namespace Newtonsoft.Json private static bool IsZero(double value) { - double epsilon = 2.2204460492503131e-016; + const double epsilon = 2.2204460492503131e-016; return Math.Abs(value) < 10.0 * epsilon; } @@ -731,7 +731,7 @@ namespace Newtonsoft.Json bool IJsonLineInfo.HasLineInfo() { IJsonLineInfo lineInfo = _reader as IJsonLineInfo; - return (lineInfo != null) ? lineInfo.HasLineInfo() : false; + return lineInfo != null && lineInfo.HasLineInfo(); } int IJsonLineInfo.LineNumber diff --git a/Src/Newtonsoft.Json/JsonWriter.cs b/Src/Newtonsoft.Json/JsonWriter.cs index f782b41a..0eb68379 100644 --- a/Src/Newtonsoft.Json/JsonWriter.cs +++ b/Src/Newtonsoft.Json/JsonWriter.cs @@ -341,7 +341,7 @@ namespace Newtonsoft.Json case JsonToken.StartConstructor: string constructorName = reader.Value.ToString(); // write a JValue date when the constructor is for a date - if (string.Compare(constructorName, "Date", StringComparison.Ordinal) == 0) + if (string.Equals(constructorName, "Date", StringComparison.Ordinal)) WriteConstructorDate(reader); else WriteStartConstructor(reader.Value.ToString()); diff --git a/Src/Newtonsoft.Json/Linq/Extensions.cs b/Src/Newtonsoft.Json/Linq/Extensions.cs index d4b52726..250bbf94 100644 --- a/Src/Newtonsoft.Json/Linq/Extensions.cs +++ b/Src/Newtonsoft.Json/Linq/Extensions.cs @@ -182,7 +182,7 @@ namespace Newtonsoft.Json.Linq { foreach (JToken t in token.Children()) { - yield return t.Convert(); ; + yield return t.Convert(); } } } @@ -236,7 +236,7 @@ namespace Newtonsoft.Json.Linq { ValidationUtils.ArgumentNotNull(source, "source"); - foreach (JToken token in source) + foreach (T token in source) { yield return Convert(token); } diff --git a/Src/Newtonsoft.Json/Linq/JArray.cs b/Src/Newtonsoft.Json/Linq/JArray.cs index 19058b9c..3705a8d8 100644 --- a/Src/Newtonsoft.Json/Linq/JArray.cs +++ b/Src/Newtonsoft.Json/Linq/JArray.cs @@ -39,7 +39,7 @@ namespace Newtonsoft.Json.Linq /// public class JArray : JContainer, IList { - private IList _values = new List(); + private readonly IList _values = new List(); /// /// Gets the container's children tokens. diff --git a/Src/Newtonsoft.Json/Linq/JConstructor.cs b/Src/Newtonsoft.Json/Linq/JConstructor.cs index c2e0c5d2..3a9d26d4 100644 --- a/Src/Newtonsoft.Json/Linq/JConstructor.cs +++ b/Src/Newtonsoft.Json/Linq/JConstructor.cs @@ -38,7 +38,7 @@ namespace Newtonsoft.Json.Linq public class JConstructor : JContainer { private string _name; - private IList _values = new List(); + private readonly IList _values = new List(); /// /// Gets the container's children tokens. diff --git a/Src/Newtonsoft.Json/Linq/JEnumerable.cs b/Src/Newtonsoft.Json/Linq/JEnumerable.cs index 71c5fbb4..799e411b 100644 --- a/Src/Newtonsoft.Json/Linq/JEnumerable.cs +++ b/Src/Newtonsoft.Json/Linq/JEnumerable.cs @@ -18,7 +18,7 @@ namespace Newtonsoft.Json.Linq /// public static readonly JEnumerable Empty = new JEnumerable(Enumerable.Empty()); - private IEnumerable _enumerable; + private readonly IEnumerable _enumerable; /// /// Initializes a new instance of the struct. diff --git a/Src/Newtonsoft.Json/Linq/JObject.cs b/Src/Newtonsoft.Json/Linq/JObject.cs index a12aa221..0478d2c3 100644 --- a/Src/Newtonsoft.Json/Linq/JObject.cs +++ b/Src/Newtonsoft.Json/Linq/JObject.cs @@ -83,7 +83,7 @@ namespace Newtonsoft.Json.Linq } } - private JPropertKeyedCollection _properties = new JPropertKeyedCollection(StringComparer.Ordinal); + private readonly JPropertKeyedCollection _properties = new JPropertKeyedCollection(StringComparer.Ordinal); /// /// Gets the container's children tokens. diff --git a/Src/Newtonsoft.Json/Linq/JToken.cs b/Src/Newtonsoft.Json/Linq/JToken.cs index 0ca8f02c..019fbc1e 100644 --- a/Src/Newtonsoft.Json/Linq/JToken.cs +++ b/Src/Newtonsoft.Json/Linq/JToken.cs @@ -773,7 +773,7 @@ namespace Newtonsoft.Json.Linq if (v == null || !ValidateString(v)) throw new ArgumentException("Can not convert {0} to String.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); - return (v.Value != null) ? Convert.ToString(v.Value) : null; + return (v.Value != null) ? Convert.ToString(v.Value, CultureInfo.InvariantCulture) : null; } /// diff --git a/Src/Newtonsoft.Json/Linq/JTokenWriter.cs b/Src/Newtonsoft.Json/Linq/JTokenWriter.cs index 2aa233d1..d5875393 100644 --- a/Src/Newtonsoft.Json/Linq/JTokenWriter.cs +++ b/Src/Newtonsoft.Json/Linq/JTokenWriter.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.Linq; using System.Text; using Newtonsoft.Json.Utilities; @@ -303,7 +304,7 @@ namespace Newtonsoft.Json.Linq public override void WriteValue(char value) { base.WriteValue(value); - AddValue(value.ToString(), JsonToken.String); + AddValue(value.ToString(CultureInfo.InvariantCulture), JsonToken.String); } /// diff --git a/Src/Newtonsoft.Json/Linq/JValue.cs b/Src/Newtonsoft.Json/Linq/JValue.cs index 2054e84f..7d574128 100644 --- a/Src/Newtonsoft.Json/Linq/JValue.cs +++ b/Src/Newtonsoft.Json/Linq/JValue.cs @@ -197,7 +197,7 @@ namespace Newtonsoft.Json.Linq string s1 = Convert.ToString(objA, CultureInfo.InvariantCulture); string s2 = Convert.ToString(objB, CultureInfo.InvariantCulture); - return s1.CompareTo(s2); + return string.CompareOrdinal(s1, s2); case JTokenType.Boolean: bool b1 = Convert.ToBoolean(objA, CultureInfo.InvariantCulture); bool b2 = Convert.ToBoolean(objB, CultureInfo.InvariantCulture); @@ -544,7 +544,7 @@ namespace Newtonsoft.Json.Linq writer.WriteValue((DateTimeOffset)_value); else #endif - writer.WriteValue(Convert.ToDateTime(_value, CultureInfo.InvariantCulture)); ; + writer.WriteValue(Convert.ToDateTime(_value, CultureInfo.InvariantCulture)); return; case JTokenType.Bytes: writer.WriteValue((byte[])_value); diff --git a/Src/Newtonsoft.Json/Properties/AssemblyInfo.cs b/Src/Newtonsoft.Json/Properties/AssemblyInfo.cs index a6e80ad8..2a2a8264 100644 --- a/Src/Newtonsoft.Json/Properties/AssemblyInfo.cs +++ b/Src/Newtonsoft.Json/Properties/AssemblyInfo.cs @@ -85,7 +85,7 @@ using System.Security; // by using the '*' as shown below: [assembly: AssemblyVersion("4.0.5.0")] #if !PocketPC -[assembly: AssemblyFileVersion("4.0.5.14516")] +[assembly: AssemblyFileVersion("4.0.5.14518")] #endif [assembly: CLSCompliant(true)] diff --git a/Src/Newtonsoft.Json/Schema/JsonSchemaGenerator.cs b/Src/Newtonsoft.Json/Schema/JsonSchemaGenerator.cs index 21266c14..4ab26140 100644 --- a/Src/Newtonsoft.Json/Schema/JsonSchemaGenerator.cs +++ b/Src/Newtonsoft.Json/Schema/JsonSchemaGenerator.cs @@ -77,7 +77,7 @@ namespace Newtonsoft.Json.Schema } private JsonSchemaResolver _resolver; - private IList _stack = new List(); + private readonly IList _stack = new List(); private JsonSchema _currentSchema; private JsonSchema CurrentSchema @@ -282,7 +282,7 @@ namespace Newtonsoft.Json.Schema CurrentSchema.Id = GetTypeId(type, false); JsonArrayAttribute arrayAttribute = JsonTypeReflector.GetJsonContainerAttribute(type) as JsonArrayAttribute; - bool allowNullItem = (arrayAttribute != null) ? arrayAttribute.AllowNullItems : true; + bool allowNullItem = (arrayAttribute == null || arrayAttribute.AllowNullItems); Type collectionItemType = ReflectionUtils.GetCollectionItemType(type); if (collectionItemType != null) diff --git a/Src/Newtonsoft.Json/Utilities/CollectionUtils.cs b/Src/Newtonsoft.Json/Utilities/CollectionUtils.cs index c34a8c72..fec0c945 100644 --- a/Src/Newtonsoft.Json/Utilities/CollectionUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/CollectionUtils.cs @@ -43,27 +43,6 @@ namespace Newtonsoft.Json.Utilities return enumerable.Cast().Where(o => o is T).Cast(); } - public static List CreateList(params T[] values) - { - return new List(values); - } - - /// - /// Determines whether the collection is null or empty. - /// - /// The collection. - /// - /// true if the collection is null or empty; otherwise, false. - /// - public static bool IsNullOrEmpty(ICollection collection) - { - if (collection != null) - { - return (collection.Count == 0); - } - return true; - } - /// /// Determines whether the collection is null or empty. /// @@ -80,113 +59,6 @@ namespace Newtonsoft.Json.Utilities return true; } - /// - /// Determines whether the collection is null, empty or its contents are uninitialized values. - /// - /// The list. - /// - /// true if the collection is null or empty or its contents are uninitialized values; otherwise, false. - /// - public static bool IsNullOrEmptyOrDefault(IList list) - { - if (IsNullOrEmpty(list)) - return true; - - return ReflectionUtils.ItemsUnitializedValue(list); - } - - /// - /// Makes a slice of the specified list in between the start and end indexes. - /// - /// The list. - /// The start index. - /// The end index. - /// A slice of the list. - public static IList Slice(IList list, int? start, int? end) - { - return Slice(list, start, end, null); - } - - /// - /// Makes a slice of the specified list in between the start and end indexes, - /// getting every so many items based upon the step. - /// - /// The list. - /// The start index. - /// The end index. - /// The step. - /// A slice of the list. - public static IList Slice(IList list, int? start, int? end, int? step) - { - if (list == null) - throw new ArgumentNullException("list"); - - if (step == 0) - throw new ArgumentException("Step cannot be zero.", "step"); - - List slicedList = new List(); - - // nothing to slice - if (list.Count == 0) - return slicedList; - - // set defaults for null arguments - int s = step ?? 1; - int startIndex = start ?? 0; - int endIndex = end ?? list.Count; - - // start from the end of the list if start is negitive - startIndex = (startIndex < 0) ? list.Count + startIndex : startIndex; - - // end from the start of the list if end is negitive - endIndex = (endIndex < 0) ? list.Count + endIndex : endIndex; - - // ensure indexes keep within collection bounds - startIndex = Math.Max(startIndex, 0); - endIndex = Math.Min(endIndex, list.Count - 1); - - // loop between start and end indexes, incrementing by the step - for (int i = startIndex; i < endIndex; i += s) - { - slicedList.Add(list[i]); - } - - return slicedList; - } - - - /// - /// Group the collection using a function which returns the key. - /// - /// The source collection to group. - /// The key selector. - /// A Dictionary with each key relating to a list of objects in a list grouped under it. - public static Dictionary> GroupBy(ICollection source, Func keySelector) - { - if (keySelector == null) - throw new ArgumentNullException("keySelector"); - - Dictionary> groupedValues = new Dictionary>(); - - foreach (V value in source) - { - // using delegate to get the value's key - K key = keySelector(value); - List groupedValueList; - - // add a list for grouped values if the key is not already in Dictionary - if (!groupedValues.TryGetValue(key, out groupedValueList)) - { - groupedValueList = new List(); - groupedValues.Add(key, groupedValueList); - } - - groupedValueList.Add(value); - } - - return groupedValues; - } - /// /// Adds the elements of the specified collection to the specified generic IList. /// @@ -214,126 +86,6 @@ namespace Newtonsoft.Json.Utilities wrapper.AddRange(collection.Cast()); } - public static List Distinct(List collection) - { - List distinctList = new List(); - - foreach (T value in collection) - { - if (!distinctList.Contains(value)) - distinctList.Add(value); - } - - return distinctList; - } - - public static List> Flatten(params IList[] lists) - { - List> flattened = new List>(); - Dictionary currentList = new Dictionary(); - - Recurse(new List>(lists), 0, currentList, flattened); - - return flattened; - } - - private static void Recurse(IList> global, int current, Dictionary currentSet, List> flattenedResult) - { - IList currentArray = global[current]; - - for (int i = 0; i < currentArray.Count; i++) - { - currentSet[current] = currentArray[i]; - - if (current == global.Count - 1) - { - List items = new List(); - - for (int k = 0; k < currentSet.Count; k++) - { - items.Add(currentSet[k]); - } - - flattenedResult.Add(items); - } - else - { - Recurse(global, current + 1, currentSet, flattenedResult); - } - } - } - - public static List CreateList(ICollection collection) - { - if (collection == null) - throw new ArgumentNullException("collection"); - - T[] array = new T[collection.Count]; - collection.CopyTo(array, 0); - - return new List(array); - } - - public static bool ListEquals(IList a, IList b) - { - if (a == null || b == null) - return (a == null && b == null); - - if (a.Count != b.Count) - return false; - - EqualityComparer comparer = EqualityComparer.Default; - - for (int i = 0; i < a.Count; i++) - { - if (!comparer.Equals(a[i], b[i])) - return false; - } - - return true; - } - - #region GetSingleItem - public static bool TryGetSingleItem(IList list, out T value) - { - return TryGetSingleItem(list, false, out value); - } - - public static bool TryGetSingleItem(IList list, bool returnDefaultIfEmpty, out T value) - { - return MiscellaneousUtils.TryAction(delegate { return GetSingleItem(list, returnDefaultIfEmpty); }, out value); - } - - public static T GetSingleItem(IList list) - { - return GetSingleItem(list, false); - } - - public static T GetSingleItem(IList list, bool returnDefaultIfEmpty) - { - if (list.Count == 1) - return list[0]; - else if (returnDefaultIfEmpty && list.Count == 0) - return default(T); - else - throw new Exception("Expected single {0} in list but got {1}.".FormatWith(CultureInfo.InvariantCulture, typeof(T), list.Count)); - } - #endregion - - public static IList Minus(IList list, IList minus) - { - ValidationUtils.ArgumentNotNull(list, "list"); - - List result = new List(list.Count); - foreach (T t in list) - { - if (minus == null || !minus.Contains(t)) - result.Add(t); - } - - return result; - } - public static IList CreateGenericList(Type listType) { ValidationUtils.ArgumentNotNull(listType, "listType"); @@ -341,42 +93,6 @@ namespace Newtonsoft.Json.Utilities return (IList)ReflectionUtils.CreateGeneric(typeof(List<>), listType); } - public static IDictionary CreateGenericDictionary(Type keyType, Type valueType) - { - ValidationUtils.ArgumentNotNull(keyType, "keyType"); - ValidationUtils.ArgumentNotNull(valueType, "valueType"); - - return (IDictionary)ReflectionUtils.CreateGeneric(typeof(Dictionary<,>), keyType, valueType); - } - - public static bool IsListType(Type type) - { - ValidationUtils.ArgumentNotNull(type, "type"); - - if (type.IsArray) - return true; - if (typeof(IList).IsAssignableFrom(type)) - return true; - if (ReflectionUtils.ImplementsGenericDefinition(type, typeof(IList<>))) - return true; - - return false; - } - - public static bool IsCollectionType(Type type) - { - ValidationUtils.ArgumentNotNull(type, "type"); - - if (type.IsArray) - return true; - if (typeof(ICollection).IsAssignableFrom(type)) - return true; - if (ReflectionUtils.ImplementsGenericDefinition(type, typeof(ICollection<>))) - return true; - - return false; - } - public static bool IsDictionaryType(Type type) { ValidationUtils.ArgumentNotNull(type, "type"); @@ -416,33 +132,6 @@ namespace Newtonsoft.Json.Utilities throw new Exception("Can not create ListWrapper for type {0}.".FormatWith(CultureInfo.InvariantCulture, list.GetType())); } } - public static IWrappedList CreateListWrapper(object list) - { - ValidationUtils.ArgumentNotNull(list, "list"); - - Type listDefinition; - if (ReflectionUtils.ImplementsGenericDefinition(list.GetType(), typeof(IList<>), out listDefinition)) - { - Type collectionItemType = ReflectionUtils.GetCollectionItemType(listDefinition); - - // Activator.CreateInstance throws AmbiguousMatchException. Manually invoke constructor - Func, object> instanceCreator = (t, a) => - { - ConstructorInfo c = t.GetConstructor(new[] {listDefinition}); - return c.Invoke(new[] { list }); - }; - - return (IWrappedList)ReflectionUtils.CreateGeneric(typeof(ListWrapper<>), new[] { collectionItemType }, instanceCreator, list); - } - else if (list is IList) - { - return new ListWrapper((IList)list); - } - else - { - throw new Exception("Can not create ListWrapper for type {0}.".FormatWith(CultureInfo.InvariantCulture, list.GetType())); - } - } public static IWrappedDictionary CreateDictionaryWrapper(object dictionary) { @@ -601,11 +290,6 @@ namespace Newtonsoft.Json.Utilities return false; } - public static bool AddRangeDistinct(this IList list, IEnumerable values) - { - return list.AddRangeDistinct(values, EqualityComparer.Default); - } - public static bool AddRangeDistinct(this IList list, IEnumerable values, IEqualityComparer comparer) { bool allAdded = true; @@ -632,18 +316,6 @@ namespace Newtonsoft.Json.Utilities return -1; } - /// - /// Returns the index of the first occurrence in a sequence by using the default equality comparer. - /// - /// The type of the elements of source. - /// A sequence in which to locate a value. - /// The object to locate in the sequence - /// The zero-based index of the first occurrence of value within the entire sequence, if found; otherwise, –1. - public static int IndexOf(this IEnumerable list, TSource value) where TSource : IEquatable - { - return list.IndexOf(value, EqualityComparer.Default); - } - /// /// Returns the index of the first occurrence in a sequence by using a specified IEqualityComparer. /// diff --git a/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs b/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs index 2cc4f734..45dc8c37 100644 --- a/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs @@ -97,92 +97,7 @@ namespace Newtonsoft.Json.Utilities return o => call(null, o); } - public static bool CanConvertType(Type initialType, Type targetType, bool allowTypeNameToString) - { - ValidationUtils.ArgumentNotNull(initialType, "initialType"); - ValidationUtils.ArgumentNotNull(targetType, "targetType"); - - if (ReflectionUtils.IsNullableType(targetType)) - targetType = Nullable.GetUnderlyingType(targetType); - - if (targetType == initialType) - return true; - - if (typeof(IConvertible).IsAssignableFrom(initialType) && typeof(IConvertible).IsAssignableFrom(targetType)) - { - return true; - } - -#if !PocketPC && !NET20 - if (initialType == typeof(DateTime) && targetType == typeof(DateTimeOffset)) - return true; -#endif - - if (initialType == typeof(Guid) && (targetType == typeof(Guid) || targetType == typeof(string))) - return true; - - if (initialType == typeof(Type) && targetType == typeof(string)) - return true; - -#if !PocketPC - // see if source or target types have a TypeConverter that converts between the two - TypeConverter toConverter = GetConverter(initialType); - - if (toConverter != null && !IsComponentConverter(toConverter) && toConverter.CanConvertTo(targetType)) - { - if (allowTypeNameToString || toConverter.GetType() != typeof(TypeConverter)) - return true; - } - - TypeConverter fromConverter = GetConverter(targetType); - - if (fromConverter != null && !IsComponentConverter(fromConverter) && fromConverter.CanConvertFrom(initialType)) - return true; -#endif - - // handle DBNull and INullable - if (initialType == typeof(DBNull)) - { - if (ReflectionUtils.IsNullable(targetType)) - return true; - } - - return false; - } - - private static bool IsComponentConverter(TypeConverter converter) - { -#if !SILVERLIGHT && !PocketPC - return (converter is ComponentConverter); -#else - return false; -#endif - } - #region Convert - /// - /// Converts the value to the specified type. - /// - /// The type to convert the value to. - /// The value to convert. - /// The converted type. - public static T Convert(object initialValue) - { - return Convert(initialValue, CultureInfo.CurrentCulture); - } - - /// - /// Converts the value to the specified type. - /// - /// The type to convert the value to. - /// The value to convert. - /// The culture to use when converting. - /// The converted type. - public static T Convert(object initialValue, CultureInfo culture) - { - return (T)Convert(initialValue, culture, typeof(T)); - } - /// /// Converts the value to the specified type. /// @@ -285,41 +200,6 @@ namespace Newtonsoft.Json.Utilities #endregion #region TryConvert - /// - /// Converts the value to the specified type. - /// - /// The type to convert the value to. - /// The value to convert. - /// The converted value if the conversion was successful or the default value of T if it failed. - /// - /// true if initialValue was converted successfully; otherwise, false. - /// - public static bool TryConvert(object initialValue, out T convertedValue) - { - return TryConvert(initialValue, CultureInfo.CurrentCulture, out convertedValue); - } - - /// - /// Converts the value to the specified type. - /// - /// The type to convert the value to. - /// The value to convert. - /// The culture to use when converting. - /// The converted value if the conversion was successful or the default value of T if it failed. - /// - /// true if initialValue was converted successfully; otherwise, false. - /// - public static bool TryConvert(object initialValue, CultureInfo culture, out T convertedValue) - { - return MiscellaneousUtils.TryAction(delegate - { - object tempConvertedValue; - TryConvert(initialValue, CultureInfo.CurrentCulture, typeof(T), out tempConvertedValue); - - return (T)tempConvertedValue; - }, out convertedValue); - } - /// /// Converts the value to the specified type. /// @@ -337,31 +217,6 @@ namespace Newtonsoft.Json.Utilities #endregion #region ConvertOrCast - /// - /// Converts the value to the specified type. If the value is unable to be converted, the - /// value is checked whether it assignable to the specified type. - /// - /// The type to convert or cast the value to. - /// The value to convert. - /// The converted type. If conversion was unsuccessful, the initial value is returned if assignable to the target type - public static T ConvertOrCast(object initialValue) - { - return ConvertOrCast(initialValue, CultureInfo.CurrentCulture); - } - - /// - /// Converts the value to the specified type. If the value is unable to be converted, the - /// value is checked whether it assignable to the specified type. - /// - /// The type to convert or cast the value to. - /// The value to convert. - /// The culture to use when converting. - /// The converted type. If conversion was unsuccessful, the initial value is returned if assignable to the target type - public static T ConvertOrCast(object initialValue, CultureInfo culture) - { - return (T)ConvertOrCast(initialValue, culture, typeof(T)); - } - /// /// Converts the value to the specified type. If the value is unable to be converted, the /// value is checked whether it assignable to the specified type. @@ -390,61 +245,6 @@ namespace Newtonsoft.Json.Utilities } #endregion - #region TryConvertOrCast - /// - /// Converts the value to the specified type. If the value is unable to be converted, the - /// value is checked whether it assignable to the specified type. - /// - /// The type to convert the value to. - /// The value to convert. - /// The converted value if the conversion was successful or the default value of T if it failed. - /// - /// true if initialValue was converted successfully or is assignable; otherwise, false. - /// - public static bool TryConvertOrCast(object initialValue, out T convertedValue) - { - return TryConvertOrCast(initialValue, CultureInfo.CurrentCulture, out convertedValue); - } - - /// - /// Converts the value to the specified type. If the value is unable to be converted, the - /// value is checked whether it assignable to the specified type. - /// - /// The type to convert the value to. - /// The value to convert. - /// The culture to use when converting. - /// The converted value if the conversion was successful or the default value of T if it failed. - /// - /// true if initialValue was converted successfully or is assignable; otherwise, false. - /// - public static bool TryConvertOrCast(object initialValue, CultureInfo culture, out T convertedValue) - { - return MiscellaneousUtils.TryAction(delegate - { - object tempConvertedValue; - TryConvertOrCast(initialValue, CultureInfo.CurrentCulture, typeof(T), out tempConvertedValue); - - return (T)tempConvertedValue; - }, out convertedValue); - } - - /// - /// Converts the value to the specified type. If the value is unable to be converted, the - /// value is checked whether it assignable to the specified type. - /// - /// The value to convert. - /// The culture to use when converting. - /// The type to convert the value to. - /// The converted value if the conversion was successful or the default value of T if it failed. - /// - /// true if initialValue was converted successfully or is assignable; otherwise, false. - /// - public static bool TryConvertOrCast(object initialValue, CultureInfo culture, Type targetType, out object convertedValue) - { - return MiscellaneousUtils.TryAction(delegate { return ConvertOrCast(initialValue, culture, targetType); }, out convertedValue); - } - #endregion - private static object EnsureTypeAssignable(object value, Type initialType, Type targetType) { Type valueType = (value != null) ? value.GetType() : null; diff --git a/Src/Newtonsoft.Json/Utilities/DynamicWrapper.cs b/Src/Newtonsoft.Json/Utilities/DynamicWrapper.cs index f2b37c2f..78995094 100644 --- a/Src/Newtonsoft.Json/Utilities/DynamicWrapper.cs +++ b/Src/Newtonsoft.Json/Utilities/DynamicWrapper.cs @@ -53,7 +53,7 @@ namespace Newtonsoft.Json.Utilities private static byte[] GetStrongKey() { - string name ="Newtonsoft.Json.Dynamic.snk"; + const string name = "Newtonsoft.Json.Dynamic.snk"; using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(name)) { diff --git a/Src/Newtonsoft.Json/Utilities/EnumUtils.cs b/Src/Newtonsoft.Json/Utilities/EnumUtils.cs index e40c80e4..1d904f2e 100644 --- a/Src/Newtonsoft.Json/Utilities/EnumUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/EnumUtils.cs @@ -33,36 +33,6 @@ namespace Newtonsoft.Json.Utilities { internal static class EnumUtils { - /// - /// Parses the specified enum member name, returning it's value. - /// - /// Name of the enum member. - /// - public static T Parse(string enumMemberName) where T : struct - { - return Parse(enumMemberName, false); - } - - /// - /// Parses the specified enum member name, returning it's value. - /// - /// Name of the enum member. - /// If set to true ignore case. - /// - public static T Parse(string enumMemberName, bool ignoreCase) where T : struct - { - ValidationUtils.ArgumentTypeIsEnum(typeof(T), "T"); - - return (T)Enum.Parse(typeof(T), enumMemberName, ignoreCase); - } - - public static bool TryParse(string enumMemberName, bool ignoreCase, out T value) where T : struct - { - ValidationUtils.ArgumentTypeIsEnum(typeof(T), "T"); - - return MiscellaneousUtils.TryAction(() => Parse(enumMemberName, ignoreCase), out value); - } - public static IList GetFlagsValues(T value) where T : struct { Type enumType = typeof(T); @@ -97,17 +67,6 @@ namespace Newtonsoft.Json.Utilities return GetNamesAndValues(typeof(T)); } - /// - /// Gets a dictionary of the names and values of an Enum type. - /// - /// - public static EnumValues GetNamesAndValues() - where TEnum : struct - where TUnderlyingType : struct - { - return GetNamesAndValues(typeof(TEnum)); - } - /// /// Gets a dictionary of the names and values of an Enum type. /// @@ -142,11 +101,6 @@ namespace Newtonsoft.Json.Utilities return nameValues; } - public static IList GetValues() - { - return GetValues(typeof(T)).Cast().ToList(); - } - public static IList GetValues(Type enumType) { if (!enumType.IsEnum) @@ -167,11 +121,6 @@ namespace Newtonsoft.Json.Utilities return values; } - public static IList GetNames() - { - return GetNames(typeof(T)); - } - public static IList GetNames(Type enumType) { if (!enumType.IsEnum) @@ -190,47 +139,5 @@ namespace Newtonsoft.Json.Utilities return values; } - - - /// - /// Gets the maximum valid value of an Enum type. Flags enums are ORed. - /// - /// The type of the returned value. Must be assignable from the enum's underlying value type. - /// The enum type to get the maximum value for. - /// - public static TEnumType GetMaximumValue(Type enumType) where TEnumType : IConvertible, IComparable - { - if (enumType == null) - throw new ArgumentNullException("enumType"); - - Type enumUnderlyingType = Enum.GetUnderlyingType(enumType); - - if (!typeof(TEnumType).IsAssignableFrom(enumUnderlyingType)) - throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "TEnumType is not assignable from the enum's underlying type of {0}.", enumUnderlyingType.Name)); - - ulong maximumValue = 0; - IList enumValues = GetValues(enumType); - - if (enumType.IsDefined(typeof(FlagsAttribute), false)) - { - foreach (TEnumType value in enumValues) - { - maximumValue = maximumValue | value.ToUInt64(CultureInfo.InvariantCulture); - } - } - else - { - foreach (TEnumType value in enumValues) - { - ulong tempValue = value.ToUInt64(CultureInfo.InvariantCulture); - - // maximumValue is smaller than the enum value - if (maximumValue.CompareTo(tempValue) == -1) - maximumValue = tempValue; - } - } - - return (TEnumType)Convert.ChangeType(maximumValue, typeof(TEnumType), CultureInfo.InvariantCulture); - } } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Utilities/EnumValue.cs b/Src/Newtonsoft.Json/Utilities/EnumValue.cs index 0f199c34..40355f2a 100644 --- a/Src/Newtonsoft.Json/Utilities/EnumValue.cs +++ b/Src/Newtonsoft.Json/Utilities/EnumValue.cs @@ -32,8 +32,8 @@ namespace Newtonsoft.Json.Utilities { internal class EnumValue where T : struct { - private string _name; - private T _value; + private readonly string _name; + private readonly T _value; public string Name { diff --git a/Src/Newtonsoft.Json/Utilities/JavaScriptUtils.cs b/Src/Newtonsoft.Json/Utilities/JavaScriptUtils.cs index d4ee35ed..c36020ce 100644 --- a/Src/Newtonsoft.Json/Utilities/JavaScriptUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/JavaScriptUtils.cs @@ -44,19 +44,15 @@ namespace Newtonsoft.Json.Utilities if (s != null) { char[] chars = null; - int lastWritePosition = -1; + int lastWritePosition = 0; - for (var index = 0; index < s.Length; ++index) + for (int i = 0; i < s.Length; i++) { - var c = s[index]; - - if (c >= ' ' && c < 128 && c != '\"' && c != '\\' && c != '\'') - { - if (lastWritePosition == -1) - lastWritePosition = index; + var c = s[i]; + // don't escape standard text/numbers except '\' and the text delimiter + if (c >= ' ' && c < 128 && c != '\\' && c != '\'' && c != '"') continue; - } string escapedValue; @@ -103,38 +99,33 @@ namespace Newtonsoft.Json.Utilities } if (escapedValue == null) - { - if (lastWritePosition == -1) - lastWritePosition = index; - continue; - } - if (lastWritePosition != -1) + if (i > lastWritePosition) { if (chars == null) chars = s.ToCharArray(); - writer.Write(chars, lastWritePosition, index - lastWritePosition); - lastWritePosition = -1; + // write unchanged chars before writing escaped text + writer.Write(chars, lastWritePosition, i - lastWritePosition); } + lastWritePosition = i + 1; writer.Write(escapedValue); } - if (lastWritePosition != -1) + if (lastWritePosition == 0) { - if (lastWritePosition == 0) - { - writer.Write(s); - } - else - { - if (chars == null) - chars = s.ToCharArray(); + // no escaped text, write entire string + writer.Write(s); + } + else + { + if (chars == null) + chars = s.ToCharArray(); - writer.Write(chars, lastWritePosition, s.Length - lastWritePosition); - } + // write remaining text + writer.Write(chars, lastWritePosition, s.Length - lastWritePosition); } } diff --git a/Src/Newtonsoft.Json/Utilities/MathUtils.cs b/Src/Newtonsoft.Json/Utilities/MathUtils.cs index 1059686e..d955c619 100644 --- a/Src/Newtonsoft.Json/Utilities/MathUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/MathUtils.cs @@ -42,23 +42,6 @@ namespace Newtonsoft.Json.Utilities return (int)Math.Floor(Math.Log10(i)) + 1; } - public static int HexToInt(char h) - { - if ((h >= '0') && (h <= '9')) - { - return (h - '0'); - } - if ((h >= 'a') && (h <= 'f')) - { - return ((h - 'a') + 10); - } - if ((h >= 'A') && (h <= 'F')) - { - return ((h - 'A') + 10); - } - return -1; - } - public static char IntToHex(int n) { if (n <= 9) @@ -68,23 +51,6 @@ namespace Newtonsoft.Json.Utilities return (char)((n - 10) + 97); } - public static int GetDecimalPlaces(double value) - { - // increasing max decimal places above 10 produces weirdness - int maxDecimalPlaces = 10; - double threshold = Math.Pow(0.1d, maxDecimalPlaces); - - if (value == 0.0) - return 0; - int decimalPlaces = 0; - while (value - Math.Floor(value) > threshold && decimalPlaces < maxDecimalPlaces) - { - value *= 10.0; - decimalPlaces++; - } - return decimalPlaces; - } - public static int? Min(int? val1, int? val2) { if (val1 == null) @@ -105,16 +71,6 @@ namespace Newtonsoft.Json.Utilities return Math.Max(val1.Value, val2.Value); } - public static double? Min(double? val1, double? val2) - { - if (val1 == null) - return val2; - if (val2 == null) - return val1; - - return Math.Min(val1.Value, val2.Value); - } - public static double? Max(double? val1, double? val2) { if (val1 == null) diff --git a/Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs b/Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs index 1f4ea291..0a904ddf 100644 --- a/Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs @@ -202,27 +202,6 @@ namespace Newtonsoft.Json.Utilities : t; } - //public static bool IsValueTypeUnitializedValue(ValueType value) - //{ - // if (value == null) - // return true; - - // return value.Equals(CreateUnitializedValue(value.GetType())); - //} - - public static bool IsUnitializedValue(object value) - { - if (value == null) - { - return true; - } - else - { - object unitializedValue = CreateUnitializedValue(value.GetType()); - return value.Equals(unitializedValue); - } - } - public static object CreateUnitializedValue(Type type) { ValidationUtils.ArgumentNotNull(type, "type"); @@ -238,13 +217,6 @@ namespace Newtonsoft.Json.Utilities throw new ArgumentException("Type {0} cannot be instantiated.".FormatWith(CultureInfo.InvariantCulture, type), "type"); } - public static bool IsPropertyIndexed(PropertyInfo property) - { - ValidationUtils.ArgumentNotNull(property, "property"); - - return !CollectionUtils.IsNullOrEmpty(property.GetIndexParameters()); - } - public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceDefinition) { Type implementingType; @@ -441,45 +413,6 @@ namespace Newtonsoft.Json.Utilities return keyType; } - /// - /// Tests whether the list's items are their unitialized value. - /// - /// The list. - /// Whether the list's items are their unitialized value - public static bool ItemsUnitializedValue(IList list) - { - ValidationUtils.ArgumentNotNull(list, "list"); - - Type elementType = GetCollectionItemType(list.GetType()); - - if (elementType.IsValueType) - { - object unitializedValue = CreateUnitializedValue(elementType); - - for (int i = 0; i < list.Count; i++) - { - if (!list[i].Equals(unitializedValue)) - return false; - } - } - else if (elementType.IsClass) - { - for (int i = 0; i < list.Count; i++) - { - object value = list[i]; - - if (value != null) - return false; - } - } - else - { - throw new Exception("Type {0} is neither a ValueType or a Class.".FormatWith(CultureInfo.InvariantCulture, elementType)); - } - - return true; - } - /// /// Gets the member's underlying type. /// @@ -657,11 +590,6 @@ namespace Newtonsoft.Json.Utilities } } - public static List GetFieldsAndProperties(BindingFlags bindingAttr) - { - return GetFieldsAndProperties(typeof(T), bindingAttr); - } - public static List GetFieldsAndProperties(Type type, BindingFlags bindingAttr) { List targetMembers = new List(); @@ -723,7 +651,7 @@ namespace Newtonsoft.Json.Utilities { T[] attributes = GetAttributes(attributeProvider, inherit); - return CollectionUtils.GetSingleItem(attributes, true); + return attributes.SingleOrDefault(); } public static T[] GetAttributes(ICustomAttributeProvider attributeProvider, bool inherit) where T : Attribute @@ -751,13 +679,6 @@ namespace Newtonsoft.Json.Utilities return (T[])attributeProvider.GetCustomAttributes(typeof(T), inherit); } - public static string GetNameAndAssessmblyName(Type t) - { - ValidationUtils.ArgumentNotNull(t, "t"); - - return t.FullName + ", " + t.Assembly.GetName().Name; - } - public static Type MakeGenericType(Type genericTypeDefinition, params Type[] innerTypes) { ValidationUtils.ArgumentNotNull(genericTypeDefinition, "genericTypeDefinition"); @@ -788,17 +709,6 @@ namespace Newtonsoft.Json.Utilities return instanceCreator(specificType, args); } - public static bool IsCompatibleValue(object value, Type type) - { - if (value == null) - return IsNullable(type); - - if (type.IsAssignableFrom(value.GetType())) - return true; - - return false; - } - public static object CreateInstance(Type type, params object[] args) { ValidationUtils.ArgumentNotNull(type, "type"); @@ -883,7 +793,7 @@ namespace Newtonsoft.Json.Utilities public static MemberInfo GetMemberInfoFromType(Type targetType, MemberInfo memberInfo) { - BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; + const BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; switch (memberInfo.MemberType) { diff --git a/Src/Newtonsoft.Json/Utilities/StringUtils.cs b/Src/Newtonsoft.Json/Utilities/StringUtils.cs index 3bb5ddc3..e6cd6c6d 100644 --- a/Src/Newtonsoft.Json/Utilities/StringUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/StringUtils.cs @@ -41,11 +41,6 @@ namespace Newtonsoft.Json.Utilities public const char LineFeed = '\n'; public const char Tab = '\t'; - //public static string FormatWith(this string format, params object[] args) - //{ - // return FormatWith(format, null, args); - //} - public static string FormatWith(this string format, IFormatProvider provider, params object[] args) { ValidationUtils.ArgumentNotNull(format, "format"); @@ -53,26 +48,6 @@ namespace Newtonsoft.Json.Utilities return string.Format(provider, format, args); } - /// - /// Determines whether the string contains white space. - /// - /// The string to test for white space. - /// - /// true if the string contains white space; otherwise, false. - /// - public static bool ContainsWhiteSpace(string s) - { - if (s == null) - throw new ArgumentNullException("s"); - - for (int i = 0; i < s.Length; i++) - { - if (char.IsWhiteSpace(s[i])) - return true; - } - return false; - } - /// /// Determines whether the string is all white space. Empty string will return false. /// @@ -97,152 +72,6 @@ namespace Newtonsoft.Json.Utilities return true; } - /// - /// Ensures the target string ends with the specified string. - /// - /// The target. - /// The value. - /// The target string with the value string at the end. - public static string EnsureEndsWith(string target, string value) - { - if (target == null) - throw new ArgumentNullException("target"); - - if (value == null) - throw new ArgumentNullException("value"); - - if (target.Length >= value.Length) - { - if (string.Compare(target, target.Length - value.Length, value, 0, value.Length, StringComparison.OrdinalIgnoreCase) == - 0) - return target; - - string trimmedString = target.TrimEnd(null); - - if (string.Compare(trimmedString, trimmedString.Length - value.Length, value, 0, value.Length, - StringComparison.OrdinalIgnoreCase) == 0) - return target; - } - - return target + value; - } - - public static bool IsNullOrEmptyOrWhiteSpace(string s) - { - if (string.IsNullOrEmpty(s)) - return true; - else if (IsWhiteSpace(s)) - return true; - else - return false; - } - - /// - /// Perform an action if the string is not null or empty. - /// - /// The value. - /// The action to perform. - public static void IfNotNullOrEmpty(string value, Action action) - { - IfNotNullOrEmpty(value, action, null); - } - - private static void IfNotNullOrEmpty(string value, Action trueAction, Action falseAction) - { - if (!string.IsNullOrEmpty(value)) - { - if (trueAction != null) - trueAction(value); - } - else - { - if (falseAction != null) - falseAction(value); - } - } - - /// - /// Indents the specified string. - /// - /// The string to indent. - /// The number of characters to indent by. - /// - public static string Indent(string s, int indentation) - { - return Indent(s, indentation, ' '); - } - - /// - /// Indents the specified string. - /// - /// The string to indent. - /// The number of characters to indent by. - /// The indent character. - /// - public static string Indent(string s, int indentation, char indentChar) - { - if (s == null) - throw new ArgumentNullException("s"); - - if (indentation <= 0) - throw new ArgumentException("Must be greater than zero.", "indentation"); - - StringReader sr = new StringReader(s); - StringWriter sw = new StringWriter(CultureInfo.InvariantCulture); - - ActionTextReaderLine(sr, sw, delegate(TextWriter tw, string line) - { - tw.Write(new string(indentChar, indentation)); - tw.Write(line); - }); - - return sw.ToString(); - } - - private delegate void ActionLine(TextWriter textWriter, string line); - - private static void ActionTextReaderLine(TextReader textReader, TextWriter textWriter, ActionLine lineAction) - { - string line; - bool firstLine = true; - while ((line = textReader.ReadLine()) != null) - { - if (!firstLine) - textWriter.WriteLine(); - else - firstLine = false; - - lineAction(textWriter, line); - } - } - - /// - /// Numbers the lines. - /// - /// The string to number. - /// - public static string NumberLines(string s) - { - if (s == null) - throw new ArgumentNullException("s"); - - StringReader sr = new StringReader(s); - StringWriter sw = new StringWriter(CultureInfo.InvariantCulture); - - int lineNumber = 1; - - ActionTextReaderLine(sr, sw, delegate(TextWriter tw, string line) - { - tw.Write(lineNumber.ToString(CultureInfo.InvariantCulture).PadLeft(4)); - tw.Write(". "); - tw.Write(line); - - lineNumber++; - }); - - return sw.ToString(); - } - /// /// Nulls an empty string. /// @@ -253,60 +82,6 @@ namespace Newtonsoft.Json.Utilities return (string.IsNullOrEmpty(s)) ? null : s; } - public static string ReplaceNewLines(string s, string replacement) - { - StringReader sr = new StringReader(s); - StringBuilder sb = new StringBuilder(); - - bool first = true; - - string line; - while ((line = sr.ReadLine()) != null) - { - if (first) - first = false; - else - sb.Append(replacement); - - sb.Append(line); - } - - return sb.ToString(); - } - - public static string Truncate(string s, int maximumLength) - { - return Truncate(s, maximumLength, "..."); - } - - public static string Truncate(string s, int maximumLength, string suffix) - { - if (suffix == null) - throw new ArgumentNullException("suffix"); - - if (maximumLength <= 0) - throw new ArgumentException("Maximum length must be greater than zero.", "maximumLength"); - - int subStringLength = maximumLength - suffix.Length; - - if (subStringLength <= 0) - throw new ArgumentException("Length of suffix string is greater or equal to maximumLength"); - - if (s != null && s.Length > maximumLength) - { - string truncatedString = s.Substring(0, subStringLength); - // incase the last character is a space - truncatedString = truncatedString.Trim(); - truncatedString += suffix; - - return truncatedString; - } - else - { - return s; - } - } - public static StringWriter CreateStringWriter(int capacity) { StringBuilder sb = new StringBuilder(capacity); @@ -333,23 +108,6 @@ namespace Newtonsoft.Json.Utilities return new string(new[] { '\\', 'u', h1, h2, h3, h4 }); } - public static void WriteCharAsUnicode(TextWriter writer, char c) - { - ValidationUtils.ArgumentNotNull(writer, "writer"); - - char h1 = MathUtils.IntToHex((c >> 12) & '\x000f'); - char h2 = MathUtils.IntToHex((c >> 8) & '\x000f'); - char h3 = MathUtils.IntToHex((c >> 4) & '\x000f'); - char h4 = MathUtils.IntToHex(c & '\x000f'); - - writer.Write('\\'); - writer.Write('u'); - writer.Write(h1); - writer.Write(h2); - writer.Write(h3); - writer.Write(h4); - } - public static TSource ForgivingCaseSensitiveFind(this IEnumerable source, Func valueSelector, string testValue) { if (source == null) @@ -357,7 +115,7 @@ namespace Newtonsoft.Json.Utilities if (valueSelector == null) throw new ArgumentNullException("valueSelector"); - var caseInsensitiveResults = source.Where(s => string.Compare(valueSelector(s), testValue, StringComparison.OrdinalIgnoreCase) == 0); + var caseInsensitiveResults = source.Where(s => string.Equals(valueSelector(s), testValue, StringComparison.OrdinalIgnoreCase)); if (caseInsensitiveResults.Count() <= 1) { return caseInsensitiveResults.SingleOrDefault(); @@ -365,7 +123,7 @@ namespace Newtonsoft.Json.Utilities else { // multiple results returned. now filter using case sensitivity - var caseSensitiveResults = source.Where(s => string.Compare(valueSelector(s), testValue, StringComparison.Ordinal) == 0); + var caseSensitiveResults = source.Where(s => string.Equals(valueSelector(s), testValue, StringComparison.Ordinal)); return caseSensitiveResults.SingleOrDefault(); } } diff --git a/Src/Newtonsoft.Json/Utilities/ValidationUtils.cs b/Src/Newtonsoft.Json/Utilities/ValidationUtils.cs index 50654480..47e724e6 100644 --- a/Src/Newtonsoft.Json/Utilities/ValidationUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/ValidationUtils.cs @@ -33,12 +33,6 @@ namespace Newtonsoft.Json.Utilities { internal static class ValidationUtils { - public const string EmailAddressRegex = @"^([a-zA-Z0-9_'+*$%\^&!\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9:]{2,4})+$"; - public const string CurrencyRegex = @"(^\$?(?!0,?\d)\d{1,3}(,?\d{3})*(\.\d\d)?)$"; - public const string DateRegex = - @"^(((0?[1-9]|[12]\d|3[01])[\.\-\/](0?[13578]|1[02])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}|\d))|((0?[1-9]|[12]\d|30)[\.\-\/](0?[13456789]|1[012])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}|\d))|((0?[1-9]|1\d|2[0-8])[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}|\d))|(29[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00|[048])))$"; - public const string NumericRegex = @"\d*"; - public static void ArgumentNotNullOrEmpty(string value, string parameterName) { if (value == null) @@ -48,14 +42,6 @@ namespace Newtonsoft.Json.Utilities throw new ArgumentException("'{0}' cannot be empty.".FormatWith(CultureInfo.InvariantCulture, parameterName), parameterName); } - public static void ArgumentNotNullOrEmptyOrWhitespace(string value, string parameterName) - { - ArgumentNotNullOrEmpty(value, parameterName); - - if (StringUtils.IsWhiteSpace(value)) - throw new ArgumentException("'{0}' cannot only be whitespace.".FormatWith(CultureInfo.InvariantCulture, parameterName), parameterName); - } - public static void ArgumentTypeIsEnum(Type enumType, string parameterName) { ArgumentNotNull(enumType, "enumType"); @@ -78,68 +64,12 @@ namespace Newtonsoft.Json.Utilities throw new ArgumentException(message, parameterName); } - public static void ArgumentNotNullOrEmpty(ICollection collection, string parameterName) - { - ArgumentNotNullOrEmpty(collection, parameterName, "Collection '{0}' cannot be empty.".FormatWith(CultureInfo.InvariantCulture, parameterName)); - } - - public static void ArgumentNotNullOrEmpty(ICollection collection, string parameterName, string message) - { - if (collection == null) - throw new ArgumentNullException(parameterName); - - if (collection.Count == 0) - throw new ArgumentException(message, parameterName); - } - public static void ArgumentNotNull(object value, string parameterName) { if (value == null) throw new ArgumentNullException(parameterName); } - public static void ArgumentNotNegative(int value, string parameterName) - { - if (value <= 0) - throw MiscellaneousUtils.CreateArgumentOutOfRangeException(parameterName, value, "Argument cannot be negative."); - } - - public static void ArgumentNotNegative(int value, string parameterName, string message) - { - if (value <= 0) - throw MiscellaneousUtils.CreateArgumentOutOfRangeException(parameterName, value, message); - } - - public static void ArgumentNotZero(int value, string parameterName) - { - if (value == 0) - throw MiscellaneousUtils.CreateArgumentOutOfRangeException(parameterName, value, "Argument cannot be zero."); - } - - public static void ArgumentNotZero(int value, string parameterName, string message) - { - if (value == 0) - throw MiscellaneousUtils.CreateArgumentOutOfRangeException(parameterName, value, message); - } - - public static void ArgumentIsPositive(T value, string parameterName) where T : struct, IComparable - { - if (value.CompareTo(default(T)) != 1) - throw MiscellaneousUtils.CreateArgumentOutOfRangeException(parameterName, value, "Positive number required."); - } - - public static void ArgumentIsPositive(int value, string parameterName, string message) - { - if (value > 0) - throw MiscellaneousUtils.CreateArgumentOutOfRangeException(parameterName, value, message); - } - - public static void ObjectNotDisposed(bool disposed, Type objectType) - { - if (disposed) - throw new ObjectDisposedException(objectType.Name); - } - public static void ArgumentConditionTrue(bool condition, string parameterName, string message) { if (!condition)