Home | | Internet & World Wide Web HOW TO PROGRAM | | Internet Programming | | Web Programming | Creating a Cover Viewer for Silverlight 1.1 Alpha

Chapter: Internet & World Wide Web HOW TO PROGRAM - Rich Internet Application Client Technologies - Microsoft ilverlight and Rich Internet Applications

| Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail |

Creating a Cover Viewer for Silverlight 1.1 Alpha

Our next example is a Deitel book cover viewer (Fig. 19.20) written in XAML (Fig. 19.21) with a Visual Basic code-behind file (Fig. 19.22) for Silverlight 1.1 Alpha

Creating a Cover Viewer for Silverlight 1.1 Alpha

 

Our next example is a Deitel book cover viewer (Fig. 19.20) written in XAML (Fig. 19.21) with a Visual Basic code-behind file (Fig. 19.22) for Silverlight 1.1 Alpha







Refresh. This cover viewer retrieves an RSS feed containing the image URIs, and displays three covers at a time. Clicking the cover on the left or right triggers an animation that moves the cover the user clicked to the center. You can test a live version of this application at  test.deitel.com/examples/iw3htp4/silverlight/CoverViewer/index.html.

 

Creating a Silverlight 1.1 Application in Visual Studio 2008

To create a Silverlight 1.1 Alpha Refresh project, open Visual Studio 2008 and select New Project in the File menu. Next, select Visual Basic (for your later projects, you can also se-lect Visual C#), then Silverlight, then specify the name and location of your project, and click OK. The project will initially contain a XAML file, Page.xaml, a code-behind file, Page.xaml.vb, Silverlight.js and the HTML wrapper, TestPage.html. You can work on this project in both Visual Studio and Expression Blend at the same time. When you make a change in one program, then switch to the other, it will alert you that the file has been modified outside the program and prompt you to reload the file. Select Yes to ensure that you include any changes you made in the other program.

 

At line 7 of Page.xaml (Fig. 19.21), we define the x:Class attribute, which specifies the Class that contains our event handlers, in this case the Page class in Page.xaml.vb (lines 9–159 of Fig. 19.22). The GUI contains two TextBlocks—titleTextBlock (lines 230–233) and errorTextBlock (lines 234–236)–and three Images—prevImage (lines 237–248), currentImage (lines 249–250) and nextImage (lines 251–262). Both next-Image and prevImage have a MouseLeftButtonDown attribute, registering the event handlers for this event.

 

1    <!-- Fig. 19.21: Page.xaml -->

 

2    <!-- Deitel Cover Viewer in Silverlight 1.1 Alpha Refresh -->

 

3    <Canvas

 

4          xmlns = "http://schemas.microsoft.com/client/2007"

 

5          xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"

 

6          x:Name = "parentCanvas" Loaded = "Page_Loaded"

 

7          x:Class = "CoverViewer.Page;assembly=ClientBin/CoverViewer.dll"

 

8          Width = "640" Height = "480" Background = "Black">

 

9          <Canvas.Resources>

 

10               <Storyboard x:Name = "nextImageAnimation"

 

11                      Completed = "nextImageSwitch">

12

13                      <!-- Lines 12-99 of the autogenerated code were -->

 

14                      <!-- removed to save space. -->

15

100            </Storyboard>

 

101            <Storyboard x:Name = "prevImageAnimation"

 

102                   Completed = "prevImageSwitch">

103

104                   <!-- Lines 103-226 of the autogenerated code were -->

 

105                   <!-- removed to save space. -->

106

227            </Storyboard>

 

228     </Canvas.Resources>

229      

230     <TextBlock x:Name = "titleTextBlock" Canvas.Left = "199.994"

 

231            Canvas.Top = "5" FontSize = "24" Width = "238.308"

 

232            TextWrapping = "Wrap" Foreground = "#FFFFFFFF"

 

233            Text = "Deitel Cover Viewer" />

 

234     <TextBlock x:Name = "errorTextBlock" Canvas.Left = "0"

 

235            Canvas.Top = "400" FontSize = "12" Width = "640"

 

236            TextWrapping = "Wrap" Foreground = "#FFFFFFFF" />

 

237     <Image x:Name = "prevImage" MouseLeftButtonDown = "prevImageHandler"

 

238            Width = "149.64" Height = "196.652" Canvas.Left = "8"

 

239            Canvas.Top = "142" RenderTransformOrigin = "0.5, 0.5" >

 

240            <Image.RenderTransform>

 

241                   <TransformGroup>

 

<ScaleTransform ScaleX = "1" ScaleY = "1" />

243                         <SkewTransform AngleX = "0" AngleY = "0" />

 

244                         <RotateTransform Angle = "0" />

 

245                         <TranslateTransform X = "0" Y = "0" />

 

246                   </TransformGroup>

 

247             </Image.RenderTransform>

 

248      </Image>

 

249      <Image x:Name = "currentImage" Width = "265.302" Height = "348.652"

 

250             Canvas.Left = "186" Canvas.Top = "64.79" />

 

251      <Image x:Name = "nextImage" MouseLeftButtonDown = "nextImageHandler"

 

252             Width = "149.64" Height = "196.652" Canvas.Left = "482.36"

 

253             Canvas.Top = "142" RenderTransformOrigin = "0.5, 0.5" >

 

254             <Image.RenderTransform>

 

255                   <TransformGroup>

 

256                         <ScaleTransform ScaleX = "1" ScaleY = "1" />

 

257                         <SkewTransform AngleX = "0" AngleY = "0" />

 

258                         <RotateTransform Angle = "0" />

 

259                         <TranslateTransform X = "0" Y = "0" />

 

260                   </TransformGroup>

 

261             </Image.RenderTransform>

 

262      </Image>

 

263    </Canvas>

 

Fig. 19.21 | Deitel Cover Viewer in Silverlight 1.1 Alpha Refresh.

 

In lines 10–100 (of which lines 12–99 are not shown to save space), the nextImageAnimation Storyboard moves and resizes the three images so that the nextImage replaces the currentImage, the currentImage replaces the prevImage, and the prevImage disappears. This animation code was generated using Expression Blend. To create this ani-mation, first click the Create new Storyboard button (Fig. 19.4). Name the Storyboard nextImageAnimation, and select the Create as a Resource checkbox. Then, select next-Image and click Record Keyframe. Move the time slider to 0.5 seconds, then move and resize the element so that it replaces currentImage. You can click the Play button to see a preview of the animation.

 

Storyboard nextImageAnimation has a Completed attribute (line 11) that specifies the event handler to be called when the animation is complete. In lines 101–227 (of which lines 103–226 are not shown to save space), the prevImageAnimation Storyboard moves and resizes the three images so that the prevImage replaces the currentImage, the currentImage replaces the nextImage, and the nextImage disappears. This animation also has a Completed attribute (line 102) that specifies the event handler to be called when the animation is complete.

 

Visual Basic Code-Behind File

The Visual Basic code-behind file, Page.xaml.vb (Fig. 19.22), begins by importing the class libraries the application will use (lines 3–7). Lines 9–10 specify that the Page class Inherits methods and properties from the Canvas class. Lines 13–15 declare the instance variables the application will use. These include imageURIArrayList (a List of the image Uris), currentImageIndex (which holds the index number of the Uri in imageURIArray-List to be displayed as the currentImage), and appRootURI (which uses the appRootURI-Gen method (lines 151–158) to find the root URI of the application at runtime).

 

1     ' Fig. 19.22: Page.xaml.vb

 

2     ' VB code-behind file for Cover Viewer.

 

3     Imports System.IO

 

4     Imports System.Text

 

5     Imports System.Windows.Browser

 

6     Imports System.Windows.Browser.Net

 

7     Imports System.Collections.Generic

8

9     Partial Public Class Page

 

10          Inherits Canvas

11

12          ' Instance variables

 

13          Dim currentImageIndex = 0 ' Initialize index of currentImage as 0

 

14          Dim imageURIArrayList As New List(Of Uri)() ' Create ArrayList of URIs

 

15          Dim appRootURI = appRootURIGen() ' Store application root URI

16

17          Public Sub Page_Loaded(ByVal o As Object, ByVal e As EventArgs)

 

18                 ' Required to initialize variables

 

19                 InitializeComponent()

20                 Try

 

Dim httpRequest As New  _

22

BrowserHttpWebRequest( _         

23        New Uri(appRootURI + "bookCoversRSS.xml"))          

24                   

25        ' Save response in variable

 

26        Dim httpResponse = httpRequest.GetResponse()

27       

28        ' Save response stream in variable

 

29        Dim httpResponseStream = httpResponse.GetResponseStream()

30       

 

 

31        Dim currentImageURI ' Store Image URI

32       

33        ' Create an XmlReader to parse the response stream

 

34        Using xmlReader As XmlReader = xmlReader.Create( _

 

New StreamReader(httpResponseStream))                  

35                               

36                                                                                                       

37        ' Start reading response stream, exit loop when done 

38                    While (xmlReader.Read())                                    

39                                                                                                       

40                                ' Find item element in response stream  

41                                If ((xmlReader.IsStartElement()) And _               

42                                ("item" = xmlReader.LocalName)) Then             

43                                                                                                       

44                                ' Create an XmlReader for item element 

45                                Using itemXMLReader As XmlReader = _         

46                                            xmlReader.ReadSubtree()            

47                                                                                                       

48                                ' Start reading item element, exit loop when done        

49                                While (itemXMLReader.Read())   

50                                                                                                       

51                                            ' Find image child element of item           

52                                            If (itemXMLReader.IsStartElement()) Then        

53                                            If ("image" = itemXMLReader.LocalName) Then          

54           

55   ' Save Uri of image into ArrayList   

56        currentImageURI = appRootURI + _ 

57        itemXMLReader.ReadElementContentAsString

58        imageURIArrayList.Add( _    

59        New Uri(currentImageURI))   

60   End If   

61   End If   

62   End While

63   End Using

64   End If   

65                              End While

 

66                       End Using

67

68                       ' Close BrowserHttpWebRequest

 

69                       httpResponse.Close()

70

71                       ' Initialize currentImage and nextImage Sources

 

72                       currentImage.Source = imageURIArrayList(currentImageIndex)

 

73                       nextImage.Source = imageURIArrayList(currentImageIndex + 1)

74           

75                 Catch ex As Exception

 

76                              errorTextBlock.Text = "Error: " & ex.Message

 

77                 End Try

 

78          End Sub ' Page_Loaded

79

80          ' Handle nextImageAnimation's Completed event

 

81          Private Sub nextImageSwitch(ByVal sender As Object, _

 

82                 ByVal e As EventArgs)

 

83                 nextImageAnimation.Stop()

84

85                 ' Test if at end of images

 

86                 If (currentImageIndex = (imageURIArrayList.Count - 2)) Then

 

87                       currentImageIndex += 1 ' Increment currentImageIndex

88

89                       ' Set Source of prevImage and currentImage

 

90                       prevImage.Source = imageURIArrayList(currentImageIndex - 1)

 

91                       currentImage.Source = imageURIArrayList(currentImageIndex)

 

92                       nextImage.Opacity = 0 ' Hide nextImage

93                 Else

 

94                       currentImageIndex += 1 ' Increment currentImageIndex

95

96                       ' Set Source of prevImage, currentImage and nextImage

 

97                       prevImage.Source = imageURIArrayList(currentImageIndex - 1)

 

98                       currentImage.Source = imageURIArrayList(currentImageIndex)

 

99                       nextImage.Source = imageURIArrayList(currentImageIndex + 1) 100 prevImage.Opacity = 1 ' Show prevImage

101               End If

 

102        End Sub ' nextImageSwitch

103        

104        ' Handle prevImageAnimation's Completed event

 

105        Private Sub prevImageSwitch(ByVal sender As Object, _

 

ByVal e As EventArgs)

prevImageAnimation.Stop()   

109               Test if at beginning of images

 

110               If (currentImageIndex = 1) Then

 

111                     currentImageIndex -= 1 ' Decrement currentImageIndex

 

112                     prevImage.Opacity = 0 ' Hide prevImage

113

114                     ' Set Source of currentImage and nextImage

 

115                     currentImage.Source = imageURIArrayList(currentImageIndex)

 

116                     nextImage.Source = imageURIArrayList(currentImageIndex + 1)

117               Else

 

118                     currentImageIndex -= 1 ' Decrement currentImageIndex

119

120                     ' Set Source of prevImage, currentImage and nextImage

 

121                     prevImage.Source = imageURIArrayList(currentImageIndex - 1)

 

122                     currentImage.Source = imageURIArrayList(currentImageIndex)

 

123                     nextImage.Source = imageURIArrayList(currentImageIndex + 1)

 

124                     nextImage.Opacity = 1 ' Show nextImage

125               End If

 

126        End Sub ' prevImageSwitch

127

128        ' Handle nextImage's MouseLeftButtonDown event

 

129        Private Sub nextImageHandler(ByVal sender As Object, _

 

130               ByVal e As EventArgs)

131

132               ' Make sure there are more images to the right

 

133               If (currentImageIndex < (imageURIArrayList.Count - 1)) Then

 

134                     nextImageAnimation.Begin()

135               End If

 

136        End Sub ' nextImageHandler

137

138        ' Handle prevImage's MouseLeftButtonDown event

 

139        Private Sub prevImageHandler(ByVal sender As Object, _

 

140               ByVal e As EventArgs)

141

142               ' Make sure there are more images to the left

 

143               If (currentImageIndex > 1) Then

 

144                     prevImageAnimation.Begin()

 

145               ElseIf (currentImageIndex > 0) Then

 

146                     prevImageAnimation.Begin()

147               End If

 

148        End Sub ' prevImageHandler

149

150        ' Generate root URI of application

 

151        Public Function appRootURIGen() As String

152        

153               ' Find root directory of application

 

154               Dim path = HtmlPage.DocumentUri.AbsolutePath

 

155               Dim lastSlash = path.LastIndexOf("/")

 

156               path = path.Substring(0, lastSlash + 1)

 

157               Return "http://" & HtmlPage.DocumentUri.Host & path

 

158        End Function ' appRootURIGen

 

159    End Class ' Page

 

Fig. 19.22 | VB code-behind file for Cover Viewer.

 

In method Page_Loaded (lines 17–78), line 19 initializes the application using the InitializeComponent method located in the autogenerated Page.g.vb file (located in the obj\Debug directory). This file takes any XAML elements that have an x:Name attribute, and uses the FindName method to map each element to a variable of the same name. This means that we do not have to do this manually, as we did for the Silverlight 1.0 Movie Viewer example. It also allows us to use Visual Studio’s IntelliSense feature to autocom-plete XAML element names in our code-behind file.

Lines 20–77 try to download an RSS file, bookCoversRSS.xml (Fig. 19.23), and create an array of image Uris. First, lines 21–23 create a BrowserHttpWebRequest object that downloads the RSS file located at the URI created by concatenating the appRootURI variable with bookCoversRSS.xml. Note that the BrowserHttpWebRequest object does not currently support cross-domain requests, so the application and the RSS file must be located on the same server. Lines 26 and 29 get the object used to manipulate the request’s response, then get the stream associated with that object. Lines 34–35 create an XmlReader object to parse the RSS content. The XmlReader class provides read-only access to the ele-ments in an XML document. Lines 38–65 contain a While loop in which the condition remains True until the XmlReader has reached the end of the RSS. Lines 41–42 search for an item element in the RSS, and lines 45–53 read the contents of that element and search for an image element inside the item element. Upon finding an image element, lines 56– 59 add the contents of the image element (the image’s filename) to the imageURIArray-List as a complete Uri including the application’s root Uri (appRootURI). Line 69 closes the BrowserHttpWebRequest. Lines 72–73 set the Source attribute of the currentImage and nextImage to the first and second elements of the imageURIArrayList. Lines 75–76 catch any exceptions and display the error message in the errorTextBlock.

 

1    <?xml version = "1.0" encoding = "ISO-8859-1" ?>

 

2    <!-- Fig. 19.23: bookCoversRSS.xml -->

 

3    <!-- RSS for Deitel book-cover viewer -->

 

4    <rss version = "2.0">

 

5          <link rel = "alternate" type = "application/rss+xml"

 

6                 title = "Deitel Cover Viewer" href = "http://www.deitel.com/" />

 

7          <channel>

 

8                 <title>Deitel Cover Viewer</title>

 

9                 <link>http://www.deitel.com/</link>

 

10               <description>View the Deitel book covers.</description>

 

11               <copyright>2008 Deitel And Associates</copyright>

 

12               <language>en-us</language>

13

14               <item>

 

15                      <title>C How to Program</title>

 

16                      <link>images/chtp5.jpg</link>

 

17                      <image>images/chtp5.jpg</image>

 

18               </item>

 

19               <item>

 

20                      <title>C++ How to Program</title>

 

21                      <link>images/cpphtp6.jpg</link>

 

22                      <image>images/cpphtp6.jpg</image>

 

</item>

24                <item>

 

25                      <title>Internet How to Program</title>

 

26                      <link>images/iw3htp4.jpg</link>

 

27                      <image>images/iw3htp4.jpg</image>

 

28                </item>

 

29                <item>

 

30                      <title>Java How to Program</title>

 

31                      <link>images/jhtp7.jpg</link>

 

32                      <image>images/jhtp7.jpg</image>

 

33                </item>

 

34                <item>

 

35                      <title>VB How to Program</title>

 

36                      <link>images/vbhtp3.jpg</link>

 

37                      <image>images/vbhtp3.jpg</image>

 

38                </item>

 

39                <item>

 

40                      <title>Visual C# How to Program</title>

 

41                      <link>images/vcsharphtp2.jpg</link>

 

42                      <image>images/vcsharphtp2.jpg</image>

 

43                </item>

 

44                <item>

 

45                      <title>Simply C++</title>

 

46                      <link>images/simplycpp.jpg</link>

 

47                      <image>images/simplycpp.jpg</image>

 

48                </item>

 

49                <item>

 

50                      <title>Simply VB 2005</title>

 

51                      <link>images/simplyvb2005.jpg</link>

 

52                      <image>images/simplyvb2005.jpg</image>

 

53                </item>

 

54                <item>

 

55                      <title>Simply Java</title>

 

56                      <link>images/simplyjava.jpg</link>

 

57                      <image>images/simplyjava.jpg</image>

 

58                </item>

 

59                <item>

 

60                      <title>Small C++ How to Program</title>

 

61                      <link>images/smallcpphtp5.jpg</link>

 

62                      <image>images/smallcpphtp5.jpg</image>

 

63                </item>

 

64                <item>

 

65                      <title>Small Java</title>

 

66                      <link>images/smalljavahtp6.jpg</link>

 

67                      <image>images/smalljavahtp6.jpg</image>

 

68                </item>

 

69         </channel>

 

70   </rss>

 

Fig. 19.23 | RSS for Deitel book-cover viewer.

 

 

Method appRootURIGen (Fig. 19.22, lines 151–158) first uses the HtmlPage element to find the AbsolutePath of the page. Lines 155–156 find the last forward slash (/) of the Uri and save the Uri up to that last slash as a string, using the Substring method. Line 157 returns a string concatenating "http://", the Silverlight application’s Host (the domain name or IP address of the server) and the path string.

 

Method nextImageHandler (lines 129–136) handles nextImage’s MouseLeftButton-Down event. Line 133 checks whether there are, in fact, additional book covers to the right.

 

If so, line 134 begins the nextImageAnimation Storyboard. Upon completion, this Storyboard will call the nextImageSwitch method (lines 81–102). Line 86 checks whether there is only one more book cover to the right, in which case it will increment the currentImageIndex by one (line 87), update the Source of prevImage and currentImage (90–91), and hide nextImage (line 92). If there is more than one book cover to the right, lines 94–100 will increment the currentImageIndex by one (line 94), update the Source of all three Images (lines 97–99), and ensure that prevImage is visible (line 100), in case the user is going from the first book cover (where prevImage would be hidden) to the second book cover. Methods prevImageHandler (lines 139–148) and prevImageSwitch (lines 105–126) provide the corresponding functionality for prevImage.


Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail


Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.