Thursday, October 22, 2015

Different encoding systems for "Hello" example:

48 65 6C 6C 6F

Unicode (little-endian) encoding with no BOM.
48 00 65 00 6C 00 6C 00 6F 00

Unicode (little-endian) encoding with BOM
FF FE 48 00 65 00 6C 00 6C 00 6F 00

Unicode (big-endian) encoding with no BOM
00 48 00 65 00 6C 00 6C 00 6F

Unicode (big-endian) encoding with BOM
FE FF 00 48 00 65 00 6C 00 6C 00 6F

UTF-8 encoding
EF BB BF 48 65 6C 6C 6F

UTF-7 encoding
2B 2F 76 38 2D 48 65 6C 6C 6F


Friday, October 16, 2015

How to fix issue "The target GatherAllFilesToPublish does not exist"?

#1 Option:
Add following tag into project file:
  <Target Name="GatherAllFilesToPublish">
But will output all of source files into web site.

#2 Option:
<Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" Condition="false"/>
<Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" Condition="'$(VSToolsPath)' != ''" />


Wednesday, October 7, 2015


Excerpt from DDD book:

"The beauty of objects is their ability to encapsulate all that so that client code is simple and can be interpreted in terms of higher-level concepts.
But if the interface doesn’t tell the client developer what he needs to know in order to use the object effectively, he will have to dig into the internals and understand the details. A reader of the client code will have to do that same. Then most of the value of the encapsulation is lost. We are always fighting cognitive overload. If the client developer’s mind is flooded with detail about how a component does its job, his mind isn’t clear to work out the intricacies of the client design. This is true even when the same person is playing both roles, developing and using his own code, because even if he doesn’t have to learn those details, there is a limit to how many factors he can consider at once."

It is so true if working on a larger dev team.

Thursday, September 24, 2015

Another way to talk about CQRS/Event Sourcing

"A more promising model, used in some systems, is to think of a database as an always-growing collection of immutable facts. You can query it at some point in time — but that’s still old, imperative style thinking. A more fruitful approach is to take the streams of facts as they come in, and functionally process them in real-time."

Turning the database inside-out with Apache Samz

Monday, September 14, 2015

How to swap two numbers without third variable?

int first,second ;
first = 1;
second = 2;
first = first + second;
second = first - second;
first = first - second;

Friday, August 14, 2015

Practicing Programming

Practicing to make skills better, no problem, but many Programming technologies are going away all the time.

Monday, August 10, 2015

Architects Should Code: The Architect's Misconception

Architecture Spike

The architect could lead a development spike focused on architectural discovery or delivery. A spike is a functional, proof of concept implementation for some aspect of the architecture used to identify or mitigate risk by exploring a new technology.

Tuesday, August 4, 2015

How to solve log4net not writing into database problem

log4net not writing into database problem
Turn on debug, no problem found. At last, change bufferSize from 400 to 1
<bufferSize value="1" />
Everything is working fine.


Thursday, July 30, 2015

How to compare two tables schema by SQL query in MS SQL?

How to compare two tables schema  by SQL query in MS SQL?
SELECT name,system_type_id,user_type_id,max_length,precision,scale,collation_name,is_nullable into #Tablescehma1
FROM sys.columns WHERE object_id = OBJECT_ID('TABLE1')

SELECT name,system_type_id,user_type_id,max_length,precision,scale,collation_name,is_nullable into #Tablescehma2
FROM sys.columns WHERE object_id = OBJECT_ID('TABLE2')

select * from #Tablescehma1
select * from #Tablescehma2

Monday, July 27, 2015

Secondary skills for software engineers

Secondary skills for software engineers

What are the most important skills?
1. Language(s)
2. Problem
3. Naming
4. Communication

Thursday, July 23, 2015

In ASP.NET Logout: GET or POST?

In ASP.NET Logout: GET or POST?

I just switch from POST to GET, and tested in Chrome, no problem found for now
Suggestion from Stackoverflow

Monday, June 15, 2015

Long sentence

Long sentence =>
complicated sentence =>
- Need to remember context
- Not to extend and repeat previsoue idea

Thursday, June 11, 2015

Binary tree search logic in pseudo code

  node search (node, key) {
       if node is null then return null;
       if node.key = key then
          return node
       if key < node then
          return search (node.left, key);
          return search (node.right, key);


Wednesday, June 10, 2015

How to solve problem "Inheritance security rules violated by type: 'System.Web.WebPages.Razor.WebPageRazorHost'. Derived types must either match the security accessibility of the base type or be less accessible."

How to solve problem "Inheritance security rules violated by type: 'System.Web.WebPages.Razor.WebPageRazorHost'. Derived types must either match the security accessibility of the base type or be less accessible."

This error happens after add Razor engine into ASP.NET MVC 4 project by nuget package.

I fixed this problem by remove following part from web.config
        <assemblyIdentity name="System.Web.Razor" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="" newVersion="" />

Default ASP.NET MVC 4 razor engine is version 2, and nuget for RazorEngine project is version 3.

Monday, June 8, 2015

Make hard coding your default choice

To my experiences, I divide this kind of  "magic number" into three categories:

#1 Very small chance to change: Hard coding
#2 Good chance to change in the future:
  Hard coding with default value but checking config file first
string ConfigSetting_SMTP_host = ConfigurationManager.AppSettings["SMTP_host"] ?? "";

#3 For sure change (such as dev vs product environment): read from config file directly

Tuesday, June 2, 2015

How to solve Access is denied problem for a ASP.NET MVC 4 Windows Authentication project

Create a ASP.NET MVC 4 intranet project, and run, get following error:

Access is denied
Description: An error occurred while accessing the resources required to serve this request. The server may not be configured for access to the requested URL.
Error message 401.2.: Unauthorized: Logon failed due to server configuration.  Verify that you have permission to view this directory or page based on the credentials you
supplied and the authentication methods enabled on the Web server.  Contact the Web server's administrator for additional assistance.

Press F4 to get project property windows:
Change Anonymous to Disabled
Change Windows Authentication to Enabled.

(Why just publish a correct project template for Windows Authentication in the first place?)

Friday, May 22, 2015

How to solve problem: System.IO.FileLoadException was unhandled by user code HResult=-2146234304?

Make sure you get latest version WebGrease 1.6

Full error message:
System.IO.FileLoadException was unhandled by user code   HResult=-2146234304
  Message=Could not load file or assembly 'WebGrease, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
  FileName=WebGrease, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35
  FusionLog==== Pre-bind state information ===
LOG: DisplayName = WebGrease, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35

Install-Package Microsoft.AspNet.Web.Optimization
Update-Package WebGrease
Uninstall-Package Microsoft.AspNet.Web.Optimization
Uninstall-Package WebGrease
Install-Package Microsoft.AspNet.Web.Optimization
Update-Package WebGrease

Wednesday, May 20, 2015

How to fix ASP.NET MVC Bundle not working (not rendering script files)

To my case, it is because System.Web.Optimization  is version 1.0.0
After getting the latest version (1.3), everything is fine

How to fix "The target GatherAllFilesToPublish does not exist"

By adding following section into Project file:

<Target Name="GatherAllFilesToPublish">

Wednesday, May 13, 2015

How to apply i18n to support multiple languages in ASP.NET MVC?

For ASP.NET MVC part: Functions to switch language and get resource by culture:
javascript -> cookie -> Base Controller/Razor view base page -> i18n lib functions

How to edit PO files
#1 Online editor: edit, add, and delete etc.
#2 Local open source app

Monday, May 11, 2015

C# Safe Navigation Operator ?.

Read code to understand:

var g1 = parent?.child?.child?.child;
if (g1 != null) // TODO

Wednesday, May 6, 2015

How to solve problem "The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at"

To my case:
The password is wrong.

var client = new SmtpClient("", 587)
                Credentials = new NetworkCredential("", "mypwd"),
                EnableSsl = true
            client.Send("", "", "test", "testbody");

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at

Friday, May 1, 2015

SQLBolt, interactive lessons to learn SQL in browser
Welcome to SQLBolt, a series of interactive lessons and exercises designed to help you quickly learn SQL right in your browser

Tuesday, April 28, 2015

How good is your C#?

Friday, April 24, 2015

How to solve problem "Unable to load the specified metadata resource." in Entity Framework?

Replace EDMX connection metadata part to

Wednesday, April 22, 2015

How to create a SFTP server on the fly for unit test?\

NuaneSFTPServer server = new NuaneSFTPServer("username", "Passw0rd!", SftpRootFolder, 990);


    public class NuaneSFTPServer
        volatile SftpServer sFTPserver = null;
        public string UserName;
        public string Password;
        public string FtpPath;
        public int PortNumber;
        private static Thread workerThread;

        public NuaneSFTPServer(string userName, string password, string ftpPath, int portNumber)
            UserName = userName;
            Password = password;
            FtpPath = ftpPath;
            PortNumber = portNumber;
            SshKey rsaKey = SshKey.Generate(SshKeyAlgorithm.RSA, 1024);
            SshKey dssKey = SshKey.Generate(SshKeyAlgorithm.DSS, 1024);

            // add keys, bindings and users
            sFTPserver = new SftpServer();
            sFTPserver.Log = Console.Out;
            sFTPserver.Bindings.Add(IPAddress.Any, portNumber);
            sFTPserver.Users.Add(new SshUser(userName, password, ftpPath));
        public void Start()
            workerThread = new Thread(sFTPserver.Start);
            while (!workerThread.IsAlive) ;
        public void Stop()

How to fix The thread xxx has exited with code 259 (0x103)?

When try to wait for a thread to be alive, but not call thread Start method, will get a lot of errors like this::The thread xxx has exited with code 259 (0x103)

            workerThread = new Thread(StartMethod);
//            workerThread.Start();
            while (!workerThread.IsAlive) ;


Tuesday, April 14, 2015

How to create a sub domain on the fly in IIS Server / ASP.NET project

How to create a sub domain on the fly in IIS Server / ASP.NET project

Step 1: Add following DNS records into your donmain:  IN A XXX.XXX.XXX.XXX  IN A XXX.XXX.XXX.XXX IN A XXX.XXX.XXX.XXX

# Wild card DNS record

Step 2: Create your website in IIS Server for

Step 3: Get your sub domain name in ASP.NET MVC project
        var uri = Request.Url;
        var fullDomain = uri.GetComponents(UriComponents.Host, UriFormat.SafeUnescaped);
        var domainParts = fullDomain
            .Split('.') // ["test", "example", "com"]
            .Take(1);    // ["com", "example"]
        var subdomain = String.Join(".", domainParts);

DTO vs Value Object vs POCO

Monday, April 13, 2015

Architectures Comparison Summary

For Event-Driven architecture. there are two problems:
Testability and Development

But with CQRS/Event Sourcing, it is very easy to create BDD unit test.


Friday, April 10, 2015

Complexity is the enemy


"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it."

Thursday, April 9, 2015

Friday, March 27, 2015

How much code coverage do you really need?

Two quotes from Uncle Bob
“Two things. Repeatability and cost. Manual tests are horrifically expensive compared to automated tests.”

“Manual tests aren't tests; they are trials. And since there are humans involved, they are suspect."

Tuesday, March 24, 2015

Last line effect

We expose the “last line effect,” the phenomenon that the last line or statement in a micro-clone is much more likely to contain an error than the previous lines or statements. We do this by analyzing 208 open source projects and reporting on 202 faulty micro-clones.

x += o t h e r . x ;
y += o t h e r . y ;
z += o t h e r . y ;

Thursday, March 19, 2015

About Command Idempotency

Definition from Gregor (New ACID)
“In the world of distributed systems, idempotency translates to the fact that an operation can be invoked repeatedly without changing the result.”

Idempotency Patterns

Tuesday, March 10, 2015

How to deal with communication between aggregate roots?

What is Event-driven architecture?

Behind Event-driven architecture, system model is treated as a state machine. After a command changed the state, an event is generated to notify other components.

What is a simple explanation of higher order functions and callbacks in JavaScript?

  { name: 'Waffles'type: 'dog', age: 12 },
  { name: 'Fluffy',   type: 'cat', age: 14 },
  { name: 'Spelunky', type: 'dog', age: 4 },
  { name: 'Hank',     type: 'dog', age: 11 },
var oldDogs = animals.filter(function(animal) {
  return animal.age > 10 && animal.type === 'dog';

Friday, March 6, 2015

What is category in Event Store?

 If put dash into stream name, the first part will be saved as category name

Source code from Event Store 

  _handler = new CategorizeEventsByStreamPath("-", Console.WriteLine);

        public override string GetCategoryByStreamId(string streamId)
            string category = null;
            if (!streamId.StartsWith("$"))
                var lastSeparatorPosition = streamId.IndexOf(_separator);
                if (lastSeparatorPosition > 0)
                    category = streamId.Substring(0, lastSeparatorPosition);
            return category;


How to add Multiple Regular Expression Validation attribute into one Property in ASP.Net MVC?

Create another new attribute and inherit from RegularExpressionAttribute

    public class RegularExpressionAttribute : ValidationAttribute
        private string _pattern;
        public RegularExpressionAttribute(string pattern)
            _pattern = pattern;
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
            if (value == null) return null;
            if (!System.Text.RegularExpressions.Regex.IsMatch(value.ToString(), _pattern))
                return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
            return null;

    public class RegularExpression2ndAttribute : RegularExpressionAttribute {}

So in view model:
        [ValidURL(ErrorMessage = "Invalid URL")]
        [RegularExpression(@"^.*\.(jpg|JPG|gif|GIF|jpeg)$", ErrorMessage = "Not a image URL")]
        public string LogoUrl { get; set; }

Friday, February 27, 2015

What is unit of work and relationship with CQRS/Event Sourcing?


But I think this pattern is not applicable for CQRS/Event Sourcing, because SAGA is the way to deal with transaction in CQRS/Event Sourcing.

Wednesday, February 25, 2015

What is Aggregate in DDD?

From Eric Evans book DDD Page 90
An AGGREGATE is a cluster of associated objects that we treat as a unit for the purpose of data changes. Each AGGREGATE has a root and a boundary. The boundary defines what is inside the AGGREGATE. The root is a single specific ENTITY contained in the AGGREGATE. The root is the only member of the AGGREGATE that outside objects are allowed to hold references to, although objects within the boundary may hold references to each other. ENTITIES other than the root have local identity, but it only needs to be unique within the aggregate, since no outside object can ever see it out of the context of the root ENTITY.

By Martin Fowler
a cluster of domain objects that can be treated as a single unit.

Monday, February 23, 2015

How to enable intellisense in Visual Studio after remove reSharper?

My Visual Studio inellisense stopped working after removed ReSharper(ReSharper is so slow).

The solution:
Tools->Options->Text Editor->All Languages->General
Turn off "Auto list members", and "Parameter information"
And turn on again.

Friday, February 20, 2015

How to get stream name list from Event Store?

Better idea from Greg Young

Greg Young 

Feb 20 (3 days ago)
to event-store 
What will happe  to your projection with 100m streams?

Original test code:

        $init: function(s,e) { return {streanList:"", count:0} },
        $any : function(s,e) {
            if (!s.streanList){
                s.streanList =" ";
            if (s.streanList.indexOf(e.streamId) < 0){
               s.streanList = s.streanList + e.streamId +",";


How to count event number in one stream?

        $init: function() {
           return { count: 0 }
        $any : function(s,e) { return s + 1;}

How to count event number in Event Store?

        $init: function(s,e) { return 0;},
        $any : function(s,e) { return s + 1;}

Wednesday, February 18, 2015

How to solve problem "Read access denied for stream" while reading events from event store?

Get this error on following line:
var event = connection.ReadStreamEventsForwardAsync(streamid, 0, 1, false).Result;

Need to add credential for reading
var event = connection.ReadStreamEventsForwardAsync(streamid, 0, 1, false,  new UserCredentials("admin", "changeit")).Result;

How to solve problem "System.AggregateException: One or more errors occured ---> EventStore.ClientAPI.Exceptions.RetriesLimitReachedException" when try to connect to write event to Event Store?

This error happened  after downloaded Event Store 3.0.1 and tried following code for the testing

            string serverIpaddress = "";
            var connection = EventStoreConnection.Create(new IPEndPoint(IPAddress.Parse(serverIpaddress), 2113));
            var myEvent = new EventData(Guid.NewGuid(), "testEvent", false,
                                        Encoding.UTF8.GetBytes("some data1"),
                                        Encoding.UTF8.GetBytes("some metadata"));
                               ExpectedVersion.Any, myEvent).Wait();

On line of AppendToStreamAsync, exception throws:
 "System.AggregateException: One or more errors occured ---> EventStore.ClientAPI.Exceptions.RetriesLimitReachedException"

Cause: .NET API of Event Store goes by TCP port, which default value is 1113, http port number is 2113 by default.

Just change to            
          var connection = EventStoreConnection.Create(new IPEndPoint(IPAddress.Parse(serverIpaddress), 1113));


Thursday, February 12, 2015

How to check TcpListener is listening?

In TcpListener class, there is a property called Active but it a proctected one.

Create a sub class from TcpListener, and expose this property by yourself.

Code example:
    public class Listener : TcpListener
        public Listener(int portNumber): base(IPAddress.Any, portNumber) {}
        public bool IsAcitve
            get { return this.Active; }

Wednesday, February 11, 2015

What is projection in event sourcing

Projection is about deriving current state from the stream of events

Quote from Ralph Johnson: Before software can be reusable it first has to be usable.

Reusable software is not number one priority anymore. So why want to design software to be reusable.

Tuesday, February 10, 2015

Reading about CQRS and event souring

Exploring CQRS and Event Sourcing

Applying CQRS and Event Sourcing in Microsoft .NET Applications TechEd Europe 2014

Monday, February 9, 2015

What is bounded context?

From DDD website:
[[Bounded Context]] The delimited applicability of a particular model. BOUNDING CONTEXTS gives team members a clear and shared understanding of what has to be consistent and what can develop independently.

From Martin Folwer:
Bounded Context is a central pattern in Domain-Driven Design. It is the focus of DDD's strategic design section which is all about dealing with large models and teams. DDD deals with large models by dividing them into different Bounded Contexts and being explicit about their interrelationships.

The term bounded context comes from Eric Evans' book. In brief, Evans introduces this concept as a way to decompose a large, complex system into more manageable pieces; a large system is composed of multiple bounded contexts. Each bounded context is the context for its own self-contained domain model, and has its own ubiquitous language. You can also view a bounded context as an autonomous business component defining clear consistency boundaries: one bounded context typically communicates with another bounded context by raising events.

From "DDD: The Bounded Context Explained"

really Explained?

Same question at

Conclusion:  bounded context is a fence.

How come a key concept in DDD is with so many ambiguous definitions?

Procedural vs OO, Anthropomorphism Gone Wrong: Poor Motivating Example for OOP

Procedural vs OO with code example

Thursday, February 5, 2015

How to solve Visual Studio git push problem "You cannot publish local branch master to the remote repository origin"?

Error happened:
When I created a local git repository and tried to push to remote repository, got following error:

"You cannot publish local branch master to the remote repository origin because a branch with the same name already exists there. You might want to rename your local branch and try again"

- Install 3rd party git tool
- Add remote repository in GitUI
- Click push, and select "remote repository"

Thursday, January 29, 2015

Wednesday, January 28, 2015

Why readonly in C#?

Make summary form following post:

1. Improve readability: tell how to not use in other way.
2. Nothing to do with performance
3. Immutable data structures in threading

Monday, January 26, 2015

What is real purpose of Enable Visual Studio Hosting Process?

According to MSDN:
"The Visual Studio hosting process improves debugger performance and enables new debugger features, such as partial-trust debugging and design-time expression evaluation"

In real world:
Sometimes, vshost.exe always running, and you can't even kill it from Task Manager. (After killed it, it restores automatically, need to quit Visual Studio)

Need to disable this feature/bug by following steps:
Properties of project =>
"Debug" tab =>
uncheck "Enable the Visual Studio hosting process"

How to solve in C++ upgraded project for error LNK2001: unresolved external symbol "?.cctor@@$$FYMXXZ" (?.cctor@@$$FYMXXZ)?

Remove /Zl from Configuration Properties -> C/C++ -> All Options -> Additional Options

Friday, January 23, 2015

TDD is about Development not Design

TDD is about Development not Design

In initial design stage, need to hide unrelated detail as much as possible, cover high level scenario only.

Test Driven Design forces thinking on low level details. In this way, it is very easy to lose focus.

Try a new project to see if TDD stands for Test Driven Development, or Test Driven Design

Thursday, January 22, 2015

Why I Don't Teach SOLID

"The main culprit is SOLID's focus on dependencies. "
"These all lead developers to create interfaces everywhere.  They litter the codebase with interfaces like IFooer, IDoer, IMooer, and IPooer.  Navigating it becomes a nightmare. "

Personal experience:
I ever worked on a similar project:  this project has two functions: a wrapper for Icewarp API to create/update email accounts.
3k line of codes, near 10 layers of interface. Indeed, it is "SOLID" :)

Tuesday, January 20, 2015

TDD Is About Design, Not Testing

"Writing tests after writing code is a corruption of TDD"
"The act of writing a unit test is more an act of design than of verification."

TDD is a way to design software? or a way to verify/refine design? or both?

Thursday, January 15, 2015

How to solve problem: Installed Windows service by installutil not showing up in MMC services windows

Although installutil tells you everything is fine, the new service will not show up in MMC services windows.
Solution: use sc
sc create servicename binPath= servicebin.exe

Wednesday, January 14, 2015

Readonly vs const in C#

A const field can only be initialized at the declaration of the field.
A readonly field can be initialized either at the declaration or in a constructor

Tuesday, January 13, 2015

What is "Architectural Spike"?

An architectural spike is a thin slice of the entire application built for the purpose of determining and testing a potential architecture.

Definition from:

Friday, January 9, 2015

The most difficult part of TDD: You have to write tests first before coding/design/implementation

"Have to actually think what you expect from a piece of code BEFORE you write it! Madness! Instead of just writing code, you have to think before you code! And if you can't formulate properly an expectation, HOW do you write the code in the first place?!"

CQRS, Command Query Responsibility Segregation FAQ

CQRS by Martin Fowler

Introducing the Command Query Responsibility Segregation Pattern from MSDN

C# code exmaple: LIntroduction to CQRS