CSharp - Other

Filtering the object of a type with OfType

Filtering Numeric Data


Sample Input

var mixedData = new object[] { 1, "Hello", 3.14, 42, "World", 7 };
var integers = mixedData.OfType<int>();


Expected Output

[1, 42, 7]


Extracting Strings from a List


Sample Input

var mixedData = new object[] { "Apple", 10, "Banana", 3.14, "Cherry", 42 };
var strings = mixedData.OfType<string>();


Expected Output

["Apple", "Banana", "Cherry"]


Type-Specific Operations in a UI


Sample Input

var uiElements = new object[] { new TextBox(), new Button(), new Label(), new Button() };
var buttons = uiElements.OfType<Button>();


Expected Output

[Button, Button]


Handling Polymorphic Objects


Sample Input

var vehicles = new Vehicle[] { new Car(), new Truck(), new Car(), new Bike() };
var cars = vehicles.OfType<Car>();


Expected Output

[Car, Car]


Processing Specific Exception Types


Sample Input

var exceptions = new Exception[] { new Exception(), new ArgumentException(), new NullReferenceException(), new ArgumentException() };
var argumentExceptions = exceptions.OfType<ArgumentException>();


Expected Output

[ArgumentException, ArgumentException]


Extracting Numeric Data for Calculations


Sample Input

var mixedData = new object[] { 1, 3.14, 2.71, "Hello", 42, 6.28 };
var doubles = mixedData.OfType<double>();


Expected Output

[3.14, 2.71, 6.28]


Filtering Media Content by Type


Sample Input

var mediaLibrary = new object[] { new Audio(), new Video(), new Video(), new Image() };
var videos = mediaLibrary.OfType<Video>();


Expected Output

[Video, Video]


Processing Specific Events in Logs


Sample Input

var logs = new object[] { new InfoLog(), new ErrorLog(), new DebugLog(), new ErrorLog() };
var errorLogs = logs.OfType<ErrorLog>();


Expected Output

[ErrorLog, ErrorLog]


Handling API Responses


Sample Input

var apiResponses = new object[] { new SuccessResponse(), new ErrorResponse(), new ErrorResponse(), new WarningResponse() };
var errorResponses = apiResponses.OfType<ErrorResponse>();


Expected Output

[ErrorResponse, ErrorResponse]


Analyzing Mixed Sensor Data


Sample Input

var sensorReadings = new object[] { new PressureSensorData(), new TemperatureSensorData(), new TemperatureSensorData(), new HumiditySensorData() };
var temperatureSensorData = sensorReadings.OfType<TemperatureSensorData>();


Expected Output

[TemperatureSensorData, TemperatureSensorData]


Flattening a Multi-Dimensional Array

int[,] matrix = { { 1, 2 }, { 3, 4 }, { 5, 6 } };
int[] flattened = matrix.Cast<int>().ToArray();
// Result: flattened = { 1, 2, 3, 4, 5, 6 }

Format a Number as Currency

Formatting numbers as currency can be achieved in a single line using ToString.

double amount = 1234.56;
Console.WriteLine(amount.ToString("C"));


Explanation: Using the "C" format specifier, this snippet converts the numeric value into a currency format based on the current culture settings.

Frozen collections

Frozen collections in .NET are special types of collections. Collections like lists, dictionaries, arrays, etc. The frozen collections can't be changed when the data has been set. We call this "immutable". This means you can look at the data inside, but you can't change the data after it's frozen.


They are really fast because your application knows the data won't change. And because of that it can prevent accidental modifications, making your application do things you don't want it to be doing.


FrozenSet<Product> frozenProducts = ProductList.Products.ToFrozenSet();

frozenProducts.Single(x => x.Title == "Meatballs").Stock = 23;

foreach (Product product in products.Where(x => x.Stock > 10))
    Console.WriteLine($"{product.Title} ({product.Stock})");

Generate Tooltip via ASP.NET MVC Model Attribute

Model Attribute

[Display(Name = "Text Box Label", Description = "Text Box Tooltip Description")]


View

var description = ModelMetadata.FromStringExpression(Model.Name, ViewData).Description;

<a href="javascript:void(0)" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="@description">
    <i class="fa-solid fa-circle-info"></i>
</a>


JavaScript

$(document).ready(function () {
    $('[data-bs-toggle="tooltip"]').tooltip();
})

Generate Unique ID

Guid.NewGuid().ToString("N");

Get Enum Description

public string GetEnumDescription(Enum value)
{
    FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
    
    DescriptionAttribute[] attributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);

    return attributes != null && attributes.Length > 0 ? attributes[0].Description : value.ToString();
}

GetEnumDescription(enumVal);

Get model's field attribute in custom editor template

ID

@ViewData.TemplateInfo.GetFullHtmlFieldId("")


Name

@ViewData.TemplateInfo.GetFullHtmlFieldName("")

GlobalUsings namespace in ASP.NET Core

Controllers & Services


The GlobalUsings.cs file is used to define global using directives. These directives allow you to import namespaces globally, meaning all files in your project automatically have access to them without needing individual using statements.

Creating GlobalUsings.cs. Place this file inside the Infrastructure folder.

global using System;
global using System.Collections.Generic;
global using Microsoft.AspNetCore.Mvc;
global using Microsoft.EntityFrameworkCore;


Razor Views


Creating _ViewImports.cshtml. Place this file inside the /Views folder.

@using Microsoft.AspNetCore.Mvc
@using Microsoft.AspNetCore.Mvc.RazorPages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers



Handling Exceptions Globally in ASP.NET Core

app.UseExceptionHandler(errorApp =>
{
    errorApp.Run(async context =>
    {
        var exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>();
        var exception = exceptionHandlerPathFeature?.Error;

        await context.Response.WriteAsync("An error occurred.");
    });
});

High-Performance SMS Sending with RabbitMQ and MassTransit in .NET

Design SMS Message Payload

Use a structured payload to handle metadata and SMS content:

{
  "api_token": "your-api-token",
  "sid": "SERVICE_ID",
  "msisdn": "88019XXXXXXXX",
  "sms_body": "Hello, your OTP is 123456",
  "csms_id": "unique_id_for_tracking"
}


Create a WebAPI project

dotnet new webapi -n MyWebApiProject


NuGet Packages:

Install the necessary MassTransit and RabbitMQ packages:

dotnet add package MassTransit
dotnet add package MassTransit.RabbitMQ


Config RabbitMQ

Configure the connection to your RabbitMQ instance in appsettings.json:

"RabbitMQ": {
    "HostName": "your_rabbitmq_host",
    "UserName": "your_username",
    "Password": "your_password"
}


Create SMS Message Model

Define a model for your SMS messages:

public class SmsMessage
{
        public string api_token { get; set; }
        public string sid { get; set; }
        public string msisdn { get; set; }
        public string sms_body { get; set; }
        public string csms_id { get; set; }
}


Producer (API Gateway):

Publish SMS messages to the RabbitMQ queue:

public class SmsService : ISmsService
{
    private readonly IPublishEndpoint _publishEndpoint;

    public SmsService(IPublishEndpoint publishEndpoint)
    {
        _publishEndpoint = publishEndpoint;
    }

    public async Task SendSmsAsync(SmsMessage message)
    {
        await _publishEndpoint.Publish(message);
    }
}


Consumer (SMS Worker):

Consume messages from the queue and send SMS using a chosen provider:

public class SmsWorker : IConsumer<SmsMessage>
{
    private readonly ISmsProvider _smsProvider;

    public SmsWorker(ISmsProvider smsProvider)
    {
        _smsProvider = smsProvider;
    }

    public async Task Consume(ConsumeContext<SmsMessage> context)
    {
        var message = context.Message;
        await _smsProvider.SendSmsAsync(message.To, message.From, message.Body);
    }
}


SMS Provider Interface:

Define an interface for interacting with different SMS providers:

public interface ISmsProvider
{
    Task SendSmsAsync(string to, string from, string body);
}


MassTransit Configuration:

Configure MassTransit in your Program.cs:

builder.Services.AddMassTransit(x =>
{
    x.AddConsumer<SmsWorker>();
    x.UsingRabbitMq((context, cfg) =>
    {
        cfg.Host(configuration["RabbitMQ:HostName"], "/", h =>
        {
            h.Username(configuration["RabbitMQ:UserName"]);
            h.Password(configuration["RabbitMQ:Password"]);
        });
        cfg.ReceiveEndpoint("sms_queue", e =>
        {
            e.ConfigureConsumer<SmsWorker>(context);
        });
    });
});
builder.Services.AddMassTransitHostedService();


Run & Test

How can I split a string with a string delimiter ?

string[] tokens = str.Split(new[] { "token" }, StringSplitOptions.None);