1 / 55

ASP.NET Rina Zviel-Girshin Lecture 6

ASP.NET Rina Zviel-Girshin Lecture 6. Overview. DataGrid XML XSD XML and DataSet System.Xml XmlDataDocument XmlReader/XmlWriter. Display Controls. In ASP.NET exists a set of controls called “ display controls ”. These controls are

tex
Download Presentation

ASP.NET Rina Zviel-Girshin Lecture 6

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. ASP.NET Rina Zviel-Girshin Lecture 6

  2. Overview • DataGrid • XML • XSD • XML and DataSet • System.Xml • XmlDataDocument • XmlReader/XmlWriter Rina Zviel-Girshin @Paralex

  3. Display Controls • In ASP.NET exists a set of controls called “display controls”. • These controls are • asp:Repeater (not at our course – uses Templates), • asp:DataList, • and asp:DataGrid. • The main purpose of these controls is displaying information from database tables and other external data stores to the screen. Rina Zviel-Girshin @Paralex

  4. DataGrid • The DataGrid control is the most complex and powerful of the controls used to display and maintain sets of data. • It has near a 100 properties, methods and events (more during tirgul). • The DataGrid displays a tabular data (data organized into rows and columns) from the data source or renders a table containing the SQL data. Rina Zviel-Girshin @Paralex

  5. Example Rina Zviel-Girshin @Paralex

  6. DataGrid.aspx <%@ Page Language="C#"%> <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SqlClient" %> <script runat="server"> protected void Page_Load(Object sender, EventArgs e) { SqlConnection con = new SqlConnection("Server=localhost;uid=sa; database=pubs" ); SqlDataAdapter myCommand = new SqlDataAdapter("select * from Authors", con); DataSet ds = new DataSet(); myCommand.Fill(ds, "Authors"); MyDataGrid.DataSource=ds.Tables["Authors"].DefaultView; MyDataGrid.DataBind(); } </script> Rina Zviel-Girshin @Paralex

  7. DataGrid.aspx <html><head><title>DataGrid basic example</title></head> <body> <h3><font face="Verdana">Simple Select to a DataGrid Control </font></h3> <asp:DataGrid id="MyDataGrid" runat="server" Width="700" BackColor="#ccccff" BorderColor="black" ShowFooter="false" CellPadding=3 Font-Name="Verdana" Font-Size="8pt" HeaderStyle-BackColor="#aaaadd" EnableViewState="false" /> </body> </html> Rina Zviel-Girshin @Paralex

  8. Data Source • To specify the data source for the DataGrid you have to perform the following operations: MyDataGrid.DataSource=ds.Tables["Authors"].DefaultView; MyDataGrid.DataBind(); • Or an alternative syntax is to specify both a DataSource and a DataMember from the DataSet to be used: MyDataGrid.DataSource=ds; MyDataGrid.DataMember="Authors"; MyDataGrid.DataBind(); Rina Zviel-Girshin @Paralex

  9. Columns • The DataGrid automatically displays data in a table format (grid layout) . • A first row in the DataGrid is a row of column headings. It is generated from the column names in the data source. MyDataGrid.DataSource=ds.Tables["Authors"].DefaultView; //display all the columns • The number of columns in DataGrid object equals to the number of columns in the data source. Rina Zviel-Girshin @Paralex

  10. Columns display • A DataGrid permits selections of data columns for display. • In order to select which columns to display, first specify AutoGenerateColumns="False" for the grid. • Then add a <Columns> section in the control. • In this section an <asp:BoundColumn> control is added for each column to be displayed. • This bound column binds to a column of the data source with the DataField="ColumnName" property setting. Rina Zviel-Girshin @Paralex

  11. Example <asp:DataGrid id="ProductGrid" runat="server"  AutoGenerateColumns="False"    >  <Columns>    <asp:BoundColumn      DataField=“au_fname"      HeaderText=“Author’s Family Name"      />    <asp:BoundColumn      DataField=“au_id"      HeaderText=“Author’s ID*"      ItemStyle-HorizontalAlign="Right"      FooterText="*The Id is written in XXX-XX-XXXX format"      FooterStyle-Font-Size="7pt"      />  </Columns></asp:DataGrid> Rina Zviel-Girshin @Paralex

  12. Some DataGrid properties • You can use property="value" settings to define DataGrid’slayout and styles. • Width="700“ – table’s width in pixel or % • BackColor="#ccccff" – table cells background color • BorderColor="black" – border color • BorderWidth="1"– border’s width in pixel • CellPadding=3 – amount of space (in pixels) between cell’s border and contents • CellSpacing="0” - amount of space (in pixels) between columns. Default is 0. • ShowFooter="false" – does not display table’s footer • Font-Name="Verdana" Font-Size="8pt" - defines font family • And more… Rina Zviel-Girshin @Paralex

  13. EnableViewState • EnableViewState property gets and sets a value indicating whether the server control persists its view state. • The default value is true. • That means the DataGrid stores all of its data when maintaining state and in each request all information is sent through a round trip with the form posts. • To improve the performance of your pages turn this property off. EnableViewState=“false” Rina Zviel-Girshin @Paralex

  14. XML and the DataSet • DataSet can read/write XML for its data and/or schema • You can create or modify data in a DataSet using XML file stream • You can create or modify the DataSets schema using XML schema. • XML-related DataSet methods for reading: • ReadXml: Reads an XML schema and data into the DataSet • ReadXmlSchema (xsd file): Reads an XML schema into the DataSet. • And for writing: • WriteXml, WriteXmlSchema • GetXml, GetXmlSchema Rina Zviel-Girshin @Paralex

  15. Example <%@ Page Language="C#" %> <%@ Import Namespace="System.Data" %> <script runat=server> void Page_Load(Object sender , EventArgs e) { DataSet ds = new DataSet(); ds.ReadXml(“C:\Menu.xml" ); dgrd.DataSource = ds; dgrd.DataBind(); } </script> <html><head><title>ReadXMLExample.aspx</title></head><body> <asp:DataGrid ID="dgrd" cellpadding="10" runat="server" /> </body></html> Rina Zviel-Girshin @Paralex

  16. XML • XML stands for eXtensible Markup Language. • XML is a markup language much like HTML, but its purpose is to describe data(not to display data like HTML). • XML like HTML has tags, attributes and values. • The difference is that you can define your own new tags. • You can use XML to create your own Markup Language and later use it to markup (format) your documents. Rina Zviel-Girshin @Paralex

  17. XML usage • XML is a text-based language that stores data in a way that also describes the structure of the data. • It provides a consistent format for data that can be passed easily • between applications • and across networks • and the Internet. • XML is a common data format. • Many other applications use it for configuration files. Rina Zviel-Girshin @Paralex

  18. XML data format • Visual Studio. NET uses XML as the format for storing data records, communicating, and sharing data. • XML is the native data format for ADO.NET DataSets. • The underlying fields and records in the disconnected dataset are stored as XML. • XML is optimized for sharing data across the Internet. • Office XP stores data as XML. Rina Zviel-Girshin @Paralex

  19. Some facts • Exists since 1998. • XML does not do anything. • Not owned by any one company. • An open standard. • Can represent almost any kind of data. • Supports sophisticated integrity constraints. • Simple XML documents are human-readable. • Easily converted to other formats. Rina Zviel-Girshin @Paralex

  20. XML tags/elements • XML is case-sensitive (there is a difference between upper and lowercase letters). • <Author> and <author> are two different XML tags. • You can define your own tags, called elements. • Elements naming: • Names can contain letters, numbers, and other characters, can be in any language (not advisable). • Names must not start with a number or punctuation character. • Names must not start with the letters xml (or XML or Xml or any other combination of xml). • Names cannot contain spaces. Rina Zviel-Girshin @Paralex

  21. XML File • An XML file is an ASCII text file with XML markup tags. • It has a .xml extension. • Example:myfile.xml • An XML file contains a declaration that announces that this is an XML file. • Example:<?xml version="1.0"?> • An XML file contains a content marked up with XML tags. Rina Zviel-Girshin @Paralex

  22. Example <?xml version="1.0"?> <course_info> <instructor> <iname>Rina</iname> <fname>Zviel-Girshin</fname> </instructor> <course> <cname>Web_System Development</cname> <max_st_number>20</max_st_number> <hours>3 hours a week</hours> </course> </course_info> Rina Zviel-Girshin @Paralex

  23. Inner nodes • XML inner nodes can have the same structure or can have a different structure. • Example: <instructor> and <course> • Inner nodes can have children. • Every node can have attributes. • Attribute values are quoted " or '.  • Example: <ingredient quantity="2“ units="cups">flour</ingredient> Rina Zviel-Girshin @Paralex

  24. XSD • The XML Schema language is also referred to as XML Schema Definition (XSD). • The purpose of an XML Schema is to define the legal building blocks of an XML document or to validate XML file structure. • XML Schemas are written in XML (no need to learn another new syntax and you can operate on your schemas with XML tools.). • Defines a class of documents. • Individual documents (instances) can conform to a given schema. Rina Zviel-Girshin @Paralex

  25. An XML Schema • Defines elements that can appear in a document. • Defines attributes that can appear in a document. • Defines • which elements are child elements • the order of child elements • the number of child elements • Defines whether an element is empty or can include text. • Defines data types for elements and attributes. • Defines default and fixed values for elements and attributes. Rina Zviel-Girshin @Paralex

  26. XSD file • XML Schemas are extensible to future additions • XSD Schemas support data types. • XML Schemas support namespaces. • XML Schema file has a .xsd extension. • The file defines the elements of the legal XML document. • The file starts with an <?xml version="1.0“?> prolog. • The <schema> element is the root element of every XML Schema: <xs:schema and some attributes>. Rina Zviel-Girshin @Paralex

  27. Example Student.xsd <?xml version="1.0" encoding="UTF-8"?> <xsd:schemaxmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:elementname=“Student"> <xsd:complexType> <xsd:sequence> <xsd:elementname="first_name" type="xsd:string"/> <xsd:elementname="last_name" type="xsd:string"/> <xsd:elementname="id" type="xsd:integer"/> </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:schema> Rina Zviel-Girshin @Paralex

  28. Methods of Reading and Writing XML // Code for creating the DataSet ds and loading the // DataSet from a data source not shown. DataSet ds; … String oFile = “C:\Rina\myXmlOutput.xsd”; String iFile = “C:\Rina\myXmlInput.xsd”; // Write the DataSet’s XMLSchema to an XML Document ds.WriteXmlSchema( oFile ); // Read/Upload XML Data into the DataSet ds.ReadXml( iFile); // Write the existing Data to an XML Document ds.WriteXml( "C:\Rina\myXMLData.xml", XmlWriteMode.DiffGram); XmlWriteMode.DiffGram: writes the entire DataSet original and current values. Rina Zviel-Girshin @Paralex

  29. XML document and data table • XML files are hierarchical data structures they can be treated as database tables. • For this purpose the xml file should be limited to a three-level hierarchy: • Table name • Rows • columns Rina Zviel-Girshin @Paralex

  30. customer city phone street levi tell-aviv 039876543 namir Customers table avivi eilat 056999999 shushanim cohen haifa 048294444 prahim Example <?xml version=“1.0”?> <customers> <row> <customer>levi</customer> <city>tell-aviv</city> <phone>039876543</phone> <street>namir</street> </row> <row> <customer>avivi</customer> <city>eilat</city> <phone>056999999</phone> <street>shushanim</street> </row> … </customers> The resulting XML document: Rina Zviel-Girshin @Paralex

  31. XML with DataSets • A DataSet can be used to represent XML data. • A DataSet can represent XML data in two ways: • Load XML directly into a DataSet • ds.ReadXml(somefile); • Build an XmlDataDocument class from an existing DataSet • ds.ReadXml(somefile); • XmlDataDocument xdd= new XmlDataDocument (ds); Rina Zviel-Girshin @Paralex

  32. Reading an XML file to a DataSet <%@ Page Language="C#" %> <%@ Import Namespace="System.Data" %> <script runat=“server”> void Page_Load(Object sender , EventArgs e) { DataSet ds= new DataSet(); ds.ReadXml( MapPath( “Customers.xml" ) ); dgrd.DataSource = ds; dgrd.DataBind(); } </script> <html><head><title>ReadXmlFile.aspx</title></head> <body><asp:DataGrid ID="dgrd" cellpadding="10" runat="server" /> </body></html> Rina Zviel-Girshin @Paralex

  33. Output <?xml version="1.0"?> <customers> <row> <customer>Levi</customer> <city>Tell-Aviv</city> <phone>039876543</phone> <street>Namir</street> </row> <row> <customer> Avivi</customer> <city>Eilat</city> <phone>056999999</phone> <street>Shushanim</street> </row> <row> <customer> Cohen</customer> <city>Haifa</city> <phone>048294444</phone> <street>Prahim</street> </row> </customers> Rina Zviel-Girshin @Paralex

  34. ReadXml DataSet ds= new DataSet(); ds.ReadXml( MapPath( “Customers.xml" ) ); • A DataSet object is created. • ReadXml() method is used to read Customers.xml file from the hard drive to this ds object. • MapPath() method or more correctly Page.MapPath() method returns a physical path that a virtual path maps to. • A ds object is bound to the DataGrid and displayed. Rina Zviel-Girshin @Paralex

  35. Using a Schema • In last example a DataSet object guesses the structure of XML document. • Checked is the elements under the root can be presented as tables. • If not checks if it is a single table. • All elements presented as strings. • A best practice is to include the schema to match the xml file. Rina Zviel-Girshin @Paralex

  36. Adding a Schema • You specify a schema with an XML file in the following ways: • include the schema into the same file (schema and data) • include schema’s name in prolog section of the document • Read the schema separately using ReadXmlSchema() method of a DataSet. Rina Zviel-Girshin @Paralex

  37. Example <%@ Page Language="C#" %> <%@ Import Namespace="System.Data" %> <script runat=“server”> void Page_Load(Object sender , EventArgs e) { DataSet ds= new DataSet(); ds.ReadXmlSchema( MapPath( " Customers.xsd" ) ); ds.ReadXml( MapPath( " Customers.xml" ) ); dgrd.DataSource = ds; dgrd.DataBind(); } </script> Rina Zviel-Girshin @Paralex

  38. Example <html> <head><title>ReadSchema.aspx</title></head> <body> <asp:DataGrid ID="dgrd" cellpadding="10" runat="server" /> </body></html> Rina Zviel-Girshin @Paralex

  39. Writing an XML from a DataSet • To retrieve a string representation of Xml data GetXml() method of the DataSet can be used. • String strxml=ds.GetXml(); • This method retrieves both: the XML data and the XML schema for the DataSet. • To retrieve only a schema you can use GetXmlSchema() method. Rina Zviel-Girshin @Paralex

  40. Example <%@ Page Language="C#" %> <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SqlClient" %> <script runat=server> void Page_Load(Object sender , EventArgs e) { DataSet ds = new DataSet(); SqlConnection con = new SqlConnection("Server=localhost;uid=sa; database=pubs" ); SqlDataAdapter da = new SqlDataAdapter( "Select * From authors", con); da.Fill( ds, “DlastName" ); //name of DataMember string strXml = ds.GetXml(); Response.Write( "<pre>" + Server.HtmlEncode( strXml) + "</pre>" ); }</script> Rina Zviel-Girshin @Paralex

  41. Writing to an Xml file or a Stream • An XML representation of the DataSet can be written to a stream using: • WriteXml() method of the DataSet • WriteXmlSchema() method of the DataSet. • You can choose the output stream and the writing mode: • DiffGram – writes Xml data in such way that it can be uploaded to Sql200Server using UpdateGram method • IgnoreSchema – writes an xml data without including the schema • WriteSchema – (the default) writes both the xml data and the schema Rina Zviel-Girshin @Paralex

  42. Example <%@ Page Language="C#" %> <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SqlClient" %> <script runat=“server”> void Page_Load(Object sender , EventArgs e) { string strXml; DataSet ds = new DataSet(); SqlConnection con = new SqlConnection("Server=localhost;uid=sa; database=pubs" ); SqlDataAdapter da = new SqlDataAdapter( "Select * From authors ", con); da.Fill( ds, “DlastName" ); //name of DataMember ds.WriteXml( Response.OutputStream, XmlWriteMode.IgnoreSchema ); }</script> Writes an XML representation of the DataSet to the Response object OutputStream. Rina Zviel-Girshin @Paralex

  43. System.Xml namespace In .NET exist a group of classes that can be used to process XML data System.Xml XmlDocument XmlReader XmlWriter XmlElement XmlNodeReader XmlAttribute XmlDataDocument XmlTextReader XmlTextWriter and more Rina Zviel-Girshin @Paralex

  44. XmlDataDocument • The ADO.NET DataSet provides you with a relational representation of data (tables). • Sometimes a tree representation of the DataSet can be useful. • For hierarchical data access, you can use the XmlDataDocument class of .NET. • The DataSet can be associated with an XmlDataDocument by adding a DataSet name in the constructor of an XmlDataDocument object. • XmlDataDocument xdd = new XmlDataDocument( ds ); Rina Zviel-Girshin @Paralex

  45. Example <%@ Page Language="C#" %> <%@ import Namespace="System.Data" %> <%@ import Namespace="System.Xml" %> <script runat="server"> void Page_Load(Object sender , EventArgs e) { DataSet ds =new DataSet(); ds.ReadXml( MapPath( "Customers.xml" ) ); XmlDataDocument xdd = new XmlDataDocument( ds ); XmlNodeList nl = xdd.GetElementsByTagName("customer"); for( int i=0; i< nl.Count; i++) { lblOutput.Text += nl[i].InnerXml; } } </script> Rina Zviel-Girshin @Paralex

  46. Example <html><head> <title>XmlDataDocument.aspx</title> </head> <body> <h2>All Customers </h2> <asp:Label id="lblOutput" Runat="Server"></asp:Label> </body></html> Rina Zviel-Girshin @Paralex

  47. DataReader DataAdapter SqlData- Reader SqlData- Adapter OleDbData- Reader OleDbData- Adapter A DataSet associated with an XmlDataDocument XmlData-Document DataSet Sync XmlReader XmlText- Reader XmlNode- Reader .NET Data Provider Rina Zviel-Girshin @Paralex

  48. XmlTextReader • An XmlTextReader class provides a fast forward only access to the raw data contained in XML document. • Example: XmlTextReader xmltr; xmltr = new XmlTextReader("MyFile.xml"); while(xmltr.Read()) { …processing… } Rina Zviel-Girshin @Paralex

  49. XmlTextWriter • An XmlTextWriter class provides a fast forward only method to write data to an Xml file. • The resulting XML file conforms to the W3C XML version 1.0 and the Namespaces in XML specifications. • To create an XmlTextWriter object a constructor with file straem name or object and encoding type should be used. • Example: • XmlTextWriter xmltw = new XmlTextWriter (“stam.xml", Encoding.Unicode); Rina Zviel-Girshin @Paralex

  50. XmlTextWriter methods • The most important methods are: • WriteStartDocument() - is called to start creating an XML document. This will create the first line in the XML document (a prolog). • WriteStartElement(string) - this method creates a new element in the XML document with the name specified by the string input parameter. (You can also specify a namespace as a second, optional string parameter.) • WriteEndElement() - this method closes off the element created in the WriteStartElement(string) method call. Rina Zviel-Girshin @Paralex

More Related