Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Merge branch 'csharp562v18'

  • Loading branch information...
commit 5825955911d86b2adfd27a60099a7a6915395b60 2 parents e13c7ba + cf64c55
rstam authored
Showing with 703 additions and 978 deletions.
  1. +5 −15 MongoDB.Bson/ObjectModel/BsonArray.cs
  2. +30 −144 MongoDB.Bson/ObjectModel/BsonDocument.cs
  3. +27 −20 MongoDB.Bson/ObjectModel/BsonDocumentWrapper.cs
  4. +0 −44 MongoDB.Bson/ObjectModel/BsonElement.cs
  5. +4 −153 MongoDB.Bson/ObjectModel/BsonValue.cs
  6. +5 −0 MongoDB.Bson/Serialization/BsonDefaultSerializationProvider.cs
  7. +10 −0 MongoDB.Bson/Serialization/BsonMemberMap.cs
  8. +22 −2 MongoDB.Bson/Serialization/BsonSerializer.cs
  9. +2 −1  MongoDB.Bson/Serialization/Conventions/DiscriminatorConventions.cs
  10. +22 −13 MongoDB.Bson/Serialization/Serializers/BsonArraySerializer.cs
  11. +26 −32 MongoDB.Bson/Serialization/Serializers/BsonBinaryDataSerializer.cs
  12. +10 −15 MongoDB.Bson/Serialization/Serializers/BsonBooleanSerializer.cs
  13. +67 −18 MongoDB.Bson/Serialization/Serializers/BsonClassMapSerializer.cs
  14. +10 −175 MongoDB.Bson/Serialization/Serializers/BsonDateTimeSerializer.cs
  15. +118 −7 MongoDB.Bson/Serialization/Serializers/BsonDocumentSerializer.cs
  16. +20 −3 MongoDB.Bson/Serialization/Serializers/BsonDocumentWrapperSerializer.cs
  17. +11 −15 MongoDB.Bson/Serialization/Serializers/BsonDoubleSerializer.cs
  18. +11 −15 MongoDB.Bson/Serialization/Serializers/BsonInt32Serializer.cs
  19. +11 −15 MongoDB.Bson/Serialization/Serializers/BsonInt64Serializer.cs
  20. +12 −14 MongoDB.Bson/Serialization/Serializers/BsonJavaScriptSerializer.cs
  21. +14 −16 MongoDB.Bson/Serialization/Serializers/BsonJavaScriptWithScopeSerializer.cs
  22. +12 −13 MongoDB.Bson/Serialization/Serializers/BsonMaxKeySerializer.cs
  23. +12 −13 MongoDB.Bson/Serialization/Serializers/BsonMinKeySerializer.cs
  24. +5 −23 MongoDB.Bson/Serialization/Serializers/BsonNullSerializer.cs
  25. +11 −15 MongoDB.Bson/Serialization/Serializers/BsonObjectIdSerializer.cs
  26. +11 −15 MongoDB.Bson/Serialization/Serializers/BsonRegularExpressionSerializer.cs
  27. +11 −15 MongoDB.Bson/Serialization/Serializers/BsonStringSerializer.cs
  28. +3 −25 MongoDB.Bson/Serialization/Serializers/BsonSymbolSerializer.cs
  29. +11 −15 MongoDB.Bson/Serialization/Serializers/BsonTimestampSerializer.cs
  30. +11 −13 MongoDB.Bson/Serialization/Serializers/BsonUndefinedSerializer.cs
  31. +47 −11 MongoDB.Bson/Serialization/Serializers/BsonValueSerializer.cs
  32. +1 −1  MongoDB.Bson/Serialization/Serializers/DecimalSerializer.cs
  33. +15 −14 MongoDB.BsonUnitTests/IO/BsonDocumentReaderTests.cs
  34. +4 −3 MongoDB.BsonUnitTests/IO/BsonRoundTripTests.cs
  35. +0 −4 MongoDB.BsonUnitTests/IO/JsonWriterTests.cs
  36. +6 −11 MongoDB.BsonUnitTests/Jira/CSharp446Tests.cs
  37. +12 −11 MongoDB.BsonUnitTests/ObjectModel/BsonDocumentTests.cs
  38. +62 −39 MongoDB.BsonUnitTests/Serialization/Serializers/BsonValueSerializerTests.cs
  39. +1 −1  MongoDB.BsonUnitTests/Serialization/Serializers/CircularReferencesTests.cs
  40. +2 −1  MongoDB.Driver/Builders/CollectionOptionsBuilder.cs
  41. +2 −1  MongoDB.Driver/Builders/FieldsBuilder.cs
  42. +2 −1  MongoDB.Driver/Builders/GeoHaystackSearchOptionsBuilder.cs
  43. +2 −1  MongoDB.Driver/Builders/GeoNearOptionsBuilder.cs
  44. +2 −1  MongoDB.Driver/Builders/GroupByBuilder.cs
  45. +2 −1  MongoDB.Driver/Builders/IndexKeysBuilder.cs
  46. +2 −1  MongoDB.Driver/Builders/IndexOptionsBuilder.cs
  47. +3 −2 MongoDB.Driver/Builders/MapReduceOptionsBuilder.cs
  48. +2 −1  MongoDB.Driver/Builders/SortByBuilder.cs
  49. +2 −2 MongoDB.Driver/Builders/UpdateBuilder.cs
  50. +3 −2 MongoDB.Driver/Communication/Messages/MongoReplyMessage.cs
  51. +2 −1  MongoDB.Driver/GridFS/MongoGridFSFileInfo.cs
  52. +2 −2 MongoDB.Driver/MongoDBRef.cs
  53. +2 −1  MongoDB.DriverUnitTests/Jira/CSharp231Tests.cs
  54. +1 −1  MongoDB.DriverUnitTests/Jira/CSharp365Tests.cs
View
20 MongoDB.Bson/ObjectModel/BsonArray.cs
@@ -21,6 +21,7 @@
using System.Text.RegularExpressions;
using MongoDB.Bson.IO;
+using MongoDB.Bson.Serialization;
namespace MongoDB.Bson
{
@@ -412,17 +413,10 @@ public new static BsonArray Create(object value)
/// </summary>
/// <param name="bsonReader">The reader.</param>
/// <returns>A BsonArray.</returns>
+ [Obsolete("Use BsonSerializer.Deserialize<BsonArray> instead.")]
public static new BsonArray ReadFrom(BsonReader bsonReader)
{
- var array = new BsonArray();
- bsonReader.ReadStartArray();
- while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
- {
- var value = BsonValue.ReadFrom(bsonReader);
- array.Add(value);
- }
- bsonReader.ReadEndArray();
- return array;
+ return BsonSerializer.Deserialize<BsonArray>(bsonReader);
}
// public methods
@@ -870,14 +864,10 @@ public override string ToString()
/// Writes the array to a BsonWriter.
/// </summary>
/// <param name="bsonWriter">The writer.</param>
+ [Obsolete("Use BsonSerializer.Serialize<BsonArray> instead.")]
public new void WriteTo(BsonWriter bsonWriter)
{
- bsonWriter.WriteStartArray();
- for (int i = 0; i < _values.Count; i++)
- {
- _values[i].WriteTo(bsonWriter);
- }
- bsonWriter.WriteEndArray();
+ BsonSerializer.Serialize(bsonWriter, this);
}
// explicit interface implementations
View
174 MongoDB.Bson/ObjectModel/BsonDocument.cs
@@ -26,6 +26,7 @@
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.IdGenerators;
using MongoDB.Bson.Serialization.Options;
+using MongoDB.Bson.Serialization.Serializers;
namespace MongoDB.Bson
{
@@ -371,8 +372,7 @@ public static BsonDocument Parse(string json)
{
using (var bsonReader = BsonReader.Create(json))
{
- var document = new BsonDocument();
- return (BsonDocument)((IBsonSerializable)document).Deserialize(bsonReader, typeof(BsonDocument), null);
+ return (BsonDocument)BsonDocumentSerializer.Instance.Deserialize(bsonReader, typeof(BsonDocument), null);
}
}
@@ -381,11 +381,12 @@ public static BsonDocument Parse(string json)
/// </summary>
/// <param name="buffer">The BsonBuffer.</param>
/// <returns>A BsonDocument.</returns>
+ [Obsolete("Use BsonSerializer.Deserialize<BsonDocument> instead.")]
public static BsonDocument ReadFrom(BsonBuffer buffer)
{
using (BsonReader bsonReader = BsonReader.Create(buffer))
{
- return ReadFrom(bsonReader);
+ return BsonSerializer.Deserialize<BsonDocument>(bsonReader);
}
}
@@ -394,10 +395,10 @@ public static BsonDocument ReadFrom(BsonBuffer buffer)
/// </summary>
/// <param name="bsonReader">The BsonReader.</param>
/// <returns>A BsonDocument.</returns>
+ [Obsolete("Use BsonSerializer.Deserialize<BsonDocument> instead.")]
public static new BsonDocument ReadFrom(BsonReader bsonReader)
{
- BsonDocument document = new BsonDocument();
- return (BsonDocument)((IBsonSerializable)document).Deserialize(bsonReader, typeof(BsonDocument), null);
+ return BsonSerializer.Deserialize<BsonDocument>(bsonReader);
}
/// <summary>
@@ -405,13 +406,10 @@ public static new BsonDocument ReadFrom(BsonReader bsonReader)
/// </summary>
/// <param name="bytes">The byte array.</param>
/// <returns>A BsonDocument.</returns>
+ [Obsolete("Use BsonSerializer.Deserialize<BsonDocument> instead.")]
public static BsonDocument ReadFrom(byte[] bytes)
{
- MemoryStream stream = new MemoryStream(bytes);
- using (BsonReader bsonReader = BsonReader.Create(stream))
- {
- return ReadFrom(bsonReader);
- }
+ return BsonSerializer.Deserialize<BsonDocument>(bytes);
}
/// <summary>
@@ -419,12 +417,10 @@ public static BsonDocument ReadFrom(byte[] bytes)
/// </summary>
/// <param name="stream">The stream.</param>
/// <returns>A BsonDocument.</returns>
+ [Obsolete("Use BsonSerializer.Deserialize<BsonDocument> instead.")]
public static BsonDocument ReadFrom(Stream stream)
{
- using (BsonReader bsonReader = BsonReader.Create(stream))
- {
- return ReadFrom(bsonReader);
- }
+ return BsonSerializer.Deserialize<BsonDocument>(stream);
}
/// <summary>
@@ -432,12 +428,12 @@ public static BsonDocument ReadFrom(Stream stream)
/// </summary>
/// <param name="filename">The name of the file.</param>
/// <returns>A BsonDocument.</returns>
+ [Obsolete("Use BsonSerializer.Deserialize<BsonDocument> instead.")]
public static BsonDocument ReadFrom(string filename)
{
- FileStream stream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.None);
- using (BsonReader bsonReader = BsonReader.Create(stream))
+ using (var stream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.None))
{
- return ReadFrom(bsonReader);
+ return BsonSerializer.Deserialize<BsonDocument>(stream);
}
}
@@ -796,34 +792,7 @@ public override BsonValue DeepClone()
[Obsolete("Deserialize was intended to be private and will become private in a future release.")]
public object Deserialize(BsonReader bsonReader, Type nominalType, IBsonSerializationOptions options)
{
- if (bsonReader.GetCurrentBsonType() == Bson.BsonType.Null)
- {
- bsonReader.ReadNull();
- return null;
- }
- else
- {
- var documentSerializationOptions = (options ?? DocumentSerializationOptions.Defaults) as DocumentSerializationOptions;
- if (documentSerializationOptions == null)
- {
- var message = string.Format(
- "Serialize method of BsonDocument expected serialization options of type {0}, not {1}.",
- BsonUtils.GetFriendlyTypeName(typeof(DocumentSerializationOptions)),
- BsonUtils.GetFriendlyTypeName(options.GetType()));
- throw new BsonSerializationException(message);
- }
- _allowDuplicateNames = documentSerializationOptions.AllowDuplicateNames;
-
- bsonReader.ReadStartDocument();
- Clear();
- BsonElement element;
- while (BsonElement.ReadFrom(bsonReader, out element))
- {
- Add(element);
- }
- bsonReader.ReadEndDocument();
- return this;
- }
+ return BsonDocumentSerializer.Instance.Deserialize(bsonReader, nominalType, options);
}
/// <summary>
@@ -836,37 +805,8 @@ public object Deserialize(BsonReader bsonReader, Type nominalType, IBsonSerializ
[Obsolete("GetDocumentId was intended to be private and will become private in a future release. Use document[\"_id\"] or document.GetValue(\"_id\") instead.")]
public bool GetDocumentId(out object id, out Type idNominalType, out IIdGenerator idGenerator)
{
- BsonElement idElement;
- if (TryGetElement("_id", out idElement))
- {
- // TODO: in a future release we will always return a BsonValue (GetDocumentId is not supposed to transform Id values in any way)
- // we're returning the raw value in 1.4.2 to remain temporarily backward compatible with 1.4.0 and earlier
- id = idElement.Value.RawValue;
- if (id == null)
- {
- id = idElement.Value;
- }
- idGenerator = BsonSerializer.LookupIdGenerator(id.GetType());
-
- if (idGenerator == null)
- {
- // note: in 1.4.2 this code isn't yet used because if the RawValue was a Guid then the GuidIdGenerator was found
- // but once we start returning BsonValue like we should this code will start being used
- var idBinaryData = id as BsonBinaryData;
- if (idBinaryData != null && (idBinaryData.SubType == BsonBinarySubType.UuidLegacy || idBinaryData.SubType == BsonBinarySubType.UuidStandard))
- {
- idGenerator = BsonBinaryDataGuidGenerator.GetInstance(idBinaryData.GuidRepresentation);
- }
- }
- }
- else
- {
- id = null;
- idGenerator = ObjectIdGenerator.Instance; // TODO: in a future release we will return an instance of BsonObjectIdGenerator
- }
-
- idNominalType = typeof(BsonValue);
- return true;
+ var idProvider = (IBsonIdProvider)BsonDocumentSerializer.Instance;
+ return idProvider.GetDocumentId(this, out id, out idNominalType, out idGenerator);
}
/// <summary>
@@ -1102,45 +1042,7 @@ public void RemoveElement(BsonElement element)
[Obsolete("Serialize was intended to be private and will become private in a future release.")]
public void Serialize(BsonWriter bsonWriter, Type nominalType, IBsonSerializationOptions options)
{
- if (bsonWriter == null)
- {
- throw new ArgumentNullException("bsonWriter");
- }
- if (nominalType == null)
- {
- throw new ArgumentNullException("nominalType");
- }
- var documentSerializationOptions = (options ?? DocumentSerializationOptions.Defaults) as DocumentSerializationOptions;
- if (documentSerializationOptions == null)
- {
- var message = string.Format(
- "Serialize method of BsonDocument expected serialization options of type {0}, not {1}.",
- BsonUtils.GetFriendlyTypeName(typeof(DocumentSerializationOptions)),
- BsonUtils.GetFriendlyTypeName(options.GetType()));
- throw new BsonSerializationException(message);
- }
-
- bsonWriter.WriteStartDocument();
- int idIndex;
- if (documentSerializationOptions.SerializeIdFirst && _indexes.TryGetValue("_id", out idIndex))
- {
- _elements[idIndex].WriteTo(bsonWriter);
- }
- else
- {
- idIndex = -1; // remember that when TryGetValue returns false it sets idIndex to 0
- }
-
- for (int i = 0; i < _elements.Count; i++)
- {
- // if serializeIdFirst is false then idIndex will be -1 and no elements will be skipped
- if (i != idIndex)
- {
- _elements[i].WriteTo(bsonWriter);
- }
- }
-
- bsonWriter.WriteEndDocument();
+ BsonDocumentSerializer.Instance.Serialize(bsonWriter, nominalType, this, options);
}
/// <summary>
@@ -1186,31 +1088,8 @@ public BsonDocument Set(string name, BsonValue value)
[Obsolete("SetDocumentId was intended to be private and will become private in a future release. Use document[\"_id\"] = value or document.Set(\"_id\", value) instead.")]
public void SetDocumentId(object id)
{
- if (id == null)
- {
- throw new ArgumentNullException("id");
- }
-
- // TODO: in a future release we will just cast directly to BsonValue because the caller is required to pass a BsonValue
- // var idBsonValue = (BsonValue)id;
-
- var idBsonValue = id as BsonValue;
- if (idBsonValue == null)
- {
- // SetDocumentId contract requires that caller provide an id of the correct type so this conversion is not correct
- // for temporary backward compatibility with versions prior to 1.4.2 we continue to map objects to BsonValue for now
- idBsonValue = BsonValue.Create(id); // TODO: in a future release this mapping will be removed
- }
-
- BsonElement idElement;
- if (TryGetElement("_id", out idElement))
- {
- idElement.Value = idBsonValue;
- }
- else
- {
- InsertAt(0, new BsonElement("_id", idBsonValue));
- }
+ var idProvider = (IBsonIdProvider)BsonDocumentSerializer.Instance;
+ idProvider.SetDocumentId(this, id);
}
/// <summary>
@@ -1348,20 +1227,22 @@ public bool TryGetValue(string name, out BsonValue value)
/// Writes the document to a BsonWriter.
/// </summary>
/// <param name="bsonWriter">The writer.</param>
+ [Obsolete("Use BsonSerializer.Serialize<BsonDocument> instead.")]
public new void WriteTo(BsonWriter bsonWriter)
{
- ((IBsonSerializable)this).Serialize(bsonWriter, typeof(BsonDocument), null);
+ BsonSerializer.Serialize(bsonWriter, this);
}
/// <summary>
/// Writes the document to a BsonBuffer.
/// </summary>
/// <param name="buffer">The buffer.</param>
+ [Obsolete("Use BsonSerializer.Serialize<BsonDocument> instead.")]
public void WriteTo(BsonBuffer buffer)
{
using (BsonWriter bsonWriter = BsonWriter.Create(buffer))
{
- WriteTo(bsonWriter);
+ BsonSerializer.Serialize(bsonWriter, this);
}
}
@@ -1369,11 +1250,12 @@ public void WriteTo(BsonBuffer buffer)
/// Writes the document to a Stream.
/// </summary>
/// <param name="stream">The stream.</param>
+ [Obsolete("Use BsonSerializer.Serialize<BsonDocument> instead.")]
public void WriteTo(Stream stream)
{
using (BsonWriter bsonWriter = BsonWriter.Create(stream))
{
- WriteTo(bsonWriter);
+ BsonSerializer.Serialize(bsonWriter, this);
}
}
@@ -1381,11 +1263,15 @@ public void WriteTo(Stream stream)
/// Writes the document to a file.
/// </summary>
/// <param name="filename">The name of the file.</param>
+ [Obsolete("Use BsonSerializer.Serialize<BsonDocument> instead.")]
public void WriteTo(string filename)
{
using (FileStream stream = new FileStream(filename, FileMode.Create, FileAccess.Write))
{
- WriteTo(stream);
+ using (BsonWriter bsonWriter = BsonWriter.Create(stream))
+ {
+ BsonSerializer.Serialize(bsonWriter, this);
+ }
}
}
View
47 MongoDB.Bson/ObjectModel/BsonDocumentWrapper.cs
@@ -24,6 +24,7 @@
using MongoDB.Bson.IO;
using MongoDB.Bson.Serialization;
+using MongoDB.Bson.Serialization.Serializers;
namespace MongoDB.Bson
{
@@ -86,6 +87,31 @@ public BsonDocumentWrapper(Type wrappedNominalType, object wrappedObject, bool i
_isUpdateDocument = isUpdateDocument;
}
+ // public properties
+ /// <summary>
+ /// Gets whether the wrapped document is an update document.
+ /// </summary>
+ public bool IsUpdateDocument
+ {
+ get { return _isUpdateDocument; }
+ }
+
+ /// <summary>
+ /// Gets the nominal type of the wrapped document.
+ /// </summary>
+ public Type WrappedNominalType
+ {
+ get { return _wrappedNominalType; }
+ }
+
+ /// <summary>
+ /// Gets the wrapped object.
+ /// </summary>
+ public object WrappedObject
+ {
+ get { return _wrappedObject; }
+ }
+
// public static methods
/// <summary>
/// Creates a new instance of the BsonDocumentWrapper class.
@@ -234,26 +260,7 @@ public override int GetHashCode()
[Obsolete("Serialize was intended to be private and will become private in a future release.")]
public void Serialize(BsonWriter bsonWriter, Type nominalType, IBsonSerializationOptions options)
{
- if (_isUpdateDocument)
- {
- var savedCheckElementNames = bsonWriter.CheckElementNames;
- var savedCheckUpdateDocument = bsonWriter.CheckUpdateDocument;
- try
- {
- bsonWriter.CheckElementNames = false;
- bsonWriter.CheckUpdateDocument = true;
- BsonSerializer.Serialize(bsonWriter, _wrappedNominalType, _wrappedObject, options);
- }
- finally
- {
- bsonWriter.CheckElementNames = savedCheckElementNames;
- bsonWriter.CheckUpdateDocument = savedCheckUpdateDocument;
- }
- }
- else
- {
- BsonSerializer.Serialize(bsonWriter, _wrappedNominalType, _wrappedObject, options);
- }
+ BsonDocumentWrapperSerializer.Instance.Serialize(bsonWriter, nominalType, this, options);
}
/// <summary>
View
44 MongoDB.Bson/ObjectModel/BsonElement.cs
@@ -159,43 +159,6 @@ public static BsonElement Create(string name, BsonValue value)
}
}
- // internal static methods
- internal static bool ReadFrom(BsonReader bsonReader, out BsonElement element)
- {
- BsonType bsonType;
- if ((bsonType = bsonReader.ReadBsonType()) != BsonType.EndOfDocument)
- {
- var name = bsonReader.ReadName();
- var value = BsonValue.ReadFrom(bsonReader);
- element = new BsonElement(name, value);
- return true;
- }
- else
- {
- element = null;
- return false;
- }
- }
-
- internal static BsonElement ReadFrom(BsonReader bsonReader, string expectedName)
- {
- BsonElement element;
- if (ReadFrom(bsonReader, out element))
- {
- if (element.Name != expectedName)
- {
- string message = string.Format("Expected element '{0}', not '{1}'.", expectedName, element._name);
- throw new FileFormatException(message);
- }
- return element;
- }
- else
- {
- string message = string.Format("Element '{0}' is missing.", expectedName);
- throw new FileFormatException(message);
- }
- }
-
// private static methods
private static void ValidateElementName(string name)
{
@@ -285,12 +248,5 @@ public override string ToString()
{
return string.Format("{0}={1}", _name, _value);
}
-
- // internal methods
- internal void WriteTo(BsonWriter bsonWriter)
- {
- bsonWriter.WriteName(_name);
- _value.WriteTo(bsonWriter);
- }
}
}
View
157 MongoDB.Bson/ObjectModel/BsonValue.cs
@@ -1111,59 +1111,10 @@ public static BsonValue Create(object value)
/// </summary>
/// <param name="bsonReader">The reader.</param>
/// <returns>A BsonValue.</returns>
+ [Obsolete("Use BsonSerializer.Deserialize<BsonValue> instead.")]
public static BsonValue ReadFrom(BsonReader bsonReader)
{
- BsonType bsonType = bsonReader.GetCurrentBsonType();
- switch (bsonType)
- {
- case BsonType.Array:
- return BsonArray.ReadFrom(bsonReader);
- case BsonType.Binary:
- return bsonReader.ReadBinaryData();
- case BsonType.Boolean:
- return (BsonBoolean)bsonReader.ReadBoolean();
- case BsonType.DateTime:
- return new BsonDateTime(bsonReader.ReadDateTime());
- case BsonType.Document:
- return BsonDocument.ReadFrom(bsonReader);
- case BsonType.Double:
- return new BsonDouble(bsonReader.ReadDouble());
- case BsonType.Int32:
- return new BsonInt32(bsonReader.ReadInt32());
- case BsonType.Int64:
- return new BsonInt64(bsonReader.ReadInt64());
- case BsonType.JavaScript:
- return new BsonJavaScript(bsonReader.ReadJavaScript());
- case BsonType.JavaScriptWithScope:
- string code = bsonReader.ReadJavaScriptWithScope();
- var scope = BsonDocument.ReadFrom(bsonReader);
- return new BsonJavaScriptWithScope(code, scope);
- case BsonType.MaxKey:
- bsonReader.ReadMaxKey();
- return BsonMaxKey.Value;
- case BsonType.MinKey:
- bsonReader.ReadMinKey();
- return BsonMinKey.Value;
- case BsonType.Null:
- bsonReader.ReadNull();
- return BsonNull.Value;
- case BsonType.ObjectId:
- return bsonReader.ReadObjectId();
- case BsonType.RegularExpression:
- return bsonReader.ReadRegularExpression();
- case BsonType.String:
- return new BsonString(bsonReader.ReadString());
- case BsonType.Symbol:
- return BsonSymbolTable.Lookup(bsonReader.ReadSymbol());
- case BsonType.Timestamp:
- return new BsonTimestamp(bsonReader.ReadTimestamp());
- case BsonType.Undefined:
- bsonReader.ReadUndefined();
- return BsonUndefined.Value;
- default:
- var message = string.Format("Invalid BsonType {0}.", bsonType);
- throw new BsonInternalException(message);
- }
+ return BsonSerializer.Deserialize<BsonValue>(bsonReader);
}
// public methods
@@ -1316,110 +1267,10 @@ public virtual DateTime ToUniversalTime()
/// Writes the BsonValue to a BsonWriter.
/// </summary>
/// <param name="bsonWriter">The writer.</param>
+ [Obsolete("Use BsonSerializer.Serialize<BsonValue> instead.")]
public void WriteTo(BsonWriter bsonWriter)
{
- switch (_bsonType)
- {
- case BsonType.Array:
- ((BsonArray)this).WriteTo(bsonWriter);
- break;
- case BsonType.Binary:
- var binaryData = (BsonBinaryData)this;
- var bytes = binaryData.Bytes;
- var subType = binaryData.SubType;
- var guidRepresentation = binaryData.GuidRepresentation;
- var writerGuidRepresentation = bsonWriter.Settings.GuidRepresentation;
- if (subType == BsonBinarySubType.UuidLegacy && writerGuidRepresentation != GuidRepresentation.Unspecified)
- {
- if (guidRepresentation != writerGuidRepresentation)
- {
- if (guidRepresentation == GuidRepresentation.Unspecified)
- {
- var message = string.Format("Cannot write binary data of sub type UuidLegacy and GuidRepresentation Unspecified to a collection with GuidRepresentation {0}.", writerGuidRepresentation);
- throw new BsonSerializationException(message);
- }
- var guid = GuidConverter.FromBytes(bytes, guidRepresentation);
- bytes = GuidConverter.ToBytes(guid, writerGuidRepresentation);
- subType = (writerGuidRepresentation == GuidRepresentation.Standard) ? BsonBinarySubType.UuidStandard : BsonBinarySubType.UuidLegacy;
- guidRepresentation = writerGuidRepresentation;
- }
- }
- binaryData = new BsonBinaryData(bytes, subType, guidRepresentation);
- bsonWriter.WriteBinaryData(binaryData);
- break;
- case BsonType.Boolean:
- bsonWriter.WriteBoolean(((BsonBoolean)this).Value);
- break;
- case BsonType.DateTime:
- bsonWriter.WriteDateTime(((BsonDateTime)this).MillisecondsSinceEpoch);
- break;
- case BsonType.Document:
- var document = this as BsonDocument;
- if (document != null)
- {
- document.WriteTo(bsonWriter);
- }
- else
- {
- var documentWrapper = this as BsonDocumentWrapper;
- if (documentWrapper != null)
- {
- ((IBsonSerializable)documentWrapper).Serialize(bsonWriter, typeof(BsonDocument), null);
- }
- else
- {
- var message = string.Format("BsonType Document can only be used with the classes BsonDocument or BsonDocumentWrapper, not with the class {0}.", this.GetType().FullName);
- throw new BsonInternalException(message);
- }
- }
- break;
- case BsonType.Double:
- bsonWriter.WriteDouble(((BsonDouble)this).Value);
- break;
- case BsonType.Int32:
- bsonWriter.WriteInt32(((BsonInt32)this).Value);
- break;
- case BsonType.Int64:
- bsonWriter.WriteInt64(((BsonInt64)this).Value);
- break;
- case BsonType.JavaScript:
- bsonWriter.WriteJavaScript(((BsonJavaScript)this).Code);
- break;
- case BsonType.JavaScriptWithScope:
- var script = (BsonJavaScriptWithScope)this;
- bsonWriter.WriteJavaScriptWithScope(script.Code);
- script.Scope.WriteTo(bsonWriter);
- break;
- case BsonType.MaxKey:
- bsonWriter.WriteMaxKey();
- break;
- case BsonType.MinKey:
- bsonWriter.WriteMinKey();
- break;
- case BsonType.Null:
- bsonWriter.WriteNull();
- break;
- case BsonType.ObjectId:
- var objectId = ((BsonObjectId)this).Value;
- bsonWriter.WriteObjectId(objectId);
- break;
- case BsonType.RegularExpression:
- BsonRegularExpression regex = (BsonRegularExpression)this;
- bsonWriter.WriteRegularExpression(regex);
- break;
- case BsonType.String:
- bsonWriter.WriteString(((BsonString)this).Value);
- break;
- case BsonType.Symbol:
- bsonWriter.WriteSymbol(((BsonSymbol)this).Name);
- break;
- case BsonType.Timestamp:
- bsonWriter.WriteTimestamp(((BsonTimestamp)this).Value);
- break;
- case BsonType.Undefined:
- bsonWriter.WriteUndefined();
- break;
- }
+ BsonSerializer.Serialize(bsonWriter, this);
}
// protected methods
View
5 MongoDB.Bson/Serialization/BsonDefaultSerializationProvider.cs
@@ -128,6 +128,11 @@ public IBsonSerializer GetSerializer(Type type)
return serializer;
}
+ if (typeof(BsonDocument).IsAssignableFrom(type))
+ {
+ return BsonDocumentSerializer.Instance;
+ }
+
if (type.IsGenericType)
{
var genericTypeDefinition = type.GetGenericTypeDefinition();
View
10 MongoDB.Bson/Serialization/BsonMemberMap.cs
@@ -40,6 +40,7 @@ public class BsonMemberMap
private int _order = int.MaxValue;
private MemberInfo _memberInfo;
private Type _memberType;
+ private bool _memberTypeIsBsonValue;
private Func<object, object> _getter;
private Action<object, object> _setter;
private IBsonSerializationOptions _serializationOptions;
@@ -65,6 +66,7 @@ public BsonMemberMap(BsonClassMap classMap, MemberInfo memberInfo)
_classMap = classMap;
_memberInfo = memberInfo;
_memberType = BsonClassMap.GetMemberInfoType(memberInfo);
+ _memberTypeIsBsonValue = typeof(BsonValue).IsAssignableFrom(_memberType);
_defaultValue = GetDefaultValue(_memberType);
_defaultValueSpecified = false;
}
@@ -95,6 +97,14 @@ public Type MemberType
}
/// <summary>
+ /// Gets whether the member type is a BsonValue.
+ /// </summary>
+ public bool MemberTypeIsBsonValue
+ {
+ get { return _memberTypeIsBsonValue; }
+ }
+
+ /// <summary>
/// Gets the name of the element.
/// </summary>
public string ElementName
View
24 MongoDB.Bson/Serialization/BsonSerializer.cs
@@ -25,6 +25,7 @@
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Bson.Serialization.IdGenerators;
+using MongoDB.Bson.Serialization.Serializers;
namespace MongoDB.Bson.Serialization
{
@@ -207,8 +208,7 @@ public static object Deserialize(BsonReader bsonReader, Type nominalType, IBsonS
{
if (nominalType == typeof(BsonDocument))
{
- var bsonDocument = new BsonDocument();
- return ((IBsonSerializable)bsonDocument).Deserialize(bsonReader, nominalType, options);
+ return BsonDocumentSerializer.Instance.Deserialize(bsonReader, nominalType, options);
}
// if nominalType is an interface find out the actualType and use it instead
@@ -529,6 +529,12 @@ public static IIdGenerator LookupIdGenerator(Type type)
/// <returns>A serializer for the Type.</returns>
public static IBsonSerializer LookupSerializer(Type type)
{
+ // since we don't allow registering serializers for BsonDocument no lookup is needed
+ if (type == typeof(BsonDocument))
+ {
+ return BsonDocumentSerializer.Instance;
+ }
+
// since we don't allow registering serializers for classes that implement IBsonSerializable no lookup is needed
if (typeof(IBsonSerializable).IsAssignableFrom(type))
{
@@ -734,6 +740,13 @@ public static void RegisterSerializationProvider(IBsonSerializationProvider prov
/// <param name="serializer">The serializer.</param>
public static void RegisterSerializer(Type type, IBsonSerializer serializer)
{
+ // don't allow any serializers to be registered for subclasses of BsonDocument
+ if (typeof(BsonDocument).IsAssignableFrom(type))
+ {
+ var message = string.Format("A serializer cannot be registered for type {0} because it is a subclass of BsonDocument.", BsonUtils.GetFriendlyTypeName(type));
+ throw new BsonSerializationException(message);
+ }
+
if (typeof(IBsonSerializable).IsAssignableFrom(type))
{
var message = string.Format("A serializer cannot be registered for type {0} because it implements IBsonSerializable.", BsonUtils.GetFriendlyTypeName(type));
@@ -806,6 +819,13 @@ public static void Serialize(BsonWriter bsonWriter, Type nominalType, object val
object value,
IBsonSerializationOptions options)
{
+ // since we don't allow registering serializers for BsonDocument no lookup is needed
+ if (nominalType == typeof(BsonDocument))
+ {
+ BsonDocumentSerializer.Instance.Serialize(bsonWriter, nominalType, value, options);
+ return;
+ }
+
// since we don't allow registering serializers for classes that implement IBsonSerializable no lookup is needed
var bsonSerializable = value as IBsonSerializable;
if (bsonSerializable != null)
View
3  MongoDB.Bson/Serialization/Conventions/DiscriminatorConventions.cs
@@ -20,6 +20,7 @@
using System.Reflection;
using MongoDB.Bson.IO;
+using MongoDB.Bson.Serialization.Serializers;
namespace MongoDB.Bson.Serialization.Conventions
{
@@ -153,7 +154,7 @@ public Type GetActualType(BsonReader bsonReader, Type nominalType)
var actualType = nominalType;
if (bsonReader.FindElement(_elementName))
{
- var discriminator = BsonValue.ReadFrom(bsonReader);
+ var discriminator = (BsonValue)BsonValueSerializer.Instance.Deserialize(bsonReader, typeof(BsonValue), null);
if (discriminator.IsBsonArray)
{
discriminator = discriminator.AsBsonArray.Last(); // last item is leaf class discriminator
View
35 MongoDB.Bson/Serialization/Serializers/BsonArraySerializer.cs
@@ -15,11 +15,11 @@
using System;
using System.Collections.Generic;
+using System.IO;
using System.Linq;
using System.Text;
using MongoDB.Bson.IO;
-using MongoDB.Bson.Serialization.Options;
namespace MongoDB.Bson.Serialization.Serializers
{
@@ -36,7 +36,6 @@ public class BsonArraySerializer : BsonBaseSerializer
/// Initializes a new instance of the BsonArraySerializer class.
/// </summary>
public BsonArraySerializer()
- : base(new RepresentationSerializationOptions(BsonType.Array))
{
}
@@ -67,14 +66,21 @@ public static BsonArraySerializer Instance
VerifyTypes(nominalType, actualType, typeof(BsonArray));
var bsonType = bsonReader.GetCurrentBsonType();
- if (bsonType == BsonType.Null)
+ switch (bsonType)
{
- bsonReader.ReadNull();
- return null;
- }
- else
- {
- return BsonArray.ReadFrom(bsonReader);
+ case BsonType.Array:
+ bsonReader.ReadStartArray();
+ var array = new BsonArray();
+ while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
+ {
+ var value = (BsonValue)BsonValueSerializer.Instance.Deserialize(bsonReader, typeof(BsonValue), null);
+ array.Add(value);
+ }
+ bsonReader.ReadEndArray();
+ return array;
+ default:
+ var message = string.Format("Cannot deserialize BsonArray from BsonType {0}.", bsonType);
+ throw new FileFormatException(message);
}
}
@@ -93,13 +99,16 @@ public static BsonArraySerializer Instance
{
if (value == null)
{
- bsonWriter.WriteNull();
+ throw new ArgumentNullException("value");
}
- else
+
+ var array = (BsonArray)value;
+ bsonWriter.WriteStartArray();
+ for (int i = 0; i < array.Count; i++)
{
- var array = (BsonArray)value;
- array.WriteTo(bsonWriter);
+ BsonValueSerializer.Instance.Serialize(bsonWriter, typeof(BsonValue), array[i], null);
}
+ bsonWriter.WriteEndArray();
}
}
}
View
58 MongoDB.Bson/Serialization/Serializers/BsonBinaryDataSerializer.cs
@@ -20,7 +20,6 @@
using System.Text;
using MongoDB.Bson.IO;
-using MongoDB.Bson.Serialization.Options;
namespace MongoDB.Bson.Serialization.Serializers
{
@@ -37,7 +36,6 @@ public class BsonBinaryDataSerializer : BsonBaseSerializer
/// Initializes a new instance of the BsonBinaryDataSerializer class.
/// </summary>
public BsonBinaryDataSerializer()
- : base(new RepresentationSerializationOptions(BsonType.Binary))
{
}
@@ -70,9 +68,6 @@ public static BsonBinaryDataSerializer Instance
var bsonType = bsonReader.GetCurrentBsonType();
switch (bsonType)
{
- case BsonType.Null:
- bsonReader.ReadNull();
- return null;
case BsonType.Binary:
return bsonReader.ReadBinaryData();
default:
@@ -96,40 +91,39 @@ public static BsonBinaryDataSerializer Instance
{
if (value == null)
{
- bsonWriter.WriteNull();
+ throw new ArgumentNullException("value");
}
- else
- {
- var binaryData = (BsonBinaryData)value;
- var bytes = binaryData.Bytes;
- var subType = binaryData.SubType;
- var guidRepresentation = binaryData.GuidRepresentation;
- if (subType == BsonBinarySubType.UuidStandard || subType == BsonBinarySubType.UuidLegacy)
+ var binaryData = (BsonBinaryData)value;
+
+ var subType = binaryData.SubType;
+ if (subType == BsonBinarySubType.UuidStandard || subType == BsonBinarySubType.UuidLegacy)
+ {
+ var writerGuidRepresentation = bsonWriter.Settings.GuidRepresentation;
+ if (writerGuidRepresentation != GuidRepresentation.Unspecified)
{
- var writerGuidRepresentation = bsonWriter.Settings.GuidRepresentation;
- if (writerGuidRepresentation != GuidRepresentation.Unspecified)
+ var bytes = binaryData.Bytes;
+ var guidRepresentation = binaryData.GuidRepresentation;
+
+ if (guidRepresentation == GuidRepresentation.Unspecified)
{
- if (guidRepresentation == GuidRepresentation.Unspecified)
- {
- var message = string.Format(
- "Cannot serialize BsonBinaryData with GuidRepresentation Unspecified to destination with GuidRepresentation {0}.",
- writerGuidRepresentation);
- throw new BsonSerializationException(message);
- }
- if (guidRepresentation != writerGuidRepresentation)
- {
- var guid = GuidConverter.FromBytes(bytes, guidRepresentation);
- bytes = GuidConverter.ToBytes(guid, writerGuidRepresentation);
- subType = (writerGuidRepresentation == GuidRepresentation.Standard) ? BsonBinarySubType.UuidStandard : BsonBinarySubType.UuidLegacy;
- guidRepresentation = writerGuidRepresentation;
- }
+ var message = string.Format(
+ "Cannot serialize BsonBinaryData with GuidRepresentation Unspecified to destination with GuidRepresentation {0}.",
+ writerGuidRepresentation);
+ throw new BsonSerializationException(message);
+ }
+ if (guidRepresentation != writerGuidRepresentation)
+ {
+ var guid = GuidConverter.FromBytes(bytes, guidRepresentation);
+ bytes = GuidConverter.ToBytes(guid, writerGuidRepresentation);
+ subType = (writerGuidRepresentation == GuidRepresentation.Standard) ? BsonBinarySubType.UuidStandard : BsonBinarySubType.UuidLegacy;
+ guidRepresentation = writerGuidRepresentation;
+ binaryData = new BsonBinaryData(bytes, subType, guidRepresentation);
}
}
-
- binaryData = new BsonBinaryData(bytes, subType, guidRepresentation);
- bsonWriter.WriteBinaryData(binaryData);
}
+
+ bsonWriter.WriteBinaryData(binaryData);
}
}
}
View
25 MongoDB.Bson/Serialization/Serializers/BsonBooleanSerializer.cs
@@ -20,7 +20,6 @@
using System.Text;
using MongoDB.Bson.IO;
-using MongoDB.Bson.Serialization.Options;
namespace MongoDB.Bson.Serialization.Serializers
{
@@ -37,7 +36,6 @@ public class BsonBooleanSerializer : BsonBaseSerializer
/// Initializes a new instance of the BsonBooleanSerializer class.
/// </summary>
public BsonBooleanSerializer()
- : base(new RepresentationSerializationOptions(BsonType.Boolean))
{
}
@@ -68,14 +66,13 @@ public static BsonBooleanSerializer Instance
VerifyTypes(nominalType, actualType, typeof(BsonBoolean));
var bsonType = bsonReader.GetCurrentBsonType();
- if (bsonType == BsonType.Null)
+ switch (bsonType)
{
- bsonReader.ReadNull();
- return null;
- }
- else
- {
- return (BsonBoolean)((bool)BooleanSerializer.Instance.Deserialize(bsonReader, typeof(bool), options));
+ case BsonType.Boolean:
+ return (BsonBoolean)bsonReader.ReadBoolean();
+ default:
+ var message = string.Format("Cannot deserialize BsonBoolean from BsonType {0}.", bsonType);
+ throw new FileFormatException(message);
}
}
@@ -94,13 +91,11 @@ public static BsonBooleanSerializer Instance
{
if (value == null)
{
- bsonWriter.WriteNull();
- }
- else
- {
- var bsonBoolean = (BsonBoolean)value;
- BooleanSerializer.Instance.Serialize(bsonWriter, nominalType, bsonBoolean.Value, options);
+ throw new ArgumentNullException("value");
}
+
+ var bsonBoolean = (BsonBoolean)value;
+ bsonWriter.WriteBoolean(bsonBoolean.Value);
}
}
}
View
85 MongoDB.Bson/Serialization/Serializers/BsonClassMapSerializer.cs
@@ -24,6 +24,7 @@
using MongoDB.Bson.IO;
using MongoDB.Bson.Serialization.Options;
+using MongoDB.Bson.Serialization.Serializers;
namespace MongoDB.Bson.Serialization
{
@@ -377,7 +378,7 @@ public BsonSerializationInfo GetMemberSerializationInfo(string memberName)
if (discriminator != null)
{
bsonWriter.WriteName(discriminatorConvention.ElementName);
- discriminator.WriteTo(bsonWriter);
+ BsonValueSerializer.Instance.Serialize(bsonWriter, typeof(BsonValue), discriminator, null);
}
}
}
@@ -446,7 +447,7 @@ public void SetDocumentId(object document, object id)
extraElements = new BsonDocument();
extraElementsMemberMap.Setter(obj, extraElements);
}
- var bsonValue = BsonValue.ReadFrom(bsonReader);
+ var bsonValue = (BsonValue)BsonValueSerializer.Instance.Deserialize(bsonReader, typeof(BsonValue), null);
extraElements[elementName] = bsonValue;
}
else
@@ -464,7 +465,7 @@ public void SetDocumentId(object document, object id)
}
extraElementsMemberMap.Setter(obj, extraElements);
}
- var bsonValue = BsonValue.ReadFrom(bsonReader);
+ var bsonValue = (BsonValue)BsonValueSerializer.Instance.Deserialize(bsonReader, typeof(BsonValue), null);
extraElements[elementName] = BsonTypeMapper.MapToDotNetValue(bsonValue);
}
}
@@ -473,30 +474,45 @@ private void DeserializeMember(BsonReader bsonReader, object obj, BsonMemberMap
{
try
{
- object value;
-
var nominalType = memberMap.MemberType;
+ object value = null;
+
var bsonType = bsonReader.GetCurrentBsonType();
if (bsonType == BsonType.Null && nominalType.IsInterface)
{
bsonReader.ReadNull();
- value = null;
+ goto setvalue;
}
- else{
- Type actualType;
- if (bsonType == BsonType.Null)
+ else if (memberMap.MemberTypeIsBsonValue)
+ {
+ if (bsonType == BsonType.Document && IsCSharpNullRepresentation(bsonReader))
{
- actualType = nominalType;
+ // if IsCSharpNullRepresentation returns true it will have consumed the document representing C# null
+ goto setvalue;
}
- else
+
+ // handle BSON null for backward compatibility with existing data (new data would have _csharpnull)
+ if (bsonType == BsonType.Null && (nominalType != typeof(BsonValue) && nominalType != typeof(BsonNull)))
{
- var discriminatorConvention = memberMap.GetDiscriminatorConvention();
- actualType = discriminatorConvention.GetActualType(bsonReader, nominalType); // returns nominalType if no discriminator found
+ bsonReader.ReadNull();
+ goto setvalue;
}
- var serializer = memberMap.GetSerializer(actualType);
- value = serializer.Deserialize(bsonReader, nominalType, actualType, memberMap.SerializationOptions);
}
+ Type actualType;
+ if (bsonType == BsonType.Null)
+ {
+ actualType = nominalType;
+ }
+ else
+ {
+ var discriminatorConvention = memberMap.GetDiscriminatorConvention();
+ actualType = discriminatorConvention.GetActualType(bsonReader, nominalType); // returns nominalType if no discriminator found
+ }
+ var serializer = memberMap.GetSerializer(actualType);
+ value = serializer.Deserialize(bsonReader, nominalType, actualType, memberMap.SerializationOptions);
+
+ setvalue:
memberMap.Setter(obj, value);
}
catch (Exception ex)
@@ -508,6 +524,33 @@ private void DeserializeMember(BsonReader bsonReader, object obj, BsonMemberMap
}
}
+ private bool IsCSharpNullRepresentation(BsonReader bsonReader)
+ {
+ var bookmark = bsonReader.GetBookmark();
+ bsonReader.ReadStartDocument();
+ var bsonType = bsonReader.ReadBsonType();
+ if (bsonType == BsonType.Boolean)
+ {
+ var name = bsonReader.ReadName();
+ if (name == "_csharpnull" || name == "$csharpnull")
+ {
+ var value = bsonReader.ReadBoolean();
+ if (value)
+ {
+ bsonType = bsonReader.ReadBsonType();
+ if (bsonType == BsonType.EndOfDocument)
+ {
+ bsonReader.ReadEndDocument();
+ return true;
+ }
+ }
+ }
+ }
+
+ bsonReader.ReturnToBookmark(bookmark);
+ return false;
+ }
+
private void SerializeExtraElements(BsonWriter bsonWriter, object obj, BsonMemberMap extraElementsMemberMap)
{
var extraElements = extraElementsMemberMap.Getter(obj);
@@ -518,7 +561,8 @@ private void SerializeExtraElements(BsonWriter bsonWriter, object obj, BsonMembe
var bsonDocument = (BsonDocument)extraElements;
foreach (var element in bsonDocument)
{
- element.WriteTo(bsonWriter);
+ bsonWriter.WriteName(element.Name);
+ BsonValueSerializer.Instance.Serialize(bsonWriter, typeof(BsonValue), element.Value, null);
}
}
else
@@ -535,7 +579,7 @@ private void SerializeExtraElements(BsonWriter bsonWriter, object obj, BsonMembe
else
{
var bsonValue = BsonTypeMapper.MapToBsonValue(dictionary[key]);
- bsonValue.WriteTo(bsonWriter);
+ BsonValueSerializer.Instance.Serialize(bsonWriter, typeof(BsonValue), bsonValue, null);
}
}
}
@@ -552,12 +596,17 @@ private void SerializeMember(BsonWriter bsonWriter, object obj, BsonMemberMap me
}
bsonWriter.WriteName(memberMap.ElementName);
-
var nominalType = memberMap.MemberType;
if (value == null && nominalType.IsInterface)
{
bsonWriter.WriteNull();
}
+ else if (value == null && memberMap.MemberTypeIsBsonValue)
+ {
+ bsonWriter.WriteStartDocument();
+ bsonWriter.WriteBoolean("_csharpnull", true);
+ bsonWriter.WriteEndDocument();
+ }
else
{
var actualType = (value == null) ? nominalType : value.GetType();
View
185 MongoDB.Bson/Serialization/Serializers/BsonDateTimeSerializer.cs
@@ -21,7 +21,6 @@
using System.Text;
using MongoDB.Bson.IO;
-using MongoDB.Bson.Serialization.Options;
namespace MongoDB.Bson.Serialization.Serializers
{
@@ -38,7 +37,6 @@ public class BsonDateTimeSerializer : BsonBaseSerializer
/// Initializes a new instance of the BsonDateTimeSerializer class.
/// </summary>
public BsonDateTimeSerializer()
- : base(DateTimeSerializationOptions.Defaults)
{
}
@@ -67,102 +65,16 @@ public static BsonDateTimeSerializer Instance
IBsonSerializationOptions options)
{
VerifyTypes(nominalType, actualType, typeof(BsonDateTime));
- var dateTimeSerializationOptions = EnsureSerializationOptions<DateTimeSerializationOptions>(options);
var bsonType = bsonReader.GetCurrentBsonType();
- if (bsonType == BsonType.Null)
+ switch (bsonType)
{
- bsonReader.ReadNull();
- return null;
- }
- else
- {
- long? millisecondsSinceEpoch = null;
- long? ticks = null;
- switch (bsonType)
- {
- case BsonType.DateTime:
- millisecondsSinceEpoch = bsonReader.ReadDateTime();
- break;
- case BsonType.Document:
- bsonReader.ReadStartDocument();
- millisecondsSinceEpoch = bsonReader.ReadDateTime("DateTime");
- bsonReader.ReadName("Ticks");
- var ticksValue = BsonValue.ReadFrom(bsonReader);
- if (!ticksValue.IsBsonUndefined)
- {
- ticks = ticksValue.ToInt64();
- }
- bsonReader.ReadEndDocument();
- break;
- case BsonType.Int64:
- ticks = bsonReader.ReadInt64();
- break;
- case BsonType.String:
- // note: we're not using XmlConvert because of bugs in Mono
- DateTime dateTime;
- if (dateTimeSerializationOptions.DateOnly)
- {
- dateTime = DateTime.SpecifyKind(DateTime.ParseExact(bsonReader.ReadString(), "yyyy-MM-dd", null), DateTimeKind.Utc);
- }
- else
- {
- var formats = new string[] { "yyyy-MM-ddK", "yyyy-MM-ddTHH:mm:ssK", "yyyy-MM-ddTHH:mm:ss.FFFFFFFK", };
- dateTime = DateTime.ParseExact(bsonReader.ReadString(), formats, null, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal);
- }
- ticks = dateTime.Ticks;
- break;
- default:
- var message = string.Format("Cannot deserialize DateTime from BsonType {0}.", bsonType);
- throw new FileFormatException(message);
- }
-
- BsonDateTime bsonDateTime;
- if (ticks.HasValue)
- {
- bsonDateTime = new BsonDateTime(new DateTime(ticks.Value, DateTimeKind.Utc));
- }
- else
- {
- bsonDateTime = new BsonDateTime(millisecondsSinceEpoch.Value);
- }
-
- if (dateTimeSerializationOptions.DateOnly)
- {
- var dateTime = bsonDateTime.ToUniversalTime();
- if (dateTime.TimeOfDay != TimeSpan.Zero)
- {
- throw new FileFormatException("TimeOfDay component for DateOnly DateTime value is not zero.");
- }
- bsonDateTime = new BsonDateTime(DateTime.SpecifyKind(dateTime, dateTimeSerializationOptions.Kind)); // not ToLocalTime or ToUniversalTime!
- }
- else
- {
- if (bsonDateTime.IsValidDateTime)
- {
- var dateTime = bsonDateTime.ToUniversalTime();
- switch (dateTimeSerializationOptions.Kind)
- {
- case DateTimeKind.Local:
- case DateTimeKind.Unspecified:
- dateTime = DateTime.SpecifyKind(BsonUtils.ToLocalTime(dateTime), dateTimeSerializationOptions.Kind);
- break;
- case DateTimeKind.Utc:
- dateTime = BsonUtils.ToUniversalTime(dateTime);
- break;
- }
- bsonDateTime = new BsonDateTime(dateTime);
- }
- else
- {
- if (dateTimeSerializationOptions.Kind != DateTimeKind.Utc)
- {
- throw new FileFormatException("BsonDateTime is outside the range of .NET DateTime.");
- }
- }
- }
-
- return bsonDateTime;
+ case BsonType.DateTime:
+ var millisecondsSinceEpoch = bsonReader.ReadDateTime();
+ return new BsonDateTime(millisecondsSinceEpoch);
+ default:
+ var message = string.Format("Cannot deserialize BsonDateTime from BsonType {0}.", bsonType);
+ throw new FileFormatException(message);
}
}
@@ -181,88 +93,11 @@ public static BsonDateTimeSerializer Instance
{
if (value == null)
{
- bsonWriter.WriteNull();
+ throw new ArgumentNullException("value");
}
- else
- {
- var bsonDateTime = (BsonDateTime)value;
- var dateTimeSerializationOptions = EnsureSerializationOptions<DateTimeSerializationOptions>(options);
- DateTime utcDateTime = DateTime.MinValue;
- long millisecondsSinceEpoch;
- if (dateTimeSerializationOptions.DateOnly)
- {
- if (bsonDateTime.ToUniversalTime().TimeOfDay != TimeSpan.Zero)
- {
- throw new BsonSerializationException("TimeOfDay component is not zero.");
- }
- utcDateTime = DateTime.SpecifyKind(bsonDateTime.ToUniversalTime(), DateTimeKind.Utc); // not ToLocalTime
- millisecondsSinceEpoch = BsonUtils.ToMillisecondsSinceEpoch(utcDateTime);
- }
- else
- {
- if (bsonDateTime.IsValidDateTime)
- {
- utcDateTime = BsonUtils.ToUniversalTime(bsonDateTime.ToUniversalTime());
- }
- millisecondsSinceEpoch = bsonDateTime.MillisecondsSinceEpoch;
- }
-
- switch (dateTimeSerializationOptions.Representation)
- {
- case BsonType.DateTime:
- bsonWriter.WriteDateTime(millisecondsSinceEpoch);
- break;
- case BsonType.Document:
- bsonWriter.WriteStartDocument();
- bsonWriter.WriteDateTime("DateTime", millisecondsSinceEpoch);
- if (bsonDateTime.IsValidDateTime)
- {
- bsonWriter.WriteInt64("Ticks", utcDateTime.Ticks);
- }
- else
- {
- bsonWriter.WriteUndefined("Ticks");
- }
- bsonWriter.WriteEndDocument();
- break;
- case BsonType.Int64:
- if (bsonDateTime.IsValidDateTime)
- {
- bsonWriter.WriteInt64(utcDateTime.Ticks);
- }
- else
- {
- throw new BsonSerializationException("BsonDateTime is not a valid DateTime.");
- }
- break;
- case BsonType.String:
- if (dateTimeSerializationOptions.DateOnly)
- {
- bsonWriter.WriteString(bsonDateTime.ToUniversalTime().ToString("yyyy-MM-dd"));
- }
- else
- {
- // we're not using XmlConvert.ToString because of bugs in Mono
- var dateTime = bsonDateTime.ToUniversalTime();
- if (dateTime == DateTime.MinValue || dateTime == DateTime.MaxValue)
- {
- // serialize MinValue and MaxValue as Unspecified so we do NOT get the time zone offset
- dateTime = DateTime.SpecifyKind(dateTime, DateTimeKind.Unspecified);
- }
- else if (dateTime.Kind == DateTimeKind.Unspecified)
- {
- // serialize Unspecified as Local se we get the time zone offset
- dateTime = DateTime.SpecifyKind(dateTime, DateTimeKind.Local);
- }
- bsonWriter.WriteString(dateTime.ToString("yyyy-MM-ddTHH:mm:ss.FFFFFFFK"));
- }
- break;
- default:
- var message = string.Format("'{0}' is not a valid DateTime representation.", dateTimeSerializationOptions.Representation);
- throw new BsonSerializationException(message);
- }
- }
+ var bsonDateTime = (BsonDateTime)value;
+ bsonWriter.WriteDateTime(bsonDateTime.MillisecondsSinceEpoch);
}
}
}
View
125 MongoDB.Bson/Serialization/Serializers/BsonDocumentSerializer.cs
@@ -15,10 +15,12 @@
using System;
using System.Collections.Generic;
+using System.IO;
using System.Linq;
using System.Text;
using MongoDB.Bson.IO;
+using MongoDB.Bson.Serialization.IdGenerators;
using MongoDB.Bson.Serialization.Options;
namespace MongoDB.Bson.Serialization.Serializers
@@ -66,7 +68,36 @@ public static BsonDocumentSerializer Instance
{
VerifyTypes(nominalType, actualType, typeof(BsonDocument));
- return BsonDocument.ReadFrom(bsonReader);
+ var bsonType = bsonReader.GetCurrentBsonType();
+ string message;
+ switch (bsonType)
+ {
+ case BsonType.Document:
+ var documentSerializationOptions = (options ?? DocumentSerializationOptions.Defaults) as DocumentSerializationOptions;
+ if (documentSerializationOptions == null)
+ {
+ message = string.Format(
+ "Serialize method of BsonDocument expected serialization options of type {0}, not {1}.",
+ BsonUtils.GetFriendlyTypeName(typeof(DocumentSerializationOptions)),
+ BsonUtils.GetFriendlyTypeName(options.GetType()));
+ throw new BsonSerializationException(message);
+ }
+
+ bsonReader.ReadStartDocument();
+ var document = new BsonDocument(documentSerializationOptions.AllowDuplicateNames);
+ while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
+ {
+ var name = bsonReader.ReadName();
+ var value = (BsonValue)BsonValueSerializer.Instance.Deserialize(bsonReader, typeof(BsonValue), null);
+ document.Add(name, value);
+ }
+ bsonReader.ReadEndDocument();
+
+ return document;
+ default:
+ message = string.Format("Cannot deserialize BsonDocument from BsonType {0}.", bsonType);
+ throw new FileFormatException(message);
+ }
}
/// <summary>
@@ -84,7 +115,30 @@ public static BsonDocumentSerializer Instance
out IIdGenerator idGenerator)
{
var bsonDocument = (BsonDocument)document;
- return ((IBsonSerializable)bsonDocument).GetDocumentId(out id, out idNominalType, out idGenerator);
+
+ BsonElement idElement;
+ if (bsonDocument.TryGetElement("_id", out idElement))
+ {
+ id = idElement.Value;
+ idGenerator = BsonSerializer.LookupIdGenerator(id.GetType());
+
+ if (idGenerator == null)
+ {
+ var idBinaryData = id as BsonBinaryData;
+ if (idBinaryData != null && (idBinaryData.SubType == BsonBinarySubType.UuidLegacy || idBinaryData.SubType == BsonBinarySubType.UuidStandard))
+ {
+ idGenerator = BsonBinaryDataGuidGenerator.GetInstance(idBinaryData.GuidRepresentation);
+ }
+ }
+ }
+ else
+ {
+ id = null;
+ idGenerator = BsonObjectIdGenerator.Instance;
+ }
+
+ idNominalType = typeof(BsonValue);
+ return true;
}
/// <summary>
@@ -102,13 +156,47 @@ public static BsonDocumentSerializer Instance
{
if (value == null)
{
- bsonWriter.WriteNull();
+ throw new ArgumentNullException("value");
}
- else
+
+ // could get here with a BsonDocumentWrapper from BsonValueSerializer switch statement
+ var wrapper = value as BsonDocumentWrapper;
+ if (wrapper != null)
{
- var bsonDocument = (BsonDocument)value;
- ((IBsonSerializable)bsonDocument).Serialize(bsonWriter, nominalType, options);
+ BsonDocumentWrapperSerializer.Instance.Serialize(bsonWriter, nominalType, value, null);
+ return;
}
+
+ var bsonDocument = (BsonDocument)value;
+ var documentSerializationOptions = (options ?? DocumentSerializationOptions.Defaults) as DocumentSerializationOptions;
+ if (documentSerializationOptions == null)
+ {
+ var message = string.Format(
+ "Serialize method of BsonDocument expected serialization options of type {0}, not {1}.",
+ BsonUtils.GetFriendlyTypeName(typeof(DocumentSerializationOptions)),
+ BsonUtils.GetFriendlyTypeName(options.GetType()));
+ throw new BsonSerializationException(message);
+ }
+
+ bsonWriter.WriteStartDocument();
+ BsonElement idElement = null;
+ if (documentSerializationOptions.SerializeIdFirst && bsonDocument.TryGetElement("_id", out idElement))
+ {
+ bsonWriter.WriteName(idElement.Name);
+ BsonValueSerializer.Instance.Serialize(bsonWriter, typeof(BsonValue), idElement.Value, null);
+ }
+
+ foreach (var element in bsonDocument)
+ {
+ // if serializeIdFirst is false then idElement will be null and no elements will be skipped
+ if (!object.ReferenceEquals(element, idElement))
+ {
+ bsonWriter.WriteName(element.Name);
+ BsonValueSerializer.Instance.Serialize(bsonWriter, typeof(BsonValue), element.Value, null);
+ }
+ }
+
+ bsonWriter.WriteEndDocument();
}
/// <summary>
@@ -118,8 +206,31 @@ public static BsonDocumentSerializer Instance
/// <param name="id">The Id.</param>
public void SetDocumentId(object document, object id)
{
+ if (document == null)
+ {
+ throw new ArgumentNullException("document");
+ }
+ if (id == null)
+ {
+ throw new ArgumentNullException("id");
+ }
+
var bsonDocument = (BsonDocument)document;
- ((IBsonSerializable)bsonDocument).SetDocumentId(id);
+ var idBsonValue = id as BsonValue;
+ if (idBsonValue == null)
+ {
+ idBsonValue = BsonValue.Create(id); // be helpful and provide automatic conversion to BsonValue if necessary
+ }
+
+ BsonElement idElement;
+ if (bsonDocument.TryGetElement("_id", out idElement))
+ {
+ idElement.Value = idBsonValue;
+ }
+ else
+ {
+ bsonDocument.InsertAt(0, new BsonElement("_id", idBsonValue));
+ }
}
}
}
View
23 MongoDB.Bson/Serialization/Serializers/BsonDocumentWrapperSerializer.cs
@@ -80,12 +80,29 @@ public static BsonDocumentWrapperSerializer Instance
{
if (value == null)
{
- bsonWriter.WriteNull();
+ throw new ArgumentNullException("value");
+ }
+
+ var wrapper = (BsonDocumentWrapper)value;
+ if (wrapper.IsUpdateDocument)
+ {
+ var savedCheckElementNames = bsonWriter.CheckElementNames;
+ var savedCheckUpdateDocument = bsonWriter.CheckUpdateDocument;
+ try
+ {
+ bsonWriter.CheckElementNames = false;
+ bsonWriter.CheckUpdateDocument = true;
+ BsonSerializer.Serialize(bsonWriter, wrapper.WrappedNominalType, wrapper.WrappedObject, null); // TODO: wrap options also?
+ }
+ finally
+ {
+ bsonWriter.CheckElementNames = savedCheckElementNames;
+ bsonWriter.CheckUpdateDocument = savedCheckUpdateDocument;
+ }
}
else
{
- var bsonDocumentWrapper = (BsonDocumentWrapper)value;
- ((IBsonSerializable)bsonDocumentWrapper).Serialize(bsonWriter, nominalType, options);
+ BsonSerializer.Serialize(bsonWriter, wrapper.WrappedNominalType, wrapper.WrappedObject, null); // TODO: wrap options also?
}
}
}
View
26 MongoDB.Bson/Serialization/Serializers/BsonDoubleSerializer.cs
@@ -15,11 +15,11 @@
using System;
using System.Collections.Generic;
+using System.IO;
using System.Linq;
using System.Text;
using MongoDB.Bson.IO;
-using MongoDB.Bson.Serialization.Options;
namespace MongoDB.Bson.Serialization.Serializers
{
@@ -36,7 +36,6 @@ public class BsonDoubleSerializer : BsonBaseSerializer
/// Initializes a new instance of the BsonDoubleSerializer class.
/// </summary>
public BsonDoubleSerializer()
- : base(new RepresentationSerializationOptions(BsonType.Double))
{
}
@@ -67,14 +66,13 @@ public static BsonDoubleSerializer Instance
VerifyTypes(nominalType, actualType, typeof(BsonDouble));
var bsonType = bsonReader.GetCurrentBsonType();
- if (bsonType == BsonType.Null)
+ switch (bsonType)
{
- bsonReader.ReadNull();
- return null;
- }
- else
- {
- return new BsonDouble((double)DoubleSerializer.Instance.Deserialize(bsonReader, typeof(double), options));
+ case BsonType.Double:
+ return new BsonDouble(bsonReader.ReadDouble());
+ default:
+ var message = string.Format("Cannot deserialize BsonDouble from BsonType {0}.", bsonType);
+ throw new FileFormatException(message);
}
}
@@ -93,13 +91,11 @@ public static BsonDoubleSerializer Instance
{
if (value == null)
{
- bsonWriter.WriteNull();
- }
- else
- {
- var bsonDouble = (BsonDouble)value;
- DoubleSerializer.Instance.Serialize(bsonWriter, nominalType, bsonDouble.Value, options);
+ throw new ArgumentNullException("value");
}
+
+ var bsonDouble = (BsonDouble)value;
+ bsonWriter.WriteDouble(bsonDouble.Value);
}
}
}
View
26 MongoDB.Bson/Serialization/Serializers/BsonInt32Serializer.cs
@@ -15,11 +15,11 @@
using System;
using System.Collections.Generic;
+using System.IO;
using System.Linq;
using System.Text;
using MongoDB.Bson.IO;
-using MongoDB.Bson.Serialization.Options;
namespace MongoDB.Bson.Serialization.Serializers
{
@@ -36,7 +36,6 @@ public class BsonInt32Serializer : BsonBaseSerializer
/// Initializes a new instance of the BsonInt32Serializer class.
/// </summary>
public BsonInt32Serializer()
- : base(new RepresentationSerializationOptions(BsonType.Int32))
{
}
@@ -67,14 +66,13 @@ public static BsonInt32Serializer Instance
VerifyTypes(nominalType, actualType, typeof(BsonInt32));
var bsonType = bsonReader.GetCurrentBsonType();
- if (bsonType == BsonType.Null)
+ switch (bsonType)
{
- bsonReader.ReadNull();
- return null;
- }
- else
- {
- return new BsonInt32((int)Int32Serializer.Instance.Deserialize(bsonReader, typeof(int), options));
+ case BsonType.Int32:
+ return new BsonInt32(bsonReader.ReadInt32());
+ default:
+ var message = string.Format("Cannot deserialize BsonInt32 from BsonType {0}.", bsonType);
+ throw new FileFormatException(message);
}
}
@@ -93,13 +91,11 @@ public static BsonInt32Serializer Instance
{
if (value == null)
{
- bsonWriter.WriteNull();
- }
- else
- {
- var bsonInt32 = (BsonInt32)value;
- Int32Serializer.Instance.Serialize(bsonWriter, nominalType, bsonInt32.Value, options);
+ throw new ArgumentNullException("value");
}
+
+ var bsonInt32 = (BsonInt32)value;
+ bsonWriter.WriteInt32(bsonInt32.Value);
}
}
}
View
26 MongoDB.Bson/Serialization/Serializers/BsonInt64Serializer.cs
@@ -15,11 +15,11 @@
using System;
using System.Collections.Generic;
+using System.IO;
using System.Linq;
using System.Text;
using MongoDB.Bson.IO;
-using MongoDB.Bson.Serialization.Options;
namespace MongoDB.Bson.Serialization.Serializers
{
@@ -36,7 +36,6 @@ public class BsonInt64Serializer : BsonBaseSerializer
/// Initializes a new instance of the BsonInt64Serializer class.
/// </summary>
public BsonInt64Serializer()
- : base(new RepresentationSerializationOptions(BsonType.Int64))
{
}
@@ -67,14 +66,13 @@ public static BsonInt64Serializer Instance
VerifyTypes(nominalType, actualType, typeof(BsonInt64));
var bsonType = bsonReader.GetCurrentBsonType();
- if (bsonType == BsonType.Null)
+ switch (bsonType)
{
- bsonReader.ReadNull();
- return null;
- }
- else
- {
- return new BsonInt64((long)Int64Serializer.Instance.Deserialize(bsonReader, typeof(long), options));
+ case BsonType.Int64:
+ return new BsonInt64(bsonReader.ReadInt64());
+ default:
+ var message = string.Format("Cannot deserialize BsonInt64 from BsonType {0}.", bsonType);
+ throw new FileFormatException(message);
}
}
@@ -93,13 +91,11 @@ public static BsonInt64Serializer Instance
{
if (value == null)
{
- bsonWriter.WriteNull();
- }
- else
- {
- var bsonInt64 = (BsonInt64)value;
- Int64Serializer.Instance.Serialize(bsonWriter, nominalType, bsonInt64.Value, options);
+ throw new ArgumentNullException("value");
}
+
+ var bsonInt64 = (BsonInt64)value;
+ bsonWriter.WriteInt64(bsonInt64.Value);
}
}
}
View
26 MongoDB.Bson/Serialization/Serializers/BsonJavaScriptSerializer.cs
@@ -15,6 +15,7 @@
using System;
using System.Collections.Generic;
+using System.IO;
using System.Linq;
using System.Text;
@@ -65,15 +66,14 @@ public static BsonJavaScriptSerializer Instance
VerifyTypes(nominalType, actualType, typeof(BsonJavaScript));
var bsonType = bsonReader.GetCurrentBsonType();
- if (bsonType == BsonType.Null)
+ switch (bsonType)
{
- bsonReader.ReadNull();
- return null;
- }
- else
- {
- var code = bsonReader.ReadJavaScript();
- return new BsonJavaScript(code);
+ case BsonType.JavaScript:
+ var code = bsonReader.ReadJavaScript();
+ return new BsonJavaScript(code);
+ default:
+ var message = string.Format("Cannot deserialize BsonJavaScript from BsonType {0}.", bsonType);
+ throw new FileFormatException(message);
}
}
@@ -92,13 +92,11 @@ public static BsonJavaScriptSerializer Instance
{
if (value == null)
{
- bsonWriter.WriteNull();
- }
- else
- {
- var script = (BsonJavaScript)value;
- bsonWriter.WriteJavaScript(script.Code);
+ throw new ArgumentNullException("value");
}
+
+ var script = (BsonJavaScript)value;
+ bsonWriter.WriteJavaScript(script.Code);
}
}
}
View
30 MongoDB.Bson/Serialization/Serializers/BsonJavaScriptWithScopeSerializer.cs
@@ -15,6 +15,7 @@
using System;
using System.Collections.Generic;
+using System.IO;
using System.Linq;
using System.Text;
@@ -65,16 +66,15 @@ public static BsonJavaScriptWithScopeSerializer Instance
VerifyTypes(nominalType, actualType, typeof(BsonJavaScriptWithScope));
var bsonType = bsonReader.GetCurrentBsonType();
- if (bsonType == BsonType.Null)
+ switch (bsonType)
{
- bsonReader.ReadNull();
- return null;
- }
- else
- {
- var code = bsonReader.ReadJavaScriptWithScope();
- var scope = BsonDocument.ReadFrom(bsonReader);
- return new BsonJavaScriptWithScope(code, scope);
+ case BsonType.JavaScriptWithScope:
+ var code = bsonReader.ReadJavaScriptWithScope();
+ var scope = (BsonDocument)BsonDocumentSerializer.Instance.Deserialize(bsonReader, typeof(BsonDocument), null);
+ return new BsonJavaScriptWithScope(code, scope);
+ default:
+ var message = string.Format("Cannot deserialize BsonJavaScriptWithScope from BsonType {0}.", bsonType);
+ throw new FileFormatException(message);
}
}
@@ -93,14 +93,12 @@ public static BsonJavaScriptWithScopeSerializer Instance
{
if (value == null)
{
- bsonWriter.WriteNull();
- }
- else
- {
- var script = (BsonJavaScriptWithScope)value;
- bsonWriter.WriteJavaScriptWithScope(script.Code);
- script.Scope.WriteTo(bsonWriter);
+ throw new ArgumentNullException("value");
}
+
+ var script = (BsonJavaScriptWithScope)value;
+ bsonWriter.WriteJavaScriptWithScope(script.Code);
+ BsonDocumentSerializer.Instance.Serialize(bsonWriter, typeof(BsonDocument), script.Scope, null);
}
}
}
View
25 MongoDB.Bson/Serialization/Serializers/BsonMaxKeySerializer.cs
@@ -15,6 +15,7 @@
using System;
using System.Collections.Generic;
+using System.IO;
using System.Linq;
using System.Text;
@@ -65,15 +66,14 @@ public static BsonMaxKeySerializer Instance
VerifyTypes(nominalType, actualType, typeof(BsonMaxKey));
var bsonType = bsonReader.GetCurrentBsonType();
- if (bsonType == BsonType.Null)
+ switch (bsonType)
{
- bsonReader.ReadNull();
- return null;
- }
- else
- {
- bsonReader.ReadMaxKey();
- return BsonMaxKey.Value;
+ case BsonType.MaxKey:
+ bsonReader.ReadMaxKey();
+ return BsonMaxKey.Value;
+ default:
+ var message = string.Format("Cannot deserialize BsonMaxKey from BsonType {0}.", bsonType);
+ throw new FileFormatException(message);
}
}
@@ -92,12 +92,11 @@ public static BsonMaxKeySerializer Instance
{
if (value == null)
{
- bsonWriter.WriteNull();
- }
- else
- {
- bsonWriter.WriteMaxKey();
+ throw new ArgumentNullException("value");
}
+
+ var bsonMaxKey = (BsonMaxKey)value; // check type by casting
+ bsonWriter.WriteMaxKey();
}
}
}
View
25 MongoDB.Bson/Serialization/Serializers/BsonMinKeySerializer.cs
@@ -15,6 +15,7 @@
using System;
using System.Collections.Generic;
+using System.IO;
using System.Linq;
using System.Text;
@@ -65,15 +66,14 @@ public static BsonMinKeySerializer Instance
VerifyTypes(nominalType, actualType, typeof(BsonMinKey));
var bsonType = bsonReader.GetCurrentBsonType();
- if (bsonType == BsonType.Null)
+ switch (bsonType)
{
- bsonReader.ReadNull();
- return null;
- }
- else
- {
- bsonReader.ReadMinKey();
- return BsonMinKey.Value;
+ case BsonType.MinKey:
+ bsonReader.ReadMinKey();
+ return BsonMinKey.Value;
+ default:
+ var message = string.Format("Cannot deserialize BsonMinKey from BsonType {0}.", bsonType);
+ throw new FileFormatException(message);
}
}
@@ -92,12 +92,11 @@ public static BsonMinKeySerializer Instance
{
if (value == null)
{
- bsonWriter.WriteNull();
- }
- else
- {
- bsonWriter.WriteMinKey();
+ throw new ArgumentNullException("value");
}
+
+ var bsonMinKey = (BsonMinKey)value; // check type by casting
+ bsonWriter.WriteMinKey();
}
}
}
View
28 MongoDB.Bson/Serialization/Serializers/BsonNullSerializer.cs
@@ -66,28 +66,13 @@ public static BsonNullSerializer Instance
VerifyTypes(nominalType, actualType, typeof(BsonNull));
var bsonType = bsonReader.GetCurrentBsonType();
- string message;
switch (bsonType)
{
case BsonType.Null:
bsonReader.ReadNull();
return BsonNull.Value;
- case BsonType.Document:
- bsonReader.ReadStartDocument();
- var name = bsonReader.ReadName();
- if (name == "_csharpnull" || name == "$csharpnull")
- {
- var csharpNull = bsonReader.ReadBoolean();
- bsonReader.ReadEndDocument();
- return csharpNull ? null : BsonNull.Value;
- }
- else
- {
- message = string.Format("Unexpected element name while deserializing a BsonNull: {0}.", name);
- throw new FileFormatException(message);
- }
default:
- message = string.Format("Cannot deserialize BsonNull from BsonType {0}.", bsonType);
+ var message = string.Format("Cannot deserialize BsonNull from BsonType {0}.", bsonType);
throw new FileFormatException(message);
}
}
@@ -107,14 +92,11 @@ public static BsonNullSerializer Instance
{
if (value == null)
{
- bsonWriter.WriteStartDocument();
- bsonWriter.WriteBoolean("_csharpnull", true);
- bsonWriter.WriteEndDocument();
- }
- else
- {
- bsonWriter.WriteNull();
+ throw new ArgumentNullException("value");
}
+
+ var bsonNull = (BsonNull)value; // check type by casting
+ bsonWriter.WriteNull();
}
}
}
View
26 MongoDB.Bson/Serialization/Serializers/BsonObjectIdSerializer.cs
@@ -15,11 +15,11 @@
using System;
using System.Collections.Generic;
+using System.IO;
using System.Linq;
using System.Text;
using MongoDB.Bson.IO;
-using MongoDB.Bson.Serialization.Options;
namespace MongoDB.Bson.Serialization.Serializers
{
@@ -36,7 +36,6 @@ public class BsonObjectIdSerializer : BsonBaseSerializer
/// Initializes a new instance of the BsonObjectIdSerializer class.
/// </summary>
public BsonObjectIdSerializer()
- : base(new RepresentationSerializationOptions(BsonType.ObjectId))
{
}
@@ -67,14 +66,13 @@ public static BsonObjectIdSerializer Instance
VerifyTypes(nominalType, actualType, typeof(BsonObjectId));
var bsonType = bsonReader.GetCurrentBsonType();
- if (bsonType == BsonType.Null)
+ switch (bsonType)
{
- bsonReader.ReadNull();
- return null;
- }
- else
- {
- return new BsonObjectId((ObjectId)ObjectIdSerializer.Instance.Deserialize(bsonReader, typeof(ObjectId), options));
+ case BsonType.ObjectId:
+ return new BsonObjectId(bsonReader.ReadObjectId());
+ default:
+ var message = string.Format("Cannot deserialize BsonObjectId from BsonType {0}.", bsonType);
+ throw new FileFormatException(message);
}
}
@@ -93,13 +91,11 @@ public static BsonObjectIdSerializer Instance
{
if (value == null)
{
- bsonWriter.WriteNull();
- }
- else
- {
- var bsonObjectId = (BsonObjectId)value;
- ObjectIdSerializer.Instance.Serialize(bsonWriter, nominalType, bsonObjectId.Value, options);
+ throw new ArgumentNullException("value");
}
+
+ var objectId = ((BsonObjectId)value).Value;
+ bsonWriter.WriteObjectId(objectId);
}
}
}
View
26 MongoDB.Bson/Serialization/Serializers/BsonRegularExpressionSerializer.cs
@@ -15,11 +15,11 @@
using System;
using System.Collections.Generic;
+using System.IO;
using System.Linq;
using System.Text;
using MongoDB.Bson.IO;
-using MongoDB.Bson.Serialization.Options;
namespace MongoDB.Bson.Serialization.Serializers
{
@@ -36,7 +36,6 @@ public class BsonRegularExpressionSerializer : BsonBaseSerializer
/// Initializes a new instance of the BsonRegularExpressionSerializer class.
/// </summary>