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 :: CommandResponse<T>: Streamlining C# Error and Success Handling

clock August 26, 2025 09:14 by author Peter

Understanding CommandResponse<T> in C#
When building applications, it’s common to write methods that need to return data along with the status of execution (success or failure). Instead of just returning raw data or a boolean, a better approach is to use a wrapper response object.
What is CommandResponse<T>?

CommandResponse<T> is a generic wrapper class that can hold:

  • Data: the actual result of the operation.
  • Errors: a list of errors if something went wrong.
  • Success: a quick way to check if the operation succeeded.
public class CommandResponse<T> where T : class, new()
{
    public T? Data { get; set; }
    public List<UserError>? Errors { get; set; }

    // Success is true if there are no errors
    public bool Success => Errors == null || Errors.Count == 0;
}

public class UserError
{
    public string Code { get; set; }
    public string Message { get; set; }
}

Why use it?
Imagine you are calling a service method like CreateUser. You don’t just want to know if it worked — you also want:
  • The created user details (on success).
  • The reason for failure (on error).
Instead of returning User or bool, you wrap everything into CommandResponse<User>.

Example: Service Method with CommandResponse<T>
public CommandResponse<User> CreateUser(string name, string email)
{
    var response = new CommandResponse<User>();

    if (string.IsNullOrWhiteSpace(name))
    {
        response.Errors = new List<UserError>
        {
            new UserError { Code = "NAME_EMPTY", Message = "Name cannot be empty." }
        };
        return response;
    }

    if (!email.Contains("@"))
    {
        response.Errors = new List<UserError>
        {
            new UserError { Code = "INVALID_EMAIL", Message = "Email is not valid." }
        };
        return response;
    }

    // If everything is fine, create a user
    response.Data = new User { Id = 1, Name = name, Email = email };
    return response;
}

How to Use It?
var service = new UserService();
var result = service.CreateUser("Shubham", "[email protected]");

if (result.Success)
{
    Console.WriteLine($"User created: {result.Data.Name}");
}
else
{
    foreach (var error in result.Errors)
    {
        Console.WriteLine($" Error: {error.Code} - {error.Message}");
    }
}


Benefits of CommandResponse<T>
  • Consistency: Every method can return success, data, and errors in a structured way.
  • Error Handling: avoids throwing exceptions for normal validation failures.
  • Clean Code: separates data from error handling.
In short, CommandResponse<T> is a standardised response wrapper that makes your code cleaner, easier to test, and more maintainable.

HostForLIFE ASP.NET Core 9.0 Hosting

European Best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



European ASP.NET Core 9.0 Hosting - HostForLIFE :: An Improved Method for Handling NuGet Dependencies

clock August 19, 2025 10:17 by author Peter

It can be challenging to manage packages in a.NET solution with numerous projects.  You've probably seen issues like this if you've worked on big apps with dozens or even hundreds of projects.

  • Projects utilizing various iterations of the same NuGet package are known as version mismatches.
  • Manual labor: Each must be updated. csproj files one after the other.
  • Build failures: CI/CD pipelines malfunctioning due to mismatched package versions.

To make this easier, Microsoft introduced Central Package Management (CPM) in .NET, starting with NuGet 6.0 and SDK-style projects.

What is Central Package Management?
Central Package Management lets you keep all NuGet package versions in one central file for your solution. Instead of writing the version number in every project file, you set it once in a file called Directory.Packages.props, and all projects use that version.

This makes upgrades easier, keeps versions consistent, and reduces maintenance work.

How It Works
Create a central file:
At the solution’s root, add a file named Directory.Packages.props.
<Project>
  <PropertyGroup>
    <ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
  </PropertyGroup>
  <ItemGroup>
    <PackageVersion Include="Newtonsoft.Json" Version="13.0.3" />
    <PackageVersion Include="RabbitMQ.Client" Version="7.1.2" />
    <PackageVersion Include="Swashbuckle.AspNetCore" Version="9.0.3" />
  </ItemGroup>
</Project>


Central Package Management
2. Reference packages in projects (without specifying versions):

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Newtonsoft.Json" />
    <PackageReference Include="RabbitMQ.Client" />
  </ItemGroup>

</Project>


Central Package Management
Note: The project file doesn’t include a version number. Instead, the version is defined in Directory.Packages.props.

3. Automatic adoption:

The .NET SDK automatically finds the Directory.Packages.props file in your solution folder and applies it to all projects.

Benefits of Central Package Management

  • Consistency – Every project uses the same package version, avoiding conflicts.
  • One place to update – Change the version in a single file instead of many.
  • Fewer code conflicts – No version mismatches in .csproj files.
  • Reliable builds – CI/CD pipelines run more smoothly.
  • Simpler project files – .csproj files stay clean and easy to read.

Here’s a simpler example with different packages:
Suppose you have a solution with 15 projects, all using Newtonsoft.Json. Without CPM, updating it means changing 15 .csproj files.

With CPM, you just add this to Directory.Packages.props:
<PackageVersion Include="Newtonsoft.Json" Version="13.0.3" />

Now all projects use the new version automatically.

Conclusion
Central Package Management (CPM) in .NET makes life easier for teams working on solutions with many projects. It keeps package versions consistent, simplifies updates, and saves time. If you haven’t tried it yet, create a Directory.Packages.props file in your solution. You’ll quickly see the advantages. Happy Coding!

HostForLIFE ASP.NET Core 9.0 Hosting

European Best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



European ASP.NET Core 9.0 Hosting - HostForLIFE :: Why C# Objects Aren't Immutable Despite Being Readonly?

clock August 11, 2025 08:57 by author Peter

When you first encounter the Readonly keyword in C#, it seems straightforward, prevent fields from being reassigned after construction. But once you start applying it to reference types, things get more nuanced. We’ll break down what Readonly really means, especially when dealing with objects, how it behaves differently with value vs. reference types, and what developers should keep in mind to write safer, cleaner code.

What Does Readonly Actually Do?

In C#, the Readonly keyword:

  • Can be applied to fields.
  • Ensures the field can only be assigned during declaration or inside the constructor of the class/struct.
  • Once assigned, the field can’t point to a different object.

public class User
{
    public string Name { get; set; }
}

public class Account
{
    private readonly User _user = new User();
    public void ChangeUser()
    {
        // This is possible
        _user.Name = "New Name";
        // But this will result in compile-time error
        _user = new User();
    }
}

Misunderstanding:
A Readonly field of a reference type doesn’t make the object itself immutable, it only means the reference can’t be reassigned. You can still modify the object’s internal state.
Reference Types vs. Value Types with Readonly

Value Types:
readonly int number = 5;
// Compile-time error
number = 10;


With value types (like int, bool, struct), Readonly means you cannot change the value.
Reference Types:
readonly List<string> items = new List<string>();
// Possible
items.Add("Test");
// Compile-time error
items = new List<string>();

So, the object can still mutate , it’s the reference that’s locked.

Then, How to Make Reference Types Truly Immutable?
To make an object’s state immutable, you must:

  • Avoid set accessors in properties.
  • Make all fields Readonly.
  • Use init accessors for initialization only.
  • Don’t expose collection fields directly.

Example
public class User
{
    public string Name { get; init; }
}

Readonly with Properties
While Readonly can be used on fields, it cannot be directly used on properties. But you can mimic the behavior using init accessor:
public string Role { get; init; } = "admin";

These make the property immutable after initialization.

HostForLIFE ASP.NET Core 9.0 Hosting

European Best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



European ASP.NET Core 9.0 Hosting - HostForLIFE :: Building Interactive Web Apps with Blazor

clock July 22, 2025 06:59 by author Peter

JavaScript is frequently used in contemporary web development to create interactive user interfaces. But now that Blazor has been released, Microsoft has given.NET developers the ability to create sophisticated, client-side web apps with C# rather than JavaScript. Blazor supports both client-side and server-side application models and is a component of the ASP.NET Core ecosystem.

What is Blazor?
Blazor is a web UI framework that allows developers to build interactive web UIs using C#. It runs in two main modes:

  • Blazor Server: Runs the application on the server and uses SignalR to manage UI interactions.
  • Blazor WebAssembly: Runs entirely on the browser using WebAssembly to execute C# code client-side.

Blazor combines the flexibility of modern web development with the productivity of .NET.

Key Features of Blazor

  • Component-based architecture for building reusable UI blocks.
  • Full .NET support — use C#, Razor, and existing .NET libraries.
  • Two-way data binding for easy synchronization of data and UI.
  • Dependency injection built-in.
  • Routing, event handling, and JavaScript interop support.

Blazor Development Workflow

1. Prerequisites
.NET SDK (.NET 8 or later)
Visual Studio 2022+ or Visual Studio Code
Blazor WebAssembly or Server project template

2. Create a New Project
Using CLI
​dotnet new blazorserver -o BlazorApp

or for WebAssembly
dotnet new blazorwasm -o BlazorApp

3. Project Structure

  • Pages/: Razor components (.razor files)
  • Shared/: Reusable layout or menu components
  • Program.cs: App startup and service configuration
  • _Imports.razor: Global namespaces for all components

4. Build and Run
cd BlazorApp dotnet run
Then open http://localhost:5000 in your browser.

Simple Example: Counter Component
<h3>Counter</h3> <p>Current count: @count</p> <button class="btn btn-primary" @onclick="IncrementCount">Click me</button> @code { private int count = 0; private void IncrementCount() { count++; } }

This is a basic component showing a counter that increments when the button is clicked. It's fully written in Razor and C# — no JavaScript involved.

Use Cases for Blazor

  • Enterprise internal tools and dashboards
  • Form-driven business applications
  • Interactive reporting interfaces
  • Progressive Web Apps (PWAs)

Best Practices

  • Break UIs into reusable components.
  • Use state management properly for large apps.
  • Secure APIs and validate user inputs.
  • Use JavaScript interop only when necessary.
  • Monitor performance in WebAssembly mode for large apps.

Conclusion
Blazor is revolutionizing web development by enabling full-stack C# development. With its flexible architecture, developer-friendly tooling, and integration with the .NET ecosystem, Blazor is an ideal choice for modern, scalable web applications. Whether you're building line-of-business apps or looking to transition from JavaScript frameworks, Blazor provides a productive and powerful alternative.

HostForLIFE ASP.NET Core 9.0 Hosting

European Best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



European ASP.NET Core 9.0 Hosting - HostForLIFE :: Create Sturdy Middleware in.NET: Circuit Breaker and Retry Using Polly v8

clock July 16, 2025 09:23 by author Peter

Applications commonly depend on external databases, services, and APIs to operate in today's distributed systems and microservices architecture. High traffic, network problems, or temporary difficulties can cause certain dependencies to fail. It is our responsibility as developers to build apps that can gracefully handle such failures. Resilience patterns can help with that. We will use the most recent Polly v8 coupled with Microsoft to construct middleware for Retry and Circuit Breaker in this blog. extensions. tenacity.

When should I use a circuit breaker? What is its pattern?
Modern applications employ the Circuit Breaker design pattern to avoid invoking a service or function that is prone to malfunction. Consider it analogous to your home's electric circuit breaker, which trips and cuts off the electrical supply in the event of an overload to guard against harm. In software, a circuit breaker momentarily halts calls to a malfunctioning service in order to prevent further overloading it.

When Should You Use It?

  • When an external service is known to fail frequently.
  • When you want to fail fast instead of waiting for timeouts.
  • To prevent cascading failures in microservices.
  • To improve overall system responsiveness and stability.

Circuit Breaker Flow

What is Polly?
Polly is a .NET resilience and transient-fault-handling library that allows developers to express policies such as Retry, Circuit Breaker, Timeout, Bulkhead Isolation, and Fallback. Polly has been widely adopted in the .NET community, and with Polly v8, Microsoft has introduced deep integration into the Microsoft.Extensions ecosystem through the new Microsoft.Extensions.Resilience package.

Polly with Microsoft.Extensions.Resilience
In Polly v8, resilience is more declarative and integrated into .NET’s dependency injection and configuration model. This makes it easier to build policies that are environment-aware and configurable. Let’s start building our retry and circuit breaker middleware using the latest packages.

Step 1. Set Up Your Project

Create a new web API project in Visual Studio, or if you are using Visual Studio Code, you can execute the following commands.
mkdir PollyResilienceApp
cd PollyResilienceApp
dotnet new PollyV8RetryDemo


Post that adds below the NuGet package
# In case of Visual Studio Code
dotnet add package Microsoft.Extensions.Resilience

# In case of Visual Studio Package Manager Console
NuGet\Install-Package Microsoft.Extensions.Resilience

Step 2. Configure Resilience Policies in the Program.cs
Open the Program.cs file and add the required namespace and Poly service to place it in the middleware. Below is the snippet of Program.cs file with service.
// namespaces
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Resilience;

var builder = WebApplication.CreateBuilder(args);

// add service
builder.Services.AddResiliencePipeline("standard-pipeline", pipelineBuilder =>
{
    // add retry configurations
    pipelineBuilder.AddRetry(new RetryStrategyOptions
    {
        MaxRetryAttempts = 3,  // -> this should be from appSettings.json
        Delay = TimeSpan.FromMilliseconds(500), // -> this should be from appSettings.json
        BackoffType = DelayBackoffType.Exponential
    });

    // set the circuit breaker pattern
    // configuration numbers should be driven from appSettings.json
    pipelineBuilder.AddCircuitBreaker(new CircuitBreakerStrategyOptions
    {
        FailureRatio = 0.5,  // -> this should be from appSettings.json
        SamplingDuration = TimeSpan.FromSeconds(30),
        MinimumThroughput = 10,
        BreakDuration = TimeSpan.FromSeconds(15)
    });
});

var app = builder.Build();

app.MapControllers();

app.Run();


Step 3. Inject and Use the Policy in a Controller
Once you set the service in the program.cs, it is time to inject the same in the Controllers. Below is an example of a sample controller where ResiliencePipelineProvider has been injected to execute
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Resilience;

[ApiController]
[Route("api/[controller]")]
public class MyAPIController : ControllerBase
{
    private readonly ResiliencePipelineProvider<string> _pipelineProvider;

    public MyAPIController(ResiliencePipelineProvider<string> pipelineProvider)
    {
        _pipelineProvider = pipelineProvider;
    }

    [HttpGet("execute")]
    public async Task<IActionResult> Execute_v1()
    {
        var pipeline = _pipelineProvider.GetPipeline("standard-pipeline");

        try
        {
            var result = await pipeline.ExecuteAsync(async token =>
            {
                // Actual operations goes here
                // For test, can place an sleep command
                // await Task.Delay(100);
                throw new HttpRequestException("Failure");
            });

            return Ok(result);
        }
        catch (Exception ex)
        {
            return StatusCode(500, $"Operation failed: {ex.Message}");
        }
    }
}

How Polly Helps Achieve the Circuit Breaker Pattern?
Polly allows you to plug in the circuit breaker logic without cluttering your business code. The resilience pipeline acts as a middleware that surrounds your code, monitoring failures, retries, and triggering breaks when needed.

With Polly, you get:

  • Observability: You can plug in logging and metrics easily.
  • Composability: You can combine Retry + Circuit Breaker + Timeout.
  • Declarative configuration: Adjust thresholds without touching the logic.

The diagram below explains how the request is flowing.

While all the retry actions are executing by Polly, logs can be done through the Logging Service. To enable the same, add the following code snippet in Program.cs. Appenders can be used based on the project needs.
builder.Services.AddLogging();

Conclusion
By integrating Polly v8 with Microsoft.Extensions.Resilience, you can build reliable, maintainable, and production-ready applications in .NET. Using the Retry and Circuit Breaker patterns, you shield your applications from transient errors and cascading failures.

If you’re building services at scale or working in a microservices environment, implementing these patterns is not just a good-to-have but a necessity.

HostForLIFE ASP.NET Core 9.0 Hosting

European Best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



European ASP.NET Core 9.0 Hosting - HostForLIFE :: MediatR Library Modern in.NET Core 9.0

clock July 11, 2025 08:29 by author Peter

MediatR
The application's package message dispatcher is called MediatR. Commands, queries, and handlers are examples of requests and answers that can be implemented with its help. Additionally, MediatR supports a variety of architectural patterns in contemporary.NET and.NET Core apps and permits the delivery of messages. It’s introduced as a .NET Standard library, starting from .NET Core 2.0, 3.1, and till supports the latest .NET 9.0. Additionally, it is a robust, open-source framework for.NET applications that implements the Mediator paradigm. Below is a list of architectures that support mediatR.

Clean Architecture: Well-suited for decoupling the application layers from presentation and infrastructure layers. Clean Architecture is used to keep business logic isolated.
CQRS (Command Query Responsibility Segregation): CQRS  is fit for handling separate write and read operations (commands and queries) in request/responses APIs.
DDD (Domain-Driven Design): This is suitable for loosely coupling applications that can be created with domain events and services.
Event-Driven Architecture: it supports publishing and handling events using INotification and INotificationHandler<T>
Test-Driven Development (TDD): This architecture Handlers are easy to unit test, it's isolated from controllers and infrastructure.

MediatR Features in .NET 9 Core

  • .NET 9.0 minimal API and modular project structure enhancements in a better way
  • Dynamic Database support provided for using the Entity Framework (SQL Server, PostgreSQL, MySQL, SQLite)
  • Better developer experience in lightweight, testable service layers.
  • MediatR is used for implementing CQRS and a separate layer like Application, Domain, and infrastructure.
  • Event handling is improved with built-in support for Server-Sent Events (SSE), 

Advantages of MediatR in the latest version of .NET

  • Testability improved; unit test handlers are easy and isolated
  • Good for large applications that maintain many modules and features
  • Logging, Validation, and Caching are supported in Pipeline behaviours
  • Efficient for real-time applications and event-driven applications, and streaming API like OpenAI’s

HostForLIFE ASP.NET Core 9.0 Hosting

European Best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



About HostForLIFE

HostForLIFE 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 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in