PartiallyRawBsonDocumentSerializer.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /* Copyright 2015-present MongoDB Inc.
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the 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
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. using System;
  16. using System.Reflection;
  17. using MongoDB.Bson.IO;
  18. namespace MongoDB.Bson.Serialization.Serializers
  19. {
  20. /// <summary>
  21. /// Represents a serializer for a BsonDocument with some parts raw.
  22. /// </summary>
  23. public class PartiallyRawBsonDocumentSerializer : SerializerBase<BsonDocument>
  24. {
  25. // private fields
  26. private readonly string _name;
  27. private readonly IBsonSerializer _rawSerializer;
  28. // constructors
  29. /// <summary>
  30. /// Initializes a new instance of the <see cref="PartiallyRawBsonDocumentSerializer"/> class.
  31. /// </summary>
  32. /// <param name="name">The name.</param>
  33. /// <param name="rawSerializer">The raw serializer.</param>
  34. public PartiallyRawBsonDocumentSerializer(string name, IBsonSerializer rawSerializer)
  35. {
  36. if (name == null)
  37. {
  38. throw new ArgumentNullException("name");
  39. }
  40. if (rawSerializer == null)
  41. {
  42. throw new ArgumentNullException("rawSerializer");
  43. }
  44. if (!typeof(BsonValue).GetTypeInfo().IsAssignableFrom(rawSerializer.ValueType))
  45. {
  46. throw new ArgumentException("RawSerializer ValueType must be a BsonValue.", "rawSerializer");
  47. }
  48. _name = name;
  49. _rawSerializer = rawSerializer;
  50. }
  51. // public methods
  52. /// <inheritdoc/>
  53. public override BsonDocument Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
  54. {
  55. var document = new BsonDocument();
  56. var reader = context.Reader;
  57. reader.ReadStartDocument();
  58. while (reader.ReadBsonType() != 0)
  59. {
  60. var name = reader.ReadName();
  61. var serializer = ChooseSerializer(name);
  62. var value = (BsonValue)serializer.Deserialize(context);
  63. document[name] = value;
  64. }
  65. reader.ReadEndDocument();
  66. return document;
  67. }
  68. private IBsonSerializer ChooseSerializer(string name)
  69. {
  70. if (name == _name)
  71. {
  72. return _rawSerializer;
  73. }
  74. else
  75. {
  76. return BsonValueSerializer.Instance;
  77. }
  78. }
  79. }
  80. }