Building Microsoft ASP.NET Applications for Mobile Devices, Second Edition [Electronic resources] نسخه متنی

اینجــــا یک کتابخانه دیجیتالی است

با بیش از 100000 منبع الکترونیکی رایگان به زبان فارسی ، عربی و انگلیسی

Building Microsoft ASP.NET Applications for Mobile Devices, Second Edition [Electronic resources] - نسخه متنی

Andy Wigley; Peter Roxburgh

نمايش فراداده ، افزودن یک نقد و بررسی
افزودن به کتابخانه شخصی
ارسال به دوستان
جستجو در متن کتاب
بیشتر
تنظیمات قلم

فونت

اندازه قلم

+ - پیش فرض

حالت نمایش

روز نیمروز شب
جستجو در لغت نامه
بیشتر
افزودن یادداشت
افزودن یادداشت جدید






Chapter 2, you created applications that consisted only of controls dragged out of the Visual Studio.NET Toolbox and positioned on a mobile Web Forms control. Of course, these simple examples are not representative of real applications. In reality, your applications consist not only of controls dragged onto a form, but also code that runs on the server to perform some function and then displays the results using the mobile controls. To demonstrate how you run code in your application, we'll create a simple application that displays a command button. When the user clicks the command button, the form displays the current time. We'll program this in two different ways: using code-behind files and then using inline code.


The Code-Behind Technique


With the code-behind technique, you place your application's mobile controls in an .aspx file and you store the application's code in a separate file. The code file usually has the extension .aspx.cs for C# files, and .aspx.vb for Microsoft Visual Basic .NET files.

Create a new ASP.NET mobile Web project, named Time. Drag a Label control and a Command control from the Toolbox onto the Form1 control, which will display the time. Clear the Text property of the Label control. Set the Text property of the Command control to Update Time. If you now double-click the Command control, Visual Studio .NET opens an editing window on a different file which is the code-behind module for the application, with the cursor positioned in the Command1_Click method that it has created for you. This method executes every time the user clicks the command button. Enter the following code in the Command1_Click method:

    private void Command1_Click(object sender, System.EventArgs e) 
{
Label1.Text = DateTime.Now.ToString("T");
}

This code uses the Now method of the .NET Framework System.DateTime class to get the current date and time and then converts that information to a string using the ToString method. The "T" format modifier ensures that the return string contains just the time portion of the DateTime object. Build and run this application to verify that it works correctly.

Notice that the file containing the program code that Visual Studio .NET displays is named MobileWebForm1.aspx.cs and that it contains a complete class definition. The Design view that was displayed by the Mobile Internet Designer when you first opened the project is a view of a file named MobileWebForm1.aspx.

Working with Controls in the Code-Behind Class


The code-behind version of the Time application sets the Text property of Label1 with the following code:

protected System.Web.UI.MobileControls.Label Label1;


private void Command1_Click(object sender, System.EventArgs e)
{
Label1.Text = DateTime.Now.ToString("T");
}


The Label1 object is declared as a data member of the class of type System.Web.UI.MobileControls.Label. If you look at the Design view of the .aspx file, the Properties window of the same Label control reveals that Visual Studio .NET has set the ID property of the label to Label1.

To manipulate a mobile control in class methods in the code-behind module, you must include in that class a reference to the mobile control using the same name as the ID assigned to the control in the .aspx file. This reference must be declared using the protected modifier, which is similar to a private class member but is accessible to descendant classes. As you'll learn in the next section, the .aspx file actually defines a class that is a descendant of the class in the code-behind file, so this modifier is necessary to tie the two parts together. Listings 3-1 and 3-2 demonstrate how to use this modifier.





Note

When you drag a control onto a form using the Mobile Internet Designer, Visual Studio .NET automatically adds the required object declarations for the control to your code-behind class.


Listing 3-1: C# example that declares a class member for manipulating visual controls from the parent class






using System;
namespace Time
{
public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage
{
protected System.Web.UI.MobileControls.Label Label1;
protected System.Web.UI.MobileControls.Command Command1;
override protected void OnInit(EventArgs e)
{
this.Command1.Click +=
new System.EventHandler(this.Command1_Click);
}
private void Command1_Click(object sender, System.EventArgs e)
{
Label1.Text = DateTime.Now.ToString("T");
}
}
}











Listing 3-2: Visual Basic .NET example that declares a class member for manipulating visual controls from the parent class






Public Class MobileWebForm1
Inherits System.Web.UI.MobileControls.MobilePage
Protected Label1 As System.Web.UI.MobileControls.Label
Protected WithEvents Command1 As System.Web.UI.MobileControls.Command
Private Sub Command1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Command1.Click
Label1.Text = DateTime.Now.ToString("T")
End Sub
End Class












Design and HTML Views


Before we consider the inline coding technique for creating ASP.NET mobile Web Forms, let's look more closely at the .aspx file for the code-behind version. Understanding this file will help you to understand the difference between the two techniques.

On the taskbar at the bottom of the Design window for MobileWebForm1.aspx in the Time application, you'll see two view options: Design and HTML. Select HTML view (shown in Figure 3-1).


Figure 3-1: The MobileWebForm1.aspx mobile Web Forms page in HTML view

The Design and HTML views offer alternative ways to view the same file. In Design view, you drag visual representations of the mobile controls from the Toolbox onto a mobile Web Forms page. Whenever you drop a control onto a Form, Visual Studio .NET writes XML representing that control into the .aspx file. The visual display of mobile controls that you see in the Design view is simply a visual representation of the XML stored in the .aspx file. When you save the .aspx file, you're not saving a complex document with embedded graphical objects, you're actually saving a simple text file in ASP.NET server control syntax, which is the text shown when you select HTML view. In fact, Source view might be a more appropriate name than HTML view, since the text you are looking at is not HTML at all, but XML, but Microsoft uses the latter term because ASP.NET is a successor to Microsoft Active Server Pages (ASP) and ASP developers are accustomed to working with the HTML view.

The two lines of code at the top of the HTML view in Figure 3-1 are ASP.NET page directives, which specify settings that ASP.NET compilers must use when processing the page. The @ Page directive defines page-specific attributes that the ASP.NET page parser and compiler use. Some of the more important attributes are described here:



language="c#"This directive tells the ASP.NET runtime to compile any inline code included within the page as C#. For example, code included in the page might appear as inline rendering (code enclosed by <% %> or <%= %> tags) or as code-declaration blocks (code within <script> and </script> tags), as described in the next section.



Codebehind="MobileWebForm1.aspx.cs"As an alternative to inline code—or in addition to it—ASP.NET allows you to place code logic in an alternative file, the code-behind file. The Codebehind="MobileWebForm1.aspx.cs" declaration tells the runtime where to find this code. Visual Studio .NET always creates a code-behind module for a mobile Web Forms page.



Inherits="Time.MobileWebForm1"Although not a program module in the traditional sense, the source in the .aspx file actually defines a .NET class, which inherits from a class defined in its code-behind module. Every mobile Web Forms page must inherit from the .NET MobilePage class or a class that derives from it. The class that the ASP.NET page compiler constructs from this page inherits from the Time.MobileWebForm1 class, which is the class defined in the code-behind module.



The second line of the mobile Web Forms page that Visual Studio .NET generated reads as follows:

<%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" 
Assembly="System.Web.Mobile" %>

This syntax simply tells the ASP.NET runtime that when it compiles the page for display, any server control tags using the prefix mobile (such as <mobile:Form…> and <mobile:Label…>) represent controls found in the System.Web.UI.MobileControls namespace, within the System.Web.Mobile assembly. (An assembly is the .NET name for a compiled file containing executable code, similar to an .exe or a .dll file. The System.Web.Mobile.dll assembly contains the Mobile Internet Controls Runtime and all the mobile Web Forms controls.)

Below the heading lines, you'll see the following syntax contained in the <body> element:

<mobile:Form id=Form1 runat="server">
<mobile:Label id="Label1" runat="server"></mobile:Label>
<mobile:Command id="Command1" runat="server">Update Time</mobile:Command>
</mobile:Form>

An XML element represents each control that you place on a mobile Web Forms page. The start tag for the mobile Form control is <mobile:Form …>, and the end tag is </mobile:Form>. The elements for the Label control and the Command control are enclosed within the Form control's tags. The syntax you use for this XML representation of visual controls is called ASP.NET server control syntax and it is also known as the persistence format.

When you drag a control from the Toolbox onto the Form control using the Mobile Internet Designer, the designer records this action by writing the XML element for that control within the Form tags. The Text property of controls that you set through the Properties window appears here as the value of the XML element, which is the text positioned between a control's start and end tags. For example, if you use the Visual Studio .NET Properties window to set the Text property of the Label control to "Hello World", the server control syntax for the Label control would look like this:

<mobile:Label id=Label1 runat="server">Hello World</mobile:Label>

The other way to represent properties in server control syntax is as XML attributes, which assign values to identifiers within a control's start tags using the form property-name=value. For example, you can set a control's ID property through an attribute, as shown here:

<mobile:Form id=Form1 runat="server"></mobile:Form>

The XML text, which represents the mobile controls, lies within the body of the document and is enclosed within the <body> and </body> tags. The three <meta> tags are additional metadata that Visual Studio .NET uses only at design time.


The Inline Coding Technique


When you use inline coding, program logic is in the same file as your mobile controls. You must work in the HTML View of a mobile Web Forms page. You can include inline code within mobile Web Forms pages in two ways. The first and perhaps most commonly used syntax is to delimit sections of code by using <script> tags. You can use a text editor to create a new version of the Time application using inline coding, as shown here:

<%@ Page Inherits="System.Web.UI.MobileControls.MobilePage" Language="C#"%>
<%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls"
Assembly="System.Web.Mobile" %>
<script language="C#" runat="server">
public void DisplayCurrentTime(Object sender, EventArgs e)
{
Label1.Text=DateTime.Now.ToString("T");
}
</script>
<mobile:Form runat="server">
<mobile:Label runat="server" id="Label1" text="/>
<mobile:Command runat="server" text="Update Time" id="Command1"
onClick="DisplayCurrentTime"/>
</mobile:Form>

Most of this code is similar to that shown in the HTML view of the Time application you created in Visual Studio .NET. However, the section enclosed by the lines containing the <script> tags is new. The first of these <script> tags declares that the following section is script rather than mobile Web Forms controls. This element has two attributes: the Language attribute states that the code is written in C#, and the runat attribute states that code should execute on the server.

The inline code consists of the three lines that are between the <script> and </script> tags. This C# code displays the current time in the Label1 control. If you look at the line further down that begins with <mobile:Command, you'll see that the Command control has an event attribute named onClick. This attribute's value is the name of the inline code method that executes when the command button's onClick event fires.

Save the code to a file named InlineTime.aspx, and place it in the root directory of your Internet Information Services (IIS) server (in \inetpub\wwwroot). If you access the URL http://localhost/InlineTime.aspx from a browser, you'll see an application that behaves the same as the Time application you created in Visual Studio .NET.








Language Choice


You can code a code-behind module in any of the more than 20 .NET languages available from Microsoft and other suppliers, because you must compile it into a separate assembly before deploying your application and put the resulting dynamic-link library (DLL) into your application's /bin directory.

You have less flexibility with inline code that you include in <script> … </script> blocks in an .aspx file. This file is compiled at run time by the ASP.NET page compiler, and the compiler understands only Visual Basic .NET, C#, J#, or Microsoft JScript .NET.











Inline Coding with Data-Binding Statements


Data binding, the second way of providing inline code, is a little more complex than placing blocks of code inside <script> tags. You can include data-binding statements anywhere within your mobile Web Forms page. The binding takes the form <%# InlineCode %>, where InlineCode can be one of the following items:



The name of a property or collection in the code-behind module



An expression, which the runtime evaluates



A call to a method in the code-behind module



When the runtime loads the Web Forms page, it evaluates any expressions, makes any method calls, and then writes the results—along within any property or collection values—to the requesting device.

This method of inline coding is particularly useful when you're working with templates and list controls. In Chapter 9, Chapter 10, and Chapter 11, we'll discuss the data binding technique more fully, in the context of the more advanced scenarios in which it's used.





Note

ASP developers might wonder whether they can use the <% … %> syntax to include inline code within a mobile Web Forms page. When using ASP.NET mobile Web Forms, you can't use this syntax. The closest syntax is that used for data binding. ASP developers might be interested to know that ASP.NET does support the use of this syntax in nonmobile projects, but unlike in ASP, it's illegal to declare a method or a class within these delimiters.



The MobilePage Class


The example we used in the previous section, called The Inline Coding Technique, begins with the following @ Page statement:

<%@ Page Inherits="System.Web.UI.MobileControls.MobilePage" Language="C#"%>

Notice that there is no Codebehind attribute naming a code-behind module and the Inherits attribute states that this Web Forms page inherits from System.Web.UI.MobileControls.MobilePage rather than from a class in a code-behind module. If you look again at the code-behind module for the first version of the Time application you created in this chapter, you'll notice that the class defined in that module inherits from MobilePage. Figure 3-2 compares the inheritance trees for ASP.NET mobile Web Forms using inline coding to those using a code-behind module. In fact, more classes are involved than are shown here—the MobilePage class itself inherits from System.Web.UI.Page, which is the class that implements an ASP.NET Web Forms control targeting desktop browsers.


Figure 3-2: Inheritance for a single file ASP.NET Mobile Web Forms application compared to an application using a code-behind module

Although it doesn't appear anything like a class definition written in a programming language like C# or Visual Basic .NET, the text in the .aspx file is also a class definition. The first time a client calls an ASP.NET application, the ASP.NET runtime parses the .aspx file and builds a .NET class from it, which it then compiles into a .NET assembly. (Subsequent calls to the same application use a cached version of the generated assembly, so the compilation process does not need to be repeated.) As explained in the section "Design and HTML Views," earlier in this chapter, the ASP.NET server control syntax maps directly to control classes, and attributes and values define properties of those controls. The ASP.NET page compiler creates a class containing instances of the mobile controls that you dragged onto the mobile Web Forms control when you designed it—such as a mobile Web Forms control containing a mobile Label control and a mobile Command control, as in the sample Time application. The ASP.NET runtime executes the compiled assembly to generate the markup that is sent back to the client.


Properties of the MobilePage Class


The MobilePage class is the base class for all mobile Web Forms pages. The MobilePage class provides a number of properties that you can use in your applications. Table 3-1 describes some of the more commonly used properties. Look up the MobilePage class in the .NET Framework SDK documentation for details of all the properties available to you.



























Table 3-1: Commonly Used MobilePage Class Properties


Property


Description


ActiveForm


Sets or gets the currently active Form control. Mobile Web Forms often contain more than one Form control. The ActiveForm property specifies which Form control is displayed to the user.


Device


Provides access to the MobileCapabilities object for the current requesting device. See Chapter 9 for details of how to make use of the MobileCapabilities object.


HiddenVariables


Returns a dictionary of hidden variables in which data associated with the mobile Web Forms page can be stored.


IsPostBack


This property returns False the very first time an application runs the code in your application, but True on each subsequent postback. See the next example application in this chapter for an example of its use.


ViewState


Provides access to a dictionary structure, which is useful for persisting variables in a MobilePage-derived class across different requests (as shown in the section "Programming State Management in ASP.NET," later in this chapter). The ViewState property is saved on the Web server so that token round-trips between the client and ViewState can be tracked and restored on subsequent requests.


A run-time error occurs if a compiled instance of MobilePage—in other words, your mobile Web application—doesn't contain any Form controls. A mobile Web Forms page must contain at least one Form control.

/ 145