IPAddressSerializer.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /* Copyright 2010-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.Net;
  17. using System.Net.Sockets;
  18. namespace MongoDB.Bson.Serialization.Serializers
  19. {
  20. /// <summary>
  21. /// Represents a serializer for IPAddresses.
  22. /// </summary>
  23. public class IPAddressSerializer : ClassSerializerBase<IPAddress>
  24. {
  25. // constructors
  26. /// <summary>
  27. /// Initializes a new instance of the <see cref="IPAddressSerializer"/> class.
  28. /// </summary>
  29. public IPAddressSerializer()
  30. {
  31. }
  32. // public methods
  33. /// <summary>
  34. /// Deserializes a value.
  35. /// </summary>
  36. /// <param name="context">The deserialization context.</param>
  37. /// <param name="args">The deserialization args.</param>
  38. /// <returns>A deserialized value.</returns>
  39. protected override IPAddress DeserializeValue(BsonDeserializationContext context, BsonDeserializationArgs args)
  40. {
  41. var bsonReader = context.Reader;
  42. EnsureBsonTypeEquals(bsonReader, BsonType.String);
  43. var stringValue = bsonReader.ReadString();
  44. IPAddress address;
  45. if (IPAddress.TryParse(stringValue, out address))
  46. {
  47. return address;
  48. }
  49. var message = string.Format("Invalid IPAddress value '{0}'.", stringValue);
  50. throw new FormatException(message);
  51. }
  52. /// <summary>
  53. /// Serializes a value.
  54. /// </summary>
  55. /// <param name="context">The serialization context.</param>
  56. /// <param name="args">The serialization args.</param>
  57. /// <param name="value">The object.</param>
  58. protected override void SerializeValue(BsonSerializationContext context, BsonSerializationArgs args, IPAddress value)
  59. {
  60. var bsonWriter = context.Writer;
  61. string stringValue;
  62. if (value.AddressFamily == AddressFamily.InterNetwork)
  63. {
  64. stringValue = value.ToString();
  65. }
  66. else
  67. {
  68. stringValue = string.Format("[{0}]", value);
  69. }
  70. bsonWriter.WriteString(stringValue);
  71. }
  72. }
  73. }