Welcome to my blog!

Performance Tips

August 24, 2021 10:51

Performance Tips (edit)

C#.NET Tutorials For Beginners and Professionals - Dot Net Tutorials

  • Enums
  • Strings
  • Arrays
  • Lists
  • Interfaces
  • Switch Statements
  • Operators

5) Contains method in HashSet<T> and List<T>

HashSet<T> Class (System.Collections.Generic) | Microsoft Docs

List<T> Class (System.Collections.Generic) | Microsoft Docs

Sourcec# - Performance Benchmarking of Contains, Exists and Any - Stack Overflow

  • HashSet<T>.Contains :     0 ms (10000 items)
  • List<T>.Contains        : 569 ms (10000 items)


Source: theburningmonk/HashSet-vs-List-vs-Dictionary: Simple performance test of HashSet<T> vs List<T> and Dictionary<TKey, TValue> (github.com)

How to use HashSet in C# | InfoWorld

HashSet vs List vs Dictionary | theburningmonk.com

So sánh tốc độ List collection và HashSet collection trong C# - Tungnt.net

4) String

  • Sử dụng StringBuilder với những đoạn code cộng chuỗi cho n (n > 3) phép cộng chuỗi sẽ tốt hơn dùng toán tử cộng chuỗi.
  • Sử dụng toán tử "+" chuỗi khi có tổng cộng n (n <= 3) phép cộng chuỗi.
  • Thử với String.Concat
  • Thử với String.Join(";", array);
  • Thử với String.Format
  • Thử với String interpolation: @$"{}"

3/ Integer

  • Sử dụng Int32.TryParse sẽ tốt hơn Int32.Parse

Not Good

numVal = Int32.Parse("-105")


if (Int32.TryParse("-105", out int j)) // Does not throw exception

2/ Dictionary

Nếu bạn đang cố gắng lấy ra giá trị từ từ điển, thì TryGetValue (khóa, giá trị ngoài) là lựa chọn tốt nhất, nhưng nếu bạn đang kiểm tra sự hiện diện của khóa, để chèn mới, không ghi đè các khóa cũ, ContainsKey (khóa) là tùy chọn tốt nhất.

  • Sử dụng Dictionary.TryGetValue() sẽ tốt hơn Dictionary.ContainsKey() trong trường hợp cố gắng lấy ra giá trị từ từ điển.
  • Sử dụng Dictionary.ContainsKey() sẽ tốt hơn Dictionary.TryGetValue() trong trường hợp kiểm tra trùng lặp khóa để thêm phần tử vào Dictionary.


if (counts.ContainsKey("key"))
if (counts.TryGetValue("key", out T value)) // Does not throw exception

1/ DataReader

  • Sử dụng DataReader.GetSchemaTable khi cần lấy tên cột và kiểu dữ liệu trả về.
    • DataTable schemaTable = reader.GetSchemaTable();
    • var colNames = schemaTable.Rows.Cast<DataRow>().Select(row => row["ColumnName"] as string).ToArray();
    • var colDataTypes = schemaTable.Rows.Cast<DataRow>().Select(row => (row["DataType"] as Type).Name).ToArray();
  • Sử dụng DataReader.InitialLOBFetchSize = -1 (đối với query có chứa trường LOB) sẽ tốt hơn với các trường LOB và dữ liệu trả về cho mỗi LOB gần giống nhau.
  • Sử dụng DataColumn.Ordinal (column ordinal) nhanh hơn dùng DataColumn.ColumnName (column name): faster using column ordinals instead of column names.

Đọc trường LOBs (BLOBs, CLOBs, and NCLOBs)

using (var conn = new OracleConnection(OracleConnString))

using (var cmd = new OracleCommand(sql, conn))
var param = cmd.CreateParameter();
param.ParameterName = ":p__linq__0";
param.Value = 4879975843;
param.DbType = DbType.Int64;

cmd.InitialLOBFetchSize = -1;
using (var reader = cmd.ExecuteReader())
while (reader.Read())
if (colNames.Contains("ORDER_CODE") && !reader.IsDBNull("ORDER_CODE"))
dto.ORDER_CODE = reader.GetValueOrDefault<String>("ORDER_CODE");

Kiểm tra ExistColumn

DataTable schemaTable = reader.GetSchemaTable();
string[] colNames = schemaTable.Rows.Cast<DataRow>().Select(row => row["ColumnName"] as string).ToArray();
string[] colDataTypes = schemaTable.Rows.Cast<DataRow>().Select(row => (row["DataType"] as Type).Name).ToArray();
if (colNames.Contains("ORDER_CODE") && !reader.IsDBNull("ORDER_CODE"))
dto.ORDER_CODE = reader.GetValueOrDefault<String>("ORDER_CODE");

Lấy giá trị khi đọc DataReader

public static class DataReaderExtension
public static bool IsDBNull(this IDataReader dataReader, string columnName)
return dataReader[columnName] == DBNull.Value;

public static T GetValueOrDefault<T>(this IDataRecord row, string fieldName)
int ordinal = row.GetOrdinal(fieldName);
return row.GetValueOrDefault<T>(ordinal);

public static T GetValueOrDefault<T>(this IDataRecord row, int ordinal)
return (T)(row.IsDBNull(ordinal) ? default(T) : row.GetValue(ordinal));


Const vs Static vs Readonly in C# (exceptionnotfound.net)

Retrieving Data Using a DataReader - Samir Daoudi's Technical Blog (daoudisamir.com)

Create a Windows Service in C# or Convert your Console App to a Service - Samir Daoudi's Technical Blog (daoudisamir.com)

Run part of your C# Code under a different user - Samir Daoudi's Technical Blog (daoudisamir.com)

C#, Authenticate against AD - Samir Daoudi's Technical Blog (daoudisamir.com)

Modal PoP Up in SharePoint using BootStrap - Samir Daoudi's Technical Blog (daoudisamir.com)

Senior Full Stack Developer

August 20, 2021 21:59

Senior Full-Stack JS Developer (edit)

  • Front-end
  • Back-end
  • DevOps
  • Docker
  • Linux or Nginx | Ubuntu
  • Cloud Computing (Azure) (Amazon S3)

 minimum required skills list and it looks like this:

  • A basic understanding of how the internet works and HTTP requests (GET, POST, PUT, PATCH and DELETE) and the basic response codes (200, 404, 500)
  • HTML - W3Schools HTML
  • CSS - W3Schools CSS
  • A CSS frameworks like Tailwind or Bootstrap
  • JavaScript - W3Schools JS - yes just one language, it’s the only viable option for frontend so just use it on the backend as well.
  • Package manager like npm - @allthecode npm overview
  • NodeJS - W3Schools NodeJS and ExpressJS
  • React
  • React Component library like MaterialUI
  • Git version control - W3Schools Git
  • Know enough about security to know that you don’t know enough about security (CORS, HTTPS, Content Security Policy) - Web Dev Security Basics
  • A database technology (pick a or b)
  • How to make a REST API in NodeJS and Express
  • Docker and containerization - this is a more advanced topic however having an awareness of Docker and the basics of a Docker file would be a big ✅
  • Awareness of testing with Jest for Javascript.
  • Understanding of Linux commands and some basic OS principles.

Absolutely required items are in bold.

Senior Full-Stack .NET Developer


  • JavaScript + jQuery + ASP.NET Core MVC + ASP.NET Core WEB API
  • TypeScript + ASP.NET Core MVC + ASP.NET Core WEB API
  • Angular + ASP.NET Core WEB API
  • ReactJS + ASP.NET Core WEB API

ASP.NET Core Console Application - Starting Template

ShawnShiSS/aspnetcore-console-app-template: A starting template for ASP.NET Core 3.1 Console application that supports dependency injection, asynchronous programming, logging using Serilog, strongly-typed configuration, etc.. (github.com)

Getting Started With Entity Framework Core - Console | Learn Entity Framework Core

Transaction Scope

June 13, 2021 15:43

Transaction Scope (edit)

Implementing an Implicit Transaction using Transaction Scope | Microsoft Docs

Implementing an Implicit Transaction using Transaction Scope | Microsoft Docs

TransactionScope: A simple way to handle transactions in .NET | Code Wala (2018)

TransactionScope Considered Annoying | Josh the Coder (2020)

  • Transaction Management
  • Transaction or TransactionScope
  • TransactionScope
  • TransactionScope Timeout
  • Multiple databases
  • Dapper
  • Dapper CommandTimeout
  • Logging
  • Autofac DI using in Console Application

All About TransactionScope - CodeProject

Handling Transactions in .NET Using TransactionScope (codeguru.com)

  1. using (var transactionScope = new TransactionScope())
  2. using (var transactionScope = new TransactionScope(TransactionScopeOption.Required)) // default
  3. using (var transactionScope = new TransactionScope(TransactionScopeOption.RequiresNew))

c# - Advanced System.Transactions debugging - Stack Overflow

   <source name="System.Transactions" switchValue="Information">
    <add name="tx" type="System.Diagnostics.XmlWriterTraceListener" initializeData= "tx.log" />

[SOLVED] => Transaction scope timeout on 10 minutes (entityframework.net)

Transaction Scope uses the Machine config setting as the maximum timeout. The default machine timeout is 10 minutes.

TransactionScope Has a Default Timeout (stephencleary.com)

Passing TimeSpan.Zero into the TransactionScope constructor will instruct it to use the maximum timeout (TransactionManager.MaximumTimeout, which has a default value of 10 minutes) instead of the default. Unfortunately, the maximum timeout can only be increased by editing the machine.config file.

using new TransactionScope() Considered Harmful | Microsoft Docs

public class TransactionUtils {
    public static TransactionScope CreateTransactionScope() {
        var transactionOptions = new TransactionOptions();
        transactionOptions.IsolationLevel = IsolationLevel.ReadCommitted;
        transactionOptions.Timeout = TransactionManager.MaximumTimeout;
        return new TransactionScope(TransactionScopeOption.Required, transactionOptions);

Show me the code

using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew, new TransactionOptions() {
IsolationLevel = System.Transactions.IsolationLevel.Serializable,
Timeout = TimeSpan.FromMinutes(10)

void SomeMethod()
{ try { using (var _transactionScope = new TransactionScope(TransactionScopeOption.Required, transactionOptions)) { using (SqlConnection _connection = new SqlConnection(connectionstring)) { _connection.Open(); DoSomething()... } _transactionScope.Complete(); } } catch (TransactionAbortedException e) { nlog.Error(string.Format("The transaction has been aborted: {0}", e.Message)); throw; } catch (Exception e) { throw; } }

Autofac DI container in Console App

dependency injection - Correct use of Autofac in C# console application - Stack Overflow

c# - Autofac DI container in console app - Code Review Stack Exchange

DI in .NET Core Console Application

Dependency injection in .NET Core console applications (gunnarpeipman.com)

TransactionScope & Transaction in EF6

Entity Framework (EF) TransactionScope vs Database.BeginTransaction (vunvulearadu.blogspot.com)

Unit Testing

c# - Full integration test for a Console application - Code Review Stack Exchange

How to unit test C# Dynamics CRM interface code (alexanderdevelopment.net)

jordimontana82/fake-xrm-easy: The testing framework for Dynamics CRM and Dynamics 365 which runs on an In-Memory context and deals with mocks or fakes for you (github.com)

Console Application Basic

June 12, 2021 00:51

Console Application Basic (edit)

  • JsonTextWriter
  • Console Formatting (Indent) (PadLeft)
  • Console Output/Input Encoding
  • NLog & Log4Net
  • Debug Mode
  • Unicode characters (Janpanese)

Console Application | Microsoft Docs

Tutorial: Create a simple C# console app - Visual Studio | Microsoft Docs

Tutorial: Extend a simple C# console app - Visual Studio | Microsoft Docs

Perfect console application in .net Core: add unit tests – Michał Białecki Blog (michalbialecki.com) (.NET Core) (HAY HAY HAY)

Perfect console application in .net Core: set up dependency injection – Michał Białecki Blog (michalbialecki.com) (SimpleInjector) (Unit Testing) (Dependency Injection)

C#: Building a Useful, Extensible .NET Console Application Template for Development and Testing - CodeProject (HAY HAY HAY)

Some Best Practices for C# Application Development (Explained) - CodeProject (HAY HAY HAY)

Command line - Correct way to implement C# console application? - Stack Overflow (HAY HAY HAY)

C# Logging best practices in 2021 with examples and tools · Raygun Blog (HAY HAY HAY)

C# Console Application Examples (50+ C# Examples) – Programming, Pseudocode Example, C# Programming Example (csharp-console-examples.com)

Error messages should be written to stderr aka Console.Error, and normal output to stdout aka Console.Out. This is particularly important for "filter" type console apps whose output (stdout) can be piped to another process, e.g. in a batch file.

Generally if you encounter an error, write an error message to Console.Error and return a non-zero result. Or if it's an exception, just don't bother handling it.

To return a result code, you can either pass it as an argument to Environment.Exit, set the Environment.ExitCode property, or return a non-zero value from main.

For simple console apps I would:

  • have a helper class to parse the command line.

  • have a facade class that provides a testable API for the functionality implemented by your command line tool. Like most .NET APIs, this would normally throw an exception if an error occurs.

  • the main program simply uses the helper to parse the command line and calls the API passing the arguments passed from the command line. It optionally catches exceptions thrown from the API, logs them, writes a user-oriented error message to Console.Error and sets a non-zero return code.

But I wouln't consider this to be the one true way: there isn't really such a thing which is why you're unlikely to find the book you're looking for.

Debug mode

private void PrintFirstName()
string firstName = string.Empty;
firstName = GetFirstName();
private void PrintFirstName()
string firstName = GetFirstName();

try {
//Do something
catch(ex as Exception) {

Show me the code

Console.Title = typeof(Program).Name;

Console.OutputEncoding = Encoding.UTF8;
Console.InputEncoding = Encoding.UTF8;

// Set the Foreground color to blue
Console.ForegroundColor = ConsoleColor.Blue;

// Set the Background color to black
Console.ForegroundColor = ConsoleColor.Blue;

Console.BackgroundColor = ConsoleColor.Red;
Console.ForegroundColor = ConsoleColor.Black;

// Clear output screen

// Restore the original console colors.

public class ConsoleFormatting
    public static string Indent(int count)
        return "".PadLeft(count);

JsonWriter writer;

public Calculator()
    StreamWriter logFile = File.CreateText("calculatorlog.json");
    logFile.AutoFlush = true;
    writer = new JsonTextWriter(logFile);


ConsoleApplicationBase/Program.cs at master · TypecastException/ConsoleApplicationBase (github.com)

Console Command

ConsoleApplicationBase/ConsoleCommand.cs at master · TypecastException/ConsoleApplicationBase (github.com)

Console Formatting (HAY HAY HAY)

ConsoleApplicationBase/ConsoleFormatting.cs at master · TypecastException/ConsoleApplicationBase (github.com)


Please use the .net port of the apache commons cli API. This works great.


And the original API for concepts and introduction


Unicode characters

C# Unicode (Japanese Characters) - Stack Overflow

There are two conditions that must be satisfied in order for this to work:

  1. The console's output encoding must be able to represent Japanese characters
  2. The console's font must be able to render them

Condition 1 should be fairly simple to deal with; just set System.Console.OutputEncoding to an appropriate Encoding, such as a UTF8Encoding. (Of course, this won't work on Windows 9x, since that doesn't really support encodings or Unicode. But you aren't using that, now, are you?)

Satisfying condition 2 is a bit more involved:

  1. First, an appropriate font must be installed on the user's system. If there aren't any installed yet, the user will have to install some, perhaps by:

    • Opening intl.cpl ("Regional and Language Options" in the Control Panel on Windows XP in English)
    • Going to the "Languages" tab
    • Enabling "Install files for East Asian languages"
    • Clicking "OK"
  2. Actually getting the console to use such a font seems to be fairly hairy; see the question: How to display japanese Kanji inside a cmd window under windows? for more about that.

c# - How to write Unicode characters to the console? - Stack Overflow

Besides Console.OutputEncoding = System.Text.Encoding.UTF8;

for some characters you need to install extra fonts (ie. Chinese).

In Windows 10 first go to Region & language settings and install support for required language: enter image description here

After that you can go to Command Prompt Proporties (or Defaults if you like) and choose some font that supports your language (like KaiTi in Chinese case): enter image description here

Now you are set to go: enter image description here


Console.OutputEncoding Property (System) | Microsoft Docs

Encoding.UTF8 Property (System.Text) | Microsoft Docs

Change Console Foreground And Background Color In C# (c-sharpcorner.com)

C# | How to change Foreground Color of Text in Console - GeeksforGeeks

C# Convert console output UTF-8 to display in textbox - special characters problems (microsoft.com)


Recent posts