protected override void EnsureViewData(FileEditorModel model, Framework.Persistence.Model.IO.File file)
        {
            base.EnsureViewData(model, file);

            // Setup UIElements
            model.UIElements.Add(new SeperatorUIElement());
            model.UIElements.Add(new ButtonUIElement
            {
                Alias = "InsertField",
                Title = "Insert an umbraco page field",
                CssClass = "insert-field-button toolbar-button",
                AdditionalData = new Dictionary<string, string>
                {
                    { "id", "submit_InsertField" },
                    { "name", "submit.InsertField" }
                }
            });
            model.UIElements.Add(new ButtonUIElement
            {
                Alias = "InsertMacro",
                Title = "Insert a macro",
                CssClass = "insert-macro-button toolbar-button",
                AdditionalData = new Dictionary<string, string>
                {
                    { "id", "submit_InsertMacro" },
                    { "name", "submit.InsertMacro" }
                }
            });
        }
        /// <summary>
        /// Need to custom create the model since theres no empty constructor for the FileEditorModel
        /// </summary>
        /// <param name="controllerContext"></param>
        /// <param name="bindingContext"></param>
        /// <param name="modelType"></param>
        /// <returns></returns>
        protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
        {
            //try to extract the id from the request as this will give us all of the information about the file
            var idName = string.IsNullOrEmpty(bindingContext.ModelName) ? "id" : bindingContext.ModelName;
            var valueProviderResult = bindingContext.ValueProvider.GetValue(idName);
            var rawId = valueProviderResult.AttemptedValue;

            var name = bindingContext.ValueProvider.GetValue("name").AttemptedValue;
            var content = bindingContext.ValueProvider.GetValue("fileContent").AttemptedValue;

            FileEditorModel model;
            if (string.IsNullOrEmpty(rawId))
            {
                model = FileEditorModel.CreateNew();
                model.Name = name;
                model.FileContent = content;
            }
            else
            {
                var id = HiveId.TryParse(rawId);
                if (id.Success)
                {
                    if (!id.Result.IsNullValueOrEmpty())
                    {
                        model = new FileEditorModel(id.Result, name, DateTimeOffset.UtcNow, DateTimeOffset.UtcNow,
                                                    () => content);
                    }
                    else
                    {
                        model = FileEditorModel.CreateNew();
                        model.Name = name;
                        model.FileContent = content;
                    }
                }
                else
                {
                    throw new ArgumentException("The id parameter in the route values could not parse into a HiveId");
                }
            }

            return model;
        }
 protected override void OnBeforeCreate(CreateFileModel createModel, FileEditorModel editorModel)
 {
     createModel.ParentId = editorModel.ParentId = FixedHiveIds.SystemRoot;
 }
        protected override void PopulateFileContentFromStub(FileEditorModel model, HiveId stubFileId, IDictionary<string, string> replacements)
        {
            var parentId = model.ParentId;

            model.ParentId = FixedHiveIds.SystemRoot;

            replacements = new Dictionary<string, string> { { "$layout$", "" }, { "$sections$", "" } };

            if (!stubFileId.IsNullValueOrEmpty())
            {
                if (!parentId.IsNullValueOrEmpty() && parentId != FixedHiveIds.SystemRoot)
                {
                    using (var uow = Hive.Create())
                    {
                        var parentFile = uow.Repositories.Get<File>(parentId);
                        if (parentFile == null)
                            throw new ArgumentException("No file could be found for the parent id specified");

                        replacements["$layout$"] = parentFile.Name;
                        replacements["$sections$"] = new TemplateParser().Parse(parentFile).Sections.Where(x => x != "Body")
                            .Aggregate("", (current, section) => current + ("\n@section " + section + "\n{\n\n}\n"));
                    }
                }
            }
            
            base.PopulateFileContentFromStub(model, stubFileId, replacements);
        }
        protected override void EnsureViewData(FileEditorModel model, File file)
        {
            // Setup UIElements
            model.UIElements.Add(new SeperatorUIElement());
            model.UIElements.Add(new ButtonUIElement
            {
                Alias = "InsertField",
                Title = "Insert an umbraco page field",
                CssClass = "insert-field-button toolbar-button",
                AdditionalData = new Dictionary<string, string>
                {
                    { "id", "submit_InsertField" },
                    { "name", "submit.InsertField" }
                }
            });
            model.UIElements.Add(new ButtonUIElement
            {
                Alias = "InsertPartial",
                Title = "Insert a partial view",
                CssClass = "insert-partial-button toolbar-button",
                AdditionalData = new Dictionary<string, string>
                {
                    { "id", "submit_InsertPartial" },
                    { "name", "submit.InsertPartial" }
                }
            });
            model.UIElements.Add(new ButtonUIElement
            {
                Alias = "InsertMacro",
                Title = "Insert a macro",
                CssClass = "insert-macro-button toolbar-button",
                AdditionalData = new Dictionary<string, string>
                {
                    { "id", "submit_InsertMacro" },
                    { "name", "submit.InsertMacro" }
                }
            });
            model.UIElements.Add(new SeperatorUIElement());
            model.UIElements.Add(new ButtonUIElement
            {
                Alias = "DefineSection",
                Title = "Define a Section",
                CssClass = "define-section-button toolbar-button",
                AdditionalData = new Dictionary<string, string>
                {
                    { "id", "submit_DefineSection" },
                    { "name", "submit.DefineSection" }
                }
            });
            model.UIElements.Add(new ButtonUIElement
            {
                Alias = "ImplementSection",
                Title = "Implement a Section",
                CssClass = "implement-section-button toolbar-button",
                AdditionalData = new Dictionary<string, string>
                {
                    { "id", "submit_ImplementSection" },
                    { "name", "submit.ImplementSection" }
                }
            });
            model.UIElements.Add(new SeperatorUIElement());
            model.UIElements.Add(new SelectListUIElement
            {
                Alias = "Layout",
                Title = "Layout",
                CssClass = "layout-select-list",
                AdditionalData = new Dictionary<string, string>
                {
                    { "id", "select_Layout" },
                    { "name", "select.Layout" }
                }
            });

            // Setup data
            var parser = new TemplateParser();
            ViewBag.CurrentLayout = file != null ? parser.Parse(file).Layout : "";
            using (var uow = BackOfficeRequestContext.Application.Hive.OpenReader<IFileStore>(new Uri("storage://templates")))
            {
                //create the allowed templates check box list
                ViewBag.AvailableTemplates = new List<SelectListItem>(
                    uow.Repositories.GetAllNonContainerFiles()
                    .OrderBy(x => x.Name)
                    .Select(x =>
                        new SelectListItem
                        {
                            Text = x.GetFileNameForDisplay(),
                            Value = x.Name
                        })).ToArray();
            }
        }
        protected virtual void PopulateFileContentFromStub(FileEditorModel model, HiveId stubFileId, IDictionary<string, string> replacements)
        {
            var stubHive = BackOfficeRequestContext.Application.Hive.GetReader<IFileStore>(stubFileId.ToUri());
            using (var uow = stubHive.CreateReadonly())
            {
                var stubFile = uow.Repositories.Get<File>(stubFileId);
                if(stubFile != null)
                {
                    var fileContent = Encoding.UTF8.GetString(stubFile.ContentBytes);

                    foreach (var replacement in replacements)
                        fileContent = fileContent.Replace(replacement.Key, replacement.Value);

                    model.FileContent = fileContent;
                }
            }
        }
 protected virtual void PopulateFileContentFromStub(FileEditorModel model, HiveId stubFileId)
 {
     PopulateFileContentFromStub(model, stubFileId, new Dictionary<string, string>());
 }
 protected virtual void EnsureViewData(FileEditorModel model, File file)
 {
     // To be overridden
 }
        /// <summary>
        /// Does the save.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <returns></returns>
        internal File PerformSave(FileEditorModel model)
        {
            using (var uow = Hive.Create())
            {
                var repo = uow.Repositories;

                File file;
                if (model.Id.IsNullValueOrEmpty())
                {
                    //its new

                    file = BackOfficeRequestContext.Application.FrameworkContext.TypeMappers.Map<File>(model);

                    //we are creating a new file, need to validate the parent id and make sure we are saving it under the parent)
                    if (model.ParentId != FixedHiveIds.SystemRoot)
                    {
                        if (model.ParentId.IsNullValueOrEmpty())
                            throw new ArgumentNullException("Creating a new file requires the ParentId property to be set");
                        var parent = uow.Repositories.Get<File>(model.ParentId);
                        if (parent == null)
                            throw new ArgumentException("No folder could be found for the parent id specified");

                        //ensure that we save the file under the current parent
                        file.RootedPath = Path.Combine(parent.RootedPath, model.Name);
                    }
                }
                else
                {
                    //it exists

                    file = repo.Get<File>(model.Id);
                    if (file == null)
                        throw new ArgumentException("No file could be found for the id specified");

                    BackOfficeRequestContext.Application.FrameworkContext.TypeMappers.Map(model, file);
                }

                OnBeforeSave(file);

                repo.AddOrUpdate(file);
                uow.Complete();

                return file;
            }
        }
 /// <summary>
 /// Used by inheritors to make any changes to the model before creation
 /// </summary>
 /// <param name="model"></param>
 protected virtual void OnBeforeCreate(CreateFileModel createModel, FileEditorModel editorModel)
 {
     
 }
        /// <summary>
        /// Used by inheritors to make any changes to the model before creation
        /// </summary>
        /// <param name="model"></param>
        protected virtual void OnBeforeUpdate(FileEditorModel editorModel)
        {

        }
        public virtual JsonResult Save(FileEditorModel model)
        {
            Mandate.ParameterNotNull(model, "model");

            if (!TryValidateModel(model))
            {
                return ModelState.ToJsonErrors();
            }

            OnBeforeUpdate(model);

            var file = PerformSave(model);

            using (var uow = Hive.Create())
            {
                Notifications.Add(new NotificationMessage(SaveSuccessfulMessage, SaveSuccessfulTitle, NotificationType.Success));
                var path = CreatePaths(file).ToJson();
                return new CustomJsonResult(new
                {
                    id = file.Id.ToString(),
                    //need to send the path back so we can sync the tree
                    path,
                    notifications = Notifications,
                    success = true
                }.ToJsonString);
            }
        }