Added hammock project to debug streaming issues
[pithos-ms-client] / trunk / hammock / src / net35 / Hammock.Tests / Postmark / Converters / NameValueCollectionConverter.cs
1 using System;
2 using System.Collections.Specialized;
3 using System.Linq;
4 using Newtonsoft.Json;
5
6 namespace Hammock.Tests.Postmark.Converters
7 {
8     internal class NameValuePair
9     {
10         public string Name { get; set; }
11         public string Value { get; set; }
12     }
13
14     internal class NameValueCollectionConverter : JsonConverter
15     {
16         public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
17         {
18             if (!(value is NameValueCollection))
19             {
20                 return;
21             }
22
23             var collection = (NameValueCollection)value;
24             var container = collection.AllKeys.Select(key => new NameValuePair
25                                                                  {
26                                                                      Name = key,
27                                                                      Value = collection[key]
28                                                                  }).ToList();
29
30             var serialized = JsonConvert.SerializeObject(container);
31
32             writer.WriteRawValue(serialized);
33         }
34
35         public override object ReadJson(JsonReader reader, Type objectType, object originalValue, JsonSerializer serializer)
36         {
37             return reader.Value;
38         }
39
40         public override bool CanConvert(Type objectType)
41         {
42             var t = (IsNullableType(objectType))
43                         ? Nullable.GetUnderlyingType(objectType)
44                         : objectType;
45
46             return typeof(NameValueCollection).IsAssignableFrom(t);
47         }
48
49         public static bool IsNullable(Type type)
50         {
51             return type != null && (!type.IsValueType || IsNullableType(type));
52         }
53
54         public static bool IsNullableType(Type type)
55         {
56             if (type == null)
57             {
58                 return false;
59             }
60
61             return (type.IsGenericType &&
62                     type.GetGenericTypeDefinition() == typeof(Nullable<>));
63         }
64     }
65 }
66
67