-Removed unused utility methods

-Fixed various code warnings
This commit is contained in:
JamesNK
2012-01-17 11:22:16 +00:00
parent 2941344044
commit 61db48c01d
29 changed files with 59 additions and 1131 deletions
@@ -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
@@ -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)
{
+2 -2
View File
@@ -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)
{
+1 -1
View File
@@ -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));
}
/// <summary>
@@ -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();
@@ -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)
{
@@ -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;
/// <summary>
/// Gets or sets how reference loops (e.g. a class referencing itself) is handled.
@@ -116,6 +116,11 @@ namespace Newtonsoft.Json
/// <value>The context.</value>
public StreamingContext Context { get; set; }
static JsonSerializerSettings()
{
DefaultContext = new StreamingContext();
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonSerializerSettings"/> class.
/// </summary>
+2 -2
View File
@@ -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
+1 -1
View File
@@ -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());
+2 -2
View File
@@ -182,7 +182,7 @@ namespace Newtonsoft.Json.Linq
{
foreach (JToken t in token.Children())
{
yield return t.Convert<JToken, U>(); ;
yield return t.Convert<JToken, U>();
}
}
}
@@ -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<JToken, U>(token);
}
+1 -1
View File
@@ -39,7 +39,7 @@ namespace Newtonsoft.Json.Linq
/// </summary>
public class JArray : JContainer, IList<JToken>
{
private IList<JToken> _values = new List<JToken>();
private readonly IList<JToken> _values = new List<JToken>();
/// <summary>
/// Gets the container's children tokens.
+1 -1
View File
@@ -38,7 +38,7 @@ namespace Newtonsoft.Json.Linq
public class JConstructor : JContainer
{
private string _name;
private IList<JToken> _values = new List<JToken>();
private readonly IList<JToken> _values = new List<JToken>();
/// <summary>
/// Gets the container's children tokens.
+1 -1
View File
@@ -18,7 +18,7 @@ namespace Newtonsoft.Json.Linq
/// </summary>
public static readonly JEnumerable<T> Empty = new JEnumerable<T>(Enumerable.Empty<T>());
private IEnumerable<T> _enumerable;
private readonly IEnumerable<T> _enumerable;
/// <summary>
/// Initializes a new instance of the <see cref="JEnumerable{T}"/> struct.
+1 -1
View File
@@ -83,7 +83,7 @@ namespace Newtonsoft.Json.Linq
}
}
private JPropertKeyedCollection _properties = new JPropertKeyedCollection(StringComparer.Ordinal);
private readonly JPropertKeyedCollection _properties = new JPropertKeyedCollection(StringComparer.Ordinal);
/// <summary>
/// Gets the container's children tokens.
+1 -1
View File
@@ -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;
}
/// <summary>
+2 -1
View File
@@ -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);
}
/// <summary>
+2 -2
View File
@@ -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);
@@ -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)]
@@ -77,7 +77,7 @@ namespace Newtonsoft.Json.Schema
}
private JsonSchemaResolver _resolver;
private IList<TypeSchema> _stack = new List<TypeSchema>();
private readonly IList<TypeSchema> _stack = new List<TypeSchema>();
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)
@@ -43,27 +43,6 @@ namespace Newtonsoft.Json.Utilities
return enumerable.Cast<object>().Where(o => o is T).Cast<T>();
}
public static List<T> CreateList<T>(params T[] values)
{
return new List<T>(values);
}
/// <summary>
/// Determines whether the collection is null or empty.
/// </summary>
/// <param name="collection">The collection.</param>
/// <returns>
/// <c>true</c> if the collection is null or empty; otherwise, <c>false</c>.
/// </returns>
public static bool IsNullOrEmpty(ICollection collection)
{
if (collection != null)
{
return (collection.Count == 0);
}
return true;
}
/// <summary>
/// Determines whether the collection is null or empty.
/// </summary>
@@ -80,113 +59,6 @@ namespace Newtonsoft.Json.Utilities
return true;
}
/// <summary>
/// Determines whether the collection is null, empty or its contents are uninitialized values.
/// </summary>
/// <param name="list">The list.</param>
/// <returns>
/// <c>true</c> if the collection is null or empty or its contents are uninitialized values; otherwise, <c>false</c>.
/// </returns>
public static bool IsNullOrEmptyOrDefault<T>(IList<T> list)
{
if (IsNullOrEmpty<T>(list))
return true;
return ReflectionUtils.ItemsUnitializedValue<T>(list);
}
/// <summary>
/// Makes a slice of the specified list in between the start and end indexes.
/// </summary>
/// <param name="list">The list.</param>
/// <param name="start">The start index.</param>
/// <param name="end">The end index.</param>
/// <returns>A slice of the list.</returns>
public static IList<T> Slice<T>(IList<T> list, int? start, int? end)
{
return Slice<T>(list, start, end, null);
}
/// <summary>
/// Makes a slice of the specified list in between the start and end indexes,
/// getting every so many items based upon the step.
/// </summary>
/// <param name="list">The list.</param>
/// <param name="start">The start index.</param>
/// <param name="end">The end index.</param>
/// <param name="step">The step.</param>
/// <returns>A slice of the list.</returns>
public static IList<T> Slice<T>(IList<T> 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<T> slicedList = new List<T>();
// 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;
}
/// <summary>
/// Group the collection using a function which returns the key.
/// </summary>
/// <param name="source">The source collection to group.</param>
/// <param name="keySelector">The key selector.</param>
/// <returns>A Dictionary with each key relating to a list of objects in a list grouped under it.</returns>
public static Dictionary<K, List<V>> GroupBy<K, V>(ICollection<V> source, Func<V, K> keySelector)
{
if (keySelector == null)
throw new ArgumentNullException("keySelector");
Dictionary<K, List<V>> groupedValues = new Dictionary<K, List<V>>();
foreach (V value in source)
{
// using delegate to get the value's key
K key = keySelector(value);
List<V> groupedValueList;
// add a list for grouped values if the key is not already in Dictionary
if (!groupedValues.TryGetValue(key, out groupedValueList))
{
groupedValueList = new List<V>();
groupedValues.Add(key, groupedValueList);
}
groupedValueList.Add(value);
}
return groupedValues;
}
/// <summary>
/// Adds the elements of the specified collection to the specified generic IList.
/// </summary>
@@ -214,126 +86,6 @@ namespace Newtonsoft.Json.Utilities
wrapper.AddRange(collection.Cast<object>());
}
public static List<T> Distinct<T>(List<T> collection)
{
List<T> distinctList = new List<T>();
foreach (T value in collection)
{
if (!distinctList.Contains(value))
distinctList.Add(value);
}
return distinctList;
}
public static List<List<T>> Flatten<T>(params IList<T>[] lists)
{
List<List<T>> flattened = new List<List<T>>();
Dictionary<int, T> currentList = new Dictionary<int, T>();
Recurse<T>(new List<IList<T>>(lists), 0, currentList, flattened);
return flattened;
}
private static void Recurse<T>(IList<IList<T>> global, int current, Dictionary<int, T> currentSet, List<List<T>> flattenedResult)
{
IList<T> currentArray = global[current];
for (int i = 0; i < currentArray.Count; i++)
{
currentSet[current] = currentArray[i];
if (current == global.Count - 1)
{
List<T> items = new List<T>();
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<T> CreateList<T>(ICollection collection)
{
if (collection == null)
throw new ArgumentNullException("collection");
T[] array = new T[collection.Count];
collection.CopyTo(array, 0);
return new List<T>(array);
}
public static bool ListEquals<T>(IList<T> a, IList<T> b)
{
if (a == null || b == null)
return (a == null && b == null);
if (a.Count != b.Count)
return false;
EqualityComparer<T> comparer = EqualityComparer<T>.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<T>(IList<T> list, out T value)
{
return TryGetSingleItem<T>(list, false, out value);
}
public static bool TryGetSingleItem<T>(IList<T> list, bool returnDefaultIfEmpty, out T value)
{
return MiscellaneousUtils.TryAction<T>(delegate { return GetSingleItem(list, returnDefaultIfEmpty); }, out value);
}
public static T GetSingleItem<T>(IList<T> list)
{
return GetSingleItem<T>(list, false);
}
public static T GetSingleItem<T>(IList<T> 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<T> Minus<T>(IList<T> list, IList<T> minus)
{
ValidationUtils.ArgumentNotNull(list, "list");
List<T> result = new List<T>(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<Type, IList<object>, 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<object>((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<T>(this IList<T> list, IEnumerable<T> values)
{
return list.AddRangeDistinct(values, EqualityComparer<T>.Default);
}
public static bool AddRangeDistinct<T>(this IList<T> list, IEnumerable<T> values, IEqualityComparer<T> comparer)
{
bool allAdded = true;
@@ -632,18 +316,6 @@ namespace Newtonsoft.Json.Utilities
return -1;
}
/// <summary>
/// Returns the index of the first occurrence in a sequence by using the default equality comparer.
/// </summary>
/// <typeparam name="TSource">The type of the elements of source.</typeparam>
/// <param name="list">A sequence in which to locate a value.</param>
/// <param name="value">The object to locate in the sequence</param>
/// <returns>The zero-based index of the first occurrence of value within the entire sequence, if found; otherwise, –1.</returns>
public static int IndexOf<TSource>(this IEnumerable<TSource> list, TSource value) where TSource : IEquatable<TSource>
{
return list.IndexOf<TSource>(value, EqualityComparer<TSource>.Default);
}
/// <summary>
/// Returns the index of the first occurrence in a sequence by using a specified IEqualityComparer.
/// </summary>
@@ -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
/// <summary>
/// Converts the value to the specified type.
/// </summary>
/// <typeparam name="T">The type to convert the value to.</typeparam>
/// <param name="initialValue">The value to convert.</param>
/// <returns>The converted type.</returns>
public static T Convert<T>(object initialValue)
{
return Convert<T>(initialValue, CultureInfo.CurrentCulture);
}
/// <summary>
/// Converts the value to the specified type.
/// </summary>
/// <typeparam name="T">The type to convert the value to.</typeparam>
/// <param name="initialValue">The value to convert.</param>
/// <param name="culture">The culture to use when converting.</param>
/// <returns>The converted type.</returns>
public static T Convert<T>(object initialValue, CultureInfo culture)
{
return (T)Convert(initialValue, culture, typeof(T));
}
/// <summary>
/// Converts the value to the specified type.
/// </summary>
@@ -285,41 +200,6 @@ namespace Newtonsoft.Json.Utilities
#endregion
#region TryConvert
/// <summary>
/// Converts the value to the specified type.
/// </summary>
/// <typeparam name="T">The type to convert the value to.</typeparam>
/// <param name="initialValue">The value to convert.</param>
/// <param name="convertedValue">The converted value if the conversion was successful or the default value of <c>T</c> if it failed.</param>
/// <returns>
/// <c>true</c> if <c>initialValue</c> was converted successfully; otherwise, <c>false</c>.
/// </returns>
public static bool TryConvert<T>(object initialValue, out T convertedValue)
{
return TryConvert(initialValue, CultureInfo.CurrentCulture, out convertedValue);
}
/// <summary>
/// Converts the value to the specified type.
/// </summary>
/// <typeparam name="T">The type to convert the value to.</typeparam>
/// <param name="initialValue">The value to convert.</param>
/// <param name="culture">The culture to use when converting.</param>
/// <param name="convertedValue">The converted value if the conversion was successful or the default value of <c>T</c> if it failed.</param>
/// <returns>
/// <c>true</c> if <c>initialValue</c> was converted successfully; otherwise, <c>false</c>.
/// </returns>
public static bool TryConvert<T>(object initialValue, CultureInfo culture, out T convertedValue)
{
return MiscellaneousUtils.TryAction<T>(delegate
{
object tempConvertedValue;
TryConvert(initialValue, CultureInfo.CurrentCulture, typeof(T), out tempConvertedValue);
return (T)tempConvertedValue;
}, out convertedValue);
}
/// <summary>
/// Converts the value to the specified type.
/// </summary>
@@ -337,31 +217,6 @@ namespace Newtonsoft.Json.Utilities
#endregion
#region ConvertOrCast
/// <summary>
/// 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.
/// </summary>
/// <typeparam name="T">The type to convert or cast the value to.</typeparam>
/// <param name="initialValue">The value to convert.</param>
/// <returns>The converted type. If conversion was unsuccessful, the initial value is returned if assignable to the target type</returns>
public static T ConvertOrCast<T>(object initialValue)
{
return ConvertOrCast<T>(initialValue, CultureInfo.CurrentCulture);
}
/// <summary>
/// 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.
/// </summary>
/// <typeparam name="T">The type to convert or cast the value to.</typeparam>
/// <param name="initialValue">The value to convert.</param>
/// <param name="culture">The culture to use when converting.</param>
/// <returns>The converted type. If conversion was unsuccessful, the initial value is returned if assignable to the target type</returns>
public static T ConvertOrCast<T>(object initialValue, CultureInfo culture)
{
return (T)ConvertOrCast(initialValue, culture, typeof(T));
}
/// <summary>
/// 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
/// <summary>
/// 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.
/// </summary>
/// <typeparam name="T">The type to convert the value to.</typeparam>
/// <param name="initialValue">The value to convert.</param>
/// <param name="convertedValue">The converted value if the conversion was successful or the default value of <c>T</c> if it failed.</param>
/// <returns>
/// <c>true</c> if <c>initialValue</c> was converted successfully or is assignable; otherwise, <c>false</c>.
/// </returns>
public static bool TryConvertOrCast<T>(object initialValue, out T convertedValue)
{
return TryConvertOrCast<T>(initialValue, CultureInfo.CurrentCulture, out convertedValue);
}
/// <summary>
/// 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.
/// </summary>
/// <typeparam name="T">The type to convert the value to.</typeparam>
/// <param name="initialValue">The value to convert.</param>
/// <param name="culture">The culture to use when converting.</param>
/// <param name="convertedValue">The converted value if the conversion was successful or the default value of <c>T</c> if it failed.</param>
/// <returns>
/// <c>true</c> if <c>initialValue</c> was converted successfully or is assignable; otherwise, <c>false</c>.
/// </returns>
public static bool TryConvertOrCast<T>(object initialValue, CultureInfo culture, out T convertedValue)
{
return MiscellaneousUtils.TryAction<T>(delegate
{
object tempConvertedValue;
TryConvertOrCast(initialValue, CultureInfo.CurrentCulture, typeof(T), out tempConvertedValue);
return (T)tempConvertedValue;
}, out convertedValue);
}
/// <summary>
/// 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.
/// </summary>
/// <param name="initialValue">The value to convert.</param>
/// <param name="culture">The culture to use when converting.</param>
/// <param name="targetType">The type to convert the value to.</param>
/// <param name="convertedValue">The converted value if the conversion was successful or the default value of <c>T</c> if it failed.</param>
/// <returns>
/// <c>true</c> if <c>initialValue</c> was converted successfully or is assignable; otherwise, <c>false</c>.
/// </returns>
public static bool TryConvertOrCast(object initialValue, CultureInfo culture, Type targetType, out object convertedValue)
{
return MiscellaneousUtils.TryAction<object>(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;
@@ -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))
{
@@ -33,36 +33,6 @@ namespace Newtonsoft.Json.Utilities
{
internal static class EnumUtils
{
/// <summary>
/// Parses the specified enum member name, returning it's value.
/// </summary>
/// <param name="enumMemberName">Name of the enum member.</param>
/// <returns></returns>
public static T Parse<T>(string enumMemberName) where T : struct
{
return Parse<T>(enumMemberName, false);
}
/// <summary>
/// Parses the specified enum member name, returning it's value.
/// </summary>
/// <param name="enumMemberName">Name of the enum member.</param>
/// <param name="ignoreCase">If set to <c>true</c> ignore case.</param>
/// <returns></returns>
public static T Parse<T>(string enumMemberName, bool ignoreCase) where T : struct
{
ValidationUtils.ArgumentTypeIsEnum(typeof(T), "T");
return (T)Enum.Parse(typeof(T), enumMemberName, ignoreCase);
}
public static bool TryParse<T>(string enumMemberName, bool ignoreCase, out T value) where T : struct
{
ValidationUtils.ArgumentTypeIsEnum(typeof(T), "T");
return MiscellaneousUtils.TryAction(() => Parse<T>(enumMemberName, ignoreCase), out value);
}
public static IList<T> GetFlagsValues<T>(T value) where T : struct
{
Type enumType = typeof(T);
@@ -97,17 +67,6 @@ namespace Newtonsoft.Json.Utilities
return GetNamesAndValues<ulong>(typeof(T));
}
/// <summary>
/// Gets a dictionary of the names and values of an Enum type.
/// </summary>
/// <returns></returns>
public static EnumValues<TUnderlyingType> GetNamesAndValues<TEnum, TUnderlyingType>()
where TEnum : struct
where TUnderlyingType : struct
{
return GetNamesAndValues<TUnderlyingType>(typeof(TEnum));
}
/// <summary>
/// Gets a dictionary of the names and values of an Enum type.
/// </summary>
@@ -142,11 +101,6 @@ namespace Newtonsoft.Json.Utilities
return nameValues;
}
public static IList<T> GetValues<T>()
{
return GetValues(typeof(T)).Cast<T>().ToList();
}
public static IList<object> GetValues(Type enumType)
{
if (!enumType.IsEnum)
@@ -167,11 +121,6 @@ namespace Newtonsoft.Json.Utilities
return values;
}
public static IList<string> GetNames<T>()
{
return GetNames(typeof(T));
}
public static IList<string> GetNames(Type enumType)
{
if (!enumType.IsEnum)
@@ -190,47 +139,5 @@ namespace Newtonsoft.Json.Utilities
return values;
}
/// <summary>
/// Gets the maximum valid value of an Enum type. Flags enums are ORed.
/// </summary>
/// <typeparam name="TEnumType">The type of the returned value. Must be assignable from the enum's underlying value type.</typeparam>
/// <param name="enumType">The enum type to get the maximum value for.</param>
/// <returns></returns>
public static TEnumType GetMaximumValue<TEnumType>(Type enumType) where TEnumType : IConvertible, IComparable<TEnumType>
{
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<object> 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);
}
}
}
+2 -2
View File
@@ -32,8 +32,8 @@ namespace Newtonsoft.Json.Utilities
{
internal class EnumValue<T> where T : struct
{
private string _name;
private T _value;
private readonly string _name;
private readonly T _value;
public string Name
{
@@ -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);
}
}
@@ -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)
@@ -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<ParameterInfo>(property.GetIndexParameters());
}
public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceDefinition)
{
Type implementingType;
@@ -441,45 +413,6 @@ namespace Newtonsoft.Json.Utilities
return keyType;
}
/// <summary>
/// Tests whether the list's items are their unitialized value.
/// </summary>
/// <param name="list">The list.</param>
/// <returns>Whether the list's items are their unitialized value</returns>
public static bool ItemsUnitializedValue<T>(IList<T> 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;
}
/// <summary>
/// Gets the member's underlying type.
/// </summary>
@@ -657,11 +590,6 @@ namespace Newtonsoft.Json.Utilities
}
}
public static List<MemberInfo> GetFieldsAndProperties<T>(BindingFlags bindingAttr)
{
return GetFieldsAndProperties(typeof(T), bindingAttr);
}
public static List<MemberInfo> GetFieldsAndProperties(Type type, BindingFlags bindingAttr)
{
List<MemberInfo> targetMembers = new List<MemberInfo>();
@@ -723,7 +651,7 @@ namespace Newtonsoft.Json.Utilities
{
T[] attributes = GetAttributes<T>(attributeProvider, inherit);
return CollectionUtils.GetSingleItem(attributes, true);
return attributes.SingleOrDefault();
}
public static T[] GetAttributes<T>(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)
{
+2 -244
View File
@@ -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);
}
/// <summary>
/// Determines whether the string contains white space.
/// </summary>
/// <param name="s">The string to test for white space.</param>
/// <returns>
/// <c>true</c> if the string contains white space; otherwise, <c>false</c>.
/// </returns>
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;
}
/// <summary>
/// Determines whether the string is all white space. Empty string will return false.
/// </summary>
@@ -97,152 +72,6 @@ namespace Newtonsoft.Json.Utilities
return true;
}
/// <summary>
/// Ensures the target string ends with the specified string.
/// </summary>
/// <param name="target">The target.</param>
/// <param name="value">The value.</param>
/// <returns>The target string with the value string at the end.</returns>
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;
}
/// <summary>
/// Perform an action if the string is not null or empty.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="action">The action to perform.</param>
public static void IfNotNullOrEmpty(string value, Action<string> action)
{
IfNotNullOrEmpty(value, action, null);
}
private static void IfNotNullOrEmpty(string value, Action<string> trueAction, Action<string> falseAction)
{
if (!string.IsNullOrEmpty(value))
{
if (trueAction != null)
trueAction(value);
}
else
{
if (falseAction != null)
falseAction(value);
}
}
/// <summary>
/// Indents the specified string.
/// </summary>
/// <param name="s">The string to indent.</param>
/// <param name="indentation">The number of characters to indent by.</param>
/// <returns></returns>
public static string Indent(string s, int indentation)
{
return Indent(s, indentation, ' ');
}
/// <summary>
/// Indents the specified string.
/// </summary>
/// <param name="s">The string to indent.</param>
/// <param name="indentation">The number of characters to indent by.</param>
/// <param name="indentChar">The indent character.</param>
/// <returns></returns>
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);
}
}
/// <summary>
/// Numbers the lines.
/// </summary>
/// <param name="s">The string to number.</param>
/// <returns></returns>
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();
}
/// <summary>
/// Nulls an empty string.
/// </summary>
@@ -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<TSource>(this IEnumerable<TSource> source, Func<TSource, string> 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();
}
}
@@ -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>(T value, string parameterName) where T : struct, IComparable<T>
{
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)