Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

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

…rays
  • Loading branch information...
commit e710cca1f39ee576ff84e2e4b9acebdc3f5f1b67 1 parent b5d9d0a
@phatboyg authored
View
125 src/MassTransit.Tests/Serialization/ByteArray_Specs.cs
@@ -1,64 +1,63 @@
-// Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, Simon Guindon, et. al.
-//
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
-// this file except in compliance with the License. You may obtain a copy of the
-// License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software distributed
-// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
-// CONDITIONS OF ANY KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations under the License.
-namespace MassTransit.Tests.Serialization
-{
- using System;
- using Magnum.TestFramework;
- using MassTransit.Testing;
-
- [Scenario]
- public class When_a_byte_array_value_is_serialized
- {
- A _received;
- A _sent;
- HandlerTest<A> _test;
-
- [When]
- public void Setup()
- {
- _test = TestFactory.ForHandler<A>()
- .New(x =>
- {
- _sent = new A
- {
- Contents = new byte[] {0x56, 0x34, 0xf3}
- };
- x.Send(_sent);
-
- x.Handler((context, message) => { _received = message; });
- });
-
- _test.Execute();
-
- _test.Received.Any<A>().ShouldBeTrue();
- }
-
- [Finally]
- public void Teardown()
- {
- _test.Dispose();
- _test = null;
- }
-
- [Then]
- public void Should_receive_byte_array()
- {
- _sent.Contents.ShouldEqual(_received.Contents);
- }
-
- class A
- {
- public byte[] Contents { get; set; }
- }
- }
+// Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al.
+//
+// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
+// this file except in compliance with the License. You may obtain a copy of the
+// License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software distributed
+// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
+// CONDITIONS OF ANY KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations under the License.
+namespace MassTransit.Tests.Serialization
+{
+ using Magnum.TestFramework;
+ using MassTransit.Testing;
+
+ [Scenario]
+ public class When_a_byte_array_value_is_serialized
+ {
+ A _received;
+ A _sent;
+ HandlerTest<A> _test;
+
+ [When]
+ public void Setup()
+ {
+ _test = TestFactory.ForHandler<A>()
+ .New(x =>
+ {
+ _sent = new A
+ {
+ Contents = new byte[] {0x56, 0x34, 0xf3}
+ };
+ x.Send(_sent);
+
+ x.Handler((context, message) => { _received = message; });
+ });
+
+ _test.Execute();
+
+ _test.Received.Any<A>().ShouldBeTrue();
+ }
+
+ [Finally]
+ public void Teardown()
+ {
+ _test.Dispose();
+ _test = null;
+ }
+
+ [Then]
+ public void Should_receive_byte_array()
+ {
+ _sent.Contents.ShouldEqual(_received.Contents);
+ }
+
+ class A
+ {
+ public byte[] Contents { get; set; }
+ }
+ }
}
View
1  src/MassTransit/MassTransit.csproj
@@ -369,6 +369,7 @@
<Compile Include="Saga\SubscriptionConnectors\StateMachineSagaConnector.cs" />
<Compile Include="Saga\SubscriptionConnectors\StateMachineSagaWorkerConnector.cs" />
<Compile Include="Serialization\BsonMessageSerializer.cs" />
+ <Compile Include="Serialization\ByteArrayConverter.cs" />
<Compile Include="Serialization\Custom\Continuation.cs" />
<Compile Include="Serialization\DictionaryJsonConverter.cs" />
<Compile Include="Serialization\EncryptedMessageEnvelope.cs" />
View
90 src/MassTransit/Serialization/ByteArrayConverter.cs
@@ -0,0 +1,90 @@
+// Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al.
+//
+// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
+// this file except in compliance with the License. You may obtain a copy of the
+// License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software distributed
+// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
+// CONDITIONS OF ANY KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations under the License.
+namespace MassTransit.Serialization
+{
+ using System;
+ using System.Collections.Generic;
+ using System.Globalization;
+ using Newtonsoft.Json;
+
+ public class ByteArrayConverter :
+ JsonConverter
+ {
+ public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
+ {
+ if (value == null)
+ {
+ writer.WriteNull();
+ }
+ else
+ {
+ byte[] byteArray = GetByteArray(value);
+ writer.WriteValue(byteArray);
+ }
+ }
+
+ public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
+ JsonSerializer serializer)
+ {
+ if (reader.TokenType == JsonToken.Null)
+ {
+ return null;
+ }
+ byte[] numArray;
+ if (reader.TokenType == JsonToken.StartArray)
+ numArray = ReadByteArray(reader);
+ else if (reader.TokenType == JsonToken.String)
+ numArray = Convert.FromBase64String(reader.Value.ToString());
+ else
+ throw new Exception(
+ string.Format("Unexpected token parsing binary. Expected String or StartArray, got {0}.",
+ reader.TokenType));
+
+ return numArray;
+ }
+
+ public override bool CanConvert(Type objectType)
+ {
+ if (objectType == typeof(byte[]))
+ return true;
+
+ return false;
+ }
+
+ byte[] GetByteArray(object value)
+ {
+ return value as byte[];
+ }
+
+ byte[] ReadByteArray(JsonReader reader)
+ {
+ var list = new List<byte>();
+ while (reader.Read())
+ {
+ switch (reader.TokenType)
+ {
+ case JsonToken.Comment:
+ continue;
+ case JsonToken.Integer:
+ list.Add(Convert.ToByte(reader.Value, CultureInfo.InvariantCulture));
+ continue;
+ case JsonToken.EndArray:
+ return list.ToArray();
+ default:
+ throw new Exception(string.Format("Unexpected token when reading bytes: {0}", reader.TokenType));
+ }
+ }
+ throw new Exception("Unexpected end when reading bytes.");
+ }
+ }
+}
View
4 src/MassTransit/Serialization/JsonMessageSerializer.cs
@@ -47,9 +47,10 @@ public static JsonSerializer Deserializer
ContractResolver = new JsonContractResolver(),
Converters = new List<JsonConverter>(new JsonConverter[]
{
+ new ByteArrayConverter(),
new ListJsonConverter(),
new InterfaceProxyConverter(),
- new StringDecimalConverter(),
+ new StringDecimalConverter(),
new IsoDateTimeConverter{DateTimeStyles = DateTimeStyles.RoundtripKind},
})
}));
@@ -70,6 +71,7 @@ public static JsonSerializer Serializer
ContractResolver = new JsonContractResolver(),
Converters = new List<JsonConverter>(new JsonConverter[]
{
+ new ByteArrayConverter(),
new IsoDateTimeConverter{DateTimeStyles = DateTimeStyles.RoundtripKind},
}),
}));
View
102 src/Transports/MassTransit.Transports.RabbitMq.Tests/Bytes_Specs.cs
@@ -0,0 +1,102 @@
+// Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al.
+//
+// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
+// this file except in compliance with the License. You may obtain a copy of the
+// License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software distributed
+// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
+// CONDITIONS OF ANY KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations under the License.
+namespace MassTransit.Transports.RabbitMq.Tests
+{
+ using System;
+ using System.Linq;
+ using BusConfigurators;
+ using Magnum.Extensions;
+ using Magnum.TestFramework;
+ using NUnit.Framework;
+ using TestFramework;
+
+ [TestFixture]
+ public class Bytes_Specs :
+ Given_a_rabbitmq_bus
+ {
+ A _sent;
+ Future<A> _received;
+
+ protected override void ConfigureServiceBus(Uri uri, ServiceBusConfigurator configurator)
+ {
+ base.ConfigureServiceBus(uri, configurator);
+
+ _received = new Future<A>();
+
+ configurator.Subscribe(x => { x.Handler<A>(msg => _received.Complete(msg)); });
+ }
+
+ class A
+ {
+ public byte[] Contents { get; set; }
+
+ public bool Equals(A other)
+ {
+ if (ReferenceEquals(null, other))
+ return false;
+ if (ReferenceEquals(this, other))
+ return true;
+ return other.Contents.SequenceEqual(Contents);
+ }
+
+ public override bool Equals(object obj)
+ {
+ if (ReferenceEquals(null, obj))
+ return false;
+ if (ReferenceEquals(this, obj))
+ return true;
+ if (obj.GetType() != typeof(A))
+ return false;
+ return Equals((A)obj);
+ }
+
+ public override int GetHashCode()
+ {
+ return (Contents != null ? Contents.GetHashCode() : 0);
+ }
+ }
+
+ [Test]
+ public void Should_receive_byte_array()
+ {
+ _sent = new A
+ {
+ Contents = new byte[] {0x56, 0x34, 0xf3}
+ };
+
+ LocalBus.Endpoint.Send(_sent);
+
+ _received.WaitUntilCompleted(8.Seconds()).ShouldBeTrue();
+ }
+
+ [Test]
+ public void Should_receive_byte_array_of_bigness()
+ {
+ Random random = new Random();
+ byte[] bytes = new byte[512];
+ for (int i = 0; i < 512; i++)
+ {
+ bytes[i] = (byte)random.Next(255);
+ }
+ _sent = new A
+ {
+ Contents = bytes
+ };
+
+ LocalBus.Endpoint.Send(_sent);
+
+ _received.WaitUntilCompleted(8.Seconds()).ShouldBeTrue();
+ _received.Value.ShouldEqual(_sent);
+ }
+ }
+}
View
1  ...sports/MassTransit.Transports.RabbitMq.Tests/MassTransit.Transports.RabbitMq.Tests.csproj
@@ -91,6 +91,7 @@
<Compile Include="Assumptions\PerformanceAssumptions.cs" />
<Compile Include="Assumptions\RoutingAssumptions.cs" />
<Compile Include="Assumptions\TransactionAssumptions.cs" />
+ <Compile Include="Bytes_Specs.cs" />
<Compile Include="ContextSetup.cs" />
<Compile Include="Request_Specs.cs" />
<Compile Include="TestFactory.cs" />

0 comments on commit e710cca

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