- In dotnet, a
Middleware
is a piece of code that runs in the request pipeline. - Middlewares are put together in a sequence, and their order matters.
- When a request is made, it goes through each of the middleware.
- Response flow back in reverse order through the middleware.
- Each middleware has capability to modify the request or short circuits the pipeline.
- Each middleware can change the response before it’s sent to the client.
Jwt Authention and role base authorization in Dotnet Core
Create a new web api project
Run these commands in a sequence to create a new project.
dotnet new sln -o JwtDotnet9
cd JwtDotnet9
dotnet sln add JwtDotnet9/JwtDotnet9.csproj
Open the project in vs code.
code .
=> Source Code
=> Securing The .NET 9 App: Signup, Login, JWT, Refresh Tokens, and Role Based Access with PostgreSQL
Install the required nuget packages
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
Jwt configuration in appsettings
Open appsettings.json
and add these lines
C#: Byte and Its Use Cases
byte
is a value type in c#byte
is an unsigned integer which stores value from 0 to 255, which means it can not store negetive numbers.- Size of
byte
is 8-bit (1 byte) - CTS equivalent of byte is
System.Byte
- It’s default value is 0
- It is great for memory optimization when dealing with small numbers.
Examples:
byte a = 10;
Console.WriteLine(a);
Use cases
- Working with ASCII value
byte asciiValue = (byte)'R'; // 82
byte asciiValue2 = (byte)'r'; // 114
- Encoding text into bytes
using System.Text;
string message = "Ravindra";
byte[] encoded = Encoding.UTF8.GetBytes(message);
Console.WriteLine($"{string.Join(",",encoded)}");
// op: 82,97,118,105,110,100,114,97
Note: Each character is encoded using UTF-8. For standard letters, the byte values match their ASCII codes.. (R: 82, a:97, v:118 …)
[Read More]IEnumerable Vs IQueryable In C#
There has been a discussion around town about the difference between an IEnumerable
and an IQueryable
, especially in c# interviews. I won’t be diving into the fact that IEnumerable
is part of the System.Collections
namespace and IQueryable
belongs to System.Linq
namespace (or did I???). Rather, I’ll focus on the practical usage of both—how they work, and when to use each.
IQueryable
public IActionResult GetPeople()
{
// It will retrieve 2 records from database
IQueryable<Person> people = _context.People.Take(2);
// Note: At the above line, no data will be retrieved from the database
return Ok(people); // Data will be retrieved here
}
Corresponding sql
Note that, I am using Sqlite
, the above code is translated to this query:
Bulk insert in dapper with table valued parameter
There might be instances when you want to insert bulk data. For an instance, you want to create an order, where you need to add multiple items. Let’s see how can we insert bulk data in c# using dapper.
Note: It is only good for adding bunch of rows. But if you are looking for adding hundreds of rows then better to use other approaches. There are many, if you look out.
[Read More]EF Core under the hood: Count() vs Any()
Let’s say you want to execute a code block when Book
table is not empty. In Entity Framework Core, we can achieve this in two ways (there might be others but I am unaware of them):
Option 1:
if(context.Books.Count()>0)
{
// do something
}
Option 2:
if (context.Books.Any())
{
// do something
}
Note 📢: I am testing these queries against a table containing 1 million rows.
[Read More]Linux Basic Commands
- Contents of a file:
ls
- Content list with long format:
ls -l
orls -l -h
human readable or concat the bothls -lh
. - Change directory:
cd DirectoryName
- Move to the upper directory:
cd ..
- Switch to previous directory :
cd -
- Change to home directory:
cd ~
- Go to full path:
cd /Home/Documents/Pitctures/MyPictures
- Tilde (~) for home directory :
MyPc:~/Documents$ cd ~/Videos
- Clear screen:
clear
- Show different drives in the computer (List block devices):
lsblk
- Opening a file in the text editor :
# open in nano
nano filename
#open in xed editor
xed filename
- Root directory:
cd /
- Press
Tab
to autocomlete. - Create a directory :
mkdir blah
- Remove a directory :
rmdir blah
- Creating a blank file :
touch something.txt
14.1. Creating multiple files at once:touch f1.txt f2.txt f3.txt f4.md f5.md
- Printing something in terminal :
echo hello
- Create a file with text:
echo "blah blah" > blah.txt
- Show contents of a file:
cat blah.txt
- Copy file :
cp /source/filename.ext destination/filename.ext
# note: I am currently in the `Desktop` directory
# copy `blah.txt` from `Desktop` to `Documents` directory
cp blah.txt ~/Documents/blah2.txt
# copy `blah.txt` from `Desktop` to `Documents` directory with changed filename
cp blah.txt ~/Documents/blah2.txt
# it will copy `blah.txt from `Desktop` to `Documents` directory with changed file name `blah2.txt`
Copy all files (. allfiles.allextensions):
[Read More]cp *.* ~/Documents
How to Install DotNet SDK In Ubuntu Based Distros?
My Distro
I am using linux mint 22.1
which is based on Ubuntu 24.04
.
Straightforeward command
sudo apt-get update
sudo apt-get install -y dotnet-sdk-9.0
But…
I have tried to run this command sudo apt-get install -y dotnet-sdk-9.0
but unfortunately I got no success. I have found that, this command works only with Ubuntu 24.10
. For Ubuntu 24.04
I need to use different approach.
Uninstall prior version if exists
sudo apt-get remove dotnet-sdk-8.0
Now, run these commands in a sequence:
[Read More]Dapper: Output Parameter
Stored procedure
CREATE OR ALTER PROCEDURE [dbo].[CreateTrackEntry]
@EntryDate DATE,
@SleptAt DATETIME2,
@WokeUpAt DATETIME2,
@NapInMinutes SMALLINT,
@TotalWorkInMinutes SMALLINT,
@Remarks NVARCHAR(1000) = NULL,
@TrackEntryId INT OUTPUT
AS
BEGIN
-- code removed for brevity
END
We have a stored procedure that returns TrackEntryId
as an output parameter. Let’s see how can we execute it from the dapper?
using IDbConnection connection = new SqlConnection(_connectionString);
var parameters = new DynamicParameters(trackEntryToCreate);
// Input params
parameters.Add("@EntryDate", trackEntryToCreate.EntryDate);
parameters.Add("@SleptAt", trackEntryToCreate.SleptAt);
parameters.Add("@WokeUpAt", trackEntryToCreate.WokeUpAt);
parameters.Add("@NapInMinutes", trackEntryToCreate.NapInMinutes);
parameters.Add("@TotalWorkInMinutes", trackEntryToCreate.TotalWorkInMinutes);
parameters.Add("@Remarks", trackEntryToCreate.Remarks);
// output params
parameters.Add("@TrackEntryId", dbType: DbType.Int32, direction: ParameterDirection.Output);
await connection.ExecuteAsync("CreateTrackEntry", parameters,commandType:CommandType.StoredProcedure);
int trackEntryId = parameters.Get<int>("@TrackEntryId");
Configuring dotnet core apps for OpenApi with SwaggerUi or Scalar
SwaggerUI
, which was previously bundled with .NET Core APIs, has been dropped in .NET 9. However, .NET Core Web APIs still support generating OpenAPI
documents. .NET Core apps have built-in support for generating information about endpoints and it uses Microsoft.AspNetCore.OpenApi
package for that. To configure interactive UIs for these OpenAPI documents, we have several options. We are going to explore these two:
- Swashbuckle SwaggerUI
- Scalar
Create a new project, if does not have an existing
Execute these commands in a sequence
[Read More]