Skip to main content

Using Newtonsoft serializer in CosmosDB client

Problem

In some scenarios engineers might want to use a custom JSON serializer for documents stored in CosmosDB. 

Solution

In CosmosDBV3 .NET Core API, when creating an instance of CosmosClient one of optional setting in CosmosClientOptions is to specify an instance of a Serializer. This serializer must be JSON based and be of CosmosSerializer type. This means that if a custom serializer is needed this should inherit from CosmosSerializer abstract class and override its two methods for serializing and deserializing of an object. The challenge is that both methods from CosmosSerializer are stream based and therefore might be not as easy to implement as engineers used to assume - still not super complex. 
For demonstration purpose as or my custom serializer I'm going to use Netwonsoft.JSON library. Firstly a new type is needed and this must inherit from CosmosSerializer. 

using Microsoft.Azure.Cosmos;

using Newtonsoft.Json;
 
using System.IO;
using System.Text;
 
/// <summary>
/// Custom serializer for CosmosDB client.
/// </summary>
public class SerliarizationService : CosmosSerializer
{
    private readonly JsonSerializer serializer;
 
    public SerliarizationService()
    {
        this.serializer = new JsonSerializer
        {
            NullValueHandling = NullValueHandling.Ignore
        };
    }
 
    /// <summary>
    /// Logic for deserialization.
    /// </summary>
    public override T FromStream<T>(Stream stream)
    {
        return this.serializer.Deserialize<T>(new JsonTextReader(new StreamReader(stream)));
    }
 
    /// <summary>
    /// Serialization logic.
    /// </summary>
    public override Stream ToStream<T>(T input)
    {
        using var stringWriter = new StringWriter();
        using var jsonTextWriter = new JsonTextWriter(stringWriter);
        this.serializer.Serialize(jsonTextWriter, input, input.GetType());
 
        return new MemoryStream(Encoding.UTF8.GetBytes(stringWriter.ToString()));
    }
}
With a custom serialization in place, the only thing to change is to change settings when initializing a new instance of CosmosClient.

cosmosClient = new CosmosClient(
    this.dbConfig.EndpointUrl,
    this.dbConfig.AuthorizationKey,
    new CosmosClientOptions()
    {
        Serializer = new SerliarizationService(),
    });

Job done.
Thank you

/dz

Popular posts from this blog

Using Hortonworks Hive in .NET

A few months ago I decided to learn a big data. This sounds very complex and of course it is. All these strange names which actually tells nothing to person who is new in these area combined with different way of looking at data storage makes entire topic even more complex. However after reading N blogs and watching many, many tutorials today I finally had a chance to try to write some code. As in last week I managed to setup a Hortonworks distribution of Hadoop today I decided to connect to it from my .NET based application and this is what I will describe in this post. First things first I didn`t setup entire Hortonworks ecosystem from scratch - I`d love to but for now it`s far beyond my knowledge thus I decided to use a sandbox environment provided by Hortonworks. There are multiple different VMs available to download but in my case I`ve choose a Hyper-V. More about setting this environment up you can read here . Picture 1. Up and running sandbox environment. Now whe...

Creating common partial class with Entity Framework

When we use the Entity Framework (EF) in multilayer information systems sometimes we want to extend classes generated by EF by adding some common properties or functions. Such operation can`t be conduct on *.edmx data model so we need to make some improvement in our solution. Let`s begin... Lets assumed that in our soulution we have only three layer (three project): Client console application which has reference to the second layer  - ' ConsoleApplication ' project name Class library project with class interfaces only - ' Interfaces ' project name Class library class implementation and data model referenced to 'Interfaces' project - ' Classes ' project name. Picture 1. Solution structure. Now when we have all solution structure we can focus on data model. In the ' Classes ' project we create a new folder named ' Model ' and inside add new item of ADO.NET Entity Data Model named ' Learning.edmx ' - it may be empty ...

Full-Text Search with PDF in Microsoft SQL Server

Last week I get interesting task to develop. The task was to search input text in PDF file stored in database as FileStream. The task implementation took me some time so I decided to share it with other developers. Here we are going to use SQL Server 2008 R2 (x64 Developers Edition), external driver from Adobe, Full-Text Search technology and FileStream technology.Because this sems a little bit comlicated let`s make this topic clear and do it step by step. 1) Enable FileStream - this part is pretty easy, just check wheter You already have enabled filestream on Your SQL Server instance - if no simply enable it as in the picture below. Picture 1. Enable filestream in SQL Server instance. 2) Create SQL table to store files  - mainly ther will be PDF file stored but some others is also be allright. Out table DocumentFile will be created in dbo schema and contain one column primary key with default value as sequential GUID. Important this is out table contains FileSt...