1. Trang chủ
  2. » Công Nghệ Thông Tin

Mastering Microsoft Visual Basic 2010 phần 9 docx

105 390 0

Đ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

Thông tin cơ bản

Định dạng
Số trang 105
Dung lượng 0,94 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

In this chapter, you’ll learn how to do the following: ◆ Add browser functionality to your Windows Forms applications using the WebBrowsercontrol ◆ Access information and services on the

Trang 1

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: theSave Data Locally and Load Local Data buttons The first one saves the DataSet to a localfile via the WriteXml method of the DataSet, and the second button loads the DataSet via theReadXml 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 additionalargument that stores not only the data but the changes as well Here’s the code behind the twobuttons:

Private Sub Button1_Click(…) Handles Button1.ClickDS.WriteXml("tmpData.#@#", XmlWriteMode.DiffGram)End Sub

Private Sub Button2_Click(…) Handles Button2.ClickProductsBindingSource.SuspendBinding()

DS.ReadXml("tmpData.#@#", XmlReadMode.DiffGram)ProductsBindingSource.ResumeBinding()

End Sub

Let’s explore now how data binding can be used in combination with Language IntegratedQuery (LINQ) query syntax

Data Binding with LINQ

You are surely convinced by now that LINQ is a fundamental part of NET query ture You have explored LINQ in detail in Chapter 14, ‘‘An Introduction to LINQ,’’ where Ialso mentioned the LINQ to DataSet technology

infrastruc-The great thing about LINQ is that once you learn how to write queries, you can apply thesame syntax to any data source that supports LINQ DataSets and typed DataSets also supportLINQ, and you can apply the same syntax you saw used to query objects in LINQ to Objectsand 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 programmerdeveloping data-centric applications And you have already witnessed the power of LINQ Thetwo 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 andcustomizable view of data and provides a number of data manipulation methods UsingDataView, 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 theAsDataView extension method Thanks to this extension method, you can set the query as aDataSourceof 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 yourdata bound applications Let’s illustrate this by adding some querying features to our Productsapplication, as shown earlier in the chapter in Figure 18.21

Trang 2

Using LINQ to Filter Products Data

In cases where data operators have to manage a large number of entries, listing all of these onthe form with navigation capability can prove not to be very practical Users will be forced tospend a lot of time while navigating between records In such cases, providing some filteringcapability 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 productunits 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 beapplied or not, it is best to count on some special value If the Units In Stock Less and Units OnOrder 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 populatesthe Categories Combobox and is placed inside the Form_Load event handler:

cboCategoryFilter.DisplayMember = "CategoryName"

cboCategoryFilter.ValueMember = "CategoryID"

cboCategoryFilter.Items.Insert(0, "All")

Trang 3

For Each category In NorthwindDataSet.CategoriescboCategoryFilter.Items.Insert(category.CategoryID, category)Next

Now you are ready to write the LINQ query that uses these criteria Because these criteriacan be used in any combination, writing the query might prove to be a bit trickier than youinitially thought

The solution is to use the special value of criteria inside the query itself For example, theexpression cboCategoryFilter.Text = "All" is true if the user does not want to applythe categories criteria As you can see, I have named the categories ComboBox cboCategory-Filter If you combine this statement with product.CategoryID = categoryId using theOrElse operator, then you can use the cboCategoryFilter.Text = "All" expression to turnoff the categories criteria when the user selects All in the Categories combo The completestatement 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.ClickDim categoryId As Integer

If Not cboCategoryFilter.Text = "All" ThencategoryId = CType(cboCategoryFilter.SelectedItem,

NorthwindDataSet.CategoriesRow).CategoryIDEnd If

queryResult = From product In NorthwindDataSet.Products

Where ((cboCategoryFilter.Text = "All" OrElseproduct.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 productProductsBindingSource.DataSource = queryResult.AsDataView()End Sub

Trang 4

The Bottom Line

Design and use typed DataSets. Typed DataSets are created with visual tools at design timeand allow you to write type-safe code A typed DataSet is a class created by the wizard on thefly, 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 allthe 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 thecolumn’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 theAsDataViewextension 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 queriescan be embedded inside the Visual Basic code and can be used to query the Entity Data Modelprovided 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

Trang 6

Part 6

Developing for the Web

Chapter 19: Accessing the Web

Chapter 20: Building Web Applications

Chapter 21: Building and Using Web Services

Trang 8

Accessing the Web

The Internet has changed our everyday lives in many ways, and it has changed the ming landscape completely It is hardly imaginable today to develop any application that is not

program-at least in some way relprogram-ated to the Internet HTTP, the underlying protocol of the Internet, is astandard 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 awebsite using a web browser Sometimes, information is useful as is, and you will see how it iseasy to incorporate such information into your applications using the WebBrowser control

In other situations, you need to access and extract information from unstructured HTMLpages 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 serversever discover that they are not communicating with a web browser but with your Visual Basicprogram 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 HttpWebResponseclasses These classes can be used to access applications that provide structured informationmeant 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 likeSOAP (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 webapplications — applications made to serve the clients over the Internet In this chapter, we’lltake a look at how you can be on the other side, the consuming side of the wire You will learnhow 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 WebBrowsercontrol

◆ Access information and services on the Web from within your code using WebClient orHttpWebRequest and HttpWebResponse classes

Trang 9

The WebBrowser Control

The WebBrowser control is the simplest option for adding some browser functionality to a dows Forms application It is capable of presenting HTML content with all the usual browserfeatures: hyperlinks, navigation, multimedia content, Favorites, and the like

Win-There can be a number of reasons you would want to add web browser functionality toyour 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 toname 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 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 webbrowser functionality with the WebBrowser control, I am sure you will think of many otheruseful ways to enrich your applications with Internet content

con-With a little bit of work, the WebBrowser control can be used to make a full-fledged customweb browser This can be useful in situations in which your client needs to restrict the access tointranet-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 touse the WebBrowser control in a plausible application scenario, let’s inspect some of its mostimportant properties

WebBrowser Control under the Hood

The WebBrowser control is a managed NET wrapper over the Internet Explorer ActiveXdynamic link library This is the same library that the Internet Explorer executable usesinternally and is available on any Windows machine

As a consequence, you will not be able to exhort the usual level of control over you cation Since Internet Explorer is essentially part of the Windows operating system, it will beupdated through the Windows Automatic Updates service, so you cannot control the version

appli-of Internet Explorer that is being used to render the HTML in your application While mostInternet Explorer versions still in circulation work in a similar manner, there are some knowndifferences in how they render the HTML

The browser operations a user performs on a WebBrowser control will affect the InternetExplorer 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 aWebBrowser control will create a new Windows shortcut And so on

One important aspect to consider when using a WebBrowser control is security In thisrespect, the control behaves in the same manner as Internet Explorer and will run scripts andembedded 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 WebBrowsercontrol 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 atits properties

WebBrowser Control Properties

Like any other visible Windows Forms control, the WebBrowser control has a number ofcommon layout-related properties, including Size, MaximumSize, MinimumSize, Location,Margin, and Anchor They all work as you would expect from your experience with other

Trang 10

Windows Forms controls, so I will not go into more details on any of these While belonging tothis 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 tainer and how it will behave as the container is resized Anchoring and docking controls arediscussed in detail in Chapter 6, ‘‘Working with Forms.’’

con-When a WebBrowser control is added to an empty form or a container control, the defaultvalue 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 youchange 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 resent a unique identifier or an address (familiar URL) on the Internet You will typically useinstances 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 caninstantiate the Uri class by passing a string representation of the URL to its constructor Here isthe correct way to set the WebBrowser URL property in your code:

rep-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 Browser control when AllowNavigation is set to False will have no effect The only page thecontrol will display is the one that was loaded initially

Web-Bear in mind that AllowNavigation does not alter the visual representation of the page orthe cursor Hyperlinks are still rendered distinctly as hyperlinks (underlined blue text), and themouse 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

Trang 11

Internet Explorer will display the scroll bars when the loaded page is not fully visible By ting ScrollBarsEnabled to False, you can prevent scroll bars from appearing even if the pageloaded into the WebBrowser control is not fully visible

set-AllowBrowserDrop

The AllowBrowserDrop property controls the WebBrowser control’s drag-and-drop behavior.When it’s set to True, you can open the HTML file in Internet Explorer by dragging the filefrom Windows Explorer and dropping it on the browser The WebBrowser control behaves

in the same manner by default To disable drag-and-drop behavior in the WebBrowsercontrol, you can set AllowBrowserDrop to False You should be aware, however, that thisproperty is superseded by the AllowNavigation property; if AllowNavigation is set toFalse and AllowBrowserDrop is set to True, the WebBrowser control will not react to adrag-and-drop This is to be expected because dropping the file on a WebBrowser control isjust another way of telling the WebBrowser control to navigate to a certain address — in thiscase a local HTML file

WebBrowserShortcutsEnabled

In Internet Explorer, you can use a number of key combinations as keyboard shortcuts

or accelerators For example, Alt+ the left arrow key combination is a shortcut for ing the Back button in Internet Explorer and Alt+ the right arrow key is a shortcut forclicking Forward You can disable accelerators in the WebBrowser control by setting theWebBrowserShortcutsEnabled property to False This property is enabled by default

click-IsWebBrowserContextMenuEnabled

IsWebBrowserContextMenuEnabled controls the display of a context-sensitive, shortcut menuwhen a user right-clicks the control The shortcut menu contains some standard browsershortcuts, but it can also contain some shortcuts contributed by various Internet Exploreradd-ons and accelerators You can see a context menu displayed over a WebBrowser control in

a custom WebBrowser control–based implementation of a web browser in Figure 19.1

When Internet Explorer encounters an error in JavaScript code (or some other script code),

it will by default display a dialog window with detailed error information and prompt theuser to decide whether to continue to run the script code In a WebBrowser control, you cancontrol this behavior through the ScriptErrorsSuppressed property Set it to False and theWebBrowser control will bear any error in the script code silently

Script error messages are rarely of any help to the end user, so it is best to set this property

to False in the final version of your application Even if errors in JavaScript code are present,the pages often still display and provide some limited functionality You can take a look at aScript Error dialog window displayed by the WebBrowser control in Figure 19.2

Trang 12

Script Error dialog

win-dow 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 todisplay the page that will submit a search term to the Google search engine

Trang 13

Listing 19.1: Loading a WebBrowser control with HTML content from a string literal

WebBrowser1.DocumentText =

"<html><body>Search in Google:<br/>" &

"<form method=’get’ action=’http://www.google.com/search’>" &

"<input type=’text’ name=’as_q’/><br/>" &

"<input type=’submit’ value=’Search’/>" &

"</form></body></html>"

Just place a WebBrowser control named WebBrowser1 onto a form and write the code inListing 19.1 into the Form Load event to see the snippet in action

DocumentStream

The DocumentStream property is similar to the DocumentText property Instead of a string,

it uses a System.IO.Stream instance as a property value Using the stream interface, youcan easily load content from a file (and from numerous other sources) into a WebBrowsercontrol

Document

The Document property is the pivotal property for manipulating a currently loaded HTML pagefrom within your code The method returns a System.Windows.Forms.HtmlDocument instancerepresenting the current page’s Document Object Model (DOM) document — a structured rep-resentation of a web page If you have ever manipulated an HTML page in JavaScript, you willfind this object quite familiar

You can accomplish pretty much anything using a web page’s DOM You can obtain andmanipulate 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 inListing 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) HandlesWebBrowser1.Navigating

Dim document = WebBrowser1.Document

If document IsNot Nothing Anddocument.All("as_q") IsNot Nothing AndString.IsNullOrEmpty( _

document.All("as_q").GetAttribute("value")) Thene.Cancel = True

MsgBox("Please enter a search term.")End If

End Sub

Trang 14

The validation implemented in Listing 19.2 is rather simple It cancels navigation and warnsthe user that the search string is empty Being able to access and manipulate web page struc-ture is not limited to such simple operations Indeed, this feature opens a wealth of implemen-tation possibilities.

WebBrowser Control Methods

The WebBrowser control provides a number of methods that make it possible to emulate dard browser behavior Let’s start with some navigation-related methods

stan-Navigate

Essentially, calling the Navigate method has the same effect as writing the URL address in

the Internet Explorer address bar and pressing Enter Similar to using the URL property, callingthe Navigate method results in the browser displaying the specified URL This method will beignored if the WebBrowser AllowNavigation property is set to False The method has a num-ber of overloaded variants, but the most typical variants accept a URL parameter in the form ofvalid URL string:

WebBrowser1.Navigate("http://www.google.com")

Go Methods

The WebBrowser control has a number of methods whose names start with the prefix Go Youcan use them to invoke typical browser navigation behavior Table 19.1 lists these methods andthe results of their invocation

Stop

You can use this method to cancel the current navigation Sometimes, a page can take longerthan expected to load, or it can even hang In those situations, you need to be able to cancel thenavigation The Stop method provides this capability

Refresh

You can use the Refresh method to reload the current page to the WebBrowser control Thismethod can be useful when displaying frequently changing information and can be easily auto-mated so it is invoked in certain time intervals in combination with the Timer control

Table 19.1: WebBrowser Go navigation methods

GoForward Navigate to the next page in history

GoSearch Navigate to the default search page for the current user

Trang 15

Show Methods

The WebBrowser control supports a number of methods for displaying different dialog dows with some advanced browser functionality Table 19.2 lists these methods and explainstheir purpose

win-Print

This method prints the current web page using the default print settings and without ing the print dialog window

display-WebBrowser Control Events

A WebBrowser control operates in asynchronous mode Loading a page will not freeze yourapplication; the application will continue to run while the WebBrowser control is downloadingand rendering a page This is why events play an important role in the WebBrowser program-matic model Let’s take a look at a few important ones

Navigating

You have already seen the Navigating event at work in Listing 19.2 This event is raised

to signal the navigation You can use this event to cancel the navigation if necessary, bysetting the Cancel property of WebBrowserNavigatingEventArgs parameter to True You canobtain the URL that the navigation is targeting through the TargetFrameName property of theWebBrowserNavigatingEventArgs parameter If you wish to measure the time a certain webpage takes to load, you can use the Navigating event to signal the start of navigation and theDocumentCompleted event to signal the end of the page load process

DocumentCompleted

The DocumentCompleted event occurs when a web page is completely loaded inside the Browser control It means that the Document property is available and will return the completestructure of the loaded document

Web-Table 19.2: WebBrowser Show navigation methods

ShowPrintDialog Displays browser’s print dialog used to print the current web

pageShowPrintPreviewDialog Displays browser’s print preview dialogShowPageSetupDialog Displays page setup dialog window used to set printing

options like Paper Option, Margins, Header, and FooterShowSaveAsDialog Displays browser’s Save As dialog used to save the current

web page to a fileShowPropertiesDialog Displays current page’s Properties window

Trang 16

VB 2010 at Work: The Stock Quotes Project

A WebBrowser control opens the world of the Internet to your Windows Forms projects in asimple and direct manner Popular websites often offer a way to embed a part of their function-ality inside another website Such widgets can be easily integrated into your Windows Formsprojects

In the Stock Quotes project, you will use the WebBrowser control to display quotes for

selected stocks on a Windows form Yahoo! Finance offers free Yahoo! badges that display thelatest news, stock tickers, charts, and other types of information that are specifically designed

to be integrated into your website You can find out more about Yahoo! badges at the followingURL: http://finance.yahoo.com/badges/ If you plan to use this feature in a production

environment, please read the terms of service carefully While the Yahoo! website clearly statesthat the service is free, I am no expert on legal matters and there might be limitations and

conditions on how the service may be used

Obtaining the HTML Widget

You will need a Yahoo.com account to complete the following steps, and you will be prompted

to create one if you do not have one Start by navigating to http://finance.yahoo.com/badges/,click the Start Now button, and follow these steps to obtain the HTML code needed to embedthe stock ticker inside the web page:

1. Choose a module to embed I chose the most compact module, called Quotes

2. Customize the module

Option 1: Enter MSFT, GOOG, IBM, and ORCL Delete the default entry.

Option 2: Select the Medium (200 px) value for the width of the badge

Option 3: Select the first (black) color theme

Option 4: Check the check box signaling that you agree to the terms of service and pressthe Get Code button

3. Once the code is displayed, copy and save it in some temporary file You’ll need it soon

Creating the Stock Quotes Project

Create a new Windows Forms project and name it StockQuotes You will display the Yahoo!

badge inside a WebBrowser control To do so, perform the following steps:

1. Add a WebBrowser control to Form1 Leave the name of the control as is — WebBrowser1

2. Disable the scroll bars on the WebBrowser1 control by setting the ScrollBarsEnabled

Trang 17

5. Add a new quotes.html file to the project While I could embed the HTML code for thestock ticker badge inside my Visual Basic code, it will be easier to edit it inside a separateHTML file.

Now that you have created all the items you will need for the StockQuotes project, youneed to load the quotes.html file content into the WebBrowser control You can accomplishthis by setting the WebBrowser.Url property with a Uri instance representing the quotes.htmlfile location Since the quotes.html file is part of your project, you can obtain its locationthrough a My.Application object Here is the code for the Form_Load event, used to set theWebBrowser.Urlproperty:

Private Sub Form1_Load(ByVal sender As System.Object,ByVal e As System.EventArgs) Handles MyBase.LoadWebBrowser1.Url = New Uri(

My.Application.Info.DirectoryPath.ToString() &

"\quotes.html")End Sub

Just to make sure everything works as expected, add some text (for example, ‘‘Hello fromquotes.html!’’) to the quotes.html file and run the project When the form is displayed, theWebBrowser control should show the text contained in the quotes.html file

Displaying the Stock Quotes Badge inside the WebBrowser Control

As you are already guessing, instead of embedding the stock quotes badge inside HTML page

on some website, you will display the badge inside the local HTML file distributed with yourWindows Forms application You can accomplish this by making the quotes.html a properlystructured HTML file (You will learn more about HTML in the next chapter.) For now, youshould know that a typical HTML page has html, head, and body elements Add the followingHTML code to the quotes.html file:

Wid-Although the application is now working, I would like to show you how to tweak the visualappearance of the badge First, we’ll minimize the margins surrounding the badge, and thenwe’ll set the color of the HTML page so it blends better with the badge itself I guess the graycolor will do

Trang 18

To minimize the margins and change the background color, we will add some CSS code tothe quotes.html page (You will learn more about the CSS in the next chapter.) For now, justmodify the quotes.html file so it includes a style tag:

Figure 19.3

Windows form with

embedded Yahoo!

Finance badge

Trang 19

Fiddler — HTTP Debugging Proxy

While you are developing applications that communicate over the network, you often need totake a peek at the traffic going over the wire Fiddler is one tool that can help you do exactlythat, and it’s available as a free download from www.fiddler2.com

Fiddler installs itself between your web browser and web server It fools the browser intobelieving it is communicating directly with the web server, while the server is convinced it

is communicating with the browser In the meantime, you will be able to observe and evenmodify the communication between the two sides

Fiddler’s purpose is not malicious It can be of great help to web developers It providesnumerous statistics on request/response size, time, performance, and so forth and can helpyou monitor and debug the conversation

The Fiddler window consists of two main areas, as shown here

On the left side, you will find a listing of all the HTTP requests and responses On the rightside, you can inspect each request and response You can visualize HTTP headers and displaythe body as text, XML, or even as it would appear in the browser by way of a tab calledWebView Further, you can modify and reissue the request from Fiddler itself, automate thewhole process through the Fiddler scripting support, or even extend Fiddler with extensionsprogrammed in the NET Framework

Trang 20

Accessing the Web with the WebClient and

HttpWebRequest/Response Classes

The simplest way to publish services on the Internet is to make proper use of HTTP HTTP isthe underlying protocol for all kinds of web services, and web services come in different shapesand forms Some make more direct use of HTTP, while others use it with a lot of overhead

Lightweight web services typically use HTTP to transport data in XML or JSON format

JavaScript Object Notation (JSON) is a data format similar to XML but more bandwidth

effi-cient Lightweight web services can be by orders of magnitude more efficient than more tous SOAP web services (You will read more about web services and SOAP in Chapter 21.) Forlightweight web services, the WebClient class and the HttpWebRequest and HttpWebResponseclasses will help you program simple and efficient client applications

ubiqui-A lot of information and services available on the Internet today are not properly structuredfor machine consumption While humans can make use of it, it is difficult to consume such

services programmatically In such situations, the only way to access these services matically is to behave in the same way as an Internet browser application The WebClient classand the HttpWebRequest and HttpWebResponse classes provide an API that can accomplish

program-exactly that Accessing information contained inside standard HTML pages is generally known

as HTML screen scraping

The WebClient Class

WebClient is a lightweight, simple alternative for accessing the Web It represents a higher-levelwrapper over the WebRequest and WebResponse classes You will find that it can handle most

of the cases that the HttpWebRequest and HttpWebResponse combination can

WebClient Class Properties

The WebClient class gives you a lot of control over the HTTP communication You can accessrequest and response headers, configure a proxy, set your credentials, and more

QueryString

You can always set query parameters manually by concatenating strings and adding the query

as the final part of a URL A more structured way to accomplish this uses name-value pairs andthe QueryString property The following code snippet illustrates how a q parameter can be

added to a query string The q parameter is often used in search engines to convey the searchcriteria

Dim webClient As New WebClient

Dim queryParameters As New System.Collections.Specialized.NameValueCollection()

queryParameters.Add("q", "SearchCriteria")

webClient.QueryString = queryParameters

As you can see, the QueryString property is a NameValueCollection type from the System.Collections.Specialized namespace

Trang 21

The Headers property represents a collection of request headers Response headers can beaccessed through the ResponseHeaders property Headers are an important part of HTTP.For example, a user-agent header is used to convey a lot of client-related information to theserver A user-agent header can include information on the browser version and type, the oper-ating system, even the version of the NET Framework that has been installed on the machinewhere the browser is running

The WebClient class does not set any headers by default Some servers might expect somestandard headers with the request, so if you are experiencing any problems accessing certainservers with the WebClient class, be sure to add some standard headers, like user-agent.Servers will often use user-agent header information to render the response that bestaccommodates the reported browser type For example, the server might exclude JavaScriptcode from pages if the browser does not support JavaScript, or it might render the page

so it fits smaller displays if it detects that the request is coming from a mobile device Alisting of standard request and response headers is available on Wikipedia at following URL:http://en.wikipedia.org/wiki/List of HTTP headers

ResponseHeaders

ResponseHeaders provides access to headers included in the response by server These ers can include a lot of information regarding the response, like mime type, encoding, contentlength, and so forth The ETag and Cache-Control headers can affect the caching mechanism.Responding with a value of ‘‘no-cache’’ in the Cache-Control header indicates to the browserand to any other HTTP intermediary that the content should not be cached

head-Another important response header is Set-Cookie Although, if you need to manipulate

or receive cookies, you are better off using the HttpWebRequest and HttpWebResponse classesbecause they have better support for this feature

WebClient Class Methods

The WebClient class provides a number of methods for sending a request for a resource under

a given URI and receiving the requested data Most of these methods come in two flavors:

◆ Synchronous

◆ AsynchronousAsynchronous methods permit the background execution of request-response operations.Since the calling (for example, UI) thread is not blocked, the main line of execution can proceedwithout waiting for the download to finish This feature can be used for implementing appli-cations with a more responsive user interface, permitting the user to continue working withthe application in the same time that communication is performed or to cancel the request inprogress if they wish to do so

Download Methods

The WebClient class has a number of methods with names that start with Download Thesemethods essentially perform the same operation — download a resource from a specified URI.The main difference is in the type of the method’s return value Table 19.3 lists the methodsand return types

Trang 22

Table 19.3: Download methods return types

dif-formed asynchronously To 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 anexample of using the DownloadStringAsync method in an address visualization form projectand 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 Methods

These methods perform similar functions to the Download methods Each returns a readable

stream from a resource specified as the method parameter

Upload and Upload*Async Methods

These methods have their counterparts in the Download group of methods Instead of

down-loading the data, these methods are used to upload it

CancelAsync Method

The CancelAsync method aborts the current asynchronous download or upload operation

It bears noting that the corresponding Download*Completed and Upload*Completed events

are still raised by the class It is possible for an operation to complete successfully even after

CancelAsynchas been called — after all, you can have no control over how the remote call wasfinalized on the other side of the wire To check the outcome of asynchronous operation, checkthe Canceled property of the Download*CompletedEventArgs or Upload*CompletedEventArgsevent handler parameter

WebClient Class Event

A majority of WebClient class events has to do with asynchronous modus-operandi of the

down-load and updown-load operations

Download*Completed and Upload*Completed events

These events are used to signal the completion of the asynchronous operation Results of

the download operation can be accessed through an event handler’s property as well as

through the outcome of the asynchronous operation, presented in the Canceled property of theDownload*CompletedEventArgsor Upload*CompletedEventArgs parameter

Trang 23

WebClient Asynchronous Download Example

The code in Listing 19.3 shows the Windows form with a simple example of an asynchronousdownload operation using the WebClient’s asynchronous programming model The formincludes two buttons: bttnDownload, used to initiate the download operation, and bttnCancel,which can be used to cancel the download operation in progress

Listing 19.3: Asynchronous download with WebClient

Imports System.ComponentModelPublic Class Form1

Dim webClient As New WebClient()Private Sub Form1_Load(ByVal sender As System.Object,

ByVal e As System.EventArgs) Handles MyBase.LoadAddHandler webClient.DownloadStringCompleted,AddressOf webClient_DownloadStringCompletedEnd Sub

Private Sub webClient_DownloadStringCompleted(ByVal sender As Object,

ByVal e As DownloadStringCompletedEventArgs)Dim asyncCompletedParam As AsyncCompletedEventArgs =TryCast(e, AsyncCompletedEventArgs)

If Not asyncCompletedParam.Cancelled = True ThenConsole.WriteLine(CStr(e.Result))

ElseConsole.WriteLine("Asynchronous download canceled by user!")End If

MsgBox("Download operation completed See the Output window.")End Sub

Private Sub bttnDownload_Click(ByVal sender As System.Object,

ByVal e As System.EventArgs) Handles bttnDownload.ClickwebClient.DownloadStringAsync(New Uri("http://www.google.com"))End Sub

Private Sub bttnCancel_Click(ByVal sender As System.Object,

ByVal e As System.EventArgs) Handles bttnCancel.ClickwebClient.CancelAsync()

End SubEnd Class

Trang 24

The DownloadStringCompleted event handler routine is assigned to a WebClient in a formload routine The event handler first checks the outcome of the download operation through theAsyncCompletedEventArgs parameter’s Cancel property and, if the operation was successful,prints the download result from the www.google.com URL to the console output.

Finally, the bttnCancel event handling routine is used to call the WebClient’s CancelAsyncmethod If the asynchronous download is in progress, it is canceled; otherwise, calling the

CancelAsync has no effect

HttpWebRequest and HttpWebResponse Classes

These classes from the System.Net namespace are used internally by the WebClient for load and upload operations over HTTP and HTTPS While you should prefer the WebClient

down-class because of its simplicity, you can always make use of the HttpWebRequest and

Http-WebResponse classes where more granular control over the communication is necessary TheHttpWebRequest and HttpWebResponse classes provide an explicit manner for handling the

HTTP cookies

Managing Cookies with HttpWebRequest and HttpWebResponse

To manage cookies with HttpWebRequest and HttpWebResponse, you first need to create theinstance of the CookieContainer class and attach it to HttpWebRequest Then you can access

the cookies set by the server through the HttpWebRequest Cookies property The following

code illustrates how you can list all of the cookies set by the Hotmail server to the console

output:

Dim request As HttpWebRequest = CType(WebRequest.Create(

"http://www.hotmail.com"), HttpWebRequest)request.CookieContainer = New CookieContainer()

Using response As HttpWebResponse =

CType(request.GetResponse(), HttpWebResponse)

Console.WriteLine("Server set {0} cookies", response.Cookies.Count)

Dim cookie As Cookie

For Each cookie In response.Cookies

Console.WriteLine("Cookie: {0} = {1}", 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 addressand display them on a map I decided to name the sample project ViewAddressOnAMap Youcan download the project from www.sybex.com/go/masteringvb2010

The business case for such functionality is more than common; many call centers have to

record clients’ addresses This can be an error-prone process, so being able to see the address

on the map while talking to a client can be a real plus for a call center attendant Also, someaddresses are difficult to find without additional information (‘‘The street sign blew down inlast night’s storm, so look for the pink house with purple trim and then turn right at the nextstreet.’’) Field employees can really benefit from the additional information that goes along withthe address Again, a call center attendant can easily enter these indications while talking to a

Trang 25

client and looking at the map Fortunately, there are services on the Internet today that makesuch an application possible.

Composing Web Services

You will learn more about web services and especially SOAP web services in Chapter 21 In abroader sense, a web service is any service that can be consumed by a program (as opposed to

a human) over the Internet So, to implement the address visualization form, we will make use

of two web services:

◆ Address coordinates search (geocoding) service

◆ Mapping serviceLet’s look at the services I chose for the ViewAddressOnAMap sample project in moredetail

Yahoo! Geocoding API

A geocoding service returns the exact latitude and longitude for a street address These dinates can then be used as parameters for a mapping service, which will return the map for agiven coordinate

coor-Yahoo! provides a geocoding API as a part of its coor-Yahoo! Maps web services You can findmore information about the Geocoding API at http://developer.yahoo.com/maps/rest/V1/geocode.html

To run the ViewAddressOnAMap sample project, you should follow the Get An App IDlink found on the Geocoding API page (at the URL in the preceding paragraph) and replacethe YahooAppId in the sample code with the Yahoo! ID you obtained this way

The Yahoo! Geocoding API is a RESTful web service REST stands for Representational State

Transfer and is actually the simplest way to use HTTP as an application protocol and not just

as a transport protocol like SOAP This means that to obtain the coordinates, you can submitaddress parameters as a part of a URL query string It also means that you can make use ofthis service with a simple browser because it uses HTTP as a native, application-level protocol

To test the service, you can write the following URL into your browser:

At that same URL, you can find another example of the Yahoo! Geocoding URL, and itmight be easier to copy and paste that link to use for testing

The Yahoo! Geocoding Web Service query URL is pretty much self-explanatory You passthe address information as parameters inside the URL query You can pass street, city, stateand zip together with the Yahoo! App ID as parameters You should encode the spaces insidethe parameter values with a plus sign, so 701 First Ave becomes 701+First+Ave

Trang 26

Now, you can take a look at the result The browser should display the following response:

Google Maps Service

Now let’s use Google Maps Service to display the address coordinates on a map Use this vice in a manner similar to the way the Yahoo! badges service was used in the Stock Quotes

ser-project earlier in this chapter Display the service response in a WebBrowser control

The Google Maps JavaScript API is free, and (as of this writing) there is no limit to the

number of page requests you can generate per day Still, I suggest you register for the GoogleMaps API and read the related conditions carefully You can read more about Google Maps

JavaScript API at http://code.google.com/apis/maps/documentation/v3/introduction.html.The Google Maps JavaScript API provides simple scripts that you can embed inside your

HTML page to add Google Maps functionality to your website To use this functionality, youneed the HTML code shown on code.google.com in the section ‘‘The ‘Hello, World’ of GoogleMaps v3’’ of the Maps V3 tutorial This code can be used in ViewAddressOnAMap project withminimal modifications Take a look at the original Hello World code:

<html>

<head>

<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />

<script type="text/javascript" src="http://maps.google.com/maps/api/js?

Trang 27

mapTypeId: google.maps.MapTypeId.ROADMAP};

var map = new google.maps.Map(

as in this case

Coding Address Visualization Form

Now that you have all necessary information for the project, you can create a new WindowsForms project and name it ViewAddresOnAMap The project will have a single form, and theclient’s address will be both saved and shown on the map Since we are interested in onlythe address visualization functionality for this exercise, you do not have to implement the code

to actually save or maintain the address data

Assembling the Address Visualization Form

Let’s start by adding all the necessary controls to the form You will need a number of textboxes where users can enter the address information, buttons to save the address and to showthe address on the map, and finally, one WebBrowser control to display the map The formshould look like one shown in Figure 19.4

The large white area on the right side of the form is the WebBrowser control Text boxcontrols in the Address GroupBox have the following names: txtStreet, txtSecondLine, txtCity,txtState, txtZip, and txtObservations The buttons are names bttnSave and bttnShow Now youare ready to add some behavior to the form

For the txtState control, you should limit the length to 2 A text box with verification of thevalue entered is a much better option than a states ComboBox control For txtObservations, youshould set the Multiline property to True

Finally, you can add a label named lblError to the bottom of the form Here you can play the errors related to address visualization functionality This functionality should not inter-fere with the main form functionality consisting of address data entry

dis-Constructing the Geocoding Service URL and Query Parameters

To obtain the address coordinates, you can use the WebClient class to query the Yahoo! ing service To do so, you should first construct the URL You can declare the Yahoo! service

Trang 28

geocod-Figure 19.4

Address visualization

form

URL as a constant and create the query parameters Listing 19.4 shows how to construct the

NameValueCollectionwith query parameters for the Yahoo! Geocoding Web Service

Listing 19.4: Form code with constructed Yahoo! geocoding service URL and query parameters

Public Class Form1

Private Shared YahooAppId As String = "BPdn3S7V34GMfMZ5ukBuHAMYuj" &

"APFGN10xYiHINOslptpcZsrgFbzsTHKr8HgBk7EA81QRe_"

Private Shared YahooGeocodeServiceUrl = "http://local.yahooapis.com" &

"/MapsService/V1/geocode"

Dim yahooGeoCodeParameters As NameValueCollection

Private Sub GenerateYahooGeoCodeParameters(ByVal street As String,

ByVal city As String, ByVal state As String,

ByVal zip As String)

yahooGeoCodeParameters = New NameValueCollection

Trang 29

Since generated URL query parameters should not contain spaces, space characters arereplaced with a plus sign using the Replace method of the String class Now, you are ready toinvoke the Yahoo! geocoding service in an asynchronous manner.

Invoking the Yahoo! Geocoding Web Service

Since address visualization is not a principal feature on the form, you should not make userswait for the map to appear before they can save the address It is quite possible that the userknows the address well; in that case, waiting for the visualization would be more of a hin-drance than a help

If you use the asynchronous capacities of the WebClient class, you will not block the mainthread of execution and users will be able to proceed with their work while the map is loaded

in the background Listing 19.5 shows the bttnRefresh button event handling code invokingthe FindLocation routine that uses the WebClient class to code the Yahoo! Geocoding WebService asynchronously

Listing 19.5: Form with constructed Yahoo! Geocoding Web Service URL and query parameters

Imports System.NetImports System.IOImports System.Collections.SpecializedPublic Class Form1

Private Shared YahooAppId As String = "BPdn3S7V34GMfMZ5ukBuHAMYuj" &

End SubPrivate Sub GenerateYahooGeoCodeParameters(ByVal street As String,

ByVal city As String, ByVal state As String,ByVal zip As String)

yahooGeoCodeParameters = New NameValueCollectionyahooGeoCodeParameters.Add("appid", YahooAppId)

Trang 30

yahooGeoCodeParameters.Add("street", street.Replace(" "c,

"+"c))yahooGeoCodeParameters.Add("city", city.Replace(" "c, "+"c))

yahooGeoCodeParameters.Add("zip", zip)

yahooGeoCodeParameters.Add("state", state)

End Sub

Private Sub FindLocation()

Dim client As New WebClient()

If you look at the code carefully, you will note that bttnShow_Click handles both the

bttnShow.Click and the txtZip.Leave events This way, the address will be shown on the

map automatically once the user has filled all the address fields Since the service invocation

code is asynchronous, it will not prevent the user from continuing to operate on the form

Now you need to take care of the DownloadStringAsync event handler

Processing the Yahoo! Geocoding Service Response

Before you can process the geocoding service response, you will need to create a structure thatcan hold the geocoding information In this case, a simple structure will do; name the structure

Coordinatesand set up two String properties: Latitude and Longitude Add the new class

named Coordinates to the project Listing 19.6 shows the code for the Coordinates structure

Listing 19.6: The Coordinates structure

Public Structure Coordinates

Property Latitude As String

Property Longitude As String

End Structure

Now you can code the DownloadStringCompleted event handler You should bear in mindthat the Yahoo! geocoding service responds in XML format The easiest way to process it is touse LINQ to XML (I explained how you can work with XML in Visual Basic NET in detail inChapter 13, ‘‘XML in Modern Programming,’’ and Chapter 14, ‘‘An Introduction to LINQ.’’)

To process the Yahoo! geocoding service response with LINQ to XML, you should import theXML namespace for the response using the Imports directive at the top of the form code in thefollowing manner:

Imports <xmlns="urn:yahoo:maps">

Trang 31

When implementing the functionality, be sure to check for errors and handle multiple resultresponses In the event of an error or multiple result responses, the best bet is to display thefirst location encountered while informing the user that the coordinates displayed on a map arenot very precise because the service responded with multiple locations Listing 19.7 shows thecode that handles the Yahoo! geocoding service response.

Listing 19.7: DownloadStringCompleted event handling code

Sub webClient_DownloadStringCompleted(ByVal sender As Object,ByVal e As DownloadStringCompletedEventArgs)

If e.Error IsNot Nothing ThenlblError.Text = "Address could not be located on a map"

ReturnEnd IfyahooResponse = XDocument.Parse(CStr(e.Result))ValidateResponseAndProceede()

End SubPrivate Sub ValidateResponseAndProceede()

If (yahooResponse <Result>.Count = 0) ThenlblError.Text = "Address could not be located on a map"

ReturnEnd If

If (yahooResponse <Result>.Count > 1) ThenlblError.Text = "Multiple locations found - showing first." &

" Correct the address and press Refresh"

End IfGenerateLocation()ShowLocationOnMap()End Sub

Private Sub GenerateLocation()addressLocation.Latitude = yahooResponse <Result>.First.<Latitude>.ValueaddressLocation.Longitude = yahooResponse <Result>.First.<Longitude>.ValueEnd Sub

As you can see, the code handles errors that occur in communication or while querying theYahoo! geocoding service and displays a message when the results are not very precise and theservice responds with multiple results

Displaying Coordinates on the Map

To show the location on the map, you need to load the WebBrowser control with the simpleHTML page that contains the Google Maps Service code Since this code contains coordinates,

it cannot be loaded from the static HTML file You can, however, use the static HTML file as

Trang 32

a template, load the file, and then replace latitude and longitude tokens with information

obtained from the Yahoo! geocoding service before loading it into the WebBrowser control

Add the new gmapsTemplate.html file to the ViewAddressOnAMap project Make sure

the ‘‘Copy to Output Directory file’’ property is set to ‘‘Copy if newer’’ With this, Visual

Studio will make the copy of the file inside the bin/Debug folder and you will be able to

access the file while debugging the solution The code for gmapsTemplate.html is shown in

replacement code can be implemented in a GenerateMapsHtml routine:

Private Sub GenerateMapsHtml()

googleMapsHtml = googleMapsHtmlTemplate

Replace("replace_me_latitude", addressLocation.Latitude)

Replace("replace_me_longitude", addressLocation.Longitude)

End Sub

Trang 33

With this, you have finished implementing the address visualization functionality You cantake a look at the complete code of the form in Listing 19.9.

Listing 19.9: Address visualization form code

Imports System.NetImports System.IOImports System.LinqImports System.Xml.LinqImports <xmlns="urn:yahoo:maps">

Imports System.Collections.SpecializedPublic Class Form1

Private Shared YahooAppId As String = "BPdn3S7V34GMfMZ5ukBuHAMYuj" &

"\gmapsTemplate.html"

Private googleMapsHtml As StringPrivate addressLocation As CoordinatesPrivate yahooResponse As XDocumentDim yahooGeoCodeParameters As NameValueCollectionPublic Sub New()

InitializeComponent()googleMapsHtmlTemplate = My.Computer.FileSystem.ReadAllText(

googleMapsHtmlTemplatePath)Console.WriteLine(googleMapsHtmlTemplate)End Sub

Private Sub bttnShow_Click(ByVal sender As System.Object,

ByVal e As System.EventArgs) Handles

Trang 34

bttnShow.Click, txtZip.Leave

lblError.Text = ""

GenerateYahooGeoCodeParameters(txtStreet.Text.Trim(), txtCity.Text.Trim(),

txtState.Text.Trim(), txtZip.Text.Trim())FindLocation()

End Sub

Private Sub GenerateYahooGeoCodeParameters(ByVal street As String,

ByVal city As String, ByVal state As String,

ByVal zip As String)

yahooGeoCodeParameters = New NameValueCollection

Private Sub FindLocation()

Dim client As New WebClient()

If e.Error IsNot Nothing Then

lblError.Text = "Address could not be located on a map"

lblError.Text = "Multiple locations found - showing first." &

" Correct the address and press Refresh"

End If

Trang 35

GenerateLocation()ShowLocationOnMap()End Sub

Private Sub GenerateLocation()addressLocation.Latitude = yahooResponse <Result>.First.<Latitude>.ValueaddressLocation.Longitude =

yahooResponse <Result>.First.<Longitude>.ValueEnd Sub

Private Sub ShowLocationOnMap()GenerateMapsHtml()

mapBrowser.DocumentText = googleMapsHtmlEnd Sub

Private Sub GenerateMapsHtml()googleMapsHtml = googleMapsHtmlTemplate

Replace("replace_me_latitude", addressLocation.Latitude)

Replace("replace_me_longitude", addressLocation.Longitude)End Sub

Private Sub bttnSave_Click(ByVal sender As System.Object,

ByVal e As System.EventArgs) Handles bttnSave.ClickMsgBox("Unimplemented on purpose " &

"See ‘Coding Address Visualization Form’" &

"section in Chapter 20 Try the ‘Show’ button.")End Sub

End Class

When you run the application, enter the address data on the form, and click the Show ton, the form should look like the one shown on Figure 19.5

but-The Bottom Line

Access a website on the Internet using the WebClient class. The WebClient class provides

an easy and simple way to access resources on the Web programmatically from Visual Basiccode The WebClient class implements many features of HTTP, making it easy to access thesites on the Web in the same way the browser application does The web server will not dis-tinguish a request coming from a WebClient site from one coming from a user-operated webbrowser

The WebClient class can be very useful in HTML screen scraping scenarios, where the data to

be extracted from HTML is meant to be read by a human, or in lightweight web service cols like REST and/or AJAX-styled XML and JSON over HTTP

Trang 36

proto-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 cation is coming from some mobile device

Use a WebBrowser control to add web browser functionality to your Windows Forms cation. The WebBrowser control provides all the basic functionality of a browser in a form

appli-of Windows Forms control Visually, it consists only appli-of a main browser window To provideadditional functionality, like an address bar and Back, Forward, Refresh, and other buttons,

you will have to add the appropriate controls and program them yourself The WebBrowsercontrol uses the same browser engine as Internet Explorer

A WebBrowser control’s behavior can be customized to a large degree You can decide to show

or not show the scroll bars, allow or disallow navigation, show or not show the context menu,and so forth Finally, since the control does not contain the address bar, you can also controlwhich sites a user can access

Master It Create a custom web browser that can navigate to a limited number of URLs

Trang 38

Building Web Applications

Developing web applications in Visual Studio 2010 is similar to developing traditional desktopapplications You drag and drop controls onto a form and build your business logic with yourlanguage of choice — in our case, Visual Basic 2010 However, as you will see, there are alsomany differences There are underlying technologies of which you, the developer, should have

a solid understanding, and there are additional control sets to work with and some tal differences in the way the standard controls behave Another important difference betweenweb and desktop applications is the way the application state is managed In desktop appli-cations, the application state is implicit and it is managed by the NET runtime environment

fundamen-In web applications, on the other hand, the situation is much more complex A web server canattend to numerous clients simultaneously, but thanks to ASP NET internal mechanisms, youprogram your application as if you have only one user to serve Another issue is the statelessnature of the underlying communication (HTTP) protocol There is nothing to link two HTTPrequests In ADO NET, the link is provided in the form of a connection object While all ofthe state-related issues are resolved by ASP NET technology, it is important to understand theunderlying mechanisms because of the numerous implications for application characteristics,like performance and security

In this chapter, you will learn how to do the following:

◆ Create a basic XHTML/HTML page

◆ Format a page with CSS

◆ Set up a master page for your website

◆ Use some of the ASP.NET intrinsic objects

Developing for the Web

In the early days of web development (not all that long ago!), a developer could earn bigmoney creating what were essentially online brochures by using a basic knowledge ofHypertext Markup Language (HTML) and some simple design skills

These days, we expect a great deal from websites and web applications Entertainment sitesare now fully equipped to engage the visitor with rich user interfaces incorporating a widerange of visual and aural experiences Members of the corporate world expect their virtualpresence to mirror their full range of business practices

Trang 39

In addition, web development, although still seen as a specialized area, is now part of thecorporate mainstream, and the developer is expected to be well versed across a range of tech-nologies and techniques.

The modern web application combines a wide range of sophisticated technologies graftedonto the HTTP/HTML backbone Cascading Style Sheets (CSS) are used to control the layoutand appearance of a website Data is managed with the use of Extensible Markup Language(XML) and back-end databases such as SQL Server, while rich user interfaces are developedusing XML, JavaScript, and other technologies such as Adobe Flash AJAX, a clever implemen-tation of existing technologies, combines XML, JavaScript, and asynchronous technologies toenable the developer to create online applications that exhibit traditional desktop behavior.XML web services, multimedia content, RSS feeds, and the use of microformats to assist dataaggregators have all become typical features of modern websites

In addition, developers can now expect a website to be accessed by more than just a desktopcomputer Mobile phones, PDAs, and other small form factor devices are all used to access theWeb in the twenty-first century Websites, to be truly ubiquitous, are increasingly expected to

be able to dynamically render their content into an appropriate format

Visual Studio 2010 provides a range of tools that enable the modern developer to meet thedemands of website creation from the comfort of a Visual Basic environment Database connec-tivity is simplified from the traditional complexity of hand-coding scripted server-side pages,and you don’t need to build multiple versions of an individual site to dynamically render tosuit a wide range of devices By compiling much of the code used to drive a site, you can avoidmany of the security issues that plagued scripted sites

Typically, a modern website or web application relies on code that is executed both at theclient (web browser) and server (web server) ends In addition, there may be a whole range ofother services provided by other servers on the hosting network, such as media or databasesand even services sourced from other websites Visual Studio 2010 provides the tools to tie allthis together

This chapter gives an overview of the core technologies that drive the modern web tion and demonstrates the basic tools available to the developer in Visual Studio 2010

applica-I will begin with some basic concepts applica-If you are already familiar with HTML, JavaScript,and server technologies, you may wish to skip ahead to material that is new to you, such asthe material in the section ‘‘Creating a Web Application.’’

Understanding HTML and XHTML

HTML is essentially a language to describe text formatting and enable linking of documents(web pages) delivered over the Web HTML has grown since its original inception but is stillfundamentally limited The area where it does excel is in its ability to act as a framework inwhich other technologies such as JavaScript can be embedded

Extensible HTML (XHTML) is the latest incarnation of HTML It was developed by theWorld Wide Web Consortium (W3C) to bring HTML syntax into line with other markuplanguages such as XML Most of the tags from HTML 4 (the most recent update to HTML)remained the same, but much stricter syntax rules apply The basic changes are as follows:

XHTML is case sensitive, and all tags are in lowercase.

◆ All tags must be closed You can no longer get away with using multiple <p> tags withoutcorresponding closing </p> tags This includes tags such as <img> that previously had no

Trang 40

corresponding closing tag Close these tags with a trailing backslash before the final anglebracket, as shown in this example:

<img src =’my_picture.jpg’ alt =’picture’ \>

◆ All tag attributes must be enclosed in quotation marks (either single or double)

◆ All pages must include an XHTML !DOCTYPE definition and an XML version declaration

JavaScript must also conform to case syntax — for example, onmouseover not

onMouseOver

The W3C encourages developers to use XHTML over HTML However, for practical

pur-poses, web browsers still support HTML, and you can get away with not updating older sitesand continuing to work with HTML’s lack of strict syntax See the sidebar ‘‘Upgrading from

HTML to XHTML’’ if you wish to upgrade older sites

Upgrading from HTML to XHTML

Converters exist for porting your HTML sites to XHTML There are also tools to assist in the

process manually The W3C provides an online validator at http://validator.w3.org

You can use the validator to initially ensure that your pages conform to the HTML 4

specifica-tion and that they all contain a !DOCTYPE definispecifica-tion such as the following:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"

"http://www.w3.org/TR/html4/strict.dtd">

After your pages are validated for HTML 4, you will need to add the XML declaration to the

top of each page:

<?xml version="1.0" encoding="iso-8859-1"?>

Then convert the !DOCTYPE definition to the XHTML version:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Finally, modify the <HTML> tag to read as follows:

<HTML xmlns="http://www.w3.org/1999/xhtml">

Now that you have made all the correct syntax changes, run the validator again and see how

your page performs

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