Json.NET

Top 10 Longest Uncovered Source Code Blocks


D:\Users\John\Documents\Work\Json.NET\Json\Newtonsoft.Json.Tests\Converters\CustomCreationConverterTests.cs, lines 39 to 90

L V Source
34
 0
      }
35
    }
36

  
37
    public void DeserializeObject()
38
    {
39
 0
      string json = JsonConvert.SerializeObject(new List<Employee>
40
 0
        {
41
 0
          new Employee
42
 0
            {
43
 0
              BirthDate = new DateTime(1977, 12, 30, 1, 1, 1, DateTimeKind.Utc),
44
 0
              FirstName = "Maurice",
45
 0
              LastName = "Moss",
46
 0
              Department = "IT",
47
 0
              JobTitle = "Support"
48
 0
            },
49
 0
          new Employee
50
 0
            {
51
 0
              BirthDate = new DateTime(1978, 3, 15, 1, 1, 1, DateTimeKind.Utc),
52
 0
              FirstName = "Jen",
53
 0
              LastName = "Barber",
54
 0
              Department = "IT",
55
 0
              JobTitle = "Manager"
56
 0
            }
57
 0
        }, Formatting.Indented);
58

  
59
      //[
60
      //  {
61
      //    "FirstName": "Maurice",
62
      //    "LastName": "Moss",
63
      //    "BirthDate": "\/Date(252291661000)\/",
64
      //    "Department": "IT",
65
      //    "JobTitle": "Support"
66
      //  },
67
      //  {
68
      //    "FirstName": "Jen",
69
      //    "LastName": "Barber",
70
      //    "BirthDate": "\/Date(258771661000)\/",
71
      //    "Department": "IT",
72
      //    "JobTitle": "Manager"
73
      //  }
74
      //]
75

  
76
 0
      List<IPerson> people = JsonConvert.DeserializeObject<List<IPerson>>(json, new PersonConverter());
77

  
78
 0
      IPerson person = people[0];
79

  
80
 0
      Console.WriteLine(person.GetType());
81
      // Newtonsoft.Json.Tests.Employee
82

  
83
 0
      Console.WriteLine(person.FirstName);
84
      // Maurice
85

  
86
 0
      Employee employee = (Employee)person;
87

  
88
 0
      Console.WriteLine(employee.JobTitle);
89
      // Support
90
 0
    }
91

  
92
    public class MyClass
93
    {
94
      public string Value { get; set; }

D:\Users\John\Documents\Work\Json.NET\Json\Newtonsoft.Json\Utilities\ConvertUtils.cs, lines 102 to 151

L V Source
97
 1
      return o => call(null, o);
98
 4
    }
99

  
100
    public static bool CanConvertType(Type initialType, Type targetType, bool allowTypeNameToString)
101
    {
102
 0
      ValidationUtils.ArgumentNotNull(initialType, "initialType");
103
 0
      ValidationUtils.ArgumentNotNull(targetType, "targetType");
104

  
105
 0
      if (ReflectionUtils.IsNullableType(targetType))
106
 0
        targetType = Nullable.GetUnderlyingType(targetType);
107

  
108
 0
      if (targetType == initialType)
109
 0
        return true;
110

  
111
 0
      if (typeof(IConvertible).IsAssignableFrom(initialType) && typeof(IConvertible).IsAssignableFrom(targetType))
112
      {
113
 0
        return true;
114
      }
115

  
116
#if !PocketPC && !NET20
117
 0
      if (initialType == typeof(DateTime) && targetType == typeof(DateTimeOffset))
118
 0
        return true;
119
#endif
120

  
121
 0
      if (initialType == typeof(Guid) && (targetType == typeof(Guid) || targetType == typeof(string)))
122
 0
        return true;
123

  
124
 0
      if (initialType == typeof(Type) && targetType == typeof(string))
125
 0
        return true;
126

  
127
#if !PocketPC
128
      // see if source or target types have a TypeConverter that converts between the two
129
 0
      TypeConverter toConverter = GetConverter(initialType);
130

  
131
 0
      if (toConverter != null && !IsComponentConverter(toConverter) && toConverter.CanConvertTo(targetType))
132
      {
133
 0
        if (allowTypeNameToString || toConverter.GetType() != typeof(TypeConverter))
134
 0
          return true;
135
      }
136

  
137
 0
      TypeConverter fromConverter = GetConverter(targetType);
138

  
139
 0
      if (fromConverter != null && !IsComponentConverter(fromConverter) && fromConverter.CanConvertFrom(initialType))
140
 0
        return true;
141
#endif
142

  
143
      // handle DBNull and INullable
144
 0
      if (initialType == typeof(DBNull))
145
      {
146
 0
        if (ReflectionUtils.IsNullable(targetType))
147
 0
          return true;
148
      }
149

  
150
 0
      return false;
151
 0
    }
152

  
153
    private static bool IsComponentConverter(TypeConverter converter)
154
    {
155
#if !SILVERLIGHT && !PocketPC

D:\Users\John\Documents\Work\Json.NET\Json\Newtonsoft.Json.Tests\Serialization\JsonSerializerTest.cs, lines 1199 to 1241

L V Source
1194
 1
      Console.WriteLine(javascriptJson);
1195
 1
    }
1196

  
1197
    public void GenericListAndDictionaryInterfaceProperties()
1198
    {
1199
 0
      GenericListAndDictionaryInterfaceProperties o = new GenericListAndDictionaryInterfaceProperties();
1200
 0
      o.IDictionaryProperty = new Dictionary<string, int>
1201
 0
                                {
1202
 0
                                  {"one", 1},
1203
 0
                                  {"two", 2},
1204
 0
                                  {"three", 3}
1205
 0
                                };
1206
 0
      o.IListProperty = new List<int>
1207
 0
                          {
1208
 0
                            1, 2, 3
1209
 0
                          };
1210
 0
      o.IEnumerableProperty = new List<int>
1211
 0
                                {
1212
 0
                                  4, 5, 6
1213
 0
                                };
1214

  
1215
 0
      string json = JsonConvert.SerializeObject(o, Formatting.Indented);
1216

  
1217
 0
      Assert.AreEqual(@"{
1218
 0
  ""IEnumerableProperty"": [
1219
 0
    4,
1220
 0
    5,
1221
 0
    6
1222
 0
  ],
1223
 0
  ""IListProperty"": [
1224
 0
    1,
1225
 0
    2,
1226
 0
    3
1227
 0
  ],
1228
 0
  ""IDictionaryProperty"": {
1229
 0
    ""one"": 1,
1230
 0
    ""two"": 2,
1231
 0
    ""three"": 3
1232
 0
  }
1233
 0
}", json);
1234

  
1235
 0
      GenericListAndDictionaryInterfaceProperties deserializedObject = JsonConvert.DeserializeObject<GenericListAndDictionaryInterfaceProperties>(json);
1236
 0
      Assert.IsNotNull(deserializedObject);
1237

  
1238
 0
      CollectionAssert.AreEqual(o.IListProperty.ToArray(), deserializedObject.IListProperty.ToArray());
1239
 0
      CollectionAssert.AreEqual(o.IEnumerableProperty.ToArray(), deserializedObject.IEnumerableProperty.ToArray());
1240
 0
      CollectionAssert.AreEqual(o.IDictionaryProperty.ToArray(), deserializedObject.IDictionaryProperty.ToArray());
1241
 0
    }
1242

  
1243
    [Test]
1244
    public void DeserializeBestMatchPropertyCase()
1245
    {

D:\Users\John\Documents\Work\Json.NET\Json\Newtonsoft.Json\Utilities\CollectionUtils.cs, lines 121 to 155

L V Source
116
    /// <param name="end">The end index.</param>
117
    /// <param name="step">The step.</param>
118
    /// <returns>A slice of the list.</returns>
119
    public static IList<T> Slice<T>(IList<T> list, int? start, int? end, int? step)
120
    {
121
 0
      if (list == null)
122
 0
        throw new ArgumentNullException("list");
123

  
124
 0
      if (step == 0)
125
 0
        throw new ArgumentException("Step cannot be zero.", "step");
126

  
127
 0
      List<T> slicedList = new List<T>();
128

  
129
      // nothing to slice
130
 0
      if (list.Count == 0)
131
 0
        return slicedList;
132

  
133
      // set defaults for null arguments
134
 0
      int s = step ?? 1;
135
 0
      int startIndex = start ?? 0;
136
 0
      int endIndex = end ?? list.Count;
137

  
138
      // start from the end of the list if start is negitive
139
 0
      startIndex = (startIndex < 0) ? list.Count + startIndex : startIndex;
140

  
141
      // end from the start of the list if end is negitive
142
 0
      endIndex = (endIndex < 0) ? list.Count + endIndex : endIndex;
143

  
144
      // ensure indexes keep within collection bounds
145
 0
      startIndex = Math.Max(startIndex, 0);
146
 0
      endIndex = Math.Min(endIndex, list.Count - 1);
147

  
148
      // loop between start and end indexes, incrementing by the step
149
 0
      for (int i = startIndex; i < endIndex; i += s)
150
      {
151
 0
        slicedList.Add(list[i]);
152
      }
153

  
154
 0
      return slicedList;
155
 0
    }
156

  
157

  
158
    /// <summary>
159
    /// Group the collection using a function which returns the key.

D:\Users\John\Documents\Work\Json.NET\Json\Newtonsoft.Json\Utilities\EnumUtils.cs, lines 203 to 234

L V Source
198
    /// <typeparam name="TEnumType">The type of the returned value. Must be assignable from the enum's underlying value type.</typeparam>
199
    /// <param name="enumType">The enum type to get the maximum value for.</param>
200
    /// <returns></returns>
201
    public static TEnumType GetMaximumValue<TEnumType>(Type enumType) where TEnumType : IConvertible, IComparable<TEnumType>
202
    {
203
 0
      if (enumType == null)
204
 0
        throw new ArgumentNullException("enumType");
205

  
206
 0
      Type enumUnderlyingType = Enum.GetUnderlyingType(enumType);
207

  
208
 0
      if (!typeof(TEnumType).IsAssignableFrom(enumUnderlyingType))
209
 0
        throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "TEnumType is not assignable from the enum's underlying type of {0}.", enumUnderlyingType.Name));
210

  
211
 0
      ulong maximumValue = 0;
212
 0
      IList<object> enumValues = GetValues(enumType);
213

  
214
 0
      if (enumType.IsDefined(typeof(FlagsAttribute), false))
215
      {
216
 0
        foreach (TEnumType value in enumValues)
217
        {
218
 0
          maximumValue = maximumValue | value.ToUInt64(CultureInfo.InvariantCulture);
219
        }
220
      }
221
      else
222
      {
223
 0
        foreach (TEnumType value in enumValues)
224
        {
225
 0
          ulong tempValue = value.ToUInt64(CultureInfo.InvariantCulture);
226

  
227
          // maximumValue is smaller than the enum value
228
 0
          if (maximumValue.CompareTo(tempValue) == -1)
229
 0
            maximumValue = tempValue;
230
        }
231
      }
232

  
233
 0
      return (TEnumType)Convert.ChangeType(maximumValue, typeof(TEnumType), CultureInfo.InvariantCulture);
234
 0
    }
235
  }
236
}

D:\Users\John\Documents\Work\Json.NET\Json\Newtonsoft.Json\Utilities\ReflectionUtils.cs, lines 362 to 392

L V Source
357
    /// </summary>
358
    /// <param name="list">The list.</param>
359
    /// <returns>Whether the list's items are their unitialized value</returns>
360
    public static bool ItemsUnitializedValue<T>(IList<T> list)
361
    {
362
 0
      ValidationUtils.ArgumentNotNull(list, "list");
363

  
364
 0
      Type elementType = GetCollectionItemType(list.GetType());
365

  
366
 0
      if (elementType.IsValueType)
367
      {
368
 0
        object unitializedValue = CreateUnitializedValue(elementType);
369

  
370
 0
        for (int i = 0; i < list.Count; i++)
371
        {
372
 0
          if (!list[i].Equals(unitializedValue))
373
 0
            return false;
374
        }
375
      }
376
 0
      else if (elementType.IsClass)
377
      {
378
 0
        for (int i = 0; i < list.Count; i++)
379
        {
380
 0
          object value = list[i];
381

  
382
 0
          if (value != null)
383
 0
            return false;
384
        }
385
      }
386
      else
387
      {
388
 0
        throw new Exception("Type {0} is neither a ValueType or a Class.".FormatWith(CultureInfo.InvariantCulture, elementType));
389
      }
390

  
391
 0
      return true;
392
 0
    }
393

  
394
    /// <summary>
395
    /// Gets the member's underlying type.
396
    /// </summary>

D:\Users\John\Documents\Work\Json.NET\Json\Newtonsoft.Json\Utilities\DictionaryWrapper.cs, lines 195 to 220

L V Source
190
 0
      }
191
    }
192

  
193
    public bool Remove(KeyValuePair<TKey, TValue> item)
194
    {
195
 0
      if (_genericDictionary != null)
196
      {
197
 0
        return _genericDictionary.Remove(item);
198
      }
199
      else
200
      {
201
 0
        if (_dictionary.Contains(item.Key))
202
        {
203
 0
          object value = _dictionary[item.Key];
204

  
205
 0
          if (object.Equals(value, item.Value))
206
          {
207
 0
            _dictionary.Remove(item.Key);
208
 0
            return true;
209
          }
210
          else
211
          {
212
 0
            return false;
213
          }
214
        }
215
        else
216
        {
217
 0
          return true;
218
        }
219
      }
220
 0
    }
221

  
222
    public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
223
    {
224
 0
      if (_genericDictionary != null)

D:\Users\John\Documents\Work\Json.NET\Json\Newtonsoft.Json\Utilities\StringUtils.cs, lines 284 to 308

L V Source
279
 0
      return Truncate(s, maximumLength, "...");
280
 0
    }
281

  
282
    public static string Truncate(string s, int maximumLength, string suffix)
283
    {
284
 0
      if (suffix == null)
285
 0
        throw new ArgumentNullException("suffix");
286

  
287
 0
      if (maximumLength <= 0)
288
 0
        throw new ArgumentException("Maximum length must be greater than zero.", "maximumLength");
289

  
290
 0
      int subStringLength = maximumLength - suffix.Length;
291

  
292
 0
      if (subStringLength <= 0)
293
 0
        throw new ArgumentException("Length of suffix string is greater or equal to maximumLength");
294

  
295
 0
      if (s != null && s.Length > maximumLength)
296
      {
297
 0
        string truncatedString = s.Substring(0, subStringLength);
298
        // incase the last character is a space
299
 0
        truncatedString = truncatedString.Trim();
300
 0
        truncatedString += suffix;
301

  
302
 0
        return truncatedString;
303
      }
304
      else
305
      {
306
 0
        return s;
307
      }
308
 0
    }
309

  
310
    public static StringWriter CreateStringWriter(int capacity)
311
    {
312
 38
      StringBuilder sb = new StringBuilder(capacity);

D:\Users\John\Documents\Work\Json.NET\Json\Newtonsoft.Json\Utilities\CollectionUtils.cs, lines 421 to 445

L V Source
416
 0
        throw new Exception("Can not create ListWrapper for type {0}.".FormatWith(CultureInfo.InvariantCulture, list.GetType()));
417
      }
418
 2
    }
419
    public static IWrappedList CreateListWrapper(object list)
420
    {
421
 0
      ValidationUtils.ArgumentNotNull(list, "list");
422

  
423
      Type listDefinition;
424
 0
      if (ReflectionUtils.ImplementsGenericDefinition(list.GetType(), typeof(IList<>), out listDefinition))
425
      {
426
 0
        Type collectionItemType = ReflectionUtils.GetCollectionItemType(listDefinition);
427

  
428
        // Activator.CreateInstance throws AmbiguousMatchException. Manually invoke constructor
429
 0
        Func<Type, IList<object>, object> instanceCreator = (t, a) =>
430
 0
        {
431
 0
          ConstructorInfo c = t.GetConstructor(new[] {listDefinition});
432
 0
          return c.Invoke(new[] { list });
433
 0
        };
434

  
435
 0
        return (IWrappedList)ReflectionUtils.CreateGeneric(typeof(ListWrapper<>), new[] { collectionItemType }, instanceCreator, list);
436
      }
437
 0
      else if (list is IList)
438
      {
439
 0
        return new ListWrapper<object>((IList)list);
440
      }
441
      else
442
      {
443
 0
        throw new Exception("Can not create ListWrapper for type {0}.".FormatWith(CultureInfo.InvariantCulture, list.GetType()));
444
      }
445
 0
    }
446

  
447
    public static IWrappedDictionary CreateDictionaryWrapper(object dictionary)
448
    {
449
 1
      ValidationUtils.ArgumentNotNull(dictionary, "dictionary");

D:\Users\John\Documents\Work\Json.NET\Json\Newtonsoft.Json.Tests\PerformanceTests.cs, lines 254 to 277

L V Source
249
 2
      return test;
250
 2
    }
251

  
252
    public string SerializeJsonNet(object value)
253
    {
254
 0
      Type type = value.GetType();
255

  
256
 0
      Newtonsoft.Json.JsonSerializer json = new Newtonsoft.Json.JsonSerializer();
257

  
258
 0
      json.NullValueHandling = NullValueHandling.Ignore;
259

  
260
 0
      json.ObjectCreationHandling = Newtonsoft.Json.ObjectCreationHandling.Replace;
261
 0
      json.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore;
262
 0
      json.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
263

  
264

  
265
 0
      StringWriter sw = new StringWriter();
266
 0
      Newtonsoft.Json.JsonTextWriter writer = new JsonTextWriter(sw);
267

  
268
 0
      writer.Formatting = Formatting.None;
269

  
270
 0
      writer.QuoteChar = '"';
271
 0
      json.Serialize(writer, value);
272

  
273
 0
      string output = sw.ToString();
274
 0
      writer.Close();
275

  
276
 0
      return output;
277
 0
    }
278

  
279
    public string SerializeWebExtensions(object value)
280
    {
281
 5001
      JavaScriptSerializer ser = new JavaScriptSerializer();