3
votes

I have created some Razor code to output images onto a page if the exist. It is detailed below and contains some simple checks to prevent rendering a blank list item. The site has gone live and works fine. The client then deleted the image from the media folder within Umbraco, meaning my node had a valid image assigned but the image just didn't exists. I got the following exception:

'string' does not contain a definition for 'crops'

How do I deal with this?

@using umbraco.MacroEngines;
@inherits umbraco.MacroEngines.DynamicNodeContext
@using umbraco.presentation.nodeFactory
@using umbraco.cms.businesslogic.media

<ul>
    @foreach (dynamic client in @Model.Children)
    {
        var image = Model.MediaById(client.Logo);
        var crops = image.imageCropper.crops;

        <li>
            <h2><span>@client.Name</span></h2>

            @if (crops != null || crops.GetType().ToString() != "System.String")
            {
                <span class="itemImage">
                    <img src="@crops.Find("@name", "cropname").url" alt="@client.Name" />
                </span>
            }
        </li>
    }
</ul>
2

2 Answers

0
votes

In this case you'll probably need to do a type check. I believe the MediaById method should return a DynamicNode if it's valid, so something like the following should work:

if(image.GetType() == typeof(DynamicNode))
{
    ...
}
0
votes

I was getting this issue. What I found is that the Model.MediaById(imageid) call would throw an exception if the Media had been deleted (and had already been picked in the past).

So I setup my test like this:

dynamic mainMediaImage = new DynamicNull();
try
{
  mainMediaImage = Model.MediaById(related.eventMainImage);
}
catch(Exception e)
{
  <p style='display: none;'>@e.Message</p>
}
var cropUrl = "";

if(mainMediaImage.GetType() == typeof(DynamicMedia))
{  
   cropUrl = GetImageCropperUrl(Model.MediaById(related.eventMainImage).crops, "List Image");    
}       

I still get the error, but it doesn't display to the user.

I found it would never get to my DynamicMedia check so I had to add the try...catch() around the call or else to entire Macro would fail.