Tuesday, 3 June 2025

ASP.NET Core Web API Login with MongoDB

Leave a Comment

 How to use MongoDB in.NET 8 to configure logging in an ASP.NET Core Web API. This comprehensive tutorial demonstrates how to use Serilog to record logs and store them in MongoDB, which facilitates error tracking, API behavior monitoring, and real-time application activity analysis.



One of the most crucial aspects of developing a practical application is logging. It assists you in tracking faults, keeping an eye on behavior, and comprehending the background operations of your application.

In this article, you’ll learn how to,

  • Set up a Web API in ASP.NET Core (.NET 8)
  • Use Serilog for logging
  • Store logs in MongoDB
  • View logs in MongoDB Compass

We’ll keep things simple but detailed so even beginners can follow along.

Prerequisites

Make sure you have these installed.

  • .NET 8 SDK
  • MongoDB
  • MongoDB Compass (optional, for viewing logs)
  • Basic knowledge of ASP.NET Core

Step 1. Create a New ASP.NET Core Web API Project.

Open your terminal and run.

dotnet new webapi -n LoggingWithMongo
cd LoggingWithMongo

This will create a sample Web API project.

Step 2. Install Required NuGet Packages.

We’ll use Serilog to handle logging, and a MongoDB sink to write logs to MongoDB.

Run these commands.

dotnet add package Serilog.AspNetCore
dotnet add package Serilog.Sinks.MongoDB

Step 3. Set Up Serilog in Program.cs.

Open Program.cs, and update it as follows.

1. Add the using statement.

using Serilog;

2. Configure Serilog Logging.

Add this before the builder.Build()

Log.Logger = new LoggerConfiguration()
    .WriteTo.Console()
    .WriteTo.MongoDB(
        "mongodb://localhost:27017/logs", // MongoDB connection string
        collectionName: "logEntries",     // MongoDB collection name
        cappedMaxSizeMb: 50               // Optional: limit collection size
    )
    .Enrich.FromLogContext()
    .CreateLogger();

builder.Host.UseSerilog();

Here’s the full updated Program.cs.

using Serilog;

var builder = WebApplication.CreateBuilder(args);

// Configure Serilog
Log.Logger = new LoggerConfiguration()
    .WriteTo.Console()
    .WriteTo.MongoDB(
        "mongodb://localhost:27017/logs", // Replace with your MongoDB connection string
        collectionName: "logEntries"
    )
    .Enrich.FromLogContext()
    .CreateLogger();

builder.Host.UseSerilog(); // Replace default logger

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

app.UseSwagger();
app.UseSwaggerUI();

app.UseAuthorization();

app.MapControllers();

app.Run();

Step 4. Add Logging to a Controller.

Let’s add some logging inside the default WeatherForecastController.

Open Controllers/WeatherForecastController.cs and update it like this.

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    private readonly ILogger<WeatherForecastController> _logger;

    public WeatherForecastController(ILogger<WeatherForecastController> logger)
    {
        _logger = logger;
    }

    [HttpGet(Name = "GetWeatherForecast")]
    public IEnumerable<WeatherForecast> Get()
    {
        _logger.LogInformation("Weather forecast requested at {Time}", DateTime.UtcNow);

        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = Summaries[Random.Shared.Next(Summaries.Length)]
        })
        .ToArray();
    }
}

This line.

_logger.LogInformation("Weather forecast requested at {Time}", DateTime.UtcNow);

will write a log entry each time the endpoint is called.

Step 5. Run the Application.

Use this command to start the app.

dotnet run

Now open your browser and go to,

https://localhost:5001/weatherforecast

Each time you refresh the page, a new log will be generated and saved to MongoDB.

Step 6. View Logs in MongoDB.

Open MongoDB Compass or use the Mongo shell.

In MongoDB Compass.

  • Connect to your server (mongodb://localhost:27017)
  • Open the database logs
  • Go to the logEntries collection

You’ll see documents like this.

{
  "_id": ObjectId("665d1739a92a511a28e4d341"),
  "Timestamp": "2025-06-03T14:00:00Z",
  "Level": "Information",
  "MessageTemplate": "Weather forecast requested at {Time}",
  "RenderedMessage": "Weather forecast requested at 6/3/2025 2:00:00 PM",
  "Properties": {
    "Time": "2025-06-03T14:00:00Z",
    "SourceContext": "LoggingWithMongo.Controllers.WeatherForecastController"
  }
}

You can use MongoDB queries to search, filter, or export logs.

Conclusion

Now your Web API logs are being saved in MongoDB! This is useful for,

  • Centralized log storage
  • Debugging issues
  • Monitoring app activity
  • Viewing logs from multiple servers

You can expand this by adding more structured data, custom enrichers, and log filtering.

Let me know if you’d like help adding things like,

  • Request/response logging
  • Error logging middleware
  • Logging user info or IP addresses

Happy coding!

ASP.NET Core 10.0 Hosting Recommendation

One of the most important things when choosing a good ASP.NET Core 10.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 HostForLIFE.eu 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, 27 May 2025

Comparing Two Images in .NET Core Using Bitmap

Leave a Comment

Create a.net core Console application in Visual Studio and install System.Drawing. The common library can be found in the NuGet Package Manager or the command line. In this post, we will compare two photos using the BitMap library in the dot net core application.

For the NuGet Package Manager Console, run the below command.

Install-Package System.Drawing.Common

For the .NET CLI command line, run the below command.

dotnet add package System.Drawing.Common

Basic image identification can be done with Hashing MD5 using the Cryptography library. For quick comparison generate a hash for each image and compare the image hashes and it will give the result.

Code Example

using System.Drawing;
using System.Security.Cryptography;

Console.WriteLine("Cryptography MD5 Quick Comparison ");
bool st= AreImagesIsIdentical(@"image1.PNG",@"image2.PNG");


Console.WriteLine("is Same image :" + st);
string GetImageHash(string imagePath)
{
    using (var md5 = MD5.Create())
    {
        using (var stream = new FileStream(imagePath, FileMode.Open))
        {
            var hash = md5.ComputeHash(stream);
            return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
        }
    }
}

 bool AreImagesIdentical(string imagePath1, string imagePath2)
{
    return GetImageHash(imagePath1) == GetImageHash(imagePath2);
}

Output

The bitmap library will help to compare pixels in the images. For comparing the pixel values of the two images, the code example is below.

using System.Drawing;

Console.WriteLine("Pixel Comparison ");
bool st= AreImagesIsIdentical(@"image1.PNG",@"image2.PNG");

bool AreImagesIsIdentical(string imagePath1, string imagePath2)
{
    using (Bitmap bmp1 = new Bitmap(imagePath1))
    using (Bitmap bmp2 = new Bitmap(imagePath2))
    {
        if (bmp1.Width != bmp2.Width || bmp1.Height != bmp2.Height)
        {
            return false;
        }

        for (int y = 0; y < bmp1.Height; y++)
        {
            for (int x = 0; x < bmp1.Width; x++)
            {
                if (bmp1.GetPixel(x, y) != bmp2.GetPixel(x, y))
                {
                    return false;
                }
            }
        }
    }
    return true;
}

Output

 

Best ASP.NET Core 10.0 Hosting Recommendation

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

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

Thursday, 22 May 2025

Best & Cheap ASP.NET Core 10.0 Hosting in Europe

Leave a Comment
Recently, many of our readers have e-mailed us asking about the hosting quality of HostForLIFEASP.NET. Therefore, to present the detailed information about this company, we have done a comprehensive and in-depth review of HostForLIFEASP.NET hosting service, which helps our readers find out whether this is a good hosting provider or not. Note that the final result is based on our real hosting experience with this company that is 100% objective and worth considering.

Best & Cheap ASP.NET Core 10.0 Hosting in Europe

Before presenting the detailed review, we’d like to insert an editorial rating chart that is based on price, features, page loading speed, reliability, technical support, and industry reputation, with which readers can have an overall impression about the hosting service of this company.

https://hostforlifeasp.net
Moreover, if there is anything wrong, customers can cancel the service, and ask their full money within the first 30 days, according to HostForLIFEASP.NET’s 30 Days Money Back Guarantee. HostForLIFEASP.NET is Microsoft No #1 Recommended Windows and ASP.NET Hosting in European Continent. Their service is ranked the highest top #1 spot in several European countries, such as: Germany, Italy, Netherlands, France, Belgium, United Kingdom,Sweden, Finland, Switzerland and many top European countries.

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

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


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

Plesk Control Panel

HostForLIFE revolutionized hosting with Plesk Control Panel, a Web-based interface that provides customers with 24x7 access to their server and site configuration tools. Some other hosting providers manually execute configuration requests, which can take days. Plesk completes requests in seconds.

Some other hosting providers manually execute configuration requests, which can take days. Plesk completes requests in seconds. It is included free with each hosting account. Renowned for its comprehensive functionality - beyond other hosting control panels - and ease of use, Plesk Control Panel is available only to HostForLIFE's customers.

Trust HostForLIFEASP.NET to Protect Your Data

It goes without saying that your data is important to you, and they take that premise very seriously - they do everything they can to keep your data safe. They’ve implemented a revolutionary custom in-house backup system, allowing them to create an entire backup ecosystem. They remotely backup your data across multiple datacenters every night, giving you the ability to restore precious data in an instant.



Recommended Customer Support

HostForLIFEASP.NET offers Europe based customer support via an email ticketing system and helpdesk. Support is available to HostForLIFEASP.NET customers 24/7 who have a question or problem with their web hosting account. From our experience, their customer support is professional, friendly and very helpful. They hired an army of the very best technicians, managers and web hosting gurus. That means clear, professional support, fast. Their team are standing by to respond to your queries around the clock, big or small, and they’ll be there for you - 24x7, 365 days a year. You can contact them via all standard communication channels - by e-mail, through the ticketing system, or via an online form - should you have any pre-sales questions.

Reliability and Stability Guaranteed

HostForLIFEASP.NET dedicated to being more than just another ASP.NET Core 10.0 hosting provider in Europe. Combining industry-best practices and staff with cutting-edge knowledge and expertise, they provide the stability and reliability you need to realize success in today's modern world.

Their single focus concern is providing your websites with the utmost in terms of reliability and stability. To that end, they have built an industry-leading web hosting platform featuring the best of modern technology and industry practices.

Conclusion - Best ASP.NET Core 10.0 Hosting in Europe !

HostForLIFEASP.NET provides one of the Best ASP.NET Core 10.0 Hosting in Europe! for its affordable price, rich feature, professional customer support, and high reliability. It’s highly recommended for asp.net developers, business owners and anyone who plan to build a web site based on ASP.NET Core 10.0. 
hostforlife.eu/European-ASPNET-Core-2-Hosting
Read More...

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