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 Hosting - HostForLIFE :: How to Fix v3 API Downtime Problems with NuGet Package Manager?

clock May 14, 2025 07:57 by author Peter

If you're working with NuGet in Visual Studio and encountering issues due to the NuGet v3 API being temporarily unavailable, you're not alone. Many developers have experienced downtime with the NuGet v3 API, leading to errors and hindering package management workflows. Fortunately, there is a quick workaround to resolve these issues.

Recognizing the Issue
Installing, updating, and managing third-party libraries and tools in projects is made simple for developers by NuGet, a well-liked package management for.NET. One of the main resources for managing and retrieving these packages is the NuGet v3 API. However, developers may encounter challenges when trying to restore or manage packages because of sporadic outages or connectivity problems with the NuGet v3 API.

A timeout or an inability to retrieve the required resources from the v3 API are common ways that the issue appears. When you're in the thick of development and require access to particular packages, this becomes really challenging.

Steps to Switch to NuGet v2 API

  • Open Visual Studio
    • Launch Visual Studio, the IDE you are using for your .NET projects.
  • Navigate to NuGet Package Manager Settings
    • Go to Tools in the top menu.
    • Select NuGet Package Manager.
    • Choose Package Manager Settings.
  • Change the Package Source URL
    • In the settings window, go to Package Sources.
    • You'll see the default NuGet source listed as https://api.nuget.org/v3/index.json.
    • Change this URL to https://www.nuget.org/api/v2/ to switch to the v2 API.
  • Save and Close
    • After updating the URL, click OK to save your settings.
  • Rebuild Your Project
    • Clean your project and rebuild it. This will allow NuGet to start using the v2 API to restore and manage packages.

Once these steps are completed, NuGet will automatically use the v2 API, bypassing the downtime issues caused by the v3 API.

Why Switch to NuGet v2 API?

The v2 API is older but still very reliable for managing packages. It allows for smoother transitions in cases of downtime, ensuring that your workflow remains uninterrupted. By using the v2 API, you can avoid the issues caused by API unavailability and continue your development efforts.

Additional Tips

  • Clear the NuGet Cache: If you face persistent issues even after switching the source, clearing the NuGet cache might help. This ensures that NuGet doesn’t use any outdated or corrupted cached data.
  • To clear the cache, go to:
    • Tools -> NuGet Package Manager -> Package Manager Settings -> Clear All NuGet Cache(s)
  • Check NuGet Status: Keep an eye on the official NuGet status page to see when the v3 API is back online. The NuGet team regularly updates the page with the status of their API services.
  • Revert Back to v3 Once Restored: Once the v3 API is back up and running, you can switch the URL back to the default v3 URL to take advantage of its enhanced features, such as better performance and newer functionalities.

Conclusion
Package management for your project may come to a complete stop if the NuGet v3 API goes down. However, you can carry on with your development without any disruptions if you swiftly transition to the v2 API as a temporary fix. This straightforward procedure guarantees that your workflow is unaffected while you wait for the v3 API to reactivate. To reduce interruptions to your development process, always maintain your NuGet settings current and monitor the state of the NuGet services.

HostForLIFE ASP.NET Core 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 Hosting - HostForLIFE :: Constructing a Secure SQL Injection Test Form with C# and ASP.NET

clock May 5, 2025 08:50 by author Peter

This blog post will discuss how to use C# and ASP.NET Web Forms to create a secure SQL injection testing website. This project is perfect for implementing input sanitization, error handling, and parameterized queries as well as learning about fundamental SQL injection protection measures.

Technologies Used

  • ASP.NET Web Forms (ASPX)
  • C# (Code-Behind)
  • SQL Server
  • ADO.NET with SqlHelper (Application Block)
  • Bootstrap 5 (Frontend UI)

Goal of This Application

  • Provide a login form that is intentionally structured to test SQL injection patterns.
  • Detect and block malicious inputs from both query string and form fields.
  • Log all suspicious activity.
  • Redirect users to a custom error page when SQL injection attempts are detected.

1. ASPX Page Code (Frontend Form)
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SqlInjection.aspx.cs" Inherits="TaskPractices.SqlInjection" %>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>SQL Injection Test</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />

    <style>
        body {
            background-color: #f8f9fa;
            padding: 50px;
        }

        .container {
            max-width: 500px;
            margin: auto;
        }

        .warning {
            color: red;
            font-size: 0.9rem;
        }
    </style>
</head>
<body>
    <div class="container border p-4 bg-white rounded shadow">
        <h3 class="text-center mb-4">SQL Injection Test Form</h3>
        <form runat="server">
            <div class="mb-3">
                <label for="username" class="form-label">Username</label>
                <input type="text" class="form-control" id="username" name="username" placeholder="Enter username" runat="server" />
            </div>

            <div class="mb-3">
                <label for="password" class="form-label">Password</label>
                <input type="password" class="form-control" id="password" name="password" placeholder="Enter password" runat="server" />
            </div>

            <asp:Button class="btn btn-primary w-100" Text="Login" ID="loginbtn" OnClick="loginbtn_Click" runat="server" />

            <p class="warning mt-3">
                ?? This form is for testing purposes only. Ensure backend uses parameterized queries.
            </p>
        </form>
    </div>
</body>
</html>

2. Code-Behind: SQL Injection Detection and Login Logic

using AppBlock;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TaskPractices.Allkindoflog;

namespace TaskPractices
{
    public partial class SqlInjection : System.Web.UI.Page
    {
        public string[] BlackList = new string[]
        {
            "@@", "/*", "*/", "function", "truncate ", "alter", "begin", "create", "cursor",
            "delete ", "exec", "<script>", "</script>", "script", "execute", "fetch", "insert ",
            "kill", "drop", "sysobjects", "syscolumns", "update ", "document.cookie", "'", ":",
            "--", "%", "=", " or ", ">", "<", "exec(", " del", "chr", "asc", "update "
        };

        public string[] chars = new string[]
        {
            "@@", "/*", "*/", "function", "truncate ", "alter", "begin", "create", "cursor",
            "delete ", "exec", "<script>", "</script>", "script", "execute", "fetch", "insert ",
            "kill", "drop ", "sysobjects", "syscolumns", "update ", "document.cookie", "'", ":",
            " or ", ">", "<", "exec(", " del", "chr", "asc", "update "
        };

        public string strURLRewrited = "";
        string sqlcon = ConfigurationManager.ConnectionStrings["Sqlconnection"].ToString();

        protected void Page_Load(object sender, EventArgs e)
        {
            strURLRewrited = Request.RawUrl;
            sqlInjection1();
            RemoveSpecialChars(strURLRewrited);
        }

        private bool CheckStringForSQL(string pStr)
        {
            if (string.IsNullOrEmpty(pStr) || pStr.CompareTo("") == 0)
                return false;

            string lstr = pStr.ToLower();

            foreach (string item in BlackList)
            {
                if (lstr.ToUpper() == item.ToUpper())
                    return true;
            }

            return false;
        }

        public void sqlInjection1()
        {
            try
            {
                string ErrorPage = "/ErrorPage/ErrorPage-Demo1.aspx";

                // Form data check
                for (int i = 0; i < Request.Form.Count; i++)
                {
                    if (CheckStringForSQL(Request.Form[i]))
                    {
                        Log.errorlog(Request.Form[i], strURLRewrited);
                        Response.Redirect(ErrorPage);
                    }
                }

                // Query string check
                for (int i = 0; i < Request.QueryString.Count; i++)
                {
                    if (CheckStringForSQL(Request.QueryString[i]))
                    {
                        Log.errorlog(Request.QueryString[i], strURLRewrited);
                        Response.Redirect(ErrorPage);
                    }
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

        public void RemoveSpecialChars(string str)
        {
            foreach (string c in chars)
            {
                if (str.Contains(c))
                {
                    Log.errorlog(str, strURLRewrited);
                    Response.Redirect("/ErrorPage/ErrorPage-Demo1.aspx");
                }
            }
        }

        protected void loginbtn_Click(object sender, EventArgs e)
        {
            DataSet ds = new DataSet();

            try
            {
                SqlParameter[] param = {
                    new SqlParameter("@PAN", username.Value.Trim()),
                    new SqlParameter("@EMAIL", password.Value.Trim())
                };

                string sql = "SELECT * FROM ClientData (NOLOCK) WHERE PAN=@PAN AND EMAIL=@EMAIL";
                ds = SqlHelper.ExecuteDataset(sqlcon, CommandType.Text, sql, param);

                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {
                    HttpContext.Current.Session["ClientCode"] = ds.Tables[0].Rows[0]["ClientId"].ToString().Trim();
                    HttpContext.Current.Session["ClientFname"] = ds.Tables[0].Rows[0]["Name"].ToString().Trim();
                    HttpContext.Current.Session["Pan"] = ds.Tables[0].Rows[0]["PAN"].ToString().Trim();
                    HttpContext.Current.Session["Email"] = ds.Tables[0].Rows[0]["EMAIL"].ToString().Trim();

                    ScriptManager.RegisterStartupScript(this, typeof(string), "Message", "alert('Login successfully');", true);
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this, typeof(string), "Message", "alert('User Not Exists !');", true);
                }
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this, typeof(string), "Message", $"alert('{ex.Message}');", true);
            }
        }
    }
}

Key Takeaways

  • Always use parameterized queries instead of string concatenation to prevent SQL injection.
  • Implement input sanitization and validation on both the server and client sides.
  • Maintain a blacklist of harmful SQL keywords to filter user input.
  • Redirect to custom error pages and log malicious attempts for analysis.

Improvements You Can Add

  • Use a whitelist approach for known safe characters.
  • Integrate logging with tools like ELMAH or Serilog.
  • Use Stored Procedures instead of inline queries for extra safety.
  • Replace hard-coded blacklists with centralized config-based filters.

Conclusion
This project helps demonstrate SQL injection defense in a hands-on way using ASP.NET. It’s a great way to test and validate your security practices while building safe and user-friendly forms. Would you like a downloadable PDF of this documentation?


HostForLIFE ASP.NET Core 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 Hosting - HostForLIFE :: The Greatest Option for Reactive Systems in C#.NET 9 is Akka.NET

clock April 28, 2025 08:46 by author Peter

In a world where software needs to be message-driven, elastic, resilient, and responsive, traditional thread-based and monolithic designs frequently break under complexity or stress. Reactive systems excel in this situation, and Akka.NET makes it not only feasible but also pleasurable to design them in C# with.NET 9. Originally created for the JVM and then transferred to.NET, Akka.NET is an open-source toolkit built on the actor paradigm. It makes it simple to create distributed, concurrent, and fault-tolerant systems.

This post will explain why Akka.NET is the greatest option for developing reactive systems in.NET 9 and provide a step-by-step demonstration of a practical example.

Why Choose Akka.net for Reactive Systems?
Akka.NET is an open-source .NET framework that implements the actor model — a proven approach to building concurrent systems. Each actor is an independent unit that processes messages asynchronously and maintains its own internal state.

Core Features of Akka.NET
Asynchronous by default: Actors process messages concurrently without locking.

  • Resilient architecture: Supervision strategies handle failures gracefully.
  • Scalable: Easily scale horizontally using Akka.Cluster and Cluster.Sharding.
  • Decoupled components: Built on message passing, not shared state.
  • Built-in support for persistence, routing, and remote messaging.

Akka.NET allows you to build applications that are not only scalable and efficient but also fault-tolerant by design.

Step-by-Step: Building a Reactive System with Akka.NET
Let’s create a simple reactive banking system where.

  • Users can deposit, withdraw, and check their balance.
  • Each operation is handled as a message by an actor.

Step 1. Create a New Console App
dotnet new console -n AkkaReactiveBank
cd AkkaReactiveBank


Step 2. Add Akka.NET NuGet Package
dotnet add package Akka

Step 3. Define Actor Messages
Create a new file BankMessages.cs.
public record Deposit(decimal Amount);
public record Withdraw(decimal Amount);
public record CheckBalance;


These represent the commands sent to the actor.

Step 4. Create the Bank Actor
Create a new file BankActor.cs.
using Akka.Actor;
using System;

public class BankActor : ReceiveActor
{
    private decimal _balance;

    public BankActor()
    {
        Receive<Deposit>(msg => HandleDeposit(msg));
        Receive<Withdraw>(msg => HandleWithdraw(msg));
        Receive<CheckBalance>(_ => HandleCheckBalance());
    }

    private void HandleDeposit(Deposit msg)
    {
        _balance += msg.Amount;
        Console.WriteLine($"[Deposit] Amount: {msg.Amount}, New Balance: {_balance}");
    }

    private void HandleWithdraw(Withdraw msg)
    {
        if (_balance >= msg.Amount)
        {
            _balance -= msg.Amount;
            Console.WriteLine($"[Withdraw] Amount: {msg.Amount}, Remaining Balance: {_balance}");
        }
        else
        {
            Console.WriteLine("[Withdraw] Insufficient funds.");
        }
    }

    private void HandleCheckBalance()
    {
        Console.WriteLine($"[Balance] Current Balance: {_balance}");
    }
}


Step 5. Set Up the Actor System in the Program.cs
Replace the content of the Program.cs.
using Akka.Actor;
class Program
{
    static void Main(string[] args)
    {
        using var system = ActorSystem.Create("BankSystem");

        var bankActor = system.ActorOf<BankActor>("Bank");

        bankActor.Tell(new Deposit(1000));
        bankActor.Tell(new Withdraw(200));
        bankActor.Tell(new CheckBalance());

        Console.ReadLine();
    }
}

Step 6. Run the Application
dotnet run

Output
[Deposit] Amount: 1000, New Balance: 1000
[Withdraw] Amount: 200, Remaining Balance: 800
[Balance] Current Balance: 800


You’ve just created a reactive banking system with Akka.NET in .NET 9.

HostForLIFE ASP.NET Core 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 Hosting - HostForLIFE :: Apps for.NET 9 Run Faster Than Before

clock April 21, 2025 08:49 by author Peter

Microsoft continues to push the limits of what can be done with.NET with every new release, and.NET 9 is no exception. From quicker APIs, serialization, and more effective JIT compilation to better memory management, this most recent version offers observable performance gains across the board. This post will examine the main performance improvements in.NET 9, contrast the actual code execution of.NET 8 and.NET 9, and demonstrate how upgrading to.NET 9 can significantly improve your apps with little modification.

What's New in .NET 9 Performance?

  • Some standout performance improvements in .NET 9.
  • Improved JIT Compiler (RyuJIT)
  • Reduced GC (Garbage Collection) Pauses
  • Faster System.Text.Json Serialization/Deserialization
  • Enhanced HTTP/3 and Kestrel Web Server
  • More Efficient Task and Thread Management

Real Programming Comparison: .NET 8 vs .NET 9
Let's take a real example that most applications deal with — JSON serialization and HTTP response via Minimal APIs.

Example. Minimal API returning JSON data
Code (Same for .NET 8 and .NET 9)
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/data", () =>
{
    var data = Enumerable.Range(1, 1000)
        .Select(x => new { Id = x, Name = $"Item {x}" });
    return Results.Ok(data);
});

app.Run();


We’ll test this endpoint using a load test tool (e.g., wrk or Apache Benchmark) to compare .NET 8 and .NET 9.

Benchmark Result

Environment

  • OS: Windows 11 / Ubuntu 22.04
  • Load Test: 100,000 requests / 10 concurrent threads
Metric .NET 8 .NET 9 Improvement
Requests/sec 29,200 34,500 +18%
Avg Response Time 12.4 ms 9.8 ms -21%
Memory Allocations 2.5 MB 1.8 MB -28%
CPU Usage (under load) High Reduced  

Another Example: String Parsing Function
Let’s compare a simple string parsing function using BenchmarkDotNet.

Code
public class TextProcessor
{
    public static List<string> ExtractWords(string sentence)
    {
        return sentence
            .Split([' ', ',', '.', '!'], StringSplitOptions.RemoveEmptyEntries)
            .Where(word => word.Length > 3)
            .ToList();
    }
}


Benchmark Test
[MemoryDiagnoser]
public class BenchmarkTest
{
    private readonly string sentence = "The quick brown fox jumps over the lazy dog. Testing .NET performance!";

    [Benchmark]
    public List<string> RunTest() => TextProcessor.ExtractWords(sentence);
}

Benchmark Result

Runtime Mean Time Allocated Memory
.NET 8 5.10 µs 1.65 KB
.NET 9 4.01 µs 1.32 KB

Result: .NET 9 is ~21% faster and uses ~20% less memory.

System.Text.Json Serialization Comparison

Code

var person = new { Name = "Peter", Age = 30 };
string json = JsonSerializer.Serialize(person);
Framework Serialization Time Memory Allocation
.NET 8 2.4 µs 560 B
.NET 9 1.9 µs 424 B

.NET 9 improves System.Text.Json serialization speed and lowers memory usage for large object graphs.

Conclusion
.NET 9 is a performance beast. With smarter memory handling, improved JIT, and optimizations to HTTP servers, JSON serialization, and general computation — your apps will run faster and leaner by default. No major code changes are needed — just upgrade and reap the benefits. Whether you're building APIs, desktop apps, or microservices, .NET 9 is built to scale faster, respond quicker, and consume fewer resources. Now is the time to upgrade and experience the performance leap.

Upgrade to .NET 9 and unleash the true speed of your apps!

HostForLIFE ASP.NET Core 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 Hosting - HostForLIFE :: Discover how to integrate Firebase with .NET

clock April 14, 2025 07:19 by author Peter

A free database is provided by a Firebase database connection.  In essence, we are able to perform CRUD tasks, which include Insert, Update, Get, and Delete.  I've broken out how to install and create a project on the Firebase console panel here.  Opening Firebase and logging into your account is the first step.  The second step is to select the terminal application that opens Dashboard, click Create Project, and then enter the name of your project.

 

Making a real-time database is the third phase. Then select the test mode and press the "enable" button. You can now use this configuration for crude operations as your database has been built. The first step is to register for a Firebase account. I've included a link that will assist you in using the Firebase console app to create a project.

These are some steps listed below that take you to the exact place of Firebase integration with .NET. Firstly, you need to create a .net project and then install the NuGet package; and name of the package is FireSharp, and the version of the package is 2.0.4.

Now, you will need credentials to perform the CRUD operation.

To connect with your real-time database, copy the base path from the console app.

Then we need the authsecret key, that key you can fetch from the project setting > service account > database secret key.


Lastly, let’s write code in .NET.
// Firebase configuration
IFirebaseConfig ifc = new FirebaseConfig()
{
    AuthSecret = "**********x8Ed6HVU0YXlXW-L75ho4ps",
    BasePath = "https://we****.firebaseio.com/"
};

IFirebaseClient client;

// Create a user object
User user = new User()
{
    Id = 1,
    FirstName = "Test 1",
    LastName = "Test 2"
};

// Initialize Firebase client
client = new FireSharp.FirebaseClient(ifc);

// Insert data
var set = client.Set("User/" + user.Id, user);

// Delete data
set = client.Delete("User/" + user.Id);

// Update data
set = client.Update("User/" + user.Id, user);

// Retrieve data
set = client.Get("User/" + user.Id);


To explore more classes, please visit the official doc of Firebase Admin .NET SDK: firebase.google.com/docs/reference/admin/dotnet



European ASP.NET Core Hosting - HostForLIFE :: Creating Custom Components in Blazor

clock April 11, 2025 09:33 by author Peter

Microsoft created the open-source Blazor web framework, which enables programmers to create interactive online apps with C# and.NET. Blazor builds modular and reusable user interface components using a component-based architecture. Building intricate and reusable web apps requires the use of custom components. We will use examples to demonstrate how to develop custom components in Blazor in this article.

Prerequisites
Before we begin, ensure you have the following set up on your development environment:

  • Visual Studio 2022.
  • Basic knowledge of C# and HTML.

Understanding Components in Blazor
Components in Blazor are similar to user controls in other web frameworks. They are self-contained pieces of code that contain both markup and logic. Components can be composed and nested to create complex UI elements. In Blazor, components can be created using Razor syntax or using C# code. There are two types of components in Blazor:

  • Razor Components: These are defined using Razor syntax (.razor files) and allow for a mix of HTML and C# code.
  • Code-Behind Components: These are defined using C# classes and are more suitable for more complex logic or when you want to separate the UI and C# code.

In this article, we'll focus on creating custom Razor components.

Step 1. Create a New Blazor Project
Let's start by creating a new Blazor project. Open Visual Studio and follow these steps:

  • Click on "Create a new project."
  • In the "Create a new project" dialog, search for "Blazor WebAssembly App," select the "Blazor WebAssembly App" template and click on "Next".
  • Choose a name and location for your project, and click "Next".
  • Choose the ".NET 7.0" option from the framework and click "Create" to generate the project.

Step 2. Add a Custom Component
In this example, we'll create a simple custom component that displays a welcome message with the ability to customize the name.

  • Right-click on the "Pages" folder in your Blazor project, and select "Add" > "New Folder." Name the folder "Components."
  • Right-click on the newly created "Components" folder, and select "Add" > "New Item."
  • In the "Add New Item" dialog, search for "Razor Component" and select the "Razor Component" template.
  • Name the component "WelcomeMessage.razor" and click "Add."

Step 3. Define the Custom Component
Now, let's define the content of our custom component. Open the "WelcomeMessage.razor" file and replace its content with the following code.
@code {
    [Parameter] public string Name { get; set; } = "Guest";
}
<h3>Welcome, @Name!</h3>

In this code, we have a simple Razor component with a parameter named "Name." The parameter represents the name of the user to display in the welcome message. We've set a default value of "Guest" in case the name is not provided.

Step 4. Using the Custom Component

Now that we have our custom component defined let's use it in one of our existing Blazor pages. Open the "Index.razor" file located in the "Pages" folder and add the following line at the top of the file to import the "WelcomeMessage" component.
@page "/"

@using YourAppName.Components


Next, add the following code within the existing <div> tag in the "Index.razor" file:
<WelcomeMessage Name="Peter" />

This line of code will render the "WelcomeMessage" component with the name "Peter".

Step 5. Build and Run the Application

With the custom component in place, we can now build and run the application to see it in action. Press Ctrl + F5 or click the "Start Debugging" button in Visual Studio to build and run the application.
Once the application loads in your browser, you should see the welcome message, "Welcome, Peter!" If you don't see the name, check if you've correctly implemented the custom component.

How to Create Reusable Components?
One of the main benefits of using custom components in Blazor is the ability to create reusable UI elements. To create a reusable component, you can define it in a separate file and import it into other components as needed. Here's an example of a reusable component that displays a button.

Create a new component named as SubmitButton and add the below code.
<button class="@ButtonClass" @onclick="OnClick">@ButtonText</button>

@code {
    [Parameter]
    public string ButtonText { get; set; } = "Button";

    [Parameter]
    public string ButtonClass { get; set; } = "btn-primary";

    [Parameter]
    public EventCallback<MouseEventArgs> OnClick { get; set; }
}


This component takes three parameters: the button text, the button class, and a callback that is triggered when the button is clicked. The default values for the button text and class are set in the component, but they can be overridden when the component is used.

To use this component in your application, you can add the following code to a Razor page.
<SubmitButton ButtonText="Click Me" ButtonClass="btn-success" OnClick="HandleClick" />
@code {
    private async Task HandleClick(MouseEventArgs args)
    {
        // Handle the button click event
    }
}


This will render a button with the text "Click Me" and the class "btn-success". When the button is clicked, the HandleClick method will be called.

Conclusion

Custom components are a powerful feature of Blazor that allow developers to create reusable and modular UI elements. By creating custom components, developers can build complex web applications more efficiently and with greater flexibility. In this article, we explored how to create custom components in Blazor using examples. We hope this article has been helpful in understanding how to create custom components in Blazor.

HostForLIFE ASP.NET Core 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 Hosting - HostForLIFE :: ASP.NET Core Advanced APIs: Versioning, EF Core, and Middleware

clock April 7, 2025 10:15 by author Peter

My preferred framework for creating scalable web services is ASP.NET Core Web API. When creating scalable web services, I like to use the ASP.NET Core Web API. I can't wait to tell you about it. Using Entity Framework Core, Dependency Injection, API versioning, and a little extra code to log requests and responses, I'll walk you through how I created it in this tutorial.

We're looking at sophisticated concepts for developing APIs that expand as your program gets larger, so this won't be your typical beginner's assignment. Let's get started.

Step 1. Setting Up the Project
First, I fired up Visual Studio and created a new ASP.NET Core Web API project. Here’s how I did it.

  • Open Visual Studio and click on Create a new project.
  • I chose ASP.NET Core Web API and clicked Next.
  • Named the project EmployeeManagementAPI—you can name it whatever you like—and clicked Create.
  • I selected .NET 7.0 and hit Create.

Once Visual Studio had set up the basic project structure, I was ready to roll. Next, it was time to integrate Entity Framework Core so I could store and manage employee data in a database.

Step 2. Integrating Entity Framework Core

I needed to hook up a database to store employee records. For this, I went with Entity Framework Core because it’s super flexible and easy to work with.

Installing EF Core

First things first, I installed the required packages via Package Manager Console.
Install-Package Microsoft.EntityFrameworkCore.SqlServer
Install-Package Microsoft.EntityFrameworkCore.Tools


With that out of the way, I moved on to creating a DbContext to represent the database. I created a folder called Data and added a new class called EmployeeContext. Here’s the code I put in.
using Microsoft.EntityFrameworkCore;
using EmployeeManagementAPI.Models;

namespace EmployeeManagementAPI.Data
{
    public class EmployeeContext : DbContext
    {
        public EmployeeContext(DbContextOptions<EmployeeContext> options)
            : base(options)
        {
        }

        public DbSet<Employee> Employees { get; set; }
    }
}


Next, I needed an Employee model. In the Models folder, I added the Employee.cs class.
namespace EmployeeManagementAPI.Models
{
    public class Employee
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Department { get; set; }
        public decimal Salary { get; set; }
    }
}


Configuring the Database Connection
With the DbContext and model in place, I needed to configure the connection string. I added the connection string in appsettings.json like this.

"ConnectionStrings": {
  "EmployeeConnection": "Server=(localdb)\\mssqllocaldb;Database=EmployeeManagementDB;Trusted_Connection=True;"
}

Then, in Program.cs, I added the following line to register EmployeeContext with Dependency Injection.

builder.Services.AddDbContext<EmployeeContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("EmployeeConnection")));


Running Migrations
Finally, I created the database using EF Core migrations. Here’s what I did.

  • Add-Migration InitialCreate
  • Update-Database

This created the Employees table in the database. With the database ready, it was time to move on to the service layer.

Step 3. Building the Service Layer
Rather than dumping all the logic into the controller, I created a service layer to handle employee operations. This helps keep the code cleaner and easier to maintain.
Creating the Service Interface and Implementation

In the Services folder, I added an interface, IEmployeeService, and its implementation, EmployeeService. Here's what I came up with,

First, the interface.

public interface IEmployeeService
{
    Task<IEnumerable<Employee>> GetAllEmployeesAsync();
    Task<Employee> GetEmployeeByIdAsync(int id);
    Task AddEmployeeAsync(Employee employee);
    Task UpdateEmployeeAsync(Employee employee);
    Task DeleteEmployeeAsync(int id);
}


Then, I implemented the interface in EmployeeService.cs.

public class EmployeeService : IEmployeeService
{
    private readonly EmployeeContext _context;

    public EmployeeService(EmployeeContext context)
    {
        _context = context;
    }

    public async Task<IEnumerable<Employee>> GetAllEmployeesAsync()
    {
        return await _context.Employees.ToListAsync();
    }

    public async Task<Employee> GetEmployeeByIdAsync(int id)
    {
        return await _context.Employees.FindAsync(id);
    }

    public async Task AddEmployeeAsync(Employee employee)
    {
        _context.Employees.Add(employee);
        await _context.SaveChangesAsync();
    }

    public async Task UpdateEmployeeAsync(Employee employee)
    {
        _context.Entry(employee).State = EntityState.Modified;
        await _context.SaveChangesAsync();
    }

    public async Task DeleteEmployeeAsync(int id)
    {
        var employee = await _context.Employees.FindAsync(id);
        if (employee != null)
        {
            _context.Employees.Remove(employee);
            await _context.SaveChangesAsync();
        }
    }
}


Now, I needed to register this service in Program.cs so it could be injected into the controllers.

builder.Services.AddScoped<IEmployeeService, EmployeeService>();


Step 4. Building the Employee Controller
With the service layer ready, I moved on to the controller. In the Controllers folder, I created EmployeesController.cs.

[Route("api/[controller]")]
[ApiController]
public class EmployeesController : ControllerBase
{
    private readonly IEmployeeService _employeeService;

    public EmployeesController(IEmployeeService employeeService)
    {
        _employeeService = employeeService;
    }

    [HttpGet]
    public async Task<IActionResult> GetAllEmployees()
    {
        var employees = await _employeeService.GetAllEmployeesAsync();
        return Ok(employees);
    }

    [HttpGet("{id}")]
    public async Task<IActionResult> GetEmployeeById(int id)
    {
        var employee = await _employeeService.GetEmployeeByIdAsync(id);
        if (employee == null)
        {
            return NotFound();
        }
        return Ok(employee);
    }

    [HttpPost]
    public async Task<IActionResult> AddEmployee([FromBody] Employee employee)
    {
        await _employeeService.AddEmployeeAsync(employee);
        return CreatedAtAction(nameof(GetEmployeeById), new { id = employee.Id }, employee);
    }

    [HttpPut("{id}")]
    public async Task<IActionResult> UpdateEmployee(int id, [FromBody] Employee employee)
    {
        if (id != employee.Id)
        {
            return BadRequest();
        }
        await _employeeService.UpdateEmployeeAsync(employee);
        return NoContent();
    }

    [HttpDelete("{id}")]
    public async Task<IActionResult> DeleteEmployee(int id)
    {
        await _employeeService.DeleteEmployeeAsync(id);
        return NoContent();
    }
}


This controller was straightforward and tied everything together. I now had a fully functional API for managing employees.

Step 5. Adding API Versioning
As the API grew, I knew I’d need to implement API versioning to ensure backward compatibility. I installed the versioning package.
Install-Package Microsoft.AspNetCore.Mvc.Versioning


Next, I configured versioning in Program.cs.
builder.Services.AddApiVersioning(options =>
{
    options.AssumeDefaultVersionWhenUnspecified = true;
    options.DefaultApiVersion = new ApiVersion(1, 0);
    options.ReportApiVersions = true;
});


Now, I could version my controllers like this.

[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
[ApiController]
public class EmployeesV1Controller : ControllerBase
{
    // Version 1.0 controller code
}


Step 6. Custom Middleware for Logging
One thing I always like to do is log requests and responses, especially when working with APIs. So, I wrote some custom middleware to log incoming requests and outgoing responses.

Here’s what my middleware looked like.

public class RequestLoggingMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger<RequestLoggingMiddleware> _logger;

    public RequestLoggingMiddleware(RequestDelegate next, ILogger<RequestLoggingMiddleware> logger)
    {
        _next = next;
        _logger = logger;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        _logger.LogInformation($"Incoming request: {context.Request.Method} {context.Request.Path}");
        await _next(context);
        _logger.LogInformation($"Outgoing response: {context.Response.StatusCode}");
    }
}


Then, I registered this middleware in Program.cs.
app.UseMiddleware<RequestLoggingMiddleware>();

Now, every request and response was being logged, which made debugging much easier.

Conclusion

And there you have it—an advanced Employee Management API built with ASP.NET Core Web API. We covered a lot of ground, from integrating Entity Framework Core to creating a solid service layer, and even added some extra touches like API versioning and custom middleware.

This is the kind of architecture that scales well and keeps things organized. If you’ve made it this far, your API is in great shape for future growth.

Next Steps

  • Consider adding authentication and authorization to secure the API (I recommend using JWT).
  • Look into caching to improve performance, especially for frequently accessed data.
  • Write unit tests for your services and controllers to ensure your API behaves as expected.

Happy coding!

HostForLIFE ASP.NET Core 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 Hosting - HostForLIFE :: Using IOptions Pattern with Records in .NET 9.0

clock March 24, 2025 09:00 by author Peter

In modern .NET applications, effective configuration management is essential for ensuring flexibility and a clear separation of concerns. The IOptions<T> pattern is the preferred approach for injecting configuration settings into services. With .NET 9.0, records provide a concise and immutable way to represent configuration models. In this blog, we’ll explore how to utilize the IOptions<T> pattern efficiently with records.

Why Choose Records for Configuration?
Using records in C# for configuration settings offers several advantages:

  • Immutability: Prevents unintentional modifications to configuration values.
  • Value-based equality: Instances with identical values are treated as equal.
  • Concise syntax: Reduces boilerplate code compared to traditional classes.

Configuring Settings in .NET 9.0
Step 1. Create the Configuration Record
Rather than using a class, define a record to represent your configuration settings.
public record AppSettings
    {
       public const string SectionName = "AppSettings";
        public required string ApplicationName { get; init; }
        public required int MaxRequests { get; init; }
        public required LoggingSettings Logging { get; init; }
    }

    public record LoggingSettings
    {
        public required string LogLevel { get; init; }
    }
}


Step 2. Configure Settings in appsettings.json
Specify your configuration values within the appsettings.json file:

{
  "AllowedHosts": "*",
  "AppSettings": {
    "ApplicationName": "MyCoolApp",
    "MaxRequests": 100,
    "Logging": {
      "LogLevel": "Information"
    }
  }
}

Step 3. Register Configuration in Program.cs
Use the Configure method to bind the configuration to the record.
builder.Services.Configure<AppSettings>(builder.Configuration.GetSection(AppSettings.SectionName));

Step 4. Inject Configuration with IOptions<T>

Inject IOptions<AppSettings> into services, controllers, or components.
public class RecordService
{
   private readonly AppSettings _settings;

    public RecordService(
        IOptions<AppSettings> settings)
    {
        _settings = settings.Value;

    }

    public AppSettings GetAppSettingsAsync()
    {
        return  _settings;
    }
}

Step 5. Configure Service Registration
Register the service in Program.cs:
builder.Services.AddSingleton<RecordService>();

Step 6. Utilize the Service
Resolve the service and call its methods.

[Route("api/[controller]")]
[ApiController]
public class RecordsController : ControllerBase
{
    private readonly RecordService _recordService;

    public RecordsController(RecordService recordService)
    {
        _recordService = recordService;
    }


    [HttpGet]
    [Route("settings")]
    public IActionResult GetAppSettings()
    {
        return Ok(_recordService.GetAppSettingsAsync());
    }
}


Execute the Code
Execute the code and see the result for yourself.


  • Alternative: Using IOptionsSnapshot<T> and IOptionsMonitor<T>
  • IOptionsSnapshot<T>: Provides a scoped instance of options, making it useful for refreshing values between requests in a web application.
  • IOptionsMonitor<T>: Enables real-time configuration updates without requiring an application restart.

Conclusion
Leveraging records with the IOptions pattern in .NET 8.0 results in cleaner, immutable, and more efficient configuration management. Whether you use IOptions<T>, IOptionsSnapshot<T>, or IOptionsMonitor<T>, this approach fosters a well-organized and maintainable application.

Do you incorporate records for configuration in your .NET applications? Feel free to share your thoughts in the comments!

HostForLIFE ASP.NET Core 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 Hosting - HostForLIFE :: AI and.NET: Using.NET 9AI and.NET: Using.NET 9 to Create Intelligent Apps to Create Intelligent Apps

clock March 10, 2025 08:21 by author Peter

The way we create applications is evolving as a result of the convergence of artificial intelligence (AI) and contemporary software development. Microsoft continues to provide developers with tools and frameworks that make it simple to integrate AI capabilities into robust, scalable applications with the introduction of.NET 9.

We'll examine how.NET 9 facilitates AI-driven development in this post, with an emphasis on machine learning models and a demonstration of an intelligent sentiment analysis API project with sample code.

Why Develop AI with.NET 9?
Better performance, enhanced support for cloud-native apps, and an improved ecosystem that excels at AI workloads are just a few of the fantastic new features in.NET 9. It's an excellent option for creating intelligent, high-performance programs because of its extremely straightforward APIs, improved AOT (Ahead-of-Time) compilation, and improved container integration. Additionally, developers can include AI directly into their.NET solutions thanks to libraries like ML.NET and compatibility with well-known AI frameworks like TensorFlow and ONNX.

Setting the Stage: Tools and Prerequisites

To follow along, you’ll need,

  • Visual Studio or VS Code with .NET 9 SDK: Install the latest version from the official Microsoft site, for coding and debugging. I will be using VS Code for the demo project.
  • ML.NET: A machine learning framework for .NET (install via NuGet: Microsoft.ML).
  • A Basic Understanding of ASP.NET Core: For building the API.

Project Overview: Sentiment Analysis API

Let’s build a simple ASP.NET Core Web API that uses ML.NET to do sentiment analysis on text submitted by users. The API will predict if a text expresses positive or negative sentiment, which is a great starting point for AI-driven apps.

Step 1. Setting Up the Project
Create a new ASP.NET Core Web API project.
dotnet new webapi -n dotnet9SentimentApi -f net9.0
cd dotnet9SentimentApi

Open the folder in VS Code. The project should be as shown below.

Let’s add the ML.NET NuGet package.

You can either run the command or do it from VS code UI as illustrated below.

dotnet add package Microsoft.ML

Step 2. Define the Data Models
Create a folder named Models and add two classes: SentimentData and SentimentPrediction.

SentimentData.cs: Represents the input data for the model.
namespace dotnet9SentimentApi.Models;

public record SentimentData
{
    public string Text { get; set; } = string.Empty;
}


SentimentPrediction.cs: Represents the model’s output.
namespace dotnet9SentimentApi.Models;

public record SentimentPrediction
{
    public bool Prediction { get; set; } // True = Positive, False = Negative
    public float Probability { get; set; }
}

Step 3. Training a Simple Sentiment Model with ML.NET
For simplicity, we’ll use a pre-trained model approach here, but ML.NET allows you to train your own model with a dataset. Create a SentimentModelTrainer.cs class in a Services folder to simulate model setup:

To train the model with your own data.
private void TrainModel()
    {
        // Simulated training data (in practice, load from a file or database)
        var data = BuildTrainingData();

        var dataView = _mlContext.Data.LoadFromEnumerable(data);

        // Enhanced pipeline with text preprocessing
        var pipeline = _mlContext.Transforms.Text.FeaturizeText("Features", new Microsoft.ML.Transforms.Text.TextFeaturizingEstimator.Options
        {
            WordFeatureExtractor = new Microsoft.ML.Transforms.Text.WordBagEstimator.Options(),
            StopWordsRemoverOptions = new Microsoft.ML.Transforms.Text.StopWordsRemovingEstimator.Options()
        }, nameof(SentimentTrainingData.Text))
            .Append(_mlContext.BinaryClassification.Trainers.LbfgsLogisticRegression(labelColumnName: nameof(SentimentTrainingData.Sentiment)));

        // Train the model
        _model = pipeline.Fit(dataView);

        // Optional: Save the model for reuse
        _mlContext.Model.Save(_model, dataView.Schema, "sentiment_model.zip");
    }

Note. In a real-world scenario, you’d train with a larger dataset (e.g., from a CSV file) and save the model using _mlContext.Model.Save().

Complete SentimentModelTrainer.cs class

using System;
using dotnet9SentimentApi.Models;
using Microsoft.ML;

namespace dotnet9SentimentApi.Services;

public class SentimentModelTrainer
{
    private readonly MLContext _mlContext;
    private ITransformer _model;

    public SentimentModelTrainer()
    {
        _mlContext = new MLContext();
        TrainModel();

    }

    private void TrainModel()
    {
        // Simulated training data (in practice, load from a file or database)
        var data = BuildTrainingData();

        var dataView = _mlContext.Data.LoadFromEnumerable(data);
        // Enhanced pipeline with text preprocessing
        var pipeline = _mlContext.Transforms.Text.FeaturizeText("Features", new Microsoft.ML.Transforms.Text.TextFeaturizingEstimator.Options
        {
            WordFeatureExtractor = new Microsoft.ML.Transforms.Text.WordBagEstimator.Options(),
            StopWordsRemoverOptions = new Microsoft.ML.Transforms.Text.StopWordsRemovingEstimator.Options()
        }, nameof(SentimentTrainingData.Text))
            .Append(_mlContext.BinaryClassification.Trainers.LbfgsLogisticRegression(labelColumnName: nameof(SentimentTrainingData.Sentiment)));

        // Train the model
        _model = pipeline.Fit(dataView);

        // Optional: Save the model for reuse
        _mlContext.Model.Save(_model, dataView.Schema, "sentiment_model.zip");
    }

    public SentimentPrediction Predict(string text)
    {
        var predictionEngine = _mlContext.Model.CreatePredictionEngine<SentimentData, SentimentPrediction>(_model);
        return predictionEngine.Predict(new SentimentData { Text = text });
    }

    //build training data
    private List<SentimentTrainingData> BuildTrainingData()
    {
        return new List<SentimentTrainingData>
        {
            new() { Text = "I love this product!", Sentiment = true },
            new() { Text = "This is terrible.", Sentiment = false },
            new() { Text = "The weather is nice!", Sentiment = true },
            new() { Text = "Horrible service, never again.", Sentiment = false },
            new() { Text = "Absolutely fantastic experience!", Sentiment = true },
            new() { Text = "It’s a complete disaster.", Sentiment = false },
            new() { Text = "I’m so happy with this!", Sentiment = true },
            new() { Text = "Disappointing and awful.", Sentiment = false },
            new() { Text = "I’m so impressed!", Sentiment = true },
            new() { Text = "I’m never coming back.", Sentiment = false },
            new() { Text = "I’m so excited!", Sentiment = true },
            new() { Text = "I’m so disappointed.", Sentiment = false },
            new() { Text = "I’m so pleased with this!", Sentiment = true },
            new() { Text = "I’m so upset.", Sentiment = false },
            new() { Text = "I’m so satisfied with this!", Sentiment = true },
            new() { Text = "I’m so angry.", Sentiment = false },
            new() { Text = "I’m so grateful for this!", Sentiment = true },
            new() { Text = "I’m so annoyed.", Sentiment = false },
            new() { Text = "I’m so thankful for this!", Sentiment = true }
        };
    }

}
public record SentimentTrainingData
{
    public string Text { get; set; } = string.Empty;
    public bool Sentiment { get; set; }
}


Step 4. Build the API Controller
Create a SentimentController in the Controllers folder.
using dotnet9SentimentApi.Models;
using dotnet9SentimentApi.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace dotnet9SentimentApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class SentimentController : ControllerBase
    {
        private readonly SentimentModelTrainer _modelTrainer;

        public SentimentController(SentimentModelTrainer modelTrainer)
        {
            _modelTrainer = modelTrainer;
        }

        [HttpPost("analyze")]
        public ActionResult<SentimentPrediction> AnalyzeSentiment([FromBody] SentimentData input)
        {
            if (string.IsNullOrEmpty(input.Text))
                return BadRequest("Text cannot be empty.");

            var prediction = _modelTrainer.Predict(input.Text);
            return Ok(new { Sentiment = prediction.Prediction ? "Positive" : "Negative", Confidence = prediction.Probability });
        }
    }
}

Step 5. Register Services in the Program.cs
Update Program.cs to use minimal APIs and register the service.
// Add services to the container
builder.Services.AddControllers();
builder.Services.AddSingleton<SentimentModelTrainer>();

// Configure the HTTP request pipeline
app.UseHttpsRedirection();
app.MapControllers();

Complete the code for the Program.cs
using dotnet9SentimentApi.Services;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();

// Add services to the container
builder.Services.AddControllers();
builder.Services.AddSingleton<SentimentModelTrainer>();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.MapOpenApi();
}

// Configure the HTTP request pipeline
app.UseHttpsRedirection();
app.MapControllers();

app.Run();

Our solution is ready to test.

The folder structure looks as shown below.

Test the API
dotnet run

You can use Postman to test the API or HTTP file in VS Code. I will test using VS Code .http file.
@dotnet9SentimentApi_HostAddress = http://localhost:5288

# post analyze sentiment
POST {{dotnet9SentimentApi_HostAddress}}/api/sentiment/analyze
Content-Type: application/json

{
  "text": "I am not happy with the result!"
}

###

The result is shown below

The result is not as expected – indicates an issue with the sentiment analysis model’s training or configuration. Given the tiny dataset and simplistic setup in the original sample, the model isn’t learning meaningful patterns.

However, we can improve the result with more training data and testing.

Enhancing the Project
Scalability: Deploy to Azure with container support for cloud-native scaling.
Model Accuracy: Use a real dataset (e.g., IMDB reviews) and train with more sophisticated algorithms like FastTree.
Performance: Cache predictions for frequently analyzed text using MemoryCache.
Integration: Extend with Azure Cognitive Services or TensorFlow.NET for advanced AI capabilities.

HostForLIFE ASP.NET Core 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 Hosting - HostForLIFE :: Using Delegate Chaining in.NET to Create a Chain of Responsibility

clock March 6, 2025 06:46 by author Peter

One of the most underappreciated yet effective design patterns is the Chain of Responsibility, or CoR, pattern. Like ASP.NET Core middleware or HttpClient handlers, it enables us to create adaptable, extensible processing pipelines.

How .NET Uses Chain of Responsibility?

The CoR pattern is heavily used in .NET, especially in ASP.NET Core and HttpClient.

  • ASP.NET Core Middleware
    • Middleware components are chained together to process HTTP requests.
    • Each middleware can decide to process the request, pass it to the next middleware, or short-circuit the pipeline.
  • HttpClient Handlers
    • It uses a chain of HttpMessageHandler instances to process HTTP requests.
    • Each handler can modify the request, pass it to the next handler, or short-circuit the pipeline.
  • Validation Pipelines: Libraries like FluentValidation use a similar pattern to chain validation rules.

Delegate-Based CoR for Validation Rules
Instead of hardcoding validation logic, we dynamically add validation rules using delegate chaining.

Define the Delegate Pipeline with Short-Circuit support.

public class ValidationPipeline
{
    private Func<User, Task<bool>> _pipeline = user => Task.FromResult(true); // Default: Always passes
    public void AddRule(Func<User, Task<bool>> rule)
    {
        var previous = _pipeline;
        _pipeline = async user => await previous(user) && await rule(user); // Chain with AND condition
    }
    public async Task<bool> ValidateAsync(User user) => await _pipeline(user);
}


Dynamically Add Rules
Validate Pipeline
public class FeatureToggleService : IFeatureToggleService
{
    private readonly ValidationPipeline _validateRules;
    private readonly IFeatureManagerSnapshot _featureManager;
    public FeatureToggleService(IFeatureManagerSnapshot featureManager)
    {
        _validateRules = new ValidationPipeline();
        _featureManager = featureManager;
    }
    public async Task<bool> CanAccessFeatureAsync(User user)
    {
        _validateRules.AddRule(async user => await _featureManager.IsEnabledAsync("CustomGreeting"));
        _validateRules.AddRule(user => Task.FromResult(user.Role == "Amin"));
        _validateRules.AddRule(user => Task.FromResult(user.HasActiveSubscription));

        return await _validateRules.ValidateAsync(user);
    }
}
public interface IFeatureToggleService
{
    Task<bool> CanAccessFeatureAsync(User user);
}

How Can It Help?

  • Dynamic & Extensible: Add/remove rules without modifying existing logic.
  • Follows Open-Closed Principle (OCP): New rules can be added without modifying old code.
  • Composable: Chain rules like ASP.NET Core middleware.
  • Async-Support: Works well with async validation.  

HostForLIFE ASP.NET Core 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