Ejemplo n.º 1
0
 private void FilterOrderLimitResult <T>(ActionExecutedContext context, HttpRequest request, OkObjectResult resultResponse)
 {
     if (resultResponse != null)
     {
         var result = resultResponse.Value as IEnumerable <T>;
         if (result != null)
         {
             if (result.Any())
             {
                 var newObject = result;
                 newObject = FilterResult(result, request);
                 newObject = OrderResult(newObject, request);
                 newObject = LimitObjectResult(newObject, request);
                 //minify dynamic content
                 if (_minifyResponse)
                 {
                     var json     = JsonConvert.SerializeObject(newObject, Startup.jsonSettings);
                     var minified = minifyJs.Minify(json, false);
                     if (!minified.Errors.Any())
                     {
                         context.Result = new OkObjectResult(minified.MinifiedContent);
                     }
                     else
                     {
                         context.Result = new OkObjectResult(newObject);
                     }
                 }
                 else
                 {
                     context.Result = new OkObjectResult(newObject);
                 }
             }
         }
     }
 }
Ejemplo n.º 2
0
        public static async Task <IActionResult> ToMongoDB <T>(this object collection, bool update = false, bool storeMinified = false)
        {
            var collectionName = typeof(T).Name.ToLower();
            var collectionUrl  = $"{baseUrl}databases/{defaultDatabase}/collections/{collectionName}?apiKey={apiKey}&m=true&u=true";
            var stringPayload  = JsonConvert.SerializeObject(collection, Startup.jsonSettings);

            if (storeMinified)
            {
                var minified = minifyJs.Minify(stringPayload, false);
                if (minified.Errors.Count == 0)
                {
                    stringPayload = minified.MinifiedContent;
                }
            }
            var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json");

            using (var response = update ? await Helpers.Net.PutResponse(collectionUrl, httpContent) : await Helpers.Net.PostResponse(collectionUrl, httpContent))
            {
                response.EnsureSuccessStatusCode();
                var content = await response.Content.ReadAsStringAsync();

                return(new OkObjectResult(content));
            }
        }
Ejemplo n.º 3
0
        public string Process(string content, string filePath)
        {
            var result = _minifier.Minify(content, isInlineCode: false);

            if (result.Errors.Count > 0)
            {
                var message = string.Concat($"Js minification of '{(filePath ?? "n/a")}' failed:", Environment.NewLine, "{REASON}");
                var reason  = string.Join(Environment.NewLine, result.Errors.Select(e => e.Message));
                _logger.LogWarning(message, reason);

                return(content);
            }
            else if (result.Warnings.Count > 0)
            {
                var message = string.Concat($"Js minification of '{(filePath ?? "n/a")}' completed with warnings:", Environment.NewLine, "{REASON}");
                var reason  = string.Join(Environment.NewLine, result.Warnings.Select(e => e.Message));
                _logger.LogWarning(message, reason);
            }

            return(result.MinifiedContent);
        }
Ejemplo n.º 4
0
        public string Process(string content, string filePath)
        {
            global::WebMarkupMin.Core.CodeMinificationResult result = _minifier.Minify(content, isInlineCode: false);

            if (result.Errors.Count > 0)
            {
                _logger.LogWarning($"Js minification of '{{FILEPATH}}' failed:{Environment.NewLine}{{REASON}}",
                                   filePath ?? "(content)",
                                   result.Errors.Select(e => e.Message));

                return(content);
            }
            else if (result.Warnings.Count > 0)
            {
                _logger.LogWarning($"Js minification of '{{FILEPATH}}' completed with warnings:{Environment.NewLine}{{REASON}}",
                                   filePath ?? "(content)",
                                   result.Warnings.Select(e => e.Message));
            }

            return(result.MinifiedContent);
        }
Ejemplo n.º 5
0
        private static Dictionary <string, Tuple <string, byte[]> > LoadCache(string basePath, string[] extensions = null)
        {
            //put static files minificated in a memory store -> cache
            var staticFilesStorage = new Dictionary <string, Tuple <string, byte[]> >();
            //read all static files and load into mmemory
            var files = Directory.GetFiles(basePath, "*", SearchOption.AllDirectories).ToList();

            if (extensions != null)
            {
                files = files.Where(f => extensions.Contains(Path.GetExtension(f))).ToList();
            }
            var minifyJs   = new WebMarkupMin.Core.CrockfordJsMinifier();
            var minifyCss  = new WebMarkupMin.Core.KristensenCssMinifier();
            var minifyHtml = new WebMarkupMin.Core.HtmlMinifier();

            files.ForEach(file =>
            {
                var content = File.ReadAllBytes(file);
                var ext     = Path.GetExtension(file);
                //compress or minify
                if (Environment.GetEnvironmentVariable("minifyResponse") != "false")
                {
                    switch (ext)
                    {
                    case ".js":
                        //javascript minify
                        var js         = System.Text.UTF8Encoding.Default.GetString(content);
                        var minifiedJs = minifyJs.Minify(js, false);
                        if (!minifiedJs.Errors.Any())
                        {
                            content = System.Text.UTF8Encoding.Default.GetBytes(minifiedJs.MinifiedContent);
                        }
                        break;

                    case ".css":
                        //css minify
                        var css         = System.Text.UTF8Encoding.Default.GetString(content);
                        var minifiedCss = minifyCss.Minify(css, false);
                        if (!minifiedCss.Errors.Any())
                        {
                            content = System.Text.UTF8Encoding.Default.GetBytes(minifiedCss.MinifiedContent);
                        }
                        break;

                    case ".html":
                        //html minify
                        var html         = System.Text.UTF8Encoding.Default.GetString(content);
                        var minifiedHtml = minifyHtml.Minify(html, false);
                        if (!minifiedHtml.Errors.Any())
                        {
                            content = System.Text.UTF8Encoding.Default.GetBytes(minifiedHtml.MinifiedContent);
                        }
                        break;
                    }
                }
                staticFilesStorage.Add(file, new Tuple <string, byte[]>(MimeMapping.MimeUtility.GetMimeMapping(file), content));
            });

            var usedMemory = Math.Round(staticFilesStorage.Select(s => s.Value).Sum(s => s.Item2.Length) / 1024.0 / 1024.0);

            Console.WriteLine($"{staticFilesStorage.Count} static files loaded into memory using {usedMemory} MB");
            return(staticFilesStorage);
        }
Ejemplo n.º 6
0
        public static void Run(
            AbsolutePath scriptsDirectory,
            AbsolutePath componentsDirectory,
            string bundleFileName)
        {
            var componentsFolderPath    = componentsDirectory;
            var componentsPathForBundle = GetRelativePath(scriptsDirectory, componentsDirectory).Replace('\\', '/').Trim('/');
            var componentsFolder        = new DirectoryInfo(componentsFolderPath);

            var jsMinifier   = new WebMarkupMin.Core.CrockfordJsMinifier();
            var htmlMinifier = new WebMarkupMin.Core.HtmlMinifier(jsMinifier: jsMinifier);

            var bundleParts = componentsFolder.EnumerateDirectories().SelectMany(x =>
                                                                                 x.EnumerateFiles().Select(y =>
            {
                var name        = y.Name.Replace(y.Extension, string.Empty);
                var path        = string.Empty;
                var contentType = ContentType.Unknown;
                var content     = string.Empty;

                if (string.Equals(y.Extension, ".js", StringComparison.InvariantCultureIgnoreCase))
                {
                    path        = $"{componentsPathForBundle}/{x.Name}/{name}";
                    contentType = ContentType.Js;
                }
                else if (string.Equals(y.Extension, ".html", StringComparison.InvariantCultureIgnoreCase))
                {
                    path        = $"text!{componentsPathForBundle}/{x.Name}/{y.Name}";
                    contentType = ContentType.Html;
                }
                else
                {
                    return(ContentType: contentType, ModuleName: x.Name, ContentPath: y.FullName, Content: string.Empty);
                }

                using (var stream = File.OpenRead(y.FullName))
                    using (var reader = new StreamReader(stream))
                    {
                        content = reader.ReadToEnd();
                        switch (contentType)
                        {
                        case ContentType.Js:
                            content = jsMinifier.Minify(content, false).MinifiedContent;
                            break;

                        case ContentType.Html:
                            content = htmlMinifier.Minify(content).MinifiedContent.Replace("\r", "").Replace("\n", "").Replace("\'", "\\'");
                            break;

                        default:
                            break;
                        }
                    }
                return(ContentType: contentType, ModuleName: x.Name, ContentPath: path.Replace("\\", "/"), Content: content);
            })).ToList();

            var part1 = string.Join(string.Empty, bundleParts.SelectMany(x => x.ContentType == ContentType.Html ? new[] { $"define('{x.ContentPath}', [], function () {{ return '{x.Content}';}});" } : new string[] { }));
            var part2 = string.Join(string.Empty, bundleParts.SelectMany(x => x.ContentType == ContentType.Js ? new[] { x.Content } : new string[] { }));
            var moduleDescriptions = bundleParts.GroupBy(x => x.ModuleName);
            var part3 = $"define('components', [{string.Join(",", moduleDescriptions.Select(x => "'" + x.Key + "'"))}]);";
            var part4 = string.Join(string.Empty, moduleDescriptions.Select(x => $"define('{x.Key}', [{string.Join(",", x.Select(y => "'" + y.ContentPath + "'"))}]);"));

            using (var stream = File.Create(componentsFolderPath / bundleFileName))
                using (var writer = new StreamWriter(stream))
                {
                    writer.Write(string.Join(Environment.NewLine, new[] { part1, part2, part3, part4 }));
                }
            Console.WriteLine("Bundle assembled!");
        }