I needed to convert the type for some media files. Suddenly webp files were sent to the CMS from an external system and webp was not added to the ExtensionString in the MediaDescriptor yet. So they ended up as generic media (MediaData), instead of an ImageFile (ImageData).
There is not an out of the box way to do this, like with converting page types. So I decided to borrow some of the code that is used to convert page types and use it in a migrationstep. There are also some sql solutions to be found when you look for it, but I found those a bit scary tbh
The full migration step is in a gist, so I will just go through the steps in short here
First I needed to get all the GenericMedia
var usages = _contentModelUsage.ListContentOfContentType(contentType).Select(u => u.ContentLink.ToReferenceWithoutVersion()).Distinct().ToList();
If the name of the file ended with .webp add it to a list to process later
if (genericMedia.Name.EndsWith(".webp", StringComparison.OrdinalIgnoreCase))
{
webpFiles.Add(genericMedia);
}
The converter needs a property mapping so you will need to create one like this (based on Alloy)
var oldProperties = oldContentType.PropertyDefinitions;
var newProperties = newContentType.PropertyDefinitions;
var propertyMap = new List<KeyValuePair<int, int>>();
foreach (var oldProperty in oldProperties)
{
var propertyDefinition = newProperties.FirstOrDefault(p =>
p.Name.Equals(oldProperty.Name, StringComparison.OrdinalIgnoreCase));
if (propertyDefinition != null)
{
propertyMap.Add(new KeyValuePair<int, int>(oldProperty.ID, propertyDefinition.ID));
}
}
// Of course if you have vastly different properties/named properties you have to do a "manual" lookup in the definitions and add it to the mapping
var description = oldProperties.FirstOrDefault(p => p.Name.Equals("Description", StringComparison.OrdinalIgnoreCase));
var copyRight = newProperties.FirstOrDefault(p => p.Name.Equals("Copyright", StringComparison.OrdinalIgnoreCase));
if (description != null && copyRight != null)
{
propertyMap.Add(new KeyValuePair<int, int>(description.ID, copyRight.ID));
}
With all the needed info you can call the borrowed, and slightly adapted (as it was just for PageData), Convert method
ConvertMedia(content.ContentLink.ID, oldContentType.ID, newContentType.ID, propertyMap, false, false);
The result is that webp files that were GenericMedia are now ImageFiles.
The complete migrationstep is, as said before, in a gist.