DNS
Dynamic DNS, which is enabled by default, attempts to automatically discover the DNS servers. You can verify if dynamic DNS is enabled by checking the read-only IsDynamicDnsEnabled property. You can also explicitly specify a list of DNS server IP addresses on your network using the EnableStaticDns method.
DHCP Service
Alternatively, calling EnableStaticIP will deactivate the usage of DHCP.
Dynamic IP addresses are assigned temporarily. You can release a dynamic IP address with ReleaseDhcpLease or renew it with RenewDhcpLease. The IsDhcpEnabled property indicates if DHCP is currently enabled.
What is Gateway Address?
What is Subnet Mask?
What is MAC Address?
identifier provided by default, and you should ensure that all devices on your network have a unique identifier.
UDP protocol
One of the additional advantages of using UDP is the ability to broadcast or multicast data across a network. The DNS service to resolve Internet addresses and the discovery service of the Device Profile for Web Services use the broadcast feature of UDP.
With UDP, a client does not need to connect to a server. Connectionless transmission takes place with the SendTo and ReceiveFrom methods. ReceiveFrom returns an endpoint object that is populated with the actual sender information. Listing 6-4 shows a UDP client and Listing 6-5 a UDP server. They demonstrate the usage of a connectionless end-to-end transmission but are not using the broadcast feature.
If you want to send a broadcast message that theoretically all network nodes will get, you can use the IP address 255.255.255.255. There is no predefined broadcast address like Any or Loopback as there is with the full .NET Framework. You can also create a broadcast IP address object using new IPAddress(0xFFFFFFFF);.
Transmitting Data with a Socket
clientSocket.Send(Encoding.UTF8.GetBytes("Hello World!"));
And you can receive data with the Receive method. The maximum number of bytes the Receive method reads is limited by the amount the specified buffer can hold. The method returns the actual number of bytes that were read:
byte[] inBuffer = new byte[100];
int count = clientSocket.Receive(inBuffer);
char[] chars = Encoding.UTF8.GetChars(inBuffer);
string str = new string(chars, 0, count);
Debug.Print(str);
You can poll the socket to test if data has been received. The first polling parameter specifies the amount of time, in microseconds, you want your application to wait for a response. Set it to –1 or System.Threading.Timeout.Infinite to let your application to wait an infinite amount of time:
if (communicationSocket.Poll(-1, //timeout in microseconds (-1 = infinite)
SelectMode.SelectRead))
{
...//read data here
}
Using the Available property of the Socket class, you can determine the number of bytes that are available to read before receiving them, which allows you to allocate a buffer that can hold all available bytes before reading the data.
Addressing NET Micro Framework
You cannot directly parse an IP address from a string with the Parse method of IPAddress as you can with the full .NET Framework; the .NET Micro Framework does not provide a Parse method for IPAddress. You can indirectly parse using the System.Net.Dns class, but first, take a look at the following code snippet, which demonstrates how you can convert a dotted decimal IP address to an IP address of the long value type.
public static long DottedDecimalToIp(byte a1, byte a2, byte a3, byte a4)
{
return (long)((ulong)a4 << 24 | (ulong)a3 << 16 | (ulong)a2 << 8 | (ulong)a1);
}
Using the preceding snippet, you can easily create an endpoint with legible decimal notation:
IPEndPoint ep = new IPEndPoint(DottedDecimalToIp(192, 168, 101, 100), 80);
As I said, there is a way to convert the IP address using the System.Net.Dns class, which allows you to use the Internet Domain Name System (DNS). The Dns class is responsible for resolving server names. Server addresses can be specified either in decimal notation or as a server name like www.microsoft.com. The GetHostEntry method returns a collection of the entries found in the DNS database. If you pass a particular address in decimal notation, you will always get one entry in the form of an IPAddress object:
IPHostEntry entry = Dns.GetHostEntry("192.168.101.100");
IPAddress ipAddr = entry.AddressList[0];
IPEndPoint ep = new IPEndPoint(ipAddr, 80);
Passing an empty string ("") to the GetHostEntry method will deliver the local IP address of the device.
The IPAddress class possesses two predefined static addresses properties: IPAddress.Loopback and IPAddress.Any IPAddress.Loopback describes the address 127.0.0.1, which is used if the client and server are on the same PC or device. IPAddress.Any is 0.0.0.0 and does not have a meaning for client applications; we will discuss that parameter in detail later, with server
applications.
For example, to connect with a server at the address 192.168.101.100 on the port 80, you need the following code:
Socket clientSocket = new Socket(Addressfamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
IPEndPoint serverEndPoint = new IPEndPoint(DottedDecimalToIp(192, 168, 101, 100),
80); // port no
clientSocket.Connect(serverEndPoint);
You can obtain the two endpoints of the socket when a connection is available with the RemoteEndPoint and LocalEndPoint properties. Casting these into an IPEndPoint object will make the IP address available over the Address property.
You can determine the individual bytes of an IP address with the GetAddressBytes method, which supplies a byte array. With IP version 4, GetAddressBytes returns a byte array of 4 bytes.
In addition, the ToString method provides a string displaying the IP address in dotted decimal notation.
IPEndPoint remoteIPEndPoint = (IPEndPoint)communicationSocket.RemoteEndPoint;
byte[] addressBytes = remoteIPEndPoint.Address.GetAddressBytes();
TCP Programming
A TCP/IP connection is the right choice when you need a reliable two-way, connection-based communication that ensures that data packets will be received in the correct order and that no data will be lost or transferred multiple times. You can create a TCP/IP socket with the following code:
Socket socket = new Socket(Addressfamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
Connecting to a Server as a Client
After you have created a socket object, you are able to initiate a connection to a (remote) server with the Connect method of your socket. Your .NET Micro Framework application is thereby the client application. The connection establishment takes place synchronously, so your client application will be blocked until a connection is available.
public void Connect(EndPoint remoteEP);
Take note of the remoteEP parameter of the abstract type System.Net.EndPoint in the signature of the Connect method. For IP connections, you need to pass an instance of the System.Net.IPEndPoint class to the Connect method. IPEndPoint contains the IP address and the communication port, and it is derived from EndPoint.
You can create an IPEndPoint object with one of the following two constructors:
public IPEndPoint(long address, int port)
public IPEndPoint(IPAddress address, int port)
Sockets Programming
The most important class for network programming is System.Net.Sockets.Socket. The Socket class abstracts and implements the Socket API and/or Berkeley socket interface standard.
The Socket API was developed at the beginning of the 1980s at the University of California,Berkeley for Berkeley Software Distribution (BSD) UNIX.
A socket is an endpoint of a connection. With sockets, you can read and send data to and from a network on both the client and server sides. To send or receive data from a socket, you need to know the IP address of the other communication partner (endpoint) and one agreedupon port number, which can vary depending on application purposes. A client application, thus, must know the IP address of the server and connect with that server on a particular port.
The server listens on the agreed port or ports and accepts incoming connections from one or more clients.
Accessing SPI Devices with the .NET Micro Framework
Why Reserve Pins?
The RS232 Serial Port
Together with the serial interface, you quite often hear the terms "UART," "USART," and "RS232." UART and USART are names for the serial hardware component, the Universal (Synchronous) Asynchronous Receiver Transmitter. The RS232 standard describes how data will be physically transferred over the cable. Further standards are RS422 and RS485.
What Are GPIO Ports?
diode (LED). Monitoring a push button or a switch is the function of an input line.
A GPIO port can have either a low (0 volts) or high (a positive voltage, usually 3.3 volts) status. In the .NET Micro Framework, the status of a GPIO port is represented as a Boolean value. The value false corresponds to low status and true to high.
TFConvert Tool
In the Tools\Fonts subdirectory, you can find some sample TrueType fonts from Ascender Corporation, which you can convert to meet your needs. These free sample fonts provide a reduced character set; the full versions can be purchased from the company.
The TFConvert command line tool is located in the Tools subdirectory of your .NET Micro Framework installation. TFConvert accepts a path to a font definition file that describes the font's size, style, and characters to convert.
The system tool character map (charmap.exe) provided with your Windows installation can help you determine which characters or character ranges to convert.
To get more information about creating .tinyfnt fonts with the TFConvert tool, please see the .NET Micro Framework SDK documentation, where this is described in detail.
In addition, on the SJJ Embedded Micro Solutions web site, you can find a great article that describes how to convert fonts with TFConvert (www.sjjmicro.com/SJJ_Articles.html).
On the web site of a Czech .NET Micro Framework enthusiast, Jan Kucera, at www.microframework.eu, you can find the Tiny Font Tool GUI. This tool provides a graphical user interface that assists you in creating the font definition files.
MFDeploy [.NET Micro Framework Deployment Tool ]
The features of MFDeploy include the following:
• Discovering and pinging devices to test if they are responsive
• Creating a standard deployment from a master device
Copying your application to the device
• Upgrading firmware
• Creating and updating device keys
• Signing code
• Setting network parameters and USB names
• Use via a UI or automatically via the command line or programmatically
.NET Micro Framework Base Class Library
The runtime libraries that you can find in the Assemblies subdirectory of your .NET Micro Framework installation include the following:
• Mscorlib.dll: A subset of the core .NET classes.
• System.dll: Only the System.Net namespace.
• System.Xml.dll: A subset of the core .NET XML classes necessary to read XML files.
• Microsoft.SPOT.Native.dll: Core .NET Micro Framework classes.
• Microsoft.SPOT.Hardware.dll: Managed hardware drivers.
• Microsoft.SPOT.Graphics.dll: Low-level graphics classes.
• Microsoft.SPOT.TinyCore.dll: User interface elements for complex WPF GUIs.
• Microsoft.SPOT.Net.dll: Internal socket drivers.
When using network sockets, you need to include System.dll and Microsoft.SPOT.Net.dll.
Further assemblies for the Device Profile for Web Services (DPWS) stack are also included.
Although provided with the .NET Micro Framework 2.5 SDK release, the implementation of the DPWS stack is still in beta, and therefore, the DPWS libraries are not installed by default with the .NET Micro Framework SDK. When installing the SDK you need to choose either the Install All option or the Custom Installation option with DPWS selected.
.NET Micro Framework System Requirements
Developing for the .NET Micro Framework requires the following:
• Microsoft Windows XP or Vista
• Microsoft Visual Studio 2005 Standard Edition or better, with Service Pack 1
• .NET Micro Framework SDK version 2 with Service Pack 1 or version 2.5
The free Express editions of Visual Studio cannot be used with the .NET Micro Framework,because they do not allow installing extensions at all. Do not forget to install Visual Studio 2005 Service Pack 1.
What Is the .NET Micro Framework?
The .NET Micro Framework enables you to write embedded applications for small, connected, embedded devices with Visual Studio and C#. That means you can now use the same development tools and language that you use to build desktop and smart device (PDA and smartphone) applications to develop applications for microcontrollers. The .NET Micro Framework also provides an extensible hardware emulator for rapid prototyping and debugging.
The .NET Micro Framework requires no underlying operating system. A scaled-down version of the Common Language Runtime (TinyCLR) sits directly on the hardware, so the framework is often called a bootable runtime. The runtime has a small footprint; it uses only a few hundred kilobytes of RAM and does not require the processor to have a memory management unit (MMU).
Therefore, the .NET Micro Framework can run on small and inexpensive 32-bit processors without consuming a lot of power.
How to: Improve the Startup Time of WCF Client Applications using the XmlSerializer
serializable using the XmlSerializer generate and compile
serialization code for those data types at runtime, which can result
in slow start-up performance.
Note:
Pre-generated serialization code can only be used in client
applications and not in services.
The ServiceModel Metadata Utility Tool (Svcutil.exe) can improve
start-up performance for these applications by generating the
necessary serialization code from the compiled assemblies for the
application. Svcutil.exe generates serialization code for all data
types used in service contracts in the compiled application assembly
that can be serialized using the XmlSerializer. Service and operation
contracts that use the XmlSerializer are marked with the
XmlSerializerFormatAttribute.
To generate XmlSerializer serialization code
Compile your service or client code into one or more assemblies.
Open an SDK command prompt.
At the command prompt, launch the Svcutil.exe tool using the following format.
svcutil.exe /t:xmlSerializer <assemblyPath>*
The assemblyPath argument specifies the path to an assembly that
contains service contract types. Svcutil.exe generates serialization
code for all data types used in service contracts in the compiled
application assembly that can be serialized using the XmlSerializer.
Svcutil.exe can only generate C# serialization code. One source code
file is generated for each input assembly. You cannot use the
/language switch to change the language of the generated code.
To specify the path to dependent assemblies, use the /reference option.
Make the generated serialization code available to your application by
using one of the following options:
Compile the generated serialization code into a separate assembly with
the name [original assembly].XmlSerializers.dll (for example,
MyApp.XmlSerializers.dll). Your application must be able to load the
assembly, which must be signed with the same key as the original
assembly. If you recompile the original assembly, you must regenerate
the serialization assembly.
Compile the generated serialization code into a separate assembly and
use the XmlSerializerAssemblyAttribute on the service contract that
uses the XmlSerializerFormatAttribute. Set the AssemblyName or
CodeBase properties to point to the compiled serialization assembly.
Compile the generated serialization code into your application
assembly and add the XmlSerializerAssemblyAttribute to the service
contract that uses the XmlSerializerFormatAttribute. Do not set the
AssemblyName or CodeBase properties. The default serialization
assembly is assumed to be the current assembly.
Example
The following command generates serialization types for XmlSerializer
types that any service contracts in the assembly use.
svcutil /t:xmlserializer myContractLibrary.exe
How to: Use Svcutil.exe to Download Metadata Documents
to save the metadata to local files. For HTTP and HTTPS URL schemes,
Svcutil.exe attempts to retrieve metadata using WS-MetadataExchange
and XML Web Service Discovery. For all other URL schemes, Svcutil.exe
uses only WS-MetadataExchange.
By default, Svcutil.exe uses the bindings defined in the
MetadataExchangeBindings class. To configure the binding used for
WS-MetadataExchange, you must define a client endpoint in the
configuration file for Svcutil.exe (svcutil.exe.config) that uses the
IMetadataExchange contract and that has the same name as the Uniform
Resource Identifier (URI) scheme of the metadata endpoint address.
To download metadata using Svcutil.exe
Locate the Svcutil.exe tool at the following location:
C:\Program Files\Microsoft SDKs\Windows\v1.0.\bin
At the command prompt, launch the tool using the following format.
svcutil.exe /t:metadata <url>* | <epr>
You must specify the /t:metadata option to download metadata.
Otherwise, client code and configuration are generated.
The <url> argument specifies the URL to a service endpoint that
provides metadata or to a metadata document hosted online. The <epr>
argument specifies the path to an XML file that contains a
WS-Addressing EndpointAddress for a service endpoint that supports
WS-MetadataExchange.
For more options about using this tool for metadata download, see
ServiceModel Metadata Utility Tool (Svcutil.exe).
Example
The following command downloads metadata documents from a running service.
svcutil /t:metadata http://service/metadataEndpoint
How to: Use Svcutil.exe to Validate Compiled Service Code
detect errors in service implementations and configurations without
hosting the service.
To validate a service
Compile your service into an executable file and one or more dependent
assemblies.
Open an SDK command prompt
At the command prompt, launch the Svcutil.exe tool using the following format.
svcutil.exe /validate /serviceName:<serviceConfigName> <assemblyPath>*
You must use the /serviceName option to indicate the configuration
name of the service you want to validate.
The assemblyPath argument specifies the path to the executable file
for the service and one or more assemblies that contain the service
types to be validated. The executable assembly must have an associated
configuration file to provide the service configuration. You can use
standard command-line wildcards to provide multiple assemblies.
How to: Use Svcutil.exe to Export Metadata from Compiled Service Code
types in compiled assemblies, as follows:
To export metadata for all compiled service contracts for a set of
assemblies using Svcutil.exe, specify the assemblies as input
parameters. This is the default behavior.
To export metadata for a compiled service using Svcutil.exe, specify
the service assembly or assemblies as input parameters. You must use
the /serviceName option to indicate the configuration name of the
service you want to export. Svcutil.exe automatically loads the
configuration file for the specified executable assembly.
To export all data contract types within a set of assemblies, use the
/dataContractOnly option.
Note:
Use the /reference option to specify the file paths to any dependent assemblies.
How to generating a WCF Client from Service Metadata
Online retrieval follows either the WS-MetadataExchange protocol or
the Microsoft Discovery (DISCO) protocol. Svcutil.exe issues the
following metadata requests simultaneously to retrieve metadata:
WS-MetadataExchange (MEX) request to the supplied address.
MEX request to the supplied address with /mex appended.
DISCO request (using the DiscoveryClientProtocol from ASP.NET Web
services) to the supplied address.
Svcutil.exe generates the client based on the Web Services Description
Language (WSDL) or policy file received from the service. The user
principal name (UPN) is generated by concatenating the user name with
"@" and then adding a fully-qualified domain name (FQDN). However, for
users who registered on Active Directory, this format is not valid and
the UPN that the tool generates causes a failure in the Kerberos
authentication with the following error message: The logon attempt
failed. To resolve this problem, manually fix the client file that the
tool generated.
svcutil.exe [/t:code] <metadataDocumentPath>* | <url>* | <epr>
ServiceModel Metadata Utility Tool (Svcutil.exe)
model code from metadata documents and metadata documents from service
model code.
Installing ASP.NET AJAX
This topic describes how to install Microsoft ASP.NET AJAX. It also
describes how to install the optional ASP.NET 2.0 AJAX Futures CTP and
optional ASP.NET AJAX Control Toolkit.
ASP.NET AJAX
ASP.NET AJAX enables you to create dynamic Web pages that support
partial-page updates. It includes Microsoft ASP.NET 2.0 AJAX
Extensions, which is a server framework, and the Microsoft AJAX
Library, which consists of client script that runs on the browser.
note
The installation process installs the ASP.NET AJAX assembly
(System.Web.Extensions.dll) in the global assembly cache (GAC). Do not
include the assembly in the Bin folder of your AJAX-enabled Web site.
You can install and use ASP.NET AJAX with Microsoft Visual Studio 2005
or Microsoft Visual Web Developer Express Edition. However, you do not
require Visual Studio 2005 to use ASP.NET AJAX to create ASP.NET Web
applications.
You can install and use the Microsoft AJAX Library without the .NET
Framework. You can also install it on non-Windows environments to
create client-based Web applications for any browser that supports
ECMAScript (JavaScript).
ASP.NET 2.0 AJAX Futures CTP
The CTP release is community supported. The features in the CTP
release might be added to the supported features in future versions of
ASP.NET AJAX. The CTP release is compatible with ASP.NET AJAX.
ASP.NET AJAX Control Toolkit
The ASP.NET Control Toolkit provides features that extend
functionality of ASP.NET AJAX version 1.0. These features enhance the
depth and breadth of the platform and include new ideas and concepts.
The ASP.NET Control Toolkit is community supported and community
driven.
System Requirements for Installation
Microsoft ASP.NET AJAX requires the following software.
Supported Operating Systems
Windows Server 2003
Windows XP Home Edition
Windows XP Professional
Windows Vista
Any Windows operating system version (including Windows 2000) that
supports the Microsoft .NET Framework version 2.0. Note that support
will be limited to the terms of support for that platform.
Required Software
The .NET Framework 2.0 or version 3.0.
Internet Explorer 5.01 or later.
Optional Software
Microsoft Visual Studio 2005 or Visual Web Developer Express Edition
Installing Microsoft ASP.NET AJAX
Follow these steps to install ASP.NET AJAX.
To install Microsoft ASP.NET AJAX
Make sure that you are logged in with an account that has Administrator rights.
If your account does not have Administrator rights, the installation
process displays the error "The system administrator has set policies
to prevent this installation."
Uninstall any earlier versions of ASP.NET AJAX. If the installation
process finds an earlier version on your computer, it will stop.
You can remove earlier versions with the Add or Remove Programs
application in Control Panel.
Download the ASPAJAXExtSetup.msi installation package from the ASP.NET
AJAX Downloads Web site.
To install ASP.NET AJAX from the Windows interface, double-click
ASPAJAXExtSetup.msi in Windows Explorer.
By default, the .msi file is installed in the following location:
drive:\..\Program Files\Microsoft ASP.NET\ASP.NET 2.0 AJAX Extensions\v1.0.nnnn.
To install ASP.NET AJAX from the command line, execute the following
command at a command prompt:
msiexec /i ASPAJAXExtSetup.msi [/q] [/log <log file name>]
[INSTALLDIR=<installation path>]
Specify the /q option to perform the installation without user
prompts. You can optionally provide an installation path and a file
name for logging. If you do not provide an installation path, the
default installation path is used.
If you want to add the ASP.NET 2.0 AJAX Futures CTP, download and
install it from the ASP.NET AJAX Downloads Web site.
If you want to add the ASP.NET AJAX Control Toolkit, download and
install it from ASP.NET AJAX Control Toolkit Web site.
Using ASP.NET AJAX with Visual Studio
If you have Microsoft Visual Studio 2005 installed on your computer,
the installation process installs templates for AJAX-enabled Web site
projects. It also installs an assembly (AJAXExtensionToolbox.dll) that
extends the Visual Studio toolbox. When you create a new AJAX-enabled
Web site by using Microsoft Visual Studio 2005, the template
automatically includes the Web.config file that includes the elements
required for ASP.NET AJAX components.
To add ASP.NET AJAX components to an existing site, modify the
Web.config file in the Web application by using the configuration
values from the sample Web.config file in the installation path. For
more information about ASP.NET AJAX configuration values, see
Configuring ASP.NET AJAX.
Using ASP.NET AJAX Without Visual Studio
If Microsoft .NET Framework version 2.0 is installed on a computer
without Microsoft Visual Studio 2005 or Visual Web Developer Express
Edition, the ASP.NET AJAX installation process adds the
System.Web.Extensions.dll assembly that contains server components to
the global assembly cache. It also copies a sample Web.config file to
the installation path. It does not install templates for AJAX-enabled
Web site projects or install the assembly for extending the Visual
Studio toolbox.
You can use ASP.NET AJAX in a Web application by adding the sample
Web.config file from the installation folder to the Web site
directory. You can also modify the Web.config file in an existing Web
application by using the configuration values from the sample
Web.config file. For more information about the ASP.NET AJAX
configuration values, see Configuring ASP.NET AJAX.
Installing the Microsoft AJAX Library on Non-Windows Environments
You do not have to build a Web site on a Windows-based environment to
use the client framework provided by the Microsoft AJAX Library. The
Microsoft AJAX Library consists of JavaScript files and will work with
any browsers that can run JavaScript code.
note
The Microsoft AJAX Library is installed with the full installation.
You do not have to install the Microsoft AJAX Library separately if
you have completed the full installation.
To install Microsoft AJAX Library
Download the MicrosoftAJAXLibrary.zip package from the ASP.NET AJAX
Downloads Web site.
Unzip the MicrosoftAJAXLibrary.zip package.
Copy the JavaScript files to the Web site.
ASP.NET AJAX Client Life-Cycle Events
Introduction
A Microsoft ASP.NET AJAX page raises the same server life-cycle events as an ASP.NET 2.0 Web page and also raises client life-cycle events. The client events enable you to customize the UI for both postbacks and for asynchronous postbacks (partial-page updates). The client events also help you manage custom script components during the lifetime of the page in the browser.
The client events are raised by classes in the Microsoft AJAX Library. These classes are automatically instantiated when a page contains ASP.NET AJAX server controls. The client classes provide APIs that enable you to bind to events and to provide handlers for those events. Because the Microsoft AJAX Library is browser independent, the code you write for your handlers works the same in all supported browsers.
The key event for initial requests (GET requests) and synchronous postbacks is the load event of the Application instance. When script in a load event handler runs, all scripts and components have been loaded and are available. When partial-page rendering with UpdatePanel controls is enabled, the key client events are the events of the PageRequestManager class. These events enable you to handle many common scenarios. These include the ability to cancel postbacks, to give precedence to one postback over another, and to animate UpdatePanel controls when their content is refreshed.
Client events are useful whether you are creating pages or writing components. If you are a page developer, you can provide custom script that is called when the page loads and unloads in the browser.
Client Classes
The two main Microsoft AJAX Library classes that raise events during the client life cycle of an ASP.NET AJAX Web page are the Application and PageRequestManager classes.
The Application class is instantiated in the browser when the page contains a ScriptManager control. The Application class resembles the Page server control, which derives from the Control class, but provides additional functionality for raising server events. Similarly, the Application class derives from the Sys.Component class, but raises client life-cycle events that you can handle.
If a page contains a ScriptManager control and one or more UpdatePanel controls, the page can perform partial-page updates (if partial-page rendering is enabled and supported in the browser). In that case, an instance of the PageRequestManager class is automatically available in the browser. The PageRequestManager class raises client events that are specific to asynchronous postbacks. For details about partial-page rendering, see Partial-Page Rendering Overview.
Adding Handlers for Client Events
To add or remove handlers for events raised by the Application and PageRequestManager classes, use the add_eventname and remove_eventname methods of those classes. The following example shows how to add a handler named MyLoad to the init event of the Application object.
CS
Sys.Application.add_init(MyInit);
function MyInit(sender) {
}
Sys.Appplication.remove_init(MyInit);
VB
Sys.Application.add_init(MyInit);
function MyInit(sender) {
}
Sys.Appplication.remove_init(MyInit);
This example shows just the syntax of the add_eventname and remove_eventname methods. Details about what you can do with specific events are provided later in this topic.
Handling the Application Load and Unload Events
To handle the load and unload events of the Application object, you do not have to explicitly bind a handler to the event. Instead, you can create functions that use the reserved names pageLoad and pageUnload. The following example shows how to add a handler for the load event of the Application object by using this approach.
CS
function pageLoad(sender, args) {
}
VB
function pageLoad(sender, args) {
}
Events for Other Client Classes
This topic describes only the events that are raised by the Application and PageRequestManager classes. The Microsoft AJAX Library also contains classes for adding, clearing, and removing handlers for DOM element events. These classes include the following:
-
The Sys.UI.DomEvent.addHandler method or the shortcut $addHandler.
-
The Sys.UI.DomEvent.clearHandlers method or the shortcut $clearHandlers.
-
The Sys.UI.DomEvent.removeHandler method or the shortcut $removeHandler.
Events raised by DOM elements are not discussed in this topic.
Client Events of the Application and PageRequestManager Classes
The following table lists client events of the Application and PageRequestManager classes that you can handle in AJAX ASP.NET-enabled pages. The order in which the events are raised is described later in this topic.
Event | Description |
---|---|
init Event | Raised after all scripts have been loaded but before any objects are created. If you are writing a component, the init event gives you a point in the life cycle to add your component to the page. The component can then be used by other components or by script later in the page life cycle. If you are a page developer, you should use the load event instead of the init event for most scenarios. The init event is raised only one time when the page is first rendered. Subsequent partial-page updates do not raise the init event. |
load Event | Raised after all scripts have been loaded and all objects in the application that are created by using $create are initialized. The load event is raised for all postbacks to the server, which includes asynchronous postbacks. If you are a page developer, you can create a function that has the name pageLoad, which automatically provides a handler for the load event. The pageLoad handler is called after any handlers that have been added to the load event by the add_load method. The load event takes an eventargs parameter, which is an Sys.ApplicationLoadEventArgs object. You can use the event arguments to determine whether the page is being refreshed as a result of a partial-page update and what components were created since the previous load event was raised. |
unload Event | Raised before all objects are disposed and before the browser window's window.unload event occurs. If you are a page developer, you can create a function that has the name pageUnload, which automatically provides a handler for the unload event. The pageUnload event is called just before the page is unloaded from the browser. During this event, you should free any resources that your code is holding. |
propertyChanged Event | Potentially raised when a property of a component changes. The Application object inherits this event from the Component class. This event is raised only if a component developer has called the Sys.Component.raisePropertyChange method in a property set accessor. For more information, see Defining Custom Component Properties and Raising PropertyChanged Events. The propertyChanged event takes an eventargs parameter, which is a Sys.applicationLoadEventArgs object. |
disposing Event | Raised when the Application instance is disposed. The Application object inherits this event from the Component class. |
initializeRequest Event | Raised before an asynchronous request starts. You can use this event to cancel a postback, such as to give precedence to another asynchronous postback. The initializeRequest event takes an eventargs parameter, which is a Sys.WebForms.InitializeRequestEventArgs object. This object makes available the element that caused the postback and the underlying request object. InitializeRequestEventArgs also exposes a cancel property. If you set cancel to true, the new postback is canceled. |
beginRequest Event | Raised before an asynchronous postback starts and the postback is sent to the server. If there is a postback already processing, it is stopped (by using the abortPostBack method). You can use this event to set request headers or to begin an animation on the page to indicate that the request is in process. The beginRequest event takes an eventargs parameter, which is a Sys.WebForms.BeginRequestEventArgs object. This object makes available the element that caused the postback and the underlying request object. |
pageLoading Event | Raised after the response from the server to an asynchronous postback is received, but before any content on the page is updated. You can use this event to provide a custom transition effect for updated content. The pageLoading event takes an eventargs parameter, which is an Sys.WebForms.PageLoadingEventArgs object. This object makes available information about what panels will be deleted and updated as a result of the most recent asynchronous postback. |
pageLoaded Event | Raised after all content on the page is refreshed, as a result of either a synchronous or an asynchronous postback. For synchronous postbacks, panels can only be created, but for asynchronous postbacks, panels can be both created and updated. You can use this event to manage a custom transition effect for updated content. The pageLoaded event takes an eventargs parameter, which is an Sys.WebForms.PageLoadedEventArgs object. This object makes available information about which panels were updated and created in the most recent postback. |
endRequest Event | Raised after the response for an asynchronous postback is processed and the page is updated, or during the processing of the response if there is an error. If an error occurs, the page is not updated. Use this event to provide customized error notification to users or to log errors. The endRequest event takes an eventargs parameter, which is a Sys.WebForms.EndRequestEventArgs object. This object makes available information about errors that have occurred and whether the error was handled. It also makes available the response object. |
Browser Compatibility and Security Settings for AJAX-Enabled ASP.NET Sites
Introduction
ASP.NET AJAX is compatible with most modern browsers. It runs with the default security settings for these browsers.
Browser and Operating System Compatibility
Users can view your AJAX-enabled ASP.NET sites by using most modern browsers. The following lists show compatible browser versions and operating systems.
Supported Browsers
-
Microsoft Internet Explorer 6.0 or later versions.
-
Mozilla Firefox version 1.5 or later versions.
-
Opera version 9.0 or later versions.
-
Apple Safari version 2.0 or later versions.
Supported Operating Systems
-
Microsoft Windows XP with Service Pack 2 installed.
-
Microsoft Vista.
-
Apple OSX (Intel architecture only).
Security and Privacy Settings
The following table lists required browser security and privacy settings for both user browsing and site development. In all cases, the recommended settings are the default settings for that browser.
Internet Explorer 6 | Make sure that the Internet Zone in the Security Zones settings is set to Medium. |
Internet Explorer 7 | Make sure that the Internet Zone in the Security Zones settings is set to Medium-High. |
FireFox 1.5 or later versions | In the Tools menu under Options, make sure that Enable JavaScript is selected. |
Opera 9.0 or later versions | In the Tools menu under Quick preferences, make sure that Enable JavaScript is selected. |
Safari 2.0 or later versions | Click Safari, Preferences, Security, and then Web Content and make sure that Enable JavaScript is selected. |
Configuring ASP.NET AJAX
Introduction
This topic describes the elements in the Web.config file that support Microsoft ASP.NET AJAX. It also describes how to incorporate those elements into the Web.config file for an existing ASP.NET application.
Using the ASP.NET AJAX Web Configuration File in a New Web Site
When you create a new AJAX-enabled Web site, you can use the Web.config file provided in the installation package to add the required configuration settings. In Visual Studio, the Web.config file for Microsoft ASP.NET AJAX is included in your project when you create a new ASP.NET AJAX-enabled Web Site.
If you have to manually add the Web.config file to a new Web site, you can get a copy of it from the installation path. By default, the file is in the following location:
Adding ASP.NET AJAX Configuration Elements to an Existing Web Site
In an existing Web site, you typically have values in the Web.config file that you want to retain. In that case, you can add the new ASP.NET AJAX elements into the existing Web.config file.
The new elements are part of the following configuration sections:
-
The <configSections> element
-
The <controls> element
-
The <assemblies> element
-
The <httpHandlers> element
-
The <httpModules> element
-
The <system.web.extensions> element
-
The <system.webserver> element
The <configSections> Element
The <configSections> element creates a configuration section and subsections for the SystemWebExtensionsSectionGroup class. You set the properties for these sections in the <system.web.extensions> element.
The following example shows the <configSections> element for ASP.NET AJAX. Add this section to the existing Web.config file as a child of the <configuration> element.
<configuration>
<configSections>
<sectionGroup name="system.web.extensions"
type="System.Web.Configuration.SystemWebExtensionsSectionGroup,
System.Web.Extensions, Version=1.0.61025.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35">
<sectionGroup name="scripting"
type="System.Web.Configuration.ScriptingSectionGroup,
System.Web.Extensions, Version=1.0.61025.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35">
<section name="scriptResourceHandler"
type="System.Web.Configuration.ScriptingScriptResourceHandlerSection,
System.Web.Extensions, Version=1.0.61025.0,
Culture=neutral, PublicKeyToken=31bf3856ad364e35"
requirePermission="false"
allowDefinition="MachineToApplication"/>
<sectionGroup name="webServices"
type="System.Web.Configuration.ScriptingWebServicesSectionGroup,
System.Web.Extensions, Version=1.0.61025.0,
Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<section name="jsonSerialization"
type="System.Web.Configuration.ScriptingJsonSerializationSection,
System.Web.Extensions, Version=1.0.61025.0,
Culture=neutral, PublicKeyToken=31bf3856ad364e35"
requirePermission="false" allowDefinition="Everywhere" />
<section name="profileService"
type="System.Web.Configuration.ScriptingProfileServiceSection,
System.Web.Extensions, Version=1.0.61025.0,
Culture=neutral, PublicKeyToken=31bf3856ad364e35"
requirePermission="false"
allowDefinition="MachineToApplication" />
<section name="authenticationService"
type="System.Web.Configuration.ScriptingAuthenticationServiceSection,
System.Web.Extensions, Version=1.0.61025.0,
Culture=neutral, PublicKeyToken=31bf3856ad364e35"
requirePermission="false"
allowDefinition="MachineToApplication" />
</sectionGroup>
</sectionGroup>
</sectionGroup>
</configSections>
</configuration>
The <controls> Element
The <controls> element registers ASP.NET AJAX namespaces in the System.Web.Extensions assembly and maps the asp tag prefix as an alias for these namespaces. The controls in the ASP.NET AJAX namespaces can be referenced in a Web page with syntax such as the following:
<asp:ScriptManager ID="ScriptManager1" runat="server" />
The following example shows the <controls> element for ASP.NET AJAX. Add this section to the existing Web.config file as a child of the <system.web><pages> element.
<system.web>
<pages>
<controls>
<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</controls>
</pages>
</system.web>
The <assemblies> Element
The <assemblies> element registers the System.Web.Extensions assembly.
The following example shows the <assemblies> element for ASP.NET AJAX. Add this section to the existing Web.config file as a child of the <system.web><compilation> element.
<system.web>
<compilation>
<assemblies>
<add assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</assemblies>
</compilation>
</system.web>
The <httpHandlers> Element
The <httpHandlers> element adds new handlers for script requests.
The following example shows the <httpHandler> element for ASP.NET AJAX. Add this section to the existing Web.config file as a child of the <system.web> element.
<system.web>
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>
</httpHandlers>
</system.web>
The <httpModules> Element
The <httpModules> element defines HTTP modules used in ASP.NET AJAX.
The following example shows the <httpModules> element for ASP.NET AJAX. Add this section to the existing Web.config file as a child of the <system.web> element.
<system.web>
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</httpModules>
</system.web>
The <system.web.extensions> Element
The <system.web.extensions> element provides elements that can be uncommented to configure how Web services are called from Microsoft ASP.NET AJAX applications. The <jsonSerialization> element is used to specify custom type converters and to override default settings for JSON serialization. The <converters> element specifies custom type converters. The <authenticationService> element is used to enable or disable the authentication service. The <profileService> element is used to enable or disable the profile service and to specify which properties are exposed by the service. The <scriptResourceHandler> element is used to enable or disable caching and compression of resources used with scripts.
The <scriptResourceHandler> element, <authenticationService> element, and <profileService> element can be defined only in the Machine.config file or in the Web.config file in the application root directory. The <jsonSerialization> element can be defined in the Machine.config file, in the Web.config file in the application root directory, or in a Web.config file in a subfolder of the Web site.
The following example shows the <system.web.extensions> element for ASP.NET AJAX. Add this section and its subsections to the existing Web.config file as a child of the <configuration> element.
<system.web.extensions>
<scripting>
<webServices>
<!-- Uncomment this line to customize maxJsonLength and add a
custom converter -->
<!--
<jsonSerialization maxJsonLength="500">
<converters>
<add name="ConvertMe"
type="Acme.SubAcme.ConvertMeTypeConverter"/>
</converters>
</jsonSerialization>
-->
<!-- Uncomment this line to enable the authentication service.
Include requireSSL="true" if appropriate. -->
<!--
<authenticationService enabled="true" requireSSL = "true|false"/>
-->
<!-- Uncomment these lines to enable the profile service. To
allow profile properties to be retrieved
and modified in ASP.NET AJAX applications, you need to add
each property name to the readAccessProperties and
writeAccessProperties attributes. -->
<!--
<profileService enabled="true"
readAccessProperties="propertyname1,propertyname2"
writeAccessProperties="propertyname1,propertyname2" />
-->
</webServices>
<!--
<scriptResourceHandler enableCompression="true"
enableCaching="true" />
-->
</scripting>
</system.web.extensions>
The <system.webserver> Element
The <system.webserver> element contains configuration settings used by Microsoft Internet Information Server (IIS) 7.0.
The following example shows the <system.webserver> element for ASP.NET AJAX. Add this section to the existing Web.config file as a child of the <configuration> element.
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules>
<add name="ScriptModule"
preCondition="integratedMode"
type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</modules>
<handlers>
<remove name="WebServiceHandlerFactory-ISAPI-2.0"/>
<add name="ScriptHandlerFactory" verb="*" path="*.asmx"
preCondition="integratedMode"
type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add name="ScriptHandlerFactoryAppServices" verb="*"
path="*_AppService.axd" preCondition="integratedMode"
type="System.Web.Script.Services.ScriptHandlerFactory,
System.Web.Extensions, Version=1.0.61025.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35"/>
<add name="ScriptResource" preCondition="integratedMode"
verb="GET,HEAD" path="ScriptResource.axd"
type="System.Web.Handlers.ScriptResourceHandler,
System.Web.Extensions, Version=1.0.61025.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35" />
</handlers>
</system.webServer>
Explain ASP.NET AJAX Client Architecture
The ASP.NET AJAX client-script libraries consist of JavaScript (.js) files that provide features for object-oriented development. The object-oriented features included in the ASP.NET AJAX client-script libraries enable a high level of consistency and modularity in client scripting. The following layers are included in the ASP.NET AJAX script libraries:
-
A browser compatibility layer. This provides compatibility across the most frequently used browsers (including Microsoft Internet Explorer, Mozilla Firefox, and Apple Safari) for your ASP.NET AJAX scripts.
-
ASP.NET AJAX core services, which include extensions to JavaScript, such as classes, namespaces, event handling, inheritance, data types, and object serialization.
-
An ASP.NET AJAX base class library, which includes components such as string builders and extended error handling.
-
A networking layer that handles communication with Web-based services and applications, and that manages asynchronous remote method calls.
-
Support for JavaScript libraries that are either embedded in an assembly or are provided as standalone JavaScript (.js) files. Embedding JavaScript libraries in an assembly can make it easier to deploy applications and can solve versioning issues.
-
Support for accessing server-based forms authentication and profile information in client script. This support is also available to Web applications that are not created by using ASP.NET, as long as the application has access to the Microsoft AJAX Library.
-
Support for release and debug modes and localization support for both assembly-embedded and standalone JavaScript files
What are ASP.NET AJAX Server Controls?
The ASP.NET AJAX server controls consist of server and client code that integrate to produce AJAX-like behavior. The following list describes the most frequently used ASP.NET AJAX server controls.
- ScriptManager
-
Manages script resources for client components, partial-page rendering, localization, globalization, and custom user scripts. The ScriptManager control is required in order to use the UpdatePanel, UpdateProgress, and Timer controls.
- UpdatePanel
-
Enables you to refresh selected parts of the page, instead of refreshing the whole page by using a synchronous postback.
- UpdateProgress
-
Provides status information about partial-page updates in UpdatePanel controls.
- Timer
-
Performs postbacks at defined intervals. You can use the Timer control to post the whole page, or use it together with the UpdatePanel control to perform partial-page updates at a defined interval.
Why Use ASP.NET AJAX?
-
Improved efficiency by performing significant parts of a Web page's processing in the browser.
-
Familiar UI elements such as progress indicators, tooltips, and pop-up windows.
-
Partial-page updates that refresh only the parts of the Web page that have changed.
-
Client integration with ASP.NET application services for forms authentication and user profiles.
-
Integration of data from different sources through calls to Web services.
-
A framework that simplifies customization of server controls to include client capabilities.
-
Support for the most popular and generally used browsers, which includes Microsoft Internet Explorer, Mozilla Firefox, and Apple Safari.
Why is the .NET Framework 3.0 a major version numb...
Which version of the Common Language Runtime (CLR)...
Will the name change be reflected in any of the ex...
How does the .NET Framework 3.0 relate to the .NET...
What happens to the WinFX technologies?
What is the .NET Framework 3.0 (formerly WinFX)?
System Requirements for Installing .NET Framework ...
What Improvements does WCF offers over its earlier...
What are WCF features and what communication probl...
What contemporary computing problems WCS solves?
What contemporary computing problems WPF solves?
What is XAML ?
What is XBAP?
What is a service contract ( In WCF) ?
In terms of WCF, What is a message?
In terms of WCF, What is a service?
In terms of WCF, What is an endpoint?
In terms of WCF, What is an application endpoint?
In terms of WCF, What is an infrastructure endpoin...
In terms of WCF, What is an address?
In terms of WCF, What is an address?
In terms of WCF, What is binding?
What is an operation contract?
What is a message contract?
What is a fault contract?
N WCF, what do you understand by metadata of a ser...
What is password fatigue?
What are activities in WWF?
Jobs in USA ->NET
Learn .NET Framework 3.0
Download Microsoft .NET Framework 3.0 Redistributa...