.NET 8 - Keyed service dependency injection container support 🔝
Keyed services are useful when you have an interface/service with multiple implementations that you want to use in your app. What's more, you need to use each of those implementations in different places in your app.☄️
Sample:
〰️〰️〰️〰️〰️〰️
#DotNet #DotNetCore #AspNetCore #CSharp
@ProgrammingTip
Keyed services are useful when you have an interface/service with multiple implementations that you want to use in your app. What's more, you need to use each of those implementations in different places in your app.
Sample:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddKeyedSingleton<INotificationService, SmsNotificationService>("sms");
builder.Services.AddKeyedSingleton<INotificationService, EmailNotificationService>("email");
builder.Services.AddKeyedSingleton<INotificationService, PushNotificationService>("push");
[ Article ] : https://andrewlock.net/exploring-the-dotnet-8-preview-keyed-services-dependency-injection-support〰️〰️〰️〰️〰️〰️
#DotNet #DotNetCore #AspNetCore #CSharp
@ProgrammingTip
Please open Telegram to view this post
VIEW IN TELEGRAM
Telegram
Programming Tips Resources
Introducing .NET Aspire: Simplifying Cloud-Native Development with .NET 8 🔥
.NET Aspire is an opinionated stack for building resilient, observable, and configurable cloud-native applications with .NET. It includes a curated set of components enhanced for cloud-native by including service discovery, telemetry, resilience, and health checks by default.👍
Sample Usage:
[ Article ] : https://devblogs.microsoft.com/dotnet/introducing-dotnet-aspire-simplifying-cloud-native-development-with-dotnet-8
〰️〰️〰️〰️〰️〰️
#DotNET #AspNetCore #CSharp #Aspire
@ProgrammingTip
.NET Aspire is an opinionated stack for building resilient, observable, and configurable cloud-native applications with .NET. It includes a curated set of components enhanced for cloud-native by including service discovery, telemetry, resilience, and health checks by default.
Sample Usage:
var builder = DistributedApplication.CreateBuilder(args);
var cache = builder.AddRedisContainer("cache");
var apiservice = builder.AddProject<Projects.AspireApp_ApiService>("apiservice");
builder.AddProject<Projects.AspireApp_Web>("webfrontend")
.WithReference(cache)
.WithReference(apiservice);
builder.Build().Run();
[ Article ] : https://devblogs.microsoft.com/dotnet/introducing-dotnet-aspire-simplifying-cloud-native-development-with-dotnet-8
〰️〰️〰️〰️〰️〰️
#DotNET #AspNetCore #CSharp #Aspire
@ProgrammingTip
Please open Telegram to view this post
VIEW IN TELEGRAM
Microsoft News
Introducing .NET Aspire: Simplifying Cloud-Native Development with .NET 8
Introducing .NET Aspire: A cloud ready stack for building observable, production ready, distributed applications
🔍 Challenge: Create a compact Maze Game in C# under 2KB without .NET Runtime, Small enough to fit in a QR Code 🤔
👨💻 Process:
• Self-Contained: Includes all necessary components to run on any OS.✔️
• Game Type: A graphical maze, utilizing Win32 APIs, avoiding WinForms.⭐️
• Size Reduction Steps:
1- Initial Size: 64MB (with CoreCLR)
2- Post-Compression: 35.2MB
3- IL Trimming Applied: 10MB
4- Native AOT Compilation: 1.13MB
5- Removing Unused Features: 923KB
6- Using bflat Compiler: 882KB
7- bflat with Zerolib: 9KB
8- Direct PInvoke: 8KB
9- Eliminating Debugging and Relocations: 7KB
10- Targeting x86 Architecture: 6.5KB
11- Final Step with Crinkler Linker: 1,936 Bytes
🎉 Outcome: Achieved a C# game small enough to fit in a QR code!
[ Full Article 🔗 ] : https://migeel.sk/blog/2024/01/02/building-a-self-contained-game-in-csharp-under-2-kilobytes
〰️〰️〰️〰️〰️〰️
#CSharp #DotNet #Optimization #LowLevel
@ProgrammingTip
• Self-Contained: Includes all necessary components to run on any OS.
• Game Type: A graphical maze, utilizing Win32 APIs, avoiding WinForms.
• Size Reduction Steps:
1- Initial Size: 64MB (with CoreCLR)
2- Post-Compression: 35.2MB
3- IL Trimming Applied: 10MB
4- Native AOT Compilation: 1.13MB
5- Removing Unused Features: 923KB
6- Using bflat Compiler: 882KB
7- bflat with Zerolib: 9KB
8- Direct PInvoke: 8KB
9- Eliminating Debugging and Relocations: 7KB
10- Targeting x86 Architecture: 6.5KB
11- Final Step with Crinkler Linker: 1,936 Bytes
🎉 Outcome: Achieved a C# game small enough to fit in a QR code!
[ Full Article 🔗 ] : https://migeel.sk/blog/2024/01/02/building-a-self-contained-game-in-csharp-under-2-kilobytes
〰️〰️〰️〰️〰️〰️
#CSharp #DotNet #Optimization #LowLevel
@ProgrammingTip
Please open Telegram to view this post
VIEW IN TELEGRAM
Telegram
Programming Tips Resources
Introducing WireMock.NET: Master HTTP API Testing 🚀
WireMock.NET simulates HTTP API behaviors, enabling seamless integration and testing for developers.
👌 Ideal Use Cases:
• HTTP Dependencies Not Ready: Leap over the hurdle of incomplete HTTP APIs in microservice architectures by mimicking their behavior with WireMock.Net.
• Unit Testing HTTP-Dependent Classes: Test classes that rely on HTTP APIs as a cohesive unit, ensuring your code communicates effectively with the actual APIs.
• Integration/End-to-End Tests: Overcome the challenges of testing with external HTTP APIs—like variable data, slow responses, and network restrictions—by employing WireMock.Net for consistent and swift testing.
[ GitHub ] : https://github.com/WireMock-Net/WireMock.Net
〰️〰️〰️〰️〰️〰️
#DotNet #WireMock #IntegrationTest
@ProgrammingTip
WireMock.NET simulates HTTP API behaviors, enabling seamless integration and testing for developers.
👌 Ideal Use Cases:
• HTTP Dependencies Not Ready: Leap over the hurdle of incomplete HTTP APIs in microservice architectures by mimicking their behavior with WireMock.Net.
• Unit Testing HTTP-Dependent Classes: Test classes that rely on HTTP APIs as a cohesive unit, ensuring your code communicates effectively with the actual APIs.
• Integration/End-to-End Tests: Overcome the challenges of testing with external HTTP APIs—like variable data, slow responses, and network restrictions—by employing WireMock.Net for consistent and swift testing.
public class ExternalService(HttpClient httpClient)
{
public async Task<string> GetAsync()
{
var response = await httpClient.GetAsync("/ping");
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
}
public class ExternalServiceTests
{
[Fact]
public async Task GetAsync_WhenCalled_ReturnsString()
{
// Arrange
var fakeServer = WireMockServer.Start();
fakeServer
.Given(Request.Create().WithPath("/ping").UsingGet())
.RespondWith(Response.Create()
.WithStatusCode(200)
.WithBody("pong")
);
var fakeClient = fakeServer.CreateClient();
var externalService = new ExternalService(fakeClient);
// Act
var response = await externalService.GetAsync();
// Assert
response.Should().Be("pong");
}
}
[ GitHub ] : https://github.com/WireMock-Net/WireMock.Net
〰️〰️〰️〰️〰️〰️
#DotNet #WireMock #IntegrationTest
@ProgrammingTip
Telegram
Programming Tips Resources
🚀Ready to Track Your Application with Metrics? 📊
Looking to keep a close eye on your ASP.NET Core applications? With the latest update in .NET 8, you can now easily track various aspects of your application's performance and health through built-in metrics.
Here's why it's exciting:
• HTTP Request Insights: Get a detailed view of your HTTP requests, including counts, durations, and more.
• Real-time Alerts: Set up alerts to notify you if your app's performance exceeds predefined thresholds.
• Error Handling Diagnostics: Pinpoint and address issues faster with detailed error handling diagnostics.
•User-friendly .NET Aspire Dashboards: Access a user-friendly dashboard through .NET Aspire, making it easy to visualize and understand your app's metrics.
• Customizable Grafana Dashboards: Dive deep into your app's performance with customizable Grafana dashboards, tailored specifically for ASP.NET Core metrics
Excited to learn more? Dive into the details and revolutionize your app monitoring experience! 💻💡
[ Article ] : https://devblogs.microsoft.com/dotnet/introducing-aspnetcore-metrics-and-grafana-dashboards-in-dotnet-8/
〰️〰️〰️〰️〰️〰️
#DotNet #Metrics #Grafana #Dotnet_Aspire #Monitoring
@ProgrammingTip
Looking to keep a close eye on your ASP.NET Core applications? With the latest update in .NET 8, you can now easily track various aspects of your application's performance and health through built-in metrics.
Here's why it's exciting:
• HTTP Request Insights: Get a detailed view of your HTTP requests, including counts, durations, and more.
• Real-time Alerts: Set up alerts to notify you if your app's performance exceeds predefined thresholds.
• Error Handling Diagnostics: Pinpoint and address issues faster with detailed error handling diagnostics.
•User-friendly .NET Aspire Dashboards: Access a user-friendly dashboard through .NET Aspire, making it easy to visualize and understand your app's metrics.
• Customizable Grafana Dashboards: Dive deep into your app's performance with customizable Grafana dashboards, tailored specifically for ASP.NET Core metrics
Excited to learn more? Dive into the details and revolutionize your app monitoring experience! 💻💡
[ Article ] : https://devblogs.microsoft.com/dotnet/introducing-aspnetcore-metrics-and-grafana-dashboards-in-dotnet-8/
〰️〰️〰️〰️〰️〰️
#DotNet #Metrics #Grafana #Dotnet_Aspire #Monitoring
@ProgrammingTip
Telegram
Programming Tips Resources
5 Rules for Writing Better and Cleaner DTOs 🧹
Crafting clean and maintainable DTOs is essential for keeping your codebase healthy and scalable. But let's face it, sometimes DTOs can morph into these complex beasts that leave you scratching your head.
Fear not, fellow developers!
This article (or the accompanying video!) dives into 5 key principles to help you write simpler, more understandable DTOs.
You'll learn about:
• Keeping things clear and concise
• Utilizing properties effectively ✨
• Crafting descriptive names that make sense
And also other tips to transform your DTOs from chaotic to crystal clear! By following these principles, you'll be well on your way to writing cleaner, more maintainable DTOs that make your code easier to understand for you and your team.
Ready to up your DTO game? Check out the full article or watch the video for examples and take your codebase to the next level!
[ Article ] : https://ardalis.com/5-rules-dtos
[ YouTube ] : https://www.youtube.com/watch?v=W4n9x_qGpT4
〰️〰️〰️〰️〰️〰️
#Dto #Dotnet #csharp #programming
@ProgrammingTip
Crafting clean and maintainable DTOs is essential for keeping your codebase healthy and scalable. But let's face it, sometimes DTOs can morph into these complex beasts that leave you scratching your head.
Fear not, fellow developers!
This article (or the accompanying video!) dives into 5 key principles to help you write simpler, more understandable DTOs.
You'll learn about:
• Keeping things clear and concise
• Utilizing properties effectively ✨
• Crafting descriptive names that make sense
And also other tips to transform your DTOs from chaotic to crystal clear! By following these principles, you'll be well on your way to writing cleaner, more maintainable DTOs that make your code easier to understand for you and your team.
Ready to up your DTO game? Check out the full article or watch the video for examples and take your codebase to the next level!
[ Article ] : https://ardalis.com/5-rules-dtos
[ YouTube ] : https://www.youtube.com/watch?v=W4n9x_qGpT4
〰️〰️〰️〰️〰️〰️
#Dto #Dotnet #csharp #programming
@ProgrammingTip
https://ardalis.com
5 Rules for DTOs
These are 5 rules for writing better DTOs.
OpenAI .NET 👾
The OpenAI .NET library provides convenient access to the OpenAI REST API from .NET applications.✔️
The full API of this library can be found in the api.md file, and there are many code examples to help. For instance, the following snippet illustrates the basic use of the chat completions API:
The library is organized into several namespaces corresponding to OpenAI feature areas. Each namespace contains a corresponding client class:
• AssistantClient
• AudioClient
• BatchClient
• ChatClient
• EmbeddingClient
• FineTuningClient
• FileClient
• ImageClient
• ModelClient
• ModerationClient
• VectorStoreClient
[ GitHub ] : https://github.com/openai/openai-dotnet
〰️〰️〰️〰️〰️〰️
#AI #OpenAI #DotNet #CSharp
@ProgrammingTip
The OpenAI .NET library provides convenient access to the OpenAI REST API from .NET applications.
The full API of this library can be found in the api.md file, and there are many code examples to help. For instance, the following snippet illustrates the basic use of the chat completions API:
ChatClient client = new(model: "gpt-4o", "OPENAI_API_KEY");
ChatCompletion completion = client.CompleteChat("Say 'this is a test.'");
Console.WriteLine($"[ASSISTANT]: {completion}");
The library is organized into several namespaces corresponding to OpenAI feature areas. Each namespace contains a corresponding client class:
• AssistantClient
• AudioClient
• BatchClient
• ChatClient
• EmbeddingClient
• FineTuningClient
• FileClient
• ImageClient
• ModelClient
• ModerationClient
• VectorStoreClient
[ GitHub ] : https://github.com/openai/openai-dotnet
〰️〰️〰️〰️〰️〰️
#AI #OpenAI #DotNet #CSharp
@ProgrammingTip
Please open Telegram to view this post
VIEW IN TELEGRAM
NetPad 🔥
A cross-platform C# editor and playground.
NetPad is a C# playground that lets you run C# code instantly, without the hassle of creating and managing projects. Open NetPad, start coding, hit Run, and see your output immediately. It's that simple.✔️
• Prototyping and Testing: Quickly prototype and test code snippets before incorporating them into your projects.
• Data Visualization: Visualize data interactively for better insights and analysis.
• Database Queries: Query databases using LINQ or SQL effortlessly.
• Learn and Experiment: Experiment with new C# features or start learning C# in an intuitive and accessible environment.
• Utility Scripts: Create and save your own utility or administration scripts for repeated use.
[ GitHub ] : https://github.com/tareqimbasher/NetPad
〰️〰️〰️〰️〰️〰️
#NetPad #Linqpad #CSharp #DotNet
@ProgrammingTip
A cross-platform C# editor and playground.
NetPad is a C# playground that lets you run C# code instantly, without the hassle of creating and managing projects. Open NetPad, start coding, hit Run, and see your output immediately. It's that simple.
• Prototyping and Testing: Quickly prototype and test code snippets before incorporating them into your projects.
• Data Visualization: Visualize data interactively for better insights and analysis.
• Database Queries: Query databases using LINQ or SQL effortlessly.
• Learn and Experiment: Experiment with new C# features or start learning C# in an intuitive and accessible environment.
• Utility Scripts: Create and save your own utility or administration scripts for repeated use.
[ GitHub ] : https://github.com/tareqimbasher/NetPad
〰️〰️〰️〰️〰️〰️
#NetPad #Linqpad #CSharp #DotNet
@ProgrammingTip
Please open Telegram to view this post
VIEW IN TELEGRAM
Telegram
Programming Tips Resources
I Built a .NET App Using AI (with Cursor) - This Is Amazing ✅
Discover how Cursor AI can transform your .NET development workflow!🚀
In this video, you will see how this AI-powered code editor can help you write better code faster, understand complex codebases, and automate repetitive tasks. Whether you're a seasoned developer or just getting started with .NET, Cursor's AI capabilities will change how you think about coding.
[ YouTube ] : https://youtu.be/5hyRBuW560c
〰️〰️〰️〰️〰️〰️
#AI #Cursor #DotNET #CSharp
@ProgrammingTip
Discover how Cursor AI can transform your .NET development workflow!
In this video, you will see how this AI-powered code editor can help you write better code faster, understand complex codebases, and automate repetitive tasks. Whether you're a seasoned developer or just getting started with .NET, Cursor's AI capabilities will change how you think about coding.
[ YouTube ] : https://youtu.be/5hyRBuW560c
〰️〰️〰️〰️〰️〰️
#AI #Cursor #DotNET #CSharp
@ProgrammingTip
Please open Telegram to view this post
VIEW IN TELEGRAM
Telegram
Programming Tips Resources
Build a Model Context Protocol (MCP) Server in C# 🧠
Learn how to create an MCP server using .NET 8 and ASP.NET Core!⚡️
This guide walks you through building a server that can interact with AI models via the Model Context Protocol — a standard for managing model prompts, memory, and tools. Great for AI agent developers!🤖 🧠
[ Blog ] : https://devblogs.microsoft.com/dotnet/build-a-model-context-protocol-mcp-server-in-csharp
〰️〰️〰️〰️〰️〰️
#AI #MCP #dotnet #csharp
@ProgrammingTip
Learn how to create an MCP server using .NET 8 and ASP.NET Core!
This guide walks you through building a server that can interact with AI models via the Model Context Protocol — a standard for managing model prompts, memory, and tools. Great for AI agent developers!
[ Blog ] : https://devblogs.microsoft.com/dotnet/build-a-model-context-protocol-mcp-server-in-csharp
〰️〰️〰️〰️〰️〰️
#AI #MCP #dotnet #csharp
@ProgrammingTip
Please open Telegram to view this post
VIEW IN TELEGRAM
Microsoft News
Build a Model Context Protocol (MCP) server in C#
Learn how to build a Model Context Protocol (MCP) server using the C# SDK to enable seamless communication between AI models and applications.
C# 14 - Extension Members 🚀
C# 14 adds new syntax to define extension members. The new syntax enables you to declare extension properties in addition to extension methods.✔️
You can also declare extension members that extend the type, rather than an instance of the type. In other words, these new extension members can appear as static members of the type you extend.
The following code example shows an example of the different kinds of extension members you can declare:
The members in the first extension block are called as though they're instance members of
[ Blog ] : https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods
〰️〰️〰️〰️〰️〰️
#csharp #dotnet
@ProgrammingTip
C# 14 adds new syntax to define extension members. The new syntax enables you to declare extension properties in addition to extension methods.
You can also declare extension members that extend the type, rather than an instance of the type. In other words, these new extension members can appear as static members of the type you extend.
The following code example shows an example of the different kinds of extension members you can declare:
public static class Enumerable
{
// Extension block
extension<TSource>(IEnumerable<TSource> source) // extension members for IEnumerable<TSource>
{
// Extension property:
public bool IsEmpty => !source.Any();
// Extension indexer:
public TSource this[int index] => source.Skip(index).First();
// Extension method:
public IEnumerable<TSource> Where(Func<TSource, bool> predicate) { ... }
}
// extension block, with a receiver type only
extension<TSource>(IEnumerable<TSource>) // static extension members for IEnumerable<Source>
{
// static extension method:
public static IEnumerable<TSource> Combine(IEnumerable<TSource> first, IEnumerable<TSource> second) { ... }
// static extension property:
public static IEnumerable<TSource> Identity => yield return default;
}
}
The members in the first extension block are called as though they're instance members of
IEnumerable<TSource>
, for example sequence.IsEmpty
. The members in the second extension block are called as though they're static members of IEnumerable<TSource>
, for example IEnumerable<int>.Identity
.[ Blog ] : https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods
〰️〰️〰️〰️〰️〰️
#csharp #dotnet
@ProgrammingTip
Please open Telegram to view this post
VIEW IN TELEGRAM
Telegram
Programming Tips Resources
The Hidden Cost of DateTime.Now in .NET 🕰
You're Using DateTime.Now — and It's Breaking Your Code …❌
Let's be honest: We've all written this:
It works… until it doesn't.
In production, this little line can wreck your logic due to clock drift, time zone shifts, or mocking nightmares. 🐞
[ Article ] : https://freedium.cfd/https://medium.com/@yaseer.arafat/the-hidden-cost-of-datetime-now-and-what-every-net-developer-should-use-instead-8859863257a1
〰️〰️〰️〰️〰️〰️
#dotnet #csharp
@ProgrammingTip
You're Using DateTime.Now — and It's Breaking Your Code …
Let's be honest: We've all written this:
if (DateTime.Now > token.Expiry)
{
return Unauthorized();
}
It works… until it doesn't.
In production, this little line can wreck your logic due to clock drift, time zone shifts, or mocking nightmares. 🐞
[ Article ] : https://freedium.cfd/https://medium.com/@yaseer.arafat/the-hidden-cost-of-datetime-now-and-what-every-net-developer-should-use-instead-8859863257a1
〰️〰️〰️〰️〰️〰️
#dotnet #csharp
@ProgrammingTip
Please open Telegram to view this post
VIEW IN TELEGRAM
Telegram
Programming Tips Resources
Preparing for the .NET 10 GC 🔥
In .NET 9 DATAS (Dynamic Adaptation To Application Sizes) got enabled by default, but .NET 9 is not an LTS release, so for many people they will be getting DATAS for the first time when they upgrade to .NET 10.
What does “application size” mean exactly?
This is the LDS (Live Data Size) from GC’s point of view, meaning that if we did the most aggressive GC possible, this is how much memory your application uses. Another way to look at it is this is your long lived data + whatever inflight data you have when a GC occurs.
The goal for DATAS is that you no longer need to do various configurations to try to achieve a heap size proportional to your application usage. The 2 main cases we target with DATAS are:
1) Bursty workloads running in memory constraint environments. DATAS aims to retract the heap size back when the application doesn’t require as much memory and grow it when the app requires more. This is especially important for apps running in containers with memory limits.
2) Small workloads using Server GC — for example, if someone wants to try out a small asp.net core app to see what the experience is like in .NET, DATAS aims provide a heap size much more inline with what the small app actually needs.
[ Article ] : https://maoni0.medium.com/preparing-for-the-net-10-gc-88718b261ef2
〰️〰️〰️〰️〰️〰️
#dotnet #gc
@ProgrammingTip
In .NET 9 DATAS (Dynamic Adaptation To Application Sizes) got enabled by default, but .NET 9 is not an LTS release, so for many people they will be getting DATAS for the first time when they upgrade to .NET 10.
What does “application size” mean exactly?
This is the LDS (Live Data Size) from GC’s point of view, meaning that if we did the most aggressive GC possible, this is how much memory your application uses. Another way to look at it is this is your long lived data + whatever inflight data you have when a GC occurs.
The goal for DATAS is that you no longer need to do various configurations to try to achieve a heap size proportional to your application usage. The 2 main cases we target with DATAS are:
1) Bursty workloads running in memory constraint environments. DATAS aims to retract the heap size back when the application doesn’t require as much memory and grow it when the app requires more. This is especially important for apps running in containers with memory limits.
2) Small workloads using Server GC — for example, if someone wants to try out a small asp.net core app to see what the experience is like in .NET, DATAS aims provide a heap size much more inline with what the small app actually needs.
[ Article ] : https://maoni0.medium.com/preparing-for-the-net-10-gc-88718b261ef2
〰️〰️〰️〰️〰️〰️
#dotnet #gc
@ProgrammingTip
Please open Telegram to view this post
VIEW IN TELEGRAM
Telegram
Programming Tips Resources