Example #1
0
        ///<summary>
        ///Compiles less file into multiple css files if total number of css selectors is > 4095.
        ///<para>Creates "ie9" folder at the same level as less file and puts css files in there.
        ///The output "style.css" will import other css files.</para>
        ///<param name="absolutePath">Absolute path to less file.</param>
        /// </summary>
        public static string CompileLess(string absolutePath)
        {
            Trace.WriteLine("Compilation process started...");
            var files_list    = new List <string>();
            var dotlessConfig = new dotless.Core.configuration.DotlessConfiguration();

            //dotlessConfig.Web = true;
            dotlessConfig.RootPath = "../";
            var fileLocation = absolutePath;
            var relDir       = absolutePath.Substring(0, absolutePath.LastIndexOf("\\"));
            var currentDir   = relDir;
            var count        = 0;

            if (File.Exists(fileLocation))
            {
                using (var file = new System.IO.StreamReader(fileLocation))
                {
                    Directory.SetCurrentDirectory(currentDir);
                    string parsed = Less.Parse(file.ReadToEnd(), dotlessConfig);
                    parsed = RemoveComments(parsed);
                    var rules = Regex.Matches(parsed, RULES_REGEX);
                    foreach (var rule in rules)
                    {
                        var value = rule.ToString();
                        count += value.Split(',').Count();
                    }
                    //replace with "count > RULES_LIMIT" later
                    if (count > RULES_LIMIT)
                    {
                        var tmp = "";

                        var file_and_contents_dic = new Dictionary <string, string>();

                        var styleSheet = new Stylesheet();
                        var medias     = GetMedias(parsed, out tmp);

                        var reminder_rules = GetRules(tmp, RULES_REGEX);

                        styleSheet.Medias = medias;
                        styleSheet.Rules  = reminder_rules;

                        var rules_files = MakeFilesFromRules(reminder_rules);
                        var media_files = MakeFilesFromMedia(medias);
                        rules_files.AddRange(media_files);
                        var files = BuildFileNames(rules_files);
                        files_list = files.Keys.ToList();
                        AssembleFiles(files, currentDir, relDir);
                    }
                    file.Close();
                }

                Trace.WriteLine("Compilation process ended. File is closed.");
            }
            return(string.Format("{0}/ie9/style.css", relDir));
        }
Example #2
0
        public bool ProcessEpub()
        {
            ePubDisplayModel = new EpubDisplayModel();

            // Opens a book and reads all of its content into memory
            var epubBookRef = EpubReader.OpenBook(_ePubFilePath); // not using ReadBook as that loads the whole epub book in memory

            if (epubBookRef != null)
            {
                // get file date
                var fileDateStamp = new FileInfo(_ePubFilePath).LastWriteTime;

                var bookContent = epubBookRef.Content;

                var requestIsForXhtml = false; // a whole epub xhtml file has been requested - this happens when a link in the html is selected as it could be a link anywhere in the whole book

                // *************************************************************************
                // check if this request is for a chapter or a file asset i.e. image or font
                // *************************************************************************

                var extension = Path.GetExtension(_processAction);

                if (!string.IsNullOrEmpty(extension))                                                           // this might be a request for a file ie. font or image
                {
                    if (SafeFileTypes.Contains(extension))                                                      // this filetype is in the SafeFileTypes list
                    {
                        Dictionary <string, EpubContentFileRef> allFiles = bookContent.AllFiles;                // would use bookContent.css/fonts/images but fonts have missing mime-types in the EpubReader package, and so are noth being selected as fonts
                        foreach (var item in allFiles)                                                          // loop all the files in the epub archive
                        {
                            if (item.Key.EndsWith(_processAction, StringComparison.InvariantCultureIgnoreCase)) // this filename matches the requested action (_processAction)
                            {
                                switch (item.Value)                                                             // switch based on the class of the EpubContentFileRef type
                                {
                                case EpubByteContentFileRef itemValue:

                                    FileToServe = new FileToServe(itemValue.ReadContentAsBytes(), itemValue.ContentMimeType, itemValue.FileName, fileDateStamp);

                                    return(false);    // return ProcessEPub()

                                case EpubContentFileRef textItem:

                                    if (textItem.ContentType == EpubContentType.XHTML_1_1)
                                    {
                                        requestIsForXhtml = true;        // we want to process this file as it is not a 'File' to serve, it is an HTML document to process
                                    }
                                    else                                 // stop any other text file from being processed or served
                                    {
                                        FileToServe = new FileToServe(); // this will stop this file being served
                                        return(false);                   // return ProcessEPub()
                                    }
                                    break;

                                default:
                                    FileToServe = new FileToServe(); // this will stop this file being served
                                    return(false);                   // return ProcessEPub()
                                }
                            }
                        }
                    }
                    else // disallow filetype
                    {
                        FileToServe = new FileToServe(); // this will stop this file being served
                        return(false);  // return ProcessEPub()
                    }
                }

                // check if this chapter has been cached in Application memory. If so then return that without continuing.
                if (_isToCache)
                {
                    _cacheHash = GetMd5Hash(_ePubFilePath + _processAction); // create unique hash of this chapter in this book
                    var cachedItem = HttpContext.Current.Cache.Get(_cacheHash);
                    if (cachedItem != null)                                  // cached chapter found
                    {
                        ePubDisplayModel = (EpubDisplayModel)cachedItem;
                        return(true);
                    }
                }

                // Book's title
                ePubDisplayModel.Title = epubBookRef.Title;

                // Book's authors (comma separated list)
                ePubDisplayModel.Authors = epubBookRef.Author;

                // try and find the requested chapter or xhtml file
                if (requestIsForXhtml)
                {
                    FindAndProcessXHTML(ref ePubDisplayModel, epubBookRef); // updates ePubDisplayModel by reference with content
                }
                else
                {
                    FindAndProcessChapter(ref ePubDisplayModel, epubBookRef); // updates ePubDisplayModel by reference with content
                }

                if (!string.IsNullOrEmpty(ePubDisplayModel.RedirectToChapter)) // we need to redirect to a chapter so exit this method
                {
                    return(false);
                }

                // All fonts in the book (file name is the key)
                //Dictionary<string, EpubByteContentFileRef> fonts = bookContent.Fonts; // Note: VersOne.Epub is missing some font mime-types so be aware that all/some the fonts will not be in this object. They will, however, be in the .AllFiles() object

                // All CSS files in the book (file name is the key)
                Dictionary <string, EpubTextContentFileRef> cssFiles = bookContent.Css;
                string cssContent = string.Empty;

                foreach (var cssFile in cssFiles.Values)
                {
                    cssContent += cssFile.ReadContentAsText();
                }

                // using dotless (css preprocessor) we will add '.epub' to all the book styles in order to keep the book styles restricted to the book and not affect the rest of the browser page.
                string finalCss = string.Format(".epub {{{0}}}", cssContent); // add '.epub' class to all css elements, so we can contain all the book styles to just to book div (which should have a .epub class added to it)

                var dotlessConfig = new dotless.Core.configuration.DotlessConfiguration
                {
                    MinifyOutput = true
                };

                var resultCss = Less.Parse(finalCss, dotlessConfig);

                // FOR REFERENCE IF NEEDED - <base href="'. $this->base_link. '/" target="_self"> // need to include <base> as some cms's adds a trailing '/' to all requests which brakes the relative links in the epub html
                ePubDisplayModel.ChapterHtml = string.Format("<html><head><style>{0}</style></head><body><div class='epub'>{1}</div></body></html>", resultCss, ePubDisplayModel.ChapterHtml);

                if (_isToCache) // if using application cache
                {
                    try
                    {
                        HttpContext.Current.Cache.Insert(_cacheHash, ePubDisplayModel, null, DateTime.Now.AddDays(1), System.Web.Caching.Cache.NoSlidingExpiration);
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }

            return(true);
        }
Example #3
0
 public CachedCssResponse(IHttp http, IClock clock, dotless.Core.configuration.DotlessConfiguration config)
     : this(http, config.HandleWebCompression, config.HttpExpiryInMinutes, clock)
 {
 }
Example #4
0
        public void ProcessRequest(HttpContext context)
        {
            var host = Host.Get(Host.DefaultId);

            var lastModifiedDateUtc = Configuration.LastModifiedDateUtc;

            if (lastModifiedDateUtc > DateTime.UtcNow)
            {
                lastModifiedDateUtc = DateTime.UtcNow;
            }

            context.Response.ContentType = "text/css";
            var cacheKey = CacheKey + host.AbsoluteUrl("~/");

            var cachedStyleSheet = host.Cache.Get(cacheKey) as CachedStyleSheet;

            if (cachedStyleSheet == null || cachedStyleSheet.LastModifiedDateUtc < lastModifiedDateUtc)
            {
                cachedStyleSheet = new CachedStyleSheet();
                cachedStyleSheet.LastModifiedDateUtc = lastModifiedDateUtc;
                cachedStyleSheet.StyleSheet          = string.Empty;

                var styleSheets = Configuration.StyleSheets;
                if (styleSheets != null)
                {
                    var less = string.Join("\n", styleSheets);

                    var config = new dotless.Core.configuration.DotlessConfiguration();
                    config.CacheEnabled             = false;
                    config.Debug                    = false;
                    config.DisableParameters        = false;
                    config.DisableUrlRewriting      = true;
                    config.DisableVariableRedefines = false;
                    config.HandleWebCompression     = false;
                    config.ImportAllFilesAsLess     = false;
                    config.InlineCssFiles           = false;
                    config.KeepFirstSpecialComment  = false;
                    config.MapPathsToWeb            = false;
                    config.MinifyOutput             = false;
                    config.Web         = false;
                    config.LessSource  = typeof(LessFileReader);
                    config.LogLevel    = dotless.Core.Loggers.LogLevel.Warn;
                    config.Logger      = typeof(DotLessLogger);
                    config.SessionMode = dotless.Core.configuration.DotlessSessionStateMode.Disabled;

                    try
                    {
                        var engine = new dotless.Core.EngineFactory(config).GetEngine();

                        cachedStyleSheet.StyleSheet = engine.TransformToCss(UpdateEmbeddedFileReferences(context, less), null) + ((DotLessLogger)((dotless.Core.LessEngine)((dotless.Core.ParameterDecorator)engine).Underlying).Logger).GetMessages();
                    }
                    catch (Exception ex)
                    {
                        host.LogError("An error occurred while processing LESS directives in stylesheets.", ex);
                        context.Response.StatusCode = 500;
                        return;
                    }
                }

                host.Cache.Put(cacheKey, cachedStyleSheet, 30 * 60);
            }

            context.Response.Cache.SetAllowResponseInBrowserHistory(true);
            context.Response.Cache.SetLastModified(lastModifiedDateUtc);
            context.Response.Cache.SetETag(lastModifiedDateUtc.Ticks.ToString());
            context.Response.Cache.SetCacheability(HttpCacheability.Public);
            context.Response.Cache.SetExpires(DateTime.UtcNow.AddHours(2));
            context.Response.Cache.SetValidUntilExpires(false);
            context.Response.Write(cachedStyleSheet.StyleSheet);
        }
Example #5
0
 public CssResponse(IHttp http, dotless.Core.configuration.DotlessConfiguration config)
     : this(http, config.HandleWebCompression)
 {
 }
Example #6
0
 public LessEngine(Parser.Parser parser, ILogger logger, dotless.Core.configuration.DotlessConfiguration config)
     : this(parser, logger, config.MinifyOutput, config.Debug, config.DisableVariableRedefines, config.DisableColorCompression, config.KeepFirstSpecialComment, config.Plugins)
 {
 }
Example #7
0
 public AspResponseLogger(dotless.Core.configuration.DotlessConfiguration config, IResponse response)
     : this(config.LogLevel, response)
 {
 }
Example #8
0
 public Parser(dotless.Core.configuration.DotlessConfiguration config, IStylizer stylizer, IImporter importer)
     : this(config.Optimization, stylizer, importer, config.Debug)
 {
 }