[CSHARP-2333] Custom Serializer returned value not being respected Created: 18/Jul/18  Updated: 20/Jan/20  Resolved: 20/Jan/20

Status: Closed
Project: C# Driver
Component/s: Serialization
Affects Version/s: 2.7.0
Fix Version/s: None

Type: Bug Priority: Minor - P4
Reporter: Magnus Assignee: Robert Stam
Resolution: Done Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Cosmos Db



 Description   

 

The string returned by my custom serializer, which is overriding how datetime strings are formatted is "2018-07-18T14:35:27.7108283+02:00". However in my database the stored value is "2018-07-18T12:35:27.7108283+00:00".

My code:

BsonSerializer.RegisterSerializer(new DateTimeOffsetSerializer(BsonType.Document));   
 
public class MyDateTimeOffsetSerializer : StructSerializerBase<DateTimeOffset>
    {
        public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args,
            DateTimeOffset value)
        {
            IBsonWriter writer = context.Writer;
            writer.WriteString(ToString(value));
        }        
public static string ToString(DateTimeOffset value)
        {
            var x = value.ToString("O");
            return x; // returns string like "2018-07-18T14:35:27.7108283+02:00"
        }        
    }

The serializer is registered right before I Insert the document. What is happening to the value after I've serialized it and how can I change it?

 



 Comments   
Comment by Robert Stam [ 02/Oct/18 ]

I tried your sample code and set a breakpoint to verify that the Serialize method in your custom serializer is in fact being called.

I used the following class to test:

public class C
{
    public int Id { get; set; }
    public DateTimeOffset D { get; set; }
}

And the following test program:

public static void Main(string[] args)
{
    BsonSerializer.RegisterSerializer(new MyDateTimeOffsetSerializer());
 
    var client = new MongoClient();
    var database = client.GetDatabase("test");
    database.DropCollection("test");
    var collection = database.GetCollection<C>("test");
 
    var document = new C { Id = 1, D = DateTimeOffset.Now };
    collection.InsertOne(document);          
}

The document inserted into the database looks just like you would expect:

> db.test.find()
{ "_id" : 1, "D" : "2018-10-02T09:37:12.4030520-04:00" }
>

So it looks like the driver is doing what we would expect. Are you doing something different than I am?

Comment by Magnus [ 18/Jul/18 ]

Correction; the code for registering the serializer is

BsonSerializer.RegisterSerializer(new MyDateTimeOffsetSerializer());

Generated at Wed Feb 07 21:42:16 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.