internal File PerformSave(MacroEditorModel model)
        {
            Mandate.ParameterNotNull(model, "model");

            using (var uow = Hive.Create())
            {
                var fileName  = model.Alias.ToUmbracoAlias() + ".macro";
                var newFileId = new HiveId(fileName);
                var macroFile = new File
                {
                    Name         = fileName,
                    ContentBytes = Encoding.UTF8.GetBytes(MacroSerializer.ToXml(model).ToString())
                };
                var existing = uow.Repositories.Get <File>(newFileId);
                //delete the file first before re-saving as AddOrUpdate seems to append to the file
                if (existing != null)
                {
                    uow.Repositories.Delete <File>(newFileId);
                }
                uow.Repositories.AddOrUpdate(macroFile);
                //TODO: the Hive IO provider commit seems to do nothing :( ... needs to be implemented!
                uow.Complete();

                return(macroFile);
            }
        }
Пример #2
0
 /// <summary>
 /// Used by inheritors to make any changes to the model before redirecting
 /// </summary>
 /// <param name="file"></param>
 protected virtual EntityPathCollection CreatePaths(File file)
 {
     using (var uow = Hive.Create())
     {
         return(uow.Repositories.GetEntityPaths <File>(file.Id, FixedRelationTypes.DefaultRelationType));
     }
 }
Пример #3
0
        internal string GetContainingFolder(File file)
        {
            var dir = Path.GetDirectoryName(file.RootedPath);

            // Ensure the folder name ends with a trailing slash)
            return(dir.NormaliseDirectoryPath());
        }
Пример #4
0
        private File Hydrate(FileSystemInfo fileInfo)
        {
            var id = GenerateId(fileInfo.FullName);

            var file = new File(id)
            {
                Name             = fileInfo.Name,
                RootedPath       = fileInfo.FullName,
                IsContainer      = fileInfo is DirectoryInfo,
                UtcCreated       = fileInfo.CreationTimeUtc,
                UtcModified      = fileInfo.LastWriteTimeUtc,
                UtcStatusChanged = fileInfo.LastWriteTimeUtc,
                RootRelativePath = Settings.ApplicationRelativeRoot + ((string)id.Value).Replace('\\', '/'),
            };

            file.PublicUrl = Settings.RootPublicDomain.TrimEnd('/') + "/" + file.RootRelativePath.TrimStart('~', '/');

            if (!file.IsContainer)
            {
                //assign the lazy load delegate to access the stream
                file.SetContentStreamFactory(theFile => ((FileInfo)fileInfo).OpenRead());
            }

            return(file);
        }
Пример #5
0
 /// <summary>
 /// Returns the file extension
 /// </summary>
 /// <param name="file"></param>
 /// <returns></returns>
 public static string GetFileExtension(this File file)
 {
     if (file == null)
     {
         return(string.Empty);
     }
     return(Path.GetExtension(file.Name));
 }
Пример #6
0
 /// <summary>
 /// Returns a nicely formatted file name: without extension and hyphens replaced by spaces for display
 /// </summary>
 /// <param name="file"></param>
 /// <returns></returns>
 public static string GetFileNameForDisplay(this File file)
 {
     if (file == null)
     {
         return(string.Empty);
     }
     return(file.Name.ToFileNameForDisplay());
 }
Пример #7
0
 public static bool IsImage(this File file)
 {
     if (file == null)
     {
         return(false);
     }
     return((",.jpeg,.jpg,.gif,.bmp,.png,.tiff,.tif,")
            .IndexOf("," + Path.GetExtension(file.Name) + ",", StringComparison.InvariantCultureIgnoreCase) > -1);
 }
Пример #8
0
        public static string GetFilePathWithoutExtension(this File file)
        {
            if (file == null)
            {
                return(string.Empty);
            }
            var path = string.Join("/", file.Id.Value.Value.ToString().Split('\\'));

            return(path.Contains(".") ? path.Substring(0, path.LastIndexOf(".")) : path);
        }
Пример #9
0
        private File Hydrate(FileSystemInfo fileInfo)
        {
            var id = GenerateId(fileInfo.FullName);

            var file = new File(id)
            {
                Name         = fileInfo.Name,
                Location     = fileInfo.FullName,
                IsContainer  = fileInfo is DirectoryInfo,
                UtcCreated   = fileInfo.CreationTimeUtc,
                UtcModified  = fileInfo.LastWriteTimeUtc,
                AbsolutePath = _dataContext.ApplicationRelativeRoot + (string)id.Value
            };

            if (!file.IsContainer)
            {
                //assign the lazy load delegate to access the stream
                file.LazyContentStream = new Lazy <Stream>(() => ((FileInfo)fileInfo).OpenRead());
            }

            file.Relations.LazyLoadFactory =
                (source, scope) =>
            {
                var sourceAsFile = (File)source;
                var relations    = new List <Relation>();

                switch (scope)
                {
                case HierarchyScope.AllOrNone:
                    relations.AddRange(GetParent(sourceAsFile));
                    relations.AddRange(GetChildren(file, fileInfo));
                    break;

                case HierarchyScope.Children:
                case HierarchyScope.Descendents:
                case HierarchyScope.DescendentsOrSelf:
                    relations.AddRange(GetChildren(file, fileInfo));
                    break;

                case HierarchyScope.Parent:
                case HierarchyScope.Parents:
                case HierarchyScope.Ancestors:
                case HierarchyScope.AncestorsOrSelf:
                    relations.AddRange(GetParent(sourceAsFile));
                    break;
                }

                return(relations);
            };

            return(file);
        }
Пример #10
0
 public static string GetMimeType(this File file)
 {
     if (file != null)
     {
         var extension     = Path.GetExtension(file.Name);
         var fileExtension = extension.IsNullOrWhiteSpace() ? file.Name : extension.ToLower();
         var rk            = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(fileExtension);
         if (rk != null && rk.GetValue("Content Type") != null)
         {
             return(rk.GetValue("Content Type").ToString());
         }
     }
     return("application/octet-stream");
 }
Пример #11
0
        public static File CreateFile(string contents)
        {
            var file = new File
                {
                    Name = Guid.NewGuid().ToString("N"),
                };

            if (!String.IsNullOrEmpty(contents))
                file.ContentBytes = Encoding.Default.GetBytes(contents);
            else
                file.IsContainer = true;

            return file;
        }
Пример #12
0
        public static File CreateFile(string contents)
        {
            var file = new File
            {
                Name = Guid.NewGuid().ToString("N"),
            };

            if (!String.IsNullOrEmpty(contents))
            {
                file.ContentBytes = Encoding.Default.GetBytes(contents);
            }
            else
            {
                file.IsContainer = true;
            }

            return(file);
        }
Пример #13
0
        private static DirectoryInfo GetParentDirectoryInfo(File file)
        {
            DirectoryInfo parent = null;

            // If the file is a container, the parent is the parent folder
            if (file.IsContainer)
            {
                //check if the current object is the root path, if so return null
                if (((string)file.Id.Value.Value).IsNullOrWhiteSpace())
                {
                    return(null);
                }
                parent = Directory.GetParent(file.RootedPath.TrimEnd('\\')); // .NET thinks the "current" folder in a path is the one without a trailing slash
            }
            else
            {
                parent = Directory.GetParent(file.RootedPath);
            }
            return(parent);
        }
Пример #14
0
        internal File GetParentModel(File file)
        {
            //check if the entity is actually the root path, if so, then return null
            if (file.IsContainer && file.RootedPath.NormaliseDirectoryPath().InvariantEquals(Settings.AbsoluteRootedPath.NormaliseDirectoryPath()))
            {
                //we are the root folder, return null
                return(null);
            }

            var parent = GetParentDirectoryInfo(file);

            if (parent == null)
            {
                return(null);
            }

            var normalisedPath = parent.FullName.NormaliseDirectoryPath();

            return(this.Get <File>(GenerateId(normalisedPath)));
        }
Пример #15
0
        private IEnumerable <Relation> GetParent(File file)
        {
            var relations = new List <Relation>();

            // Get parent file relation
            var currentFolder = (file.IsContainer
                                     ? file.Location
                                     : file.Location.Replace(file.Name, string.Empty))
                                .TrimEnd(Path.DirectorySeparatorChar);

            if (currentFolder != _rootFolder)
            {
                var dir = new DirectoryInfo(currentFolder);
                relations.Add(new Relation(
                                  FixedRelationTypes.FileRelationType,
                                  file.IsContainer
                        ? GetEntity <File>(GenerateId(dir.Parent.FullName + Path.DirectorySeparatorChar))
                        : GetEntity <File>(GenerateId(dir.FullName)),
                                  file
                                  ));
            }
            else
            {
                //if the folder matches the root folder and the file is not a container, then we need to return the root folder
                if (!file.IsContainer)
                {
                    relations.Add(new Relation(
                                      FixedRelationTypes.FileRelationType,
                                      Hydrate(_directory),
                                      file
                                      ));
                }
            }

            // Get other relations
            relations.AddRange(GetRelationsByPattern("*-" + file.Id.ToString().ToMd5()));

            return(relations);
        }
Пример #16
0
        private IEnumerable <Relation> GetChildren(File file, FileSystemInfo fileInfo)
        {
            var relations = new List <Relation>();

            // Get file relations
            if (file.IsContainer)
            {
                var files = GetFiles((DirectoryInfo)fileInfo);

                relations.AddRange(files.Select(f =>
                                                new Relation(
                                                    FixedRelationTypes.FileRelationType,
                                                    file,
                                                    Hydrate(f)
                                                    )
                                                )
                                   .ToList());
            }

            // Get other relations
            relations.AddRange(GetRelationsByPattern(file.Id.ToString().ToMd5() + "-*"));

            return(relations);
        }
Пример #17
0
 protected virtual void EnsureViewData(FileEditorModel model, File file)
 {
     // To be overridden
 }
        public virtual ActionResult CreateNewForm(CreateFileModel createModel)
        {
            Mandate.ParameterNotNull(createModel, "createModel");
            Mandate.That<NullReferenceException>(createModel.Name != null);
            Mandate.That<NullReferenceException>(!createModel.ParentId.IsNullValueOrEmpty());

            EnsureViewData(createModel);

            //validate the model
            if (!TryUpdateModel(createModel))
            {
                return View(createModel);
            }

            using (var uow = Hive.Create())
            {
                if (createModel.ParentId != FixedHiveIds.SystemRoot)
                {
                    //validate the parent
                    var parentFile = uow.Repositories.Get<File>(createModel.ParentId);
                    if (parentFile == null)
                        throw new ArgumentException("No folder could be found for the parent id specified");
                }


                //if its a folder, then we just create it and return success.                
                if (createModel.CreateType == CreateFileType.Folder)
                {
                    var folder = new File()
                        {
                            IsContainer = true,
                            RootedPath = createModel.ParentId == FixedHiveIds.SystemRoot
                                ? createModel.Name.ToUmbracoAlias(removeSpaces: true)
                                : (string)createModel.ParentId.Value + "/" + createModel.Name.ToUmbracoAlias(removeSpaces: true)
                        };
                    uow.Repositories.AddOrUpdate(folder);
                    uow.Complete();

                    //add notification
                    Notifications.Add(new NotificationMessage("Folder.Save.Message".Localize(this), "Folder.Save.Title".Localize(this), NotificationType.Success));

                    //add path for entity for SupportsPathGeneration (tree syncing) to work
                    GeneratePathsForCurrentEntity(CreatePaths(folder));

                    return RedirectToAction("CreateNew", new { id = folder.Id });

                }

                var model = FileEditorModel.CreateNew();
                model.Name = createModel.Name.ToUmbracoAlias(removeSpaces:true) + createModel.FileExtension;
                model.ParentId = createModel.ParentId;

                if (!createModel.Stub.IsNullValueOrEmpty())
                    PopulateFileContentFromStub(model, createModel.Stub.Value);

                EnsureViewData(model, null);

                OnBeforeCreate(createModel, model);

                var file = PerformSave(model);

                OnAfterCreate(file);

                //add notification
                Notifications.Add(new NotificationMessage(SaveSuccessfulMessage, SaveSuccessfulTitle, NotificationType.Success));

                //add path for entity for SupportsPathGeneration (tree syncing) to work
                GeneratePathsForCurrentEntity(CreatePaths(file));

                return RedirectToAction("Edit", new { id = file.Id });

            }

        }
 protected virtual void EnsureViewData(FileEditorModel model, File file)
 {
     // To be overridden
 }
 /// <summary>
 /// Used by inheritors to make any changes to the model before redirecting
 /// </summary>
 /// <param name="file"></param>
 protected virtual EntityPathCollection CreatePaths(File file)
 {
     using (var uow = Hive.Create())
     {
         return uow.Repositories.GetEntityPaths<File>(file.Id, FixedRelationTypes.DefaultRelationType);
     }
 }
        /// <summary>
        /// Used by inheritors to make any changes to the model before creation
        /// </summary>
        /// <param name="model"></param>
        protected virtual void OnAfterCreate(File file)
        {

        }
 /// <summary>
 /// Used by inheritors to make any changes to the file before it is persisted
 /// </summary>
 /// <param name="file"></param>
 protected virtual void OnBeforeSave(File file)
 {            
 }
Пример #23
0
        internal static void CreateThumbnail(IGroupUnit<IFileStore> uow, File original, Image image, string mediaId, int maxWidthHeight)
        {
            var extension = Path.GetExtension(original.Name).ToLower();
            var thumbFileName = Path.GetFileNameWithoutExtension(original.Name) + "_" + maxWidthHeight + extension;

            // Create file entity
            var thumb = new File
                            {
                                RootedPath = mediaId + "/" + thumbFileName             
                            };

            // Resize image
            var val = (float)image.Width / (float)maxWidthHeight;
            var val2 = (float)image.Height / (float)maxWidthHeight;

            var num = Math.Max(val, val2);

            var num2 = (int)Math.Round((double)((float)image.Width / num));
            var num3 = (int)Math.Round((double)((float)image.Height / num));

            if (num2 == 0)
            {
                num2 = 1;
            }

            if (num3 == 0)
            {
                num3 = 1;
            }

            using(var bitmap = new Bitmap(num2, num3))
            using (var graphics = Graphics.FromImage(bitmap))
            {
                graphics.SmoothingMode = SmoothingMode.HighQuality;
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

                var destRect = new Rectangle(0, 0, num2, num3);
                graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);

                var imageEncoders = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo encoder = null;
                if (extension == ".png" || extension == ".gif")
                    encoder = imageEncoders.Single(t => t.MimeType.Equals("image/png"));
                else
                    encoder = imageEncoders.Single(t => t.MimeType.Equals("image/jpeg"));

                var stream = new MemoryStream();
                var encoderParameters = new EncoderParameters();
                encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 90L);
                bitmap.Save(stream, encoder, encoderParameters);

                thumb.ContentBytes = stream.ToArray();
            }

            // Add or update file
            uow.Repositories.AddOrUpdate(thumb);

            // Create relation
            uow.Repositories.AddRelation(original, thumb, FixedRelationTypes.ThumbnailRelationType, 0, new RelationMetaDatum("size", maxWidthHeight.ToString()));
        }
Пример #24
0
        internal static void CreateThumbnails(IGroupUnit<IFileStore> uow, File original, string mediaId, string thumbSizes = null)
        {
            if (original.IsImage())
            {
                var img = Image.FromStream(new MemoryStream(original.ContentBytes));

                // Create default thumbnail
                CreateThumbnail(uow, original, img, mediaId, 100);

                // Create additional thumbnails
                if (!String.IsNullOrEmpty(thumbSizes))
                {
                    var sizes = thumbSizes.Split(',');
                    foreach (var size in sizes)
                    {
                        var intSize = 0;
                        if (Int32.TryParse(size, out intSize))
                        {
                            CreateThumbnail(uow, original, img, mediaId, intSize);
                        }
                    }
                }
            }
        }
Пример #25
0
        internal static IDictionary<string, object> WriteUploadedFile(Guid mediaId, bool removeExistingFile, HttpPostedFileBase httpFile, IGroupUnitFactory<IFileStore> groupUnitFactory, HiveId existingFileId = default(HiveId), string thumbSizes = null)
        {
            var val = new Dictionary<string, object>();

            //add the media id to be saved
            val.Add("MediaId", mediaId.ToString("N"));

            // Check to see if we should delete the current file
            // either becuase remove file is checked, or we have a replacement file
            if (existingFileId != HiveId.Empty && (removeExistingFile || HasFile(httpFile)))
            {
                if (!existingFileId.IsNullValueOrEmpty())
                {
                    // delete entire property folder (deletes image and any thumbnails stored)
                    //var folderHiveId = HiveId.Parse("storage://file-uploader/string/" + MediaId.ToString("N"));
                    var folderHiveId = new HiveId("storage", "file-uploader", new HiveIdValue(mediaId.ToString("N")));

                    using (var uow = groupUnitFactory.Create())
                    {
                        try
                        {
                            uow.Repositories.Delete<File>(existingFileId); // Must delete file entity so that relations are deleted
                            uow.Repositories.Delete<File>(folderHiveId);
                            uow.Complete();
                        }
                        catch (Exception ex)
                        {
                            LogHelper.Warn(typeof(ContentExtensions), "Could not delete previous file and/or container", ex);
                        }
                    }
                }
            }

            // If we've received a File from the binding, we need to save it
            if (HasFile(httpFile))
            {
                // Open a new unit of work to write the file
                using (var uow = groupUnitFactory.Create())
                {
                    // Create main file
                    var file = new File
                                   {
                                       RootedPath =
                                           mediaId.ToString("N") + "/" + Path.GetFileName(httpFile.FileName)
                                                .Replace(" ", "").Replace(",", "")
                                   };

                    var stream = httpFile.InputStream;
                    if (stream.CanRead && stream.CanSeek)
                    {
                        stream.Seek(0, SeekOrigin.Begin);
                        using (var mem = new MemoryStream())
                        {
                            stream.CopyTo(mem);
                            file.ContentBytes = mem.ToArray();
                        }
                    }

                    uow.Repositories.AddOrUpdate(file);

                    // Create thumbnails (TODO: Need to encapsulate this so it can be reused in other places?)
                    CreateThumbnails(uow, file, mediaId.ToString("N"), thumbSizes);

                    uow.Complete();

                    val.Add("Value", file.Id);
                }
            }
            else if (!existingFileId.IsNullValueOrEmpty() && !removeExistingFile)
            {
                val.Add("Value", existingFileId);
            }
            else
            {
                val.Add("Value", HiveId.Empty);
            }

            return val;
        }
Пример #26
0
 public static string GetFilePathForDisplay(this File file)
 {
     return(file == null ? string.Empty : string.Join("/", file.Id.Value.Value.ToString().Split('\\').Select(x => x.ToFileNameForDisplay())));
 }
Пример #27
0
        private void CreateThumbnail(IGroupUnit <IFileStore> uow, File original, Image image, string mediaId, int maxWidthHeight)
        {
            var extension     = Path.GetExtension(original.Name).ToLower();
            var thumbFileName = Path.GetFileNameWithoutExtension(original.Name) + "_" + maxWidthHeight + extension;

            // Create file entity
            var thumb = new File
            {
                RootedPath = mediaId + "/" + thumbFileName
            };

            // Resize image
            var val  = (float)image.Width / (float)maxWidthHeight;
            var val2 = (float)image.Height / (float)maxWidthHeight;

            var num = Math.Max(val, val2);

            var num2 = (int)Math.Round((double)((float)image.Width / num));
            var num3 = (int)Math.Round((double)((float)image.Height / num));

            if (num2 == 0)
            {
                num2 = 1;
            }

            if (num3 == 0)
            {
                num3 = 1;
            }

            using (var bitmap = new Bitmap(num2, num3))
                using (var graphics = Graphics.FromImage(bitmap))
                {
                    graphics.SmoothingMode     = SmoothingMode.HighQuality;
                    graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    graphics.PixelOffsetMode   = PixelOffsetMode.HighQuality;

                    var destRect = new Rectangle(0, 0, num2, num3);
                    graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);

                    var            imageEncoders = ImageCodecInfo.GetImageEncoders();
                    ImageCodecInfo encoder       = null;
                    if (extension == ".png" || extension == ".gif")
                    {
                        encoder = imageEncoders.Single(t => t.MimeType.Equals("image/png"));
                    }
                    else
                    {
                        encoder = imageEncoders.Single(t => t.MimeType.Equals("image/jpeg"));
                    }

                    var stream            = new MemoryStream();
                    var encoderParameters = new EncoderParameters();
                    encoderParameters.Param[0] = new EncoderParameter(global::System.Drawing.Imaging.Encoder.Quality, 90L);
                    bitmap.Save(stream, encoder, encoderParameters);

                    thumb.ContentBytes = stream.ToArray();
                }

            // Add or update file
            uow.Repositories.AddOrUpdate(thumb);

            // Create relation
            uow.Repositories.AddRelation(original, thumb, FixedRelationTypes.ThumbnailRelationType, 0, new RelationMetaDatum("size", maxWidthHeight.ToString()));
        }
Пример #28
0
        public virtual ActionResult CreateNewForm(CreateFileModel createModel)
        {
            Mandate.ParameterNotNull(createModel, "createModel");
            Mandate.That <NullReferenceException>(createModel.Name != null);
            Mandate.That <NullReferenceException>(!createModel.ParentId.IsNullValueOrEmpty());

            EnsureViewData(createModel);

            //validate the model
            if (!TryUpdateModel(createModel))
            {
                return(View(createModel));
            }

            using (var uow = Hive.Create())
            {
                if (createModel.ParentId != FixedHiveIds.SystemRoot)
                {
                    //validate the parent
                    var parentFile = uow.Repositories.Get <File>(createModel.ParentId);
                    if (parentFile == null)
                    {
                        throw new ArgumentException("No folder could be found for the parent id specified");
                    }
                }


                //if its a folder, then we just create it and return success.
                if (createModel.CreateType == CreateFileType.Folder)
                {
                    var folder = new File()
                    {
                        IsContainer = true,
                        RootedPath  = createModel.ParentId == FixedHiveIds.SystemRoot
                                ? createModel.Name.ToUmbracoAlias(removeSpaces: true)
                                : (string)createModel.ParentId.Value + "/" + createModel.Name.ToUmbracoAlias(removeSpaces: true)
                    };
                    uow.Repositories.AddOrUpdate(folder);
                    uow.Complete();

                    //add notification
                    Notifications.Add(new NotificationMessage("Folder.Save.Message".Localize(this), "Folder.Save.Title".Localize(this), NotificationType.Success));

                    //add path for entity for SupportsPathGeneration (tree syncing) to work
                    GeneratePathsForCurrentEntity(CreatePaths(folder));

                    return(RedirectToAction("CreateNew", new { id = folder.Id }));
                }

                var model = FileEditorModel.CreateNew();
                model.Name     = createModel.Name.ToUmbracoAlias(removeSpaces: true) + createModel.FileExtension;
                model.ParentId = createModel.ParentId;

                if (!createModel.Stub.IsNullValueOrEmpty())
                {
                    PopulateFileContentFromStub(model, createModel.Stub.Value);
                }

                EnsureViewData(model, null);

                OnBeforeCreate(createModel, model);

                var file = PerformSave(model);

                OnAfterCreate(file);

                //add notification
                Notifications.Add(new NotificationMessage(SaveSuccessfulMessage, SaveSuccessfulTitle, NotificationType.Success));

                //add path for entity for SupportsPathGeneration (tree syncing) to work
                GeneratePathsForCurrentEntity(CreatePaths(file));

                return(RedirectToAction("Edit", new { id = file.Id }));
            }
        }
        public void Initialize()
        {
            #region Vars

            IReadonlyEntityRepositoryGroup<IContentStore> readonlyContentStoreRepository;
            IReadonlySchemaRepositoryGroup<IContentStore> readonlyContentStoreSchemaRepository;
            IEntityRepositoryGroup<IContentStore> contentStoreRepository;
            ISchemaRepositoryGroup<IContentStore> contentStoreSchemaRepository;

            IReadonlyEntityRepositoryGroup<IFileStore> readonlyFileStoreRepository;
            IReadonlySchemaRepositoryGroup<IFileStore> readonlyFileStoreSchemaRepository;
            IEntityRepositoryGroup<IFileStore> fileStoreRepository;
            ISchemaRepositoryGroup<IFileStore> fileStoreSchemaRepository;

            #endregion

            var hive = MockHiveManager.GetManager()
                .MockContentStore(out readonlyContentStoreRepository, out readonlyContentStoreSchemaRepository, out contentStoreRepository, out contentStoreSchemaRepository)
                .MockFileStore(out readonlyFileStoreRepository, out readonlyFileStoreSchemaRepository, out fileStoreRepository, out fileStoreSchemaRepository);

            //Setup file store
            var fileId = new HiveId("storage", "file-uploader", new HiveIdValue("test.jpg"));
            var file = new File
            {
                Id = fileId,
                Name = "test.jpg",
                ContentBytes = Encoding.UTF8.GetBytes("test")
            };

            readonlyFileStoreRepository
                .Get<File>(true, Arg.Any<HiveId[]>())
                .Returns(new[] { file });

            var thumbnailId = new HiveId("storage", "file-uploader", new HiveIdValue("test_100.jpg"));
            var thumbnail = new File
            {
                Id = thumbnailId,
                Name = "test_100.jpg",
                ContentBytes = Encoding.UTF8.GetBytes("test_100")
            };

            var relation = Substitute.For<IReadonlyRelation<IRelatableEntity, IRelatableEntity>>();
            relation.MetaData.Returns(new RelationMetaDataCollection(new[] { new RelationMetaDatum("size", "100") }));
            relation.Source.Returns(file);
            relation.SourceId.Returns(fileId);
            relation.Destination.Returns(thumbnail);
            relation.DestinationId.Returns(thumbnailId);

            readonlyFileStoreRepository.GetLazyChildRelations(fileId, FixedRelationTypes.ThumbnailRelationType)
                .Returns(new[]{ relation });

            //Setup media store
            var mediaPickerAttributeDefType = new AttributeType { RenderTypeProvider = CorePluginConstants.FileUploadPropertyEditorId };
            var mediaPickerAttributeDef = new AttributeDefinition("umbracoFile", "") { Id = FixedHiveIds.FileUploadAttributeType, AttributeType = mediaPickerAttributeDefType };
            var mediaPickerProperty = new TypedAttribute(mediaPickerAttributeDef, fileId.ToString());

            var mediaId = new HiveId("0A647849-BF5C-413B-9420-7AB4C9521505");
            var mediaEntity = new TypedEntity { Id = mediaId };
            //mediaEntity.SetupFromSchema(FixedSchemas.MediaImageSchema);
            mediaEntity.Attributes.Add(mediaPickerProperty);
            mediaEntity.Attributes["umbracoFile"].Values["MediaId"] = "0A647849-BF5C-413B-9420-7AB4C9521505";

            //readonlyContentStoreRepository
            //    .Get<TypedEntity>(true, Arg.Any<HiveId[]>())
            //    .Returns(new[] { mediaEntity });

            //readonlyContentStoreRepository
            //    .SingleOrDefault<TypedEntity>(Arg.Any<Expression<Func<TypedEntity, bool>>>())
            //    .Returns(mediaEntity);

            var mediaEntityList = new List<TypedEntity> { mediaEntity };
            readonlyContentStoreRepository
                .Query()
                .Returns(mediaEntityList.AsQueryable());

            // Setup application
            var appContext = Substitute.For<IUmbracoApplicationContext>();
            appContext.Hive.Returns(hive);

            // Setup back office request
            _backOfficeRequestContext = Substitute.For<IBackOfficeRequestContext>();
            _backOfficeRequestContext.Application.Returns(appContext);

            var member = new Member {Id = new HiveId("0285372B-AB14-45B6-943A-8709476AB655"), Username = "******"};

            // Setup fake HttpContext (Just needed to fake current member)
            var identity = new GenericIdentity(member.Username);
            var user = new GenericPrincipal(identity, new string[0]);
            var wp = new SimpleWorkerRequest("/virtual", "c:\\inetpub\\wwwroot\\physical\\", "page.aspx", "query", new StringWriter());
            HttpContext.Current = new HttpContext(wp) {User = user};

            appContext.Security.Members.GetByUsername(member.Username).Returns(member);

            appContext.Security.PublicAccess.GetPublicAccessStatus(member.Id, mediaEntity.Id)
                .Returns(new PublicAccessStatusResult(mediaEntity.Id, true));
        }
        protected ActionResult ProcessSubmit(PackageDefinitionEditorModel model, bool publish)
        {
            Mandate.ParameterNotNull(model, "model");

            //if there's model errors, return the view
            if (!ModelState.IsValid)
            {
                AddValidationErrorsNotification();
                return View("Edit", model);
            }

            //persist the data
            using (var uow = _hive.Create())
            {
                var entity = BackOfficeRequestContext.Application.FrameworkContext.TypeMappers.Map
                            <PackageDefinitionEditorModel, PackageDefinition>(model);

                var randomId = Guid.NewGuid().ToString();

                if(!model.Id.IsNullValueOrEmpty())
                {
                    var oldFolder = uow.Repositories.Get<Umbraco.Framework.Persistence.Model.IO.File>(model.Id);
                    if (oldFolder != null)
                    {
                        uow.Repositories.Delete<Umbraco.Framework.Persistence.Model.IO.File>(oldFolder.Id);
                        randomId = oldFolder.Id.Value.ToString();
                    }
                }

                // Create folder
                var folder = new Umbraco.Framework.Persistence.Model.IO.File(
                    randomId, "") { IsContainer = true };

                uow.Repositories.AddOrUpdate(folder);

                // Create definition file
                var file = new Umbraco.Framework.Persistence.Model.IO.File(
                    randomId + "/package.definition",
                    Encoding.UTF8.GetBytes(entity.ToJsonString()));

                uow.Repositories.AddOrUpdate(file);

                model.Id = folder.Id;

                uow.Complete();

                //add path for entity for SupportsPathGeneration (tree syncing) to work
                GeneratePathsForCurrentEntity(new EntityPathCollection(model.Id, new[]{ new EntityPath(new[]
                    {
                        new HiveId(FixedSchemaTypes.SystemRoot, null, new HiveIdValue(new Guid("802282F2-134E-4165-82B5-6DB2AFDDD135"))),
                        new HiveId(3), 
                        model.Id, 
                    })
                }));

                if(publish)
                {
                    // Generate the package file
                    var result = PackageBuilderHelper.CreatePackage(randomId, entity);
                    if(!result.Success)
                    {
                        ModelState.AddModelError("", "An error occured whilst trying to create the package file:\n"+ result.ErrorMessage);
                        return View("Edit", model);
                    }
                }

                Notifications.Add(new NotificationMessage(
                    "Package.Save.Message".Localize(this),
                    "Package.Save.Title".Localize(this),
                    NotificationType.Success));

                return RedirectToAction("Edit", new { id = model.Id });
            }
        }
Пример #31
0
 /// <summary>
 /// Used by inheritors to make any changes to the file before it is persisted
 /// </summary>
 /// <param name="file"></param>
 protected virtual void OnBeforeSave(File file)
 {
 }
Пример #32
0
        internal File PerformSave(MacroEditorModel model)
        {
            Mandate.ParameterNotNull(model, "model");

            using (var uow = Hive.Create())
            {
                var fileName = model.Alias.ToUmbracoAlias() + ".macro";
                var newFileId = new HiveId(fileName);
                var macroFile = new File
                {
                    Name = fileName,
                    ContentBytes = Encoding.UTF8.GetBytes(MacroSerializer.ToXml(model).ToString())
                };
                var existing = uow.Repositories.Get<File>(newFileId);
                //delete the file first before re-saving as AddOrUpdate seems to append to the file
                if (existing != null)
                    uow.Repositories.Delete<File>(newFileId);
                uow.Repositories.AddOrUpdate(macroFile);
                //TODO: the Hive IO provider commit seems to do nothing :( ... needs to be implemented!
                uow.Complete();

                return macroFile;
            }
        }
Пример #33
0
 /// <summary>
 /// Used by inheritors to make any changes to the model before creation
 /// </summary>
 /// <param name="model"></param>
 protected virtual void OnAfterCreate(File file)
 {
 }
        public JsonResult CreateSnapshot(SnapshotModel model)
        {
            var resultModel = new SnapshotResultModel();
            var snap = DateTime.Now.Ticks.ToString();
            resultModel.SnapshotCreated = true;
            resultModel.SnapshotLocation = "/App_Data/Data/" + snap;

            using (var uow = _hive.Create())
            {
                // Create folder
                var folder = new Umbraco.Framework.Persistence.Model.IO.File(snap, "") { IsContainer = true };
                uow.Repositories.AddOrUpdate(folder);
                uow.Complete();
            }

            var docTypeList = new Dictionary<string, string>();
            var contentList = new Dictionary<string, string>();
            var mediaList = new Dictionary<string, string>();

            if (!model.IncludeDocumentTypes)
            {
                //Access ContentStore and get all distinct document types
                using (var uow = _requestContext.Application.Hive.OpenReader<IContentStore>())
                {
                    var docTypes =
                        uow.Repositories.Schemas.GetDescendentRelations(FixedHiveIds.ContentRootSchema,
                                                                        FixedRelationTypes.DefaultRelationType)
                            .Where(x => !x.DestinationId.IsSystem())
                            .DistinctBy(x => x.DestinationId);

                    foreach (var docType in docTypes)
                    {
                        var schema = uow.Repositories.Schemas.Get<EntitySchema>(docType.DestinationId);
                        var result = _requestContext.Application.FrameworkContext.Serialization.ToStream(schema);
                        docTypeList.Add(docType.DestinationId.Value.ToString(), result.ResultStream.ToJsonString());
                    }
                }

                //Dump json strings as files to 'DocumentType' data folder
                if(docTypeList.Any())
                {
                    using (var uow = _hive.Create())
                    {
                        foreach (var pair in docTypeList)
                        {
                            var file = new Umbraco.Framework.Persistence.Model.IO.File(
                                snap + "/DocumentTypes/" + pair.Key,
                                Encoding.UTF8.GetBytes(pair.Value));
                            uow.Repositories.AddOrUpdate(file);
                        }

                        uow.Complete();
                    }
                }
            }

            if (!model.IncludeMedia)
            {
                //Access ContentStore and get all distinct media
                using (var uow = _requestContext.Application.Hive.OpenReader<IMediaStore>())
                {
                    var medias =
                        uow.Repositories.Schemas.GetDescendentRelations(FixedHiveIds.MediaVirtualRoot,
                                                                        FixedRelationTypes.DefaultRelationType)
                            .Where(x => !x.DestinationId.IsSystem())
                            .DistinctBy(x => x.DestinationId);

                    foreach (var media in medias)
                    {
                        var schema = uow.Repositories.Get(media.DestinationId);
                        var result = _requestContext.Application.FrameworkContext.Serialization.ToStream(schema);
                        mediaList.Add(media.DestinationId.Value.ToString(), result.ResultStream.ToJsonString());
                    }
                }

                //Dump json strings as files to 'Media' data folder
                if(mediaList.Any())
                {
                    using (var uow = _hive.Create())
                    {
                        foreach (var pair in docTypeList)
                        {
                            var file = new Umbraco.Framework.Persistence.Model.IO.File(
                                snap + "/Media/" + pair.Key,
                                Encoding.UTF8.GetBytes(pair.Value));
                            uow.Repositories.AddOrUpdate(file);
                        }

                        uow.Complete();
                    }
                }
            }

            if (!model.IncludeContent)
            {
                //Access ContentStore and get all distinct content - latest revision
                using (var uow = _requestContext.Application.Hive.OpenReader<IContentStore>())
                {
                    var contents =
                        uow.Repositories.Schemas.GetDescendentRelations(FixedHiveIds.ContentVirtualRoot,
                                                                        FixedRelationTypes.DefaultRelationType)
                            .Where(x => !x.DestinationId.IsSystem())
                            .DistinctBy(x => x.DestinationId);

                    foreach (var content in contents)
                    {
                        var schema = uow.Repositories.Get(content.DestinationId);
                        var result = _requestContext.Application.FrameworkContext.Serialization.ToStream(schema);
                        contentList.Add(content.DestinationId.Value.ToString(), result.ResultStream.ToJsonString());
                    }
                }

                //Dump json strings as files to 'Content' data folder
                if(contentList.Any())
                {
                    using (var uow = _hive.Create())
                    {
                        foreach (var pair in docTypeList)
                        {
                            var file = new Umbraco.Framework.Persistence.Model.IO.File(
                                snap + "/Content/" + pair.Key,
                                Encoding.UTF8.GetBytes(pair.Value));
                            uow.Repositories.AddOrUpdate(file);
                        }

                        uow.Complete();
                    }
                }
            }

            //Set Success
            resultModel.NotificationTitle = "Snapshot created";
            resultModel.NotificationMessage = "A snapshot with the selected types has been created";
            resultModel.NotificationType = NotificationType.Success.ToString().ToLower();

            //Invalid data in model (client slide validation should catch this, in as fail safe)
            /*resultModel.SnapshotCreated = false;

            resultModel.NotificationTitle = "An error occured";
            resultModel.NotificationMessage = "Some of the data was invalid";
            resultModel.NotificationType = NotificationType.Error.ToString().ToLower();*/

            //Return some JSON
            return Json(resultModel);
        }
Пример #35
0
        public override IDictionary <string, object> GetSerializedValue()
        {
            var val = new Dictionary <string, object>();

            //generate an id if we need one
            if (MediaId == Guid.Empty)
            {
                MediaId = Guid.NewGuid();
            }

            //add the media id to be saved
            val.Add("MediaId", MediaId.ToString("N"));

            // Check to see if we should delete the current file
            // either becuase remove file is checked, or we have a replacement file
            if (RemoveFile || HasFile())
            {
                if (!Value.IsNullValueOrEmpty())
                {
                    // delete entire property folder (deletes image and any thumbnails stored)
                    //var folderHiveId = HiveId.Parse("storage://file-uploader/string/" + MediaId.ToString("N"));
                    var folderHiveId = new HiveId("storage", "file-uploader", new HiveIdValue(MediaId.ToString("N")));

                    using (var uow = _hive.Create())
                    {
                        uow.Repositories.Delete <File>(Value); // Must delete file entity so that relations are deleted
                        uow.Repositories.Delete <File>(folderHiveId);
                        uow.Complete();
                    }
                }
            }

            // If we've received a File from the binding, we need to save it
            if (HasFile())
            {
                // Open a new unit of work to write the file
                using (var uow = _hive.Create())
                {
                    // Create main file
                    var file = new File
                    {
                        RootedPath = MediaId.ToString("N") + "/" + Path.GetFileName(NewFile.FileName).Replace(" ", "")
                    };

                    var stream = NewFile.InputStream;
                    if (stream.CanRead && stream.CanSeek)
                    {
                        stream.Seek(0, SeekOrigin.Begin);
                        using (var mem = new MemoryStream())
                        {
                            stream.CopyTo(mem);
                            file.ContentBytes = mem.ToArray();
                        }
                    }

                    uow.Repositories.AddOrUpdate(file);

                    // Create thumbnails (TODO: Need to encapsulate this so it can be reused in other places?)
                    if (file.IsImage())
                    {
                        var img = Image.FromFile(file.RootedPath);

                        // Create default thumbnail
                        CreateThumbnail(uow, file, img, MediaId.ToString("N"), 100);

                        // Create additional thumbnails
                        if (!string.IsNullOrEmpty(PreValueModel.Sizes))
                        {
                            var sizes = PreValueModel.Sizes.Split(',');
                            foreach (var size in sizes)
                            {
                                var intSize = 0;
                                if (Int32.TryParse(size, out intSize))
                                {
                                    CreateThumbnail(uow, file, img, MediaId.ToString("N"), intSize);
                                }
                            }
                        }
                    }

                    uow.Complete();

                    val.Add("Value", file.Id);
                }
            }
            else if (!Value.IsNullValueOrEmpty() && !RemoveFile)
            {
                val.Add("Value", Value);
            }
            else
            {
                val.Add("Value", HiveId.Empty);
            }

            return(val);
        }