Monday, 5 January 2026

ASP.NET Core's Observability Becomes a First-Class Feature

Leave a Comment
Contemporary applications require visibility into production in addition to functional coding. With built-in metrics, diagnostics, logging, and tracing, ASP.NET Core now views observability as a first-class feature.

This article discusses:
  • ASP.NET Core's built-in observability features
  • Detailed setup
  • Examples of real-world coding for tracking, logging, and metrics
  • Alerts, dashboards, and production preparedness
What Is Observability and Why Does It Matter?

Observability is the ability to understand the internal state of your application from external outputs like metrics, logs, and traces.

Core Observability Components

  1. your application's internal state from external outputs such asMetrics – Quantitative data (request rate, latency, errors).

  2. Logs – Detailed events or errors with structured information.as Metrics

  3. Traces – End-to-end visibility of requests across services.

Proper observability ensures you can detect and diagnose issues without guessing .

Built-In Observability Features in ASP.NET Core

ASP.NET Core now ships with rich diagnostics:

  • HTTP request counts and durations

  • Active requests

  • Failed requests (4xx / 5xx)

  • Connection, TLS, and runtime metrics (CPU, memory, GC)

These features reduce the need for heavy custom instrumentation and integrate easily with Prometheus, Grafana, and Azure Monitor.

Step-by-Step Setup of Observability

1. Create or Open Your ASP.NET Core App

dotnet new webapi -n ObservabilityDemo
cd ObservabilityDemo

2. Add Required NuGet Packages

dotnet add package OpenTelemetry
dotnet add package OpenTelemetry.Extensions.Hosting
dotnet add package OpenTelemetry.Instrumentation.AspNetCore
dotnet add package OpenTelemetry.Exporter.Prometheus.AspNetCore

3. Configure OpenTelemetry in Program.cs

using OpenTelemetry.Metrics;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddOpenTelemetry()
    .WithMetrics(metrics =>
    {
        metrics
            .AddAspNetCoreInstrumentation()
            .AddRuntimeInstrumentation()
            .AddPrometheusExporter();
    });

var app = builder.Build();

app.MapPrometheusScrapingEndpoint();
app.MapControllers();

app.Run();

Your app now exposes production-ready metrics at /metrics.

Real-World Coding Examples

These examples illustrate practical observability in production scenarios.

Example 1: Track API Usage (Business Metric)

using System.Diagnostics.Metrics;

public static class AppMetrics
{
    public static readonly Meter Meter = new("ObservabilityDemo");

    public static readonly Counter<int> OrdersCreated =
        Meter.CreateCounter<int>("orders_created");
}

[ApiController]
[Route("api/orders")]
public class OrdersController : ControllerBase
{
    [HttpPost]
    public IActionResult CreateOrder()
    {
        AppMetrics.OrdersCreated.Add(1);
        return Ok("Order created successfully");
    }
}

Scenario: Track how many orders your API receives per minute for business insight.

Example 2: Measure Request Duration for a Specific Endpoint

using System.Diagnostics;

[HttpGet("inventory")]
public async Task<IActionResult> GetInventory()
{
    var stopwatch = Stopwatch.StartNew();

    var inventory = await _inventoryService.GetItemsAsync();

    stopwatch.Stop();
    Console.WriteLine($"Inventory request took {stopwatch.ElapsedMilliseconds} ms");

    return Ok(inventory);
}

Scenario: Measure performance of heavy endpoints like inventory queries or report generation.

Example 3: Track Failures with Custom Counter

public static readonly Counter<int> PaymentFailures =
    AppMetrics.Meter.CreateCounter<int>("payment_failures");

[HttpPost("payments")]
public IActionResult ProcessPayment(PaymentRequest request)
{
    try
    {
        _paymentService.Process(request);
        return Ok();
    }
    catch(Exception)
    {
        PaymentFailures.Add(1);
        return StatusCode(500, "Payment failed");
    }
}

Scenario: Monitor payment failures in real-time for alerting or retries.

Example 4: Add Distributed Tracing for Downstream Calls

builder.Services.AddOpenTelemetry()
    .WithTracing(tracing =>
    {
        tracing.AddAspNetCoreInstrumentation();
        tracing.AddHttpClientInstrumentation();
    });

[HttpGet("external-data")]
public async Task<IActionResult> GetExternalData()
{
    var client = _httpClientFactory.CreateClient();
    var response = await client.GetAsync("https://api.example.com/data");
    return Ok(await response.Content.ReadAsStringAsync());
}

Scenario: Trace latency across external API calls to identify bottlenecks.

Dashboards and Alerts
Prometheus & Grafana

For dashboards and alerts we can use open sourced, self-hosted, cloud-friendly observability tools Prometheus and Grafana. They work on-prem, cloud, hybrid, and air-gapped systems. Cloud providers offer managed versions.

Dashboard Panels:

  • Request rate ( http_server_request_duration_seconds_count )

  • Latency P95 ( histogram_quantile(0.95, rate(...)) )

  • Error rate ( rate(http_server_request_duration_seconds_count{status_code=~"5.."}[1m]) )

Alerts:

  • High error rate

  • High latency

  • CPU/memory spikes

Include service name, severity, and dashboard links in every alert.

Production Observability Checklist

Before going live, ensure:

  • Metrics endpoint exposes system and business metrics

  • Structured logging with correlation IDs is enabled

  • Distributed tracing is enabled for all incoming/outgoing requests

  • Health checks and readiness probes are configured

  • Dashboards visualize key metrics and errors

  • Alerts are actionable and tested

  • Deployment markers and versions are visible

Production-ready apps answer: "What broke, why, and how badly — using metrics, logs, and traces alone."

Key Takeaways

ASP.NET Core's first-class observability enables developers to monitor apps confidently in production. By combining metrics, logs, tracing, dashboards, and alerts, you can proactively detect and resolve issues, optimize performance, and ensure your applications are reliable.

Observability is no longer optional — it's essential. Start implementing it from day one and make your app production-ready.

Happy Coding!

I write about modern C#, .NET, and real-world development practices. Follow me on C# Corner for regular insights, tips, and deep dives.

Best ASP.NET Core 10.0 Hosting Recommendation

One of the most important things when choosing a good ASP.NET Core 8.0 hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable ASP.NET Core, their servers are optimized for PHP web applications. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFEASP.NET, customers can also experience fast ASP.NET Core hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFEASP.NET guarantees 99.9% uptime for ASP.NET Core. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up.
Read More...

Monday, 22 December 2025

Session Count-Based Concurrent Login Management in ASP.NET WebForms

Leave a Comment

Limiting the amount of concurrent logins per user is a typical practice in many real-world applications, including banking portals, trading platforms, admin panels, and business systems.
Data inconsistencies, license abuse, and security problems might result from permitting infinite logins with the same credentials.


This article describes a traditional concurrent login/session-count control requirement, explores several solutions, and offers a simple ASP.NET WebForms + SQL Server solution with functioning logic and output explanation.

Problem Statement

  • A single user account should be allowed to log in from only N sessions (example: 2, 3, or 4).

  • If the user logs in again after reaching the limit:

    • Either deny login OR

    • Automatically terminate the oldest inactive session and allow new login.

  • Sessions may remain active if:

    • Browser is closed suddenly

    • User forgets to log out

  • The system must handle these cases automatically.

Requirements Summary

  • Allow configurable session count per user

  • Track:

    • Login time

    • Last activity

    • Active / inactive status

  • Automatically expire unused sessions

  • Ensure latest active users are not disturbed

Possible Approaches

Option 1: ASP.NET Session Only (Not Recommended )

  • Uses Session[] variables

  • Fails when:

    • Browser crashes

    • Multiple devices used

  • No central control

Not suitable for concurrent login control

Option 2: Database-Based Session Tracking (Recommended )

  • Store sessions in a database table

  • Track activity per login

  • Kill old sessions safely

This is the correct and professional approach

Database Design

adminmaster Table

Stores user details and allowed session count.

CREATE TABLE adminmaster
(
    Srno INT PRIMARY KEY,
    userid VARCHAR(50),
    password VARCHAR(50),
    SessionCount INT DEFAULT 3
);

UserSessions Table

Tracks each login session.

CREATE TABLE UserSessions
(
    SessionId UNIQUEIDENTIFIER PRIMARY KEY,
    UserSrno INT NOT NULL,
    LoginTime DATETIME,
    LastActivity DATETIME,
    IsActive BIT,
    CONSTRAINT FK_UserSession_Admin
        FOREIGN KEY (UserSrno) REFERENCES adminmaster(Srno)
);

Concept Used

1. GUID-Based Session Identification

  • Each login creates a unique SessionId

  • Avoids conflicts

  • Safe across multiple users and devices

2. Least Recently Used (LRU) Strategy

  • Sessions ordered by LastActivity

  • Oldest inactive session is terminated first

3. Configurable Session Limit

  • Each user has a different SessionCount

  • Can be changed without code modification

Login Flow Logic

  1. Validate username & password

  2. Read allowed session count

  3. Fetch active sessions

  4. If session limit reached:

    • Kill the oldest active session

  5. Create a new session

  6. Allow login

ASP.NET WebForms Login Code

// Validate user
string sqlqry = @"
SELECT Srno, userid, SessionCount
FROM adminmaster (NOLOCK)
WHERE userid=@UserId AND password=@passwrd";

DataSet ds = SqlHelper.ExecuteDataset(con, CommandType.Text, sqlqry, param);

if (ds == null || ds.Tables[0].Rows.Count == 0)
{
    ErrLbl.Text = "Invalid UserID or Password";
    return;
}

// User is valid
DataRow row = ds.Tables[0].Rows[0];
int userSrno = Convert.ToInt32(row["Srno"]);
int maxSession = row["SessionCount"] == DBNull.Value ? 0 : Convert.ToInt32(row["SessionCount"]);

// Get active sessions
string activeQry = @"
SELECT SessionId
FROM UserSessions
WHERE UserSrno=@uid AND IsActive=1
ORDER BY LastActivity";

SqlParameter[] pActive =
{
    new SqlParameter("@uid", userSrno)
};

DataTable dtActive =
    SqlHelper.ExecuteDataset(con, CommandType.Text, activeQry, pActive)
    .Tables[0];

// Kill oldest session if limit reached
if (dtActive.Rows.Count >= maxSession)
{
    Guid oldSessionId =
        Guid.Parse(dtActive.Rows[0]["SessionId"].ToString());

    SqlParameter[] pKill =
    {
        new SqlParameter("@sid", oldSessionId)
    };

    SqlHelper.ExecuteNonQuery(
        con,
        CommandType.Text,
        "UPDATE UserSessions SET IsActive=0 WHERE SessionId=@sid",
        pKill);
}

// Create new session
Guid newSessionId = Guid.NewGuid();

SqlParameter[] pInsert =
{
    new SqlParameter("@sid", newSessionId),
    new SqlParameter("@uid", userSrno)
};

SqlHelper.ExecuteNonQuery(
    con,
    CommandType.Text,
    @"INSERT INTO UserSessions
      VALUES (@sid,@uid,GETDATE(),GETDATE(),1)",
    pInsert);

// Store session
Session["UserSrno"] = userSrno;
Session["SessionId"] = newSessionId;

Response.Redirect("Dashboard.aspx");

Session Activity Update (BasePage Concept)

protected void Page_Load(object sender, EventArgs e)
{
    if (Session["SessionId"] != null)
    {
        SqlParameter[] p =
        {
            new SqlParameter("@sid", Session["SessionId"])
        };

        SqlHelper.ExecuteNonQuery(
            con,
            CommandType.Text,
            @"UPDATE UserSessions
              SET LastActivity=GETDATE()
              WHERE SessionId=@sid AND IsActive=1",
            p);
    }
}

Auto-Expire Inactive Sessions (SQL Job)

UPDATE UserSessions
SET IsActive = 0
WHERE IsActive = 1
AND DATEDIFF(MINUTE, LastActivity, GETDATE()) > 30;

Purpose

  • Handles browser crash

  • Cleans unused sessions

  • Keeps session count accurate

Output Explanation

Scenario 1

User allowed 3 sessions, logs in 3 times
All logins allowed

Scenario 2

User logs in 4th time

  • Oldest session is terminated automatically

  • New session is created

  • Login succeeds

Scenario 3

User closes browser without logout

  • Session becomes inactive after timeout

  • Slot is freed for new login

Advantages of This Approach
  • Secure

  • Scalable

  • Works across devices

  • Handles unexpected logouts

  • Professional enterprise-ready solution

Conclusion

Concurrent login control is a critical security feature in modern applications.
By using a database-driven session tracking mechanism with GUID-based session IDs and LRU session termination, we can efficiently control active logins without impacting user experience.

This solution is simple, clean, and production-ready for ASP.NET WebForms applications.

 

Best ASP.NET Core 10.0 Hosting Recommendation

One of the most important things when choosing a good ASP.NET Core 8.0.11 hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable ASP.NET Core, their servers are optimized for PHP web applications. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFE.eu, customers can also experience fast ASP.NET Core hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFEASP.NET guarantees 99.9% uptime for ASP.NET Core. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up.

Read More...

Tuesday, 16 December 2025

ASP.NET Core Tutorial :: An Example of the Post-Redirect-Get (PRG) Pattern in ASP.NET Core

Leave a Comment

Form submissions are a common feature of web applications, where users upload data to the server. When a user refreshes the site after completing a form, a frequent problem occurs: the browser makes the POST request again, which could result in double submissions. Developers use the Post-Redirect-Get (PRG) pattern, a well-known design strategy that improves user experience and avoids inadvertent duplicate operations, to lessen this.

Understanding the PRG Pattern

The PRG pattern follows a simple workflow:

  1. Post: The client submits data via an HTTP POST request.

  2. Redirect: The server processes the request and issues an HTTP redirect (usually 302 Found) to a new URL.

  3. Get: The client follows the redirect and issues an HTTP GET request to retrieve the updated resource or confirmation page.

This ensures that refreshing the page only repeats the GET request, not the original POST, thereby avoiding duplicate submissions.

Benefits of PRG

  • Prevents Duplicate Form Submissions: Refreshing or navigating back does not resubmit the POST request.

  • Improves User Experience: Users see a clean confirmation or result page after submission.

  • Supports Bookmarking and Sharing: Since the final step is a GET request, the resulting URL can be bookmarked or shared.

  • Aligns with REST Principles: GET requests are idempotent, making them safe for repeated execution.

When to Use the PRG Pattern

  • Form Submissions: Use PRG for any scenario where a form submission can create or change server-side data (e.g., orders, registrations, comments).

  • Multi-Step Processes: It’s useful in multi-step forms or wizards where each step might commit data changes that should not be duplicated.

Example Implementation in ASP.NET Core

Step 1: Create the Model

public class Feedback
{
    public string Name { get; set; }
    public string Comments { get; set; }
}

Step 2: Create the Controller

public class FeedbackController : Controller
{
    [HttpGet]
    public IActionResult Submit()
    {
        return View();
    }

    [HttpPost]
    public IActionResult Submit(Feedback model)
    {
        if (ModelState.IsValid)
        {
            // Process the feedback (e.g., save to database)

            // Redirect to confirmation page using PRG
            return RedirectToAction("Confirmation");
        }
        return View(model);
    }

    [HttpGet]
    public IActionResult Confirmation()
    {
        return View();
    }
}

Step 3: Create the Views

  • Submit.cshtml: Contains the feedback form.

  • Confirmation.cshtml: Displays a success message after submission.

Workflow Explanation

  1. The user navigates to /Feedback/Submit and fills out the form.

  2. On submission, the form data is posted to the server via POST.

  3. The server processes the data and issues a redirect to /Feedback/Confirmation.

  4. The browser follows the redirect and performs a GET request to display the confirmation page.

  5. If the user refreshes the confirmation page, only the GET request is repeated, not the original POST.

Best Practices

  • Always validate input before redirecting.

  • Use TempData to pass short-lived messages (e.g., success notifications) across redirects.

  • Ensure redirects point to meaningful pages that provide feedback to the user.

  • Combine PRG with anti-forgery tokens for secure form submissions.

One reliable solution to the issue of duplicate form submissions in web applications is the Post-Redirect-Get (PRG) pattern. Using RedirectToAction or Redirect, ASP.NET Core offers simple ways to implement PRG. Developers can produce apps that are safer, more user-friendly, and compliant with web standards by following this approach.

Best ASP.NET Core 10.0 Hosting Recommendation

One of the most important things when choosing a good ASP.NET Core 8.0.11 hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable ASP.NET Core, their servers are optimized for PHP web applications. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFE.eu, customers can also experience fast ASP.NET Core hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFEASP.NET guarantees 99.9% uptime for ASP.NET Core. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up.

Read More...

Monday, 8 December 2025

A Comprehensive Guide for Developers on Image Generation in.NET

Leave a Comment

AI-powered image generating has revolutionized contemporary applications in automation, design, e-commerce, and content development. With Azure OpenAI, OpenAI models (such GPT-4o and DALL·E), and.NET 8, developers can create robust image-generation systems with straightforward APIs. This article describes popular use cases, best practices, interview-ready concepts, how image generation operates, and how to connect it with .NET.

1. What Is AI Image Generation?

AI image generation is the process of creating new images from text instructions (prompts).
Modern models such as DALL·E, Stable Diffusion, and GPT-4o convert natural language into high-quality images by understanding your scene description.

Capabilities
  • Generate new images from text

  • Modify or extend existing images

  • Change styles (photorealistic, 3D, illustration)

  • Remove/replace objects

  • Upscale or improve quality

2. Tools Available for Image Generation in .NET
1. OpenAI / Azure OpenAI Image API

Supports:

  • Text-to-Image

  • Image editing

  • Image variations

NuGet package:

dotnet add package OpenAI
2. Third-party models (Stable Diffusion, Midjourney APIs)

Useful when:

  • You need local/on-prem image generation

  • GPU-based custom workflows

3. Custom models with ONNX Runtime

For enterprise offline image synthesis.

3. Setting Up Image Generation in .NET

First install the official OpenAI package:

dotnet add package OpenAI

Then initialize the client:

using OpenAI;

var client = new OpenAIClient("your_api_key");
4. Generate Images from Text (Text-to-Image)

This is the most common use case.

var result = await client.Images.GenerateAsync(new ImageGenerationRequest
{
    Prompt = "A futuristic city skyline at sunset with flying cars",
    Size = "1024x1024",
    Model = "gpt-image-1"
});

var imageBytes = Convert.FromBase64String(result.Data[0].B64Json);
await File.WriteAllBytesAsync("city.png", imageBytes);

Explanation

  • Model: "gpt-image-1" or latest

  • Prompt: Natural-language description

  • Size: 256x256, 512x512, 1024x1024

  • Result is Base64 encoded, saved as PNG

5. Image Editing in .NET (Add / Modify Content)

You can edit existing images by providing:

  • Base image

  • Mask image (transparent area = editable)

  • New prompt

Example: Replacing the background of a product image.

var baseImage = await File.ReadAllBytesAsync("product.png");
var maskImage = await File.ReadAllBytesAsync("mask.png");

var response = await client.Images.EditAsync(new ImageEditRequest
{
    Image = baseImage,
    Mask = maskImage,
    Prompt = "Replace the background with a clean white studio backdrop",
    Size = "1024x1024"
});

var edited = Convert.FromBase64String(response.Data[0].B64Json);
await File.WriteAllBytesAsync("output.png", edited);
6. Create Image Variations

Useful in:

  • Logo generation

  • Different styles of same object

  • Marketing content variations

var original = await File.ReadAllBytesAsync("logo.png");

var variation = await client.Images.CreateVariationAsync(new ImageVariationRequest
{
    Image = original,
    Size = "512x512"
});

var output = Convert.FromBase64String(variation.Data[0].B64Json);
await File.WriteAllBytesAsync("logo_variation.png", output);
7. Real-World Use Cases
1. E-commerce
  • Auto-generate product images

  • Change backgrounds

  • Create color variations

  • Social media previews

2. Marketing and Design
  • Banner images

  • Thumbnails

  • Posters

  • Animated storyboard frames

3. App & Game Development
  • Character avatars

  • Environment concept art

  • Texture generation

4. Automation
  • Generate dozens of images dynamically through .NET APIs

  • Auto-generate visuals for reports

8. Architecture for Image Generation in .NET
Pattern 1: REST API Microservice
  • ASP.NET Core MVC or Minimal API

  • Expose /generate-image, /edit-image endpoints

  • Can scale independently

  • Works well with frontend apps (React, Angular, MAUI)

Pattern 2: Background Task Worker
  • Queue requests

  • Generate images in background job

  • Use Hangfire, Azure Functions, or WorkerService

Pattern 3: Hybrid RAG + Image Generation
  • Search metadata for design descriptions

  • Generate images automatically

  • Useful in content automation platforms

9. Best Practices
  1. Use meaningful long prompts

  2. Always compress or resize for storage

  3. Cache generated images to reduce cost

  4. Validate user prompts to avoid misuse

  5. Limit max image-size for performance

  6. Avoid blocking UI threads; use async

Conclusion

Integrating AI-based image generation into .NET applications is now straightforward. With simple APIs, you can generate complex visuals, automate design workflows, and build creative tools directly within .NET. As .NET continues evolving, image generation will play an increasingly important role in enterprise automation, marketing, and end-user applications.

Best ASP.NET Core 10.0 Hosting in Europe with 15% OFF Discount!

One of the most important things when choosing a good ASP.NET Core 10.0 hosting in Europe is the feature and reliability. Led by a team with expert who are familiar on ASP.NET technologies, HostForLIFE offers an array of both basic and advanced ASP.NET Core 10.0 features in the package at the same time, such as:


All of their Windows & ASP.NET Core 10.0 Hosting servers are located in state of the art data center facilities that provide 24 hour monitoring and security. You can rest assured that while we do aim to provide cheap Windows and ASP.NET Core 10.0 hosting, we have invested a great deal of time and money to ensure you get excellent uptime and optimal performance. While there are several ASP.NET Core 10.0 Hosting providers many of them do not provide an infrastructure that you would expect to find in a reliable Windows platform.

 

Read More...

Tuesday, 2 December 2025

HostForLIFE.eu presents Hosting for ASP.NET Core 10.0

Leave a Comment
European premier web hosting service, HostForLIFE.eu announces the availability of ASP.NET Core 10.0 Hosting

HostForLIFE.eu was founded to address a niche market in the hosting sector: web hosting for clients seeking top-notch support. HostForLIFE.eu is an affordable, dependable hosting solution for cutting-edge Windows and ASP.NET technologies with consistent uptime, outstanding customer support, and high quality. With pride, HostForLIFE.eu announces that ASP.NET Core 10.0 hosting is now available across their whole server environment.


ASP.NET Core 10.0, the successor to .NET 9, is supported for three years as a long-term support (LTS) release. The .NET 10 runtime introduces new features and performance improvements. Key updates include: Array interface method devirtualization: The JIT can now devirtualize and inline array interface methods, improving performance for array enumerations. Array enumeration de-abstraction: Enhancements to reduce abstraction overhead for array iteration via enumerators, enabling better inlining and stack allocation. Inlining of late devirtualized methods: The JIT can now inline methods that become eligible for devirtualization due to previous inlining. Devirtualization based on inlining observations: The JIT uses precise type information from inlining to devirtualize subsequent calls. Stack allocation of arrays: Small, fixed-sized arrays can now be stack-allocated. AVX10.2 support: Introduced support for Advanced Vector Extensions (AVX) 10.2 for x64-based processors, though currently disabled by default. NativeAOT enhancements: Support for casting and negation in NativeAOT's type preinitializer.

HostForLIFE.eu hosts its servers in top class data centers that is located in Amsterdam (NL), London (UK), Paris (FR), Frankfurt(DE) and Seattle (US) to guarantee 99.9% network uptime. All data center feature redundancies in network connectivity, power, HVAC, security, and fire suppression. All hosting plans from HostForLIFE.eu include 24×7 support and 30 days money back guarantee. The customers can start hosting their ASP.NET Core 10.0 site on their environment from as just low €3.00/month only.

HostForLIFE.eu is a popular online ASP.NET based hosting service provider catering to those people who face such issues. The company has managed to build a strong client base in a very short period of time. It is known for offering ultra-fast, fully-managed and secured services in the competitive market.

HostForLIFE.eu offers the latest European ASP.NET Core 10.0 hosting installation to all their new and existing customers. The customers can simply deploy their ASP.NET Core 10.0 website via their world-class Control Panel or conventional FTP tool. HostForLIFE.eu is happy to be offering the most up to date Microsoft services and always had a great appreciation for the products that Microsoft offers. Further information and the full range of features ASP.NET Core 10.0 Hosting can be viewed here https://hostforlife.eu/European-ASPNET-Core-10-Hosting
 
About Company
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. HostForLIFE.eu deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

HostForLIFE.eu is awarded Top No#1 SPOTLIGHT Recommended Hosting Partner by Microsoft. Their service is ranked the highest top #1 spot in several European countries, such as: Germany, Italy, Netherlands, France, Belgium, United Kingdom, Sweden, Finland, Switzerland and other European countries. Besides this award, they have also won several awards from reputable organizations in the hosting industry and the detail can be found on their official website.
 
ASP.NET Core 10.0
Read More...

Tuesday, 25 November 2025

How Every Beginner Should Know How to Write SQL Queries?

Leave a Comment

Writing SQL queries is the core skill every backend, full-stack, or data engineer must learn. SQL Server may look complicated initially, but once you understand a few foundational queries like:

  • SELECT

  • WHERE

  • ORDER BY

  • JOIN

  • GROUP BY

  • Aggregations (COUNT, SUM, AVG)

you can query almost any business database.

This article takes a practical approach. The examples are based on a real-world automotive service management system, similar to the database from Article 1. Every query comes with:

  • The problem scenario

  • How the query works

  • A working SQL script example

This is written for beginners but structured in a way that builds real production readiness.

Real-World Context

Our database has three tables:

Customer

CREATE TABLE Customer (
    CustomerId INT PRIMARY KEY,
    FullName NVARCHAR(100),
    City NVARCHAR(100)
);

Car

CREATE TABLE Car (
    CarId INT PRIMARY KEY,
    CustomerId INT,
    Brand NVARCHAR(50),
    Model NVARCHAR(50),
    FOREIGN KEY (CustomerId) REFERENCES Customer(CustomerId)
);

ServiceRecord

CREATE TABLE ServiceRecord (
    ServiceId INT PRIMARY KEY,
    CarId INT,
    ServiceDate DATE,
    Cost DECIMAL(10,2),
    FOREIGN KEY (CarId) REFERENCES Car(CarId)
);

We will write SQL queries based on this data model.

SELECT: Retrieving Data

The SELECT command is used to fetch data from a table.

Example: Get all customers.

SELECT * FROM Customer;

While SELECT * is useful during development, in production always use explicit columns.

SELECT CustomerId, FullName, City FROM Customer;
WHERE: Filtering Records

Example: Customers from Mumbai.

SELECT FullName, City
FROM Customer
WHERE City = 'Mumbai';

You can use comparison operators:

  • =

  • !=

  • >

  • <

  • BETWEEN

  • LIKE

Example: Find customers whose name starts with "P".

SELECT FullName
FROM Customer
WHERE FullName LIKE 'P%';
ORDER BY: Sorting Results

Sort customer list alphabetically.

SELECT FullName, City
FROM Customer
ORDER BY FullName ASC;

Sort by most recent service first:

SELECT CarId, ServiceDate, Cost
FROM ServiceRecord
ORDER BY ServiceDate DESC;
JOIN: Combining Data from Multiple Tables

JOINs allow you to read related data across tables.

INNER JOIN

Get all cars with customer names.

SELECT
    Customer.FullName,
    Car.Brand,
    Car.Model
FROM Car
INNER JOIN Customer
    ON Customer.CustomerId = Car.CustomerId;
LEFT JOIN

Get all customers even if they do not own a car.

SELECT
    Customer.FullName,
    Car.Brand,
    Car.Model
FROM Customer
LEFT JOIN Car
    ON Customer.CustomerId = Car.CustomerId;
RIGHT JOIN (Rarely Used)
SELECT *
FROM Customer
RIGHT JOIN Car
    ON Customer.CustomerId = Car.CustomerId;
GROUP BY: Summarizing Data

GROUP BY is used with aggregate functions like COUNT, SUM, AVG.

Example: Count how many cars each customer owns.

SELECT
    Customer.FullName,
    COUNT(Car.CarId) AS TotalCars
FROM Customer
LEFT JOIN Car
    ON Customer.CustomerId = Car.CustomerId
GROUP BY Customer.FullName;

Example: Total service cost per car.

SELECT
    Car.Brand,
    Car.Model,
    SUM(ServiceRecord.Cost) AS TotalServiceCost
FROM Car
INNER JOIN ServiceRecord
    ON Car.CarId = ServiceRecord.CarId
GROUP BY Car.Brand, Car.Model;
HAVING: Filtering Group Results

Unlike WHERE, HAVING works after grouping.

Example: Customers who own more than one car.

SELECT
    Customer.FullName,
    COUNT(Car.CarId) AS CarCount
FROM Customer
LEFT JOIN Car
    ON Customer.CustomerId = Car.CustomerId
GROUP BY Customer.FullName
HAVING COUNT(Car.CarId) > 1;
TOP: Limit Results

Example: Get the most expensive service.

SELECT TOP 1 *
FROM ServiceRecord
ORDER BY Cost DESC;
DISTINCT: Remove Duplicates

Example: List all unique cities.

SELECT DISTINCT City
FROM Customer;
Combining Multiple Clauses

Example:
Get top 5 customers with the highest total service spending.

SELECT TOP 5
    Customer.FullName,
    SUM(ServiceRecord.Cost) AS TotalSpent
FROM Customer
JOIN Car ON Customer.CustomerId = Car.CustomerId
JOIN ServiceRecord ON Car.CarId = ServiceRecord.CarId
GROUP BY Customer.FullName
ORDER BY TotalSpent DESC;

This is similar to a real dashboard/report query.

Real-World Case Study

A service company initially exported all service records to Excel and manually calculated revenue. It took nearly 5 hours per week and had frequent mistakes.

After learning GROUP BY queries:

  • Revenue reports were generated instantly.

  • Customer trends became visible.

  • The business started offering targeted service packages.

SQL skills directly improved business outcomes.

Common Beginner Mistakes
MistakeBetter Practice
Using SELECT * in productionUse explicit column names
Forgetting WHERE conditionMay return huge datasets
Using RIGHT JOIN instead of LEFT JOINLEFT JOIN is usually easier and logical
Using HAVING for non-aggregatesUse WHERE instead
No ORDER BY in reportsReports appear random

Best Practices
  • Always format your SQL for readability.

  • Use meaningful aliases.

  • Use LIMIT/TOP when testing.

  • Follow naming conventions.

Example with formatting

SELECT
    c.FullName,
    SUM(sr.Cost) AS TotalSpent
FROM Customer c
JOIN Car ca ON c.CustomerId = ca.CustomerId
JOIN ServiceRecord sr ON ca.CarId = sr.CarId
GROUP BY c.FullName
ORDER BY TotalSpent DESC;
Summary

SQL querying begins with understanding and practicing:

  • SELECT

  • JOIN

  • GROUP BY

  • Filtering and sorting

These building blocks enable beginners to confidently query real business systems and prepare for more advanced topics like indexing, triggers, optimization, and stored procedures.

Best SQL 2022 Hosting Recommendation

One of the most important things when choosing a good SQL 2022 hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable SQL 2022, their servers are optimized for PHP web applications. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFE, customers can also experience fast SQL 2022 hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFE guarantees 99.9% uptime for SQL 2022. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up.

 

Read More...

Tuesday, 18 November 2025

.NET 10 Destroys MessagingCenter: The Cutting-Edge Substitute for Your MAUI App

Leave a Comment

With the release of .NET 10 , Microsoft has officially eliminated MessagingCenter , a long-standing functionality that many Xamarin. For lightweight communication between components, early MAUI developers relied on forms. This move may seem disruptive if your app still utilizes MessagingCenter, but in reality, safer, better, and easier-to-maintain alternatives have already taken its place.



This article outlines the reasons behind MessagingCenter's demise, suggests contemporary substitutes, and discusses how to seamlessly transfer your MAUI program without interfering with current features.

Why MessagingCenter Was Removed
MessagingCenter was originally introduced for simple publish–subscribe messaging, but over time developers ran into repeated issues:

  • Hidden communication made debugging difficult
  • Subscriptions often caused memory leaks
  • It didn’t align with dependency injection or MVVM best practices
  • Modern .NET messaging tools are cleaner and more efficient

To encourage better architecture and avoid unpredictable behavior, Microsoft removed MessagingCenter entirely in .NET 10.

Meet the Modern Replacement: WeakReferenceMessenger
The best replacement — and Microsoft’s deliberate direction — is WeakReferenceMessenger , part of the .NET Community Toolkit.

Why it’s better?

  1. Strongly typed messages
  2. No memory leaks thanks to weak references
  3. Great for MVVM
  4. Fully supported and actively updated
  5. Faster and more optimized than MessagingCenter

It provides the same pub/sub workflow, but without the pitfalls.

Basic Usage Examples
Send a message

WeakReferenceMessenger.Default.Send(new UserLoggedInMessage(userId));
Receive a message
WeakReferenceMessenger.Default.Register<UserLoggedInMessage>(this, (r, m) =>
{
    // Handle login message
});
Message definition
public class UserLoggedInMessage : ValueChangedMessage<string>
{
    public UserLoggedInMessage(string value) : base(value) { }
}

This pattern is clean, simple, and scales beautifully as your app grows.

Migrating From MessagingCenter to WeakReferenceMessenger
Here’s a common real-world example.

Old (MessagingCenter)
MessagingCenter.Subscribe<HomePage, string>(this, "LoggedIn", (sender, value) =>
{
    // handle login
});
New (WeakReferenceMessenger)
WeakReferenceMessenger.Default.Register<LoggedInMessage>(this, (r, m) =>
{
    // handle login
});

Send the message
WeakReferenceMessenger.Default.Send(new LoggedInMessage("success"));

Migration Tips for Large Apps

If your MAUI app uses MessagingCenter heavily, follow this structured migration path:

  1. Search for all MessagingCenter usages
  2. Create equivalent message classes
  3. Replace subscriptions with registrations
  4. Replace publish calls with messenger sends
  5. Test navigation scenarios for memory leaks

With WeakReferenceMessenger’s weak references, cleanup becomes much easier.

Why the New Approach Is Better for Your App?
Switching to modern messaging patterns gives you:

  • Cleaner, more predictable architecture
  • Faster message handling
  • Zero hidden dependencies
  • Fewer memory leaks
  • Easier debugging and testing
  • Future-proofing for new .NET MAUI updates

MessagingCenter may be gone, but the alternatives are significantly better.

Final Thoughts
The removal of MessagingCenter in .NET 10 marks the end of an old era and the beginning of a cleaner, more modern approach to app communication. Whether you migrate to WeakReferenceMessenger , traditional events, or a DI-driven pattern, your MAUI app will benefit from improved maintainability and performance. 

ASP.NET Core 10.0 Hosting Recommendation

One of the most important things when choosing a good ASP.NET Core 9.0 hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable ASP.NET Core, their servers are optimized for PHP web applications. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFE.eu, customers can also experience fast ASP.NET Core hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFEASP.NET guarantees 99.9% uptime for ASP.NET Core. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up.


Read More...