Pages

Monday, October 13, 2008

Extending JavaScript with ASP.NET AJAX

ASP.NET AJAX Introduction-2

Client Scripting

Extending JavaScript with ASP.NET AJAX
Introduction

Microsoft ASP.NET AJAX enables you to write rich, interactive applications in JavaScript that target the browser. The Microsoft AJAX Library adds a type system and extensions to JavaScript objects in order to provide namespaces, inheritance, interfaces, enumerations, reflection, and helpers for strings and arrays. These additions provide functionality similar to the .NET Framework. They enable you to write ASP.NET AJAX applications in a structured way that improves maintainability, makes it easier to add features, and makes it easier to layer functionality.

In this section you will learn how to use the following JavaScript Microsoft AJAX Library features:

*

Classes
*

Namespaces
*

Inheritance
*

Interfaces
*

Enumerations
*

Reflection

Classes, Members, and Namespaces

Classes are reference types. All classes in JavaScript derive from object. (Similarly, in the .NET Framework class library, all classes derive from Object.) Classes in ASP.NET AJAX enable you to create objects and components that derive from base classes in the Microsoft AJAX Library by using an object-oriented programming model.

Classes can have four kinds of members: fields, properties, methods, and events. Fields and properties are name/value pairs that describe characteristics of an instance of a class. Fields are composed of primitive types and are accessed directly, as in the following example:

myClassInstance.name="Fred"

With properties, the value can be any primitive or reference type and is accessed by get and set accessor methods. In ASP.NET AJAX, the get and set accessors are separate functions, which by convention use the prefix "get_" or "set_" in the function name. For example, to get or set a value for a property such as cancel, you call the get_cancel or set_cancel methods.

A method is a function that performs an action instead of just returning a property value. Both methods and properties are illustrated in the examples in this topic.

Events are programmatic notifications that particular actions have occurred. When an event is raised, it can call one or more functions, referred to as handlers, to perform tasks that were waiting for that event. For more information about events in ASP.NET AJAX, see ASP.NET AJAX Client Life-Cycle Events.

A namespace is a logical grouping of related classes (types). Namespaces enable you to group common functionality. The following example demonstrates how to add a Person class to the Demo namespace using the Type.registerNamespace and .registerClass methods.

To enable ASP.NET AJAX functionality for an ASP.NET Web page, you must add an control to the page. When the page is rendered, the appropriate script references to ASP.NET AJAX libraries are generated automatically. The following example shows a page with an control.
cs



The following example shows how to register the namespace, create the class, and then register the class.
cs

Type.registerNamespace("Demo");

Demo.Person = function(firstName, lastName, emailAddress) {
this._firstName = firstName;
this._lastName = lastName;
this._emailAddress = emailAddress;
}

Demo.Person.prototype = {

getFirstName: function() {
return this._firstName;
},

getLastName: function() {
return this._lastName;
},

getName: function() {
return this._firstName + ' ' + this._lastName;
},

dispose: function() {
alert('bye ' + this.getName());
}
}
Demo.Person.registerClass('Demo.Person', null, Sys.IDisposable);

// Notify ScriptManager that this is the end of the script.
if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();


To see a Web page that uses the preceding script file, click the Run It button.

Access Modifiers

Most object-oriented programming languages include the concept of access modifiers, which allow you to specify under what contexts a class or member is available, such as to outside programs, internal classes within the same namespace, or only within a specific code block. There are no access modifiers in JavaScript, however ASP.NET AJAX follows the convention that members with names that start with the underscore character ("_") are considered private and not accessed outside the class they are a part of.
Inheritance

Inheritance is the ability of one class to derive from another class. A derived class automatically inherits all the fields, properties, methods and events of the base class. A derived class also adds new members or overrides existing members of the base class to change their behavior.

The following example contains two classes defined in script: Person and Employee, where Employee derives from Person. Both classes illustrate the use of private fields, and both have public properties and methods. In addition, Employee overrides the toString implementation of the Person class, and uses the base class functionality.
cs

Type.registerNamespace("Demo");

Demo.Person = function(firstName, lastName, emailAddress) {
this._firstName = firstName;
this._lastName = lastName;
this._emailAddress = emailAddress;
}

Demo.Person.prototype = {
getFirstName: function() {
return this._firstName;
},

getLastName: function() {
return this._lastName;
},

getEmailAddress: function() {
return this._emailAddress;
},
setEmailAddress: function(emailAddress) {
this._emailAddress = emailAddress;
},

getName: function() {
return this._firstName + ' ' + this._lastName;
},

dispose: function() {
alert('bye ' + this.getName());
},

sendMail: function() {
var emailAddress = this.getEmailAddress();

if (emailAddress.indexOf('@') < 0) {
emailAddress = emailAddress + '@example.com';
}
alert('Sending mail to ' + emailAddress + ' ...');
},

toString: function() {
return this.getName() + ' (' + this.getEmailAddress() + ')';
}
}
Demo.Person.registerClass('Demo.Person', null, Sys.IDisposable);
Demo.Employee = function(firstName, lastName, emailAddress, team, title) {
Demo.Employee.initializeBase(this, [firstName, lastName, emailAddress]);

this._team = team;
this._title = title;
}

Demo.Employee.prototype = {

getTeam: function() {
return this._team;
},
setTeam: function(team) {
this._team = team;
},

getTitle: function() {
return this._title;
},
setTitle: function(title) {
this._title = title;
},
toString: function() {
return Demo.Employee.callBaseMethod(this, 'toString') + '\r\n' + this.getTitle() + '\r\n' + this.getTeam();
}
}
Demo.Employee.registerClass('Demo.Employee', Demo.Person);

To see a Web page that uses the preceding script file, click the Run It button.

Interfaces

An interface is a logical structure that defines the input and output requirements of classes that implement it. This enables a function to interact with classes that implement the same interface regardless of what other functionality the class implements.

The following example defines a Tree base class and an IFruitTree interface. Apple and Banana, two derived classes, implement the IFruitTree interface, but the Pine class does not.
cs

Type.registerNamespace("Demo.Trees");

Demo.Trees.IFruitTree = function() {}
Demo.Trees.IFruitTree.Prototype = {
bearFruit: function(){}
}
Demo.Trees.IFruitTree.registerInterface('Demo.Trees.IFruitTree');


Demo.Trees.Tree = function(name) {
this._name = name;
}
Demo.Trees.Tree.prototype = {
returnName: function() {
return this._name;
},

toStringCustom: function() {
return this.returnName();
},

makeLeaves: function() {}
}
Demo.Trees.Tree.registerClass('Demo.Trees.Tree');


Demo.Trees.FruitTree = function(name, description) {
Demo.Trees.FruitTree.initializeBase(this, [name]);
this._description = description;
}
Demo.Trees.FruitTree.prototype.bearFruit = function() {
return this._description;
}
Demo.Trees.FruitTree.registerClass('Demo.Trees.FruitTree', Demo.Trees.Tree, Demo.Trees.IFruitTree);

Demo.Trees.Apple = function() {
Demo.Trees.Apple.initializeBase(this, ['Apple', 'red and crunchy']);
}
Demo.Trees.Apple.prototype = {
makeLeaves: function() {
alert('Medium-sized and desiduous');
},
toStringCustom: function() {
return 'FruitTree ' + Demo.Trees.Apple.callBaseMethod(this, 'toStringCustom');
}
}
Demo.Trees.Apple.registerClass('Demo.Trees.Apple', Demo.Trees.FruitTree);

Demo.Trees.GrannySmith = function() {
Demo.Trees.GrannySmith.initializeBase(this);
// You must set the _description feild after initializeBase
// or you will get the base value.
this._description = 'green and sour';
}
Demo.Trees.GrannySmith.prototype.toStringCustom = function() {
return Demo.Trees.GrannySmith.callBaseMethod(this, 'toStringCustom') + ' ... its GrannySmith!';
}
Demo.Trees.GrannySmith.registerClass('Demo.Trees.GrannySmith', Demo.Trees.Apple);


Demo.Trees.Banana = function(description) {
Demo.Trees.Banana.initializeBase(this, ['Banana', 'yellow and squishy']);
}
Demo.Trees.Banana.prototype.makeLeaves = function() {
alert('Big and green');
}
Demo.Trees.Banana.registerClass('Demo.Trees.Banana', Demo.Trees.FruitTree);



Demo.Trees.Pine = function() {
Demo.Trees.Pine.initializeBase(this, ['Pine']);
}
Demo.Trees.Pine.prototype.makeLeaves = function() {
alert('Needles in clusters');
}
Demo.Trees.Pine.registerClass('Demo.Trees.Pine', Demo.Trees.Tree);


To see a Web page that uses the preceding script file, click the Run It button.

Enumerations

An enumeration is a class that contains a set of named integer constants. You access the values like properties, as in the following example:

myObject.color = myColorEnum.red

Enumerations provide an easily readable alternative to integer representations. For more information about enumerations in ASP.NET AJAX, see registerEnum Method.

The following example defines an enumeration of named colors that represent hexadecimal values.
cs

Type.registerNamespace("Demo");

// Define an enumeration type and register it.
Demo.Color = function(){};
Demo.Color.prototype =
{
Red: 0xFF0000,
Blue: 0x0000FF,
Green: 0x00FF00,
White: 0xFFFFFF
}
Demo.Color.registerClass("Demo.Color");

To see a Web page that uses the preceding script file, click the Run It button.
Reflection

Reflection is the ability to examine the structure and components of a program at run time. The APIs that implement reflection are extensions of the Type class. These methods enable you to collect information about an object, such as what it inherits from, whether it implements a particular interface, and whether it is an instance of a particular class.
Creating Custom Client Script in ASP.NET AJAX
Introduction

Microsoft ASP.NET AJAX provides features that help you create client script and integrate it into ASP.NET applications. This includes a type system and extensions to existing ECMAScript (JavaScript) objects to give them the richness of .NET Framework classes. It also provides the ScriptManager control to manage these script libraries and any custom script in your application.
Creating Scripts

The Microsoft AJAX Library includes features that contribute to a richer, more powerful JavaScript development experience.

The Type class adds object-oriented features such as classes and inheritance to JavaScript programming. Any JavaScript object that is registered by using the Type class automatically has access to this functionality. For more information, see Extending JavaScript with ASP.NET AJAX.

The following example shows how to use the Type class to create and register a namespace and a class in a JavaScript file:
cs

Type.registerNamespace("Demo");

Demo.Person = function(firstName, lastName, emailAddress) {
this._firstName = firstName;
this._lastName = lastName;
this._emailAddress = emailAddress;
}

Demo.Person.prototype = {

getFirstName: function() {
return this._firstName;
},

getLastName: function() {
return this._lastName;
},

getName: function() {
return this._firstName + ' ' + this._lastName;
},

dispose: function() {
alert('bye ' + this.getName());
}
}
Demo.Person.registerClass('Demo.Person', null, Sys.IDisposable);

// Notify ScriptManager that this is the end of the script.
if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();


Extensions to JavaScript base types provide additional functionality for those types. For more information about these extensions, see the following topics:

*

Array Type Extensions
*

Boolean Type Extensions
*

Date Type Extensions
*

Error Type Extensions
*

Number Type Extensions
*

Object Type Extensions
*

String Type Extensions

The Sys.Debug class provides extensive debugging capabilities. For more information, see ASP.NET AJAX Debugging and Tracing Overview and the Sys.Debug class overview.

Component developers can create debug and retail versions of script files that are automatically managed by the ScriptManager control. You can identify debug versions of script files by including ".debug" as part of the script file name. For example, the following script file names identify retail and debug versions of a file:

*

Retail: MyScript.js
*

Debug: MyScript.debug.js

Integrating Client Script into ASP.NET Web Applications

Any ASP.NET Web page can access a script file by referring to it in a

However, a script invoked in this manner cannot participate in partial-page rendering or access certain components of the Microsoft AJAX Library. To make a script file available for partial-page rendering in an ASP.NET AJAX Web application, the script must be registered with the ScriptManager control on the page. To register a script file, create a ScriptReference object that points to the file question and that adds it to the Scripts collection. The following example shows how to do this in markup:







For script files to be processed correctly by the ScriptManager control, each file must include a call to the Sys.Application.notifyScriptLoaded method at the end of the file. This call notifies the application that the file has finished loading. The following example shows the code to use for this purpose:

if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

If your script is embedded in an assembly, you do not have to include a notification statement in the script. You also do not have to specify a path attribute in the script reference. However, you must provide the name of the assembly without the file name extension, as shown in the following example:




Name="MyScript.js" Assembly="MyScriptAssembly"/>



note

This scenario is not common for page developers, because most controls with embedded script libraries reference their scripts internally. For more information, see Embedding a JavaScript File as a Resource in an Assembly.

You can also register scripts programmatically by creating script references in code and then adding them to the Scripts collection. For more information, see Dynamically Assigning ASP.NET AJAX Script References.

You can register scripts that are required for partial-page updates by using the registration methods of the ScriptManager control. You can use these methods in the following ways:

*

To generate client script in code, build a block of script as a string and pass it to the RegisterClientScriptBlock) method.
*

To add standalone script files that have no Microsoft AJAX Library dependencies, use the RegisterClientScriptInclude) method.
*

To add script files that are embedded in an assembly, use the RegisterClientScriptResource method.
note

Scripts that are registered by using these methods do not have localization support.

For a complete list of script-registration methods and their uses, see the ScriptManager control overview.

Any script blocks or inline script that you are registering must be inside the page's
element. Otherwise, the script is not registered with the ScriptManager control and cannot access ASP.NET AJAX functionality. For more information, see initialize Method.
Embedding a JavaScript File as a Resource in an Assembly
Introduction

In this tutorial, you will include a JavaScript file as an embedded resource in an assembly. You embed a JavaScript file when you have a client-script component that must be distributed with an assembly that you have created. For example, you might create a custom ASP.NET server control that uses JavaScript files to implement ASP.NET AJAX functionality. You can embed the JavaScript files in the assembly, and they can then be referenced from a Web application that registers the assembly.

To implement the procedures in this tutorial you need:

*

Microsoft Visual Studio 2005.
note

You cannot use Visual Web Developer 2005 Express Edition, because Visual Web Developer Express Edition does not enable you to create the class library project required in the tutorial.
*

The latest release of Microsoft ASP.NET AJAX installed and configured. For more information, see Installing ASP.NET AJAX.

Creating an Assembly that Contains an Embedded JavaScript File

To begin, you will create a file that contains the JavaScript code that you want to embed in the assembly.
To embed a client script file in an assembly

1.

In Visual Studio, create a new class library project named SampleControl.
2.

Add references to the System.Web, System.Drawing, and System.Web.Extensions namespaces to the project.
3.

Add a new JScript file named UpdatePanelAnimation.js to the project.
4.

Add the following code to the UpdatePanelAnimation.js file:
CS

BorderAnimation = function(color) {
this._color = color;
}

BorderAnimation.prototype = {
animate: function(panelElement) {
var s = panelElement.style;
s.borderWidth = '2px';
s.borderColor = this._color;
s.borderStyle = 'solid';

window.setTimeout(
function() {{
s.borderWidth = 0;
}},
500);
}
}


vb

BorderAnimation = function(color) {
this._color = color;
}

BorderAnimation.prototype = {
animate: function(panelElement) {
var s = panelElement.style;
s.borderWidth = '2px';
s.borderColor = this._color;
s.borderStyle = 'solid';

window.setTimeout(
function() {{
s.borderWidth = 0;
}},
500);
}
}


The code contains a JavaScript function that temporarily displays a colored border around an UpdatePanel control.
5.

In the Properties window for the UpdatePanelAnimation.js file, set Build Action to Embedded Resource.
Set script file to embedded resource
6.

Add a class file named CustomControl to the project.
7.

Replace any code in the CustomControl file with the following code:
CS

using System;
using System.Drawing;
using System.Web.UI;
using System.Web;
using System.Globalization;

namespace SampleControl
{
public class UpdatePanelAnimationWithClientResource : Control
{
private string _updatePanelID;
private Color _borderColor;
private Boolean _animate;
public Color BorderColor
{
get
{
return _borderColor;
}
set
{
_borderColor = value;
}
}

public string UpdatePanelID
{
get
{
return _updatePanelID;
}
set
{
_updatePanelID = value;
}
}

public Boolean Animate
{
get
{
return _animate;
}
set
{
_animate = value;
}
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (Animate)
{

UpdatePanel updatePanel = (UpdatePanel)FindControl(UpdatePanelID);

string script = String.Format(
CultureInfo.InvariantCulture,
@"
Sys.Application.add_load(function(sender, args) {{
var {0}_borderAnimation = new BorderAnimation('{1}');
var panelElement = document.getElementById('{0}');
if (args.get_isPartialLoad()) {{
{0}_borderAnimation.animate(panelElement);
}}
}})
",
updatePanel.ClientID,
ColorTranslator.ToHtml(BorderColor));


ScriptManager.RegisterStartupScript(
this,
typeof(UpdatePanelAnimationWithClientResource),
ClientID,
script,
true);
}
}
}
}

vb

Imports System.Web.UI
Imports System.Drawing
Imports System.Globalization

Public Class UpdatePanelAnimationWithClientResource
Inherits Control

Private _updatePanelID As String
Private _borderColor As Color
Private _animate As Boolean

Public Property BorderColor() As Color
Get
Return _borderColor
End Get
Set(ByVal value As Color)
_borderColor = value
End Set
End Property

Public Property UpdatePanelID() As String
Get
Return _updatePanelID
End Get
Set(ByVal value As String)
_updatePanelID = value
End Set
End Property

Public Property Animate() As Boolean
Get
Return _animate
End Get
Set(ByVal value As Boolean)
_animate = value
End Set
End Property

Protected Overrides Sub OnPreRender(ByVal e As EventArgs)
MyBase.OnPreRender(e)
If (Animate) Then

Dim updatePanel As UpdatePanel = CType(Me.FindControl(UpdatePanelID), UpdatePanel)

Dim script As String = String.Format( _
CultureInfo.InvariantCulture, _
"Sys.Application.add_load(function(sender, args) {{var {0}_borderAnimation = new BorderAnimation('{1}');var panelElement = document.getElementById('{0}');if (args.get_isPartialLoad()) {{{0}_borderAnimation.animate(panelElement);}}}});", _
updatePanel.ClientID, _
ColorTranslator.ToHtml(BorderColor))


ScriptManager.RegisterStartupScript( _
Me, _
GetType(UpdatePanelAnimationWithClientResource), _
ClientID, _
script, _
True)
End If
End Sub
End Class

This class contains properties for customizing the border that is displayed around the UpdatePanel control. The code also registers JavaScript code to use in a Web page. The code creates a handler for the load event of the Sys.Application object. The animate function in the UpdatePanelAnimation.js file is called when a partial-page update is processed.
8.

Add the following line to the AssemblyInfo file.
CS

[assembly: System.Web.UI.WebResource("SampleControl.UpdatePanelAnimation.js", "application/x-javascript")]

vb



note

The AssemblyInfo.vb file is in the My Project node of Solution Explorer. If you do not see any files in the My Project node, in the Project menu, click Show All Files. The AssemblyInfo.cs file is in the Properties node of Solution Explorer.

The WebResource definition must include the default namespace of the assembly and the name of the .js file.
9.

Build the project.

When compilation finishes, you will have an assembly named SampleControl.dll. The JavaScript code in the UpdatePanelAnimation.js file is embedded in this assembly as a resource.

Referencing the Embedded Script File

You can now reference the embedded script file in a Web application.
note

Although you can create the class library project and the Web site in the same Visual Studio solution, in this tutorial it is not assumed that you are doing this. Having the projects in separate solutions emulates how a control developer and a page developer would work separately. However, for convenience you can create both projects in the same solution and make small adjustments to procedures in the tutorial.
To reference the embedded script file

1.

In Visual Studio, create a new AJAX-enabled Web site.
2.

Create a Bin folder in the root directory of the Web site.
3.

Copy SampleControl.dll from the Bin\Debug or Bin\Release directory of the class library project to the Bin folder of the Web site.
note

If you created the class library project and the Web site in the same Visual Studio solution, you can add a reference from the class library project to the Web site. For details, see How to: Add a Reference to a Visual Studio Project in a Web Site.
4.

Replace the code in the Default.aspx file with the following code:
CS

<%@ Page Language="C#" %>
<%@ Register TagPrefix="Samples" Namespace="SampleControl" Assembly="SampleControl" %>


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">












EnablePartialRendering="True"
runat="server">







ID="UpdatePanelAnimator1"
BorderColor="Green"
Animate="true"
UpdatePanelID="UpdatePanel1"
runat="server" >


UpdateMode="Conditional"
runat="server">


runat="server">








vb

<%@ Page Language="VB" AutoEventWireup="true" %>

<%@ Register TagPrefix="Samples" Namespace="SampleControl" Assembly="SampleControl" %>


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">










EnablePartialRendering="True"
runat="server">







ID="UpdatePanelAnimator1"
BorderColor="Green"
Animate="true"
UpdatePanelID="UpdatePanel1"
runat="server" >


UpdateMode="Conditional"
runat="server">


runat="server">








This code includes an element that references the assembly and the name of the .js file that you created in the previous procedure. The name of the .js file includes a prefix that references the default namespace of the assembly.
5.

Run the project, and in the page, click dates in the calendar.

Every time that you click a date in the calendar, you see a green border around the UpdatePanel control.

Review

This tutorial showed you how to embed a JavaScript file as a resource in an assembly. The embedded script file can be accessed in a Web application that contains the assembly.

The next step is to learn how to embed localized resources in an assembly for use in client script. For more information, see Embedding Localized Resources for a JavaScript File.

Embedding Localized Resources for a JavaScript File
Introduction

In this tutorial you will include a JavaScript file as an embedded resource in an assembly, and also include localized strings for use in the JavaScript file. You embed a JavaScript file in an assembly when you have a client script component that must be distributed with the assembly. The JavaScript file can be referenced from a Web application that registers the assembly. You embed localized resources when you have to modify values that are used by the JavaScript file for different languages and cultures.

To implement the procedures in this tutorial you need:

*

Microsoft Visual Studio 2005.
note

You cannot use Visual Web Developer 2005 Express Edition, because Visual Web Developer Express Edition does not enable you to create the class library project required in the tutorial.
*

The latest release of Microsoft ASP.NET AJAX installed and configured. For more information, see Installing ASP.NET AJAX.

Creating an Assembly that Contains an Embedded JavaScript File

You will begin by creating an assembly (.dll file) that contains the JavaScript file that you want to treat as a resource. You will do so by creating a class library project in Visual Studio, which creates an assembly as its output.
To embed a client script file and resources in an assembly

1.

In Visual Studio, create a new class library project named LocalizingScriptResources.
2.

Add references to the System.Web and System.Web.Extensions namespaces to the project.
3.

Add a new JScript file to the project named CheckAnswer.js.
4.

Add the following code to the CheckAnswer.js file.
cs

function CheckAnswer()
{
var firstInt = $get('firstNumber').innerText;
var secondInt = $get('secondNumber').innerText;
var userAnswer = $get('userAnswer');

if ((Number.parseLocale(firstInt) + Number.parseLocale(secondInt)) == userAnswer.value)
{
alert(Answer.Correct);
return true;
}
else
{
alert(Answer.Incorrect);
return false;
}
}

vb

function CheckAnswer()
{
var firstInt = $get('firstNumber').innerText;
var secondInt = $get('secondNumber').innerText;
var userAnswer = $get('userAnswer');

if ((Number.parseLocale(firstInt) + Number.parseLocale(secondInt)) == userAnswer.value)
{
alert(Answer.Correct);
return true;
}
else
{
alert(Answer.Incorrect);
return false;
}
}

The script checks the user's result for adding two numbers. It uses the alert function to let the user know whether the answer is correct. The message displayed in the alert dialog box is read from a localized resource without a postback to the server.

A placeholder named Answer is used in the script to identify which resource files contain the localized strings. The Answer placeholder will be defined later in this procedure.
5.

In the Properties window for CheckAnswer.js, set Build Action to Embedded Resource.
Set script file to embedded resource
6.

Add a class to the project named ClientVerification.
7.

Replace any code in the ClientVerification file with the following code:
cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Resources;


namespace LocalizingScriptResources
{
public class ClientVerification : Control
{
private Button _button;
private Label _firstLabel;
private Label _secondLabel;
private TextBox _answer;
private int _firstInt;
private int _secondInt;

protected override void CreateChildControls()
{
Random random = new Random();
_firstInt = random.Next(0, 20);
_secondInt = random.Next(0, 20);

ResourceManager rm = new ResourceManager("LocalizingScriptResources.VerificationResources", this.GetType().Assembly);
Controls.Clear();

_firstLabel = new Label();
_firstLabel.ID = "firstNumber";
_firstLabel.Text = _firstInt.ToString();

_secondLabel = new Label();
_secondLabel.ID = "secondNumber";
_secondLabel.Text = _secondInt.ToString();

_answer = new TextBox();
_answer.ID = "userAnswer";

_button = new Button();
_button.ID = "Button";
_button.Text = rm.GetString("Verify");
_button.OnClientClick = "return CheckAnswer();";

Controls.Add(_firstLabel);
Controls.Add(new LiteralControl(" + "));
Controls.Add(_secondLabel);
Controls.Add(new LiteralControl(" = "));
Controls.Add(_answer);
Controls.Add(_button);
}
}
}

vb

Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Resources

Public Class ClientVerification
Inherits Control

Private _button As Button
Private _firstLabel As Label
Private _secondLabel As Label
Private _answer As TextBox
Private _firstInt As Int32
Private _secondInt As Int32


Protected Overrides Sub CreateChildControls()
Dim random = New Random()
_firstInt = random.Next(0, 20)
_secondInt = random.Next(0, 20)

Dim rm = New ResourceManager("LocalizingScriptResources.VerificationResources", Me.GetType().Assembly)
Controls.Clear()

_firstLabel = New Label()
_firstLabel.ID = "firstNumber"
_firstLabel.Text = _firstInt.ToString()

_secondLabel = New Label()
_secondLabel.ID = "secondNumber"
_secondLabel.Text = _secondInt.ToString()

_answer = New TextBox()
_answer.ID = "userAnswer"

_button = New Button()
_button.ID = "Button"
_button.Text = rm.GetString("Verify")
_button.OnClientClick = "return CheckAnswer();"

Controls.Add(_firstLabel)
Controls.Add(New LiteralControl(" + "))
Controls.Add(_secondLabel)
Controls.Add(New LiteralControl(" = "))
Controls.Add(_answer)
Controls.Add(_button)
End Sub

End Class

The code creates a custom ASP.NET control. It contains two Label controls, a TextBox control, and a Button control. The code displays two randomly generated integers and provides a text box for an answer. When the button is clicked, the CheckAnswer function is called.
8.

Add a resources file to the project and name it VerificationResources.resx.
9.

Add a string resource named Correct with a value of "Yes, your answer is correct."
10.

Add a string resource named Incorrect with a value of "No, your answer is incorrect."
11.

Add a string resource named Verify with a value of "Verify Answer".

This resource is not retrieved by using client script. Instead, it is used to set to the Text property of the Button control when the button is created.
12.

Save and close the VerificationResources.resx file.
13.

Add a resources file named VerificationResources.it.resx to the project.

This file will contain resource strings in Italian.
14.

Add a string resource named Correct with a value of "Si, la risposta e’ corretta."
15.

Add a string resource named Incorrect with a value of "No, la risposta e’ sbagliata."
16.

Add a string resource named Verify with a value of "Verificare la risposta".

As with the "Verify" resource that you created in English, this resource is not retrieved by using client script. Instead, it is used to set the Text property of the Button control when the button is created.
17.

Save and close the VerificationResources.it.resx file.
18.

Add the following line to the AssemblyInfo file. You can specify any name for the type name in the ScriptResourceAttribute attribute, but it must match the type name that is used in the client script. In this example, it is set to Answer.
cs

[assembly: System.Web.UI.WebResource("LocalizingScriptResources.CheckAnswer.js", "application/x-javascript")]
[assembly: System.Web.UI.ScriptResource("LocalizingScriptResources.CheckAnswer.js", "LocalizingScriptResources.VerificationResources", "Answer")]

vb




note

The AssemblyInfo.vb file is in the My Project node of Solution Explorer. If you do not see any files in the My Project node, in the Project menu, click Show All Files. The AssemblyInfo.cs file is in the Properties node of Solution Explorer.

The WebResource definition must include the default namespace of the assembly and the name of the .js file. The ScriptResource definition does not include the file name extension or the localized .resx files.
19.

Build the project.

When compilation finishes, you will have an assembly named LocalizingScriptResources.dll. The JavaScript code in the CheckAnswer.js file and the resources in the two .resx files are embedded in this assembly as resources.

You will also have an assembly named LocalizingScriptResources.resources.dll (a satellite assembly) that contains the Italian resources for server code.

Referencing the Embedded Script and Resources

You can now use the assembly in an AJAX-enabled ASP.NET Web site. You will be able to read the .js file and the resource values in client script.
note

Although you can create the class library project and the Web site in the same Visual Studio solution, in this tutorial it is not assumed that you are doing this. Having the projects in separate solutions emulates how a control developer and a page developer would work separately. However, for convenience you can create both projects in the same solution and make small adjustments to procedures in the tutorial.
To reference the embedded script and resources

1.

In Visual Studio, create a new AJAX-enabled Web site.
2.

Add a Bin folder under the Web site root.
3.

Add the LocalizingScriptResources.dll assembly from the class library project to the Bin folder.
note

If you created the class library project and the Web site in the same Visual Studio solution, you can add a reference from the class library project to the Web site. For details, see How to: Add a Reference to a Visual Studio Project in a Web Site.
4.

Create a folder in the Bin folder and give it the name it (for Italian).
5.

Add the LocalizingScriptResources.resources.dll satellite assembly from the it folder in the LocalizingScriptResources project to the it folder in the Web site.
6.

Add a new ASP.NET Web page to the project.
7.

Replace the code in the page with the following code:
cs

<%@ Page Language="C#" AutoEventWireup="true" UICulture="auto" Culture="auto" %>
<%@ Register TagPrefix="Samples" Namespace="LocalizingScriptResources" Assembly="LocalizingScriptResources" %>




























vb

<%@ Page Language="VB" AutoEventWireup="true" UICulture="auto" Culture="auto" %>
<%@ Register TagPrefix="Samples" Namespace="LocalizingScriptResources" Assembly="LocalizingScriptResources" %>




























The control that you created in the LocalizingScriptResources project is included on the page. This control displays two numbers for the user to add and a TextBox control for the user to enter an answer. It also displays a button that calls the script in the CheckAnswer function when the button is clicked. The CheckAnswer function runs in the browser and displays a localized message that states whether the answer is correct.

You must set the EnableScriptLocalization property of the ScriptManager object to true to enable the ScriptManager control to retrieve localized resources. You must also set the culture and UI culture to "auto" to display the strings that are based on the browser's settings.

The page contains a DropDownList control that you can use to change the language settings without changing the settings in the browser. When the SelectedIndex property of the DropDownList control changes, the CurrentUICulture property of the CurrentThread instance is set to the value that you have selected.
8.

Run the project.

You will see an addition problem with two randomly generated numbers and a TextBox control for entering an answer. When you enter an answer and click the Verify Answer button, you see the response in a message window that tells you whether the answer is correct. By default, the response will be returned in English.

However, if you have set Italian as your preferred language in the browser, the answer will be in Italian. You can change the language for the response by selecting a language in the DropDownList control or by changing the preferred language in the browser.

Review

This tutorial introduced the concept of embedding a JavaScript file as a resource in an assembly and of including localized strings. The embedded script file can be referenced and accessed in a Web application that contains the assembly. The localized strings will be displayed based on the language setting in the browser or on the language provided by the user.

Debugging and Tracing
ASP.NET AJAX Debugging and Tracing Overview
Introduction

Microsoft ASP.NET AJAX applications contain a mix of server code and client code. The browser can also request additional data asynchronously. This can make debugging AJAX-enabled Web applications challenging. This overview discusses some techniques and tools that can help you debug your code more easily.
note

With the exception of Visual Studio and Internet Explorer, the programs mentioned in this topic are third-party tools and are not supported by Microsoft. Please see the tool's Web site for licensing and support information.

This topic contains:

*

Scenarios
*

Background
*

Class Reference

Scenarios

You can use the following approaches to debug an ASP.NET AJAX application at different stages of development:

*

Enable debugging in the configuration file.
*

Use tracing on the server.
*

Use the methods of the Sys.Debug class to set breakpoints and handle trace output.
*

Enable debugging in your browser.
*

Attach the Visual Studio debugger to your Internet Explorer instance, or use external tools to debug in other browsers.
*

Use external tools to capture HTTP traffic.

Back to top
Background

The ASP.NET AJAX architecture provides a model for release and debug modes. Release mode provides error checking and exception handling optimized for performance, with minimized script size. Debug mode provides more robust debugging features, such as type and argument checking. If you create debug versions of your client scripts or script resources, ASP.NET runs the debug versions when the application is in debug mode. This enables you to throw exceptions in debug scripts while minimizing the size of release code.

A debug helper class, Sys.Debug, provides methods for displaying objects in readable form at the end of a Web page. It also shows trace messages, enables you to use assertions, and lets you break into the debugger. An extended Error Object object API provides helpful exception details with support for release and debug modes.

The following sections provide detail about the techniques and tools that you can use for debugging and tracing.
Configuring the Application for Debugging

To enable debugging, add a compilation element to the site's root Web.config file, and then set its debug attribute to true. For more information, see compilation Element (ASP.NET Settings Schema).

The following example shows a section from a Web.config file that has the debug attribute set.








When debugging is enabled, ASP.NET AJAX uses a debug version of the client libraries.
Setting the Application from Debug to Release Mode for Deployment

When you deploy a release version of an AJAX-enabled ASP.NET application, make sure that it is set to release mode. This makes sure that ASP.NET uses the performance-optimized release version of the ASP.NET AJAX libraries. If you have created debug and release versions of your custom scripts and script resources, ASP.NET also uses the release versions. To set the application to release mode, do the following:

*

In the Web.config file, if the compilation element contains a debug attribute, make sure that the debug attribute is set to false.
*

Make sure that any Web page that contains a ScriptManager control has its ScriptMode property set to Release.

The debug attribute of the @ Page directive does not affect ASP.NET AJAX applications. The ScriptManager control uses only the settings in the Web.config file and in its IsDebuggingEnabled and ScriptMode properties to determine whether to render debug scripts.
Tracing on the Server

If you are using tracing on the server to debug Web pages that have partial-page rendering enabled, you should use the trace viewer (Trace.axd) to display trace output. You can append trace output to the end of the page, and it is displayed the first time the page is rendered. However, the trace display is not updated as a result of asynchronous postbacks, because only the contents of UpdatePanel controls that have to be refreshed will change. For more information about how to use the trace viewer, see ASP.NET Tracing.
note

Partial-page rendering is enabled when the page contains a ScriptManager control with its EnablePartialRendering property set to true. The page must also contain one or more UpdatePanel controls.
Debug Helper Class

Microsoft AJAX Library provides the Sys.Debug class for debugging client applications. By calling methods of the Sys.Debug class, you can display objects in readable form at the end of the page, show trace messages, use assertions, and break into the debugger.

If you are using Visual Studio and Internet Explorer, you can attach the Visual Studio debugger to the browser and view debugger trace messages in the Output window. If you are not using Visual Studio, you can view debugger trace messages in Internet Explorer by creating a textarea element on the page and setting its ID to TraceConsole. In Mozilla Firefox, you can view debugger trace messages by using tools that are available as extensions. The Apple Safari and Opera browsers display trace messages in their respective debugging consoles.

The following table lists the methods of the Sys.Debug class.

Sys.Debug.assert(condition, message, displayCaller)

Checks for a condition, and if the condition is false, displays a message and prompts the user to break into the debugger.
Sys.Debug.clearTrace()

Clears all trace messages from the TraceConsoletextarea element.
Sys.Debug.traceDump(object, name)

Dumps an object to the debugger console and to the TraceConsoletextarea element, if available.
Sys.Debug.fail(message)

Displays a message in the debugger's output window and breaks into the debugger.
Sys.Debug.trace(text)

Appends a text line to the debugger console and to the TraceConsoletextarea element, if available.

The following example shows how to call methods of the Sys.Debug class:
Run View
Configuring Internet Explorer for Debugging

By default, Internet Explorer ignores problems it encounters in JavaScript. You can enable debugging by using the following procedure.
To enable debugging in Internet Explorer

1.

In the Tools menu, click Internet Options.
2.

In the Advanced tab, clear the Disable Script Debugging (Internet Explorer) check box and the Disable Script Debugging (Other) check box.
3.

Select the Display a notification about every script error check box.
4.

To turn off "friendly" error messages, clear the Show friendly HTTP error messages check box.

If "friendly" error message are enabled and if an HTTP 500 error response from the server is less than 513 bytes long, Internet Explorer masks the content. In place of the error information, Internet Explorer displays a message that is meant for end users, not developers.

Attaching the Visual Studio Debugger to Internet Explorer

To debug client script, you must attach a debugger to Internet Explorer. In Visual Studio, if you start your application for debugging (by pressing F5 or using the Start Debugging command in the Debug menu), the debugger is attached automatically.

You can also attach the Visual Studio debugger to Internet Explorer when the application is already running. To do so, in the Debug menu, click Attach to Process.... In the Attach to Process dialog box, select the instance of Internet Explorer (iexplore.exe) that you want to attach the debugger to.
note

If Internet Explorer is configured for debugging, the Type column for the relevant instance of Internet Explorer displays Script, x86. If you see only x86 in the Type column, make sure that Internet Explorer is configured for debugging.

If Internet Explorer encounters a script error and is configured for script debugging, but it is not currently attached to a debugger, the browser prompts you to select a debugger. You can either continue without debugging or attach a debugger and step through the code.
Internet Explorer Known Debugging Issues and Workarounds

When you debug ASP.NET AJAX applications that use Internet Explorer, be aware of the following issues and workarounds:

*

After the Visual Studio debugger is attached to Internet Explorer, you can see a list of the scripts that are being debugged in the Visual Studio Script Explorer window. (To display this window, in the Debug menu, click Windows, and then click Script Explorer). The ASP.NET AJAX client library will appear as a resource starting with ScriptResource.axd?..., which the server generates dynamically from the ASP.NET AJAX assembly. A known bug in Visual Studio might prevent you from opening the file. If Visual Studio displays an error message to that effect, or if it ignores clicks on the file name, close all script files that are open. You can then open the page and select the script files that you want to debug.
*

You cannot set breakpoints in JavaScript code inside script elements in an ASP.NET page until after the debugger has stepped into JavaScript code on that page. To work around this issue, set the breakpoint on the function that the call comes from, and step into the code on the ASP.NET Web page. After the debugger has stopped on a line of JavaScript code in the page, you can set breakpoints as usual. Another way to have the debugger recognize scripts in an ASP.NET page is to create a method in the ASP.NET page file that calls the Sys.Debug.fail method. When you call this method, the debugger will stop on the call to Sys.Debug.fail and let you set breakpoints elsewhere. A third alternative is to put all your custom code in external JavaScript files.
*

Visual Studio enables you to set breakpoints on the first line of a regular JavaScript function, but not on the first line of anonymous methods, which ASP.NET AJAX uses. If an anonymous method contains only one line of code, or if you must set a breakpoint on the first line of an anonymous method, insert a dummy line of code. You can then set the breakpoint on the second line of the method.

Capturing HTTP Traffic

When you develop Web applications, it is often useful to monitor the HTTP traffic between the server and the client. A tool that can perform this task is Fiddler, which you can get from the Fiddler PowerToy page on the MSDN Web site. Fiddler runs as a proxy that logs all HTTP traffic. It supports Internet Explorer and other browsers. By using Fiddler, you can examine each request and response, which includes headers, cookies, and message contents.
Debugging in Mozilla Firefox

Mozilla Firefox is not integrated with the Visual Studio debugger. As a result, you cannot use the Visual Studio debugger to step through client code that is running in Firefox. However, Firefox supports some debugging functionality, such as a JavaScript console. You can also install the following extensions available from Mozilla that can enhance your debugging capabilities:

*

Fire B ug enables you to step through client script and examine HTML DOM elements. It also provides a script console, a command line, and other tools.
*

The JavaScript Debugger (also known as "Venkman") provides a JavaScript debugging environment that includes a source-code browser and other features.
*

The Web Developer extension enables you to inspect the DOM and CSS styles.

Fiddler also works with Firefox. However, you must configure Firefox to route HTTP requests through the proxy running on port 8888 on the local computer. For more information, see the "Configuring Clients" page on the Fiddler Web site.

Back to top
Class Reference

Debug Class

Provides methods that define breakpoints and handle trace output.

Web Services
Asynchronous Communication Layer Overview
Introduction

The Microsoft ASP.NET AJAX asynchronous communication layer enables a browser to call Web service methods on the server by using ECMAScript (JavaScript). It exposes APIs that JavaScript functions can use in any browser to call Web service methods on the server. These APIs use the functionality for browser asynchronous behavior provided by the browser's XMLHTTP object. For more information about the XMLHTTP object, see About Native XMLHTTP on the MSDN Web site.

The asynchronous communication layer provides a clear separation between the business and data tiers on the server, and the presentation tier on the client. The browser has control of the presentation tier and provides a rich and responsive user interface, and the server performs the business and data tier tasks.

This topic contains the following information:

*

Asynchronous Communication Layer Features
*

Background
*

Code Examples
*

Class Reference
*

Additional Resources
*

What's New

Asynchronous Communication Layer Features

The asynchronous communication layer offers the following features:

*

Enables JavaScript code to perform asynchronous calls to the server.
*

Can invoke methods in Web services that are implemented as .asmx files.
*

Can invoke ASP.NET static page methods as if they were Web service methods.
*

Can be configured to enable and disable the ability to call Web services from ASP.NET AJAX applications.
*

Supports a variety of serialization formats for passing data between the browser and the server, including JavaScript Object Notation (JSON), string data, and XML data.
*

Makes Web service interactions easier by generating JavaScript proxies for Web services that can be accessed from client script.
*

Provides extensibility for client executors that are used by the proxy objects. An executor is a component that functions as an interface between a client Web request and the network or other media. You can write your own executor that plugs into the asynchronous communication layer. For more information, see XMLHttpExecutor Class.
*

Can be used with Medium trust.

Back to top
Background

The asynchronous communication layer provides an abstraction of low-level components in the browser and on the server that enable you to perform client-server communication in JavaScript.
AJAX

Asynchronous JavaScript and XML (AJAX) enables you to create more interactive and more responsive Web applications than those that rely exclusively on complete page postbacks. With AJAX-style programming, the browser can exchange only the data it needs with the server, without having to update the complete page.

AJAX relies on the following combination of technologies:

*

Asynchronous communication between the browser and server by using the XMLHTTP object that is built into browsers.
*

A format for exchanging data between the browser and server. This format usually is XML, but it can also be JSON (as in ASP.NET AJAX) or another format.
*

Data presentation in the browser by using XHTML, HTML, and CSS.
*

Client scripting that uses the browser document object model (DOM) and JavaScript to create a responsive user interface (UI).

JSON

JavaScript Object Notation (JSON) is a lightweight format for representing objects and their state. The asynchronous communication layer uses JSON as a serialization format instead of the SOAP format more typically used with Web services. Using JSON simplifies client-server interaction, because it eliminates the need for extensive client script to construct requests that use SOAP and XML.
note

You do not have to understand the details of JSON format or serialization unless you have to extend or customize system capabilities. For example, you might have to know JSON format if you want to modify the way that ASP.NET 2.0 AJAX Extensions serializes specific custom types.
Calling Web Service Methods

ASP.NET 2.0 AJAX Extensions enables you to call ASP.NET Web services from the browser by using client script. The page can call server-based methods without a postback and without refreshing the whole page, because only data is transferred between the browser and the Web server. This following code example shows how to expose a Web service method in an ASP.NET Web page.
Run View
This example is currently not available.
Making HTTP Requests

The previous example of calling a Web service method from script does not require detailed knowledge of HTTP requests. For more advanced scenarios, the asynchronous communication layer enables a JavaScript to make a request over the network to any HTTP end point by using the Sys.Net.WebRequest class.

The following example shows how to use a WebRequest object to implement GET and POST Web requests that connect to the specified URLs (HTTP end points).
Run View
This example is currently not available.

To run the example you need the following:

*

A ConnectingEndPoints.aspx test page. This page contains a button to run the script that makes a GET request and then a POST request. The results are returned asynchronously by the default Sys.Net.XmlHttpExecutor instance and are displayed in the page.
*

The GetTarget.htm and the PostTarget.aspx pages. These are the target pages for the GET request and the POST request, respectively.
*

The supporting ConnectingEndPoints.js script. This script does the actual work of making the requests, and it provides the handler function which receives the results of the request.

Client-Server Communication

The following illustration shows how the asynchronous communication layer communicates between the client and the server.
ACSC Communication
Client-server communication

In physical terms, part of the asynchronous communication layer is on the client in the form of downloaded scripts. The other part is on the server in the form of handlers and Web services.
Client Architecture

The client asynchronous communication layer consists of several JavaScript components. The following illustration shows the client architecture of the asynchronous communication layer.
ACSC Client Architecture
Client architecture

The client architecture contains two main groups: the communication group and the support group.
Communication Group

The communication group contains client script that performs Web services communication between the client and the server. Note that Web request handling is intrinsically an asynchronous process. The communication group is based on the browser’s XMLHTTP object and on executor objects that dispatch browser requests to the Web service.
Web Service Proxy Classes

In Microsoft ASP.NET AJAX, the asynchronous communication layer generates client-script proxy classes automatically. You can then use the JavaScript proxy objects to make asynchronous requests to the server from client script. There are two possible approaches to making a Web service request:

*

Calling Web services by using the HTTP POST verb. A POST request has a body that contains the data that the browser sends to the server. It does not have a size limitation. Therefore, you can use a POST request when the size of the data exceeds the intrinsic size limitation for a GET request. The client serializes the request into JSON format and sends it as POST data to the server. The server deserializes the JSON data into .NET types and makes the actual Web service call. During the response, the server serializes the return values and passes them back to the client, which deserializes them into JavaScript objects for processing.
*

Calling Web services by using the HTTP GET verb. This resembles the functionality of a POST request, with the following differences:
o

The client uses a query string to send the parameters to the server.
o

A GET request can call only a Web service method that is configured by using the [ScriptMethod(UseHttpGet = true)] attribute.
o

Data size is limited to the URL length allowed by the browser.
note

GET requests are not recommended for method calls that modify data on the server or that expose critical information. In GET requests, the message is encoded by the browser into the URL and is therefore an easier target for tampering. For both GET and POST requests, you should follow security guidelines to protect sensitive data.

Page Method Proxy Classes

Page methods provide the scripting infrastructure for client script to call a static method in an ASP.NET page (an .aspx page, master page, or .ascx control) as if it were a Web service method.
Support Group

The support group is responsible for handling proxy classes and the serialization required for client-server communication.
Authentication Proxy Class

The authentication proxy class is generated by the server authentication service. It enables the user to log in or log out through JavaScript in the browser without making a round trip to the server.
Profile Proxy Class

The profile proxy class is generated by the server profile service. It makes the current user's profile information available to the client through JavaScript without making round trips to the server. It also enables saving modified profile information to the server by using script.
JSON Serialization

The client JSON serialization component serializes JavaScript objects into JSON format. Deserialization is available by using the JavaScript eval function.

Although JSON is the default serialization format, individual methods in Web services and in ASP.NET Web pages can return alternative formats such as XML. The serialization format of a method can be specified with attributes. For example, the [ScriptMethod(ResponseFormat.Xml)] attribute causes a Web service method to return data in a browser-specific XMLDocument type. For more information, see XML DOM Properties in the MSDN Library and the ScriptMethodAttribute class overview.
Server Architecture

The server asynchronous communication layer consists of several components. The following illustration shows the server architecture of the asynchronous communication layer.
ACSC Server Architecture
Server architecture

The server asynchronous communication layer includes two main groups: a communication group and a support group.
Communication Group

The server communication group is the high-level interface between the server and the client. It contains the server communication components that correspond to similar components on the client.
Web Services

In the Web Services component, the server performs all the required processing and returns an appropriate response to the client.
Page Methods

The page-methods component enables a method in an ASP.NET page (an .aspx page, master page, or .ascx control) to be called as if it were a Web service method.
Support Group

Components for the support group handle additional tasks such as serialization and application services that are required for client-server data exchange.
JSON Serialization

The server JSON serialization component enables customizable serialization and deserialization of common .NET types to and from JSON format.
XML Serialization

The asynchronous communication layer supports returning XML types from a Web service. If a Web method returns an XmlDocument object, as specified by the server attribute [ScriptMethod(ResponseFormat.Xml)], the callback function receives the return value as a browser-specific XmlDocument type. For more information, see XMLDocument Property in the MSDN Library.
Authentication Service

The authentication service generates an authentication proxy class and makes it available to client script. This enables the user to log in or log out through JavaScript in the client.
Profile Service

The profile service generates a profile proxy class, which can be used in client script to get and set profile properties for the user identity associated with the current request. The profile service works for for authenticated users and for anonymous users when the anonymous identification feature is enabled.

Back to top
Code Examples

Calling Web Services from Client Script

Exposing Web Services to Client Script

Using Forms Authentication

Using Profile Information

Back to top
Class Reference
Client Types

Name


Description

WebServiceProxy Class


Enables calling a method of a specified Web service asynchronously.

WebRequest Class


Models the information needed by the asynchronous client-server communication infrastructure to make an HTTP request. This class is used by other asynchronous client-server communication classes.

WebRequestExecutor Class -


Provides the functionality for interfacing with the network to perform Web requests.

WebRequestManager Class


Manages the flow of network requests from the WebRequest class to the XMLHttpExecutor class that is responsible for making the actual network requests.

WebServiceError Class


Handles errors for the Sys.Net namespace classes.

XMLHttpExecutor Class


Makes asynchronous network requests using the browser's XMLHTTP support.

JavaScriptSerializer Class


Provides serialization and deserialization functionality.

AuthenticationService Class


Provides the client proxy class for the authentication service.

ProfileGroup Class


Defines a profile group.

ProfileService Class


Provides the client proxy class for the profile service.
Server Types

Name


Description

ScriptingAuthenticationServiceSection


Represents the configuration section for authentication service settings.

ScriptingProfileServiceSection


Represents the configuration section for profile service settings.

JavaScriptConverter


Provides an abstract base class for a custom type converter.

JavaScriptSerializer


Provides serialization and deserialization functionality.

JavaScriptTypeResolver


Provides an abstract base class for implementing a custom type resolver.

ScriptIgnoreAttribute


Specifies that a public property or public field will be ignored by the JavaScriptSerializer when serializing or deserializing an instance of a class.

SimpleTypeResolver


Provides a type resolver for managed types.

GenerateScriptTypeAttribute


Specifies that the server type must be generated in the proxy object.

ResponseFormat


Specifies how the Web method return type is serialized.

ScriptMethodAttribute


Specifies which HTTP verb is used to invoke a method, and the format of the response.

ScriptServiceAttribute


Indicates to the asynchronous communication layer that a Web service can be invoked from script.

AuthenticationServiceManager


Configures the location of the authentication service.

ProfileServiceManager


Configures the location of the profile service.

Calling Web Services from Client Script in ASP.NET AJAX
Introduction

This topic explains how to use to call a Web service from ECMAScript (JavaScript). To enable your application to call ASP.NET AJAX Web services by using client script, the server asynchronous communication layer automatically generates JavaScript proxy classes. A proxy class is generated for each Web service for which an element is included under the control in the page.

For more information, see Exposing Web Services to Client Script.

To call a method of the Web service, you call the corresponding method of the generated JavaScript proxy class. The proxy class in turn communicates with the Web service.
Calling Web Service Methods

Calling a Web service method from script is asynchronous. To get a return value or to determine when the request has returned, you must provide a succeeded callback function. The callback function is invoked when the request has finished successfully, and it contains the return value (if any) from the Web method call. You can also provide a failed callback function to handle errors. Additionally, you can pass user context information to use in the callback functions.

The following example shows how to make the following types of Web service calls:

*

Calling a Web service that has no return value.
*

Calling a Web service that returns a value.
*

Calling a Web service method that takes parameters.
*

Calling a Web service method by using the HTTP GET verb.
*

Calling a Web service method that returns an XmlDocument object.

Run View
Specifying Callback Functions as Default Properties

In the previous examples, calls to Web service methods are made by using the proxy class. Information about the succeeded callback function, the failed callback function, and the user context is passed by using additional parameters in the call.

As an alternative, you can specify a succeeded callback function, a failed callback function, and user context as default properties for the class. Your script can then invoke the Web service methods of the proxy class without passing these values as parameters in the call. This simplifies the syntax of calling Web service methods.

The following example shows how to set default properties on the Web service proxy class, and then call a Web service method.

MyNameSpace.MyService.set_defaultSucceededCallback(SucceededCallback);
MyNameSpace.MyService.set_defaultFailedCallback(FailedCallback);
MyNameSpace.MyService.set_defaultUserContext("my context");
MyNameSpace.MyService.myServiceMethod(param1, param2);

Setting Callback Functions as Properties of Proxy Class Instances

You can also create instances of the generated proxy class. In that case, you can specify a succeeded callback function, a failed callback function, and user context as default properties for each instance. As with calling the generated proxy class, you can then use the proxy class instances to call Web service methods without passing these values as parameters in the call.

You typically create proxy-class instances when you want to make multiple calls to methods of the Web service and use different default property values for each instance. For example, you can specify different callback functions for each instance. By using different callback functions, you can process the returned data in different ways based on your application needs and on the nature of the returned data.

The following example shows how to create an instance of a proxy class, set its default properties, and call the related Web service method:

var myServiceProxy = new MyNameSpace.MyService();
myServiceProxy.set_defaultSucceededCallback(SuccededCallback);
myServiceProxy.set_defaultFailedCallback(FailedCallback);
MyNameSpce.MyService.set_defaultUserContext("my context");
myServiceProxy.myServiceMethod(param1, param2);

For more information, see Generated Proxy Classes.
Handling Errors in Web Service Method Calls

The following example shows how to handle errors that are raised by Web service methods. In order to catch errors, you must provide a failed callback function that accepts a single parameter. This parameter will contain the error object sent by the Web service.

The following example show how to provide a failed callback function that is called if an error occurs during a Web service method call.
Run View
Calling a Single Callback Function from Multiple Web Service Methods

You can provide a single succeeded callback function that is invoked from multiple Web service method calls. In order for the function to distinguish between callers, you can pass user context to it, or you can test for the name of the calling method. The user context and the calling method name are both available in the callback function, as shown in the following example:
Run View
Passing and Returning Complex Types

If the Web service method returns a complex type, the succeeded callback function receives a return value in the form of a JavaScript object that corresponds to the server type. The following example shows a Web service method that returns a complex type.
Run View

The following example shows how to call Web service methods that have parameters that correspond to complex types. Proxy classes for the types will be automatically generated. This enables client script to create instances of the type to pass as parameters to the method call.
Run View
Passing Parameters Typed as Generics or Arrays

A Web service method might support parameters or a return value that are typed as generics or arrays of lists of type T. In that case, ASP.NET AJAX automatically generates proxy classes for the type T for use with client script. However if a generic type takes more than one type argument, such as Dictionary>, ASP.NET AJAX does not generate proxy classes for the types.

For ASP.NET AJAX to generate a proxy class for the type T, the Web service class that uses the type must be qualified with the GenerateScriptTypeAttribute attribute for the type T.

The following example shows how to call a Web service method from client script when the parameters are typed as generics or arrays.
Run View
Passing Parameters Typed as Enumerators

An enumerator type can be accessed by using the automatically generated proxy class.
note

You cannot access enumerators by using instances of the generated proxy class.

The following example shows how to call a Web service method from client script when the parameters are typed as enumerators.
Run View

0 comments: