Exemple #1
0
        private ResourcePath ProcessGroup(ResourceCollection set, bool minify, bool cacheRefresh)
        {
            if (!set.Any())
            {
                throw new ApplicationException("Cannot process empty group");
            }

            var firstElement = set.First();

            if (set.Count() == 1 && firstElement.IsExternal)
            {
                return new ResourcePath {
                           ContentType = firstElement.ContentType, Url = firstElement.Url
                }
            }
            ;

            var cacheKey = minify ? set.UnqiueId.ToMinPath() : set.UnqiueId;

            var upgraded = false;

            try
            {
                cacheLock.EnterUpgradeableReadLock();

                var cached = cacheProvider.Get <ResourcePath>(cacheKey);
                if (cached != null && cacheRefresh)
                {
                    return(cached);
                }

                cacheLock.EnterWriteLock();
                upgraded = true;

                var priorWrite = cacheProvider.Get <ResourcePath>(cacheKey);
                if (priorWrite != null && cacheRefresh)
                {
                    return(priorWrite);
                }

                // regenerate
                var result = new ResourcePath();
                result.ContentType = firstElement.ContentType;
                result.Url         = Url.Action("fetch", "resource", new { id = cacheKey });

                // mash
                result.Contents = set.Mash();

                // minify
                if (minify)
                {
                    result.Contents = firstElement.ContentType == "text/javascript"
                                          ? JavaScriptCompressor.Compress(result.Contents)
                                          : CssCompressor.Compress(result.Contents);
                }

                // write backup file
                var physicalFilePath = GetFilePath(set.UnqiueId, minify);

                if (!Directory.Exists(Path.GetDirectoryName(physicalFilePath)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(physicalFilePath));
                }

                if (File.Exists(physicalFilePath))
                {
                    File.Delete(physicalFilePath);
                }

                File.WriteAllText(physicalFilePath, result.Contents);
                result.FileName = physicalFilePath;

                cacheProvider.Add(cacheKey, result, set.Files());
                return(result);
            }
            finally
            {
                if (upgraded)
                {
                    cacheLock.ExitWriteLock();
                }

                cacheLock.ExitUpgradeableReadLock();
            }
        }