Using the AJAX Library C# Help

There is a great deal of functionality available in the AJAXLibrary that you can use to further enhance your Web applications. However, to do this you need at least a working knowledge of JavaScript. In this section, you see some of this functionality, although this is not an exhaustive tutorial.

The basic principles behind the use of the AJAXLibrary are much the same as for adding any type of client-side script to a Web application. You will still use the core JavaScript language, and you will still interact with the DOM. However, there are many areas where the AJAXLibrary makes things easier for you. This section explains many of these areas and provides a foundation that you can build on with further experimentation and study of the online AJAXLibrary documentation.

The techniques covered in this section are illustrated in the PCSLibraryDerno project, which is referred to throughout the rest.

Adding JavaScript to a Web Page

The first thing you need to know is how to add client-side JavaScript to a Web Page. You have three
Opti Ory here:

°  Add JavaScript inline in ASPJ’JETWeb pages, by using the <script> element.
°  Add JavaScript to ‘separate JavaScript files with the extension  and reference these files from <script> elements or (preferably) by using the <Scripts> child element of the ScriptManager control.
°  Generate JavaScript from server-side code, such as code behind or custom extender controls.

Each of these techniques has its own benefits. For prototyping code, there is no substitute for inline code because it is so quick and easy to use. You will also find it easy to associate client-side event handlers of HTML-elements ana server controls with client-side functions, because everything is in the same file. Having separate files is good for reusability, because you may create your own library of classes much like the existing AJAXLibrary JavaScript files.

Generating code from code behind can be tricky to implement because you will not usually have access to IntelliSense for JavaScript programming when you use C# code. However, you will be able to generate code dynamically in response to application state, and sometimes this is the only way to do things.

The extenders that you can create with the AJAXControl Toolkit include a separate JavaScript file that you use to define behaviors, which gets around some of the problems of exposing client-side code from the server.

In this chapter, you use the inline code technique, because it is simplest and allows you to concentrate on the JavaScript functionality.

Global Utility Functions

One of the fe~tures supplied by the AJAXLibrary that you will use most often is the set of global functions that wrap other functionality. These include the following:

¤   $get () – This function enables you to get a reference to a DOM element by supplying its client-side id value as a parameter, with an optional second parameter to specify the parent element to search in.

¤   $create () -‘- This function enables you to create objects of a specific JavaScript type and perform initialization at the same time. You can supply between one and five parameters to this function. The first parameter is the type you want to instantiate, which will typically be a type defined by the AJAXLibrary. The other parameters enable you to specify initial property values, event handlers, references to other components, and the DOM element that the object is attached to, respectively.

¤   $addHandler() – This function provides a shorthand for adding an event handler to an object.

There are more global functions, but these are the ones you will use most often. .$create () in particular is a very useful way to reduce the amount of code required to create and initialize an object.

Using the AJAX Library JavaScrlpt OOP Extensions

The AJAXLibrary includes an enhanced framework for defining types that uses an OOP-based system that maps closely to .NET Framework techniques. You can create namespaces, add types to namespaces, add constructors, methods, properties, and events to types, and even use inheritance and interfaces in type definitions.

In this section, you see how to implement the basics of this functionality, but you won’t look at events and interfaces here. These constructs are beyond the scope.

Defining Namespaces

To define a namespace, you use the Type. regis terNamespace () function, for example:
Type.registerNamespace(“ProCSharp”);
Once you have registered a namespace you can add types to it.

Defining Classes

Defining a class is a three-stage process. First, you define the constructor. Next, you add properties and methods. Finally, you register the class.

To define a constructor, you define a function using a namespace and class name, for example

ProCSharp.Shape = function(color, scaleFactor)
this._color = color: *
this._scaleFactor = scaleFactor;
}

This constructor takes two parameters and uses them to set local fields (note that you do not have to
explicitly define these fields – you just have to set their values).

To add properties and methods, you assign them to the prototype property of the class as follows:

This code defines two properties by their get and set accessors.
To register a class,you call its registerClass (.) function:
ProCSharp.Shape.registerClass(‘ProCSharp.Shape’);

Inheritance

You derive a class in much the same way as creating a class but with some slight differences.You use the initializeBase (). function to initialize the base class in the constructor, passing parameters in the
form of an array:

ProCSharp.Circle = function (color, scaleFactor, diameter) {
ProCSharp.Circle.initializeBase(this, [color, scaleFactor]);
this._diameter = diameter;
}

You define properties and methods in the same way as before:

W!’en you register the class, you provide the base class type as a second parameter:

ProCSharp.Circle.registerClass(‘ProCSharp.Circle’, ProCSharp.Shape);
You can implement interfaces by passing them as additional parameters, although, to keep things simple, you won’t see details of that here.

Using User-Defined Types

Once you have defined classes in this way, you can instantiate and use them with simple syntax, For
example:

var myCircle = new ProCSharp.Circle(‘red’. 1.0, 4.4);
myCircle.describe();
This code would result in a JavaScript alert box, as shown in Figure 39-7.

FIgure 39-7

Figure 39-7

If you want to test this, run the PCSLibraryDemoproject and click the Test OOP Functionality button.

The PageRequestManager and Application Objects

Among the most useful classes that the AJAXLibrary provides are the PageRequestManager and Application classes. You will find PageRequestManager in the Sys. WebForrnsnamespace and Application in the Sys namespace. The important thing about these classes is that they expose several events that you can attach JavaScript event handlers to. These events occur at particularly interesting points in the life cycle of a page (for Application) or partial-page postback (for PageRequestManager) and enable you to perform operations at these critical times.

The AJAXLibrary defines event handlers in a similar way to event handlers in the .NET Framework. Every event handler has a similar signature, with two parameters. The first parameter is a reference to the object that-generated the event. The second parameter is an instance of the Sys .EventArgs class or an instance of a class that derives from this class. Many of the events exposed by PageRequestManager and Application include specialized event argument classes that you can use to determine more information about the event. The following table lists these events in the order they will occur in a page that is loaded, triggers a partial-page postback, and is then closed.

Event                          Description

Application.init: This event is the first to occur in the life cycle of a page. It is raised after all the JavaScript roes have been loaded but before any objects in the application have been created.

Application. load: This event fires after the objects in the application have loaded and been initialized. You will often use an event handler attached to this event to perform actions when the page is first loaded. You can also provide an implementation for a function called pageLoad () on a page, which is automatically defined as an event handler for this event. It sends event arguments by using a Sys .ApplicationLoadEventArgs object, which includes the iSPartialLoad property that you can use to determine if a partial-page postback has occurred. Access this property with the get_isPartialLoad () accessor.

PageRequestManager .initializeRequest: This event occurs before a partial-page postback, before the request object is created. You can use the Sys .WebForrns . InitializeRequestEventArgs event argument properties to access the element that triggered the postback (postBackElement) and the underlying request object (request).

PageRequestManager .beginRequest: This event occurs before a partial-page postback, after the request object is created. You can use the Sys .WebForms. BeginRequestEventArgs event argument properties to access the element that triggered the postback (postBackEl.ement) and the underlying request object (request).

pageRequestManager .pageLoading: This event is raised after a partial-page postback, before any
subsequent processing occurs. This processing can include <di v> elements that will be deleted or updated, which you can reference through the Sys. WebForms.PageLoadingEventArgs object by sing \ the panelSDeleting and panelsUpdating properties.

PageRequest Manager.pageLoaded: This event is raised after a partial-page postback, after UpdatePanel controls have been processed. This processing can include <di v» elements that have been created or updated, which you can reference through the Sys .WebForms. PageLoadedEventArgs object by using ,the panelsCreated and panelsUpdated properties.

PageRequestManager .endRequest: This event occurs after processing of a partial-page postback has completed. The Sys. WebForms.EndRequestEventArgs object passed to the event handler enables you to detect and process server-side errors (by using the error and errorHandled properties) as well as to access the response object through response.

Application. unload: This event is raised just before the objects in the application are disposed, which gives you a chance to perform final actions or cleanup if necessary.

You can add an event handler to an event of the Application object by using the static add_xxX () functions, for example

The process is similar for PageRequestManager, but you must use the get_instance () function to obtain an instance of the current object, for example:

Sys.WebForms.pageRequestManager.getlnstance() begin Request (  Begin Request Handler)

function BeginRequestHandler(sender. args)
{
II Event handler code.
}

In the PCSLibraryDemo application, an event handler is added to the pageRequestManager endRequest event. This event handler responds to server-side processing errors and displays an error message in a <span> element with an id of errorDisplay. To test this method, click the Test Client- Side ‘Error Display button, as shown in Figure 39-8:

Figure 39-8

Figure 39-8

The code that achieves this is:

Note that the errorHandled property of the EndRequestEventArgs object is set to true. This prevents the default behavior, which is to display the error message in a dialog box by using the ]avaScript alert () function.

The error itself is generated by throwing an exception on the server as follows:

There are many other situations when you will want to use event handling techniques to act on the Application and PageRequestManager events.

JavaScript Debugging

In the past, ]avaScript has had a reputation of being difficult to debug. However, this has been addressed in the latest version of VisualStudio. You can now add breakpoints and step through ]avaScript code just like 0# code. You can also interrogate object state in break mode, change property values, and so on. The IntelliSense that is available when you write ]avaScript code is also vastly improved in the latest version of Visual Studio.

However, there will still be times when you will want to add debug and trace code to report information as code is executed. For example. you might want to use the ]avaScript alert () function to show information in dialog boxes.

There are also SOJne third-party tools that you can use to add a client-side UI for debugging. These include:

¤    Fiddler- This tool, which you can obtain from www.fl.ddlertool.com. enablesyou to log all HTfP traffic between your computer and a Web application – including partial-page postbacks. There are also additional tools that you can use to look at what occurs during the processing of Web pages in more detail.

¤    Nikhil’s Web Development Helper- his tool, available at http://csharpaid.com/ can also log HTfP traffic. In addition, this toorctmtains a number of utilities specifically aimed at ASP.NETand ASP.NETAJAXdevelopment, for example, the ability to examine view state and to execute immediate JavaScript code. This latter feature is particularly useful to test objects tha~you may have created on the client. The Web Development Helper also displays extended error; information when JavaScript errors occur, which makes it easier to track down bugs in JavaScript code.

The AJAXLibrary also provides the Sys. Debug class, which you can use to add some extra debugging features to your application. One of the most useful features of this class is the Sys .Debug traceDump () function, which enables you to analyze objects. One way to use !his function is to place a text area control on your Web page with an id attribute of TraceConsole. Then; all output from Debug will be sent to this control. For example, can use the traceDump () me .od to output information about the Application object to the console:

This results in output along the lines of the following:

You can see all the properties of this object in·this output. This technique can be extremely useful for ASP.NETAJAXdevelopment

Making Asynchronous Web Method calls

One of the most powerful features of ASP.NETAJAXis the ability to call Web methods from client-side
script. This gives you access to data, server-side processing, and all manner of other functionality.

You will not be looking at Web methods in this book until Chapter 42, ‘Windows Communication Foundation,” so we will save the details until then and cover the basics here. Put simply, a Web method is a method that you can expose from a Web service that enables you to access remote resources over the Internet. In ASP.NET AJAX, you can also expose Web methods as static methods of server-side Web page code-behind code. You can use parameters and return values in Web methods jus~as you do in other method types. In ASP.NET AJAX, Web methods are called asynchronously. You pass parameters to a Web method and define a callback function, which is called when the Web method call completes. You use this callback function to process the Web method response. You can also provide-an alternative callback function to call in the event of a call failure.

In the PCSLibraryDemoapplication, you can see a Web method call being performed by clicking the Call Web Method button, as shown in Figure 39.

Figure 39-9

Figure 39-9

Before you can use a Web method from client-side script, you must generate a client-side proxy class to perform the communication. The easiest way to do this is simply to reference the URL of the Web service that contains the Web method in the ScriptManager control.

ASP.NET Web services use the extension. asmx, as shown in this code. To use a client-side proxy to
access a Web method in a Web service, you must apply the System. Web.Script. SerVices . S«r iptService attribute to the Web service.

For Web methods in the code-behind for the Web page, you do not need this attribute, or this reference in ScriptManager, but you must use static m~hods and apply the System. Web.Services. WebMethod attribute to the methods.

Once you have generated a client-side stub, you can access the Web.method by its name, which is defined as a function of a class with the same name as the Web service. In PCSLibraryDemo,the SiInpleService. asmxWeb service has a Web method called Multiply ( ), which multiplies two double parameters. When you call this method from client-side code, you pass the two parameters required by the method (obtained from HTML <input> elements in the example) and can pass one or two callback function references. If you pass one reference, this is the callback function that is used when the call returns a success result. If you pass two references, the second one is the callback function that is used for Web method failure.

This method is a very simple one but illustrates the ease with which you can call Web services asynchronously from client-side code.

ASP.NET Application Services

ASP.NETAJAXincludes three specialized Web services at you can use to access ASP.NETapplication services. These services are accessed through the following client-side classes.

¤   Sys. Services .AuthenticationService – This service includes methods to log in or log out a user or determine whether a user is logged in.
¤   Sys. services. ProfileService – This service enables you to get and set profile properties for the currently logged-on user. The profile properties are configured in the Web.contig file for the application.
¤   Sys. Services. RoleService – This service enables you to determine role membership for the currently logged-on user.

Used properly, these dasses enable you to implement extremely responsive user interfaces that include authorization, profile, and membership functionality. These services are beyond the scope of this chapter, but you should be aware of them, and they are well worth investigating.

Posted on November 2, 2015 in ASP.NET AJAX

Share the Story

Back to Top