Skip to content

Instantly share code, notes, and snippets.

@dampee
Created December 28, 2018 13:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dampee/fc037b5e0b44b554676ecb6d667106fa to your computer and use it in GitHub Desktop.
Save dampee/fc037b5e0b44b554676ecb6d667106fa to your computer and use it in GitHub Desktop.
Reproduction of U4-9904
using System.IO;
using System.Linq;
using System.Net;
using System.Web.Http;
using Umbraco.Core.Models;
using Umbraco.Web.WebApi;
namespace U4_9904.Controllers
{
public class MediaTestController : UmbracoApiController
{
[HttpGet]
public bool CreateImage(int timesToRun = 1, bool? withworkaround = null)
{
for (int i = 0; i < timesToRun; i++)
{
GetAndSaveImage(withworkaround ?? false);
}
return true;
}
private void GetAndSaveImage(bool withworkaround)
{
// Get the image from umbraco
IMedia firstFolderWeCanFind = Services.MediaService.GetChildren(-1)
.FirstOrDefault(m => m.ContentType.Alias == "Folder");
if (firstFolderWeCanFind == null)
{
// make sure we have a folder
firstFolderWeCanFind = Services.MediaService.CreateMedia("beautiful images", -1, "Folder");
Services.MediaService.Save(firstFolderWeCanFind);
}
// Get the image from the interwebz
string photoUrl = "https://picsum.photos/200/300/?random";
WebRequest req = WebRequest.Create(photoUrl);
WebResponse response = req.GetResponse();
using (Stream stream = response.GetResponseStream())
using (MemoryStream ms = new MemoryStream())
{
int count = 0;
do
{
byte[] buf = new byte[1024];
count = stream.Read(buf, 0, 1024);
ms.Write(buf, 0, count);
} while (stream.CanRead && count > 0);
// b = ms.ToArray();
ms.Position = 0;
// Determine the internal filename
int startIndex = photoUrl.LastIndexOf("/", System.StringComparison.Ordinal) + 1;
var lenght = (photoUrl.IndexOf("?", startIndex, System.StringComparison.Ordinal) >= 0)
? photoUrl.IndexOf("?", startIndex, System.StringComparison.Ordinal) - startIndex
: photoUrl.Length - startIndex;
var fileName = photoUrl.Substring(startIndex, lenght);
if (fileName == "")
{
fileName = "random-image.jpg";
}
// Get the image from umbraco
IMedia image = Services.MediaService.GetChildren(firstFolderWeCanFind.Id)
.FirstOrDefault(m => m.ContentType.Alias == "Image");
if (image == null)
{
image = Services.MediaService.CreateMedia(fileName, firstFolderWeCanFind, "Image");
}
else if (withworkaround == true)
{
// https://issues.umbraco.org/issue/U4-9904
// Set the umbracoFile value to null, so that when SetValue is called
// the 'old' value will be null and Umbraco will not try to delete the file
image.Properties["umbracoFile"].Value = null;
}
image.SetValue("umbracoFile", fileName, ms);
Services.MediaService.Save(image);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment