Posts

Showing posts with the label C#

Simple Memory Cache in ASP.NET Core

Image
In this blog post, we'll explore how to use in-memory caching in ASP.NET Core. Caching can highly enhance the performance of your web application by reducing the number of times data needs to be retrieved or computed. We'll use a simple example to illustrate how you can implement in-memory caching in your ASP.NET Core application. Setting Up the Project First, let's set up our ASP.NET Core project. We'll start with the HomeController class, which will handle our web requests. Here's the code for our HomeController: public class HomeController : Controller {     private readonly ILogger<HomeController> _logger;     private readonly IMemoryCache _memoryCache;     public HomeController(ILogger<HomeController> logger, IMemoryCache memoryCache)     {         _logger = logger;         _memoryCache = memoryCache;     }     public IActionResult Index()   ...

Building a Background Task Scheduler in ASP.NET Core: Step-by-Step Guide

Image
Introduction: In many web applications, there arises a need to perform certain tasks in the background at regular intervals, such as sending emails, updating caches, or fetching data from external sources. ASP.NET Core provides a easy way to achieve this through hosted services. In this blog, will walk through the process of creating a simple background task scheduler using ASP.NET Core's hosted services feature. Step 1: Creating a New ASP.NET Core Web Application Launch Visual Studio. Click on "Create a new project". In the "Create a new project" window, select "ASP.NET Core Web Application" and click Next. Project Name: Enter SampleBackgroundService. Location: Choose a location to save your project. Click Next. Step 2: Creating the Background Service Create a new class named MyBackgroundService.cs in your project and implement the background task logic. This class should inherit from BackgroundService and override the ExecuteAsync method...

Localization in ASP.NET Core MVC with Example

Image
Using Query Strings for Request Culture and Simplifying Localization with IStringLocalizer Interface Let’s see how to implement Localization in ASP.NET Core MVC. In the first example, I am going to use the IStringLocalizer Interface in the controller to implement Localization. Additionally, when the user passes the desired language through the query string, it will display content in that language. First, let’s configure the settings in the program.cs file. builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");  The AddLocalization method adds the localization service to the service container. I have added the supported cultures here. I have added two cultures: en for English and nl for Dutch. In the RequestCultureProviders , I have included QueryStringRequestCultureProvider() . This allows the system to determine the culture information from the query string. UseRequestLocalization initializes a RequestLocalizationOptions o...

Simplifying Code with Null Propagation in C#

Image
Code readability, maintenance, and reducing the risk of unexpected crashes. Earlier, developers used nested null checks to navigate through complex object structures, ensuring that each step along the way is not null. But WWith the introduction of Null Propagation in C#, a cleaner and simpler syntax appears, streamlining the process of handling null references. In this blog post, we'll explore Null Propagation using a simple code snippet. Before Null Propagation: Let's consider a scenario where we have a Person object and want to retrieve the city from their address. Here's how it might have been done traditionally: Person ? person = null ; string ? city = null ; if (person != null && person.Address != null ) { city = person.Address.City; } ...

A Step-by-Step Guide to Implementing Identity in ASP.NET Core MVC

Image
Are you ready to enhance your ASP.NET Core MVC project with the power of Identity? In this comprehensive guide, we'll walk you through the process of setting up and customizing the Identity system in your web application. By the end of this tutorial, you'll be able to implement secure user authentication and authorization for your ASP.NET Core project. Step 1: Create a New ASP.NET Core Web App Begin by opening Visual Studio and selecting "ASP.NET Core Web App (Model-View-Controller)" as your project template. Follow these steps: 1. Open Visual Studio and create a new project, selecting "ASP.NET Core Web App (Model-View-Controller)". 2. In the "Configure your project" window, enter the project name and choose the project's location. 3. In the "Additional Information" window, select the framework and choose "Individual Accounts" as the Authentication type. 4. Click "Create" to generate your project....

Improving Code Readability in C# with Digit Separators

Image
What Are Digit Separators? Digit separators were introduced in C# 7.0. When dealing with large numbers, digit separators help enhance the readability of your code. By using underscore (_) as a separator within groups of numbers, you can significantly improve code readability. Why Use Digit Separators? Consider the scenario where you need to work with the number 1000000000. Without digit separators, reading this number can be challenging. However, by using digit separators and representing the number as 1_000_000_000, it becomes much easier to read one billion. Examples of Digit Separators Let's explore a few examples to understand how digit separators function: int totalPopulation = 7_900_000_000 ; double distanceToMoon = 384_400 . 0 ; long nationalDebt = 28_000_000_000_000 ; As evident, adding digit separators in between groups of digits has no impact on the numerical value itself. It only improves human readability. Conclusion The introduction of d...

Simplify Your Code with Pattern Matching: Type Tests in C#

Image
Introduction: Pattern matching in C# is a powerful feature that simplifies common programming patterns and enables you to perform type tests and extract values from objects in a clear and brief way. In this blog post, you will explore the concept of type tests in pattern matching and demonstrate how they can simplify your code. Let's dive in! Understanding Type Tests in Pattern Matching: Type tests in pattern matching involve checking if an object is of a particular type and then extracting and working with the object in a type-safe manner. This eliminates the need for explicit casting and provides a more readable and maintainable solution. Let's illustrate this with an example: // Base shape class class   Shape  { } // Circle class class   Circle  :  Shape {      public   double   Radius  {  get ;  set ; } } // Rectangle class class   Rectangle  :  Shape {      public   double ...

Exploring EventCallback in Blazor: Building Interactive Components

Image
Introduction: Blazor is a powerful framework for building web applications using C# instead of JavaScript. It allows developers to create interactive and dynamic user interfaces with ease. One of the key features in Blazor is the EventCallback<T> pattern, which enables communication between components through events. In this blog post, we will explore how to use the EventCallback<T> pattern in Blazor by building a simple example. Creating the Event-Driven Component: Let's start by creating a Blazor component called MyComponent. This component will raise an event when a button is clicked. Here's the code for the MyComponent.razor file: MyComponent.razor < h3 > My Component < / h3 > < button @onclick = " RaiseEvent " > Raise Event < / button > @code { [ Parameter ] public EventCallback < string > EventRaised { get ; set ; } private async Task RaiseEvent ( ) { await EventRais...

String Manipulation with C#'s TrimStart() and TrimEnd()

Image
The TrimStart() and TrimEnd() methods, which allow developers to easily trim leading and trailing characters from strings.TrimStart() and TrimEnd() are two string manipulation methods provided by C#. Both methods enable the removal of specified characters from the beginning (leading) or end (trailing) of a given string. Overloads of TrimStart() and TrimEnd() Method with Examples TrimStart() The basic TrimStart() method removes all leading whitespace characters from the current string. This includes spaces, tabs, line breaks, and other similar characters. It is commonly used to clean user input or clean up strings before further processing. string input = "   Hello, World!   "; string trimmed = input.TrimStart(); Console.WriteLine(trimmed); // Output: "Hello, World!   " TrimEnd() Likewise, the TrimEnd() method removes all trailing whitespace characters from the current string. It eliminates spaces, tabs, line breaks, and similar charac...

String Interpolation in C#

Image
Programmers can incorporate expressions into string literals using the C# functionality known as string interpolation. Complex string messages with variables and expressions are made easier to generate as a result. The '$' character is used in C# string interpolation to indicate interpolated expressions within a string literal. We will examine string interpolation in C# and present examples in this blog article. Basic syntax String interpolation is used by prefixing a string literal with the '$' character and then including one or more expressions inside curly braces. Here's an illustration: string name = " John "; int age = 30 ; Console .WriteLine($" My name is {name} and I am {age} years old. "); In this example, we have a string literal with two expressions enclosed by curly brackets. At runtime, the expressions are evaluated and the resulting values are placed into the string. Output: My name is John and ...