Beginning Web Development, Silverlight, and ASP.NET AJAX From Novice to Professional phần 2 pot

44 386 0
Beginning Web Development, Silverlight, and ASP.NET AJAX From Novice to Professional phần 2 pot

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Figure 2-14. Creating a web reference Visual Studio will then create a special type of class called a proxy. This is simply a local repr esentation of the remote service, allowing you to call methods as if they were implemented on your local computer. However, under the covers, ASP.NET will forward all of the proxy method calls to the remote service for execution. If Visual Studio interprets the file successfully, you will see a list of available methods ( GetStockQuotes in the example in Figur e 2-14). You can then create a name for the web reference and add the reference to your project. At this point in your project, you can create an instance of the web reference proxy class and call the method on it to get data back fr om the web service. I n fact, let’s do that now so that we can call a remote web service to obtain stock quotes for our example. Right-click the project name and select Add Web Reference. When the Add Web Reference dialog box appears, type http://services.xmethods.net/ soap/urn:xmethods-delayed-quotes.wsdl into the URL field and click Go. We’ll be using a service provided by XMethods ( www.xmethods.com) that reports delayed stock quotes given a stock ticker symbol. You can see this in Figure 2-14. After clicking Go, Visual Studio con- tacts XMethods, downloads the WSDL, and displays the available methods it finds for you to review. Note the value in the Web reference name field ( net.xmethods.services), which will ultimately form the namespace of the proxy class you’ll be using. Change the value you find there to “QS” for “quote service,” and then click Add Reference. At this point, CHAPTER 2 ■ BASICS OF WEB DEVELOPMENT WITH ASP.NET24 9594CH02.qxd 1/3/08 10:46 AM Page 24 Visual Studio converts the WSDL into a C# class (the proxy) and stores it under the App_WebReferences folder, which Visual Studio also creates for you. Later in the chapter, we’ll use this quote service to actually retrieve stock quote values. Copy Web Site This enables you to copy your web site to a new location. This can be another directory on your file system or a remote directory on an FTP or IIS server. Copy Web Site can also be used to back up or deploy your web site. Start Options This enables you to specify the action to take when you start the project. It’s a shortcut to the Property Pages window, with the start options already selected (see Figure 2-15). Figure 2-15. Web Start options You can use this dialog box to specify how the application will start—for example, launching the current page (in the IDE) as the start page, specifying a particular page, or starting an external program first before launching the site. You can also specify the server to use and how to authenticate against that server. CHAPTER 2 ■ BASICS OF WEB DEVELOPMENT WITH ASP.NET 25 9594CH02.qxd 1/3/08 10:46 AM Page 25 View in Browser The default browser on your system shows the currently selected page (or the default page as specified in Web Start options if nothing is selected). Browse With This option enables you to specify the browser that you will use to browse the site. By default, Microsoft Internet Explorer and the Visual Studio built-in browser are available, but you can easily use the dialog box to add other browsers such as Mozilla Firefox. Refresh Folder This option refreshes and redraws the contents of the Solution Explorer. If you’ve added new files or references and they haven’t shown up yet, choose Refresh Folder to see them. Property Pages This option calls up the Property Pages dialog box. You’ve already seen this with the Web Start options selection, where the property pages were launched with the Start Options section already selected. You can also use the Property Pages option to manage refer- ences and the build process. Figure 2-16 shows an example of Property Pages being used to manage references. Figure 2-16. Managing application references with Property Pages CHAPTER 2 ■ BASICS OF WEB DEVELOPMENT WITH ASP.NET26 9594CH02.qxd 1/3/08 10:46 AM Page 26 You can use Property Pages to view existing references, which will either be application references (type GAC) or web references (type WEB) on the references list. You can also add application or web references from this window, following the same workflow that you followed when you chose to add them directly from the context menu. If you want to remove unwanted references, select them and click Remove. Finally, web services may change over time, causing your proxy to break because it is out of sync with the originating service. If you want to make sure that your proxy is up-to-date and able to communicate with the service, select the web reference and click Update. Of course, when the update to your web reference indicates the originating service actually did change, you may need to change your own code that uses the web service. Figure 2-17 shows the Build options. Figure 2-17. The Build options I n Visual Studio, pressing the F5 key starts your application. You can use the Property P ages dialog bo x to specify what should happen when the application star ts. By default, the web site will be built every time, but there are other available options, including No Build (where the current build of the site will be run, ignoring changes since the last build) and B uild P age (wher e only the curr ent page will be built befor e executing). The latter option is useful, for example , in a lar ger site when y ou just want to unit test one page without r ebuilding ev er ything. CHAPTER 2 ■ BASICS OF WEB DEVELOPMENT WITH ASP.NET 27 9594CH02.qxd 1/3/08 10:46 AM Page 27 The Code and Design Windows At the center of the IDE screen you’ll see the Source and Design window. If you are view- ing an ASPX file and you select the Source tab at the bottom, the window will look like Figure 2-18. Figure 2-18. The Source and Design window At the bottom of the screen, you can select Design view or Source view. Source view for an ASPX page looks a lot like HTML, and in fact that’s exactly what it is—specially marked-up HTML that the ASP.NET-based server recognizes. At the top of the document, you see the markup beginning with <%@, which indicates to the server that this is an active page and that the content should be parsed to generate HTML code. The code-behind file is specified as part of the Page tag at the top. In addition, as you place controls on the page, you’ll see the server-side code specified using tags such as <asp:Button> for a server- side button. As the server parses the page, it recognizes tags like this and generates the appropriate HTML to render the desired content. Design view shows the design surface for the page. In Design view, you can drag and drop controls from the Toolbox onto the page to create your web UI. See the example in Figure 2-19, where an ASP.NET Button, Label, and TextBox control have been added to the page. CHAPTER 2 ■ BASICS OF WEB DEVELOPMENT WITH ASP.NET28 9594CH02.qxd 1/3/08 10:46 AM Page 28 Figure 2-19. The design surface You can use the Properties window to set the properties of the currently selected item. So, for example, you can change the label on the button from Button to Get by find- ing the Text entry in the Properties window and using it to set the button text to Get (see Figure 2-20). You can also change the name of a button using the ID property. Figure 2-20. Setting the label for a button by using the Properties window CHAPTER 2 ■ BASICS OF WEB DEVELOPMENT WITH ASP.NET 29 9594CH02.qxd 1/3/08 10:46 AM Page 29 For the stock quote application you are creating, set the properties of the three controls as follows: TextBox: Change the ID to txtTicker. Button: Change the ID to btnGet, and change the text to Get. Label: Change the ID to lblQuote, and change the text to '' (an empty string). The page will now look something like what you see in Listing 2-1. Listing 2-1. The Stock Quote Application <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:TextBox ID="txtTicker" runat="server"></asp:TextBox> <asp:Button ID="btnGet" runat="server" Text="Get" /> <asp:Label ID="lblQuote" runat="server"></asp:Label></div> </form> </body> </html> You can see the <asp:> labels for the three controls as well as their attributes, which define the properties that you just set. If you don’t want to use the Property Editor to set the properties, you can instead use the source editor to enter these properties manually, and IntelliSense will even help you with this. If you haven’t done so already, make sure that you add a web reference to the XM ethods quote ser vice at www.swanandmokashi.com/HomePage/WebServices/StockQuotes. asmx?WSDL. C all the ser vice r efer ence 'QS'. CHAPTER 2 ■ BASICS OF WEB DEVELOPMENT WITH ASP.NET30 9594CH02.qxd 1/3/08 10:46 AM Page 30 Now, in the Default.aspx page’s Design view, double-click the button, and a click event handler will be added to the code-behind file. This event handler will be called btnGet_Click. Edit the event handler so that it looks like this: p rotected void btnGet_Click(object sender, EventArgs e) { QS.StockQuotes myQuote = new QS.StockQuotes(); QS.Quote[] res; res = myQuote.GetStockQuotes(txtTicker.Text); lblQuote.Text = res[0].StockQuote; } This code creates an instance of the web service proxy called 'MyQuote'. It then calls the getStockQuotes method on this proxy (and by extension the web service), which returns a stock quote for the string ticker. As you can see from the code, the contents of the txtTicker text box are being passed to the quote retrieval web service. The service returns an array of Quote objects, and the label then has its text set to the value of the StockQuote property of the first element in this array, converted to a string. Do note, how- ever, that this is just example code. In a real scenario, you would likely want to at least add some form of error handling to check for a timeout or other error in calling the web service. For production systems, you may also want to look into asynchronous web serv- ice calls. Now if you run the application, type a stock ticker (e.g., MSFT, RTRSY, or BEAS) into the text box, and click Get, the web service will return a stock quote for that ticker. You can see this in action in Figure 2-21. Figure 2-21. The simple stock quote web site CHAPTER 2 ■ BASICS OF WEB DEVELOPMENT WITH ASP.NET 31 9594CH02.qxd 1/3/08 10:46 AM Page 31 Architecture of ASP.NET The simplicity of developing the stock quote application proves the power that ASP.NET affords you as a web developer. Some fairly complex stuff was going on behind the scenes, enabling you to focus on the business logic for your application, instead of all the underlying plumbing necessary to get it to work. Figure 2-22 shows how the underlying ASP.NET components all work together in an ASP.NET application. At the bottom of the figure, you see the host operating system on which the web server runs. The web server for ASP.NET can be Cassini or IIS. The web server receives the incoming request from the browser and passes it to the ASP.NET run- time, which sits on top of the operating system. This runtime can use a global application file, called Global.asax, to manage func- tions that are central to your web site. A number of modules are available to the runtime for handling sessions, authentication, and caching. Finally, your application or web service sits on top of these modules and executes. Upon executing, it generates HTML markup that gets passed back to the process that initiated the request thr ough the web server. Figure 2-22. ASP .NET ar chitectur e CHAPTER 2 ■ BASICS OF WEB DEVELOPMENT WITH ASP.NET32 9594CH02.qxd 1/3/08 10:46 AM Page 32 The ASP.NET Worker Process and State Management In the stock quote application, when the web browser requested the page from the server, the server recognized the .aspx page name extension as an ASP.NET page, and passed the request to the ASP.NET runtime, which processed the ASP.NET code and returned the output to the client. Take a look back at Listing 2-1, where the page was defined using extended HTML. If you look at the code being rendered by the browser (by selecting View Source from your browser when viewing the Default.aspx page), you’ll see something different. Take a look at Listing 2-2. Listing 2-2. The Stock Quote Application As Rendered by the Browser <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>Untitled Page</title> </head> <body> <form name="form1" method="post" action="Default.aspx" id="form1"> <div> <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTU5MTA2ODYwOWRk1kQjjKUNXCMmyhw9mwUkqs1+CdU=" /> </div> <div> <input name="txtTicker" type="text" id="txtTicker" /> <input type="submit" name="btnGet" value="Get" id="btnGet" /> <span id="lblQuote"></span> </div> <div> <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWAwKQ0uDFBALGsPqoBgKLk8m1C0va3iCLI38aZ+8cKQVn2KcWFC3g" /> </div> </form> </body> </html> CHAPTER 2 ■ BASICS OF WEB DEVELOPMENT WITH ASP.NET 33 9594CH02.qxd 1/3/08 10:46 AM Page 33 [...]... or settings within Web. config will break your site, so be careful when editing it by hand! You can see the Web Site Administration Tool in Figure 2- 23 35 9594CH 02. qxd 36 1/3/08 10:46 AM Page 36 CHAPTER 2 s BASICS OF WEB DEVELOPMENT WITH ASP.NET Figure 2- 23 The Web Site Administration Tool Summary In this chapter, you took a brief look at ASP.NET and how you can use the VWDE tool to build a simple ASP... 9594CH03.qxd 1 /2/ 08 2: 57 PM Page 45 CHAPTER 3 s WEB FORMS WITH ASP.NET Listing 3-4 Handling the HTML Form in the ASP NET Agent using using using using using using using using using System; System.Data; System.Configuration; System .Web; System .Web. Security; System .Web. UI; System .Web. UI.WebControls; System .Web. UI.WebControls.WebParts; System .Web. UI.HtmlControls; public partial class _Default : System .Web. UI.Page... such as when you want to see a web page or other resource, while HTTP-POST is used to send information to the server for processing (push model), such as when submitting data from a web form in response to a button click In Chapter 2, the browser issued an HTTP-GET verb to request the Default.aspx page, and then an HTTP-POST verb in response to the button click, sending the stock ticker value recorded... 9594CH03.qxd 1 /2/ 08 2: 57 PM CHAPTER Page 37 3 Web Forms with ASP.NET A t the heart of web applications and web sites in ASP.NET are the elements that you use to build the pages that the user will see These are called web forms, terminology that is a holdover from Windows development when windows were built using forms This methodology is unique and innovative in web development It enables you to create... simple matter to provide feedback of the operation to your users Modify the Page_Load event handler to look like Listing 3-6 Listing 3-6 Modified Page_Load to Provide Feedback using using using using using using using using using System; System.Data; System.Configuration; System .Web; System .Web. Security; System .Web. UI; System .Web. UI.WebControls; System .Web. UI.WebControls.WebParts; System .Web. UI.HtmlControls;... System .Web. Security; System .Web. UI; System .Web. UI.WebControls; System .Web. UI.WebControls.WebParts; System .Web. UI.HtmlControls; public partial class _Default : System .Web. UI.Page { protected void Page_Load(object sender, EventArgs e) { 9594CH03.qxd 1 /2/ 08 2: 57 PM Page 51 CHAPTER 3 s WEB FORMS WITH ASP.NET if (IsPostBack) { string strOperation = Request.Form["optOperation"]; int nF = 0; Int 32. TryParse(txtFirst.Text,... 9594CH03.qxd 1 /2/ 08 2: 57 PM Page 55 CHAPTER 3 s WEB FORMS WITH ASP.NET submit button) To see the postback and how it contains information for all events, add an ASP NET button to the form, run it, select a list item, and then click the button You’ll see that your breakpoint on the ListBox’s SelectedIndexChanged handler still trips, even though your action was to click the form’s submit button (Note that... processing to the client, providing a richer client experience (they make more frequent asynchronous postbacks to the server to make the application appear more responsive), but your web applications still have a server element to them, and understanding how to handle this is vital as you write your web applications Typical web applications are stateless: To maintain a clean relationship between the client and. .. tree that ASP.NET exposes to you as a developer Finally, you’ll take an in-depth look at the Page class, and how it can be used to control the flow between the server and your users, enabling you to access the request and response streams, and parse and/ or override them as necessary By the end of the chapter, you’ll have a good understanding of how web forms work, and how you can use them to add great... limited to getting and setting properties—it can also respond to events within the controls Remember, as the code is running on the client, and since the client is constrained to the 9594CH03.qxd 1 /2/ 08 2: 57 PM Page 53 CHAPTER 3 s WEB FORMS WITH ASP.NET workflow that HTML forms offer, something is necessary to bubble the events up to the server so that the server knows what event to respond to The flow . 35 9594CH 02. qxd 1/3/08 10:46 AM Page 35 Figure 2- 23. The Web Site Administration Tool Summary In this chapter, you took a brief look at ASP. NET and how you can use the VWDE tool to build a simple ASP. NET. applications. CHAPTER 2 ■ BASICS OF WEB DEVELOPMENT WITH ASP. NET3 6 9594CH 02. qxd 1/3/08 10:46 AM Page 36 Web Forms with ASP. NET At the heart of web applications and web sites in ASP. NET are the elements. can drag and drop controls from the Toolbox onto the page to create your web UI. See the example in Figure 2- 19, where an ASP. NET Button, Label, and TextBox control have been added to the page. CHAPTER

Ngày đăng: 12/08/2014, 09:20

Mục lục

  • Basics of Web Development with ASP.NET

    • Using Visual Studio

      • Visual Studio and Solutions

        • Copy Web Site

        • Start Options

        • View in Browser

        • Browse With

        • Refresh Folder

        • Property Pages

        • The Code and Design Windows

        • Architecture of ASP.NET

          • The ASP.NET Worker Process and State Management

          • Using the Web Configuration File

          • Summary

          • Web Forms with ASP.NET

            • Understanding Page Processing

            • Looking at Web Forms

              • HTML Forms

              • An HTML Forms Example in ASP.NET

              • Using a Server Control to Provide Feedback

              • Using ASP.NET Events and Automatic Postbacks

              • View State

              • Processing Web Forms

                • Page Framework Initialization

                • Application Code Initialization

                • Performing Validation

                • Performing Event Handling

Tài liệu cùng người dùng

Tài liệu liên quan