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

Silverlight Elevated Permissions

(6 votes)
Corrado Cavalli
>
Corrado Cavalli
Joined Dec 15, 2009
Articles:   1
Comments:   2
More Articles
18 comments   /   posted on Dec 15, 2009
Tags:   out-of-browser , elevated-trust , corrado-cavalli
Categories:   Line-of-Business , General

This article is compatible with the latest version of Silverlight.

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:

 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:

 Application.Current.MainWindow.Width = 500;
 Application.Current.MainWindow.Height = 400;
 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:

 public MainPage()
 {
    InitializeComponent();
    if (Application.Current.HasElevatedPermissions && Application.Current.IsRunningOutOfBrowser)
    {
       Application.Current.MainWindow.WindowState = WindowState.Maximized;
       Application.Current.MainWindow.TopMost = true;
    }
 }

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:

 private void button4_Click(object sender, RoutedEventArgs e)
 {
    Uri uri = new Uri(@"http://www.ansa.it/web/images/logo_ansa_hp.gif");
    WebClient wc = new WebClient();
    wc.OpenReadCompleted+=(s,arg)=>
       {               
          if (arg.Error == null)
          {
             //Save image
          }
      };
   
     wc.OpenReadAsync(uri);
 }

 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:

 if (Application.Current.HasElevatedPermissions)
 {
    string path = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
    var files=Directory.EnumerateFiles(path);
    ObservableCollection<string> picFiles = new ObservableCollection<string>(files);
    listBox1.ItemsSource = picFiles;            
 }

 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)

 if (Application.Current.HasElevatedPermissions && ComAutomationFactory.IsAvailable)
 {
    MessageBox.Show("Ava");
    dynamic outlook = ComAutomationFactory.CreateObject("Outlook.Application");
    dynamic mail = outlook.CreateItem(0);
    mail.To = "john@doe.com";
    mail.Subject = "Silverlight 4.0 question";
    mail.Body = "I have a question for you";
    mail.Display();
 }

 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:

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

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

HTML Hosting

Silverlight 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:

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

 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:

 NotificationWindow notifyWin = null;
  
 private void OnToastWindowClick(object sender, RoutedEventArgs e)
 {
    if (App.Current.IsRunningOutOfBrowser)
    {
       int interval = 3500; 
       //ToastWindow is a userControl representing notification content
       ToastWindow content = new ToastWindow();
       if (notifyWin == null)
          notifyWin=new NotificationWindow()
          {
              Content=content,
              Width=content.Width,
              Height=content.Height
          };
       else
       {
          if(notifyWin.Visible) notifyWin.Close();
       }         
       notifyWin.Show(interval);
    }
 }

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.


Subscribe

Comments

  • -_-

    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.
  • corradocavalli

    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)?
  • corradocavalli

    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.
  • -_-

    RE: Silverlight 4 elevated permissions


    posted by Gio on Sep 14, 2010 17:42

    No permissions for AppData!!!

    ..applications can read all the user's private documents but cannot store configuration files (or whatever) in AppData ?

    If i plan to use OOB usually i will need to store an offline db for later sync, or maybe configuration files, or cached photos for a catalog...all things that deserves an AppData space or something similar!

    where is supposed to store this files with OOB ?

    At this point this restriction seems very ugly, especially if i can do this things "non-natively" with COM ... but why i need to use COM in this case???

    Remove this restriction...is a joke...!

  • -_-

    RE: Silverlight 4 elevated permissions


    posted by Rod on Sep 16, 2010 14:01

    I have signed my OOB app with my validated certificate and use elevated permissions. However, I can't launch my app in FullScreen mode - only with a maximised window? I want it to load directly into fullscreen - is this possible?

    If you click on the "Start Tourney" button it goes into FullScreen mode but I want it to work with no user interaction....

  • -_-

    RE: Silverlight 4 elevated permissions


    posted by JewelThief on Oct 26, 2010 08:20
    Does elevated trust in Silverlight also provides some elevation in MAC OSX?
  • -_-

    RE: Silverlight 4 elevated permissions


    posted by Ric Bailey on Oct 26, 2010 15:39
    I'm running in OOB mode, I have selected Elevated Permissions, and have given the user group Everyone full control of the Pictures folder in my web site, and I still can't read in the jpg names from it!!! This is infuriating. I just want a dynamic bunch of thumbnails from what whatever is in the folder. My third party web hoster doesn't give me access to anything except the folders I create within my site. There is no concept of My Documents when you are running on someone else's server. So how do I show the user a bunch of thumbnails?
  • -_-

    RE: Silverlight 4 elevated permissions


    posted by Amanda on Nov 21, 2010 03:39

    Any answer ? Elevated trust in Silverlight provides elevation in MAC OSX?

    Amanda - rakeback

  • -_-

    RE: Silverlight Elevated Permissions


    posted by daman on May 17, 2011 16:03
    Can i access DOM elements from webbrowser control in silverlight OOB. the url source is outside say it is www.google.com
  • vinoo

    Re: Silverlight Elevated Permissions


    posted by vinoo on Dec 11, 2012 11:58

    When I am running my out of browser SL app, it works fine on local machine, but when I publish on server, it won't update the latest changes as it does for local app. I am using CheckAndDownloadUpdateAsync to check and update and works fine locally.

    Any solution would of great help.

Add Comment

Login to comment:
  *      *