megacolorboy

Abdush Shakoor's Weblog

Writings, experiments & ideas.

Using records for DTOs

If you're building an application or API using .NET Core in where you might have to integrate with any external services or third-party APIs, this is for you.

What are records?

It's a feature introduced since C# 9.0 that allows you to create simple and immutable data types. When representing DTOs (Data Transfer Objects), it comes in handy because the syntax in concise and it's primarily used to transfer data between layers of an application such as the Core and Presentation Layer.

Here's an example of a car using a regular class type:

public class Car
{
    public string Manufacturer { get; init; }
    public double Price { get; init; }
    public string Color { get; init; }
}

And here's a simplified version of that using record type:

public record Car(
    string Manufacturer,
    double Price,
    string Color
);

Making use of the record type to manage Data Transfer Objects makes use of clean coding practicies by writing concise yet maintainable code.

So, no need of using classes?

Well, it depends because records aren't meant to replace classes for all scenarios. It's still recommended to use regular classes for complex types with complex behavior and whereas, records can be used for simple data structures.

Hope you found this article useful!

Using Property Pattern Matching in C#

Alright, we've all been there especially when it comes to writing IF conditions with multiple checks in a single line like the example below:

if(employee != null && employee.Age > 20 && employee.Address.City == "Dubai")
{
    // Do something here...
}

As you can see, this condition is straight-forward but can sometimes hinder readability and doesn't really ensure type safety.

Here's where you can make use Property Pattern Matching.

What's Property Pattern Matching?

This type of pattern matching is used to match the defined expression if the conditions/nested conditions successfully matches the corresponding property or the field of the result and output of the result is not null. Here's an example of how it might be like:

if(employee is { Age: > 20 && Address.City == "Dubai" })
{
    // Do something here...
}

This pattern elevates your code's readability, ensures type safety and enable flexibility in terms of data manipulation.

Hope you found this tip useful!

Remove Control Flags

There are times when we write flags to control the flow of the program. I mean, it's good to use control flags (sometimes) but it's not necessary to be used in most cases. Like the one shown below:

public bool HandlePaymentRecords(List<PaymentRecord> paymentRecords)
{
    bool isSuccessful = true;

    foreach(var paymentRecord in paymentRecords)
    {
        if(!ProcessPaymentRecord(paymentRecord))
        {
            isSuccessful = false;
            break;
        }
    }

    return isSuccessful;
}

The name of method states it's purpose but it seems a tad bit complicated and might confuse some developers who get on-board with it.

Instead, you can make of use of a refactoring technique called Remove Control Flags and modify the method to look like this:

public bool HandlePaymentProcess(List<PaymentRecord> paymentRecords)
{
    foreach(var paymentRecord in paymentRecords)
    {
        if(!ProcessPaymentRecord(paymentRecord))
        {
            return false;
        }
    }

    return true;
}

The logic is the same but now the code is now simplified, less complex to read and much more maintainable.

Less code is good code.

Hope this helps you out!

Error loading V8 startup snapshot file in Visual Studio Code

Unusually, one fine afternoon, I was facing issues with opening my VSCode editor and I faced the followinge error when I tried code . on my project directory:

[0830/101630.031:FATAL:v8_initializer.cc(527)] Error loading V8 startup snapshot file

I didn't really understand what might have caused it but after reading this issue raised on GitHub, I realized that occurred due to a corrupted update while I was shutting down my PC (Good job, Windows! :facepalm:)

If you're are lucky enough, here's how you can get it back to work:

  1. Go C:\Users\XXX\AppData\Local\Programs\Microsoft VS Code directory
  2. If you spot a folder titled _, copy the contents and paste it in the VS Code directly
  3. Try starting your editor again

The following steps worked out for me and if it worked out for you, that's great! Else, you'll have to re-install your editor all over again, which means you might have to re-install your extensions and re-configure it again (if you haven't taken a backup of it).

Hope this helps you out!

Generating custom snippets using Visual Studio Code

I've always wanted to write about this feature and I believe this is one of the most productivity hacks you can do to speed your work and worry-less about writing boilerplate code.

For example, if I wanted to write a piece of code that fetches a list of books asynchronously using JavaScript, I would have to type it or maybe copy-paste that stub from another file or project and edit it accordingly. That's fine but when working on a large project or tight deadlines, it can be quite time-consuming if all you want is just a boilerplate code that's ready to begin with.

Here's how you can create your own snippet:

  1. Press Ctrl+Shift+P
  2. Type Configure User Snippets and hit Enter
  3. Select the language for which it should appear and hit Enter

Once done, a new tab will open up with simple instructions for you to get started with. The instructions are quite straight-forward and you can write something like this right below the note:

{
    // Place your snippets for javascript here. Each snippet is defined under a snippet name and has a prefix, body and 
    // description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. Possible variables are:
    // $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders. Placeholders with the 
    // same ids are connected.
    // Example:
    // "Print to console": {
    //  "prefix": "log",
    //  "body": [
    //      "console.log('$1');",
    //      "$2"
    //  ],
    //  "description": "Log output to console"
    // }
    "AJAX Get Method": {
        "prefix": "ajax-get",
        "body": [
            "$.ajax({",
            "\turl: '/',",
            "\tmethod: 'GET',",
            "\tdatatype: 'json',",
            "\tsuccess: (data) => {",
            "\t\tconsole.log(data);",
            "\t},",
            "\terror: (err) => {",
            "\t\tconsole.error(err);",
            "\t}",
            "});",
        ],
        "description": "A simple AJAX GET Method"
    }
}

Save the file and test if the snippet works fine by opening any file, in this case, open an empty .js file and type ajax-get and hit Tab at the end of the prefix. The generated snippet would look like this:

$.ajax({
    url: '/',
    method: 'GET',
    datatype: 'json',
    success: (data) => {
        console.log(data);
    },
    error: (err) => {
        console.error(err);
    }
});

Learn more about generating snippets by reading the documentation about it.

Hope this tip helps you out!

Using the null-coaleascing operator in C#

Null checks are the most underrated thing and despite years of experience, we still forget to write a null check in our code.

When it comes to writing null checks, this is what one would most write:

string foo = null;
string bar;
if(foo != null)
{
    bar = foo;
}
else
{
    bar = "Hello, friend!";
}
Console.WriteLine(bar) // Output: Hello, friend!

Yes, it does the job but it's a bit lengthy and not so readable. Let's see how the ?? operator i.e. the null-coalescing operator can help simplify your logic:

string foo = null;
string bar = foo ?? "Hello, friend!";
Console.WriteLine(bar) // Output: Hello, friend!

Now, you can bid goodbyes to writing verbose null checks and make your code more cleaner and readable.

Hope this tip helps you out!

Check if a string is a UNIQUEIDENTIFIER in SQL Server

Recently, when I was performing a data migration that contained previous payment history, I came across a table that had a column named PaymentId which is supposed to have a UUID styled format but funnily enough, it was kind of confusing because some of them had numbers in it.

Luckily, the ones that weren't in UUID format are not supposed to be migrated, so I decided to write a SELECT query and filter the records using the TRY_CONVERT function:

SELECT 
    * 
FROM 
    dbo.YourTable 
WHERE 
    TRY_CONVERT(UNIQUEIDENTIFIER, YourColumn) IS NOT NULL;

Yes, it's that simple. You don't need to write any complex regular expressions for such operations.

Hope you found this tip useful!

Filtering results by weekdays in SQL Server

Ever wanted to know how many people are actively posting something on a Monday? Or maybe during the weekends?

You can do that by using the DATEPART and DATENAME functions. Let me show you how they work.

Using DATEPART

The DATEPART function represents weekdays as integers from 1 (Sunday) to 7 (Saturday).

Let's say that you wanted to filter between Monday and Friday, you can achieve something like this:

SELECT * FROM dbo.YourTable WHERE DATEPART(WEEKDAY, YourDateColumn) BETWEEN 2 and 6;

One thing to note, in SQL Server, Sunday is the first day of the week. So, if you wanted to set the first day of the week, you can write the following statement before executing your query:

SET DATEFIRST 1;  -- Set Monday as the first day of the week
SELECT * FROM dbo.YourTable WHERE DATEPART(WEEKDAY, YourDateColumn) BETWEEN 1 and 5;

In the example above, you'll achieve the same results as the previous one.

Using DATENAME

The DATENAME function represents weekdays as a string from Monday to Sunday.

Let's replicate the previous example using this function:

SELECT * FROM dbo.YourTable WHERE DATENAME(WEEKDAY, YourDateColumn) IN ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday');

If you want to know more about filtering your records effectively using these methods, you can the read the documentation:

Hope you found this tip useful!