It's not what you read, it's what you ignore

A long time ago, I watched an online presentation by Scott Hanselman (@shanselman) about productivity. One of the best I’ve seen. These days I found my handwritten notes about it. Today, I want to share my takeaways and the tools I’ve used since I watched it the first time.

Triage every inbox

Do triage the same way doctors do it. Set three goals for your day, week, and year.

Separate your tasks into four categories divided into two quadrants: important versus urgent.

  • If something is Urgent and Important, act on it immediately. Think of a server down.
  • If something is Important but Not Urgent, it’s your regular job. Work on it.
  • If something is Not Urgent and Not Important, delegate it. Ask somebody else to do it.
  • If something is Not Urgent and Not Important, drop it. Ignore it.

Don’t read email first thing in the morning

Create rules in your email. Separate your emails into folders. For example,

  • Inbox for regular emails
  • CC for emails where you’re CCed. These are FYI emails
  • Bosses for your managers, CTO and CEO
  • External for emails from customers and clients

Conserve your keystrokes. Imagine your number of keystrokes is limited. Write 3 or 5 sentence emails. Anything longer should be in a wiki, blog post, or documentation.

timer on a table
Photo by Marcelo Leal on Unsplash

Use Pomodoro technique

Work in 25-minute sessions of intense concentration between 5-minute breaks. After 4 or 5 work sessions, take a longer break for 15 minutes. This is the Pomodoro technique in a nutshell.

During your Pomodoros, keep track of your internal and external interruptions. For example, I keep my cell phone out of sight and in silence mode while working on something important.

Don’t set up a guilty system

Put on your desktop what you really are going to do. Don’t pile up books on your desktop.

When you feel overwhelmed, sync to paper. Write down what you have to do.

“If it’s not helping me to <put-your-own-goal-here>, if it’s not improving my life in some way, it’s mental clutter and it’s out”

Voilà! These are some of my takeaways. I learned from this presentation to keep my emails separated into folders and to consider my keystrokes limited. For example, I’ve written some of my posts to answer friends and coworkers. That way I can help more than one person while keeping my keystrokes limited.

For more content on productivity, check my Visual Studio setup for C# and some tools that saved me 100 hours. For other presentations, check Livable Code.

Happy coding!

Want to ace your next take-home coding exercises? Follow these 13 short tips

Take-home coding exercises aren’t rare in interviews.

I’ve found from 4-hour exercises to 2-day exercises to a Pull Request in an open-source project.

Even though, in my CV I have links to my GitHub profile (with some green squares, not just cricket sounds) and my personal blog (the one you’re reading), I’ve had to finish take-home exercises.

Yes, hiring is broken!

For my last job, I had to solve a take-home challenge when applying as a C#/.NET backend software engineer. It was a decent company and I wanted to play the hiring game. So I accepted.

After I joined I was assigned to review applicants’ solutions.

Here are 13 short tips to help you solve your next take-home interview exercise. These are the same guidelines I used to review other people’s take-home exercises.

Stick to standards

Follow good practices and stick to coding standards. Write clean code.

1. Write descriptive names. Don’t use Information or Info as name suffixes, like AccountInfo. Keep names consistent all over your code. If you used AddAccount in one place, don’t use AccountAdd anywhere else.

2. Use one single “spoken” language. Write variables, functions, classes, and all other names in the same language. Don’t mix English and your native language if your native language isn’t English. Always prefer the language you will be using at the new place.

3. Don’t keep commented-out code. And don’t have extra blank lines. Use linters and extensions to keep your code tidy.

4. Use third-party libraries to solve common problems. But don’t keep unused libraries or NuGet packages around.

5. Have clearly separated responsibilities. Use separate classes, maybe Services and Repositories or Commands and Queries. But stay away from Helper and Utility classes full of static methods. Often, they mean you have wrong abstractions.

6. Add unit or integration tests, at least for the main parts of your solution.

If you’re new to unit testing or want to learn more, don’t miss my Unit Testing 101 series where I cover everything from the basics of unit testing to mocking and best practices.

Framed wall art
Write code you would print and hang on a wall. Photo by Lefty Kasdaglis on Unsplash

Version Control your solution

Keep your solution under version control. Use Git.

7. Write small and incremental commits. Don’t just use a single commit with “Finished homework” as the message.

8. Write good commit messages. Don’t use “Uploading changes,” “more changes,” or anything along those lines.

9. Use GitHub, GitLab, or any hosting service, unless you have different instructions for your take-home exercise.

Write a good README file

Write a good README file for your solution. Don’t miss this one! Seriously!

10. Add installation instructions. Make it easy for reviewers to install and run your solution. Consider using Docker or deploying your solution to a free hosting provider.

11. Add instructions to run and test your solution. Maybe, some step-by-step instructions with screenshots or a Postman collection with the endpoints to hit. You get the idea!

12. Tell what third-party tools you used. Include what libraries, NuGet packages, or third-party APIs you used.

13. Document any major design choices. Did you choose any architectural patterns? Any storage layer? Tell why.

Voilà! These are my best tips to succeed at your next take-home interview challenge. Remember, it’s your time to shine. Write code as clean as possible and maintain consistency. Good luck!

If you want to see how I followed these tips on a real take-home coding exercise, check SignalChat on my GitHub account. It’s a simple browser-based chat application using ASP.NET Core and SignalR.

canro91/SignalChat - GitHub

Get ready for your next interview with these tips for remote interviews. And, to prepare for your technical interviews, check how to evaluate a postfix expression, how to solve the two-sum problem, and how to shift array elements. These are real questions I got in previous interviews.

Happy coding!

BugOfTheDay: There are pending requests working on this transaction

These days I got this exception message: “The transaction operation cannot be performed because there are pending requests working on this transaction.” This is how I fixed it after almost a whole day of Googling and debugging.

To fix the “pending requests” exception, make sure to properly await all asynchronous methods wrapped inside any database transaction.

Pipeline pattern and reverting reservations

I was working with the pipeline pattern to book online reservations.

The reservation process used two types of steps inside a pipeline: foreground and background steps.

The foreground steps ran to separate enough rooms for the reservation. And the background steps did everything else to fulfill the reservation but in background jobs.

If anything wrong happened while executing the foreground steps, the whole operation rollbacked. And there were no rooms set aside for the incoming reservation. To achieve this, every foreground step had a method to revert its own operation.

The code to revert the whole pipeline was wrapped inside a transaction. It looked something like this,

using (var transactionScope = _transactionManager.Create(IsolationLevel.Serializable))
{
    try
    {
        await pipeline.RevertAsync();

        transactionScope.Commit();
    }
    catch (Exception e)
    {
        transactionScope.Rollback();

        _logger.LogError(e, "Something horribly horribly wrong happened");

        throw;
    }
}

The Commit() method broke with the exception mentioned earlier. Arrrggg!

Broken display glass
No displays or electronic devices were damaged while debugging this issue. Photo by Julia Joppien on Unsplash

Always await async methods

After Googling for a while, I found a couple of StackOverflow answers that mention to await all asynchronous methods. But, I thought it was a silly mistake and I started to look for something else more complicated.

After checking for a while, trying to isolate the problem, following one of my debugging tips, something like this code got all my attention.

public async Task RevertAsync(ReservationContext context)
{
    var reservation = context.Reservation;
    if (reservation == null)
    {
        return;
    }

    var updatedByUserId = GetSystemUserAsync(context).Id;
    await _roomService.UnassignRooms(reservation, updatedByUserId);
}

private async Task<User> GetSystemUserAsync()
{
    var systemUser = await _userRepository.GetSystemUserAsync();
    return systemUser;
}

Did you notice any asynchronous methods not being awaited? No? I didn’t for a while. Neither did my reviewers.

But, there it was. Unnoticed for the code analyzer too. And, for all the passing tests.

Oh, dear! var updatedByUserId = GetSystemUserAsync(context).Id. This line was the root of the issue. It was meant to log the user Id who performed an operation, not the Id of the Task not being awaited.

Voilà! In case you have to face this exception, take a deep breath and carefully look for any async methods not being awaited inside your transactions.

If you want to read more content, check my debugging tips. To learn to write unit tests, start reading Unit Testing 101. A better failing test would’ve caught this issue.

To read about C# async/await keywords, check my C# Definitive Guide. It contains good resources to be a fluent developer in C#.

Happy bug fixing!

Monday Links: Workplaces, studying and communication

Another Monday Links. Five articles I found interesting in last month.

Don’t waste time on heroic death marches

“Successful companies, whether they’re programming houses, retailers, law firms, whatever, make their employees’ needs a priority.” Totally agree. No more comments! Read full article

How to study effectively

One of my favorite subjects: how to study. Don’t cram. Don’t reread the material. Don’t highlight. Instead, study in short sessions and recall the material. Easy! There are even more strategies. Read full article

Undervalued Software Engineering Skills: Writing Well

We, as developers, spend a lot of time writing prose, not only code. Commit messages, ticket and PR descriptions, README files. We should get better at it. To check my writings, I use the Hemingway app often. Read full article

women sitting on chairs
Once upon a time, there were no Zoom calls. Photo by Boston Public Library on Unsplash

15 signs you joined the wrong company as a developer

Number 12. and 13. are BIG red flags. Let’s pay attention to those. Recently, I read about “disagree with your feet.” It resonates with this article. When you don’t like something about your job and you can’t do anything about it, walk away. Read full article

No, we won’t have a video call for that

I don’t like those chat messages with only “Hi!” or “How are you?” when we both know that’s not the message. This article shows how to better communicate on remote teams. Embrace asynchronous communication. Prefer (in order) Issue tracker, Wiki, email, and chat. Stay away from video calls as much as possible. Don’t ping people on chat software. And other ideas. Read full article, Watch full presentation.

Voilà! This Monday Links ended up being about better workplaces. See you in a month or two in the next Monday Links! In the meantime, grab your own copy of my free eBook Unit Testing 101. Don’t miss the previous Monday Links on Farmers, Incidents and Holmes.

Happy reading!

TIL: Dictionary keys are converted to lowercase too on serialization

Today, I needed to pass a dictionary between two ASP.NET Core 6.0 API sites. To my surprise, on the receiving side, I got the dictionary with all its keys converted to lowercase instead of PascalCase. I couldn’t find any element on the dictionary, even though the keys had the same names on each API site. This is what I learned about serializing dictionary keys.

Serialization with Newtonsoft.Json

It turns out that the two API sites were using Newtonsoft.Json for serialization. Both of them used the CamelCasePropertyNamesContractResolver when adding Newtonsoft.Json.

Something like this,

using Newtonsoft.Json.Serialization;
using Newtonsoft.Json;

var builder = WebApplication.CreateBuilder(args);
builder.Services
    .AddControllers()
    .AddNewtonsoftJson(options =>
    // ^^^^^
    {
        options.SerializerSettings.NullValueHandling
            = NullValueHandling.Ignore;

        options.SerializerSettings.ContractResolver
            = new CamelCasePropertyNamesContractResolver();
            //    ^^^^^
            // This is what I mean
    });

var app = builder.Build();
app.MapControllers();
app.Run();

With CamelCasePropertyNamesContractResolver, Newtonsoft.Json writes property names in camelCase. But, Newtonsoft.Json treats dictionary keys like properties too.

That was the reason why I got my dictionary keys in lowercase. I used one-word names and Newtonsoft.Json made them camelCase.

To prove this, let’s create a simple controller that read and writes a dictionary. Let’s do this,

using Microsoft.AspNetCore.Mvc;

namespace LowerCaseDictionaryKeys.Controllers;

[ApiController]
[Route("[controller]")]
public class DictionaryController : ControllerBase
{
    [HttpPost]
    public MyViewModel Post(MyViewModel input)
    {
        return input;
        //     ^^^^^
        // Just return the same input
    }
}

public class MyViewModel
{
    public IDictionary<string, string> Dict { get; set; }
}

Now, let’s notice in the output from Postman how the request and the response differ. The keys have a different case. Arggg!

Postman request and response bodies
Postman request and response bodies

1. Configure Newtonsoft.Json naming strategy

To preserve the case of dictionary keys with Newtonsoft.Json, configure the ContractResolver setting with CamelCaseNamingStrategy class and set its ProcessDictionaryKeys property to false.

When registering Newtonsoft.Json, in the SerializerSettings option, let’s do:

using Newtonsoft.Json.Serialization;
using Newtonsoft.Json;

var builder = WebApplication.CreateBuilder(args);
builder.Services
    .AddControllers()
    .AddNewtonsoftJson(options =>
    // ^^^^^
    {
        options.SerializerSettings.NullValueHandling
            = NullValueHandling.Ignore;

        options.SerializerSettings.ContractResolver
            = new CamelCasePropertyNamesContractResolver
            {
                NamingStrategy = new CamelCaseNamingStrategy
                {
                    ProcessDictionaryKeys = false
                    // ^^^^^
                    // Do not change dictionary keys casing
                }
            };
    });

var app = builder.Build();
app.MapControllers();
app.Run();

For more details, see Newtonsoft.Json docs to Configure NamingStrategy dictionary serialization.

After changing the naming strategy, let’s see the response of our sample controller. That’s what I wanted!

Postman request and response after changing NamingStrategy
Postman request and response bodies

What about System.Text.Json?

To maintain case of dictionary keys with System.Text.Json, let’s set the DictionaryKeyPolicy property inside the JsonSerializerOptions to JsonNamingPolicy.CamelCase.

In our Program.cs class, let’s write,

using System.Text.Json;

var builder = WebApplication.CreateBuilder(args);
builder.Services
    .AddControllers()
    .AddJsonOptions(options =>
    // ^^^^^
    {
        options.JsonSerializerOptions
            .DictionaryKeyPolicy = JsonNamingPolicy.CamelCase;
            // ^^^^^
    });

var app = builder.Build();
app.MapControllers();
app.Run();

For more naming policies, see Microsft docs to customize property names and values with System.Text.Json.

2. Use a comparer with dictionaries

Another alternative is to use a dictionary with a comparer that ignores case of keys.

On the receiving API site, let’s add an empty constructor on the request view model to initialize the dictionary with a comparer to ignore cases.

In my case, I was passing a metadata dictionary between the two sites. I could use a StringComparer.OrdinalIgnoreCase to create a dictionary ignoring the case of keys.

This way, no matter the case of keys, I could find them when using the TryGetValue() method.

public class MyViewModel
{
    public MyViewModel()
    {
        Dict = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
        //                                    ^^^^^
    }

    public Dictionary<string, string> Dict { get; set; }
}

Voilà! That’s how we can configure the case of dictionary keys when serializing requests and how to read dictionaries with keys no matter the case of its keys.

If you want to read about ASP.NET Core, check how to add a caching layer and how to read your appsettings.json configuration file. To avoid KeyNotFoundException and other exceptions when working with dictionaries, check my idioms on dictionaries.

Happy C# time