The module is developed by @maaakstiles and I really like it because it’s easy to extend/change to fit your requirements. The basic idea is very easy. It gets data from somewhere (Sitecore/CSV/SQL/MySQL). I played with the SQL part.
I would like to import files from another database and create a media item from it. To make it work I had to do 2 changes.
Make it to deal with byte[]
using System; | |
using System.Data; | |
using Sitecore.Data; | |
using Sitecore.Data.Items; | |
namespace Sitecore.SharedSource.DataImporter.Providers | |
{ | |
public class CustomSqlDataMap : Sitecore.SharedSource.DataImporter.Providers.SqlDataMap | |
{ | |
public CustomSqlDataMap(Database db, string connectionString, Item importItem) | |
: base(db, connectionString, importItem) | |
{} | |
protected override string GetFieldValue(object importRow, string fieldName) | |
{ | |
var item = importRow as DataRow; | |
var f = item[fieldName]; | |
// it was the missing area because the default solution calls the .ToString() | |
// and if it's byte[] then I get "System.Byte[]" | |
var bytes = f as byte[]; | |
if (bytes != null) | |
{ | |
return Convert.ToBase64String(bytes); | |
} | |
return (f != null) ? f.ToString() : string.Empty; | |
} | |
} | |
} |
So now I have the byte array converted to string. This value is passed to the FillField method so now I need to change that to attach this stream to the media item.
using System; | |
using System.IO; | |
using Sitecore.Data.Items; | |
using Sitecore.Resources.Media; | |
using Sitecore.SharedSource.DataImporter.Mappings.Fields; | |
using Sitecore.SharedSource.DataImporter.Providers; | |
namespace Sitecore.SharedSource.DataImporter.Mappings.Fields | |
{ | |
public class ToMedia : ToText | |
{ | |
public ToMedia(Item i) | |
: base(i) | |
{} | |
public override void FillField(BaseDataMap map, ref Item newItem, string importValue) | |
{ | |
var bytes = Convert.FromBase64String(importValue); | |
var media = MediaManager.GetMedia(newItem); | |
// here upload the picture as a .jpg | |
media.SetStream(new MemoryStream(bytes, false), "jpg"); | |
// it's needed to make it editable after SetStream becauase it closes the edit context | |
if (!newItem.Editing.IsEditing) | |
{ | |
newItem.Editing.BeginEdit(); | |
} | |
} | |
} | |
} |
Remaining step is create a new template for Field in Sitecore and use it. This video shows how you can do that: