Tuesday, December 31, 2013

How to wrap up a website into a Windows Store app?

1. In Visual Studio 2013, create a new C# blank app project
2. Drag a WebView into your app’s XAML

3. Add following code into your MainPage.xaml.cs file
webView1.Navigate(new Uri(@"http://myevents.apphb.com/"));


Monday, December 30, 2013

How to fix 0x0000000A while install Windows 8 on Virtualbox?

Enable two options in your computer BIOS setting

+[x] Virtualization Technology
+[x] VT-d Feature

Monday, December 23, 2013

How to deal with “An error occurred on the server when processing the URL” problem for classic ASP?

This is a generic error for classic ASP hosted on IIS 7.

Go to IIS Server feature: ASP
Enable option: Send Errors to Browser

Then will find underneath real problem

Thursday, December 19, 2013

How to access Google spreadsheet by C#?

            SpreadsheetsService myService = new SpreadsheetsService("test");
            myService.setUserCredentials("AAA@gmail.com", "password");

            SpreadsheetQuery query = new SpreadsheetQuery();
            SpreadsheetFeed feed = myService.Query(query);

            Console.WriteLine("Your spreadsheets:");
            foreach (SpreadsheetEntry entry in feed.Entries)
API download link:


Data Structure Visualizations


Why use Tuple in C#?

1. To pass or return a group of values in single parameter
2. To create a temp record for a set of data without making a new class for it.

var population = Tuple.Create("New York", 7891957, 7781984, 7894862, 7071639, 7322564, 8008278);
Console.WriteLine("Population of {0} in 2000: {1:N0}",
                  population.Item1, population.Item7);

Friday, December 13, 2013

What is the way to avoid memory leak and faulted state when using block to call WCF client ?

DO NOT USE using block:

catch (CommunicationException e)
catch (TimeoutException e)
catch (Exception e)
    throw; //Make sure to keep original exception 


Wednesday, December 11, 2013

How to make a MD5 hash from a string?

        public string CalculateMD5Hash(string input)
            // step 1, calculate MD5 hash from input
            MD5 md5 = System.Security.Cryptography.MD5.Create();
            byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
            byte[] hash = md5.ComputeHash(inputBytes);

            // step 2, convert byte array to hex string
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hash.Length; i++)
            return sb.ToString();


What is BSON

Stand for Bin­ary JSON
It is Lightweight, Traversable and Efficient

Tuesday, December 10, 2013

How to solve Entity Framework “Invalid Column Name” problem?

Most of cases, because the schema of current database is different with original one.

Compare two database schema to find out the difference.

How to solve "LINQ to Entities does not recognize the method" problem

Linq will convert syntax into a SQL expression. If any method is not available in SQL query, will get this error.
Such as:
- NQ to Entities does not recognize the method System.Guid Parse(System.String) method, and this method cannot be translated into a store expression.
- NQ to Entities does not recognize the method 'System.String ToString()' method

Prepare value before run LINQ query..

A re-introduction to JavaScript


Thursday, December 5, 2013

How to extract text from html tages?

By HtmlAgilityPack

HtmlDocument doc = new HtmlDocument();
            string text = doc.DocumentNode.InnerText;
            text = Regex.Replace(text, @"\s+", " ").Trim();

Wednesday, December 4, 2013

AbsoluteActionLink, an extended method for HtmlHelper to render an absolute URL in ASP.NET MVC 3

using System.Reflection;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace me.ExtensionMethods
    public static class Html
        public static MvcHtmlString AbsoluteActionLink(this HtmlHelper htmlHelper, string text, string actionName, string controllerName, object routeValues, object htmlAttributes)
            var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
            string baseUrl = BaseUrl(htmlHelper.ViewContext.RequestContext.HttpContext.Request, urlHelper.Content("~/"));
            var rd = CastBackTo(routeValues);
            string routelist = GetRouteData(rd);

            var htmls = CastBackTo(htmlAttributes);
            string htmlattributeslist = GetHtmlAttributes(htmls);

            var htmlstring = string.Format("{4}", baseUrl, actionName, controllerName, routelist, text, htmlattributeslist);
            return new MvcHtmlString(htmlstring);

        private static string GetHtmlAttributes(RouteValueDictionary htmls)
            string htmlattributeslist = "";
            foreach (var one in htmls.Keys)
                object value = "";
                htmls.TryGetValue(one, out value);
                htmlattributeslist = htmlattributeslist + string.Format("{0}='{1}'", one, value);
            return htmlattributeslist;

        private static string GetRouteData(RouteValueDictionary rd)
            string routelist = "";
            foreach (var one in rd.Values)
                routelist = routelist + (routelist == "" ? "" : "/") + one;
            return routelist;
        public static RouteValueDictionary CastBackTo(object ob)
            RouteValueDictionary result = new RouteValueDictionary();
            foreach (PropertyInfo property in ob.GetType().GetProperties())
                result.Add(property.Name,  property.GetValue(ob, null));
            return result;

        public static string BaseUrl(HttpRequestBase Request, string rootpath)
            var baseUrl = string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, rootpath);
            if (!baseUrl.ToLower().Contains("localhost"))
                string result = "";
                string[] baseUrlSections = baseUrl.ToLower().Split("/".ToCharArray());
                foreach (var one in baseUrlSections)
                    if (one.Contains(":") && !one.Contains("http"))
                        result = result + "/" + one.Substring(0, one.IndexOf(":"));
                        result = result + (result == "" ? "" : "/") + one;
                baseUrl = result;
            return baseUrl;

Tuesday, December 3, 2013

How to fix disappeared Immediate Windows in Visual Studio menu?

If cannot find it in View menu, then open Command Windows first by:
View -> Other Windows ->Command Window:
Then type: immed and enter.

Thursday, November 28, 2013

How to solve problem: Visual Studio cannot recognize name space even already added related project as reference?

Check two projects’ target framework are same.
My case: one target framework is .Net 4.0, another is .Net 4.5

CSS box model and element vertical align issue

Many vertical align issues are related to margine and padding value, so understand css box model will be helpful.

Wednesday, November 27, 2013

How to solve "This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault="Deny"), or set explicitly by a location tag with overrideMode="Deny" or the legacy allowOverride="false". "

When deploy a website on IIS Server first time, get following 500 internal server error:
This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault="Deny"), or set explicitly by a location tag with overrideMode="Deny" or the legacy allowOverride="false".

The first thing to do is to run
turn on/off Windows features:

So can check if related features are enabled on the server

Tuesday, November 26, 2013

How to enable html source button on tinyMCE?

Add "code" into plugins list, then add "code" into button array
            // General options
            mode: "textareas",
            plugins: "spellchecker,code",
            theme : "advanced",
            theme_advanced_buttons1 : "bold,italic,underline,separator,strikethrough,justifyleft,justifycenter,justifyright,justifyfull,bullist,numlist,undo,redo,link,unlink,code",
            theme_advanced_buttons2 : "code",

Weinre with Browserstack


Wednesday, November 20, 2013

How to implement minimum string length validation by Data annotation in ASP.NET MVC?

Two ways:
        [StringLength(50, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 10)]
Regular expression
[RegularExpression(@"^.{10,}$", ErrorMessage = "Minimum 10 characters required")]

Tuesday, November 19, 2013

How to set base URL in ASP.NET MVC for JavaScript?

In _Layout.cshtml, Add base tag in head, and pass base URL.

    <base href='@string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~"))'/>

Monday, November 18, 2013

How to fix problem: To call this method, the "Membership.Provider" property must be an instance of "ExtendedMembershipProvider"?

Because you are using SimpleMembership provider.
Either remove any other membership provider setting in web.config
you add following setting in web.config file



How to change password format in SimpleMembership?

No. Can't change password format like: SqlMembershipProvider.PasswordFormat

Thursday, November 14, 2013

How to use bundle for Javascript and css in ASP.NET MVC?

1. Define bundle:
    public class BundleConfig
        // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725
        public static void RegisterBundles(BundleCollection bundles)
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
            bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
2. Register Bundle:
In Global.asax
        protected void Application_Start()
3. Refer bundle
In Razor view

"display: inline-block" (Items does not display horizontally) not working in IE

Change to:
display: inline;

How to implement multiple [Order by] in LINQ?

Var list = _db.Lists.Orderby(c => c.filed1).ThenBy(n => n.field2)

Wednesday, November 13, 2013

Prevent Duplicate Form Submission


- Disable submit button
- PRG (Post/Redirect/Get)
- Unique token in the session

Tuesday, November 12, 2013

How to store resource into database or xml in ASP.NET MVC ?


How to render a ASP.NET MVC view into html string?

        public string RenderRazorViewToString(string viewName, object model)
            ViewData.Model = model;
            using (var sw = new StringWriter())
                var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
                var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
                viewResult.View.Render(viewContext, sw);
                viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
                return sw.GetStringBuilder().ToString();

Monday, November 11, 2013

DataAnnotations regular expression for email address in ASP.NET MVC

RegularExpression(@"^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(([0-9]{1,3})|([a-zA-Z]{2,3})|(aero|coop|info|museum|name))$", ErrorMessage = "Invalid Email Address")]

Thursday, November 7, 2013

How to remove nodes in HTMLAgilityPack? Such as remove all of invisible div?

            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            var Divs = doc.DocumentNode.SelectNodes("//div[(contains(@style,'display:none'))]");
            if (noneDivs != null)
                foreach (var one in noneDivs.ToList())

Wednesday, November 6, 2013

How to fix "Cannot insert duplicate key in object . The duplicate key value is" problem while insert a new record in SQL Server?

First all, Run:
dbcc checkident([tablename],noreseed)
to check the latest id

Then run
DBCC CHECKIDENT ([tablename], reseed, latest id)
to correct latest id

How to solve Google OVER_QUERY_LIMIT problem?

Google usage limit:
The Google Geocoding API has the following limits in place:

2,500 requests per day.
Google Maps API for Business customers have higher limits:
100,000 requests per day.

Two choices:
1. Buy a business acccount
2. Use Proxy to change your ip address

Tuesday, November 5, 2013

How to get latitude and longitude from address by Google geocode api in C#?


var json = new WebClient().DownloadString(
, "1600+Amphitheatre+Parkway,+Mountain+View,+CA"));
            var serializer = new JavaScriptSerializer();
            serializer.RegisterConverters(new[] { new DynamicJsonConverter() });
            dynamic obj = serializer.Deserialize(json, typeof(object));
            if (obj.status == "OK")
                var lat = obj.results[0].geometry.location.lat;
                var lng = obj.results[0].geometry.location.lng;
public sealed class DynamicJsonConverter : JavaScriptConverter
    public override object Deserialize(IDictionary dictionary, Type type, JavaScriptSerializer serializer)
        if (dictionary == null)
            throw new ArgumentNullException("dictionary");

        return type == typeof(object) ? new DynamicJsonObject(dictionary) : null;

    public override IDictionary Serialize(object obj, JavaScriptSerializer serializer)
        throw new NotImplementedException();

    public override IEnumerable SupportedTypes
        get { return new ReadOnlyCollection(new List(new[] { typeof(object) })); }

    #region Nested type: DynamicJsonObject

    private sealed class DynamicJsonObject : DynamicObject
        private readonly IDictionary _dictionary;

        public DynamicJsonObject(IDictionary dictionary)
            if (dictionary == null)
                throw new ArgumentNullException("dictionary");
            _dictionary = dictionary;

        public override string ToString()
            var sb = new StringBuilder("{");
            return sb.ToString();

        private void ToString(StringBuilder sb)
            var firstInDictionary = true;
            foreach (var pair in _dictionary)
                if (!firstInDictionary)
                firstInDictionary = false;
                var value = pair.Value;
                var name = pair.Key;
                if (value is string)
                    sb.AppendFormat("{0}:\"{1}\"", name, value);
                else if (value is IDictionary)
                    new DynamicJsonObject((IDictionary)value).ToString(sb);
                else if (value is ArrayList)
                    sb.Append(name + ":[");
                    var firstInArray = true;
                    foreach (var arrayValue in (ArrayList)value)
                        if (!firstInArray)
                        firstInArray = false;
                        if (arrayValue is IDictionary)
                            new DynamicJsonObject((IDictionary)arrayValue).ToString(sb);
                        else if (arrayValue is string)
                            sb.AppendFormat("\"{0}\"", arrayValue);
                            sb.AppendFormat("{0}", arrayValue);

                    sb.AppendFormat("{0}:{1}", name, value);

        public override bool TryGetMember(GetMemberBinder binder, out object result)
            if (!_dictionary.TryGetValue(binder.Name, out result))
                // return null to avoid exception.  caller can check for null this way...
                result = null;
                return true;

            result = WrapResultObject(result);
            return true;

        public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
            if (indexes.Length == 1 && indexes[0] != null)
                if (!_dictionary.TryGetValue(indexes[0].ToString(), out result))
                    // return null to avoid exception.  caller can check for null this way...
                    result = null;
                    return true;

                result = WrapResultObject(result);
                return true;

            return base.TryGetIndex(binder, indexes, out result);

        private static object WrapResultObject(object result)
            var dictionary = result as IDictionary;
            if (dictionary != null)
                return new DynamicJsonObject(dictionary);

            var arrayList = result as ArrayList;
            if (arrayList != null && arrayList.Count > 0)
                return arrayList[0] is System.Collections.Generic.IDictionary? new List(arrayList.Cast>().Select(x => new DynamicJsonObject(x))):new List(arrayList.Cast());             }              return result;         }     }      #endregion }   

How to add reference for JavaScriptSerializer class into project?

Add a reference to System.Web.Extensions
Although JavaScriptSerializer namespace is: System.Web.Script.Serialization

Tuesday, October 29, 2013

ASP.NET, source code link

ASP.NET is a free web framework for building great web sites and applications.

Monday, October 28, 2013

How to fix obtrusive JavaScript validation not working in ASP.NET MVC?

There are reasons to cause this problem. For my case is I make a new class inherit from RequriedAtribute, but not resister in the Application_Start event.

protected void Application_Start()
typeof(i18n.DataAnnotations.RequiredAttribute), typeof(RequiredAttributeAdapter));

namespace i18n.DataAnnotations
    public class RequiredAttribute : System.ComponentModel.DataAnnotations.RequiredAttribute, ILocalizing
        private readonly I18NSession _session;

        public RequiredAttribute()
            _session = new I18NSession();   

        public virtual IHtmlString _(string text)
            return new HtmlString(_session.GetText(HttpContext.Current, text));

        public virtual string TT(string text)
            return _session.GetText(HttpContext.Current, text);

        public override string FormatErrorMessage(string name)
            var formatted = base.FormatErrorMessage(name);
            return _(formatted).ToHtmlString();

Thursday, October 24, 2013

Thursday, October 17, 2013

What is CDATA tag in JavaScript for?

CDATA stands for (Unparsed) Character Data, and tell XML parser NOT to parse enclosed data (Javascript).

Definition from W3C

Wednesday, October 16, 2013

How to valid email address by regular expression in C#

return System.Text.RegularExpressions.Regex.IsMatch(email, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"); 

How to copy a report in SQL Server Reporting Services from one folder to another?

1. Download to local
2. Upload to another folder

Wednesday, October 9, 2013

How to solve "Could not load file or assembly 'MySql.Web, Version=" when try to open a ASP.NET project?

Detail error message:
Could not load file or assembly 'MySql.Web, Version=, Culture=neutral, PublicKeyToken=c5687fc88969c44d' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\machine.config line 258)

Modify Machine.config in

Comment all of lines related MySql
Like following:

What's your favorite “programmer” cartoon?


alt text

Async File Uploads in MVC 4


Monday, October 7, 2013

Where to find CRM SDK URL in CRM 2013?

Settings -> Customizations -> Developer Resources
Organization Service,  Format like:

Thursday, October 3, 2013

How to solve problem "Cannot start Microsoft Outlook. Cannot open the Outlook window. The set of folders cannot be opened. You must connect to Microsoft Exchange with the current profile before you can synchronize your folders with your Outlook data file (.ost)."

How to solve problem "Cannot start Microsoft Outlook. Cannot open the Outlook window. The set of folders cannot be opened. You must connect to Microsoft Exchange with the current profile before you can synchronize your folders with your Outlook data file (.ost)."

Start Microsoft Exchange RPC Client Access service on Exchange Server box 

How to solve problem "E-Mail-Router: "Incoming Status: Failure - The request failed with HTTP status 403: Forbidden"

Exchange Web Services URL is wrong.

How to solve problem "Incoming Status: Failure - The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel. The remote certificate is invalid according to the validation procedure."

How to solve problem "Incoming Status: Failure - The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel. The remote certificate is invalid according to the validation procedure."?

Install valid certificate on CRM box

Wednesday, October 2, 2013

How to solve Error message on CRM Dashboard "you do not have sufficient privileges to view this chart. Contact your system administrator"?

Setting ->  Administration -> Users -> Client Access License (CAL) Information
Access Mode: Read-Write
License Type: Full

Thursday, September 26, 2013

Common tasks related to CRM Queue management

1. How to create a queue
Settings -> Business Management -> Queues
2. How to assign a queue to team or user
Settings -> Business Management -> Queues
3. How to assign items to a queue
Workplace -> Activities-> Tasks -> Save -> Add to Queue
4. How to assign queue item to an user
Who is working on: Workplace -> Queues -> Item -> Queue Item Detail
5. How to enable an entity to a queue
Settings -> Customizations -> Customize the System -> Entities -> Queues checkbox

Graph Based Routing


graph complex

Monday, September 23, 2013

What is Queue definition in Microsoft CRM?

Queues are places in organizing, prioritizing, and monitoring the progress of your working items in CRM.

In CRM following entities are enabled for Queues by default:


Wednesday, September 18, 2013

How to solve problem "Metadata contains a reference that cannot be resolved" while try to create connection with CRM server?

First of all, check the url if correct. If wrong url, will get this error.(http://{}/{orgName}/XRMServices/2011/Organization.svc)
If cannot find the problem, run CrmSvcUtil with enabled tracing information by

Will get detailed error information

How to implement paging by LINQ

            int numberOfObjectsPerPage = 5001;
            int pageNumber = 1;
            var queryResultPage = acountlist
              .Skip(numberOfObjectsPerPage * pageNumber)

Monday, September 16, 2013

Decoupling Your HTML, CSS, and JavaScript: Classes Are Your Contract


How to solve problem "EntityState must be set to null, Created (for Create message) or Changed (for Update message)" while to try to update earlying binding entity?

How to solve problem "EntityState must be set to null, Created (for Create message) or Changed (for Update message)" while to try to update earlying binding entity?

There is one method in OrganizationServiceContext object calls: UpdateObject
Do not use the one in OrganizationServiceProxy. If use, the get the error message


ASP.NET and Web Tools for Visual Studio 2013 RC


Friday, September 13, 2013

The funny way to tell difference between null and undefined in JavaScript

You: What is name?
JavaScript: name? What's a name? I don't know what you're talking about. You haven't ever mentioned any name before. Are you seeing some other scripting language on the (client-)side?

name = null;
You: What is name?
JavaScript: I don't know.
In short; undefined is where no notion of the thing exists; it has no type, and it's never been referenced before in that scope; null is where the thing is known to exist, but it's not known what the value is.
One thing to remember is that null is not, conceptually, the same as false or "" or such, even if they equate after type casting, i.e.

name = false;
You: What is name?
JavaScript: Boolean false.

name = '';
You: What is name?
JavaScript: Empty string


The minimum steps to try out Microsoft CRM early binding

1. Generate CRM entity by CrmSDvcUtil.exe tool in folder of crm\sdk\bin
CrmSvcUtil.exe /url:http://ServerName/OrganizationName/XRMServices/2011/Organization.svc /out:CSFileName.cs /username:usernamewithDomain /password:password /namespace:namespace /serviceContextName:contexName

2. Add following code in console app (Copy generate cs file into project and add it into)
            var _credentials = new ClientCredentials();
            _credentials.Windows.ClientCredential = (NetworkCredential)CredentialCache.DefaultCredentials;
            string CRM_SDK_URL = "http://ServerName/OrganizationName/XRMServices/2011/Organization.svc";
            OrganizationServiceProxy proxy = new OrganizationServiceProxy(new Uri(CRM_SDK_URL), null, _credentials, null);
            Account account = new Account { Name = "Sample Parent Account" };
            var _parentAccountId = proxy.Create(account);

Thursday, September 12, 2013

How to get list of sub accounts in CRM plugin ?

public void Execute(IServiceProvider serviceProvider)
            Microsoft.Xrm.Sdk.IPluginExecutionContext context = (Microsoft.Xrm.Sdk.IPluginExecutionContext) serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext));
            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                Entity entity = (Entity)context.InputParameters["Target"];
                if (entity.LogicalName == "account") 
                    // Obtain the organization service reference.
                    IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                    IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

                    //Get current account id (accountid)
                    var currentAccountid = entity["accountid"];
                    Microsoft.Xrm.Sdk.Query.QueryByAttribute querybyattribute = new Microsoft.Xrm.Sdk.Query.QueryByAttribute("account");
                    querybyattribute.ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet("accountnumber", "accountid", "emailaddress1");


                    EntityCollection retrieved = service.RetrieveMultiple(querybyattribute);
                    int count = 0;
                    foreach (var en in retrieved.Entities)
                        count += 1;
                        en.Attributes["accountnumber"] = count.ToString();

Wednesday, September 11, 2013

How to remote debug Microsoft CRM plugin?

0. Tried Visual Studio 2010, failed. 32 bit VS not working with 64 bit remote debugger.
Error message:
Unable to attach to the process. The 32-bit version of the Visual Studio Remote Debugging Monitor (MSVSMON.EXE) cannot be used to debug 64-bit processes or 64-bit dumps. Please use the 64-bit version instead.
Certainly, you can not connect 2010 remote debugger with 2012
Unable to connect to the Microsoft Visual Studio Remote Debugging Monitor named 'CHATHAM\rwang@CRM'.  The Microsoft Visual Studio Remote Debugging Monitor (MSVSMON.EXE) does not appear to be running on the remote computer. This may be because a firewall is preventing communication to the remote computer. Please see Help for assistance on configuring remote debugging.

1. Remote tools for Remote Tools for Visual Studio 2012 Update 2
2. Run and Get Tcp/ip port number
3. Copy plugin pdb file into CRM box folder:
 C:\Program Files\Microsoft Dynamics CRM\Server\bin\assembly
4. In VS2012, Debug -> attach, put mahine_name@port_number in the qualifier box
5. Then attach to w3p process.

How to solve “Action failed for: Assembly must be registered in isolation” when try to register a plugin into CRM?

The user account must exist in the Deployment Administrators group of Deployment Manager.

The Whole error message:
Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: Action failed for assembly 'SamplePlugins, Version=, Culture=neutral, PublicKeyToken=829f574d80e89132': Assembly must be registered in isolation.


Monday, September 9, 2013

Why should not use eval in Javascript

- Open up code for injection attack
- Hard to deubg

Code example:
document.write("<br>" + eval("2+2"));
document.write("<br>" + eval(x+17));

How to create a Plugin to Microsoft CRM?

1. Download and install CRM SDK
2. Open Visual Studio and create new CRM plugin project
3. Set up Signing property for this project
4. Run pluginregistration Utility in the folder of "\sdk\bin"
5. In CRM, goto Setting->Customization->Plugin, will see the new plugin

Friday, August 30, 2013

Why C still matters in 2013: a simple example


  Language                           Time (in sec)
  Java                               0.133
  C Language                         0.006
  CPython                            0.534
  Javascript V8                      0.284

Thursday, August 8, 2013

Full stack web development


How to solve Entity framework problem: System.InvalidOperationException: Mapping and metadata information could not be found for EntityType entity framework Unable to load the specified metadata resource?

Once you use self-tracking entities, if want to add new one. Please keep using same type.

In one assembly, entity framework only allow one kind mapping. If more than one mapping type, will get above weird error message.

How to install or uninstall Windows Service from CMD command line?

In command line, go to .Net Framework folder:

Run following line:
installutil C:\folder name\ServiceHost.exe

installutil /u C:\folder name\ServiceHost.exe

If want to install service with different display name:
sc create "Your Service Name" binpath= "fullpath of your exe file"

Tuesday, July 30, 2013

Example project for MySQL with Entity Framework

Official exmaple:

Another one:

How to get Open ticket number for one queue in OTRS MySQL database by .Net ?

using MySql.Data.MySqlClient;
public class MySQLDBConnector
    private MySqlConnection connection;
    private string server;
    private string database;
    private string uid;
    private string password;

    public MySQLDBConnector()

    //Initialize values
    private void Initialize()
        server = "10.0.x.x"; // "otrs.chatham.teksavvy.ca";
        database = "otrs";
        uid = "xxxx";
        password = "xxxx";
        string connectionString = "SERVER=" + server + ";Port=3306;" + "DATABASE=" +
        database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";

        connection = new MySqlConnection(connectionString);

    //open connection to database
    public bool OpenConnection()
            return true;
        catch (MySqlException ex)
            switch (ex.Number)
            return false;

    public int Count()
        string query = @"select count(*) from ticket inner join queue on ticket.queue_id= queue.id inner join ticket_state on ticket_state.id = ticket.ticket_state_id 
where queue.name ='Junk' and ticket.ticket_state_id = 4";
        int Count = -1;

        //Open Connection
        if (this.OpenConnection() == true)
            //Create Mysql Command
            MySqlCommand cmd = new MySqlCommand(query, connection);

            //ExecuteScalar will return one value
            Count = int.Parse(cmd.ExecuteScalar() + "");

            //close Connection

            return Count;
            return Count;

Monday, July 29, 2013

How to get Open ticket count for specic queue in OTRS by SQL query?

select count(*) from ticket
inner join queue on ticket.queue_id= queue.id
inner join ticket_state on ticket_state.id = ticket.ticket_state_id
where queue.name ='Postmaster' and ticket.ticket_state_id = 4

How to get table columns list from MySQL database?


How to open 3306 port on Windows 2008 for MySQL?

In command line as administrator, run following command:
netsh advfirewall firewall add rule name="MySQL Server" action=allow protocol=TCP dir=in localport=3306


Monday, July 22, 2013

How to use two views for one Action in ASP.NET MVC?

public ActionResult Process(id)
  if (Condition)
    return View ('SpecialView')
    return View (); //Default view 

Friday, July 19, 2013

How to add a field to save current time in SQL Server?

In property window for that culumn:
set the "Default value or binding" getdate()

Thursday, July 18, 2013

How to add System.Web.Extensions reference in Console project?

In Visual Studio, project property page
Change Target Framework from Client profile to the full framework

How to make ASP.NET MVC action no caching?

        [OutputCache(Duration = 0, VaryByParam = "None")]
        public ActionResult ActionName()

15 jQuery Code Snippets for Developers


Wednesday, July 17, 2013

What is the event called for closing window in Javascript?

Reference: https://developer.mozilla.org/en-US/docs/Web/API/window.onbeforeunload

window.onbeforeunload = function(e) {
  return 'Dialog text here.';

Wednesday, July 10, 2013

In Visual Studio, how to make post build event only happening in DEBUG mode?

Add a condition like:
if $(ConfigurationName) == Debug "$(TargetDir)i18n.PostBuild.exe" "$(ProjectDir)"


JavaScript implementation of most formula functions supported by Microsoft Excel 2013 and Google Spreadsheets


Monday, July 8, 2013

How to do server side validation for ASP.NET MVC Model?

Implement IValidatableObject interface inside model :

public System.Collections.Generic.IEnumerable Validate(ValidationContext validationContext)
                yield return new ValidationResult("error message", new string[] { "Validated Object Name" });                


Friday, July 5, 2013

How to get RouteData in Application_BeginRequest or Application_EndRequest

RouteData routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(HttpContext.Current));
            if (routeData == null) return;
            string action= routeData.GetRequiredString("action");

Wednesday, July 3, 2013

How to make a CodeSnippet in Visual Studio for i18n?

If use i18n for ASP.NET MVC, need to add a lot of surroundings for strings.
A CodeSnippet could help a little bit:
In VS, Tools menu, click Code Snippets Manager. then import following xml file:

i18n i18n Code snippet for @_ Microsoft Corporation Expansion SurroundsWith
expression Exception type SimpleTypeName(global::System.Exception)

Friday, June 28, 2013

How to solve JavaScript error: Unable to get value of the property '': object is null or undefined?

There are normally two reasons to cause this problem:
1. Lost reference of needed JavaScript library.
2. The reference JavaScript library is not loaded when your script run.

Thursday, June 27, 2013

How to set and get selected value in dropdown list by jQuery

Set selected value:
var selectstring = 'select option[value="' + selectedValue + '"]';
$(selectstring).attr('selected', true);

Get selected value:
$("#dropdownlistId").change(function () {

Wednesday, June 26, 2013

Javascript Cookie helper

function createCookie(name,value,days) {
 if (days) {
  var date = new Date();
  var expires = "; expires="+date.toGMTString();
 else var expires = "";
 document.cookie = name+"="+value+expires+"; path=/";

function readCookie(name) {
 var nameEQ = name + "=";
 var ca = document.cookie.split(';');
 for(var i=0;i < ca.length;i++) {
  var c = ca[i];
  while (c.charAt(0)==' ') c = c.substring(1,c.length);
  if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
 return null;

function eraseCookie(name) {


What is PO file?

PO file is the file format to save message for internationalization and localization (I18n, L10n)

It is from a open source project: gettext

The format like:
# translator-comments
#. extracted-comments
#: reference...
#, flag...
#| msgid previous-untranslated-string
msgid untranslated-string
msgstr translated-string

#: lib/error.c:116
msgid "Unknown system error"
msgstr "Error desconegut del sistema"

It is very friendly for developer and translator working together, and also make code more readable. To ASP.NET developer is another choice than resource file.

Monday, June 24, 2013

What's the class for Razor View in ASP.NET MVC


Could change this setting from
to customized one

URL encoding


Monday, June 17, 2013

What is closure in Javascript by exmaple code?

var variable = "top-level";
function parentFunction() {
  var variable = "local";
  function childFunction() {

A Javascript function is defined inside another function, its local environment will be based on the local environment that surrounds it instead of the top-level environment.


Friday, June 14, 2013

How to export html table into Excel file in ASP.MVC?

        public ActionResult ExportToExcel(int id)
            string sb = "html table tag in here";
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(sb.ToString());
            return File(buffer, "application/vnd.ms-excel");

How to render a view into a string in ASP.NET MVC?

        protected string RenderPartialViewToString(string viewName, object model)
            if (string.IsNullOrEmpty(viewName))
                viewName = ControllerContext.RouteData.GetRequiredString("action");

            ViewData.Model = model;

            using (StringWriter sw = new StringWriter())
                ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
                ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
                viewResult.View.Render(viewContext, sw);

                return sw.GetStringBuilder().ToString();

How to set default value to a radio button in ASP.NET MVC 3

            @Html.RadioButtonFor(model => model.TermsAndConditions, "True")
            @Html.RadioButtonFor(model => model.TermsAndConditions, "False", new { Checked = "checked" })

How many number data type in Javascript?

Only one. All numbers in Javascript are 64bit (8 bytes) floating point numbers

Thursday, June 13, 2013

How to make content inside iframe 100% height without scrollbar?

<script language="javascript" type="text/javascript">
  function resizeIframe(obj) {
    obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
<iframe src="http://google.com/" frameborder="0" scrolling="no" id="iframe" onload='javascript:resizeIframe
(this);' />

SignalR example code projects

Asp.Net SignalR Chat Room


Wednesday, June 12, 2013

How to solve problem: Bootstrap not working with jQuery UI datepicker?

Need to make sure the references for javascript and css in following order:


How to get current Action and Controller name in ASP.NET MVC?

From ViewContext
        string action = ViewContext.RouteData.Values["action"].ToString();
        string controller = ViewContext.RouteData.Values["controller"].ToString();

Tuesday, June 11, 2013

JSbooks, Javascript free resources


Monday, June 10, 2013

How to make footer fixed to the bottom in Bootstrap?

By new class in Bootstrap 2.2.1: navbar-fixed-bottom

How to add Bootstrap into ASP.NET MVC 3?


Download different themes from

How to upgrade ASP.NET MVC 3 to MVC 4?

By nuget package:
PM> Install-Package UpgradeMvc3ToMvc4


Friday, May 31, 2013

How to update BLOB field in SQL Server?

UPDATE myTable
SET theBlobField =
WHERE [ID] = 1

How to save binary (BLOB) field into local file from SQL Server database by SQL?

 @ObjectToken INT

  SELECT csl_CompanyLogo from mlm_CSCompanySettingsLocalizations


  SET @TIMESTAMP = 'd:\' + replace(replace(replace(replace(convert(varchar,getdate(),121),'-',''),':',''),'.',''),' ','') + '.bmp'


  EXEC sp_OACreate 'ADODB.Stream', @ObjectToken OUTPUT
  EXEC sp_OASetProperty @ObjectToken, 'Type', 1
  EXEC sp_OAMethod @ObjectToken, 'Open'
  EXEC sp_OAMethod @ObjectToken, 'Write', NULL, @IMG_PATH
  EXEC sp_OAMethod @ObjectToken, 'SaveToFile', NULL, @TIMESTAMP, 2
  EXEC sp_OAMethod @ObjectToken, 'Close'
  EXEC sp_OADestroy @ObjectToken




Thursday, May 30, 2013

How to solve "null reference exception" problem when turn off ProxyCreationEnabled in Code first Entity framework?

If turn on lazy loading in entity framework by:
Configuration.ProxyCreationEnabled = false;
Will get null reference exception problem when try to get navigation properties.

Need to do eagerly loading for navigation property by include clause
using (var context = new BloggingContext())
    // Load all blogs and related posts
    var blogs1 = context.Blogs
                          .Include(b => b.Posts)


Inheritance in Entity Framework Code First

public abstract class Person
     public int PersonID { get; set; }
     public string Name { get; set; }
public class StaffMember : Person
     public string BadgeNumber { get; set; }
     public virtual ICollection Appointments { get; set; }
public class Client : Person
     public virtual ICollection Appointments { get; set; }

public class MyContext : DbContext
     public DbSet People { get; set; }
     protected override void OnModelCreating(DbModelBuilder modelBuilder)
     public void Seed(MyContext context)
          Client c1 = new Client { Name = "Steve Client" };
          StaffMember sm1 = new StaffMember { Name = "Staff 1", BadgeNumber = "1234" };
          StaffMember sm2 = new StaffMember { Name = "Staff 2", BadgeNumber = "5678" };

      public MyContext()
           Database.SetInitializer(new DropCreateDatabaseAlways());


Friday, May 24, 2013

What's the difference between IFrame and Frameset?

Frameset is dead and long live iframe :)
Frameset replace body elment. And ifeame can be anywhere in the body. Also frameset is NOT supported in HTML 5


Wednesday, May 22, 2013

How to insert BLOB data into database by SQL script?

SELECT ThumbnailPhoto.*, null, null, N'tricycle_pink.gif'
(BULK 'c:\images\tricycle.jpg', SINGLE_BLOB) ThumbnailPhoto

Tuesday, May 21, 2013

How to add jQuery reference into ASP.NET MVC 4 project?


How to solve "Access is denied" problem in new ASP.NET MVC 4 project?

- Press F4 on the MVC project to open project property window
- Change "Windows Authentication" from "Disabled" to "Enabled"

Error message

Server Error in '/' Application.
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.

Thursday, May 16, 2013

How to get visitor's MAC address in ASP.NET?

No, you can't. MAC address is not included in request IP header.

Monday, May 13, 2013

How to login into ASP.NET webforms site by HttpWebRequest


private void Button5_Click(object sender, System.EventArgs e)
// first, request the login form to get the viewstate value
HttpWebRequest webRequest = WebRequest.Create(LOGIN_URL) as HttpWebRequest;
StreamReader responseReader = new StreamReader(
string responseData = responseReader.ReadToEnd();

// extract the viewstate value and build out POST data
string viewState = ExtractViewState(responseData);
string postData =

// have a cookie container ready to receive the forms auth cookie
CookieContainer cookies = new CookieContainer();

// now post to the login form
webRequest = WebRequest.Create(LOGIN_URL) as HttpWebRequest;
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.CookieContainer = cookies;

// write the form values into the request message
StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream());

// we don't need the contents of the response, just the cookie it issues

// now we can send out cookie along with a request for the protected page
webRequest = WebRequest.Create(SECRET_PAGE_URL) as HttpWebRequest;
webRequest.CookieContainer = cookies;
responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());

// and read the response
responseData = responseReader.ReadToEnd();


Friday, May 10, 2013

How to add static html in ASP.NET MVC site?

Need to change routing setting in Global.asax.cs file like following:

        public static void RegisterRoutes(RouteCollection routes)

Thursday, May 9, 2013

How to change URL without reloading current page by Javascript

window.history.pushState('page2', 'Title', '/page2');

Tuesday, May 7, 2013

What is the difference between Html button and input type=button?

Almost same, but button with more rendering abilities.

Buttons created with the BUTTON element function just like buttons created with the INPUT element, but they offer richer rendering possibilities: the BUTTON element may have content. For example, a BUTTON element that contains an image functions like and may resemble an INPUT element whose type is set to “image”, but the BUTTON element type allows content.
The Button Element - W3C


Friday, May 3, 2013

How to extract text from html by HtmlAgilityPack?

            string htmlstring ="


"; HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(htmlstring); foreach (var script in doc.DocumentNode.Descendants("script").ToArray()) script.Remove(); foreach (var style in doc.DocumentNode.Descendants("style").ToArray()) style.Remove(); string ExtractedText = doc.DocumentNode.InnerText;

How to change EDMX connection string at runtime in Entity Framework?

Call constructor with connection string parameter like:
var db = new dbContext(connectionstring);

How to use MVC, Webforms and Web API in same ASP.NET project?


Leverage Multiple Code Frameworks with One ASP.NE

Remove Unwanted HTTP Response Headers


Server - Specifies web server version.
X-Powered-By - Indicates that the website is "powered by ASP.NET."
X-AspNet-Version - Specifies the version of ASP.NET used.

Thursday, May 2, 2013

How to change cursor when loading page or selecting item from dropdownlist in ASP.NET webform?

Goto master page
Add two events in body tag like following
<body onbeforeunload="document.body.style.cursor = 'wait';" onunload="document.body.style.cursor = 'default';">

Use a Software Bug to Win Video Poker? That’s a Federal Hacking Case


Monday, April 29, 2013

How to create image link in ASP.NET MVC?

@Html.ActionLink("buttontext", "actionName", "controllerName", null, new { @class="alinkimage" })

CSS definition:

background: url(../Images/image.gif) no-repeat top left;
display: block;
width: 150px;
height: 150px;

Saturday, April 27, 2013

How to encode url in ASP.NET MVC 3


Wednesday, April 24, 2013

The best interface is no interface


How to validate Canada postal code by regular expression?

Code example for ASP.NET webform  RegularExpression validator

<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="*" ControlToValidate="TextBoxPostalCode" ValidationExpression="^[ABCEGHJKLMNPRSTVXY]\d[A-Z]\d[A-Z]\d$"></asp:RegularExpressionValidator>

Basic Concept
Online Regular Expression tester

Monday, April 22, 2013

How to convert ASP.NET textbox input value into upcase right way?

Add following javascript into ASP.NET textbox control

Friday, April 19, 2013

How to add ajax validation on field in ASP.NET MVC 3?
By Remote Attribute. This way is MS designed for you.

//In Model
        [Remote("CheckExistedEmail", "ControllerName")]
        [Display(Name = "Email address")]
        [RegularExpression(@"^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$",ErrorMessage="Invalid email address")]
        public string Email { get; set; }

//In Action 
        public JsonResult CheckExistedEmail(string Email)
            if (EmailExisted(Email))
                return Json("Existed Email.", JsonRequestBehavior.AllowGet);
                return Json(true, JsonRequestBehavior.AllowGet);


Thursday, April 18, 2013

How many ways to redirect URL in Javascript?

1. window.location.href=”login.htm";
2. window.navigate(”login.htm”);
3. self.location=”login.htm”;

Any other way?

Wednesday, April 17, 2013

How to disable browser back button in asp.net?

Should make ASP.NET page cache expired instead of disable browser back button


Tuesday, April 16, 2013

How to get active users in last 10 minutes in ASP.NET membership database?

select top 300 * from dbo.aspnet_Users u
where u.LastActivityDate > DATEADD(minute, -10, GETUTCDATE())
order by u.LastActivityDate desc

Monday, April 15, 2013

How to fix problem: missing files when publish a website in Visual Studio for ASP.NET?

In Visual Studiio, Content files need to be marked for publishing
Right click on the file missed -> Properties -> Build Action set to Content.

Thursday, April 11, 2013

How to find common items in two set of items in C#?

            var list1 = new List() { 1, 3, 4, 5 };
            var list2 = new List() { 2, 3, 4, 5 };
            var commonItems = list1.Intersect(list2);

Friday, April 5, 2013

MVC 4: facebook twitter login with oAuth


Wednesday, April 3, 2013

How to set Connection: Keep-Alive in C# HttpWebRequest class ?

Cannot set by: webrequest.KeepAlive = true;
Have to set this request header by reflection
var req = (HttpWebRequest)WebRequest.Create(someUrl);

var sp = req.ServicePoint;
var prop = sp.GetType().GetProperty("HttpBehaviour", BindingFlags.Instance | BindingFlags.NonPublic);
prop.SetValue(sp, (byte)0, null);


Tuesday, April 2, 2013

How to validate a URL in ASP.NET?

By Regular expression data annotation in Model class

[RegularExpression(@"^(http|https|ftp)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|localhost|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\?\'\\\+&%\$#\=~_\-]+))*$", ErrorMessage = "Invalid url")]
public string Url { get; set; }

How to set Max length for an input in ASP.NET MVC

By StringLength data annotation

[StringLength(20, ErrorMessage = "Name cannot be longer than 20 characters.")]
public string Name { get; set; }

Monday, April 1, 2013

How to use TextArea for @Html.EditorFor in ASP.NET MVC?

Two ways:
1. Add data annotation in Model class
public string Text { get; set; }

2. @Html.TextAreaFor(model => model.Text)

How to change EditFor width in ASP.NET MVC 3?

Should be very simple? But need to two steps to do so:
1. Replace EditFor with TextBoxFor
2. Pass html property into TextBoxFor

@Html.TextBoxFor(m => m.Name, new {style = "width:50px"})

How to add data annotations to a class without changing it?

By MetadataType class
- Inherent from it, make it to be base class
- Then use metadata class to add validation data annotations in subclass
public class Model : Base_Class {

internal class ModelMetadata {
    public string Name { get; set; }

Thursday, March 28, 2013

Wednesday, March 27, 2013

How to deal with error "System.Data.MetadataException: Unable to load the specified metadata resource" when move edmx entity file to another project?

Cause: the res:// path changed. Need to be modified

Change connection for edmx file from

Monday, March 25, 2013

What is constructor instruction in C#?

The red color part is intructing to call another contructor.
    class ListNode
        private object data;
        private ListNode next;
        public ListNode(object dataValue) : this(dataValue, null)
        public ListNode(object dataValue, ListNode nextNode)
            data = dataValue;
            next = nextNode;

Friday, March 22, 2013

What is exception code: 0xe053534f

Mean: soft stack overflow
If hapends in IIS server, check code related to the permision

Wednesday, March 20, 2013

Hacking the HTML a tag in 100 characters

// Uncompressed
var links = document.links;
for(i in links) {
    links[i].onclick = function(){
        this.href = 'http://bit.ly/141nisR';

// Compressed (was 100; now 67 characters exc. the link)
// Thanks to sgoel from HN
o=document.links;for(i in o){o[i].onclick=function(){this.href='//bit.ly/141nisR'}}

Monday, March 18, 2013

Why session expired so fast in ASP.NET?

A lot of reasons, check following list for detail:


Thursday, March 14, 2013

Tuesday, March 12, 2013

How to read cookie value in ASP.NET MVC razor view?



Monday, March 11, 2013

ASP.NET Web API REST Security Basic


Thursday, March 7, 2013

How to keep ASP.NET application "alive" ?

There is one event call, Application_End in Global.asax. It happens when IIS application pool is recycled or the application itself is unloaded.
So add one call to self website to make application running again.

        protected void Application_End(object sender, EventArgs e)
                WebClient http = new WebClient();
                string Result = http.DownloadString(yourwebsiteurl);
            catch (Exception ex)
                string Message = ex.Message;

Tuesday, March 5, 2013

How to get started on “Service Unavailable 503” error in ASP.NET?

In IIS Server application pool default settings,
If application crashed 5 times in 5 minutes, IIS will return 503 error.
Check log to get detail of errors


Friday, March 1, 2013

How to reset Orchard admin password from database?

  update [Orchard_Users_UserPartRecord] 
  SET [Password] ='password', [PasswordFormat] ='Clear'
  where [UserName] ='admin'

Thursday, February 28, 2013

Wednesday, February 27, 2013

How to create web service project in Visual Studio 2010?

1. New Project
2. Change .Net Framwork version from 4.0 to 3.5
3. Click Web

Tuesday, February 26, 2013



What is Emergent Design?

The essence of incremental design is that we start with what we know, create an initial design, and then extend the design as we learn more.

This is also called “emergent design” as the design emerges over time.

Consuming ASP.NET Web API services in Windows 8 C# XAML apps


Monday, February 25, 2013

Friday, February 22, 2013

How to check one web site is HTTP compression enabled?

1. By this website

2. By Chrome f12 tool/Firefox Firebug
Checking reponse headers if exists: Content-Encoding:gzip

(IE f12 tool does not display this header)

How to add GZip compression in ASP.NET?


Thursday, February 21, 2013

How to develop Android apps by C#?


Wednesday, February 20, 2013

Can you Restore SQL Server 2012 backup to a SQL Server 2008 database?

No. Error message: Specified cast is not valid. (SqlManagerUI)
You can restore 2008 to 2012, but not backward.

Tuesday, February 19, 2013

How to Cache image in IHttpHandler?

1. Check header If-Modified-Since, if found, then return Not modified
2. Set Last-Modified header in response header
    public class GetImage : IHttpHandler
        public void ProcessRequest(HttpContext context)
            var If_Modified_Since = context.Request.Headers["If-Modified-Since"];
            if (If_Modified_Since != null)
                context.Response.StatusCode = 304;
            context.Response.BinaryWrite(Image2Byte(CreateBitmapImage("Hello World")));
            context.Response.Cache.SetMaxAge(new TimeSpan(1, 0, 0)); 
            context.Response.ContentType = "image";

How to solve "This operation requires IIS integrated pipeline mode."

Change from:
context.Response.Headers.Add("header", "header");
context.Response.AddHeader("header", "header");

Friday, February 15, 2013

How to extract Javascript from html source by HtmlAgilityPack

            HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
            var scriptList = htmlDoc.DocumentNode.Descendants()
                .Where(n => n.Name == "script" );

Thursday, February 14, 2013

How to cache image in httphandler?

        public void ProcessRequest(HttpContext context)
            context.Response.BinaryWrite(Image2Byte(CreateBitmapImage("Hello World")));
            context.Response.Expires = 100;

Tuesday, February 12, 2013

How to implement IoC in ASP.NET webform by HttpModule/CustomAttribute/Windsor


   // index.aspx.cs
    public partial class IndexPage : System.Web.UI.Page
        protected void Page_Load(object sender, EventArgs e)
            Logger.Write("page loading");

        public ILogger Logger { get; set; }

    // WindsorHttpModule.cs
    public class WindsorHttpModule : IHttpModule
        private HttpApplication _application;
        private IoCProvider _iocProvider;

        public void Init(HttpApplication context)
            _application = context;
            _iocProvider = context as IoCProvider;

            if(_iocProvider == null)
                throw new InvalidOperationException("Application must implement IoCProvider");

            _application.PreRequestHandlerExecute += InitiateWindsor;

        private void InitiateWindsor(object sender, System.EventArgs e)
            Page currentPage = _application.Context.CurrentHandler as Page;
            if(currentPage != null)
                currentPage.InitComplete += delegate { InjectUserControls(currentPage); };

        private void InjectUserControls(Control parent)
            if(parent.Controls != null)
                foreach (Control control in parent.Controls)
                    if(control is UserControl)

        private void InjectPropertiesOn(object currentPage)
            PropertyInfo[] properties = currentPage.GetType().GetProperties();
            foreach(PropertyInfo property in properties)
                object[] attributes = property.GetCustomAttributes(typeof (InjectAttribute), false);
                if(attributes != null && attributes.Length > 0)
                    object valueToInject = _iocProvider.Container.Resolve(property.PropertyType);
                    property.SetValue(currentPage, valueToInject, null);

    // Global.asax.cs
    public class Global : System.Web.HttpApplication, IoCProvider
        private IWindsorContainer _container;

        public override void Init()


        private void InitializeIoC()
            _container = new WindsorContainer();

        public IWindsorContainer Container
            get { return _container; }

    public interface IoCProvider
        IWindsorContainer Container { get; }

Monday, February 11, 2013

How to TryParse Enum?

    public enum color
        red =1, blue=2

            color result;
            bool IsParsingCorrect = Enum.TryParse("red", true, out result);
            IsParsingCorrect = Enum.TryParse("green", true, out result);

Thursday, February 7, 2013

What is Reponsive UI?

Website is able to changes layout by device type.


Wednesday, February 6, 2013

How to fix "Hexadecimal value 0x is an invalid character"?

Because xml includes invalid character.
Add an filter following for xml content

/// Remove illegal XML characters from a string.
public string SanitizeXmlString(string xml)
 if (xml == null)
  throw new ArgumentNullException("xml");
 StringBuilder buffer = new StringBuilder(xml.Length);
 foreach (char c in xml)
  if (IsLegalXmlChar(c))
 return buffer.ToString();

/// Whether a given character is allowed by XML 1.0.
public bool IsLegalXmlChar(int character)
   character == 0x9 /* == '\t' == 9   */          ||
   character == 0xA /* == '\n' == 10  */          ||
   character == 0xD /* == '\r' == 13  */          ||
  (character >= 0x20    && character <= 0xD7FF  ) ||
  (character >= 0xE000  && character <= 0xFFFD  ) ||
  (character >= 0x10000 && character <= 0x10FFFF)


Tuesday, February 5, 2013

How to fix "The type or namespace name could not be found (are you missing a using directive or an assembly reference?)"

First of all, check if this assembly you already added into your project.

If yes, but still get this problem:
Go to Project Properties -> Application -> Target framework
Change this value to .NET Framework 4.0 from .NET Framework 4.0 Client Profile

Monday, February 4, 2013

Friday, February 1, 2013

The clearest way to express polymorphism

public abstract class Human
   public abstract void goPee();

public class Male extends Human
public void goPee()
System.out.println("Stand Up");

public class Female extends Human
public void goPee()
System.out.println("Sit Down");
//Now we can tell an entire room full of Humans to go pee.

public static void main(String args)
ArrayList group = new ArrayList();
group.add(new Male());
group.add(new Female());
// ... add more...

// tell the class to take a pee break
for( Human person : group) person.goPee();

Wednesday, January 30, 2013

How to generate and download iCalendar file in ASP.NET MVC?

public ActionResult DownloadiCalendar()
            MemoryStream output = new MemoryStream();
            StreamWriter writer = new StreamWriter(output, System.Text.Encoding.UTF8);
            output.Seek(0, SeekOrigin.Begin);
            return File(output, "text/calendar", "appointment.ics");

        private string GetCalendarString()
            string DateFormat = "yyyyMMddTHHmmssZ";
            DateTime startDate = DateTime.Now.AddDays(5);
            DateTime endDate = startDate.AddMinutes(35);
            string organizer = "foo@bar.com";
            string location = "My House";
            string summary = "My Event";
            string description = "Please come to\\nMy House";

            string calendar = "BEGIN:VCALENDAR";
            calendar = calendar + "\nVERSION:2.0";
            calendar = calendar + "\nMETHOD:PUBLISH";
            calendar = calendar + "\nBEGIN:VEVENT";
            calendar = calendar + "\nORGANIZER:MAILTO:" + organizer;
            calendar = calendar + "\nDTSTART:" + startDate.ToUniversalTime().ToString(DateFormat);
            calendar = calendar + "\nDTEND:" + endDate.ToUniversalTime().ToString(DateFormat);
            calendar = calendar + "\nLOCATION:" + location;
            calendar = calendar + "\nUID:" + DateTime.Now.ToUniversalTime().ToString(DateFormat) + "@mysite.com";
            calendar = calendar + "\nDTSTAMP:" + DateTime.Now.ToUniversalTime().ToString(DateFormat);
            calendar = calendar + "\nSUMMARY:" + summary;
            calendar = calendar + "\nDESCRIPTION:" + description;
            calendar = calendar + "\nPRIORITY:5";
            calendar = calendar + "\nCLASS:PUBLIC";
            calendar = calendar + "\nEND:VEVENT";
            calendar = calendar + "\nEND:VCALENDAR";

            return calendar;

How run a ASP.NET project without Visual Studio and IIS configuration?

By ASP.NET development server:

"C:\Program Files (x86)\Common Files\microsoft shared\DevServer\10.0\webdev.webserver40.exe" /path:"C:\ProjectFolder" /vpath:/

Tuesday, January 29, 2013

Monday, January 28, 2013

How to delete cookies in ASP.NET?

In fact, delete mean "expire"

if (Request.Cookies["UserSettings"] != null)
    HttpCookie myCookie = new HttpCookie("UserSettings");
    myCookie.Expires = DateTime.Now.AddDays(-1d);

iPhone 4 simulator


ASP.NET Image Control With Fallback URL


Friday, January 18, 2013

How to validate an email address by Model DataAnnotations in ASP.NET MVC

        [Display(Name = "Email address")]
        [RegularExpression(@"^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$",ErrorMessage="Invalid email address")]
        public string Email { get; set; }

What is the best regular expression for an email address?




Adding SignalR to an ASP.Net WebForms Project