Wednesday, 14 November 2012

HMTL 5, CSS3 and JavaScript for Windows 8 – sessionStorage vs localStorage

HTML5 has introduced a new paradigm in the save state or save objects world for HTML5. Unfortunately this is not available for all the browsers yet, but it is available for the whole Windows 8 platform, including apps.

There are two types of Web Storage so far, and these are the localStorage, and the sessionStorage. The main difference is that the localStorage persists over different tabs or windows, and even if we close the browser, accordingly with the domain security policy and user choices about quota limit. The antagonist is the sessionStorage object which follows this rule:

When a new HTMLDocument is created, the user agent must check to see if the document's top-level browsing context has allocated a session storage area for that document's origin. If it has not, a new storage area for that document's origin must be created.

Each Document object must have a separate object for its Window's sessionStorage attribute.

sessionStorage object will not persist if we close the tab (top-level browsing context) as it does not exists if we surf via another tab or window. As summary, as soon as we are in our tab the session storage allows us to save a large amount of key/value pairs and lots of text, something impossible to do via cookie. This is what my implementation is trying to do with browsers that do not implement this special object. If you have doubts, you can directly test the demo link, and come back whenever you want.

To create applications which requiere to remember past data localStorage is our object. For other purposes we can use sessionStorage which at the end of the day is like Session in ASP.NET.

Tuesday, 13 November 2012

HMTL 5, CSS3 and JavaScript for Windows 8 – Calling a Web Service with AJAX

There are different ways to call a web service in JavaScript, but the best ones are done with AJAX. I have decided to add the same call but with different formats, so you can’t get lost and choose your favourite.

url: Web service address
type: Protocol, you can choose between GET and POST
timeout: Who long it is your application waiting for the web service.
dataType: Type of data, it could be text , json etc.
contentType: The content type you want, ie: "application/json; charset=utf-8",
cache: Read example below…
datafilter: Read example below…
Accepts:
Read example below…

METHOD 1

     $.ajax({
         url: '/sdsd/sdsd',
         type: 'GET',
         timeout: 1000,
         dataType: 'text'
     }).done(function (responsetext) {
         //do something
     }).fail(function () {
         //do something
     });



METHOD 2

     $.ajax({
         url: '/sdsd/sdsd',
         type: 'GET',
         timeout: 1000,
         dataType: 'text',
         success: function (responsetext) {
             //do something
         },
         error: function (e) {
             //do something
         }
     });




If you don’t specify an error handling jQuery will keep running.



To work with JSON so you can pass data across, JavaScript provides JSON.stringify and JSON.parse.



If you want to send JSON data , you can use something like this (Thanks Bobby):

 function InfoByDate(sDate, eDate) {
        var divToBeWorkedOn = "#AjaxPlaceHolder";
        var webMethod = "http://MyWebService/Web.asmx/GetInfoByDates";
        var parameters = "{'sDate':'" + sDate + "','eDate':'" + eDate + "'}";
        $.ajax({
            type: "POST",
            url: webMethod,
            data: parameters,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                $(divToBeWorkedOn).html(msg.d);
            },
            error: function (e) {
                $(divToBeWorkedOn).html("Unavailable");
            }
        });
    }



The onreadystatechange event is key in AJAX. This is the only way to monitor what is going on. We have three core properties. Please check the values and the example.



onreadystatechange
Stores a function (or the name of a function) to be called automatically each time the readyState property changes

readyState
Holds the status of the XMLHttpRequest. Changes from 0 to 4:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready

status
200: "OK"
404: Page not found

<html>
<head>
<script>
    function loadXMLDoc() {
        var xmlhttp;
        if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        }
        else {// code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET", "ajax_info.txt", true);
        xmlhttp.send();
    }
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
I recently show this question in a what it could be a Microsoft exam, and I think it will be quite useful to try to understand ajax calls, it is based on the accepts and datafilter parameter:

You are developing a web application that retrieves data from a web service. The data being retrieved is a custom binary datatype named bint. The data can also be represented in XML. Two existing methods named parseXml() and parseBint() are defined on the page. The application must:
· Retrieve and parse data from the web service by using binary format if possible
· Retrieve and parse the data from the web service by using XML when binary format is not possible



You need to develop the application to meet the requirements. What should you do? (To answer, drag the appropriate code segment to the correct location. Each code segment may be used once, more than once, or not at all. You may need to drag the split bar between panes or scroll to view content.)

          var request = $.ajax({
            uri:'/',
            accepts: 'application/bint, text/xml',
            datafilter: function(data,type){
                if(request.getResponseHeader("Content-Type")=="application/bint")
                   return parseBint(data);
                else
                   return parseXml();
                 },            
            success: function (data) {
              start(data);
            }
        });


Another interesting example is the way you can display on-line stock rates in real time. One of the features we should use to get a time stamp in the header is cache set to false. This will force requested pages not to be cached by the browser. I attach an example:

var stockRate;
function getResults(){
$.ajax({
            async: false,
            cache:false,
            type: "POST",
            url: "stockrates.asmx/rates"
            data: {'stockname':stockName},
            dataType: "json",
            success: function (msg) {
               stockRate=result;
        });
        ShowRate();
}

HMTL 5, CSS3 and JavaScript for Windows 8 – User Input Validation

HTML 5 Supports new validation fields and new input types. This new features are going to make the life really easy for us if we know what we have and what we can use.

The <input> tag supports in the type attribute, the following values:

button
checkbox
color
date
datetime
datetime-local
email
file
hidden
image
month
number
password
radio
range
reset
search
submit
tel
text
time
url
week

There are some tips you should know:

    • If one of the types is not supported by the browser, the field will be displayed anyway, but not in the correct format.
    • Use the form event to validate instead the input event.
    • HTML likes to emphasize the name and id attributes. id for CSS and name when the form is submitted.

We also have the required attribute. This attribute is completely new and allow us to validate client-side. A good validation will include server-side validation as well, so don’t forget to do that.

ie:  <input type="text" name="username" required="required" />

We can set maximum and minimum values with our input control. To do that we will be using the max attribute and the min attribute.

ie: <input type="text" name="price" type=”number” required="required" min=”5” max=”100” />

There is an excellent attribute it is going to help us formatting numbers or any character, very useful for phone numbers by the way. The attribute is called pattern.

The pattern attribute specifies a regular expression against which the control's value, or, when the multiple attribute applies and is set, the control's values, are to be checked.

If specified, the attribute's value must match the JavaScript Pattern production. [ECMA262]

If an input element has a pattern attribute specified, and the attribute's value, when compiled as a JavaScript regular expression with the global, ignoreCase, and multiline flags disabled (see ECMA262 Edition 5, sections 15.10.7.2 through 15.10.7.4), compiles successfully, then the resulting regular expression is the element's compiled pattern regular expression. If the element has no such attribute, or if the value doesn't compile successfully, then the element has no compiled pattern regular expression. [ECMA262]

Constraint validation: If the element's value is not the empty string, and either the element's multiple attribute is not specified or it does not apply to the input element given its type attribute's current state, and the element has a compiled pattern regular expression but that regular expression does not match the entirety of the element's value, then the element is suffering from a pattern mismatch.

Constraint validation: If the element's value is not the empty string, and the element's multiple attribute is specified and applies to the input element, and the element has a compiled pattern regular expression but that regular expression does not match the entirety of each of the element's values, then the element is suffering from a pattern mismatch.

The compiled pattern regular expression, when matched against a string, must have its start anchored to the start of the string and its end anchored to the end of the string.

Note:
This implies that the regular expression language used for this attribute is the same as that used in JavaScript, except that the pattern attribute is matched against the entire value, not just any subset (somewhat as if it implied a ^(?: at the start of the pattern and a )$ at the end).

When an input element has a pattern attribute specified, authors should include a title attribute to give a description of the pattern. User agents may use the contents of this attribute, if it is present, when informing the user that the pattern is not matched, or at any other suitable time, such as in a tooltip or read out by assistive technology when the control gains focus.

ie: <label> Part number: <input pattern="[0-9][A-Z]{3}" name="part" title="A part number is a digit followed by three uppercase letters."/> </label>

It will produce the following:

A part number is a digit followed by three uppercase letters.
You cannot submit this form when the field is incorrect.

How to create a nice border validation?
The best practice for validation logic is to add a red border when the validation has not been done properly. In CSS 3 you can add the valid/invalid into the input element.

For validation you could have the following:
input {
  border: solid 1px;
}
input:invalid{
   border-color: #f00;
}
input:valid{
  border-color: #0f0;
}