Skip to content
This repository
Browse code

Added ByteArrayConverter to JSON.NET for Base64 conversion of byte ar…

…rays
  • Loading branch information...
commit e710cca1f39ee576ff84e2e4b9acebdc3f5f1b67 1 parent b5d9d0a
Chris Patterson authored March 28, 2012
125  src/MassTransit.Tests/Serialization/ByteArray_Specs.cs
... ...
@@ -1,64 +1,63 @@
1  
-// Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, Simon Guindon, et. al.
2  
-//  
3  
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not use 
4  
-// this file except in compliance with the License. You may obtain a copy of the 
5  
-// License at 
6  
-// 
7  
-//     http://www.apache.org/licenses/LICENSE-2.0 
8  
-// 
9  
-// Unless required by applicable law or agreed to in writing, software distributed 
10  
-// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 
11  
-// CONDITIONS OF ANY KIND, either express or implied. See the License for the 
12  
-// specific language governing permissions and limitations under the License.
13  
-namespace MassTransit.Tests.Serialization
14  
-{
15  
-    using System;
16  
-    using Magnum.TestFramework;
17  
-    using MassTransit.Testing;
18  
-
19  
-    [Scenario]
20  
-    public class When_a_byte_array_value_is_serialized
21  
-    {
22  
-        A _received;
23  
-        A _sent;
24  
-        HandlerTest<A> _test;
25  
-
26  
-        [When]
27  
-        public void Setup()
28  
-        {
29  
-            _test = TestFactory.ForHandler<A>()
30  
-                .New(x =>
31  
-                {
32  
-                    _sent = new A
33  
-                    {
34  
-                        Contents = new byte[] {0x56, 0x34, 0xf3}                        
35  
-                    };
36  
-                    x.Send(_sent);
37  
-
38  
-                    x.Handler((context, message) => { _received = message; });
39  
-                });
40  
-
41  
-            _test.Execute();
42  
-
43  
-            _test.Received.Any<A>().ShouldBeTrue();
44  
-        }
45  
-
46  
-        [Finally]
47  
-        public void Teardown()
48  
-        {
49  
-            _test.Dispose();
50  
-            _test = null;
51  
-        }
52  
-
53  
-        [Then]
54  
-        public void Should_receive_byte_array()
55  
-        {
56  
-            _sent.Contents.ShouldEqual(_received.Contents);
57  
-        }
58  
-
59  
-        class A
60  
-        {
61  
-            public byte[] Contents { get; set; }            
62  
-        }
63  
-    }
  1
+// Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al.
  2
+//  
  3
+// Licensed under the Apache License, Version 2.0 (the "License"); you may not use 
  4
+// this file except in compliance with the License. You may obtain a copy of the 
  5
+// License at 
  6
+// 
  7
+//     http://www.apache.org/licenses/LICENSE-2.0 
  8
+// 
  9
+// Unless required by applicable law or agreed to in writing, software distributed 
  10
+// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 
  11
+// CONDITIONS OF ANY KIND, either express or implied. See the License for the 
  12
+// specific language governing permissions and limitations under the License.
  13
+namespace MassTransit.Tests.Serialization
  14
+{
  15
+    using Magnum.TestFramework;
  16
+    using MassTransit.Testing;
  17
+
  18
+    [Scenario]
  19
+    public class When_a_byte_array_value_is_serialized
  20
+    {
  21
+        A _received;
  22
+        A _sent;
  23
+        HandlerTest<A> _test;
  24
+
  25
+        [When]
  26
+        public void Setup()
  27
+        {
  28
+            _test = TestFactory.ForHandler<A>()
  29
+                .New(x =>
  30
+                    {
  31
+                        _sent = new A
  32
+                            {
  33
+                                Contents = new byte[] {0x56, 0x34, 0xf3}
  34
+                            };
  35
+                        x.Send(_sent);
  36
+
  37
+                        x.Handler((context, message) => { _received = message; });
  38
+                    });
  39
+
  40
+            _test.Execute();
  41
+
  42
+            _test.Received.Any<A>().ShouldBeTrue();
  43
+        }
  44
+
  45
+        [Finally]
  46
+        public void Teardown()
  47
+        {
  48
+            _test.Dispose();
  49
+            _test = null;
  50
+        }
  51
+
  52
+        [Then]
  53
+        public void Should_receive_byte_array()
  54
+        {
  55
+            _sent.Contents.ShouldEqual(_received.Contents);
  56
+        }
  57
+
  58
+        class A
  59
+        {
  60
+            public byte[] Contents { get; set; }
  61
+        }
  62
+    }
64 63
 }
1  src/MassTransit/MassTransit.csproj
@@ -369,6 +369,7 @@
369 369
     <Compile Include="Saga\SubscriptionConnectors\StateMachineSagaConnector.cs" />
370 370
     <Compile Include="Saga\SubscriptionConnectors\StateMachineSagaWorkerConnector.cs" />
371 371
     <Compile Include="Serialization\BsonMessageSerializer.cs" />
  372
+    <Compile Include="Serialization\ByteArrayConverter.cs" />
372 373
     <Compile Include="Serialization\Custom\Continuation.cs" />
373 374
     <Compile Include="Serialization\DictionaryJsonConverter.cs" />
374 375
     <Compile Include="Serialization\EncryptedMessageEnvelope.cs" />
90  src/MassTransit/Serialization/ByteArrayConverter.cs
... ...
@@ -0,0 +1,90 @@
  1
+// Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al.
  2
+//  
  3
+// Licensed under the Apache License, Version 2.0 (the "License"); you may not use 
  4
+// this file except in compliance with the License. You may obtain a copy of the 
  5
+// License at 
  6
+// 
  7
+//     http://www.apache.org/licenses/LICENSE-2.0 
  8
+// 
  9
+// Unless required by applicable law or agreed to in writing, software distributed 
  10
+// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 
  11
+// CONDITIONS OF ANY KIND, either express or implied. See the License for the 
  12
+// specific language governing permissions and limitations under the License.
  13
+namespace MassTransit.Serialization
  14
+{
  15
+    using System;
  16
+    using System.Collections.Generic;
  17
+    using System.Globalization;
  18
+    using Newtonsoft.Json;
  19
+
  20
+    public class ByteArrayConverter :
  21
+        JsonConverter
  22
+    {
  23
+        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  24
+        {
  25
+            if (value == null)
  26
+            {
  27
+                writer.WriteNull();
  28
+            }
  29
+            else
  30
+            {
  31
+                byte[] byteArray = GetByteArray(value);
  32
+                writer.WriteValue(byteArray);
  33
+            }
  34
+        }
  35
+
  36
+        public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
  37
+                                        JsonSerializer serializer)
  38
+        {
  39
+            if (reader.TokenType == JsonToken.Null)
  40
+            {
  41
+                return null;
  42
+            }
  43
+            byte[] numArray;
  44
+            if (reader.TokenType == JsonToken.StartArray)
  45
+                numArray = ReadByteArray(reader);
  46
+            else if (reader.TokenType == JsonToken.String)
  47
+                numArray = Convert.FromBase64String(reader.Value.ToString());
  48
+            else
  49
+                throw new Exception(
  50
+                    string.Format("Unexpected token parsing binary. Expected String or StartArray, got {0}.",
  51
+                        reader.TokenType));
  52
+
  53
+            return numArray;
  54
+        }
  55
+
  56
+        public override bool CanConvert(Type objectType)
  57
+        {
  58
+            if (objectType == typeof(byte[]))
  59
+                return true;
  60
+
  61
+            return false;
  62
+        }
  63
+
  64
+        byte[] GetByteArray(object value)
  65
+        {
  66
+            return value as byte[];
  67
+        }
  68
+
  69
+        byte[] ReadByteArray(JsonReader reader)
  70
+        {
  71
+            var list = new List<byte>();
  72
+            while (reader.Read())
  73
+            {
  74
+                switch (reader.TokenType)
  75
+                {
  76
+                    case JsonToken.Comment:
  77
+                        continue;
  78
+                    case JsonToken.Integer:
  79
+                        list.Add(Convert.ToByte(reader.Value, CultureInfo.InvariantCulture));
  80
+                        continue;
  81
+                    case JsonToken.EndArray:
  82
+                        return list.ToArray();
  83
+                    default:
  84
+                        throw new Exception(string.Format("Unexpected token when reading bytes: {0}", reader.TokenType));
  85
+                }
  86
+            }
  87
+            throw new Exception("Unexpected end when reading bytes.");
  88
+        }
  89
+    }
  90
+}
4  src/MassTransit/Serialization/JsonMessageSerializer.cs
@@ -47,9 +47,10 @@ public static JsonSerializer Deserializer
47 47
                         ContractResolver = new JsonContractResolver(),
48 48
                         Converters = new List<JsonConverter>(new JsonConverter[]
49 49
                             {
  50
+                                new ByteArrayConverter(), 
50 51
                                 new ListJsonConverter(),
51 52
                                 new InterfaceProxyConverter(),
52  
-                                new StringDecimalConverter(), 
  53
+                                new StringDecimalConverter(),
53 54
                                 new IsoDateTimeConverter{DateTimeStyles = DateTimeStyles.RoundtripKind},
54 55
                             })
55 56
                     }));
@@ -70,6 +71,7 @@ public static JsonSerializer Serializer
70 71
                         ContractResolver = new JsonContractResolver(),
71 72
                         Converters = new List<JsonConverter>(new JsonConverter[]
72 73
                             {
  74
+                                new ByteArrayConverter(), 
73 75
                                 new IsoDateTimeConverter{DateTimeStyles = DateTimeStyles.RoundtripKind},
74 76
                             }),
75 77
                     }));
102  src/Transports/MassTransit.Transports.RabbitMq.Tests/Bytes_Specs.cs
... ...
@@ -0,0 +1,102 @@
  1
+// Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al.
  2
+//  
  3
+// Licensed under the Apache License, Version 2.0 (the "License"); you may not use 
  4
+// this file except in compliance with the License. You may obtain a copy of the 
  5
+// License at 
  6
+// 
  7
+//     http://www.apache.org/licenses/LICENSE-2.0 
  8
+// 
  9
+// Unless required by applicable law or agreed to in writing, software distributed 
  10
+// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 
  11
+// CONDITIONS OF ANY KIND, either express or implied. See the License for the 
  12
+// specific language governing permissions and limitations under the License.
  13
+namespace MassTransit.Transports.RabbitMq.Tests
  14
+{
  15
+    using System;
  16
+    using System.Linq;
  17
+    using BusConfigurators;
  18
+    using Magnum.Extensions;
  19
+    using Magnum.TestFramework;
  20
+    using NUnit.Framework;
  21
+    using TestFramework;
  22
+
  23
+    [TestFixture]
  24
+    public class Bytes_Specs :
  25
+        Given_a_rabbitmq_bus
  26
+    {
  27
+        A _sent;
  28
+        Future<A> _received;
  29
+
  30
+        protected override void ConfigureServiceBus(Uri uri, ServiceBusConfigurator configurator)
  31
+        {
  32
+            base.ConfigureServiceBus(uri, configurator);
  33
+
  34
+            _received = new Future<A>();
  35
+
  36
+            configurator.Subscribe(x => { x.Handler<A>(msg => _received.Complete(msg)); });
  37
+        }
  38
+
  39
+        class A
  40
+        {
  41
+            public byte[] Contents { get; set; }
  42
+
  43
+            public bool Equals(A other)
  44
+            {
  45
+                if (ReferenceEquals(null, other))
  46
+                    return false;
  47
+                if (ReferenceEquals(this, other))
  48
+                    return true;
  49
+                return other.Contents.SequenceEqual(Contents);
  50
+            }
  51
+
  52
+            public override bool Equals(object obj)
  53
+            {
  54
+                if (ReferenceEquals(null, obj))
  55
+                    return false;
  56
+                if (ReferenceEquals(this, obj))
  57
+                    return true;
  58
+                if (obj.GetType() != typeof(A))
  59
+                    return false;
  60
+                return Equals((A)obj);
  61
+            }
  62
+
  63
+            public override int GetHashCode()
  64
+            {
  65
+                return (Contents != null ? Contents.GetHashCode() : 0);
  66
+            }
  67
+        }
  68
+
  69
+        [Test]
  70
+        public void Should_receive_byte_array()
  71
+        {
  72
+            _sent = new A
  73
+                {
  74
+                    Contents = new byte[] {0x56, 0x34, 0xf3}
  75
+                };
  76
+
  77
+            LocalBus.Endpoint.Send(_sent);
  78
+
  79
+            _received.WaitUntilCompleted(8.Seconds()).ShouldBeTrue();
  80
+        }
  81
+
  82
+        [Test]
  83
+        public void Should_receive_byte_array_of_bigness()
  84
+        {
  85
+            Random random = new Random();
  86
+            byte[] bytes = new byte[512];
  87
+            for (int i = 0; i < 512; i++)
  88
+            {
  89
+                bytes[i] = (byte)random.Next(255);
  90
+            }
  91
+            _sent = new A
  92
+                {
  93
+                    Contents = bytes
  94
+                };
  95
+
  96
+            LocalBus.Endpoint.Send(_sent);
  97
+
  98
+            _received.WaitUntilCompleted(8.Seconds()).ShouldBeTrue();
  99
+            _received.Value.ShouldEqual(_sent);
  100
+        }
  101
+    }
  102
+}
1  src/Transports/MassTransit.Transports.RabbitMq.Tests/MassTransit.Transports.RabbitMq.Tests.csproj
@@ -91,6 +91,7 @@
91 91
     <Compile Include="Assumptions\PerformanceAssumptions.cs" />
92 92
     <Compile Include="Assumptions\RoutingAssumptions.cs" />
93 93
     <Compile Include="Assumptions\TransactionAssumptions.cs" />
  94
+    <Compile Include="Bytes_Specs.cs" />
94 95
     <Compile Include="ContextSetup.cs" />
95 96
     <Compile Include="Request_Specs.cs" />
96 97
     <Compile Include="TestFactory.cs" />

0 notes on commit e710cca

Please sign in to comment.
Something went wrong with that request. Please try again.