C# Generics

C# allows you to define generic classes, interfaces, abstract classes, fields, methods, static methods, properties, events, delegates, and operators using the type parameter and without the specific data type. A type parameter is a placeholder for a particular type specified when creating an instance of the generic type.

Generic Class

class DataStore<T>
{
    public T Data { get; set; }
}

You can also define multiple type parameters separated by a comma.

class KeyValuePair<TKey, TValue>
{
    public TKey Key { get; set; }
    public TValue Value { get; set; }
}

Instantiating Generic Class

DataStore<string> store = new DataStore<string>();
DataStore<string> store = new DataStore<string>();
store.Data = "Hello World!";
//store.Data = 123; //compile-time error

You can specify the different data types for different objects, as shown below.

DataStore<string> strStore = new DataStore<string>();
strStore.Data = "Hello World!";
//strStore.Data = 123; // compile-time error

DataStore<int> intStore = new DataStore<int>();
intStore.Data = 100;
//intStore.Data = "Hello World!"; // compile-time error

KeyValuePair<int, string> kvp1 = new KeyValuePair<int, string>();
kvp1.Key = 100;
kvp1.Value = "Hundred";

KeyValuePair<string, string> kvp2 = new KeyValuePair<string, string>();
kvp2.Key = "IT";
kvp2.Value = "Information Technology";

Generic Fields

class DataStore<T>
{
    public T data;
}
class DataStore<T>
{
    public T[] data = new T[10];
}

Generic Methods

class DataStore<T>
{
    private T[] _data = new T[10];
    
    public void AddOrUpdate(int index, T item)
    {
        if(index >= 0 && index < 10)
            _data[index] = item;
    }

    public T GetData(int index)
    {
        if(index >= 0 && index < 10)
            return _data[index];
        else 
            return default(T);
    }
}
DataStore<string> cities = new DataStore<string>();
cities.AddOrUpdate(0, "Mumbai");
cities.AddOrUpdate(1, "Chicago");
cities.AddOrUpdate(2, "London");

DataStore<int> empIds = new DataStore<int>();
empIds.AddOrUpdate(0, 50);
empIds.AddOrUpdate(1, 65);
empIds.AddOrUpdate(2, 89);
class Printer
{
    public void Print<T>(T data)
    {
        Console.WriteLine(data);
    }
}

Printer printer = new Printer();
printer.Print<int>(100);
printer.Print(200); // type infer from the specified value
printer.Print<string>("Hello");
printer.Print("World!"); // type infer from the specified value

References
https://www.tutorialsteacher.com/csharp/csharp-generics
https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/types/generics

Raw string literals in C# 11

Raw string literals can contain arbitrary text, including whitespace, new lines, embedded quotes, and other special characters without requiring escape sequences.

string longMessage = """
    This is a long message.
    It has several lines.
        Some are indented
                more than others.
    Some should start at the first column.
    Some have "quoted text" in them.
    """;

Raw string literals can be combined with string interpolation to include braces in the output text. Multiple $ characters denote how many consecutive braces start and end the interpolation:

var location = $$"""
   You are at {{{Longitude}}, {{Latitude}}}
   """;

References
https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-11#raw-string-literals

required modifier in C# 11

public class Person
{
    public Person() { }

    [SetsRequiredMembers]
    public Person(string firstName, string lastName) =>
        (FirstName, LastName) = (firstName, lastName);

    public required string FirstName { get; init; }
    public required string LastName { get; init; }

    public int? Age { get; set; }
}

public class Student : Person
{
    public Student() : base()
    {
    }

    [SetsRequiredMembers]
    public Student(string firstName, string lastName) :
        base(firstName, lastName)
    {
    }

    public double GPA { get; set; }
}

The SetsRequiredMembers disables the compiler’s checks that all required members are initialized when an object is created. Use it with caution.

References
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/required
https://youtu.be/9CDgPgWF9IY

Read characters from a string in C#

using System;
using System.IO;

public class CharsFromStr
{
    public static void Main()
    {
        string str = "Some number of characters";
        char[] b = new char[str.Length];

        using (StringReader sr = new StringReader(str))
        {
            // Read 13 characters from the string into the array.
            sr.Read(b, 0, 13);
            Console.WriteLine(b);

            // Read the rest of the string starting at the current string position.
            // Put in the array starting at the 6th array member.
            sr.Read(b, 5, str.Length - 13);
            Console.WriteLine(b);
        }
    }
}
// The example has the following output:
//
// Some number o
// Some f characters

References
https://learn.microsoft.com/en-us/dotnet/standard/io/how-to-read-characters-from-a-string

Deserialize XML to Object in C#

<?xml version="1.0" encoding="utf-8"?>
<Company xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Employee name="x" age="30" />
  <Employee name="y" age="32" />
 </Company>
using System.Xml.Serialization;

[XmlRoot(ElementName = "Company")]
public class Company

{
    public Company()
    {  
        Employees = new List<Employee>();
    }

    [XmlElement(ElementName = "Employee")]
    public List<Employee> Employees { get; set; }

    public Employee this[string name]
    {
        get { return Employees.FirstOrDefault(s => string.Equals(s.Name, name, 							StringComparison.OrdinalIgnoreCase)); }
    }
}

public class Employee
{
    [XmlAttribute("name")]
    public string Name { get; set; }

    [XmlAttribute("age")]
    public string Age { get; set; }
}
public static T DeserializeXml<T>(string str)
{
    var serializer = new XmlSerializer(typeof(T));
    object result;

    using (TextReader reader = new StringReader(str))
    {
        result = serializer.Deserialize(reader);
    }

    return (T) result;
}
var s = "--your xml string--";
var obj = Deserialize<CMS>(s);

References
https://www.delftstack.com/howto/csharp/deserialize-xml-to-object-in-csharp/
https://stackoverflow.com/questions/47158427/how-to-convert-xml-to-list-of-objects

ASP.NET Core Blazor State Management

We can use ASP.NET Core Protected Browser Storage:

Use the Local Storage

@page "/"
@using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage
@inject ProtectedLocalStorage BrowserStorage

<h1>Local Storage!</h1>

<input class="form-control" @bind="currentInputValue" />
<button class="btn btn-secondary" @onclick="Save">Save</button>
<button class="btn btn-secondary" @onclick="Read">Read</button>
<button class="btn btn-secondary" @onclick="Delete">Delete</button>

@code {
  string currentInputValue;

  public async Task Save()
  {
    await BrowserStorage.SetAsync("name", currentInputValue);
  }

  public async Task Read()
  {
    var result = await BrowserStorage.GetAsync<string>("name");
    currentInputValue = result.Success ? result.Value : "";
  }

  public async Task Delete()
  {
    await BrowserStorage.DeleteAsync("name");
  }
}

Use the Session Storage

@using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage
@inject ProtectedSessionStorage ProtectedSessionStore

References
https://docs.microsoft.com/en-us/aspnet/core/blazor/state-management?view=aspnetcore-6.0&pivots=server
https://www.thomasclaudiushuber.com/2021/04/19/store-data-of-your-blazor-app-in-the-local-storage-and-in-the-session-storage/

Transient fault handling in gRPC with retries in C#

gRPC calls can be interrupted by transient faults. Transient faults include:

  • Momentary loss of network connectivity.
  • Temporary unavailability of a service.
  • Timeouts due to server load.

When a gRPC call is interrupted, the client throws an RpcException with details about the error. The client app must catch the exception and choose how to handle the error.

var client = new Greeter.GreeterClient(channel);
try
{
    var response = await client.SayHelloAsync(
        new HelloRequest { Name = ".NET" });

    Console.WriteLine("From server: " + response.Message);
}
catch (RpcException ex)
{
    // Write logic to inspect the error and retry
    // if the error is from a transient fault.
}

Duplicating retry logic throughout an app is verbose and error-prone. Fortunately, the .NET gRPC client now has built-in support for automatic retries. Retries are centrally configured on a channel, and there are many options for customizing retry behavior using a RetryPolicy.

var defaultMethodConfig = new MethodConfig
{
    Names = { MethodName.Default },
    RetryPolicy = new RetryPolicy
    {
        MaxAttempts = 5,
        InitialBackoff = TimeSpan.FromSeconds(1),
        MaxBackoff = TimeSpan.FromSeconds(5),
        BackoffMultiplier = 1.5,
        RetryableStatusCodes = { StatusCode.Unavailable }
    }
};

// Clients created with this channel will automatically retry failed calls.
var channel = GrpcChannel.ForAddress("https://localhost:5001", new GrpcChannelOptions
{
    ServiceConfig = new ServiceConfig { MethodConfigs = { defaultMethodConfig } }
});

References
https://devblogs.microsoft.com/dotnet/grpc-in-dotnet-6/
https://docs.microsoft.com/en-us/aspnet/core/grpc/retries?view=aspnetcore-6.0

gRPC client-side load balancing in C#

The following code example configures a channel to use DNS service discovery with round-robin load balancing:

var channel = GrpcChannel.ForAddress(
    "dns:///my-example-host",
    new GrpcChannelOptions
    {
        Credentials = ChannelCredentials.Insecure,
        ServiceConfig = new ServiceConfig { LoadBalancingConfigs = { new RoundRobinConfig() } }
    });
var client = new Greet.GreeterClient(channel);

var response = await client.SayHelloAsync(new HelloRequest { Name = "world" });

References
https://devblogs.microsoft.com/dotnet/grpc-in-dotnet-6/
https://docs.microsoft.com/en-us/aspnet/core/grpc/loadbalancing?view=aspnetcore-6.0

Parallel.ForEachAsync in .NET 6

using System.Net.Http.Headers;
using System.Net.Http.Json;

var userHandlers = new []  { "users/VahidN", "users/shanselman", "users/jaredpar", "users/davidfowl" };

using HttpClient client = new()
{
    BaseAddress = new Uri("https://api.github.com"),
};
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("DotNet", "6"));

ParallelOptions parallelOptions = new() { MaxDegreeOfParallelism = 3 };

await Parallel.ForEachAsync(userHandlers, parallelOptions, async (uri, token) =>
{
    var user = await client.GetFromJsonAsync<GitHubUser>(uri, token);
    Console.WriteLine($"Name: {user.Name}\nBio: {user.Bio}\n");
});

public class GitHubUser
{
    public string Name { get; set; }
    public string  Bio { get; set; }
}

References
https://www.hanselman.com/blog/parallelforeachasync-in-net-6