views:

3183

answers:

2

A while back I wrote a silverlight user control which had a csv import/export feature. This has been working fine, until recently I discovered it erroring in one scenario. This may have been due to moving to Silverlight 3.

The Error:
Message: Unhandled Error in Silverlight 2 Application
Code: 4004
Category: ManagedRuntimeError
Message: System.Security.SecurityException: Dialogs must be user-initiated.
       at System.Windows.Controls.OpenFileDialog.ShowDialog()
       at MyControl.OpenImportFileDialog()
       at ...

The Code:

private void BrowseFileButton_Click(object sender, RoutedEventArgs e)
{
    if (string.IsNullOrEmpty(lblFileName.Text))
    {
        if (MessageBox.Show("Are you sure you want to change the Import file?", "Import", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
        {
            return;
        }
    }
    EnableDisableImportButtons(false);
    var fileName = OpenImportFileDialog();
    lblFileName.Text = fileName ?? string.Empty;
    EnableDisableImportButtons(true);    
}

private string OpenImportFileDialog()
{
    var dlg = new OpenFileDialog { Filter = "CSV Files (*.csv)|*.csv" };
    if (dlg.ShowDialog() ?? false)
    {
        using (var reader = dlg.File.OpenText())
        {
            string fileName;
            //process the file here and store fileName in variable
            return fileName;
        }
    }
}

I can open an import file, but if i want to change the import file, and re-open the file dialog, it errors. Does anyone know why this is the case?
Also, I am having trouble debugging because placing a breakpoint on the same line (or prior) to the dlg.ShowDialog() call seems to cause this error to appear as well. Any help would be appreciated?

+4  A: 

You do two actions on one user click.

You show a messagebox which effectively uses your permission to show a dialog on user action.

You then try to show the dialog, since this is a second dialog on user action it's not allowed.

Get rid of the confirmation dialog and you'll be fine.

Graeme Bradbury
A: 

ok Pal. I cracked this nasty one. As a workaround do an IISreset and the System.Security.SecurityException goes away! Mail me if you need this working cos I got this working after a bit of hair pulling! Take care, VJ Koganti, United Kingdom ([email protected])

VJ Koganti