Saturday 31 December 2011

Microsoft Managed Extensibility Framework (MEF)

Managed Extensibility Framework (MEF) is a composition layer for .NET that improves the flexibility, maintainability and testability of large applications. MEF can be used for third-party plugin extensibility, or it can bring the benefits of a loosely-coupled plugin-like architecture to regular applications.


MEF is a part of the Microsoft .NET Framework, with types primarily under theSystem.ComponentModel.Composition.* namespaces.

  • MEF has shipped with .NET 4.0 and Silverlight 4
  • MEF 2 is under development and can be downloaded in source code and binary form from this site

For more information, click here.



Saturday 24 December 2011

Useful Git Terms



  • master: this is the main code branch, equivalent to trunk in Subversion. Branches are generally created off of master.
  • origin: the default remote repository that all your branches are pull'ed from and push'ed to. This is defined when you execute the initial git clone command.
  • fast-forward: the process of bringing a branch up-to-date with another branch, by fast-forwarding the commits in one branch onto the other.
  • rebase: the process by which you cut off the changes made in your local branch, and graft them onto the end of another branch.
  • unpublished vs. published branches: an unpublished branch is a branch that only exists on your local workstation, in your local repository. Nobody but you know that branch exists. A published branch is one that has beenpush'ed up to github, and is available for other developers to checkout and work on.

Thursday 22 December 2011

NuGet Install Castle.Windsor and factilies for NLog or log4net

Install the following Castle packages from NuGet command line.
  1. PM>  install-package Castle.Windsor 
  2. PM>  install-package Castle.Core-NLog 
  3. PM> install-package Castle.Core-log4net
  4. PM> install-package Castle.LoggingFacility

 Notes: that Castle.Core-NLog has the Castle.Facilities for NLog.

Thursday 8 December 2011

Validation of viewstate MAC failed,in hosting on a web farm

If a web application is hosted by a web farm or cluster, you would experience this exception if you didn't set up the web.config correctly. The solution for resolving this exception is to ensure the configuration specifies the same validation key and validation algorithm in every single web.config in your deployment. AutoGeneration by default cannot be used in a cluster environment. Below is the sample machinekey config entry for your web.config
 
<configuration>
    <appSettings/>
    <connectionStrings/>
    <system.web>
        <machineKey  validationKey='44DB9132AD56D581F6DBFDD8F09EDFD167B75283771DB3241804B0F03602EBACF6349C724FAC64785F60653EC9F9CA20A4D377387A1677704525FE9147CE6AC3' decryptionKey='C77E66D32F8F554C507DDEC6DA2A1A470B5EE195DA584EDD' validation='SHA1'/>
    </system.web>
</configuration>
 

Sunday 13 November 2011

Manage IIS Application Pool from .Net C# code

  .Net framework provides a very easy-to-use API wrapper class, ServerManager, to help manage IIS system from any .Net application using either C# or VB.net. Below C# code snippet demonstrates how to restart/recycle a given AppPool in IIS.
     
    public void RestartAppPool(string appPool)
        {
            try
            {
                logger.Info("Restarting app pool: " + appPool);

                // Recycle app pool
                using (var manager = new ServerManager())
                {
                    var pool = manager.ApplicationPools[appPool];

                    if (pool != null) 
                    {
                        Process process = null;

                        if (pool.WorkerProcesses.Count > 0)
                        {
                            process = Process.GetProcessById(pool.WorkerProcesses[0].ProcessId);
                        }

                        if (pool.State == ObjectState.Stopped)
                            pool.Start();
                        else
                            pool.Recycle();

                        // clean up any worker thread created by app pool
                        if (process != null)
                        {
                            while (!process.HasExited)
                            {
                                Thread.Sleep(10);
                            }

                            process.Dispose();
                        }
                    }
                }

                //logger.Info("Successfully restarted app pool: " + appPool);
            }
            catch (Exception ex)
            {
               // logger.Error("Restart app pool error: " + ex);
            }
        }
 

Tuesday 8 November 2011

JQuery extension: numeric only input text

Here is the simply but re-usable approach, IMO: create an jquery numeric extension and then use the numeric extension in your input text box:

 
// numeric extension
jQuery.fn.onlyNumeric = function () {
    return this.each(function () {
        $(this).keydown(function (e) {
            var key = e.which || e.keyCode;
            if (!e.shiftKey && !e.altKey && !e.ctrlKey &&
                key >= 48 && key <= 57 || key >= 96 && key <= 105 ||
                key == 8 || key == 13 || key == 46 ||
                key == 35 || key == 36 || key == 37 || key == 39)
                return true;
            return false;
        });
    });
};
// use it in your input text box
$('#input_box').onlyNumeric();
 

Wednesday 2 November 2011

HTML meta tags for mobile or regular sites

For mobile site specifically:
<meta content='HandheldFriendly' name='true' />
<meta content='width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;' name='viewport' />
<meta name="viewport" content="width=device-width" />
<meta content='MobileOptimized' name='width' />
<meta content='HandheldFriendly' name='true' />
<meta name="google-site-verification" content="wYqVbCtxN_YM1tLTZmGkUDbEmNrSjpB7hBNp5_Avsvs" />


General meta tags for all sites:

<meta name="keywords" content="key words of you site" />
<meta name="description" content="description of your site" />

<meta http-equiv="Content-Typ" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=8" />




Friday 21 October 2011

Load testing ajax application using Visual Studio 2010

In order to do this, you need to extend Visual Studio Web Performance Test  with your own Extraction and/or Validation Rule. Visual Studio 2010, which my current working copy, has all interfaces provided for the needed customizations.

Here is an official tutorial for Creating a Custom Extraction Rule, which can lead you to the place where you can find all useful information and a real code example.

For java users, you may want to explore HtmlUnit platform.

Wednesday 19 October 2011

Avoid InfoWindow from shifting Google Maps

It's kind of inconsistent in some cases that Google InfoWindow would shift the map while panning. That's a huge user experience if this map behaviour is not your intention. There a couple ways to resolve it, either close the InfoWindow when panning the map way far causing it invisible, or set the proper value to an attribute of InfoWindow, which I believe it is the easiest and most solid solution. Here is the code snippet for the 2nd solution.

 
var infoWin = new google.maps.InfoWindow({disableAutoPan: true});
 

Tuesday 18 October 2011

Get Ready for Android App Development

Being excited about mobile application and open source platform? Apple or Android? Personally I like both platforms but more lean to Android as I don't have any "expensive" Apple computer. Would be nice if I could get a sponsor. So Android App is my target for contributing to the community.

To get ready for your Android App development, you need the following stuff.
  1. JDK, any version since1.6.x or later and can be downloaded from here.
  2. Android SDK, and it can be downloaded from here.
  3. Eclipse IDE (recommended but not necessary), preferable to download Java EE Developer version
  4. Download and install Android Development Tools (ADT) plug-in for Eclipse.
  5. Add Android platforms to development environment.
    • From Eclipse, go to Window -> Android SDK and AVD Manager.
    • On Windows, double click the SDK Manager.exe file at the root fo the Android SDK directory.
    • On Mac or Linux, open a terminal and navigate to the tools/ directory in the Android SDK, then execute command: android
Now, you should be ready to get your hands wet on your first Android App development, Hello Word, for example. :)

For more information, you can always go to Android official home site for developers.





Sunday 16 October 2011

Convert Latitude and Longitude to android.maps.GeoPoint

Use the following code snippets


 
GeoPoint point = new GeoPoint((int)(latitude * 1e6), (int)(longitude * 1e6));
 

Obtain Android Google Maps SDK Debug Certificate

For developing your Google Maps application for android, I would like to obtain a debug Google Maps SDK debug certificate before production release. Android.com provides a very thorough instruction for helping newbies and beginners. Here I just list the steps that I went through in my own development environment: Windows 7 32bit + JDK1.7.0. Hope it would help simplify your learning curve.


1. Locate your debug.keystore.
    By default, build tools create the debug keystore in the active AVD directory which varies by platform:
  •     Windows Vista/7: c:\users\<user>\.android\debug.keystore
    For eclipse/ADT user, go to Windows -> Preferences -> Android -> Build for the full path of debug.keystore.

2. After the debug.keystore was located, use keytool utility to obtain the MD5 fingerprint of the debug certificate.
    Replace the below command with your JDK installation path and your actual user id
    "c:\program files\java\jdk1.7.0\bin\keytool" -v -list -alias androiddebugkey -keystore c:\users\<user>\.android\debug.keystore -storepass android -keypass android
    Note: only the MD5 fingerprint is recognized by Google. Other version, such as SHA1/256, is new since JDK 1.7, and cannot be used for registering Google Maps API.

3. Now, follow steps below to register your debug certificate with Google Maps Service
  1. Go to http://code.google.com/android/maps-api-signup.html
  2. If you don't have a Google account, use the link on the page to set one up. 
  3. Read the Android Maps API Terms of Service carefully. If you agree to the terms, indicate so using the checkbox on the screen. 
  4. Paste the MD5 certificate fingerprint of the certificate that you are registering into the appropriate form field. 
  5. Click "Generate API Key" 
The server will handle your request, associating the fingerprint with your developer identity and generating a unique Maps API Key, and then will return a results page that gives you your Key string.

Wednesday 5 October 2011

Find GPS location (latitude and longitude) is within given radius

In a project, I need to determine whether a given GPS location (latitude and longitude) is within a pre-set radius area, for example, within a 2 kilometres circle of a target place - Vancouver Convention Centre. It's not a rocket science to do it but it would be helpful for those who need to implement the similar logic.

Here is code snippet in javascript, and could be easily ported to other languages, like C#.

 
// center: the center goelocation of the radius
// radius: radius in meter
// loc: the geolocation that you want to check
function isInArea(center, radius, loc) {
        var R = 6371;
        var lat1 = loc.lat();
        var lon1 = loc.lng();
        var lat2 = center.lat();
        var lon2 = center.lng();
        var dLat = (lat2 - lat1) * Math.PI / 180;
        var dLon = (lon2 - lon1) * Math.PI / 180;
        var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
		Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
		Math.sin(dLon / 2) * Math.sin(dLon / 2);
        var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        var d = R * c;
        return (d * 1000 <= radius)
    };
 

Tuesday 27 September 2011

Create/Change SVN user and password using htpasswd

To create a new SVN user c:\program files\Collabnet\bin\htpasswd -cm ../config/authz-file username password To change existing SVN user's password c:\program files\Collabnet\bin\htpasswd -m ../config/authz-file username

Saturday 24 September 2011

Android Historical Version Names

Android version history and its nick name.
1.5 Cupcake
1.6 Donut
2.0 Eclair
2.2 Froyo
2.3 Gingerbread
3.0 Honeycomb

Friday 23 September 2011

JQuery Ajax Call to Web service via POST

Have been used a lots of jquery in the recent real-time information web development project, I found this quite easy to initiate a POST HTTP call to web service through JQuery. Here are 2 sample code snippets.

Case 1: Pass no parameter

 
<script type="text/javascript">
    // in this case, we post nothing back to api but
    // just call it (no parameter required) and expected json object as result
    function callWebApiViaPost() {
        $.ajax({
            type: "POST",
            url: "yourwebapi",
            data: "{}",
            contentType: "application/json;",
            dataType: "json",
            success: function (t) {
                $("#your_result_display_div").text(t.d);
            }
        });
    }

</script>
 

Case 2: Pass parameter(s)

For example, you have a API like below:
 
[WebMethod]
public static string ToUpperCase(string yourparam)
{
    return yourparam.ToUpper();
}
 
The corresponding jquery ajax post call will be like this:
 
<script type="text/javascript">
    // in this case, we post nothing back to api but
    // just call it (no parameter required) and expected json object as result
    function callWebApiViaPost() {
        $.ajax({
            type: "POST",
            url: "yourweb/ToUpperCase",
            data: "{yourparam: 'hello-world'}",
            contentType: "application/json;",
            dataType: "json",
            success: function (t) {
                $("#your_result_display_div").text(t.d);
            }
        });
    }

</script>
 

Friday 16 September 2011

SQL Server deadlock caused by Inappropriete Index

Recently one of my projects experienced weird transaction deadlock error on the data processing component. The component was running well without errors in the first week of production, but suddenly threw dozens of SQL exception "Transaction (Process ID 69) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.". After digging into a day of the code and database analysis, it appears that a row update operation actually causes an exclusive table level lock. As the result, other update request(s) from my multi-threading component trigger the deadlocks. A further analysis, the grief was a inappropriate primary key index which trigger SQL Server escalates the lock level from row to table. Once the root cause was identified, the remediation is considerable easy and is to make sure the "ALLOW_ROW_LOCKS" option was checked which should be a default setting in SQL Server 2008, and the index type is clustered.

 
alter index [your_index_name] on [dbo].[your_table_name] set (allow_row_locks = ON);
 

Friday 9 September 2011

Hash Table or Key/Value pair Array in JavaScript

Key/Value or hash table sometimes is very handy and helpful on implementing your business logic. In .Net world, I use a lot of Dictionary<TKey, TValue> collection object. How to do the same thing using Javascript is bit a tricky to me as I spent most of my time in the past using Microsoft C++ and C# developing server-side system. Google it a bit and here is my working solution including of declaration, insertion and deletion of items.
 
// declare a hash table
var myTable = new Array();
// add new items to the table
myTable['key1'] = 'hello';
myTable['key2'] = 'world';
myTable['key3'] = ' world.';

// remove a item from the table
delete myTable['key2'];
 

Thursday 8 September 2011

Dynamically add CSS file to ASP.Net page

Programmatically include CSS file to ASP.Net page is considerable simple. Add follow code to your page initialization event. Next time when page was loaded, reference to your css file will be added at runtime.

 
    protected void Page_Init(object sender, EventArgs e)
    {
        HtmlLink css = new HtmlLink();
        css.Href = "css/fancyforms.css";
        css.Attributes["rel"] = "stylesheet";
        css.Attributes["type"] = "text/css";
        css.Attributes["media"] = "all";
        Page.Header.Controls.Add(css);
    }
 

Tuesday 6 September 2011

Detect Browser or User Agent from Server-side

My previous post on Detect Browser or User Agent using JavaScript has described a solution on how to do it from client-side. Today, I want to show how to detect user agent or browser type at server-side. It's quite straightforward under ASP.Net framework. Put the following code in your Global.asax so it checks for every new request. The sample code is written in C# and can be in any .Net language.


 
public class Global : System.Web.HttpApplication
{
    void Session_Start(object sender, EventArgs e)
    {
        DetectBrowser();
    }
    // detect browser type by checking user agent
    // and then do specific things for each platform
    private void DetectBrowser()
    {
        string agent = Request.UserAgent.ToLower();
        if (agent.Contains("iphone") ||
            agent.Contains("symbianos") || 
            agent.Contains("ipad") || 
            agent.Contains("ipod") || 
            agent.Contains("android") || 
            agent.Contains("blackberry") || 
            agent.Contains("samsung") || 
            agent.Contains("nokia") || 
            agent.Contains("windows ce") || 
            agent.Contains("sonyericsson") || 
            agent.Contains("webos") || 
            agent.Contains("wap") || 
            agent.Contains("motor") || 
            agent.Contains("symbian"))
        {
            // do your logic here for device specific requests
        }
        else
        {
            // do your logic here for PC/Mac requests
        }
    }
}
 

Monday 5 September 2011

Detect Browser or User Agent from Client-side using JavaScript

Optimized or tweaked your website for particular device platform, such as iPhone, Android, Windows 7 and etc., becomes more and more critical for improving user experience and attracting more traffic to your website. Usually it makes more sense to detect user browser or user agent on server side in order to redirect traffic to your well built device specific version of your main site as well as regular PC or Mac users. But there is always a case that client-side detection is more handy. Furthermore, it's very easy to do it using JavaScript and is supported by almost every browser platform.

 

<script type="text/javascript">
function doDevice () {
   var agent = navigator.userAgent;
   if (agent.indexOf('Windows') > 0) {
       // it's windows platform
   } else if (agent.indexOf('Android') > 0){
      // it's android platform
   } else if (agent.indexOf('iPhone') > 0) {
      // it's iPhone platform
  }
}
</script>

 

Thursday 1 September 2011

Generate Random bytes using C#

There is a quick way to generate random bytes for any given size using .Net framework. Why people would want to do so? I personally find it very handy in case I need to test network flow, encryption and/or do load/stress testing. Here is the code that you can past to your project. It generate a random bytes array for the given size.
 
public static byte[] GenerateRandomBytes(int length)
{
      // Create a buffer
      byte[] randBytes;
 
      if (length >= 1)
       {
            randBytes = new byte[length];
        }
        else
        {
            randBytes = new byte[1];
        }

        // Create a new RNGCryptoServiceProvider.
        System.Security.Cryptography.RNGCryptoServiceProvider rand = 
             new System.Security.Cryptography.RNGCryptoServiceProvider();

        // Fill the buffer with random bytes.
        rand.GetBytes(randBytes);

        // return the bytes.
        return randBytes;
}
 
 

Wednesday 31 August 2011

Convert XML to JSON using C#

Here is the working solution I borrowed and modified from somewhere. But I forgot the original source. If you're the original author, please let me know if you'd like your name listed on this post.

 
public static class JSon
{
    public static string XmlToJSON(string xml)
    {
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(xml);

        return XmlToJSON(doc);
    }
    public static string XmlToJSON(XmlDocument xmlDoc)
    {
        StringBuilder sbJSON = new StringBuilder();
        sbJSON.Append("{ ");
        XmlToJSONnode(sbJSON, xmlDoc.DocumentElement, true);
        sbJSON.Append("}");
        return sbJSON.ToString();
    }

    //  XmlToJSONnode:  Output an XmlElement, possibly as part of a higher array
    private static void XmlToJSONnode(StringBuilder sbJSON, XmlElement node, bool showNodeName)
    {
        if (showNodeName)
            sbJSON.Append("\"" + SafeJSON(node.Name) + "\": ");
        sbJSON.Append("{");
        // Build a sorted list of key-value pairs
        //  where   key is case-sensitive nodeName
        //          value is an ArrayList of string or XmlElement
        //  so that we know whether the nodeName is an array or not.
        SortedList<string, object> childNodeNames = new SortedList<string, object>();

        //  Add in all node attributes
        if (node.Attributes != null)
            foreach (XmlAttribute attr in node.Attributes)
                StoreChildNode(childNodeNames, attr.Name, attr.InnerText);

        //  Add in all nodes
        foreach (XmlNode cnode in node.ChildNodes)
        {
            if (cnode is XmlText)
                StoreChildNode(childNodeNames, "value", cnode.InnerText);
            else if (cnode is XmlElement)
                StoreChildNode(childNodeNames, cnode.Name, cnode);
        }

        // Now output all stored info
        foreach (string childname in childNodeNames.Keys)
        {
            List<object> alChild = (List<object>)childNodeNames[childname];
            if (alChild.Count == 1)
                OutputNode(childname, alChild[0], sbJSON, true);
            else
            {
                sbJSON.Append(" \"" + SafeJSON(childname) + "\": [ ");
                foreach (object Child in alChild)
                    OutputNode(childname, Child, sbJSON, false);
                sbJSON.Remove(sbJSON.Length - 2, 2);
                sbJSON.Append(" ], ");
            }
        }
        sbJSON.Remove(sbJSON.Length - 2, 2);
        sbJSON.Append(" }");
    }

    //  StoreChildNode: Store data associated with each nodeName
    //                  so that we know whether the nodeName is an array or not.
    private static void StoreChildNode(SortedList<string, object> childNodeNames, string nodeName, object nodeValue)
    {
        // Pre-process contraction of XmlElement-s
        if (nodeValue is XmlElement)
        {
            // Convert  <aa></aa> into "aa":null
            //          <aa>xx</aa> into "aa":"xx"
            XmlNode cnode = (XmlNode)nodeValue;
            if (cnode.Attributes.Count == 0)
            {
                XmlNodeList children = cnode.ChildNodes;
                if (children.Count == 0)
                    nodeValue = null;
                else if (children.Count == 1 && (children[0] is XmlText))
                    nodeValue = ((XmlText)(children[0])).InnerText;
            }
        }
        // Add nodeValue to ArrayList associated with each nodeName
        // If nodeName doesn't exist then add it
        List<object> ValuesAL;

        if (childNodeNames.ContainsKey(nodeName))
        {
            ValuesAL = (List<object>)childNodeNames[nodeName];
        }
        else
        {
            ValuesAL = new List<object>();
            childNodeNames[nodeName] = ValuesAL;
        }
        ValuesAL.Add(nodeValue);
    }

    private static void OutputNode(string childname, object alChild, StringBuilder sbJSON, bool showNodeName)
    {
        if (alChild == null)
        {
            if (showNodeName)
                sbJSON.Append("\"" + SafeJSON(childname) + "\": ");
            sbJSON.Append("null");
        }
        else if (alChild is string)
        {
            if (showNodeName)
                sbJSON.Append("\"" + SafeJSON(childname) + "\": ");
            string sChild = (string)alChild;
            sChild = sChild.Trim();
            sbJSON.Append("\"" + SafeJSON(sChild) + "\"");
        }
        else
            XmlToJSONnode(sbJSON, (XmlElement)alChild, showNodeName);
        sbJSON.Append(", ");
    }

    // Make a string safe for JSON
    private static string SafeJSON(string sIn)
    {
        StringBuilder sbOut = new StringBuilder(sIn.Length);
        foreach (char ch in sIn)
        {
            if (Char.IsControl(ch) || ch == '\'')
            {
                int ich = (int)ch;
                sbOut.Append(@"\u" + ich.ToString("x4"));
                continue;
            }
            else if (ch == '\"' || ch == '\\' || ch == '/')
            {
                sbOut.Append('\\');
            }
            sbOut.Append(ch);
        }
        return sbOut.ToString();
    }
}
 
To convert a given XML string to JSON, simply call XmlToJSON() function as below.
 
 
string xml = "<menu id=\"file\" value=\"File\"> " +
                  "<popup>" +
                    "<menuitem value=\"New\" onclick=\"CreateNewDoc()\" />" +
                    "<menuitem value=\"Open\" onclick=\"OpenDoc()\" />" +
                    "<menuitem value=\"Close\" onclick=\"CloseDoc()\" />" +
                  "</popup>" +
                "</menu>";

    string json = JSON.XmlToJSON(xml);
    // json = { "menu": {"id": "file", "popup": { "menuitem": [ {"onclick": "CreateNewDoc()", "value": "New" }, {"onclick": "OpenDoc()", "value": "Open" }, {"onclick": "CloseDoc()", "value": "Close" } ] }, "value": "File" }}
 

Output JSON from WCF RESTful Web Service


Under Microsoft WCF 4 framework, output either XML or JSON is fairly straightforward by simply setting a proper attribute property in your public service API function.

 
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class MyWebService
{
   [OperationContract]
   [WebGet(UriTemplate = "MyWebFunction/{userReq}", 
           ResponseFormat = WebMessageFormat.Json )]
   public string MyWebFunction(string userReq)
   {
      // do your magic here
      return "your magic result";
   }
   
   // your other public web function(s)
}
 

Tuesday 30 August 2011

Convert JSON text to object in Javascript

JSON (JavaScript Object Notation) is lightweight data-interchange structure which is fairly easy for human to read/write as well as for computer to process. GO here if you know more about it.

There are 2 cheap ways to consume JSON using javascript without a need of any 3rd party library. One is eval() function which is very fast. However it also compile and execute any javascript and impose potential security issue.
 

   function toObject(jsonText){
      return eval(jsonText);
   }

 

If this concerns you, a JSON parser should be used indeed. In browsers that provide native JSON support, call JSON.parse() function.

 

   function toObject(jsonTextn){
      return JSON.parse(jsonText);
   }

 

Display Close button on Input Box on iPhone

This can be easily archived by using new HTML5 input type: search. See the sample code below.


 
 

 


Friday 26 August 2011

JQuery Change Input Box Type

For security reason, some browsers such as IE don't allow modifying input type on the fly. Code snippet #1 won't know. In case you know exactly what you are doing and really want to modify the type dynamically for any good reasons. Here is a way to do so (see code snippet #2).

Code #1 - doesn't work in most of the browsers

 
Code #2 - works

 

Thursday 25 August 2011

Dynamically add meta tags in ASP.Net

Add the following code to master page on the page_load event handler. All it does is to add a keyword meta tag to the header of the html page from server-side, which opens a door to all other possibilities.

protected void Page_Load(object sender, EventArgs e)
{
   HtmlMeta meta = new HtmlMeta();
   meta.Name = "keywords";
   meta.Content = "ASP.Net, Web, meta tag";
   Header.Controls.Add(meta);
}

Thursday 18 August 2011

Visual Studio 2010 Load Test and Web Performance Test- Part 1

VS 2010 Ultimate subscribers can take advantage of advanced feature: Performance Test and Load Testing. The difference between performance test and load testing is:
Performance Test = how fast can your system be
Load Test = how much volume the system can process in a given interval

In Visual Studio 2010, a performance test must be created prior to setting up load testing as performance test (aka .webtest) is the only source of load test (aka .loadtest).

Will go through a working sample to dome how to set up performance test and load test in VS 2010.

Tuesday 16 August 2011

Reverse DNS lookup in Windows Command Line

Want to look up the domain name from a IP address in Windows platform? Use either of these 2 commands from your command prompt.

c:>ping -a xxx.xxx.xxx.xxx
or
c:>nslookup xxx.xxx.xxx.xxx

The output of each command is different but does one common thing returning the domain name of the IP address you enter.

Validation of viewstate MAC failed. System.Web.HttpException (0x80004005)

There are few workarounds provided by Microsoft back to 2008. See the original posting in here.

Personally I prefer solution#3 with Alex's improvement (see below). Luckily, .Net 4.0 or above has fix it within the framework.


 
public class BasePage : Page
{
private static string[] aspNetFormElements = new string[] 
{ 
"__EVENTTARGET",
"__EVENTARGUMENT",
"__VIEWSTATE",
"__EVENTVALIDATION",
"__VIEWSTATEENCRYPTED",
};

protected override void Render(HtmlTextWriter writer)
{
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
base.Render(htmlWriter);
string html = stringWriter.ToString();
int formStart = html.IndexOf("<form");
int endForm = -1;
if (formStart >= 0)
endForm = html.IndexOf(">", formStart);

if (endForm >= 0)
{
StringBuilder viewStateBuilder = new StringBuilder();
foreach (string element in aspNetFormElements)
{
int startPoint = html.IndexOf("<input type=\"hidden\" name=\"" + element + "\"");
if (startPoint >= 0 && startPoint > endForm)
{
int endPoint = html.IndexOf("/>", startPoint);
if (endPoint >= 0)
{
endPoint += 2;
string viewStateInput = html.Substring(startPoint, endPoint - startPoint);
html = html.Remove(startPoint, endPoint - startPoint);
viewStateBuilder.Append(viewStateInput).Append("\r\n");
}
}
}

if (viewStateBuilder.Length > 0)
{
viewStateBuilder.Insert(0, "\r\n");
html = html.Insert(endForm + 1, viewStateBuilder.ToString());
}
}

writer.Write(html);
}
}
 
 


Monday 15 August 2011

Trim leading zeros using javascript

Using simple RegExp in javacript can easily trim all leading zeros.


 
var numberString = ‘00220’;
var noLeadingZerosString = numberString.replace(/^0+/, ‘’); // noLeadingZerosString  = ‘220’;
 
 

Hide/remove transit stations from Google Map

I have been searching for the solution for a while on my recent real time transit project. The solution doesn't appear to be documented clearly. Here is my simplified working solution and hope it helps.


  

var latLng = new google.maps.LatLng(49.22587, -123.14044000000001); 
var mapOptions = {
zoom: 16,
minZoom: 10,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};

var node = document.getElementById("map_canvas");
var map = new google.maps.Map(node, mapOptions);
var ntss = [{
  featureType: 'transit.station',
  elementType: 'all',
  stylers: [{ visibility: 'off' }]
}];

var mapType = new google.maps.StyledMapType(ntss, { name: 'ntsss' }); 

map.mapTypes.set('nstps', mapType);

map.setMapTypeId('nstps'); 

  

Thursday 11 August 2011

Use and transform NLog config in web.config

Ever wonder how to integrate your log platform configuration into your web.config so it can be transformed nicely into different environments, such as QA, staging and production environment? Below is a example config that I worked on for a public transit website.


The original web.config looks like
 
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <targets>
      <target xsi:type="File"
              name="FileLog"
              layout="${longdate} | ${level:uppercase=true} | ${logger} | ${message}"
              fileName="c:\logs\log_${shortdate}.log"/>
    <rules>
      <logger name="*" minlevel="Trace" writeTo="FileLog" />
    </rules>
  </nlog>
 

Your Release.config, for example, will set to below if the production has different path for log files.

 
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"
  xmlns:nlg="http://www.nlog-project.org/schemas/NLog.xsd">

...

<nlg:nlog  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <nlg:targets >
      <nlg:target xsi:type="File"
              name="FileLog"
              layout="${longdate} | ${level:uppercase=true} | ${logger} | ${message}"
              fileName="d:\logs\prod\Log_${shortdate}.log"  xdt:Transform="SetAttributes"  xdt:Locator="Match(name)" />
    </nlg:targets>
  </nlg:nlog>
</configuration>
 

Wednesday 10 August 2011

Enable .Net 4.0 in IIS 7.0/7.5

Go to C:\Windows\Microsoft.NET\Framework(64)\v4.0.30319 and run the command from command prompt using "Run as Administrator".

cd \
cd C:\Windows\Microsoft.NET\Framework(64)\v4.0.30319
aspnet_regiis -ir

Monday 25 July 2011

Day One on Tech Has no Boundary

Computer Technologies has been intentionally divided into couple of  territories, Microsoft, Java, iOS, Unix/Linux and etc. Which is the best is an endless argument for decades. And what ends up to us, like most of the IT folks, is to learn various of platforms, terminologies and languages in order keep up our works/jobs. Lots of time was wasting on duplicating works that had been done by other people in a different platform/languages. How many people feel comfortable with that? Some may do as this is how the money comes from, right.?