Refactoring towards better design: Extract/inline method part 1

Hello my dear developers

How do you feel today?

On this refactor I want to pay attention to a code smell called Feature envy, this smell is easy to spot because code outside a class uses data from a class for the application flow.

I have it in my sample when accession pieces position to find a given piece.

private bool TryFindPiece(Position position, out Piece piece)
{
    if (!_pieces.Any(p => p.Position.Equals(position)))
    {
        piece = default(Piece);
        return false;
    }
...
}

Therefore let’s use the extract method refactor to have a IsAt method on piece

private bool TryFindPiece(Position position, out Piece piece)
{
    if (!_pieces.Any(p => p.Position.Equals(position)))
    {
        piece = default(Piece);
        return false;
    }
...
}
private bool TryFindPiece(Position position, out Piece piece)
{
    if (!_pieces.Any(p => p.IsAt(position)))
    {
        piece = default(Piece);
        return false;
    }
...
}

This follow the principal only talk to your friends and on this case Position is a friend of Piece. So if Piece is friends with Board, talking to Position would be talking to a friend of a friend.

I hope that this was as helpful for me as it was for you.

Happy coding and remember… there is life beyond coding 😄

Refactoring towards better design: Introduce parameter object

Hello my dear developers

How do you feel today?

It was my understanding that changing code to improve it structure is called redeveloping. To refactor you need code coverage to ensure that your changes don’t modify the behaviour of your code.

On the other hand, I’ve grown fond of living always green, meaning to apply very small changes in your code so your tests keep green, and most importantly committing these smalls increments to your source control.

To try and go always green on my tests I use TPP (Transformation priority premise) but it felt somewhat a little outdated. After all, most IDEs have some sort of refactor pre-sets (on Visual studio for instance extract method is your first option).

I wandered how to learn these techniques and found Catalog of refactoring that lists all of them.

The samples are not super descriptive, in my opinion, plus it feels that every clean code related sample is java. Therefore, being a dot net developer, I’ll try to make my own dotnet 6 samples on my Github repo.

Starting with Introduce parameter object sample.

public void Move(string startColumn, int startRow, string endColumn, int endRow)
{            
    if(TryFindPiece(startColumn, startRow, out Piece piece))
    {                
        _pieces.Remove(piece);
        _pieces.Add(piece.Move(endColumn, endRow));                
    }
}
public void Move(Position start, Position end)
{
    if(TryFindPiece(start, out Piece piece))
    {                
        _pieces.Remove(piece);
        _pieces.Add(piece.Move(end));
    }
}

I hope that this was as helpful for me as it was for you.

Happy coding and remember… there is life beyond coding 😄

Using API key for authentication on Identity Server 4

Hello my dear developers!

How do you feel today?

There are challenges when dealing with IAM nowadays.

On one hand, you have a great solution for IAM management on your asp.net applications with IdentityServer.

On the other, a challenge arises when you need to authenticate applications that consume your API. For instance, authenticating kubecost at a highly available cluster on Kubernetes, would be desirable.

Sadly, IdentityServer 4 does not have API key authentication support, but at this article they found a very interesting work around for the former situation.

Detailed instructions on how to secure you asp.net application with API key authentication can be found here.

An advantage of using IdentityServer is that simply adding this nuget package to your asp.net core application you can easily implement it.

It goes without saying that out of the box you need a database and by default your connection is managed by EFCore. Of course this can be tweaked but this is beyond the scope of this article.

I hope that this was as helpful for me as it was for you.

Happy coding and remember…there is life beyond coding 😊

Mapping claims using OpenID Connect authentication

Hello my dear developers!

How do you feel today?

Recently I have been looking into IAM highly available systems. There are 2 side to this story.

First, your regular database has a hardware limit when scaling horizontally on a cluster.

One way to avoid this would be to have replica sets for a mySQL image with volume storing those changes. The former approach allows you to scale and still have a single source of truth. Check this article for further reading on the matter.

The problem comes when you have multiple clusters at many regions, how do you keep consistency among them? This is yet to be determined.

Meanwhile, if you use JWT tokens there is an excellent way to avoid cluttering them with a tone of claims. This article explains how to make a claim mandatory and how to map extra claims to your user on asp.net core.

I hope that this was as helpful for me as it was for you.

Happy coding and remember…there is life beyond coding 😊

Flattening json objects

Hello my dear developers!

How do you feel today?

Recently I had a need to flatten json structures to have them separated as claims.

Therefore, a json like the following:

{
    "areaAccess":{
        "firstSite":{
            "read":true,
            "write":false
        },
        "secondSite":"All"
    }
}

Would turn into a claim list like:

  • areaAcces:firstSite:read=True
  • areaAcces:firstSite:write=False
  • areaAcces:secondSite=”All”

A good starting point is https://newbedev.com/c-flattening-json-structure that explains a neat way to do that. Unfortunately, it is not so straight foreward boolean, since text json has JsonValueKind.True and JsonValueKind.False but it is a solid start.

I hope that this was as helpful for me as it was for you.

Happy coding and remember…there is life beyond coding 🙂

Token based authentication from HttpClient

Hello my dear developers!

How do you feel today?

Recently I’ve been having at token based authentication in more depth and found a few wringcles in the experience. First, for references please read these 2 articles that do a wanderfull job. They explain how to implement token based authentication in a very simple fashion:

Another more advance resource for managing security is : https://docs.microsoft.com/en-us/aspnet/core/security/authentication/social/additional-claims?view=aspnetcore-6.0

For my simple code reference go to : https://github.com/ambsenyestudi/aspnetcore_3_token_based_authentication

Ok, once you implement token based authentication your typical attempt is to add an authentication header to your httpClient default headers or to the very HttpRequestMessage.

For default header

var response = await client.PostAsync(settings.LoginEndpoint, content).ConfigureAwait(false);
var json = await response.Content.ReadAsStringAsync();
token = JsonSerializer.Deserialize<Token>(json, serializationOptions);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Bearer);

For HttpRequestMessage

var requestMessage = new HttpRequestMessage(HttpMethod.Post, settings.GameEndpoint);
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token.Bearer);
requestMessage.Content = content;
var response = await client.SendAsync(requestMessage).ConfigureAwait(false);

This is all very fine and good, the problem comes if the API that you are calling to has redirect activated.

On your API Startup.cs

...
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseSwagger();
        app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Ambseny.ChessEngine.Api v1"));
    }

    //this causes your redirection when calling to your http url 
    app.UseHttpsRedirection();
...
}

It took me a tone of research to find this https://github.com/dotnet/runtime/issues/26475

The former basically tells you that on a redirect you loose the authentication headers on you request. So, make sure to direct your calls to the https url or you will never get authenticaiton due to the redirect security fix.

I hope that this was as helpful for me as it was for you.

Happy coding and remember…there is life beyond coding🙂

Mounting volumes on Kubernetes

Hello my dear developers!

How do you feel today?

Lately I have been having problem when managing keys and configurations on Kubernetes. Since having volumes is a great way to do manage that I stated researching and stumbled across the following article.

Mounting volumes to kubernetes Pod container using helm chart – manikandank (tech.blog)

In my opinion the previous article isI very concise and informative

I hope you enjoyed the article as much as I did.

Happy coding and remember…there is life beyond coding🙂

Introduction to Kubernetes

Hello my dear developers!

How do you feel today?

I stumbled upon a very nice video that explianis the basics of kubernetes with docker for windows. It also explians how to take advantge of the kubernetes vs code extension to generete deployment (yaml) files.

I hope you enjoy this article as much as I did.

Happy coding and remember…there is life beyond coding

Asp.net core 5 setting up your httpClient

Hello my dear developers!

How do you feel today?

If you use a gateway on your projects, I’m guessing that you register it as .AddHttpClient. Another common practice is to configure an IOptions<yourSettingsClassType> and have DI container inject it in your gateway constructor.

That is a fine approach, but lately I had an httpClient that needed lots of headers every time you sent a request. So, the IOptions approach caused lots of repeated code in my gateway.

My first instinct to overcome that was to use custom http message handlers to add headers in my requests, but it felt a bit of an overkill. Headers like: Accept, apikey or your base url, never change throughout the life of your httpClient.

So, in my opinion it made sense setting those up when registering my gateway’s httpClient. Therefore, to have an identifiable set of never changing properties I defined an interface for each of them, so I can have a flexible configuration.. Here is the gist fo it.

I hope you enjoy this article as much as I did.

Happy coding and remember…there is life beyond coding

Verifying your memory cache through Moq

Hello my dear developers!

How do you feel today?

This week I wanted to verify a call to MemoryCache and got lost trying with Set method. Apparently, it’s an extension method so it cannot be spied with Moq, so I had to use whole different strategy.

You need to mock the create entry method and mock it and the CacheEntry as well.

Here is the gist of it

I hope you enjoy this article as much as I did.

Happy coding and remember…there is life beyond coding