Sie sind auf Seite 1von 31

5

Web Enabling Data


We now have to our credit, programs that enable execution of a general purpose select statement
as well as those that update, insert and delete commands. These were all C# programs which
were compiled into executable files.

Let's assume you want to display the contents of the customer table. Our program will very well
serve this purpose. Alternatively, the program can be made to accept user input and depending
upon the table name that the user typed in, the program can display contents of that table. You
can easily do so with the help of a function called GetLine in Console. GetLine will cause the
program to wait at the console for the user input followed by the 'Enter' key.

This situation comes with its share of problems though. The problem is that if there are five
people who are going to use this program then you need to give them five copies of the program.
If there are five thousand such users then you have to copy this on to five thousand different
machines. Simply not possible. Wait a minute! Did you get a sudden brainwave? The perfect
solution would be to 'put it on a network'!! But don't forget that there are many networking
standards available. Some may have Novell, some may have Windows 2000, and others may
have the Macintosh or even Linux/Unix. So what do we do now? You will have to make sure
that the same program works under Linux as well as it does under a Mac or any other standard.
Apart from this you would have the headache of having to train people to use the program.

The only solution to this problem is Web enabling data. This is the new standard of writing code.
You need to access your data using Internet Technologies. It's only then that we can eliminate
the loopholes that exist within the already available standards.

No matter which operating system you install, along with it you get access to a browser. When
you use the Internet you use a browser, a.k.a. an user agent, that enables you to view web pages
and enables data transfer over the Internet.

Since we do have a browser, can't we do a simple thing? Let the user type the name of our
machine and get a form. Within the form he can key in the table name and once he does that he
will get the details of that table. Which means you will now have to execute your code on a
program called the WebServer. This is what is meant by Web Enabling Data.

But before we leapfrog into the world of Web Enabling Data, let's acquaint ourselves with the
basic language that the browser understands. It is called HTML.
HTML

Amongst browsers, the usual suspects are Netscape Navigator and Internet Explorer. What
happens when you view a web page using such a browser? Technically speaking, you connect to
a web server and a file comes over onto your computer, which is generally an HTML file.

HTML is the acronym for Hyper Text Markup Language. It is a document-formatting language.
HTML is basically a stream of characters without any intelligent functionalities like the for and
if statements. Hence it cannot be considered an equivalent of a programming language. HTML,
as simple as it is, allows any bumpkin to be an ace at it!

Assuming you have a Web Browser, let's write our first HTML program. You can use any editor
like word to type your program in. The only thing that you must bear in mind is that the file must
be saved with the extension .htm or .html. Create the file in your root directory. In our case, we
will save in c: and since we are using the dos editor we shall begin by saying edit a.html

C:>edit a.html

Type the code as we have done below.

a.html

Hi

Bye

Output

Hi Bye

Note that the text must be on two separate lines. Once you have saved your file run your
browser. In the browser you will see a white text box known as the address bar. Click there and
type c:/a.html, in our case we have saved the file in the root of the C drive.

As of now we are picking up this html file from our hard disk. But when you are on the Net you
are accessing a file from some other machine on the net. In that case, you give the address of that
machine. For instance, if you want to connect to the Microsoft site, you will type
www.microsoft.com. Apart from that there is no difference in trying this on the Net or off the
Net.

When the browser sees an html file, it reads it line by line. Hence, in the browser window you
will see Hi Bye displayed. Wow! You have just written your first html program!

But didn't we write Hi and Bye on two separate lines? The browser, dumb as it is doesn't seem to
understand this. Looks like the browser, by default, ignores enters! So, how can we make the
browser understand? We can do so with the help of 'tags'.
HTML is based on 'tags', which instruct the browser how to display a piece of text or an
image/picture. A tag begins with '<' and ends with '>'.

So let's add a tag.

a.html

Hi <br>

Bye

Output

Hi

Bye

Going by the definition of a tag you will realize that br is a tag. It is enclosed within the angular
brackets. <br> means next line. Save the file. Now when you view this file in the browser you
will find that Hi and Bye are displayed on two separate lines.

Hence, HTML is nothing but a collection of tags. You just need to know which tag satisfies what
purpose.

a.html

<b> Hi </b> <br>

Bye

Output

Hi

Bye

In this program, the tag b means bold. But here we also have </b>, which is a closing tag. This
indicates that we are closing the <b> tag. Whatever is enclosed between the two will be made
bold. Hence only Hi will be bold. HTML tags are romantic, most of them always travel in pairs -
called an opening tag and a closing tag. But some tags like <br> like to play the field for they
prefer to remain single.

Using the <i> tag we will display Hi in italics.


a.html

<i> Hi </i> <br>

Bye

Output

Hi

Bye

It is all very mechanical! <i> means italics and hence Hi is displayed in italics. Had you included
bye within <i> and </i> then bye would be in italics too! That's all the understanding that is
required to learn HTML!

Now we have included another tag <h1>

a.html

<i> Hi </i> <br>

<b> Bye </b> <br>

<h1> You are Welcome again! <h1>

Output

Hi

Bye

You are Welcome again!

Since Hi is included in <i> </i> it will be displayed in italics. Bye is displayed in bold due to the
<b> tag. <hi> means heading1, it makes the text bigger. Thus, 'You are Welcome again!' is
displayed in a bigger font.

a.html

<html>

<body>

<i> Hi </i> <br>


<b> Bye </b> <br>

<h1> You are Welcome again! <h1>

</body>

</html>

Output

Hi

Bye

You are Welcome again!

This program outputs the same result as the above. The only difference is that now it is a well-
formed HTML program. Every HTML file must begin with the <html> and end with </html>
tag. Whatever text is to be displayed within the browser must be enclosed within the <body> and
</body> tag. This is the way an HTML program must be written. Hope the purists have forgiven
us now!

Let's make our page attractive by adding a picture to it. Copy any gif file to your root directory
and name it aa.gif. In our case, we copied it to c:

a.html

<html>

<body>

<i> Hi </i> <br>

<b> Bye </b> <br>

<img src="aa.gif">

<h1> You are Welcome again! <h1>

</body>

</html>

img is the image tag, it is used to display pictures. Along with this tag you have to specify the
name of the image file. Following the word 'img' is the word 'src' and after the '=' sign you
specify your filename. i.e. aa.gif. You can give the name of any picture file. But follow this
syntax! Another thing to note is that you can have the file name included in single quotes or
double quotes or you may exclude them totally. Thus viewing this file in the browser will now
display the image you specified along with the text. In HTML parlance, src is called an attribute.
An attribute describes / qualifies a tag.

<a href=a.html> Hi </a>

<a href=b.html> Bye </a>

You will see two hyperlinks in your browser window. The names of the html files will not be
displayed but the words Hi and Bye will be underlined. And if you click on hi and bye the
respective html files will be displayed instead.

Then there are tables in HTML

a.html

<html>

<table border=10>

<tr>

<td>hi</td><td>100</td>

</tr>

<tr>

<td>1000</td><td>bye</td>

</tr>

</table>

</html>

The table tag has one attribute, border, that specifies how the lines or borders between columns
looks like. The table tag encompasses two tags . tr stands for a table row and td for a table
columns. We have two tr's , hence we have two rows and each tr encloses two td's one for each
column.

Similarly, you can keep adding more and more tags depending on how you want your page to be
displayed. Any book on HTML will list all the available tags. Our aim is not to learn html here
but to use C# on the Net. Since knowing this much will suffice our forthcoming needs, let's get
back on track!
Using C# on the Net

Now that you are familiar with the rudimentary elements of HTML, let's see how we can apply
our recently acquired knowledge in conjunction with C# on the Net.

First and foremost you need a Web Server. Hence you will now need to install Apache. You can
download Apache from http://www.apache.org and then run the installer program. Among the
Apache directories, there are two sub-directories that are of importance to us, namely, cgi-bin
and htdocs.

The cgi-bin sub-directory is used for storing executable files.

In order to change to the cgi-bin sub-directory follow the path as given below.

C:\progra~1\apache~1\apache\cgi-bin

And to change to the htdocs sub-directory give the following path.

C:\progra~1\apache~1\apache\htdocs

The htdocs sub-directory is used for storing html files.

To install the Apache Web Server all that you need to do is download the install program on your
hard disk. Run the executable program which will install apache in the apache group directory of
program files. Change to C:\progra~1\apache~1\apache directory and then run the web server as
follows.

C:\progra~1\apache~1\apache >apache

If you get an error about some server name, cd to the conf sub directory , edit a file called
httpd.conf , change a line starting with #ServerName to ServerName localhost and all should be
well after that.

Now that you have the Apache server running, activate your web browser. Type the address
127.0.0.1 in the address bar and press enter. Every machine on the internet is known by a
number. We call this number an IP address. IP stands for the Internet Protocol. Every machine
that has the Internet software running is also known by the number 127.0.0.1 or localhost. In case
a file called index.html exists, the browser will display it. This is because it is located in htdocs
and is the file that gets picked up by default when you give your machine address and you have
Apache running.

Change to the htdocs sub-directory and create an html file a.html to display a form.

a.html
<html>

<form>

<input type=submit value=Search>

<form>

</html>

The <form> tag is used to specify that we are creating a form. <input type=submit is the syntax
for creating a button. Value =Search means that 'Search' is the word that will appear on the
button. Had we said Value = Vijay, you would see the 'vijay' on the button.

Save the file as a.html in the htdocs subdirectory. Go to the browser window and type
http://127.0.0.1/a.html in the address bar and press enter. You will now see a button with the
name Search on it. But clicking on this button doesn't serve any purpose as of now.

Let's alter the program such that when the user clicks on the Search button our C# program
should execute.

So first we will write our C# program.

C:\csharp>edit a.cs

Now type the following code.

a.cs

class zzz

public static void Main()

System.Console.WriteLine("hi<b>bye");

Output

hi<b>bye
This is a simple program that should display hi and bye. Save the program as a.cs. On compiling
the program an executable file 'a' is created. If you run the program as we have been doing, you
will see the output as given above. But remember, what we just told you about executables?
When you are using Apache you must save all executables in the cgi-bin sub-directory as a
security precaution. Hence you must copy a.exe to cgi-bin by giving the following command.

C:\csharp>copy a.exe c:\progra~1\apache~1\apache\cgi-bin

Now we will alter our HTML program. Within the form tag include action=http://127.0.0.1/cgi-
bin/a.exe This indicates the action to be performed when the button is clicked. Since we want our
program a.exe to run, we have given its path.

a.html

<html>

<form action=http://127.0.0.1/cgi-bin/a.exe>

<input type=submit value=Search>

<form>

</html>

Now that we have everything ready, let's get on with the show! Activate your browser and type
http://127.0.0.1/a.html in the address bar. You see the button labeled Search. Now click on this
button. To your horror you see an error! The browser window displays an Internal Server Error.
Note the url in the address bar- http://127.0.0.1/cgi-bin/a.exe?

Now make the changes as we have done below.

a.cs

class zzz

public static void Main()

System.Console.WriteLine("Content-Type:text/html\n");

System.Console.WriteLine("hi<b>bye");

}
}

Output in Browser

hibye

Save your file, compile it and again copy it to cgi-bin once again. Now when you run your
program from the browser, the error vanishes! And you will see hibye displayed. That means it is
mandatory to give Content-Type. It tells the browser that what is being sent across is a text file.
Also the content is qualified as html and not pure text. It is also called a header. Because we are
saying html, the bye is displayed in bold. So we created a file and the file goes over i.e. what
ever is in Console.WriteLine goes over.

Now remove html and instead write plain. Let's see what happens. After making the necessary
changes and compiling the program copy it again to cgi-bin.

a.cs

class zzz

public static void Main()

System.Console.WriteLine("Content-Type:text/plain\n");

System.Console.WriteLine("hi<b>bye");

Output in Browser

hi<b>bye

Now run your program from the browser. You will notice that bye is not displayed in bold. Also
note that now the tags are displayed as normal text. They show no formatting effects. This is
because instead of the word html we are now saying plain. That means the browser will now
display everything as plain text.

Thus the Content-Type: header is used to indicate to the browser that we are sending text
followed by HTML. Thus if we want our program to execute on the web it is mandatory that we
include this header in our program as the web server does not know what is the file type it is
sending over.

Now that we have all the ingredients for the final show, let's get on with it. We will now add the
header to our general-purpose select program. We will do this so that we can display the contents
of a table on the web. Thus the only change that we have made to the program is to add the
following line:

System.Console.WriteLine("Content-Type:text/html\n");

a.cs

using System.Data.OleDb;

class zzz

public static void Main()

try

OleDbConnection s;

s = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;

Data Source=c:\\zzz.mdb");

s.Open();

OleDbCommand c;

c=new OleDbCommand("select * from abc",s);

OleDbDataReader r;

r = c.ExecuteReader();

System.Console.WriteLine("Content-Type:text/html\n");

while ( r.Read() )
{

for ( int i = 0 ; i < r.FieldCount ; i++)

System.Console.Write(r.GetValue(i)+" ");

System.Console.WriteLine(“<br>”);

catch(System.Exception e)

System.Console.WriteLine(e.ToString());

We have also added System.Console.WriteLine("<br>"); so that each record is displayed on a


new line. The browser will see <br> and understand it as an html tag. This is because in the
header we have specified text/html. As such you will see each record on a new line.

Now save the file and compile it. Copy the file a.exe to the cgi-bin sub-directory. Activate the
browser window and type http://127.0.0.1/a.html in the address bar. Now click on the search
button. Accolades! You have successfully run your C# program from the browser. You will now
see all the contents of the abc table. Why the abc table? Because that's the table you specified in
your program.

Thus, whenever the user clicks on the button in the browser he is calling a program on the server.
The server could be a trillion miles away!! However, even now everything is not hunky dory.
The major problem being that this entire approach is inflexible.

Earlier, we told you we need this type of programming because we didn't want to copy the
programs on each machine. But the problem with the Web Server is that if it contains ten html
files then we can give the user only those ten html files. So we are only giving him ten views.
However, what we really need to do is that we need to pass data from us to his machine.

For example, let's assume we have a database that has names of people. We should have a form
in which the user can write the name of a person. When he clicks on 'ok' that name should get
added to the database. In effect, we are adding one person’s data to the database. Similarly, we
should be able to delete a person from the database too. And finally we can have a table-display
program wherein the user will provide the table name. When he clicks on ok, the contents of that
table will be displayed. Thus you can now think of generating flexible programs. You probably
felt limited earlier as you could display contents of only that table whose name you had provided
within the program.

Environmental Variables

Before we get down to making our programs flexible we need to understand as to how we can
deal with Environmental Variables in C#. An Environmental Variable is a word that the
operating system understands.

a.cs

class zzz

public static void Main(){

string s;

System.Console.WriteLine("Content-Type:text/html\n");

s=System.Environment.GetEnvironmentVariable("PATH");

System.Console.WriteLine(s);

Output

Content-Type:text/html

C:\JDK1.2.2\BIN; C:\WINDOWS\MICROSOFT.NET\FRAMEWORK\V1.0.2204\;
C:\WINDOWS; C:\WINDOWS\COMMAND; C:\BORLANDC\BIN; C:\WINDOWS;
C:\WINDOWS\COMMAND; C:\PROGRAM FILES\MTS

Displays the value of environmental variable called PATH. An environmental variable is a word,
which stores a value. When you give the command set xyz=bye at the command prompt, xyz
becomes an environmental variable, which stores the value bye. All operating systems allow you
to create environmental variables . The environmental variable PATH stores a list of directories
that the operating system searches for to find executables files. Run it off the web server or by
itself.
a.cs

class zzz

public static void Main(){

System.Collections.IDictionary i;

i=System.Environment.GetEnvironmentVariables ();

System.Collections.IDictionaryEnumerator d;

d=i.GetEnumerator();

System.Console.WriteLine("Content-Type:text/html\n");

System.Console.WriteLine(i.Count + "<br>");

while (d.MoveNext())

System.Console.WriteLine("{0}={1}<br>",d.Key,d.Value);

There can be 100's of environmental variables and we would like a list of all of them. The class
Environment in the System namespace has a function GetEnvironmentVariables which returns
an object that looks like IDictionary. This IDictionary object has a function called
GetEnumerator which returns an object that looks like IDictionaryEnumerator. You have to learn
all this by rote, there is no other option available. We are then displaying how many
environmental variables there are by printing a member Count in IDictionary. Then we need to
activate each variable by calling MoveNext which returns true if there are more environmental
variables in the list. An environmental variable is represented by a key-value pair, which is also
variable in the IDictionaryEnumerator class. Thus we can display all the environmental variables
starting with a count of how many there are.

If you check the list of environmental variables in your browser, you will see one called
QUERY_STRING , but it will have no value.
Now run as http://127.0.0.1/cgi-bin/a.exe?aa=ho and see the variable QUERY_STRING have a
value aa=ho.

a.html

<html>

<form action=http://127.0.0.1/cgi-bin/a.exe>

<input type=submit value=Search>

<input type=text name=aa>

<form>

</html>

Run the file in the browser. And you will now see a text box which is internally called aa. This is
because of the tag input type=text. Type ho in the text box and click on search. The URL will
now change to http://127.0.0.1/cgi-bin/a.exe?aa=ho and the variable QUERY_STRING will have
the value aa=ho.

a.html

<html>

<form action= http://127.0.0.1/cgi-bin/a.exe >

<input type=submit value=Search>

<input type=text name=aa>

<input type=text name=bb>

<form>

</html>

Now we will see two text boxes in which we will type in ho and no. Click on Search and the url
will change to http://127.0.0.1/cgi-bin/a.exe?aa=ho&bb=no and the variable QUERY_STRING
will have the value aa=ho&bb=no.

CGI Programming

Let us now understand what goes on once again. What we have been trying to explain to you is
called CGI programming where CGI stands for Common Gateway Interface. Everyone refers to
by its acronym rather than its expanded full form. CGI is a means by which a client i.e. a browser
can send some information to the web server.

Now typically what happens when we land up at a search engine? Well, we want to send the web
server i.e. yahoo the words that we want it to search the internet for. At times we are asked to fill
up a form on the web asking for some personal details. The information we key in is sent across
to the web server. Lets start with the above HTML file that makes CGI happen. We have two
input tags which have an attribute type=text. Thus we see two text boxes on our screen. We will
type in them hi and bye respectively. The third input tag has a type=submit and another attribute
value=search. This makes it into a button with the word search written on it.

Now, when we click on search after typing in data in the text boxes, the browser knows that you
have clicked on a button of type submit. So, it will now look for a tag form , and when it finds it ,
it will read the attribute action. Whatever is the value of action, it will write it in the address bar.

In the address bar we write a URL or Uniform Resource Locator or the address of a computer on
the net. In our specific case, our browser's address bar will contain http://127.0.0.1/cgi-bin/a.exe.
The browser does not stop here. It then adds a ? to the end of the above URL . Now it looks at
every text box that we have in the form. The first one has been given a name aa and we type hi in
it. So our URL now changes to http://127.0.0.1/cgi-bin/a.exe?aa=hi.

It's not over yet as we have one more text box to finish with. This one is called bb and has bye in
it. Thus our URL now reads http://127.0.0.1/cgi-bin/a.exe?aa=hi&bb=bye. The & is used to
separate different parameters. aa and bb are also called parameters. This url is sent across to the
web server. The web server is just another name for a file server. It can only send files across. In
this case we are asking it to run a program called a.exe from the cgi-bin sub directory. Before the
web server runs a.exe, it creates one environmental variable called QUERY_STRING and
initializes it to whatever follows the ? i.e. in this case aa=hi&bb=bye. The web server now runs
a.exe. What a.exe actually does is none of its concern. All that is wants from a.exe is a html file
which the web server sends back to the browser.

The web server also needs at least one header Content-Type which tells it the type of file being
sent across. Normally a.exe would read the environmental variable QUERY_STRING, extract
the parameters, then read a database, extract some values from it and finally create an HTML file
which it would hand over to the web server. All in all, this is how the magic of the internet is
bought about.

Now, let's learn some more C#.

a.cs

class zzz

public static void Main(){


string s ;

string [] e;

char[] c ;

s = "hi=bye&no=bad" ;

c = new char[2];

c[0] = '&';

c[1] = '=';

e = s.Split(c);

foreach ( string t in e)

System.Console.WriteLine(t);

Output

hi

bye

no

bad

s is a string which has been initialized to hi=bye&no=bad which looks similar to what
QUERY_STRING as explained earlier looks like. C is an array of chars which has two members
initialized to & and = respectively. The string class has a member Split, which will split a string
as per the delimiters provided as the first parameters in an array of chars. Thus the split function
will take the string s and split it whenever it sees a & or a = . In this case it will result in 4
strings. Split returns an array of strings which we are storing in an array e and using foreach to
display the array.

Now lets us create a simple form based web application which will accept a table name and then
display the entire table for us.

The html file a.html as usual will be copied to the htdocs sub-directory.
a.html

<html>

<form action= http://127.0.0.1/cgi-bin/a.exe >

<b> Enter Table Name </b>

<input type=text name=aa> <p>

<input type=submit value="Show Table">

<form>

</html>

We will run as:

http://127.0.0.1/a.html

Our C# program freshly compiled and copied to the cgi-bin subdirectory would now read as:

a.cs

using System.Data.OleDb;

class zzz

public static void Main()

try

string t;

t=System.Environment.GetEnvironmentVariable("QUERY_STRING");

string [] u;

char [] v = new char[1];


v[0] = '=';

u = t.Split(v);

string w;

w = "select * from " + u[1];

OleDbConnection s;

s = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;

Data Source=c:\\zzz.mdb");

s.Open();

OleDbCommand c;

c=new OleDbCommand(w,s);

OleDbDataReader r;

r = c.ExecuteReader();

System.Console.WriteLine("Content-Type:text/html\n");

while ( r.Read() )

for ( int i = 0 ; i < r.FieldCount ; i++)

System.Console.Write(r.GetValue(i)+" ");

System.Console.WriteLine("<br>");

catch(System.Exception e)

System.Console.WriteLine(e.ToString());
}

At our web form we are asked to write the name of the table. Then click on the button Show
Table. The web browser now writes the following URL in the address bar after we wrote abc as
the name of our table. http://127.0.0.1/cgi-bin/a.exe?aa=abc. The Apache Web Server now runs
a.exe. a.exe is nearly similar to what we wrote earlier with some minor modifications. t contains
the value of the environmental variable QUERY_STRING . v is an array of chars with one
member which is our delimiter '='. Split will return an array of strings in u , in our case aa and
abc which will be stored in u[0] and u[1]. Earlier we hard-coded the SQL Select statement. Here
w starts with the constant string 'Select * from ' and the name of the table is got from u[1] which
in turn gets its value from the environmental variable QUERY_STRING. Write the name of any
table that exists in the database in the text box and see how you have been able to web enable
your data on the net.

Lets use the table tags to make our data look more appealing in the browser.

a.cs

using System.Data.OleDb;

class zzz

public static void Main()

try

string t;

t=System.Environment.GetEnvironmentVariable("QUERY_STRING");

string [] u;

char [] v = new char[1];

v[0] = '=';
u = t.Split(v);

string w;

w = "select * from " + u[1];

OleDbConnection s;

s = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;

Data Source=c:\\zzz.mdb");

s.Open();

OleDbCommand c;

c=new OleDbCommand(w,s);

OleDbDataReader r;

r = c.ExecuteReader();

System.Console.WriteLine("Content-Type:text/html\n");

System.Console.WriteLine("<table border=10>");

while ( r.Read() )

System.Console.WriteLine("<tr>");

for ( int i = 0 ; i < r.FieldCount ; i++) {

System.Console.Write("<td>" + r.GetValue(i) + "</td>");

System.Console.WriteLine("</tr>");

System.Console.WriteLine("</table>");

}
catch(System.Exception e)

System.Console.WriteLine(e.ToString());

The output looks great. We have made very small additions to our program, mostly cosmetic. We
start with the table tag with a border. The while gets called once for every record and in this
while we start and end with a row tag tr and /tr. The for gets called for every field and here we
enclose the field value with a tag td and /td. At the end of the while we end with the /table tag.
The only problem is that we have not displayed the field names at all. Let the next program do
so.

a.cs

using System.Data.OleDb;

class zzz

public static void Main()

try

string t;

t=System.Environment.GetEnvironmentVariable("QUERY_STRING");

string [] u;

char [] v = new char[1];

v[0] = '=';

u = t.Split(v);
string w;

w = "select * from " + u[1];

OleDbConnection s;

s = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\zzz.mdb");

s.Open();

OleDbCommand c;

c=new OleDbCommand(w,s);

OleDbDataReader r;

r = c.ExecuteReader();

System.Console.WriteLine("Content-Type:text/html\n");

System.Console.WriteLine("<table border=10>");

System.Console.WriteLine("<tr>");

for ( int i = 0 ; i < r.FieldCount ; i++)

System.Console.WriteLine("<td>" + r.GetName(i) + "</td>");

System.Console.WriteLine("</tr>");

while ( r.Read() )

System.Console.WriteLine("<tr>");

for ( int i = 0 ; i < r.FieldCount ; i++) {

System.Console.Write("<td>" + r.GetValue(i) + "</td>");

System.Console.WriteLine("</tr>");

}
System.Console.WriteLine("</table>");

catch(System.Exception e)

System.Console.WriteLine(e.ToString());

All that we did was to copy the for loop which generated the field names from an earlier
program. We put a tr and a /tr around the for loop and the names of fields are tagged with td.
Great looking output.

a.cs

class zzz

public static void Main()

string t;

t=System.Environment.GetEnvironmentVariable("QUERY_STRING");

System.Console.WriteLine("Content-Type:text/html\n");

System.Console.WriteLine(t);

Output

aa=select+*+from+abc
In the original a.html instead of writing a simple table name we wrote ‘select * from abc’
instead. When we displayed the environment variable QUERY_STRING we learn that the
spaces are replaced with a + sign. The rules of creating a URL specify that a space is a forbidden
character and all spaces that we write are replaced by a +. Thus we have to convert the + back
into spaces.

a.cs

class zzz

public static void Main()

string t,s;

t=System.Environment.GetEnvironmentVariable("QUERY_STRING");

System.Console.WriteLine("Content-Type:text/html\n");

s = t.Replace('+',' ');

System.Console.WriteLine(s + "<br>");

System.Console.WriteLine(t);

Output

aa=select * from abc

aa=select+*+from+abc

The string class has a method called replace which replaces every occurrence of the first
parameter i.e. + with the second i.e. a space. Thus s is t but with the plus sign replaced by a
space.

Lets us know write an insert statement which will ask the user to key in his first and last name
and then add it into a table. We create a table 'bbb' in our database with two fields f1 and f2 both
character type. Our html file also now changes to.
a.html

<html>

<form action= http://127.0.0.1/cgi-bin/a.exe >

<b> Enter Users First Name </b>

<input type=text name=aa> <p>

<b> Enter Users Last Name </b>

<input type=text name=bb> <p>

<input type=submit value="Add">

<form>

</html>

a.cs

using System.Data.OleDb;

class zzz

public static void Main()

try

OleDbConnection s;

s = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;

Data Source=c:\\zzz.mdb");

s.Open();

OleDbCommand c;
string t;

t=System.Environment.GetEnvironmentVariable("QUERY_STRING");

string [] u;

char [] v = new char[2];

v[0] = '=';

v[1] = '&';

u = t.Split(v);

string f1,f2,f3;

f1 = u[1].Replace('+',' ');

f2 = u[3].Replace('+',' ');

f3 = "insert into bbb values('" + f1 + "','" + f2 + "')";

System.Console.WriteLine("Content-Type:text/html\n");

System.Console.WriteLine(f3);

c=new OleDbCommand(f3,s);

c.ExecuteNonQuery();

catch(System.Exception e)

System.Console.WriteLine(e.ToString());

Output
insert into bbb values('vijay ram','mukhi')

URL in Address Bar.

http://127.0.0.1/cgi-bin/a.exe?aa=vijay+ram&bb=mukhi

The first change is that our array of chars is now two members large and the second delimiter is
the '&'. Thus our QUERY_STRING will break into 4 strings aa , vijay+ram , bb and mukhi in
u[0] to u[3]. We replace the + with the ' ' in both strings and dynamically generate the insert
statement. It looks confusing but is not, Once again f1 and f2 contain the dynamic data but
because they are strings we need them to be separated by a single inverted comma. Thus the
complication in concatenating strings. The browser displays the SQL statement that will be
executed, but in real life we would display a success or error message.

Data Search Program

Now let us write a search engine or more precisely, a general purpose data retrieval engine. For
which we have to first create a simple database that will contain the following fields :

Keyword - that will store what the page contains,

url - the address of the page,

name - to be displayed instead of the url

and finally the text that will be displayed explaining the page.

create table ss ( keyword char(10), url char(100), name char(100), descrip char(100));

We will also add the following records.

insert into ss values ( 'java', 'a.html', 'java site', 'great java site');

insert into ss values ( 'c', 'b.html', 'c site', 'great c site');

insert into ss values ( 'basic', 'c.html', 'basic site', 'great basic site');

insert into ss values ( 'cobol', 'd.html', 'cobol site', 'great cobol site');

Create the following html files in the htdocs subdirectory

search.html

<html>

<form action= http://127.0.0.1/cgi-bin/a.exe >


<b> Enter keyword </b>

<input type=text name=aa> <p>

<input type=submit value="Search">

<form>

</html>

a.html

The file is for java

b.html

The file is for C

c.html

The file is for Basic

d.html

The file is for Cobol

The C# program will be as follows

a.cs

using System.Data.OleDb;

class zzz

public static void Main()

try

string t;
t=System.Environment.GetEnvironmentVariable("QUERY_STRING");

string [] u;

char [] v = new char[1];

v[0] = '=';

u = t.Split(v);

string w;

System.Console.WriteLine("Content-Type:text/html\n");

w = "select * from ss where keyword='" + u[1] + "'";

OleDbConnection s;

s = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\zzz.mdb");

s.Open();

OleDbCommand c;

c=new OleDbCommand(w,s);

OleDbDataReader r;

r = c.ExecuteReader();

while ( r.Read() )

System.Console.WriteLine("<a href=/{0}> {1} </a> {2}


<br>",r.GetValue(1),r.GetValue(2),r.GetValue(3));

catch(System.Exception e)

System.Console.WriteLine(e.ToString());
}

Open up the browser and enter the url 'http://127.0.0.1/search.html'

All that this program does is use the concept of a hyperlink to build a search engine and extract
data from a database. We assume we have a database of a trillion records that map the internet
telling us the keywords that each url stands for. The user keys in the name of a language and we
use the select statement to fetch the records meeting the condition, format it and then send the
html file across.

We can use the same concept to fill up a list box. The html tags for list box are as follows

<select name = aa>

<option> blue </option>

<option> red</option>

<option> orange </option>

</select>

In a real life situation, the colours will be retrieved from a database and the HTML file generated
by a CGI program.

Das könnte Ihnen auch gefallen