How to use the Visibility API

Browser tabs have revolutionized the way we browse the Web, but they’ve given us an tricky problem: developers can’t tell if the tab their site is displayed in is being viewed.To solve that problem we have the Visibility API, which allows us to test whether the browser content can be seen, and respond accordingly. It’s ideal for sites that play music for example, to pause the playback whilst the user is away. The Page Visibility API comes with several properties:

  • document.hidden: This property returns true if our page is hidden from the user. If it’s minimized or in a different tab.
  • document.visibilityChange: This will trigger every time there is a change in the visibility of your page.
  • document.visibilityState: This will tell you if your website is visible, hidden or in pre-render state.

These simple properties go a long way to allowing us to detect how a user is interacting with our site. Browser support for this feature is good. All modern browsers support it, and you only really need the -webkit-prefix for Android and Blackberry browsers. Let’s take a look at the code we need:

var hidden, state, visibilityChange; 
if (typeof document.hidden !== "undefined") {
    hidden = "hidden";
    visibilityChange = "visibilitychange";
    state = "visibilityState";
} else if (typeof document.webkitHidden !== "undefined") {
    hidden = "webkitHidden";
    visibilityChange = "webkitvisibilitychange";
    state = "webkitVisibilityState";

As you can see, we test whether document.hidden is undefined and then assign variables based on the result. (This technique was first implemented by Sam Dutton back when there were a lot of prefixes to concern ourselves with. Next, we need to listen for changes in the visibility state, which we do with a listener:

document.addEventListener(visibilityChange, function() {
 // Code to manipulate the document    
}, false);

Now we’re listening for a change and running a function each time it occurs. We can do anything we like inside that function; for the purposes of demonstration we’ll change the message on the page:

document.addEventListener(visibilityChange, function() {
    if(document.visibilityState == hidden) {
        document.title = ' Where are you going?';
    } else {
        document.title = 'Oh good you are back.';
}, false);

This code doesn’t affect the page when it first loads, only if the user changes the visibility of the page. If you want to set a different message as soon as the page loads you’d use something like:

document.title = 'Default Title';

Just by adding this the page will use this as default and then change the title according to the visibility state.

Awesome trick to validate Email Address in C# .Net (without Regular Expression)



Recently I came across this fine, precise, code by Rion Williams, to check and validate an Email Address.
The code uses System.Net.Mail Namespace to check email address and returns True/False.

Very Effective and Easy!

Source Link

bool IsValidEmail(string email)
    try {
        var addr = new System.Net.Mail.MailAddress(email);
        return true;
    catch {
        return false;

Please feel free to share your thoughts, Or similar code you’ve encountered recently in Comment section.

SQL Injection

When SQL is used to display data on a web page, it is common to let web users input their own search values.

Since SQL statements are text only, it is easy, with a little piece of computer code, to dynamically change SQL statements to provide the user with selected data:

txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId;

Let’s say that the original purpose of the code was to create an SQL statement to select a user with a given user id.

If there is nothing to prevent a user from entering “wrong” input, the user can enter some “smart” input like this:

105 or 1=1

SELECT * FROM Users WHERE UserId = 105 or 1=1

The SQL above is valid. It will return all rows from the table Users, since WHERE 1=1 is always true.

Does the example above seem dangerous? What if the Users table contains names and passwords?

The SQL statement above is much the same as this:

SELECT UserId, Name, Password FROM Users WHERE UserId = 105 or 1=1

A smart hacker might get access to all the user names and passwords in a database by simply inserting 105 or 1=1 into the input box.


SQL injection errors occur when:

  1. Data enters a program from an untrusted source.
  2. The data used to dynamically construct a SQL query.

For More:

What is ‘Content Delivery Network’ (CDN)?

A Content Delivery Network (CDN) works by providing alternative server nodes for users to download resources (usually static content like images and JavaScript).
A CDN is essentially a network of geographically dispersed servers. Each CDN node (also called Edge Servers) caches the static content of a site like the images, CSS/JS files and other structural components. The majority of an end-user’s page load time is spent on retrieving this content, and so it makes sense to provide these “building blocks” of a site in as many server nodes as possible, distributed throughout the world.

When a user requests your site, the node closest in proximity to user will deliver the static content, ensuring the shortest distance for the data to travel (reduced latency), therefore providing the fastest site experience.

Why do I need a CDN?

The number one reason for using a CDN is to improve your user’s experience in terms of speed, and as we know – >>speed>> matters!

Ensuring a consistent experience for all your users is important.
A website may be hosted in a particular region, but have the majority of its users coming from an entirely different region – for example, if your site is hosted in North America, sites that measures website speed might report fast speeds based on our default test location, but if a good chunk of your users come from Europe, their speed will not be as fast as you experience it to be.
A global CDN would allow users from a European point of origin to download static content from a closer source. Instead of spanning the Atlantic ocean to retrieve data, they can connect to a server in say, London, UK, to get the same data. This reduces latency and provides a faster loading of your website.

CDNs not only ensure a faster experience to your users, but they also help to prevent site crashes in the event of traffic surges – CDNs help to distribute bandwidth across multiple servers, instead of allowing one server to handle all traffic.

…But CDNs Aren’t Absolutely Necessary.

A CDN is a “next-level” optimization. It is not a self-contained fix like a server configuration change or a small code modification. CDNs are paid, third-party services, and so implementation of one depends on your goals, priorities and budget.

Will a CDN help improve the performance of your website? Yes. Is it absolutely required for all websites? No. You can still provide a decently fast website experience without a CDN – but it would probably be faster with one.

For those with heavy traffic, mission critical websites and that are serious about providing the best possible experience for all their users, a CDN should be a crucial part of their optimization strategy.

CSS selector for all the textboxes

Usual way of applying styles for all the textboxes is like below

input[type=”text”] {
/*CSS here*/

Problem with the above is, it will not include the textboxes which get renders when you simply put a <input> tag. Note that when you do not specify the type attribute in input elements, it will render as the default input element, textbox. The above CSS selector won’t work in such cases. In such cases, you can use the below

input:not([type]), input[type=”text”]
/*CSS here*/

It will select all the input control without a type attribute as well as which are marked as type=”text”

Validation in MVC

Range Validation in MVC

The Range attribute specifies minimum and maximum constraints for a numerical value. If the Music Store only wanted to serve middle-aged customers, you could add an Age property to the Order class and use the Range attribute as in the following code:

public int Age { get; set; }

 The first parameter to the attribute is the minimum value, and the second parameter is the maximum value. The values are inclusive. The Range attribute can work with integers and doubles, and another overloaded version of the constructor will take a Type parameter and two strings (which can allow you to add a range to date and decimal properties, for example).

[Range(typeof(decimal), "0.00", "49.99")]
public decimal Price { get; set; }

RegularExpression Validation in MVC

Some properties of Order require more than a simple presence or length check. For example, you’d like to ensure the Email property of an Order contains a valid, working e-mail address. Unfortunately, it’s practically impossible to ensure an e-mail address is working without sending a mail message and waiting for a response. What you can do instead is ensure the value looks like a working e-mail address using a regular expression:

public string Email { get; set; }

Regular expressions are an effi cient and terse means to enforce the shape and contents of a string value. If the customer gives you an e-mail address and the regular expression doesn’t think the string looks like an e-mail address, the customer will see the error in Figure.

StringLength Validation in MVC

You’ve forced the customer to enter his name, but what happens if he enters a name of enormous length? Wikipedia says the longest name ever used belonged to a German typesetter who lived in Philadelphia. His full name is more than 500 characters long. Although the .NET string type can store (in theory) gigabytes of Unicode characters, the MVC Music Store database schema sets the maximum length for a name at 160 characters. If you try to insert a larger name into the database, you’ll have an exception on your hands. The StringLength attribute can ensure the string value provided by the customer will fit in the database:

public string FirstName { get; set; }
public string LastName { get; set; }

Notice how you can stack multiple validation attributes on a single property. With the attribute in place, if a customer enters too many characters, he’ll see the default error message shown below the LastName field in Figure.


MinimumLength is an optional, named parameter you can use to specify the minimum length for a string. The following code requires the FirstName property to contain a string with three or more characters (and less than or equal to 160 characters) to pass validation:

[StringLength(160, MinimumLength=3)]
public string FirstName { get; set; }

Required Validation in MVC

Because you need the customer to give you his fi rst and last name, you can decorate the FirstName and LastName properties of the Order model with the Required attribute:

public string FirstName { get; set; }
public string LastName { get; set; }
[Required(ErrorMessage = "Nick name is required")]
public string NickName { get; set; }

 The attribute raises a validation error if either property value is null or empty.

Like all the built-in validation attributes, the Required attribute delivers both server-side and client side validation logic (although internally, it is another, different component in the MVC framework that delivers the client-side validation logic for the attribute through a validation adapter design).

With the attribute in place, if the customer tries to submit the form without providing a last name, he’ll see the default error in Figure.


However, even if the customer does not have JavaScript enabled in his browser, the validation logic will catch an empty name property on the server, too.

Send Email using Link Tag!

Having a link that allows visitors to send email from your website can be a great addition to your site, making it easy for your visitors to send questions or comments.

There is a special link for this action.

Email links are done much the same as links to other pages, using the
<a href> tag.

An email link would require the following code:

<a href=”mailto:RecipientEmailAddress”>Email Me</a>

This will result in the visitor’s email program opening a new email with Email address already in the To: field using Exchange Server (Outlook).

If you wish to have a specific subject in the email, you can add it to the html code using subject= setting [similar adding data in url(QueryString)]:

<a href=” %20Using %20Html %20Link”>
Send Email</a>

// %20 is HTML encode for a Blank space

Suppose you want an email link for your visitors containing specific text in the body of their message, simply add &body=:

<a href=” subject=Sending %20Using %20Html %20Link&body=Please send me a copy of your new initiative!”>Send Email</a>


According to RFC 2368:

The special hname “body” indicates that the associated hvalue is the body of the message. The “body” hname should contain the content for the first text/plain body part of the message. The mailto URL is primarily intended for generation of short text messages that are actually the content of automatic processing (such as “subscribe” messages for mailing lists), not general MIME bodies.

In short, trying stuff like embedding an image using <img /> tag or using HTML bold tag as following, inside body setting,  simply won’t work!



Difference between .parent() and .closest in jQuery

I have been using jQuery for a while. I wanted to use the parent() selector. I also came up with the closest() selector. I was intrigued to find difference between them.

The .parents() and .closest() methods are similar in that they both traverse up the DOM tree. The differences between the two, though subtle, are significant:


  • Begins with the current element
  • Travels up the DOM tree until it finds a match for the supplied selector
  • The returned jQuery object contains zero or one element


  • Begins with the parent element
  • Travels up the DOM tree to the document’s root element, adding each ancestor element to a temporary collection; it then filters that collection based on a selector if one is supplied
  • The returned jQuery object contains zero, one, or multiple elements


  • Given a jQuery object that represents a set of DOM elements, the .parent() method allows us to search through the parents of these elements in the DOM tree and construct a new jQuery object from the matching elements.

Note: The .parents() and .parent() methods are similar, except that the latter only travels a single level up the DOM tree. Also, $(“html”).parent() method returns a set containing document whereas $(“html”).parents() returns an empty set.

Compress Javascript/CSS to keep web pages lightweight, and improve its performance

Improving the design of a page or a web application usually yields the biggest savings and that should always be a primary strategy. There are many secondary strategies for improving performance such as minification of the code, HTTP compression, using CSS sprites, etc.

The importance of keeping web pages as lightweight as possible can be understood by the fact that about 20% of all page views can be done with an empty cache using these techniques! 40% to 60% of web users could have an empty cache experience.

In terms of code minification, one of the the most widely used tools is to minify JavaScript code. Most of the file size reduction is achieved by removing comments and extra whitespace characters that are not needed by web browsers or visitors. It can also be useful measure in order to make it obfuscate(unclear) javascript code from external users.

The goal of JavaScript and CSS minification is always to preserve the operational qualities of the code while reducing its overall byte footprint (both in raw terms and after gzipping, as most JavaScript and CSS served from production web servers is gzipped as part of the HTTP protocol).

There are many sites available for compressing Javascript or JS Code online like You can either upload your js file or simply copy code.

There are many other sites, just google ‘compress javascript code’. Likewise, you can compress your CSS files too; google ‘compress css’.