Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 105 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
105
Dung lượng
0,94 MB
Nội dung
808 CHAPTER 18 BUILDING DATA-BOUND APPLICATIONS For a truly disconnected application, you should give users a chance to store the data locally at the client. The LinkedDataTables application’s main form contains two more buttons: the Save Data Locally and Load Local Data buttons. The first one saves the DataSet to a local file via the WriteXml method of the DataSet, and the second button loads the DataSet via the ReadXml method. The application uses the tmpData.#@# filename in the application’s folder to store the data. It also uses an overloaded form of the two methods to accept an additional argument that stores not only the data but the changes as well. Here’s the code behind the two buttons: Private Sub Button1_Click(…) Handles Button1.Click DS.WriteXml("tmpData.#@#", XmlWriteMode.DiffGram) End Sub Private Sub Button2_Click(…) Handles Button2.Click ProductsBindingSource.SuspendBinding() DS.ReadXml("tmpData.#@#", XmlReadMode.DiffGram) ProductsBindingSource.ResumeBinding() End Sub Let’s explore now how data binding can be used in combination with Language Integrated Query (LINQ) query syntax. Data Binding with LINQ You are surely convinced by now that LINQ is a fundamental part of .NET query infrastruc- ture. You have explored LINQ in detail in Chapter 14, ‘‘An Introduction to LINQ,’’ where I also mentioned the LINQ to DataSet technology. The great thing about LINQ is that once you learn how to write queries, you can apply the same syntax to any data source that supports LINQ. DataSets and typed DataSets also support LINQ, and you can apply the same syntax you saw used to query objects in LINQ to Objects and in LINQ to SQL to typed DataSets. So far in this chapter you saw how data binding can make life a lot easier for a programmer developing data-centric applications. And you have already witnessed the power of LINQ. The two can be used in combination as a powerful tool for data manipulation. Enabling the Binding with the DataView Class The central class for binding support is the DataView class. It represents a bindable and customizable view of data and provides a number of data manipulation methods. Using DataView, data can be filtered, searched, sorted, edited, used for navigation, and so on. LINQ to DataSet queries are capable of returning the DataView instance by means of the AsDataView extension method. Thanks to this extension method, you can set the query as a DataSource of a BindingDataSource class like this: mybindingSource.DataSource = (From product In NorthwindDataSet.Products Select product).AsDataView() Now you see how you will be able to add some sophisticated querying capabilities to your data bound applications. Let’s illustrate this by adding some querying features to our Products application, as shown earlier in the chapter in Figure 18.21. DESIGNING DATA-DRIVEN INTERFACES THE EASY WAY 809 Using LINQ to Filter Products Data In cases where data operators have to manage a large number of entries, listing all of these on the form with navigation capability can prove not to be very practical. Users will be forced to spend a lot of time while navigating between records. In such cases, providing some filtering capability can prove to be very beneficial. Let’s add some filtering features to our form in the Products project. I will use following criteria for the filtering functionality: ◆ Category selected by user ◆ Units in stock less than the number entered by the user ◆ Units on order greater than the number entered by the user This way, users will be able to filter products by category and by some important opera- tional data. They will be able to see when the numbers of units in stock is low or what product units for an order are piling up. Figure 18.23 shows the new version of the Products interface. Figure 18.23 Reviewing the deleted rows in the DataSet You can use these criteria in any kind of combination. To know whether criteria should be applied or not, it is best to count on some special value. If the Units In Stock Less and Units On Order Greater text boxes are empty, then they should not be used in a query. For the category, the special value of the combo box is the text All. To add this value to Combobox, it has to be populated by your application and not through the data binding. The following code populates the Categories Combobox and is placed inside the Form_Load event handler: cboCategoryFilter.DisplayMember = "CategoryName" cboCategoryFilter.ValueMember = "CategoryID" cboCategoryFilter.Items.Insert(0, "All") 810 CHAPTER 18 BUILDING DATA-BOUND APPLICATIONS For Each category In NorthwindDataSet.Categories cboCategoryFilter.Items.Insert(category.CategoryID, category) Next Now you are ready to write the LINQ query that uses these criteria. Because these criteria can be used in any combination, writing the query might prove to be a bit trickier than you initially thought. The solution is to use the special value of criteria inside the query itself. For example, the expression cboCategoryFilter.Text = "All" is true if the user does not want to apply the categories criteria. As you can see, I have named the categories ComboBox cboCategory- Filter. If you combine this statement with product.CategoryID = categoryId using the OrElse operator, then you can use the cboCategoryFilter.Text = "All" expression to turn off the categories criteria when the user selects All in the Categories combo. The complete statement to be put in the Where part of the LINQ query for Categories combo is as follows: cboCategoryFilter.Text = "All" OrElse product.CategoryID = categoryId. The same pattern can be applied to rest of conditions. For other criteria, the special value is an empty string. You can take a look at the complete code for the Filter button in Listing 18.9. Listing 18.9: Coloring the edited and inserted rows on the DataGridView control Private Sub bttnFilter_Click( ) Handles bttnFilter.Click Dim categoryId As Integer If Not cboCategoryFilter.Text = "All" Then categoryId = CType(cboCategoryFilter.SelectedItem, NorthwindDataSet.CategoriesRow).CategoryID End If queryResult = From product In NorthwindDataSet.Products Where ((cboCategoryFilter.Text = "All" OrElse product.CategoryID = categoryId) And (String.IsNullOrEmpty(txtUnitsOnOrderFilter.Text) OrElse product.UnitsOnOrder > CInt(txtUnitsOnOrderFilter.Text)) And (String.IsNullOrEmpty(txtUnitsInStockFilter.Text) OrElse product.UnitsInStock < CInt(txtUnitsInStockFilter.Text))) Select product ProductsBindingSource.DataSource = queryResult.AsDataView() End Sub THE BOTTOM LINE 811 The Bottom Line Design and use typed DataSets. Typed DataSets are created with visual tools at design time and allow you to write type-safe code. A typed DataSet is a class created by the wizard on the fly, and it becomes part of the project. The advantage of typed DataSets is that they expose functionality specific to the selected tables and can be easily bound to Windows forms. The code that implements a typed DataSet adds methods and properties to a generic DataSet, so all the functionality of the DataSet object is included in the autogenerated class. Master It Describe the basic components generated by the wizard when you create a typed DataSet with the visual tools of Visual Studio. Bind Windows forms to typed DataSets. The simplest method of designing a data-bound form is to drop a DataTable, or individual columns, on the form. DataTables are bound to DataGridView controls, which display the entire DataTable. Individual columns are bound to simple controls such as TextBox, CheckBox, and DateTimePicker controls, depending on the column’s type. In addition to the data-bound controls, the editor generates a toolbar control with some basic navigational tools and the Add/Delete/Save buttons. Master It Outline the process of binding DataTables to a DataGridView control. Compare a LINQ query used to filter data with an eSQL dynamic query. You can use the AsDataView extension method of the DataTable class to enable binding of the LINQ query results when querying the DataSet in LINQ to DataSet technology. In this chapter, you have seen how a LINQ query can be used to provide filtering capabilities on a data-entry form. Entity SQL (eSQL) is a query language with syntax similar to Transact-SQL. Entity SQL queries can be embedded inside the Visual Basic code and can be used to query the Entity Data Model provided by the Entity Framework. You saw how to use Entity SQL to construct dynamic queries in Chapter 17. Master It Compare LINQ queries to queries written in Entity SQL. Explain the main benefits and drawbacks of each technology. Part 6 Developing for the Web ◆ Chapter 19: Accessing the Web ◆ Chapter 20: Building Web Applications ◆ Chapter 21: Building and Using Web Services Chapter 19 Accessing the Web The Internet has changed our everyday lives in many ways, and it has changed the program- ming landscape completely. It is hardly imaginable today to develop any application that is not at least in some way related to the Internet. HTTP, the underlying protocol of the Internet, is a standard protocol for application interoperability and distributed application development. The Internet provides a wealth of information and functionality available in different forms. Most of this information is structured with a human user in mind; a user who will access a website using a web browser. Sometimes, information is useful as is, and you will see how it is easy to incorporate such information into your applications using the WebBrowser control. In other situations, you need to access and extract information from unstructured HTML pages. This process is often referred to as HTML screen scraping. The .NET Framework pro- vides all you need to simulate the browser and access such pages without having the servers ever discover that they are not communicating with a web browser but with your Visual Basic program instead. Support for such access comes in the form of the WebClient class and, in sit- uations where you need more low-level control, the HttpWebRequest and HttpWebResponse classes. These classes can be used to access applications that provide structured information meant to be accessed by other applications but use some more lightweight forms of interop- erability, like XML over HTTP, as opposed to a dedicated information exchange protocol like SOAP. (You will learn more about SOAP in Chapter 21, ‘‘Building and Using Web Services.’’) In the Chapter 20, ‘‘Building Web Applications,’’ you will learn how to develop web applications — applications made to serve the clients over the Internet. In this chapter, we’ll take a look at how you can be on the other side, the consuming side of the wire. You will learn how to access different resources and applications on the Internet through your code and how to integrate browser functionality inside your applications. In this chapter, you’ll learn how to do the following: ◆ Add browser functionality to your Windows Forms applications using the WebBrowser control ◆ Access information and services on the Web from within your code using WebClient or HttpWebRequest and HttpWebResponse classes 816 CHAPTER 19 ACCESSING THE WEB The WebBrowser Control The WebBrowser control is the simplest option for adding some browser functionality to a Win- dows Forms application. It is capable of presenting HTML content with all the usual browser features: hyperlinks, navigation, multimedia content, Favorites, and the like. There can be a number of reasons you would want to add web browser functionality to your application. The Internet provides a wealth of useful information and ready-to-use func- tionalities like address validation, weather forecasts, online calendars, and stock quotes, just to name a few. Many times this information is tailored so it can be included like a ‘‘widget’’ or a ‘‘gadget’’ inside some other web page. These make it especially easy to embed Internet con- tent inside your Windows Forms application, as you will see in the section ‘‘VB 2010 at Work: The Stock Quotes Project’’ later in this chapter. Once you see how easy it is to integrate web browser functionality with the WebBrowser control, I am sure you will think of many other useful ways to enrich your applications with Internet content. With a little bit of work, the WebBrowser control can be used to make a full-fledged custom web browser. This can be useful in situations in which your client needs to restrict the access to intranet-only sites or only to selected Internet sites. Or you might use a WebBrowser control to make a child-friendly browser that can eliminate adult content. Before I show you how to use the WebBrowser control in a plausible application scenario, let’s inspect some of its most important properties. WebBrowser Control under the Hood The WebBrowser control is a managed .NET wrapper over the Internet Explorer ActiveX dynamic link library. This is the same library that the Internet Explorer executable uses internally and is available on any Windows machine. As a consequence, you will not be able to exhort the usual level of control over you appli- cation. Since Internet Explorer is essentially part of the Windows operating system, it will be updated through the Windows Automatic Updates service, so you cannot control the version of Internet Explorer that is being used to render the HTML in your application. While most Internet Explorer versions still in circulation work in a similar manner, there are some known differences in how they render the HTML. The browser operations a user performs on a WebBrowser control will affect the Internet Explorer installation. For example, a Favorite added to the list of Favorites through a Web- Browser control will appear in the Internet Explorer list of Favorites. Pages accessed through a WebBrowser control will appear in the Internet Explorer history. Adding a shortcut using a WebBrowser control will create a new Windows shortcut. And so on. One important aspect to consider when using a WebBrowser control is security. In this respect, the control behaves in the same manner as Internet Explorer and will run scripts and embedded controls inside web pages. In such situations, the WebBrowser control is, according to MSDN, ‘‘no less secure than Internet Explorer would be, but the managed WebBrowser control does not prevent such unmanaged code from running.’’ Now that you have seen what a WebBrowser control is really made of, let’s take a look at its properties. WebBrowser Control Properties Like any other visible Windows Forms control, the WebBrowser control has a number of common layout-related properties, including Size, MaximumSize, MinimumSize, Location, Margin,andAnchor. They all work as you would expect from your experience with other THE WEBBROWSER CONTROL 817 Windows Forms controls, so I will not go into more details on any of these. While belonging to this group, a small note is in order for the Dock property. Dock The Dock property determines how the WebBrowser control is positioned in relation to a con- tainer and how it will behave as the container is resized. Anchoring and docking controls are discussed in detail in Chapter 6, ‘‘Working with Forms.’’ When a WebBrowser control is added to an empty form or a container control, the default value for the Dock property is Fill. As a result, the whole form area will be covered by the Web- Browser control. The WebBrowser control drops into your form as a square with no visible clues as to its position. Although the control’s white background will stand out, you still might be confused at first as to where it is positioned on the form. Just change the default value of the Dock property to some other value, like None, and the control will become visible as you change the form’s size. URL The URL property lets you specify the target URL address for the WebBrowser control in the design time. When you display the form, the WebBrowser control will load that URL by default. If you change the property at runtime, the control will navigate to the new URL. In this respect, setting the URL property works the same as calling the WebBrowser control’s Navigate method (described in the section ‘‘WebBrowser Control Methods’’ later in this chapter). The URL property type is the System.Uri class. A URI (Uniform Resource Identifier) can rep- resent a unique identifier or an address (familiar URL) on the Internet. You will typically use instances of this class to represent an Internet address. When doing so, do not forget to spec- ify the protocol part of the address, otherwise you will get an Invalid URI exception. You can instantiate the Uri class by passing a string representation of the URL to its constructor. Here is the correct way to set the WebBrowser URL property in your code: WebBrowser1.Url = New Uri("http://www.google.com") AllowNavigation The AllowNavigation property sets the WebBrowser control behavior in regards to navigation. If you set the AllowNavigation property to False, the WebBrowser control will not react when a user clicks a hyperlink and will not load the page specified in the hyperlink. It will not react to navigation attempts from within your code either. Calling the Navigate method on a Web- Browser control when AllowNavigation is set to False will have no effect. The only page the control will display is the one that was loaded initially. Bear in mind that AllowNavigation does not alter the visual representation of the page or the cursor. Hyperlinks are still rendered distinctly as hyperlinks (underlined blue text), and the mouse cursor will change to a hand shape when hovering over the hyperlink. Finally, while the AllowNavigation property can prevent users from following a standard HTML hyperlink, it will not prevent the browser from opening a new window as directed by JavaScript code, as, for example, when calling the window.open JavaScript function. Finally, if the user presses F5 (Refresh), the page loaded initially will reload. [...]... addressLocation.Latitude) Replace("replace_me_longitude", addressLocation.Longitude) End Sub 8 39 840 CHAPTER 19 ACCESSING THE WEB With this, you have finished implementing the address visualization functionality You can take a look at the complete code of the form in Listing 19. 9 Listing 19. 9: Imports Imports Imports Imports Imports Imports Address visualization form code System.Net System.IO System.Linq System.Xml.Linq... construct the URL You can declare the Yahoo! service PUTTING IT ALL TOGETHER: THE ADDRESS VISUALIZATION FORM Figure 19. 4 Address visualization form URL as a constant and create the query parameters Listing 19. 4 shows how to construct the NameValueCollection with query parameters for the Yahoo! Geocoding Web Service Listing 19. 4: Form code with constructed Yahoo! geocoding service URL and query parameters Public... VISUALIZATION FORM Now, you can take a look at the result The browser should display the following response: 37.416 397 -122.025055 701 1st Ave Sunnyvale CA 94 0 89- 10 19... control in Figure 19. 2 THE WEBBROWSER CONTROL Figure 19. 1 A context menu in a custom WebBrowser control–based web browser Figure 19. 2 Script Error dialog window displayed by the WebBrowser control DocumentText You can use this property to obtain a string representation of a currently loaded web page or to load a web page from a string For example, you can use the code shown in Listing 19. 1 to display... protocols like REST and/or AJAX-styled XML and JSON over HTTP THE BOTTOM LINE Figure 19. 5 Address visualization form showing the address on the map Master It Use the Headers property of the WebClient class to fine-tune HTTP requests Trick Google into believing that a request that you are sending from your Visual Basic application is coming from some mobile device Use a WebBrowser control to add web... receive the data asynchronously, you need to provide an event handling routine for Download*Completed events Take a look at the code in Listing 19. 5 for an example of using the DownloadStringAsync method in an address visualization form project and in Listing 19. 3 in the WebClient asynchronous download example for a simple illustration of an asynchronous operation of the WebClient class OpenRead and OpenReadAsync... the outcome of the asynchronous operation, presented in the Canceled property of the Download*CompletedEventArgs or Upload*CompletedEventArgs parameter 8 29 830 CHAPTER 19 ACCESSING THE WEB WebClient Asynchronous Download Example The code in Listing 19. 3 shows the Windows form with a simple example of an asynchronous download operation using the WebClient’s asynchronous programming model The form includes... cookie.Name, cookie.Value) Next End Using Putting It All Together: The Address Visualization Form In the following sections, I will show you how to find the map coordinates of a street address and display them on a map I decided to name the sample project ViewAddressOnAMap You can download the project from www.sybex.com/go/masteringvb2010 The business case for such functionality is more than common; many call... page or to load a web page from a string For example, you can use the code shown in Listing 19. 1 to display the page that will submit a search term to the Google search engine 8 19 820 CHAPTER 19 ACCESSING THE WEB Listing 19. 1: Loading a WebBrowser control with HTML content from a string literal WebBrowser1.DocumentText = "Search in Google:" & ""... anything using a web page’s DOM You can obtain and manipulate values on forms, invoke embedded scripts, manipulate page structure, and so on The code in Listing 19. 2 adds simple validation to the Google search form code displayed in Listing 19. 1 Listing 19. 2: Validating an HTML form through the WebBrowser Document property Private Sub webBrowser1_Navigating(ByVal sender As Object, ByVal e As WebBrowserNavigatingEventArgs) . displayed by the WebBrowser control in Figure 19. 2. THE WEBBROWSER CONTROL 8 19 Figure 19. 1 Acontextmenuina custom WebBrowser control–based web browser Figure 19. 2 Script Error dialog win- dow d isplayed. the autogenerated class. Master It Describe the basic components generated by the wizard when you create a typed DataSet with the visual tools of Visual Studio. Bind Windows forms to typed DataSets can use the code shown in Listing 19. 1 to display the page that will submit a search term to the Google search engine. 820 CHAPTER 19 ACCESSING THE WEB Listing 19. 1: Loading a WebBrowser control