Sunday, 20 April 2025

Advanced Configuration in .NET Core

Leave a Comment

 

1. Configuration Providers

.NET Core supports many configuration sources.


  • appsettings.json
  • appsettings.{Environment}.json
  • Environment variables
  • Command-line arguments
  • User Secrets
  • Azure Key Vault
var builder = WebApplication.CreateBuilder(args);

builder.Configuration
    .AddJsonFile("appsettings.json")
    .AddJsonFile(
        $"appsettings.{builder.Environment.EnvironmentName}.json",
        optional: true
    )
    .AddEnvironmentVariables()
    .AddCommandLine(args);
2. Strongly Typed Configuration

Map configuration to C# classes using the IOptions pattern.

// appsettings.json
{
  "MySettings": {
    "SiteTitle": "My App",
    "MaxItems": 10
  }
}
public class MySettings
{
    public string SiteTitle { get; set; }
    public int MaxItems { get; set; }
}
builder.Services.Configure<MySettings>(
    builder.Configuration.GetSection("MySettings")
);
public class HomeController : Controller
{
    private readonly MySettings _settings;
    public HomeController(IOptions<MySettings> options)
    {
        _settings = options.Value;
    }
}
3. Validate Options at Startup
builder.Services
    .AddOptions<MySettings>()
    .Bind(builder.Configuration.GetSection("MySettings"))
    .Validate(settings => settings.MaxItems > 0, "MaxItems must be > 0");
4. Reloading Config on Changes

Enable hot reload for appsettings.json.

builder.Configuration
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);

Use IOptionsSnapshot<T> to get updated config per request.

5. Secret Management

Use User Secrets for local development.

dotnet user-secrets init
dotnet user-secrets set "MySettings:ApiKey" "123456"
builder.Configuration
       .AddUserSecrets<Program>();
6. Azure Key Vault Integration
builder.Configuration.AddAzureKeyVault(
    new Uri("https://yourvault.vault.azure.net/"),
    new DefaultAzureCredential());

Make sure your app is registered and granted access to the vault.

7. Custom Configuration Provider

You can create a custom provider for things like databases or external services.

  • Inherit from ConfigurationProvider and ConfigurationSource
  • Inject it into the builder with the Add method

Points to consider

  • Use IConfiguration for raw access to values
  • Use IOptions for dependency injection & structured data
  • Store secrets outside of source-controlled files
  • Group related settings into sections

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

Tuesday, 15 April 2025

RadioButtonList Control Overview

Leave a Comment

In this walk-through, you will learn about RadioButtonList in detail, and you get answers of the following questions.

  1. What is RadioButtonList?
  2. How many Layout types?
  3. Which Layout is good to use?
  4. Generate a RadioButtonList with the following:
    1. List Collection Object C#
    2. Database Table data
    3. Manually ListItem
  5. Working Suggestion with RadioButtonList.
 

What is RadioButtonList?

RadioButtonList is a Form-Control of Standard section under the Asp.Net WebForms project template. Naming conventions for RadioButtonList is rbl. Using naming conventions helps you find objects on an aspx page very smartly and easily.

RadioButtonList render a group of Radio-Buttons by using data-source, manually added list-item. RadioButtonList allows users to select only one option (Radio -Button) from a list.

RadioButtonList Layout Types

RepeatDirection: Set rendering direction on browser. There are two types.

  • Horizontal
  • Vertical

RepeatLayout: Support the following types of layout.

  • Flow: Normal rendering.
  • OrderedList: This will display options with 1,2,3,4,5 numbering.
  • Table: Under Table layout.
  • UnorderedList: This will display a bulleted list •.
Which Layout is good to use?
  • Table: For perfect alignment and view. This will render using HTML tags.
  • Flow: It is very lightweight, and Custom CSS can be applied for beautification and alignment as per your current design.

Right Combination of RepeatDirection and RepeatLayout.

SR. NO. RepeatDirection RepeatLayout Remarks
1 Horizontal Flow Working fine.
2 Horizontal OrderedList Not Working, Error Message:
The UnorderedList and OrderedList layouts only support vertical layout.
3 Horizontal Table Working fine.
4 Horizontal UnorderedList Not Working, Error Message:
The UnorderedList and OrderedList layouts only support vertical layout.
5 Vertical Flow Working fine.
6 Vertical OrderedList Working fine.
7 Vertical Table Working fine.
8 Vertical UnorderedList Working fine.

Generate a RadioButtonList with the following.

1. List Collection Object C# to generate RadioButtonList

ASPX Page Code

<div style="border:1px solid black;width:50%;">
    <h2>Hardcoded Radiobutton List using C# List Collection Object</h2>
    <hr />

    <asp:RadioButtonList
        ID="rblListObj"
        runat="server"
        onClick="HardCodeRbl()"
        ClientIDMode="Static">
    </asp:RadioButtonList>

    <br /><br />

    <span id="lblListObj" style="font:20px arial;"></span>
</div>

C# Code

// Create a list of fruits
List<string> fruits = new List<string>
{
    "Apple",
    "Banana",
    "Cherry",
    "Mango",
    "Orange",
    "Pineapple",
    "Strawberry"
};
rblListObj.DataSource = fruits;
rblListObj.DataBind();

JavaScript Code

<script>
    function HardCodeRbl() {
        var selected = "";

        // Read Hardcoded RadioButton List
        var rbl = document.getElementById("rblListObj");

        // Get all input elements
        var inputs = rbl.getElementsByTagName('input');
        var flag = false;

        for (var i = 0; i < inputs.length; i++) {
            if (inputs[i].checked) {
                selected = inputs[i];
                flag = true;
                break;
            }
        }

        // Check if a selection was made
        if (flag) {
            alert(selected.value);
            document.getElementById("lblListObj").innerHTML =
                "HardCoded List Collection Object Radiobutton List <br>Selected: <b>" + selected.value + "</b>";
        } else {
            alert('Please select an option.!');
            return false;
        }
    }
</script>

Output


2. Database Table data used to generate RadioButtonList
ASPX Page Code
<div style="border:2px solid green; width:50%; margin-top:50px;">
    <h2>Database Table used to populate Radiobutton List</h2>
    <hr />

    <asp:RadioButtonList
        ID="rblTableBase"
        runat="server"
        onClick="TableBaseRbl()"
        ClientIDMode="Static">
    </asp:RadioButtonList>

    <br /><br />

    <span id="lblTableBase" style="font:20px arial;"></span>
</div>
C# Code
// Database Table used to populate Radiobutton List
BindSportsList();

// BindSportsList Method
private void BindSportsList()
{
    // Database connection string
    string connStr = ConfigurationManager.ConnectionStrings["dbTestConstr"].ConnectionString;

    using (SqlConnection conn = new SqlConnection(connStr))
    {
        conn.Open();
        SqlCommand cmd = new SqlCommand("SELECT SportID, SportName FROM tblSports", conn);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);

        rblTableBase.DataSource = dt;
        rblTableBase.DataTextField = "SportName";
        rblTableBase.DataValueField = "SportID";
        rblTableBase.DataBind();
    }
}
Javascript Code
<script>
    function TableBaseRbl() {
        var selected = "";
        var selectedText = "";

        // Read Hardcoded RadioButton List
        var rbl = document.getElementById("rblTableBase");

        // Get all input elements
        var inputs = rbl.getElementsByTagName('input');
        var flag = false;

        for (var i = 0; i < inputs.length; i++) {
            if (inputs[i].checked) {
                selected = inputs[i];
                selectedText = document.querySelector("label[for='" + inputs[i].id + "']").innerText;
                flag = true;
                break;
            }
        }

        // Check if a selection was made
        if (flag) {
            alert(selected.value);
            document.getElementById("lblTableBase").innerHTML =
                "Tablebase Radiobutton List Selected: <b>" + selected.value + " ----- " + selectedText + "</b>";
        } else {
            alert('Please select an option.!');
            return false;
        }
    }
</script>

OUTPUT

3. Manually ListItem added to generated RadioButtonList

ASPX Page Code

<div style="border:2px solid red; width:50%; margin-top:50px;">
    <h2>Manually Added ListItem to populate Radiobutton List</h2>
    <hr />

    <asp:RadioButtonList
        ID="rblListItemManually"
        runat="server"
        onClick="rblListItem()"
        ClientIDMode="Static"
        RepeatDirection="Vertical"
        RepeatLayout="UnorderedList">

        <asp:ListItem Text="Bougainvillea" Value="1" />
        <asp:ListItem Text="Petunia" Value="2" />
        <asp:ListItem Text="Zinnia" Value="3" />
        <asp:ListItem Text="Sunflower" Value="4" />
        <asp:ListItem Text="Daffodil" Value="5" />
        <asp:ListItem Text="Lotus" Value="6" />

    </asp:RadioButtonList>

    <br /><br />

    <span id="lblListItem" style="font:20px arial;"></span>
</div>

NO C# Code Wirtten

Javascript Code

<script>
    function rblListItem() {
        var selected = "";
        var selectedText = "";

        // Read Hardcoded RadioButton List
        var rbl = document.getElementById("rblListItemManually");

        // Get all input elements
        var inputs = rbl.getElementsByTagName('input');
        var flag = false;

        for (var i = 0; i < inputs.length; i++) {
            if (inputs[i].checked) {
                selected = inputs[i];
                selectedText = document.querySelector("label[for='" + inputs[i].id + "']").innerText;
                flag = true;
                break;
            }
        }

        // Check if a selection was made
        if (flag) {
            alert(selected.value);
            document.getElementById("lblListItem").innerHTML =
                "Manually Added ListItem Radiobutton List Selected: <b>" + selected.value + " ----- " + selectedText + "</b>";
        } else {
            alert('Please select an option.!');
            return false;
        }
    }
</script>

OUTPUT

Working Suggestion with RadioButtonList

1. Use CLientIDMode = “Static”. This will not generate a dynamic id of RadioButtonList control. This will help you use id easily in Javascript.

ClientIDMode="Static"

Note: The above settings are recommended for all Form-Controls.

2. Use Javascript for the event and get the selected value of the Radio Button. Try to use Maximum Javascript because this will reduce the server roundtrip and help to run the application faster.

3. For handling server-side events, you have to use the following settings.

  • AutoPostBack="true"
  • OnSelectedIndexChanged event method.

Happy Coding!

Best ASP.NET Core 9 Hosting Recommendation

One of the most important things when choosing a good ASP.NET Core 9 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...

Tuesday, 8 April 2025

Unit Test Web API CRUD operations with the NUnit Testing Framework

Leave a Comment

A key component of software development is unit testing, which is examining individual code units—usually functions or methods—to make sure they operate as intended. You can use a variety of testing frameworks to write unit tests in C#, such as:



NUnit: A well-liked.NET testing framework with an intuitive API and an extensive feature set.
Another popular testing framework that provides a more contemporary and adaptable method of unit testing is xUnit.

Unit testing in C# can be made more effective and dependable by using libraries like Moq or NSubstitute to isolate dependencies and construct mock objects.

NUnit is a popular, open-source unit testing framework for C# and other .NET languages, initially ported from JUnit, used for writing and executing automated tests to ensure code quality.

Here, we are implementing basic CRUD operation in web API using C#, and then we are enlisting the different test cases for all those operations and writing a code to test those scenarios using the NUnit framework.

Pre-requisite

1. Open VS 2022

2. Create a Web API project


 3. Add NUnit Test Project


 4. Install required packages from NuGet Package


Core Features of NUnit

NUnit framework has extensive tools for streamlining unit testing, including accurate code verification, logical test design, and broad test coverage. Let's look at three crucial aspects for building good tests.

NUnit Test Lifestyle Attributes

  • [Test Fixture]: is a class or function that has the [TestFixture] attribute, which indicates that it contains tests.
  • [SetUp]: This method initializes resources.
  • [Test]: It contains the test logic.
  • [TearDown]: It assures cleanup after each test.

Now, list down all possible test case scenarios w.r.t the web API and create a test method for each of them.


In each test method, we need to follow the 3A pattern of the NUnit Framework i.e. AAA[Arrange-Act-Assert]. It is a common way to structure unit tests to make them more readable and organized.

  • Arrange: Set up everything needed for the test—objects, variables, mock data, etc.
  • Act: Perform the actual action that you want to test.
  • Assert: Verify that the outcome is what you expected.


Once we have done coding on all possible scenarios, then we can run the NUnit project by executing the “Run All Test” option.

We can run all test cases at a single time, and for complex test cases, we can also debug at a breakpoint by opting for “Debug All Tests”.

On running all test cases, a Test Explorer will open a listing of all test methods as a monitoring window, which depicts the result of all test cases.

If any scenario doesn’t meet the required criteria or expected results, then it will be indicated in the test explorer in red color with the reasonable issue and its possible solution.

In this article, we've explored the key features of NUnit testing, from understanding the basics of unit testing to setting up and using the NUnit framework for your.NET unit testing applications. You may efficiently validate your code by learning how to build simple unit tests, leverage test assertions, and arrange them with test fixtures.

NUnit's adaptability makes it a powerful tool for unit testing in software engineering, whether concentrating on isolated components or complicated situations. Using NUnit testing tools and rigorous testing techniques can lead to high-quality, bug-free code in your apps.

Best ASP.NET Core 9 Hosting Recommendation

One of the most important things when choosing a good ASP.NET Core 9 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...

Tuesday, 25 March 2025

ASP.NET Hosting Tutorial: Knowing SQL System-Versioned Tables

Leave a Comment

One aspect of SQL that enables automatic tracking of data changes over time is system-versioned tables. In order to facilitate auditing changes and retrieving historical data, these tables aid in maintaining history versions of records.

How Do Tables With System Versions Operate?
The components of a system-versioned table are

Current data is stored in the main table.
History table: Maintains records from the past automatically.

Making a Table with System Versions
The SQL script that follows generates a history table and a system-versioned table called Employees.

CREATE TABLE Employees (
    EmployeeID INT PRIMARY KEY,
    Name NVARCHAR(100),
    Position NVARCHAR(100),
    Salary DECIMAL(10, 2),
    ValidFrom DATETIME2 GENERATED ALWAYS AS ROW START HIDDEN NOT NULL,
    ValidTo DATETIME2 GENERATED ALWAYS AS ROW END HIDDEN NOT NULL,
    PERIOD FOR SYSTEM_TIME (ValidFrom, ValidTo)
)
WITH (
    SYSTEM_VERSIONING = ON (
        HISTORY_TABLE = dbo.EmployeesHistory
    )
);

Querying System-Versioned Tables

Get Current Data

SELECT *
FROM Employees;

Get Historical Data

SELECT *
FROM EmployeesHistory;

Retrieve Data at a Specific Time

SELECT *
FROM Employees
FOR SYSTEM_TIME AS OF '2024-03-01T10:00:00';

Advantages of System-Versioned Tables

  • Automatically tracks data changes.
  • Provides historical auditing without manual tracking.
  • Allows time-travel queries to retrieve past data states.
  • Ensures data integrity and compliance with regulatory requirements.

System-versioned tables are highly beneficial for applications that require auditing, data recovery, and change tracking. 

Best ASP.NET Core 9 Hosting Recommendation

One of the most important things when choosing a good ASP.NET Core 9 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...

Tuesday, 18 March 2025

The Object Oriented Programming in ASP.NET

Leave a Comment
The scalability and reusability of the code are enhanced by object-oriented programming, or OOP. Class and objects make up this. This is an example of object-oriented programming utilizing the C# language for traffic management.
 

Object

Any entity that has a state and behavior is known as an object. It can be defined as the Instance of the Class.

Class

The collection of objects is known as Class. It can also be defined as Blue Print from which you can Create the Objects.

The Object Oriented Programming contains the following four concepts.

  • Encapsulation
  • Abstraction
  • Inheritance
  • Polymorphism

1. Encapsulation

Wrapping of code and data in to signle unit is known as Encapsulation. Here in the Traffic Signal Management Concept the Encapsulation is used for Managing Traffic Signal State.

Encapsulation ensures traffic signals change safely without external interference.

Example

public class TrafficSignal
{
    private string signalColor;

    public void ChangeSignal(string color)
    {
        if (color == "Red" || color == "Green" || color == "Yellow")
        {
            signalColor = color;
            Console.WriteLine($"Signal changed to {signalColor}");
        }
        else
        {
            Console.WriteLine("Invalid signal color.");
        }
    }

    public string GetSignalColor()
    {
        return signalColor;
    }
}

2. Abstraction

Here in the Traffic Signal Management Concept the Abstraction is used for Controlling Road Barriers.

Abstraction hides complex logic behind simplified interfaces.

Example

public abstract class RoadBarrier
{
    public abstract void Operate();
}

public class TollGate : RoadBarrier
{
    public override void Operate()
    {
        Console.WriteLine("Toll gate is opening for the vehicle.");
    }
}

3. Inheritance

Here in the Traffic Signal Management Concept, the Inheritance is used for Specialized Traffic Lanes.

Inheritance helps define specialized behavior for different vehicle types.

Example

public class TrafficLane
{
    public void AllowVehicles()
    {
        Console.WriteLine("General vehicles are allowed.");
    }
}

public class EmergencyLane : TrafficLane
{
    public void AllowAmbulance()
    {
        Console.WriteLine("Ambulance is given priority in the emergency lane.");
    }
}

4. Polymorphism

Here in Traffic Signal Management Concept Polymorphism is used for Dynamic Traffic Control.

Polymorphism enables dynamic behavior changes.

Example

public class TrafficController
{
    public virtual void ControlTraffic()
    {
        Console.WriteLine("Managing normal traffic flow.");
    }
}

public class SmartTrafficController : TrafficController
{
    public override void ControlTraffic()
    {
        Console.WriteLine("Adjusting traffic lights dynamically based on congestion.");
    }
}

5. Main Program Execution

Below, we can see the usage of All OOp Concept.

Example

class Program
{
    static void Main()
    {
        // Calling of Encapsulation Example.
        TrafficSignal signal = new TrafficSignal();
        signal.ChangeSignal("Green");
        Console.WriteLine($"Current Signal: {signal.GetSignalColor()}");

        // Calling of Abstraction Example
        RoadBarrier toll = new TollGate();
        toll.Operate();

        // Calling of Inheritance Example
        EmergencyLane lane = new EmergencyLane();
        lane.AllowVehicles();
        lane.AllowAmbulance();

        // Calling of Polymorphism Example
        TrafficController controller = new SmartTrafficController();
        controller.ControlTraffic();
    }
}

Sample Output for Traffic Management System.

  • Signal changed to Green
  • Current Signal: Green
  • A toll gate is opened for the vehicle.
  • General vehicles are allowed.
  • Ambulance is given priority in the emergency lane.
  • Adjusting traffic lights dynamically based on congestion.
Conclusion
  • This Traffic Management System uniquely showcases OOP principles in C#. Encapsulation secures signal data, abstraction simplifies road barriers, inheritance enables specialized lanes, and polymorphism allows adaptive traffic control.
  • Using OOP effectively leads to well-structured, scalable applications in real-world scenarios.

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