Using ASP.NET Rich Controls

72
Chapter 4 1 Using ASP.NET Rich Controls Introduction to ASP.NET By Kathleen Kalata

description

Using ASP.NET Rich Controls. Introduction to ASP.NET By Kathleen Kalata. Objectives. In this chapter, you will: Learn how ASP.NET Rich controls can enhance your Web applications Identify the format and structure of an XML document Create an XSLT stylesheet - PowerPoint PPT Presentation

Transcript of Using ASP.NET Rich Controls

Page 1: Using ASP.NET Rich Controls

Chapter 4 1

Using ASP.NET Rich Controls

Introduction to ASP.NET

By Kathleen Kalata

Page 2: Using ASP.NET Rich Controls

Chapter 4 2

Objectives

• In this chapter, you will:

• Learn how ASP.NET Rich controls can enhance your Web applications

• Identify the format and structure of an XML document

• Create an XSLT stylesheet

• Read and display an XML data file using the XML controls

• Create a rotating banner advertisement on the Web page using the AdRotator control

• Create an interactive calendar using the calendar control

• Create ASP.NET pages that allow you to upload a file to the Web server

Page 3: Using ASP.NET Rich Controls

Chapter 4 3

XML Technologies

• Extensible Markup Language (XML), like HTML, is a markup language that provides access to structured content

• But, unlike HTML, XML is not limited to a set of tags or to being displayed in a browser

• XML allows you to define your own elements

• XML documents can be shared across applications, file systems, and operating systems– The XML standards are maintained by the World Wide Web

Consortium (www.w3c.org) and http://www.w3c.org/XML

Page 4: Using ASP.NET Rich Controls

Chapter 4 4

XML Technologies

The XML document can be formatted using a style sheet known as XSLT stylesheets XSL Transformations (XSLT) is a language for transforming

XML documents

XSLT stylesheets use XSLT to interact with an XML document

XSLT stylesheets can format individual or groups of elements within the XML document

XSLT is a form of XSL that transforms the XML data using processing rules in the XSLT stylesheet

Page 5: Using ASP.NET Rich Controls

Chapter 4 5

XML Technologies

Page 6: Using ASP.NET Rich Controls

Chapter 4 6

XML Editing Tools

• View the XML document using an XML parser

• MSXML Parser is built into Internet Explorer

– XML documents can be used by other types of applications such as Window Forms

• Create the XML documents using:

– Simple text editor such as Notepad

– Visual Studio .NET provides HTML/XML editor

– Microsoft XML NotePad called xmlpad.exe

• File extensions

– Generally saved with the file extension .xml

Page 7: Using ASP.NET Rich Controls

Chapter 4 7

XML Introduction

• An XML document must be well-formed

• A well-formed document follows XML standards and can therefore be read by any XML parser

– There can be only one root element, within which all other elements are nested

– You cannot mix nesting elements<b>Welcome to <i>Tara Store</b></i>

<b>Welcome to <i>Tara Store</i></b>

– Enclose the values of properties within double quotation marks

– XML is case sensitive. The case for the opening and closing tags of an element must match

Page 8: Using ASP.NET Rich Controls

Chapter 4 8

The Prologue

• The first section, known as the prologue, contains global information such as the XML version, formatting information, and schema definitions– The question mark indicates that this tag, XML, is a

processing instruction and therefore does not contain data. The Character-encoding property describes any coding algorithms<?xml version="1.0" encoding="utf-8" ?>

– Add a reference to a CSS stylesheet in an XML document to an external Cascading Style Sheet (CSS) or an XSL file to format the XML document<?xml:stylesheet type="text/css" href="taragifts.css">

Page 9: Using ASP.NET Rich Controls

Chapter 4 9

The Body• The XML document complies with the XML DOM

standards

• The XML DOM states that XML documents must have a logical structure

• The root container element (node) must nest all the elements and data– The root node can contain many other elements

– All tags must be nested within the root node (or root tag)

• The root node is a container element because all elements must be nested within the root element in an XML document

Page 10: Using ASP.NET Rich Controls

Chapter 4 10

Sample Root Node

• Productlist is the root node and contains other 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>

Page 11: Using ASP.NET Rich Controls

Chapter 4 11

Modifying an XML document

– You can edit XML data manually in XML view, or in Data view which allows you to enter the data using a table structure

– The XML view supports IntelliSense and color coding to help you create your XML code

– Create a new ASP.NET Web application named Chapter4, create an images folder, import the project images, and import the products.xml file which contains eight products

– Modify the products.xml file and use the XML Designer in Visual Studio .NET

Page 12: Using ASP.NET Rich Controls

Chapter 4 12

Add a Product Node Using XML View

• Add the product using the XML view<product>

<code>387-463-55-00</code>

<name>Waterford Crystal Shamrock Paperwight</name>

<price>120.00</price>

<category>Gifts</category>

<image>547.gif</image>

<rating>2</rating>

</product>

Page 13: Using ASP.NET Rich Controls

Chapter 4 13

Modify a Product Node Using Data View

Page 14: Using ASP.NET Rich Controls

Chapter 4 14

Using Special Characters in an XML Document

• Certain character entities are not supported within the tags because they are used to separate XML elements

• Replace these characters with the equivalent element markup codes

Character XML Character Markup Code

‘ &apos;“ &quote;& &amp;< &lt;> &gt;

Page 15: Using ASP.NET Rich Controls

Chapter 4 15

XSLT Stylesheets

• The XSTL stylesheet is an XML document that contains information about how to format a different XML document– The XSLT stylesheet can contain HTML, style rules, and XSTL

commands

– The first line identifies the version of XML and a root node is used to indicate that the document is an XSTL stylesheet

• The name for the root node for the XSLT stylesheet is xsl:stylesheet

• Add comments using the <! - - and - - > tags

• The usual file extension for a cascading style sheet is .css and for the XSLT stylesheet is .xsl

Page 16: Using ASP.NET Rich Controls

Chapter 4 16

XSLT Stylesheets

• The xmlns:xsl attribute indicates the schema to be supported for the stylesheet– The schema or rules are the XSL Transform standards

which are maintained by the W3C

– These standards describe how XSLT stylesheets are used to format XML documents

• Close the root element<xsl:stylesheet version="1.0"

xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><!- - Put your formatting code here - - >

</xsl:stylesheet>

Page 17: Using ASP.NET Rich Controls

Chapter 4 17

Formatting the Main Template

• The main template is indicated by the match attribute with a forward slash and is used to format the XML document– You must match the root node of the existing XML document. This

is used by the XSLT processor to read the document and to know where to start formatting the document

– You do not have to use all of the elements that are contained within the XML document

– You can nest basic HTML tags within the templates

– The xsl:for-each statement is a processing instruction that is applied to the node provided in the selected attribute

– CSS Classes can be applied to format the XML elements

Page 18: Using ASP.NET Rich Controls

Chapter 4 18

Formatting the Main Template

• Displays the product name, a colon, and the category, followed by a line break tag

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

Page 19: Using ASP.NET Rich Controls

Chapter 4 19

The Main Template

• There is a template in the page outside of the main template that contains the formatting instruction for each element in the main template

<xsl:template match="/"><html><head><title>Tara Store Product List</title>...</head><body>...<xsl:for-each select="//product"><xsl:apply-templates select="name" /><xsl:apply-templates select="category" /><xsl:apply-templates select="code" /><xsl:apply-templates select="price" /><xsl:apply-templates select="rating" /></xsl:for-each>... </body></html></xsl:template>

Page 20: Using ASP.NET Rich Controls

Chapter 4 20

Formatting the Elements Using Element Templates

• You can define individual templates for individual elements– The match attribute indicates the name of the element to apply the

template

– The xsl:value-of attribute indicates that the value of the element is retrieved and displayed

– To display the contents of any node, use <xsl:value-of select="." />

– The period means that everything within the node is selected

<xsl:template match="product">

<b><xsl:value-of select="." /> </b>

</xsl:template>

Page 21: Using ASP.NET Rich Controls

Chapter 4 21

Formatting the Elements Using Element Templates

• If you want a template to apply to all the other elements, you can use an asterisk as the value for the match property

<xsl:template match="*">

<div class="product">

<xsl:value-of select="."/>

</div>

</xsl:template>

Page 22: Using ASP.NET Rich Controls

Chapter 4 22

Formatting the Elements Using Element Templates

• The DIV tag uses the class defined in the embedded style sheet 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>

Page 23: Using ASP.NET Rich Controls

Chapter 4 23

Create a Simple XSLT Stylesheet

• Create listproducts.xsl to display the data in the products.xml file

• In listproducts.xsl indicate the XSL stylesheet standard version – Add the prologue

– Add the code to create the main template, and the for-each processing instruction

– Add the element templates

Page 24: Using ASP.NET Rich Controls

Chapter 4 24

Using the XML Control

• Document property - indicates that the XML data is located in an object called XMLDocument– DocumentContent property indicates that the XML data is a

string containing the entire text of the XML document

– DocumentSource allows you to identify a physical or virtual path to the XML document

• Transform property - where the style information is located– XSLTransform object contains the XSL or XSLT stylesheet

– TransformSource attribute identifies the physical or virtual path to the XSL or XSLT stylesheet

Page 25: Using ASP.NET Rich Controls

Chapter 4 25

Using the XML Control

• Visual Studio .NET provides a graphical tool in the toolbox to insert the XML control

<asp:Xml runat="server" id="Xml1"

TransformSource="listproducts.xsl"

DocumentSource="products.xml" />

Page 26: Using ASP.NET Rich Controls

Chapter 4 26

Create the WebForm

• Create a Web page named listproducts.aspx that displays an XML document named products.xml using an XSLT stylesheet

– DocumentSource property to products.xml

– TransformSource property to listview.xsl

Page 27: Using ASP.NET Rich Controls

Chapter 4 27

listproducts.aspx

Page 28: Using ASP.NET Rich Controls

Chapter 4 28

listproducts.aspx

Page 29: Using ASP.NET Rich Controls

Chapter 4 29

Modifying XSLT Stylesheets

• You can specify attributes for any of the HTML properties in the template using the xsl:attribute command

• 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>

Page 30: Using ASP.NET Rich Controls

Chapter 4 30

Inserting a Table with XSLT Stylesheets

• The heading and closing table tag of the table is separated outside of the for-each loop so that the heading only appears once<xsl:template match="/"><table border="0" cellspacing="10"><tr><th>Image</th>...<th>Price</th></tr><xsl:for-each select="//product">

<tr><td><xsl:apply-templates select="image"/></td>...<td><xsl:apply-templates select="price"/></td></tr>

</xsl:for-each></table></xsl:template>...

Page 31: Using ASP.NET Rich Controls

Chapter 4 31

Inserting an Image with an XSLT Stylesheet

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

Page 32: Using ASP.NET Rich Controls

Chapter 4 32

Write Out Text– The xsl:text instruction is used to write out the value

of the text such as special control characters

– The disable-output-escaping attribute is used to generate characters without escaping such as the single < character

– Creates a hyperlink to a URL, and passes the name of the image in a querystring

– You are creating an anchor tag that will create a basic hyperlink such as

<a href = "ProcessingPage.aspx?ImageUrl=15.jpg"> Belleek Frames & Clocks</a>

Page 33: Using ASP.NET Rich Controls

Chapter 4 33

Create Hyperlinks

<xsl:template match="/">

<xsl:for-each select="//Category"><xsl:apply-templates select="ImageUrl" />...

</xsl:for-each></xsl:template>

<xsl:template match="ImageUrl"><a>

<xsl:attribute name="href">images/

<xsl:for-each select=".">

</xsl:attribute>Click here to see the image.

</a>

</xsl:template> ...

Page 34: Using ASP.NET Rich Controls

Chapter 4 34

Processing XML Data with an XSLT Stylesheet

• XSLT stylesheets can analyze the contents of the element and performs actions

• Stylesheet:.over {font-family:Verdana; font-size:11pt;

color:green; font-weight:bold}.under {font-family:Verdana; font-size:10pt;

color:red; font-weight:bold}

• Main Template:<xsl:for-each select="//product">

<xsl:apply-templates select="name"/>

<xsl:apply-templates select="rating"/>

</xsl:for-each>

Page 35: Using ASP.NET Rich Controls

Chapter 4 35

Processing XML Data with an XSLT Stylesheet

• Element Templates:

<xsl:template match="name"><div class="product">

<b><xsl:value-of select="." /></b>

</div>

</xsl:template>

Page 36: Using ASP.NET Rich Controls

Chapter 4 36

Additional XSL Commands

• xsl:choose - to analyze the value of the rating

• xsl:when – if the condition in the test attribute is met

– The greater than sign is written as &gt; because the XML parser may interpret as XML

– You can use the period (.) to represent the element data or the element name

• xsl:otherwise - to apply when no choice listed is met

• xsl:sort – command to sort the data

• xsl:if statement - similar to the xsl:if-else-end if

• string-length - tests the length of the element

Page 37: Using ASP.NET Rich Controls

Chapter 4 37

Additional XSL Commands

<xsl:template match="rating">

<xsl:choose>

<xsl:when test=". &gt; 3"><span class="over"><img src="clover.gif" align="bottom" hspace="5"/> Excellent! </span>

</xsl:when><xsl:otherwise>

This is within current projections.<br />

</xsl:otherwise>

</xsl:choose>

...</xsl:template>

Page 38: Using ASP.NET Rich Controls

Chapter 4 38

XML Schemas

• To eliminate confusion when working with multiple XML documents, XML documents can identify a namespace associated with the document – This set of rules or namespace is called a schema

– Schemas are used to define the structure, content, and semantics of XML documents

– The schema can be written in a Document Type Definition (DTD) document or an XML Schema document

– Parsers use the schema to determine the rules to validate the XML data. The XML parser will use that schema to validate the structure of the XML document

Page 39: Using ASP.NET Rich Controls

Chapter 4 39

XML Schemas

• Below is the DTD that is used with Web pages that comply with the strict HTML 4.0 standards. The DTD must be the first line in the Web page before the beginning <html> tag

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"

"http://www.w3.org/TR/html4/strict.dtd">

• When you create an ASP.NET page with Visual Studio .NET, the property used to identify the schema is called TargetSchema

Page 40: Using ASP.NET Rich Controls

Chapter 4 40

Create a Schema for an XML Document

– View the inventory.xml

– Create a Schema named inventory.xsd using Visual Studio .NET based on inventory.xml. Visual Studio can create a schema for you based on an existing XML document within the XML Designer. The schema document file extension is .xsd

– Modify the schema using the Schema view of the XML Designer. The DataSet view displays the schema using tables, while the XML view displays the schema using XML code

– The xmlns attribute is added to the element to identify the XML schema document associated with the XML document as shown in the sample code below<elementname xmlns="http://tempuri.org/schemaname.xsd">

Page 41: Using ASP.NET Rich Controls

Chapter 4 41

XML Schema in DataSet View

Page 42: Using ASP.NET Rich Controls

Chapter 4 42

The AdRotator Control

• The AdRotator control allows you to display a banner ad on a Web page

– The AdRotator control class is contained within the System.Web.UI.WebControl.AdRotator namespace

– The Advertisement File is an XML document that stores the ad information

– The Web page is an ASP.NET page that contains a WebForm which displays the ads

– The banner ad is a hyperlinked image

Page 43: Using ASP.NET Rich Controls

Chapter 4 43

Advertisement File

• External XML document which contains information that creates the HTML image tag, inserts the image, and creates the hyperlink using an anchor tag

– The filename has the file extension .xml

– The first line of the AdvertisementFile indicates the version of the XML document

<?xml version="1.0" encoding="utf-8" ?>

• The rest of the file is contained within a root node named advertisements

• The ad tag is an element that contains the individual properties for each ad used to create the image and hyperlink

Page 44: Using ASP.NET Rich Controls

Chapter 4 44

Ad Properties and Methods

• Each ad contains several properties that are used to create the image and hyperlink– ImageURL is used to create the SRC property in

the image tag. Only images in the format of JPG, GIF, or PNG

– NavigateURL is used to create the href property within the anchor (<a>)

– AlternateText is used to create the ALT property of the image tag

Page 45: Using ASP.NET Rich Controls

Chapter 4 45

Ad Properties and Methods

– Impressions property - used to indicate the frequency with which the banner ad is displayed. Refer to your log files to determine the exact number of times that the ad was displayed

– Keyword property - used to indicate one or more words that categorize the banner ad

– KeywordFilter method - screens the banner ads in the XML file where the keyword property matched

Page 46: Using ASP.NET Rich Controls

Chapter 4 46

Advertisement File

• Sample<Advertisements>

<Ad><ImageUrl>banner1.gif</ImageUrl>

<NavigateUrl>http://www.course.com/ </NavigateUrl>

<AlternateText>Course Technology</AlternateText>

<Impressions>60</Impressions>

<Keyword>Books</Keyword>

</Ad>...

<Advertisements>

Page 47: Using ASP.NET Rich Controls

Chapter 4 47

Creating the Advertisement File

• Add a new banner ad to the AdvertisementFile in XML view, then,

<Ad><ImageUrl>images/547.gif</ImageUrl>

<NavigateUrl>getproduct.aspx?id=547.gif

</NavigateUrl>

<AlternateText>Waterford Crystal Shamrock

Paperweight</AlternateText>

<Impressions>10</Impressions>

<Keyword>Waterford</Keyword>

</Ad>

Page 48: Using ASP.NET Rich Controls

Chapter 4 48

Creating the Advertisement File

• Add a new record in DataView

– ImageUrl = images/803.gif

– NavigateUrl = getproduct.aspx?id=803.jpg

– AlternateText = Traditional Music of Ireland

– Impressions = 10

– Keyword = Music

Page 49: Using ASP.NET Rich Controls

Chapter 4 49

Inserting an Ad in Data View

Page 50: Using ASP.NET Rich Controls

Chapter 4 50

Inserting the AdRotator Control

• The control is identified with the prefix ASP, AdRotator, and a semicolon (<asp:AdRotator>)– Set the runat property to server

– Configure the AdvertisementFile property to point to the location of the Advertisement File

– Set the ID property

– Set the height and width properties

– Close the tag with /> or </asp:AdRotator>

<asp:AdRotator runat="server" id="AdRotator1"

AdvertisementFile="ads.xml"

KeywordFilter="Waterford" />

Page 51: Using ASP.NET Rich Controls

Chapter 4 51

Additional Properties of the AdRotator Control

– Style properties - can be set such as BorderColor, BorderWidth, BorderStyle, Visible, TabIndex, and absolute positioning

– ToolTip property - stores a message as a string used by browsers that display the message in the ToolTip when the user mouses over the banner image

– Target property - the window to open the new link. Default is set to _top

– KeywordFilter property - retrieves only the banner ads from the XML document where the Keyword matches exactly. Use quotation marks

Page 52: Using ASP.NET Rich Controls

Chapter 4 52

displayBanner.aspx

– Create a banner advertisement

– Set the KeywordFilter property to Waterford

– Set the AdvertisementFile property to ads.xml

– Import the getproducts.aspx and add the code in the Page_Load handler that retrieves the value from the URL and displays the imageDim imagename As String

imagename = Page.Request.QueryString("ID")

Image1.ImageUrl = "images/" & imagename

Page 53: Using ASP.NET Rich Controls

Chapter 4 53

displayBanner.aspx

Page 54: Using ASP.NET Rich Controls

Chapter 4 54

The Calendar Control

• The Calendar control is created by the Calendar class– The Calendar class is located in the System.Web.UI.WebControls.Calendar namespace

• The calendar displays a single calendar month

• By default, the current month is displayed– You can configure the appearance of the calendar by

setting the properties of the calendar control

– You can create programs that interact with the calendar using methods and event handlers

Page 55: Using ASP.NET Rich Controls

Chapter 4 55

The Calendar Control

• The name of the control includes the prefix ASP: followed by calendar

– The runat property must be assigned to server

– Assign a value to the ID property

– Close the tag with /> or </asp:Calendar

<asp:calendar id="MyCal" runat="server" />

• Style properties can modify the background color, text color, font face, size, and style, alignment, width and height, wrapping, and border style

– You can also assign a CSS class to the property which can be used to configure the styles from an external style sheet

Page 56: Using ASP.NET Rich Controls

Chapter 4 56

Calendar Style Properties

Page 57: Using ASP.NET Rich Controls

Chapter 4 57

Calendar Style Properties

– DayHeaderStyle sets the style for the days of the week

– DayStyle sets the style for the individual dates

– NextPrevStyle sets the style for the navigation controls in the heading

– OtherMonthDayStyle sets the style for dates that are not in the current month

– SelectedDateStyle sets the style for the dates that were selected

– SelectorStyle sets the style for the month date selection column

– TitleStyle sets the style for the title in the heading

Page 58: Using ASP.NET Rich Controls

Chapter 4 58

Calendar Style Properties

– TodayDateStyle sets the style for the current date

– WeekendDayStyle sets the style for weekend dates

– ShowDayHeader property shows or hides the days of the week heading row

– ShowGridLines property shows or hides the gridlines which divide the days of the month. ShowTitle property shows or hides the title in the heading

– ShowNextPrev property shows or hides the navigation controls. Navigation controls are used to navigate to the next or previous month

Page 59: Using ASP.NET Rich Controls

Chapter 4 59

Calendar Properties and Methods

– SelectionChanged event occurs when the user clicks a new date. This event changes the 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

– ToShortDateString property of the SelectedDate displays the selected date using the short date format as mm/dd/yyyy

– VisibleMonthChanged event occurs when the user clicks on the next or previous month hyperlinks

Page 60: Using ASP.NET Rich Controls

Chapter 4 60

Retrieving Multiple Selected Dates

• To refer to each date selected by its position within the SelectedDates object

MyCalendar.SelectedDates(i)

– SelectedDates object – can be used to retrieve the multiple values selected. Use a For-Next loop to iterate through each date that was selected

– Count property - provides the number of dates that were selected

– Index position - the position within the object

Page 61: Using ASP.NET Rich Controls

Chapter 4 61

Create a Calendar

– Insert a calendar control in a Web page and set the properties of the calendar control

– Create an event handler which will detect when the user clicks on a new date, and display a message in the Web page indicating the value of the new date

– You will use an if-then control structure to determine if the date selected is the current date

– If the date selected is the current date, you will display a different message in the label control

– The Page_Load code executes when the user clicks on a new date and changes the text property of a label control named Label1

Page 62: Using ASP.NET Rich Controls

Chapter 4 62

Create a Calendar– The message displayed includes a string message. Use the

ToShortDateString property for both date objects when comparing the datesPrivate Sub Calendar1_SelectionChanged(...)

Label1.Text = "You selected: " _

& ChrW(60) & "br" & ChrW(62) _

& ChrW(60) & "br" & ChrW(62)

If Calendar1.SelectedDate.ToShortDateString() = Date.Now.ToShortDateString() Then

Label1.Text &= _

"Today all Waterford products are 30% off."

Else

Label1.Text &= _

"Today all products are 10% off during this month."

End If

End Sub

Page 63: Using ASP.NET Rich Controls

Chapter 4 63

calendar.aspx

Page 64: Using ASP.NET Rich Controls

Chapter 4 64

The File Upload Control

• The file upload control allows you to upload a file to a Web server

– The file upload control is not listed as a rich control but can significantly enhance your application

• Modifying the Form

– The file upload control is an HTML server control known as the InputFile HTML Server Control

– The file upload control class inherits from the System.Web.UI.HTMLInputControl namespace

• Security Issues

– You do not need to set permissions to allow anonymous users to create and write to the folder

Page 65: Using ASP.NET Rich Controls

Chapter 4 65

Creating the File Upload Page: The Form Tag

– Enctype attribute is set to multipart/form-data and indicates that there is a file attached to the URL request

<form enctype="multipart/form-data" runat="server">

<input id="uploadFilePath" type="file"

size="40" name="txtFileName" runat="server">

<input id="FileName" type="text" runat="server">

<br /><br />

<input type=button id="btnUpload"

value="Upload a File" runat="server"

OnServerClick="btnUpload_Click">

</form>

Page 66: Using ASP.NET Rich Controls

Chapter 4 66

Other Properties• Accept attribute - allows you to specify the MIME formats that

can be uploaded

– Accept= “image/jpg” - upload only JPEG images

– image/* - upload any image type

– Enter multiple MIME formats delimited with a comma

• 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">

Page 67: Using ASP.NET Rich Controls

Chapter 4 67

Uploading the File

• The file is uploaded using the HTTPPostedFile class – To save the file you must call the PostedFile.SaveAs

command and pass the path to the file on the clients computer

– The PostedFile allows you to 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

Page 68: Using ASP.NET Rich Controls

Chapter 4 68

The Path Object

• The Path object is derived from the System.IO namespace

– MapPath method maps the path to a file. Written as Server.Mappath(filename)

– GetExtension method retrieves the file extension

– FileName property retrieves the complete filename on the client’s computer

Page 69: Using ASP.NET Rich Controls

Chapter 4 69

The Path Object

• 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

Page 70: Using ASP.NET Rich Controls

Chapter 4 70

Retrieving Information About the File

– ContentLength property - obtains the size of the file

– ContentType property - detects the MIME type

– FileName property - retrieves the path, filename, and file extension

Dim UploadedFile as HttpPostedFile = _

UploadedFile.PostedFile

If UploadedFile.ContentLength = nothing then"No file was selected. Pick a file to upload."

Else

"The file has been uploaded."

End if

Page 71: Using ASP.NET Rich Controls

Chapter 4 71

uploadfile.aspx

– Create a login form. After the user is authenticated, the file upload control is shown

– Authenticated users are allowed to upload the file to the Web server

– Here is the code to upload the file:Dim strFilePath As String

strFilePath =

System.IO.Path.GetDirectoryName(Server.MapPath("uploadfile.aspx"))

uploadFilePath.PostedFile.SaveAs((strFilePath & "\" & txtFileName.Value))

Page 72: Using ASP.NET Rich Controls

Chapter 4 72

uploadfile.aspx