In the following sections, you learn how to use three of the more feature-rich controls in the ASP.NET framework. You learn how to use the Calendar control to display interactive calendars, the AdRotator control to display rotating banner advertisements, and the HTMLInputFile control to accept file uploads. Displaying Interactive Calendars with the Calendar ControlYou can use the ASP.NET Calendar control to display an interactive calendar on a page. This control enables you to select particular days, weeks, or months. You can also display custom content on each day. All the properties, methods , and events of this control are listed in Table 4.3. Table 4.3. Calendar Properties, Methods, and Events
Typical uses for the Calendar control include displaying a schedule of events. You can customize the appearance of each cell in the calendar as it is displayed. You can even display a hyperlink to more information within each calendar day. Another common use of the Calendar control is scheduling. Because you can select particular days, weeks, or months on the calendar, you can use the control to reserve dates for meetings or events. A complex calendar can be added to a page with very few lines of code. For example, Listing 4.14 displays the default calendar displayed by the Calendar control (see Figure 4.8). Listing 4.14 Calendar.aspx<html> <head><title>calendar.aspx</title></head> <body> <form Runat="Server"> <asp:Calendar Runat="Server" /> </form> </body> </html> The C# version of this code can be found on the CD-ROM. Figure 4.8. Calendar control with default properties.
Customizing the Appearance of the Calendar ControlYou can customize the appearance of the Calendar control in three ways: You can use the formatting properties common to all controls, you can use the general formatting properties of the Calendar control, or you can apply one or more custom style objects to the control. The Calendar control supports all the common Web control formatting properties described in Chapter 2. For example, you can modify Calendar properties such as BackColor , ForeColor , Border , Font , Height , and Width by modifying the base Web control formatting properties. NOTE All the common Web control formatting properties are listed under the base Web control properties in Appendix C, "Web Control Reference." The page contained in Listing 4.15 illustrates how you can modify several of these properties (see Figure 4.9 for the output). Listing 4.15 CalendarBaseFormatting.aspx<html> <head><title>CalendarBaseFormatting.aspx</title></head> <body> <form Runat="Server"> <asp:Calendar Width="100%" BackColor="blue" ForeColor="Yellow" Font-Name="Script" Font-Size="24pt" Font-Bold="True" Runat="Server" /> </form> </body> </html> The C# version of this code can be found on the CD-ROM. Figure 4.9. A calendar with different base Web control formatting properties.
You also can modify the general formatting properties of the Calendar control itself. Examples of these properties are ShowGridLines , NextMonthText , PrevMonthText , and TitleFormat . You can find a list of all these properties in Table 4.3. To change the way the next and previous month links are displayed, for example, you can modify the NextPrevFormat , NextMonthText , PrevMonthText , and ShowNextPrevMonth properties. You can even use images for the link to the next and previous months by setting the properties like this: <asp:Calendar ID="myCal" PrevMonthText="<img src='prev.gif'>" NextMonthText="<img src='next.gif'>" Runat="Server" /> To modify the way the list of weekdays appears in the calendar, modify the DayNameFormat property. When this property has the value FirstLetter , only the first letter of each day is shown. When this property has the value FirstTwoLetters , only the first two letters of each day are shown. When this property has the value Full , the full day name is shown. When this property has the value Short , three letters are shown for each day. You also can modify the format of a Calendar control by applying any one of several style objects to the calendar. The Calendar control supports the style objects listed in Table 4.4. Table 4.4. Calendar Style Objects
All the style objects, with the exception of the TitleStyle object, support the properties of the TableItemStyle style class. (The properties of this class are listed in Appendix C.) The TitleStyle object supports all the styles of the base style class (also listed in Appendix C). Suppose that you want to display most days in blue, but show weekends in green, today in yellow, and the selected date in orange. You can do so by modifying the style objects. Listing 4.16 contains a (very ugly) Calendar control formatted with these properties. Listing 4.16 CalendarStyle.aspx<html> <head><title>CalendarStyle.aspx</title></head> <body> <form Runat="Server"> <asp:Calendar DayStyle-BackColor="Blue" WeekendDayStyle-BackColor="Green" TodayDayStyle-BackColor="Yellow" SelectedDayStyle-BackColor="Orange" Runat="Server" /> </form> </body> </html> The C# version of this code can be found on the CD-ROM. Selecting Days, Weeks, and Months with the Calendar ControlBy default, the Calendar control enables you to pick a particular day on the calendar. However, you can modify the properties of the Calendar control so that it enables you to select weeks or months. You can even set the Calendar control so that it does not allow you to pick anything. To pick weeks or months, modify the SelectionMode property. You can assign the values Day , DayWeek , DayWeekMonth , or None to this property. For example, the value DayWeekMonth enables you to select either a day, week, or month. After you modify the SelectionMode property to enable week or month selection, you can modify the SelectWeekText and SelectMonthText properties to display different links for selecting the day or month. You can even assign images to these properties by using syntax like this: <asp:Calendar ID="myCal" SelectionMode="DayWeekMonth" SelectWeekText="<img src='selectWeek.gif'>" SelectMonthText="<img src='selectMonth.gif'>" Runat="Server" /> To determine the dates that have been selected on the calendar, use the SelectionChanged event. When this event is raised, you can use the SelectedDate property to determine what date is selected or the SelectedDates property to determine what dates are selected. The page in Listing 4.17, for example, demonstrates how you can retrieve and display the dates selected on a calendar (see Figure 4.10). Listing 4.17 CalendarSelected.aspx<Script Runat="Server"> Sub Calendar_SelectionChanged( s As Object, e As EventArgs ) Dim dtmDate As DateTime lblDates.Text = "<h2>You selected the following date(s):</h2>" For Each dtmDate in calCalendar.SelectedDates lblDates.Text &= "<li>" & dtmDate.ToString( "D" ) Next End Sub </Script> <html> <head><title>CalendarSelected.aspx</title></head> <body> <form Runat="Server"> <asp:Calendar id="calCalendar" SelectionMode="DayWeekMonth" SelectWeekText="Select Week" SelectMonthText="Select Month" OnSelectionChanged="Calendar_SelectionChanged" Runat="Server" /> <asp:Label ID="lblDates" Runat="Server" /> </form> </body> </html> The C# version of this code can be found on the CD-ROM. Figure 4.10. Selecting calendar dates.
When a new day, week, or month is selected, the SelectionChanged event is raised. This event is handled in Listing 4.17 by a subroutine named Calendar_SelectionChanged . This subroutine loops through the collection of dates represented by the Calendar control's SelectedDates property. Each item in this collection is a DateTime . Rendering Calendar DaysWhenever the Calendar control renders a particular day, the control raises the DayRender event. You can write a subroutine that handles this event and display custom content on each calendar day. To capture the DayRender event, create a subroutine with these parameters: Sub Calendar_DayRender( s As Object, e As DayRenderEventArgs ) End Sub The second parameter passed to the subroutine, DayRenderEventArgs , has a number of properties that you can use in your code. These properties are listed in Table 4.5. Table 4.5. DayRenderEventArgs Properties
Listing 4.18 illustrates how you can use the DayRender event to display a daily horoscope in a Calendar control. Listing 4.18 CalendarHoroscope.aspx<%@ Import Namespace="System.Drawing" %> <Script Runat="Server"> Dim RanNum As New Random( 23 ) Sub Calendar_RenderDay( s As Object, e As DayRenderEventArgs ) Dim ctlCell As TableCell Dim strHoroscope As String ctlCell = e.Cell Select Case RanNum.Next( 4 ) Case 0 strHoroscope = "Good things will happen today!" ctlCell.BackColor = Color.FromName( "Green" ) Case 1 strHoroscope = "You're doomed! Hide in bed!" ctlCell.BackColor = Color.FromName( "Red" ) Case 2 strHoroscope = "Something unexpected will happen" Case 3 strHoroscope = "Look before you leap!" End Select ctlCell.Controls.Add( New LiteralControl( "<p>" ) ) ctlCell.Controls.Add( New LiteralControl( strHoroscope ) ) End Sub </Script> <html> <head><title>CalendarHoroscope.aspx</title></head> <body> <h1>Horoscope:</h1> <form Runat="Server"> <asp:Calendar Width="100%" CellPadding="10" ShowGridLines="True" SelectionMode="None" OnDayRender="Calendar_RenderDay" Runat="Server" /> </form> </body> </html> The C# version of this code can be found on the CD-ROM. The Calendar_RenderDay subroutine is called for each day rendered on the calendar. This subroutine randomly selects from four possible horoscopes and displays one for the particular day being rendered (see Figure 4.11). Figure 4.11. Handling the DayRender event.
Notice how the Controls collection of the calendar cell is used. To add new content to a day, you add new controls to the Controls collection of a calendar cell. In Listing 4.18, you add two LiteralControl controls: One LiteralControl represents an HTML paragraph break, and the other represents the text of the horoscope. NOTE You can also add text to a particular calendar cell by using the TableCell 's Text property. This works fine for plain text or HTML content. However, you cannot use the Text property to add ASP.NET controls, such as TextBox controls. Creating an Interactive Meeting SchedulerIn this section, you build a more complex application using the Calendar control. You create a Web application that enables you to add notes to any day on the calendar and save the notes between visits . The complete code for this application is contained in Listing 4.19. The ASP.NET page in Listing 4.19 contains Calendar , TextBox , and Button controls. If you want to add a note to a date, you select the date on the calendar, enter the note in the text box, and click the Save Changes button. Every date on the calendar is represented by a two-dimensional array named arrCalendar . The first index of the array represents the month, and the second index represents the day. The Calendar_RenderDay subroutine is called for each day that is rendered on the calendar. This subroutine displays the day with an orange background color if a note is associated with the day. When you click Save Changes, the contents of the arrCalendar array are saved to disk. This is accomplished in the btnSave_Click subroutine. The array is saved to a file named schedule.bin located in the root of the C: drive. If you save changes and return to the page on a later date, the notes are preserved. When the page is first loaded, the notes are retrieved from the schedule.bin file saved on disk. After the notes are loaded the first time, they are subsequently retrieved from the cache to improve performance. NOTE Since the page in Listing 4.19 writes to the file system, you'll need to grant write permissions to the ASPNET user account to write to the directory containing the schedule.bin file. For more information on the ASPNET user account see Chapter 20, "Using Windows-Based Authentication." Listing 4.19 CalendarSchedule.aspx<%@ Import Namespace="System.IO" %> <%@ Import Namespace="System.Runtime.Serialization" %> <%@ Import Namespace="System.Runtime.Serialization.Formatters.Binary" %> <%@ Import Namespace="System.Drawing" %> <Script Runat="Server"> Dim arrCalendar( 13, 32 ) As String ' Get schedule from cache or disk Sub Page_Load Dim strmFileStream As FileStream Dim fmtrBinaryFormatter As BinaryFormatter If Cache( "arrCalendar" ) Is Nothing Then If File.Exists( "c:\schedule.bin" ) Then strmFileStream = _ New FileStream( "c:\schedule.bin", FileMode.Open ) fmtrBinaryFormatter = New BinaryFormatter arrCalendar = _ CType( fmtrBinaryFormatter.Deserialize( strmFileStream ), Array ) strmFileStream.Close() Cache( "arrCalendar" ) = arrCalendar End If Else arrCalendar = Cache( "arrCalendar" ) End If End Sub ' Save schedule to file Sub btnSave_Click( s As Object, e As EventArgs ) Dim dtmDate As DateTime Dim strmFileStream As FileStream Dim fmtrBinaryFormatter As BinaryFormatter dtmDate = calSchedule.SelectedDate arrCalendar( dtmDate.Month, dtmDate.Day ) = txtNotes.Text strmFileStream = _ New FileStream( "c:\schedule.bin", FileMode.Create ) fmtrBinaryFormatter = New BinaryFormatter fmtrBinaryFormatter.Serialize( strmFileStream, arrCalendar ) strmFileStream.Close() Cache( "arrCalendar" ) = arrCalendar End Sub ' Pick a date Sub Calendar_SelectionChanged( s As Object, e As EventArgs ) Dim dtmDate As DateTime dtmDate = calSchedule.SelectedDate txtNotes.Text = arrCalendar( dtmDate.Month, dtmDate.Day ) End Sub ' Display each calendar day Sub Calendar_RenderDay( s As Object, e As DayRenderEventArgs ) Dim dtmDate As DateTime Dim ctlCell As TableCell dtmDate = e.Day.Date ctlCell = e.Cell If arrCalendar( dtmDate.Month, dtmDate.Day ) <> "" Then ctlCell.BackColor = Color.FromName( "Orange" ) End If End Sub </Script> <html> <head><title>CalendarSchedule.aspx</title></head> <body> <form Runat="Server"> <asp:Calendar id="calSchedule" Width="100%" ShowGridLines="True" OnSelectionChanged="Calendar_SelectionChanged" OnDayRender="Calendar_RenderDay" Runat="Server" /> <p> <asp:TextBox id="txtNotes" TextMode="MultiLIne" Columns="50" Rows="10" Runat="Server" /> <p> <asp:Button id="btnSave" Text="Save Changes" OnClick="btnSave_Click" Runat="Server" /> </form> </body> </html> The C# version of this code can be found on the CD-ROM. Displaying Banner Advertisements with the AdRotator ControlYou can use the AdRotator control to randomly display banner advertisements on your Web pages. In most cases, you use the AdRotator control with an advertisement file that contains a list of the properties of banner advertisements to display. All the properties, methods, and events of this control are listed in Table 4.6. Table 4.6. AdRotator Control Properties, Methods, and Events
The Advertisement File is an XML file with the following format: <Advertisements> <Ad> <ImageUrl>URL of image to display</ImageUrl> <TargetUrl> URL of page to link to </TargetUrl> <AlternateText> Text to show as ToolTip </AlternateText> <Keyword>keyword used to filter</Keyword> <Impressions>relative weighting of ad</Impressions> </Ad> </Advertisements> The file enables you to specify the properties for each banner advertisement described in Table 4.7:
All the preceding properties are optional except ImageUrl . For example, if you do not specify a NavigateUrl , the banner advertisement is displayed without a link. TIP You can add your own custom properties to the advertisement file. For example, you can add a Campaign property that indicates the particular banner campaign for the advertisement. An example of a custom property is included in the next section, "Tracking AdRotator Impressions." The page contained in Listing 4.20 illustrates how you can use the AdRotator control with an Advertisement File named myAds.xml , which is included in Listing 4.21. Listing 4.20 AdRotator.aspx<html> <head><title>AdRotator.aspx</title></head> <body> <form Runat="Server"> <asp:AdRotator AdvertisementFile="myAds.xml" Runat="Server" /> </form> </body> </html> The C# version of this code can be found on the CD-ROM. Listing 4.21 myAds.xml<Advertisements> <Ad> <ImageUrl>AspWorkshopsBanner.gif</ImageUrl> <NavigateUrl>http://www.AspWorkshops.com</NavigateUrl> <AlternateText> Need ASP.NET Training? </AlternateText> <Impressions>2</Impressions> </Ad> <Ad> <ImageUrl>SuperexpertBanner.gif</ImageUrl> <NavigateUrl>http://www.superexpert.com</NavigateUrl> <AlternateText> Click here to visit Superexpert.com! </AlternateText> <Impressions>1</Impressions> </Ad> </Advertisements> The C# version of this code can be found on the CD-ROM. Tracking AdRotator ImpressionsIf you add a subroutine to handle the AdCreated event, you can track the number of times each banner advertisement is displayed. You can use this subroutine to record advertisement statistics to a database table, an XML file, or the file system. When the AdCreated event is raised, an instance of the AdCreatedEventArgs class is passed to the subroutine that handles the event. The properties of the AdCreatedEventArgs class are listed in Table 4.8. Table 4.8. AdCreatedEventArgs Properties
For example, the page in Listing 4.22 records statistics on the number of times each advertisement is displayed to the file system. The page uses the advertisement file in Listing 4.23. Each advertisement in the advertisement file has a custom Campaign property. When the AdRotator in Listing 4.22 displays an advertisement, the AdRotator_ AdCreated subroutine updates the statistics for the advertisement. For example, if the AspWorkshops advertisement is displayed, then the number of impressions for this advertisement is recorded to a file named AspWorkshops.imp . The name of the file _corresponds to the Campaign property in the advertisement file. Listing 4.22 AdRotatorImpressions.aspx<%@ Import Namespace="System.IO" %> <Script runat="Server"> Sub AdRotator_AdCreated( s As Object, e As AdCreatedEventArgs ) Dim intImpressions As Integer = 0 Dim strFileName As String Dim strmStreamReader As StreamReader Dim strmStreamWriter As StreamWriter ' Assign file name strFileName = e.AdProperties( "Campaign" ).Trim & ".imp" If strFileName = "" Then strFileName = "default.imp" End If ' Read current impressions If File.Exists( MapPath( strFileName ) ) Then strmStreamReader = File.OpenText( MapPath( strFileName ) ) intImpressions = Cint( strmStreamReader.ReadLine ) strmStreamReader.Close End If ' Write current impressions strmStreamWriter = File.CreateText( MapPath( strFileName ) ) strmStreamWriter.Write( intImpressions + 1 ) strmStreamWriter.Close End Sub </Script> <html> <head><title>AdRotatorImpressions.aspx</title></head> <body> <form Runat="Server"> <asp:AdRotator AdvertisementFile="AdCampaigns.xml" OnAdCreated="AdRotator_AdCreated" Runat="Server" /> </form> </body> </html> The C# version of this code can be found on the CD-ROM. Listing 4.23 AdCampaigns.xml<Advertisements> <Ad> <Campaign>AspWorkshops</Campaign> <ImageUrl>AspWorkshopsBanner.gif</ImageUrl> <NavigateUrl>http://www.AspWorkshops.com</NavigateUrl> <AlternateText> Need ASP.NET Training? </AlternateText> <Impressions>2</Impressions> </Ad> <Ad> <Campaign>Superexpert</Campaign> <ImageUrl>SuperexpertBanner.gif</ImageUrl> <NavigateUrl>http://www.superexpert.com</NavigateUrl> <AlternateText> Click here to visit Superexpert.com! </AlternateText> <Impressions>1</Impressions> </Ad> </Advertisements> The C# version of this code can be found on the CD-ROM. Accepting File Uploads with the HTMLInputFile ControlIn many situations, you need to enable the users of your Web site to upload files to your Web server. For example, you might want to create a form that provides your users with a means to upload images if you are constructing an image library. Or you might want to build a central document repository to store Microsoft Word documents. You can use the HTMLInputFile control to enable users to transfer any type of file from their hard drive to your Web site. You can upload images, HTML files, Microsoft Word documents, MPEG files, or video files with the HTMLInputFile control. All the properties, methods, and events of this control are listed in Table 4.9. Table 4.9. HTMLInputFile Properties, Methods, and Events
The page in Listing 4.24 illustrates how you can create a simple upload form that enables you to upload an image file (GIF file). Any file uploaded with this form is saved with the name NewFile.gif in a folder named c:\uploads (you'll need to create this folder yourself). Listing 4.24 HtmlInputFile.aspx<Script Runat="Server"> Sub Button_Click( s As Object, e As EventArgs ) inpFileUp.PostedFile.SaveAs( "c:\Uploads\NewFile.gif" ) End Sub </Script> <html> <head><title>HtmlInputFile.aspx</title></head> <body> <form EncType="multipart/form-data" Runat="Server"> <input id="inpFileUp" Type="File" Runat="Server"> <p> <asp:Button Text="Upload File!" OnClick="Button_Click" Runat="Server" /> </form> </body> </html> The C# version of this code can be found on the CD-ROM. The HTMLInputFile is an HTML control (not a Web control). The control is declared on the page with the following tag: <input id="fileUp" Type="File" Runat="Server"> On Internet Explorer (version 3.02 and higher), or Netscape Navigator (version 3.0 or higher), this tag renders a text box field accompanied by a Browse button that enables you to select a file to upload from your hard drive (see Figure 4.12). Figure 4.12. Creating a file upload form with the HTMLInputFile control.
If you include an HTMLInputFile control in a form, you must change the default encoding format used by the form. You can change the encoding format by modifying the form's EncType property. The form in Listing 4.24 is created with the following tag: <form EncType="multipart/form-data" Runat="Server"> When the button is clicked and the file is uploaded, the Button_Click subroutine saves the file to disk. The file is saved with the following statement: inpFileUp.PostedFile.SaveAs( "c:\Uploads\NewFile.gif" ) The PostedFile property refers to whatever file was uploaded. Technically, this property refers to an instance of the HttpPostedFile class. Here, you are calling the SaveAs() method of the HttpPostedFile class to save the uploaded file to disk. The properties and methods of the HttpPostedFile class are listed in Table 4.10. Table 4.10. HttpPostedFile Properties, Methods, and Events
You can use the properties of the HttpPostedFile class to retrieve additional information about an uploaded file. For example, you can use the ContentLength property to check the size of a file and not save it when the file is too big. You can use the ContentType property to determine whether an uploaded file is an image file, a Microsoft Word document, or some other type of file. |