Tuesday, February 20, 2018

ASP.NET Core - IHttpContextAccessor

ASP.NET Core introduces the IHttpContextAccessor interface as a way to provide access to the HttpContext. Before you can use it, you have to register it at application startup inside the IServicesCollection. During a code review I noticed that it was registered like this:

This turns out to be wrong. The IHttpContextAccessor should be registered as a singleton. So the correct code is the following:

More information: https://www.strathweb.com/2016/12/accessing-httpcontext-outside-of-framework-components-in-asp-net-core/

Monday, February 19, 2018

JSON.NET–Resolve private setters

On one of my projects we are using event sourcing as our data persistence strategy. Based on the event stream I build projections using read models.

I prefer to keep my projected read model immutable but turns out that JSON.NET fails to deserialize the state. All properties retain their default values.

A solution is to create a custom contract resolver that uses reflection to set the property values:

Don't forget to apply this contract resolver using the JsonSerializerSettings:

Thursday, February 15, 2018

PostgreSQL–Generate an auto incrementing number on year basis

For an application we are building we had the following requirement:

A unique increasing number should be generated for every document on a year by year basis. So at the end of each year the document counter should be reset to 0 and start to increase again.

As we are using PostgreSQL as our database, I decided to implement this feature using sequences.

First thing I did was creating a function that generates a new sequence based on a specific name:

This allows me to create a new sequence dynamically at the beginning of each year.

Next thing I did was creating another function that will first invoke the f_create_seq function to see if a sequence already exists and then calls this sequence to get the next number in line.

I invoke this function from my application where I pass a year as the sequence name parameter:

Wednesday, February 14, 2018

Stacktrace demystifier

As the C# compiler gets smarter and smarter and more complex features like iterators, generics, async/await are added, our stack traces become more and more unreadible. This is because the .NET stack traces output the compiler transformed methods; rather than the source code methods, which make them slow to mentally parse and match back to the source code.

A library that can help you get more readible stacktraces is Ben.Demystifier.

Let’s try it:

  • Create a new console application. Set the C# target version to 7.1(Instructions here)
  • Include the Ben.Demystifier nuget package
  • Add the following code:
    • Note that we call the exception.Demystify() extension method to generate a better stacktrace.
  • Let’s now run the application first and compare our stacktraces:

The normal stacktrace(with a lot of compiler noise):

  at System.ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion()
   at System.Collections.Generic.List`1.Enumerator.MoveNextRare()
   at ConsoleApp1.Program.<Iterator>d__2.MoveNext() in c:\projects\test\ConsoleApp1\ConsoleApp1\Program.cs:line 35
   at System.Linq.Enumerable.Count[TSource](IEnumerable`1 source)
   at ConsoleApp1.Program.<AsyncCount>d__1.MoveNext() in c:\projects\test\ConsoleApp1\ConsoleApp1\Program.cs:line 28
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at ConsoleApp1.Program.<Main>d__0.MoveNext() in c:\projects\test\ConsoleApp1\ConsoleApp1\Program.cs:line 15

The demystified stacktrace:

System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
   at bool System.Collections.Generic.List<T>+Enumerator.MoveNextRare()
   at IEnumerable<string> ConsoleApp1.Program.Iterator(int startAt)+MoveNext() in c:\projects\test\ConsoleApp1\ConsoleApp1\Program.cs:line 35
   at int System.Linq.Enumerable.Count<TSource>(IEnumerable<TSource> source)
   at async Task ConsoleApp1.Program.AsyncCount() in c:\projects\test\ConsoleApp1\ConsoleApp1\Program.cs:line 28
    at async Task ConsoleApp1.Program.Main(string[] args) in c:\projects\test\ConsoleApp1\ConsoleApp1\Program.cs:line 15

Check out the documentation to see the full list of problems with your default stacktraces that this library solves.

Tuesday, February 13, 2018

Rearchitect a monolithic .NET application using microservices

Google goes “all-in” to win the hearth and mind of .NET developers to let them use the Google Cloud Platform. To support this effort they released a set of whitepapers to help you rearchitect your monolithic .NET application using microservices and modernize your authentication, database and caching building blocks.

Here are the whitepapers:

image image

All improvement steps are done on a typical .NET application. You can find the related code in this GitHub repository.

Monday, February 12, 2018

Failed to load resource: the server responded with a status of 400 (Bad Request (Request Header too long))

During development, my web debugging sessios suddenly started to fail with a 400 Bad Request error. I started looking around what I could have done wrong but I couldn’t find any mistake in my code(at least not one that could explain this error).


A search on the Internet brought some insights, the error is probably related to a corrupt website cookie. So I deleted all my cookies and indeed the problem disappeared.