Monday 31 December 2012

Using MS-SQL's NOLOCK for faster queries

NOLOCK (aka READUNCOMMITED) is a t-sql hint (directive) that allows MS SQL Server to ignore the normal locks that are placed and held for a transaction and allows the query to complete without having to wait for the first transaction to finish and therefore release the locks.

Using NOLOCK gives significant improvement on large tables, where insert / update commands cantake 3-15 seconds.

However you need to be very carefully with using NOLOCK. Remember you can get some records that were partially updated or inserted. It is safe to use NOLOCK on rows that you know are not changing right now.For example, records that belong to some user and he is running reports, but not updates, however some users can do updates / inserts at the same time.

Example:

SELECT * FROM ORDERS (NOLOCK) WHERE orderdate < GETDATE() - 1

Issues

You can get dirty reads using the NOLOCK hint. These are also other terms you may encounter for this hint.

  • Dirty Reads - this occurs when updates are done, so the data you select could be different.
  • Nonrepeatable Reads - this occurs when you need to read the data more than once and the data changes during that process
  • Phantom Reads - occurs where data is inserted or deleted and the transaction is rolled back. So for the insert you will get more records and for the delete you will get less records.

Understanding the SQL Server NOLOCK hint

MSDN >> Concurrency Effects

Mobile Site vs. Full Site

Good mobile user experience requires a different design than what's needed to satisfy desktop users. Two designs, two sites, and cross-linking to make it all work.

  • Build a separate mobile-optimized site (or mobile site ) if you can afford it. When people access sites using mobile devices, their measured usability is much higher for mobile sites than for full sites.
  • If mobile users arrive at your full site's URL, auto-redirect them to your mobile site. Sadly, many search engines still don't rank mobile sites high enough for mobile users, so people are often (mis)guided to full sites instead of the mobile ones, which offer a vastly superior user experience.
  • Offer a clear link from your full site to your mobile site for users who end up at the full site despite the redirect.
  • Offer a clear link from your mobile site to your full site for those (few) users who need special features that are found only on the full site.

The findings and guidelines regarding mobile and full sites are the same on all the currently popular platforms (including iPhone, Android, Windows Phone, and BlackBerry).

The guidelines are different for large tablets (10-inch form factor, as in Apple iPad, Lenovo IdeaPad, Samsung Galaxy, etc.), where full sites work reasonably well. For small tablets (7-inch form factor, as in Amazon Kindle Fire) the ideal would be to create yet a third design optimized for mid-sized devices, though most companies can get away with serving their mobile site to Kindle Fire users.

Mobile-optimized sites

The basic ideas are to:

  • cut features, to eliminate things that are not core to the mobile use case;
  • cut content, to reduce word count and defer secondary information to secondary pages; and
  • enlarge interface elements, to accommodate the "fat finger" problem.

The challenge is to eliminate features and word count without limiting the selection of products. A mobile site should have less information about each product and fewer things users can do with the products, but the range of items should remain the same as on the full site. If users can't find a product on a mobile site, they assume the company doesn't sell it and go elsewhere.

Why full-sites don't work for mobile use

It's common today to hear people argue the following: Mobile users have increasingly high expectations for what they should be able to accomplish on their phones, so eliminating content or features will inevitably disappoint some people. It's therefore better, the (flawed) argument goes, to serve the full site to everybody, including mobile users.

This analysis is flawed because it assumes that the only choice is between the full-featured desktop site and a less-featured mobile site. However, any mobile site that complies with the usability guidelines will provide links to the full site wherever features or content are missing, so users have access to everything when and if they need it.

The design challenge is to place the cut between mobile and full-site features in such a way that the mobile site satisfies almost all the mobile users' needs. If this goal is achieved, the extra interaction cost of following the link to the full site will be incurred fairly rarely.

The correct analysis goes as follows:

  • For the vast majority of tasks , mobile users will get a vastly better user experience from a well-designed mobile site than from the full site.
  • For a small minority of tasks , mobile users will be slightly delayed by the extra click to the full site.

A big gain that's experienced often will comfortably outweigh a small penalty that's suffered rarely.

A second argument against the mobile site option is that you could just optimize the entire website for mobile in the first place. Then, giving mobile users the "full" site wouldn't cause them any trouble. While true, this analysis neglects the penalty imposed on desktop users when you give them a design that's suboptimal for bigger screens and better input devices (see sidebar on mouse vs. fingers). If desktop users were a minute minority this might be acceptable, but almost all websites get substantially more traffic (and even more business) from desktop users than from mobile users. So, while we do want to serve mobile users, we can't neglect desktop users— who, after all, pay most of our salaries.

The basic point? The desktop user interface platform differs from the mobile user interface platform in many ways, including interaction techniques, how people read, context of use, and the plain number of things that can be grasped at a glance. This inequality is symmetric : mobile users need a different design than desktop users. But, just as much, desktop users need a different design than mobile users.

source: http://www.nngroup.com/articles/mobile-site-vs-full-site/

Tuesday 27 November 2012

Why is Request.UrlReferrer null?

I was looking for a consistent way to know the url a user was coming from when loading a page. I thought I will be able to use Request.UrlReferrer. But it proved otherwise when I did some experiments.

The situations where it does work include the following methods of a browser loading a URL:

  • clicking on a straight HTML @lt;a href> link;
  • submitting a form, using POST or GET, from a submit button, or client-side script (form.submit())

The situations where it doesn't work:

  • using Response.Redirect / Server.Transfer;
  • clicking on a Favorite, History, or the recently-typed URLs list;
  • clicking on 'Home' in IE's toolbar, or an item in IE's 'Links' toolbar;
  • using location.href or location.replace() in client-side JScript/JavaScript/VBScript;
  • typing the URL directly in the browser and hitting Enter or clicking 'Go';
  • launching a clickable URL from an e-mail or MS Office document;
  • using Response.AddHeader or <meta http-equiv=refresh> to redirect;
  • loading the URL with XML
More:
http://forums.asp.net/t/1097333.aspx/1
http://www.kruegerwebdesign.com/blog/request-urlreferrer-is-null-what-gives
http://www.codeproject.com/Questions/104895/Is-there-any-alternative-for-UrlReferrer-and-HTTP_

Monday 26 November 2012

Validating User Input to Avoid Attacks

To protect against vulnerabilities such as script injection and cross-site scripting, user input can be verified and rejected, or an application can remove harmful characters and continue processing. This topic provides example code that uses regular expressions to verify user input.

Example code

The following examples shows you how to validate a string using a regular expression. The regular expression, ^[\w\.:\?&=/]*$, searches for a complete string (from beginning to end) that contains only the following characters:

  • alphanumeric or underscore (_)
  • periods (.)
  • colons (:)
  • question marks (?)
  • ampersands (&)
  • equal signs (=)
  • forward slashes (/)

The following example shows you how to use the Visual Basic programming language to include a function that returns a Boolean value indicating if the string that it sent to the function is a valid URL, which might contain a query string.

Public Function ValidateInput(ByVal sInput As String) As Boolean 
    Dim reValid As RegExp 
    Set reValid = New RegExp 

    reValid.Pattern = "^[\w\.:\?&=/]*$" 
    reValid.MultiLine = False 
    reValid.Global = True 

    ValidateInput = reValid.Test(sInput) 
End Function 

Public Function RedirectTo() As Boolean 
    If ValidateInput(myURL) Then 
        Dim objContext As ObjectContext 
        Dim objResponse As Response 
        Set objContext = GetObjectContext() 
        Set objResponse = objContext("Response") 
        objResponse.Redirect (myURL) 
        RedirectTo = True 
    Else 
        RedirectTo = False 
    End If 
End Function 
source: http://msdn.microsoft.com/en-us/library/ms525361%28v=vs.90%29.aspx

ASP ServerVariables Collection

The ServerVariables collection is used to retrieve the server variable values.

The ServerVariables collection retrieves the values of predetermined environment variables and request header information.

Server variables obtain most of their information from headers. It is wise to not trust the data that is contained in headers, as this information can be falsified by malicious users. For example, do not rely on data such as cookies to securely identify a user.

Below table lists name of few server variable and the value it returns

VariableDescription
ALL_HTTPReturns all HTTP headers sent by the client. Always prefixed with HTTP_ and capitalized
CONTENT_TYPEReturns the data type of the content
HTTP_REFERERReturns a string containing the URL of the page that referred the request to the current page using an <a> tag. If the page is redirected, HTTP_REFERER is empty
REMOTE_ADDRReturns the IP address of the remote host making the request
URLReturns the base portion of the URL

 

Click here for a complete list of Server Variables

Request.ServerVariables Collection

Wednesday 7 November 2012

Add Remove option to SELECT list jQuery

Add options to the end of select element

$('#elementid').append('<option value="1">UK</option>');

Add options to the start of select element

$('#elementid').prepend('<option value="0">Before UK</option>');

Add options after selected index

$("#elementid option:eq(0)").after("<option value='4'>US</option>);"

Add options before selected index

$("#elementid option:eq(3)").before("<option value='5'>India</option>")

Replace items at a certain index

$("#elementid option:eq(1)").replaceWith("<option value='2'>China</option>")

Remove option at specified index

$("#elementid option:eq(0)").remove()

Remove first option

$("#elementid option:first").remove()

Remove last option

$("#elementid option:last").remove()

Remove option with a specific value

$("#elementid option:[value='UK']").remove()

http://comp345.awardspace.com/select_element_cheatsheet.pdf

How to avoid CVS - Computer Vision Syndrome?

what exactly is CVS?

Pinching headache, redness in the eyes, dryness, persistent pain in the neck, back and shoulder… these are not signs of aging but a common problem that even children and young adults are facing today. You can blame it on the dependency on electronic gadgets like computers and laptops.

We neglect minor pains thinking it is due to stress, migraine or work pressure but the underlying problem which has grown rapidly in metro cities is Computer Vision Syndrome, a complex of eye or vision problems which are experienced during and related to computer use.

What causes it?

Eyes are the most delicate part of the body. Staring at the brightly-lit computer screen for hours at a stretch is adversely affecting the eyesight of people across the globe. This health condition most commonly occurs when the viewing demand of the task exceeds the visual ability of the video display terminal user. CVS is caused by our eyes and brain reacting differently to characters on the screen than they do to printed characters.

Working at a computer requires focus on the computer screen. In this modern age where everything is getting digital you have to sit for hours in front of the computer screen. Prolonged viewing is the most common cause and it has been proven to be unnatural for the human optical system.

How you can avoid contracting CVS

Blinking is very important when working at a computer -- it rewets your eyes to avoid dryness and irritation. When working on a computer, people blink less frequently. The human eye normally blinks approximately 14 times per minute but when we use computer the blinks are limited only 4 to 6 times per minute. Lower blinking rates cause the eye moisture to evaporate and this is generally referred to as dry eye.

Dry eye causes people to arch their foreheads in an effort to see better, thus causing headaches. The awkward, unnatural postures, leads to sore backs, stiff necks and pain in the shoulder.

Aches and pains are often caused by trying to read the screen through the bottom portion of bifocals, or though half-eye reading glasses. You tip your head up or lean forward to see and this unnatural posture makes you sore.

Computer eyeglasses make the screen look clearer because they eliminate the constant refocusing effort that the eyes go through when viewing the screen. It has also been proven clinically that having the correct prescription in computer eyeglasses increases productivity and accuracy.

If you work in a brightly lit office, you may benefit from a light tint applied to your computer lenses. This can cut the amount of light that reaches your eyes and provide relief in some cases. But tints and filters don't address the underlying cause of computer eyestrain.

Tips to safeguard your eyes

Some important steps that you can take to safeguard your eyes from CVS are:

  • use proper lighting
  • minimize the glaze and brightness of the computer
  • the quality of your monitor display etc.

More than 70 percent of computer users need computer eyeglasses according to a study performed by the University of California, Berkeley, 25 per cent -30 per cent of children would benefit from computer eyewear.

Ergonomics is a vital aspect of safeguarding your eyes from CVS. Changing one's computer workstation can certainly help to minimise other physical symptoms. But ergonomics cannot fix a visual problem. The proper prescription computer eyeglass at the proper computer distance (18" to 28") is the most important. This can be done only with the right computer lens prescription.

Place your monitor directly in front of you, not off to one side (it should be about 20 to 26 inches away from you).

Make sure your monitor is NOT too high. CVS expert Dr James Sheedy recommends that the center of the screen be four to nine inches below your straight-ahead gaze.

If you reposition your chair, keep in mind that your arms should be parallel to the floor when you type, and your feet should be flat on the floor (or a footstool).

Keep contrast and brightness at moderate levels and reduce your screen glare, you should it a point to make blink rapidly.

Blink 10 times by closing your eyes as if falling asleep (very slowly). This will help rewet your eyes. Do this after every 30 minutes and take frequent breaks and exercise your eyes whenever possible.

Source: Rediff.com's article on CVS wrritter by Dr Sri Ganesh, the chairman and managing director of Bangalore's Nethradhama Hospital Pvt Ltd.

Tuesday 30 October 2012

How to check a website is safe?

It can be done here >> http://www.networking4all.com/en/support/tools/site+check/

Check your SSL certificate with www.networking4all.com 's Site Check tool, to see if your site is really safe and secure. Verify whether your SSL certificate is correctly installed and which security options are in use.

The Site Check not only checks the presence of a SSL certificate, but also lists additional information which will give you an overall idea about the quality of the SSL connection. You will get information on the Certificate Authority, the expiry date, the encryption strength, EV support, SGC support and more.

Enter the url of your secured website or any other url like www.networking4all.com, to check how safe the connection to that site really is.

Thursday 25 October 2012

Outlook Express Keyboard Shortcuts

1st key2nd key3rd keyWhat it does
ALTSSend a mail message
CTRLDDelete a mail message
CTRLFForward a message
CTRLMSend and receive mail
CTRLNOpen or post a new message
CTRLRReply to message author
CTRLSHIFTRReply to all
CTRLSHIFTSInsert signature
F4Find text
source: http://www.stevenchalmers.com/Tips/Outlook.shtml

How do I use the hosts file?

Introduction

When using the Internet most people connect to web sites, ftp servers or other Internet servers by connecting to a domain name, as in www.bleepingcomputer.com. Internet applications, though, do not communicate via domain names, but rather using IP addresses, such as 192.168.1.1. Therefore when you type a domain name in your program that you wish to connect to, your application must first convert it to an IP address that it will use to connect to.

The way these hostnames are resolved to their mapped IP address is called Domain Name Resolution. On almost all operating systems whether they be Apple, Linux, Unix, Netware, or Windows the majority of resolutions from domain names to IP addresses are done through a procedure called DNS.

What is DNS

DNS stands for Domain Name System and is the standard domain name resolution service used on the Internet. Whenever a device connects to another device on the Internet it needs to connect to it via the IP address of the remote device. In order to get that IP address, DNS is used to resolve that domain name to its mapped IP address. This is done by the device querying its configured DNS Servers and asking that server what the IP address is for that particular domain name. The DNS server will then query other servers on the Internet that know the correct information for that domain name, and then return to the device the IP address. The device will then open a connection directly to the IP address and perform the desired operation.

If you would like a more detailed explanation of the Domain Name System you can find it here: The Domain Name System

Enter the Hosts File

There is another way to resolve domain names without using the Domain Name System, and that is by using your HOSTS file. Almost every operating system that communicates via TCP/IP, the standard of communication on the Internet, has a file called the HOSTS file. This file allows you to create mappings between domain names and IP addresses.

The HOSTS file is a text file that contains IP addresses separated by at least once space and then a domain name, with each entry on its own line. For example, imaging that we wanted to make it so that if you typed in www.google.com, instead of going to Google we would go to www.yahoo.com. In order to do this you would need to find out one of the IP addresses of Yahoo and map www.google.com to that IP address.

NOTE: When inputting entries in the hosts file there must be at least one space between the IP address and the domain name. You should not use any web notations such as \, /, or http://. You can disable a specific entry by putting a # sign in front of it.

You may be wondering why this would work as we said previously that when you need to resolve a domain name to an IP address the device will use its configured DNS servers. Normally this is true, but on most operating system the default configuration is that any mappings contained in the Hosts file overrides any information that would be retrieved from a DNS server. In fact, if there is a mapping for a domain name in a hosts file, then your computer will not even bother querying the DNS servers that are authoritative for that domain, but instead read the IP address directly from the HOSTS file. It is also important to note that when you add entries to your HOSTS file they automatically start working. There is no need to reboot or enter another command to start using the entries in the HOSTS file.

An example HOSTS file can be found here: HOSTS

Please note that there are ways to change the order that your computer performs Domain Name Resolution. If there are problems with HOSTS file not working you may want to read this article that goes into much greater detail on Domain Name Resolution on various operating systems: Understanding Domain Name Resolution

For reference the HOSTS file is located in the following locations for the listed operating systems:

Operating System Location on Hard Drive
Linux/Unix /etc/hosts
Windows 3.1/95/98/ME c:\windows\hosts
Windows NT/2000/XP Pro c:\winnt\system32\drivers\etc\hosts or c:\windows\system32\drivers\etc\hosts
Windows XP Home c:\windows\system32\drivers\etc\hosts
Netware SYS:ETC/HOSTS
Apple System Folder:Preferences and in the System Folder itself.

In Windows machines you may not already have a hosts file. If this is the case there will most likely be a sample hosts file called hosts.sam that you can rename to hosts and use as you wish. You can edit this file either from the cmd prompt using Edit or Notepad on windows or VI on Unix/Linux. Really any text editor can open and modify the HOSTS file. It is also recommended that if you use this file that you make periodic backups of it by copying it to another name. Some people recommend that you make this file read only so that it will be harder to modify by a malicious program, which there are Hijackers that are known to do this, but there are Hijackers such as CoolWebSearch that add entries to the file regardless of whether or not its read only. Therefore you should not think that having your HOSTS as read only will make it safe from modification.

Why would I want to use a HOSTS file

There are a variety reasons as to why you would want to use a HOSTS file and we will discuss a few examples of them so you can see the versatility of the little file called the HOSTS file.

Network Testing

- I manage a large Internet Data center and many times we need to set up test machines or set up development servers for our customers applications. When connecting to these development or test machines, you can use the HOSTS file to test these machines as if they were the real thing and not a development server. As an example, lets say that you had a domain name for a development computer called development.mydomain.com. When testing this server you want to make sure it operates correctly if people reference it as the true web server domain name, www.mydomain.com. Since if you change www.mydomain.com in the DNS Server to point to the development server everyone on the Internet would connect to that server, instead of the real production server. This is where the HOSTS file comes in. You just need to add an entry into your HOSTS file that maps www.mydomain.com to the IP address of the development server on the computers that you will be testing with, so that the change is local to the testing machines and not the entire Internet. Now when you connect to www.mydomain.com from your computer with the modified HOSTS file you are really connecting to the development machine, but it appears to the applications that you are using that you are connecting to www.mydomain.com.

Potentially Increase Browsing Speed

- By adding IP address mappings to sites you use a lot into your HOSTS file you can potentially increase the speed of your browsing. This is because your computer no longer has to ask a DNS server for the IP address and wait to receive it's response, but instead can quickly query a local file. Keep in mind that this method is not advised as there is no guarantee that the IP address you have for that domain name will always stay the same. Therefore if the web site owner decides to change their IP address you will no longer be able to connect.

Block Spyware/Ad Networks

- This reason is becoming a very popular reason to use the HOSTS file. By adding large lists of known ad network and Spyware sites into your hosts file and mapping the domain names to the 127.0.0.1, which is an IP address that always points back to your own machine, you will block these sites from being able to be reached. This has two benefits; one being that it can make your browsing speed up as you no longer have to wait while you download ads from ad network sites and because your browsing will be more secure as you will not be able to reach known malicious sites.

NOTE: It is important to note that there have been complaints of system slowdowns when using a large hosts file. This is usually fixed by turning off and disabling the DNS Client in your Services control panel under Administrative Tools. The DNS client caches previous DNS requests in memory to supposedly speed this process up, but it also reads the entire HOSTS file into that cache as well which can cause a slowdown. This service is unnecessary and can be disabled.

There are HOSTs file that are already made that you can download which contain a large list of known ads servers, banner sites, sites that give tracking cookies, contain web bugs, or infect you with hijackers. Listed below are web sites that produce these types of hosts files:

hpguru's HOSTS File can be found here: http://www.hosts-file.net/ The MVPS Host File can be found at: http://www.mvps.org. Hosts File Project can be found here : http://remember.mine.nu/

If you choose to download these files, please backup your original by renaming it to hosts.orig and saving the downloaded HOSTS file in its place. Using a HOSTS file such as these is highly recommended to protect your computer.

Utilities for your HOSTS file

If you do not plan on modifying your HOSTS file much and plan on using it occasionally for testing purposes, then the basic text editors like VI, Notepad, and Edit are more than adequate for managing your HOSTS file. If on the other hand you plan on using the HOSTS file extensively to block ads/spyware or for other reasons, then there are two tools that may be of use to you.

eDexter - When you block ads on web sites using a HOSTS file, there tends to be empty boxes on the web site you are visiting where the ad would normally have appeared. If this bothers you, you can use the program eDexter to fill in the image with one on your local machine such as a clear image or any other one for that matter. This removes the empty boxes and is quick because the replacement image is loaded off of your hard drive.

Hostess - Hostess is an application that is used to maintain and organize your HOSTS file. This program will read your HOSTS file and organize the entries contained in it into a database. You can then use this database to scan for duplicates and to manage the entries. It is a program that is definitely worth checking out if you plan on using the HOSTS file extensively.

Conclusion

As you can see the HOSTS file is a powerful tool if you understand how to use it. You should now know how to use the HOSTS file to manipulate Domain Name Resolution to suit your needs. It is also important that you use its ability to block malicious programs as discussed above to make your computing environment more secure.

Source: http://www.bleepingcomputer.com/tutorials/hosts-files-explained/

Tuesday 16 October 2012

Stop or disable resizing textarea FireFox

FireFox has a feature which allows to resize multi-line textboxes (textareas). This is done by clicking and dragging at the bottom right corner of the textarea. It is a nice feature but in some cases we may have to restrict or stop the user from doing it. If so it can be achieved using below CSS.

textarea {resize:none}

Wednesday 25 July 2012

Remove specific element from a javascript array

JavaScript Array has a splice() method which can be used to remove an element or set of elements starting from a given index. First, find the index of the element you want to remove:

var array = [2, 5, 9];
var index = array.indexOf(2);
Then remove it with splice:

array.splice(index,1);

How to break out of jQuery.each()?

JavaScript break statement doesn't work with jQuery.each(). But the same functionality can be achieved by adding a "return false" statement within jQuery.each() once the breaking condition is reached.

$(‘ul li’).each(function(index){
  if ( $(this).hasClass(‘selected’) )
  {
    selected = index;
    return false; 
  } 
});

Html.Partial vs Html.RenderPartial

Html.Partial returns a string, Html.RenderPartial calls Write internally, and returns void. The usage (using Razor syntax):

@Html.Partial("ViewName")

@{ Html.RenderPartial("ViewName");  }
The usage (using WebForms syntax):

<%: Html.Partial("ViewName") %>

<% Html.RenderPartial("ViewName"); %>
Will do exactly the same. You can store the output of Html.Partial in a variable, or return it from a function. You cannot do this with Html.RenderPartial. The result will be written to the Response stream during the execution. The same is true for Html.Action and Html.RenderAction.

Asp.Net MVC partial view controller action

While you can have an action that returns a partial view, you don't need an action to render a partial view. RenderPartial takes the partial view and renders it, using the given model and view data if supplied, into the current (parent) view.
Html.RenderPartial( "Partial");
You might want an action that returns a partial view if you are using AJAX to load/reload part of a page. In that case, returning the full view is not desired since you only want to reload part of the page. In this case you can have the action just return the partial view that corresponds to that section of the page.

public ActionResult Action(...)
{ 
    return PartialView( "Partial");
}

How slow is jQuery "slow"?

jQuery animation methods like fadeIn() allows you to specify whether you want to do the animation 'slow' or 'fast'. In fact durations are given in milliseconds; higher values indicate slower animations, not faster ones. The strings 'fast' and 'slow' can be supplied to indicate durations of 200 and 600 milliseconds, respectively. If any other string is supplied, or if the duration parameter is omitted, the default duration of 400 milliseconds is used.

How to detect IE7 with jQuery?

jQuery has a property called "$.browser.msie" which returns true when the browser is Internet Explorer. It can be combined with "$.browser.version" to decide what version of IE it is.


if ($.browser.msie  && parseInt($.browser.version, 10) === 7) {
  alert('IE7'); 
} else {
  alert('Non IE7');
}


Friday 20 July 2012

How to find event target using jQuery?

This can be done using event.target property. It returns a reference to the DOM element that initiated the event. t is often useful to compare event.target to this in order to determine if the event is being handled due to event bubbling. This property is very useful in event delegation, when events bubble.

Example: Implements a simple event delegation: The click handler is added to an unordered list, and the children of its li children are hidden. Clicking one of the li children toggles (see toggle()) their children.


<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  
<ul>
  <li>item 1
    <ul>
      <li>sub item 1-a</li>
      <li>sub item 1-b</li>
    </ul>
  </li>
  <li>item 2
    <ul>
      <li>sub item 2-a</li>
      <li>sub item 2-b</li>
    </ul>
  </li>  
</ul>

<script>

function handler(event) {

var $target = $(event.target);

  if( $target.is("li") ) {
    $target.children().toggle();
  }
}

$("ul").click(handler).find("ul").hide();

</script>

</body>
</html>


Friday 13 July 2012

Deserializing ASP.NET AJAX JSON date using JavaScript

Modern websites are using AJAX a lot to improve customer experience by redudcing/avoiding full page reload in response to a user interaction. When AJAX is used with ASP.NET DateTime values are deserialized into below format.

"\/Date(1342137600000)\/"

Following JavaScript function can be used to deserialize it into a JavaScript Date object.

function GetDateFromJSONString(s) {
                    var d = s.replace(/\/Date\(/gi, '');
                    d = d.replace(/\)\//gi, '');
                    return  new Date(Number(d));
}

var s = "\/Date(1342137600000)\/";

alert(GetDateFromJSONString(s));

The issue with this is that JavaScript will apply the locale timezone of the client's machine while doing the deserialization which may result in a different Date value. This can be avoided by doing the deserialization bit differrently using JavaScript's toUTCString() method. This function will deserialize it into UTC Date.

var monthNames = { JAN: 0, FEB: 1, MAR: 2, APR: 3, MAY: 4, 
JUN: 5, JUL: 6, AUG: 7, SEP: 8, OCT: 9, NOV: 10, DEC: 11 }

function GetUTCDateFromJSONString(s) {
         var d = s.replace(/\/Date\(/gi, '');
         d = d.replace(/\)\//gi, '');
         var utc = new Date(Number(d)).toUTCString(); 
         //Sample value: Mon, 1 Feb 1982 00:00:00 UTC
         utc = utc.split(',')[1].substring(1).split(' ');
         utc[0] = utc[3] != '00:00:00' ? Number(utc[0]) + 1 : utc[0]; 
         return new Date(utc[2], monthNames[utc[1].toUpperCase()], utc[0]);  
}

var s = "\/Date(1342137600000)\/";

alert(GetUTCDateFromJSONString(s));



You can read more about toUTCString() method on w3schools.com. Click Here

Thursday 12 July 2012

How to center DIV in a DIV?

This can be achieved by applying below CSS to the inner div:
#outer {
  width: 100%;
}

#inner {
    width: 50%;
    margin: 0px auto;
}
Of course, you don't have to set the width to 50%. Any width less than the containing div will work. The margin: 0px auto is what does the actual centering. It can be done in a different way as well.
#outer {
  width: 100%;
  text-align: center;
}

#inner {
  display: inline-block;
}
That makes the inner div into an inline element that can be centered with text-align.

Tuesday 10 July 2012

ASP.NET MVC 3 and the @helper syntax within Razor

The @helper syntax within Razor enables you to easily create re-usable helper methods that can encapsulate output functionality within your view templates. They enable better code reuse, and can also facilitate more readable code.

Key points:

  • Just like a standard C#/VB method, it can contain any number of arguments (you can also define the arguments to be either nullable or optional). Unlike standard C#/VB methods @helper methods can contain both content and code, and support the full Razor syntax within them – which makes it really easy to define and encapsulate rendering/formatting helper methods.

  • You can invoke @helper methods just like you would a standard C# or VB method.

  • @helper method can be defined within the same view template as the code that called it. Alternatively, we can define the @helper method outside of our view template, and enable it to be re-used across all of the view templates in our project. We can accomplish this by saving our @helper methods within .cshtml/.vbhtml files that are placed within a \App_Code directory that you create at the root of a project.

@helper DisplayPrice(Decimal price)
{
      if(price == 0)
      {
         <span>FREE</span>
      }
      else
      {
         <text> <b>Price:<b> &pound;@(price) </text>
      }
}
Click here for more information about the @helper syntax

Import a namespace in Razor View Page?

If you want to import a namespace in your CSHTML file it can be done using @using (C#) or @imports (VB.NET) statement.

C# Example

@using System.Configuration;

Tuesday 19 June 2012

Classic vs. Integrated mode in IIS 7

IIS 6.0 and previous versions allowed the development of .NET application components via the ASP.NET platform. ASP.NET integrated with IIS via an ISAPI extension, and exposed its own application and request processing model. This effectively exposed two separate server pipelines, one for native ISAPI filters and extension components, and another for managed application components. ASP.NET components would execute entirely inside the ASP.NET ISAPI extension bubble and only for requests mapped to ASP.NET in the IIS script map configuration.

IIS 7.0 integrates the ASP.NET runtime with the core web server, providing a unified request processing pipeline that is exposed to both native and managed components known as modules.

The many benefits of integration include:
  • Allowing services provided by both native and managed modules to apply to all requests, regardless of handler. For example, managed Forms Authentication can be used for all content, including ASP pages, CGIs, and static files.
  • Empowering ASP.NET components to provide functionality that was previously unavailable to them due to their placement in the server pipeline. For example, a managed module providing request rewriting functionality can rewrite the request prior to any server processing, including authentication.
  • A single place to implement, configure, monitor and support server features such as single module and handler mapping configuration, single custom errors configuration, single url authorization configuration.
Follow this link to read more on this

Classic mode is where IIS only works with ISAPI extensions and ISAPI filters directly. This is how IIS 6 and below behaved. Using classic mode, ASP.NET is simply an ISAPI extension (aspnet_isapi.dll) and an ISAPI filter (aspnet_filter.dll). When using classic mode the server uses two piplines to handle requests, one for native code and the other for managed code. In this mode the application doesn't take full advantage of everything IIS 7.X has to offer.

Integrated mode handles all requests through a unified pipeline for IIS and is tightly integrated with ASP.NET through that same pipeline. ASP.NET sees every relevant request and manipulates things along the way rather than acting as an external plugin. With integrated mode ASP.NET runs much more efficiently in IIS and will yield greater performance for your site.

Thursday 14 June 2012

ASP.NET MVC - Domain specific routes using RouteConstraint

I’ve come across using different routes depending upon the domain that the end user is browsing. That might be different based on language (browsing your “.co.uk” site gets English URLs, browsing “.fr” gets French), or perhaps based on brand. Maybe some functionality on your web site is only available to certain sub-brands. Or perhaps you want to direct users that visit uat.mydomain.com to new functionality so they can test it. All of this becomes possible with a Route Constraint. These are simply used to validate whether a route should match a particular incoming URL.

HostConstraint

To apply this kind of filtering based on the host in the URL (i.e. the domain the user is browsing) is such a simple piece of code;
public class HostConstraint : IRouteConstraint
{
    private readonly Regex _host;
 
    public HostConstraint(string pattern)
    {
        _host = new Regex(pattern, 
                RegexOptions.Compiled | RegexOptions.IgnoreCase);
    }
 
    public bool Match(
        HttpContextBase httpContext, 
        Route route, 
        string parameterName, 
        RouteValueDictionary values, 
        RouteDirection routeDirection)
    {
        return _host.IsMatch(httpContext.Request.Url.Host);
    }
}
You can see this constraint takes a Regular Expression pattern to describe host names that it should match, and simply checks the Url.Host on the current HttpContext for success.

Using HostConstraint

Using our new class is really simple - we add it to an anonymous type in the MapRoute call;
routes.MapRoute(
    "Default_us",
    "ussitemap",
    new { controller = "Home", action = "SiteMap" },
    new { host = new HostConstraint("\\.com$") }
);
 
routes.MapRoute(
    "Default_fr",
    "frenchsitemap",
    new { controller = "Home", action = "SiteMap" },
    new { host = new HostConstraint("\\.fr$") }
);

Tuesday 15 May 2012

Make entire Div clickable using jQuery

$(".myBox").click(function(){
    window.location=$(this).find("a").attr("href");
    return false;
});



Looks for a link inside div with class of "myBox". Redirects to that links value when anywhere in div is clicked.
Reference HTML:


<div class="myBox">
blah blah blah.
<a href="http://google.com">link</a>
</div>

Friday 20 January 2012

IIS URL Rewrite Module Configuration Reference

What is URL Rewrite Module


The URL Rewrite Module rewrites request URLs to simple, user-friendly, and search-engine friendly addresses that are displayed to users or in Web applications. URL Rewrite uses defined rules to evaluate and then map the request URL to the address defined in the rule before it is processed by an IIS Web server. You can define URL rewriting logic that includes regular expressions and wildcards, and rules can be applied based on the request URL, HTTP headers, and server variables. While the primary purpose of the module is to rewrite request URLs to more friendly URLs, you can also use the module to define rules that perform redirects, send custom responses, or abort requests.

URL Rewrite Module Overview



A rewrite rule defines the logic of what to compare or match the request URL with, and what to do if the comparison is successful.

Rewrite rules consists of the following parts:


  • Pattern – The rule pattern is used to specify either the regular expression or a wildcard pattern that is used to match URL strings.

  • Conditions – The optional conditions collection is used to specify additional logical operations to perform if a URL string matches the rule pattern. Within the conditions, you can check for certain values of HTTP headers or server variables, or verify if the requested URL corresponds to a file or directory on a physical file system.

  • Action – The action is used to specify what to do if the URL string matches the rule pattern and all the rule conditions are met.



Click here to read the full reference from learn.iis.net.

Using server variables in rewrite rules



Server variables provide additional information about current HTTP requests. You can sue this information to make rewriting decisions or to compose the rewritten URL.

Using back-references in rewrite rules



Parts of rules or conditions inputs can be captures in back-references. These can be then used to construct substitution URLs within rules actions or to construct input strings for rule conditions.

Back-references are generated in different ways, depending on which kind of pattern syntax is used for the rule. When an ECMAScript pattern syntax is used, a back-reference can be created by putting parenthesis around the part of the pattern that must capture the back-reference. For example, the pattern ([0-9]+)/([a-z]+)\.html will capture 07 and article in back-references from this requested URL: 07/article.html.

Using String functions in rewrite rules



There are three string functions available for changing the values within a rewrite rule action, as well as any conditions:

ToLower - returns the input string converted to lower case.
UrlEncode - returns the input string converted to URL-encoded format. This function can be used if the substitution URL in rewrite rule contains special characters (for example non-ASCII or URI-unsafe characters).
UrlDecode - decodes the URL-encoded input string. This function can be used to decode a condition input before matching it against a pattern.

The functions can be invoked by using the following syntax:
{function_name:any_string}

Where "function_name" can be on eof the following: "ToLower", "UrlEncode", "UrlDecode". "Any_string" can be either a literal string or a string built by using server variables or back-references. For example, the following are valid invocations of string functions:
{ToLower:DEFAULT.HTM}
{UrlDecode:{REQUEST_URI}}
{UrlEncode:{R:1}.aspx?p=[résumé]}

Rewrite maps



A rewrite map is an arbitrary collection of name-value pairs that can be used within rewrite rules to generate the substitution URL during rewriting. Rewrite maps are particularly useful when you have a large set of rewrite rules and all of these rules use static strings (that is, when there is no pattern matching used).

Click here to read the full reference from learn.iis.net.

Is HTML case sensitive?

HTML tags are not case sensitive: <P> means the same as <p>. Many web sites use uppercase HTML tags.

World Wide Web Consortium (W3C) recommends lowercase in HTML 4, and demands lowercase tags in XHTML.

Source

Monday 9 January 2012

Basics of anonymous Methods in C# 2.0

Anonymous method is a new language feature in C# 2.0.

Anonymous methods allow us to define a code block where a delegate object is acceptable. This facility saves us an extra step of creating a delegate for small code blocks that we want to pass to a delegate. It also removes the cluttering of small methods in the class code.

For example, that let us say we have a string collection class named MyCollection. This class has a method that retrieves all the items in the collection that satisfies a user supplied criteria, i.e., the caller decides whether a particular item in the collection qualifies for being retrieved as part of the return array from this method.


public class MyCollection
{
public delegate bool SelectItem(string sItem);

public string[] GetFilteredItemArray(SelectItem itemFilter)
{
List sList = new List();
foreach(string sItem in m_sList)
{
if (itemFilter(sItem) == true) sList.Add(sItem);
}
return sList.ToArray();
}

public List ItemList
{
get
{
return m_sList;
}
}

private List m_sList = new List();
}


We can write code as shown below to use the above defined class:


protected void Page_Load(object sender, EventArgs e)
{
MyCollection objMyCol = new MyCollection();
objMyCol.ItemList.Add("Aditya");
objMyCol.ItemList.Add("Tanu");
objMyCol.ItemList.Add("Manoj");
objMyCol.ItemList.Add("Ahan");
objMyCol.ItemList.Add("Hasi");

// get an array of string items in the collection that start

// with letter 'A'

//

string[] AStrings = objMyCol.GetFilteredItemArray(FilterStringWithA);
Console.WriteLine("----- Strings starting with letter 'A' -----");
foreach (string s in AStrings)
{
Console.WriteLine(s);
}

// get an array of string items in the collection that start

// with letter 'T'

//

string[] TStrings = objMyCol.GetFilteredItemArray(FilterStringWithT);
Console.WriteLine("----- Strings starting with letter 'T' -----");
foreach (string s in TStrings)
{
Console.WriteLine(s);
}
}

public static bool FilterStringWithA(string sItem)
{
if (sItem[0] == 'A')
return true;
else
return false;
}

public static bool FilterStringWithT(string sItem)
{
if (sItem[0] == 'T')
return true;
else
return false;
}


Here the problem is for each simple criteria we want to provide, we should define a method (static or instance). This soon clutters the class code. With anonymous methods, the code becomes much natural. Below is the re-written code using anonymous methods.


protected void Page_Load(object sender, EventArgs e)
{
MyCollection objMyCol = new MyCollection();
objMyCol.ItemList.Add("Apple");
objMyCol.ItemList.Add("Grape");
objMyCol.ItemList.Add("Orange");
objMyCol.ItemList.Add("Blackberry");
objMyCol.ItemList.Add("Blueberry");

// get an array of string items in the collection that start

// with letter 'A'

//

string[] AStrings = objMyCol.GetFilteredItemArray(delegate(string sItem)
{
if (sItem[0] == 'A')
return true;
else
return false;
});
System.Diagnostics.Debug.WriteLine("----- Strings starting with letter 'A' -----");
foreach (string s in AStrings)
{
System.Diagnostics.Debug.WriteLine(s);
}

// get an array of string items in the collection that start

// with letter 'T'

//

string[] TStrings = objMyCol.GetFilteredItemArray(delegate(string sItem)
{
if (sItem[0] == 'B')
return true;
else
return false;
});
Console.WriteLine("----- Strings starting with letter 'B' -----");
foreach (string s in TStrings)
{
System.Diagnostics.Debug.WriteLine(s);
}
}


As shown in the above sample, we were able to define the criteria with in-line code blocks instead of defining a new method to represent each criteria. Truly speaking, using such inline code may look natural and avoid defining new methods, but if this technique is used for larger inline code blocks, then the code soon becomes unmanageable and may lead to duplications. So, be selective in using methods vs. inline anonymous methods as delegates/event handlers.

Now, this is the basics of anonymous methods. The rest of the article deals with how anonymous methods work internally in different scenarios. Understanding how anonymous methods are implemented and work internally is important for their correct usage. Else, the results of your code using anonymous methods will look unpredictable.

Anonymous methods always start with a delegate keyword, followed by parameters to be used inside the method and the method body itself. As seen from the above code sample, users need not specify the return type of the anonymous method. It is inferred from the return statement within the method body. The .NET CLR cannot execute free flowing code blocks like anonymous methods. CLR requires that every method it executes is part of a type and should be a static method or instance method. So when you write anonymous methods in a class code and compile the code, the C# compiler silently creates a static or instance method within the same class where you defined the anonymous method. So anonymous methods are just a convenient syntax for defining your own methods inside the class to pass to delegates (delegate handlers/event handlers).

When you compile the above sample, the C# compiler creates two private static methods inside the class, where we defined the anonymous methods. It then replaces the anonymous methods with the address of those static methods. How the compiler decides to create static methods or instance methods depends on the usage of the static or instance data members of the class within which the anonymous methods are defined.

Click here to read more about the internal of anonymous methods.

Where does Console.WriteLine go in ASP.NET?

If you wonder where you can see the output from a Console.WriteLine() statement in an ASPX page here is the answer - you can't see it anywhere, because it is not outputted anywhere.

The reaseon is:

if you look at the Console class in Reflector, you'll find that if a process doesn't have an associated console, Console.Out and Console.Error are backed by Stream.Null (wrapped inside a TextWriter), which is a dummy implementation of Stream that basically ignores all input, and gives no output.

The alternative to Console.WriteLine is System.Diagnostics.Debug.WriteLine()



If you use System.Diagnostics.Debug.WriteLine() instead of Console.WriteLine(), then you can see the results in the Output window of Visual Studio.

Friday 6 January 2012

ASP.NET IsDebuggingEnabled Property

HttpContext.Current.IsDebuggingEnabled:

- It is a property of HttpContext object that identifies whether debug property of <compilation> element in web.config file is set to true or not.

How to remove a property from a JavaScript object

JavaScript's 'delete' operator can be used for this.

The delete operator deletes a property of an object. It is part of JavaScript 1.2.

Syntax



delete expression

where expression should evaluate to a property reference, e.g.:

delete variableName

delete objectExpression.property

delete objectExpression["property"]

delete objectExpression[index]

Parameters



objectName
The name of an object.

property
The property to delete.

index
An integer representing the array index to delete.

Returns



Returns false only if the property exists and cannot be deleted. It returns true in all other cases.

Example




var myJSONObject = {};
myJSONObject.id = 101;

delete myJSONObject.id;
//OR
delete myJSONObject['id'];