Pregunta

Estoy cargando imágenes del usuario utilizando Silverlight 3. Todo funciona bien y que puede establecer el flujo de archivos a un BitmapImage y se rindió bien.

El problema es que si intento cargar algo que no es una imagen (como un .exe que ha sido renombrada como .png) Silverlight se estrella con un System.Exception que dice "error catastrófico". La documentación de MSDN inútilmente dice que debería ser por lo que MSDN enlace y yo debería escuchar al evento ImageFailed (que nunca es despedido).

Me estoy perdiendo algo allí o se ha roto la biblioteca durante la carga de una corriente?

El código tengo cargar la imagen de la fuente:

        var openFileDialog = new OpenFileDialog();
        openFileDialog.Filter = "*.jpg;*.jpeg;*.png|*.jpg;*.jpeg;*.png";
        openFileDialog.Multiselect = false;
        var showDialog = openFileDialog.ShowDialog();

        if (showDialog.HasValue && showDialog.Value)
        {
            using (var reader = openFileDialog.File.OpenRead())
            {
                var picture = new BitmapImage();

                picture.DownloadProgress += (o, e) => System.Threading.SynchronizationContext.Current.Send((oo) => System.Windows.Browser.HtmlPage.Window.Alert("Download progress: " + e.Progress), null);
                picture.ImageFailed += (o, e) => System.Threading.SynchronizationContext.Current.Send((oo) => System.Windows.Browser.HtmlPage.Window.Alert("Image failed: " + e.ErrorException), null);
                picture.ImageOpened += (o, e) => System.Threading.SynchronizationContext.Current.Send((oo) => System.Windows.Browser.HtmlPage.Window.Alert("Image opened: " + e.OriginalSource), null);

                picture.SetSource(reader); // BANG! here without any of the alerts showing up
            }
        }
¿Fue útil?

Solución

Eso es raro, pero tienes razón, que se comporta de esa manera, incluso en Silverlight 4.

No puede ser una opción mejor, pero de una manera que he encontrado para trabajar en torno a estas excepciones que no pueden ser manejados de otra forma es modificar el método App.Application_UnhandledException (). Esto funcionaría para usted:

private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
    // Handle stupid image load exception.  Can't think of a better way to do it -- sorry.
    if (e.ExceptionObject is System.Exception && e.ExceptionObject.Message.Contains("HRESULT") && e.ExceptionObject.Message.Contains("E_UNEXPECTED"))
    {
        Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                MessageBox.Show("Error loading image.");
            });
        e.Handled = true;
        return;
    }

    // If the app is running outside of the debugger then report the exception using
    // the browser's exception mechanism. On IE this will display it a yellow alert 
    // icon in the status bar and Firefox will display a script error.
    if (!System.Diagnostics.Debugger.IsAttached)
    {

        // NOTE: This will allow the application to continue running after an exception has been thrown
        // but not handled. 
        // For production applications this error handling should be replaced with something that will 
        // report the error to the website and stop the application.
        e.Handled = true;
        Deployment.Current.Dispatcher.BeginInvoke(delegate { ReportErrorToDOM(e); });
    }
}

Es un truco y no me gusta, pero es mejor que una excepción no controlada.

Por cierto, que realmente debería informar de un problema Connect en este comportamiento. Es con toda seguridad no pasa la "Ley de asombro menos". Ver el post de Tim Heuer sobre cómo conseguir el insecto presentó: http://timheuer.com/blog/archive/2010/05/03/ways-to-give-feedback-on-silverlight.aspx

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top