My app has a 'open file' button. Before launching the OpenFileDialog, it asks whether the user wants to save the current file, and if they do, it launches a SaveFileDialog. It then launches the OpenFileDialog. Pretty standard stuff.
My problem is that silverlight then sees the OpenFileDialog.ShowDialog() method as not user-initiated, and I get a SecurityException.
Is there any known reasonable way to avoid this exception? Surely this is a pretty standard scenario?
The app is within a browser.
Any ideas welcome
EDIT:
Sorry, not allowed to release actual code :( The logic is pretty simple though: In psuedocode the 'OpenFile" button press event calls a method something like:
*Launch a new SL message asking whether to save first.
*On message window yes/no clicked: -If No, Go to Load -If Yes, Launch SaveFileDialog.ShowDialog(), go to Load
*Load: Launch An Open File Dialog
EDIT 2: Mini programme...
XML content for the main page:
<Grid x:Name="LayoutRoot" Background="White">
<Button Content="Open" Click="Button_Click"/>
</Grid>
Code:
using System.Windows;
using System.Windows.Controls;
namespace SilverlightApplication15
{
public partial class MainPage : UserControl
{
AskWindow aw = new AskWindow();
public MainPage()
{
InitializeComponent();
aw.Closed += new System.EventHandler(aw_Closed);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
aw.Show();
}
private void aw_Closed(object sender, System.EventArgs e)
{
if (aw.DialogResult == true)
{
SaveFileDialog svd = new SaveFileDialog();
svd.ShowDialog();
}
OpenFileDialog ofd = new OpenFileDialog();
ofd.ShowDialog();//Causes security exception
}
}
public class AskWindow : ChildWindow
{
public AskWindow()
{
Button b = new System.Windows.Controls.Button();
b.Click += new System.Windows.RoutedEventHandler(b_Click);
b.Content = "Yes, save it";
this.Content = b;
}
private void b_Click(object sender, System.Windows.RoutedEventArgs e)
{
this.DialogResult = true;
}
}
}
It may be a standard scenario for a desktop application but you aren't creating a desktop application. You are creating a component that runs in a secure sandbox and that comes with some fairly stringent restrictions for good reasons.
There is no slick way to handle this scenario. You could provide a close "document" feature which will popup a confirmation box warning the continuing will loses work.
In an attempt to open another "document" whilst the current is unsaved all you can do is display message instructing the user on their choices, either close the current "document" and abandon its changes or to choose to save. The user will have to manually perform these actions and then choose again to open a "document".
You might be able to improve things a bit if your app supported multiple "open" documents, at least the user wouldn't be taxed for openning a "document".