Mobile Zone is brought to you in partnership with:

Chris has been married to the love of his life, Danielle, for over four years now and they recently had their first child, their daughter Helena. Chris was an expert wrangler of developer content for DZone, but recently started creating marketing content for DZone and AnswerHub. If you're looking for someone to bore you to death with endless football knowledge, Chris is your go-to-guy! Chris is a DZone employee and has posted 286 posts at DZone. You can read more from them at their website. View Full User Profile

BackgroundCreation Crashing the Designer in Visual Studio? STOP IT!

01.31.2012
| 1938 views |
  • submit to reddit

Windows Phone Mango introduced a new enum value to bitmap creation that will actually load and decode the image on a background thread instead of on the UI thread. In some cases, that gives noticeable perf benefits, but there are a few things that are problematic about it.

Default is everything

For some very good reasons, this behavior is off by default. Developers need to opt-in to it.

That also means though, that 99% of the apps out there are just not using it. That’s not a big deal in most cases, but in some, it can make your app feel much snappier.

Originally Authored by Social Ebola

 

So where’s the crash?

In Visual Studio, if you try to use this property, under certain circumstances, the designer will crash (show an error on the designer surface):

System.Reflection.TargetInvocationException
Exception has been thrown by the target of an invocation.
   at System.RuntimeMethodHandle._InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeType typeOwner)
   at System.RuntimeMethodHandle.InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeType typeOwner)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
   at System.Delegate.DynamicInvokeImpl(Object[] args)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)

System.InvalidOperationException
Layout measurement override of element 'Microsoft.Windows.Design.Platform.SilverlightViewProducer+SilverlightContentHost' should not return PositiveInfinity as its DesiredSize, even if Infinity is passed in as available size.
   at System.Windows.UIElement.Measure(Size availableSize)
   at MS.Internal.Designer.DeviceSkinViewPresenter.DeviceDesignerBackground.MeasureOverride(Size constraint)
   at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
   at System.Windows.UIElement.Measure(Size availableSize)
   at Microsoft.Windows.Design.Interaction.DesignerView.MeasureOverride(Size constraint)
   at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
   at System.Windows.UIElement.Measure(Size availableSize)
   at MS.Internal.Designer.Viewport.MeasureOverride(Size availableSize)
   at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
   at System.Windows.UIElement.Measure(Size availableSize)
   at MS.Internal.Helper.MeasureElementWithSingleChild(UIElement element, Size constraint)
   at System.Windows.Controls.ScrollContentPresenter.MeasureOverride(Size constraint)
   at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
   at System.Windows.UIElement.Measure(Size availableSize)
   at System.Windows.Controls.Grid.MeasureCell(Int32 cell, Boolean forceInfinityV)
   at System.Windows.Controls.Grid.MeasureCellsGroup(Int32 cellsHead, Size referenceSize, Boolean ignoreDesiredSizeU, Boolean forceInfinityV)
   at System.Windows.Controls.Grid.MeasureOverride(Size constraint)
   at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
   at System.Windows.UIElement.Measure(Size availableSize)
   at System.Windows.Controls.ScrollViewer.MeasureOverride(Size constraint)
   at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
   at System.Windows.UIElement.Measure(Size availableSize)
   at System.Windows.Controls.Grid.MeasureOverride(Size constraint)
   at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
   at System.Windows.UIElement.Measure(Size availableSize)
   at MS.Internal.Helper.MeasureElementWithSingleChild(UIElement element, Size constraint)
   at System.Windows.Controls.ContentPresenter.MeasureOverride(Size constraint)
   at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
   at System.Windows.UIElement.Measure(Size availableSize)
   at System.Windows.Controls.Control.MeasureOverride(Size constraint)
   at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
   at System.Windows.UIElement.Measure(Size availableSize)
   at System.Windows.Interop.HwndSource.SetLayoutSize()
   at System.Windows.Interop.HwndSource.set_RootVisualInternal(Visual value)
   at MS.Internal.DeferredHwndSource.ProcessQueue(Object sender, EventArgs e)


So what’s the problem?

The issue is with the runtime used in Visual Studio to display the WP7 XAML. Visual Studio 2010 uses the Silverlight engine for this and the Silverlight engine apparently does not have that enum value implemented – and so, if there’s a design time DataContext applied in XAML, Silverlight craps out and crashes, causing the error message you see.

How do you solve it?

There may be a bunch of ways of solving it, but mine involves a Converter. Use the <Image> XAML element as you usually would, but in the Binding of the Source, apply the attached converter with the relevant parameters:

<Image Source="{Binding Path=MyImage, Converter={StaticResource RuntimeImageLoaderConverter1}, ConverterParameter=bd}"/>


The converter obviously needs to be declared in the Resources of the page or control. The interesting bit is the use of the converter parameters:

ConverterParameter=bd

“b” will make sure the image gets loaded in the background (the aforementioned BackgroundCreation flag) and “d” will make sure that it’s delay loaded.

That’s it – once you use the designer, the system will load the image normally (no funky flags) when in the designer and with the relevant flags when actually running on the phone.

How does it work?

It’s pretty simple, the converter checks to see if it’s in the design environment and if it is, it will default-create the Image. Otherwise, it will use the relevant flags (it also makes sure it knows how to load string URIs and regular URIs):

public class RuntimeImageLoaderConverter : IValueConverter
{

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        Uri uri = null;
        if (value is Uri)
        {
            uri = (Uri)value;
        }
        else if (value is String)
        {
            string s = (string)value;
            if (s.StartsWith("/"))
            {
                Uri.TryCreate(s, UriKind.Relative, out uri);
            }
            else
            {
                Uri.TryCreate(s, UriKind.Absolute, out uri);
            }
        }

        BitmapCreateOptions options = BitmapCreateOptions.None;

        string p = parameter as string;
        if (p != null && GetIsInDesignMode())
        {
            if (p.Contains("b") || p.Contains("B"))
            {
                options |= BitmapCreateOptions.BackgroundCreation;
            }

            if (p.Contains("d") || p.Contains("D"))
            {
                options |= BitmapCreateOptions.DelayCreation;
            }
        }

        BitmapImage result = null;
        if (uri != null)
        {
            result = new BitmapImage();
            result.CreateOptions = options;
            result.UriSource = uri;
        }

        return result;
    }


That’s about it. Hope this helps someone. :)

Download



Source: http://socialebola.wordpress.com/2012/01/25/backgroundcreation-crashes-the-designer/