(X) Hide this
    • Login
    • Join
      • Generate New Image
        By clicking 'Register' you accept the terms of use .

10 Laps around Silverlight 5 (Part 6 of 10)

(6 votes)
Michael Crump
>
Michael Crump
Joined Nov 12, 2010
Articles:   18
Comments:   17
More Articles
3 comments   /   posted on Nov 15, 2011
This article is sponsored by Telerik RadControls for Silverlight. For similarly awesome content check out Telerik XAMLflix, your step-by-step guide to Telerik Silverlight and WPF controls. Get access to video tutorials, written tutorials, and tons of code!

Tweet

To contact me directly please visit my blog at http://michaelcrump.net/ or through twitter at http://twitter.com/mbcrump.

This article is Part 6 of the series “10 Laps around Silverlight 5.” If you have missed any other section then please see the Roadmap below.

To refresh your memory on what Silverlight is:

Microsoft Silverlight is an application framework for writing Rich Internet Applications.

The run-time environment is available as a plug-in for most web browsers and works on a variety of operating systems including Windows, Mac and Linux.

To recap what we learned in the previous section:

  • We spend the entire “lap” discussing improvements in text in Silverlight 5.
  • We discussed Linked and Multi-Column Text and where it might be useful in your next Silverlight application.
  • We also looked at character spacing, open-type font. pixel snapped text and TextOptions.

In this article, I am going to discuss several new operating system integration features in Silverlight 5 including: P/Invoke, Multiple Windows and Unrestricted File System Access in Full Trust. Please review the Roadmap for the series before going any further.

The Roadmap for this Series

I’ve included the Roadmap for the series below as you may want to visit other sections as you learn Silverlight 5. I picked the following features as I thought that you may find them useful in your day-to-day work. If you want a specific topic covered then please leave it in the comments below.

1) Introduction to SL5 – This post which provides a brief history of Silverlight and relevant links.

2) Binding- Ancestor Relative Source Binding and Implicit Data Templates.

3) Graphics –XNA 3D API and Improved Graphics Stack.

4) Media - Low-Latency Sound using XNA and Remote Control and Media Command (Keys) Support.

5) Text - Text Tracking and Leading, Linked and Multi-column Text, OpenType Support, Pixel Snapped Text and TextOptions.

6) Operating System Integration [This post] - Part 1 - P/Invoke, Multiple Windows and Unrestricted File System Access in Full Trust.

7) Operating System Integration Part 2 - Default Filename for SaveFileDialog, 64-bit browser support and Power Awareness.

8) Productivity and Performance - XAML Binding Debugging, Parser Performance Improvements and Multi-core JIT for improved start-up time.

9) Controls - Double and Triple click support, PivotViewer and ComboBox Type-Ahead.

10) Other items - In-Browser HTML, PostScript and Tasks for TPL.

P/Invoke or Platform Invocation

Before we dive into an example. Let’s first answer the question, What is it? Platform Invocation Services, commonly referred to as P/Invoke, is a feature of Common Language Infrastructure implementations, like Microsoft's Common Language Runtime, that enables managed code to call native code.

*Reference to Wiki

This feature is new to Silverlight 5 and we will take a look at how to use it in your own applications. 

In order to create a new P/Invoke application in Silverlight 5, we will need to enable “Require elevated trust” in Silverlight 5. We can also use the functionality in-browser or out-of-browser. Let’s begin.

Fire up a new Silverlight 5 project and right click on our project and select Properties. Put a check in “Enable running application out of the browser” as shown below.

After you put a check in “Enable running application out of the browser”, go ahead and click the button. Now put a check in “Require elevated trust when running outside the browser”.

Switch back over to the MainPage.xaml and add in the following code:

   1: <Grid x:Name="LayoutRoot" Background="White">
   2:     <Button Height="23" HorizontalAlignment="Left" Margin="169,132,0,0" VerticalAlignment="Top" Width="75" x:Name="btnclick" Content="click" Click="click_Click" />
   3: </Grid>

This simply puts a button on our page that when the user clicks it the pc will make a beep sound.

Go ahead and add a new class to the project named PlatformInvokeTest.cs and add the following code.

   1: using System;
   2: using System.Runtime.InteropServices;
   3:  
   4: namespace PInvoke
   5: {
   6:     public class PlatformInvokeTest
   7:     {   
   8:         [DllImport("kernel32.dll")]
   9:         public static extern bool Beep(int frequency, int duration);
  10:  
  11:      
  12:         public static void PlaySound()
  13:         {
  14:             Random random = new Random();
  15:             for (int i = 0; i < 50; i++)
  16:             {
  17:                 Beep(random.Next(10000), 100);
  18:             }
  19:         }
  20:  
  21:     }
  22: }

Let’s switch back over to the MainPage.xaml.cs and add the following code to our button event handler:

   1: private void click_Click(object sender, RoutedEventArgs e)
   2: {
   3:     PlatformInvokeTest.PlaySound();
   4: }

If we run the application now, we will hear our PC beep many times.  There are many other thing you can do with P/Invoke such as Detecting if the user inserted a USK Key into their computer, opening the run dialog box and much much more! Very cool stuff!

Multiple Window Support

With Silverlight 5, we now have the ability to spawn multiple windows from an Out-of-Browser application with elevated trust with just a couple of lines of code.

A few things to note about Multiple Window Support though:

  • If the main window closes, then all spawned windows close.
  • You need to be running your application “Out-of-Browser” as well as in Elevated Trust mode.

If you followed the P/Invoke guide before then you will need to do the same thing for Multiple Window Support. That is, make this an out-of-browser application and add Elevated Trust.

After that is complete then go ahead and double click on your MainPage.xaml.cs file and add the following code:

   1: public MainPage()
   2: {
   3:     InitializeComponent();
   4:     Loaded += new RoutedEventHandler(MainPage_Loaded);
   5: }
   6:  
   7: void MainPage_Loaded(object sender, RoutedEventArgs e)
   8: {
   9:     for (int i = 0; i < 5; i++)
  10:     {
  11:         new Window()
  12:            {
  13:                Height = 400,
  14:                Width = 600,
  15:                Top = 24,
  16:                Left = 30,
  17:                Title = "Silverlight Show New Window",
  18:                Content = new Button() { Content = "Can be any Framework Element" },
  19:                Visibility = Visibility.Visible
  20:            };
  21:     }
  22:    
  23: }

This application will spawn 5 windows when you run it. Below is a sample screenshot from the application with 2 additional windows showing. The other windows are closed for demonstration purposes.

Unrestricted File System Access in Full Trust

Have you ever wanted to write a file anywhere on a users computer in earlier versions of Silverlight but found out that you couldn’t? Well in Silverlight 5 you can.

Just like the earlier samples make this an out-of-browser application and add Elevated Trust. (See the P/Invoke demo at the beginning of this article for a quick-how to.)

Switch over to the MainPage.xaml and add in the following code:

   1: <Grid x:Name="LayoutRoot" Background="White">
   2:     <Button Height="23" HorizontalAlignment="Left" Margin="169,132,0,0" VerticalAlignment="Top" Width="75" x:Name="btnclick" Content="click" Click="click_Click" />
   3: </Grid>

Let’s switch back over to the MainPage.xaml.cs and add the following code to our button event handler:

   1: private void click_Click(object sender, RoutedEventArgs e)
   2: {
   3:     // Create a Directory on the Root of C
   4:     var tempDirectory = @"c:\michaelcrump";
   5:     if (!Directory.Exists(tempDirectory))
   6:     {
   7:         Directory.CreateDirectory(tempDirectory);
   8:     }
   9:  
  10:     // Give it a FileName
  11:     var filename = string.Format("slshowrocks.txt");
  12:     var fullPath = System.IO.Path.Combine(tempDirectory, filename);
  13:  
  14:     // Write Something in the File!
  15:     using (FileStream fs = File.Create(fullPath))
  16:     using (StreamWriter sr = new StreamWriter(fs, Encoding.UTF8))
  17:     {
  18:         sr.WriteLine("Hello World");
  19:     }
  20: }

This will create a directory on our C:\ called michaelcrump. Then it will create a file named “slshowrocks.txt” and give it some content. If you run the application and click on the button then you should have the new folder/file created on your root hard disk.

If Visual Studio 2010 is complaining of any missing namespaces then just make sure you add the following:

   1: using System.IO;
   2: using System.Text;

Very easy to accomplish and it is not limited to writing files. You can also read files from anywhere on the hard disk! In the next part of this series, we will look at letting the user specify the location of the saved file.

Conclusion

At this point, we have seen how you would use P/Invoke, Multiple Windows and Unrestricted File System Access in Full Trust in your Silverlight 5 Applications. We have also discussed a few other features in Silverlight 5. In the next part of the series, I am going to take a look at more new operating system features including : Default Filename for SaveFileDialog, 64-bit browser support and Power Awareness.  Again, thanks for reading and please come back for the next part.

To contact me directly please visit my blog at http://michaelcrump.net/ or through twitter at http://twitter.com/mbcrump.


Subscribe

Comments

  • tcochran64

    Re: 10 Laps around Silverlight 5 (Part 6 of 10)


    posted by tcochran64 on Nov 15, 2011 18:07
    Have you see a bug/problem with running Elevated Trust in the browser and also using RIA Services?  I can get it to work RIA Services is not included, but the app will crash with RIA Services included.  I think there is the bug filed for the RC, but wasn't sure if you have seen this and/or have a workaround?
  • mbcrump

    Re: 10 Laps around Silverlight 5 (Part 6 of 10)


    posted by mbcrump on Nov 15, 2011 18:14

    I have seen a bug request in Microsoft's Connect Site for that particular issue. As we get closer to the final release, it should be resolved. 

  • DBKarron

    Re: 10 Laps around Silverlight 5 (Part 6 of 10)


    posted by DBKarron on Jan 19, 2012 21:52

    has anyone tried making hard/soft/symbolic links ?

    does it work from SL5 ?

    dB

Add Comment

Login to comment:
  *      *       

From this series