Transactions in Dapper

Isn’t it already described in Dapper docs? Sure it is. Why do I bother to write this? Am I just wtiting it for the sake of “posting”? No, I am not. Actually, I was trying to write the code by using Dapper’s docs. Unfortunately, I ran into a few bugs. I am using .NET 9, by the way and this is not even a blog post; it’s just a code snippet. I thought I should share it, may be someone else is facing the same problem as me.

[Read More]

Keyset Pagination In Entity Framework Core

Keyset Pagination In Entity Framework Core

First we need to know about the traditional offset based pagination and the problems it introduces.

Offset pagination

In the code below we are using the offset pagination.

[HttpGet("offset")]
public async Task<IActionResult> GetBooks(int limit=10, int page=1)
{
    var books = await _context.Books
        .AsNoTracking()
        .OrderBy(a => a.Id)
        .Skip(limit * (page - 1))
        .Take(limit)
        .ToListAsync();
    return Ok(books);
}

Which translates to the following sql:

SELECT
   [b].[Id],
   [b].[Author],
   [b].[Country],
   [b].[ImageLink],
   [b].[Language],
   [b].[Link],
   [b].[Pages],
   [b].[Price],
   [b].[Title],
   [b].[Year]
FROM [Book] AS [b]
ORDER BY [b].[Id]
OFFSET @__p_0 ROWS
FETCH NEXT @__p_1 ROWS ONLY

Note: In every pagination logic, ordering must be unique. In our case we are using Id which is unique.

[Read More]

Rest Api Designing Best Practices

Rest Api Designing Best Practices

There are some common practices one should take care of while designing REST APIs.

There is also a video version of this post.

1. Use descriptive names for resources

  • ❌ /api/getAllBooks
  • ❌ /api/retrieveBooks
  • ❌ /api/manageBooks
  • ❌ /api/process
  • ✅ /api/books

2. Use nouns not verbs

  • ❌ /api/mangage-books
  • ✅ /api/books

3. Use plural nouns

❌ Singular Nouns✅ Plural Nouns
/api/book/api/books
/api/movie/api/movies
/api/person/api/people
/api/customer/api/customers

4. Use hyphens (-) in url for better readabilty

  • ❌ /api/useraccounts
  • ✅ /api/user-accounts

5. Never use crud method names in url

HttpMethod❌❌❌✅✅✅
GET/api/books/GetAllBooks/api/books
GET/api/books/GetBookById/{id}/api/books/{id}
POST/api/books/CreateBook/api/books
PUT/api/books/UpdateBook/{id}/api/books/{id}
DELETE/api/books/DeleteBook/{id}/api/books/{id}

6. Use http method properly

HttpMethodEndpointDescription
GET/api/booksIndicates a get resources
GET/api/books/{id}Indicates a get resource with id
POST/api/booksIndicates creating a resource
PUT/api/books/{id}Indicates updating a resource
DELETE/api/books/{id}Indicates deleting a resource

7. Use Http StatusCodes Correctly

These are the most commonly used status codes.

[Read More]

Dotnet Service Lifetime : AddTransient(), AddScoped(), AddSingleton()

Dotnet Service Lifetime : AddTransient(), AddScoped(), AddSingleton()

Example Setup

I am using a MinimalApi application. Create a new one if you need.

dotnet new webapi -n DITest

Open it in a IDE or editor of your choice.

public interface IMyService
{
    Guid InstanceId { get; }
}

public class MyService : IMyService
{
    public Guid InstanceId { get; }

    public MyService()
    {
        InstanceId = Guid.NewGuid();
        // We are logging in the constructor, so that we get notified whenever the instance is created
        Console.WriteLine($"==> Service created with InstanceId: {InstanceId}");
    }
}

IMyService have a read-only property named InstanceId of type Guid, which is set from the constructor. We are logging inside the constructor, so that we can get notified whenever the new instance is created.

[Read More]

SingleAsync vs SingleOrDefaultAync vs FirstAsync vs FirstOrDefaultAsync vs FindAync

SingleAsync vs SingleOrDefaultAync vs FirstAsync vs FirstOrDefaultAsync vs FindAync

I don’t think there is any need of introduction. Let’s jump to the code section. We coders understand with code more. Let’s understand the concept then you don’t need to remember any definition.

This is the recordset against which I am running queries.

IdFirstNameLastName
1JohnDoe
2RavindraDevrani
3MohanSingh
20MaheshSoni
21JohnSnow

First and foremost let’s say we need a record with LastName=”Doe”.

[Read More]

Database Firsts Approach In EF Core

Database Firsts Approach In EF Core

I have used database first approach in the .NET Framework 4.X. But It is the first time I am trying to use Db First approach in the .NET Core (I am using .net 9). Microsoft refers it ‘Scaffolding (Reverse Engineering)’. Personally I prefer Dapper for DB First approach. May be you have an existing database and you want to use it with ENTITY FRAMEWORK, then this approach might be helpful. I am playing around it and documenting it and sharing that journey with you. Let’s see what it offers.

[Read More]

Creating and Installing Dotnet CLI Tool

In this tutorial we are going to learn:

  • How to create a cli tool?
  • How to create a nuget package?
  • How to install it in our machine.

CLI tools are very useful, they are very easy to use. We are already using it in our every day.

dotnet new console -o CliToolDemo

It is the example of dotnet cli tool, simple way to create a .net console application. You can also create your own cli tools. We are going to use a package created by Microsoft named System.CommandLine , which is a pre-released version as of I am writing this blog post. It is a pre-released version for so long, I wonder what are the plans about this package. You can also use a library named Cocona to create cli tools, which is pretty simple and widely popular. But I am going to stick with System.CommandLine . You should definitely checkout the cocona.

[Read More]

Securing The .NET 9 App: Signup, Login, JWT, Refresh Tokens, and Role Based Access with PostgreSQL

Securing The .NET 9 App: Signup, Login, JWT, Refresh Tokens, and Role Based Access with PostgreSQL

REST APIs are stateless, so server does not store any information about the client. So we can not authorize the rest application in a traditional way. How does a server knows if the user is authenticated user or not? In this situation the Json Web Token (JWT) saves the day.

JSON Web Tokens are an open, industry standard RFC 7519 method for representing claims securely between two parties. Source: jwt.io

[Read More]

Handle Exceptions Globally in .NET Core With IExceptionHandler And IProblemDetailService

Handle Exceptions Globally in .NET Core With IExceptionHandler And IProblemDetailService

Problem details is a standard way to communicate error details in HttpResponse, defined in rfc 7807. Standard ProblemDetails Properties:

  • Type: URI identifying problem type
  • Title: Short error description
  • Status: HTTP status code
  • Detail: Specific error explanation
  • Instance: URI identifying specific error occurrence

Problem details is automatically integrated with .net core APIs. When we return the BadRequest we generally get response with problem details.

// controller method
return BadRequest();

// response

{
 "type": "https://tools.ietf.org/html/rfc9110#section-15.5.1",
 "title": "Bad Request",
 "status": 400,
 "traceId": "00-2d4948694b0f223f7f5dff215b42481b-0288bb95d7604783-00"
}

The same thing happens when we return the NotFoundException.

[Read More]

Dotnet Core Api CRUD With Dapper and PostgreSql

Dotnet Core Api CRUD With Dapper and PostgreSql

💻Source Code: https://github.com/rd003/PostgressDapperDemo

Tools and technology used

  • VS Code (editor)
  • .Net 8
  • Postgres
  • Dapper

Let’s get started with creating the database first.

create database PersonDb;

Now, create a table within the database.

create table Person
(
 Id serial primary key,
 Name varchar(30) not null,
 Email varchar(30) not null
);

To create a new project you need to run these commands in a sequence.

> dotnet new sln -o PostgressDapperDemo

> cd PostgressDapperDemo

> dotnet sln add .\PostgressDapperDemo\

> code . #this command will open this project in the vs code

Nuget packages

Install the following nuget packages.

[Read More]