Exemplo n.º 1
0
        public HttpResponseMessage Svg(int id, bool clean = false, string color = "") // /umbraco/api/carbidefile/svg/?id=1024&color=008BFF
        {
            string result = "";

            try
            {
                var umbracoHelper = new UmbracoHelper(Carbide.ContextHelpers.EnsureUmbracoContext());
                var svg           = umbracoHelper.TypedMedia(id);

                if (svg != null)
                {
                    result = StorageHelpers.ReadFile(svg.Url);

                    if (result.Length > 0)
                    {
                        if (result.Contains("<svg "))
                        {
                            if (clean)
                            {
                                result = MediaHelpers.CleanSvg(result, removeStyles: false, fixStyles: false, removeXmlHeader: false);
                            }

                            if (color != "" && color.Length < 10)
                            {
                                result = MediaHelpers.CleanSvg(result, removeStyles: true, fixStyles: false, removeXmlHeader: false);
                                result = Regex.Replace(result, "#[0-9a-fA-F]{6,8}", color.FixHexColor(), RegexOptions.Singleline);
                                result = result.Replace("<svg ", "<svg style=\"fill: " + color.FixHexColor() + ";\" ");
                            }
                        }
                    }
                }
            }

            catch
            {
            }

            var response = new HttpResponseMessage(HttpStatusCode.OK);

            response.Content = new StringContent(result, Encoding.UTF8, "image/svg+xml");
            return(response);
        }
Exemplo n.º 2
0
        /// <summary><![CDATA[
        /// Include a URL asset into a web page using relative paths. Optionally add dynamic cachebuster and minify JS and CSS files.
        /// ]]></summary>
        /// <param name="url">UrlHelper object</param>
        /// <param name="contentPath">Relative path to the asset</param>
        /// <param name="addCacheBuster">If true, appends a cachebuster to the generated URL from the file modification date</param>
        /// <param name="minify">If true minifies CSS and JS assets as new files and points the URL to them instead</param>
        /// <param name="fallback">If cachebuster fails, use this fallback value</param>
        /// <returns></returns>
        public static string Content(this UrlHelper url, string contentPath, bool addCacheBuster = false, bool minify = false, string fallback = "")
        {
            var queryString = contentPath.QueryString();
            var filePath    = contentPath.RemoveQueryString();

            try
            {
                if (minify && !filePath.StartsWith("_carbide.generated."))
                {
                    if (filePath.EndsWith(".js") || filePath.EndsWith(".css"))
                    {
                        bool proceed        = true;
                        var  newContentpath = "";

                        if (filePath.Contains("/"))
                        {
                            newContentpath = filePath.Substring(0, filePath.LastIndexOf("/") + 1) + "_carbide.generated." + filePath.Substring(filePath.LastIndexOf("/") + 1);
                        }

                        else
                        {
                            newContentpath = "_carbide.generated." + filePath;
                        }

                        FileInfo fileInfo     = new FileInfo(StorageHelpers.MapPath(filePath));
                        DateTime lastModified = fileInfo.LastWriteTime;
                        var      item         = fileInfo.Length + "|" + lastModified.DateFormat(Carbide.Constants.DateFormats.Utc);

                        if (HttpContext.Current.Application.KeyExists(StorageHelpers.ConvertFilePathToKey(filePath)))
                        {
                            if (HttpContext.Current.Application[StorageHelpers.ConvertFilePathToKey(filePath)].ToString() == item)
                            {
                                if (StorageHelpers.FileExists(newContentpath))
                                {
                                    filePath = newContentpath;
                                    proceed  = false;
                                }
                            }

                            else
                            {
                                if (StorageHelpers.FileExists(filePath) == false)
                                {
                                    filePath = newContentpath;
                                    proceed  = false;
                                }
                            }
                        }

                        else
                        {
                            if (StorageHelpers.FileExists(filePath) == false)
                            {
                                proceed = false;
                            }
                        }

                        if (proceed)
                        {
                            if (StorageHelpers.FileExists(newContentpath))
                            {
                                StorageHelpers.DeleteFiles(newContentpath);
                            }

                            var minified = "";

                            if (filePath.EndsWith(".js"))
                            {
                                var jsc = new JavaScriptCompressor();
                                minified = jsc.Compress(StorageHelpers.ReadFile(filePath));
                            }

                            if (filePath.EndsWith(".css"))
                            {
                                var cssc = new CssCompressor();
                                minified = cssc.Compress(StorageHelpers.ReadFile(filePath));
                            }

                            StorageHelpers.WriteFile(newContentpath, minified);

                            Debug.WriteLine("MINIFIED TO " + newContentpath);

                            fileInfo     = new FileInfo(StorageHelpers.MapPath(filePath));
                            lastModified = fileInfo.LastWriteTime;
                            item         = fileInfo.Length + "|" + lastModified.DateFormat(Carbide.Constants.DateFormats.Utc);

                            HttpContext.Current.Application[StorageHelpers.ConvertFilePathToKey(filePath)] = item;

                            filePath = newContentpath;
                        }

                        else
                        {
                            Debug.WriteLine("SKIPPED MINIFICATION FOR " + filePath);
                        }
                    }
                }

                if (addCacheBuster)
                {
                    queryString += (queryString.Contains("?") ? "&" : "?") + "_cachebuster=" + StorageHelpers.MakeCacheBuster(filePath, fallback);
                }
            }

            catch (Exception e)
            {
                Debug.WriteLine(e);
            }

            return(url.Content(filePath + queryString));
        }
Exemplo n.º 3
0
        /// <summary><![CDATA[
        /// Read a folder of filenames (SCSS partials) and inject them into a SCSS file as import statements.
        /// Add the following to your SCSS file so the method knows where to inject the import statements,
        /// including the leading "// ":
        /// // $CARBIDE_PARTIALS:BEGIN
        /// // $CARBIDE_PARTIALS:END
        /// ]]></summary>
        /// <param name="scssPath">Relative web path to the SCSS files (e.g. "/scss/").</param>
        /// <param name="scssFilename">File name for the SCSS file in which to inject the partials as import statements (e.g. "application.scss").</param>
        /// <param name="partialPath">Relative web path to the folder containing the SCSS partials to read (e.g. "/scss/custom/").</param>
        public static void InjectScssPartials(string scssPath, string scssFilename, string partialPath)
        {
            try
            {
                var _scssPath    = "/" + scssPath.ToLower().Trim('/') + "/";
                var _partialPath = "/" + partialPath.ToLower().Trim('/') + "/";
                _partialPath = _partialPath.Replace(_scssPath, "");
                var      scss   = StorageHelpers.ReadFile(_scssPath + scssFilename);
                string[] delims = { "// $CARBIDE_PARTIALS:BEGIN", "// $CARBIDE_PARTIALS:END" };

                if (scss.Length > (delims[0].Length + delims[1].Length))
                {
                    if (scss.Contains(delims[0]) && scss.Contains(delims[1]))
                    {
                        if (scss.IndexOf(delims[0]) < scss.IndexOf(delims[1]))
                        {
                            List <string> chunks  = new List <string>(scss.Split(delims, StringSplitOptions.RemoveEmptyEntries));
                            var           oldList = "";

                            if (chunks.Count == 3)
                            {
                                oldList = chunks[1];
                                chunks.RemoveAt(1);
                            }

                            if (chunks.Count == 2)
                            {
                                var       inject  = "";
                                ArrayList folders = GetWebFolders(_scssPath + _partialPath, includeRoot: true);

                                foreach (var folder in folders)
                                {
                                    var _files = StorageHelpers.GetFiles(folder.ToString(), "*.scss");
                                    _files.Sort();

                                    if (_files.Count > 0)
                                    {
                                        foreach (var file in _files)
                                        {
                                            inject += "@import \"" + folder.ToString().Replace(_scssPath, "") + file + "\";\r\n";
                                        }
                                    }
                                }

                                // Only write imports if there are changes...
                                if (oldList == "" || inject.ToLower().Trim().Replace("\r\n", "|").Replace("\r", "|").Replace("\n", "|") != oldList.ToLower().Trim().Replace("\r\n", "|").Replace("\r", "|").Replace("\n", "|"))
                                {
                                    var finalFile = chunks[0] + delims[0] + "\r\n" + inject + delims[1] + chunks[1];

                                    StorageHelpers.WriteFile(_scssPath + scssFilename, finalFile);

                                    Debug.WriteLine("SCSS import changes detected, writing to " + _scssPath + scssFilename);
                                }

                                else
                                {
                                    Debug.WriteLine("No SCSS import changes detected in " + _scssPath + scssFilename + ", skipping");
                                }
                            }
                        }
                    }
                }
            }

            catch (Exception e)
            {
                Debug.WriteLine("EXCEPTION: Carbide.StorageHelpers.InjectScssPartials() - " + e.Message);
            }
        }