Home > Articles > Programming > C#

  • Print
  • + Share This
Like this article? We recommend

Like this article? We recommend

Change 1: URL-->RawHTML

The first information change we need to code is as follows:

string:URL-->string:RawHTML-->ArrayList:ImageList-->Disk:Files

We start by coding the method declaration. To help you and others understand and maintain your code, one convention you ought to adopt is naming your methods after the changes they perform. In our case this would be URLtoRawHTML. This method takes a URL as a string type and returns the HTML source code (raw HTML) that it finds at that URL as a string. You would implement the declaration for this method as shown in Listing 16:

Listing 16—Method Declaration: URLtoRawHTML

public string URLtoRawHTML(string URL)
{
}

The hard part is figuring out how to get the raw HTML from a URL. Unless you want to write low-level networking code, which would also entail handling the necessary protocols for interacting with web servers, it's best to search the documentation for Microsoft's .NET Framework Class Library to find out whether there are existing objects that you can use that do (most of) the work for you. It turns out that the System.Net and System.IO namespaces contain descriptions of objects that allow us to code this change using two motifs. Remember, you should really try to understand these motifs because they're general building blocks that you can use in other applications.

Motif 1: URL to Stream

The first motif you'll learn is the URL to Stream motif. This motif is useful whenever you're in a programming situation where you have a web address and you want to do something with the contents at this address. For our vampire bot example, we have the address of a web page and we want to extract all the images from this page. But before you can do anything with the content of a web page you need to first convert it to a Stream object. The motif that does so looks like Listing 17.

Listing 17—Motif 1: URL to Stream

using System.Net;
using System.IO;

WebRequest req;
WebResponse res;
Stream   str;

req = WebRequest.Create(URL);
res = req.GetResponse();
str = res.GetResponseStream();

This motif takes a web address as a string (URL) and returns a Stream object (str). As a matter of notational convention, when describing motifs we'll depict invariant code in bold and variables in italics. Moreover, we'll represent any entry variables in red italics (URL) and exit variables in blue italics (str).

Detailed Explanation

You first create a WebRequest object (req) by passing a URL as a string to the Create() method of that object (see Listing 18):

Listing 18—Explanation Motif 1: WebRequest.Create()

using System.Net;
using System.IO;

WebRequest req;
WebResponse res;
Stream   str;

req = WebRequest.Create(URL);
res = req.GetResponse();
str = res.GetResponseStream();

The WebRequest (req) object doesn't do much yet except remember the web page that you want to access. To read from the web page you need to first create a WebResponse object (res) by calling req's GetResponse() method (see Listing 19).

Listing 19—Explanation Motif 1: GetResponse()

using System.Net;
using System.IO;

WebRequest req;
WebResponse res;
Stream   str;

req = WebRequest.Create(URL);
res = req.GetResponse();
str = res.GetResponseStream();

But res also isn't in a form that you can do much with. You need to instruct res to return a Stream object, which you can work with (see Listing 20).

Listing 20—Explanation Motif 1: GetResponseStream()

using System.Net;
using System.IO;

WebRequest req;
WebResponse res;
Stream   str;

req = WebRequest.Create(URL);
res = req.GetResponse();
str = res.GetResponseStream();

The Stream object (str) gives you a lot of flexibility. From this object you can create files, strings, and various other representations of the streamed information. In our case, we're going to create a string that holds the contents of the web address (URL).

Motif 2: Building a String from a Stream (Stream to String)

Given a Stream object, it's quite common to read all the information from that Stream and store it locally in either an array or a file. For our vampire bot, where the Stream consists of HTML source code, we want to store the information into a string; strings contain built-in methods for searching and extracting substrings, which is what our vampire bot needs to do (for example, search and extract all the GIF filenames from the HTML source code). One basic motif for building a string from a stream is shown in Listing 21.

Listing 21—Motif 2: Stream to String

using System.IO;

string   RawHTML;
int     ch;

RawHTML = "";
while ((ch=str.ReadByte())!=-1)
 RawHTML=RawHTML+Convert.ToChar(ch);

This motif assumes that you already have a Stream object (str in our example; also see motif 1). The code loops through, reading one character (ch) at a time from the Stream (str), and appending that character to the destination string (RawHTML). Of course, we should point out that there are faster motifs for converting Streams to strings. For instance, instead of reading one byte at a time, you can read and append a block of characters each time through the loop. However, for instructional purposes this is a straightforward motif.

Detailed Explanation

First define a string variable (RawHTML) and initialize its value to empty (see Listing 22).

Listing 22—Explanation Motif 2: String Setup

using System.IO;

string   RawHTML;
int     ch;

RawHTML = "";
while ((ch=str.ReadByte())!=-1)
 RawHTML=RawHTML+Convert.ToChar(ch);

Read one byte (ch) from the Stream (str) using the Stream's built-in ReadByte() method (see Listing 23).

Listing 23—Explanation Motif 2: ReadByte()

using System.IO;

string   RawHTML;
int     ch;

RawHTML = "";
while ((ch=str.ReadByte())!=-1)
 RawHTML=RawHTML+Convert.ToChar(ch);

Use the + operator to append this character (ch) to the destination string (RawHTML), as shown in Listing 24.

Listing 24—Explanation Motif 2: Concatenation and Convert.ToChar()

using System.IO;

string   RawHTML;
int     ch;

RawHTML = "";
while ((ch=str.ReadByte())!=-1)
 RawHTML=RawHTML+Convert.ToChar(ch);

Note that ch is actually an integer because the ReadByte() method returns an integer. Thus, you must convert ch to a character via the Convert.ToChar() method prior to appending it.

To complete the motif, simply loop through until there are no more characters in the stream, which is denoted by ReadByte() returning a value of -1. One way to implement this loop is by putting the code that reads the character from the stream (ch=str.ReadByte()) in the condition portion of a while loop (see Listing 25).

Listing 25—Explanation Motif 2: Looping to Read All Bytes

using System.IO;

string   RawHTML;
int     ch;

RawHTML = "";
while ((ch=str.ReadByte())!=-1)
 RawHTML=RawHTML+Convert.ToChar(ch);

Completing the Method: Combining Motifs

To combine these motifs, move the motifs' variable declarations near the top of the method, and put the code blocks one after another. In Listing 26, we've highlighted motifs 1 and 2 in green and aqua, respectively, so you can better see how we've combined them.

Listing 26—URLtoRawHTML, Completed Method: Motifs 1 and 2 Combined

public string URLtoRawHTML(string URL)
{
WebRequest req;
WebResponse res;
Stream   str;

string   RawHTML;
int     ch;

req = WebRequest.Create(URL);
res = req.GetResponse();
str = res.GetResponseStream();

RawHTML = "";
while ((ch=str.ReadByte())!=-1)
 RawHTML=RawHTML+Convert.ToChar(ch);

str.Close();
res.Close();

return RawHTML;
}

Note that prior to returning RawHTML (return RawHTML), you need to close both the Stream object (str) and the WebResponse object (res), using each object's .Close() method; in other words, str.Close() and res.Close(), respectively.

  • + Share This
  • 🔖 Save To Your Account