Meet The Author

I'm Ethan Jackson, An 25 years old blogger Currently living in London, United Kingdom. I'm a Skilled Blogger, Part Time web Developer And Creating new things as a web Designer.

author

SQL Server Integration in Aspire Applications: .NET Aspire Integrations

Leave a Comment

Databases, caches, message brokers, APIs, telemetry systems, and other supporting technologies are all essential to modern cloud-native applications. Writing business logic is only one aspect of creating such an application; another is carefully connecting these services in a scalable, observable, and maintainable manner. By providing a strong application model that makes it simple for developers to create, set up, and maintain service dependencies,.NET Aspire reduces this complexity.

What do Aspire Integrations bring to the Table?

When you add an integration to an Aspire project, you get.

  • Typed configuration and DI setup: Auto-wiring of client libraries with configuration via strongly typed options.
  • Health checks: Automatic inclusion of health checks for critical dependencies.
  • Connection string propagation: Seamless sharing of connection strings across projects using Aspire's service discovery.
  • Dashboard visibility: Integrated resources are visible and traceable through the Aspire Dashboard.
  • Simplified Dev Experience: You don’t have to manually set up service bindings or write boilerplate configuration.

These integrations promote a cloud-native design, while also making local development and testing smoother and more predictable.

Common Integrations in .NET Aspire

.NET Aspire comes with official and community-supported packages that make integrating third-party services a breeze. Below is a curated list of popular tools and services across different categories that work seamlessly with Aspire.

Databases
Service Integration Package Notes
SQL Server Aspire.Hosting.SqlServer Connection string, health check, and discovery are handled automatically.
PostgreSQL Microsoft.Extensions.Hosting.PostgreSql Community-supported; connection string injection.
MySQL Microsoft.Extensions.Hosting.MySql Similar benefits to PostgreSQL.

Caching & Data Store
Service Integration Package Notes
Redis Microsoft.Extensions.Caching.StackExchangeRedis.Aspire Adds Redis as a resource, injects connection string, auto configures.
MongoDB MongoDB.Driver.Aspire (community) Mongo client setup via Aspire DI.

Messaging & Eventing
Service Integration Package Notes
RabbitMQ Tye.Hosting.RabbitMQ.Aspire (community) Easy messaging setup.
Azure Service Bus Microsoft.Azure.ServiceBus.Aspire (planned) Advanced integration expected in future releases.

Observability & Monitoring
Tool Integration Package Notes
OpenTelemetry Microsoft.Extensions.Telemetry.Aspire Auto-wires tracing/metrics.
Grafana + Prometheus Community Templates Can export Aspire metrics here.

External Services & APIs
Type Example Aspire Support Notes
HTTP APIs REST, GraphQL, gRPC APIs Use .WithEndpoint() to define upstream APIs.
Cloud SDKs Azure, AWS Aspire config + DI bindings are supported manually.

.NET Aspire SQL Server integration

Let’s see in action how to get an Aspire Integrations with SQL Server.

When building distributed applications, a database is often a critical component.

.NET Aspire simplifies integrating SQL Server into your project by providing first-class support through its Aspire.Hosting.SqlServer package.

This integration focuses on,

  • Spinning up SQL Server instances (locally or containerized) during development.
  • Managing connection strings automatically.
  • Sharing database endpoints across your application components.
  • Adding health checks for SQL Server availability.
  • Visualizing the SQL Server resource in the Aspire Dashboard.
Setting Up SQL Server Integration

Step 1. Install the SQL Server Aspire Package.

In your AppHost project, run.

dotnet add package Aspire.Hosting.SqlServer

Or simply visit to manage NuGet Packages and “Aspire.Hosting.SQLServer” in App Host.


This package brings in the AddSqlServer extension method that makes adding SQL easy.

Step 2.
Define the SQL Server Resource.
In your Program.cs inside the AppHost project.

SQL Server Resource

Here is what this code does.

  1. Define a parameter for the SQL Server password.
    IResourceBuilder<ParameterResource>? dbPassword =
        builder.AddParameter("dbPassword", true);

Key Points in This Setup

  • AddParameter("dbPassword", true): Securely prompts for the database password if it's not already configured.
  • AddSqlServer("sql", dbPassword, 1455): Adds a SQL Server resource running on custom port 1455 and uses the provided password.
  • .WithLifetime(ContainerLifetime.Persistent): Ensures the SQL Server container persists between runs.
  • AddDatabase("database"): Defines a database inside SQL Server for use by the application.
  • .WithReference(db) and .WithReference(MyAPI): Links services together by passing resources like connection strings automatically.

Step 3. Configure Parameters Securely.

Instead of hardcoding sensitive information like database passwords in your code, Aspire encourages you to use Parameters.

In your appsettings.json, define the SQL Server password under the Parameters section.

  • dbPassword is injected at runtime into the SQL Server resource.
  • You can also override it using environment variables or secret managers for production.
  • This keeps your applications secure, configurable, and environment-agnostic.

Important. If the “dbPassword” is not found in your settings or environment, Aspire will prompt you to enter it at startup (because of the true flag in AddParameter("dbPassword", true)).

Pro Tip. Managing Sensitive Parameters in .NET Aspire Applications.

  • Never hardcode secrets like passwords directly in code files.
  • Prefer appsettings.json for local development, but move to secret managers like Azure Key Vault or environment variables in production.
  • Use AddParameter with isSecret: true to ensure Aspire handles the value securely, and prompts when missing.
  • Do not commit real secrets into your source control repositories (e.g., GitHub).
  • Leverage dotnet user-secrets for development.
    dotnet user-secrets set "Parameters:dbPassword" "YourSecurePassword"
  • Configure deployment environments to provide required parameters securely during CI/CD pipeline runs.
Aspire Dashboard View

When you run the application, the Aspire Dashboard will show your SQL Server alongside your services, making the architecture and dependencies crystal clear.

Example

[SQL Server] <--- connected to ---> [Web API]
Aspire Dashboard View

When you run the application, the Aspire Dashboard will show your SQL Server alongside your services, making the architecture and dependencies crystal clear.

Example

[SQL Server] <--- connected to ---> [Web API]
SQL

Step 1. SQL Server and Database Creation Verification.

  • Open your application in the Aspire Dashboard (localhost:17010).
  • In the Resources tab, you will see a list of services.
  • Notice two services.
    • SQL (SQL Server): Running state with the source pointing to mcr.microsoft.com/mssql/server2022-latest.
    • Database: Running state.

  • These were automatically created based on the definitions provided in your Program.cs file.
  • The SQL Server service is configured to expose on tcp://localhost:1455, as per the given port number.

Step 2. Verifying API Environment Variables

  • In the Aspire Dashboard, under Resources, locate the API service.
  • Click the three dots (...) next to the API service.
  • Select View details from the dropdown menu.

Step 3. Checking the Database Connection String.

  • In the Project: API details view, scroll to the Environment Variables section.
  • Look for the environment variable named: ConnectionStrings__database.
  • You will find the database connection string, such as Server=127.0.0.1,1455;User ID=sa;Password=Nit1n5QL;
  • This confirms that the API service has the database connection string injected correctly through environment variables.

Step 4. Aspire Action Reflected in Docker (Local).

You can see the side effects of Aspire's local work in Docker Desktop.

  • Images: An image mcr.microsoft.com/mssql/server:2022-latest is pulled into Docker.
  • Containers: A container sql-xxx is running, exposing the SQL Server on port 1455.

Result: Aspire used Docker to spin up the local SQL server dynamically for your app.

Area Action by Aspire Result Seen Where
Database Server SQL Server container created on port 1455 Docker Desktop (Containers tab)
Database Resource Database initialization or setup done Aspire Dashboard - Resources
API Env Setup Database connection string injected automatically Aspire Dashboard - API - Environment Variables
Docker Image MSSQL Image pulled if not present Docker Desktop (Images tab)

Debugging the Connection String: Verify reading the environment variables

Let’s try reading the Connection string from the environment variables, As we have added the reference of SQL Server database to the Weather API Project from App host with Aspire Hosting.

To do that I have added a code to read the connection string from application configuration variables with the name “database” in my API Controller’s Get method “GetWeatherForecast”:

Run the solution and open API swagger to hit the API End Point for debugging the code with a breakpoint on the same line.

You can see the connection string is available for the API Project from the application configurations even though we don’t have any local parameter the name of “database”.

Here is the connection string we got.

Server=127.0.0.1,1455;User ID=sa;Password=Nit1n5QL;TrustServerCertificate=true;Initial Catalog=database

Testing in SSMS

If you want you can use the same connection string in the SQL Server Management Studio to check this Database and its table, which may help you inthe future.

Paste the same connection String in the last tab “Additional Connection Parameters” and hit connect.

I am sure you must be able to see the connected Server and Database in SSMS’s Object Explorer.

Why Use SQL Server Integration with Aspire?
Benefit Description
Fast Setup No manual container configuration is needed.
Secure Connection Management Credentials and connection strings are injected safely.
Automatic Health Monitoring Built-in health checks for SQL Server connectivity.
Easy Switching Easily swap local dev SQL Server with Azure SQL for production.

Similarly, you can use Aspire Immigrations for Databases and other tools.

Windows Hosting Recommendation

HostForLIFEASP.NET receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 7.0.10 , ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/
Read More

A Brief Introduction to SignalR in.Net Core

Leave a Comment

These days, people expect apps to updates in real-time like live chats, notifications, or game scores, without refreshing the page again and again. SignalR in .NET Core helps you do just that by making real-time communication easy. In this blog, we’ll quickly show you how to get started with it in your own .NET Core project.

SignalR: What is it?

Microsoft created the SignalR real-time messaging library, which enables two-way communication between clients—such as desktop programs, mobile apps, or web browsers—and the server. Adding real-time functionality to your web apps is simple and scalable, allowing users to get updates and notifications quickly without requiring manual requests or page refreshes.

Usages of SignalR

Here are some common use cases where SignalR can be a great fit for adding real-time functionality to your applications.

  • Chat Applications: SignalR is perfect for building mid-level chat applications where users can exchange messages instantly. It supports sending messages to all users, specific groups, or individual users in real-time. For a higher-level chatting application, XMPP or WebSocket is the best option.
  • Notifications: You can use SignalR to push real-time notifications to users for events such as new messages, system alerts, or order updates without making them refresh the page.
  • Live Dashboards: For use cases like monitoring systems or admin panels, SignalR enables real-time dashboards that automatically refresh as data changes, helping users make quick decisions.
  • Online Exams or Quizzes: SignalR can be used in online test platforms to push time updates or instant results to participants during live sessions.
  • Live Polls and Q&A: Apps that conduct live polls or Q&A during webinars or events can benefit from SignalR by showing real-time responses and updates to all viewers instantly.
  • Collaboration Tools: SignalR is again helpful in mid-level collaborative apps where multiple users need to work together in real-time—like document editing, whiteboards, or project tracking tools.
How to use in an ASP.NET Core project?

To use in a .NET Core project, you have to install the SignalR NuGet package. Run the below command from NuGet Package Manager or PowerShell

# .NET CLI
dotnet add package Microsoft.AspNet.SignalR

# Nuget Package Manager
NuGet\Install-Package Microsoft.AspNet.SignalR
Bash

Now you have to create a Hub. Let's say we are building a chatbot using SignalR; hence, we are creating a chat hub. This hub will handle the server-side logic for sending messages.

// ChatHub.cs
using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;
public class ChatHub : Hub
{
    public async Task SendMessage(string user, string message)
    {
        await Clients.All.SendAsync("ReceiveMessage", user, message);
    }
}

Next, we have to register ChatHub in the program.cs file so that it can initialize at the time of starting.

// program.cs

var builder = WebApplication.CreateBuilder(args);

// Register services
builder.Services.AddRazorPages();
builder.Services.AddSignalR(); // Register SignalR

var app = builder.Build();

// Configure middleware
app.UseStaticFiles();
app.UseRouting();

// Map endpoints
app.MapRazorPages();
app.MapHub<ChatHub>("/chathub"); // Map Chathub with an endpoint

app.Run();
How to use in Front-end projects?

As our backend code is reday. Now let's use this in the frontend. Either you can use CDN script of SignalR or npm package of SignalR in case of Angular, React, or Next JS like below.

Using CDN

<!-- CDN for SignalR -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/7.0.5/signalr.min.js"></script>

<script>
    // Setting up the endpoint
    const connection = new signalR.HubConnectionBuilder()
        .withUrl("/chathub")
        .build();

    connection.on("ReceiveMessage", (user, message) => {
        const msg = `${user} - ${message}`;
        const li = document.createElement("li");
        li.textContent = msg;
        document.getElementById("messagesList").appendChild(li);
    });

    connection.start()
        .catch(err => console.error(err.toString()));

    document.getElementById("sendButton").addEventListener("click", () => {
        const user = document.getElementById("userInput").value;
        const message = document.getElementById("messageInput").value;

        connection.invoke("SendMessage", user, message)
            .catch(err => console.error(err.toString()));
    });
</script>
Using an NPM package in Angular

To use in Angular, you have to install the SignalR npm package

npm install @microsoft/signalr

Then have to create a service for the communication.

/* signalr.service.ts */

import { Injectable } from '@angular/core';
import * as signalR from '@microsoft/signalr';

@Injectable({
  providedIn: 'root'
})
export class SignalrService {
  private hubConnection: signalR.HubConnection;
  public messages: string[] = [];

  public startConnection(): void {
    this.hubConnection = new signalR.HubConnectionBuilder()
      .withUrl('http://localhost:5000/chathub') // URL to be fetched from environment config
      .build();

    this.hubConnection
      .start()
      .then(() => console.log('Connection started'))
      .catch(err => console.log('Error while starting connection: ' + err));

    this.hubConnection.on('ReceiveMessage', (user: string, message: string) => {
      this.messages.push(`${user}: ${message}`);
    });
  }

  public sendMessage(user: string, message: string): void {
    this.hubConnection.invoke('SendMessage', user, message)
      .catch(err => console.error(err));
  }
}

And now it's time to consume this service from a component.

/* app.component.ts */
/* In the blog app.component has been used. In actual project, please create a new component and register */

import { Component, OnInit } from '@angular/core';
import { SignalrService } from './signalr.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
})
export class AppComponent implements OnInit {
  user = '';
  message = '';

  constructor(public signalRService: SignalrService) {}

  ngOnInit(): void {
    this.signalRService.startConnection();
  }

  sendMessage(): void {
    this.signalRService.sendMessage(this.user, this.message);
    this.message = '';
  }
}

In the HTML, place the text box & div to view the messages.

<!-- app.component.html -->

<div>
  <input [(ngModel)]="user" placeholder="Your name" />
  <input [(ngModel)]="message" placeholder="Message" />
  <button (click)="sendMessage()">Send</button>

  <ul>
    <li *ngFor="let msg of signalRService.messages">
      {{ msg }}
    </li>
  </ul>
</div>
Architectural components of SignalR

Now, as you know how to use SignalR, let's also deep dive into the architectural components of SignalR. Here are the main parts that make up the SignalR setup.

  • Hubs: A Hub is a central part of SignalR that manages communication between the server and connected clients. It takes care of handling connections, sending messages, and converting data formats. With Hubs, clients can call server-side methods, and the server can also call methods on the clients.
  • Clients: Clients are applications or devices, such as browsers or mobile apps, that connect to the SignalR server to exchange real-time messages. Using the SignalR client library, these clients can easily send messages to the server and receive updates without delay.
  • Transports: SignalR uses different methods, called transports, to create and maintain the connection between the client and the server. These include WebSockets, Server-Sent Events (SSE), Long Polling, and Forever Frame, depending on what the client and server support.
  • Connections: A connection refers to the link between a single client and the SignalR server. Each connection has a unique ID that keeps track of the client and sends messages to the right one.
  • SignalR Server: The SignalR server handles all the communication between clients. It manages connections, routes messages to the right clients, and controls the flow of data through the pipeline.

Windows Hosting Recommendation

HostForLIFEASP.NET receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 7.0.10 , ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/

 

Read More

What is Interlocked In .NET?

Leave a Comment

In multithreaded applications, multiple threads can access and modify shared variables concurrently. This can lead to race conditions. The System.Threading.Interlocked class provides atomic operations on variables, ensuring thread safety without using locks.


Common Use Cases

  • Counters (Increment/Decrement)
  • Flags (Boolean states)
  • Exchange operations
  • Compare-and-swap (CAS)

Why Use Interlocked?

  • Atomic operations: Guaranteed to complete without interruption
  • Lightweight: Faster than locking mechanisms
  • Lock-free: Reduces the chance of deadlocks

Thread-Safe Counter Example
using System;
using System.Threading;

class Program
{
    private static int counter = 0;

    static void Main()
    {
        Thread[] threads = new Thread[10];

        for (int i = 0; i < threads.Length; i++)
        {
            threads[i] = new Thread(() =>
            {
                for (int j = 0; j < 1000; j++)
                {
                    Interlocked.Increment(ref counter);
                }
            });
            threads[i].Start();
        }

        foreach (var t in threads) t.Join();

        Console.WriteLine($"Final counter value: {counter}");
    }
}


Methods in Interlocked

  • Interlocked.Increment(ref int location)
  • Interlocked.Decrement(ref int location)
  • Interlocked.Add(ref int location, int value)
  • Interlocked.Exchange(ref T location, T value)
  • Interlocked.CompareExchange(ref T location, T value, T comparand)

Thread-Safe Flag Example (Boolean)
Booleans aren't directly supported by Interlocked, but you can simulate them using integers:
private static int isRunning = 0;

if (Interlocked.CompareExchange(ref isRunning, 1, 0) == 0)
{
    try
    {
        // Do work
    }
    finally
    {
        Interlocked.Exchange(ref isRunning, 0);
    }
}


Summary
Interlocked is ideal for low-level concurrency control. Best for simple shared variable updates. Use it when you want lock-free synchronization. For complex data structures, prefer lock or concurrent collections.

Windows Hosting Recommendation

HostForLIFEASP.NET receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 7.0.10 , ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/
Read More

What's New in C# 14 and ASP.NET Core 10?

Leave a Comment

C# 14 introduces several powerful language features focused on performance, flexibility, and developer convenience.

 

Here are the key updates:

Implicit Span Conversions

C# 14 offers first-class support for the System.Span<T> and System.ReadOnlySpan<T>. These types are designed for high-performance, memory-safe manipulation of contiguous data. C# 14 introduces implicit conversions between.

  • T[ ] → Span<T>
  • T[ ] → ReadOnlySpan<T>
  • Span<T> → ReadOnlySpan<T>

This means you can now write APIs that accept spans and call them with arrays, reducing the need for explicit casts and avoiding unnecessary allocations.

void Print(ReadOnlySpan<char> data)
{
    foreach (var ch in data)
        Console.Write(ch);
    Console.WriteLine();
}

char[] buffer = { 'H', 'e', 'l', 'l', 'o' };
// Implicitly converts char[] to ReadOnlySpan<char>
Print(buffer);

Benefits

  • Zero allocations
  • Type safety
  • Improved performance for memory-intensive operations
Unbound Generic Types in the nameof

Before C# 14, you could only use closed generic types with nameof, such as nameof(List<int>). With C# 14, you can now reference unbound generics in the nameof, enabling cleaner and more flexible metadata or logging scenarios.

Console.WriteLine(nameof(Dictionary<,>));
Console.WriteLine(nameof(List<>));

Output

  • Dictionary
  • List
Simple Lambda Parameters with Modifiers

C# 14 allows you to use modifiers like ref, out, in, scoped, and ref readonly in lambda parameters, even without specifying the type. Previously, you had to provide full-type declarations to use modifiers.

delegate bool TryParse<T>(string text, out T result);
private static void LambdaParameterModifiersExample()
{
  TryParse<int> tryParse = (text, out result) => int.TryParse(text, out result);

  if (tryParse("123", out var num))
  Console.WriteLine($"Parsed: {num}");
  else
  Console.WriteLine("Failed to parse");
}
C#

Benefits

  • Cleaner syntax
  • Better support for modern API design
  • Enhanced lambda expressiveness

.NET 10 Library Enhancements

.NET 10 introduces powerful enhancements to its base-class libraries. Here's a breakdown of the most impactful additions.

Finding Certificates by Thumbprint (SHA-2 & SHA-3)

Before .NET 10: Only SHA-1 hash thumbprints were supported, limiting security standards. Now, you can use secure hashing algorithms like SHA-256 or SHA-3 directly.

X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);

string thumbprint = "ABCD1234...";
X509Certificate2Collection certs = store.Certificates.FindByThumbprint(HashAlgorithmName.SHA256, thumbprint);

if (certs.Count == 1)
{
    Console.WriteLine("Certificate found: " + certs[0].Subject);
}

Benefits: Stronger certificate validation in secure systems.

Improved PEM File Parsing (UTF-8)

Initially, manual encoding conversion was needed to read UTF-8 PEM files. Now, Native support for UTF-8 parsing simplifies the process.

byte[] pemData = File.ReadAllBytes("key.pem");
PemFields pemFields = PemEncoding.FindUtf8(pemData);
string label = Encoding.UTF8.GetString(pemData[pemFields.Label]);
byte[] keyData = Convert.FromBase64String(Encoding.UTF8.GetString(pemData[pemFields.Base64Data]));

Benefits: Faster, cleaner handling of standard security file formats.

Numeric String Comparison

Earlier, strings sorted lexically, so "File10" came before "File2". Now, natural numeric ordering is built-in.

var versions = new[] { "File1", "File10", "File2" };
Array.Sort(versions, StringComparer.Create(CultureInfo.InvariantCulture, CompareOptions.NumericString));

Console.WriteLine(string.Join(", ", versions)); // File1, File2, File10

Benefits: Sorting UI lists, filenames, and version numbers.

TimeSpan.FromMilliseconds Overloads

Earlier, Ambiguity with LINQ and long arrays. Now, cleaner LINQ integration.

long[] delays = { 200, 400, 800 };
var spans = delays.Select(TimeSpan.FromMilliseconds);

foreach (var span in spans)
    Console.WriteLine(span);

Benefits: Simplifies time-related functional code.

OrderedDictionary Enhancements

Earlier, limited index handling APIs. Now, you can update values directly using index-aware methods.

var counts = new OrderedDictionary<string, int>();
if (!counts.TryAdd("bananas", 1, out int idx))
{
    counts.SetAt(idx, counts.GetAt(idx).Value + 1);
}
Console.WriteLine(counts.GetAt(0));

Benefits: Frequency tracking, ordered logs, quick updates.

ReferenceHandler Support in JSON Source Generators

Earlier, serializing object graphs with cycles caused stack overflows. Now, the Preserve option supports circular references.

public class Category
{
    public string Name { get; set; }
    public Category? Parent { get; set; }
}
[JsonSourceGenerationOptions(ReferenceHandler = JsonKnownReferenceHandler.Preserve)]
[JsonSerializable(typeof(Category))]
internal partial class JsonCtx : JsonSerializerContext { }
var node = new Category { Name = "Root" };
node.Parent = node;
string output = JsonSerializer.Serialize(node, JsonCtx.Default.Category);
Console.WriteLine(output);

Benefits: Enables safe serialization for complex graphs.

Wrapping Up

The combination of C# 14 and the new base library capabilities in .NET 10 presents a compelling platform for modern developers. With enhancements in API design, runtime performance, and language expressiveness, this release solidifies .NET as a top-tier development framework. I have added one demo project with the article. Please feel free to explore that as well.

Thank You, and Stay Tuned for More!

Windows Hosting Recommendation

HostForLIFEASP.NET receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 7.0.10 , ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/
Read More

Integration of SonarLint with Various IDEs

Leave a Comment

For incorporating static code analysis straight into your development environment, SonarLint is a well-liked tool. Additionally, it helps detect any errors, vulnerabilities, and code smells while giving immediate feedback on the quality of the code. You can incorporate SonarLint into your development process in the following ways:

1. Supported IDEs

SonarLint supports the following IDEs:

  • Visual Studio
  • Visual Studio Code
  • IntelliJ IDEA
  • Eclipse
2. SonarLint for Visual Studio

2.1 Install the SonarLint Extension

  1. Open Visual Studio.
  2. Go to Extensions > Manage Extensions.
  3. Search for "SonarLint".
  4. Click Install and restart Visual Studio.

2.2 Configure SonarLint

  1. Open any project in Visual Studio.
  2. SonarLint automatically starts analyzing your code as you edit and saves your changes.
  3. View detected issues in the Error List window.

2.3 Optional: Bind to SonarQube or SonarCloud

  1. Go to Tools > Options > SonarLint.
  2. Bind to a SonarQube server or SonarCloud project for enhanced issue detection (e.g., issues with organization-specific rules).
3. SonarLint for Visual Studio Code

3.1 Install the SonarLint Extension

  1. Open Visual Studio Code.
  2. Go to the Extensions view (Ctrl+Shift+X).
  3. Search for "SonarLint".
  4. Install the extension.

3.2 Configure SonarLint

  • SonarLint automatically analyzes your code when you open or save files.
  • To customize settings:
    1. Open the Command Palette (Ctrl+Shift+P).
    2. Search for and select Preferences: Open Settings (JSON).
    3. Add SonarLint settings. Example:
"sonarlint.connectedMode.servers": [

    {

        "serverId": "my-server",
        "serverUrl": "http://localhost:9000",
        "token": "your-sonarqube-token"
    }

],

"sonarlint.connectedMode.project": {

    "serverId": "my-server",
    "projectKey": "my-project-key"

}
4. SonarLint for IntelliJ IDEA

4.1 Install the SonarLint Plugin

  1. Open IntelliJ IDEA.
  2. Go to File > Settings > Plugins.
  3. Search for "SonarLint".
  4. Click Install and restart IntelliJ IDEA.

4.2 Configure SonarLint

  • SonarLint analyzes your code on-the-fly.
  • To bind to SonarQube or SonarCloud:
    1. Go to File > Settings > Tools > SonarLint.
    2. Add your SonarQube server details and authenticate.
5. SonarLint for Eclipse

5.1 Install the SonarLint Plugin

  1. Open Eclipse.
  2. Go to Help > Eclipse Marketplace.
  3. Search for "SonarLint".
  4. Click Install and restart Eclipse.

5.2 Configure SonarLint

  • SonarLint automatically scans your code.
  • To bind to SonarQube:
    1. Go to Window > Preferences > SonarLint > Connected Mode.
    2. Add your SonarQube server and bind to a project.
6. Advantages of SonarLint Integration
  • On-the-Fly Feedback: Instantly see potential issues while coding.
  • Seamless Workflow: Works directly in your IDE without requiring additional steps.
  • Custom Rules: Leverages SonarQube/SonarCloud for organization-specific coding standards.
  • Local Validation: No need to commit code before seeing results.
7. Tips for Best Practices
  • Always keep the SonarLint plugin updated for the latest rules and bug fixes.
  • Use connected mode to ensure consistent rules between SonarLint and your SonarQube/SonarCloud instance.
  • Regularly address code smells and vulnerabilities highlighted by SonarLint to maintain high-quality code.

HostForLIFE is Best Option for ASP.NET Core 9.0 Hosting in Europe

Frankly speaking, HostForLIFE is best option to host your ASP.NET Core 9.0 Hosting in Europe. You just need to spend €2.97/month to host your site with them and you can install the latest ASP.NET Core 9.0 via their Plesk control panel. We would highly recommend them as your ASP.NET Core 9.0 Hosting in Europe.

http://hostforlifeasp.net/European-ASPNET-Core-2-Hosting
Read More
Previous PostOlder Posts Home