You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Since version 7 approaches serialization in a very different way, we want to still provide snippet support for serializing Money instances.
Old code in src/NMoneys.Serialization
/// <summary>/// Converts a <see cref="Money"/> (or <see cref="Nullable{T}"/>) instance to and from JSON in the canonical way./// </summary>/// <remarks>The canonical way is the one implemented in NMoneys itself, with an <c>Amount</c>/// numeric property and a <c>Currency</c> object with a three-letter code <c>IsoCode"</c> property./// <para>/// Property casing must be configured apart from this serializer using, for instance, another set of/// <see cref="IConvention"/>/// </para>/// </remarks>/// <example>/// <code>{"Amount" : 123.4, "Currency" : {"IsoCode" : "XXX"}}</code>/// <code>{"amount" : 123.4, "currency" : {"isoCode" : "XXX"}}</code>/// </example>publicclassCanonicalMoneySerializer:MoneySerializer{publicCanonicalMoneySerializer():base(m =>new CanonicalMoneyReader(m),m =>new CanonicalMoneyWriter(m)){}}/// <summary>/// Converts a <see cref="Money"/> (or <see cref="Nullable{Money}"/>) instance to and from JSON in a default (standard) way./// </summary>/// <remarks>The default (standard) way is the one that a normal serializer would do for a money instance,/// with an <c>Amount</c> numeric property and a <c>Currency</c> code. The <c>Currency</c> property can be/// serialized either as a number (the default or using a <see cref="EnumRepresentationConvention"/> with <see cref="BsonType.Int32"/>) or as/// a string (using a <see cref="EnumRepresentationConvention"/> with <see cref="BsonType.String"/>)./// <para>/// Property casing must be configured apart from this serializer using, for instance, another set of/// <see cref="IConvention"/>/// </para>/// </remarks>/// <example>/// <code>{"Amount" : 123.4, "Currency" : "XXX"}</code>/// <code>{"amount" : 123.4, "currency" : 999}</code>/// </example>publicclassDefaultMoneySerializer:MoneySerializer{publicDefaultMoneySerializer():base(m =>new DefaultMoneyReader(m),m =>new DefaultMoneyWriter(m)){}}/// <summary>/// Base class for custom <see cref="Money"/> serializers/// </summary>publicabstractclassMoneySerializer:IBsonSerializer{privatereadonlyLazy<IMoneyReader>_reader;privatereadonlyLazy<IMoneyWriter>_writer;internalMoneySerializer(Func<BsonClassMap<Money>,IMoneyReader>reader,Func<BsonClassMap<Money>,IMoneyWriter>writer){_reader=newLazy<IMoneyReader>(()=>{varmap=(BsonClassMap<Money>)BsonClassMap.LookupClassMap(typeof(Money));return reader(map);});_writer=newLazy<IMoneyWriter>(()=>{varmap=(BsonClassMap<Money>)BsonClassMap.LookupClassMap(typeof(Money));return writer(map);});}/// <summary>/// Deserializes an object from a BsonReader./// </summary>/// <param name="bsonReader">The BsonReader.</param>/// <param name="nominalType">The nominal type of the object.</param>/// <param name="options">The serialization options.</param>/// <returns>An object.</returns>publicobjectDeserialize(BsonReaderbsonReader,TypenominalType,IBsonSerializationOptionsoptions){Moneymoney= _reader.Value.ReadFrom(bsonReader);returnmoney;}/// <summary>/// Deserializes an object from a BsonReader./// </summary>/// <param name="bsonReader">The BsonReader.</param>/// <param name="nominalType">The nominal type of the object.</param>/// <param name="actualType">The actual type of the object.</param>/// <param name="options">The serialization options.</param>/// <returns>An object.</returns>publicobjectDeserialize(BsonReaderbsonReader,TypenominalType,TypeactualType,IBsonSerializationOptionsoptions){return Deserialize(bsonReader, nominalType, options);}/// <summary>/// Gets the default serialization options for this serializer./// </summary>/// <returns>/// The default serialization options for this serializer./// </returns>public IBsonSerializationOptions GetDefaultSerializationOptions(){returnnew DocumentSerializationOptions();}/// <summary>/// Serializes an object to a BsonWriter./// </summary>/// <param name="bsonWriter">The BsonWriter.</param>/// <param name="nominalType">The nominal type.</param>/// <param name="value">The object.</param>/// <param name="options">The serialization options.</param>publicvoidSerialize(BsonWriterbsonWriter,TypenominalType,objectvalue,IBsonSerializationOptionsoptions){varmoney=(Money)value;
_writer.Value.WriteTo(money, bsonWriter);}}internalstaticclassPropertyNameCapitalizer{publicstaticstringCapitalizeAs(thisstringpascalCasedPropertyName,BsonMemberMapsampleMap){varsb=new StringBuilder(pascalCasedPropertyName, pascalCasedPropertyName.Length);if(char.IsLower(sampleMap.ElementName[0])){
sb[0]=char.ToLowerInvariant(sb[0]);}return sb.ToString();}}internalinterfaceIMoneyWriter{voidWriteTo(Moneyinstance,BsonWriterwriter);}internalabstractclassMoneyWriter:IMoneyWriter{publicvoidWriteTo(Moneyinstance,BsonWriterwriter){
writer.WriteStartDocument();
writeAmount(instance, writer);
writeCurrency(instance, writer);
writer.WriteEndDocument();}protectedabstractvoidwriteAmount(Moneyinstance,BsonWriterwriter);protectedabstractvoidwriteCurrency(Moneyinstance,BsonWriterwriter);}internalclassCanonicalMoneyWriter:MoneyWriter{privatereadonlyBsonClassMap<Money>_map;publicCanonicalMoneyWriter(BsonClassMap<Money>map){_map=map;}protectedoverridevoidwriteAmount(Moneyinstance,BsonWriterwriter){BsonMemberMapamount= _map.GetMemberMap(m => m.Amount);
writer.WriteDouble(amount.ElementName, Convert.ToDouble(instance.Amount));}protectedoverridevoidwriteCurrency(Moneyinstance,BsonWriterwriter){BsonMemberMapcurrency= _map.GetMemberMap(m => m.CurrencyCode);
writer.WriteName("Currency".CapitalizeAs(currency));
writer.WriteStartDocument();
writer.WriteString("IsoCode".CapitalizeAs(currency), instance.CurrencyCode.AlphabeticCode());
writer.WriteEndDocument();}}internalclassDefaultMoneyWriter:MoneyWriter{privatereadonlyBsonClassMap<Money>_map;publicDefaultMoneyWriter(BsonClassMap<Money>map){_map=map;}protectedoverridevoidwriteAmount(Moneyinstance,BsonWriterwriter){BsonMemberMapamount= _map.GetMemberMap(m => m.Amount);
writer.WriteDouble(amount.ElementName, Convert.ToDouble(instance.Amount));}protectedoverridevoidwriteCurrency(Moneyinstance,BsonWriterwriter){BsonMemberMapcurrency= _map.GetMemberMap(m => m.CurrencyCode);
writer.WriteName("Currency".CapitalizeAs(currency));
currency.GetSerializer(typeof(CurrencyIsoCode)).Serialize(writer,typeof(CurrencyIsoCode), instance.CurrencyCode, currency.SerializationOptions);}}
#region serializers
/// <summary>/// Converts a <see cref="Money"/> (or <see cref="Nullable{Money}"/>) instance to and from JSON in a default (standard) way./// </summary>/// <remarks>The default (standard) way is the one that a normal serializer would do for a money instance,/// with an <c>Amount</c> numeric property and a <c>Currency</c> code. The <c>Currency</c> property can be/// serialized either as a number (the default or using a <see cref="EnumRepresentationConvention"/> with <see cref="BsonType.Int32"/>) or as/// a string (using a <see cref="EnumRepresentationConvention"/> with <see cref="BsonType.String"/>)./// <para>/// Property casing must be configured apart from this serializer using, for instance, another set of/// <see cref="IConvention"/>/// </para>/// </remarks>/// <example>/// <code>{"Amount" : 123.4, "Currency" : "XXX"}</code>/// <code>{"amount" : 123.4, "currency" : 999}</code>/// </example>publicclassDefaultMoneySerializer:MoneySerializer{publicDefaultMoneySerializer():base(m =>new DefaultMoneyReader(m),m =>new DefaultMoneyWriter(m)){}}/// <summary>/// Converts a <see cref="Money"/> (or <see cref="Nullable{T}"/>) instance to and from JSON in the canonical way./// </summary>/// <remarks>The canonical way is the one implemented in NMoneys itself, with an <c>Amount</c>/// numeric property and a <c>Currency</c> object with a three-letter code <c>IsoCode"</c> property./// <para>/// Property casing must be configured apart from this serializer using, for instance, another set of/// <see cref="IConvention"/>/// </para>/// </remarks>/// <example>/// <code>{"Amount" : 123.4, "Currency" : {"IsoCode" : "XXX"}}</code>/// <code>{"amount" : 123.4, "currency" : {"isoCode" : "XXX"}}</code>/// </example>publicclassCanonicalMoneySerializer:MoneySerializer{publicCanonicalMoneySerializer():base(m =>new CanonicalMoneyReader(m),m =>new CanonicalMoneyWriter(m)){}}publicabstractclassMoneySerializer:SerializerBase<Money>{privatereadonlyLazy<IMoneyReader>_reader;privatereadonlyLazy<IMoneyWriter>_writer;internalMoneySerializer(Func<BsonClassMap<Money>,IMoneyReader>reader,Func<BsonClassMap<Money>,IMoneyWriter>writer){_reader=newLazy<IMoneyReader>(()=>{varmap=(BsonClassMap<Money>)BsonClassMap.LookupClassMap(typeof(Money));return reader(map);});_writer=newLazy<IMoneyWriter>(()=>{varmap=(BsonClassMap<Money>)BsonClassMap.LookupClassMap(typeof(Money));return writer(map);});}/// <summary>/// Deserializes a value./// </summary>/// <param name="context">The deserialization context.</param>/// <param name="args">The deserialization args.</param>/// <returns>/// A deserialized value./// </returns>publicoverride Money Deserialize(BsonDeserializationContextcontext,BsonDeserializationArgsargs){return _reader.Value.ReadFrom(context, args);}/// <summary>/// Serializes a value./// </summary>/// <param name="context">The serialization context.</param>/// <param name="args">The serialization args.</param>/// <param name="value">The value.</param>publicoverridevoidSerialize(BsonSerializationContextcontext,BsonSerializationArgsargs,Moneyvalue){
_writer.Value.Write(value, context, args);}}
#endregion
internalstaticclassPropertyNameCapitalizer{publicstaticstringCapitalizeAs(thisstringpascalCasedPropertyName,BsonMemberMapsampleMap){varsb=new StringBuilder(pascalCasedPropertyName, pascalCasedPropertyName.Length);if(char.IsLower(sampleMap.ElementName[0])){
sb[0]=char.ToLowerInvariant(sb[0]);}return sb.ToString();}}
#region support for reading
internalinterfaceIMoneyReader{
Money ReadFrom(BsonDeserializationContextcontext,BsonDeserializationArgsargs);}internalabstractclassMoneyReader:IMoneyReader{protectedreadonlyBsonClassMap<Money>_map;protectedMoneyReader(BsonClassMap<Money>map){_map=map;}public Money ReadFrom(BsonDeserializationContextcontext,BsonDeserializationArgsargs){
context.Reader.ReadStartDocument();decimalamount= readAmount(context.Reader);CurrencyIsoCodecurrencyCode= readCurrency(context, args);
context.Reader.ReadEndDocument();returnnew Money(amount, currencyCode);}protectedvirtualdecimalreadAmount(IBsonReaderreader){BsonMemberMapamountMap= _map.GetMemberMap(m => m.Amount);
reader.ReadName(amountMap.ElementName);decimalamount;// support old numeric representationsBsonTypetype= reader.GetCurrentBsonType();switch(type){case BsonType.Double:{doubleamountRead= reader.ReadDouble();amount= Convert.ToDecimal(amountRead);break;}case BsonType.Decimal128:{Decimal128amountRead= reader.ReadDecimal128();amount= Decimal128.ToDecimal(amountRead);break;}case BsonType.String:{stringamountRead= reader.ReadString();amount=decimal.Parse(amountRead, CultureInfo.InvariantCulture);break;}default:varmessage=$"Cannot convert a {type} to a Decimal.";thrownew NotSupportedException(message);}returnamount;}protectedabstract CurrencyIsoCode readCurrency(BsonDeserializationContextcontext,BsonDeserializationArgsargs);}internalclassDefaultMoneyReader:MoneyReader{publicDefaultMoneyReader(BsonClassMap<Money>map):base(map){}protectedoverride CurrencyIsoCode readCurrency(BsonDeserializationContextcontext,BsonDeserializationArgsargs){varcurrencyMap= _map.GetMemberMap(m => m.CurrencyCode);
context.Reader.ReadName("Currency".CapitalizeAs(currencyMap));varcurrencyCode=(CurrencyIsoCode)currencyMap.GetSerializer().Deserialize(context, args);returncurrencyCode;}}internalclassCanonicalMoneyReader:MoneyReader{publicCanonicalMoneyReader(BsonClassMap<Money>map):base(map){}protectedoverride CurrencyIsoCode readCurrency(BsonDeserializationContextcontext,BsonDeserializationArgsargs){
context.Reader.ReadStartDocument();BsonMemberMapcurrencyMap= _map.GetMemberMap(m => m.CurrencyCode);stringcurrency= context.Reader.ReadString("IsoCode".CapitalizeAs(currencyMap));
context.Reader.ReadEndDocument();CurrencyIsoCodecurrencyCode= Currency.Code.Parse(currency);returncurrencyCode;}}
#endregion
#region support for writing
internalinterfaceIMoneyWriter{voidWrite(Moneyvalue,BsonSerializationContextcontext,BsonSerializationArgsargs);}internalabstractclassMoneyWriter:IMoneyWriter{protectedreadonlyBsonClassMap<Money>_map;protectedMoneyWriter(BsonClassMap<Money>map){_map=map;}publicvoidWrite(Moneyvalue,BsonSerializationContextcontext,BsonSerializationArgsargs){
context.Writer.WriteStartDocument();
writeAmount(value, context.Writer);
writeCurrency(value, context, args);
context.Writer.WriteEndDocument();}protectedvirtualvoidwriteAmount(Moneyvalue,IBsonWriterwriter){BsonMemberMapamountMap= _map.GetMemberMap(m => m.Amount);
writer.WriteDecimal128(amountMap.ElementName,new Decimal128(value.Amount));}protectedabstractvoidwriteCurrency(Moneyvalue,BsonSerializationContextcontext,BsonSerializationArgsargs);}internalclassCanonicalMoneyWriter:MoneyWriter{publicCanonicalMoneyWriter(BsonClassMap<Money>map):base(map){}protectedoverridevoidwriteCurrency(Moneyvalue,BsonSerializationContextcontext,BsonSerializationArgsargs){BsonMemberMapcurrencyMap= _map.GetMemberMap(m => m.CurrencyCode);
context.Writer.WriteName("Currency".CapitalizeAs(currencyMap));
context.Writer.WriteStartDocument();
context.Writer.WriteString("IsoCode".CapitalizeAs(currencyMap), value.CurrencyCode.AlphabeticCode());
context.Writer.WriteEndDocument();}}internalclassDefaultMoneyWriter:MoneyWriter{publicDefaultMoneyWriter(BsonClassMap<Money>map):base(map){}protectedoverridevoidwriteCurrency(Moneyvalue,BsonSerializationContextcontext,BsonSerializationArgsargs){BsonMemberMapcurrencyMap= _map.GetMemberMap(m => m.CurrencyCode);
context.Writer.WriteName("Currency".CapitalizeAs(currencyMap));
currencyMap.GetSerializer().Serialize(context, args, value.CurrencyCode);}}
#endregion
Old code in src/NMoneys.Serialization.Mongo_DB.Tests
Since version 7 approaches serialization in a very different way, we want to still provide snippet support for serializing
Money
instances.Old code in src/NMoneys.Serialization
Old code in src/NMoneys.Serialization.Tests
Old code in src/NMoneys.Serialization.Mongo_DB
Old code in src/NMoneys.Serialization.Mongo_DB.Tests
The text was updated successfully, but these errors were encountered: