Sunday, April 28, 2013

If element doesn't not exist

var obj=$("divElement");

If there is no element named "divElement", JQuery will not raise any error and JQuery will do nothing.
If you want to check if the element exists in the document, check the length property:

if ($("divElement").length>0)
{
//element exists, code
}

"length" property will return 0 if the element doesn't  exist.

document.ready() vs window.onload()

window.onload() is traditional Java script code which is called when the page is loaded.

The main difference is that document.ready() event gets called as soon as your DOM is loaded. It does not wait for the contents to get loaded fully.
For example, there are very heavy images on any web page and takes time to load. If you have used window.onload then it will wait until all your images are loaded successfully, so it slows down the execution. But, document.ready() does not wait for elements to get loaded

Tuesday, April 23, 2013

JQuery DataTable

You can have a table with paging, sorting, filtering...only by one line of code.
$("table#myTableId").dataTable();
Get the DataTable from NuGet, it's very powerful and easy to use. And especially, the performance is very good.
Note: JQuery DataTable works with <THead>, <TBody> , and <TFooter>. So, you need to define these sections in the table.

Get the detail and example from here.

Sunday, April 21, 2013

MVC, anti Cross Site Scripting

By default the ValidateInput value is true.
When you set the ValidateInput (false) , the system will not verify the input. So, the system will accept any text/content even it includes HTML tags. This is easy for malicious user to perform the cross site scripting (XSS).

To prevent the XSS when you set ValidateInput to false:
- Install the "AntiXSSLibrary" from NuGet
- and in your code, sanitize the content of textbox by:
     textbox1.Body = Sanitizer.GetSafeHtmlFragment(textbox1.Body);

How to improve performance of the MVC web application

Here are some tips:
1- Simplify the page's design
2- Reduce the number of HTTP requests by:
  - Minify Javascript and CSS and use bundle:
      @Styles.Render("...")
      @Scripts.Render("...")

 - CSS Sprites: combine your background image into a single image and  use the CSS background-image and background-position properties to display the desired image segment.
 - Image maps combine multiple images into a single image. The overall size is about the same, but reducing the number of HTTP requests speeds up the page. Image maps only work if the images are contiguous in the page, such as a navigation bar. Defining the coordinates of image maps can be tedious and error prone. Using image maps for navigation is not accessible too, so it's not recommended.

 - Inline images: Combining inline images into your (cached) stylesheets is a way to reduce HTTP requests and avoid increasing the size of your pages.

3- Use a Content Delivery Network (CDN)
Deploying your content across multiple, geographically dispersed servers will make your pages load faster from the user's perspective.

4- Use/Add Output Cache: to any frequently request pages
5- Put Stylesheets at the top: While researching performance at Yahoo!, we discovered that moving stylesheets to the document HEAD makes pages appear to be loading faster. This is because putting stylesheets in the HEAD allows the page to render progressively.

6- Put script at the bottom: The problem caused by scripts is that they block parallel downloads. The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname. If you serve your images from multiple hostnames, you can get more than two downloads to occur in parallel. While a script is downloading, however, the browser won't start any other downloads, even on different hostnames.

7- Avoid CSS Expression: CSS expressions are a powerful (and dangerous) way to set CSS properties dynamically. They were supported in Internet Explorer starting with version 5, but were deprecated starting with IE8. As an example, the background color could be set to alternate every hour using CSS expressions:

      background-color: expression( (new Date()).getHours()%2 ? "#B8D4FF" : "#F08A00" );

As shown here, the expression method accepts a JavaScript expression. The CSS property is set to the result of evaluating the JavaScript expression. The expression method is ignored by other browsers, so it is useful for setting properties in Internet Explorer needed to create a consistent experience across browsers.

8- Make Javascript and CSS as external files: Using external files in the real world generally produces faster pages because the JavaScript and CSS files are cached by the browser. JavaScript and CSS that are inlined in HTML documents get downloaded every time the HTML document is requested. This reduces the number of HTTP requests that are needed, but increases the size of the HTML document. On the other hand, if the JavaScript and CSS are in external files cached by the browser, the size of the HTML document is reduced without increasing the number of HTTP requests.

9- Remove/avoid duplicate scripts

10- Disable Request Validation : (becareful with XSS- Cross Site Scripting)  use client validation instead

    [ValidateInput(false)]
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Create([Bind(Exclude="Id")]Employee empObj)

    {
    
    }

11- Isolate Data Access Logic From the Controller: The Controller in an ASP.NET MVC application should never have the Data Access logic. The Controller in an ASP.NET MVC application is meant to render the appropriate view based on some user interface action. You should make use of Repository Pattern to isolate Data Access Logic from the Controller – you might need dependency injection to inject the appropriate Repository to your controller at runtime.

12- Disabled unused view engines: The more view engines you have registered the longer this will take and since the miss is not cached the process will have to be repeated the next time a page is requested. If you are using only one view engine in your project you should remove the other ones in Global.asax.

ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new RazorViewEngine());

13- Deploy Production Code in Release Mode: When we develop ASP.NET applications using Visual Studio, the default value for debug attribute is true. These settings will give a poor performance in production if released in the default debug mode. So, never release your website or application with debug mode set to true. It should be set to false in web.config when moving to production.
 <compilation debug="false" />

14- Removing unused HTTP Modules in web.config: remove the module that you don't need such as

 <httpModules>
  <remove name="PassportAuthentication" />
  <remove name="Profile" />
  <remove name="AnonymousIdentification" />
</httpModules>

REF and Details in:
- http://developer.yahoo.com/performance/rules.html
- http://blogs.msdn.com/b/marcinon/archive/2011/02/07/mvc-performance-tips.aspx
- http://www.codeguru.com/csharp/.net/net_asp/mvc/top-10-asp.net-mvc-best-practices.htm
- http://www.codeproject.com/Articles/41930/How-To-Improve-the-Performance-of-ASP-NET-MVC-Web

Friday, April 19, 2013

Joke :)

A helicopter was flying around above Seattle when an electrical malfunction disabled all of the aircraft's electronic navigation and communications equipment.

Due to the clouds and haze, the pilot could not determine the helicopter's position. The pilot saw a tall building, flew toward it, circled, and held up a handwritten sign that said "WHERE AM I?" in large letters. People in the tall building quickly responded to the aircraft, drew a large sign, and held it in a building window. Their sign said "YOU ARE IN A HELICOPTER."

The pilot smiled, waved, looked at his map, determined the course to steer to SEATAC airport, and landed safely. After they were on the ground, the copilot asked the pilot how he had done it.

"I knew it had to be the Microsoft Building, because they gave me a technically correct but completely useless answer."

Question of the day ????

What would be the right answer to the question "what would you do if you meet technical difficulties? "

Finally, it's on Google

Google Translate finally supports Khmer (Cambodian language) as the 66th language.
But the accuracy is still low lolzz...a good start anyway :)

http://thenextweb.com/asia/2013/04/19/google-translate-gains-support-for-its-66th-language-cambodias-khmer/

Data Collection Objects

- IEnumerable : a list object that can be only iterated through. It supports generic type and enforces type-safety.
- ICollection: a list object that can be iterated through and modified. It supports generic type and enforces type-safety.
- List: a list object that can be iterated through, modified, and sorted. It supports generic type and enforces type-safety.
- IQueryable : is for an interface LINQ-to-SQL

e.g. IEnuerable <Persons> persons=  PersonModel.GetPerson();
          var  person_female= persons.Where (p=>p.gender=="F");

The database will load all the person from the database. Then filter is applied in the program. So, all the records are loaded from the database, and the filter is applied.

e.g. IQueryable<Persons> persons=  PersonModel.GetPerson();
      var  person_female= persons.Where (p=>p.gender=="F"); // the data is retrieved here

The database's execution is : "Select * from Persons where Gender="F"). So, only the records with Gender="F" are returned to the program.

- HashTable: non-generic, it doesn't enforce type-safety
- Dictionary:  a hashtable that supports generic type and enforces type-safety
- Array
- ArrayList : doesn't support generic type, so it doesn't enforces type-satety
- Stack: LIFO
- Queue: FIFO

Thursday, April 18, 2013

MaxPageStateFieldLength

I have never used this property, however it's good to know.
MaxPageStateFieldLength specifies the maximum bytes that the view state can be placed in one hidden field. If the view state is larger than the value of  maxPageStateFieldLength, the view state will  be separated into several hidden fields automatically.

Setting the MaxPageStateFieldLength property to a negative number (the default is -1) indicates that the viewstate field should not be separated into chunks. Setting the MaxPageStateFieldLength to a small number may result in poor performance.

The benefit of this feature is that some proxies and firewalls will deny access to the aspx page that contains a huge ViewState size. So by enabling the viewstate chunking mechanism will allow you to bypass this policy.

In Web.Config:
<pages maxPageStateFieldLength="10">

My Favorite Piece of Code

I was asked " what is your favorite piece of code? ".
I checked my old projects, most of the codes/modules are very complex and not easy to code....these can be considered as good and smart codes/applications, but I don't think it's my favorite one.

Then, something came into my mind...wow, now, I got my current favorite piece of code...yeahhh...
I like cartoon, and this one also made me think of creating a game and mobile app....:)

<!DOCTYPE HTML>
<html>
<head>
<style>
canvas {
    position: absolute;
    top: 0;
    left: 0;
 }
</style>
</head>
<body>
    <canvas id="canvasSmile" width="1000" height="400"></canvas>
    <canvas id="canvasRun" width="1000" height="400"></canvas>
    <script>
      var canvas = document.getElementById('canvasSmile');
      var ctx = canvas.getContext('2d');
      var canvasRun= document.getElementById('canvasRun');
      var ctxRun= canvasRun.getContext('2d');    
      var centerX = canvas.width / 2;
      var centerY = canvas.height / 2;
      var face_radius = 70;
      var mouth_radius=40;
      var eye_radius=10;
      var Shine_radius= face_radius *2;
      var variant=  face_radius-mouth_radius;   
      var run_radius= face_radius;
    
  
    //--- DRAW THE FACE CIRCLE---------
      ctx.beginPath();
      ctx.arc(centerX, centerY, face_radius, 0, 2 * Math.PI, false);
      ctx.fillStyle = 'yellow';
      ctx.fill();
      ctx.lineWidth = 1;
      ctx.strokeStyle = '#FF0000';
      ctx.stroke();

    //---DRAW THE MOUTH----------
      ctx.beginPath();
      ctx.arc(centerX, centerY, mouth_radius,1/4, Math.PI-(1/4), false);
      ctx.lineWidth=10;
      ctx.stroke();  
    
    //----DRAW THE LEFT EYE----------
      ctx.beginPath();
      ctx.arc(centerX - variant, centerY - variant, eye_radius, 0, 2* Math.PI, false);
      ctx.fillStyle='red';
      ctx.fill();

    //----DRAW THE RIGHT EYE----------                 
      ctx.beginPath();
      ctx.arc(centerX + variant, centerY - variant, eye_radius, 0, 2* Math.PI, false);
      ctx.fillStyle='red';
      ctx.fill();


    //----DRAW THE LINE AROUND THE CIRCLE---------
      for(var p=0; p<= 2* Math.PI; p+=(2 * Math.PI)/10)
      {
         var x1= centerX + face_radius * Math.cos(p);
         var y1=centerY + face_radius * Math.sin(p);

         var x2= centerX + Shine_radius * Math.cos(p);
         var y2=centerY + Shine_radius * Math.sin(p);
      
     ctx.beginPath();
         ctx.moveTo(x1, y1);
     ctx.lineTo (x2,y2);
         ctx.lineWidth=3;
         ctx.stroke();
       }

        ctx.closePath();
        var func=CircleRun;
        var run=setInterval(func,300);


    //-------RUNNING CIRCLE-------
    function CircleRun()
        {
       run_radius+=10;
           if(run_radius >Shine_radius)
           {
               run_radius=face_radius;
               ctxRun.clearRect(0,0,1000,400);
            }
            ctxRun.beginPath();
            ctxRun.arc(centerX, centerY, run_radius, 0,2 * Math.PI, false);
            ctxRun.lineWidth=1;
            ctxRun.strokeStyle='yellow';
            ctxRun.stroke();
         }     
  
     
    </script>
  </body>
</html>