Encode or Decode HTML entities with jQuery

Javascript fumction for client side HTML encode and decode

function htmlEncode(value){
return $(‘<div/>’).text(value).html();
}

function htmlDecode(value){
return $(‘<div/>’).html(value).text();
}

how its works…….

The div element is created bit it is never appended to the HTML document

use of .html(): Get the HTML contents of the first element in the set of matched elements or set the HTML contents of every matched element.

use of .text(): Get the combined text contents of each element in the set of matched elements, including their descendants, or set the text contents of the matched elements.

function htmlEncode: set the innerText of the element, and retrieve the encoded innerHTML
function htmlDecode: set the innerHTML value of the element and the innerText is retrieved.

Author : Rony T Sam

Advertisements

JavaScript Regular Expression and samples

                     The regular expression’s elements specify what you would like to match or replace. The flags specify whether the matching/replacing must be done in the case-insensitive (i) and/or global (g) and/or multiline (m) mode.
To create a regular expression, you can use a regular expression literal or the RegExp constructor.

Regular expression literals in JavaScript use this syntax:
/elements/flags or, without the optional flags, simply:
/elements/

Examples of regular expression literals:
re = /^\s+|\s+$/g // any number of leading/trailing whitespaces
re = /\d\d\d/ // one sequence of 3 digits (1st match only)
re = /\d\d\d/g // any sequence of 3 digits
re = /[0-9][0-9][0-9]/g // any sequence of 3 digits
re = /jan|feb|mar|apr/i // Jan or Feb or Mar or Apr (case-insensitive)
re = /”[a-z]+”/gi // any sequence of Latin letters, in quotes

The RegExp constructor has this syntax:
new RegExp(elements,flags)

Examples of the RegExp constructor (the constructor calls below create regular expressions similar to the above):
//to get \s in regular expression, pass \\s to RegExp constructor!
re = new RegExp(“^\\s*|\\s*$”,”g”)
re = new RegExp(“\\d\\d\\d”,”)
re = new RegExp(“\\d\\d\\d”,’g’)
re = new RegExp(“[0-9][0-9][0-9]”,”g”)
re = new RegExp(“jan|feb|mar|apr”,”i”)

Whether you use constructors or literals, your regular expressions can include the following elements and flags. The elements describe the pattern you want to match, while the flags specify how the matching should be performed.

Element Matches this…
[xyz] Any one character x or y or z, as listed in square brackets
[x-z] Any one character within the range specified in brackets
[^xyz] Any one character except x, y, z
[^x-z] Any one character except the range in brackets
. Any character except newline
\d \D Any digit (\d), any non-digit (\D)
\s \S Any whitespace (\s), any non-whitespace (\S)
\w \W Any word character (\w), any non-word character (\W)
\b \B Word boundary (\b), non-boundary (\B)
[\b] Backspace (the square brackets help distinguish backspace from word boundary)
^ Beginning of string; beginning of line if the m flag is set
$ End of string; end of line if the m flag is set
\n \r \f \t \v Newline, carriage return, form feed, tab, vertical tab
\+ \- \. \* \? \| Match + – . * ? | etc. verbatim (not as a special character)
\/ \\ \^ \$ Match / \ ^ $ verbatim (not as a special character)
\[ \] \( \) \{ \} Match brackets/parentheses/braces verbatim
\xAB Match the character with hexadecimal code AB
\uABCD Match the Unicode character with hexadecimal code ABCD

x|y Match x or y
+ Match the preceding element one or more times
* Match the preceding element zero or more times
? Match the preceding element zero or one time
{n} Match the preceding element exactly n times
{n,} Match the preceding element n or more times
{m,n} Match the preceding element at least m, at most n times

(…) Match … as a capturing group: store the matching substring
(used with string.match(re) to return an array of matching strings)
\1 \2 \3 etc. Match the same substring as in capturing group number 1, 2, 3 etc.
$1 $2 $3 etc. Replace with the characters that matched group number 1, 2, 3 etc.
(used in the second argument of replace() method)
(?:…) Match … as a non-capturing group: grouping only, no storing

Any character Match the character verbatim
(except the above)
RegExp flags can be any combination of the following:

i Ignore case (both lowercase and uppercase letters will match)
g Global (allow multiple matches)
m Multiline (^ and $ will match the beginning/end of lines)
The effect of not setting these flags is as follows:
i not set The regular expression is case-sensitive
g not set Use only the first match (no global search)
m not set ^ and $ match the beginning/end of the entire string
Notes
(1) A whitespace (\s) in a regular expression matches any one of the characters: space, formfeed (\f), newline (\n), return (\r), tab (\t), vertical tab (\v), non-breaking space (\xA0), as well as the Unicode characters \u00A0 \u2028 \u2029.

(2) When using the RegExp constructor: for each backslash in your regular expression, you have to type \\ in the RegExp constructor. (In JavaScript strings, \\ represents a single backslash!) For example, the following regular expressions match all leading and trailing whitespaces (\s); note that \\s is passed as part of the first argument of the RegExp constructor:

re = /^\s+|\s+$/g
re = new RegExp(‘^\\s+|\\s+$’,’g’)

Regular Expression samples

*) Trimming a string in JavaScript
To remove all leading and trailing spaces from a string, we can use this code:

function Trim(strValue) {
var pattern = /^\s+|\s+$/g ;
strValue = strValue.replace(pattern, “”);
return strValue;
}

function TrimRight(strValue) {
var patternR = /(\s)+$/g;
strValue = strValue.replace(patternR, “”);
return strValue;
}

function TrimLeft(strValue) {
var patternL = /^(\s)+/g;
strValue = strValue.replace(patternL, “”);
return strValue;
}

This code example uses the regular expression /^\s+|\s+$/g which matches one or more occurrences of whitespace (\s) in the beginning and at the end of string. The g (global) flag in the regular expression specifies that a global search should be performed (e.g. even if a match is found in the beginning of the string, the matching process must still continue and attempt to find whitespaces at the end of the string, too). The string.replace() method is used to replace all leading and trailing whitespace characters with an empty string.

*) Is Null check in Javascript
To check whether a string is empty or not in client side, we can use this code:

function IsNull(strValue) {
//check the string is defined or not
if (!strValue) { return true; }

var pattern = /^\s+|\s+$/g ;
strValue = strValue.replace(pattern, “”);
if (strValue.length > 0) { return false; }
else { return true; }
}
This code example uses the regular expression /^\s+|\s+$/g which matches one or more occurrences of whitespace (\s) in the beginning and at the end of string. After that we will check the length of the string.

*) Decimal check in Javascript
To check whether a number is decimal or not in client side, we can use this code:

function decimalValidation(value) {
var pattern = /^\d*.\d*$/; // var pattern = /^\d*.\d{0,2}$/;
if (value.match(pattern) == null) {
return false;
}
else {
if (value == ‘.’) { return false; }
else { return true; }
}
}

*) Integer check  in Javascript
To check whether a number is integer or not in client side, we can use this code:

function integerValidation(value) {
var pattern = /^\d*$/; // var pattern = /^\d*.\d{0,2}$/;
if (value.match(pattern) == null) {
return false;
}
else {
return true;
}
}

*) Seperates the components of the number

function numberWithCommas(yourNumber) {
//Seperates the components of the number
var n = yourNumber.toString().split(“.”);
//Comma-fies the first part
n[0] = n[0].replace(/\B(?=(\d{3})+(?!\d))/g, “,”);
//Combines the two sections
return n.join(“.”);
}

Ref: http://www.javascripter.net/faq/creatingregularexpressions.htm

Author : Rony T Sam

How to get client IP address using jQuery?

ip_logo_medjQuery gets the client IP address by just passing a url, formatted with the callback=? paramtere to the $.getJSON method.

$(document).ready(function () {
   $.getJSON("http://jsonip.com?callback=?",
     function (data) {
       var ip = (data.ip).split(',');
       $('#showIP').text('Machine IP: ' + ip[0] + 'Network IP:' + ip[1]);
  });
});

Author : Aneesh Sivan

Simple RegEx Validation using jQuery

How to validate an email filed using RegEx 

HTML

Name <input type=”text” id=”txtEmail” />
<input type=”button” id=”btnOk” value=”OK”/>

jQuery

$(document).ready(function () {
       $(‘#btnOk’).live(‘click’, function () {
       email_address = $(‘#txtEmail’);
       email_regex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i;
       if (!email_regex.test(email_address.val())) {
            alert(‘this is not valid email’);
            e.preventDefault(); return false;
         }
           else {
            alert(‘Valid email’);
           }

      });
});

                                                                                        Author : Aneesh Sivan

What is the Difference Between ViewBag and ViewData in MVC 3?

Introduction

ViewBag and ViewData serve the same purpose in allowing developers to pass data from controllers to views. When we put objects in either one, those objects become accessible in the view. This is one way we interact between the view and the controller in ASP.NET MVC. We pass data from the view to the controller by placing it in these objects.

How ViewData Works

ViewData is a dictionary of objects that are accessible using strings as keys. This means that we will write code like this:

In the Controller

public ActionResult Index()
{
    var softwareDevelopers = new List<string>
    {
        "Brendan Enrick", 
        "Kevin Kuebler", 
        "Todd Ropog"
    };

    ViewData["softwareDevelopers"] = softwareDevelopers;

    return View();
}

In the View

<ul>
@foreach (var developer in (List<string>)ViewData["softwareDevelopers"])
{
    <li>
        @developer
    </li>
}
</ul>

Notice that when we go to use out object on the view that we have to cast it since the ViewData is storing everything as object. Also, we need to be careful since we’re using magic strings to access these values.

How ViewBag Works

ViewBag uses the dynamic feature that was added in to C# 4. It allows an object to dynamically have properties added to it. The code we write using ViewBag will look like this:

In the Controller

public ActionResult Index()
{
    var softwareDevelopers = new List<string>
    {
        "Brendan Enrick", 
        "Kevin Kuebler", 
        "Todd Ropog"
    };

    ViewBag.softwareDevelopers = softwareDevelopers;

    return View();
}

In the View

<ul>
@foreach (var developer in ViewBag.softwareDevelopers)
{
    <li>
        @developer
    </li>
}
</ul>

Notice here that we did not have to cast our object when using the ViewBag. This is because the dynamic we used lets us know the type. Keep in mind that these dynamics are as the name suggest, dynamic, which means that you need to be careful as these are basically magic properties instead of magic strings.

ViewBag and ViewData Under the Hood

So these two things seem to work almost exactly the same. What’s the difference? The difference is only in how you access the data. ViewBag is actually just a wrapper around the ViewData object, and its whole purpose is to let you use dynamics to access the data instead of using magic strings. Some people prefer one style over the other. You can pick whichever you like. In fact, because they’re the same data just with two different ways of accessing it, you can use them interchangeably. (I don’t recommend this, but you can do it.) If you want you are able to put data into the ViewBag and access it from the ViewData or put stuff in the ViewData and access it in the ViewBag.

This is all that the ViewBag property is. It’s just a DynamicViewDataDictionary with the ViewData as its data.

public dynamic ViewBag 
{ 
    get 
    { 
        if (_dynamicViewData == null) 
        {
            _dynamicViewData = 
                new DynamicViewDataDictionary(() => ViewData); 
        }
        return _dynamicViewData;
    }
}

Then when we access the dynamic members of the DynamicViewDataDictionary, we are actually just getting this override of the DynamicObject’s TryGetMember. In this method, it’s just using the name of the member we tried to access as the string key for the ViewData dictionary.

public override bool TryGetMember(
    GetMemberBinder binder, out object result)
{
    result = ViewData[binder.Name]; 
    return true;
}

These two objects are two different ways of accessing the exact same data. The ViewBag is just a dynamic wrapper around the ViewData dictionary.

How to disable Back functionality of a browser?

Disable Back functionality using history.forward

We can disable the back navigation by adding following code in the webpage. Now the catch here is that you have to add this code in all the pages where you want to avoid user to get back from previous page. For example user follows the navigation page1 -> page2. And you want to stop user from page2 to go back to page1. In this case all following code in page1.

<SCRIPT type="text/javascript">
    window.history.forward();
    function noBack() { window.history.forward(); }
</SCRIPT>
</HEAD>
<BODY onload="noBack();"
    onpageshow="if (event.persisted) noBack();" onunload="">

The above code will trigger history.forward event for page1. Thus if user presses Back button on page2, he will be sent to page1. But the history.forward code on page1 pushes the user back to page2. Thus user will not be able to go back from page1.

Warn User if Back is Pressed

You may want to warn user if Back button is pressed. This works in most of the cases. If you have some unsaved form data, you might want to trigger a warning message to user if Back button is pressed.

Following Javascript snippet will add a warning message in case Back button is pressed:

window.onbeforeunload = function() { return "You work will be lost."; };

Include this in your HTML page to popup a warning message.

Source: http://viralpatel.net/blogs/disable-back-button-browser-javascript/

How to call Server Side function from Client Side in ASP.NET?

Call Server Side function from Client Side Code using PageMethods in ASP.NET and jQuery

You cannot call server-side code ‘directly’ from client-side code. That is because by design, the server side code executes at server side and client side code at the client. However there are some workarounds. To call serverside code from javascript, you will need to use AJAX. Here we are using jQuery AJAX to call serverside method.

1. Create a new website.
2. Open the Default.aspx include jquery library to the page.
<script src=”Scripts/jquery-1.4.1.js” type=”text/javascript”></script>
3. Add an html button in the page

<input type=”button” value=”Get Methhod” id=”btnGetMethod” />

4. Go the Code behind file of the page and add a static method and mark them as WebMethod. Lets Say the method name is GetPageMethod which returns a status value

[System.Web.Services.WebMethod]        
public static string GetPageMethod()
{
      return “Welcome PageMethods”;
}

5. Go back to the aspx page and write the following jquery script.
<script type=”text/javascript”>
$(document).ready(function () {
$(‘#btn1’).live(‘click’, function () {
$.ajax({
type: “POST”,
url: “Default.aspx/GetPageMethod”,
data: “{}”,
contentType: “application/json; charset=utf-8”,
dataType: “json”,
success: function (msg) {
alert(msg.d);
}
});
});

});

</script>
6. Run the application.

                                                       Author: Aneesh Sivan

What is CSS media types?

Image

1. Introduction to css media types

One of the most important features of style sheets is that they specify how a document is to be presented on different media: on the screen, on paper, with a speech synthesizer, with a braille device, etc.

Certain CSS properties are only designed for certain media. On occasion, however, style sheets for different media types may share a property, but require different values for that property. For example, the ‘font size’ property is useful both for screen and print media. The two media types are different enough to require different values for the common property; a document will typically need a larger font on a computer screen than on paper. Therefore, it is necessary to express that a style sheet, or a section of a style sheet, applies to certain media types.

2. Specifying media-dependent style sheets

There are currently two ways to specify media dependencies for style sheets:

Specify the target medium from a style sheet with the @media or @import at-rules.

@import url("fancyfonts.css") screen;
@media print {
  /* style sheet for print goes here */
}

Specify the target medium within the document language. For example, in HTML 4 the “media” attribute on the LINK element specifies the target media of an external style sheet:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<HTML>
   <HEAD>
      <TITLE>Link to a target medium</TITLE>
      <LINK REL="stylesheet" TYPE="text/css" 
             MEDIA="print, handheld" HREF="foo.css">
   </HEAD>
   <BODY>
      <P>The body...
   </BODY>
</HTML>

 

 

 

The @media rule

An @media rule specifies the target media types (separated by commas) of a set of statements (delimited by curly braces). Invalid statements must be ignored per 4.1.7 "Rule sets, declaration blocks, and selectors" and 4.2 "Rules for handling parsing errors." The @media construct allows style sheet rules for various media in the same style sheet:
 
  @media print {
    body { font-size: 10pt }
  }
  @media screen {
    body { font-size: 13px }
  }
  @media screen, print {
    body { line-height: 1.2 }
  }

Style rules outside of @media rules apply to all media types that the style sheet applies to. At-rules inside @media are invalid in CSS2.1.

3. Recognized media types

The names chosen for CSS media types reflect target devices for which the relevant properties make sense. In the following list of CSS media types the names of media types are normative, but the descriptions are informative. Likewise, the “Media” field in the description of each property is informative.

all

Suitable for all devices.

braille

Intended for braille tactile feedback devices.

embossed

Intended for paged braille printers.

handheld

Intended for handheld devices (typically small screen, limited bandwidth).

print

Intended for paged material and for documents viewed on screen in print preview mode. Please consult the section on paged media for information about formatting issues that are specific to paged media.

projection

Intended for projected presentations, for example projectors. Please consult the section on paged media for information about formatting issues that are specific to paged media.

screen

Intended primarily for color computer screens.

speech

Intended for speech synthesizers. Note: CSS2 had a similar media type called ‘aural’ for this purpose. See the appendix on aural style sheets for details.

tty

Intended for media using a fixed-pitch character grid (such as teletypes, terminals, or portable devices with limited display capabilities). Authors should not use pixel units with the “tty” media type.

tv

Intended for television-type devices (low resolution, color, limited-scrollability screens, sound available).

Media type names are case-insensitive.

Media types are mutually exclusive in the sense that a user agent can only support one media type when rendering a document. However, user agents may use different media types on different canvases. For example, a document may (simultaneously) be shown in ‘screen’ mode on one canvas and ‘print’ mode on another canvas.

Note that a multimodal media type is still only one media type. The ‘tv’ media type, for example, is a multimodal media type that renders both visually and aurally to a single canvas.

@media and @import rules with unknown media types (that are nonetheless valid identifiers) are treated as if the unknown media types are not present. If an @media/@import rule contains a malformed media type (not an identifier) then the statement is invalid.

Note: Media Queries supercedes this error handling.

For example, in the following snippet, the rule on the P element applies in ‘screen’ mode (even though the ‘3D’ media type is not known).

@media screen, 3D {
  P { color: green; }
}

Note. Future updates of CSS may extend the list of media types. Authors should not rely on media type names that are not yet defined by a CSS specification.

Media groups

This section is informative, not normative.

Each CSS property definition specifies which media types the property applies to. Since properties generally apply to several media types, the “Applies to media” section of each property definition lists media groups rather than individual media types. Each property applies to all media types in the media groups listed in its definition.

CSS 2.1 defines the following media groups:

  • continuous or paged.
  • visual, audio, speech, or tactile.
  • grid (for character grid devices), or bitmap.
  • interactive (for devices that allow user interaction), or static (for those that do not).
  • all (includes all media types)

The following table shows the relationships between media groups and media types:

Relationship between media groups and media types

Media Types

Media Groups

 

continuous/paged

visual/audio/speech/tactile

grid/bitmap

interactive/static

braille

continuous

tactile

grid

both

embossed

paged

tactile

grid

static

handheld

both

visual, audio, speech

both

both

print

paged

visual

bitmap

static

projection

paged

visual

bitmap

interactive

screen

continuous

visual, audio

bitmap

both

speech

continuous

speech

N/A

both

tty

continuous

visual

grid

both

tv

both

visual, audio

bitmap

both

 Author: Aneesh Sivan,

 Reference: W3C Candidate Recommendation 12 October 2010

What is a Browser Engine?

Browser Engine

A web browser engine, (sometimes called layout engine or rendering engine), is a software component that takes marked up content (such as HTML, XML, image files, etc.) and formatting information (such as CSS, XSL, etc.) and displays the formatted content on the screen. It “paints” on the content area of a window, which is displayed on a monitor or a printer. A web browser engine is typically embedded in web browsers, e-mail clients, on-line help systems or other applications that require the displaying (and editing) of web content.

Have a look some most popular browser engines

Trident

  • Popular Browsers & Applications: Internet Explorer, Avant Browser, Maxathon, Microsoft Outlook, Outlook Express, AOL Browser
  • License: Closed-Source
  • Acid2 Compatible: Yes (in version VI included in Internet Explorer 8)
  • Acid3 Compatible: No
  • Operating Systems: Windows
  • Major Contributors: Microsoft
  • First Released: April 1997

Gecko

  • Popular Browsers & Applications: Firefox, Camino, Flock, Thunderbird, Seamonkey, Epiphany, NVU, Netscape, K-Meleon
  • License: Open-Source
  • Acid2 Compatible: Yes
  • Acid3 Compatible: No
  • Operating Systems: Windows, Mac OS X, Linux/BSD
  • Major Contributors: Mozilla Corporation, Netscape (originally)
  •  First Released: December 1998

WebKit

  • Popular Browsers & Applications: Safari, Chrome, Adobe AIR, iCab, Epiphany (experimental), Konqueror (KHTML)
  • License: Open-Source
  • Acid2 Compatible: Yes
  • Acid3 Compatible: Yes
  • Operating Systems: Windows, Mac OS X, Linux/BSD
  • Major Contributors: WebKit Foundation, Apple, Nokia, Adobe, Google, KDE Team (originally)
  • First Released: January 2003 (forked from KHTML, which was first released in October 2000)

Presto

  • Popular Browsers & Applications: Opera Desktop/Mobile/Mini, Nintendo DS, Wii Internet Channel, Macromedia Dreamweaver MX and above, Adobe CS 2 and above
  • License: Closed-Source
  • Acid2 Compatible: Yes
  • Acid3 Compatible: Yes
  • Operating Systems: Windows, Mac OS X, Linux/BSD
  • Major Contributors: Opera Software
  • First Released: November 2002

Usage share of web browsers

Author: Aneesh Sivan

What is a Web service?

Definition:

A Web service is a software system designed to support interoperable machine-to-machine interaction over a network. It has an interface described in a machine-processable format (specifically WSDL). Other systems interact with the Web service in a manner prescribed by its description using SOAP messages, typically conveyed using HTTP with an XML serialization in conjunction with other Web-related standards.

  • Web Services can convert your applications into Web-applications.
  • Web Services are published, found, and used through the Web.

What are Web Services?

  • Web services are application components
  • Web services communicate using open protocols
  • Web services are self-contained and self-describing
  • Web services can be discovered using UDDI
  • Web services can be used by other applications
  • XML is the basis for Web services

Web Services have three basic platform elements: SOAP, WSDL and UDDI.

1.SOAP (Simple Object Access Protocol)

SOAP is a protocol for accessing a Web Service. SOAP provides a standard, extensible, composable framework for packaging and exchanging XML messages.

  • SOAP stands for Simple Object Access Protocol
  • SOAP is a communication protocol
  • SOAP is a format for sending messages
  • SOAP is designed to communicate via Internet
  • SOAP is platform independent
  • SOAP is language independent
  • SOAP is based on XML
  • SOAP is simple and extensible
  • SOAP allows you to get around firewalls
  • SOAP is a W3C standard

2. WSDL (Web Services Description Language ).

WSDL is an XML-based language for locating and describing Web services.WSDL describes Web services starting with the messages that are exchanged between the requester and provider agents. The messages themselves are described abstractly and then bound to a concrete network protocol and message format.

  • WSDL stands for Web Services Description Language
  • WSDL is based on XML
  • WSDL is used to describe Web services
  • WSDL is used to locate Web services
  • WSDL is a W3C standard

3. UDDI (Universal Description Discovery and Integration)

UDDI is a directory service where companies can register and search for Web services. UDDIis a platform-independent, Extensible Markup Language (XML)-based registry for businesses worldwide to list themselves on the Internet and a mechanism to register and locate web service applications.

  • UDDI stands for Universal Description, Discovery and Integration
  • UDDI is a directory for storing information about web services
  • UDDI is a directory of web service interfaces described by WSDL
  • UDDI communicates via SOAP
  • UDDI is built into the Microsoft .NET platform

Learn ASP.NET Web Services  from MSDN >>