Friday, 30 April 2021

How to use AWS XRAY in asp.netcore?

This blog is for those who already know about distributed app development and its debugging and tracing.

And here will share simple steps for adding Xray in the Dotnet core application.

  • Install NuGet package  AWSXRayRecorder.Handlers.AwsSdk
  • Modify Startup implementation 
    public Startup(IConfiguration configuration)
        AWSXRayRecorder.InitializeInstance(configuration: configuration);
        AWSSDKHandler.RegisterXRayForAllServices(); }
  • To trace incoming request, add the following in Configure method on top
  • To trace HTTP client add
                services.AddHttpClient<ICustomClient, CustomClient>(client =>
  • To add metadata annotation
    AWSXRayRecorder.Instance.AddAnnotation("request_id", "R001");
  • If you are using a serverless.template for stack formation, to auto-enable tracing add
    • "Tracing": "Active" in AWS::Serverless::Function > Properties

There are more you can play with x-ray and dotnetcore app, reference .

Thursday, 22 April 2021

How to create custom converters for JSON serialization in dotnetcore?

If you are developing core web API and somehow getting requirements to accept custom bool value from the request. Like instead of true, false, 0, and 1 it should accept "True", "0", "1", "Y", and others. You can do it easily by creating custom converters that are available in both System.Text.Json and NewtonSoft.

Sharing snippet by using which I achieved it. 

Created a simple BooleanConverter

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
namespace JsonHelpers
    public class BooleanConverter : JsonConverter<bool>
        public override bool ReadJson(JsonReader reader, Type objectType, [AllowNull] bool existingValue, bool hasExistingValue, Newtonsoft.Json.JsonSerializer serializer)
            string boolValue = reader.Value?.ToString().ToLower();
            if (boolValue.Equals("true") || boolValue.Equals("yes") || boolValue.Equals("y") || boolValue.Equals("1"))
                return true;
            if (boolValue.Equals("false") || boolValue.Equals("no") || boolValue.Equals("n") || boolValue.Equals("0"))
                return false;
            throw new Newtonsoft.Json.JsonException($"{reader.Path}:{boolValue}, Invalid Boolean.");
        public override void WriteJson(JsonWriter writer, [AllowNull] bool value, Newtonsoft.Json.JsonSerializer serializer)
            switch (value)
                case true:
                case false:

And in .netcore start.cs added 

services.AddControllers().AddNewtonsoftJson(options =>
    options.SerializerSettings.Converters.Add(new BooleanConverter());
    options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

And your Dto should deserialize properly even if you send "y" and "1".

If you are deserializing manually then you can do it like this
var obj = JsonConvert.DeserializeObject<MyDto>(jsonString , new BooleanConverter());

Sunday, 16 August 2020

Xunit Mocking methods setup with Action<> parameter

I did setup a callback method in setup with Action<> parameter as onSuccess and onFailure callback. After seamless implementation i was trying to setup moq for the same method. And i finished everything up by using following code snippet.

Method template:

void ValidateUserAccess(List<int> conpanyIds, int? userId = null, Action<List<int>> onSuccess = null, Action<List<int>> onFailure = null, bool allowPartialExecution = false);

Moq Setup:

 _mqUserService.Setup(m => m.ValidateUserAccess(
                .Callback((List<int> ids, int? userId , Action<List<int>> onSuccess , Action<List<int>> onFailure , bool isExecteall) =>
//Other stuff to validate

Monday, 22 June 2020 Core Performance testing using Bombardier

Before staring this blog, i would like to describe the basic of DotNet tool, it will not take more than minutes.

dotnet tools

To simplify .net core work by using cli on Machine or in Path we use dotnet tools.
  • dotnet-counters
  • dotnet-ef
  • dotnet-reportgenerator-globaltool
Basic commands:
  • dotnet tool install --global <PACKAGE_NAME>
  • dotnet tool list -g|--global
  • dotnet tool run <COMMAND NAME>
  • dotnet tool uninstall <PACKAGE_NAME> -g|--global
  • dotnet tool update <PACKAGE_NAME> -g|--global
Let's have a look on a tool and It's uses:


Is used to monitor and collect diagnostic info of a running process. More could be found here on Stefan Geiger blog and Official Microsoft site.
Installation: dotnet tool install --global dotnet-counters
Monitoring: dotnet counters monitor --process-id 17264 --providers Microsoft.AspNetCore.Hosting System.Runtime

Now its good to start performance testing part from main topic. As we already know how to check various counter matrices using dotnet-counters while we will be using Bombardier.

Bombardier, Is an open source tools to make flood of http1/http2 request with various options using cli. It is written in GO programming, thus we required GO executable to understand GO command.

go get -u

bombardier -c 125 -n 10000 http://localhost:51976/api_documentation/index/index.html

Must have a look on powerful Bombardier's command.

After successful execution we can find statistics like this

Friday, 27 March 2020

Azure Cosmos Db Implementation with Dotnetcore and SQL Api

Simple step by step implementation of Cosmos DB with SQL Api in Dotnet core application. Official explanation could be find here.

Go to Azure Portal, search cosmos and create a subscription in specific resource group  with default/custom setting. I am using:
a. Subscription: Free Trial
b. Resource group: FreeStorageDemo
c. API: Core SQL
d. Account Name: cosmossqlapi

After successful creation of storage, get Keys:
a. URI
Mainly we will be using a and b in our case.

Either we can create Database manually through portal, or can use programming language. Here I am creating a simple dotnet core web api which will automatically create database and its containers with partition. Codebase for Cosmos db implementation with dotnet core api is available here on GitHub.

I have added Nuget package "Microsoft.Azure.Cosmos"

After running the endpoint in demo app, we can verified that Collection has been created under database in Azure portal

 And also verified that collection contains items.

Further we could fetch data by using API.

We can use _etag for the data consistency by using AccessConditionType  in RequestOption.

Tuesday, 18 February 2020

DotnetCore GraphQL implementation in WebApi

GraphQL is a Modern API architecture that use some standard query to make HTTP request.
You can explore more about GrapQL on official website. In this post we will described how we can create GraplQL API in existing .net core API. So that we will have both Rest and GraphQL within same App.

In GraphQL, API consist implementation of

  • Schema : Contains definition of
    • Query : That is used to fetch data.
    • Mutation : That is used to manipulate data
  • Types : Define data model like DTO.

To implement all these we would require following packages, which you can download from Nuget:

    <PackageReference Include="GraphQL" Version="3.0.0-preview-1352" />
    <PackageReference Include="GraphQL.Server" Version="" />
    <PackageReference Include="GraphQL.Server.Core" Version="3.5.0-alpha0027" />
    <PackageReference Include="GraphQL.Server.Transports.AspNetCore" Version="3.5.0-alpha0027" />
    <PackageReference Include="GraphQL.Server.Ui.Playground" Version="3.5.0-alpha0027" />
    <PackageReference Include="Microsoft.AspNetCore.App" />
    <PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />

Notice we have added GraphQL.Server.Ui.Playground, which we will be using for documentation like swagger and others. There we can explore all queries, mutations and types. As well as we can play with these in editor.

So let's start exploring  a solution from GitHub  in which we have projects:
1. DotNetCoreGraphQl.Order.WebApi
2. DotNetCoreGraphQl.Order.ViewModels
3. DotNetCoreGraphQl.Order.Providers
4. DotNetCoreGraphQl.Order.Ql

After having implementation we can make query and mutation call to endpoint /graphql in exposed UI http://localhost:60132/ui/playground

  "query" {
    "orderDetails(orderId": "12)",
      "product" {

mutation {
  addToCart(cart: {
    "quantity": 1,
    "productId": 212,
    "remarks": "Its too good"
  }) {

Key Points:
1. Each ObjectGraphType must be register.
2. Use EnableMetrics = true/false to get extensions node in response.
3. Use app.UseGraphQL() to change default endpoint (/graphql)
4. Use app.UseGraphQLPlayground() to change UI playground url (/ui/playground)

Demo on GitHub

Monday, 13 January 2020

Text to ASCII Art Generator Nuget

Create ASCII art from text with various settings like set text and background text with printing speed in .net. You might found various online Text to ASCII Art Generator, but now can do it by yourself in .net. Just Import TextToAsciiArt.dll and write some snippet and done!

Install-Package TextToAsciiArt -Version 1.0.0

Limitation: Only A-Z and 0-9 accepted.

using System;
using TextToAsciiArt;
class Program
    static void Main(string[] args)
        IArtWriter writer = new ArtWriter();
        writer.WriteConsole("happy lohri 2020", null);
        var settings = new ArtSetting
            ConsoleSpeed = 100,
            IsBreakSpace = true,
            Text = "|",
            BgText = "_"
        writer.WriteConsole("happy lohri 2020", settings);
        var data = writer.WriteString("My name is Raj");


Running demo here.

  • Text to ASCII Art Generator
  • Text Art
  • CMD Fancy Text
  • Console Text Art
  • Console Art