Free Essay

Javascript

In:

Submitted By lmoretti
Words 5454
Pages 22
11
ASP.NET
In this chapter you will: o o o o o o Learn about client/server architecture Study server-side scripting Create ASP .NET applications Learn about object collections Study ASP .NET’s core objects Create a guest book

CHAPTER

Y

our Web browser is a client in the client/server environment of the Web. Up to this point, this book has focused on client-side JavaScript development in Web browsers. For you to develop a full complement of Web development skills, you also need to understand the server side of the Web— in particular, how server-side scripting fits into Web development. In this chapter, you will study server-side scripting with ASP.NET. But before getting into server-side scripting, it’s helpful to set the stage by reviewing the fundamentals of client/server architecture.

507

508

Chapter 11

ASP.NET

CLIENT/SERVER ARCHITECTURE
There are many definitions of the term’s client and server. In traditional client/server architecture, the server is usually some sort of database from which a client requests information. A server fulfills a request for information by managing the request or serving the requested information to the client—hence the term, client/server. A system consisting of a client and a server is known as a two-tier system. One of the primary roles of the client, or front end, in a two-tier system is the presentation of an interface to the user.The user interface gathers information from the user, submits it to a server, or back end, then receives, formats, and presents the results returned from the server. The main responsibility of a server is usually data storage and management. Heavy processing, such as calculations, on client/server systems usually takes place on the server. As desktop computers become increasingly powerful, however, many client/server systems place at least some of the processing responsibilities on the client. In a typical client/server system, a client computer may contain a front end that is used for requesting information from a database on a server. The server locates records that meet the client request, performs some sort of processing, such as calculations on the data, then returns the information to the client. The client computer may also perform some processing such as building the queries that are sent to the server or formatting and presenting the returned data. Figure 11-1 illustrates the design of a two-tier client/server system.

Client request Server response

Client

Server

Figure 11-1

The design of a two-tier client/server system

The Web is built on a two-tier client/server system, in which a Web browser (the client) requests documents from a Web server.The Web browser is the client user interface.You can think of the Web server as a database of Web pages. Once a Web server returns the requested document, the Web browser (as the client user interface) is responsible for formatting and presenting the document to the user. Once you start adding databases and other types of applications to a Web server, the client/server system evolves into what is known as a three-tier client architecture. A three-tier, or multitier, client/server system consists of three distinct pieces: the client tier, the processing tier, and the data storage tier.The client tier, or user interface tier, is still the Web browser. However, the database portion of the two-tier client/server system

Client/Server Architecture

509

is split into a processing tier and the data storage tier.The processing tier, or middle tier, is sometimes called the processing bridge. It handles the interaction between the Web browser client and the data storage tier. Essentially, the client tier makes a request of a database on a Web server.The processing tier performs any necessary processing or calculations based on the request from the client tier, and then reads information from or writes information to the data storage tier. The processing tier also handles the return of any information to the client tier. Note that the processing tier is not the place processing takes place. The Web browser (client tier) still renders Web page documents (which requires processing), and the database or application in the data storage tier may also perform some processing. Client-side JavaScript exists at the client tier, while serverside JavaScript exists at the processing tier. Figure 11-2 illustrates the design of a threetier client/server system.
Two-tier client/server architecture is a physical arrangement in which the client and server are two separate computers. Three-tier client/server architecture is more conceptual than physical, because the processing tier and data storage tier can be located on the same server. Multitier client/server architecture is also referred to as n-tier architecture.

Client tier

Processing tier

Data storage tier

11

Handles user interface display (the Web browser) and submits requests to the processing tier

Handles interaction between the Web browser client and the data storage tier

Stores data in a database and returns requests presented by the processing tier

Can be the same computer

Figure 11-2

The design of a three-tier client/server system

An important question in the design of any client/server system is deciding how much processing to place on the client. In the context of Web site development with JavaScript, you must decide whether to use client-side or server-side JavaScript. This decision may sound confusing, because client-side JavaScript and server-side JavaScript share much of the same core language. However, whether to use client-side or server-side JavaScript is important consideration because the choice you make can greatly affect the performance

510

Chapter 11

ASP.NET

of your program. A general rule of thumb is to allow the client to handle the user interface processing and light processing, such as data validation, but have the server perform intensive calculations and data storage.This division of labor is especially important when dealing with the Web. Unlike with clients on a private network, it’s not possible to know in advance the computing capabilities of each client on the Web.You cannot assume that each client (browser) that accesses your client/server application (Web site) has the necessary power to perform the processing required by the application. For this reason, intensive processing should be placed on the server. Because servers are usually much more powerful than client computers, your first instinct may be to let the server handle all processing and only use the client to display a user interface. Although you do not want to overwhelm clients with processing they cannot handle, it is important to perform as much processing as possible on the client for several reasons: s Distributing processing among multiple clients creates applications that are more powerful because the processing power is not limited to the capabilities of a single computer. Client computers become more powerful every day, and advanced capabilities such as JavaScript and DHTML are now available in local Web browsers. Thus, it makes sense to use a Web application to harness some of this power and capability. (A Web application is a program that executes on a server but that clients access through a Web page loaded in a browser.) Local processing on client computers minimizes transfer times across the Internet and creates faster applications. If a client had to wait for all processing to be performed on the server, a Web application could be painfully slow over a busy Internet connection. Performing processing on client computers lightens the processing load on the server. If all processing in a three-tier client/server system is on the server, the server for a popular Web site could become overwhelmed trying to process requests from numerous clients.
The term distributed application is used to describe multiple computers sharing the computing responsibility for a single application.

s

s

Server-side Scripting

511

SERVER-SIDE SCRIPTING
Chapter 5 touched on three-tier client/server processing in relation to server-side scripting languages that execute on a Web server. Some of the more popular server-side scripting languages that are used to process form data include Common Gateway Interface (CGI), Java Server Pages (JSP), and Active Server Pages (ASP). Server-side scripting languages exist on the processing tier and have the ability to handle communication between the client tier and the data storage tier. At the processing tier, a scripting language usually prepares and processes the data in some way before submitting it to the data storage tier. Additionally, server-side JavaScript can interact closely with client-side JavaScript, because they share the same basic programming features. For these reasons, many developers prefer server-side scripting languages for handling the processing tier of a three-tier client/server system. Server-side scripting languages are not without their drawbacks. One of their biggest disadvantages is that server-side scripting languages are proprietary and vendor specific. There is no server-side scripting language standard similar to ECMAScript. Although server-side scripting languages are proprietary and vendor specific, most implementations use much of the same core language syntax that you have learned for client-side JavaScript. You can write server-side scripts using many of the skills you have already learned in client-side JavaScript, regardless of the server-side scripting language you use. In this chapter, you will use ASP.NET, which is a server-side scripting language created by Microsoft. ASP.NET is the latest version of Active Server Pages and is part of the Microsoft Visual Studio .NET line of software development products. You can create ASP.NET using one of the following Windows platforms: s s s

11

Windows 2000 (Professional, Server, and Advanced Server) Windows XP Professional Windows Server 2003 family for both client and server applications

To use ASP.NET, you must also install Internet Information Services (IIS), which are used for creating, configuring, and managing Web sites. IIS is available with each of the preceding platforms. See your Windows documentation for information on installing and configuring IIS.
The examples and figures in this chapter were created using Windows XP Professional.

The Microsoft Visual Studio .NET line of software development products includes a platform called the .NET Framework, which is designed for creating, deploying, and running Web applications and services. In order to create ASP.NET applications, you must install the .NET Framework. ASP.NET is automatically installed as part of the

512

Chapter 11

ASP.NET

Windows Server 2003 family. For Windows 2000 and Windows XP Professional, ASP.NET and the .NET Framework are installed as part of Visual Studio .NET or through the Microsoft .NET Framework SDK. If you do not have Visual Studio .NET, you can download the Microsoft .NET Framework SDK free from http://msdn.microsoft.com/ downloads/default.aspx.
Because the goal of this book is to teach JavaScript, this chapter provides only a brief overview of ASP.NET. The installation and configuration requirements for ASP.NET, the .NET Framework, or IIS are beyond the scope of this book. For installation and configuration procedures, along with additional information on working with ASP.NET, see the Microsoft ASP.NET page at http://msdn.microsoft.com/asp.net/. If you are in a classroom setting, ask your instructor for specific instructions on how to work with ASP.NET at your institution.

The ASP.NET techniques you study in this chapter are identical in both ASP and ASP.NET. Although the chapter focuses on ASP.NET, you can also perform the exercises in this chapter with ASP if you do not have access to ASP.NET. Active Server Pages are supported by Internet Information Server 3.0 and higher running on Windows NT Server 4.0 and Windows 2000, Peer Web Services running on Windows NT Workstation 4.0, and Personal Web Server running on Windows 95/98. Older versions of ASP (without the .NET extension) use a file extension of .asp. You save ASP.NET documents in a folder that you designate as a virtual directory in IIS. Once you create a virtual directory in IIS, you can open any files it contains in a Web browser using the following syntax: http://computer_name/directory/file. For example, if your computer is named personal_computer and you create a virtual directory named interests, you can open a document named index.html by typing the following statement in a Web browser’s address bar: http://personal_computer/interests/ index.html. Alternatively, you can replace the computer name with localhost, as follows: http://localhost/interests/index.html. The term localhost is an alias for the name of a computer.
You can change the name of your computer using the System Properties dialog box in the Control Panel.

In this chapter, you will create a Web site for a company named WebAdventure; the Web site will use ASP.NET to store the number of hits it receives, and it will include an area where visitors can sign a guest book. The program you create will not be a complete, robust Web site, because it includes only a hit counter and a database. However, it will serve to demonstrate how to create a basic program with ASP.NET. Next, you will create a virtual directory in IIS for the WebAdventure Web site.The following instructions are for Windows 2000, Windows XP, and Windows Server 2003. If

Server-side Scripting

513

you are running Peer Web Services or Personal Web Server, refer to your Windows documentation for information on creating a virtual directory. To create a virtual directory in IIS for the WebAdventure Web site: 1. Open the Control Panel from the Start menu. 2. If you are using Windows XP, click the Switch to Classic View link to display the Control Panel icons. 3. Use the Administrative Tools icon to open the Administrative Tools window. 4. Select Internet Information Services. The Internet Information Services window opens. 5. Click the plus sign next to the icon that represents your computer, and then click the plus sign next to the Web Sites folder, if necessary. 6. Click the plus sign next to the Default Web Site icon that appears beneath the computer name icon. Figure 11-3 shows the Internet Information Services window on a computer named DONGOSSELIN.

11

Figure 11-3

Internet Information Services window

7. Verify that the Default Web Site icon is selected, click Action on the menu bar, point to New, and then click Virtual Directory. The Virtual Directory Creation Wizard appears. 8. In the introductory dialog box of the Virtual Directory Creation Wizard, click the Next button to display the Virtual Directory Alias dialog box. 9. In the Virtual Directory Alias dialog box, type webadventure, and then click the Next button. The Web Site Content Directory dialog box appears.

514

Chapter 11

ASP.NET

10. Type the path where you store your JavaScript projects. For example, if your JavaScript projects are stored in a folder named JavaScript_Projects on your C: drive, you would type C:\JavaScript_Projects. Click the Next button when you are finished. The Access Permissions dialog box appears. 11. Leave the options in the Access Permissions dialog box set to their default values, and click the Next button to display the final Virtual Direction Wizard Creation dialog box. 12. Click Finish to create the virtual directory. 13. After you create the webadventure virtual directory, close Internet Information Services and the Administrative Tools window.

CREATING ASP.NET APPLICATIONS
ASP.NET scripts are created as text files, the same as XHTML documents, and can contain both client-side JavaScript code and server-side JavaScript code. Documents for ASP.NET applications have the .aspx file extension. ASP applications files have an .asp extension. When a client requests an ASP.NET document, the Web server executes any server-side scripting code before serving the document to the client. Once the client Web browser receives the document, it executes the client-side JavaScript. Be aware that the first time a client requests an ASP.NET document from a server, the server compiles the document, regardless of whether it contains server-side JavaScript code.The term compiling refers to the processing and assembly of programming code into an executable format. The difference between interpreting and compiling is that, while interpreted programs (such as JavaScript programs) are processed and assembled into an executable format each time they execute, compiled programs only need to be recompiled when their code changes. You do not need to compile a server-side script yourself because ASP.NET automatically recognizes any changes to an ASP.NET application and recompiles the application the next time a client requests it. Thus, installing an ASP.NET application is as simple as placing the documents that make up the application in one of the server’s directories.Additionally, an ASP.NET application starts automatically the first time a Web server receives a request for one of the application’s pages. The term ASP.NET application refers to a collection of related ASP.NET documents that exist in the same root directory.
Because the compilation process requires extra processing time, you should not use the .aspx or .asp extensions with XHTML documents that do not contain server-side JavaScript code, because XHTML documents do not need to be compiled.

Creating ASP.NET Applications

515

Code Declaration Blocks
You define ASP.NET global variables and functions within code declaration blocks, which you create with elements, the same as client-side JavaScript.You use three attributes in a code declaration block: runat=”server”, language, and src. The runat=”server” attribute is required in order to identify the script section as an ASP.NET script. The language attribute identifies the scripting language used within the code declaration block. You can use three scripting languages with ASP.NET: VB (Visual Basic), JScript (JavaScript), and C# (a .NET Framework programming language that is part of Visual Studio). Although the language attribute is optional, ASP.NET uses Visual Basic by default, so you must include the language attribute in order to use JavaScript with your ASP.NET applications.The src attribute is the same attribute that is used in client-side JavaScript to identify a source document containing scripting code. A major difference between using the element for ASP.NET instead of client-side JavaScript is that all code, with the exception of global variables, must be contained within a function. For example, the following code contains an example of a code declaration block that includes a single Write() method of the Response object within a function named sayHello(). functionƒsayHello()ƒ{ Response.Write(“HelloƒWorld”); }

11

By comparison, the following code declaration script would generate a compile error because the statement is not contained within a function: Response.Write(“HelloƒWorld”);

Because XHTML does not recognize the ASP.NET run attribute and because the language attribute is deprecated, you cannot validate the ASP.NET documents you create. However, even though you cannot validate your ASP.NET documents, you should still write well-formed XHTML elements and attributes, especially for any elements and attributes that will be returned as a response to the user. Notice that the Write() method in the preceding examples is appended to the Response object in the same manner that the write() method in client-side

516

Chapter 11

ASP.NET

JavaScript is appended to the Document object. Also notice that the Response object and Write() method are written with their first letter in uppercase. In ASP.NET, objects and methods are usually written with uppercase first letters.You will learn about the Response object later in this section.The Write() method works the same as the client-side write() method, except that instead of designating text to be output to the browser, it designates information to be returned to the client. You cannot execute a function contained within a code declaration block. Instead, you must execute a function from a code render block, which you will study next. Next, you will start creating a document that will be used as the start page for the WebAdventure Web site. To start creating a document that will be used as the start page for the WebAdventure Web site: 1. Open your text editor and create a new document. 2. Type the declaration, element, header information, and the element. Use the strict DTD and “WebAdventure” as the content of the element.Your document should appear as follows: WebAdventure

3. Add the following ASP.NET code declaration block to the document head. The script section uses the Date object to generate the date, which it sends to the client using a Response.Write() statement. functionƒtimeStamp()ƒ{ ƒƒƒƒƒƒƒvarƒnowƒ=ƒnewƒDate(); ƒƒƒƒƒvarƒdayƒ=ƒnow.getDay(); ƒƒƒƒƒvarƒdateƒ=ƒnow.getDate(); ƒƒƒƒƒvarƒyearƒ=ƒnow.getFullYear(); ƒƒƒƒƒvarƒmonthƒ=ƒnow.getMonth(); ƒƒƒƒƒvarƒhoursƒ=ƒnow.getHours(); ƒƒƒƒƒvarƒminutesƒ=ƒnow.getMinutes(); ƒƒƒƒƒvarƒsecondsƒ=ƒnow.getSeconds(); ƒƒƒƒƒvarƒdaysƒ=ƒnewƒArray(); ƒƒƒƒƒdays[0]ƒ=ƒ“Sunday”;ƒdays[1]ƒ=ƒ“Monday”;ƒ ƒƒƒƒƒdays[2]ƒ=ƒ“Tuesday”;ƒdays[3]ƒ=ƒ“Wednesday”;ƒ ƒƒƒƒƒdays[4]ƒ=ƒ“Thursday”;ƒdays[5]ƒ=ƒ“Friday”;

Creating ASP.NET Applications

517

ƒƒƒƒƒ days[6]=”Saturday”; ƒƒƒƒƒvarƒdisplayƒ=ƒdays[day]ƒ+ƒ“ƒ“ƒ+ƒmonthƒ+ƒ“/”ƒ+ƒdateƒ+ƒ“/” ƒƒƒƒƒƒƒƒƒƒƒ+ƒyearƒ+ƒ“ƒ“+ƒhoursƒ+ƒ“:”ƒ+ƒminutesƒ+ƒ“:”ƒ+ƒseconds; ƒƒƒƒƒResponse.Write(“Theƒcurrentƒdateƒandƒtimeƒareƒ“) ƒƒƒƒƒResponse.Write(display); ƒƒƒƒƒResponse.Write(“”); }

4. Add to the document body the following heading element, a form that contains a text field for the user’s first name, and a Submit button that calls the main document, named HomePage.aspx. The Submit button submits the value in the text field to the HomePage.aspx document.
PleaseƒenterƒyourƒfirstƒnameƒandƒclickƒContinue toƒproceedƒtoƒourƒhomeƒpage. FirstƒName:ƒ

5. Save the document as StartPage.aspx in your Chapter folder for Chapter 11.

Code Render Blocks
ASP.NET also uses the script delimiters to designate server-side JavaScript code. A delimiter is a character or a sequence of characters used to mark the beginning and end of a code segment.You include within the script delimiters any commands that are valid for the scripting language you are using.

11

The preceding statement creates a code render block, which executes ASP.NET code within a Web page document.You can declare the language attribute in a code render block, but you must use an ASP processing directive, which provides a Web server with information on how to process the scripts in an ASP document. ASP processing directives are created using the delimiters.You can only declare one processing directive on a page, so it is usually declared at the top of a document or above the first code render block. For example, the following statement includes an ASP processing directive, which declares that the code render block is written in JScript:

518

Chapter 11

ASP.NET

One of the primary reasons to use a code render block is to include ASP.NET inside an XHTML element. As an example, consider the Session object, which is used in ASP.NET to create custom client properties. Assume that you have created a custom property, named email, in the Session object, and you want to use that property in a link that uses the XHTML mailto: protocol.To return the custom email property of the ASP.NET Session object and use it in the link, you use syntax similar to the following: Clickƒhereƒtoƒsendƒanƒe-mail
You cannot declare a function within a code render block.

Notice in the preceding code that you refer to the email property of the Session object as an argument of the Contents object. Properties in ASP.NET are stored in data structures known as collections instead of as properties of objects. The Contents object referenced in the preceding code is actually called the Contents collection.You will learn about collections at the end of this section. An important difference between code declaration blocks and code render blocks is that any variables you define within a code render block are only available to other code render blocks on the page.You can include multiple code declaration blocks and code render blocks in a document. However, variables that you want to be globally available to all other ASP.NET code sections must be declared within a code declaration block.
Although you can include multiple code declaration blocks and code render blocks in a document, you can only use one scripting language: VB (Visual Basic), JScript (JavaScript), or C#. In other words, the value you assign to the language attributes in multiple script sections must match.

The output directive sends the result of an expression to a user’s Web browser (the client). The syntax for the output directive is . For example, if your script includes a variable named salesTotal that has been assigned a value of $24.95, then the output directive sends the value $24.95 to the client Web browser.
The output directive is equivalent to the Response object Write() method.

Creating ASP.NET Applications

519

The following code shows how to use the output directive in a code render block.The example combines the output directive with the Response object Write() method, and includes the language attribute to designate JavaScript as the default scripting language. The expression in the output directive calculates firstNum and secondNum, then sends the text “The result of 10 minus 2 is 8” to the user’s Web browser. Figure 11-4 shows the output. CodeƒRenderƒBlock

11

Figure 11-4

ASP.NET code render block example

520

Chapter 11

ASP.NET

Next, you add a processing directive and a code render block to the StartPage.aspx document. To add a processing directive and a code render block to the StartPage.aspx document: 1. Return to the StartPage.aspx document in your text editor. 2. Add the following processing directive to the top of the document. The processing directive declares JScript as the script language.

3. Now add a code render block after the closing tag in the document head. The code render block executes the timeStamp() function you added in the last exercise.

4. Save the StartPage.aspx document, and then open it in your Web browser by typing the following URL in the address box: http://localhost/ webadventure/Chapter.11/ Chapter/StartPage.aspx.You cannot open StartPage.aspx as a local file using the Open command from your Web browser’s File menu.You must type the full URL to your server. 5. After the document opens, view the source document. (In Internet Explorer, select Source from the View menu.) In the text editor that opens, notice that the document does not contain the ASP.NET statements you added. Instead, only the output from the Response.Write() statements is available to the client. Figure 11-5 shows how the document appears in a Web browser. 6. Close your Web browser window.

Figure 11-5

StartPage.aspx

Creating ASP.NET Applications

521

Mixing XHTML and ASP.NET
The ASP.NET code within code declaration blocks and code render blocks execute on a Web server before the page is sent to a user. If users were to view the source document after they received the ASP document, they would not see any elements, script delimiters, or ASP.NET code they contain. Instead, the client shows only the results returned by the code. For example, the following code shows an ASP document containing client-side JavaScript as well as ASP.NET code render blocks and code declaration blocks. Notice that the function declared within the code declaration block is executed in the last code render block. MixedƒExample functionƒcodeBlockText()ƒ{ ƒƒƒƒƒResponse.Write(“CodeƒDeclarationƒBlock”);ƒ ƒƒƒƒƒResponse.Write(“ThisƒlineƒisƒgeneratedƒbyƒanƒASP.NET codeƒdeclarationƒblock.”); }

11

The following code shows how the preceding document appears once a client receives it. Notice that the client-side JavaScript code is the same, but the ASP.NET code has been converted to elements and text. Figure 11-6 shows how the text and elements appear in a Web browser. MixedƒExample CodeƒRenderƒBlockThisƒlineƒisƒgeneratedƒbyƒanƒASP.NET codeƒrenderƒblock. CodeƒDeclarationƒBlockThisƒlineƒisƒgeneratedƒbyƒan ASP.NETƒcodeƒdeclarationƒblock.

Figure 11-6

Result of a document with multiple script sections displayed in a Web browser

You can see in the preceding example that XHTML elements and text can be interspersed with script delimiters. However, you can go even further and include XHTML elements and text as part of an ASP.NET decision-making structure, such as an if...else statement. For example, in the following code, because each if or else...if statement is enclosed by script delimiters, it is unnecessary to use the Write() method of the Response object to output the correct greeting. Only one greeting is returned, based on the results of the if...else statement. ƒƒƒƒƒBuenosƒDias ƒƒƒƒƒGutenƒTag

Creating ASP.NET Applications

523

ƒƒƒƒƒBuonƒGiorno ƒƒƒƒƒBonjour ƒƒƒƒƒIƒdon’tƒspeakƒyourƒlanguage!

You could also write the code within a single pair of script delimiters, as the following code illustrates. However, the greetings are not treated as XHTML elements or text, because they are enclosed by the script delimiters. For this reason, each greeting must include a Response.Write() statement to be returned to the client.

The following code shows another example of interspersing ASP.NET with XHTML elements and text to generate a customized Web page.The example shows an XHTML document that could be generated in response to a client request for information. Assume that the document from which the client request originates includes a form field named clientName. The example uses the clientName property of the Content collection of the Request object and uses an output directive to intersperse the property throughout the text to be returned to the client, creating a customized response. The example also assumes that the company’s e-mail address is stored in the email property of the Content collection of the Application object. Figure 11-7 shows the output in a Web browser, assuming that “Don” is the value of the clientName property. MixedƒExample Dearƒ: ThankƒyouƒforƒyourƒinterestƒinƒourƒWebƒdevelopmentƒservices. Asƒyouƒknow,ƒitƒisƒdifficultƒtoƒkeepƒupƒwithƒrapidlyƒchanging technology.ƒWithƒWebAdventure’sƒhelp,ƒyouƒcanƒbeƒconfident thatƒyourƒWebƒsiteƒwillƒbeƒonƒtheƒcuttingƒedge.ƒRemember,

11

524

Chapter 11

ASP.NET

,ƒWebAdventureƒisƒhereƒfor you.ƒForƒmoreƒinformation,ƒclickƒhereƒtoƒsendƒusƒan e-mail.

Figure 11-7

ASP.NET interspersed with XHTML in a Web browser

OBJECT COLLECTIONS
Before learning about ASP.NET core objects, you need to understand collections. Collections are data structures similar to arrays that store variables in ASP.NET core objects. The syntax for assigning a variable to a collection is object.collection (“variable”)ƒ=ƒvalue;. You then refer to the variable in ASP.NET code by using the syntax object.collection(“variable”);. For instance, the Application object and Session object both contain separate Contents collections, which store custom variables. The following code creates a name variable in the Session object Contents collection, assigns it a value of “Don Gosselin”, and then sends the value to the client browser, using a Response.Write() statement: Collections are commonly used in Visual Basic programming. Much of ASP.NET non-JavaScript syntax comes from Visual Basic programming, because the ASP.NET default scripting language is VBScript, which is derived from Visual Basic.

Object Collections

525

If a variable name you assign to a collection is unique throughout all of the collections of an object, then you can eliminate the collection name when referencing the object in code. For example, if the Session object contains only one name variable in all of its collections, then you can refer to the name variable in code by using a statement such as Response.Write(Session(“name”));. It is usually safer, however, to include the collection name in order to eliminate any uncertainty as to what collection contains a specific variable.Additionally, eliminating the collection name could cause bugs in your program if you later add the same variable name to another collection in the same object. Therefore, the code in this chapter includes collection names when referencing variables. Each variable in a collection is numbered, similar to the way element numbers are assigned to arrays.You can refer to collection variables by using numbers instead of variable names. For example, the following code creates three variables, firstName, lastName, and email, in the Contents collection of the Session object, then returns the values to the client, using the collection number of each variable.

11

Be aware that the number assigned to a variable in a collection can change if you remove items from the collection. You should not assume that a number always represents the same variable in a collection.
You can remove items from a collection using the Remove() and RemoveAll() methods of the Contents collection. Both the Application object and Session object contain Contents collections.

ASP.NET collections support a count property, which returns the number of variables in a collection.You can use the count property in a looping statement to cycle through the variables in a collection. For example, the following code uses a for loop to return the variables in the Contents collection to the client.The for loop conditional evaluation compares the curVariable variable to the count property. While curVariable is less than the count property, the for loop continues iterating through the collection.

526

Chapter 11

ASP.NET

Similar Documents

Free Essay

Javascript

...A JavaScript framework or library is a set of utilities and functions that make it much easier to produce cross-browser compatible JavaScript code. Each library is vigorously tested on modern versions of many popular Web browsers, an examples of JavaScript framework is jQuery, jQuery includes some basic UX enhancements with the core library.it has effects such as sliding and fading. It has advanced UX features in UI library, which includes more effects and is as well as interactivity features such as drag and drop, resizing, and sorting. JQuery UI also includes some widgets or components that make the development of attractive interfaces much easier. At present, these components include Accordion, Datepicker, Dialog, Progressbar, Slider, and Tabs. These widgets are completely themable, and jQuery UI includes a wide range of themes that can be used to fit the components to your own particular Web site or Web application. JQuery is a cross-platform JavaScript library designed to simplify the client-side scripting of HTML. jQuery's syntax is designed to make it easier to navigate a document, select DOM elements, create animations, handle events, and develop Ajax applications. JQuery also provides capabilities for developers to create plug-ins on top of the JavaScript library. This enables developers to create abstractions for low-level interaction and animation, advanced effects and high-level, theme-able widgets. The modular approach to the jQuery library allows the creation...

Words: 335 - Pages: 2

Premium Essay

Javascript

...JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer, Firefox, Chrome, Opera, and Safari. [pic] What You Should Already Know Before you continue you should have a basic understanding of the following: • HTML / XHTML If you want to study these subjects first, find the tutorials on our Home page. [pic] What is JavaScript? • JavaScript was designed to add interactivity to HTML pages • JavaScript is a scripting language • A scripting language is a lightweight programming language • JavaScript is usually embedded directly into HTML pages • JavaScript is an interpreted language (means that scripts execute without preliminary compilation) • Everyone can use JavaScript without purchasing a license [pic] Are Java and JavaScript the same? NO! Java and JavaScript are two completely different languages in both concept and design! Java (developed by Sun Microsystems) is a powerful and much more complex programming language - in the same category as C and C++. [pic] What can a JavaScript do? • JavaScript gives HTML designers a programming tool - HTML authors are normally not programmers, but JavaScript is a scripting language with a very simple syntax! Almost anyone can put small "snippets" of code into their HTML pages • JavaScript can put dynamic text into an HTML page - A JavaScript statement like this: document.write("" + name + "") can write...

Words: 5201 - Pages: 21

Premium Essay

Html and Javascript

...interface gathers information from the user, submits it to a server, or back end, then receives, formats, and presents the results. . What does the middle tier do in a three-tier architecture? The middle tier handles the interaction between the web browser client and the data storage tier. Essentially, the client tier makes a request of a database on a web server. The processing tier performs any necessary processing or calculations based on the request from the client tier, and then reads information from or writes information to the data storage tier. The processing tier also handles the return of any information to the client tier. . What is ECMAScript? Why was it created? ECMAScript is an international, standardized version of JavaScript. It was...

Words: 7945 - Pages: 32

Free Essay

Selenium

...Selenium Reference Concepts A command is what tells Selenium what to do. Selenium commands come in three 'flavors': Actions, Accessors and Assertions. Each command call is one line in the test table of the form: |command |target |value | Actions are commands that generally manipulate the state of the application. They do things like "click this link" and "select that option". If an Action fails, or has an error, the execution of the current test is stopped. Many Actions can be called with the "AndWait" suffix, e.g. "clickAndWait". This suffix tells Selenium that the action will cause the browser to make a call to the server, and that Selenium should wait for a new page to load. Accessors examine the state of the application and store the results in variables, e.g. "storeTitle". They are also used to automatically generate Assertions. Assertions are like Accessors, but they verify that the state of the application conforms to what is expected. Examples include "make sure the page title is X" and "verify that this checkbox is checked". All Selenium Assertions can be used in 3 modes: "assert", "verify", and "waitFor". For example, you can "assertText", "verifyText" and "waitForText". When an "assert" fails, the test is aborted. When a "verify" fails, the test will continue execution, logging the failure. This allows a single "assert" to ensure that the application is on the correct page, followed by a bunch of "verify" assertions to test form field values...

Words: 7020 - Pages: 29

Premium Essay

Introduction to Java

...Introduction to Javascript JavaScript has been around for several years now, in many different flavors. The main benefit of Javascript is to add additional interaction between the website and its visitors with just a little extra work by the web developer. Javascript allows industrious web masters to get more out of their website than HTML and CSS can provide. By definition, JavaScript is a client-side scripting language. This means the web surfer's browser will be running the script. The opposite of client-side is server-side, which occurs in a language like PHP. PHP scripts are run by the web hosting server. How To Write JavaScript If you have ever used CSS before, you will find the whole part about including JavaScript will be a lot simpler to grasp. Here are Tizag's three important steps you should always follow when creating or using someone else's JavaScript code: 1. Use the script tag to tell the browser you are using JavaScript. 2. Write or download some JavaScript 3. Test the script! There are so many different things that can go wrong with a script, be it human error, browser compatibility issues, or operating system differences. So, when using JavaScript, be sure that you test your script out on a wide variety of systems and most importantly, on different web browsers. Your First JavaScript Script To follow the classic examples of many programming tutorials, let's use JavaScript to print out "Hello World" to the browser. I know this isn't very interesting...

Words: 9622 - Pages: 39

Free Essay

Haha

...while achieving the highest quality in both media. The joining of these two great programs empowers Web developers to perform advanced Web-production tasks such as JavaScript rollovers, animations, sliced images and image maps with the advanced features of ImageReady. Not only that, but ImageReady will write the JavaScript and HTML to make your task even easier! Adobe-standard User Interface Photoshop and ImageReady are seamlessly integrated. The menu structure, tool boxes and palettes common to all of Adobe’s professional graphics programs are present. This eases the learning curve, thus allowing the user to concentrate on creating graphics. Workflow is enhanced with the addition of a nifty little Jump To icon on the toolbox of both programs. The Jump To button whisks both you and your graphic between programs while preserving all edits, effects, layers, attributes and history. Edits in one program may be easily undone in the other via the preserved history palette. Powerful JavaScript Rollover Effects Complex rollover effects are a snap in ImageReady. ImageReady’s built in Actions will add instant rollover effects creating interactive buttons for an entire navigation system in a matter of minutes. And again, it will write the HTML and the JavaScript; no need for you to write a single line of JavaScript code. Make some changes to your buttons after you’ve saved the HTML file? Not a problem, the Update HTML feature is all you need to put a new image and updated HTML...

Words: 761 - Pages: 4

Free Essay

Arcgis Viewer for Flex and Silverlight vs. Using Html 5 for Arcgis

...ArcGIS viewer for Flex vs. Silverlight vs. Using HTML 5 for ArcGIS Both ArcGIS viewer for Flex and Silverlight are both applications that make it possible for users to create their own web GIS applications and make them available for intranet and Internet use by using a web serve. The viewer for flex is produced by Adobe and has been around longer than the viewer for Silverlight which is produced by Microsoft; thus, there may be more valuable resource available for flex viewer than for Silverlight viewer (widgets for flex viewer, add-ins for Silverlight). Flex web applications can be developed by using any IDE that supports adobe flex (i.e., Eclipse and Adobe Flash Builder). Silverlight applications can be developed with any .NET programming language (C#, etc.); or software can be used in the form of Microsoft Visual Studio. Developing a Flex viewer widget, however, appears to be much easier than developing an add-in for Silverlight viewer. To develop a Flex widget, you use ArcGIS API for Flex (using the same framework for extending the viewer and developing your own applications from scratch). With the Silverlight viewer, you need to use a separate application, ArcGIS Extensibility SDK for Silverlight, which looks a bit more complex to me compared to ArcGIS API for Silverlight because it follows the Model View ViewModel (MVVM) pattern. With the Silverlight viewer, appears to let end users modify symbology of layers in the created web applications without modifying the original...

Words: 486 - Pages: 2

Premium Essay

Chapter 9, Introduction to the Internet

...Answer | | | | | Selected Answer: |   <script language="javascript"> | Correct Answer: |   <!--Hide from old browsers--> | | | | | * Question 3 0 out of 0.5 points | | | Which of the following is true regarding naming conventions for functions?Answer | | | | | Selected Answer: |   it must include a period | Correct Answer: |   it must begin with a letter or an underscore | | | | | * Question 4 0 out of 0.5 points | | | Which of the following objects represents a set of characters?Answer | | | | | Selected Answer: |   set | Correct Answer: |   string | | | | | * Question 5 0 out of 0.5 points | | | Which of the following is not a valid JavaScript variable name?Answer | | | | | Selected Answer: |   Prices | Correct Answer: |   Zip.Code | | | | | * Question 6 0.5 out of 0.5 points | | | A(n) ____ variable is one whose value is available only in the function in which it is defined.Answer | | | | | Selected Answer: |   local | Correct Answer: |   local | | | | | * Question 7 0 out of 0.5 points | | | ____ data types are variables that hold characters or a combination of letters, numbers, or symbols.Answer | | | | | Selected Answer: |   Symbol | Correct Answer: |   String | | | | | * Question 8 0 out of 0.5 points | | | A(n) ____ function is JavaScript code written to perform certain tasks repeatedly.Answer | | | | ...

Words: 1270 - Pages: 6

Free Essay

Driveyext Question

...in detail why. In order to take a test you have to click through several pages of text which all have timers associated to them. For example, a full page of text may be a 2 minute timer which prevents you from continuing until you have stayed on the page for a minimum of 2 minutes. This is an attempt to make sure you actually read the content on each page. It is very annoying, and painful. If you have to wait for all of the timers I’m guessing it will probably take 8 hours to complete the online driving school. After waiting for about 10 minutes I realized I better find a solution to this. I viewed the page source and noticed the timer is client side based javascript. Great news, lets disable Javascript in the browser! In Firefox click on Tools -> Options… -> Content tab, uncheck the ‘Enable Javascript’ checkbox, click Ok. Voila, no more timers!! If you ever get a blank page while taking this...

Words: 406 - Pages: 2

Free Essay

Hjmhg

...Gjhgjkhjkljljkl;jk; Javascript JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer, Firefox, Chrome, Opera, and Safari. [pic] What You Should Already Know Before you continue you should have a basic understanding of the following:     • HTML / XHTML If you want to study these subjects first, find the tutorials on our Home page. [pic] What is JavaScript?     • JavaScript was designed to add interactivity to HTML pages     • JavaScript is a scripting language     • A scripting language is a lightweight programming language     • JavaScript is usually embedded directly into HTML pages     • JavaScript is an interpreted language (means that scripts execute without preliminary compilation)     • Everyone can use JavaScript without purchasing a license [pic] Are Java and JavaScript the same? NO! Java and JavaScript are two completely different languages in both concept and design! Java (developed by Sun Microsystems) is a powerful and much more complex programming language - in the same category as C and C++. [pic] What can a JavaScript do?     • JavaScript gives HTML designers a programming tool - HTML authors are normally not programmers, but JavaScript is a scripting language with a very simple syntax! Almost anyone can put small "snippets" of code into their HTML pages     • JavaScript can put dynamic text into an HTML page - A JavaScript statement like this: document...

Words: 310 - Pages: 2

Free Essay

Web 238 Team Assignment

...University of Phoenix WEB/238 May 29, 2012 Tanisha D. Jackson Web Development and the Use of Javascript Creating a Website and presenting it online to users across the world has become a regular occurrence over the past few decades. Web pages belong to companies with services to sell, and others, to individuals with information to share. The basic Web site is built with HTML, and then creatively enhanced with CSS. To create a visually expressive Web site that can attract thousands of visitors each day you need to use more than HTML and decide what the site contains. There are different languages that can be used to add a sense of style to your site, some of the possible devices are JavaScript, Java, DOM, and AJAX. In the following paper our team will discuss a few examples of how each can be used in Web development. Comparison of Java and JavaScript Java and JavaScript are both object-oriented languages (Burns, 2012). Knowing how to use one language often becomes confusing when attempting to learn the other. Some of the differences between the two are that Java applets can create stand-alone applications that work across platforms running as standalone programs. However, JavaScript cannot create these stand-alone applications and reside on an Internet browser. A programmer must compile Java code before the program can run. This requires an outside program just to compile the code. A compiler turns Java code into machine...

Words: 2442 - Pages: 10

Free Essay

Document Model Prototypes

...is the first installment of a two-part series that introduces advanced JavaScript techniques in Windows Internet Explorer 8. Web applications have come a long way since the birth of the static Web page. Today, Web developers need improved programming functionality, flexibility, and features to enable them to build the next generation of Web applications. The Internet Explorer Web platform provides many of the features and functionality necessary to build those applications. Where the Web platform's built-in support ends, JavaScript, the principle scripting language used on the Web, is often used to code innovative new features that supplement the Web platform, cater to Web site specific scenarios, normalize differences between browsers, and so on. To further empower Web developers with the programming tools necessary to build new JavaScript scenarios that innovate, extend, and build-upon the Web platform, Internet Explorer 8 offers a collection of features that extend some of JavaScript's advanced functionality into the Document Object Model (DOM). This article provides an overview of JavaScript prototype inheritance and introduces the DOM prototypes feature available in Internet Explorer 8; Part 2 introduces a new type of JavaScript property called an accessor property (or getter/setter property). Prototypes in JavaScript To begin a discussion of DOM prototypes, it is crucial to understand the JavaScript notion of "prototypes." Simply put, a prototype is like a class object...

Words: 3453 - Pages: 14

Premium Essay

Webd241 Week 8 Assignment

... Give the syntax of do..while statement. do { text += "The number is " + i; i++; } while (i < 10); 2. Explain how an image could be accessed by name and by array number. You can access an image by name by simply putting the name between quotes. To access an image by number you must first give each image a number in the image array. The images should be numbered in the order that they appear in the source code. var document.images=new Array (3) document.images[0]="ImageOne.png" document.images[1]="ImageTwo.png" 3. Write a function that uses substring method of String object to get the 'Scr' part of the string 'JavaScript'. Also use the length property and write the length of the string 'JavaScript' and use the charAt method to get the 'S' from 'JavaScript' and write that. var str="JavaScript"; document.write(str.substring(4,7)+" "); 4. Explain how a Date object's instance is created and used. Also describe any three methods of the Date object. Data objects are used by the destination application either the client or the server. A data object in the destination application is one end of a connection between the source application and the destination application. A data object in the destination application is used to access and interact with the data in the data source. There are two common situations where a data object is needed. The first situation is when data is dropped in your application using drag and drop. The second situation...

Words: 600 - Pages: 3

Free Essay

Comp

...COMP101 – Problem Solving with Computing Homework - WEEK 12 [30 points] This is further review of some of the material from Chapter 6, some simple steps in coding using JavaScript and the repl.it website, and lectures from class. No credit for answers that are copies or near verbatim transcripts – please use your own words[1] and document sources where appropriate. Chapter 7 Answer the following questions: 1. JavaScript Debugging Exercises [1 point each, 5 points total] The snippets of JavaScript below contain syntax errors and/or logic errors. Identify the errors and insert your corrected code. a. function main() { var num1 = getNumber(); var num2 = getNumber(); } function getNumber() { var input = Number(prompt("Enter a number")); } main(); b. function main() { var total = 0; for (var ctr = 0; ctr < 10; ctr++) { total = computeTotal(total); } } function computeTotal(total, ctr) { total = total + ctr; return total; } main(); c. function main() { var playerName1; var playerName2; playerName1, playerName2 = getPlayerNames(); } function getPlayerNames() { var name1 = prompt("Enter the name of player1"); return name1; var name2 = prompt("Enter the name of player2"); return name2; } main(); d. module main() ...

Words: 2288 - Pages: 10

Free Essay

Script

...sADOBE® INTRODUCTION TO SCRIPTING © Copyright 2007 Adobe Systems Incorporated. All rights reserved. Introduction to Scripting for Windows® and Macintosh®. NOTICE: All information contained herein is the property of Adobe Systems Incorporated. No part of this publication (whether in hardcopy or electronic form) may be reproduced or transmitted, in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior written consent of Adobe Systems Incorporated. The software described in this document is furnished under license and may only be used or copied in accordance with the terms of such license. This publication and the information herein is furnished AS IS, is subject to change without notice, and should not be construed as a commitment by Adobe Systems Incorporated. Adobe Systems Incorporated assumes no responsibility or liability for any errors or inaccuracies, makes no warranty of any kind (express, implied, or statutory) with respect to this publication, and expressly disclaims any and all warranties of merchantability, fitness for particular purposes, and noninfringement of third party rights. Any references to company names in sample templates are for demonstration purposes only and are not intended to refer to any actual organization. Adobe®, the Adobe logo, Illustrator®, InDesign®, and Photoshop® are either registered trademarks or trademarks of Adobe Systems Incorporated in the United States and/or other countries. Apple®...

Words: 14237 - Pages: 57