Beginning asp net 2.0 with c phần 6 pdf

77 353 0
Beginning asp net 2.0 with c phần 6 pdf

Đ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

Componentization You’ll see how you can manipulate all of these controls in the same way as you might expect to when using a single file Try It Out Creating a Code-Behind File Open VWD and create a new web site called TestCodeBehind in the Chapter directory (C:\BegASPNET2\Chapters\Begin\Chapter10) Go to Solution Explorer and click the plus symbol (+) next to Default.aspx to expand the tree to reveal the file Default.aspx.cs (refer to Figure 10-1) Again, Default.aspx is the only file that has the code-behind file automatically created for you If you create another Web Form, you must make sure to check the Place Code in a Separate File option, which is unchecked by default Go back to the Default.aspx file and add two Label controls, a TextBox control, and a Button control, as shown in Figure 10-2 Figure 10-2 353 Chapter 10 Adjust the source HTML to read as follows: Go back to Design View and double-click anywhere on the background of Default.aspx other than on the controls Doing so will open up into the code-behind file, shown in Figure 10-3 Figure 10-3 Add the following code to the Page_Load event handler: if (Page.IsPostBack) { if (TextBox1.Text == “42”) Label2.Text = “So you read Douglas Adams as well ”; else { 354 Componentization Label2.Text = “No, I’m not sure that’s it”; } } Click the green arrow to run it You may get a textbox asking whether or not to add a new Web.config file or run without debugging Click the former Enter a value or lengthier sentence into the text box, as shown in Figure 10-4 Figure 10-4 How It Works It all seems very simple — instead of putting your code within tags, you place it within a separate page, connected by the Page directive tag Indeed, if you check at the top of the Source View for Default.aspx, you can see that the following was already created: This refers to the code-behind file Default.aspx.cs There the following code is run when the Page_Load event is called (when the page is viewed) This is just the normal kind of code talked about in Chapter 9: if (Page.IsPostBack) { if (TextBox1.Text == “42”) Label2.Text = “So you read Douglas Adams as well ”; else { Label2.Text = “No, I’m not sure that’s it”; } } It says if the page has been posted back (submitted), check the contents of the TextBox control If it equals 42, then you have your correct answer, and you set the Label2 control’s Text property accordingly If the contents of the TextBox control not equal 42, you display a different answer (“No, I’m not sure that’s it”) However, there is a bit more going on beneath the covers, namely the method by which your code is compiled 355 Chapter 10 Compilation in ASP.NET 2.0 Compilation is another one of those subjects that this book doesn’t go into in depth, because you don’t need to know too much about it However, you should be aware of its presence When you submit your Web Form to the server, your Web Form and ASP.NET pages first have to be translated into a language the server can understand This is known as compilation You can see how this process works in NET 2.0 in Figure 10-5 Disk ASP.NET page Compiler Request NET CLR Runtime Intermediate Code Response Figure 10-5 The compiler changes your code into something known as intermediate code, or Microsoft Intermediate Language (MSIL) This language is something that is independent of any PC it is run on The NET CLR (Common Language Runtime) is able to take this intermediate code and change it into executable code that it can run and provide output for The output is then sent back to the user as a response (There’s actually a bit more to this process, as you’ll see in Chapter 14.) During the process of compilation, your pages are approved syntactically, so if you’ve made any typos such as the following, they will be spotted at compile time: if (Paige.IsPostBack) Your code can be compiled in two ways: ❑ 356 Pre-Runtime Compilation: The “normal” way (or the “old way,” — the default way in ASP.NET 1.1) Code-behind files are compiled into an assembly and stored in the \bin directory Web Forms and aspx pages are compiled when needed Componentization ❑ Full Runtime Compilation: Code-behind files and any other associated code can now be placed in the App_Code folder ASP.NET 2.0 will then create and maintain references to the assembly that is generated from these files at runtime There is actually a third option called deployment pre-compilation, which is for full compilation of your project prior to deployment You’ll learn a little more about this in Chapter 16 The App_Code Folder If you create an App_Code folder in your project, any code you place in that project will automatically be compiled when you run the project It’s a far more robust solution than the old \bin folder used by ASP.NET 1.x, and for that reason you should use it for any code other than code-behind The reason you should not use it for code-behind is that it is easier in VWD to keep your code files attached to the page they are related to; otherwise viewing them could be a pain So not only can you organize your code and in which pages it is placed, but ASP.NET 2.0 dictates a different structure for ordering where those pages are placed Data Layers You’ve looked at how code and content can be successfully separated, but there is a third dimension to our discussions, namely that of the data Throughout this book, we’ve paused to reflect briefly on various aspects of the history of the Internet and the Web, while trying to keep you away from a huge lecture on the entire subject However, another quick history lecture is in order here to help you understand the purpose of the next ASP.NET 2.0 feature Two-Tier Applications Rather than rewinding too far back, let’s jump in halfway When HTML started getting beyond the universities, it became necessary to provide something more than just static text and images One of the first ways in which web pages were made dynamic was to enable them to access a database The browser was one tier, and the database was the second tier In this scenario, the browser dealt with rules about the business or application and user interface The term business rules is used to encompass any part of the application logic that isn’t the user interface or the database If the application isn’t being used for a business, then the term application logic might be more applicable, although they mean the same thing The data retrieval and manipulation was performed by another separate database application, such as SQL Server or Microsoft Access It would handle the data storage and retrieval device for the application These two-tier applications were also commonly know as client-server applications A typical clientserver application is depicted in Figure 10-6 357 Chapter 10 REQUEST Server Client RESPONSE Figure 10-6 The other popular variation on the two-tier application saw the business rules (application logic) being executed on the database system Such applications would commonly use stored procedures to manipulate the database (or in some cases triggers) A stored procedure is a query that is stored on the database It can be called by the client application and then run on the server It would contain rules about the business as well For example, if you had a league table on Wrox United that awarded three points for a win and one point for a draw, then in the database query, it would somehow have to record that when one side scores more goals than another side, it is worth three points This is a business rule It doesn’t matter to the database how many points you add on to the win; however, your league table would fail to work properly if you added two or five points for a win Three-Tier Applications The big difference with three-tier applications is that business rules are no longer located on either the client or the database They are stored and run on a system in between the client and the server The advantage of this is that the business rules server can ensure that all of the business processing is done correctly There is now a third layer interface, business rules and data The introduction of the data tier is illustrated in Figure 10-7 REQUEST Server Client BUSINESS RULES RESPONSE RECORDS QUERY Data Source Figure 10-7 In a three-tier application, the client never accesses the data storage system directly You can make changes to the business rules and this would mean you could change any part of the system without having to alter the other two parts As the three different sections of the application communicate via interfaces, and as long as the interface between the code and application front-end remains the same, the internal workings of each part can be changed without affecting the rest of the application The 358 Componentization advantages of doing this are similar to those for keeping code and content separate Typically, a database is managed by a database administrator (DBA), and it might even be managed by a separate company The web developer as jack-of-all-trades would previously have been required to know the intimate workings of the database, when really they shouldn’t be interfering there at all So this brings you to the end of your little excursion, because you can now look at a new feature in ASP.NET 2.0 that allows you to separate your applications more simply into three tiers What’s New in ASP.NET 2.0 In ASP.NET 2.0, you are no longer restricted to binding only to data controls You can also bind to separate business controls via the ObjectDataSource control Using the ObjectDataSource Control The new ASP.NET ObjectDataSource control enables you to declaratively bind data controls such as the GridView, DataList, and DropDownList controls to a separate business control or a data component Previously, you could only bind the controls directly to a database This new development enables the separation of your business rules from your content and your data ObjectDataSource is a more difficult control to explain than a GridView or DropDownList control, so rather than wasting excessive verbiage, it’s quicker to show you exactly what the ObjectDataSource control does in an example You’re actually going to two examples to show it in action In the first example, you’ll see how to create a data component to return a list of players from the Players table This Try It Out is split into two sections: the first section where you create the ObjectDataSource itself and the second where you bind the ObjectDataSource control to a GridView control The resulting output will be completely non-editable In the second example, you’ll use the Try It Out to create a data component that can not only read from the Wrox United database but also write data to it You’ll create and bind the data component in this same example that will make it quite lengthy The data component that you create in both examples will consist of an XSD schema file (.xsd) This file describes the data you require and defines which methods will be used to read and write data This doesn’t require any code or knowledge of XML schemas because when you run the application, the xsd file is compiled for you and performs all of the tasks needed Start by creating the data component for the read-only example Try It Out Creating the Data Component Open Visual Web Developer and select Open Web Site From the C:\BegASPNet2\Chapters\ Begin\Chapter10 folder, select ObjectDataSource and click OK In Solution Explorer, right-click the name of your web site, select Add ASP.NET Folder, and select App_Code Right-click the App_Code folder and select Add New Item from the list From the Visual Studio installed templates, click DataSet Rename the DataSet ods.xsd and click Add VWD starts the TableAdapter Configuration Wizard (Be patient here, because this one really does take a while to kick in.) When the wizard finally arrives, select ConnectionString (Web.config) from the drop-down list (see Figure 10-8) and click Next 359 Chapter 10 Figure 10-8 Next you get a page where you can choose to use SQL statements or stored procedures Select the Use SQL statements radio button (as shown in Figure 10-9) and click Next Figure 10-9 360 Componentization On the next wizard screen, you can define the SQL statement Type the following SQL statement into the “What data should be loaded into the table” area of the dialog box: SELECT PlayerID, FirstName, LastName, Position, DateJoined, DateLeft FROM Players After entering the SQL statement, click Next You can now define which methods the component will expose Uncheck the Fill a DataTable check box and make sure that the Return a DataTable check box is checked (see Figure 10-10) In the Method name box, type GetPlayers This method is used later to retrieve the data Uncheck the final check box Figure 10-10 10 Click Finish In Figure 10-11, you can see the data component in the designer It shows both the data you selected and the method you created Figure 10-11 11 12 Save the data component and close the component designer Select Build➪Build Web Site to compile the component (Note that this won’t produce anything viewable.) 361 Chapter 10 How It Works The data component is now usable as a data source within a Web Form You’ve used the wizard to create the component for you, to select the fields from the database, and also to name the method by which you want to be able to call this component Thenext step is to bind to this component To this, you can create and configure an ObjectDataSource control You can then add controls, such as the GridView control, to the page and bind them to the data source control Try It Out Binding to the ObjectDataSource Control Open the Default.aspx from Solution Explorer and switch to Design View Open the Toolbox and from the Data section drag an ObjectDataSource control onto the page Select the Toolbox again, and from the Data section drag a GridView control onto the page Click the black arrow in the top-right corner of the ObjectDataSource control The Common Tasks box appears with the words “Configure Data Source.” Click this In the dialog box that appears, there is a single drop-down list asking you to choose your business object (see Figure 10-12) There should only be one, the odsTableAdapters PlayersTableAdapter Select it and click Next Figure 10-12 362 On the next screen (shown in Figure 10-13), under the Select tab in the Choose a method dropdown box, the GetPlayers(), returns PlayersDataTable method is displayed Select it and click Finish (the other methods are automatically picked for you) Roles and Profiles The convoluted syntax for retrieving the value of each control should be a bit more familiar from the code used earlier in this How It Works section, but there’s one addition here Notice that there is a test to see if the txtName text box exists on the currently visible version of the page: TextBox NameBox = (TextBox)FCLoginView.FindControl(“txtName”); if (NameBox != null) { So, if the txtName text box is visible (which it will be if the user is logged in as a member of the FanClubMember role), then the profile data is retrieved If the user is anonymous, or is a member of other roles (and not the FanClubMember role), then the profile will not exist To avoid errors at run-time, you don’t want to try to retrieve data that does not exist, so this check is essential (just try removing it and accessing the page as an anonymous user to see the mess if you’re not careful) One last thing to consider before moving on — in the layout code (on FanClub.aspx), there were some controls that you may not be familiar with yet: Name: In the layout code, each TextBox control had a validation control next to it In this example, the txtName TextBox had a RequiredFieldValidator control next to it, which will ensure that users fill in data for each of the required fields before saving profile changes Essentially, the text box is marked as “Required,” as the validator’s name suggests If no value is entered, there will be a small red asterisk displayed next to the text box You’ll learn more about validation controls in Chapter 15, where you can see how they are used to minimize data entry errors and protect your code from malicious user input So, you’ve stored some simple data in a user profile If you want to know where exactly this data is stored, you will find it in the AspNetDB.mdf database Take a look in the aspnet_Profiles table and you will see that data, similar to Figure 11-19, is stored in your database In Figure 11-19, you can see that the Lou profile currently has some properties set, as you specified in the example You will not need (or want) to edit this data, but it’s useful to know where it’s stored 415 Chapter 11 Figure 11-19 Storing Preferences There’s one last example that you can play with in this chapter, and that goes way back to the discussions you will recall from Chapter In that chapter, along with page styling and CSS, you learned the concept of storing layout and style preferences in themes These themes can be switched on a page-by-page basis as was discussed in that chapter However, you can also store data about which theme a user may prefer to use for a site in a user profile, enabling users to personalize their viewing experience a bit more In the following Try It Out, you have a go at including this functionality in the Wrox United application Try It Out Storing Theme Preference in Profiles Add the following highlighted lines of code to the FanClub.aspx page: Membership Alias: Theme: 416 Roles and Profiles The other piece of the puzzle is to add some code to store and retrieve the theme preference from the user’s profile Modify FanClub.aspx.cs to add the following highlighted lines of code to the btnSaveChanges_Click event handler: protected void btnSaveChanges_Click( object sender, System.EventArgs e) { Profile.Theme = ((DropDownList)FCLoginView.FindControl(“ThemeList”)).SelectedValue; Profile.Name = ((TextBox)FCLoginView.FindControl(“txtName”)).Text; Profile.Address = ((TextBox)FCLoginView.FindControl(“txtAddress”)).Text; Profile.City = ((TextBox)FCLoginView.FindControl(“txtCity”)).Text; Profile.County = ((TextBox)FCLoginView.FindControl(“txtCounty”)).Text; Profile.PostCode = ((TextBox)FCLoginView.FindControl(“txtPostCode”)).Text; Profile.Country = ((TextBox)FCLoginView.FindControl(“txtCountry”)).Text; Profile.Mailings = ((CheckBox)FCLoginView.FindControl(“chkMailing”)).Checked; Profile.Email = ((TextBox)FCLoginView.FindControl(“txtEmail”)).Text; Profile.MemberName = ((TextBox)FCLoginView.FindControl(“txtAlias”)).Text; Server.Transfer(SiteMap.CurrentNode.Url); } Modify the DisplayProfileProperties method to include the code that will retrieve and display the currently stored value for the Theme property from the user’s profile: private void DisplayProfileProperties() { TextBox NameBox = (TextBox)FCLoginView.FindControl(“txtName”); if (NameBox != null) { ((DropDownList)FCLoginView.FindControl(“ThemeList”)).SelectedValue = Profile.Theme; ((TextBox)FCLoginView.FindControl(“txtName”)).Text = Profile.Name; ((TextBox)FCLoginView.FindControl(“txtAddress”)).Text = Profile.Address; ((TextBox)FCLoginView.FindControl(“txtCity”)).Text = Profile.City; ((TextBox)FCLoginView.FindControl(“txtCounty”)).Text = Profile.County; ((TextBox)FCLoginView.FindControl(“txtPostCode”)).Text = Profile.PostCode; ((TextBox)FCLoginView.FindControl(“txtCountry”)).Text = Profile.Country; ((CheckBox)FCLoginView.FindControl(“chkMailing”)).Checked = Profile.Mailings; ((TextBox)FCLoginView.FindControl(“txtEmail”)).Text = Profile.Email; ((TextBox)FCLoginView.FindControl(“txtAlias”)).Text = Profile.MemberName; } At this stage, you’ve added all the required code to store the preference The thing that’s missing is the ability to actually switch the theme on the pages on the site Right-click the App_Code folder and add a new item Select Class from the list of available templates, and call it ThemeModule.cs, as shown in Figure 11-20 417 Chapter 11 Figure 11-20 Enter the following code into the new Class file: using System; using System.Web; using System.Web.UI; namespace Wrox.Web.GlobalEvents { public class ThemeModule : IHttpModule { public void Init(HttpApplication context) { context.PreRequestHandlerExecute += new EventHandler(this.app_PreRequestHandlerExecute); } private void app_PreRequestHandlerExecute(object Sender, EventArgs E) { Page p = HttpContext.Current.Handler as Page; if (p != null) { ProfileCommon pb = (ProfileCommon)HttpContext.Current.Profile; p.Theme = pb.Theme; } } public void Dispose() { } } } 418 Save the file Open Web.config and add the following highlighted code, just below the System.Web node: Roles and Profiles Run the page You will see that there is now a drop-down box (shown at the bottom of Figure 11-21) on the page that enables you to select different themes to store in your user profile Figure 11-21 How It Works In this example, you extended the basic FanClub.aspx page so that users can store their preferred theme in their profile This facility is available only to registered members of the Fan Club Amending the layout code was a simple process of adding a DropDownList control to the page: 419 Chapter 11 The value for the theme is stored as a simple string of text in the user’s profile, and is set in the same way as any other profile setting: Profile.Theme = ((DropDownList)FCLoginView.FindControl(“ThemeList”)).SelectedValue; This code means “find me the ThemeList control; it’s a DropDownList, so get me its SelectedValue property.” In this case, the DropDownList control’s SelectedValue property will be whatever the Value property for the selected item is set to, so, for example, if the user selected the item with the text “Wrox Red,” the value stored would be WroxRed At this stage, the profile has been updated with the user’s preference, but the last bit of this exercise gave the site the capability to apply the selected theme to each page You used an HttpModule to this An HttpModule contains code that is processed every time any page in an application is processed The module can be enabled and disabled via the Web.config file The module code can handle events that are raised each time a page is requested In this case, the event that is intercepted is processed before the code on a page is processed, and the requested page’s theme can be changed to match the theme specified in the user’s profile This section of the code is getting to be quite advanced in terms of programming techniques Don’t worry if you don’t fully understand how this works — you will encounter more code like this in Professional ASP.NET 2.0, so you can treat this as a taste of what you can expect when you start to unleash the full power of ASP.NET Take a look at the code in the HttpModule and see how it works: using System; using System.Web; using System.Web.UI; namespace Wrox.Web.GlobalEvents { public class ThemeModule : IHttpModule { The first part of the code in the file imports a few useful namespaces that contain classes you’ll need later in the code The ThemeModule class is configured to reside within the Wrox.Web.GlobalEvents namespace Additionally, the ThemeModule class implements the IHttpModule interface, which turns this simple class into a class that can be used as an HttpModule, provided you then implement the required methods, because there are some specific methods that all HttpModules must implement in order to work correctly In this case, two methods have to be implemented: the Init() method and the Dispose() method Here’s the Dispose() method — because there’s nothing that you need to in this method, the empty method signature will just sit there in the file not bothering anyone: 420 Roles and Profiles public void Dispose() { } Now compare that to the code in the Init() method: public void Init(HttpApplication context) { context.PreRequestHandlerExecute += new EventHandler(this.app_PreRequestHandlerExecute); } The code within the method itself is a bit tricky to grasp at first There’s only one line to consider, which declares a new event handler The event handler will run each time the current context is at the PreRequestHandlerExecute stage in the request life cycle — in plain English, that’s pretty early in the request stage This line of code means that each time the appropriate event fires, you can add an event handler that will be processed: private void app_PreRequestHandlerExecute(object Sender, EventArgs E) { Page p = HttpContext.Current.Handler as Page; if (p != null) { ProfileCommon pb = (ProfileCommon)HttpContext.Current.Profile; p.Theme = pb.Theme; } } This method handles that PreRequestHandlerExecute event The first line in this method gets the currently requested page object so that you can interact with it: Page p = HttpContext.Current.Handler as Page; Notice the method used here to cast the current Handler object to a Page object type This means that if the requested item is a page, the cast will be successful and the p object will contain an object reference to the requested page However, if the item requested is not a page, the cast fails, and the p object is set to NULL As long as the Page object exists (and is not set to Nothing), you can then try to apply the theme to the page by obtaining the current profile properties and using that profile’s Theme property: if (p != null) { ProfileCommon pb = (ProfileCommon)HttpContext.Current.Profile; p.Theme = pb.Theme; } Notice that the way casting is performed in this case (casting the current Profile object to type Profile Common) will throw an exception if the attempted cast fails The only case when this would happen would be if you disabled profiles in the Web.config file, which would surely make this example a bit pointless At the end of this method, the Theme property of the page is set to the value stored in the profile property called Theme 421 Chapter 11 Finally, there was a new section added to the Web.config file that enabled the HttpModule itself: The section can be filled with many different modules that you may want to run In this example, there is just one module — the ThemeModule The ThemeModule class that was declared is added in the type attribute, along with the namespace that it resides in, so that NET knows exactly which ThemeModule you want to run That’s about it for this example It’s a tricky piece of code, but it’s a neat way to make themes switch instantly on pages, and to stay switched for all pages on a site, because the module will run for each requested page on a site Managing Anonymous Shopping Car ts Earlier this chapter, the presence of the following profile property was briefly mentioned: The allowAnonymous flag that is stored against the Profile.Cart value for each user session indicates that anonymous users can have a shopping cart In this case, users may visit the site and neglect to log on, or they may be completely new to the site The user will then happily fill up a basket with items, so it will be up to you to handle either switching the cart to an existing user when they log in, or creating a new profile when the anonymous user logs in and transferring the cart to the newly created user when the user attempts to check out There is code that handles this transition in the Global.asax file, which handles global events raised by the code Here’s the code as it is used in the Wrox United application: void Profile_OnMigrateAnonymous(object sender, ProfileMigrateEventArgs e) { // get the profile for the anonymous user ProfileCommon anonProfile = Profile.GetProfile(e.AnonymousID); // if they have a shopping cart, then migrate that to the authenticated user if (anonProfile.Cart != null) { if (Profile.Cart == null) Profile.Cart = new Wrox.Commerce.ShoppingCart(); Profile.Cart.Items.AddRange(anonProfile.Cart.Items); anonProfile.Cart = null; 422 Roles and Profiles } ProfileManager.DeleteProfile(e.AnonymousID); AnonymousIdentificationModule.ClearAnonymousIdentifier(); } This code is examined in far more detail in Chapter 13, when you see exactly how the whole shopping experience works, but it’s useful to understand that there are consequences when you log in as a user The transferring of a shopping cart from one profile to another is the most important, because none of the other properties can actually be set for anonymous users Summar y This chapter delved deeper into the world of roles, and introduced the concept of user profiles for storing additional data about a user The two technologies can sit happily side-by-side, and used together are a great way to control access to a site and for customizing the user experience In this chapter, you had a chance to take more control over the access permitted to users on a fully functional web application, including the following: ❑ Show or hide resources to selected user roles ❑ Display different page content depending on which role views the page ❑ Display links to selected pages, but prompt the user for more credentials for authorization ❑ Store more information about users in their user profile ❑ Store different types of data in a user profile, including the user’s preference for site theme These techniques will be expanded in the upcoming chapters to form part of the shopping cart functionality built in to the Wrox United site Exercises Create a new user account called Admin, and make this user a member of all groups Log in to the Wrox United site as Admin and test to see whether you can access all of the different pages in both the fan club and the administration section Remove the Admin user from any role other than the Administrator role and test the site again Ensure that you can access the following pages: ❑ ❑ EditNews.aspx ❑ Admin.aspx UpdateProducts.aspx The Admin user has had a request by a reporter out in the field — he’s uploaded a score for a match, but the score has just changed Unfortunately, the reporter’s laptop has run out of battery, so he’s asked the Admin user to update the score for him Make sure that the Admin user can update the score of a match 423 Chapter 11 424 Add a field to the user profile for the Wrox United application called DateOfBirth Give this property a data type of System.DateTime Add an input field to the FanClub.aspx page so that users can update their date of birth Note that you will need to convert the value entered in a text box to a DateTime value when you save the data — you might want to try the DateTime Parse() function for this purpose To retrieve the data, use the Profile.DateOfBirth ToShortDateString() function 12 Web Ser vices Web services have been “the next great thing” for a little too long now They were originally introduced as part of the NET Framework in its first incarnation (although they have been present in Java for a lot longer) Web services are a method of making information available in a standardized way that could be accessed by any developer’s application over the Web Web services can form a library or shared repository of information that could be anything from the latest weather forecast, a map of your local amenities, a mathematical function calculator, to the tracks and album cover of the CD that you just inserted into your CD-ROM drive You should be aware, though, that a web service on its own isn’t an application Web services aren’t rendered as web pages, or as executable files (.exe); they come completely shorn of a user interface It’s up to you as a developer to use them and integrate them into your applications They are there to save you time and effort by reducing code duplication They can be used in one of two ways You can create a web service that is exposed to the web, to share with other developers and other applications Or you can search for a web service that can be added to your own application (They are similar to plug-ins in that respect.) For example, if your application is a company web site and you want to include directions to company headquarters, rather than scan in a map, or attempt to hand-draw one in a graphics tool, why not use one of the web services that makes sections of maps available online? The information contained in the web service is wrapped up as an XML document (in other words, plain text), so that worries about platform-specific concerns, such as whether you’re accessing them on an old Windows 98 machine or a turbo-powered Powerbook, simply evaporate Web services aren’t really anything new either — components have been performing a similar trick for many years now However, there are some crucial differences Components had to be distributed by the developer, and they had to be downloaded and installed These things alone meant that they tended to be tied to one platform This isn’t true of web services A key word that emphasizes what web services offer is standard Everything to with web services is standardized: the method of transmission, the method used to wrap the web service up, the way the web service is defined, all have clear W3C standards associated with the technologies involved And to make life much easier, all these standards are based on XML So they’re quick and easy to download, and even easier to use Chapter 12 This chapter looks at the following: ❑ Introducing web services ❑ Consuming web services ❑ What happens in the typical life cycle of a web service ❑ Testing a web service ❑ Discovering a web service ❑ Creating and consuming an example web service that uses a parameter ❑ Creating a proxy — the old way of doing things ❑ Web service security Looking at Web Ser vices The introduction alluded to the fact that web services haven’t quite taken off in the way that was expected, and it’s true and there are probably several reasons for that, but none that should stop you from using them One is that developers and businesses don’t like giving away their hard work for free The truth is when businesses create a web service, it usually isn’t for public consumption It is for inhouse use only, and even if it is available for the public to use, it is likely to come at a price On the flipside, with free web services, you have no guarantee that they will still be there in a week or a year’s time, so it’s no good basing a large application around them So you fork out for a web service and increase the cost of your application, or take a gamble that a particular service will still be in existence over the next few years? This dilemma isn’t easily remedied Second is lack of education People are still largely unaware of what web services can offer I recently worked on a customer services application, which had to integrate with an existing contacts manager application and detect when the contacts manager was running and if it had loaded the latest customer information correctly Rather than use a web service to make this information available, the client chose instead to write to the clipboard (especially awkward considering the users themselves might also be using the clipboard) and then my application had to periodically check the clipboard for the text to indicate that the contacts manager was running As a result, the application was 20 times more complicated than it needed to be Third is the lack of a single killer application Before you started this chapter, could you name five common examples of web services? The problem is that they’re too good at the job they do, so they become practically invisible Where is the Google or Internet Explorer of web services? I don’t know, but you might just be using it unwittingly A good web service should dovetail seamlessly into your application, and your user should never know it’s there Last is the apparent learning curve required With web services, it’s easy to get drawn into listing the mass of technologies involved, and therefore easy to get confused about what you need to know SOAP, WSDL, UDDI, and DISCO all play valid parts in the process of making a web service available However, you don’t need to know about any of these acronyms to be able to use a web service In fact, before you start creating a web service and learning what goes into them, it’s a good idea to look at an example first 426 Web Services Consuming a Third-Party Web Service Consuming a web service is almost as easy as firing up your browser, typing in a URL of a web service, and pressing Return Perhaps we’re oversimplifying a little bit here, but if you browse to the URL of a web service endpoint, you will find that you can use it functionally, albeit without any graphical frills An endpoint is the specific location where the web service can be accessed So let’s exactly that Because of the nature of the Web, sites are very often up and down If you wanted to phone up a plumber on the other side of the city, you’d check your local phone directory for a number — but that plumber may or may not still be in business, and web services are just the same Several good starting points are the following sites: www.webservicex.net, www.webservicelist.com, www.webservice oftheday.com, and www.wsiam.com All of these sites provide lists of web services you can browse More alternatives are available, and if one of these sites is inoperable, another will be working There are plenty of possibilities to integrate web services into your example site Wrox United chronicles the football fixtures, results, merchandise, and news of one soccer team Now Wrox United isn’t always the most successful soccer team in the league, and they’re usually looking for an excuse on which to hang a particularly poor performance, such as the weather It would be nice if you could stick a weather report on the bottom of your match reports, just so you know that if the goalkeeper claims the fifth and sixth goals slipped through his hands, maybe the 85-degree temperature would be a bit of a giveaway In the following Try It Out, you start by finding an example weather web service that is freely available Try It Out Consuming an Example Web Service To be able to access a web service, you need to locate an asmx file (you’ll learn what one of those is after you’ve finished this example) Figure 12-1 shows an example of a weather service at www.webservicex.net/globalweather.asmx Figure 12-1 If for any reason this web service is giving an HTTP error 404, go back to any of the previous web service directories, type Weather into the search link, and use one of the example sites it returns Most weather web services work the same way 427 Chapter 12 There are two possible web services here The format and style of this screen are the same for any asmx web service file you browse The link to the web service that gives you the weather forecast is called GetWeather Click this link, and you’ll arrive at a screen similar to Figure 12-2 Figure 12-2 428 Supply the name of the city where you live, or closest to where you live, and the name of the country Scroll down and look at the code (see Figure 12-3) Figure 12-3 Web Services Click Invoke to get the result, shown in Figure 12-4 It will be customized to where you live and is dependent on the weather of the moment Figure 12-4 How It Works You’ve just consumed a web service The Wrox United application does not have the capability to weather forecasting, so you looked elsewhere to get this service By browsing to an asmx file, you are able to use the web service, and supply input and get an answer tailored to your specifics When you supplied the city name and country name, you probably noticed that your input was wrapped up in an XML document This is the document broadcast to the server Although the data can be wrapped up by three different methods, just look at the first on the page for now: POST /globalweather.asmx HTTP/1.1 Host: www.webservicex.net Content-Type: text/xml; charset=utf-16 Content-Length: length SOAPACTION: “http://www.webserviceX.NET/GetWeather” string string Your input is simply substituted for the words string in the highlighted code: Birmingham United Kingdom 429 ... ASP. NET server control 367 Chapter 10 Login Control (ASP. NET) Link to ShoppingCart Control (User) Figure 10- 16 News Control (User) So why isn’t everything an ASP. NET server control? Well, ASP. NET. .. into a central location that can be accessed from anywhere within the site These components, like user controls, can contain one or more classes However, the crucial difference is that ASP. NET uses... new ASP. NET web site called SimpleUserControl in the chapter directory (C: \BegASPNET\Chapters\Begin\Chapter10) 370 In Solution Explorer, right-click the web site and select Add New Item Select

Ngày đăng: 09/08/2014, 18:22

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

Tài liệu liên quan