Monday, December 22, 2014

Thursday, December 18, 2014

How to solve problem "Cannot find the requested object." while create an X509Certificate2 object?

It throws this exception for following line:
X509Certificate2 certificate = new X509Certificate2(@"c:\temp\server.pvk", "password");

It means: the certificate file is not valid.
The most common reason is:
Need pvkimprt tool to generate PFX files

This constructor creates a new X509Certificate2 object using a certificate file name and a password needed to access the certificate. It is used with PKCS12 (PFX) files that contain the certificate's private key. Calling this constructor with the correct password decrypts the private key and saves it to a key container.

Following are the steps to generate X509Certificate2

"C:\Program Files (x86)\Windows Kits\8.1\bin\x64\makecert" -r -pe -n "CN=Test" -sky exchange c:\temp\server.cer -sv c:\temp\server.pvk -sr currentuser
"C:\Program Files (x86)\Windows Kits\8.1\bin\x64\cert2spc"  c:\temp\server.cer server.spc
pvkimprt -pfx server.spc server.pfx

Tuesday, December 16, 2014

In MS SQL, how to count total number of major objectsr, such as table, view, store procedure etc?

Select type_desc as Type, COUNT(*) AS Count from SYS.OBJECTS
group by type_desc

The Art of Programming

Thursday, December 11, 2014

What is the simplest way to solve "Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on"

Code Example


C# Naming Conventions with example

use PascalCasing for class names and method names.
use camelCasing for method arguments and local variables
use noun or noun phrases to name a class.
prefix interfaces with the letter I.  Interface names are noun (phrases) or adjectives.


Wednesday, December 10, 2014

How to list all of listening ports in Windows command prompt?

netstat -anb | findstr /R /C:"[LISTENING]"

How to solve problem "No connection could be made because the target machine actively refused it"

#1 reason is: target machine TCP not listening.
Can run following command line to check:
netstat -anb

What is difference between and is localhost. Only same machine can access this address.
But means all of ip addresses binding to this machine.


Workflows of Refactoring

Uri Templates

        var url = new UriTemplate("{tenant}/customers")
            .AddParameter("tenant", "acmé")

        Assert.Equal("", url);

Monday, December 8, 2014

5 Incredible Features in the Visual Studio 2015 Preview

Friday, December 5, 2014

How to solve Invalid Xml syntax error after updated an older Visual Studio project

Error message:
This application has failed to start because the application configuration is incorrect. Review the manifest file for possible errors.
Reinstalling the application may fix this problem. For more details, please see the application event log.

In EventView, the error message is:
Activation context generation failed for XXXXX
XXXX on line 1. Invalid Xml syntax.

The first line in config file is
<?xml version="1.0" encoding="Windows-1252"?>

Change to
<?xml version="1.0" encoding="utf-8"?>

Wednesday, December 3, 2014

Free browser base UML modelling tool

How many kind of UML diagrams in total?

Class Diagram
Component Diagram
Deployment Diagram
Object Diagram
Package Diagram
Profile Diagram
Composite Structure Diagram
Use Case Diagram
Activity Diagram
State Machine Diagram
Sequence Diagram
Communication Diagram
Interaction Overview Diagram
Timing Diagram

Tuesday, December 2, 2014

How to install SQL Server management studio only?

On the download page:

Select the file just for SQL Server management studio installation:

How to get list of SQL Server instances on local machine?

In command line prompt (Run as admin):
reg query "HKLM\Software\Microsoft\Microsoft SQL Server\Instance Names\SQL"

Monday, November 17, 2014

Coding advice for new developers:Readable, Reliable, Correct and Efficient

Why this order?
Each attribute is fundamental to the next.
If code isn't readable, you stand no chance of making it reliable.
If code isn't reliable, it will never be correct, except by accident.
If code isn't correct, then what's the point?
If code isn't efficient, it is unlikely to be viewed as broadly useful.

Thursday, November 13, 2014

How to pass paramters in Angular for http$.get and http$.post?

For http$.get
    $scope.ButtonClickEventGet = function () {
            { params: { postcode: $scope.PostalCode } }
            function (data, status, headers, config) {
                $scope.Result = data;

For http$.post (Don't know why it is different with get method)

    $scope.ButtonClickEventPost  = function () {
        $'ControllerName/ActionName', { postcode: $scope.models.PostalCode }).success(
            function (data, status, headers, config) {
                $scope.Result = data;

10 Developer Job Interview Tips To Land The Best Job You Can

Thursday, November 6, 2014

CDN for Angular

<script src="//"></script>

Wednesday, November 5, 2014

C# Autocomplete Demo Using Bing Code Search Engine

Screw You, Angular

"Recently there has been a great little triangle of battles going on among Ember, React and Angular. The reason why these debates are so great is that each of the frameworks have various pieces that are pure genius (ex. Angular DI, React Virtual DOM, Ember Router) and it is not abnormal to see developers in one framework borrow the great idea from another framework (ex. Angular UI Router from Ember Router)."

What is XOR(^) operator in C#

A XOR B shows that it outputs true whenever the inputs differ

Sometimes, it is so easy to find a solution when you are back to basics.


Friday, October 24, 2014

Wednesday, October 15, 2014

How to check temp table exist in MS SQL Server?

IF OBJECT_ID('tempdb..#TempTable') IS NOT NULL
    DROP TABLE #TempTavle

How to write error information into MS SQL Server log?

exec master.dbo.xp_fileexist 'C:\FileName.csv',
@isExists OUTPUT
IF @isExists <> 1
RAISERROR ('Can not find csv file', -- Message text.
16, -- Severity.
1 -- State.

How to check exists file in MS SQL server

exec master.dbo.xp_fileexist 'C:\FileName.csv',
@isExists OUTPUT
IF @isExists <> 1
RAISERROR ('Can not find csv file', -- Message text.
16, -- Severity.
1 -- State.

101 Great Answers to the Toughest Interview Questions: Fourth Edition

Thursday, October 9, 2014

If url includes Dot/Period, will cause 404 error for ASP.NET routing

Need to change web.config setting at:


<modules runAllManagedModulesForAllRequests="true">

<remove name="FormsAuthenticationModule" />



Enable hotlinking on Bayimg

I made a tool to upload image to bayimg and get raw image url right way:

But Bayimg blocks hotlinking. So write a function to enable it.
For example:
Original Bayimg link:
You can use following to get access this image

The source code is located at:

How to prevent image hotlinking in ASP.NET?

In IIS Server by URL rewrite:


Monday, September 29, 2014

Wednesday, September 24, 2014

How to solve problem while upgrade to EF6: System.InvalidOperationException: No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'

To solve this problem for me is to add EntityFramework.SqlServer.dll into project reference:

System.InvalidOperationException: No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'

Tuesday, September 23, 2014

How to add Facebook comment in ASP.NET MVC project?

You can download solution on Github by

1. Create a partial view, call fbComment

2. Add this partial view into any view for comments

Monday, September 22, 2014

The case-insensitive regular expression for Canada postal code


Friday, September 19, 2014

How to display Textbox input to upper case in ASP.NET MVC razor view?

1. Create css class
text-transform: uppercase;

2. Add this class into Textbox in razor view
@Html.TextBoxFor(model => model.PostCode, new { @class = "uppercase" })

Note: the value still keeps original value.

Thursday, September 18, 2014

How to write Singleton pattern in C#?
using System;

public sealed class Singleton
   private static volatile Singleton instance;
   private static object syncRoot = new Object();

   private Singleton() {}

   public static Singleton Instance
         if (instance == null) 
            lock (syncRoot) 
               if (instance == null) 
                  instance = new Singleton();

         return instance;

No more JS frameworks

Monday, September 15, 2014

Tuesday, September 2, 2014

What Is Clean Code?
I like this one by Dave Thomas, founder of OTI and godfather of the Eclipse strategy:
It has unit and acceptance tests.
It has meaningful names.
It provides one way rather than many ways for doing one thing.
It has minimal dependencies, which are explicitly defined, and provides a clear and minimal API.
Code should be literate since, depending on the language, not all necessary information can be expressed clearly in code

If programming languages were weapons

C# is a powerful laser rifle strapped to a donkey, when taken off the donkey the laser doesn’t seem to work as well.

Monday, August 25, 2014

How to get sql query from LINQ?

Before getting linq data, using ToString method. Will see the generated SQL.
It is not easy to read and understand.

   var soldOutProducts = 
            from p in products 
            where p.UnitsInStock == 0;

   string sql =  soldOutProducts.ToString();

Wednesday, August 13, 2014

Scheduled Tasks In ASP.NET With/Without Quartz.Net


        protected void Application_Start()
            System.Timers.Timer myTimer = new System.Timers.Timer(10 * 60 * 1000);
            myTimer.Elapsed += new System.Timers.ElapsedEventHandler(ScheduledTaskMethod);
            myTimer.AutoReset = true;
            myTimer.Enabled = true;

Wednesday, July 23, 2014

Norris Numbers

Norris’ number, the untrained programmer can write 1,500 lines.
With Thoughtful class and package decomposition will let you scale up to 20,000 lines.

Friday, July 18, 2014

Tool to choose a open source lincens

If you don't use any license, the default copyright laws apply.

Thursday, July 17, 2014

How to use Bulk insert to insert one column in a mutitple columns table?

One of solutions is:
Create a view from that table with only column you want to update.
The use bulk insert:
bulk insert TableView
from 'July17_2014.csv'
with (fieldterminator = ',', rowterminator = '\n')

Monday, June 30, 2014

What Makes a Good Programmer?


Thursday, June 26, 2014

How to implement Dependency Injection by Autofac in MvcApplication class (ASP.NET MVC Global.asax)?

There are a lot of code examples for how to implement Dependency Injection for controller in ASP.NET MVC, but not too much about MvcApplication class in ASP.NET MVC.

Following is my implementation for Dependency Injection in MvcApplication class

public class MvcApplication : System.Web.HttpApplication

        protected void Application_Start()
            //pass service into other class that need this service
            var c = new OtherClassNeedService(_IYourService);

        private AutofacDependencyResolver IoCcontainer { get; set; }
        private IYourService _IYourService
                if (IoCcontainer == null) return null;
                return IoCcontainer.ApplicationContainer.Resolve();

        public void RegisterDependencies()
            var builder = new ContainerBuilder();

                .As(); //.InstancePerHttpRequest(); if added InstancePerHttpRequest, will get error: No scope with a Tag matching 'httpRequest' is visible from the scope in which the instance was requested.

            IContainer container = builder.Build();
            var aResolver = new AutofacDependencyResolver(container);
            IoCcontainer = aResolver;

        protected void Application_End(object sender, EventArgs e)

Thursday, June 19, 2014

How to get dropdown list from html by Html Agility Pack

private List GetDropdownList(string HtmlSource, string selectName)
            HtmlDocument doc = new HtmlDocument();
            return doc.DocumentNode.SelectNodes(string.Format("//select[@name='{0}']//option", selectName)).Select(v => v.Attributes["value"].Value).ToList();
Need to add HtmlNode.ElementsFlags.Remove("option");
before loading html source.

Wednesday, June 18, 2014

How to solve, Entity Framework return duplicated records from a view if there is no key in the view

1. Make sure the view should be a key there. And marked as Entity key
2. If do not have a key, add one by Row number

Do not forget: marked that field as Entity key in Edmx file


Monday, June 16, 2014

How to solve problem, An exception occurred while processing your request. Additionally, another exception occurred while executing the custom error page for the first exception. The request has been terminated.

When saw this error, go to web.config file, disable the customer error. Then you will see the real error.   Set to RemoteOnly if in the production environment, so only real error in local.
<customErrors mode="Off" >


Friday, June 6, 2014

How to get list of div that contains specific class name in Html Agility?

            var DivListContainSpeciicClassName = htmlDoc.DocumentNode.Descendants("div").Where(
                d => d.Attributes.Contains("class")

Wednesday, June 4, 2014

How to kill all current connections to a database in SQL Server ?

In case of you want to restore an database.

There are many ways to do so.
See link on Stackoverflow

Or there is another simple way:
1. In SQL Server studio, click Activity Monitor button
2. Filter by database
3. Right click to kill all of connection to that database

Monday, June 2, 2014

How to solve problem, Invalid column name 'Discriminator'?

Get this error while upgrade Entity Framework from 5.0 to 6.x.
Install Entity Framework by Nuget. The version got is 6.1

Then get this weird error: Invalid column name 'Discriminator'
All of fields for that table are in the database table, so [NotMapped] is not applicable in here

The solution to me is to revert to 6.02, problem solved.

How to solve problem, "No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'."

Entity framework is using older version 5.0 and on .Net 4.0, need to install a new one.

Go to Package Manager Console:
Install-Package EntityFramework

Thursday, May 29, 2014

How to remove ASP.NET response headers Server, X-AspNet-Version, X-AspNetMvc-Version and X-Powered-By?

Need two steps:
Step 1: add following code into Global.asax
protected void Application_PreSendRequestHeaders(object sender, EventArgs e)


Step 2
Add following config into web.config file


Is ASP.Net vNext The New Node.js

Monday, May 26, 2014

How to valid URL in ASP.NET MVC data annotation?

[RegularExpression(@"^(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&%\$#_]*)?$", ErrorMessage = "Invalid URL")]
public string Url { get; set; }

Website to test regular expression

Common Regular Expressions

Wednesday, May 21, 2014

How to fix problem, MSDTC on server xxx is unavailable?

Following are the steps I did to fix the problem:
- Uninstall: msdtc -uninstall
- Install: msdtc -install
- restarting DTC service;

- Restart SQL Server service

Tuesday, May 20, 2014

Wednesday, May 7, 2014

Why need method/function overloading in C#?

Keep same naming convention. Can not find any other benefit for overloading.

Optional parameter should be the first choice to try.
Do not put different purposes thing under same name.

Friday, May 2, 2014

How to add number only validation in ASP.NET MVC data model by Data Annotation attribute?

[Range(0, int.MaxValue, ErrorMessage = "Number please")]

How to solve, 401 unauthorized issue for ASP.NET Windows authentication in Visual studio 2013

Go to folder:

Open config file and Set windowsAuthentication to true
<windowsAuthentication enabled="true">

Wednesday, April 30, 2014

How to sovle problem, JavaScript runtime error: Object doesn't support property or method 'on'

To me,
I fixed this problem by using higher version jQuery
Originally, it was 1.5.3, changed to 1.8.3

Code snippet for reading configuration from config file

System.Configuration.ConfigurationManager.AppSettings["SettingKey"] == null ? "defaultValue" : System.Configuration.ConfigurationManager.AppSettings["SettingKey"].ToString();

Wednesday, April 23, 2014

Why need Closure in JavaScript

Safe and faster
var names = ['zero', 'one', 'two',  'three', 'four', 'five', 'six',  'seven', 'eight', 'nine'];
var digit_name = function (n) {
 return names[n];
alert(digit_name(3)); // 'three'

//Problem: not safe. It is global variable, other code could change it

var digit_name = function (n) { 
 var names = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']; 
 return names[n];
alert(digit_name(3)); // 'three'
//Problem: Safe but slow. Names hide in function scope, but need to initialize every time

var digit_name = (function () {
 var names = ['zero', 'one', 'two',  'three', 'four', 'five', 'six',  'seven', 'eight', 'nine'];
 return function (n) {
 return names[n];
alert(digit_name(3)); // 'three
//Safe and fast 

But why closure version code is faster?

Why Most Unit Testing is Waste

Keep regression tests around for up to a year — but most of those will be system-level tests rather than unit tests.
• Keep unit tests that test key algorithms for which there is a broad, formal, independent oracle of correctness, and for which there is ascribable business value.
• Except for the preceding case, if X has business value and you can text X with either a system test or a unit test, use a system test — context is everything.
• Design a test with more care than you design the code.
• Turn most unit tests into assertions.
• Throw away tests that haven’t failed in a year.
• Testing can’t replace good development: a high test failure rate suggests you should shorten development intervals, perhaps radically, and make sure your architecture and design regimens have teeth
• If you find that individual functions being tested are trivial, double-check the way you incentivize developers’ performance. Rewarding coverage or other meaningless metrics can lead to rapid architecture decay.
• Be humble about what tests can achieve. Tests don’t improve quality: developers do.

Play video in Html 5


Tuesday, April 22, 2014

What is sparse array?
a sparse array is an array in which most of the elements have the same value (known as the default value—usually 0 or null).

How to render an action without layout in ASP.NET MVC?

    public class HomeController : Controller
        public string Create()
     return "Hello";
There are a couple of other ways:
Change Layout default setting etc.
But return a string or json result, it is great way in some scenarios.

Thursday, April 17, 2014

Wednesday, April 16, 2014

How to solve problem: Proxy class not generated by wsdl command line or add service reference?

Use svcutil command line
svcutil  yourwsdlfile.wsdl
ServiceModel Metadata Utility Tool is a newer version than wsdl

Tuesday, April 15, 2014

How to manually update ASP.NET MVC 3 project to ASP.NET MVC 4?

Tried  nugget first, failed. If a simple project, should try this first.

Then follow instruction from Microsoft to upgrade manually:

In addition to reference above:
1. Change web.config file in view folder  as well
<section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />

<section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />

<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />

2. Add reference to System.Web.Optimization
By run nuget package: Install-Package Microsoft.AspNet.Web.Optimization

How to create a Windows EventLog source by command line?

Open command line window with admin permission
eventcreate /ID 2 /L APPLICATION /T INFORMATION /SO YourEventSourceName /D "Application infor"

Thursday, April 10, 2014

Where to check IIS server version

Check file property:

Tuesday, April 8, 2014

How to prevent cache in ASP.NET Single Page Application when use Javascript Ajax calls?

Turn off cache in Jquery Ajax call
            url: "url",
            cache: false,
            dataType: 'json',
            async: true,
            success: function (data) {
            error: function (xhr, ajaxOptions, thrownError) {

How to solve ASP.NET precompile problem, The type or namespace name does not exist in the namespace 'System.Web.Mvc' (are you missing an assembly reference?)

Set Copy local to true for this project reference: System.Web.Mvc
And Clear solution

How to enable static content caching in ASP.NET?

Add following configuration into web.config file


When run pagespeed, sometime will get following warning:
Leverage browser caching
Setting an expiry date or a maximum age in the HTTP headers for static resources instructs the browser to load previously downloaded resources from local disk rather than over

Enable ASP.NET static content cache to improve speed

Monday, April 7, 2014

Where to get ASP.NET MVC project MVC version?

Project reference -> system.web.mvc -> Properties- > Version

Wednesday, April 2, 2014

How to add Facebook login function into ASP.NET MVC project?

Step 1: create a Facebook app, and get appid
Step 2: Add following code into login view file

Step 3: Create an action in AccountController
        public ActionResult FacebookLogin(string token)
            WebClient client = new WebClient();
            string JsonResult = client.DownloadString(string.Concat(
                   "", token));

            var serializer = new JavaScriptSerializer();
            dynamic value = serializer.DeserializeObject(JsonResult);
            var model = new RegisterModel()
                Email = value["email"],
                FirstName = value["first_name"],
                LastName = value["last_name"]

            FormsAuthentication.SetAuthCookie(model.Email, true /* createPersistentCookie */);
            return RedirectToAction("Index", "Home");

How to solve problem, Given URL is not allowed by the Application configuration Facebook application error?

Go to
->Your app ->Settings -> Addvanced -> Valid OAuth redirect URIs -> put your login url in here

How to create a web page screenshot by Javascript lib, html2canvas

What Javascript Frameworks are used at

DropzoneJS, an open source library that provides drag'n'drop file uploads with image previews

Tuesday, April 1, 2014

How to Correctly Detect Credit Card Type

Card Type
Card Number Prefix
American Express34, 37
China UnionPay62, 88
Diners ClubCarte Blanche300-305
Diners Club International300-305, 309, 36, 38-39
Diners Club US & Canada54, 55
Discover Card6011, 622126-622925, 644-649, 65
Laser6304, 6706, 6771, 6709
Maestro5018, 5020, 5038, 5612, 5893, 6304, 6759, 6761, 6762, 6763, 0604, 6390
Visa Electron4026, 417500, 4405, 4508, 4844, 4913, 4917