European ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4, ASP.NET 4.5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

European ASP.NET Core 9.0 Hosting - HostForLIFE :: Knowing the .NET Entity Framework

clock July 28, 2025 07:06 by author Peter

What is Entity Framework?
Microsoft's ORM tool for.NET is called Entity Framework (EF). Instead of writing SQL queries directly, it enables developers to use C# objects to carry out database actions. Depending on whether we begin with code, a database, or a visual model, Entity Framework supports three primary database development approaches. Depending on the needs of the project, each strategy works in a different setting. Consider a library system, where EF manages the backend conversion of this object-oriented query into SQL.

You have classes like Book, Author, and Borrower.
Instead of writing SQL to fetch books, you just query the context.Books.Where(b => b.Author == "John").

A simple understanding of the differences between code and database.

Code (C#) Database (SQL)
Class → Table
Property → Column
Object (instance) → Row

EF Core 8, which includes.NET 8, is the most recent and stable version of Entity Framework as of 2025. It is excellent for real-world projects since it is more powerful, faster, and provides long-term support. In addition to supporting cloud databases like Azure SQL, EF Core 8 is compatible with other well-known databases, including SQL Server, PostgreSQL, SQLite, and MySQL. Because it facilitates cross-platform development, you can use it to create applications for Linux, macOS, and Windows. The Data Access Layer (DAL) of a layered.NET architecture uses Entity Framework (EF) to manage all database interactions. It enables developers to interact with C# objects rather than writing SQL queries directly, creating a clear division between data operations and business logic.

What is ORM (Object-Relational Mapping)?
ORM stands for Object-Relational Mapping. It is a programming technique that lets developers interact with a relational database (like SQL Server, MySQL, PostgreSQL) using the object-oriented paradigm (like C# or Java classes) without manually writing SQL queries for every operation.
ORM maps database tables to programming language classes and table rows to objects, so we can work with the database like working with regular code objects. ORM is like an interpreter that lets your code "talk" to the database in its own language — while you stay in your comfort zone of writing C#.

Imagine we have an Excel sheet (database) with rows and columns. Each row represents a record. Now think of C# classes as templates that match the structure of those rows. So instead of writing.
SELECT *
FROM Products
WHERE Price > 100;


With ORM (like Entity Framework), we can simply write.
var products = dbContext.Products
    .Where(p => p.Price > 100)
    .ToList();

The ORM converts that C# code into SQL behind the scenes and gets the data for us. Using an ORM offers several benefits; it avoids writing repetitive SQL code, keeps the application code cleaner and more readable, supports LINQ-based querying for more natural data access in C#, automatically maps foreign keys and relationships between tables, and makes the codebase easier to maintain, update, and test over time.

Entity Framework (EF) Approaches

Entity Framework supports three main development approaches for working with databases, depending on whether you start with code, a database, or a visual model. Each approach suits different scenarios based on project needs.

1. Code First Approach
In Code First, we start by writing C# classes that represent our data model. EF then creates the database schema based on these classes. Best suited for new projects where no existing database is present.

Use Cases: Provides complete control over the database schema through code, allowing the structure to be defined using C# classes. Ideal for scenarios that require continuous development and updates, as it supports easy schema evolution using migrations. Imagine we're building a Library Management System from scratch. We define classes like Book, Author, and Borrower in code.
public class Book {
public int Id { get; set; }
public string Title { get; set; }
public Author Author { get; set; }
}


EF uses these classes to generate tables like Books and Authors in the database.

2. Database First Approach
In the Database First method, we begin with an existing database, and Entity Framework then reverse-engineers the schema and generates the corresponding C# classes and DbContext.

Use Cases: Ideal for legacy systems or enterprise applications where the database is already created and maintained independently. This approach allows quick integration by generating the required entity classes and context directly from the existing schema, saving development time and ensuring consistency between the application and the established database structure. Imagine We're joining a team maintaining a Retail Inventory System. The SQL Server database already contains tables like Products, Suppliers, StockLevels, and PurchaseOrders, all designed and managed by a database administrator. Instead of manually recreating models, we use EF Core’s Scaffold-DbContext command to generate the entity classes and context.
dotnet ef dbcontext scaffold "DBConnectionString" Microsoft.EntityFrameworkCore.SqlServer

Now we can query context. Products or context.PurchaseOrders using LINQ, without writing SQL manually.

3. Model First Approach (EF6 only)
In Model First, we design our data model visually using the EF Designer (.edmx file). EF then generates both the database and the C# code.

Use Case: Suitable for visual-first development and rapid prototyping scenarios where the data model is designed using a graphical interface. This approach allows quick creation and modification of the model through a visual designer. It is only supported in Entity Framework 6 and is not available in EF Core. Imagine a Hospital Management System, where entities like Patient, Doctor, and Appointment are visually modeled with defined relationships.

Each appointment is linked to one patient and one doctor.
Doctors and patients can have multiple appointments.

In the Model First workflow using Entity Framework 6, development begins by opening the EF Designer within Visual Studio. Inside this design surface, entities such as Patient, Doctor, or Appointment are visually arranged to represent the intended data model. Relationships between entities are then defined, for example, linking appointments to both patients and doctors to establish clear entity interactions. Once the model is structured and all associations are in place, Entity Framework generates both the underlying SQL database schema and the C# codebase directly from the visual design, streamlining the transition from concept to implementation.

Why and When to Use Entity Framework (EF)?
Simplifies Data Access: EF allows working with databases using C# classes and LINQ instead of writing raw SQL, making development faster and easier.
Object-Relational Mapping (ORM): EF maps database tables to C# classes and rows to objects, providing a smooth object-oriented experience with relational data.
Ideal for CRUD Applications: EF is perfect for applications that need to perform Create, Read, Update, and Delete operations on structured data.
Supports Migrations and Versioning: EF (especially Code First) helps manage database schema changes over time using migrations, which is essential for agile development.
Available as a NuGet Package: EF is not built-in by default; it is available as a NuGet package, allowing you to install only what you need, such as Microsoft.EntityFrameworkCore for EF Core. If you're learning more about NuGet packages, read the full article at: https://www.c-sharpcorner.com/article/nuget-package-manager-in-net/

Conclusion
As my understanding goes, Entity Framework (EF) is a powerful and flexible ORM that simplifies data access in .NET applications. It allows developers to work with databases using C# code instead of raw SQL, making development faster, cleaner, and more maintainable. With different approaches like Code First, Database First, and Model First, EF supports a wide range of scenarios—from new projects to legacy systems. Whether building web apps, desktop software, or APIs, EF—especially EF Core—is a modern and efficient choice for building data-driven applications.



European ASP.NET Core 9.0 Hosting - HostForLIFE :: Real time Example of Constructor Chaining

clock July 24, 2025 09:26 by author Peter

A constructor is a unique kind of function that is invoked automatically when a class instance is created. Static constructors are initialized by static members of a class, while constructors overload numerous constructor procedures within a class. Constructors has no return type and will be declared by the compiler if it is not defined.

Calling one constructor from another is known as constructor chaining. This procedure cuts down on repetition and reuses code. There are two syntactic options employing the chaining procedure, which are listed below.

Make use of the base class's constructor.

public ClassName() : base() { }

Call another constructor in the same class.
public ClassName() : this() { }

Real-time examples for constructor chaining with BankAccount class constructors are given here. Constructor overloading concept will be used to call the same class constructor by using 'this' keyword.
class BankAccount {
    String accountHolder;
    String accountType;
    double balance;

    // Default constructor
    public BankAccount() {
        this("Unknown", "Savings", 0.0); // Constructor chaining
    }

    // Constructor with accountHolder
    public BankAccount(String accountHolder) {
        this(accountHolder, "Savings", 0.0); // Constructor chaining
    }

    // Constructor with accountHolder and accountType
    public BankAccount(String accountHolder, String accountType) {
        this(accountHolder, accountType, 0.0); // Constructor chaining
    }

    // Full constructor
    public BankAccount(String accountHolder, String accountType, double balance) {
        this.accountHolder = accountHolder;
        this.accountType = accountType;
        this.balance = balance;
    }

    public void displayDetails() {
        System.out.println("Account Holder: " + accountHolder);
        System.out.println("Account Type: " + accountType);
        System.out.println("Balance: " + balance);
    }
}

public class Main {
    public static void main(String[] args) {
        BankAccount account1 = new BankAccount();
        BankAccount account2 = new BankAccount("aaa");
        BankAccount account3 = new BankAccount("bbb", "Current");
        BankAccount account4 = new BankAccount("cccc", "Savings", 5000.0);

        account1.displayDetails();
        account2.displayDetails();
        account3.displayDetails();
        account4.displayDetails();
    }
}


Output
Account Holder: Unknown
Account Type: Savings
Balance: 0.0

Account Holder: aaa
Account Type: Savings
Balance: 0.0

Account Holder: bbb
Account Type: Current
Balance: 0.0

Account Holder: cccc
Account Type: Savings
Balance: 5000.0



European ASP.NET Core 9.0 Hosting - HostForLIFE :: New Features in.NET 10: Quantum Security & JSON Updates

clock July 21, 2025 09:05 by author Peter

The .NET libraries have seen significant enhancements with Microsoft's.NET 10 Preview 6 release, which focuses on security, accuracy, and cryptographic innovation. The capabilities in this preview add more control and future-proof security options to your development toolbox, whether you're working with JSON data interchange or investigating sophisticated cryptographic techniques.

In this article, we’ll dive into the key updates in Preview 6.

  • Disallowing duplicate JSON properties
  • Enforcing strict JSON serialization
  • Introduction of Post-Quantum Cryptography (PQC) support

Option to Disallow Duplicate JSON Properties
Duplicate JSON keys have historically been a gray area in JSON parsers. The JSON specification doesn’t mandate a standard behavior for duplicate properties, which can result in unpredictable runtime behavior and even security vulnerabilities.

Why does it matter?
In scenarios where malicious users could manipulate JSON payloads, duplicate properties could be used to override expected values, posing a serious security risk.

New Feature
The new AllowDuplicateProperties flag in JsonSerializerOptions and JsonDocumentOptions can now be set to false, ensuring that duplicate properties throw exceptions, improving both security and consistency.

Example
string json = """{ "Value": 1, "Value": -1 }""";
Console.WriteLine(JsonSerializer.Deserialize<MyRecord>(json).Value); // Output: -1 (last one wins)
// Enabling strict duplicate checks
JsonSerializerOptions options = new() { AllowDuplicateProperties = false };
// These will now throw JsonException
JsonSerializer.Deserialize<MyRecord>(json, options);
JsonSerializer.Deserialize<JsonObject>(json, options);
JsonSerializer.Deserialize<Dictionary<string, int>>(json, options);
JsonDocumentOptions docOptions = new() { AllowDuplicateProperties = false };
JsonDocument.Parse(json, docOptions); // Throws JsonException
record MyRecord(int Value);


Strict JSON Serialization Options
By default, the JSON serializer in .NET is designed to be flexible, but sometimes too flexible for high-security or precision-critical applications.
Introducing JsonSerializerOptions.Strict

A new strict preset configuration enables best practices automatically, including.

  • Disallowing unmapped members
  • Disabling duplicate properties
  • Enforcing case-sensitive property matching
  • Respecting nullable annotations and required constructor parameters

This preset helps enforce strict contracts between your models and incoming JSON.

Use Case Example
string validJson = """{ "Name": "Alice", "Age": 30 }""";
var person = JsonSerializer.Deserialize<Person>(validJson, strictOptions);

record Person(string Name, int Age);

Use this when deserialization must exactly match your schema, with no surprises.

Post-Quantum Cryptography (PQC)
As the threat of quantum computing becomes more real, cryptographic standards are evolving. Microsoft is proactively addressing this with Post-Quantum Cryptography (PQC) support.

With .NET 10 Preview 6, support for PQC is being introduced through the Windows CNG (Cryptography Next Generation) platform. This enables the use of quantum-resistant algorithms in your .NET applications.

Sample: Verifying a PQC Digital Signature
using System;
using System.IO;
using System.Security.Cryptography;

private static bool ValidateMLDsaSignature(ReadOnlySpan<byte> data, ReadOnlySpan<byte> signature,

string publicKeyPath)
{
    string publicKeyPem = File.ReadAllText(publicKeyPath);
    using (MLDsa key = MLDsa.ImportFromPem(publicKeyPem))
    {
        return key.VerifyData(data, signature);
    }
}


Note. This works on Windows Insider builds with PQC support (Canary Channel).
Microsoft is also working on down-level support for the .NET Framework via the Microsoft.Bcl.Cryptography package, helping legacy apps move toward quantum-safe cryptography.

Conclusion

.NET 10 Preview 6 is more than just an incremental update, it is laying the foundation for secure, resilient, and precise applications. From safer JSON parsing to next-generation cryptographic capabilities, this release reflects Microsoft’s focus on developer security and interoperability.

Try It Out

You can start testing these features today using the .NET 10 Preview 6 SDK. If you’re a library author, security-focused developer, or someone handling sensitive data contracts, these updates are for you.



European ASP.NET Core 9.0 Hosting - HostForLIFE :: Examples to Help You Understand Dependency Injection (DI) in.NET Core

clock July 15, 2025 10:08 by author Peter

Dependency Injection (DI): What is it?
A design pattern called Dependency Injection (DI) is used to accomplish loose coupling between classes and their dependencies. Dependencies are injected from the outside, typically by a framework like.NET Core, rather than being created by a class itself. This encourages improved modularity, testability, and maintainability in application design.

Why Use DI?
Improves testability (easily mock dependencies)
Enhances flexibility and maintainability

Supports SOLID principles, especially:

  • Inversion of Control (IoC)
  • Single Responsibility Principle

How DI Works in .NET Core?
.NET Core comes with a built-in IoC container that supports three main service lifetimes:

Lifetime Description Example Use Case
Singleton One instance for the entire application Caching, config, loggers
Scoped One instance per HTTP request User/session-level services
Transient New instance every time it's requested Lightweight, stateless logic

Step-by-Step Example: Injecting a Service
1. Define an Interface

public interface IMessageService
{
    string GetMessage();
}


2. Create a Concrete Implementation
public class HelloMessageService : IMessageService
{
    public string GetMessage()
    {
        return "Hello from DI!";
    }
}


3. Register the Service in the Program.cs (.NET 6+)
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddScoped<IMessageService, HelloMessageService>(); // DI registration


4. Inject the Service in a Controller
[ApiController]
[Route("[controller]")]
public class HomeController : ControllerBase
{
    private readonly IMessageService _messageService;

    public HomeController(IMessageService messageService)
    {
        _messageService = messageService;
    }

    [HttpGet]
    public string Get() => _messageService.GetMessage();
}


Output
GET /home
=> "Hello from DI!"
Real-World Use Case

In a recent project, we used DI to inject:

  • ILoggingService
  • IEmailService
  • IUserRepository

This allowed us to easily swap implementations during unit testing and to mock external services such as SendGrid and SQL Server, enabling a much more testable and scalable architecture.

Summary

  • DI is built into .NET Core via IServiceCollection.
  • Encourages clean, testable, and modular code.
  • Supports different service lifetimes (Singleton, Scoped, Transient).
  • Use constructor injection as the standard approach.


European ASP.NET Core 9.0 Hosting - HostForLIFE :: Microsoft Entra External ID Integration with Blazor Web Application

clock July 11, 2025 08:58 by author Peter

Managing external user IDs becomes crucial as businesses provide more digital services to clients, partners, and outside developers. By offering a standards-based, scalable, and safe identification solution that works well with contemporary apps, Microsoft Entra External ID assists in overcoming this difficulty. 

 This article will demonstrate how to combine an ASP.NET Core MVC application with Microsoft Entra External ID. Setting up authentication, managing user claims, and enforcing authorization for external users will all be covered. This article will assist you in implementing identity management, whether you're creating a secure, user-friendly application or a multi-tenant SaaS platform.

Get started with Integration
Step 1. Open Visual Studio 2022, click on Create a New Project, select ASP.NET Core Web App (MVC) Template, provide a project name, and click Next to get a wizard below.

Step 2. In the service dependencies wizard, add the dotnet misidentify tool to add a Microsoft identity platform, and click Next

Step 3. Select the tenant and click Create New to register a new External Entra ID application or select an existing application,  as shown in the figure below.

Step 4. The next step is to add Microsoft Graph or any other API. For a demo, I'm just going to skip this process.
Finally, click next; it will scaffold all required NuGet packages and changes in the Program.cs, appsettings.json

Step 5. In this step, switch to entra.microsoft.com and ensure you are in the External ID tenant, go to the user flow. Please refer to my article to check how to create a user flow. Select the user flow and click on Application to link our application to the user flow, as shown in the figures below.


Step 6. Finally, run the application. It will display the Microsoft Entra External ID user flow sign-in screen. Sign in using your social account credentials. After successful authentication, the application will navigate to the Home screen.

Summary
A detailed tutorial on how to integrate Microsoft Entra External ID with an ASP.NET Core MVC application has been shown to us. It clarifies key ideas including maintaining user claims, implementing secure access controls, and configuring authentication for external users. Developers may improve application security and offer a smooth experience for external partners, clients, and vendors by leveraging Microsoft's identity platform. The manual supports identity management's strategic strategy as well as its technical implementation.



European ASP.NET Core 9.0 Hosting - HostForLIFE :: LINQ and Data View in C# and VB.NET

clock July 8, 2025 07:29 by author Peter

Here, a base class example and an exploration of Data View and LINQ (Language-Integrated Query) using DataTable Query for retrieving unique values from the database will be provided. LINQ is compatible with the most recent version,.NET 9, as well as.NET Core 3.1,.NET 5, and.NET 6. We will retrieve the data from a DataTable to a DataView using an example of a Book Class. Below is an example of a model-based class.

Book.cs
public class Book
{
    public int BookID { get; set; }
    public string Title { get; set; }
    public string Author { get; set; }
    public string Genre { get; set; }
    public decimal Price { get; set; }
}

Book Class Output Example without using LINQ.

BookID Title Author Genre Price
1 XXX xxx 1.1 45.00
2 YYY yyy 2.1 45.00
3 ZZZZ zzz 1.1 50.00
4 AAA aaa 1.1 30.00

To retrieve the unique values of the version sorted by price value, the example code below is provided for C# and VB.NET.

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        List<Book> books = new List<Book>
        {
            new Book { BookID = 1, Title = "XXX", Author = "xxx", version = "1.1", Price = 45.00m },
            new Book { BookID = 2, Title = "YYY", Author = "yyy", version = "2.1", Price = 50.00m },
            new Book { BookID = 3, Title = "ZZZZ Hobbit", Author = "zz", version = "1.1", Price = 30.00m },
            new Book { BookID = 4, Title = "AAA", Author = "aa", version = "1.1", Price = 42.00m }
        };

        // LINQ: Get all 1.1 books sorted by price
        var programmingBooks = books
            .Where(b => b.version == "1.1")
            .OrderBy(b => b.Price);

        Console.WriteLine("Books (sorted by price):");
        foreach (var book in programmingBooks)
        {
            Console.WriteLine($"{book.Title} by {book.Author} - ${book.Price}");
        }
    }
}

class Book
{
    public int BookID { get; set; }
    public string Title { get; set; }
    public string Author { get; set; }
    public string version { get; set; }
    public decimal Price { get; set; }
}

Dim bookTable As New DataTable()
bookTable.Columns.Add("BookID", GetType(Integer))
bookTable.Columns.Add("Title", GetType(String))
bookTable.Columns.Add("Author", GetType(String))
bookTable.Columns.Add("Genre", GetType(String))
bookTable.Columns.Add("Price", GetType(Decimal))

' Sample data
bookTable.Rows.Add(1, "XXX", "xxx", "1.1", 45.0D)
bookTable.Rows.Add(2, "YYY", "yyy", "1.2", 45.0D)
bookTable.Rows.Add(3, "ZZZ", "zzz", "2.1", 50.0D)
bookTable.Rows.Add(4, "AAA", "aa", "1.1", 30.0D)

Dim view As New DataView(bookTable)
Dim distinctBooks As DataTable = view.ToTable(True, "Title", "Author")

For Each row As DataRow In distinctBooks.Rows
    Console.WriteLine($"Title: {row("Title")}, Author: {row("Author")}")
Next

Output
Title: XXX, Author: xxx
Title: ZZZZ, Author: zz
Title: AAA, Author: aa



European ASP.NET Core 9.0 Hosting - HostForLIFE :: Base Class Library (BCL) for .NET

clock June 30, 2025 09:58 by author Peter

One crucial component of the.NET framework is the Base Class Library (BCL). Microsoft provides a basic collection of pre-built classes and types for the.NET platform called the Base Class Library (BCL). These are the fundamental components of nearly all.NET applications, be they desktop, online, console, or API projects. It is closely linked with the Common Language and is a component of the Framework Class Library (FCL). It functions similarly to the standard toolkit included with the.NET runtime, prepared to tackle common programming tasks such as:

  • Working with strings, numbers, and dates
  • Reading and writing files
  • Managing collections of data
  • Performing network operations
  • Handling threads and asynchronous tasks
  • Encrypting and securing data
  • Parsing XML and JSON
  • Reflecting on types and assemblies

It’s implemented in assemblies like System.Runtime.dll, System.Private.CoreLib.dll, and others, and is shared across all .NET implementations—whether you're building with .NET Core, .NET Framework, or modern .NET (6/7/8).

Think of the BCL as the foundation toolkit that every .NET developer uses — just like a workshop full of power tools and templates to build robust applications without reinventing the wheel.

Framework Class Library (FCL)
The Framework Class Library includes the BCL but also adds broader APIs for developing web apps (ASP.NET), desktop apps (WinForms/WPF), database access (ADO.NET), and more.

Common Language Runtime (CLR)
The CLR is the execution engine of .NET. It handles memory management, type safety, garbage collection, exception handling, and security.

In my opinion as a developer, we use many components from the Base Class Library in our day-to-day projects. We often see some libraries being used more commonly than others. It's helpful to understand what they are and how they work with real examples.

We build our house (Application) on a strong foundation (CLR), construct it using tools like List<T>, File, and Console (BCL), and then decorate it with features like ASP.NET, ADO.NET, and WinForms (FCL).

Why Use Base Class Library (BCL) in .NET?

  • Saves Development Time - No need to write common functionality from scratch. Built-in classes like List<T>, File, DateTime make tasks faster and easier.
  • Reduces Bugs - Microsoft’s BCL classes are thoroughly tested and reliable. Reduces the risk of writing error-prone custom implementations.
  • Increases Productivity - Developers can focus on business logic instead of low-level utilities. Example: File.ReadAllText("file.txt") reads an entire file in one line.
  • 4Cross-Platform Compatible - Works consistently across Windows, Linux, and macOS using .NET Core / .NET 5+. Ensures platform-independent development.
  • Improves Code Readability - Standardized APIs make code easier to read, understand, and maintain. Using familiar classes like StringBuilder, Dictionary, and Console helps teamwork.
  • Boosts Performance - Many BCL classes (like Stopwatch, Span<T>) are optimized for speed and memory.Useful for performance-critical tasks.
  • Consistent Design - All .NET languages (C#, VB.NET, F#) use the same BCL. APIs follow predictable naming and behavior patterns.


Commonly Used Base Class Libraries
1. System

System is the core namespace in the .NET Base Class Library (BCL). It contains the fundamental types and classes that almost every .NET application uses — including data types, console I/O, math functions, exceptions, and more. The foundation layer of all your C# programs — like the basic bricks and cement used in every building project. It includes essential types like:

  • Primitive types: System.Int32, System.Boolean, System.String, etc.
  • Base object model: System.Object, System.Type, System.Exception
  • Utilities: System.Math, System.Convert, System.Environment
  • Date and time: System.DateTime, System.TimeSpan
  • Console I/O: System.Console
  • Nullable types: System.Nullable<T>
  • Tuples and value types: System.ValueTuple, System.Enum

Example code:
using System;

class Program
{
    static void Main()
    {
        string name = "C# Community";
        int year = DateTime.Now.Year;

        Console.WriteLine($"Hello, {name}! Welcome to the year {year}.");
    }
}


We used:
    System.String
    System.DateTime
    System.Console


All from the System namespace—no extra libraries needed.

Why Is It Important?

It’s automatically referenced in most .NET projects, It provides the building blocks for all other namespaces and It’s the default namespace for many language features (e.g., int is an alias for System.Int32).

2.  System.IO
The System.IO namespace in .NET is we go-to toolkit for handling files, directories, and data streams. It’s part of the Base Class Library (BCL) and provides everything we need to read, write, and manage data on disk or in memory. It enables to:

  • Read and write files (File, FileStream, StreamReader, StreamWriter)
  • Work with directories (Directory, DirectoryInfo)
  • Handle paths (Path)
  • Monitor file system changes (FileSystemWatcher)
  • Read/write binary data (BinaryReader, BinaryWriter)
  • Use memory streams (MemoryStream)


Example Code
using System;
using System.IO;

public class Program
{
    public static void Main()
    {
        string path = "myFile.txt";
        File.WriteAllText(path, "Hi! C# community, I am Miche!");
        string content = File.ReadAllText(path);
        Console.WriteLine("File content:\n" + content);
    }
}


We used using System; and using System.IO;

These two using statements import the namespaces required.
System: Gives access to Console, String, etc.
System.IO: Gives access to file-related classes like File.


Common Classes in System.IO

Class Purpose
File / FileInfo Create, delete, copy, move files
Directory / DirectoryInfo Manage folders
StreamReader / StreamWriter Read/write text
BinaryReader / BinaryWriter Read/write binary data
FileStream Low-level file access
Path Manipulate file paths
MemoryStream Work with data in memory
FileSystemWatcher Watch for file changes (great for logging or syncing apps)

Why Is It Important?
To save data locally (like logs, configs, user input),  To read config files or resources in your application, To upload/download files in web apps and To interact with the file system in background jobs, APIs, or desktop tools. System and System.IO are libraries commonly used by developers from beginner to advanced levels. In this article, we introduced them briefly, and in the upcoming articles, we will explore other important libraries — explaining them in simple terms, along with detailed examples.

Essential .NET Base Class Libraries (BCL)

Namespace What It Is  Why It’s Important Use Case / Class
System Core types and base functionality Fundamental types used in all .NET code Console, String, DateTime, Math
System.IO File and stream handling Enables file read/write, stream data File, FileInfo, StreamReader, Path
System.Net.Http HTTP communication Connects to REST APIs or web servers HttpClient for GET/POST requests
System.Collections.Generic Generic data collections Manage dynamic data with type safety List<T>, Dictionary<K,V>
System.Linq LINQ querying over collections Simplifies filtering, sorting, and projections Where, Select, FirstOrDefault
System.Threading.Tasks Asynchronous programming Perform non-blocking background operations Task, async/await, Task.Run()
System.Text Text processing and manipulation Efficient string handling and encoding StringBuilder, Encoding.UTF8
System.Text.RegularExpressions Regex-based pattern matching Validate input, extract data from text Regex.IsMatch, Regex.Replace
System.Globalization Culture-aware formatting Supports localization for global users CultureInfo, DateTime.ToString("D", culture)
System.Diagnostics Logging, tracing, performance Debug, benchmark, trace app behavior Stopwatch, Debug.WriteLine()
System.Reflection Runtime type inspection Enables plugins, dependency injection, metadata access Type, Assembly, PropertyInfo
System.Security.Cryptography Cryptographic services Secure hashing, encryption, certificates SHA256, Aes, RNGCryptoServiceProvider
System.ComponentModel Metadata for components Data annotations, property binding INotifyPropertyChanged, attributes
System.Timers Timer-based scheduling Execute code at intervals Timer.Elapsed, auto-repeating logic
System.Configuration App config settings access Read/write app configuration files ConfigurationManager.AppSettings[]
System.Data Core data access tools Work with databases or tabular data DataTable, DataSet, DbConnection

How to Use Base Class Library (BCL) in .NET

  • BCL is built-in: No need to install — it comes with .NET automatically.
  • Use using statements: Add namespaces like System, System.IO, System.Collections.Generic at the top of your file.
  • Call built-in classes: Use BCL types like Console, DateTime, File, List<T>, etc.
  • Works in all project types: Console apps, web apps, APIs, desktop apps, etc.
  • Saves time: Gives you ready-to-use tools for common tasks like reading files, formatting dates, or handling collections.

Conclusion
The BCL is more than just a library—it’s the beating heart of .NET development. Mastering these foundational namespaces allows us to build clean, efficient, and maintainable software across a wide range of applications. From System.Net.Http for HTTP communication to System.Text.Json for serialization, these tools empower us to write less boilerplate and focus more on business logic.



European ASP.NET Core 9.0 Hosting - HostForLIFE :: Troubleshooting Memory Leaks in .NET Core

clock June 25, 2025 07:51 by author Peter

Memory leaks have the potential to subtly impair the functionality of your.NET Core apps, resulting in excessive memory usage, slow performance, or even crashes. Thankfully,.NET has a comprehensive toolkit for efficiently identifying, evaluating, and repairing memory leaks. Using useful tools and a real-world example, we'll go over how to find and fix memory leaks step-by-step in this post.

 

Prerequisites
Before diving into debugging memory leaks, ensure you have the following installed and set up.

  • .NET SDK 6.0+
  • dotnet-counters tool
  • dotnet-dump tool
  • Basic understanding of C# and ASP.NET Core

To install tools.

  • dotnet tool install --global dotnet-counters
  • dotnet tool install --global dotnet-dump

Creating a Sample ASP.NET Core Application
Add a Leaky Controller
In the Controllers folder, create a new file called LeakController.cs.
[Route("api/[controller]")]
[ApiController]
public class LeakController : ControllerBase
{
    private static Dictionary<int, byte[]> _leakyCache = new();

    [HttpGet("{kb}")]
    public IActionResult LeakMemory(int kb)
    {
        var buffer = new byte[kb * 1024];
        _leakyCache[DateTime.UtcNow.Ticks.GetHashCode()] = buffer;

        return Ok(new
        {
            Message = $"Leaked {kb} KB. Cache size: {_leakyCache.Count}"
        });
    }
}


Each request allocates a byte array and stores it in a static dictionary using the current timestamp as a key. Since we never remove old items, this creates a memory leak.

Running the Application
dotnet run

The API should be available at https://localhost:7261/api/leak/{kb}. This leaks 1000 KB of memory. To simulate repeated leaking.

for i in {1..50}; do curl http://localhost:7261/api/leak/1000; done

Monitoring with dotnet counters
Use dotnet-counters to monitor real-time performance metrics.

Get the process ID (PID) of your running app.
dotnet-counters ps

Now, run the below command to get the different parameters along with the memory size. dotnet-counters monitor --refresh-interval 1 -p <PID>

What to Watch.

  • GC Heap Size: Should grow steadily
  • Gen 0/1/2 GC Count: Garbage collections increase, but the EAP never shrinks

This confirms that objects aren’t being collected – a classic memory leak.

Capturing Memory Dumps

We capture a snapshot of the memory to analyze it.
dotnet-dump collect -p <PID> -o before_leak.dmp

Trigger more leaks.
for i in {1..100}; do curl http://localhost:5000/api/leak/1000; done

Then collect another snapshot.
dotnet-dump collect -p <PID> -o after_leak.dmp

Fixing the Leak
Limit the size of the dictionary.
if (_leakyCache.Count > 100)
    _leakyCache.Clear();


Validating the Fix
Restart the app, monitor with dotnet-counters, and send repeated requests. You should now see memory usage stabilize.

Conclusion
In.NET Core, memory leaks are subtle yet fatal. You can successfully identify and resolve them with dotnet-counters, dotnet-dump, and analytic tools like SOS and Visual Studio. This post led you through constructing a leaking program, finding difficulties, examining heap dumps, and repairing the leak. To guarantee seamless performance, your development and deployment cycle should include routine diagnostics and profiling. Thank You, and Stay Tuned for More!



European ASP.NET Core 9.0 Hosting - HostForLIFE :: The Difference Between Controller API.NET Core and Minimal API

clock June 23, 2025 08:02 by author Peter

will go over how the.NET 9 Core Minimal API Controller APIs differ from one another. Introduced in.NET 6.0, the Minimal API is a lightweight and quick API development that is improved in.NET 9. Additionally, it works well with microservices, tiny APIs, and lightweight services. The basic API lacks [HttpGet] and routing characteristics. All of the logics are defined in Program.cs, making it simpler. The controller-based API is structured, scalable, and based on the Model-View-Controller (MVC) design. It will work well for complicated and sizable applications. Different controller classes are used to structure logics.

 

Minimal API (.NET 9) Controller API (.NET 9)
Quick APIs, small and compact for micro services Complex APIs, larger, and enterprise apps
Lambda expressions are used and in-line based logic development Routing is based on the Attribute and Controller APIs
Dependency Injection is supported Dependency Injection is supported and more structured
Less structured for Testing & Maintainability can be handled for larger apps also Unit Testing & Maintainability is easier with the separation of concerns
Complex routing or filter options are limited Complex routing or filters are supported and structured

Will see how to create and run both a minimal API and a Controller API. First, to create the minimal API, run the following command in the command line.

dotnet new web -n MinimalApiDemo
cd MinimalApiDemo


In the program.cs file mapping the URL and function, there are no controllers and attributes; simply added routed mappings.

Minimal API Example
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

var products = new List<Product>
{
    new(1, "Laptop", 999.99m),
    new(2, "Phone", 499.99m)
};

app.MapGet("/products", () => products);

app.MapGet("/products/{id}", (int id) =>
    products.FirstOrDefault(p => p.Id == id) is Product product
        ? Results.Ok(product)
        : Results.NotFound());

app.MapPost("/products", (Product product) =>
{
    products.Add(product);
    return Results.Created($"/products/{product.Id}", product);
});

app.Run();


To check the output, visit 'https://localhost:5001/product/1'.

Controller API Example
To create an MVC controller-based AP,I run the below command.
dotnet new webapi -n ControllerApiDemo
cd ControllerApiDemo


Here we will have a simple product API example, with [HttpGet] routing example given below.
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    private static readonly List<Product> Products = new()
    {
        new Product { Id = 1, Name = "Laptop", Price = 1200 },
        new Product { Id = 2, Name = "Smartphone", Price = 800 }
    };

    [HttpGet]
    public ActionResult<IEnumerable<Product>> GetAll()
    {
        return Ok(Products);
    }

    [HttpGet("{id}")]
    public ActionResult<Product> GetById(int id)
    {
        var product = Products.FirstOrDefault(p => p.Id == id);
        if (product == null) return NotFound();
        return Ok(product);
    }
}


To check the output, visit 'https://localhost:5001/api/products'



European ASP.NET Core 9.0 Hosting - HostForLIFE :: A Complete Guide to.NET 8 Web API Health Checks

clock June 19, 2025 08:55 by author Peter

In today's fast-paced digital landscape, keeping your web applications reliable and responsive is more critical than ever. Health checks continuously monitor vital components—from databases and external APIs to network connections providing real-time insights into potential issues. Whether you're managing a small service or a large-scale microservices architecture, effective health checks help you detect problems early, streamline diagnostics, and automate recovery processes.

This post will demonstrate how to use.NET 8 to create reliable health checks in an ASP.NET Web API. In addition to monitoring an external API and running a custom ping test for network connectivity, you'll learn how to check the condition of your SQL Server database and provide a clean, JSON-formatted response that works in unison with contemporary monitoring tools. You may increase resilience and ensure dependable, seamless operations by making sure every crucial component of your application is regularly examined.

In this article, we will:

  • Create a new ASP.NET Web API project.
  • Implement health checks for a SQL Server database, an external API, and a custom ping test.
  • Convert the health check response to JSON.
  • Discuss the benefits and potential drawbacks of using health checks.

Prerequisites
Before you begin, make sure you have:

  • .NET 8 SDK installed.
  • A basic understanding of ASP.NET Web API and C#.
  • A valid connection string for your SQL Server database.
  • An external API URL to monitor (e.g., C# Corner API).

Step 1. Create the ASP.NET Web API Project
Open your command prompt (or terminal) and run the following bash command to create a new ASP.NET Web API project named HealthCheckDemo:
dotnet new webapi -n HealthCheckDemo
cd HealthCheckDemo


This command creates a basic Web API project using the minimal hosting model found in .NET 8.
You will also need the following NuGet packages:
dotnet add package AspNetCore.HealthChecks.SqlServer
dotnet add package AspNetCore.HealthChecks.Uris

Step 2. Implement a Custom Ping Test Health Check
A custom ping test can help verify network connectivity by pinging a specific host. Create a new file called PingHealthCheck.cs in your project and add the following code:
using System;
using System.Net.NetworkInformation;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Diagnostics.HealthChecks;

public class PingHealthCheck : IHealthCheck
{
    private readonly string _host;

    public PingHealthCheck(string host)
    {
        _host = host;
    }

    public async Task<HealthCheckResult> CheckHealthAsync(
        HealthCheckContext context,
        CancellationToken cancellationToken = default)
    {
        using var ping = new Ping();
        try
        {
            // Send a ping with a 2-second timeout
            var reply = await ping.SendPingAsync(_host, 2000);
            if (reply.Status == IPStatus.Success)
            {
                return HealthCheckResult.Healthy(
                    $"Ping to {_host} succeeded with roundtrip time {reply.RoundtripTime}ms");
            }
            return HealthCheckResult.Unhealthy(
                $"Ping to {_host} failed with status {reply.Status}");
        }
        catch (Exception ex)
        {
            return HealthCheckResult.Unhealthy(
                $"Ping to {_host} resulted in an exception: {ex.Message}");
        }
    }
}


This custom health check pings the host (such as "8.8.8.8") and returns a healthy status if the ping is successful.

Step 3. Configure Health Checks in Program.cs
Open your Program.cs file and update it to register health checks for your SQL Server database, the external API, and the custom ping test. In addition, configure the endpoint to output a JSON response.
using System.Text.Json;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.Extensions.Diagnostics.HealthChecks;

var builder = WebApplication.CreateBuilder(args);

// Add services for controllers (if you plan to use controllers)
builder.Services.AddControllers();

// Retrieve the connection string from configuration (set in appsettings.json)
string connectionString = builder.Configuration.GetConnectionString("DefaultConnection");

// Register health checks.
builder.Services.AddHealthChecks()
    // SQL Server Health Check: Execute a simple query to evaluate connectivity.
    .AddSqlServer(connectionString,
                  name: "SQL Server",
                  healthQuery: "SELECT 1;",
                  failureStatus: HealthStatus.Unhealthy)
    // External API Health Check: Verify that an external API (e.g., C#-Corner) is reachable.
    .AddUrlGroup(new Uri("https://www.c-sharpcorner.com/"),
                 name: "C# Corner API",
                 failureStatus: HealthStatus.Degraded)
    // Custom Ping Test Health Check: Ping an external host (e.g., Google's public DNS).
    .AddCheck("Ping Test", new PingHealthCheck("8.8.8.8"));

var app = builder.Build();

app.UseRouting();

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();

    // Map the health check endpoint with a custom JSON response writer.
    endpoints.MapHealthChecks("/health", new HealthCheckOptions
    {
        ResponseWriter = async (context, report) =>
        {
            context.Response.ContentType = "application/json";

            var response = new
            {
                status = report.Status.ToString(),
                // Provide details about each health check.
                checks = report.Entries.Select(entry => new
                {
                    key = entry.Key,
                    status = entry.Value.Status.ToString(),
                    description = entry.Value.Description,
                    duration = entry.Value.Duration.ToString()
                }),
                totalDuration = report.TotalDuration.ToString()
            };

            // Serialize the response in indented JSON format.
            await context.Response.WriteAsync(JsonSerializer.Serialize(response, new JsonSerializerOptions
            {
                WriteIndented = true
            }));
        }
    });
});

app.Run();

Explanation of the Code
Service Registration

  • SQL Server Check: Executes a simple query (e.g., "SELECT 1;") to ensure that the database is reachable.
  • External API Check: Checks the availability of an external API (such as C# Corner's API).
  • Ping Test: Uses the custom PingHealthCheck class to verify network connectivity by pinging "8.8.8.8".
  • Custom JSON Response Writer: The response writer builds a structured JSON object that includes overall health status, details of each health check (name, status, description, and duration), plus the total duration of the process.

Step 4. Configure the Connection String
In your appsettings.json file, add your SQL Server connection string under the "DefaultConnection" key:

json
{
  "ConnectionStrings": {
    "DefaultConnection": "Server=YOUR_SERVER;Database=YOUR_DATABASE;User Id=YOUR_USER;Password=YOUR_PASSWORD;"
  }
}

Replace the placeholders with your actual SQL Server credentials.

Step 5. Testing the Health Check Endpoint

Run Your Application: In your command prompt, run:
dotnet run

Access the Health Endpoint: Open your browser or use a tool like Postman and navigate to:
http://localhost:<port>/health

A typical JSON response might look like this:

This JSON response gives a clear overview of the health status of each dependency and ensures easy integration with monitoring tools.

Benefits of Using Health Checks

  • Proactive Monitoring: Regular health checks allow for early detection of issues, enabling quick corrective actions or automated recovery processes.
  • Simplified Diagnostics: Aggregating multiple checks into a single endpoint simplifies troubleshooting by providing clear, structured output via JSON.
  • Enhanced Resilience: Health checks are integral to modern orchestration systems like Kubernetes, which use them to manage service restarts and traffic routing based on real-time status.
  • Easy Integration: A JSON-formatted health response is readily consumable by dashboards and third-party monitoring tools, providing comprehensive insights over time.

Drawbacks and Considerations

  • Performance Overhead: Detailed or numerous health checks might add overhead, particularly if they perform resource-intensive operations. Balance thorough monitoring with performance.
  • False Positives: Overly aggressive or sensitive checks might incorrectly flag transient issues as failures, resulting in unnecessary alerts.
  • Maintenance Effort: As your application evolves, updating health checks to reflect new dependencies or architectural changes may require additional maintenance.
  • Security Concerns: Exposing detailed internal health information can be risky. Consider securing the health endpoint, especially in production environments.

Conclusion
Implementing comprehensive health checks in your ASP.NET Web API using .NET 8 significantly enhances your system's resilience and reliability. These checks—whether it's verifying SQL Server connectivity, ensuring external API availability, or performing a custom ping test—offer proactive monitoring that simplifies diagnostics and facilitates automated recovery in orchestration environments. Although careful consideration is needed to balance monitoring detail with performance overhead and potential security concerns, fine-tuning these checks can lead to a robust infrastructure that minimizes downtime and improves user experience. In essence, health checks serve as a crucial asset, empowering you to maintain a healthy, high-performing application in an ever-changing digital landscape.



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in