Published on

Published in: Technology, Design
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide


  1. 1. ‘<5:-‘I15? 5 Web Enabling Data We now have to our credit. pmgmms than cnuhlc cxiccution of :1 general purpose sclcct suitcmcnl as well as those that updalc. insert and delete commands. These were all Cl! programs which were compiled into executable files. Let's assume you want to display the contents of the customer mhlc. Our program will very well serve this purpose. Alternatively. the program can be made 10 accept user input and depending upon the table mime than the user typed in. die program can display contents of than table. You can easily do so with the help of a function called GctLinc in Console. Gctljnc will cause the program I0 wait at Ihe console for the user input followed by the 'F. nIer‘ key. This situation comes with its share of problems though. The problem is that if then: 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 lhis on Io five thousand diffenem machines. Simply not poniblc. Wait 11 minute! Did you get a sudden brainwave? The perfect solution would be to ‘put it on a nctwork'! ! But don't forget that then: are many networking standards available. Some may have Novcll. some may have Windows 2000. and others may have the Macintosh or even LinuxlUnix. 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 lo train people I0 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 loophole that ciiisl within lhe already available No mailer which operating system you install. along with it you get access to a browser. When you use the Internet you use in browser. iI. l(. iL an user ugenl. (hill enables you to view web pages and enables data lnmsfcr over the Internet. Since we do have a browser. can‘! we do a simple thing? be! the user type the name of our machine and gel ll form. Within the fonn he can key in the uihlc name and once he docs 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 Dara. But bcfotc wc leapfrog into the world of Web Enabling Data. lct's acquaint ourselves with the basic language that the browser understands. II is called HTML. HTML
  2. 2. 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 HTMI. file. HTML is the acronym for Hyper Text Markup Language. It is it docur. 'nent—formatting language. HTML is basically a stream ofcharaeters without any intelligent lurrctionalities 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 burnpltin to be an see at it! Assuming you hare 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: >odlt ahtml Type the code as we have done below. & I-ll 390 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 vie 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 our 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. microsol't. 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 displayal. Wow! You have just written your First lrtml 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/ pictrre. A tag begins with '<' and ends with '>’. So let's add a tag. mtml Ht <br> 3‘/8
  3. 3. Output HI Bye Going by the definition of a tag you will realize that hr 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 sepmate lines. Henm. HTML is nothing but a collection of tags. You just need to know which tag satisfies what purpose. amnl <b> Hi </ b> <br> BY! Output HI Bye In this program, the tag b means bold. But here we also have <lb>. which is a closing tag. This indicates that we are closing the <b> tag. Whatever is enclosed between the two will he made bold. Hence only Hi will be bold HTML tags are mmantic. most of them always travel in pairs - called an opening lag and a closing tug. But some tags like <br> like to play the field for they prefer to remain single. Using the <i> lag we will display Hi in italics. a. html <i> Hi </ i> <br> Bye output HI 33!‘? 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 he in italics too! Tlmrs all the understanding that is required to learn HTML! Now we have included another tag <hl> mm: <i> Hi </ i> <br> <b> Bye </ b> <br> <hl> You are Welcome again! <hl> Output HI 3V0 You are Welcome noun!
  4. 4. Since Hi is included in <i> </ i> it will be displayed in italics. Bye is displayul in bold due to the <b> tag. <hi> means headingl. it makes the text bigger. Thus. ‘You are Welcome again! ’ is displayed in a bigger font. mtml <htrnI> <body> <i> Hi </ i> <br> <b> Bye </ b> <br> <hl> You are welcome again! <hl> </ body> </ hard) Output H’ B! - You on Welcome again! This program outputs the same result as the abote. The only difference is that now it is a well- formed HTML program. Every HTML file must begin with the <html> and end with </ htn1l> tag. Whatever text is to be displayed within the browser must be enclosed within the <body> and <Ibody> tag. This is the way an HTML program must be written. Hope the purists have forgiven us now! Let's make our page attractis-e by adding a picture to iL Copy any gif file to your root directory and name it a: t.gif. In our case. we copied it to c: am <html> <body> <i> Hi </ i> <br> <b> Bye </ b> <br> <Img src= ‘aa. gIf"> <hl> You are Welcome again! <hl> </ body> </ hurl) 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 Mart! 'img' is the word ‘tire’ and ether the 'I‘ sign you specify your iilenttme. 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 lile 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. lift is called an attribute. An attribute describes I qualifies a tag. <a bref= a.t1t: mI> l-I </ a> <a href= b.html> Bye <la>
  5. 5. You will see two hyperlinks in your browser window. ‘me names of the html files will not be displayed but the words Hi and Bye will be underlinetl And if you click on hi and bye the respective html files will be displayed instead ’I'hentheteiiretahlesinH'I'ML aflfl <html> <tabIe border=10> <tr> <h: l>hi</ td> <hd>1(l)</ tu> </ tr> <0‘) <nd>1m))</ td><td>bye</ td> </ tr> </ tame) </ hm! ) The table tag has one attribute. heater. that specifies how the. lines or borders between columns looks like. 1'he table tag encompasses two tags . tr stands for a table row and td for a table eolumnx We have two tt’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 in! the available tagn. Our aim is not to learn html here but to use Call 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 ftunilitu with the rudimentary elements of HTML. let's see how we can apply our recently acquired knowledge in conjunction with C5 on the Net. First and foremost you need ll Web Sewer. Hence you will now need to install Apache. You can download Apache fmm http: IIwww. apache. otg and then run the installer program. Among the Apache diiectories. there are two sub-diiectories that are of importance to us. nsimely. cgi-bin and htducs. The cgi-bin sub-directory is used for storing executable files. In order to change to the egi-bin sub-directory follow the path as given below. C. ‘progra~1waiche-1'-apacheegi—tiin And to change to the htdocs sub-directory give the following path. C. *orogra~taoache~1aoachehtdocs The htdocs sub-directory is used for storing httnl files.
  6. 6. 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~lapacbe~lapache directory and then run the web server as follows. C. ’tprogra~1utadte~1.9oache >apaehe If you get an error about some server name. cd to the conf sub directory . edit a file called httpdconf . change it line starting with ¢SenrerNrrrne to Scr'erNarne localhost and all should be well after that. Now that you have the Apache sewer running. activate your web browser. Type the address l27.0.0.l in the address bar and press enter. Every machine on the inaernet 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 l27.0.0.I or localhosl. In case a tile called index. html exists. tlte browser will display it. This is because it is located in htdoes and is the file that gets picked up by default when you give your machine address and you haw Apache running. Change to the htdocs sub-directory and create an html file a. htm| to display a form uttml <htm| > <form> citpm type-smtttltvalue-Seard1> dorm) </ hm! ) The <form> tag is used to specify that we are creating a form. <inpuI type-submit is the syntax for creating a button. Value useatch metms that 'Serrn: h' 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. htrul in the htdocs subdirectory. Go to the browser window and type http: //|27.0.0.l/ a.htmI in the adcbess bar anti 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: 'lcsharp>edi ace Now type the following code. L5 CBSSZZZ { public mo: vold Maino { $ystem. Console. Wtltet. ine("hi<b>tyye'); )
  7. 7. } Output hi<b>bye This is a simple program that should display hi and bye. Save the program as lLt'. ‘§. 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 executable: in the egi-bin sub-directory as a security precaution. Hence you must copy acute to cgi—l>in by giving the following command. C. *csharp>copy aexe c. *ptogra~1aoache~1apacheegl—bin Now we will alter our HTML program. Wfithin the form tag include action= http: /Il27.0.0. llcgi- bin/ aLexe This indicates the action to he performed when the button is clicked. Since vie want our program aexe to run, we have given its path. uttml <htm| > <form action= http: //»/ a.exe> citpm type-stmrttltvalue-Seard1> dorm) </ l'| tflI> Now that we have everything ready. let's get on with the show! Activate your browser and type http: //l27.0.0.lIa. htmI 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 ml in the address bar- http: lIl27.0.0. llcgi-binla. exe'. ' Now make the changes as we have done below. §: § class { public static void Maint) { 5yaem.0ortsoIe. Wr| tet. lrte("(Jonhent-Typeztext/ hhn| n'); System. CortsoIe. VIIrltet. ine('hi<b>| ;ye'); ) ) Output In Browser him Save your file. compile it and again copy it to cgi-bin once again. Now when you mn your program from the browser. the error vanishes! And you will see hihye displayed. 11|at means it is mandatory to give Content-Type. It tells the browser that what is being sent across is a text file. Also the oontent is qunlifml as html and not pure text. It is also called it header. Becutne we are saying html. the bye is displayed in bold. So we created a file and the tile goes over i. e. what ever is in Console. WriteLine goes over.
  8. 8. 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 egi-bin. iafi classzzz ( ptblic static void t-1ain() { Symm. Console. WrItet. ir1e("Contertt-Type: textJplainn"); System. cortsoIe. Wrltet. lrte("hl<b>bye'); ) ) Output in Browser l1i<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 larowser will new 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 tisplay the contents of a table on the web. Thus the only change that we have made to the program is to add the follmving line: System. cortso| e.ItIrltet. lrte('Gont: ent-1ype: te)ttIhu'ntn'); 9-_§ uang Sysmem. Data. OleDb; dass zzz { public static void Main() ( W { Oleobconnecticn 5; s I new OteDbConnectiort("Provider-Mtcmsoft. Jet. Cl. EDB.4.o; Data Source= c:1Zz. mdb'); sxovent); Oleobcornmand c; e-new OteDbCommand("setect ' from abc', s); Oleoboatakeader r; r = c. ExeetneReader(); System. Corisole. Writet. ine("Cont: ettt-Typeztaeirt/ hh11lri'); while ( r. Read() ) {
  9. 9. for(irtti=0; I <r. Flelt‘. lCot. It; i++) Sy§ern. Console. WrIte{r. GetValt. Ie(i)+" "); :; »ystem. cortsole. wrItet. trte(“<br>"); ) mtch(Syst: a'n. Exceptlon e) { $yaem. Corsole. Wtlhet. 'ne(e. ToStrlng()); ) ) ) We have also added Systern. Cortsole. 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 lile and compile it. Copy the lile a. exe to the cgi-bin sub-directory. Activate the browser window and type http: l/I27.0.0.lla. html in the address bar. Now cliclt on the search button. Accolades! You have successfully run your C8 program from the browser. You will now see all the contents of the abc table. Why the ahc 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 progratmning because we didnt 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 news. However. what we really need to do is that the 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 n1'ite the name of a person. When he clicks on ‘ok' that name should get added to the database. ln ellect. 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 P"°Sl'8|ll- 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 C8. An Environmental Variable is a word that the operating system understands. ms: dasszzz { public static void Main(){ W109 5;
  10. 10. Svstem. Cortsole. Writel. i1e('Conttatt-Type: ttexVhtrnlri'); s-System. EnvirorIrient. GetEnv'IunmentVariab| e("PATH'); system. console. wrItietJne(s); ) ) Output Content-Typertextihtrrtl C: UDK1.2.2~B| N; CAWINDOWSWIICROSOF| '.NETFFtAMEw0RKV1 .0.2204; CAWINDOWS: CfWlNDOWSOOMMAND: CABORLANDCNBN: CAWNDOWS: C. ’WINDOWS1COMMAND: CAPROGHAM FILESWTI’ S Displays the value of environmental variable called PATH. An environmental variable is a word. which stores a value. When you give the command set : tyz= 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. LE dass { public static void It-lain(}{ System. CoIet: tions. IDlctlooary I; l= &rstJem. Envtromnent. Get£nvlrorimentVarIables (); System. CuIet1ions. IDictionary€nt. merator d; d-i. Get£numerator(); system. console. MItet. h¢("0onoa1t-1/ peztma/ lanolin“); $ystem. Corsole. WrlteUne(| .Count + "<br>"); {mile (d. Mo~eNext()) : ;‘. ystem. conso| e.WrItat. lne(“{0}= (1}<br>", d.Key, d.Value); ) ) There can be |00's of environmental variables and we would like a list of all of them. The class Environment in the System names-pace has a function Getlinvirorunentvariables which mums an object that looks like lbictionary. This lDictionary object has a function called Getfinumerutor which retumx an object that looks like lDictiomryEnumerator. You have to Ieam all this by rote. there is no other option available. We are then displaying how many environmental variables there are by printing ll member Count in [Dictionary-. 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 lDictionu. ryEnumen| lur class. Thus vie can display all the environmental variables starting with it count of how many there are. If you check the list of environmental variables in your browser. wu will see one called QUERY _STRlNG , but it will have no Value. New run as http: /Il2'l.0.0.llcgi-bin/ a.exe? aa= ho and see the variable QUERY_STRlNG have a value an-ho.
  11. 11. mmt <htm| > <forrn action-ltttp: ll127.0.0.1]cg'-birIa. ex1e> <Inpm type-submit value-seard1> <tnptn type= text natne= aa> <forrn> </ hurl) Run the file in the browser. And you will now see a text box which is intemally 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 httpd/ l27.0.0. llcgi-binla. exe? aa-ho and the variable QUERY _S'l'RING will have the value aa= ho. a. httnl <htm| > <forrn action- http: // a.exe > <inpm type-swmit value-Seard1> <| npm type= text nome= aa> <tnptn type= text name= bb> <forrn> </ htn'i> Now we will see Ivm text boxes in which we will type in ho and no. Click on Search and the url will change to http'Jll27.0.0.llcgi-hin/ a.exe? aa= Ito&bb= no and the variable QUERY_S'l‘RlNG 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. at browser can send sortie 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 "Le. yahoo the words that we want it to search the intemet for. At times we are asloed to fill up a form on the web asking for some personal details. The information we key in is sent across to the net: 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 typeaubmit and another attribute value= seanch. This makes it into a button with the word search written on it. Now, when we eliclt on search after typing in data in the text boxes. the browser knows that you have elicited 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 Loeator or the address of a computer on the net In our specific case, our browsers address bar will contain http‘JIl27.0.0.l/ cgi-bin/ zLexe. The browser does not stop here. It then arfls a ‘P 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 an and use type hi in it. So our URL now changes to http: /ll 27.0.0. I/ cgi-bt'tVa. exc'. ’aa= hi.
  12. 12. It's not over yet as we have one mote text box to finish with. This one is called bb and has bye in it. Thus our URI. now reads httpt/ /l27.0.0.I/ cgi-bin/ a.exe . ".tu= hi&bb: ‘b)et The & is used to separate different parameters. mi and bb are also called parameters. This url is sent across to the web server. The web server is just another name for u file scmzr. It can nnly send files : b’. ‘l’0. In this case we are asking it to run at pmgram called at. e.e from the cgi-bin sub tlirectory. Before the web server runs n. exe. it creates one environmental variable called QUERY STRING and initializes it to whatever follows the '. ’ i. c. in this case a. i=hi&hb-= bye. The web server now‘ runs a. cc What a. cxe . ictu; :ll_v does is none of its concern, All that is wants from : i.cxe l 2: html file which the web server sends back to the browser. The web server also needs at least one header Content-T_vpe which tells it the type of file being sent ucmxs. Normally a. c.vtc would read the environmental variable QU l. iRY_S'l'RlNG. extract the parameters. then read Lt d. 'tl1lb. 't. ‘t'. '. 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. New. lC['s learn some more Cit. 6.6 C1358 ZZZ { public static void l~1ain(){ string 5 ; string [1 e; chart] c ; s ‘hl= bye&no= bad'; c new char[2]; em] = '&'; til] = '= '; e s. Sp! it(c); lOt't2BCl't ( string t in c) System. Console. WrlheLine(t); } } Output hi bye no bad s is a string which has been initialized to hi= bye&no= bnd which looks siniilzsr to what QUERY_STRlNG as explained earlier looks like. C is an array of clmrs which has two members initialized to is: and = respectively. The string Cl. 'l. ‘. has .1 member Split. which will split a string as per the delimiters provided as the tint parameters in an umiy of chats Thus the split function will take the string s and split it whenever it sees it at or at r . In this case it will result in -I strings. Split returns an array of strings which we are storing in an array c and using foneach to display the array. Now lets us create a simple fonn based web application which will accept a table name and then display the entire table for us.
  13. 13. The html file auhtml ah‘ usual will be copied to the lndocs sub dixectory. a. mi <html> <form action: http: //—bin/ a.exe > <b> Enter Tabfe Name </ b> <Inpu1typc’= te: xt namci aa> <p> <mput type= submIt vaIue= "$how Table"> <forrn> </ html) We will run an: http: // htm‘ Our Cir’ program freshly compiled and copied to the cgi-bin subdincctory would now read .15: mils using Svstem. Data.0|eOb; dass zzz { publoc static vold MaIn() { W { string t; t= SYstem. Enviror"nent. GetEnviron ment‘VariabIe("QUERY_STRlNG"); string (1 u; char [J v new char[1]; = '= '; u t. Split(v); string w; w = ‘select " from " + u[l]; Oleobconnection 5; s new 0!aDbConnection("Prcwider— MictosoftJet.0LEDB.4.0; Data Source! -czn. mdb"); 5-0pen(); Oleobcom mand c; c= new OleDbCommand(w, s); OleDbDataReoder r; I’ C. EXL'CuY. CRL‘ad<: r(); System. Console. WtlteLine("Content-Type: tex‘UhtrnIn"); while ( r. Read() ) { for ( Int I = 0; I < t. FleldCount; i++) System. Console. Wvlue(r. Ge(Value(l)+" "); System. Cansole. Wkihel. ine("<br>"); ) ) catch(Syst: em. Exception e) { System. Console. WriheLine(u. ToString()); )
  14. 14. } } At our web form we are asked to write the name of the table. Then cliclt on the button Show Table. The web browser now writes the following URL in the address bar after we wrote also as the name of our table. http: //l27.0.0.Ilcgi-binItLe: te'? uaIabc. The Apache Web Server now rurts 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 chats with one member which is our delimiter ‘I’. Split will return an array of strings in u , in our case an and nix which will be stored in u[0] and ulll. Earlier we hard-coded the SQL Select statement. Here w starts with the constant string ‘Select ' from ' and the name or the table is got from u[I] which in tum gets its value from the environmental variable QUERY_STRlNG. Write the IIIIIIIC 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. bets use the table tags to make our data look more appealing in the browser. 15 udng Syaern. Data. OleDb; class zzz ( ptbllc static vold I-‘| aln() { UV { SW09 t: t= System. EnvirorInent. Get£nvirormentVarlab| e(‘QtJERY_Sl'RING"); shine [1 us char [] v - new char[1]; V[0l = '= ‘; U - t-SDWV); string w; w = ‘select ' from ' + u[1]; Oleobcomectton s; s - new 0IeDbGomection("Pt'oIider-MiansoftJet. Cl. £DB.4.0; Data Source-c: zzz. mdb"); S-0t>en(); Oleobcornmand c; c-new O| eDbCommand(w, s); Oleoboatalteader r; r = c. Exect. neReader(); Svstem. Corsole. Writei. ine("Cont: ertt-Type: taextIhtrnIn'); System. Conso| e.Wrltet. ine("<table bordern 10>"); whi| e( r. Read() ) { $ystem. Console. WrlteUne("<tr>"); for(irtti -0; I <r. FleldCount; i++){ System. Conso| e.Wr| te("<t: d>" + r. GetVa| ue(t) + "</ td>"); ) System. Console. Wrl0ei. 'lte("</ tr>“); ) System. Conso| e.VVriH. irte("</ table>');
  15. 15. ) eatdw[Sysbern. Exoeption e) { System. Console. WtlteUne(e. ToStrlr. g()); } ) ) The output lools great. We have mude very small additions to our program. mostly cosmetic. We start with the table tag with ll border. The while gets called once for every record and in this while we start and end with .1 row tug tr and ltr. The for gets called for every field and here we enclose the field value with at tug Id and ltd. At the end of the while we end with the Itztble tag. The only problem is that we have not dicplayed the field names at all. Let the next pnogsram do so. i. £S using System. Data. O|eDb; class zzz { public static void Ma>‘n() ( trv { string t; t= System. Enviror"nent. Get£nviron mentVarlabIe("QUERY_STRlNG"); string [1 u; char [] v new char[1]; V[0l = ‘= ‘; U = t. Spl| t(v); string w; w ‘select " from " + u[1]; Oleobccnnectlon s; s = new 0reDt>Connecnon("Pro~lder= Microsott. Jet.0l£D8.4.0;Oata Source : e: zzz. mdb‘); s. Opcn(); Oleobcom mand c; c= new OleDbComrnand(w, s); OIeDbOataReader :1 r c. ExecuteReader(); System. Console. WrtteL-ne("Content-Type: text. /htrnlvi"); System. Console. WrlUelJne("<tab| e border: 10>"); System. Console. WriheLine("<tr>"); for ( inti 0; i < r. Flt= .ldCount ; i++) System. Console. Wrl0elJne("<td>' + r. GetName(t) + “</ td>"); System. ConsoIe. WrIueLine("</ tr>"); while ( r. Read() ) { System. Console. WrIteUne(''<u->"); for ( int i = 0; i < r. FleldCount ; i++) { System. Cunsole. Wrihe("<ed>" + r. GetValue(i) + "</ td>"); } 5ystem. Console. WrlteUne("</ tr>"); } System. Console. WriteLine("</ tabfe>“);
  16. 16. } catch(Syst: un. Exceptlon e) { $ystem. Console. WrIu-. t.trte(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 Itr around the for loop and the names of fields are tagged with rd. Great looking output. 3.55 dasszzz { public static void Maln() { Shins t; t-System. Environrnent. Get£nvironrnent'varlable('QtJERY_S'lRlNG"); sy§em. cortsole. wrltet. lrue("Cont: ent-1ype: textJhtrnIrt'); §ystern. Console. WriteUne(t); ) Output aa-solect+'+lrom+abc In the original a. ht1:nl instead of writing a simple table name we wrote ‘select ‘ from tube’ instead. When we displayed the environment variable QUERY_S'lRlNG we lcam 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 ll 4. Thus we have to convert the -0- back into spaces. E-_§ class { public static void l-1ain() { string t. s; t-System. Envlronrnent. GetEnvIronrnentVarlat>le(‘QlJERV_STRING"); System. CortsoIe. Wrltet. trte("Contaertt-Tl/ pe: t1ext/ htmln'); s - t. RepIace<'+'. ' '>; Systern. Console. Wrltel. i1e(s + "<br: -"); t; .ystem. console. wrItet. tne(t); ) Output aa-select ' lrom are as-selectowlrnrnoabe The string class has a method called replace which replaces every occurrence of the first parameter i. e. + with the second Le. a space. Thus 5 is t but with the plus sign replaced by a space.
  17. 17. bets 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 5! table hbb’ in our database with two fields fl and F2 both character type. Our html file also new changes to. a. ntml <htmI> dorm action- htt: p:I/127.0.0.l/ cg‘-binla. exe > <b> Enter Users First Name </ b> <| nput type= text name= aa> <p> <b> Enter Users Last Name </ b> <inpm type-text namesht» <p> <input type-subrnit value-"Add“> <forrn> </ htrrb 3.5 using Syseem. Data. O|eDb; class zzz ( pwlic static void Main() 2” Oleobcomection s; s I new O| eDbConrIection("Prtwider-Mierosan. Jet. (l. EDB.4.0; Data Source-c: zzz. mdb'); s-Ovenoz Oleobcommand c; string t; t= syst. em. Envlronment. GetEnvIronmentVarIable(‘QtJERY_s'TRING"); string [1 u; dtar [] v - new char[2]; VLD] - '-'; v[1] I '&', ‘ u = t. Spllt(v); string f1,f2,t3; fl - u[ll-ReDlane('+'. ' '): H - u[3l-Replaoe('+’. ' ‘); f3 = ‘Insert tntzo bbb values(" + ft + ", "' + f2 + "')'; System. Cortsole. Writet. ine("Conttent-Typezoext/ htrnIn'); System. Cnnsole. Writet. ine(f3); c-new OIeDb0ommand(!3,s); §-EX0C1£€N0flQ08W(): catd'o(Syst: ern. Exception e) { System. consoIe. WrIteUne(e. ToStrIng()); ) ) ) Output Insert into one vahoscvljay ram'. 'rnuct1I’]
  18. 18. URL in Aclttass Bar. http'. n'/ I27.0.0.1/ogifinla. exe‘? aa-viay+ram&bb-rnukhi The first change is that our array of chars is now two members large and the second delimiter is the '&‘. Thus our QUERY_STRlNG will bmk into 4 strings an . vijay+ram . hi: and mukhi in u[O| to u|3|. We replace the + with the ' ' in both strings and dynamically genertwe the insert statement. It looks confusing but is not. Once again I’ I and F. ’ contain the dynamic data but because they are strings we need them to be separated by a single inverted comma. Thus the complication in concatenaling strings. The browser displays the SQL statement that will be executed, but in real life we would cisplay a success or error message. Data Search Program Now let us write it 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. aeaue table ss( keyword chartltl), LI’l c|1ar(100), name char(100), descrip d'iar(100)); We will also add the following necords. Insert Into sis value ( 'java‘, ‘a. hurI', ‘java site‘, ‘great java site’); Insert Into ss values ( 'c‘, 'b. html', ‘c sine’, ‘great c site’); Insert into 95 values ( ‘basic’, 'c. htrnl', 'basic site‘, ‘great basic site‘); insert into 55 values ( ‘cabal’, 'd. htm| ', 'ooboI site’, ‘great ooboi site’); Create the following html files in the Iitclocs subdirectory setirmthm <htmI> <form action: Iittp: // aexe > <b> Enterlteyword </ b> <inpm type-text name-aa> <p> <input type= submIt value= "Seareh"> <fori'n> <[htfl'l> §~_Mn1| Thefitetsforjava Iamml lheftieisforc Ctlilml Thefileisforflaslc Qtllllllll Theflelsforcobol
  19. 19. The CO program will be as follows as using Syst: em. Data. OleDb; dass zzz { public static void Maint) { FY { W109 t; t-SystemEnvironrnent. Get£nvionrneritVarIabte('QtJERY_STRING"); smog [l 0: dtar [] v = new dtartl]; V[0l I '-'2 u - t-Snlibtv): string w; $ystem. Corisole. Wrltet. ine("Contiertt-Type: tiextIhtrntn'); w I ‘select ' from as where keyword-" 4 u[1] + ""'; Oleobcnnnection s; s = new OleDb0onrtectton("Provtoer= MIcrosolt. Jet. (X£DB.4.o; Data Source= c:zn. rndb'); sovent); Oleobcnrnmand c; c= new 0leDhCommand(w, s); Oleoboatakeader r; r - c. ExecmeReader(); whiIe( r. Raad() ) ( $ystem. Console. Wriuet. ine("<a href= I(0}> {1} </ a> {2} <br>", r.GetVah. te(1), r.GetVaIue(2), r.GetValue(3)); ) ) catch($ystiem. Exception e) { 1-)': ys£em. Corso| e.Wrlhet. 'I'te(e. TaString()); } } Open up the browser and enter the url http: //I 27.0.0.l/ searclt. html' All that this program does is use the concept of ti hyperlink to build it search engine and extract data {mm a database. We ausutne 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 me natty: of a language and we use the select statement to fetch the records meeting the condition. format it and then send the html file acrms. We can use the same concept to fill up a list box- The html tags for list box are its follows <select name = aa> <ootion> blue </ option>
  20. 20. <optlon> red</ optlon> <option> orange </ optian> </ select> In at real life situation. the colours will be retrieved from a database and the HTML file generated by a CGI program.