private void ImportImageAndAttachToEntry(InRiverImportResource inriverResource) { Guid mediaGuid = EpiserverEntryIdentifier.EntityIdToGuid(inriverResource.ResourceId); if (_contentRepository.TryGet(mediaGuid, out MediaData existingMediaData)) { _logger.Debug($"Found existing resource with Resource ID: {inriverResource.ResourceId}"); // ReSharper disable once SuspiciousTypeConversion.Global UpdateMetaData((IInRiverResource)existingMediaData, inriverResource); if (inriverResource.Action == ImporterActions.Added) { AddLinksFromMediaToCodes(existingMediaData, inriverResource.EntryCodes); } } else { existingMediaData = CreateNewFile(inriverResource); if (existingMediaData == null) { return; } AddLinksFromMediaToCodes(existingMediaData, inriverResource.EntryCodes); } }
private void UpdateMetaData(IInRiverResource resource, InRiverImportResource updatedResource) { MediaData editableMediaData = (MediaData)((MediaData)resource).CreateWritableClone(); ResourceMetaField resourceFileId = updatedResource.MetaFields.FirstOrDefault(m => m.Id == "ResourceFileId"); if (resourceFileId != null && !string.IsNullOrEmpty(resourceFileId.Values.First().Data) && resource.ResourceFileId != int.Parse(resourceFileId.Values.First().Data)) { IBlobFactory blobFactory = ServiceLocator.Current.GetInstance <IBlobFactory>(); FileInfo fileInfo = new FileInfo(updatedResource.Path); if (fileInfo.Exists == false) { throw new FileNotFoundException("File could not be imported", updatedResource.Path); } string ext = fileInfo.Extension; Blob blob = blobFactory.CreateBlob(editableMediaData.BinaryDataContainer, ext); using (Stream s = blob.OpenWrite()) { FileStream fileStream = File.OpenRead(fileInfo.FullName); fileStream.CopyTo(s); } editableMediaData.BinaryData = blob; editableMediaData.RouteSegment = GetUrlSlug(updatedResource); } ((IInRiverResource)editableMediaData).HandleMetaData(updatedResource.MetaFields); _contentRepository.Save(editableMediaData, SaveAction.Publish, AccessLevel.NoAccess); }
private List <InRiverImportResource> DeserializeRequest(ImportResourcesRequest request) { _logger.Debug($"Deserializing and preparing {request.ResourceXmlPath} for import."); var serializer = new XmlSerializer(typeof(Resources)); Resources resources; using (XmlReader reader = XmlReader.Create(request.ResourceXmlPath)) { resources = (Resources)serializer.Deserialize(reader); } var resourcesForImport = new List <InRiverImportResource>(); foreach (Resource resource in resources.ResourceFiles.Resource) { var newRes = new InRiverImportResource { Action = resource.action }; if (resource.ParentEntries?.EntryCode != null) { foreach (Interfaces.Poco.EntryCode entryCode in resource.ParentEntries.EntryCode) { if (String.IsNullOrEmpty(entryCode.Value)) { continue; } newRes.Codes.Add(entryCode.Value); newRes.EntryCodes.Add(new EntryCode { Code = entryCode.Value, IsMainPicture = entryCode.IsMainPicture }); } } if (resource.action != ImporterActions.Deleted) { newRes.MetaFields = GenerateMetaFields(resource); // path is ".\some file.ext" if (resource.Paths?.Path != null) { string filePath = resource.Paths.Path.Value.Remove(0, 1); filePath = filePath.Replace("/", "\\"); newRes.Path = request.BasePath + filePath; } } newRes.ResourceId = resource.id; resourcesForImport.Add(newRes); } return(resourcesForImport); }
private string GetUrlSlug(InRiverImportResource updatedResource) { string rawFilename = null; if (updatedResource.MetaFields.Any(f => f.Id == "ResourceFilename")) { rawFilename = updatedResource.MetaFields.First(f => f.Id == "ResourceFilename").Values[0].Data; } else if (updatedResource.MetaFields.Any(f => f.Id == "ResourceFileId")) { rawFilename = updatedResource.MetaFields.First(f => f.Id == "ResourceFileId").Values[0].Data; } return(_urlSegmentGenerator.Create(rawFilename)); }
private void ImportResource(InRiverImportResource resource) { if (resource.Action == ImporterActions.Added || resource.Action == ImporterActions.Updated) { ImportImageAndAttachToEntry(resource); } else if (resource.Action == ImporterActions.Deleted) { _logger.Debug($"Got delete action for resource id: {resource.ResourceId}."); HandleDelete(resource); } else if (resource.Action == ImporterActions.Unlinked) { HandleUnlink(resource); } }
private void HandleDelete(InRiverImportResource inriverResource) { var existingMediaData = _contentRepository.Get <MediaData>(EpiserverEntryIdentifier.EntityIdToGuid(inriverResource.ResourceId)); List <IDeleteActionsHandler> importerHandlers = ServiceLocator.Current.GetAllInstances <IDeleteActionsHandler>().ToList(); if (_config.RunDeleteActionsHandlers) { foreach (IDeleteActionsHandler handler in importerHandlers) { handler.PreDeleteResource(inriverResource); } } _contentRepository.Delete(existingMediaData.ContentLink, true, AccessLevel.NoAccess); if (_config.RunDeleteActionsHandlers) { foreach (IDeleteActionsHandler handler in importerHandlers) { handler.PostDeleteResource(inriverResource); } } }
private void HandleUnlink(InRiverImportResource inriverResource) { var existingMediaData = _contentRepository.Get <MediaData>(EpiserverEntryIdentifier.EntityIdToGuid(inriverResource.ResourceId)); DeleteLinksBetweenMediaAndCodes(existingMediaData, inriverResource.Codes); }
private MediaData CreateNewFile(InRiverImportResource inriverResource) { ResourceMetaField resourceFileId = inriverResource.MetaFields.FirstOrDefault(m => m.Id == "ResourceFileId"); if (String.IsNullOrEmpty(resourceFileId?.Values.FirstOrDefault()?.Data)) { _logger.Debug("ResourceFileId is null, won't do stuff."); return(null); } _logger.Debug($"Attempting to create and import file from path: {inriverResource.Path}"); var fileInfo = new FileInfo(inriverResource.Path); IEnumerable <Type> mediaTypes = _contentMediaResolver.ListAllMatching(fileInfo.Extension).ToList(); _logger.Debug($"Found {mediaTypes.Count()} matching media types for extension {fileInfo.Extension}."); Type contentTypeType = mediaTypes.FirstOrDefault(x => x.GetInterfaces().Contains(typeof(IInRiverResource))) ?? _contentMediaResolver.GetFirstMatching(fileInfo.Extension); if (contentTypeType == null) { _logger.Warning($"Can't find suitable content type when trying to import {inriverResource.Path}"); } else { _logger.Debug($"Chosen content type-type is {contentTypeType.Name}."); } ContentType contentType = _contentTypeRepository.Load(contentTypeType); var newFile = _contentRepository.GetDefault <MediaData>(GetFolder(fileInfo, contentType), contentType.ID); newFile.Name = fileInfo.Name; newFile.ContentGuid = EpiserverEntryIdentifier.EntityIdToGuid(inriverResource.ResourceId); // ReSharper disable once SuspiciousTypeConversion.Global if (newFile is IInRiverResource resource) { resource.ResourceFileId = Int32.Parse(resourceFileId.Values.First().Data); resource.EntityId = inriverResource.ResourceId; try { resource.HandleMetaData(inriverResource.MetaFields); } catch (Exception exception) { _logger.Error($"Error when running HandleMetaData for resource {inriverResource.ResourceId} with contentType {contentType.Name}: {exception.Message}"); } } Blob blob = _blobFactory.CreateBlob(newFile.BinaryDataContainer, fileInfo.Extension); using (Stream stream = blob.OpenWrite()) { FileStream fileStream = File.OpenRead(fileInfo.FullName); fileStream.CopyTo(stream); fileStream.Dispose(); } newFile.BinaryData = blob; _logger.Debug($"New mediadata is ready to be saved: {newFile.Name}, from path {inriverResource.Path}"); ContentReference contentReference = _contentRepository.Save(newFile, SaveAction.Publish, AccessLevel.NoAccess); var mediaData = _contentRepository.Get <MediaData>(contentReference); _logger.Debug($"Saved file {fileInfo.Name} with Content ID {contentReference?.ID}."); return(mediaData); }
public bool ImportResourcesToEPiServerCommerce(string fileNameInCloud, string baseResourcePath, string endpointAddress, string apikey, int timeout) { var serializer = new XmlSerializer(typeof(Resources)); Resources resources; var xml = GetResourceXMLFromCloudShare(context.Settings, fileNameInCloud); using (var streamReader = new StreamReader(xml)) { using (var reader = XmlReader.Create(streamReader.BaseStream)) { resources = (Resources)serializer.Deserialize(reader); } } List <InRiverImportResource> resourcesForImport = new List <InRiverImportResource>(); foreach (var resource in resources.ResourceFiles.Resource) { InRiverImportResource newRes = new InRiverImportResource(); newRes.Action = resource.action; newRes.Codes = new List <string>(); if (resource.ParentEntries != null && resource.ParentEntries.EntryCode != null) { foreach (EntryCode entryCode in resource.ParentEntries.EntryCode) { if (!string.IsNullOrEmpty(entryCode.Value)) { newRes.Codes = new List <string>(); newRes.Codes.Add(entryCode.Value); newRes.EntryCodes.Add(new Interfaces.EntryCode() { Code = entryCode.Value, SortOrder = entryCode.SortOrder }); } } } if (resource.action != "deleted") { newRes.MetaFields = this.GenerateMetaFields(resource); // path is ".\some file.ext" if (resource.Paths != null && resource.Paths.Path != null) { string filePath = resource.Paths.Path.Value.Remove(0, 1); filePath = filePath.Replace("/", "\\"); newRes.Path = filePath; } } newRes.ResourceId = resource.id; resourcesForImport.Add(newRes); } if (resourcesForImport.Count == 0) { context.Log(LogLevel.Debug, string.Format("Nothing to tell server about.")); return(true); } Uri importEndpoint = new Uri(endpointAddress); return(PostResourceDataToImporterEndPoint(fileNameInCloud, importEndpoint, resourcesForImport, apikey, timeout)); }