Docstoc

What's New in Silverlight 4 - WPF_Silverlight Comparision

Document Sample
What's New in Silverlight 4 - WPF_Silverlight Comparision Powered By Docstoc
					   What’s New in
    Silverlight 4


What’s New in Silverlight 4   Page 1 of 29
www.wintellect.com
TABLE OF CONTENTS

Table of Contents ...............................................................................................................................2
Introduction ......................................................................................................................................3
   Printing Support ........................................................................................................................................ 3
   Webcam and Microphone Support .......................................................................................................... 4
   Clipboard Access ....................................................................................................................................... 6
   Drag-and-Drop Support ............................................................................................................................ 7
   Trusted Applications ................................................................................................................................. 8
   COM Automation .................................................................................................................................... 10
   File-System Access .................................................................................................................................. 12
   HTML Hosting .......................................................................................................................................... 14
   Notification Windows ............................................................................................................................. 16
   Be Kind to the Environment .................................................................................................................... 18
   Commanding Support ............................................................................................................................. 18
   Right Mouse Button Support .................................................................................................................. 21
   Improved Element Data Binding ............................................................................................................. 22
   Implicit Styles .......................................................................................................................................... 24
   Managed Extensibility Framework ......................................................................................................... 25
   Other Enhancements .............................................................................................................................. 28




What’s New in Silverlight 4                                                                                                                  Page 2 of 29
www.wintellect.com
INTRODUCTION
Silverlight 4 is just around the corner, and the recently released beta is chock full of features intended to
help developers build richer Web applications than ever before. From printing support to HTML hosting,
there’s something there for everyone, whether they’re building line-of-business (LOB) applications or
smaller apps designed simply to add spice to a Web page. Silverlight 4 is the most ambitious version of
Silverlight yet—and it promises to be the most compelling, too.

The new features in Silverlight 4 are both rich and varied. They range from ones that add entirely new
capabilities to the platform, such as support for trusted applications that run in a relaxed sandbox
(among other things, trusted applications can access the file system without prompting the user, and
they can leverage COM automation servers installed on the host PC), to ones that merely make the
platform easier to work with, such as the new TextTrimming property added to the TextBlock class.
Together, these features open the door to kinds of applications that simply weren’t possible in
Silverlight 3.

This whitepaper surveys the new features of Silverlight 4 and provides numerous code snippets and
downloadable code samples to educate developers about the new capabilities and how to leverage
them. All samples are based on the Silverlight 4 beta released in November 2009.

To run the samples, you’ll need Visual Studio 2010 Beta 2 or Visual Web Developer Express 2010 Beta 2.
You’ll also need to install the Silverlight 4 Beta Tools for Visual Studio 2010. Download links can be found
on Microsoft’s Official Silverlight Web Site.


PRINTING SUPPORT
        One of the features developers have requested the most in Silverlight is the ability to print. This
        capability is especially important for line-of-business applications that present meaningful data
        that a user might wish to share or archive in the form of hardcopy.

        Silverlight 4’s printing API is embodied in the new System.Windows.Printing.PrintDocument
        class. The following code sample demonstrates printing at its simplest by printing the contents
        of the Silverlight control on a single page:

        PrintDocument doc = new PrintDocument();
        doc.DocumentName = "Silverlight Printing Demo";
        doc.PrintPage += new EventHandler<PrintPageEventArgs>(OnPrintPage);
        doc.Print();
          .
          .
          .
        void OnPrintPage(object sender, PrintPageEventArgs e)
        {
            e.PageVisual = Application.Current.RootVisual;
        }

        PrintPageEventArgs.PageVisual refers to the XAML element that you wish to print. It can refer to
        the element at the root of the XAML DOM, an element nested inside in the XAML DOM, or an

What’s New in Silverlight 4                                                                     Page 3 of 29
www.wintellect.com
        element that is manufactured solely for printing purposes and isn’t part of the XAML DOM. For
        example, the following PrintPage event handler prints “Hello, Silverlight” on a page, regardless
        of what content is currently visible in the Silverlight control:

        void OnPrintPage(object sender, PrintPageEventArgs e)
        {
            TextBlock tb = new TextBlock();
            tb.Text = "Hello, Silverlight";
            e.PageVisual = tb;
        }

        In addition to the PageVisual property, the PrintPageEventArgs class exposes public properties
        named PrintableArea and HasMorePages. PrintableArea reveals the dimensions of the printable
        page and can be used to size print content to the page. HasMorePages is the basis for multipage
        print documents. Setting HasMorePages to true in a PrintPage event handler tells Silverlight to
        fire another PrintPage event to print another page. The following code snippet uses
        HasMorePages to print a 10-page document with the page number (stored in a private field
        named _page) on each page:

        void OnPrintPage(object sender, PrintPageEventArgs e)
        {
            TextBlock tb = new TextBlock();
            tb.Text = _page.ToString();
            e.PageVisual = tb;

              e.HasMorePages = _page++ < 10;
        }

        In addition to firing a PrintPage event for each printable page, PrintDocument fires a StartPrint
        event at the beginning of each print job and an EndPrint event at the end. You could use these
        events to update a progress bar or activity display in order to provide visual feedback to the user
        as a print job progresses.


WEBCAM AND MICROPHONE SUPPORT
        In addition to adding printer support to the platform, Silverlight 4 introduces support for
        webcams and microphones. Six new classes provide API support for these devices:

                    Class                                       Description
          CaptureDeviceConfiguration     Provides methods for enumerating capture devices
                                         and requesting access to them
          AudioCaptureDevice             Represents audio capture devices (microphones)
          VideoCaptureDevice             Represents video capture devices (webcams)
          CaptureSource                  Provides API for starting and stopping captures and
                                         taking snapshots from running video captures
          AudioSink                      Provides access to captured audio streams
          VideoSink                      Provides access to captured video streams



What’s New in Silverlight 4                                                                    Page 4 of 29
www.wintellect.com
        Starting a capture is simplicity itself. The following code snippet starts an audio and video
        capture using the default audio and video capture devices. The capture is assigned to a
        VideoBrush, which in turn is used to paint a Rectangle:

        if (CaptureDeviceConfiguration.AllowedDeviceAccess ||
            CaptureDeviceConfiguration.RequestDeviceAccess())
        {
            // Create and configure a capture source
            CaptureSource cs = new CaptureSource();
            cs.VideoCaptureDevice =
                CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();
            cs.AudioCaptureDevice =
                CaptureDeviceConfiguration.GetDefaultAudioCaptureDevice();

              // Create a VideoBrush from the capture source and use it
              // to paint a Rectangle
              VideoBrush brush = new VideoBrush();
              brush.SetSource(cs);
              Rect.Fill = brush;

              // Start the capture
              cs.Start();
        }

        CaptureDeviceConfiguration.AllowedDeviceAccess determines whether the application can
        access capture devices without prompting the user. It returns true if the user was prompted to
        allow device access earlier in the same session and answered yes. If AllowedDeviceAccess
        returns false, CaptureDeviceConfiguration.RequestDeviceAccess prompts the user for
        permission to access capture devices:




        If the user answers yes, then the application is permitted to access capture devices. Otherwise,
        attempting to access them generates an exception.

        Rather than use the default audio and video capture devices, an application can enumerate the
        available devices and allow the user to specify which ones to use when a capture is started. The
        following statements display all available audio and video capture devices in a pair of ListBoxes:

        AudioSourcesListBox.ItemsSource =
            CaptureDeviceConfiguration.GetAvailableAudioCaptureDevices();
        VideoSourcesListBox.ItemsSource =
            CaptureDeviceConfiguration.GetAvailableVideoCaptureDevices();


What’s New in Silverlight 4                                                                    Page 5 of 29
www.wintellect.com
        The CaptureSource class provides a method named AsyncCaptureImage for snapping frames
        from running video captures. AsyncCaptureImage snaps an image from the video and passes a
        WriteableBitmap containing the image to a callback method.


CLIPBOARD ACCESS
        A new class named System.Windows.Clipboard provides static methods for accessing the system
        clipboard:

                 GetText, which retrieves Unicode text from the clipboard
                 SetText, which places Unicode text on the clipboard
                 ContainsText, which indicates whether the clipboard currently contains Unicode text

        In the Silverlight 4 beta, only Unicode text can be retrieved from the clipboard or added to it.
        The final release of Silverlight 4 is expected to support additional clipboard formats.

        The following code snippet attempts to retrieve a text string from the clipboard:

        try
        {
              if (Clipboard.ContainsText())
              {
                  string text = Clipboard.GetText();
                  // TODO: Use the text retrieved from the clipboard
              }
        }
        catch (SecurityException ex)
        {
            MessageBox.Show(ex.Message);
        }

        If the application is running in the browser or if it's running outside the browser without
        elevated permissions, the call to GetText produces a confirmation dialog:




        If the user answers yes, the application is permitted to access the clipboard. Otherwise, a
        SecurityException is thrown. Note that if the user answers yes when asked if the application can
        access the clipboard, the answer is cached for the duration of the session to prevent the prompt
        from appearing again and again.




What’s New in Silverlight 4                                                                    Page 6 of 29
www.wintellect.com
        Of course, the dialog is suppressed if the application is running outside the browser with
        elevated permissions. Out-of-browser apps (OOBs) with elevated permissions, new in Silverlight
        4, are described in the section entitled “Trusted Applications.”


DRAG-AND-DROP SUPPORT
        Silverlight 2 introduced the System.Windows.Controls.OpenFileDialog class, which allows users
        to browse for files using an OpenFileDialog (and applications to open files that the user selects).
        Silverlight 4 offers an additional mechanism for opening files: drag-and-drop. Files dragged from
        the operating system shell or other source and dropped onto a running Silverlight application
        can be consumed in much the same way as files selected in an OpenFileDialog.

        Silverlight 4 adds a new property named AllowDrop to the UIElement class. Setting this property
        to true allows a UI element to fire drag-and-drop events:

        <Rectangle AllowDrop="true" ... />

        Silverlight 4 adds four new events to the UIElement class to support drag-and-drop:

               Event                                     Description
          DragEnter           Fired when a cursor carrying a payload enters a drop target
          DragOver            Fired when a cursor carrying a payload moves over a drop target
          Drop                Fired when data is dropped onto a drop target
          DragLeave           Fired when a cursor carrying a payload leaves a drop target

        The following Drop event handler demonstrates how to enumerate the files provided to the
        drop target:

        void OnDrop(object sender, DragEventArgs e)
        {
            if (e.Data != null)
            {
                FileInfo[] files = e.Data.GetData(DataFormats.FileDrop) as FileInfo[];

                   foreach (FileInfo fi in files)
                   {
                       // TODO: Process the file
                   }
              }
        }

        The sample application pictured below demonstrates the mechanics of Silverlight drag-and-
        drop. It accepts picture files (JPEGs and PNGs) dragged from My Pictures and other file-system
        sources and displays the pictures to the user. You can click a picture to bring it to the forefront,
        or move it around the page to make room for more. Moreover, you can download the
        application, complete with source code, and try it for yourself.




What’s New in Silverlight 4                                                                     Page 7 of 29
www.wintellect.com
TRUSTED APPLICATIONS
        Prior to Silverlight 4, Silverlight applications always ran in a security sandbox that prevented
        them from doing harm to host computers but also limited their functionality.

        One of the most compelling and talked-about new features of Silverlight 4 is support for
        applications with elevated permissions, also known as trusted applications. An application with
        elevated permissions can perform actions that a sandboxed application can not. For example, it
        can access the local file system, and on Windows boxes, it can interact with COM automation
        servers. Here is a summary of the features that are available only to trusted applications:

                Trusted applications can interact with COM automation servers on platforms that
                 support COM automation. COM automation support is described in the section entitled
                 “COM Automation.”
                Trusted applications can interact with the local file system without displaying an
                 OpenFileDialog or SaveFileDialog. Direct file system access is described in the section
                 entitled “File System Access.”
                Trusted application can access the system clipboard without prompting the user for
                 permission. Silverlight 4’s new clipboard support is described in the section entitled
                 “Clipboard Access.”
                Trusted applications can perform cross-domain networking, even if the targeted servers
                 lack policy files granting permission for cross-domain accesses to occur.
                Trusted applications can use the new WebBrowser control and HtmlBrush class to
                 render content from remote domains. WebBrowser and HtmlBrush are described in the
                 section entitled “HTML Hosting.”


What’s New in Silverlight 4                                                                     Page 8 of 29
www.wintellect.com
                Trusted applications can enter full-screen mode at any time, whereas partial-trust
                 applications can only go full screen in response to user input events.
                Trusted applications continue to receive keyboard events when running full-screen,
                 whereas keyboard input is suspended when partial-trust applications go full-screen.

        Applications can only have elevated permissions when run out-of-browser, and only then if the
        user okays those permissions when the app is installed. When you configure a Silverlight app to
        run out-of-browser, you now have the option of requesting elevated permissions by checking
        “Require elevated trust when running outside the browser:”




        When the user installs the application, he or she is warned that the application requires
        elevated permissions and given the opportunity to say no:




What’s New in Silverlight 4                                                                  Page 9 of 29
www.wintellect.com
        If the user clicks “Install,” then the application is installed as an OOB and runs with elevated
        permissions each and every time it is executed.

        An application can determine at run-time whether it is running with elevated permissions by
        consulting the new HasElevatedPermissions property added to the Application class in Silverlight
        4:

        if (Application.Current.HasElevatedPermissions)
        {
             // Running with elevated permissions
        }
        else
        {
             // NOT running with elevated permissions
        }

        Obviously, an application can’t grant itself elevated permissions if the user didn’t grant those
        permissions at install time.


COM AUTOMATION
        Silverlight 4's new System.Windows.Interop.ComAutomationFactory class provides an API for
        instantiating COM automation objects and for determining whether COM automation is even
        available. (It’s not available if the app is running without elevated permissions, or if it's running
        on a platform that doesn’t support COM, such as the Macintosh.) C# 4.0's new dynamic keyword
        provides a means for interacting with automation objects, which by definition are late-bound
        (meaning they expose features to clients using an IDispatch interface).

        One practical example of what you can do with Silverlight's COM automation support is sending
        an e-mail message via Outlook:

        if (ComAutomationFactory.IsAvailable)
        {


What’s New in Silverlight 4                                                                    Page 10 of 29
www.wintellect.com
              dynamic outlook =
                  ComAutomationFactory.CreateObject("Outlook.Application");
              dynamic mail = outlook.CreateItem(0);
              mail.Recipients.Add("webmaster@contoso.com");
              mail.Subject = "Hello, Silverlight";
              mail.Body = "This message was sent from Silverlight 4";
              mail.Save();
              mail.Send();
        }

        The code is exceedingly simple and it works just fine if Outlook is installed on the client and the
        user OKs the prompt from Outlook warning that an external application is attempting to use it.
        For added robustness, you should catch the System.Exception thrown from
        ComAutomationFactory.CreateObject if object creation fails. That's exactly what will happen if
        Outlook isn't installed on the host PC.

        Another example of a feature that COM automation support brings to the table is the ability for
        a Silverlight application to launch another application—in this case, Notepad:

        if (ComAutomationFactory.IsAvailable)
        {
            dynamic command = ComAutomationFactory.CreateObject("WScript.Shell");
            command.Run("c:\\windows\\notepad.exe", 1, true);
        }

        Yet another potential use for COM automation support is using Microsoft’s speech automation
        server, which is present on most Windows PCs, to add voice to your Silverlight applications. The
        sample application pictured below, which you can download in order to see (and hear) it in
        action, uses speech to verbalize error messages:




        Clicking a button produces an Exception. If you click a button while the application is running
        inside the browser or outside the browser but without elevated permissions, the error message
        encapsulated in the exception is displayed in a message box. However, if you do the same with
        the application running with elevated permissions outside the browser, a friendly voice reads
        the error message out loud.



What’s New in Silverlight 4                                                                   Page 11 of 29
www.wintellect.com
FILE-SYSTEM ACCESS
        Another privilege that trusted applications enjoy is the ability to access parts of the local file
        system without prompting the user with an OpenFileDialog or SaveFileDialog. This feature opens
        the door to types of applications that simply weren't possible in Silverlight 3.

        File access is limited to certain locations on the hard disk: primarily the "My" folders such as My
        Documents, My Pictures, and My Music. But within those constraints, file-system access works
        essentially the same in Silverlight as it does in .NET. You generally begin by calling
        Environment.GetFolderPath to acquire a path to the folder you wish to access. The following
        code snippet enumerates the files in My Documents and stuffs the file names into a ListBox
        named FileList:

        string path =
        Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

        foreach (string file in Directory.EnumerateFiles(path))
        {
            FileList.Items.Add(file.Substring(file.LastIndexOf('\\') + 1));
        }

        Of course, you're not limited to enumerating files. You can open files, create files, and delete
        files, and you can do the same with directories. Plus, there's no limit on the amount of data you
        can write to the hard disk since the user okayed the elevated permissions when the application
        was installed.

        The sample application pictured below, which is a Silverlight front end to the user’s My Pictures
        folder, demonstrates direct file access in action. When started, it populates a TreeView control
        with all the folders and subfolders in your My Pictures directory. You can expand and collapse
        branches of the tree, and when you select a folder, the right half of the window displays
        thumbnail images of all the PNGs and JPGs in that directory. You can then click a thumbnail to
        see a close-up of the picture in a child window. Click the picture (or the X in the child window's
        upper right corner) to close the child window and continue browsing photos.




What’s New in Silverlight 4                                                                   Page 12 of 29
www.wintellect.com
        The code to populate the TreeView with folder names looks like this:

        if (Application.Current.HasElevatedPermissions)
        {
            string path =
                Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);

              foreach (string dir in Directory.EnumerateDirectories(path))
              {
                  TreeViewItem item = new TreeViewItem();
                  item.Header = dir.Substring(dir.LastIndexOf('\\') + 1);
                  DirectoryTree.Items.Add(item);
                  ProcessFolder(dir, item.Items);
              }
        }

        ProcessFolder is a recursive method that’s implemented this way:

        private void ProcessFolder(string path, ItemCollection items)
        {
            foreach (string dir in Directory.EnumerateDirectories(path))
            {
                TreeViewItem item = new TreeViewItem();
                item.Header = dir.Substring(dir.LastIndexOf('\\') + 1);
                items.Add(item);
                ProcessFolder(dir, item.Items);
            }
        }

        You can download the source code and try it for yourself. Don’t forget that the application must
        run outside the browser in order for file access to work.

What’s New in Silverlight 4                                                                Page 13 of 29
www.wintellect.com
HTML HOSTING
        Another key new feature of Silverlight 4—and one that’s only available to out-of-browser
        applications—is the ability to host HTML and script content. OOBs with elevated permissions
        can download HTML and script content from anywhere, even if that content is located in a
        remote domain. OOBs without elevated permissions can download HTML and script content,
        but only if it’s located in the host domain (the domain from which the Silverlight application was
        downloaded.) Applications that run inside the browser cannot display HTML content.

        Silverlight’s HTML hosting support isn't limited to static HTML content; the content can be
        interactive and can include script. It can even be Flash content or content that includes other
        Silverlight controls.

        To host HTML content in Silverlight, you can use either a WebBrowser control or an HtmlBrush.
        One way to display HTML content is to fire up a WebBrowser control and point it to a URL:

        <WebBrowser x:Name="WebBrowserControl" Source="http://www.bing.com" />

        Another way to do it is to call NavigateToString and pass a string of content to the WebBrowser
        control:

        WebBrowserControl.NavigateToString("<h1>Hello, Silverlight</h1>");

        If an OOB isn’t trusted, it can only display content that comes from the same domain as the
        Silverlight application. However, you can use a little trick to display cross-domain content in
        OOBs that run without elevated permissions—simply pass an IFRAME targeting the remote
        content to NavigateToString:

        WebBrowserControl.NavigateToString("<iframe src=\"http://www.bing.com\"
        style=\"width: 100%; height: 100%\"></iframe>");

        You can render HTML content with HtmlBrush, too. The following XAML snippet paints a
        Rectangle with content retrieved from Bing:

        <WebBrowser x:Name="WebBrowserControl" Source="http://www.bing.com" />
        <Rectangle>
            <Rectangle.Fill>
                <HtmlBrush SourceName="WebBrowserControl" />
            </Rectangle.Fill>
        </Rectangle>

        One difference between WebBrowser and HtmlBrush is that the former displays "live" content,
        while the latter does not. Another difference is that HtmlBrush can have transforms applied to
        it, while WebBrowser cannot. For snazzy visual effects involving HTML content like the HTML
        puzzle demoed at the PDC, you'll probably find yourself using HtmlBrush. To display live,
        interactive content, you'll find WebBrowser more useful instead.

        One of the more interesting features of the WebBrowser control is that you can use its
        InvokeScript method to call JavaScript functions in content hosted by the control. Conversely,

What’s New in Silverlight 4                                                                   Page 14 of 29
www.wintellect.com
        JavaScript hosted inside a WebBrowser control can call window.external.Notify to raise
        ScriptNotify events that can be handled in C#.

        The application pictured below demonstrates why the ability to call to and from script in a
        WebBrowser control might be useful (and how it works). It plays YouTube video using YouTube's
        API player and uses the player's JavaScript API to drive the video playback from C#. The app runs
        as an OOB and requires elevated permissions. The video it plays shows a radio-control jet
        getting a workout at a recent jet meet near Atlanta, GA. You can download the app and install it
        on your PC to try it out. Don't forget that it has to run outside the browser.




        The sample application uses a WebBrowser control to host the YouTube player. The content is
        stored in a text file packaged as a loose file inside the XAP file. It's extracted from the XAP with
        Application.GetResourceStream and passed to the WebBrowser control via NavigateToString:

        // Read the HTML content from the XAP
        StreamResourceInfo sri = Application.GetResourceStream
            (new Uri("YouTubePlayer.txt", UriKind.Relative));
        StreamReader reader = new StreamReader(sri.Stream);
        string content = reader.ReadToEnd();

        // Feed the content to the WebBrowser control
        Player.NavigateToString(content);

        The content itself includes a mix of HTML and JavaScript (mostly JavaScript). The script
        instantiates the YouTube player, forwards certain events from the player to the application so
        they can be handled in C#, and provides a thin JavaScript API layer that the application calls via
        InvokeScript to control playback of the video. For example, when the user clicks the Play,
        Pause, and Stop buttons, the application uses InvokeScript to call script funtions named play,
        pause, stop, and cue:

What’s New in Silverlight 4                                                                     Page 15 of 29
www.wintellect.com
        private void OnPlay(object sender, RoutedEventArgs e)
        {
             Player.InvokeScript("play");
        }

        private void OnPause(object sender, RoutedEventArgs e)
        {
            Player.InvokeScript("pause");
        }

        private void OnStop(object sender, RoutedEventArgs e)
        {
             Player.InvokeScript("stop");
             Player.InvokeScript("cue", "df6x4U0u7iQ");
        }

        Similarly, when the state of the player changes—for example, when video playback begins or
        ends—script inside the control uses window.external.Notify to fire a ScriptNotify event in C# and
        activate a handler that updates the visual states of the buttons:

        function onYouTubePlayerStateChange(state) {
            // Ask the Silverlight control to update the YouTube video player
            var state = document.getElementById("apiplayer").getPlayerState();
            window.external.Notify('Update:' + state.toString());
        }

        The end result is an application that demonstrates some of the more advanced features of the
        WebBrowser control and does something interesting, too.


NOTIFICATION WINDOWS
        Another feature of Silverlight 4 designed to richen the out-of-browser experience is support for
        notification windows, also known as “toast” windows. This feature is available to all OOBs,
        regardless of whether they are trusted. It is not available to applications inside the browser.

        A notification window is one that pops up in the lower right corner of the screen, similar to the
        ones that Outlook uses to notify users about incoming e-mails. (On the Macintosh, notification
        windows appear at the top of the screen rather than the bottom.) Notification windows are
        normally used to let the user know something important has happened. A classic use for them is
        to inform the user that an updated version of an out-of-browser application is available when
        the OOB is launched from the desktop or Start menu:




What’s New in Silverlight 4                                                                Page 16 of 29
www.wintellect.com
        This notification window was created by first declaring a user control named
        UpdateNotification:

        <Grid x:Name="LayoutRoot">
            <Border x:Name="Frame" Width="300" Height="100" Background="LightYellow">
                <StackPanel Orientation="Vertical">
                    <Border Width="290" Height="24" CornerRadius="4" Margin="2,4,2,4">
                        <Border.Background>
                            <LinearGradientBrush StartPoint="0.5,0.0"
                                EndPoint="0.5,1.0">
                                <GradientStop Offset="0.2" Color="#FF1C68A0" />
                                <GradientStop Offset="1.0" Color="#FF54A7E2" />
                            </LinearGradientBrush>
                        </Border.Background>
                        <Border.Effect>
                            <DropShadowEffect BlurRadius="4" ShadowDepth="4"
                                Opacity="0.4" />
                        </Border.Effect>
                        <TextBlock Text="Update Available" FontSize="12"
                            FontWeight="Bold" Foreground="White" Margin="4" />
                    </Border>
                    <StackPanel Orientation="Horizontal">
                        <Image Source="Images/Update.png" Width="32" Height="34"
                            Stretch="Fill" Margin="4" VerticalAlignment="Top" />
                        <TextBlock Width="240" Text="An updated version..."
                            FontSize="11" Foreground="#FF202020" TextWrapping="Wrap"
                            Margin="4" />
                    </StackPanel>
                </StackPanel>
            </Border>
        </Grid>

        Then it was displayed by creating an instance of System.Windows.NotificationWindow,
        instantiating the user control and assigning it to the NotificationWindow’s Content property,
        and calling NotificationWindow.Show:

        NotificationWindow win = new NotificationWindow();
        UpdateNotification un = new UpdateNotification();
        win.Width = un.Width;
        win.Height = un.Height;
        win.Content = un;
        win.Show(10000);

        The parameter passed to NotificationWindow.Show is a time-out parameter that specifies how
        long the notification window will be displayed—in this case, 10 seconds. If desired, you can call
        NotificationWindow.Close to close the notification window early—for example, in response to a
        mouse click.

        One restriction placed on notification windows is that they can’t be partially transparent as
        Outlook’s notification windows are. Another restriction—at least in the beta—is that they must



What’s New in Silverlight 4                                                                 Page 17 of 29
www.wintellect.com
        be rectangular: that is, they can’t have rounded corners. Hopefully these limitations are minor
        enough that they won’t dissuade developers from using this feature.


BE KIND TO THE ENVIRONMENT
        In Silverlight 3, out-of-browser applications had limited control over their environment—
        specifically, over the windows in which they were hosted. It was not possible, for example, for
        an OOB to resize the window in which it was hosted, or to change the window title at run-time.

        This changes in Silverlight 4 with the addition of the System.Windows.Window class and the
        new Application.MainWindow property. An out-of-browser application can get a reference to its
        window through the MainWindow property, and it can use Window properties and methods to
        interrogate and even modify the host window. The following code snippet resizes the OOB’s
        window programmatically:

        Window win = Application.Current.MainWindow;
        win.Width = 1024;
        win.Height = 768;

        Window also features properties named Left and Top for repositioning host windows,
        WindowState for minimizing, maximizing, and restoring host windows, and TopMost for
        controlling the host window’s topmost state. It also includes an Activate method for bringing a
        host window to the foreground and assigning it the focus.


COMMANDING SUPPORT
        One of the most understated but potentially impactful features of Silverlight 4 is a pair of
        properties named Command and CommandParameter added to the ButtonBase and Hyperlink
        classes. These properties represent the first real support in Silverlight for commanding, which is
        primarily beneficial to Model-View-ViewModel (MVVM) applications. MVVM has long been
        popular among WPF developers and is rapidly gaining popularity with Silverlight developers. And
        now, thanks to commanding, Silverlight comes a little closer to supporting pure MVVM
        implementations without help from auxiliary frameworks such as Prism.

        The sample RSS viewer below demonstrates Silverlight 4's new commanding infrastructure. You
        type an RSS URL into a TextBox and click the "View" button. The application responds by using a
        WebClient to fetch the RSS feed, and then data-binding the feed items to a ListBox to display
        them on the screen:




What’s New in Silverlight 4                                                                 Page 18 of 29
www.wintellect.com
        Because this is an MVVM application, the source code is structured differently than that of a
        traditional, non-MVVM app. First, the model is implemented in the RssModel class. RssModel
        exposes a method named GetRssFeedAsync that the view-model can use to fetch a live RSS
        feed. It also implements a couple of events: an RssLoadComplete event that fires following a
        successful RSS download, and an RssLoadError event that fires if an RSS download fails. These
        methods and events are part of an interface named IRssProvider, which you could mock in a
        unit-testing scenario to provide RSS content from a local source rather than a network source.

        Second, the view-model is implemented in a class named RssViewModel. Part of the intent of
        the view-model is to provide properties that the view can bind to to populate controls with
        data. To that end, RssViewModel exposes a string property named RssUri which can be bound to
        the TextBox in the view, and an ObservableCollection property named RssFeed that can be
        bound to the ListBox. It also implements a read-only ICommand property named GetRssFeed
        that returns an instance of a class named GetRssFeedCommand. This is where commanding
        enters the picture in Silverlight 4.

        Open the code-behind file for the view (RssView.xaml.cs) and you'll see that it contains no code
        other than a constructor that calls InitializeComponent. In Silverlight 3, you would have had to
        include a Click event handler that calls into the view-model to fetch the RSS feed and stuff the
        RSS items into the RssFeed property. Thanks to the command infrastructure in Silverlight 4, this
        can be accomplished declaratively. First, the view declares an instance of the view-model:

        <UserControl.Resources>
            <local:RssViewModel x:Key="RssViewModel" />
        </UserControl.Resources>


What’s New in Silverlight 4                                                                Page 19 of 29
www.wintellect.com
        Then it binds the view-model to the DataContext property of the Grid containing the TextBox,
        ListBox, and Button:

        <Grid x:Name="LayoutRoot" Background="#FFF4B3FA"
            DataContext="{StaticResource RssViewModel}">

        The TextBox's Text property and the ListBox's ItemsSource property are bound to the view-
        model's RssUri and RssFeed properties:

        <TextBox Text="{Binding RssUri, Mode=TwoWay}" ... />
        <ListBox ItemsSource="{Binding RssFeed}" ... >

        More importantly, the Button is bound to the view-model this way:

        <Button Command="{Binding GetRssFeed}"
            CommandParameter="{Binding RssUri}" ... />

        Observe that the Button declaration doesn't contain a Click attribute; in other words, the Click
        event isn't bound to an event handler in the code-behind. Instead, when the button is clicked, it
        invokes the command exposed through the view-model's GetRssFeed property. That command
        is implemented this way:

        public class GetRssFeedCommand : ICommand
        {
            private IRssProvider _model;
            private ObservableCollection<SyndicationItem> _feed;

              public GetRssFeedCommand(ObservableCollection<SyndicationItem> feed,
                  IRssProvider model)
              {
                  _feed = feed;
                  _model = model;
              }

              public event EventHandler CanExecuteChanged;

              public bool CanExecute(object parameter)
              {
                  return true;
              }

              public void Execute(object parameter)
              {
                  _model.RssLoadComplete +=
                      new EventHandler<RssEventArgs>(OnRssLoadComplete);
                  _model.GetRssFeedAsync(new Uri((string)parameter, UriKind.Absolute));
              }

              void OnRssLoadComplete(object sender, RssEventArgs e)
              {
                  if (_feed != null) // Just to be sure
                  {


What’s New in Silverlight 4                                                                 Page 20 of 29
www.wintellect.com
                         _feed.Clear();

                         using (XmlReader reader = XmlReader.Create(e.Result))
                         {
                             SyndicationFeed feed = SyndicationFeed.Load(reader);

                              foreach (SyndicationItem item in feed.Items)
                                  _feed.Add(item);
                         }
                   }
              }
        }

        At run-time, invoking the command causes its Execute method to be called, and the command
        responds by using the model to fetch the RSS feed and parsing the feed items into the view-
        model's RssFeed property. Thanks to the data binding between that property and the ListBox,
        and because RssFeed is an ObservableCollection, the items promptly appear in the ListBox.

        The binding between the Button and the view-model's GetRssFeed property is possible because
        of the Command property added to the Button class (actually, to ButtonBase) in Silverlight 4. In
        addition, Button now contains a CommandParameter property that can be used to pass a
        parameter to the command. In this example, CommandParameter is bound to the view-model's
        RssUri property, which ensures that the URL typed by the user is available to the command
        when the command is invoked.


RIGHT MOUSE BUTTON SUPPORT
        Silverlight 4 is the first version of Silverlight to include support for the right mouse button. That
        support comes in the form of two new events added to the UIElement class:
        MouseRightButtonDown and MouseRightButtonUp. These events fire when the right mouse
        button does down over a UI element, and when it goes up.

        The following example changes a Rectangle’s fill color from yellow to red when the Rectangle is
        clicked with the right mouse button. Setting MouseButtonEventArgs.Handled to true in the
        event handler suppresses the Silverlight context menu that normally appears when a right click
        occurs over a Silverlight control:

        <!-- XAML -->
        <Rectangle Width="300" Height="200" Fill="Yellow"
            MouseRightButtonDown="OnRightButtonDown" />
              .
              .
              .
        // C#
        void OnRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            (sender as Rectangle).Fill = new SolidColorBrush(Colors.Red);
            e.Handled = true;
        }


What’s New in Silverlight 4                                                                     Page 21 of 29
www.wintellect.com
        On PCs whose mouse has just one button, users can generally simulate a right-click by holding
        down the Control key and while clicking the mouse button.


IMPROVED ELEMENT DATA BINDING
        Silverlight 3 introduced element-to-element data binding, also known as element data binding,
        enabling XAML objects to be bound together declaratively. The simplest example of element
        data binding is a TextBlock bound to a TextBox so that text typed into the TextBox is echoed in
        the TextBlock:

        <TextBox x:Name="Input" />
        <TextBlock Text="{Binding Text, ElementName=Input}" />

        One limitation of element data binding in Silverlight 3 was that the target of the binding—in this
        example, the TextBox—had to derive from FrameworkElement. This meant that shapes and
        controls such as Rectangle and TextBox could participate in element data binding, but non-
        FrameworkElement-derivatives such as PlaneProjection could not.

        In order to element-data-bind a PlaneProjection to a Slider control in Silverlight 3, you had to
        invert the binding (apply the binding to the Slider rather than the PlaneProjection) and make it a
        2-way binding. The following example binds three Slider controls to the RotationX, RotationY,
        and RotationZ properties of a PlaneProjection to allow a user control to be rotated around the X,
        Y, and Z axes:

        <Grid x:Name="LayoutRoot" Background="White">
            <Border>
                <Border.Projection>
                     <PlaneProjection x:Name="Projector" />
                </Border.Projection>
                <user:PenguinUserControl />
            </Border>
            <StackPanel Orientation="Vertical" VerticalAlignment="Top">
                <Slider Minimum="0" Maximum="360"
                Value="{Binding RotationX, ElementName=Projector, Mode=TwoWay}"
                     Width="400" VerticalAlignment="Top" Margin="0,20,0,0" />
                <Slider Minimum="0" Maximum="360"
                Value="{Binding RotationY, ElementName=Projector, Mode=TwoWay}"
                     Width="400" VerticalAlignment="Top" Margin="0,20,0,0" />
                <Slider Minimum="0" Maximum="360"
                Value="{Binding RotationZ, ElementName=Projector, Mode=TwoWay}"
                     Width="400" VerticalAlignment="Top" Margin="0,20,0,0" />
            </StackPanel>
        </Grid>

        This example produces the following UI:




What’s New in Silverlight 4                                                                 Page 22 of 29
www.wintellect.com
        Silverlight 4 enhances element data binding by extending it to DependencyObject derivatives,
        allowing the previous example to be rewritten in a more intuitive fashion:

        <Grid x:Name="LayoutRoot" Background="White">
            <user:PenguinUserControl>
                <user:PenguinUserControl.Projection>
                    <PlaneProjection
                        RotationX="{Binding Value, ElementName=SliderX}"
                        RotationY="{Binding Value, ElementName=SliderY}"
                        RotationZ="{Binding Value, ElementName=SliderZ}" />
                </user:PenguinUserControl.Projection>
            </user:PenguinUserControl>
            <StackPanel Orientation="Vertical" VerticalAlignment="Top">
                <Slider x:Name="SliderX" Minimum="0" Maximum="360" Width="400"
                    VerticalAlignment="Top" Margin="0,20,0,0" />
                <Slider x:Name="SliderY" Minimum="0" Maximum="360" Width="400"
                    VerticalAlignment="Top" Margin="0,20,0,0" />
                <Slider x:Name="SliderZ" Minimum="0" Maximum="360" Width="400"
                    VerticalAlignment="Top" Margin="0,20,0,0" />
            </StackPanel>
        </Grid>

        Also note that Silverlight 4 permits you to apply a PlaneProjection directly to a user control.
        Silverlight 3 didn't support this, which explains why in the Silverlight 3 version of this example,
        the user control was contained in a Border and the PlaneProjection was applied to the Border.




What’s New in Silverlight 4                                                                    Page 23 of 29
www.wintellect.com
IMPLICIT STYLES
        In Silverlight 3, there was no built-in way to define a style and have it automatically applied to all
        controls of a specified type. You could use the Silverlight Toolkit's implicit style manager to apply
        default styles, but the fact remained that the run-time itself lacked support for the same.

        In Silverlight 4, you can define an implicit style—also known as a default style— by omitting the
        x:Key attribute from the <Style> element. Unless otherwise specified, that style will be applied
        to all elements of the type specified by the TargetType. The following XAML declares three
        buttons and styles them with an implicit style that rotates them 15 degrees:

        <UserControl.Resources>
            <Style TargetType="Button">
                <Setter Property="RenderTransformOrigin" Value="0.5,0.5" />
                <Setter Property="RenderTransform">
                     <Setter.Value>
                         <RotateTransform Angle="15" />
                     </Setter.Value>
                </Setter>
            </Style>
        </UserControl.Resources>
        <Grid x:Name="LayoutRoot" Background="White">
            <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
                <Button Width="120" Height="60" Content="Button1" Margin="8" />
                <Button Width="120" Height="60" Content="Button2" Margin="8" />
                <Button Width="120" Height="60" Content="Button3" Margin="8" />
            </StackPanel>
        </Grid>

        Here is the result:




        Of course, you might want to use implicit styles but exclude certain controls from being
        implicitly styled. You can do that by setting a control's Style property to x:Null:

        <UserControl.Resources>
            <Style TargetType="Button">
                <Setter Property="RenderTransformOrigin" Value="0.5,0.5" />
                <Setter Property="RenderTransform">
                     <Setter.Value>
                         <RotateTransform Angle="15" />
                     </Setter.Value>
                </Setter>
            </Style>
        </UserControl.Resources>


What’s New in Silverlight 4                                                                    Page 24 of 29
www.wintellect.com
        <Grid x:Name="LayoutRoot" Background="White">
            <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
                <Button Width="120" Height="60" Content="Button1" Margin="8" />
                <Button Width="120" Height="60" Content="Button2" Margin="8" />
                <Button Width="120" Height="60" Content="Button3" Margin="8"
                    Style="{x:Null}" />
            </StackPanel>
        </Grid>

        And here is the resulting UI:




        Implicit styles are a welcome addition to Silverlight 4, and it is likely that developers will find this
        feature to be as useful in Silverlight as they have already found it to be in WPF.


MANAGED EXTENSIBILITY FRAMEWORK
        Another new feature coming in Silverlight 4 is the Managed Extensibility Framework, or MEF.
        MEF, which will also be part of .NET 4.0, is a framework for building extensible applications. It
        provides infrastructure for loose coupling between components and can be used to create
        composable applications—apps that pull together "parts" from various locations to compose an
        aggregate to present to the user. In short, MEF makes composability a first-class citizen in
        Silverlight.

        One of the key concepts in MEF is that of the catalog, which tells MEF where to look for parts
        that make up an application. An application can import parts from the catalog with [Import]
        attributes, and parts themselves can use [Export] attributes to expose themselves to importers.
        That's the big picture, and of course it ignores hundreds of little details, but understanding these
        core concepts is a big help in understanding MEF as a whole.

        To see first-hand how Silverlight developers might use MEF, download MEFDemo from
        Wintellect's Web site. MEFDemo is an extensible Silverlight 4 image editor. You load photos into
        it through an OpenFileDialog, and then you click buttons to apply filters of various types to the
        photos. Here's MEFDemo showing a photo from the Vatican:




What’s New in Silverlight 4                                                                      Page 25 of 29
www.wintellect.com
        And here's MEFDemo after clicking the Blur button a few times and applying an embossing filter:




What’s New in Silverlight 4                                                              Page 26 of 29
www.wintellect.com
        Out of the box, MEFDemo offers three image filters: a grayscale filter, a blur filter, and an
        embossing filter. Because the filters are MEF plug-ins, you can easily write filters of your own
        and plug them into the application.

        One of the filters—the grayscale filter—is embedded in the main application. It's found in
        GrayscaleFilter.cs and it implements an interface named IImageFilter:

        public class GrayscaleFilter : IImageFilter
        {
            public string Label
            {
                get { return "Grayscale"; }
            }

              public void Execute(WriteableBitmap bitmap)
              {
                ...
              }
        }

        IImageFilter is defined a separate project named ImageFilterContract and is decorated with an
        [InheritedExport] attribute, which means all types that implement the interface should be
        exported by MEF:

        [InheritedExport]
        public interface IImageFilter
        {
            void Execute(WriteableBitmap bitmap);
            string Label { get; }
        }

        The other two filters are exported from a separate project named ConvolutionFilters. Because
        the project type is Silverlight Application, not Silverlight Class Library, building the solution
        places two XAP files in the Web site's ClientBin folder: MEFDemo.xap, which contains the main
        application, and ConvolutionFilters.xap, which contains BlurFilter and EmbossFilter. These
        filters, too, implement IImageFilter and are automatically exported from the XAP as a result of
        the [InheritedExport] attribute.

        In MEF terminology, the exported image filters are "parts." Which begs the question: how and
        where do the parts get imported?

        Look in MainPage.xaml.cs and you'll find the following property declaration:

        [ImportMany(AllowRecomposition = true)]
        public ObservableCollection<IImageFilter> Filters { get; set; }

        The [ImportMany] attribute tells MEF to look for all exported parts that implement IImageFilter
        and to populate the ObservableCollection with references to those parts. In MainPage's
        constructor, a single line of code binds the ObservableCollection to an ItemsControl to produce



What’s New in Silverlight 4                                                                  Page 27 of 29
www.wintellect.com
        buttons representing the imported image filters. The ItemsControl uses the following item
        template to create the buttons:

        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Button Content="{Binding Label}" Width="96" Height="32"
                    Margin="0,12,12,12" Tag="{Binding}" Click="OnExecuteFilter" />
            </DataTemplate>
        </ItemsControl.ItemTemplate>

        The text on the face of each button comes from the associated image filter's Label property, and
        the Tag property holds an IImageFilter reference to the filter itself. When a button is clicked, it's
        a simple matter to retrieve the IImageFilter reference and use it to invoke the filter:

        IImageFilter filter = (sender as Button).Tag as IImageFilter;
        filter.Execute(_bitmap);

        How does MEF know where to look for exported parts to satisfy our imports? The answer is
        found in MainPage's constructor:

        // Create a catalog and add this XAP to it
        PackageCatalog catalog = new PackageCatalog();
        catalog.AddPackage(Package.Current);

        // Download additional XAPs and add them to the catalog
        Package.DownloadPackageAsync(new Uri("ConvolutionFilters.xap",
            UriKind.Relative), (s, p) => catalog.AddPackage(p));

        // Pass the catalog to the MEF and compose the parts
        var container = new CompositionContainer(catalog);
        container.ComposeParts(this);

        The first line creates a package catalog. The second line adds the current package
        (MEFDemo.xap) to the catalog, which allows MEF to find the GrayscaleFilter class exported from
        MEFDemo.xap. The third line initiates an asynchronous download of ConvolutionFilters.xap and
        adds it to the catalog when the download completes. This allows MEF to find the BlurFilter and
        EmbossFilter classes in that XAP. Adding image filters to the application is as simple as placing
        additional XAP files containing the filters in ClientBin and adding one line of code per XAP to
        download the package and add it to the catalog. Once filters are exported and added to the
        catalog, buttons representing them will automatically show up in the UI.


OTHER ENHANCEMENTS
        Silverlight 4 introduces additional features that aren’t covered here, many of which were added
        in direct response to feedback from the community. Other enhancements added to the platform
        include:

                Integration of WCF RIA Services (formerly known as .NET RIA Services)



What’s New in Silverlight 4                                                                    Page 28 of 29
www.wintellect.com
                Media enhancements, including support for protected H.264 content and UDP
                 multicasting
                Enhancements to the {Binding} markup extension, including a new StringFormat
                 attribute for formatting text without requiring custom value converters
                Mousewheel support in ListBox and other scrolling controls
                Support for right-to-left (RTL) text and bidirectional text
                A new TextBlock property named TextTrimming for trimming text that doesn’t fit in the
                 space designated for it
                A CompositeTransform class that allows one transform to take the place of several
                ViewBox and RichTextArea controls
                Extensible navigation services via the new INavigationContentLoader interface
                IDataErrorInfo and INotifyDataErrorInfo support to ease the chore of validating user
                 input
                Official support for Google Chrome

        Silverlight 3 made huge improvements to Silverlight 2, and Silverlight 4 promises to do no less.
        The time to plan for Silverlight 4 is now.




What’s New in Silverlight 4                                                                 Page 29 of 29
www.wintellect.com

				
DOCUMENT INFO
Shared By:
Stats:
views:201
posted:12/22/2010
language:English
pages:29
Description: Microsoft Silverlight is a cross-browser, cross-platform plug-in, in order to bring the next generation of network-based. NET based media experiences and rich interactive applications. Silverlight offers a flexible programming model, and can be easily integrated into existing Web applications. Silverlight can run on Mac or Windows on the major browsers to provide high quality video information fast, low-cost delivery.