Ejemplo n.º 1
0
        public void Process(BundleContext context, BundleResponse response)
        {
            if (response == null)
            {
                throw new ArgumentNullException("response");
            }

            context.HttpContext.Response.Cache.SetLastModifiedFromFileDependencies();

            var         lessParser = new Parser();
            ILessEngine lessEngine = CreateLessEngine(lessParser);

            foreach (FileInfo fileInfo in response.Files)
            {
                SetCurrentFilePath(lessParser, fileInfo.FullName);

                var source = File.ReadAllText(fileInfo.FullName);

                var result = lessEngine.TransformToCss(source, fileInfo.FullName);

                // NOTE: HttpContext.Items is used instead of BundleResponse.Content
                // to pass processed files
                context.HttpContext.Items.Add(fileInfo.FullName, result);

                AddFileDependencies(lessParser);
            }
        }
Ejemplo n.º 2
0
        /// <inheritdoc />
        public IEnumerable <IDocument> Execute(IReadOnlyList <IDocument> inputs, IExecutionContext context)
        {
            DotlessConfiguration config = DotlessConfiguration.GetDefault();

            config.Logger = typeof(LessLogger);
            EngineFactory    engineFactory    = new EngineFactory(config);
            FileSystemReader fileSystemReader = new FileSystemReader(context.FileSystem);

            return(inputs.AsParallel().Select(context, input =>
            {
                Trace.Verbose("Processing Less for {0}", input.SourceString());
                ILessEngine engine = engineFactory.GetEngine();

                // TODO: Get rid of RefelectionMagic and this ugly hack as soon as dotless gets better external DI support
                engine.AsDynamic().Underlying.Cache = new LessCache(context.ExecutionCache);
                engine.AsDynamic().Underlying.Underlying.Parser.Importer.FileReader = fileSystemReader;

                FilePath path = input.FilePath(Keys.RelativeFilePath);
                string fileName = null;
                if (path != null)
                {
                    engine.CurrentDirectory = path.Directory.FullPath;
                    fileName = path.FileName.FullPath;
                }
                else
                {
                    engine.CurrentDirectory = string.Empty;
                    fileName = Path.GetRandomFileName();
                }
                string content = engine.TransformToCss(input.Content, fileName);
                return context.GetDocument(input, content);
            }));
        }
Ejemplo n.º 3
0
        private static IEnumerable<string> Compile(ILessEngine engine, string inputFilePath, string outputFilePath)
        {
            Console.Write("Compiling {0} -> {1} ", inputFilePath, outputFilePath);
            try
            {
                var source = new FileReader().GetFileContents(inputFilePath);
                var css = engine.TransformToCss(source, inputFilePath);

                File.WriteAllText(outputFilePath, css);
                Console.WriteLine("[Done]");

                return new[] { inputFilePath }.Concat(engine.GetImports());
            }
            catch(IOException)
            {
                throw;
            }
            catch (Exception ex)
            {
                Console.WriteLine("[FAILED]");
                Console.WriteLine("Compilation failed: {0}", ex.Message);
                Console.WriteLine(ex.StackTrace);
                return null;
            }
        }
Ejemplo n.º 4
0
 public HandlerImpl(IRequest request, IResponse response, ILessEngine engine, ILessSource lessSource)
 {
     this.request = request;
     this.response = response;
     this.engine = engine;
     this.lessSource = lessSource;
 }
Ejemplo n.º 5
0
        public IEnumerable <IDocument> Execute(IReadOnlyList <IDocument> inputs, IExecutionContext context)
        {
            DotlessConfiguration config = DotlessConfiguration.GetDefault();

            config.Logger = typeof(LessLogger);
            EngineFactory engineFactory = new EngineFactory(config);

            return(inputs.AsParallel().Select(x =>
            {
                context.Trace.Verbose("Processing Less for {0}", x.Source);
                ILessEngine engine = engineFactory.GetEngine();

                // TODO: Get rid of RefelectionMagic and this ugly hack as soon as dotless gets better external DI support
                engine.AsDynamic().Underlying.Cache = new LessCache(context.ExecutionCache);

                string path = x.Get <string>(Keys.SourceFilePath, null);
                string fileName = null;
                if (path != null)
                {
                    engine.CurrentDirectory = Path.GetDirectoryName(path);
                    fileName = Path.GetFileName(path);
                }
                else
                {
                    engine.CurrentDirectory = context.InputFolder;
                    fileName = Path.GetRandomFileName();
                }
                string content = engine.TransformToCss(x.Content, fileName);
                return x.Clone(content);
            }));
        }
Ejemplo n.º 6
0
        public void Process(BundleContext context, BundleResponse bundle)
        {
            if (bundle == null)
            {
                throw new ArgumentNullException("bundle");
            }

            context.HttpContext.Response.Cache.SetLastModifiedFromFileDependencies();

            var         lessParser = new Parser();
            ILessEngine lessEngine = CreateLessEngine(lessParser);

            var content = new StringBuilder(bundle.Content.Length);

            foreach (FileInfo file in bundle.Files)
            {
                SetCurrentFilePath(lessParser, file.FullName);
                string source = File.ReadAllText(file.FullName);
                content.Append(lessEngine.TransformToCss(source, file.FullName));
                content.AppendLine();

                AddFileDependencies(lessParser);
            }

            bundle.ContentType = "text/css";
            bundle.Content     = content.ToString();
        }
        /// <summary>
        ///     Un-decorates <see cref="LessEngine" /> from <paramref name="engine" />. Can process only
        ///     <see cref="CacheDecorator" /> and <see cref="ParameterDecorator" />, otherwise raises exception.
        /// </summary>
        /// <param name="engine">Possibly decorated <see cref="ILessEngine" /></param>
        /// <exception cref="ArgumentException">Unexpected type of <paramref name="engine" /></exception>
        /// <returns><see cref="LessEngine" /> instance.</returns>
        internal static LessEngine ResolveLessEngine(this ILessEngine engine)
        {
            if (engine == null)
            {
                throw new ArgumentNullException("engine");
            }

            while (true)
            {
                var lessEngine = engine as LessEngine;
                if (lessEngine != null)
                {
                    return(lessEngine);
                }

                var cacheDecorator = engine as CacheDecorator;
                if (cacheDecorator != null)
                {
                    engine = cacheDecorator.Underlying;
                }
                else
                {
                    var parameterDecorator = engine as ParameterDecorator;
                    if (parameterDecorator == null)
                    {
                        throw new ArgumentException(string.Format("Cannot resolve {0} to LessEngine", engine.GetType()));
                    }
                    engine = parameterDecorator.Underlying;
                }
            }
        }
Ejemplo n.º 8
0
 public LessHandlerImpl(IHttp http, IResponse response, ILessEngine engine, IFileReader fileReader)
 {
     Http = http;
     Response = response;
     Engine = engine;
     FileReader = fileReader;
 }
Ejemplo n.º 9
0
 public HandlerImpl(IHttp http, IResponse response, ILessEngine engine, IFileReader fileReader)
 {
     Http       = http;
     Response   = response;
     Engine     = engine;
     FileReader = fileReader;
 }
Ejemplo n.º 10
0
        public LessHandler(IFileWrapper fileWrapper)
        {
            this.fileWrapper = fileWrapper;
            var config = new DotlessConfiguration
            {
                CacheEnabled = false,
                Logger       = typeof(LessLogger),
                Web          = HttpContext.Current != null,
            };

            if (HttpContext.Current == null)
            {
                engine = new EngineFactory(config).GetEngine();
            }
            else
            {
                var dotLessAssembly = Assembly.GetAssembly(typeof(ContainerFactory));
                var factoryType     = dotLessAssembly.GetType("dotless.Core.AspNetContainerFactory");
                var fac             = (ContainerFactory)(factoryType.InvokeMember("", BindingFlags.CreateInstance, null, null, null));
                var locator         = factoryType.InvokeMember("GetContainer", BindingFlags.InvokeMethod, null, fac, new object[] { config });
                engine =
                    (ILessEngine)
                    (dotLessAssembly.GetType("Microsoft.Practices.ServiceLocation.IServiceLocator").InvokeMember(
                         "GetInstance", BindingFlags.InvokeMethod, null, locator, new object[] { typeof(ILessEngine) }));
            }
        }
Ejemplo n.º 11
0
 public void SetUp()
 {
     request = MockRepository.GenerateStub<IRequest>();
     response = MockRepository.GenerateStub<IResponse>();
     engine = MockRepository.GenerateStub<ILessEngine>();
     lessSource = MockRepository.GenerateStub<ILessSource>();
 }
Ejemplo n.º 12
0
        private static string TransformCss(Parser lessParser, FileInfo bundleFile, ILessEngine lessEngine)
        {
            SetCurrentFilePath(lessParser, bundleFile.FullName);
            string source = File.ReadAllText(bundleFile.FullName);
            string css    = lessEngine.TransformToCss(source, bundleFile.FullName);

            return(css);
        }
Ejemplo n.º 13
0
        private static IEnumerable <string> CompileImpl(ILessEngine engine, string inputFilePath, string outputFilePath)
        {
            engine = new FixImportPathDecorator(engine);
            var currentDir = Directory.GetCurrentDirectory();

            try
            {
                Console.WriteLine("{0} -> {1}", inputFilePath, outputFilePath);
                var directoryPath = Path.GetDirectoryName(inputFilePath);
                var fileReader    = new dotless.Core.Input.FileReader();
                var source        = fileReader.GetFileContents(inputFilePath);
                Directory.SetCurrentDirectory(directoryPath);
                var css = engine.TransformToCss(source, inputFilePath);

                File.WriteAllText(outputFilePath, css);

                if (!engine.LastTransformationSuccessful)
                {
                    returnCode = -5;
                    Console.WriteLine();
                    Console.WriteLine("[Done - Failed]");
                }
                else
                {
                    Console.WriteLine("[Done]");
                }

                var files = new List <string>();
                files.Add(inputFilePath);
                foreach (var file in engine.GetImports())
                {
                    files.Add(Path.Combine(directoryPath, Path.GetExtension(file)));
                }
                engine.ResetImports();
                return(files);
            }
            catch (IOException ex)
            {
                Console.WriteLine("[FAILED]");
                Console.WriteLine("Compilation failed: {0}", ex.Message);
                Console.WriteLine(ex.StackTrace);
                returnCode = -2;
                return(null);
            }
            catch (Exception ex)
            {
                Console.WriteLine("[FAILED]");
                Console.WriteLine("Compilation failed: {0}", ex.Message);
                Console.WriteLine(ex.StackTrace);
                returnCode = -3;
                return(null);
            }
            finally
            {
                Directory.SetCurrentDirectory(currentDir);
            }
        }
Ejemplo n.º 14
0
        private static CompilationDelegate CreationImpl(ILessEngine engine, string inputFilePath, string outputDirectoryPath)
        {
            var pathbuilder = new System.Text.StringBuilder(outputDirectoryPath + Path.DirectorySeparatorChar);

            pathbuilder.Append(Path.ChangeExtension(Path.GetFileName(inputFilePath), "css"));
            var outputFilePath = Path.GetFullPath(pathbuilder.ToString());

            return(() => CompileImpl(engine, inputFilePath, outputFilePath));
        }
Ejemplo n.º 15
0
        public Task <LessCompilationResult> CompileAsync(string content, PathString virtualPathPrefix, string filePath, IFileProvider fileProvider, PathString outputPath, CancellationToken token)
        {
            if (content == null)
            {
                throw new ArgumentNullException(nameof(content));
            }

            token.ThrowIfCancellationRequested();

            string fileBasePath, fileName;

            if (filePath != null)
            {
                filePath        = UrlUtils.NormalizePath(filePath.Replace('\\', '/'));
                fileName        = UrlUtils.GetFileNameSegment(filePath, out StringSegment basePathSegment).Value;
                basePathSegment = UrlUtils.NormalizePathSegment(basePathSegment, trailingNormalization: PathNormalization.ExcludeSlash);
                fileBasePath    = basePathSegment.Value;
            }
            else
            {
                fileBasePath = "/";
                fileName     = string.Empty;
            }

            ILessEngine engine = _engineFactory.Create(fileBasePath, virtualPathPrefix, fileProvider, outputPath, token);

            Exception transformException = null;

            try { content = engine.TransformToCss(content, fileName); }
            catch (FileNotFoundException ex) { transformException = ex; }

            if (transformException != null || !engine.LastTransformationSuccessful)
            {
                if (transformException == null && engine is LessEngine lessEngine)
                {
                    transformException = lessEngine.LastTransformationError;
                }

                filePath = filePath ?? "(content)";

                const string messageFormat = "Less compilation of '{0}' failed.";

                _logger.LogError(string.Format(messageFormat, "{FILEPATH}") + Environment.NewLine + "{REASON}", filePath, transformException?.Message ?? "Unknown reason.");

                throw new BundlingErrorException(string.Format(messageFormat, filePath), transformException);
            }

            return(Task.FromResult(new LessCompilationResult(content, engine.GetImports().Select(path => UrlUtils.NormalizePath(path, canonicalize: true)).ToArray())));
        }
Ejemplo n.º 16
0
 public LessHandler(IFileWrapper fileWrapper)
 {
     this.fileWrapper = fileWrapper;
     var config = new DotlessConfiguration
     {
         CacheEnabled = false,
         Logger = typeof(LessLogger),
         Web = HttpContext.Current != null,
     };
     var engineFactory = new EngineFactory(config);
     if (HttpContext.Current == null)
         engine = engineFactory.GetEngine();
     else
         engine = engineFactory.GetEngine(new AspNetContainerFactory());
 }
Ejemplo n.º 17
0
        public void Process(BundleContext context, BundleResponse bundle)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (bundle == null)
            {
                throw new ArgumentNullException("bundle");
            }

            context.HttpContext.Response.Cache.SetLastModifiedFromFileDependencies();

            var         lessParser = new Parser();
            ILessEngine lessEngine = CreateLessEngine(lessParser);

            var content = new StringBuilder(bundle.Content.Length);

            var bundleFiles = new List <BundleFile>();

            foreach (var bundleFile in bundle.Files)
            {
                bundleFiles.Add(bundleFile);

                var name = context.HttpContext.Server.MapPath(bundleFile.VirtualFile.VirtualPath);
                SetCurrentFilePath(lessParser, name);
                using (var stream = bundleFile.VirtualFile.Open())
                    using (var reader = new StreamReader(stream))
                    {
                        string source = reader.ReadToEnd();
                        content.Append(lessEngine.TransformToCss(source, name));
                        content.AppendLine();
                    }

                bundleFiles.AddRange(GetFileDependencies(lessParser));
            }

            if (BundleTable.EnableOptimizations)
            {
                // include imports in bundle files to register cache dependencies
                bundle.Files = bundleFiles.Distinct();
            }

            bundle.ContentType = "text/css";
            bundle.Content     = content.ToString();
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Attempts to compile a less file into css.
        /// </summary>
        /// <param name="engine">The dotless engine.</param>
        /// <param name="inputFilePath">The input less file.</param>
        /// <param name="outputFilePath">The output css file.</param>
        /// <returns>The return code. 0 is success; otherwise, value is failure.</returns>
        private int CompileImpl(ILessEngine engine, string inputFilePath, string outputFilePath)
        {
            engine = new FixImportPathDecorator(engine);
            var currentDir = Directory.GetCurrentDirectory();

            try
            {
                Log.LogMessage("Compiling less from \"{0}\" to \"{1}\".", inputFilePath, outputFilePath);
                var directoryPath = Path.GetDirectoryName(inputFilePath);
                var fileReader    = new dotless.Core.Input.FileReader();
                var source        = fileReader.GetFileContents(inputFilePath);
                Directory.SetCurrentDirectory(directoryPath);
                var css = engine.TransformToCss(source, inputFilePath);

                File.WriteAllText(outputFilePath, css);

                if (!engine.LastTransformationSuccessful)
                {
                    Log.LogError("Failed: Compiling less from \"{0}\" to \"{1}\".", inputFilePath, outputFilePath);
                    return(-5);
                }
                else
                {
                    Log.LogMessage("Success: Compiled less from \"{0}\" to \"{1}\".", inputFilePath, outputFilePath);
                }

                var files = new List <string>();
                files.Add(inputFilePath);
                foreach (var file in engine.GetImports())
                {
                    files.Add(Path.Combine(directoryPath, Path.ChangeExtension(file, "less")));
                }
                engine.ResetImports();
                return(0);
            }
            catch (Exception ex)
            {
                Log.LogError("Failed: Compiling less from \"{0}\" to \"{1}\".", inputFilePath, outputFilePath);
                Log.LogError("Compilation failed: {0}", ex.ToString());
                return(-3);
            }
            finally
            {
                Directory.SetCurrentDirectory(currentDir);
            }
        }
Ejemplo n.º 19
0
        private static void RunBenchmark(string[] files, Dictionary <string, string> contents, int rounds, Func <string, ILessEngine, int> runTest)
        {
            var engines = new ILessEngine[]
            {
                new LessEngine()
            };


            Console.Write("       File        |     Size     |");
            foreach (var engine in engines)
            {
                Console.Write(engine.GetType().Name.PadRight(24).PadLeft(29));
                Console.Write('|');
            }
            Console.WriteLine();
            Console.WriteLine(new string('-', 35 + 30 * engines.Length));

            foreach (var file in files)
            {
                var size = rounds * contents[file].Length / 1024d;
                Console.Write("{0} | {1,8:#,##0.00} Kb  | ", file.PadRight(18), size);

                var times = new List <double>();
                foreach (var engine in engines)
                {
                    try
                    {
                        var time = runTest(file, engine) / 1000d;
                        times.Add(time);
                        Console.Write("{0,8:#.00} s  {1,10:#,##0.00} Kb/s | ", time, size / time);
                    }
                    catch
                    {
                        Console.Write("Failed                      | ");
                    }
                }
                if (times.Count == 2)
                {
                    Console.Write("{0,4:0.#}x", times[0] / times[1]);
                }
                Console.WriteLine();
            }

            Console.WriteLine("Done. Press 'r' to repeat or any key to exit");
        }
Ejemplo n.º 20
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="LessCode"></param>
		/// <returns></returns>
		async static protected Task<string> TransformAsync(string LessCode, string FileName = "unknown.less")
		{
			return await TaskEx.RunPropagatingExceptionsAsync(() =>
			{
				if (Config == null)
				{
					Config = new DotlessConfiguration()
					{
						MinifyOutput = true,
					};
				}
				if (Engine == null)
				{
					Engine = new EngineFactory(Config).GetEngine();
				}
				return Engine.TransformToCss(LessCode, FileName);
			});
		}
Ejemplo n.º 21
0
        /// <inheritdoc />
        public IEnumerable <IDocument> Execute(IReadOnlyList <IDocument> inputs, IExecutionContext context)
        {
            DotlessConfiguration config = DotlessConfiguration.GetDefault();

            config.Logger = typeof(LessLogger);
            EngineFactory    engineFactory    = new EngineFactory(config);
            FileSystemReader fileSystemReader = new FileSystemReader(context.FileSystem);

            return(inputs.AsParallel().Select(context, input =>
            {
                Trace.Verbose("Processing Less for {0}", input.SourceString());
                ILessEngine engine = engineFactory.GetEngine();

                // TODO: Get rid of RefelectionMagic and this ugly hack as soon as dotless gets better external DI support
                engine.AsDynamic().Underlying.Cache = new LessCache(context.ExecutionCache);
                engine.AsDynamic().Underlying.Underlying.Parser.Importer.FileReader = fileSystemReader;

                // Less conversion
                FilePath path = _inputPath.Invoke <FilePath>(input, context);
                if (path != null)
                {
                    engine.CurrentDirectory = path.Directory.FullPath;
                }
                else
                {
                    engine.CurrentDirectory = string.Empty;
                    path = new FilePath(Path.GetRandomFileName());
                    Trace.Warning($"No input path found for document {input.SourceString()}, using {path.FileName.FullPath}");
                }
                string content = engine.TransformToCss(input.Content, path.FileName.FullPath);

                // Process the result
                FilePath cssPath = path.ChangeExtension("css");
                return context.GetDocument(
                    input,
                    context.GetContentStream(content),
                    new MetadataItems
                {
                    { Keys.RelativeFilePath, cssPath },
                    { Keys.WritePath, cssPath }
                });
            }));
        }
Ejemplo n.º 22
0
        public LessHandler(IFileWrapper fileWrapper)
        {
            this.fileWrapper = fileWrapper;
            var config = new DotlessConfiguration
            {
                CacheEnabled = false,
                Logger       = typeof(LessLogger),
                Web          = HttpContext.Current != null,
            };
            var engineFactory = new EngineFactory(config);

            if (HttpContext.Current == null)
            {
                engine = engineFactory.GetEngine();
            }
            else
            {
                engine = engineFactory.GetEngine(new AspNetContainerFactory());
            }
        }
Ejemplo n.º 23
0
        public Task <LessCompilationResult> CompileAsync(string content, string virtualPathPrefix, string filePath, IFileProvider fileProvider, CancellationToken token)
        {
            if (content == null)
            {
                throw new ArgumentNullException(nameof(content));
            }

            token.ThrowIfCancellationRequested();

            string fileBasePath, virtualBasePath, fileName;

            if (filePath != null)
            {
                fileBasePath    = Path.GetDirectoryName(filePath).Replace('\\', '/');
                virtualBasePath = new PathString(virtualPathPrefix).Add(fileBasePath);
                fileName        = Path.GetFileName(filePath);
            }
            else
            {
                fileBasePath = virtualBasePath = fileName = null;
            }

            ILessEngine engine = _engineFactory.Create(fileBasePath ?? string.Empty, virtualBasePath ?? string.Empty, fileProvider);

            content = engine.TransformToCss(content, fileName);

            if (!engine.LastTransformationSuccessful)
            {
                _logger.LogWarning($"Less compilation of '{{FILEPATH}}' failed:{Environment.NewLine}{{REASON}}",
                                   (filePath ?? "(content)"),
                                   (engine is LessEngine lessEngine ? lessEngine.LastTransformationError?.Message : null) ?? "Unknown reason.");

                content = null;
            }

            return(Task.FromResult(
                       content != null ?
                       new LessCompilationResult(content, engine.GetImports().ToArray()) :
                       LessCompilationResult.Failure));
        }
Ejemplo n.º 24
0
        private static IEnumerable <string> CompileImpl(ILessEngine engine, string inputFilePath, string outputFilePath)
        {
            var currentDir = Directory.GetCurrentDirectory();

            try
            {
                Console.WriteLine("{0} -> {1}", inputFilePath, outputFilePath);
                var directoryPath = Path.GetDirectoryName(inputFilePath);
                var source        = new dotless.Core.Input.FileReader().GetFileContents(inputFilePath);
                Directory.SetCurrentDirectory(directoryPath);
                var css = engine.TransformToCss(source, inputFilePath);
                File.WriteAllText(outputFilePath, css);
                Console.WriteLine("[Done]");

                var files = new List <string>();
                files.Add(inputFilePath);
                foreach (var file in engine.GetImports())
                {
                    files.Add(Path.Combine(directoryPath, Path.ChangeExtension(file, "less")));
                }
                engine.ResetImports();
                return(files);
            }
            catch (IOException)
            {
                throw;
            }
            catch (Exception ex)
            {
                Console.WriteLine("[FAILED]");
                Console.WriteLine("Compilation failed: {0}", ex.Message);
                Console.WriteLine(ex.StackTrace);
                return(null);
            }
            finally
            {
                Directory.SetCurrentDirectory(currentDir);
            }
        }
    public void ProcessRequest(HttpContext context)
    {
        var    request   = context.Request;
        var    response  = context.Response;
        var    user      = context.User;
        string assetUrl  = request.Url.LocalPath;
        string assetPath = context.Server.MapPath(assetUrl);
        //load less file into the data.
        var data = "";

        using (var file = new StreamReader(assetPath))
        {
            data = file.ReadToEnd();
        }
        DotlessConfiguration lessEngineConfig = DotlessConfiguration.GetDefault();

        lessEngineConfig.MapPathsToWeb       = false;
        lessEngineConfig.CacheEnabled        = false;
        lessEngineConfig.DisableUrlRewriting = false;
        lessEngineConfig.Web          = false;
        lessEngineConfig.MinifyOutput = true;
        lessEngineConfig.LessSource   = typeof(VirtualFileReader);
        var         lessEngineFactory = new EngineFactory(lessEngineConfig);
        ILessEngine lessEngine        = lessEngineFactory.GetEngine();
        string      vars = "";

        //TODO set default for vars
        if (user != null)
        {
            //TODO get vars for user
        }
        var content = lessEngine.TransformToCss(string.Format("{0}{1}", vars, data), null);

        // Output text content of asset
        response.ContentType = "text/css";
        response.Write(content);
        response.End();
    }
Ejemplo n.º 26
0
 public LessHandler(IFileWrapper fileWrapper)
 {
     this.fileWrapper = fileWrapper;
     var config = new DotlessConfiguration
     {
         CacheEnabled = false,
         Logger = typeof(LessLogger),
         Web = HttpContext.Current != null,
     };
     if (HttpContext.Current == null)
         engine = new EngineFactory(config).GetEngine();
     else
     {
         var dotLessAssembly = Assembly.GetAssembly(typeof (ContainerFactory));
         var factoryType = dotLessAssembly.GetType("dotless.Core.AspNetContainerFactory");
         var fac = (ContainerFactory)(factoryType.InvokeMember("", BindingFlags.CreateInstance, null, null, null));
         var locator = factoryType.InvokeMember("GetContainer", BindingFlags.InvokeMethod, null, fac, new object[] {config});
         engine =
             (ILessEngine)
             (dotLessAssembly.GetType("Microsoft.Practices.ServiceLocation.IServiceLocator").InvokeMember(
                 "GetInstance", BindingFlags.InvokeMethod, null, locator, new object[] {typeof (ILessEngine)}));
     }
 }
Ejemplo n.º 27
0
        private static IEnumerable<string> CompileImpl(ILessEngine engine, string inputFilePath, string outputFilePath)
        {
            engine = new FixImportPathDecorator(engine);
            var currentDir = Directory.GetCurrentDirectory();
            try
            {
                Console.WriteLine("{0} -> {1}", inputFilePath, outputFilePath);
                var directoryPath = Path.GetDirectoryName(inputFilePath);
                var source = new dotless.Core.Input.FileReader().GetFileContents(inputFilePath);
                Directory.SetCurrentDirectory(directoryPath);
                var css = engine.TransformToCss(source, inputFilePath);
                File.WriteAllText(outputFilePath, css);
                Console.WriteLine("[Done]");

                var files = new List<string>();
                files.Add(inputFilePath);
                foreach (var file in engine.GetImports())
                    files.Add(Path.Combine(directoryPath, Path.ChangeExtension(file, "less")));
                engine.ResetImports();
                return files;
            }
            catch (IOException)
            {
                throw;
            }
            catch (Exception ex)
            {
                Console.WriteLine("[FAILED]");
                Console.WriteLine("Compilation failed: {0}", ex.Message);
                Console.WriteLine(ex.StackTrace);
                return null;
            }
            finally
            {
                Directory.SetCurrentDirectory(currentDir);
            }
        }
Ejemplo n.º 28
0
        public SourceTransformation Transform(IEnumerable <FileInfo> files)
        {
            var         lessParser  = new Parser();
            ILessEngine lessEngine  = CreateLessEngine(lessParser);
            var         bundleFiles = new List <FileInfo>();
            var         content     = new StringBuilder();

            foreach (FileInfo bundleFile in files)
            {
                bundleFiles.Add(bundleFile);

                string css = TransformCss(lessParser, bundleFile, lessEngine);

                content.AppendFormat("{0}\n", css);

                bundleFiles.AddRange(GetFileDependencies(lessParser));
            }

            return(new SourceTransformation
            {
                Dependencies = bundleFiles,
                Source = content.ToString()
            });
        }
Ejemplo n.º 29
0
 public LessCompiler(ILessEngine engine)
 {
     _engine = engine;
 }
Ejemplo n.º 30
0
 public FixImportPathDecorator(ILessEngine underlying)
 {
     this.underlying = underlying;
 }
Ejemplo n.º 31
0
 public static string Parse(ILessEngine engine, string less, DotlessConfiguration config)
 {
     return(engine.TransformToCss(less, null));
 }
Ejemplo n.º 32
0
        public static void Main(string[] args)
        {
            Directory.SetCurrentDirectory(@"C:\dev\oss\less.js\test\less");

              var files = new[]
                    {
                      "colors",
                      "comments",
                      "css",
                      "css-3",
                      "mixins",
                      "mixins-args",
                      "operations",
                      "parens",
                      "rulesets",
                      "scope",
                      "selectors",
                      "strings",
                      "variables",
                      "whitespace"
                    }
            .Select(f => f + ".less");

              var contents = files
            .ToDictionary(f => f, f => new LessSourceObject { Content = File.ReadAllText(f) });

              const int rounds = 150;

              Func<string, ILessEngine, int> runTest =
            (file, engine) => Enumerable
                            .Range(0, rounds)
                            .Select(i =>
                                      {
                                        var starttime = DateTime.Now;
                                        engine.TransformToCss(contents[file]);
                                        var duration = (DateTime.Now - starttime);
                                        return duration.Milliseconds;
                                      })
                            .Sum();

              Console.WriteLine("Press Enter to begin benchmark");
              Console.ReadLine();

              Console.WriteLine("Running each test {0} times\n", rounds);

              var engines = new ILessEngine[]
                      {
                        new ExtensibleEngine(),
                        new LessJsEngine()
                      };

              Console.Write("       File        |     Size     |");
              foreach (var engine in engines)
              {
            Console.Write(engine.GetType().Name.PadRight(24).PadLeft(29));
            Console.Write('|');
              }
              Console.WriteLine();
              Console.WriteLine(new string('-', 35 + 30*engines.Length));

              foreach (var file in files)
              {
            var size = rounds*contents[file].Content.Length/1024d;
            Console.Write("{0} | {1,8:#,##0.00} Kb  | ", file.PadRight(18), size);

            foreach (var engine in engines)
            {
              try
              {
            var time = runTest(file, engine)/1000d;
            Console.Write("{0,8:#.00} s  {1,10:#,##0.00} Kb/s | ", time, size/time);
              }
              catch
              {
            Console.Write("Failied                     | ");
              }
            }
            Console.WriteLine();
              }

              //      Console.Read();
        }
Ejemplo n.º 33
0
 public LessCompiler(ILessEngine lessEngine)
 {
     this.lessEngine = lessEngine;
 }
Ejemplo n.º 34
0
        /// <summary>
        /// Attempts to compile a less file into css.
        /// </summary>
        /// <param name="engine">The dotless engine.</param>
        /// <param name="inputFilePath">The input less file.</param>
        /// <param name="outputFilePath">The output css file.</param>
        /// <returns>The return code. 0 is success; otherwise, value is failure.</returns>
        private int CompileImpl(ILessEngine engine, string inputFilePath, string outputFilePath)
        {
            engine = new FixImportPathDecorator(engine);
            var currentDir = Directory.GetCurrentDirectory();
            try
            {
                Log.LogMessage("Compiling less from \"{0}\" to \"{1}\".", inputFilePath, outputFilePath);
                var directoryPath = Path.GetDirectoryName(inputFilePath);
                var fileReader = new dotless.Core.Input.FileReader();
                var source = fileReader.GetFileContents(inputFilePath);
                Directory.SetCurrentDirectory(directoryPath);
                var css = engine.TransformToCss(source, inputFilePath);

                File.WriteAllText(outputFilePath, css);

                if (!engine.LastTransformationSuccessful)
                {
                    Log.LogError("Failed: Compiling less from \"{0}\" to \"{1}\".", inputFilePath, outputFilePath);
                    return -5;
                }
                else
                {
                    Log.LogMessage("Success: Compiled less from \"{0}\" to \"{1}\".", inputFilePath, outputFilePath);
                }

                var files = new List<string>();
                files.Add(inputFilePath);
                foreach (var file in engine.GetImports())
                    files.Add(Path.Combine(directoryPath, Path.ChangeExtension(file, "less")));
                engine.ResetImports();
                return 0;
            }
            catch (Exception ex)
            {
                Log.LogError("Failed: Compiling less from \"{0}\" to \"{1}\".", inputFilePath, outputFilePath);
                Log.LogError("Compilation failed: {0}", ex.ToString());
                return -3;
            }
            finally
            {
                Directory.SetCurrentDirectory(currentDir);
            }
        }
Ejemplo n.º 35
0
        internal static string Process(ref IEnumerable <BundleFile> files)
        {
            DotlessConfiguration lessConfig = new WebConfigConfigurationLoader().GetConfiguration();

            if (!lessConfig.LessSource.GetInterfaces().Contains(typeof(IFileReaderWithResolver)))
            {
                lessConfig.LessSource = typeof(LessVirtualFileReader);
            }

            // system.Web.Optimization cache is used instead
            lessConfig.CacheEnabled = false;

            var content = new StringBuilder();

            var targetFiles = new List <BundleFile>();

            foreach (BundleFile bundleFile in files)
            {
                // initialize the less engine once for each file.
                // this is to prevent leaking state between files
                ILessEngine lessEngine           = LessWeb.GetEngine(lessConfig);
                LessEngine  underlyingLessEngine = lessEngine.ResolveLessEngine();
                Parser      lessParser           = underlyingLessEngine.Parser;

                targetFiles.Add(bundleFile);
                string filePath = bundleFile.IncludedVirtualPath;
                filePath = filePath.Replace('\\', '/');
                filePath = VirtualPathUtility.ToAppRelative(filePath);

                lessParser.SetCurrentFilePath(filePath);
                string source    = bundleFile.ApplyTransforms();
                string extension = VirtualPathUtility.GetExtension(filePath);

                // if plain CSS file, do not transform LESS
                if (lessConfig.ImportAllFilesAsLess ||
                    ".less".Equals(extension, StringComparison.InvariantCultureIgnoreCase) ||
                    ".less.css".Equals(extension, StringComparison.InvariantCultureIgnoreCase))
                {
                    string lessOutput = lessEngine.TransformToCss(source, filePath);

                    // pass the transformation result if successful
                    if (lessEngine.LastTransformationSuccessful)
                    {
                        source = lessOutput;
                    }
                    else
                    {
                        // otherwise write out error message.
                        // the transformation error is logged in LessEngine.TransformToCss
                        if (lessConfig.Debug)
                        {
                            content.AppendLine(string.Format(
                                                   "/* Error occurred in LESS transformation of the file: {0}. Please see details in the dotless log */",
                                                   bundleFile.IncludedVirtualPath));
                        }
                        continue;
                    }
                }

                source = ConvertUrlsToAbsolute(bundleFile.IncludedVirtualPath, source);

                content.AppendLine(source);

                BundleFile[] fileDependencies = GetFileDependencies(underlyingLessEngine).ToArray();
                targetFiles.AddRange(fileDependencies);

                DependencyCache.SaveFileDependencies(filePath, fileDependencies.Select(file => file.IncludedVirtualPath).ToArray());
            }

            // include imports in bundle files to register cache dependencies
            files = BundleTable.EnableOptimizations ? targetFiles.Distinct() : targetFiles;

            return(content.ToString());
        }
Ejemplo n.º 36
0
 public CacheDecorator(ILessEngine underlying, ICache cache, ILogger logger)
 {
     Underlying = underlying;
     Cache      = cache;
     Logger     = logger;
 }
Ejemplo n.º 37
0
 public ParameterDecorator(ILessEngine underlying, IParameterSource parameterSource)
 {
     this.Underlying = underlying;
     this.parameterSource = parameterSource;
 }
Ejemplo n.º 38
0
        private static IEnumerable<string> CompileImpl(ILessEngine engine, string inputFilePath, string outputFilePath)
        {
            engine = new FixImportPathDecorator(engine);
            try
            {
                Console.WriteLine("{0} -> {1}", inputFilePath, outputFilePath);
                var directoryPath = Path.GetDirectoryName(inputFilePath);
                var fileReader = new dotless.Core.Input.FileReader();
                var source = fileReader.GetFileContents(inputFilePath);
                engine.CurrentDirectory = directoryPath;

                var watch = new Stopwatch();
                watch.Start();
                var css = engine.TransformToCss(source, inputFilePath);
                watch.Stop();

                File.WriteAllText(outputFilePath, css);

                if (!engine.LastTransformationSuccessful)
                {
                    returnCode = -5;
                    Console.WriteLine();
                    Console.WriteLine("[Done - Failed]");
                }
                else
                {
                    Console.WriteLine("[Done in {0}]", watch.Elapsed);
                }

                var files = new List<string>();
                files.Add(inputFilePath);
                foreach (var file in engine.GetImports())
					files.Add(Path.Combine(directoryPath, Path.GetExtension(file)));
                engine.ResetImports();
                return files;
            }
            catch (IOException ex)
            {
                Console.WriteLine("[FAILED]");
                Console.WriteLine("Compilation failed: {0}", ex.Message);
                Console.WriteLine(ex.StackTrace);
                returnCode = -2;
                return null;
            }
            catch (Exception ex)
            {
                Console.WriteLine("[FAILED]");
                Console.WriteLine("Compilation failed: {0}", ex.Message);
                Console.WriteLine(ex.StackTrace);
                returnCode = -3;
                return null;
            }
        }
Ejemplo n.º 39
0
 public CacheDecorator(ILessEngine underlying, ICache cache, ILogger logger)
 {
     Underlying = underlying;
     Cache = cache;
     Logger = logger;
 }
Ejemplo n.º 40
0
 public FixImportPathDecorator(ILessEngine underlying)
 {
     this.underlying = underlying;
 }
Ejemplo n.º 41
0
        public static void Main(string[] args)
        {
            Directory.SetCurrentDirectory("Input");
            var files = Directory.GetFiles(".", "*.less");

            var contents = files
                           .ToDictionary(f => f, f => File.ReadAllText(f));

            const int rounds = 150;

            Func <string, ILessEngine, int> runTest =
                (file, engine) => Enumerable
                .Range(0, rounds)
                .Select(i =>
            {
                var starttime = DateTime.Now;
                engine.TransformToCss(contents[file], file);
                var duration = (DateTime.Now - starttime);
                return(duration.Milliseconds);
            })
                .Sum();

            Console.WriteLine("Press Enter to begin benchmark");
            Console.ReadLine();

            Console.WriteLine("Running each test {0} times\n", rounds);

            var engines = new ILessEngine[]
            {
                new LessEngine()
            };


            Console.Write("       File        |     Size     |");
            foreach (var engine in engines)
            {
                Console.Write(engine.GetType().Name.PadRight(24).PadLeft(29));
                Console.Write('|');
            }
            Console.WriteLine();
            Console.WriteLine(new string('-', 35 + 30 * engines.Length));

            foreach (var file in files)
            {
                var size = rounds * contents[file].Length / 1024d;
                Console.Write("{0} | {1,8:#,##0.00} Kb  | ", file.PadRight(18), size);

                var times = new List <double>();
                foreach (var engine in engines)
                {
                    try
                    {
                        var time = runTest(file, engine) / 1000d;
                        times.Add(time);
                        Console.Write("{0,8:#.00} s  {1,10:#,##0.00} Kb/s | ", time, size / time);
                    }
                    catch
                    {
                        Console.Write("Failied                     | ");
                    }
                }
                if (times.Count == 2)
                {
                    Console.Write("{0,4:0.#}x", times[0] / times[1]);
                }
                Console.WriteLine();
            }

            //      Console.Read();
        }
Ejemplo n.º 42
0
 public static string Parse(ILessEngine engine, string less)
 {
     return(Parse(engine, less, DotlessConfiguration.GetDefault()));
 }
Ejemplo n.º 43
0
        public void Process(BundleContext context, BundleResponse bundle)
        {
            context.HttpContext.Response.Cache.SetLastModifiedFromFileDependencies();

            var content = new StringBuilder();

            var bundleFiles = new List <BundleFile>();

            foreach (var bundleFile in bundle.Files)
            {
                var         lessParser = new Parser();
                ILessEngine lessEngine = this.CreateLessEngine(lessParser);

                bool foundMinimizedVersion = false;
                bundleFiles.Add(bundleFile);

                if (BundleTable.EnableOptimizations)
                {
                    var ext = Path.GetExtension(bundleFile.VirtualFile.VirtualPath);
                    if (ext != null && ext.Equals(".less", StringComparison.InvariantCultureIgnoreCase))
                    {
                        var filepath          = bundleFile.VirtualFile.VirtualPath;
                        var minimizedFileName = string.Format(
                            "{0}.min.css",
                            filepath.Substring(0, filepath.LastIndexOf(ext, StringComparison.Ordinal)));
                        var virtualPathProvider = HostingEnvironment.VirtualPathProvider;
                        if (virtualPathProvider.FileExists(minimizedFileName))
                        {
                            var minimizedFile = virtualPathProvider.GetFile(minimizedFileName);
                            foundMinimizedVersion = true;
                            using (var reader = new StreamReader(minimizedFile.Open()))
                            {
                                content.Append(reader.ReadToEnd());
                                content.AppendLine();

                                bundleFiles.Add(new BundleFile(minimizedFile.VirtualPath, minimizedFile));
                            }
                        }
                    }
                }

                if (!foundMinimizedVersion)
                {
                    this.SetCurrentFilePath(lessParser, bundleFile.VirtualFile.VirtualPath);

                    using (var reader = new StreamReader(VirtualPathProvider.OpenFile(bundleFile.VirtualFile.VirtualPath)))
                    {
                        var fileContent = reader.ReadToEnd();
                        content.Append(lessEngine.TransformToCss(fileContent, bundleFile.VirtualFile.VirtualPath));
                        content.AppendLine();

                        bundleFiles.AddRange(this.GetFileDependencies(lessParser).Select(f => new BundleFile(f.VirtualPath, f)));
                    }
                }
            }

            if (BundleTable.EnableOptimizations)
            {
                // include imports in bundle files to register cache dependencies
                bundle.Files = bundleFiles.Distinct().ToList();
            }

            bundle.ContentType = "text/css";
            bundle.Content     = content.ToString();
        }
Ejemplo n.º 44
0
 public LessCompiler(ILessEngine engine)
 {
     _engine = engine;
 }
Ejemplo n.º 45
0
        private static IEnumerable<string> CompileImpl(ILessEngine engine, string inputFilePath, string outputFilePath, StringBuilder sb, bool silent)
        {
            try
            {
                if (!silent)
                {
                    sb.AppendFormat("{0} -> {1}\n", inputFilePath, outputFilePath);
                }

                var directoryPath = Path.GetDirectoryName(inputFilePath);
                var source = new dotless.Core.Input.FileReader(directoryPath).GetFileContents(inputFilePath);
                var css = engine.TransformToCss(source, inputFilePath);
                File.WriteAllText(outputFilePath, css);

                if (!silent)
                {
                    sb.AppendLine("[Done]");
                }

                var files = new List<string>();
                files.Add(inputFilePath);
                foreach (var file in engine.GetImports())
                {
                    files.Add(Path.Combine(directoryPath, Path.ChangeExtension(file, "less")));
                }
                engine.ResetImports();
                return files;
            }
            catch (IOException)
            {
                throw;
            }
            catch (Exception ex)
            {
                if (silent)
                {
                    // Need to know the file now
                    sb.AppendFormat("{0} -> {1}\n", inputFilePath, outputFilePath);
                }

                sb.AppendLine("[FAILED]");
                sb.AppendFormat("Compilation failed: {0}\n", ex.Message);
                sb.AppendLine(ex.StackTrace);
                return null;
            }
        }
Ejemplo n.º 46
0
 public CacheDecorator(ILessEngine underlying, ICache cache)
     : this(underlying, cache, NullLogger.Instance)
 {
 }
Ejemplo n.º 47
0
        public static void Main(string[] args)
        {
            Directory.SetCurrentDirectory("Input");
            var files = Directory.GetFiles(".", "*.less");

            var contents = files
                .ToDictionary(f => f, f => File.ReadAllText(f));

            const int rounds = 150;

            Func<string, ILessEngine, int> runTest =
                (file, engine) => Enumerable
                                      .Range(0, rounds)
                                      .Select(i =>
                                                  {
                                                      var starttime = DateTime.Now;
                                                      engine.TransformToCss(contents[file], file);
                                                      var duration = (DateTime.Now - starttime);
                                                      return duration.Milliseconds;
                                                  })
                                      .Sum();

            Console.WriteLine("Press Enter to begin benchmark");
            Console.ReadLine();

            Console.WriteLine("Running each test {0} times\n", rounds);

            var engines = new ILessEngine[]
                              {
                                  new LessEngine()
                              };


            Console.Write("       File        |     Size     |");
            foreach (var engine in engines)
            {
                Console.Write(engine.GetType().Name.PadRight(24).PadLeft(29));
                Console.Write('|');
            }
            Console.WriteLine();
            Console.WriteLine(new string('-', 35 + 30*engines.Length));

            foreach (var file in files)
            {
                var size = rounds*contents[file].Length/1024d;
                Console.Write("{0} | {1,8:#,##0.00} Kb  | ", file.PadRight(18), size);

                var times = new List<double>();
                foreach (var engine in engines)
                {
                    try
                    {
                        var time = runTest(file, engine)/1000d;
                        times.Add(time);
                        Console.Write("{0,8:#.00} s  {1,10:#,##0.00} Kb/s | ", time, size/time);
                    }
                    catch
                    {
                        Console.Write("Failied                     | ");
                    }
                }
                if (times.Count == 2)
                    Console.Write("{0,4:0.#}x", times[0] / times[1]);
                Console.WriteLine();
            }

            //      Console.Read();
        }
Ejemplo n.º 48
0
 public ParameterDecorator(ILessEngine underlying, IParameterSource parameterSource)
 {
     this.Underlying      = underlying;
     this.parameterSource = parameterSource;
 }
Ejemplo n.º 49
0
        private static IEnumerable<string> CompileImpl(ILessEngine engine, string inputFilePath, string outputFilePath)
        {
            engine = new FixImportPathDecorator(engine);
            var currentDir = Directory.GetCurrentDirectory();
            try
            {
                Console.WriteLine("{0} -> {1}", inputFilePath, outputFilePath);
                var directoryPath = Path.GetDirectoryName(inputFilePath);
                var fileReader = new dotless.Core.Input.FileReader();
                var source = fileReader.GetFileContents(inputFilePath);
                Directory.SetCurrentDirectory(directoryPath);
                var css = engine.TransformToCss(source, inputFilePath);

                File.WriteAllText(outputFilePath, css);

                if (!engine.LastTransformationSuccessful)
                {
                    returnCode = -5;
                    Console.WriteLine();
                    Console.WriteLine("[Done - Failed]");
                }
                else
                {
                    Console.WriteLine("[Done]");
                }

                var files = new List<string>();
                files.Add(inputFilePath);
                foreach (var file in engine.GetImports())
                    files.Add(Path.Combine(directoryPath, Path.ChangeExtension(file, "less")));
                engine.ResetImports();
                return files;
            }
            <<<<<<< HEAD
            //catch (IOException)
            //{
            //    throw;
            //}
            //catch (Exception ex)
            //{
            //    Console.WriteLine("[FAILED]");
            //    Console.WriteLine("Compilation failed: {0}", ex.Message);
            //    Console.WriteLine(ex.StackTrace);
            //    return null;
            //}
            =======
            catch (IOException)
            {
                returnCode = -2;
                throw;
            }
            catch (Exception ex)
            {
                Console.WriteLine("[FAILED]");
                Console.WriteLine("Compilation failed: {0}", ex.Message);
                Console.WriteLine(ex.StackTrace);
                returnCode = -3;
                return null;
            }
            >>>>>>> 57986d4e1b45102058e055468254b85e34a41e98
            finally
            {
                Directory.SetCurrentDirectory(currentDir);
            }
        }
Ejemplo n.º 50
0
 private static CompilationDelegate CreationImpl(ILessEngine engine, string inputFilePath, string outputDirectoryPath)
 {
     var pathbuilder = new System.Text.StringBuilder(outputDirectoryPath + Path.DirectorySeparatorChar);
     pathbuilder.Append(Path.ChangeExtension(Path.GetFileName(inputFilePath), "css"));
     var outputFilePath = Path.GetFullPath(pathbuilder.ToString());
     return () => CompileImpl(engine, inputFilePath, outputFilePath);
 }
Ejemplo n.º 51
0
 public CacheDecorator(ILessEngine underlying, ICache cache) : this(underlying, cache, NullLogger.Instance)
 {
 }
Ejemplo n.º 52
0
 public AspCacheDecorator(ILessEngine underlying, ICache cache)
 {
     this.underlying = underlying;
     this.cache = cache;
 }
Ejemplo n.º 53
0
 public MinifierDecorator(ILessEngine engine)
 {
     this.engine = engine;
 }