Browse files

Serializer now throws exception when when trying to serializer a non-…

…object
  • Loading branch information...
1 parent 7c560d5 commit 06d4209a24e19aa4d099056ee92a175346c5c2ca Karl Seguin committed Sep 23, 2011
Showing with 16 additions and 4 deletions.
  1. +9 −1 Metsys.Bson.Tests/SerializationTests.cs
  2. +6 −2 Metsys.Bson/Serializer.cs
  3. +1 −1 Metsys.Bson/Types.cs
View
10 Metsys.Bson.Tests/SerializationTests.cs
@@ -258,6 +258,14 @@ public void SerializesNulls()
var result = Serializer.Serialize(new Skinny{ Nint = null });
Assert.Equal(19, BitConverter.ToInt32(result, 0)); //length
Assert.Equal(10, result[4]); //type
- }
+ }
+
+ [Fact]
+ public void ThrowsExceptionOnInvalidRootTypes()
+ {
+ var message = "Root type must be an non-enumerable object";
+ Assert.Equal(message, Assert.Throws<BsonException>(() => Serializer.Serialize(3)).Message);
+ Assert.Equal(message, Assert.Throws<BsonException>(() => Serializer.Serialize(new[]{1,2,3})).Message);
+ }
}
}
View
8 Metsys.Bson/Serializer.cs
@@ -31,6 +31,11 @@ public class Serializer
public static byte[] Serialize<T>(T document)
{
+ var type = document.GetType();
+ if (type.IsValueType || typeof(IEnumerable).IsAssignableFrom(type))
+ {
+ throw new BsonException("Root type must be an non-enumerable object");
+ }
using (var ms = new MemoryStream(250))
using (var writer = new BinaryWriter(ms))
{
@@ -82,8 +87,7 @@ private void WriteDocument(object document)
private void WriteObject(object document)
{
- var typeHelper = TypeHelper.GetHelperForType(document.GetType());
-
+ var typeHelper = TypeHelper.GetHelperForType(document.GetType());
foreach (var property in typeHelper.GetProperties())
{
if (property.Ignored) { continue; }
View
2 Metsys.Bson/Types.cs
@@ -19,6 +19,6 @@ public enum Types
ScopedCode = 15,
Int32 = 16,
Timestamp = 17,
- Int64 = 18,
+ Int64 = 18,
}
}

0 comments on commit 06d4209

Please sign in to comment.