@manhng

Welcome to my blog!

Get Method Body as Text

November 11, 2020 22:15

Get Method Body as Text (edit)

Same QuestionGet Method Body as Text - CodeProject

Best SolutionC# - Programatically insert line of code before end of method body - Stack Overflow

Log Method Name.NET - Inserting code into C# methods right before compilation - Stack Overflow

  • HTTP
  • Authorization
  • OAuth 2.0 (more)
  • Azure DevOps
  • Azure DevOps Services
  • Personal Access Token
  • Visual Studio Online
  • RESTful APIs

Authorization using OAuth 2.0 - Azure DevOps | Microsoft Docs

Acessing Azure DevOps By Using PAT (c-sharpcorner.com)

Using REST APIs of TFS and Visual Studio Online | DotNetCurry

Use REST APIs to access Azure DevOps (formerly VSTS) | DotNetCurry

Samples:

Browse Code Examples (codegrepper.com)

https://www.codegrepper.com/code-examples/

GitHub - intuit/QuickBooks-V3-DotNET-SDK: .Net SDK for QuickBooks REST API v3 services

https://github.com/intuit/QuickBooks-V3-DotNET-SDK

using System;
using System.Diagnostics;
using System.IO;
using System.Text;
 
namespace ConsoleApp1
{
    /// <summary>
    /// Programatically insert line of code before end of method body
    /// </summary>
    public class Program
    {
        /// <summary>
        /// Programatically insert line of code before end of method body
        /// https://stackoverflow.com/questions/30108792/programatically-insert-line-of-code-before-end-of-method-body
        /// </summary>
        /// <param name="args"></param>
        private static void Main(string[] args)
        {
            const string methodName = "HelloWorld";
            const string filePath = @"C:\Users\Nguyen Viet Manh\Desktop\FileHelper.cs";
 
            string[] fileContent = System.IO.File.ReadAllLines(filePath, Encoding.UTF8);
 
            //const string newCode = "<--------INSERT CODE HERE -------->";
            //string fileContents = System.IO.File.ReadAllText(filePath, Encoding.UTF8);
 
            ////this should return what you want
            //string newFileContents = Regex.Replace(
            //       fileContents,
            //       @"(?<=HelloWorld([^}]*})\s*?)",
            //       Environment.NewLine + newCode + Environment.NewLine,
            //       RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace);
 
            //System.IO.File.WriteAllText(filePath.Replace(".cs", "2.cs"), newFileContents, Encoding.UTF8);
 
            int positionStart = FindLineOfCodeMethod(filePath, methodName);
            int positionEnd = FindEndOfMethod(filePath, methodName);
 
            StringBuilder sb = new StringBuilder();
            for (int i = positionStarti <= positionEndi++)
            {
                sb.AppendLine(fileContent[i]);
            }
            string newFilePath = filePath.Replace(".cs"string.Format(".{0}.cs", methodName));
            System.IO.File.WriteAllText(newFilePathsb.ToString(), Encoding.UTF8);
 
            Console.WriteLine("Hello World!");
        }
 
        private static int FindLineOfCodeMethod(string filenamestring methodToFind)
        {
            string methodName = string.Empty;
 
            if (methodToFind != null)
            {
                methodName = string.Concat(" "methodToFind.Trim(), "("); // "HelloWorld" => " HelloWorld("
            }
 
            int countStartBracket = 0;
            int countEndBracket = 0;
 
            string line = "";
            int lineNumber = -1;
 
            bool foundEnd = false;
            bool foundMethod = false;
 
            System.Action countBrackets = () =>
            {
                if (line.Contains("{"))
                {
                    countStartBracket++;
                }
 
                if (line.Contains("}"))
                {
                    countEndBracket++;
                }
 
                //If we found the method and the start and end bracke- count is the same we found the end (and they are not zero)
                if (foundMethod && countStartBracket == countEndBracket && countStartBracket != 0 && countEndBracket != 0)
                {
                    foundEnd = true;
                }
            };
 
            //Pass the file path and file name to the StreamReader constructor
            using (StreamReader sr = new StreamReader(filename))
            {
                //Continue to read until you reach end of file
                while (line != null)
                {
                    lineNumber++;
 
                    //Read next line, if it's null, we reached end of file and didn't find the place
                    if ((line = sr.ReadLine()) == null)
                    {
                        return -1;
                    }
 
                    //If we haven't found the method yet, we check each line to see if it's on this line
                    if (!foundMethod)
                    {
                        if (line.Contains(methodName))
                        {
                            foundMethod = true;
                            return lineNumber;
                        }
                    }
 
                    //If it was or has been found we count brackets to determine the closing one
                    if (foundMethod)
                    {
                        countBrackets();
                    }
 
                    if (foundEnd)
                    {
                        Debug.WriteLine(lineNumber);
                        return lineNumber;
                    }
                }
                return -1;
            }
        }
 
        private static int FindEndOfMethod(string filenamestring methodToFind)
        {
            int countStartBracket = 0;
            int countEndBracket = 0;
 
            string line = "";
            int lineNumber = -1;
 
            bool foundEnd = false;
            bool foundMethod = false;
 
            System.Action countBrackets = () =>
            {
                if (line.Contains("{"))
                    countStartBracket++;
                if (line.Contains("}"))
                    countEndBracket++;
 
                //If we found the method and the start and end bracke- count is the same we found the end (and they are not zero)
                if (foundMethod && countStartBracket == countEndBracket && countStartBracket != 0 && countEndBracket != 0)
                    foundEnd = true;
            };
 
            //Pass the file path and file name to the StreamReader constructor
            using (StreamReader sr = new StreamReader(filename))
            {
                //Continue to read until you reach end of file
                while (line != null)
                {
                    lineNumber++;
 
                    //Read next line, if it's null, we reached end of file and didn't find the place
                    if ((line = sr.ReadLine()) == null)
                        return -1;
 
                    //If we haven't found the method yet, we check each line to see if it's on this line
                    if (!foundMethod)
                        if (line.Contains(methodToFind))
                            foundMethod = true;
 
                    //If it was or has been found we count brackets to determine the closing one
                    if (foundMethod)
                        countBrackets();
 
                    if (foundEnd)
                    {
                        Debug.WriteLine(lineNumber);
                        return lineNumber;
                    }
                }
                return -1;
            }
        }
    }
}
 
// ****************************************
//
// Input: C:\FileHelper.cs
//
// ****************************************
//using System;
 
//namespace MyNameSpace
//{
//    public class MyClass
//    {
//        public void HelloWorld(string somevalue)
//        {
//            //hello world
//            switch (somevalue)
//            {
//                case "Hello World":
//                    //do something here
//                    break;
 
//                default:
//                    //HelloWorld
//                    break;
//            }
 
//            //HelloWorld
//            //HelloWorld
//            HelloWorld(somevalue);
//        }
//    }
//}
 
// ****************************************
//
// Output: C:\FileHelper.HelloWorld.cs
//
// ****************************************
//public void HelloWorld(string somevalue)
//{
//    //hello world
//    switch (somevalue)
//    {
//        case "Hello World":
//            //do something here
//            break;
 
//        default:
//            //HelloWorld
//            break;
//    }
 
//    //HelloWorld
//    //HelloWorld
//    HelloWorld(somevalue);
//}

Guide to DateTime Manipulation

September 1, 2020 11:24

Guide to DateTime Manipulation (edit)

  • Greenwich Mean Time (GMT)
  • Coordinated Universal Time (UTC)
  • International Organization for Standardization (ISO)

https://www.toptal.com/software/definitive-guide-to-datetime-manipulation

https://www.geeksforgeeks.org/javascript-date-utc-method/

https://css-tricks.com/everything-you-need-to-know-about-date-in-javascript/

How to write the current date time to logging file with the same format?

UTC & ISO in C#

var d1 = DateTime.Now;
var s1 = d1.ToUniversalTime().ToString("yyyy-MM-dd\\THH:mm:ss.fffK"); // Return => 2020-09-01T04:52:11.511Z
Console.WriteLine(s1);

var d2 = DateTime.Now;
var s2 = d2.ToUniversalTime().ToString("ddd, dd MMM yyyy HH:mm:ss 'GMT'"); // Return => Tue, 01 Sep 2020 04:46:11 GMT
Console.WriteLine(s2);

DateTime in C#

using System;
using System.Globalization;

namespace ConsoleApp1
{
internal class Program
{
private const string DateFormatInJavaScript = "yyyy-MM-dd"; //For example: 2019-07-31

private const string DateTimeString = "yyyy-MM-dd HH:mm:ss"; //For example: 2019-07-31 15:00:23

private const string DateTimeUTCString = "ddd, dd MMM yyyy HH:mm:ss 'GMT'"; //For example: Tue, 01 Sep 2020 04:46:11 GMT

private const string DateTimeGMTString = "ddd, dd MMM yyyy HH:mm:ss 'GMT'"; //For example: Tue, 01 Sep 2020 04:46:11 GMT

private const string DateTimeISOString = "yyyy-MM-dd\\THH:mm:ss.fffK"; //For example: 2020-09-01T04:52:11.511Z

private const string TimeFormatInJavaScript = "HH:mm"; //For example: 14:31

private static void Main(string[] args)
{
string dateString = "2020-09-01T04:52:11.511Z";

DateTime dt = DateTime.ParseExact(dateString.Substring(0, 24), DateTimeISOString, CultureInfo.InvariantCulture);

Console.WriteLine("Before converting:");
Console.WriteLine(dateString);

Console.WriteLine("After converting:");
Console.WriteLine(dt.ToUniversalTime().ToString(DateTimeISOString));
Console.WriteLine(dt.ToUniversalTime().ToString(DateTimeUTCString));
Console.WriteLine(dt.ToUniversalTime().ToString(DateTimeGMTString));
}
}
}

UTC & ISO in SQL + C#

https://stackoverflow.com/questions/1820915/how-can-i-format-datetime-to-web-utc-format/

https://stackoverflow.com/questions/44788305/c-sharp-convert-datetime-object-to-iso-8601-string

string foo = yourDateTime.ToUniversalTime() .ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'");

UTC & ISO in JavaScript

https://www.w3schools.com/jsref/jsref_obj_date.asp

var d1 = new Date();
var s1 = d1.toISOString();
console.log(s1);
// Return => 2020-09-01T04:34:35.194Z

var d2 = new Date();
var s2 = d2.toUTCString(); // Note: .toUTCString ~ .toGMTString()
console.log(s2);
Tue, 01 Sep 2020 04:34:58 GMT

Web API (C#)

https://stackoverflow.com/questions/31987050/how-to-force-iso-format-yyyy-mm-ddthhmmss-sss-on-the-json-output

public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
...
config.Formatters
.JsonFormatter
.SerializerSettings
.DateFormatString = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffK";
}
}

Utils (C#)

https://gist.github.com/dmorosinotto/81e8d809a3833b7caf7b3c813703a8e6

Format DateTime in C#

June 30, 2020 11:57

Date Format in CSharp (edit)

Utils Class

namespace ConsoleApp1
{
internal class Program
{
private static void Main(string[] args)
{
var dtHddt = new System.Data.DataTable();

dtHddt.Columns.Add("Dosage", typeof(int));
dtHddt.Columns.Add("Drug", typeof(string));
dtHddt.Columns.Add("Patient", typeof(string));
dtHddt.Columns.Add("commandDate", typeof(System.DateTime));

dtHddt.Rows.Add(25, "Indocin", "David", null);
dtHddt.Rows.Add(50, "Enebrel", "Sam", System.DateTime.Now);
dtHddt.Rows.Add(10, "Hydralazine", "Christoff", System.DateTime.Now);
dtHddt.Rows.Add(21, "Combivent", "Janet", System.DateTime.Now);
dtHddt.Rows.Add(100, "Dilantin", "Melanie", System.DateTime.Now);

string s = string.Empty;
for (int i = 0; i < dtHddt.Rows.Count; i++)
{
s = dtHddt.GetSafeDate(i, "commandDate");
System.Console.WriteLine(s);
}
}
}

public static class DataTableExt
{
public static string GetSafeDate(this System.Data.DataTable dt, int idx, string colName)
{
string s = string.Empty;
try
{
if (dt != null &&
dt.Rows.Count > 0 &&
dt.Rows[idx][colName] != null &&
dt.Rows[idx][colName] != System.DBNull.Value)
{
var myDateTime = System.Convert.ToDateTime(dt.Rows[idx][colName]);
s = myDateTime.ToString("dd/MM/yyyy hh:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture);
}
}
catch (System.Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
return s;
}
}
}

Usage

dtHddt: System.Data.DataTable
string s = dtHddt.GetSafeDate(0, "commandDate");

Điểm mới trong .NET Core (C#)

July 27, 2018 10:25

Điểm mới trong .NET Core (C#) (edit)

Hôm nay mình sẽ giới thiệu từ mới để các bạn tự khám phá trong ASP.NET Core 2.1

  • Span<T>
  • Memory<T>
  • ReadOnlySpan<T>

Properties

// Normal way
public string FullName
{
    get { return string.Format("{0} {1}", FirstName, LastName); }
}
 
// Using Expression (C# 6.0)
public string FullName => string.Format("{0} {1}", FirstName, LastName);
 
// Above code can be more consize using string interpolation
public string FullName =>$"{FirstName} {LastName}";

Methods

// Normal way
public string GetFullName(string firstname, string middleName, string lastName)
{
    return middleName == null ? $"{firstname} {lastName}" : $"{firstname} {middleName} {lastName}";
}
 
// Using Expessions
public string GetFullName(string firstname, string middleName, string lastName) => middleName == null ?
             $"{firstname} {lastName}" : $"{firstname} {middleName} {lastName}";

Auto properties

public string Name { get; set; }

Constructor (hàm tạo)

// Earlier
public Person(string name)
{
    this.Name = name;
}
 
// With C# 7.0
public Person(string name) => this.Name = name;

Destructor (hàm hủy)

// Earlier
~Person()
{
    Console.WriteLine("Person's destructor");
}
 
// Using Expressions
~Person() => Console.WriteLine("Person's destructor");

Readonly struct

public readonly struct Person
{
    public string FirstName { get; }
 
    public string LastName { get; }
 
    public int Age { get; }
 
    public Person(string firstName, string lastName, int age)
    {
        this.FirstName = firstName;
        this.LastName = lastName;
        this.Age = age;
    }
 
}

Ôn lại lý thuyết về Const, ReadOnly, Static và Struct

Const là một hằng số phải gán giá trị khi khai báo (complie-time constant). Mặc định const là static nên không thể thêm static trước hoặc sau const

ReadOnly là một biến được khởi tạo giá trị khi khai báo và có thể thay đổi giá trị ở hàm tạo (run-time constant).

Static đưa vào trước biến để mọi đối tượng đều có thể truy xuất vào. Chỉ áp dụng cho class, fields, properties, operators, events, constructor, không áp dụng được cho destructor và index

Struct:

Kinh nghiệm xử lý try catch throw exception

Đơn giản chỉ cần "throw;" try { ... } catch (Exception ex) { throw; }

Nếu sử dụng "throw ex;" sẽ mất stack trace dẫn đến việc debug lỗi gặp khó khăn.

Kinh nghiệm xử lý Concurrency Conflickts trong EF Core

https://docs.microsoft.com/en-us/ef/core/saving/concurrency

Kinh nghiệm xử lý Concurrency Conflicts trong EF 6

https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/handling-concurrency-with-the-entity-framework-in-an-asp-net-mvc-application

Làm thế nào để kiểm soát optimistic concurrency.

Bạn cần có một cột rowversion là một kiểu dữ liệu timestamp.

SQL Server tự động khởi tạo số nhị phân duy nhất bất cứ khi nào thao tác insert hoặc update được thực hiện trong một bảng.

https://www.codeproject.com/Articles/817432/Optimistic-Concurrency-in-Entity-Framework-Code-Fi

Technical Stack là gì?

Stack là gì? Stack là một nền tảng hệ điều hành và những phần mềm đi kèm

ELK Stack là gì?

ELK Stack là tập hợp 3 phần mềm đi chung với nhau, phục vụ cho công việc logging. Ba phần mềm này lần lượt là:

  • Elasticsearch: Cơ sở dữ liệu để lưu trữ, tìm kiếm và query log
  • Logstash: Tiếp nhận log từ nhiều nguồn, sau đó xử lý log và ghi dữ liệu và Elasticsearch
  • Kibana: Giao diện để quản lý, thống kê log. Đọc thông tin từ Elasticsearch

SQL tiếng Việt

https://www.mastercode.vn/blog/sql-server/

Xóa log file của SQL Server

https://www.mastercode.vn/blog/web-development/giam-dung-luong-tren-he-thong-server-xoa-cac-file-khong-can-thiet.97

Caching

Các loại Local Cache Store

  • In-process
  • Out-of-process

Các loại Remote Cache

  • Memcached
  • Azure
  • DiskCache
  • Redis

Top 10 OWASP (link tiếng Việt)

  1. Injection
  2. Cross-Site Scripting (XSS)
  3. Broken Authentication and Session Management
  4. Insecure Direct Object References
  5. Cross-Site Request Forgery (CSRF)
  6. Security Misconfiguration
  7. Insecure Cryptographic Storage
  8. Failure to Restrict URL Access
  9. Insufficient Transport Layer Protection
  10. Unvalidated Redirects and Forwards

Tìm hiểu thêm

C# 6.0 features

C# 7.X features

Dapper Log4net AutoMapper

March 13, 2018 08:35

How to use the Dapper (edit)

- Create new ASP.NET Web Application called WebApplication1 (MVC: Web Forms, MVC, Web API) based on .NET Framework 4.5.2

- Nuget packages:

  + Install-Package log4net

  + Install-Package Dapper

  + Install-Package MySql.Data

  + Install-Package AutoMapper

  + Install-Package Newtonsoft.Json

- Web.config/App.config

  + Define connection string in <connectionStrings> or <appSettings>

- Controllers/HomeController.cs

- Documentation

Dapper with MS SQL Server

- Dapper with raw SQL

 

- Dapper with Stored Procedure

- Sample code

Dapper with MySQL

Nuget notes

+ .NET Framework 4.5
+ ASP.NET MVC 5.2
+ ASP.NET Web API 2.2
+ Web Pages 3.2

Update-Package
Install-Package jQuery -Version 1.12.4
Install-Package Bootstrap -version 3.3.7
Install-Package modernizr
Install-Package Newtonsoft.json
Install-Package log4net
Install-Package Dapper -Version 1.50.2 (.NET Framework 4.5)
Install-Package Microsoft.AspNet.WebApi (-Version 5.2.4)
Install-Package Swashbuckle (-Version 5.6.0)

Web API & Swagger + OAuth2
http://wmpratt.com/swagger-and-asp-net-web-api-part-1/

http://wmpratt.com/part-ii-swagger-and-asp-net-web-api-enabling-oauth2/

https://www.codeproject.com/Articles/1187872/Token-Based-Authentication-for-Web-API-where-Legac

http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/ 

CSharp

May 19, 2017 10:22

C# IN ADVANCED

- Asynchronous & parallel programming
- Async Landscape in .NET
- Thread & Thread pool
- ParallelFor & ParallelForEach
- ParallelInvoke
- Parallel LINQ (PLinQ)
- Lambda expression
- Some new features on C#6

Programming with C#

May 15, 2017 01:22

C# Programming Guide

https://docs.microsoft.com/en-us/dotnet/articles/csharp/programming-guide/index

Programming with C#

About this course

Skip Course Description

 

To help ensure that your learning experience is good, please note that this course is not for beginners or those new to programming. You must have prior programming experience in an object-oriented programming language as there are concepts that are mentioned in the course that are assumed to be prior knowledge and are not explained in detail. If you are new to programming, it is highly recommended that you visit this page to learn some of the fundamentals first.

Learning C# provides a solid foundation in object-oriented programming knowledge, paves the way for learning other programming languages, and positions those who complete this course for a wide variety of in-demand computer programming jobs.  
 
The C# programming language was created to be an object-oriented programming language that offers ease of use, familiarity to C/C++ and Java developers, along with enhanced memory and resource management.  C# is prevalent on the Microsoft platform but is also being used to develop software that runs on Linux, Android, and iOS devices.  
 
This course aims to teach the basics of C# all the way through the advanced features of the language. 
 
This course is not a beginner course on C#, although beginners can still learn a lot from the material. It is intended to provide an introduction to the C# language and the world of .NET programming for existing programmers who need or want to learn more about C# and managed code development.

https://docs.microsoft.com/en-us/dotnet/articles/csharp/programming-guide/index

What you'll learn

  • C# Syntax
  • C# Language Fundamentals
  • OOP in C#
  • .NET Framework concepts

Categories

Recent posts