More from Corrado Cavalli

Skip Navigation LinksHome / Articles / View Article

Silverlight 4 elevated permissions

+ Add to SilverlightShow Favorites
11 comments   /   posted by Corrado Cavalli on Dec 15, 2009
(1 votes)
Categories: Learn , Tutorials , Resources

Among the new features introduced with Silverlight 3.0, Out-of-Browser is certainly one that has aroused more interest among developers as it opens very interesting usage scenarios that go beyond the traditional Web application, with version 4.0 this feature has been enhanced with additional options that makes it a viable alternative to classic desktop applications.

Introduction

Out-of-Browser mode allows a Silverlight 3.0 or above application to be detached from its natural host (the browser) and be run by the final user as any desktop application. To enable it all you need to do is select the "Enable application running out of the browser " option available among application properties:

image

and set available options:

image

Compared to what’s available in version 3.0 you can immediately observe that you can now set the default window location, remove default installation menu and, especially, enable the "Require Elevated trust when running outside the browser" option through which it's possible to relax the sandbox that hosts the Silverlight application. These settings are then persisted inside AppManifest.xaml file that gets embedded inside application's Xap file.

When "Require Elevated trust when running outside the browser" option is selected when the user choose to install the application locally it is prompted with a ClickOnce like security warning requiring authorization to run application with elevated privileges.

image

Just after public announce of this feature at PDC 2009, a lot of developers started seeing this feature as the end of the desktop applications but while this opens a lot of opportunities it’s worth mentioning that you can’t still have full control of local machine, for this, a Windows Presentation Foundation 4.0 XBAP application remains the viable alternative.

Detecting when application is running in elevated trust mode

Since some features requires elevated trust and initially your application is run from the browser, detecting whether the application has elevated privileges will become a common scenario inside Silverlight 4.0 applications, that’s why Application class now exposes a HasElevatedPermission property:

 1: bool featureComplete = Application.Current.HasElevatedPermissions;

Once sure about application state we can begin using new features depending on this special mode.

Interacting with application window

Silverlight 4.0 gives you more control of the application hosting window, it’s now possible to change its WindowState, set it TopMost and even change its size at runtime just using Application.MainWindow property as shown below:

 1: Application.Current.MainWindow.Width = 500;
 2: Application.Current.MainWindow.Height = 400;
 3: Application.Current.MainWindow.TopMost = true;

If application is fully trusted you can interact with application window (a.k.a Chrome) without user intervention, this means that you can use this code to easily create a full screen Silverlight application:

 1: public MainPage()
 2: {
 3:    InitializeComponent();
 4:    if (Application.Current.HasElevatedPermissions && Application.Current.IsRunningOutOfBrowser)
 5:    {
 6:       Application.Current.MainWindow.WindowState = WindowState.Maximized;
 7:       Application.Current.MainWindow.TopMost = true;
 8:    }
 9: }

Running the above snippet you’ll see no “Press ESC to exit full screen mode” warning appear, while this give you total control of the ESC key it also means that you’re in charge of closing application window. 
When not running in elevated mode interaction with application window it’s available only through a user initiated action (e.g. a Click event)
While not available in current beta it has also been announced that RTM release will include Chrome customization support.

What you can do when application is running with elevated trust

Following is a list of the features available only when application runs inside a relaxed sandbox:

a) Clipboard direct access:  When you programmatically access Clipboard class to copy or retrieve text from system clipboard, if application is running with elevated privileges the following dialog does not appear:

image

b) Relaxed cross domain restriction:  Communicating with services that are not hosted on the application’s site of origin results in Silverlight security model checking for the presence of ClientAccessPolicy.xml or CrossDomain.xml files, if none of those files are detected on target domain, operation returns a security exception.
In full trust mode security check is bypassed and application can safely interact with any domain, as example, following sample will fail in a standard sandboxed application while runs fine on a elevated permission installation:

 1: private void button4_Click(object sender, RoutedEventArgs e)
 2: {
 3:    Uri uri = new Uri(@"http://www.ansa.it/web/images/logo_ansa_hp.gif");
 4:    WebClient wc = new WebClient();
 5:    wc.OpenReadCompleted+=(s,arg)=>
 6:       {               
 7:          if (arg.Error == null)
 8:          {
 9:             //Save image
 10:          }
 11:      };
 12:  
 13:    wc.OpenReadAsync(uri);
 14: }

 c) Direct access to User folder: Through OpenFileDialog and SaveFileDialog classes any Silverlight application can access local file system, but only inside a full trust application it’s possible access it without user interaction although limited to user folders: My Documents, My Pictures, My Videos , My Music and related subfolders.
Here’s a fragment of code that loads My Pictures folder contents inside a listbox:

 1: if (Application.Current.HasElevatedPermissions)
 2: {
 3:    string path = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
 4:    var files=Directory.EnumerateFiles(path);
 5:    ObservableCollection<string> picFiles = new ObservableCollection<string>(files);
 6:    listBox1.ItemsSource = picFiles;            
 7: }

 d) COM Interoperability: Elevated trust mode give you access to COM enabled applications installed on user machine. An example might be a Silverlight 4.0 application that interacts with Office’s Outlook application to popup a send email dialog, following code shows how to do it (a reference to Microsoft.CSharp assembly is required in order to compile the sample)

 1: if (Application.Current.HasElevatedPermissions && ComAutomationFactory.IsAvailable)
 2: {
 3:    MessageBox.Show("Ava");
 4:    dynamic outlook = ComAutomationFactory.CreateObject("Outlook.Application");
 5:    dynamic mail = outlook.CreateItem(0);
 6:    mail.To = "john@doe.com";
 7:    mail.Subject = "Silverlight 4.0 question";
 8:    mail.Body = "I have a question for you";
 9:    mail.Display();
 10: }

 While this feature is incredibly awesome some caution but be taken in consideration before considering its use:

1) This feature is available on Windows platform only, that’s why code checks ComAutomationFactory.IsAvailable property.

2) Together with trust elevation COM Interoperability might open the door to potential security issues because an application could download an executable to one of the user folders and, via the WScript object, run it, potentially hurting the entire computer, following code shows how simple is to execute a local application in a full trust Silverlight application:

 1: if (Application.Current.HasElevatedPermissions && ComAutomationFactory.IsAvailable)
 2: {
 3:    dynamic cmd = ComAutomationFactory.CreateObject("WScript.Shell");
 4:    cmd.Run(@"c:\windows\notepad.exe", 1, true);
 5: }

 Obviously this works only if user authorized the application but, you know, users can be easily misleaded.

HTML Hosting

Silverlight 4.0 application running out of browser can now display HTML content using the new WebBrowser control, here’s a code snippet that allows you to navigate to a Uri:

 1: <StackPanel x:Name="LayoutRoot" Background="WhiteSmoke">
 2:     <StackPanel Orientation="Horizontal">
 3:         <TextBox x:Name="txtUrl" Text="http://www.facebook.com" Width="200" />
 4:         <Button Content="Go" Click="OnNavigate" />
 5:     </StackPanel>
 6:     <WebBrowser  x:Name="wb" Width="600" Height="250" />
 7: </StackPanel>
 8: private void OnNavigate(object sender, RoutedEventArgs e)
 9: {
 10:    Uri uri = new Uri(txtUrl.Text);
 11:    wb.Navigate(uri);
 12: }

 In order to display page content application must run in elevated trust mode otherwise WebBrowser control can only safely access pages hosted on application site of origin furthermore being WebBrowser default width and height set to zero a valid size must also be provided.
WebBrowser functionality is available in out-of-browser mode only; running the above sample inside the browser will result in a rectangle rendered as control placeholder.

Notification Window

A new feature that’s accessible in out-of-browser mode only is the Notification or ‘toast’ Window, a small area whose maximum size can’t exceed 400x100 pixels that appears for a predefined period of time in screen’s lower right corner and closes automatically when interval expires.
To display a notification window, create a UserControl that will represents notification content, and associate it to NotificationWindow’s Content property as shown in following sample:

 1: NotificationWindow notifyWin = null;
 2:  
 3: private void OnToastWindowClick(object sender, RoutedEventArgs e)
 4: {
 5:    if (App.Current.IsRunningOutOfBrowser)
 6:    {
 7:       int interval = 3500;
 8:  
 9:       //ToastWindow is a userControl representing notification content
 10:       ToastWindow content = new ToastWindow();
 11:  
 12:       if (notifyWin == null)
 13:          notifyWin=new NotificationWindow()
 14:          {
 15:             Content=content,
 16:             Width=content.Width,
 17:             Height=content.Height
 18:          };
 19:       else
 20:       {
 21:          if(notifyWin.Visible) notifyWin.Close();
 22:       }  
 23:       
 24:       notifyWin.Show(interval);
 25:    }
 26: }

trying to show a notification that’s already visible results in an exception, that’s why the sample checks notification’s Visible property and closes current window before invoking Show method again.

Summary

Out-of-browser is one of the most appealing features available in Silverlight since it quickly allows transformation of a web application in a desktop ‘like’ one; Silverlight 4.0 improves it with elevated trust mode that opens the doors to a new generation of RIA applications that can easily run on both Windows and Mac operative systems.

Share


Comments

Comments RSS RSS
  • RE: Silverlight 4 elevated permissions  

    posted by jimlizardking on Dec 15, 2009 21:05

    I was having just this discussion with a Silverlight techie from Microsoft just last week - I don't think the limits imposed by the OOB model are actually a bad thing.

    In today's user environment, especially under Win7 or Vista, it definitely pays to behave properly in terms of requesting security access and permissions. In the majority of cases the user shouldn't need to (and won't have access to) many areas beyond their own user profile so it makes sense that apps, whatever their flavor, adhere to the same restriction.

    In situations where elevated (or Elevated) permissions are required, perhaps this will make developers think more about architecture; about WCF or whether to use WPF instead (Click-once deployment is superb for WPF apps, for example, it's a real paradigm shifter for deployment in my opinion).

  • RE: Silverlight 4 elevated permissions  

    posted by Bill Storage on Dec 15, 2009 21:34
    The restriction on file access to the official User folders is maddening. It greatly interferes with the SL app's ability to monitor collections of images and large binaries, for example, which are rarely stored in My Docs, often residing on multiple portable drives. Non-trust and full-trust make sense, but the entire concept of moderate trust seems useless to me.
  • RE: Silverlight 4 elevated permissions  

    posted by Fallon Massey on Dec 15, 2009 23:45

    I'm not sure I understand the statement "it’s worth mentioning that you can’t still have full control of local machine".

    If you can access COM objects, there should be no limit to what you can do, although that requires that you build COM apps.

    Am I missing something?

  • RE: Silverlight 4 elevated permissions  

    posted by Jim McCurdy on Dec 16, 2009 00:53
    Elevated permissions also allow a user to use all of the alphanumeric keys while in full screen mode.
  • RE: Silverlight 4 elevated permissions  

    posted by corradocavalli on Dec 16, 2009 13:34
    @Fallon: Sentence refers to what you can do w/o interoperating with COM objects, e.g you can't natively interact with hardware resources
  • RE: Silverlight 4 elevated permissions  

    posted by Gabe on Dec 17, 2009 04:07
    Is there a limit to the space you can use in the user folders (My Videos, for example)?
  • RE: Silverlight 4 elevated permissions  

    posted by corradocavalli on Dec 17, 2009 07:38
    @Gabe: AFAIK No...
  • RE: Silverlight 4 elevated permissions  

    posted by olandt on Jan 30, 2010 15:05

    but how to debug that code in
    if(Application.Current.HasElevatedPermissions)
    {...how to debug these code...}

    thanks

  • RE: Silverlight 4 elevated permissions  

    posted by olandt on Jan 30, 2010 16:19
    thanks,i know.my ie is slow, so add too many comment,i am sorry :-|)
  • RE: Silverlight 4 elevated permissions  

    posted by Nathan Allan on May 14, 2010 01:00
    @olandt: you can debug out-of-browser by either attaching the debugger to the sllauncher.exe, or by specifying "Out-of-browser application" under the Debug tab of the Silverlight project properties.
  • RE: Silverlight 4 elevated permissions  

    posted by asdfff on Jun 22, 2010 15:57
    Now SL OOB apps are forced to write to My Documents, which is IMO a really bad place for programs to write stuff to without interaction. My Documents is the one place on the system where the user stores their files, now the folder should be called "Program's Documents" and the user should place their files somewhere else.

Add Comment

 
 

   
  
  
   
Please add 1 and 2 and type the answer here:

Did you notice our new Silverlight-based Showcase section ? Check it out to get a bird's eye view of all showcases featured on SilverlightShow, with a quick thumbnail preview for easier browsing. Want to view the most recent showcases only? Use Group by Month option for a chronological listing.
This is the second redesigned, entirely Silverlight-based section in SilverlightShow, after the new Books section. We look forward to your feedback on both! (hide this)