Transactions in Entity Framework

1. Using DbContextTransaction

Entity Framework allows you to manage transactions using the BeginTransaction method of the DbContext.

Example:

using (var context = new YourDbContext())
{
    using (var transaction = context.Database.BeginTransaction())
    {
        try
        {
            // Perform multiple operations
            var newEntity = new YourEntity { Name = "Example" };
            context.YourEntities.Add(newEntity);
            context.SaveChanges();

            var anotherEntity = new AnotherEntity { Value = "Test" };
            context.AnotherEntities.Add(anotherEntity);
            context.SaveChanges();

            // Commit transaction
            transaction.Commit();
        }
        catch (Exception ex)
        {
            // Rollback transaction if there is any error
            transaction.Rollback();
            Console.WriteLine(ex.Message);
        }
    }
}

2. Using TransactionScope

You can use the TransactionScope class for more advanced scenarios, which allows transactions across multiple DbContext instances.

Example:

using System.Transactions;

using (var scope = new TransactionScope())
{
    try
    {
        using (var context1 = new YourDbContext())
        {
            // Perform operations on first DbContext
            var entity1 = new YourEntity { Name = "Entity1" };
            context1.YourEntities.Add(entity1);
            context1.SaveChanges();
        }

        using (var context2 = new AnotherDbContext())
        {
            // Perform operations on second DbContext
            var entity2 = new AnotherEntity { Value = "Entity2" };
            context2.AnotherEntities.Add(entity2);
            context2.SaveChanges();
        }

        // Commit the transaction
        scope.Complete();
    }
    catch (Exception ex)
    {
        // Transaction will be rolled back automatically if not completed
        Console.WriteLine(ex.Message);
    }
}

3. Using EF Core with IDbContextTransaction

In Entity Framework Core, transactions are handled using the IDbContextTransaction interface.

Example:

using (var context = new YourDbContext())
{
    using (var transaction = await context.Database.BeginTransactionAsync())
    {
        try
        {
            // Perform database operations
            context.YourEntities.Add(new YourEntity { Name = "Entity1" });
            await context.SaveChangesAsync();

            context.AnotherEntities.Add(new AnotherEntity { Value = "Entity2" });
            await context.SaveChangesAsync();

            // Commit transaction
            await transaction.CommitAsync();
        }
        catch (Exception ex)
        {
            // Rollback transaction
            await transaction.RollbackAsync();
            Console.WriteLine(ex.Message);
        }
    }
}

 

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