Json.NET
Code Coverage Statistics for Source File

Newtonsoft.Json\Converters\BinaryConverter.cs

Symbol Coverage: 82.35% (28 of 34)

Branch Coverage: 82.61% (19 of 23)

Cyclomatic Complexity Avg: 3.40 Max:7

Code Lines: 36


L V Source
1
#region License
2
// Copyright (c) 2007 James Newton-King
3
//
4
// Permission is hereby granted, free of charge, to any person
5
// obtaining a copy of this software and associated documentation
6
// files (the "Software"), to deal in the Software without
7
// restriction, including without limitation the rights to use,
8
// copy, modify, merge, publish, distribute, sublicense, and/or sell
9
// copies of the Software, and to permit persons to whom the
10
// Software is furnished to do so, subject to the following
11
// conditions:
12
//
13
// The above copyright notice and this permission notice shall be
14
// included in all copies or substantial portions of the Software.
15
//
16
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
18
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
20
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
21
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
23
// OTHER DEALINGS IN THE SOFTWARE.
24
#endregion
25

  
26
using System;
27
#if !SILVERLIGHT
28
using System.Data.SqlTypes;
29
#endif
30
using System.Globalization;
31
using Newtonsoft.Json.Utilities;
32

  
33
namespace Newtonsoft.Json.Converters
34
{
35
#if !SILVERLIGHT && !PocketPC && !NET20
36
  internal interface IBinary
37
  {
38
    byte[] ToArray();
39
  }
40
#endif
41

  
42
  /// <summary>
43
  /// Converts a binary value to and from a base 64 string value.
44
  /// </summary>
45
  public class BinaryConverter : JsonConverter
46
  {
47
#if !SILVERLIGHT && !PocketPC && !NET20
48
    private const string BinaryTypeName = "System.Data.Linq.Binary";
49
#endif
50

  
51
    /// <summary>
52
    /// Writes the JSON representation of the object.
53
    /// </summary>
54
    /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
55
    /// <param name="value">The value.</param>
56
    /// <param name="serializer">The calling serializer.</param>
57
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
58
    {
59
 3
      if (value == null)
60
      {
61
 0
        writer.WriteNull();
62
 0
        return;
63
      }
64

  
65
 3
      byte[] data = GetByteArray(value);
66

  
67
 3
      writer.WriteValue(data);
68
 3
    }
69

  
70
    private byte[] GetByteArray(object value)
71
    {
72
#if !SILVERLIGHT && !PocketPC && !NET20
73
 3
      if (value.GetType().AssignableToTypeName(BinaryTypeName))
74
      {
75
 1
        IBinary binary = DynamicWrapper.CreateWrapper<IBinary>(value);
76
 1
        return binary.ToArray();
77
      }
78
#endif
79
#if !SILVERLIGHT
80
 2
      if (value is SqlBinary)
81
 2
        return ((SqlBinary) value).Value;
82
#endif
83
 0
      throw new Exception("Unexpected value type when writing binary: {0}".FormatWith(CultureInfo.InvariantCulture, value.GetType()));
84
 3
    }
85

  
86
    /// <summary>
87
    /// Reads the JSON representation of the object.
88
    /// </summary>
89
    /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
90
    /// <param name="objectType">Type of the object.</param>
91
    /// <param name="existingValue">The existing value of object being read.</param>
92
    /// <param name="serializer">The calling serializer.</param>
93
    /// <returns>The object value.</returns>
94
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
95
    {
96
 5
      Type t = (ReflectionUtils.IsNullableType(objectType))
97
 5
        ? Nullable.GetUnderlyingType(objectType)
98
 5
        : objectType;
99

  
100
 5
      if (reader.TokenType == JsonToken.Null)
101
      {
102
 2
        if (!ReflectionUtils.IsNullable(objectType))
103
 0
          throw new Exception("Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
104

  
105
 2
        return null;
106
      }
107

  
108
 3
      if (reader.TokenType != JsonToken.String)
109
 0
        throw new Exception("Unexpected token parsing binary. Expected String, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
110

  
111
      // current token is already at base64 string
112
      // unable to call ReadAsBytes so do it the old fashion way
113
 3
      string encodedData = reader.Value.ToString();
114
 3
      byte[] data = Convert.FromBase64String(encodedData);
115

  
116
#if !SILVERLIGHT && !PocketPC && !NET20
117
 3
      if (t.AssignableToTypeName(BinaryTypeName))
118
 1
        return Activator.CreateInstance(t, data);
119
#endif
120
#if !SILVERLIGHT
121
 2
      if (t == typeof(SqlBinary))
122
 2
        return new SqlBinary(data);
123
#endif
124
 0
      throw new Exception("Unexpected object type when writing binary: {0}".FormatWith(CultureInfo.InvariantCulture, objectType));
125
 5
    }
126

  
127
    /// <summary>
128
    /// Determines whether this instance can convert the specified object type.
129
    /// </summary>
130
    /// <param name="objectType">Type of the object.</param>
131
    /// <returns>
132
    /// 	<c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.
133
    /// </returns>
134
    public override bool CanConvert(Type objectType)
135
    {
136
#if !SILVERLIGHT && !PocketPC && !NET20
137
 325
      if (objectType.AssignableToTypeName(BinaryTypeName))
138
 4
        return true;
139
#endif
140
#if !SILVERLIGHT
141
 321
      if (objectType == typeof(SqlBinary) || objectType == typeof(SqlBinary?))
142
 7
        return true;
143
#endif
144
 314
      return false;
145
 325
    }
146
  }
147
}