c# Database

download c# Database

of 37

Transcript of c# Database

  • 8/2/2019 c# Database

    1/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 orclick a link on a Web page, you're asking aWeb hosting serveron 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 processingstep 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 server-

    side 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 ( ) brackets, they typically start with . 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.

    http://www.webhostingsearch.com/http://www.webhostingsearch.com/http://www.webhostingsearch.com/http://www.webhostingsearch.com/
  • 8/2/2019 c# Database

    2/37

    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:

    at the point where you want it to appear. When you view the page in your browser, you shouldsee 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" parttells the server, "Get me the date." The equal sign (=) tells the server to display the date in the

    Web page. If you typed just:

    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:

    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:

    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

  • 8/2/2019 c# Database

    3/37

    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 thefollowing formatting functions.

    Month and Monthname

    To display the number of the current month in a Web page, type:

    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:

    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, youcan 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.

    Asking for information

    Your name:

    Your email:

    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

  • 8/2/2019 c# Database

    4/37

    Responding to a form

    Your name is

    Your email is

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

    wherefieldname 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. Forexample, 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:

    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 . Do you want to see ?.

    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

    Name and Color

    Let me know your Name and Favorite Color:

    YOUR NAME:

    COLOR:

  • 8/2/2019 c# Database

    5/37

    Red

    Green

    Blue

    Now, create an ASP file ("nameandcolor.asp") and cut-and-paste the following text into it.

    Name and Color

    Hi, .
    I know your favorite color is

    red

    green

    blue

    .

    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.

  • 8/2/2019 c# Database

    6/37

    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

    Hello

    END

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

    The For...Next instruction allows to define the value of the increment.

    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 :

  • 8/2/2019 c# Database

    7/37

    Or

    "Hello World!"

    Data base

    Example 2

    protectedvoid Page_Load(Object s, EventArgs e){lblBegin.Visible=false;}

    protectedvoid Welcome_Click(Object s,EventArgs e){lblBegin.Visible=true;lblBegin.Text="You have registered. Thanks!";}

    protectedvoid Leave_Click(Object s,EventArgs e){

    lblBegin.Visible=true;lblBegin.Text="You have left. Thanks!";}

    TextBoxes

    First Name

  • 8/2/2019 c# Database

    8/37

    Last Name

    Email Address

    USE OF DATA BASE

    Sub Page_Load (s As Object, e As EventArgs )

    Dim conAuthors As OleDbConnection

  • 8/2/2019 c# Database

    9/37

    conAuthors=NewOleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA

    Source=c:\employees.mdb" )

    conAuthors.Open()

    End Sub

    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 toconnect 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 aMicrosoft Access databases named employees.

    Example18 OpenOleDbConnection.aspx

    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

    Connection has been opened!

  • 8/2/2019 c# Database

    10/37

    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 stringappropriate 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, toallow 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

  • 8/2/2019 c# Database

    11/37

    The SQL statement that will be used most often in ASP.NET pages is Select. The Selectstatement 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

  • 8/2/2019 c# Database

    12/37

    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

    EXAMPLE TO GET COUNT OF RECORDS

  • 8/2/2019 c# Database

    13/37

    Sub Page_Load

    Dim conNorthwind As OleDbConnection

    Dim cmdSelectCount As OleDbCommand

    conNorthwind = New OleDbConnection( "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATASource=c:\Employees.mdb")

    conNorthwind. Open ()

    cmdSelectCount = New OleDbCommand( "Select Count(*) From Authors", conNorthwind )

    lblEmp. Text = cmdSelectCount. ExecuteScalar ()

    conNorthwind. Close ()

    End Sub

    There are

    Employees in this Table

    Queries Using Parameters

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

  • 8/2/2019 c# Database

    14/37

    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 wantthat 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 theEmployees 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.

  • 8/2/2019 c# Database

    15/37

    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;DATASource=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 = "Home Phone Is" & cmdSelect. ExecuteScalar ()

    conEmployee. Close ()

    End Sub

    Employee Phone Retrieval

    First Name:


  • 8/2/2019 c# Database

    16/37

    Last Name:


    INSERTING RECORDS

  • 8/2/2019 c# Database

    17/37

    We can use INSERT command for inserting the new records in the table. The syntax of thiscommand 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

  • 8/2/2019 c# Database

    18/37

    New book Added!

    Inserting record in MS access

    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

    Add New Book Form

  • 8/2/2019 c# Database

    19/37

    Book's Name:


    Author:


    Database example 1

  • 8/2/2019 c# Database

    20/37

    -----

  • 8/2/2019 c# Database

    21/37

  • 8/2/2019 c# Database

    22/37

    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 indataset 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, sothat 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 andput 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

    http://progtutorials.tripod.com/ADO_NET.htm#_Toc80517047http://progtutorials.tripod.com/ADO_NET.htm#_Toc80517047http://vb.net-informations.com/ado.net/vb.net-ado.net-tutorial.htmhttp://vb.net-informations.com/ado.net/vb.net-ado.net-tutorial.htmhttp://vb.net-informations.com/ado.net/vb.net-ado.net-tutorial.htmhttp://progtutorials.tripod.com/ADO_NET.htm#_Toc80517047
  • 8/2/2019 c# Database

    23/37

    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

    protectedvoid Page_Load(Object Src, EventArgs E)

    {

    OleDbConnection Conn= null;OleDbDataReader Rdr=null;

    try{

    string strConn="PROVIDER=Microsoft.Jet.OLEDB.4.0;DATASOURCE=";

    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'";

  • 8/2/2019 c# Database

    24/37

    Conn=new OleDbConnection(strConn);OleDbCommand Cmd=new OleDbCommand(strSQL,Conn);Conn.Open();Rdr=Cmd.ExecuteReader();// -or-

    //Rdr=Cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection)

    D1.DataSource = Rdr;D1.DataBind();

    } // end trycatch (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

    OLEDB Database ExampleMy First Database Sample

    ASP.net 2.0 Master Pages Sampler

    http://www.learnasp.com/freebook/partners/da/tall.aspxhttp://www.learnasp.com/freebook/partners/da/tall.aspx
  • 8/2/2019 c# Database

    25/37

    HeadlineThis is some content
    Lots of SampleText

    Text is Good
    Now the content is done

    Header for Site

    L
    e
    f
    t

    Default Content

    Footer for Site

  • 8/2/2019 c# Database

    26/37

    Web services

    Imports System

    Imports System.Web.Services

    Public Class TempConvert :Inherits WebService

    Public Function FahrenheitToCelsius

    (ByVal Fahrenheit As String) As Stringdim fahr

    fahr=trim(replace(Fahrenheit,",","."))

    if fahr="" or IsNumeric(fahr)=false then return "Error"

    return ((((fahr) - 32) / 9) * 5)

    end function

    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

    Fahrenheit to Celsius:

  • 8/2/2019 c# Database

    27/37

    Celsius to Fahrenheit:

    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 XMLDocument 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 offunctionality. As the widespread use of XML increases, so does the need for manipulating XML

  • 8/2/2019 c# Database

    28/37

    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 scriptingcommunity ( 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 theW3C Document Object Model Core (Level 1)

    recommendation. It also includes a number of new methods for supporting related XMLtechnologies, 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 useand 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 beinstalled on the server itself. This is necessary due to the number of supporting componentsinstalled with IE. Once IE is installed on the server, all you have to do in ASP is create the DOM

    object as such:

    XML on the Server

    Once you have created the DOM object on the server, you can build your own XML documentor 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 accessit.

  • 8/2/2019 c# Database

    29/37

    objXML.async = False

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

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

    Copyright 1997-1999 UserLand Software, Inc.1.0

    Wed, 03 Mar 1999 08:00:00 GMT

    Thu, 04 Mar 1999 03:37:03 GMTWired: A Linux Car Stereo! Wow.

    http://www.wired.com/news/news/technology/ ...

    story/18236.htmlA Linux Car Stereo

    ...According to News.com, Hewlett-Packard will offer

    customers storage and computing on a rental basis.

    http://www.news.com/News/Item/ ...0,4,33202,00.html?st.ne.fd.mdh

    According to News.com

    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.

  • 8/2/2019 c# Database

    30/37

    Fortunately, the parseError object provides us with a lot of valuable information about the error:

    errorCode

    Property Description

    The error code

    filepos The absolute file position in the XML document containing the error

    Line The line number in the XML document where the error occurred

    linepos The character position in the line containing the error

    reason The cause of the error

    srcText The data where the error occurred

    URL The URL of the XML document containing the error

    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 onlymust 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 thedocument 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 touse 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 examiningthe 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 thatthe pubDate node cannot contain any subnodes, we can use the text property to immediately pull

    out the contents of the node.

  • 8/2/2019 c# Database

    31/37

    Set objXML = Server.CreateObject("Microsoft.XMLDOM")Set objLst = Server.CreateObject("Microsoft.XMLDOM")objXML.async = FalseobjXML.Load (Server.MapPath("mostRecentScriptingNews.xml"))If objXML.parseError.errorCode 0 Then

    handle the errorEnd If

    Set objLst = objXML.getElementsByTagName("*")

    For i = 0 to (objLst.length - 1)

    If objLst.item(i).nodeName = "pubDate" ThenStrDate = objLst.item(i).textExit For

    End If

    Next%>

    Notice in the above example we passed an "*" to getElementsByTagName. This returned a node listobject 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 thedocument. Once again, we can draw from our knowledge of the DTD and recall that theheadlines 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 methodexposed in the DOM.

    As in the example above, all we need to do is create a node list object containing all of the itemnodes. 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.

    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.

  • 8/2/2019 c# Database

    32/37

    Set objLst = Server.CreateObject("Microsoft.XMLDOM")Set objHdl = Server.CreateObject("Microsoft.XMLDOM")

    objXML.async = FalseobjXML.Load (Server.MapPath("mostRecentScriptingNews.xml"))

    If objXML.parseError.errorCode 0 Thenhandle the error

    End If

    Set objLst = objXML.getElementsByTagName("item")

    noOfHeadlines = objLst.length%>

    Scripting News Headlines

    Conclusion

    With a little information about the structure of the XML document and by harnessing the powerof 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 XMLXML stands for Extensible Markup Language. XML can be used in many ways and one ofwhich 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

  • 8/2/2019 c# Database

    33/37

    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 supportXML. 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 Ihaven'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 futurewhen 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 whilein HTML you make use of pre-defined tags. XML files most often than not begin with following

    tag on top of the page :

    This line tells the XML parser the version of XML we are using. You for now don't need tochange it, just remember to add it on top of every XML page you create.

    Every starting XML tag should have a corresponding end tag.

    Faisal Khan

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


    Thus
    tag of HTML will be written as
    in XML.

    ElementsThe tags in XML are known as 'elements'. 'elements' may or may not contain any content, thus

    following are all correct :

    Faisal Khan

    AttributesAttributes 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 :

    Faisal Khan

  • 8/2/2019 c# Database

    34/37

    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 :

    Our Page.xml fileThis is a test headingThis is our paragraph and you can write whateveryou want to in this space.

    :
    You can write any HTML code or for that matter any type of text insidethe CDATA section without a fear of getting any error.

    Note if we write this without the CDATA tags, the xml parser willraise an error and won't show the document.

    ]]>

    There are certain points to be noted in the code above. Notice that after writing the xml versionline 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 thebeginning) 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 willraise an error when it encounters HTML code which doesn't abide to XML rules. To get through

    this we make use of 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. CDATAactually 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.

  • 8/2/2019 c# Database

    35/37

    Creating 'showxml.asp' page

    We will now create a very simple ASP page and code it to show the XML data that we created inthe 'page.xml' file. Open notepad and create a new ASP page. Then copy paste the following

    code into it and save it :

    Put 'showxml.asp' page in the same directory where you have kept the 'page.xml' file.

    Explanation :

    Dim xmlSet 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 itbegins 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 XMLfile. We give it the complete physical path by using 'Server.MapPath' method to convert therelative path to complete physical path.

  • 8/2/2019 c# Database

    36/37

    Dim title, heading, paragraph, testHTMLtitle = xml.documentElement.childNodes(0).textheading = xml.documentElement.childNodes(1).textparagraph = xml.documentElement.childNodes(2).texttestHTML = xml.documentElement.childNodes(3).text

    Example

    Xml file (items.xml)

    Toast

    14.45

    Noodles

    30.00

    Pepsi

  • 8/2/2019 c# Database

    37/37

    20.00

    Aspx file

    Sub Page_Load

    Dim dstMenu As DataSet

    dstMenu = New DataSet()

    dstMenu.ReadXml(MapPath("items.xml"))

    dgrdMenu.DataSource = dstMenu

    dgrdMenu.DataBind ()

    EndSub

    ReadItems.aspx