Develop
Examples of what you can do with the add-on.
Import media files
The following sample shows how a media file is imported into Litium.
A check is performed in the import folder in Litium with the Exists method, to see whether the file already exists.
private bool Exists(string fileName, Guid folderId, out File existingFile)
{
using (var query = _dataService.CreateQuery<File>())
{
var items = query.Filter(x => x
.Bool(b => b
.Must(m => m.Field(SystemFieldDefinitionConstants.NameInvariantCulture, "eq", fileName)
.FolderSystemId(folderId))));
existingFile = items.FirstOrDefault();
return existingFile != null;
}
}
FieldTemplateService is used to get the correct template for the import-file by file extension. Then a blob container is created by the blob service and the file to import is streamed into the blob container.
protected override void ProcessItem(Item item)
{
var fieldTemplate = _fieldTemplateService.FindFileTemplate(item.FileInfo.Extension);
if(fieldTemplate == null)
{
throw new Exception($"{Messages.MediaFieldTemplateNotFoundForExtension} {item.FileInfo.Extension}");
}
long fileSize = 0;
var blobContainer = _blobService.Create(File.BlobAuthority);
using (var fileStream = item.FileInfo.OpenRead())
{
using (var stream = blobContainer.GetDefault().OpenWrite())
{
fileStream.CopyTo(stream);
fileSize = fileStream.Length;
}
}
if(Exists(item.FileInfo.Name, _importFolder.SystemId, out File existingFile))
{
existingFile = existingFile.MakeWritableClone();
existingFile.BlobUri = blobContainer.Uri;
existingFile.FileSize = fileSize;
_fileService.Update(existingFile);
}
else
{
var file = new File(fieldTemplate.SystemId, _importFolder.SystemId, blobContainer.Uri, item.FileInfo.Name)
{
FileSize = fileSize,
Id = item.FileInfo.Name
};
_fileService.Create(file);
}
}