Search code examples
c#umbracoumbraco8

Umbraco 8: SetValue has some invalid arguments - Saving new image to media C#


Q) How can I fix the method call below so it's got valid arguments?

Background to problem:

Based on this post here... - I'm trying to download an image from a URL (hard-coded below for brevity), then save it to the media folder.

I get an error:

The best overloaded method match for 'Umbraco.Core.Models.ContentBase.SetValue(string, object, string, string)' has some invalid arguments  

Imports:

using Umbraco.Web.WebApi;
using System.Collections.Generic;
using System.Net;
using System;
using System.Web;
using System.IO;
using Umbraco.Core;

Method detail:

var imageSrc = "https://images.isbndb.com/covers/81/38/9781538748138.jpg";

try 
{
    var mediaSvc = Services.MediaService;
    var mediaExtension = Path.GetExtension(imageSrc);
    var imageName = Guid.NewGuid() + mediaExtension;

    var image = DownloadImageFromUrl(imageSrc);

    const string rootPath = "~\\media";
    var fileName = HttpContext.Current.Server.MapPath(Path.Combine(rootPath, imageName));
    image.Save(fileName);

    dynamic newImage = null;

    // -1 is the root folderID, i.e. Media.  All images will be saved under Media in Umbraco
    newImage = mediaSvc.CreateMedia(imageName, -1, "Image");

    var buffer = System.IO.File.ReadAllBytes(HttpContext.Current.Server.MapPath("~\\media\\" + imageName));

    newImage.SetValue(Services.ContentTypeBaseServices, "umbracoFile", imageName, new MemoryStream(buffer));
    mediaSvc.Save(newImage);

    if (System.IO.File.Exists(HttpContext.Current.Server.MapPath("~\\media\\" + imageName)))
    {
        System.IO.File.Delete(HttpContext.Current.Server.MapPath("~\\media\\" + imageName));
    }

    return newImage.Id;
}
catch(Exception ex) {
    return ex;
}

Solution

  • I have fixed this by changing the lines

    dynamic newImage = null;
    newImage = mediaSvc.CreateMedia(imageName, -1, "Image");
    

    to:

    var newImage = mediaSvc.CreateMedia(imageName, -1, "Image");
    

    So it must be the dynamic keyword that was causing the method to match to the wrong signature, not the extension method.