6

I am getting an error:

Dialog must be user-initiated

when I am opening the savefile dialog from my silverlight applicaiton I am using below code

Main Button click event :

 private void btnSaveAttach_Click(object sender, RoutedEventArgs e)
        {
            if (EditableGV.SelectedItems.Count == 1)
            {
                PositionAttachment posAtt = new PositionAttachment();
                posAtt = (PositionAttachment)EditableGV.SelectedItems[0];
                SaveFile(posAtt.File, posAtt.FileName);

            }
            else
            {
                RadWindow.Alert("Please select a attachment from the existing attachments list.", null);
                return;
            }

        }

private void SaveFile(byte[] fileByte, string fileName)
    {
        try
        {
            byte[] fileBytes = fileByte;//your bytes here 

            //Show the dialog        

            SaveFileDialog dialog2 = new SaveFileDialog();
            saveDialog = dialog2.ShowDialog();//This line is giving the error

            if (saveDialog == true)
            {
                //Get the file stream
                dialog2.DefaultFileName = fileName;
                string fileExt = fileName.Substring(fileName.LastIndexOf('.'), fileName.Length);
                dialog2.DefaultExt = "All Files|*.*|" + fileExt + "|*." + fileExt + "";
                using (Stream fs = (Stream)dialog2.OpenFile())
                {
                    fs.Write(fileBytes, 0, fileBytes.Length);
                    fs.Close();

                    //File successfully saved
                }
            }
        }
        catch 
        {
            MessageBox.Show("Error in downloading file");
        }
    }

XMAL Code :

<StackPanel x:Name="Layout">
    <StackPanel x:Name="Messagepanel" Margin="2" Visibility="Collapsed">
        <TextBlock x:Name="txtMessage" Text="1"  Height="35"></TextBlock>
    </StackPanel>
    <StackPanel Orientation="Horizontal" Margin="4">
        <sdk:Label Height="28" Content="Select File:"   Name="lblSelectFile" Grid.Column="0" Grid.Row="0"  Width="70" />
        <TextBox Name="txtFileName" IsReadOnly="True" HorizontalAlignment="Left" VerticalAlignment="Center"  Width="303" Grid.Column="1" Margin="12,1,0,0"></TextBox>
        <Button Content="Browse" Name="btnBrows" Width="55" Height="22"  HorizontalAlignment="Left" VerticalAlignment="Center" Margin="16,1,0,0" Click="btnBrows_Click" Grid.Column="1" />
    </StackPanel>
    <StackPanel Orientation="Horizontal" Margin="4">
        <sdk:Label Height="28" Content="Description:"   Name="lblFileDescription" Grid.Column="0" Grid.Row="1"  Width="70" />
        <TextBox Height="60"   Name="txtComments" Grid.Column="1" 
         VerticalScrollBarVisibility="Auto" Width="301" Margin="13,0,85,2" Grid.Row="1" />
    </StackPanel>
    <StackPanel Orientation="Horizontal" Margin="4">

        <Button x:Name="OKButton" Content="Add" Click="OKButton_Click" Width="43" Margin="363,6,10,15" Grid.Row="2" Grid.Column="1" HorizontalAlignment="Left" />

        <Button x:Name="CancelButton" Content="Cancel" Click="CancelButton_Click" Width="53" HorizontalAlignment="Right" Margin="0,6,200,15" Grid.Row="2" Grid.Column="1" />
    </StackPanel>
    <StackPanel Orientation="Vertical" Margin="4" Height="224">
        <sdk:Label Content="Existing Attachment(s):" Height="20" Margin="15,7,324,10" Name="lblExistingAttachemnt"  />
        <telerikGrid:RadGridView x:FieldModifier="public" 
                         x:Name="EditableGV" 
                         AutoGenerateColumns="False" 
                         ItemsSource="{Binding PositionAttachemntCollection, Mode=TwoWay}" Margin="0,0,0,7" Height="150">
            <telerik:RadGridView.Columns>
                <telerik:GridViewDataColumn DataMemberBinding="{Binding FileName,Mode=TwoWay}"></telerik:GridViewDataColumn>
                <telerik:GridViewDataColumn DataMemberBinding="{Binding FileDescription,Mode=TwoWay}"></telerik:GridViewDataColumn>
                <!--<telerik:GridViewColumn Header="" >
                    <telerik:GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <telerik:RadButton Name="btnDownlaod" Content="Save" Click="HyperlinkButton_Click"></telerik:RadButton>
                            <<HyperlinkButton Click="HyperlinkButton_Click"  Content="{Binding FileName,Mode=OneWay}" TargetName="_blank" NavigateUri="http://www.google.com" />
                        </DataTemplate>
                    </telerik:GridViewColumn.CellTemplate>
                </telerik:GridViewColumn>-->
            </telerik:RadGridView.Columns>
        </telerikGrid:RadGridView>

        <StackPanel Orientation="Horizontal" Margin="0">
            <!--<Button Content="Save Attachment" Name="btnSaveAttach" Width="112" Margin="263,6,10,15"  Click="btnSaveAttach_Click" />-->
            <Button Content="Close" Name="btnClose" Width="75" Margin="3,6,10,15" Click="btnClose_Click" />
        </StackPanel>

    </StackPanel>
</StackPanel>

This function is calling on a button click. I am wondering that I have a openFiledialog also oon the same page but is opening the dialog successfully without any error. why that savefile dialog is causing an error.

Below is the stack track of the error:

    at System.Windows.Controls.SaveFileDialog.ShowDialogInternal(Window owner)
   at System.Windows.Controls.SaveFileDialog.ShowDialog()
   at IPVWorkbench.Views.AddPositionAttachments.btnSaveAttach_Click(Object sender, RoutedEventArgs e)
   at System.Windows.Controls.Primitives.ButtonBase.OnClick()
   at System.Windows.Controls.Button.OnClick()
   at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
   at System.Windows.Controls.Control.OnMouseLeftButtonUp(Control ctrl, EventArgs e)
   at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, Int32 actualArgsTypeIndex, String eventName, UInt32 flags)
Rohit Vyas
  • 1,949
  • 3
  • 19
  • 28
  • 1
    What code sits between the button click and this call? There is a minimum time between the user action and when the dialog must appear. If you are exceeding that time you'll get this error. – ChrisF Nov 23 '12 at 13:47
  • I am just fetching the File data and storing it into a public variable "fileByte" – Rohit Vyas Nov 23 '12 at 13:49
  • Where are you fetching the data from? Is it using an asynchronous call? – ChrisF Nov 23 '12 at 13:50
  • No actually I have a grid on my page which shows the FileName & File Description , when user selects the row of grid and click on save button my above function will called, I am just praparing the byte array from the selected row before this function. – Rohit Vyas Nov 23 '12 at 13:54
  • Hmm. Don't know then. It clearly thinks the dialog wasn't user initiated. – ChrisF Nov 23 '12 at 13:58
  • @ChrisF I have updated my main post with the code of button click (btnSaveAttach_Click) please have a look and suggest some workaround..i am really frustating now :-( – Rohit Vyas Nov 23 '12 at 13:58
  • Ultimately I want to download the file which I ahave in memory stream – Rohit Vyas Nov 23 '12 at 15:55
  • Maybe you could try measuring the time elapsed, to see if that's the root cause. – jv42 Nov 24 '12 at 11:43
  • For completeness, please also provide the XAML code where your `btnSaveAttach` button is defined. Also note that you cannot call `btnSaveAttach_Click` from the code (but hopefully you already know this). – Anders Gustafsson Nov 27 '12 at 12:40
  • hi @AndersGustafsson I updated the original post with the XMAL code for your reference. – Rohit Vyas Nov 27 '12 at 13:10
  • Are the properties File and FileName simple getter properties or are you doing any long calculations in them? What does the ctor of PositionAttachment do? I think it is a timing problem since you have only some milliseconds time to open the dialog after the click on the button occurs – Jehof Nov 30 '12 at 11:19
  • they are simple properties, I have tried with hardcoded them ..but still same error is coming – Rohit Vyas Dec 02 '12 at 09:12
  • i have found the workaround for this...i have added answere – Rohit Vyas Dec 02 '12 at 09:15

3 Answers3

2

The answer is given here: http://social.msdn.microsoft.com/Forums/en-US/lightswitch/thread/8c6529ab-8967-45e8-9e19-920589b060c1

This is kinda 'security feature':

Basically, you have to open a SaveFileDialog or OpenFileDialog directly in response to a event that is caused by a user action (e.g. Click), which are only raised on the main thread.

Nickolay Olshevsky
  • 13,706
  • 1
  • 34
  • 48
1

You need to show the SaveFileDialog in your btnSaveAttach_Click (that way it is user-initiated). Also remove all your breakpoints as they can produce that error too.

Try this and see if it works, then you build the rest of your code based on it:

private void btnSaveAttach_Click(object sender, RoutedEventArgs e)
{
    SaveFileDialog dialog2 = new SaveFileDialog();
    saveDialog = dialog2.ShowDialog();
}
Community
  • 1
  • 1
Salvador Sarpi
  • 981
  • 1
  • 8
  • 19
0

I have found a workaround for this. I have shown a confirm box on button click and on "OK" event of confirm box I open save file dialog box, this way it is not throwing any exception.

Rohit Vyas
  • 1,949
  • 3
  • 19
  • 28