Book Image

Microsoft AJAX Library Essentials: Client-side ASP.NET AJAX 1.0 Explained

Book Image

Microsoft AJAX Library Essentials: Client-side ASP.NET AJAX 1.0 Explained

Overview of this book

Microsoft AJAX Library Essentials is a practical reference for the client-side library of the ASP.NET AJAX Framework 1.0, and a tutorial for the underlying technologies and techniques required to use the library at its full potential. The main goal of this book is to get you comfortable with the Microsoft AJAX Library, a huge set of functions that can be used for developing powerful client-side functionality.Beginning with a hands-on tour of the basic technologies associated with AJAX, JavaScript, XMLHttpRequest, JSON, and the DOM, you'll move on to a crash course in the Microsoft AJAX tools. You will learn, through numerous step-by-step exercises, how to create basic AJAX applications, how the object-based programming model of JavaScript works, and how Microsoft AJAX Library extends this model. You'll understand the architecture of the Microsoft AJAX components, how they all fit together, and exactly what they can do for you. Then you will learn how to use the Microsoft AJAX Library in your web projects, and a detailed case study will walk you through creating your own customized client components. At every stage of your journey, you'll be able to try out examples to illuminate the theory, and consolidate your understanding. In addition to learning about the client and server controls, you'll also see how to handle errors and debug your AJAX applications.To complement your new found skills, the book ends with a visual reference of the Microsoft AJAX Library namespaces and classes, including diagrams and quick explanations for all the classes mentioned in the book, providing an invaluable reference you will turn to again and again.
Table of Contents (14 chapters)
Copyright
Credits
About the Authors
About the Reviewers
Preface

JavaScript Base Type Extensions


The ECMAScript (JavaScript) objects have been enriched with some new methods in order to make the programmer’s transition from using the .NET Framework’s classes to JavaScript’s objects much easier.

Array Class

The Array class (Figure A-9) represents an extension of the built-in JavaScript Array object. It provides reflection information about the type and the type name of an object and also additional static methods offered by the .NET environment for arrays.

Figure A-9 Array

All the methods in this class are static methods.

var a = ["1", "2", "3"];
var b = ["11", "12", "13"];
// Add an element to an array
Array.add(a, "4");
Sys.Debug.trace(a);
// Output: 1,2,3,4

// Add a range of elements to an array
Array.addRange(a, ["5", "6"]);
Sys.Debug.trace(a);
 // Output: 1,2,3,4,5,6

// Clone an array
var c = Array.clone(a);
Sys.Debug.trace(a);
// Output: 1,2,3,4,5,6

// Clear an array
Array.clear(c);
Sys.Debug.trace(c);
// Output:

// Check to see if an array has an element
         Sys.Debug.trace(Array.contains(a,"3"));
// Output: true

// Dequeue the last element from an array
Sys.Debug.trace(Array.dequeue(a));
// Output:  1

// Apply a function to all the elements of an array
Array.forEach(a,function(element, i, array){
Sys.Debug.trace("Array[" + i + "]=" + element);
});
// Output: Array[0]=2
Array[1]=3
Array[2]=4
Array[3]=5
Array[4]=6
// Search an element in an array
Sys.Debug.trace(Array.indexOf(a,"5",2));
// Output:  3

// Insert an element in an array at a specified position
Array.insert(a,3,"8");
Sys.Debug.trace(a);
// Output: 2, 3, 4, 8, 5, 6

// Parse a string and return an array
Sys.Debug.trace(Array.parse('["0","1","2"]'));
// Output : 0, 1, 2

// Remove an element from an array
Array.remove(a, "1");
Sys.Debug.trace(a);
// Output : 2, 3, 4, 8, 5, 6

// Remove an element at a specified position from an array
Array.removeAt(a,2);
Sys.Debug.trace(a);
// Output : 2, 3, 8, 5, 6

Boolean Class

The Boolean class (Figure A-10) represents an extension of the built-in JavaScript Boolean object. It provides reflection information about the type and the type name of an object and also an additional method offered by the .NET environment.

Figure A-10 Boolean

var bool = Boolean.parse("true");
         Sys.Debug.trace(bool);
// Output: true

Date Class

The Date class (Figure A-11) represents an extension of the built-in JavaScript Date object. It provides reflection information about the type and the type name of an object and also additional methods offered by the .NET environment for creating and formatting a date.

Figure A-11 Date

Note

Please refer to Sys.CultureInfo for more information about the localization features.

Date and Number JavaScript variables can be formatted to their corresponding locale.

Predefined string patterns

Description

d

Short date pattern : MM/dd/yyyy

D

Long date pattern : dddd, dd MMMM yyyy

t

Short time pattern : HH:mm

T

Long time pattern : HH:mm:ss

F

Full date time pattern : dddd, dd MMMM yyyy HH:mm:ss

M or m

Month day pattern : MMMM dd

s

Sortable date time pattern :

yyyy'-'MM'-'dd'T'HH':'mm':'ss

Y or y

Year month pattern : yyyy MMMM

The above table represents the predefined string patterns for the InvariantCulture. As we can see each predefined pattern translates into a series of format specifier characters. Below we can find the complete list of format specifier characters:

Format specifier character

Description

dddd

Full day name (Sunday, Monday, etc.)

ddd

Abbreviated day name (Sun, Mon, etc.)

dd

Day of the month, 2 digits (00...31)

d

Day of the month (0...31)

MMMM

Full month name (January, February, etc.)

MMM

Abbreviated month name (Jan, Feb, etc.)

MM

Month of the year, 2 digits (01...12)

M

Month of the year (1...12)

yyyy

Year, 4 digits (2006)

yy

Year, 2 digits (06, 00, 99)

y

Year (6, 0, 99)

hh

Hour (1...12)

h

Hour (0...23)

HH

Hour, 2 digits (00...23)

H

Hour (0...23)

mm

Minutes, 2 digits (00...59)

m

Minutes (0...59)

ss

Seconds, 2 digits (00...59)

s

Seconds (0...59)

tt

AM or PM

t

A or P (short for AM and PM)

f

Hundreds of milliseconds, 1 digit (0...9)

ff

Hundreds and tens of milliseconds, 2 digits (00...99)

fff

Milliseconds (000...999)

z

Time zone offset in hours (+7, -2)

zz

Time zone offset in hours, 2 digits (+ 07, -02)

zzz

Time zone offset in hours and minutes (+07:00, -02:00)

Note

The string passed to the format() or localeFormat() methods should have a single character if it is a predefined pattern, or at least two characters if it has format specifier characters.

// Displays the current date using the InvariantCulture object
Sys.Debug.trace ((new Date()).format("F"));
// Output: Friday, May 18, 2007 4:58:36 PM


// Displays the current date using the CurrentCulture object set for
French
Sys.Debug.trace((new Date()).localeFormat("F"));
// Output: vendredi 18 mai 2007 17:03:47


// Parse a string date using two date formats from InvariantCulture
object. The first format is skipped and the second one is choosed
Sys.Debug.trace(Date.parseInvariant("05/17/2007","MM-dd-yyyy","MM/dd/
yyyy"));
// Output: Thu May 17 00:00:00 UTC+0300 2007


// Parse a string date using the predefined short date format from
French CurrentCulture object. The short date pattern is dd/MM/yyyy
Sys.Debug.trace(Date.parseLocale("17/05/2007","d"));
// Output: Thu May 17 00:00:00 UTC+0300 2007

Error Class

The Error extension class (Figure A-12) contains a series of static methods that return Error objects.

Figure A-12 Error

create() Method

Static method that creates and returns an Error object.

Parameters

message – the optional message to be displayed in the error.

errorInfo – a JSON object containing a collection of keys and their values.

Returns

The method returns the created Error object.

Remarks

The method creates and returns an Error object. It can receive an optional message and JSON object containing an additional collection of keys and their values. This collection will be added to the error message where the keys will represent additional attributes and the values would represent their values. The message parameter is mapped as the message attribute of the Error object.

Example
var e = Error.create(displayMessage, { name: "Sys.ArgumentException",
paramName: paramName });

The preceding example is extracted from the debug version of the library in the Error.argument() method.

Following are few other examples for Error:

// Create and throw and argument error
var err = Error.argument("valueParameter", "Invalid parameter");
throw err;
/* Output: Sys.ArgumentException: Invalid parameter
Parameter name: valueParameter */


// Create and throw a null argument error
var err = Error.argumentNull("nullParameter", "The parameter does not
accept null values");
throw err;
/* Output: Sys.ArgumentNullException: The parameter does not accept
null values
Parameter name: nullParameter */


// Create and throw an argument out of range error
var err = Error.argumentOutOfRange("valueParameter", 11, "The
parameter accepts values between 1 and 10");
throw err;
/* Output: Sys.ArgumentOutOfRangeException: The parameter accepts
values between 1 and 10
Parameter name: valueParameter
Actual value was 11. */


// Create and throw an argument type error
var err = Error.argumentType("valueParameter", Date, Number, "The
parameter is not the expected type");
throw err;
/* Output Sys.ArgumentTypeException: The parameter is not the expected
type
Parameter name: valueParameter */


// Create and throw an undefined argument error
if(typeof(parameter) === 'undefined')
{

  var err = Error.argumentUndefined("parameter", "The parameter type
is undefined");
  throw err;
}

//Output Sys.ArgumentUndefinedException: The parameter type is
undefined
Parameter name: parameter

// Create and throw an invalid operation error
var err= Error.invalidOperation("An invalid operation has been
detected");
throw err;

// Output: Sys.InvalidOperationException: An invalid operation has
been detected

function test()
{

  // Create and throw a not implemented error

  var err= Error.notImplemented("Method not implemented");
  throw err;
}
test();

// Output: Sys.NotImplementedException: Method not implemented

function testParams()
{
  if(arguments.length>0)
  {

    // Create and throw a parameter count error
    var err= Error.parameterCount("Too many parameters");
    throw err;
  }
}
testParams("test");

// Output: Sys.ParameterCountException: Too many parameters

var err = Error.format("Bad format specified ");
throw err;

// Output: Sys.FormatException: Bad format specified

Number Class

This class represents an extension of the built-in JavaScript Number object. It provides reflection information about the type and the type name of an object, and also additional methods offered by the .NET environment for creating and formatting a number.

Figure A-13 Number

Note

Please refer to Sys.CultureInfo for more information about the localized features.

The patterns for the Number object are:

Format specifier character

Description

d or D

Decimal format

c or C

Currency format

n or N

Number format

p or P

Percentage

Please check the link below for more info:

http://msdn2.microsoft.com/en-us/library/44e531aa-1383-48ad-887b-
fa15d81566c3.aspx

    // This example shows how the same value is parsed using the
    InvariantCulture and the French CurrentCulture.
    var a = Number.parseInvariant("2.55");
    var b = Number.parseLocale("2,55");
    Sys.Debug.trace(a + b);

    // Output: 5.1

Object Class

This class represents an extension of the built-in JavaScript Object object and it provides reflection information about the type and the type name of an object.

Figure A-14 Object

var array = ["1","2"];
Sys.Debug.trace (Object.getTypeName(array));
// Output: Array

RegExp Class

This class represents an extension of the built-in JavaScript RegExp object and it provides reflection information about the type and the type name of a regular expression.

Figure A-15 RegExp

Without adding any additional functions, it offers the same functionality that is provided by JavaScript by default.

String Class

This class represents an extension of the built-in JavaScript String object. It provides reflection information about the type and the type name of an object and also additional methods offered by the .NET environment for arrays.

Figure A-16 String

// Trim a string
          var str = " My text ";
         Sys.Debug.trace(str.trim());
// Output:My text

         // Left trim a string
         var str = " My text ";
         Sys.Debug.trace(str.trimStart());
// Output:My text

          // Right trim a string
          var str = " My text ";
          Sys.Debug.trace(str.trimEnd());
// Output: My text

         // Test to see if a string starts with another string
         var str = "test string";
         Sys.Debug.trace(str.startsWith("tes"));
// Output:true

         // Test to see if a string ends with another string
         var str = "test string";
         Sys.Debug.trace(str.endsWith("tes"));
// Output:false

         // Format a string based on the arguments using the
            InvariantCulture object
          Sys.Debug.trace(String.format("On {0:F} the market share is
                                            {1:p}",new Date(),23.24));
// Output:On Friday, 18 May 2007 20:35:33 the market share is 23.24 %
         // Format a string based on the arguments using the
            CurrentCulture object
          Sys.Debug.trace(String.localeFormat("On {0:F} the market
                                share is {1:p}",new Date(),23.24));
// Output: On vendredi 18 mai 2007 20:35:33 the market share is
23,24 %