Tuesday, 13 May 2025

C# Developers Can Create, Run, and Debug Apps with Visual Studio Code

Leave a Comment

 Developers are urged to switch to other tools as Microsoft plans to remove Visual Studio for Mac on August 31, 2024. For C# programming on macOS, Visual Studio Code (VS Code) and the C# Dev Kit provide a stable, cross-platform environment.

So, given that this is our step-by-step approach.

  • Setting up VS Code for C# development
  • Creating and running a simple C# console application
  • Check if we can debug within VS Code

Prerequisites

Ensure the following are installed on your system.

  1. .NET SDK: Download and install the latest .NET SDK from the .NET official website.
  2. Visual Studio Code: Install VS Code from the official website.
  3. C# Extension for VS Code: Install the C# extension by Microsoft:
    • Open VS Code.
    • Navigate to the Extensions view by clicking on the Extensions icon in the Activity Bar on the left side of the window.
    • Search for "C#" and install the extension provided by Microsoft.

VS Code Extensions view highlighting the C# extension.

Create a new C# Console Application

Step 1. Open Terminal

Launch a terminal window from your preferred working location. This can be your home directory or any project folder you like to work in.

Step 2. Navigate to Your Workspace

Move to your favorite place for coding projects.

cd /Users/rikam/Projects

Step 3. Create a New Folder and Initialize the Project

Use the following commands to create a new directory for your app and generate a basic C# console application.

mkdir Leetcode
cd Leetcode
dotnet new console

This will scaffold a new project with a Program.cs file and required project configuration (.csproj file).

To open your C# project in Visual Studio Code from the terminal, use this command.

  • code: This is the command to launch VS Code.
  • This tells VS Code to open the current directory (your project folder).
code .

If the code command is not recognized

You might need to install the code command in your shell.

Use the Menu Bar

You can access the Command Palette manually.

  • Click on View in the top menu bar.
  • Select Command Palette, then type and select: "Shell Command: Install 'code' command in PATH"

Command Palette with "Shell Command: Install 'code' command in PATH" highlighted.

Now, you can open any folder in VS Code using the (code .) command

Let's write some C#

Open Program.cs: In the Explorer view, open the Program.cs file, and let's add a simple function to print numbers. We are initializing an array of five integers and printing each to the console.

void PrintNumbers()
{
    int[] numbers = { 10, 20, 30, 40, 50 };
    foreach (int number in numbers)
    {
        Console.WriteLine(number);
    }
    Console.WriteLine("Press any key to exit...");
    Console.ReadKey();
}
PrintNumbers();
Run the App

Build and Run

// Building the app
dotnet build

// Running the app
dotnet run

The console should display.

10
20
30
40
50

Debugging the Application

Step 1. Add a Breakpoint

Click in the gutter to the left of the line Console.WriteLine(number) to add a breakpoint.

The Red dot is a breakpoint set on line 6.

Step 2. Start Debugging

Press F5 or navigate to Run > Start Debugging. VS Code may prompt you to select the environment for your project. For a C# app, you'll choose ( .NET or .NET Core, depending on your version )

After this selection, VS Code automatically generates a .vscode/launch.json file in your project folder. This file contains configuration instructions that tell VS Code how to build and run your app.

launch.json

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    "version": "0.2.0",
    "configurations": [
        {
            "name": ".NET Core Launch (console)",
            "type": "coreclr",
            "request": "launch",
            "preLaunchTask": "build",
            "program": "${workspaceFolder}/bin/Debug/net8.0/Leetcode.dll",
            "args": [],
            "cwd": "${workspaceFolder}",
            "console": "internalConsole",
            "stopAtEntry": false
        },
        {
            "name": ".NET Core Attach",
            "type": "coreclr",
            "request": "attach"
        }
    ]
}

Next, the debugger will start, and execution will pause at the breakpoint.

Inspect Variables

  • Use the Debug pane to inspect the value of the number and other variables.
  • Use the Step Over (F10) and Step Into (F11) commands to navigate through the code.

Conclusion

Transitioning from Visual Studio to Visual Studio Code ensures continued support and access to modern development tools for C#. With the C# extension, VS Code provides a streamlined environment for building and debugging .NET applications.

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, 6 May 2025

Using the Aspire Dashboard for observability

Leave a Comment

It is becoming more and more important to comprehend what's going on behind the scenes as applications develop into distributed systems made up of microservices, background processes, APIs, and frontend apps. Observability enters the picture at this point. In traditional monolithic applications, debugging often involves adding logs, checking error messages, or attaching a debugger. However, this approach falls short in a distributed environment, where services communicate across processes or networks.

Observability is not just about logs. It’s about having the right data (logs, metrics, traces) and the right tools to connect the dots across your system.

With .NET Aspire, observability is a first-class citizen. Out of the box, Aspire enables.

  • Centralized monitoring of all your registered services and apps
  • Real-time streaming of logs from all your processes
  • Request tracing to follow the path of a request across services
  • Visual insights into endpoints, ports, health, and metrics

All of this is surfaced through the Aspire Dashboard, a UI that automatically launches when you run your AppHost project. No extra setup. No complex configurations.

This chapter will guide you through exploring the Aspire Dashboard and making the most of its observability features, starting with understanding the layout and moving on to practical debugging workflows.

The Aspire Dashboard: Your Observability Cockpit

The Aspire Dashboard is a powerful, real-time UI that launches automatically when you run your .NET Aspire AppHost project. It provides a unified view of all the services registered in your distributed application — making it your go-to observability cockpit.

How to Launch the Dashboard?

If you’ve configured your solution using the .NET Aspire project templates and you're running the AppHost project, the dashboard will open automatically in your default browser.

Dashboard Layout Overview

The dashboard is cleanly divided into tabs, each designed to give insights into different aspects of your application:

1. Resources Tab
  • Shows all services registered via AddProject<>, AddContainer<>, etc.
  • Lists resource names like api, myweatherapp, etc.
  • Displays their current status (Running, Stopped)
  • Provides quick actions like:
    • Viewing Swagger UI (for APIs)
    • Previewing web apps
    • Navigating to configured endpoints

2. Console Tab
  • Streams stdout logs from all running services in real-time
  • Useful during debugging to view console output, exceptions, or custom log messages
  • Supports basic text search and filtering.

3. Structured Tab
  • Displays logs in a structured, queryable format
  • Helps you drill down into specific log events across services
  • Supports rich filters like severity, time range, and resource source

4. Traces Tab
  • Shows distributed tracing data (requires OpenTelemetry setup)
  • Visualizes the journey of a request across multiple services
  • Useful for identifying slowdowns, bottlenecks, and dependencies

5. Metrics Tab
  • Tracks key performance metrics like.
    • CPU usage
    • Memory consumption
    • Request counts and durations
  • Offers charts and graphs for real-time visibility

The Aspire Dashboard is more than just a service viewer it's your developer control center, letting you,

  • See what’s running and healthy
  • Follow logs in real-time
  • Analyze structured logs and traces
  • Monitor performance metrics
Understanding the Aspire Dashboard Architecture

The .NET Aspire Dashboard is not just a UI layer it’s a lightweight diagnostic tool built into your distributed application’s lifecycle.

Architecture Breakdown
  • Hosted as a .NET Worker Service inside your AppHost project.
  • It uses gRPC for communication between the dashboard backend and instrumentation clients (your services).
  • Relies on the .NET Aspire diagnostics infrastructure to gather:
    • Logs
    • Metrics
    • Distributed traces
    • Health data

Here’s a simplified flow of how it works.

Dashboard Security Model

The Aspire Dashboard is designed for developer use only in local environments. Here's what you should know.

Access Control

  • No authentication or authorization by default
  • Exposed on localhost only
  • Do NOT expose it in production

Port Binding

  • Default port: 18888
  • Accessible only on localhost

Security Recommendations

If you need remote access (not recommended in production)

  • Use SSH tunneling (e.g., SSH -L 18888:localhost:18888 user@host)
  • Consider reverse proxy + auth (e.g., NGINX)
  • Use container isolation if running inside the Docker
Behind the Scenes: Telemetry in .NET Aspire

.NET Aspire integrates powerful telemetry capabilities out of the box. Whether you're building APIs, background workers, or full-blown microservices, Aspire automatically enables diagnostics across your services.

What Telemetry Includes?

When you run your application using the AppHost project, Aspire injects telemetry collectors that gather.

  • Logs: Real-time log streams from your services
  • Metrics: CPU, memory, request counts, latency, error rates, and more
  • Traces: Distributed traces for cross-service calls (HTTP, gRPC, etc.)
  • Health Probes: Basic up/down service checks

These diagnostics are funneled to the Aspire Dashboard without any extra configuration.

How Telemetry is Collected?

Internally, .NET Aspire uses OpenTelemetry, an open standard for distributed tracing and metrics collection. Here’s a simplified telemetry flow.

All of this happens via automatic wiring no need to explicitly configure OpenTelemetry unless you want to customize things.

Extending Telemetry

While Aspire gives you a solid default setup, you can extend or override its behavior.

  • Add custom loggers like Serilog or Seq
  • Export telemetry to external APM tools (like Azure Monitor, Grafana, or Jaeger)
  • Define custom metrics for business logic

Sample: Exporting to Console

builder.Services.AddOpenTelemetry()
    .WithMetrics(metrics => metrics.AddConsoleExporter())
    .WithTracing(tracing => tracing.AddConsoleExporter());

This uses the OpenTelemetry.Extensions.Hosting package and the standard OpenTelemetry .NET API, both of which are stable and production-ready.

Required NuGet Packages

To use this in your Aspire services, make sure to install it.

dotnet add package OpenTelemetry.Extensions.Hosting
dotnet add package OpenTelemetry.Exporter.Console

Where to Use It?

You can place this snippet in any service project (e.g., your API or Worker service) inside Program.cs.

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddOpenTelemetry()
    .WithMetrics(metrics => metrics.AddConsoleExporter())
    .WithTracing(tracing => tracing.AddConsoleExporter());

This setup.

  • Exports logs and metrics to the console
  • Is useful for debugging and local dev insights
  • Complements the Aspire Dashboard’s built-in observability

Use Case: Debugging Performance

Imagine a slow API response. With Aspire telemetry, you can:

  1. Check the trace tab to see if downstream services caused delays.
  2. Look at the metrics tab to spot CPU/memory spikes.
  3. View logs in real-time across all services from the Dashboard console.

Dashboard Themes in .NET Aspire

To enhance the user experience, the Aspire Dashboard includes built-in support for theming. This allows developers to choose how the dashboard appears visually — based on personal preference or development environment conditions.

Available Theme Modes

The Aspire Dashboard currently supports the following three visual themes.

  1. System Theme (Default)
    • This theme adapts automatically to your operating system’s light/dark setting.
    • Ideal for users who prefer consistent UI across all their tools and apps.
    • Example: If your OS is in dark mode, the dashboard switches to dark too.
  2. Light Theme
    • A clean, high-contrast theme ideal for brightly lit environments.
    • Useful when presenting on projectors or during daylight development sessions.
    • Offers maximum readability with dark text on light backgrounds.
  3. Dark Theme
    • A developer-favourite theme that reduces eye strain in low-light conditions.
    • Complements IDEs and tools that also use dark themes (like VS Code or Rider).
    • Reduces screen glare and power usage on OLED displays.
Why do Themes Matter in Observability?

Although seemingly cosmetic, theming can impact productivity and comfort. For long debugging or observability sessions, selecting the right theme can:

  • Minimize visual fatigue
  • Improve focus on logs, traces, and metrics
  • Match your development setup for visual consistency

Theme Selection Experience

You can toggle the theme from the dashboard UI itself.

  • Look for the theme selector dropdown (typically in the top-right corner).
  • Your selected theme is remembered locally between sessions.

There's no code configuration required theming is fully user-controlled through the dashboard interface.

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, 29 April 2025

You Need to Know 9 Things About the New Lambda Variance Rules of C#

Leave a Comment

In C#, lambda expressions have long been a potent tool for creating code that is expressive, adaptable, and compact. However, up until now, there was little and occasionally unclear variation in lambda expressions the flexible relationship between argument and return types. With improved lambda variance rules introduced in C# 14, lambdas become safer, more logical, and more consistent with generic delegate behaviors.

Writing more reusable and reliable code can be achieved by comprehending these variance enhancements, whether you're creating functional pipelines, developing APIs, or integrating third-party libraries. We go over the nine most crucial details of the new lambda variance mechanism in C# in this set of infographics.

 

Conclusion
The new lambda variance rules in C# 14 close long-standing gaps and open new doors for generic, flexible programming patterns. These rules make it easier to pass lambdas where previously delegates wouldn’t match—especially with base and derived types—boosting both type safety and developer happiness.

If you're serious about writing modern C# code, this is one update you don’t want to overlook. Dive into these concepts now, and you’ll gain a sharper understanding of type variance, generic lambdas, and how C# continues to evolve to support cleaner, smarter code.

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...

Wednesday, 23 April 2025

List All Power Automate Cloud Flows Programmatically

Leave a Comment

When a cloud flow is part of a solution in Power Automate, it gets stored in Microsoft Dataverse as a type of record in the workflow table.

Using either

  • Dataverse SDK for .NET: for C# developers, or
  • Dataverse Web API: for RESTful access via HTTP,
Use the Dataverse SDK in C#/.NET

Step 1. Create a new .NET console app project. For this project, we are using Visual Studio 2022 and targeting .NET 6.

Step 2. In Solution Explorer, right-click the project you created and select Manage NuGet Packages... in the context menu.


Step 3.
 Browse for the latest version of Microsoft.PowerPlatform.Dataverse.Client NuGet package and install it.

Step 4. Add the below code in program.cs file

using Microsoft.Crm.Sdk.Messages;
using Microsoft.PowerPlatform.Dataverse.Client;
using Microsoft.Xrm.Sdk;

class Program
{
   // TODO Enter your Dataverse environment's URL and logon info.
   static string url = "https://yourorg.crm.dynamics.com";  // Replace your Power Platform Environment Url from https://admin.powerplatform.microsoft.com
   static string userName = "[email protected]"; // Power Platform User Login Id
   static string password = "yourPassword"; // Power Platform user password

   // This service connection string uses the info provided above.
   // The AppId and RedirectUri are provided for sample code testing.
   static string connectionString = $@"AuthType=OAuth;Url={url};UserName={userName};Password= {password};AppId=51f81489-12ee-4a9e-aaae-a2591f45987d;RedirectUri=app://58145B91-0C36-4500-8554-080854F2AC97;LoginPrompt=Auto;RequireNewInstance=True";

   static void Main()
   {
    //ServiceClient implements IOrganizationService interface
    IOrganizationService service = new ServiceClient(connectionString);
    OutputActiveFlows(service);

    // Pause the console so it does not close.
    Console.WriteLine("Press the <Enter> key to exit.");
    Console.ReadLine();
   }
   public static void OutputActiveFlows(IOrganizationService service)
   {
     var query = new QueryExpression("workflow")
     {
         ColumnSet = new ColumnSet("category",
                                   "createdby",
                                   "createdon",
                                   "description",
                                   "ismanaged",
                                   "modifiedby",
                                   "modifiedon",
                                   "name",
                                   "ownerid",
                                   "statecode",
                                   "type",
                                   "workflowid",
                                   "workflowidunique"),
         Criteria = new FilterExpression(LogicalOperator.And)
         {
             Conditions =
             {
              { new ConditionExpression("category",ConditionOperator.Equal,5) }, // Cloud Flow
              { new ConditionExpression("statecode",ConditionOperator.Equal,1) } // Active
             }
         },
         //TopCount = 1 // Limit to one record
     };

     EntityCollection workflows = service.RetrieveMultiple(query);

     //Entity workflow = workflows.Entities.FirstOrDefault();
     foreach (var workflow in workflows.Entities)
     {
         Console.WriteLine($"category: {workflow.FormattedValues["category"]}");
         Console.WriteLine($"createdby: {workflow.FormattedValues["createdby"]}");
         Console.WriteLine($"createdon: {workflow.FormattedValues["createdon"]}");
         // Description may be null
         Console.WriteLine($"description: {workflow.GetAttributeValue<string>("description")}");
         Console.WriteLine($"ismanaged: {workflow.FormattedValues["ismanaged"]}");
         Console.WriteLine($"modifiedby: {workflow.FormattedValues["modifiedby"]}");
         Console.WriteLine($"modifiedon: {workflow.FormattedValues["modifiedon"]}");
         Console.WriteLine($"name: {workflow["name"]}");
         Console.WriteLine($"ownerid: {workflow.FormattedValues["ownerid"]}");
         Console.WriteLine($"statecode: {workflow.FormattedValues["statecode"]}");
         Console.WriteLine($"type: {workflow.FormattedValues["type"]}");
         Console.WriteLine($"workflowid: {workflow["workflowid"]}");
         Console.WriteLine($"workflowidunique: {workflow["workflowidunique"]}");
     }

 }
}

Sample Output

category: Modern Flow
createdby: SYSTEM
createdon: 5/20/2020 9:37 PM
description:
ismanaged: Unmanaged
modifiedby: Kiana Anderson
modifiedon: 5/6/2023 3:37 AM
name: When an account is updated -> Create a new record
ownerid: Monica Thomson
statecode: Activated
type: Definition
workflowid: d9e875bf-1c9b-ea11-a811-000d3a122b89
workflowidunique: c17af45c-10a1-43ca-b816-d9cc352718cf

Note. Only flows inside Solutions are accessible this way—not personal flows in the "My Flows" section.

Conclusion

Managing Power Automate cloud flows through code gives developers and IT teams powerful tools to automate, secure, and scale their operations. Whether you prefer the structured approach of the .NET SDK or the flexibility of REST APIs, you can perform critical tasks—like listing, deleting, sharing, and exporting flows—without ever opening the Power Automate UI.

We will see Create, Update, and Delete operations for cloud flows in my next Article.

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...

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...