@manhng

Welcome to my blog!

Fundamentals Concepts in C#, ASP.NET, WCF

March 27, 2022 11:08

Fundamentals Concepts in C#, ASP.NET, WCF (edit)

var vs dynamic key word
multicast delegate, what happens if 3 methods returns 3 diff types
Binary search over linear search
Rest Services
WCF: logging client ip on server side without adding it from wcf client using message inspector
HTTP handler over .aspx files
Events fires in iis when hitting an aspx page
Thread Safety in singleton
project architecture
design pattern used in ur project
SP/Triggers/Functions 
select a date in back and get all months having first day as Sunday.
What is IDisposable
-------------------------------------------------------------------
what is impersonation.
Diff between cluster and non-cluster index
impact on performance using indexes
when to use structure over class

------------------------------------------------------------------
method overloading in wcf.
can we use WCF service dll in a client witout using endpoints.
diff between class and interface.
what's new in sql server 2008
what's new in C# 4.
How would you improve performance of a SP
generate a hierarchy from a table having data with parent-child relation
steps in code review
what warning we face if a virtual method of base class is not overridden in child class
what is static class
dispose vs finalize
role of using key world in c#
if we don't use [OperationContract] then what would will happed?
when we create a asp.net wcf website, then name the three major files.
for a private assembly LocalCopy is true or false
what is CLS
--------------------------------------------------------
What is dirty read?
Where SQL jobs are stored?
What is locking?
Diff between AngularJS and javascript?
What is role of script manager?
diff between varchar and nvarchar?
SQL Server Performance tuning.
----------------------------------------
what is ABC in WCF
what types of binding available in WCF
diff between . and # in jQuery
write a code block to call ajax call in jquery
diff table variable and temp table 
diff between cluster and non-cluster indexes
scope of CTE?
types of cacheing?
constant vs read only fields

when we hit like x.com, what events fires in IIS
code for writing factorial
diff IEnumberable and IList
what is HTTP handler? and tell about IHttpHandler interface
types of state management options in .NET
page life cycle
sequence of module and handler (mhpm)
DIFF INTERFACE AND CLASS
how we can remove sub-query from SELECT * FROM EMP where ID is not in (sub query)?
types of joins?
custom http handler for image/pdf file.


REST services
write code to print Fibonacci series
alternative of cursor
what new is in C#
query to remove duplicate records from a table.
query to get parent child relationship from a table using self join and CTE
what is full outer join and cartesian join
Less.js?
Angular.js vs Knockout.js vs Node.js? what is less.js?
what is CTE?
PLINQ?
COALESCE?
ROW_RANK?
what is static class
how to prevent inserting multiple rows in DB (use unique constraint)

public class Emp { public void GetAge() {return 45;} }
public class Emp1 : Emp { public void GetAge() {return 45;} }
will it compile?

query for concatenating column values separated by ',' for each customer
types of triggers?
DIFF INTERFACE AND CLASS
protection level and security in WCF

how to handle thousands of hits in sql server db instance? suggest options?
what is GAC
----------------------------------------
int Sum(int32 x, int 32y)
int Sum(int64 x, int64 y)
will above code compile ? if then on executing code Sum(1,2), which one will be invoked?


diff types of state management techniques
in-proc and out of proc session state management
Web Farm and Web Garden?
diff between delete and truncate
what is collation 
diff table variable and temp table
diff between cluster and non-cluster indexes
can we use try catch block in a cursor to ignore an error.
what is CTE?
how we can improve sql server performance
code review techniques?
what is DCL?
how can we improve performance of sp
what is co-related sub query?
what would you prefer? inline query or SP?
can we put redirect link in a gridview control and how
how to improve asp.net page performance  
WHAT IS MULTILEVEL AND MULTIPLE INTERFACE?
IS C# SUPPORTS MULTIPLE INHERITANCE?
what is pillars of OOPs? 
What are SDLC?
basics about scrum?
what are views? can we delete/update/add records using views?
in asp.net page there is master page, then page, then two user controls in page. if one clicks on user control button then, what are event sesuencing?
types of cacheing?
how many non-cluster can we have?
what is IsPostBack?
waht are ASP.NET temporary files?
diff between dataset and data reader?
val and ref types, heap and stack and boxing and unboxing
a class have an int field. so where int field would be stored?
Multilevel and multiple inheritance in C#.


singleton design pattern
proxy
observer
----------------------------------------------------------------------------------------

WAP to check for palindrome number
get first two numbers from a sorted array of ints whose sum is 47. Also optimize it order.
what is WCF?
Types of filter types in WCF routing service?
Service versioning via routing and service contract.
protocol bridging in wcf routing service.
getting sum of +ve and -ve number from a int column in sql server
-------------------------------------------------------------------------------------
What are the challanges to deploy a website in Load Balancing environment?
HTTP Handler to fetch imges from database?
How QA process is done in MIS?
What is single sign off?
How to manage file saving in load balancing mode?
WCF security, How authentication is manage in WCF and who manages certificates/token?
----------------------------------------------------------------------------------------
WAP to count occurrence of 'o' in a given string.
WAP to count total numbers of zeros from 1 to n.
-------------------------------------------------------------------------------------
WAP to eliminate duplicate occurrence of integers from a set = {1,1,1,2,3,3,4,4,4,4,9,9}
WAP for simple Threading in C#.
There are four interfaces having a method with same name. How a class implements these interfaces?
An Interface has four methods say m1,m2,m3,m4. Now there is a base class A and a child class of A
say B. A implements Interface. Now design class A and B such that A override methods m1 and m2 & B override m3 and m4.
-----------------------------------------------------------------------------------------------------------------------------
types of functions in SQL and how we can use table valued function in SP
diff CTE and temp table
performance of SP
default isolation level for the Microsoft SQL Server Database Engine
HTTP Handler and give an example of the same in your project
Why you have static classes for utility class
Can a class has private access specifier?[You can create a private class, as a member of another type]
if we disable cookie, then how form authentication work?
Fault Contract and structural fault handling in WCF
Entity Framework: how you will save and entity in DB
Exception handling in your project.
single sign on and WIF
-------
----------------------------------------------------------------------------------------------------------------------------
how to update product price category wise?
order of execution of instance and static constructors in a class hierarchy.
How instance and class level members and variables are stored in memory.
what is form authentication.
what is impersonation.
page life cycle in master, parent and child controls.
how to improve performance of a sp.
CTE and diff between table variable and CTE.
temp tables?
diff between factory and IOC.
locking and read only cursor.


what is lambda expression.
which design pattern you have used in your project?
-----------------------------------------------------------------------------------------------------------------------------
new features of SQL Server 2008.
there is a virtual method in a base class and a child class override that method. Now there is another child of child class.
We want to prevent that method to be overridden in second child class. how will do that?
Class vs interface.
there is button control on a web page. now we refresh that page. which events would be fired again?
On successive click on a button how we prevent multiple saving in DB from code?
 how to take left outer join in LINQ.
-----------------------------------------------------------------------------------------------------------------------------
what is polymorphism.
thread safe singleton pattern.
class vs interface.
in a maintenance state, what would you prefer? abstract class or interface.
request handling in IIS.
diff between factory and IOC.
---------------------------------------------------------------------------------------------------------------------------
Fault and Fault Contract.
Façade design pattern.
Diff Factory and Abstract Factory.
Why LINQ is slow.
There are n number of services endpoints but client doesn't want to expose them in client project but single at a time. what
would be the solution?
-----------------------------------------------------------------------------------------------------------------------------
How to handle 500 users in IIS.
Load balancer in IIS.
ABC in WCF.
Diff types of Binding in WCF.
How to decide type of a binding to be used.
REST and types of binding to prefer for REST and why.
Why we prefer REST.
diff between udf. and sp.
--------------------------------------------------------------------------------------------------------------------------------
 

WCF vs ASMX
Connection pooling
in which even we have to add attribute in controls
iis recycle
can we rename .asmx file .svc?


points to be considered while deploying the application over load balancer
--------------------------------------------------------------------------------------------------------

Method Level Security in WCF
LOCKING using EF
Binding for backward compatibility
WCF security
Unity vs MEF


SOLID and best practices
MVC vs MVVM
How to use observer design pattern
How to use MEF for extensibility


WCF service versioning
ORM over ADO.NET
Method overloading in WCF
------------------------------------------------
can private virtual method overridable in child class?
can class constructor has return type?
class vs interface?
can normal class can has abstract method
dispose vs finalize
can multiple catch block be executed
name some of exception in c#
value vs ref type. name some of them
how to implement priority que?
what data structure you would use for recursion?
MSMQ
user control vs custom control
serialization


how to know that which WCF service is hitted most?
in which scenario Web API would be better
why not you replace your wcf web services by web API
wcf vs asmx

how to know that which aspx page is hitted how many times?
how to maintain states for user level and for page level?
jQuery vs JavaScript

primary key vs unique key?
can all column of unique be not null
what is composite primary key
DBMS vs RDMBS
delete, truncate, drop
DML, DDL, TCL, DCL
union, intersection and diff operator
types of joins

References

https://docs.microsoft.com/vi-vn/dotnet/framework/wcf/wcf-and-aspnet-web-api

https://gist.github.com/gtechsltn/e8ae20408263c033a00eede869472176

https://gist.github.com/akhilbhardwaj23/1312657e88e4e70400c2

https://medium.com/@smitagudale712/cartesian-product-vs-full-outer-join-in-sql-server-5742a67c656f

https://www.c-sharpcorner.com/UploadFile/b19d5a/full-outer-join-and-cross-join-in-sql-server-2008/

WCF

Basic Concepts of WCF Service With simple Example. - DotNetFunda.com

A Beginner's Tutorial for Understanding Windows Communication Foundation (WCF) - CodeProject

Fundamental Windows Communication Foundation Concepts - WCF | Microsoft Docs

WCF Tutorial for Beginners with Example in Asp.Net Step By Step - ASP.NET,C#.NET,VB.NET,JQuery,JavaScript,Gridview (aspdotnet-suresh.com)

1.3. Fundamental WCF Concepts - Learning WCF [Book] (oreilly.com)

WCF and ASP.NET Web API - WCF | Microsoft Docs

WCF: Không dùng với SignalR được

Web API: Có thể dùng SignalR

WCF + Web API - Advanced Concepts

WCF Proxy Cookie Inspector

WCF - Authentication and Authorization in Enterprise Architecting (c-sharpcorner.com)

Cookie in ASP.NET Web API

How To Set Cookies in ASP.NET Web API (c-sharpcorner.com)

Cookie (HAY HAY HAY)

Cookie Resources (c-sharpcorner.com)

Pagination in Oracle

January 3, 2022 21:39

Pagination in Oracle (edit)

  • row_number()
  • rank()
  • dense_rank()
  • count(*)

Oracle with DbDataReader

Retrieving Data Using a DataReader - ADO.NET | Microsoft Docs

c# - What is the fastest way to read data from a DbDataReader? - Stack Overflow

.net - Timeout for OracleDataReader.Read Method - Stack Overflow

c# - Changing the where clause to use Oracle Command Parameter - Stack Overflow

Example

  1  select ename,sal,
  2   row_number()
  3     over (order by sal desc)rn,
  4   rank()
  5     over (order by sal desc)rnk,
  6   dense_rank()
  7     over (order by sal desc)drnk
  8   from emp
  9  order by sal desc

Oracle sql pagination with total pages or total entries - Stack Overflow (HAY HAY HAY)

Best Practice (HAY HAY HAY)

SELECT res.*,
CEIL(total_num_rows/10) total_num_pages
FROM (SELECT o.*,
row_number() OVER (ORDER BY CREATION_TS DESC, ID DESC) rn,
COUNT(*) OVER () total_num_rows
FROM ORCL.TODOITEM o
WHERE DESCRIPTION LIKE '%ask%') res
WHERE rn BETWEEN (1 - 1) * 10 + 1 AND 1 * 10;

SELECT res.*,
CEIL(total_num_rows/pageSize) total_num_pages
FROM (SELECT o.*,
row_number() OVER (ORDER BY CREATION_TS DESC, ID DESC) rn,
COUNT(*) OVER () total_num_rows
FROM ORCL.TODOITEM o
WHERE DESCRIPTION LIKE '%ask%') res
WHERE rn BETWEEN (pageNumber - 1) * pageSize + 1 AND pageNumber * pageSize;

Pagination And Total Number Of Rows From One SELECT – Andrey Zavadskiy – SQL and .NET developer, trainer, speaker

SELECT res.*,
       CEIL(total_num_rows/pagesize) total_num_pages
FROM   (SELECT o.*,
               row_number() OVER (ORDER BY orderdate DESC, shippingdate DESC) rn,
               COUNT(*) OVER () total_num_rows
        FROM   orders o
        WHERE  customerid LIKE 'A%') res
WHERE  rn BETWEEN (pagenumber - 1) * pagesize + 1 AND pagenumber * pagesize;

Sql - (Oracle) How get total number of results when using a pagination query? - Stack Overflow

How To Do Paging With ASP.NET Web API (c-sharpcorner.com)

Simple Solution

SELECT ID, DESCRIPTION, CREATION_TS, DONE, 
(SELECT COUNT(*) FROM (SELECT ID, DESCRIPTION, CREATION_TS, DONE
FROM ORCL.TODOITEM
ORDER BY CREATION_TS DESC)) TOTAL
FROM (SELECT A.ID, A.DESCRIPTION, A.CREATION_TS, A.DONE, rownum rn
FROM (SELECT ID, DESCRIPTION, CREATION_TS, DONE
FROM ORCL.TODOITEM
ORDER BY CREATION_TS DESC) A
WHERE rownum <= 20)
WHERE rn >= 11;

Oracle Data Provider for .NET

Oracle Data Provider for .NET (ODP.NET) features optimized ADO.NET data access to the Oracle database. ODP.NET allows developers to take advantage of advanced Oracle database functionality, including Real Application Clusters, self-tuning statement cache, Application Continuity, and Fast Connection Failover. Developers can also use popular .NET features, such as Entity Framework Core.

There are three driver types: ODP.NET Core; ODP.NET, Managed Driver; and ODP.NET, Unmanaged Driver. ODP.NET Core is designed for multi-platform .NET (Core) applications. ODP.NET, Managed Driver is 100% managed code .NET Framework provider. Developers deploy a single assembly in a deployment package smaller than 10 MB. ODP.NET, Unmanaged Driver is the traditional Oracle ADO.NET provider that uses the Oracle Database Client.

ODP.NET 21c add support for user-defined types, .NET 6, Entity Framework Core 6, binary JSON data type, Client Initiated Continuous Query Notification, and more.

Oracle Data Provider for .NET (ODP.NET)

Microsoft PowerPoint - Oracle Perf .NET BP.pptx

Best practice for pagination in Oracle? - Stack Overflow

C# - What are the best practices working with Oracle.DataAccess.Client? - Stack Overflow

C# - OracleCommand SQL Parameters Binding - Stack Overflow

C# OracleCommand SQL Call Procedure with Params - Stack Overflow

Using StringBuilder To Build Query

SELECT ID, DESCRIPTION, CREATION_TS, DONE
FROM ORCL.TODOITEM;

SELECT ID, DESCRIPTION, CREATION_TS, DONE
FROM (SELECT A.ID, A.DESCRIPTION, A.CREATION_TS, A.DONE, rownum rn
FROM (SELECT ID, DESCRIPTION, CREATION_TS, DONE
FROM ORCL.TODOITEM
ORDER BY CREATION_TS DESC) A
WHERE rownum <= 10)
WHERE rn >= 1;

SELECT *
FROM (SELECT A.*, rownum rn
FROM (SELECT *
FROM your_table
ORDER BY your_column) A
WHERE rownum <= :Y)
WHERE rn >= :X

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