Ejemplo n.º 1
0
 public static void ReplaceRule(File input, string oldRuleName, StylesheetRule rule)
 {
     var contents = Encoding.UTF8.GetString(input.ContentBytes);
     var ruleRegex = new Regex(string.Format(_ruleRegexFormat, oldRuleName), RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline);
     contents = ruleRegex.Replace(contents, rule != null ? rule.ToString() : "");
     input.ContentBytes = Encoding.UTF8.GetBytes(contents);
 }
Ejemplo n.º 2
0
        public void TemplateParserTests_Pares_Success()
        {
            // Arrange
            var file = new File
            {
                ContentBytes = Encoding.UTF8.GetBytes(@"
                @{
                    Layout = ""_Layout.cshtml"";
                }
                <html>
                    <head>
                        @RenderSection(""Head"")
                    </head>
                    <body>
                        @RenderSection(""Test"", true)
                        @RenderBody()
                    </body>
                </html>
                ")
            };

            // Act
            var result = new TemplateParser().Parse(file);

            // Assert
            Assert.IsTrue(result.Layout == "_Layout.cshtml");
            Assert.IsTrue(result.Sections.Count() == 3);
            Assert.IsTrue(result.Sections.Contains("Head"));
            Assert.IsTrue(result.Sections.Contains("Test"));
            Assert.IsTrue(result.Sections.Contains("Body"));
        }
Ejemplo n.º 3
0
        public static string ResolveLayoutPath(string path, File file)
        {
            if (path.StartsWith("~") || path.StartsWith("/"))
                path = HttpContext.Current.Server.MapPath(path);
            else if (file != null)
                path = file.RootedPath.Substring(0, file.RootedPath.LastIndexOf("\\")) + "\\" + path;
            else
                path = HttpContext.Current.Server.MapPath(UmbracoSettings.GetSettings().UmbracoFolders.TemplateFolder) + "\\" + path;

            return path;
        }
        //public override ActionResult Create(string fileName, HiveId parentId, HiveId stubFileId = default(HiveId))
        //{
        //    var model = CreateNewEditorModel(fileName, parentId, stubFileId);

        //    return View("Edit", model);
        //}

        protected override EntityPathCollection CreatePaths(File file)
        {
            //return base.CreatePath(file);

            if (file.IsContainer)
                return base.CreatePaths(file);

            var parser = new TemplateParser();
            var result = parser.Parse(file);

            if (string.IsNullOrWhiteSpace(result.Layout))
                return base.CreatePaths(file);

            var path = new List<HiveId>
            {
                file.Id
            };

            using (var uow = Hive.Create())
            {
                // Get parent paths from layout
                //TODO: Need to fetch from the current folder if we want to support folders
                var files = uow.Repositories.GetAll<File>().Where(x => !x.IsContainer && x.Id != file.Id);

                var currentLayout = TemplateHelper.ResolveLayoutPath(result.Layout, file);
                while(!string.IsNullOrWhiteSpace(currentLayout))
                {
                    var parent = files.SingleOrDefault(x => TemplateHelper.ResolveLayoutPath(x.RootRelativePath, x) == currentLayout);
                    if(parent != null)
                    {
                        path.Add(parent.Id);
                        currentLayout = parser.Parse(parent).Layout;
                    }
                    else
                    {
                        currentLayout = "";
                    }
                }

                path.Reverse();

                // Insert the actual parents path at the begining
                var actualParent = uow.Repositories.GetLazyParentRelations(file.Id, FixedRelationTypes.DefaultRelationType)
                    .Select(x => x.Source as File)
                    .SingleOrDefault();

                if (actualParent != null)
                    path.InsertRange(0, base.CreatePaths(actualParent)[0]); // Assumes a template will only ever be available at one location
            }

            return new EntityPathCollection(file.Id, new[]{ new EntityPath(path) });
        }
Ejemplo n.º 5
0
        public void StylesheetHelperTests_ParseRules_DoesntParse(string css)
        {
            // Arrange
            var file = new File(new HiveId("styles.css"))
            {
                ContentBytes = Encoding.UTF8.GetBytes(css)
            };

            // Act
            var results = StylesheetHelper.ParseRules(file);

            // Assert
            Assert.IsTrue(results.Count() == 0);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Stores the file.
        /// </summary>
        /// <param name="file">The file.</param>
        /// <returns></returns>
        private HiveId StoreFile(HttpPostedFileBase file)
        {
            //saving file
            var hive = BackOfficeRequestContext.Application.Hive.GetWriter <IFileStore>(new Uri("storage://file-uploader"));

            //create new media item
            //currently code is in here but should be shared with upload prop editor

            var mediaId = Guid.NewGuid();

            // Open a new unit of work to write the file
            using (var uow = hive.Create())
            {
                // Create main file
                var f = new File
                {
                    RootedPath = mediaId.ToString("N") + "/" + file.FileName.Replace(" ", "")
                };
                //.ToString("N")
                var stream = file.InputStream;
                if (stream.CanRead && stream.CanSeek)
                {
                    stream.Seek(0, SeekOrigin.Begin);
                    using (var mem = new MemoryStream())
                    {
                        stream.CopyTo(mem);
                        f.ContentBytes = mem.ToArray();
                    }
                }

                uow.Repositories.AddOrUpdate(f);

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

                    // Create default thumbnail
                    CreateThumbnail(uow, f, img, mediaId.ToString("N"), 100);
                    //// Create additional thumbnails
                }

                uow.Complete();

                return(f.Id);
            }
        }
Ejemplo n.º 7
0
        public void StylesheetHelperTests_ParseRules_Parses(string name, string selector, string styles, string css)
        {
            // Arrange
            var file = new File(new HiveId("styles.css"))
            {
                ContentBytes = Encoding.UTF8.GetBytes(css)
            };

            // Act
            var results = StylesheetHelper.ParseRules(file);

            // Assert
            Assert.IsTrue(results.Count() == 1);

            Assert.IsTrue(results.First().RuleId.Value.Value.ToString() == file.Id.Value.Value +"/"+ name);
            Assert.IsTrue(results.First().Name == name);
            Assert.IsTrue(results.First().Selector == selector);
            Assert.IsTrue(results.First().Styles == styles);
        }
Ejemplo n.º 8
0
        public static IEnumerable<StylesheetRule> ParseRules(File input)
        {
            var rules = new List<StylesheetRule>();
            var ruleRegex = new Regex(string.Format(_ruleRegexFormat, @"[^\*\r\n]*"), RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline);
            
            var contents = Encoding.UTF8.GetString(input.ContentBytes);
            var ruleMatches = ruleRegex.Matches(contents);

            foreach (Match match in ruleMatches)
            {
                rules.Add(new StylesheetRule
                {
                    RuleId = new HiveId(new Uri("storage://stylesheets"), string.Empty, new HiveIdValue(input.Id.Value + "/" + match.Groups["Name"].Value)),
                    StylesheetId = input.Id,
                    Name = match.Groups["Name"].Value,
                    Selector = match.Groups["Selector"].Value,
                    // Only match first selector when chained together
                    Styles = string.Join(Environment.NewLine, match.Groups["Styles"].Value.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None).Select(x => x.Trim()).ToArray())
                });
            }

            return rules;
        }
        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();
            }
        }
Ejemplo n.º 10
0
 /// <summary>
 /// Parses the specified template for a Layout and any RenderSections.
 /// </summary>
 /// <param name="templateFile">The template file.</param>
 /// <returns></returns>
 public TemplateParserResult Parse(File templateFile)
 {
     //TODO: Would probably be better to use the Razor engine to parse but was unable to get it working, so resorted to Regex for now
     var fileContents = Encoding.UTF8.GetString(templateFile.ContentBytes);
     return Parse(fileContents);
 }
Ejemplo n.º 11
0
        /// <summary>
        /// Creates the thumbnail.
        /// </summary>
        /// <param name="uow">The uow.</param>
        /// <param name="original">The original.</param>
        /// <param name="image">The image.</param>
        /// <param name="mediaId">The media id.</param>
        /// <param name="maxWidthHeight">Height of the max width.</param>
        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()));
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Stores the file.
        /// </summary>
        /// <param name="file">The file.</param>
        /// <returns></returns>
        private HiveId StoreFile(HttpPostedFileBase file)
        {
             //saving file
            var hive = BackOfficeRequestContext.Application.Hive.GetWriter<IFileStore>(new Uri("storage://file-uploader"));

            //create new media item
            //currently code is in here but should be shared with upload prop editor

            var mediaId = Guid.NewGuid();   

            // Open a new unit of work to write the file
            using (var uow = hive.Create())
            {
                // Create main file
                var f = new File
                {
                    RootedPath = mediaId.ToString("N") + "/" + file.FileName.Replace(" ", "")
                };
                //.ToString("N")
                var stream = file.InputStream;
                if (stream.CanRead && stream.CanSeek)
                {
                    stream.Seek(0, SeekOrigin.Begin);
                    using (var mem = new MemoryStream())
                    {
                        stream.CopyTo(mem);
                        f.ContentBytes = mem.ToArray();
                    }
                }

                uow.Repositories.AddOrUpdate(f);

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

                    // Create default thumbnail
                    CreateThumbnail(uow, f, img, mediaId.ToString("N"), 100);
                    //// Create additional thumbnails

                }

                uow.Complete();

                return f.Id;
            }
        }
Ejemplo n.º 13
0
 public static void AppendRule(File input, StylesheetRule rule)
 {
     var contents = Encoding.UTF8.GetString(input.ContentBytes);
     contents += Environment.NewLine + Environment.NewLine + rule.ToString();
     input.ContentBytes = Encoding.UTF8.GetBytes(contents);
 }
Ejemplo n.º 14
0
        /// <summary>
        /// Creates the thumbnail.
        /// </summary>
        /// <param name="uow">The uow.</param>
        /// <param name="original">The original.</param>
        /// <param name="image">The image.</param>
        /// <param name="mediaId">The media id.</param>
        /// <param name="maxWidthHeight">Height of the max width.</param>
        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()));
        }
Ejemplo n.º 15
0
 public static MacroEditorModel FromFile(File file)
 {
     var model = FromXml(Encoding.UTF8.GetString(file.ContentBytes));
     model.Id = file.Id;
     return model;
 }