ASP.NET Server Controls
description
Transcript of ASP.NET Server Controls
ASP.NET Server Controls
ASP.NET
Some Additional ASP.NET Controls …Some Additional ASP.NET Controls …
• XML• AdRotator• Calendar• File UploadFile Upload
XML Technologies (Page 1)XML Technologies (Page 1)
• Extensible Markup Language (XML) – Like HTML, is a markup language that provides access
to structured content
– Not limited to a predefined set of tags or to being displayed in a browser
– Sort of a "combination of HTML and database"—developer defines tag style elements
– Can be shared across applications, file systems, and operating systems
• XML standards maintained by the W3C (World Wide Web Consortium)
XML Technologies (Page 2)XML Technologies (Page 2)
XSL Transformations (XSLT) A language for transforming (formatting) XML
documents XSLT stylesheets
Stylesheets format XML documents Use XSLT to interact with an XML document Can format individual or groups of elements within the
XML document A form of XSL that transforms the XML data using
processing rules in the XSLT stylesheet
XML TechnologiesXML Technologies
Well-Formed XML DocumentsWell-Formed XML Documents
• An XML document must be well-formed (follow XML standards):– One root element—all other elements must be nested
within it—do not mix nesting elements:• Incorrect:
<b>Welcome to <i>Tara Store</b></i>• Correct:
<b>Welcome to <i>Tara Store</i></b>• Always enclose attribute values within quotes, i.e.
<p align = "center">• Case sensitive—opening and closing tags must match
The Prologue (Page 1)The Prologue (Page 1)
• The first section of an XML document<?xml version="1.0" encoding="utf-8" ?>
• Continues global information such as XML version, formatting information, and schema definitions– The "?" character indicates this statement is a
processing instruction and does not contain data
– The character-encoding property (values are UTF-8 or UTF-16), which describes any coding algorithms, is optional
Open products.xmlOpen products.xml
The Prologue (Page 2)The Prologue (Page 2)
• An additional, optional statement may be included which references a CSS stylesheet or an XSLT file (an XML stylesheet) to format the XML document<?xml:stylesheet type="text/css" href="taragifts.css" ?>
The XML Body (Page 1)The XML Body (Page 1)
• Complies with the XML DOM (Document Object Model) standards– XML documents must have a logical structure
– The root element (node) must nest all the elements and the data
• Root node can contain many other elements
• All tags must be nested within the root node
• Root node is a container element
– Elements within the root may serve as container elements for subordinate objects
The XML Body (Page 2)The XML Body (Page 2)
• In the following example, "productlist" is the root node; there are many subordinate"product" nodes:<productlist> <product> <code>387-463-55-00</code> <name>Waterford Crystal Shamrock Paperweight</name> <price>99.00</price> <category>Waterford</category> <image>547.gif</image> <rating>4</rating> </product>…</productlist>
Modifying an XML File with the XML DesignerModifying an XML File with the XML Designer
• Editing XML data (click either tab at the bottom of the designer window):– Manually in XML view in which case IntelliSense and
color coding is implemented
– In Data view (in rows and columns, similar to the MS Access datasheet view)
• Filename extension for an XML document is "*.xml"
XML ViewXML View
Data ViewData View
Using Special Characters in an XML DocumentUsing Special Characters in an XML Document• represents a non-breaking space in HTML• Certain character entities are not supported within the tags because they are used to separate XML elements• Replace these characters with markup codes:
Character XML Markup Code
' '
" "
& &
< <
> >
CharacterXML Character
Markup Code
‘ '
“ "e;
& &
< <
> >
XSLT Stylesheets (Page 1)XSLT Stylesheets (Page 1)
• Contains format information for the XML file• Can contain a combination of HTML tags, style (CSS) rules
and XSLT commands• First line (root node) identifies the version of XML and
indicates it is an XSLT stylesheet– Root node name is xsl:stylesheet
• Example:<xsl:stylesheet version="1.0">
<!-- Put your formatting code here -->
</xsl:stylesheet>
• The usual file extension for XSLT stylesheets is ".xsl"
Open listProducts.xslOpen listProducts.xsl
XSLT Stylesheets (Page 2)XSLT Stylesheets (Page 2)
• The xmlns:xsl attribute indicates the schema • Schema (rules) are XSL Transform standards which are
maintained by the W3C• Example:
<xsl:stylesheet version="1.0"
xmlns:xsl= "http://www.w3.org/1999/XSL/Transform">
<!-- Put your formatting code here -->
</xsl:stylesheet>
The Main TemplateThe Main Template
• For documents with simpler formatting requirements, all formatting may be implemented by using a single main template– The main template is a code block which contains
instructions that apply formatting to an XML document
• In more complex documents, the main template is used to implement the format processing and a series of element templates specify the exact formatting
Formatting the Main Template (Page 1)Formatting the Main Template (Page 1)
• The xsl:template element surrounds and identifies each XSL template element– The match attribute specifies the node to be formatted
– The slash (/) indicates that formatting starts at the root node, that is the entire XML document will be formatted
– Example:<xsl:template match="/">
…
</xsl:template>
– It is not necessary to format all of the elements
Formatting the Main Template (Page 2)Formatting the Main Template (Page 2)
• The xsl:for-each element is a processing instruction that implements looping– Used to select every XML element of specific node-set
(members of the collection of child elements)
– Example:<xsl:for-each select="//product">
…
</xsl:for-each>
– Opening tag also may be written:<xsl:for-each select="productlist/product">
…
Formatting the Main Template (Page 3)Formatting the Main Template (Page 3)
• The xsl:apply-templates element is a processing instruction that applies a template to the current element and/or its child element(s)– The select attribute limits processing to only the child
element that matches the value of the attribute
– A series of select attributes also can specify the order in which the child nodes are processed
– Example:<xsl:apply-templates select="name" />
Formatting the Main Template (Page 4)Formatting the Main Template (Page 4)
• Example: <xsl:template match="/"><html><head><title>Tara Store Product List</title> ... </head><body><h1>Products and their categories.</h1><xsl:for-each select="//product"> <xsl:apply-templates select="name" />: <xsl:apply-templates select="category" /> <br /></xsl:for-each></body></html></xsl:template>
Element TemplatesElement Templates
• Element templates work together with the xsl:apply-templates elements in the main template
• They provide the specific (usually more detailed) formatting information for each match in the main template
• Element templates are coded outside of the main template, usually following it– Individual templates should be defined for each of the
elements in the main template
Using Element Templates (Page 1)Using Element Templates (Page 1)
• The match attribute of the xsl:template element matches and element name from the main template
• The xsl:value-of element can be used to extract the value of an XML element– Add its value to output stream of the transformation
– The period (.) indicates that everything within the node (specifed by the match attribute) is selected
– Example:<xsl:template match="product">
<b><xsl:value-of select="." /></b>
</xsl:template>
Using Element Templates (Page 2)Using Element Templates (Page 2)
• To apply a template to all the other elements, use an asterisk (*) as the value for the match property:<xsl:template match="*">
<div class="product">
<xsl:value-of select="."/>
</div>
</xsl:template>
Using Element Templates (Page 3)Using Element Templates (Page 3)
• The div tag uses the class defined in the embedded (or possibly even a linked) stylesheet to determine how to format the output:<xsl:template match="name">
<div class="product">
<b>Product Name:
<xsl:value-of select="." />
</b><br />
</div>
</xsl:template>
Creating an XSLT StylesheetCreating an XSLT Stylesheet
Inserting the XML Control (Page 1)Inserting the XML Control (Page 1)
• The XML control holds a place for the existing formatted XML file within the HTML or ASP document along with its formatting
• It is found by selecting the "Web Forms" tab of the Toolbox with the other ASP.NET server controls
• Used to insert the contents of the XML document into the Web page
• The XML control does not have a style attribute– Should be placed in a container (i.e. a Panel) to position
it at an absolute location
Open listproducts.aspxOpen listproducts.aspx
Inserting the XML Control (Page 2)Inserting the XML Control (Page 2)
• For the XML control, set the following properties:– DocumentSource attribute identifies a physical or
virtual path to the XML document
– TransformSource attribute identifies the physical or virtual path to the XSL or XSLT stylesheet
• Creates the following header tag:<asp:Xml runat="server" id="Xml1" TransformSource="listproducts.xsl" DocumentSource="products.xml" />
listproducts.aspxlistproducts.aspx
listproducts.aspx in Browserlistproducts.aspx in Browser
Modifying XSLT StylesheetsModifying XSLT Stylesheets
• Specify HTML attributes with xsl:attribute element
• An assignment operator (=) is implied, never keyed
• For example, to create a hyperlink<xsl:template match="image">
<a>
<xsl:attribute name="href">
<xsl:value-of select="." />
</xsl:attribute>
Click here to go to the Web site.
</a>
</xsl:template>
Insert an Image with XSLT StylesheetInsert an Image with XSLT Stylesheet
• Example:<xsl:template match="image">
<img>
<xsl:attribute name="src">
<xsl:value-of select="." />
</xsl:attribute>
<xsl:attribute name="align">
left
</xsl:attribute>
</img>
</xsl:template>
Inserting a Table with XSLT StylesheetInserting a Table with XSLT Stylesheet
• The table tags should be outside the for-each loop <xsl:template match="/"> <table border="0" cellspacing="10"> <tr><th>Image</th> ... </tr> <xsl:for-each select="//product"> <tr>
<td><xsl:apply-templates select="image"/></td> …
</tr> </xsl:for-each> </table></xsl:template>
Processing XML Data with an XSLT StylesheetProcessing XML Data with an XSLT Stylesheet
• XSLT stylesheets can analyze the contents of the element and performs actions
– xsl:choose–analyzes the value of the rating
– xsl:when–if the condition in the test attribute is met
– xsl:otherwise–applies when no choice listed is met
– xsl:sort–sorts the data
– xsl:if statement–similar to the xsl:if-else-end if
– string-length–tests the length of the element
The AdRotator Control (Page 1)The AdRotator Control (Page 1)
• Displays a banner ad on a Web page– The banner ad is a hyperlinked image
– Changes to different images each time page reloads
• The Advertisement File is an XML document that stores the ad information– File extension is ".xml"
– First line indicates the version of the XML
– Root node always is named Advertisements
– Each Ad element contains the properties to create the image and hyperlink
The AdRotator Control (Page 2)The AdRotator Control (Page 2)
• Property names for Advertisement File (case sensitive)– ImageUrl creates the src property (absolute or relative
address)
– NavigateUrl creates the href property (URL)
– AlternateText creates the alt property for the image
– Impressions indicates the relative frequency the banner ad is displayed (relative to other images in the file)
– Keyword property indicates one or more words that categorize the banner ad (compares to KeywordFilter property of the AdRotator control)
ads.xml—XML Viewads.xml—XML View
ads.xml—Data Viewads.xml—Data View
Inserting the AdRotator Control (Page 1)Inserting the AdRotator Control (Page 1)
• The AdRotator control holds a place for the rotating banner within the HTML or ASP document
• It is found by selecting the "Web Forms" tab of the Toolbox with the other ASP.NET server controls
• The AdvertisementFile property specifies the URL of the Advertisement File
Inserting the AdRotator Control (Page 2)Inserting the AdRotator Control (Page 2)
• Additional properties:– Height, Width and Style change appearance
– ToolTip property stores a message to display the message when the user hovers mouse over image
– Target property specifies in which window to open the link (default is "_top", meaning entire browser window which would turn off any frames)
– KeywordFilter property retrieves ads where the Keyword matches exactly
Creating Web Page to Display AdRotatorCreating Web Page to Display AdRotator
• getproducts.aspx - retrieves the value from the URL and displays the image
Dim imagename As String
imagename = Page.Request.QueryString("ID")
Image1.ImageUrl = "images/" & imagename
• AdRotator.aspx – contains the banner ad– KeywordFilter to Waterford
– AdvertisementFile property to ads.xml
AdRotator.aspxAdRotator.aspx
The Calendar Control (Page 1)The Calendar Control (Page 1)
• Displays a single calendar month– Change the appearance by setting the style templates
and properties
– Can also assign a CSS class to the style property
• Example: <asp:calendar id="MyCal" runat="server" />
The Calendar Control (Page 2)The Calendar Control (Page 2)
• Some of the Style properties– DayHeaderStyle—sets style for days of the week
– DayStyle—sets the style for individual dates
– NextPrevStyle—sets style for navigation controls
– OtherMonthDayStyle—for dates not in the current month
– SelectedDateStyle—sets style for dates selected
– SelectorStyle—sets style for month date selection column
– TitleStyle—sets the style for the title in the heading
– TodayDayStyle—sets style for current date
– WeekendDayStyle—sets style for weekend dates
The Calendar Control (Page 3)The Calendar Control (Page 3)
• Some of the Calendar properties (Boolean):– ShowDayHeader—shows/hides days of the week
– ShowGridLines—shows/hides the gridlines
– ShowTitle—shows/hides the heading title
– ShowNextPrev—shows/hides the Navigation controls
The Calendar Control (Page 4)The Calendar Control (Page 4)
• Programs can interact with the calendar:– SelectionChanged event occurs when the user clicks a
new date (changes selected date to a new selected date)
– SelectedDate property is the new selected date; the calendar control visually indicates to the user which date is selected
– VisibleMonthChanged event occurs when the user clicks on the next or previous month hyperlinks
calendar.aspxcalendar.aspx
• Example:Label1.Text = "You selected: " & _
Calendar1.SelectedDate.ToShortDateString()
If Calendar1.SelectedDate.ToShortDateString _
= Now.ToShortDateString Then
Label2.Text = _
"Today all Waterford products 30% off."
Else
Label2.Text = _
"All products 10% off this month"
End If
The Calendar Control (Page 5)The Calendar Control (Page 5)
Working with Multiple DatesWorking with Multiple Dates
• SelectedDates object (collection) retrieves the multiple values selected; use a For-Next loop to iterate through each date that was selected– Count property - number of dates selected
– Index position – zero-based
• Example:MyCalendar.SelectedDates(intCtr)
The File Upload ControlThe File Upload Control
• File Field control – client control
– HTML control – browse network and locate a file
• File Upload control – server control
– Upload a file to a Web server
– Known as InputFile HTML Server control or HTMLInputFile control
– Inherits System.Web.UI.HTMLInputControl
Uploading a FileUploading a File
• Enctype attribute - set to multipart/form-data – Indicates a file attached to the URL request
<form enctype="multipart/form-data"
runat="server">
• Accept attribute - specify the MIME formats – Accept= “image/jpg” - only JPEG images
– image/* - any image type
– Multiple MIME formats delimited with a comma
Uploading a File (continued)Uploading a File (continued)
• MaxLength property - to limit the length of filename
• Size attribute - to set the textbox width
<INPUT id="uploadFilePath"
type="file" MaxLength="50"
size="40" name="txtFileName"
runat="server"
Accept = "images/*, text/css, text/htm">
Uploading the File in the Code Behind the Page
Uploading the File in the Code Behind the Page
• HTTPPostedFile class – Call the PostedFile.SaveAs command
– Pass the file path
– PostedFile - upload the file, manipulate the file, and retrieve information about the file
Private Sub btnUpload_ServerClick(...)
strFilePath = "c:\upload\images\" & txtFileName.Value
uploadFilePath.PostedFile.SaveAs (strFilePath)
End Sub
Obtaining Information About the File Uploaded
Obtaining Information About the File Uploaded
• Properties– ContentLength - size of the file
– ContentType - MIME type
– FileName - path, filename, file extension
Dim UploadedFile as HttpPostedFile = _
UploadedFile.PostedFile
If UploadedFile.ContentLength = nothing then
Msg = "No file was selected.. .. .."
Else
Msg = "The file has been uploaded."
End if
Obtaining Information About the File Uploaded (continued)
Obtaining Information About the File Uploaded (continued)
• Path object from System.IO – MapPath method maps the path to a file.
• Server.MapPath(filename)
– GetExtension - retrieves the file extension
– FileName - retrieves the filename
Dim strFilePath As String
strFilePath =
System.IO.Path.GetDirectoryName (Server.MapPath("uploadfile.aspx"))
uploadFilePath.PostedFile.SaveAs ((strFilePath & "\" & txtFileName.Value))
Obtaining Information About the File Uploaded (continued)
Obtaining Information About the File Uploaded (continued)
• Retrieve the path and filename from the uploaded file and Path object
Dim UploadedFile as HttpPostedFile = _ UploadedFile.PostedFile
Dim FilePath As String = UploadedFile.FilePath
Dim FileName As String = Path.GetFileName(FilePath)
Dim FileExtension As String = Path.GetExtension(FileName)
Dim ContentType As String = UploadedFile.ContentType
Creating the File Upload Page uploadfile.aspx (Page 184)
Creating the File Upload Page uploadfile.aspx (Page 184)
Security Issues with the File Upload Control
Security Issues with the File Upload Control
• Page-level and application-level security
• Set NTFS Permissions
– Display NTFS information in Windows Explorer
• Turn off Simple File Sharing
– ASP.NET Machine user account
• IUSR_MACHINENAME
• Do not set permissions to allow anonymous users to create and write to the folder