Você está na página 1de 37

What Are Active Server Pages?

Active Server Pages (ASPs) are Web pages that contain server-side scripts in addition to the usual mixture of text and HTML (Hypertext Markup Language) tags. Server-side scripts are special commands you put in Web pages that are processed before the pages are sent from your Personal Web Server to the Web browser of someone who's visiting your Web site. . When you type a URL in the Address box or click a link on a Web page, you're asking a Web hosting server on a computer somewhere to send a file to the Web browser (sometimes called a "client") on your computer. If that file is a normal HTML file, it looks exactly the same when your Web browser receives it as it did before the Web server sent it. After receiving the file, your Web browser displays its contents as a combination of text, images, and sounds.

In the case of an Active Server Page, the process is similar, except there's an extra processing step that takes place just before the Web server sends the file. Before the Web server sends the Active Server Page to the Web browser, it runs all server-side scripts contained in the page. Some of these scripts display the current date, time, and other information. Others process information the user has just typed into a form, such as a page in the Web site's guestbook. To distinguish them from normal HTML pages, Active Server Pages are given the ".asp" extension. What Can You Do with Active Server Pages?
There are many things you can do with Active Server Pages.

You can display date, time, and other information in different ways. You can make a survey form and ask people who visit your site to fill it out, send emails, save the information to a file, etc

What Do Active Server Pages Look Like?


The appearance of an Active Server Page depends on who or what is viewing it. To the Web browser that receives it, an Active Server Page looks just like a normal HTML page. If a visitor to your Web site views the source code of an Active Server Page, that's what they see: a normal HTML page. However, the file located in the server looks very different. In addition to text and HTML tags, you also see serverside scripts. This is what the Active Server Page looks like to the Web server before it is processed and sent in response to a request.

What Do Server-Side Scripts Look Like?


Server-side scripts look a lot like HTML tags. However, instead of starting and ending with lesser-than ( < ) and greater-than ( > ) brackets, they typically start with <% and end with %>. The <% is called an opening tag, and the %> is called a closing tag. In between these tags are the server-side scripts. You can insert server-side scripts anywhere in your Web page--even inside HTML tags.

Do You Have to Be a Programmer to Understand Server-Side Scripting?


There's a lot you can do with server-side scripts without learning how to program. For this reason, much of the online Help for Active Server Pages is written for people who are familiar with HTML but aren't computer programmers.

Displaying the Current Date and Time The date and time described in this section are those that are on the server. Date To display the current date by itself in a Web page, type:
<% =System.datetime.now.tolongdatestring %>

at the point where you want it to appear. When you view the page in your browser, you should see something like this: Thu, Jan 23, 1997 Note: Even though "=date" is a short script, it's actually made up of two parts. The "date" part tells the server, "Get me the date." The equal sign (=) tells the server to display the date in the Web page. If you typed just:
<% date %>

the server would get the current date from your system, but that's all. It wouldn't display it. There are times when it makes sense to use an ASP function without the equal sign. Time To display the current time by itself, type:
<% =time %>

where you want it to appear. When you view the page, you should see something like this: 4:19:46 PM Now (Date and Time) To display the current date and time, type:
<% =now %>

where you want them to appear. When you view the page, you should see something like this: 1/23/97 4:19:46 PM Changing the Way Date and Time are Displayed

You can also use Active Server Pages (ASP) functions to customize the way the current date and time are displayed on your Web page. To do this, use the now function together with the following formatting functions. Month and Monthname To display the number of the current month in a Web page, type:
<% =month(now) %>

where you want it to appear. When you view the page in your browser, you'll see a 1 if the current month is January, 2 if it's February, and so on. To display the name of the current month, type:
<% =monthname(month(now)) %>

where you want it to appear.

Using Variables, and Forms in Active Server Pages


Forms are a convenient way to communicate with visitors to your Web site. Using forms, you can create a survey form and ask visitors to fill it out. When they fill out the form, you can process the results automatically. With forms, there are two steps: first you create the form, and then you process it. To create a form for an Active Server Page, just create a standard HTML form. To try out this example, create an HTML file ("form_response.html") and cut-and-paste the following text into it.
<html> <head><title>Asking for information</title></head> <body> <form method="post" action="form_response.asp"> Your name: <input type="text" name="name" size="20"><BR> Your email: <input type="password" name="email" size="15"><BR> <input type="Submit" value="Submit"> </form> </body> </html>

Active Server Pages provide a mechanism for processing forms that, unlike CGI scripting, doesn't involve serious programming: the Request.Form. Considering the form above, we may create the file bellow and get a response. form_response.asp

<html> <head><title>Responding to a form</title></head> <body> Your name is <% =Request.Form("name") %> <BR> Your email is <% =Request.Form("email") %> </body> </html>

To display the contents of each field in the form, type:


<% =Request.Form(fieldname) %>

where fieldname is the name of the field. Creating a Variable You'll probably want to do more with your forms than display their contents in a Web page. For example, based on the contents of the form, you may want to create a variable and insert that variable in different places of your response page. You may need to create a variable. To do that, just make up a name and set it equal to the contents of the field. For example, if you have a field called "CatName" in your form, you can save it into a variable called "TheName" by typing:
<% TheName = Request.Form("CatName") %>

If you want to display "VisitorName" several times within a text you only need to include the variable in the text. For example:
My cats name is <% =TheName %>. Do you want to see <% =TheName %>?.

Example The form in this example asks users to introduce their names and their favorite color: red, blue, or green. When the form is received, the server responds displaying these data.
nameandcolor.html <html> <head><title>Name and Color</title></head> <body> <FORM ACTION="nameandcolor.asp" METHOD=POST> Let me know your Name and Favorite Color: <P>YOUR NAME: <INPUT TYPE="TEXT" NAME="YOURNAME" SIZE=20> <P>COLOR:

<INPUT TYPE="RADIO" NAME="COLOR" VALUE="1" CHECKED>Red <INPUT TYPE="RADIO" NAME="COLOR" VALUE="2">Green <INPUT TYPE="RADIO" NAME="COLOR" VALUE="3">Blue <P> <INPUT TYPE="SUBMIT" VALUE="OK">

</FORM> </body> </html> Now, create an ASP file ("nameandcolor.asp") and cut-and-paste the following text into it.
<html> <head><title>Name and Color</title></head> <body>

<% TheName = Request.Form("YOURNAME") %> <% colornumber = Request.Form("COLOR") %> Hi, <% =Thename %>.<BR> I know your favorite color is <% if colornumber = "1" then %> red <% end if %> <% if colornumber = "2" then %> green <% end if %> <% if colornumber = "3" then %> blue <% end if %>. </body> </html>

If....Then...Else
The If....Then...Else instructions sequence is very similar to the one we may find in different kind of scripting languages. Let's check an example.

<% AA="water" If AA="water" Then response.write ("I want to drink water") Else response.write ("I want to drink milk")

End If %>

For....Next
This instructions is also similar in different programming languages. Let's see a typical example.
I want to say "Hello" 10 times<BR> <% For mynumber = 1 to 10 %> <% =mynumber %> Hello<BR> <% Next %> END

In this case we have defined a variable ("mynumber") and using the For...Next instruction we have repeated 10 times line 4. Similarly to If....Then....Else instruction, we are allowed to execute any kind of instructions and as many of them as we want . The For...Next instruction allows to define the value of the increment.

<% For mynumber = 1 to 20 STEP 2 response.write("Hello<BR>") Next %>

Lab Examples http://www.asptutorial.info/learn/subroutine_include.html

http://weblogs.asp.net/scottgu/archive/2009/03/10/free-asp-net-mvc-ebook-tutorial.aspx http://www.business.unr.edu/faculty/ekedahl/IS460/LectureNotes.aspx Example 1 : <html> <body> <% response.write("My first ASP script!") %>

</body> </html> Or <html> <body> <P> "Hello World!" </p> </body> </html> Data base Example 2

<script language="C#" runat="server"> protected void Page_Load(Object s, EventArgs e) { lblBegin.Visible=false; } protected void Welcome_Click(Object s,EventArgs e) { lblBegin.Visible=true; lblBegin.Text="You have registered. Thanks!"; } protected void Leave_Click(Object s,EventArgs e) { lblBegin.Visible=true; lblBegin.Text="You have left. Thanks!"; } </script> <html><head> <title>TextBoxes</title> </head> <body bgcolor="#FFFFFF"> <asp:Label ID="lblBegin" Text="Nice You Stopped By!" forecolor="red" Font-Name="Verdana" Font-Size="10" runat=server /> <form runat="server"> <Asp:Table runat="server"> <Asp:TableRow> <Asp:TableCell>First Name</Asp:TableCell>

<Asp:TableCell><ASP:TextBox id="txtFName" runat=server /></Asp:TableCell> </Asp:TableRow> <Asp:TableRow> <Asp:TableCell>Last Name</Asp:TableCell> <Asp:TableCell><ASP:TextBox id="txtLName" runat=server /></Asp:TableCell> </Asp:TableRow> <Asp:TableRow> <Asp:TableCell>Email Address</Asp:TableCell> <Asp:TableCell><ASP:TextBox id="txtEmail" runat=server /></Asp:TableCell> </Asp:TableRow> <Asp:TableRow> <Asp:TableCell></Asp:TableCell> <Asp:TableCell><ASP:Button id=btnRegister text="Register Me" OnClick="Welcome_Click" runat=server /></Asp:TableCell> </Asp:TableRow> <Asp:TableRow> <Asp:TableCell></Asp:TableCell> <Asp:TableCell><ASP:Button id=btnLeave text="I want to Leave!" OnClick="Leave_Click" runat=server /></Asp:TableCell> </Asp:TableRow> </Asp:table> </form> </body></html>

USE OF DATA BASE


<%@ Import Namespace="System.Data.OleDb" %> <Script Runat="Server"> Sub Page_Load (s As Object, e As EventArgs ) Dim conAuthors As OleDbConnection

conAuthors=NewOleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA Source=c:\employees.mdb" ) conAuthors.Open() End Sub </Script> In the first line (in the above example) we import the necessary namespace, System.Data.SqlClient, for working with SQL Server. The connection to SQL Server is created and opened in the Page_Load subroutine. First, a SqlConnection class named conPubs is created. Passing a connection string as a parameter to the constructor for the SqlConnection class initializes the conPubs class. Finally, the connection is actually opened by calling the Open () method of the SqlConnection class. The connection string contains all the necessary location and authenticated information to connect to SQL Server. Also the connection string contains the name of the server, name of the database, SQL Server login, and password as shown below: conPubs=NewSqlConnection("Server=localhost;uid=sa;pwd=secret;database= Northwind" ) You will use similar code to create a connection in a Microsoft Access database by changing the namespaces and classes. In Example 2, a database connection is created and opened for a Microsoft Access databases named employees. Example18 OpenOleDbConnection.aspx <%@ Import Namespace="System.Data.OleDb" %> <Script Runat="Server"> Sub Page_Load (s As Object, e As EventArgs ) Dim conAuthors As OleDbConnection conAuthors=NewOleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA Source=c:\employees.mdb" ) conAuthors.Open() End Sub </Script>

Connection has been opened!

The output is shown below.

As you are creating a connection for Microsoft Access, you must import the System.Data.OleDb namespace rather than the System.Data.SqlClient namespace. Next, create an instance of the OleDbConnection class and initialize it with a connection string appropriate for Microsoft Access. Finally, calling the open () method of the OleDbConnection class actually opens the database connection. In Example18, the name of the OLEDB provider for Microsoft Access (Microsoft.Jet.OLEDB.4.0) and the path to the Access database on the server is seen. If you want to connect to another type of database, you have to specify a different provider. By default when you call the Open () method with either the SqlConnection or OleDbConnection class, the connection takes 15 seconds to open before timing out. You can overwrite this default behavior by supplying a Connect Timeout attribute in the connection string. For example, to allow a connection to open in a SQL Server up to 90 seconds you have to initialize the connection like this: MyConnection=NewSqlConnection("Server=localhost;UID=sa;PWD=secret; Connect _ Timeout=90" )
Retrieving Records from a Table

The SQL statement that will be used most often in ASP.NET pages is Select. The Select statement enables you to retrieve records that match a certain condition from a database table. The syntax for a basic Select statement is as follows: SELECT column1, column2... FROM tablename1, tablename2... WHERE search condition For example, If you want to retrieve the empno and ename columns, from the employees table where the empno column has the value 1, you would use the following Select statement: Select empno, ename FROM employees WHERE empno = 1 If you simply want to retrieve all the columns and all the rows from the Authors table, you would use the following Select statement: Select * FROM employees The asterisk (*) is a wildcard character that represents all the columns. If you use a WHERE clause, all the rows from the Authors table are automatically returned. (For more information learn SqlServer and MS Access.) To execute a Select statement in an ASP.NET page follow these four steps: 1. Create and open a database connection. 2. Create a database command that represents the SQL Select statement to execute. 3. Execute the command with the ExecuteReader () method returning a DataReader. 4. Loop through the DataReader displaying the results of the query. When a query is executed using ADO.NET, the results are returned in a DataReader. Precisely the results of that query are represented by either a SqlDataReader or OleDbDataReader, depending on the database from which you are retrieving the records. A DataReader represents a forward-only stream of database records; i.e. the DataReader represents only a single record at a time. To get the next record in the stream, and display them

you must call the Read () method repeatedly until you the end of the stream is reached. Once the record is passed, there's no going back. The following example, displays all the records from a SQL Server database named Northwind and table named employees as shown below in example.
READING DATA

<%@ Import Namespace="System.Data.OleDb" %> <% Dim conEmployees As OleDbConnection Dim cmdSelectEmployees As OleDbCommand Dim dtrEmployees As OleDbDataReader conEmployees = New OleDbConnection( "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA Source=c:\Employees.mdb" ) conEmployees.Open() cmdSelectEmployees = New OleDbCommand( "Select ename From Employees", conEmployees ) dtrEmployees = cmdSelectEmployees.ExecuteReader() While dtrEmployees.Read() Response.Write (<li>) Response.Write (dtrEmployees (ename)) End While dtrEmployees. Close () conEmployees. Close () %>
EXAMPLE TO GET COUNT OF RECORDS

<%@ Import Namespace="System.Data.OleDb" %>

<Script Runat="Server"> Sub Page_Load Dim conNorthwind As OleDbConnection Dim cmdSelectCount As OleDbCommand conNorthwind = New OleDbConnection( "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA Source=c:\Employees.mdb") conNorthwind. Open () cmdSelectCount = New OleDbCommand( "Select Count(*) From Authors", conNorthwind ) lblEmp. Text = cmdSelectCount. ExecuteScalar () conNorthwind. Close () End Sub </Script> <html> <body> There are <asp:Label ID="lblEmp" Runat="Server" /> Employees in this Table </body> </html>
Queries Using Parameters

Queries using parameters are performed to make ADO.NET more efficient. A parameter is a value thats either passed in or out of a query. Using parameters helps you to keep your

information straight and makes your queries comprehensible. For example you need to retrieve all employees from a table who works in department no. 10.In this case the SQL query will be: strSql=Select * from employees where deptno=10 This will give a fixed result and the scope will be limited to department number 10. If we want that each record is changed by passing outside parameters the query will be as: strSql=Select * from employees where deptno= & tbDeptno.text This will serve the purpose of building a dynamic query, but an unrecognized one. What if you have three different textboxes? Having them would become difficult for a developer, who is trying to read the code to know as to which box contains which information. How ever, a more efficient method is to use parameters. Let us replace previous query with a parametric one: strSql= Select * from employees where deptno= @deptNo here @deptNo represents the parameter.
Using Parameters with MS Access

When using the classes from the System.Data.OleDb namespace, you need to create the parameters for MS Access. For example, to retrieve a phone number for an employee from the Employees table of Northwind database, you have to write the SQL statement like: Select HomePhone From Employees Where FirstName =? And LastName=? What is Character? This represents the parameter instead of using a named parameter like @firstname or @lastname. Important Note: - (i) Use @ character for SQL SERVER (ii) Use? Or @ character with MS Access. But is? Recommended with MS ACCESS

Example

how you can use parametric queries with a Microsoft Access database.

<%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.OleDb" %> <Script Runat="Server"> Sub Button_Click (s as Object, e As EventArgs) Dim conEmployee As OleDbConnection Dim strSelect As String Dim cmdSelect As OleDbCommand conEmployee = New OleDbConnection( "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA Source=c:\Employees.mdb" ) strSelect = "Select HomePhone From Employees Where FirstName=? And LastName=?" cmdSelect = New OleDbCommand( strSelect, conEmployee ) cmdSelect.Parameters.Add( "@firstname", tbFirstname.Text ) cmdSelect.Parameters.Add( "@lastname", tbLastname.Text ) conEmployee. Open () lblHomePhone. Text = "<b>Home Phone Is</b>&nbsp;" & cmdSelect. ExecuteScalar () conEmployee. Close () End Sub </Script> <html> <body> <form Runat="Server"> <h2>Employee Phone Retrieval</h2> <b>First Name:</b> <br>

<asp:TextBox ID="tbFirstname" Runat="Server" /> <p> <b>Last Name:</b> <br> <asp:TextBox ID="tbLastname" Runat="Server" /> <p> <asp:Button Text="Submit" OnClick="Button_Click" Runat="Server" /> <p> <asp:Label ID="lblHomePhone" Runat="Server" /> </form> </body> </html>

INSERTING RECORDS

We can use INSERT command for inserting the new records in the table. The syntax of this command is: INSERT [into] table_name (column1, column2) VALUES (value1, value2) If we try to write this command for our employees table, we will write it as: INSERT into employees (EmployeeID,FirstName,LastName) VALUES (102, 'John', Greg ) The important steps needed to execute the INSERT command is: 1. Create and open a database connection. 2. Create a database command that represents the SQL Insert statement to execute. 3. Execute the command with the ExecuteNonQuery () method. The following example demonstrates the INSERT command
SqlInsertDemo.aspx

<%@ Import Namespace="System.Data.SqlClient" %> <% Dim conNorthwind As SqlConnection Dim strInsert As String Dim cmdInsert As SqlCommand conNorthwind = New SqlConnection( "Server=localhost;UID=sa;PWD=secret;database=Northwind" ) strInsert = "Insert books ( bookName,Author) Values ('Express AspNet', 'John' )" cmdInsert = New SqlCommand( strInsert, conNorthwind ) conNorthwind. Open () cmdInsert. ExecuteNonQuery () conNorthwind. Close () %>

New book Added!

Inserting record in MS access


<%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.OleDb" %> <Script Runat="Server"> Sub Button_Click (s as Object, e As EventArgs) Dim conNorthwind As OleDbConnection Dim strInsert As String Dim cmdInsert As OleDbCommand conNorthwind = New OleDbConnection( "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA Source=c:\Books.mdb") strInsert = "Insert into Books ( bookName, Author ) Values ( @bkName, @bkAuthor )" cmdInsert = New OleDbCommand( strInsert, conNorthwind ) cmdInsert.Parameters.Add( "@bkName", txtbookName.Text ) cmdInsert.Parameters.Add( "@bkAuthor",txtAuthor.Text) conNorthwind. Open () cmdINsert. ExecuteNonQuery () conNorthwind. Close () End Sub </Script> <html> <body> <form Runat="Server"> <h3>Add New Book Form</h3>

<b>Book's Name:</b> <br> <asp:TextBox ID="txtbookName" Runat="Server" /> <p> <b>Author:</b> <br> <asp:TextBox ID="txtAuthor" Runat="Server" /> <p> <asp:Button Text="Add Books!" OnClick="Button_Click" Runat="Server" /> </form> </body> </html>

Database example 1

<html> <body>

<% set conn=Server.CreateObject("ADODB.Connection") conn.Provider="Microsoft.Jet.OLEDB.4.0" conn.Open(Server.Mappath("sample.mdb")) set rs = Server.CreateObject("ADODB.recordset") rs.Open "Select * from tbl_master ", conn do until rs.EOF for each x in rs.Fields Response.Write(x.Firstname) Response.Write(" = ") Response.Write(x.value & "<br />") next Response.Write("<br />") rs.MoveNext loop rs.close conn.close %> </body> </html> ----<html> <body> <% set conn=Server.CreateObject("ADODB.Connection") conn.Provider="Microsoft.Jet.OLEDB.4.0" conn.Open(Server.Mappath("/db/northwind.mdb")) set rs = Server.CreateObject("ADODB.recordset") rs.Open "SELECT Companyname, Contactname FROM Customers", conn %> <table border="1" width="100%"> <%do until rs.EOF%> <tr> <%for each x in rs.Fields%> <td><%Response.Write(x.value)%></td> <%next rs.MoveNext%> </tr>

<%loop rs.close conn.close %> </table> </body> </html>

<html> <body> <% set conn=Server.CreateObject("ADODB.Connection") conn.Provider="Microsoft.Jet.OLEDB.4.0" conn.Open(Server.Mappath("/db/northwind.mdb")) set rs = Server.CreateObject("ADODB.recordset") sql="SELECT Companyname, Contactname FROM Customers WHERE CompanyName LIKE 'A%'" rs.Open sql, conn %> <table border="1" width="100%"> <tr> <%for each x in rs.Fields response.write("<th>" & x.name & "</th>") next%> </tr> <%do until rs.EOF%> <tr> <%for each x in rs.Fields%> <td><%Response.Write(x.value)%></td> <%next rs.MoveNext%> </tr> <%loop rs.close conn.close %> </table> </body> </html>

Binding a Property of a Control to a DataTable Column


If we want text box tbOrderID to display the OrderID column of of a row in table Orders in dataset mds, we should bind the textboxs Text property to that column: tbOrderID.DataBindings.Add(Text, mds, Orders.OrderID)

ListControls Data Binding


Data binding for a ListControl such as a ComboBox or ListBox is complicated. Four properties needs to be set: 1. DataSource: such as a DataSet; 2. ValueMember: String, the primary key of the source table. Used to look up rows in the table, such as Employees.EmployeeID. 3. DisplayMember: String, the column in the source table that you want to display, can be the same as the ValueMember, or a different column, such as Employees.EmployeeName; 4. SelectedValue: Object, the value to be provided to the ValueMember i.e. the primary key, to look up the row, such as an Orders.EmployeeID of 1447. These properties are need in the following example. Suppose the controls on the form are bound to a record in table Orders, and the combo box is used to display column Orders.EmployeeID, which is a foreign key to table Employees. If we want to provide more convenience to user, so that the combo box displays the name of the employee instead of its ID, then we need to perform a SELECT query on table Employees, to acquire a set of EmployeeName with EmployeeID and put them into a dataset. Then we point the DataSource property of the combo box to this dataset, provide a search criteria such as EmployeeID, and ask the combo box to display the corresponding EmployeeName.
http://progtutorials.tripod.com/ADO_NET.htm#_Toc80517047 http://vb.net-informations.com/ado.net/vb.net-ado.net-tutorial.htm

protected void Button1_Click(object sender, EventArgs e){ if (TxtPassword.Text == TxtRePassword.Text) { //call the method to execute insert to the database

ExecuteInsert(TxtName.Text, TxtUserName.Text, TxtPassword.Text, DropDownList1.SelectedItem.Text, TxtAge.Text, TxtAddress.Text); Response.Write("Record was successfully added!"); ClearControls(Page); } else { Response.Write("Password did not match"); TxtPassword.Focus(); } }

http://www.learnasp.com/freebook/learn/ Example for datagrid use

<%@ Import Namespace="System.Data.OleDb" %> <script language="C#" runat="server"> protected void Page_Load(Object Src, EventArgs E) { OleDbConnection Conn= null; OleDbDataReader Rdr=null; try { string strConn="PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE="; strConn += Server.MapPath (@"\experiments\data\biblio.mdb") + ";"; /* Download data from http://www.learnasp.com/biblio strConn += Server.MapPath (@"\experiments\data\biblio.mdb") + ";"; can be changed to: strConn += Server.MapPath("biblio.mdb") + ";"; */ string strSQL; strSQL="select * from publishers where state='NY'";

Conn=new OleDbConnection(strConn); OleDbCommand Cmd=new OleDbCommand(strSQL,Conn); Conn.Open(); Rdr=Cmd.ExecuteReader(); // -or// Rdr=Cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnectio n) D1.DataSource = Rdr; D1.DataBind(); } // end try catch (Exception exc1) { litExc.Text=exc1.ToString(); } // end catch finally { if (Rdr != null) { if (Rdr.IsClosed==false) {Rdr.Close();} } if (Conn != null) { if (Conn.State==System.Data.ConnectionState.Open) {Conn.Close();} } } // end finally } // end page_load </script> <html><head><title>OLEDB Database Example</title></head> <body bgcolor="#FFFFFF"> <font face="Verdana"><h3>My First Database Sample</h3></font> <asp:literal id="litExc" runat="server" /> <ASP:DataGrid id="D1" runat="server" /> </body></html>

ASP.net 2.0 Master Pages Sampler

<%@ Page Language="VB" masterpagefile="First.master" %> <asp:content runat="server" contentplaceholderID="bodyContents"> <h2>Headline</h2> This is some content<br> Lots of SampleText<br> Text is Good<br> <h3>Now the content is done</h3> </asp:content>

<%@ Master %> <html> <body bgcolor="#FFFFFF"><form runat="server"> <h1>Header for Site</h1> <hr> <Table width="100%"> <tr> <td width="20%" bgcolor="silver"><h1>L<br>e<br>f<br>t</td> <td width="60%"> <asp:contentplaceholder id="bodyContents" runat="server"> Default Content </asp:contentplaceholder> </td> <td width="20%" bgcolor="orange">&nbsp;</td> </table> <h1>Footer for Site</h1> </form></body></html>

Web services

<%@ WebService Language="VBScript" Class="TempConvert" %> Imports System Imports System.Web.Services Public Class TempConvert :Inherits WebService <WebMethod()> Public Function FahrenheitToCelsius (ByVal Fahrenheit As String) As String dim fahr fahr=trim(replace(Fahrenheit,",",".")) if fahr="" or IsNumeric(fahr)=false then return "Error" return ((((fahr) - 32) / 9) * 5) end function <WebMethod()> Public Function CelsiusToFahrenheit (ByVal Celsius As String) As String dim cel cel=trim(replace(Celsius,",",".")) if cel="" or IsNumeric(cel)=false then return "Error" return ((((cel) * 9) / 5) + 32) end function end class

Website <form action='tempconvert.asmx/FahrenheitToCelsius' method="post" target="_blank"> <table> <tr> <td>Fahrenheit to Celsius:</td> <td> <input class="frmInput" type="text" size="30" name="Fahrenheit">

</td> </tr> <tr> <td></td> <td align="right"> <input type="submit" value="Submit" class="button"> </td> </tr> </table> </form> <form action='tempconvert.asmx/CelsiusToFahrenheit' method="post" target="_blank"> <table> <tr> <td>Celsius to Fahrenheit:</td> <td> <input class="frmInput" type="text" size="30" name="Celsius"> </td> </tr> <tr> <td></td> <td align="right"> <input type="submit" value="Submit" class="button"> </td> </tr> </table> </form>

XML in ASP

With the upcoming release of Internet Explorer 5.0, it is much easier to use XML in Web applications. Here is some information on how to harness the power of the updated XML Document Object Model (DOM) on the server to parse and use XML data in ASP applications.
The Need

The ability to parse and use XML on the server provides developers with a whole new world of functionality. As the widespread use of XML increases, so does the need for manipulating XML

on the server. To demonstrate server-side XML in ASP, I will use the syndicated XML version of the Scripting News, a Web site of news and commentary from the cross-platform scripting community ( http://www.scripting.com). I will show how to create a simple ASP page that displays the date of the last issue of the Scripting News and the number of headlines it contains, then I will display all of the current headlines with their corresponding URL links. The Document Object Model The updated XML Document Object Model in Internet Explorer 5.0 (IE 5.0) fully supports the programming interfaces described in the W3C Document Object Model Core (Level 1) recommendation. It also includes a number of new methods for supporting related XML technologies, such as XSL, XSL Pattern Matching, namespaces, data types, and schemas. The DOM is in essence an XML parser; the DOM exposes the XML document as a tree structure that is easy to navigate and use. There are two groups of DOM programming interfaces, as defined by the W3C Core recommendation. The first group defines interfaces that are needed to write applications that use and manipulate XML documents. The second group defines interfaces to assist developers and make it easier to handle XML. This second group of interfaces is for convenience and is not essential for using XML. Using the DOM on the server in an ASP application is quite easy, but requires that IE 5.0 be installed on the server itself. This is necessary due to the number of supporting components installed with IE. Once IE is installed on the server, all you have to do in ASP is create the DOM object as such:

<% Set objXML = Server.CreateObject("Microsoft.XMLDOM") %>

XML on the Server Once you have created the DOM object on the server, you can build your own XML document or load an existing document. When loading a document, you have the option of loading a string of XML text, or opening a XML document and loading the contents. For our example, we will assume that our server has a local copy of the most recent Scripting News XML document. Before loading the document, you should set the async property of the DOM object to "false." This tells the DOM object not to perform an asynchronous download of the XML document. This is important, since immediately after we load the document we are going to start using its contents. If the contents are not all loaded at that time, we may get an error when we try to access it.
<% Set objXML = Server.CreateObject("Microsoft.XMLDOM")

objXML.async = False objXML.Load (Server.MapPath("mostRecentScriptingNews.xml")) %>

Let's look at the actual XML document that we are loading:

<?xml version="1.0"?> <!DOCTYPE scriptingNews SYSTEM "http://www.scripting.com/dtd/scriptingNews.dtd"> <scriptingNews> <header> <copyright>Copyright 1997-1999 UserLand Software, Inc. </copyright> <scriptingNewsVersion>1.0</scriptingNewsVersion> <pubDate>Wed, 03 Mar 1999 08:00:00 GMT</pubDate> <lastBuildDate>Thu, 04 Mar 1999 03:37:03 GMT</lastBuildDate> </header> <item> <text>Wired: A Linux Car Stereo! Wow.</text> <link> <url>http://www.wired.com/news/news/technology/ ... story/18236.html </url> <linetext>A Linux Car Stereo</linetext> </link> </item> ... <item> <text>According to News.com, Hewlett-Packard will offer customers storage and computing on a rental basis. </text> <link> <url>http://www.news.com/News/Item/ ... 0,4,33202,00.html?st.ne.fd.mdh </url> <linetext>According to News.com</linetext> </link> </item> </scriptingNews>

The DOM object exposes a parseError object that contains information about the last parsing error. This object is extremely helpful for debugging and error handling within the ASP page. After loading the XML document, it's a good idea to check the parseError object for any errors before continuing.

<% If objXML.parseError.errorCode <> 0 Then handle the error End If %>

Fortunately, the parseError object provides us with a lot of valuable information about the error: errorCode Property The error code filepos Line linepos reason srcText URL The absolute file position in the XML document containing the error The line number in the XML document where the error occurred The character position in the line containing the error The cause of the error The data where the error occurred The URL of the XML document containing the error Description

In our Scripting News example, the parseError object takes on even greater meaning since the XML document is referencing a Document Type Definition (DTD) file. In this case, not only must the XML document be well formed, it must also be valid against the DTD in order to be error free. It is good practice to always check the parseError object after loading XML. Now that we have a well-formed and valid document in our DOM object, let's look in the document to see what we have. The DOM exposes a number of useful methods to determine exactly what is in an XML document. Because the DOM exposes the contents of the document as a tree of nested nodes (a node consists of an element and any nested subelements), we will actually end up creating a series of node objects in order to manipulate the data. We're going to use the getElementsByTagName method to get a list of the elements, or nodes, in the document. Our first goal is to discover the publishing date for our copy of Scripting News. By examining the DTD we know that this information is stored in the pubDate node. A simple way to access the contents of this node is first to create a node list object of all of the nodes within the XML document, then loop through it until we find the pubDate node. Because the DTD dictates that the pubDate node cannot contain any subnodes, we can use the text property to immediately pull out the contents of the node.
<%

Set objXML = Server.CreateObject("Microsoft.XMLDOM") Set objLst = Server.CreateObject("Microsoft.XMLDOM") objXML.async = False objXML.Load (Server.MapPath("mostRecentScriptingNews.xml")) If objXML.parseError.errorCode <> 0 Then handle the error End If Set objLst = objXML.getElementsByTagName("*") For i = 0 to (objLst.length - 1) If objLst.item(i).nodeName = "pubDate" Then StrDate = objLst.item(i).text Exit For End If Next %>

Notice in the above example we passed an "*" to getElementsByTagName. This returned a node list object containing all of the elements, or nodes, in the document. Because we have the DTD and can gain from it the exact position of the pubDate node, we could have addressed it directly using its item number. However, looping through a document, as we did in the above example, is actually quite efficient since the node list is a collection.

Now that we have the publish date, let's look at how to find the number of headlines in the document. Once again, we can draw from our knowledge of the DTD and recall that the headlines are stored in "item" nodes. There is one item node per headline in the document. We could use another loop, like we did above, and increment a counter each time we encounter an item node. However, there is a better way to retrieve this information, using another method exposed in the DOM. As in the example above, all we need to do is create a node list object containing all of the item nodes. Then we'll use the length property to find out how many nodes are in the node list object or, in other words, the number of headlines in the document.
<% Set objLst = objXML.getElementsByTagName("item") strNoOfHeadlines = objLst.Length %>

Most likely we would also like to display some of this information on our ASP page. The next example shows how we could list the headlines and their URLs in our ASP page by looping through the node list of headlines.
<% Set objXML = Server.CreateObject("Microsoft.XMLDOM")

Set objLst = Server.CreateObject("Microsoft.XMLDOM") Set objHdl = Server.CreateObject("Microsoft.XMLDOM") objXML.async = False objXML.Load (Server.MapPath("mostRecentScriptingNews.xml")) If objXML.parseError.errorCode <> 0 Then handle the error End If Set objLst = objXML.getElementsByTagName("item") noOfHeadlines = objLst.length %> <HTML><BODY> <H1>Scripting News Headlines</H1> <% For i = 0 To (noOfHeadlines - 1) Set objHdl = objLst.item(i) Response.Write("<a href=""" & _ objHdl.childNodes(1).childNodes(0).text & _ """>" & objHdl.childNodes(0).text & _ "</a><br>") Next %> </BODY></HTML>

Conclusion With a little information about the structure of the XML document and by harnessing the power of the DOM, you can easily parse the XML document on the server in ASP and send whatever results you like to the client. This example is browser neutral and would work in almost all Web browsers. Next time I will discuss how to use XSL on the server side to display complex XML documents on the cli

Use of XML to Read


Uses of XML
XML stands for Extensible Markup Language. XML can be used in many ways and one of which is 'data storage'. This is the one we will be exploring in this article. XML along with XSL ( Extensible Stylesheet Language ) can by used to present data on the web pages. XML provides

the data and XSL allows us to present it the way we want. Remember though that not all browsers support XML on the client side, only Micrsoft Internet Explorer 5.0 and above support XML. XML can also be used to perform RPC ( Remote Procedure Call ). Actually this capability of XML to allow communication between distant applications is so strong that Microsoft has developed SOAP ( Simple Object Access Protocol ) specification which uses XML to allow communication between remote applications. XML can be used for a lot more purposes which I haven't mentioned here. Also keep in mind that Microsoft's future .NET platform will make use of XML even more than any tool does today. ASP+, ADO+ and others will use XML to define and present data. So if you are comfortable with XML today, it will help you in the near future when you will be getting yourself ready to develop applications in the revolutionary platform called Microsoft .NET. What are XML files ? If you know HTML then you already know 70% XML. XML is tag based just like HTML. The major difference between HTML and XML is that in XML you can define your own tags while in HTML you make use of pre-defined tags. XML files most often than not begin with following tag on top of the page :
<?xml version="1.0"?>

This line tells the XML parser the version of XML we are using. You for now don't need to change it, just remember to add it on top of every XML page you create. Every starting XML tag should have a corresponding end tag.
<name>Faisal Khan</name>

If you don't want to write end tag then simply add forward slash in the tag like this :
<br/>

Thus <br> tag of HTML will be written as <br/> in XML. Elements The tags in XML are known as 'elements'. 'elements' may or may not contain any content, thus following are all correct :
<name>Faisal Khan</name> <name></name> <name/>

Attributes Attributes are the same name / value pairs that you use in HTML. Elements may or may not contain attributes. Following is an example of an element containing an attribute :
<name language="US-EN">Faisal Khan</name>

This was a very simple and basic introduction to XML, on the next page we will see what is the difference between well formed and valid XML documents. Creating 'Page.xml' file We will now create a simple XML file; 'page.xml'. Open notepad and create a new file 'page.xml' and then copy paste the following code into it :
<?xml version="1.0"?> <main> <title>Our Page.xml file</title> <heading>This is a test heading</heading> <paragraph>This is our paragraph and you can write whatever you want to in this space.</paragraph> <testHTML><![CDATA[We will enclose some HTML code in CDATA section now :<br> <table width="60%" border="1" bordercolor="silver" cellspacing="2" cellpadding="3"> <tr> <td> You can write any HTML code or for that matter any type of text inside the CDATA section without a fear of getting any error.<br><br> Note if we write this without the CDATA tags, the xml parser will raise an error and won't show the document. </td> </tr> </table>]]></testHTML> </main>

There are certain points to be noted in the code above. Notice that after writing the xml version line we have enclosed our three elements (title, heading, paragraph, testHTML) inside a single tag (main). This is so because in XML after the processing instructions (xml version tag in the beginning) all the elements and sub-elements that we define have to be enclosed within a single element whatever you name it. Thus in our case we defined that single element and named it 'main' which encloses our other 4 elements. Notice that in the 'testHTML' tag we have put lot of our normal HTML code. XML parser will raise an error when it encounters HTML code which doesn't abide to XML rules. To get through this we make use of <![CDATA[....]]> markup to tell the XML parser that the following text is character data and should not be parsed and evaluated like other XML data is done. CDATA actually stands for 'character data' and allows any kind of characters / text to be written inside it. So remember that whenever you want to enclose HTML inside your XML elements, enclose it between the CDATA markup tags. Rest of the code is easier to understand. In the first line we defined the processing instruction by telling the XML version to the XML parser. Then we created a 'main' tag element to enclose rest of our XML document. In the 'main' element we created 'title', 'heading', 'paragraph' and 'testHTML' tags to contain some text which will be read by our ASP page.

Creating 'showxml.asp' page We will now create a very simple ASP page and code it to show the XML data that we created in the 'page.xml' file. Open notepad and create a new ASP page. Then copy paste the following code into it and save it :
<% Option Explicit Response.Buffer = True Dim xml Set xml = Server.CreateObject("Microsoft.XMLDOM") xml.async = False xml.load (Server.MapPath("page.xml")) Dim title, heading, paragraph, testHTML title = xml.documentElement.childNodes(0).text heading = xml.documentElement.childNodes(1).text paragraph = xml.documentElement.childNodes(2).text testHTML = xml.documentElement.childNodes(3).text Set xml = Nothing %> <html> <head> <title><%= title %></title> </head> <body> <h3 align="center"><%= heading %></h3> <p align="center"><% = paragraph %></p> <div align="center"><%= testHTML %></div> </body> </html>

Put 'showxml.asp' page in the same directory where you have kept the 'page.xml' file. Explanation :
Dim xml Set xml = Server.CreateObject("Microsoft.XMLDOM")

We create the XML Document Object in the 'xml' variable.


xml.async = False

By setting '.async' option to False, we are saying to the XML parser to show the data as soon as it begins to read it. Note that by setting '.async' to False, retrieving of XML data is speeded up.
xml.load (Server.MapPath("page.xml")

Next we load the 'page.xml' file. The 'load()' method asks for complete physical path to the XML file. We give it the complete physical path by using 'Server.MapPath' method to convert the relative path to complete physical path.

Dim title, heading, paragraph, testHTML title = xml.documentElement.childNodes(0).text heading = xml.documentElement.childNodes(1).text paragraph = xml.documentElement.childNodes(2).text testHTML = xml.documentElement.childNodes(3).text

Example Xml file (items.xml)


<?xml version="1.0" ?> <Items> <FoodItems> <Food> Toast </Food> <Price> 14.45 </Price> </FoodItems> <FoodItems> <Food> Noodles </Food> <Price> 30.00 </Price> </FoodItems> <FoodItems> <Food> Pepsi </Food>

<Price> 20.00 </Price> </FoodItems> </Items>

Aspx file
<%@ Import Namespace="System.Data" %> <Script Runat="Server"> Sub Page_Load Dim dstMenu As DataSet dstMenu = New DataSet() dstMenu.ReadXml(MapPath("items.xml")) dgrdMenu.DataSource = dstMenu dgrdMenu.DataBind () End Sub </Script> <html> <head><title>ReadItems.aspx</title></head> <body> <asp:DataGrid ID="dgrdMenu" cellpadding="10" Runat="Server" /> </body> </html>

Você também pode gostar