The examples show how the .NET base classes make it very easy to download and process data from the Internet. However, so far, you have displayed files only as plain text. Quite often, you will want to view an HTML file in an Internet Explorer-style interface in which the rendered HTML allows you to see what the Web document actually looks like. Unfortunately, there is no .NET version of Microsoft’s Internet Explorer, but that does not mean that you cannot easily accomplish this task. Before the release of the .NET Framework 2.0, you could make reference to a COM object that was an encapsulation of Internet Explorer and use the .NET- interop capabilities to have aspects of your application work as a browser.
Now, in the .NET Framework 2.0, as well as the .NET Framework 3.5, you can use the built-in Web Browser control available for your Windows Forms applications.
The Web Browser control encapsulates the COM object even further for you making tasks that were once more complicated even easier. In addition to the Web Browser control, another option is to use the programmatic ability to call up Internet Explorer instances from your code.
When not using the new Web Browser control, you can programmatically start an Internet Explorer process and navigate to a Webpage using the Process class in the System. Diagnostics namespace:
Process myProcess = new Process();
myProcess.Startlnfo.FileName = ‘iexplore.exe’;
myProcess.Startlnfo.Arguments = ‘http://www.csharpaid.com’;
However, the preceding code launches Internet Explorer as a separate window. Your application has no connection to the new window and therefore cannot control the browser.
Using the new WebBrowser control, however, allows you to display and control the browser as an integrated part of your application. The new WebBrowser control is quite sophisticated, featuring a large number of methods, properties, and events.
Allowing Simple Web Browsing from Your Applications
For the sake of simplicity, start by creating a Windows Form application that simply has a TextBox control and a Web Browser control. You will build the application so that the end user will simply enter a URL into the text box and press Enter, and the Web Browser control will do all the work of fetching the Web page and displaying the resulting document.
In Visual Studio 2008 Designer, your application should look as shown in Figure 41-3.
With this application, when the end user types a URL and presses Enter, this key press will register with the application. Then the Web Browser control will go off to retrieve the requested page, subsequently displaying in the control itself.
The code behind this application is illustrated here:
From this example, you can see that each key press that the end user makes in the text box is captured by the textBox_KeyPress event. If the character input is a carriage return (a press of the Enter key, which is (char) 13 ), then you take action with the Web Browser control. Using the Web Browser control’s Navigate method, you specify the URL (as a string) using the textBox1
. Text property. The end result is shown in Figure 41-4.
Launching Internet Explorer Instances
It might be that you are not interested in hosting a browser inside of your application, as shown in the previous section, but instead are only interested in allowing the user to find your Web site in a typical
browser (for example, by clicking a link inside of you~ application). For an example of this task, create a Windows Form application that has a LinkLabel control on it. For instance, you can have a form that
has a LinkLabel control on it that states Visit our company Web site.
Once you have this control in place, use the following code to launch your company’s Web site in an
independent browser as opposed to directly being in the form of your application:
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
WebBrowser wb = new WebBrowser();
In this example, when the LinkLabel control is clicked by the user, a new instance of the Web Browser class is created. Then, using the Web Browser class’s Navigate() method, the code specifies the location of the Web page as well as a Boolean value that specifies whether this endpoint should be opened within the Windows Form application (a false value) or from within an independent browser (using a true value). By default, this is set to false. With the preceding construct, when the end user clicks the link found in the Windows application, a browser instance will be instantiated, and the csharpWeb site at www.csharpaid.com will be immediately launched.
Giving YourApplication More IE-Type Features
In the previous example, in which you used the Web Browser control directly in the Windows Form application, you will notice that when you clicked on the links contained in the page, the text within the TextBox. control was not updated to show the URL of the exact location where you were in the browsing process. You can fix this by listening for events coming from the Web Browser control and adding handlers to the control.
Updating the form’s title with the title of the HTML page is easy. You just need to use the Navigated event and update the Text property of the form:
private void web Browser_Navigated(object sender, EventArgs e)
this.Text = webBrowserl.DocumentTitle.ToString();
In this case, when the Web Browser control moves onto another page, the Navigated event will fire, and this will cause the form’s title to change to the title of the page being viewed. In some instances when working with pages on the Web, even though you have typed in a specific address, you are going to be redirected to another page altogether. You are most likely going to want to reflect this in the textbox (address bar) of the form; to do this, you change the form’s text boxbased on the complete URL of the page being viewed. To accomplish this task, you can use the Web Browser control’s Navigated event as well:
private void webBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
textBoxl.Text = webBrowserl.Url.ToString();
this.Text = webBrowser.DocumentTitle.ToString();
In this case, when the requested page has finished downloading in the Web Browser control, the Navigated event is fired. In your case, you simply update the Text value of the textBox1 control to the
URL of the page. This means that once a page is loaded in the Web Browser control’s HTML container, and if the URL changes in this process (for instance, if there is a redirect), then the new URL will be shown in the text box. If you employ these steps and navigate to the csharp Web site (www.csharpaid.com). then you will notice that the page’s URL will immediately change to www.csharpaid.com/WileyCDA. This process also means that if the end user clicks one of the links contained within the HTML view, then the URL of the newly requested page will also be shown in the text box.
Now if you run the application with the preceding changes in place, you will find that the form’s title and address bar work as they do in Microsoft’s Internet Explorer, as demonstrated in Figure 41-5.
The next step is to create an IE-like toolbar that will allow the end user to control the Web Browser control a little better. This means that you will incorporate buttons such as Back, Forward, Stop, Refresh, and Home.
Rather than using the ToolBar control, you will just add a set of But ton controls at the top of the form where you currently have the address bar. Add five buttons to the top of the control, as illustrated in Figure 41-6.
In this example, the text on the button face is changed to indicate the function of the button. Of course, you can even go as far as to use a screen capture utility to “borrow” button images from IE and use those. The buttons should be named buttonBack, buttonForward, but tonStop, buttonRefresh, and buttonHome. To get the resizing to work properly, make sure that you set the Anchor property of the three buttons on the right to Top, Right.
On startup, buttonBack, buttonForward, and buttonStop should be disabled because there is no point to the buttons if there is no initial page loaded in the Web Browser control. You will later tell the application when to enable and disable the Back and Forward buttons yourself, depending on where the user is in the page stack. In addition, when a page is being loaded, you will need to enable. the Stop button – but also, you will need to disable the Stop button once the page has finished being loaded. You will also have a Submit button on the page that will allow for the submission of the URL being requested.
First, however, you will add the functionality behind the buttons. The Web Browser class itself has all of the methods that you need, so this is all very straight forward:
Many different activities are going on in this example because there are so many options for the end user when using this application. For each of the button-dick events, there is a specific Web Browser class method assigned as the action to initiate. For instance, for the Back button on the form, you simply use the Web Browser control’s GoBack() method; for the Forward button you have the Go Forward() method; and for the others, you have methods such as Stop(), Refresh(), and GoHome() . This makes it fairly simple and straightforward to create a toolbar that will give you action similar to that of Microsoft’s Internet Explorer.
When the form is first loaded, the Form1_Load event disables the appropriate buttons. From there, the end user can enter a URL into the text box and click the Submit button to have the application retrieve the desired page.
To manage the enabling and disabling of the buttons, you must key into a couple of events. As mentioned before, whenever downloading begins, you need to enable the Stop button. For this, you simply added an event handler for the Navigating event to enable the Stop button:
Then, the Stop button is again disabled when the document has finished loading:
Enabling and disabling the appropriate Back and Forward buttons really depends on the ability to go backward or forward in the page stack. This is achieved by using both the Can GoForwardChanged() and the Can GoBackChanged() events:
Run the project now, visit a Web page, and click through a few links. You should also be able to use the toolbar to enhance your browsing experience. The end product is shown in Figure 41-7.
Printing Using the Web Browser Control
Not only can users use the Web Browser control to view pages and documents, but they can also use the control to send these pages and documents to the printer for printing. To print the page or document being viewed in the control, simply use the following construct:
As before, you do not need to view the page or document to print it. For instance, you can use the Web Browser class to load an HTML document and print it without even displaying the loaded document. This can be accomplished as shown here:
WebBrowser wb : new WebBrowser();
wb.Print () ;
Displaying the Code of a Requested Page
In the beginning of this chapter, you used the WebRequest and the Stream classes to get at a remote page to display the code of the requested page. You used this code to accomplish this task:
Now, however, with the introduction of the Web Browser control, it is quite easy to accomplish the same results. To accomplish this, change the browser application that you have been working on thus far in this chapter. To make this change, simply add a single line to the Document_Completed event, as illustrated here:
In the application itself, add another TextBox control below the Web Browser control. The idea is that when the end user requests a page, you display not only the visual aspect sf the page but also the code or the page, in the TextBox control. The code of the page is displayed simply by using the DocumentText property of the Web Browser control, which will give you the entire page’s content as a String. The other option is to get the contents of the page as a Stream using the DocumentStream property. The end result of adding the second TextBox to display the contents of the page as a String is shown in Figure 41-8.
The Web Request and Web Response Hierarchy
In this section, you will take a closer look at the underlying architecture of the WebRequest and WebResponse classes.
Figure 41-9 illustrates the inheritance hierarchy of the classes involved.
The hierarchy contains more than just the two classes you have used in your code. You should also know that the WebRequest and WebResponse classes are both abstract and cannot be instantiated: These base classes provide general functionality for dealing with Web requests and responses independent of the protocol used for a given operation. Requests are made using a particular protocol (HTTP, FTP, SMTP,
and s~on), and a derived class written for the given protocol will handle the request. Microsoft refers to this scheme as pluggable protocols. Remember in the code you examined earlier, your variables are defined as references to the base classes. However, WebRequest .Create ()actually gives you an IittpWebRequest object, and the GetResponse() method actually returns an Http WebResponse object, This factory-based mechanism hides many of the details from the client code, allowing support for a wide variety of protocols from the same code base.
The fact that you need an object specifically capable of dealing with the HTTP protocol is clear from the URI that you supply to WebRequest. create(). WebRequest. Create() examines the protocol specifier in the URI to instantiate and return an object of the appropriate class. This keeps your code free from having to know anything about the derived classes or specific protocol used. When you need to access specific features of a protocol, you might need the properties and methods of the derived class, in which case you can cast your WebRequest or WebResponse reference to the derived class.
With this architecture, you should be’able to send requests using any of the common protocols. However, Microsoft currently provides derived classes to cover only the HTTP, HTTPS, FTP,and FILE protocols. The FIP option is the latest option provided by the .NET Framework (since the .NET Framework 2.0). you want to utilize other protocols, for example, SMTP, then you will need to turn to using the Windows Communication Foundation, revert to using the Windows API, or use the SmtpClient object.