Windows Systems Programming: Spring 2004

[ Home | Syllabus | Course Notes | Assignments | Search]


Exploring the .NET FCL (Chapter 3 Prog)


File Streams

List.cs

using System;
using System.IO; // beyond simple console I/O 

class MyApp
{
    static void Main (string[] args)// zero or more command line arguments
    {
        // Make sure a file name was entered on the command line
        if (args.Length == 0) { // arrays know their length
            Console.WriteLine ("Error: Missing file name");
            return;
        }

        // Open the file and display its contents
        StreamReader reader = null; 

        try {
            reader = new StreamReader (args[0]); 
            for (string line = reader.ReadLine (); line != null;
                line = reader.ReadLine ())
                Console.WriteLine (line);
        }
        catch (IOException e) {
            Console.WriteLine (e.Message);
        }
        finally { 
            if (reader != null)
                reader.Close ();
        }
    }
}

Experiments: what can you easily learn from this program?


System.Collections

Collections are ubiquitous in programming - these are "safe" from unauthorized accesses.
Can store any object derived from "System.Object"


ArrayList

Dynamic Arrays - some examples

ArrayList list = new ArrayList ();
list.Add ("John");
list.Add ("Paul");
list.Add ("George");
list.Add ("Ringo");
 
ArrayList list = new ArrayList ();
for (int i=0; i<100000; i++)
    list.Add (i);
// a much faster version
ArrayList list = new ArrayList (100000);
for (int i=0; i<100000; i++)
    list.Add (i);
// access
int i = (int) list[0]; // need to cast System.Object
// Iteration over an ArrayList
for (int i=0; i<list.Count; i++)
    Console.WriteLine (list[i]);
// You can also iterate with foreach:
foreach (int i in list)
    Console.WriteLine (i);

   HashTable

Generalizes array to use arbitrary "key" as index

Hashtable table = new Hashtable ();
table.Add ("Sunday",    "Dimanche");
table.Add ("Monday",    "Lundi");
table.Add ("Tuesday",   "Mardi");
table.Add ("Wednesday", "Mercredi");
table.Add ("Thursday",  "Jeudi");
table.Add ("Friday",    "Vendredi");
table.Add ("Saturday",  "Samedi");
// access is by "key"
string word = (string) table["Tuesday"];
// access is through underlying DictionaryEntry object
foreach (DictionaryEntry entry in table)
     Console.WriteLine ("Key={0}, Value={1}\n", entry.Key, entry.Value

Regular Expressions

Valuable tools for "parsing" strings
I use regular expressions every couple of weeks

Regular expressions = finite state machines (CS390)

Regex regex = new Regex (@"\\");
string[] parts = regex.Split (@"c:\inetpub\wwwroot\wintellect");
foreach (string part in parts)
    Console.WriteLine (part);

And here’s the output:

c:
inetpub
wwwroot
wintellect

Regex regex = new Regex ("<[^>]*>");
string[] parts =
    regex.Split ("<b>Every</b>good<h3>boy</h3>does<b>fine</b>");
foreach (string part in parts)
    Console.WriteLine (part);

And here’s the output:

Every
good
boy
does
fine
// one common use of regular expression is for validation
bool IsValid (string input)
{
    Regex regex = new Regex ("^[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{4}$");
    return regex.IsMatch (input);
}

Regex regex = new Regex ("href\\s*=\\s*\"[^\"]*\"", RegexOptions.IgnoreCase);

StreamReader reader = new StreamReader ("Index.html");

for (string line = reader.ReadLine (); line != null;
    line = reader.ReadLine ()) {
    MatchCollection matches = regex.Matches (line);
    foreach (Match match in matches)
        Console.WriteLine (match.Value);
}

//// to extract a substring - enclose that portion of the regular expression in "( )"
//// and use Groups to get the substring (there may be more than one)
Regex regex = new Regex ("href\\s*=\\s*\"([^\"]*)\"", RegexOptions.IgnoreCase);

StreamReader reader = new StreamReader ("Index.html");

for (string line = reader.ReadLine (); line != null;
    line = reader.ReadLine ()) {
    MatchCollection matches = regex.Matches (line);
    foreach (Match match in matches)
        Console.WriteLine (match.Groups[1]);
}

HttpWebRequest and HttpWebResponse

WebRequest request = WebRequest.Create ("http://www.wintellect.com");
WebResponse response = request.GetResponse ();

GetResponse returns an HttpWebResponse object encapsulating the response. Calling GetResponseStream on HttpWebResponse returns a Stream object that you can wrap a reader around to read the response. The following code echoes the text of the response to a console window:

StreamReader reader = new StreamReader (response.GetResponseStream ());
for (string line = reader.ReadLine (); line != null;
    line = reader.ReadLine ())
    Console.WriteLine (line)
reader.Close ();

Example

linklist.cs

  • Function: lists all hyperlinks in a web page

  • Objective: Demonstrate web access and regular expressions

using System;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;

class MyApp
{
    static void Main (string[] args)
    {
        if (args.Length == 0) {
            Console.WriteLine ("Error: Missing URL");
		// common in command line console programs
            return;
        }

        StreamReader reader = null;

        try {
            WebRequest request = WebRequest.Create (args[0]); 
            WebResponse response = request.GetResponse ();
            reader = new StreamReader (response.GetResponseStream ());
            string content = reader.ReadToEnd ();

            Regex regex = new Regex ("href\\s*=\\s*\"([^\"]*)\"",
                RegexOptions.IgnoreCase);

            MatchCollection matches = regex.Matches (content);
            foreach (Match match in matches)
                Console.WriteLine (match.Groups[1]);
        }
        catch (Exception e) {
            Console.WriteLine (e.Message);
        }
        finally {
            if (reader != null)
                reader.Close ();
        }
    }
}
  • F10: Opens a web page URL

  • F11: and gets the response web page

  • F12: expression says match "href" followed by some white space followed by an equals sing "=" followed by white space followed by a quote (") THEN remember the match you make of all characters (denoted by the asterisc (*)) up to another quote (that is what the parenthesis are doing) followed by the ending quote

  • F13: enumerate all matches

  • F14: get the text that matched inside the parentheses

 


Copyright chris wild 1999-2004.
For problems or questions regarding this web contact [Dr. Wild].
Last updated: January 19, 2004.