C# CHAPTER 5

Embed Size (px)

Citation preview

  • 8/14/2019 C# CHAPTER 5

    1/31

    5Web 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 whichwere 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 dependingupon the table name that the user typed in, the program can display contents of that table. Youcan 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 networkingstandards 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 surethat 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. Whenyou 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 ourmachine 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 thebasic language that the browser understands. It is called HTML.

  • 8/14/2019 C# CHAPTER 5

    2/31

    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 toa 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, wewill 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 youare 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 tounderstand 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'.

  • 8/14/2019 C# CHAPTER 5

    3/31

    HTML is based on 'tags', which instruct the browser how to display a piece of text or an

    image/picture. A tag begins with ''.

    So let's add a tag.

    a.html

    Hi

    Bye

    Output

    Hi

    Bye

    Going by the definition of a tag you will realize that br is a tag. It is enclosed within the angularbrackets.
    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

    Hi

    Bye

    Output

    Hi

    Bye

    In this program, the tag b means bold. But here we also have , which is a closing tag. Thisindicates that we are closing the 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
    like to play the field for they

    prefer to remain single.

    Using the tag we will display Hi in italics.

  • 8/14/2019 C# CHAPTER 5

    4/31

    a.html

    Hi

    Bye

    Output

    Hi

    Bye

    It is all very mechanical! means italics and hence Hi is displayed in italics. Had you included

    bye within and then bye would be in italics too! That's all the understanding that is

    required to learn HTML!

    Now we have included another tag

    a.html

    Hi

    Bye

    You are Welcome again!

    Output

    Hi

    Bye

    You are Welcome again!

    Since Hi is included in it will be displayed in italics. Bye is displayed in bold due to the

    tag. means heading1, it makes the text bigger. Thus, 'You are Welcome again!' is

    displayed in a bigger font.

    a.html

    Hi

  • 8/14/2019 C# CHAPTER 5

    5/31

    Bye

    You are Welcome again!

    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 and end with

    tag. Whatever text is to be displayed within the browser must be enclosed within the and 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 directoryand name it aa.gif. In our case, we copied it to c:

    a.html

    Hi

    Bye

    You are Welcome again!

    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

  • 8/14/2019 C# CHAPTER 5

    6/31

    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.

    Hi

    Bye

    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 therespective html files will be displayed instead.

    Then there are tables in HTML

    a.html

    hi100

    1000bye

    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 tablecolumns. 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 bedisplayed. 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!

  • 8/14/2019 C# CHAPTER 5

    7/31

    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 candownload 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 yourhard 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 address127.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 casea file called index.html exists, the browser will display it. This is because it is located in htdocsand 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

  • 8/14/2019 C# CHAPTER 5

    8/31

    The tag is used to specify that we are creating a form. edit a.cs

    Now type the following code.

    a.cs

    class zzz

    {

    public static void Main()

    {

    System.Console.WriteLine("hibye");

    }

    }

    Output

    hibye

  • 8/14/2019 C# CHAPTER 5

    9/31

    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

    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("hibye");

    }

  • 8/14/2019 C# CHAPTER 5

    10/31

    }

    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 ismandatory 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. whatever 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("hibye");

    }

    }

    Output in Browser

    hibye

    Now run your program from the browser. You will notice that bye is not displayed in bold. Alsonote 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 nowdisplay 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

  • 8/14/2019 C# CHAPTER 5

    11/31

  • 8/14/2019 C# CHAPTER 5

    12/31

    {

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

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

    System.Console.WriteLine(
    );

    }

    }

    catch(System.Exception e)

    {

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

    }

    }

    }

    We have also added System.Console.WriteLine("
    "); so that each record is displayed on anew line. The browser will see
    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 searchbutton. 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 theprograms 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 formin 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 persons data to the database. Similarly, we

  • 8/14/2019 C# CHAPTER 5

    13/31

    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 probablyfelt 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 candeal 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 directoriesthat the operating system searches for to find executables files. Run it off the web server or by

    itself.

  • 8/14/2019 C# CHAPTER 5

    14/31

    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 + "
    ");

    while (d.MoveNext())

    {

    System.Console.WriteLine("{0}={1}
    ",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 returnsan 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 environmentalvariables 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 variablesstarting 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.

  • 8/14/2019 C# CHAPTER 5

    15/31

    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

    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 willnow 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

    Now we will see two text boxes in which we will type in ho and no. Click on Search and the urlwill 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

  • 8/14/2019 C# CHAPTER 5

    16/31

  • 8/14/2019 C# CHAPTER 5

    17/31

    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 membersinitialized 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 4strings. 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.

  • 8/14/2019 C# CHAPTER 5

    18/31

    a.html

    Enter Table Name

    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];

  • 8/14/2019 C# CHAPTER 5

    19/31

    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("
    ");

    }

    }

    catch(System.Exception e)

    {

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

  • 8/14/2019 C# CHAPTER 5

    20/31

    }

    }

    }

    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 asthe 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 onemember 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] whichin 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] = '=';

  • 8/14/2019 C# CHAPTER 5

    21/31

    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("");

    while ( r.Read() )

    {

    System.Console.WriteLine("");

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

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

    }

    System.Console.WriteLine("");

    }

    System.Console.WriteLine("");

    }

  • 8/14/2019 C# CHAPTER 5

    22/31

    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 doso.

    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);

  • 8/14/2019 C# CHAPTER 5

    23/31

    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("");

    System.Console.WriteLine("");

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

    System.Console.WriteLine("" + r.GetName(i) + "");

    System.Console.WriteLine("");

    while ( r.Read() )

    {

    System.Console.WriteLine("");

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

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

    }

    System.Console.WriteLine("");

    }

  • 8/14/2019 C# CHAPTER 5

    24/31

  • 8/14/2019 C# CHAPTER 5

    25/31

    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 forbiddencharacter 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 + "
    ");

    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 firstparameter 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 bothcharacter type. Our html file also now changes to.

  • 8/14/2019 C# CHAPTER 5

    26/31

    a.html

    Enter Users First Name

    Enter Users Last Name

    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;

  • 8/14/2019 C# CHAPTER 5

    27/31

    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

  • 8/14/2019 C# CHAPTER 5

    28/31

    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 inu[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 thecomplication 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. Forwhich 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

  • 8/14/2019 C# CHAPTER 5

    29/31

    Enter keyword

    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;

  • 8/14/2019 C# CHAPTER 5

    30/31

    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(" {1} {2}


    ",r.GetValue(1),r.GetValue(2),r.GetValue(3));

    }

    }

    catch(System.Exception e)

    {

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

  • 8/14/2019 C# CHAPTER 5

    31/31

    }

    }

    }

    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 extractdata 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 thehtml file across.

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

    blue

    red

    orange

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

    by a CGI program.