Handle Clipboard Paste in WPF

public YourWindow()
{
    InitializeComponent();

    // "yourTextBox" is your TextBox
    DataObject.AddPastingHandler(yourTextBox, OnPaste);
}

private void OnPaste(object sender, DataObjectPastingEventArgs e)
{
    var isText = e.SourceDataObject.GetDataPresent(DataFormats.UnicodeText, true);
    if (!isText) return;

    var text = e.SourceDataObject.GetData(DataFormats.UnicodeText) as string;
    // Manipulate the text here
    text = text.Replace("oldValue", "newValue"); // Example manipulation

    // Set the new data
    e.DataObject = new DataObject(DataFormats.UnicodeText, text);
}

Note that this event is triggered after the user initiates the paste command but before the content is actually pasted into the TextBox, allowing you to modify or cancel the paste operation.

References
https://stackoverflow.com/questions/3061475/paste-event-in-a-wpf-textbox

Install chromedriver Automatically while using Selenium in C#

PM> Install-Package WebDriverManager
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using WebDriverManager;
using WebDriverManager.DriverConfigs.Impl;

namespace Test
{
    [TestFixture]
    public class Tests
    {
        private IWebDriver _webDriver;

        [SetUp]
        public void SetUp()
        {
            new DriverManager().SetUpDriver(new ChromeConfig());
            _webDriver = new ChromeDriver();
        }

        [TearDown]
        public void TearDown()
        {
            _webDriver.Quit();
        }

        [Test]
        public void Test()
        {
            _webDriver.Navigate().GoToUrl("https://www.google.com");
            Assert.True(_webDriver.Title.Contains("Google"));
        }
    }
}

References
https://github.com/rosolko/WebDriverManager.Net

Ignoring SSL certificate errors in C# RestSharp Library

//bypass ssl validation check by using RestClient object
var options = new RestClientOptions(baseurl) {
    RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
};
var restClient = new RestClient(options);

or in application level

//bypass ssl validation check globally for whole application.
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;

 

Ignoring SSL certificate errors in C# HttpClient

var handler = new HttpClientHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.ServerCertificateCustomValidationCallback = 
    (httpRequestMessage, cert, cetChain, policyErrors) =>
{
    return true;
};

var client = new HttpClient(handler);

 

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