1. Trang chủ
  2. » Công Nghệ Thông Tin

C# 2005 Programmer’s Reference - chapter 20 pdf

66 331 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 66
Dung lượng 7,8 MB

Nội dung

ptg 448 CHAPTER 20 Silverlight LISTING 20.2 MainPage.xaml.cs (continued) buttonPlay.Content = “Pause”; } else if (videoPlayer.CanPause) { videoPlayer.Pause(); IsPlaying = false; buttonPlay.Content = “Play”; } } private void buttonStop_Click(object sender, RoutedEventArgs e) { videoPlayer.Stop(); IsPlaying = false; buttonPlay.Content = “Play”; } } } This is all the code you need to create your own media player on a website (see Figure 20.2). As you can see, it uses the familiar XAML and .NET code you are already used to. FIGURE 20.2 It requires very little effort to play most common types of media in a Silverlight application. From the Library of Skyla Walker ptg 449 Build a Download and Playback Progress Bar Build a Download and Playback Progress Bar Scenario/Problem: You want to display a progress bar that shows how much of the video is buffered as well as the current playback position. Solution: One thing every media content downloader needs is a bar that shows both download progress and playback position. Thankfully, Silverlight fully supports the concept of custom controls. Listing 20.3 shows the XAML, and Listing 20.4 shows the code-behind for this control. LISTING 20.3 PlayDownloadProgressControl.xaml <UserControl x:Class=”VideoPlayer.PlayDownloadProgressControl” xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml” Width=”400” Height=”300”> <Canvas x:Name=”LayoutRoot” Background=”White”> <Line x:Name=”DownloadProgress” X1=”0” Y1=”0” X2=”0” Y2=”0” Stroke=”DarkGray” Canvas.Left=”0” Canvas.Top=”2” StrokeThickness=”3”/> <Line x:Name=”PlaybackProgress” X1=”0” Y1=”0” X2=”0” Y2=”0” Stroke=”DarkGreen” Canvas.Left=”0” Canvas.Top=”2” StrokeThickness=”3”/> </Canvas> </UserControl> LISTING 20.4 PlayDownloadProgressControl.xaml.cs using System; using System.Net; using System.Windows; using System.Windows.Controls; namespace VideoPlayer { public partial class PlayDownloadProgressControl : UserControl { public PlayDownloadProgressControl() { InitializeComponent(); } From the Library of Skyla Walker ptg 450 CHAPTER 20 Silverlight LISTING 20.4 PlayDownloadProgressControl.xaml.cs (continued) public void UpdatePlaybackProgress(double playbackPercent) { PlaybackProgress.X2 = PlaybackProgress.X1 + (playbackPercent * LayoutRoot.ActualWidth / 100.0); } public void UpdateDownloadProgress(double downloadPercent) { DownloadProgress.X2 = DownloadProgress.X1 + (downloadPercent * LayoutRoot.ActualWidth / 100.0); } } } To incorporate this into video player app, add the following bolded lines to the MainPage.xaml file from Listing 20.1: <MediaElement Grid.Row=”0” x:Name=”videoPlayer” Stretch=”Fill” DownloadProgressChanged=”videoPlayer_DownloadProgressChanged” > </MediaElement> <local:PlayDownloadProgressControl x:Name=”progressBar” Height=”4” Grid.Row=”0” VerticalAlignment=”Bottom”/> <StackPanel Grid.Row=”1”> The DownloadProgressChanged event notifies you when a new chunk has been downloaded so you can update the progress: private void videoPlayer_DownloadProgressChanged(object sender, RoutedEventArgs e) { progressBar.UpdateDownloadProgress( 100.0 * videoPlayer.DownloadProgress); } However, there is no equivalent event for playback progress (which makes sense if you think about it: How often should an event like that fire anyway? Every millisecond? Every second? Every minute?) Because playback is application dependent, it is up to you to monitor the playing media and update your UI accordingly. This is the topic of the next section. From the Library of Skyla Walker ptg 451 Response to Timer Events on the UI Thread Response to Timer Events on the UI Thread Scenario/Problem: You want a timer that fires events on the UI thread so you don’t have to do the UI invoking yourself. Solution: There are a few different timers you can use for triggering events at specific intervals, but recall that all UI updates must occur from the UI thread. You can always use BeginInvoke to marshal a delegate to the UI thread, but there’s a simpler way. WPF and Silverlight provide the DispatcherTimer class in the System.Windows.Threading namespace, which always fires on the UI thread. You can use this timer for updating the playback progress. private System.Windows.Threading.DispatcherTimer timer = new System.Windows.Threading.DispatcherTimer(); public MainPage() { InitializeComponent(); //one second timer.Interval = new TimeSpan(0,0,1); timer.Start(); timer.Tick += new EventHandler(timer_Tick); } void timer_Tick(object sender, EventArgs e) { switch (videoPlayer.CurrentState) { case MediaElementState.Playing: case MediaElementState.Buffering: if (videoPlayer.NaturalDuration.HasTimeSpan) { double total = ➥videoPlayer.NaturalDuration.TimeSpan.TotalMilliseconds; if (total > 0.0) { double elapsed = ➥videoPlayer.Position.TotalMilliseconds; progressBar.UpdatePlaybackProgress( 100.0 * elapsed / total); } } break; From the Library of Skyla Walker ptg 452 CHAPTER 20 Silverlight default: //do nothing break; } } The DispatcherTimer is not Silverlight specific, and it can be used in any WPF app where you need a timer on the UI thread. NOTE Figure 20.3 shows the video application with the progress bar in action. FIGURE 20.3 Silverlight allows many of the same features of WPF, such as user controls. Put Content into a 3D Perspective Scenario/Problem: You want to put controls onto a 3D surface in a Silverlight application. Solution: You can use MediaElement.Projection to transform the MediaElement onto a 3D plane. Figure 20.4 shows the results. From the Library of Skyla Walker ptg 453 Make Your Application Run out of the Browser <MediaElement Grid.Row=”0” x:Name=”videoPlayer” Stretch=”Fill” DownloadProgressChanged=”videoPlayer_DownloadProgressChanged”> <MediaElement.Projection> <PlaneProjection RotationY=”45” RotationX=”-15”/> </MediaElement.Projection> </MediaElement> And like all other dependency properties, these can be animated. FIGURE 20.4 It’s easy to add a 3D perspective to your Silverlight app with the Projection property. Make Your Application Run out of the Browser Scenario/Problem: You want the user to be able to download and run the application without being connected to the Internet. Solution: When is a web application not a web application? When it’s been enabled to run straight from the desktop. First, add a small (say, 48×48 pixels) PNG image file to your solution and set its Build Action to Content. In the Silverlight tab of your project’s settings, there is a check box to enable running the application outside of the browser, in addition to a button that opens a dialog box enabling you From the Library of Skyla Walker ptg 454 CHAPTER 20 Silverlight to specify additional settings (such as the icon). Enabling this setting creates the file OutOfBrowserSettings.xml in the Properties folder of your project. It looks some- thing like the following: <OutOfBrowserSettings ShortName=”VideoPlayer Application” EnableGPUAcceleration=”True” ShowInstallMenuItem=”True”> <OutOfBrowserSettings.Blurb> VideoPlayer Application on your desktop; at home, ➥at work or on the go. </OutOfBrowserSettings.Blurb> <OutOfBrowserSettings.WindowSettings> <WindowSettings Title=”VideoPlayer Application” /> </OutOfBrowserSettings.WindowSettings> <OutOfBrowserSettings.Icons> <Icon Size=”48,48”>VideoPlayerIcon.png</Icon> </OutOfBrowserSettings.Icons> </OutOfBrowserSettings> When you right-click the application, you get an option to install it locally, as shown in Figure 20.5. FIGURE 20.5 It’s easy to make your Silverlight application available offline with some simple configuration settings. Once the app is installed, right-clicking it gives you the option to remove it from the local machine. From the Library of Skyla Walker ptg 455 Capture a Webcam Capture a Webcam Scenario/Problem: You want to display video output from an attached web camera. Solution: Use Silverlight 4’s support for video capture devices. To set this up, you need to first ask the user for permission to use the web cam. If granted, you can assign the device to a CaptureSource object and then assign that object to a VideoBrush. The VideoBrush can then be used as the Fill brush for the destination control (a Rectangle in this case). This technique is demonstrated in Listings 20.5 and 20.6. LISTING 20.5 MainPage.xaml <UserControl x:Class=”WebCam.MainPage” xmlns=”http://schemas.microsoft.com/ ➥winfx/2006/xaml/presentation” xmlns:x=”http://schemas.microsoft.com/ ➥winfx/2006/xaml” xmlns:d=”http://schemas.microsoft.com/ ➥expression/blend/2008” xmlns:mc=”http://schemas.openxmlformats.org/ ➥markup-compatibility/2006” mc:Ignorable=”d” d:DesignHeight=”300” d:DesignWidth=”400”> <Grid x:Name=”LayoutRoot” Background=”White”> <Rectangle x:Name=”videoRect” Fill=”Bisque” Width=”640” Height=”480” VerticalAlignment=”Top” HorizontalAlignment=”Left”/> <Button Content=”Start Webcam” Name=”buttonStartWebcam” Width=”98” Height=”23” HorizontalAlignment=”Left” VerticalAlignment=”Top” Click=”buttonStartWebcam_Click” /> </Grid> </UserControl> From the Library of Skyla Walker ptg 456 CHAPTER 20 Silverlight LISTING 20.6 MainPage.xaml.cs using System; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; namespace WebCam { public partial class MainPage : UserControl { CaptureSource _captureSource = null; public MainPage() { InitializeComponent(); } void StartWebcam() { if (_captureSource != null && _captureSource.State != CaptureState.Started) { if (CaptureDeviceConfiguration.AllowedDeviceAccess || CaptureDeviceConfiguration.RequestDeviceAccess()) { VideoCaptureDevice device = ➥CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice(); if (device != null) { _captureSource = new CaptureSource(); _captureSource.VideoCaptureDevice = device; _captureSource.Start(); VideoBrush brush = new VideoBrush(); brush.Stretch = Stretch.Uniform; brush.SetSource(_captureSource); videoRect.Fill = brush; } } } } From the Library of Skyla Walker ptg 457 Print a Document LISTING 20.6 MainPage.xaml.cs (continued) private void buttonStartWebcam_Click(object sender, RoutedEventArgs e) { StartWebcam(); } } } Print a Document Scenario/Problem: You want to print from Silverlight to a printer attached to the user’s computer. Solution: Silverlight 4 now contains printer support which you can easily take advantage of. Remember from Chapter 17, “Graphics with Windows Forms and GDI+,” that printing in .NET is similar to drawing on the screen. In Silverlight, to print, all you need to do is generate any UIElement-derived object and pass it to the printing system, as this code demonstrates: private void buttonPrint_Click(object sender, RoutedEventArgs e) { PrintDocument doc = new PrintDocument(); doc.PrintPage += new EventHandler<PrintPageEventArgs>(doc_PrintPage); doc.Print(); } void doc_PrintPage(object sender, PrintPageEventArgs e) { //simply set the PageVisual property to the UIElement //that you want to print e.PageVisual = canvas; e.HasMorePages = false; } The PrintPage event handler sets the PageVisual property to whatever control you want printed—it’s as easy as that. Too see the full example, see the SketchPad sample project in the accompanying source code. This sample app lets you draw with the mouse and then print the results. From the Library of Skyla Walker [...]... left blank From the Library of Skyla Walker PA R T I V Advanced C# IN THIS PART CHAPTER 21 LINQ 461 CHAPTER 22 Memory Management 473 CHAPTER 23 Threads, Asynchronous, and Parallel Programming 491 CHAPTER 24 Reflection and Creating Plugins 519 CHAPTER 25 Application Patterns and Tips 529 CHAPTER 26 Interacting with the OS and Hardware 575 CHAPTER 27 Fun Stuff and Loose Ends 597 APPENDIX Essential Tools... case, allBooks is a collection of Book objects The output is as follows: Le Rhin - 1842 Les Burgraves - 1843 Napoléon le Petit - 1852 Les Châtiments - 1853 Les Contemplations - 1856 Les Misérables – 1862 Order the Results Scenario/Problem: You want to organize the results in some order From the Library of Skyla Walker 464 CHAPTER 21 LINQ Solution: Use the orderby statement Here’s how to order the results... example later in this chapter Query XML Scenario/Problem: You want to extract data from XML documents Solution: LINQ contains its own set of XML-manipulation classes that are optimized for LINQ queries The syntax of the query itself is exactly the same as with plain objects: XDocument doc = XDocument.Load(“LesMis.xml”); var chaptersWithHe = from chapter in doc.Descendants( Chapter ) where chapter. Value.Contains(“... private Dictionary _cache = new Dictionary(); public void Add(TKey key, TValue value) { _cache[key] = new WeakReference(value); } public void Clear() { _cache.Clear(); } //since dead WeakReference objects could accumulate, //you may want to clear them out occasionally public void ClearDeadReferences() { foreach (KeyValuePair item in _cache)... appreciation for how much work goes into creating a good one), see Fabrice Marguerie’s LINQ to Amazon example at http://weblogs.asp.net/fmarguerie/ archive /200 6/06/26/Introducing-Linq-to-Amazon.aspx and in the book LINQ in Action From the Library of Skyla Walker 472 CHAPTER 21 LINQ Speed Up Queries with PLINQ (Parallel LINQ) Scenario/Problem: You want to take advantage of multiple processor cores during LINQ... doc.Descendants( Chapter ) where chapter. Value.Contains(“ he “) select chapter. Value; Console.WriteLine(“Chapters with ‘he’:”); foreach (var title in chaptersWithHe) { Console.WriteLine(title); } From the Library of Skyla Walker Query the Entity Framework 467 This example uses the same LesMis.xml file from Chapter 14’s XPath discussion The output is as follows: Chapters with ‘he’: What he believed What he thought Create... key) { WeakReference reference = null; if (_cache.TryGetValue(key, out reference) ) { /* Don’t check IsAlive first because the * GC could kick in right after anyway * Just retrieve the value and cast it It will be null * if the object was already collected * If you successfully get the Target value, * then you’ll create a strong reference, and prevent * it from being garbage collected */ return reference. Target... From the Library of Skyla Walker 474 CHAPTER 22 Memory Management One of the greatest advantages to using a managed language such as C# in the Common Language Runtime (CLR) environment is that you don’t have to worry about memory management as much as you did in languages such as C or C++ That said, there are still memory-related topics that you need to understand as a C# developer Furthermore, sometimes... collected when necessary Solution: The problem is that just holding a reference to an object prevents it from being garbage collected Enter WeakReference This simple Cache class uses WeakReference objects to store the actual values, allowing them to be garbage collected as needed public class Cache where TValue:class { //store WeakReference instead of TValue, //so they can be garbage collected... raw file handles, bitmaps, memory-mapped files, synchronization objects, or any other kernel object, you need to ensure that the resource is cleaned up Each of these resources is represented by handles To manipulate handles, you need to use native Windows functions via P/Invoke (see Chapter 26, “Interacting with the OS and Hardware”) From the Library of Skyla Walker 476 CHAPTER 22 Memory Management Solution: . XDocument.Load(“LesMis.xml”); var chaptersWithHe = from chapter in doc.Descendants( Chapter ) where chapter. Value.Contains(“ he “) select chapter. Value; Console.WriteLine(“Chapters with ‘he’:”); foreach (var title in chaptersWithHe) { Console.WriteLine(title); } From. IV Advanced C# IN THIS PART CHAPTER 21 LINQ 461 CHAPTER 22 Memory Management 473 CHAPTER 23 Threads, Asynchronous, and Parallel Programming 491 CHAPTER 24 Reflection and Creating Plugins 519 CHAPTER. Book objects. The output is as follows: Le Rhin - 1842 Les Burgraves - 1843 Napoléon le Petit - 1852 Les Châtiments - 1853 Les Contemplations - 1856 Les Misérables – 1862 Order the Results Scenario/Problem:

Ngày đăng: 12/08/2014, 09:23

TỪ KHÓA LIÊN QUAN

w