/// <summary>
        /// Generates a custom file name for the sprite assembly file, based off of the images being used to make the sprite.
        /// </summary>
        /// <param name="inputImages">collection of images to be sprited</param>
        /// <param name="targetFolder">folder path the filename should be in.</param>
        /// <returns>the name of the file, without extention</returns>
        private static string GenerateAssembleFileName(IEnumerable <InputImage> inputImages, string targetFolder)
        {
            var uniqueKey = WebGreaseContext.ComputeContentHash(string.Join("|", inputImages.Select(i => i.AbsoluteImagePath)));

            // the filename is the hash code of the joined file names (to prevent a large sprite from going over the 260 limit of paths).
            return(Path.GetFullPath(Path.Combine(targetFolder, uniqueKey)));
        }
Exemple #2
0
        public void ResourcePivotResourcesTmxSdkTest1()
        {
            var sourceDirectory = Path.Combine(TestDeploymentPaths.TestDirectory, @"WebGrease.Tests\ResourcesResolutionActivityTest\ResourcePivotTest1");

            LogExtendedError logExtendedError = (subcategory, code, keyword, file, number, columnNumber, lineNumber, endColumnNumber, message) => Assert.Fail(message);
            var             errors            = new List <string>();
            Action <string> logErrorMessage   = errors.Add;
            LogError        logError          = (exception, message, name) => errors.Add(message);

            var start = DateTimeOffset.UtcNow;
            var webGreaseConfiguration = new WebGreaseConfiguration(
                new FileInfo(Path.Combine(sourceDirectory, "LandingPage.xml")),
                "Release",
                sourceDirectory,
                Path.Combine(sourceDirectory, "output1"),
                Path.Combine(sourceDirectory, "logs1"),
                Path.Combine(sourceDirectory, "temp1"),
                sourceDirectory);

            var webGreaseContext = new WebGreaseContext(webGreaseConfiguration, null, null, logExtendedError, logErrorMessage, logError);

            new EverythingActivity(webGreaseContext).Execute();
            var time1 = DateTimeOffset.UtcNow - start;

            start = DateTimeOffset.UtcNow;

            var webGreaseConfiguration2 = new WebGreaseConfiguration(
                new FileInfo(Path.Combine(sourceDirectory, "LandingPage2.xml")),
                "Release",
                sourceDirectory,
                Path.Combine(sourceDirectory, "output2"),
                Path.Combine(sourceDirectory, "logs2"),
                Path.Combine(sourceDirectory, "temp2"),
                sourceDirectory);

            var webGreaseContext2 = new WebGreaseContext(webGreaseConfiguration2, null, null, logExtendedError, logErrorMessage, logError);

            new EverythingActivity(webGreaseContext2).Execute();

            if (errors.Count > 0)
            {
                foreach (var error in errors)
                {
                    Trace.WriteLine("Error: " + error);
                }

                Assert.Fail("Errors occurred, see test output for details.");
            }

            var time2 = DateTimeOffset.UtcNow - start;

            Trace.WriteLine(string.Format("Parsed: {0}ms, Cloned: {1}ms", time1.TotalMilliseconds, time2.TotalMilliseconds));

            Func <string, string> logFileChange = logFileContent => logFileContent.Replace("/output1/", "/output2/");

            CacheTests.DirectoryMatch(Path.Combine(sourceDirectory, "output1"), Path.Combine(sourceDirectory, "output2"), logFileChange);
            CacheTests.DirectoryMatch(Path.Combine(sourceDirectory, "output2"), Path.Combine(sourceDirectory, "output1"), logFileChange);
        }
Exemple #3
0
        private static string ProcessSass(string content, string filename, LogExtendedError logExtendedError = null)
        {
            var sassPreprocessingEngine = new SassPreprocessingEngine();
            var webGreaseContext        = new WebGreaseContext(new WebGreaseConfiguration(), logInformation: null, logExtendedWarning: null, logError: null, logExtendedError: logExtendedError);

            File.WriteAllText(filename, content);
            var processSassResult = sassPreprocessingEngine.Process(webGreaseContext, ContentItem.FromFile(filename), null, false);

            return(processSassResult != null
                ? processSassResult.Content
                : null);
        }
Exemple #4
0
 /// <summary>The handle other content type cache sections.</summary>
 /// <param name="context">The context.</param>
 /// <param name="parentCacheSection">The session cache section.</param>
 /// <param name="sessionCacheData">The session cache data.</param>
 /// <param name="contentTypeSectionId">The content type section id.</param>
 private void HandleOtherContentTypeCacheSections(IWebGreaseContext context, ICacheSection parentCacheSection, SessionCacheData sessionCacheData, string[] contentTypeSectionId)
 {
     if (sessionCacheData != null)
     {
         foreach (var configType in sessionCacheData.ConfigTypes.Keys.Where(ct => !ct.Equals(this.ConfigType, StringComparison.OrdinalIgnoreCase)))
         {
             // TODO: Do a better job at touching all the files used by the last build from another config type.
             var otherContentTypeCacheSection = CacheSection.Begin(context, WebGreaseContext.ToStringId(contentTypeSectionId), sessionCacheData.GetConfigTypeUniqueKey(configType), parentCacheSection);
             otherContentTypeCacheSection.Save();
         }
     }
 }
Exemple #5
0
        /// <summary>Execute a single config file.</summary>
        /// <param name="sessionContext">The session context.</param>
        /// <param name="configFile">The config file.</param>
        /// <param name="activity">The activity</param>
        /// <param name="fileType">The file types</param>
        /// <param name="measure">If it should measure.</param>
        /// <param name="fullPathToConfigFiles">The full Path To Config Files.</param>
        /// <returns>The success.</returns>
        private static Tuple <bool, int> ExecuteConfigFile(IWebGreaseContext sessionContext, string configFile, ActivityName activity, FileTypes fileType, bool measure, string fullPathToConfigFiles)
        {
            var configFileStart = DateTimeOffset.Now;

            var configFileInfo = new FileInfo(configFile);

            // Creates the context specific to the configuration file
            var fileContext = new WebGreaseContext(sessionContext, configFileInfo);

            var configFileSuccess = true;
            var fileSets          = GetFileSets(fileContext.Configuration, fileType).ToArray();

            if (fileSets.Length > 0 || (fileType.HasFlag(FileTypes.Image) && fileContext.Configuration.ImageDirectoriesToHash.Any()))
            {
                var configFileContentItem = ContentItem.FromFile(configFileInfo.FullName);
                configFileSuccess = sessionContext
                                    .SectionedActionGroup(fileType.ToString(), SectionIdParts.WebGreaseBuildTask, SectionIdParts.ConfigurationFile)
                                    .MakeCachable(configFileContentItem, new { activity, fileContext.Configuration }, activity == ActivityName.Bundle) // Cached action can only be skipped when it is the bundle activity, otherwise don't.
                                    .Execute(configFileCacheSection =>
                {
                    fileContext.Configuration.AllLoadedConfigurationFiles.ForEach(configFileCacheSection.AddSourceDependency);

                    var success = true;
                    fileContext.Log.Information("Activity Start: [{0}] for [{1}] on configuration file \"{2}\"".InvariantFormat(activity, fileType, configFile), MessageImportance.High);
                    switch (activity)
                    {
                    case ActivityName.Bundle:
                        // execute the bundle pipeline
                        var bundleActivity = new BundleActivity(fileContext);
                        success           &= bundleActivity.Execute(fileSets);
                        break;

                    case ActivityName.Everything:
                        // execute the full pipeline
                        var everythingActivity = new EverythingActivity(fileContext);
                        success &= everythingActivity.Execute(fileSets, fileType);
                        break;
                    }

                    if (success && measure)
                    {
                        var configReportFile = Path.Combine(sessionContext.Configuration.ReportPath, (configFileInfo.Directory != null ? configFileInfo.Directory.Name + "." : string.Empty) + activity.ToString() + "." + fileType + "." + configFileInfo.Name);
                        fileContext.Measure.WriteResults(configReportFile, configFileInfo.FullName, configFileStart);
                    }

                    fileContext.Log.Information("Activity End: [{0}] for [{1}] on configuration file \"{2}\"".InvariantFormat(activity, fileType, configFile), MessageImportance.High);
                    return(success);
                });
            }

            return(Tuple.Create(configFileSuccess, fileSets.Length));
        }
Exemple #6
0
        public void TestWgInclude1()
        {
            var includeFile      = Path.Combine(TestDeploymentPaths.TestDirectory, @"WebGrease.Tests\IncludeTest\Test1\test1.js");
            var ie               = new IncludePreprocessingEngine();
            var webGreaseContext = new WebGreaseContext(new WebGreaseConfiguration()
            {
                DestinationDirectory = TestDeploymentPaths.TestDirectory
            });
            var result = ie.Process(webGreaseContext, ContentItem.FromFile(includeFile, includeFile.MakeRelativeToDirectory(TestDeploymentPaths.TestDirectory)), new PreprocessingConfig(), false).Content;

            Assert.IsTrue(result.Contains("included1();"));
            Assert.IsTrue(result.Contains("included2();"));
            Assert.IsTrue(result.Contains("included3();"));
            Assert.IsTrue(result.Contains("included4();"));
            Assert.IsFalse(result.Contains("included5();"));
        }
Exemple #7
0
        public void MainActivityDebugIntegrationTest()
        {
            var testSourceDirectory  = Path.Combine(TestDeploymentPaths.TestDirectory, @"WebGrease.Tests\MainActivityTest");
            var configurationFile    = Path.Combine(testSourceDirectory, @"Input\Integration\Debug\Configuration\sample1.webgrease.config");
            var sourceDirectory      = Path.Combine(testSourceDirectory, @"Input\Integration\Debug\Content");
            var destinationDirectory = Path.Combine(testSourceDirectory, @"Output\Integration\Debug\sc");
            var logsDirectory        = Path.Combine(testSourceDirectory, @"Output\Integration\Debug\logs");

            var webGreaseConfigurationRoot = new WebGreaseConfiguration(new FileInfo(configurationFile), "Debug", sourceDirectory, destinationDirectory, logsDirectory);
            var context = new WebGreaseContext(webGreaseConfigurationRoot, logInformation: null, logExtendedWarning: null, logError: LogError, logExtendedError: LogExtendedError);

            var mainActivity = new EverythingActivity(context);
            var success      = mainActivity.Execute();

            Assert.IsTrue(success);
            VerifyStatics(destinationDirectory, logsDirectory);
        }
Exemple #8
0
        public void CloningPerf1()
        {
            var            cssFile         = Path.Combine(TestDeploymentPaths.TestDirectory, @"WebGrease.Tests\CloningTests\landingPage.tmx.pc.ms.css");
            var            css             = File.ReadAllText(cssFile);
            StyleSheetNode stylesheetNode  = null;
            StyleSheetNode stylesheetNode2 = null;
            var            loopCount       = 100;

            var timer            = DateTimeOffset.Now;
            var webGreaseContext = new WebGreaseContext(new WebGreaseConfiguration());

            Parallel.For(0, loopCount, i =>
            {
                var ss = CssParser.Parse(webGreaseContext, css, false);
                if (loopCount - 1 == i)
                {
                    stylesheetNode = ss;
                }
            });

            var timeSpent1 = DateTimeOffset.Now - timer;

            timer = DateTimeOffset.Now;
            Parallel.For(0, loopCount, i =>
            {
                var ss = stylesheetNode.Accept(new NodeTransformVisitor()) as StyleSheetNode;
                if (loopCount - 1 == i)
                {
                    Assert.AreNotEqual(ss, stylesheetNode2);
                    Assert.AreNotEqual(ss, stylesheetNode);
                    stylesheetNode2 = ss;
                }
            });

            var timeSpent2 = DateTimeOffset.Now - timer;

            Assert.AreEqual(stylesheetNode2.MinifyPrint(), stylesheetNode.MinifyPrint());
            Assert.IsTrue(timeSpent2.TotalMilliseconds < timeSpent1.TotalMilliseconds / 5);
            Trace.WriteLine(string.Format("For {0} Runs, Parsed: {1}ms, Cloned: {2}ms", loopCount, timeSpent1.TotalMilliseconds, timeSpent2.TotalMilliseconds));
        }
        public void HashingAlgorithmTest()
        {
            const string Value         = "RandomValue1";
            var          valueFileName = Path.GetTempFileName();

            File.WriteAllText(valueFileName, Value);
            Assert.AreEqual(WebGreaseContext.ComputeFileHash(valueFileName), WebGreaseContext.ComputeContentHash(Value));

            File.WriteAllText(valueFileName, Value, Encoding.Default);
            Assert.AreEqual(WebGreaseContext.ComputeFileHash(valueFileName), WebGreaseContext.ComputeContentHash(Value, Encoding.Default));

            File.WriteAllText(valueFileName, Value, Encoding.UTF8);
            Assert.AreEqual(WebGreaseContext.ComputeFileHash(valueFileName), WebGreaseContext.ComputeContentHash(Value, Encoding.UTF8));
            Assert.AreNotEqual(WebGreaseContext.ComputeFileHash(valueFileName), WebGreaseContext.ComputeContentHash(Value));

            File.WriteAllText(valueFileName, Value, Encoding.UTF32);
            Assert.AreEqual(WebGreaseContext.ComputeFileHash(valueFileName), WebGreaseContext.ComputeContentHash(Value, Encoding.UTF32));
            Assert.AreNotEqual(WebGreaseContext.ComputeFileHash(valueFileName), WebGreaseContext.ComputeContentHash(Value));

            File.WriteAllText(valueFileName, Value, Encoding.Unicode);
            Assert.AreEqual(WebGreaseContext.ComputeFileHash(valueFileName), WebGreaseContext.ComputeContentHash(Value, Encoding.Unicode));
            Assert.AreNotEqual(WebGreaseContext.ComputeFileHash(valueFileName), WebGreaseContext.ComputeContentHash(Value));
        }
Exemple #10
0
 /// <summary>Initializes a new instance of the <see cref="BundleActivity"/> class.</summary>
 /// <param name="webGreaseContext">The web grease context.</param>
 public BundleActivity(WebGreaseContext webGreaseContext)
 {
     this.context = webGreaseContext;
 }
Exemple #11
0
        /// <summary>
        /// Executes the webgrease runtime.
        /// </summary>
        /// <returns>Returns a value indicating whether the run was successful or not.</returns>
        public override bool Execute()
        {
            var start = DateTimeOffset.Now;

            var activity = this.Activity.TryParseToEnum <ActivityName>();

            if (!activity.HasValue)
            {
                this.LogError("Unknown activity: {0}".InvariantFormat(this.Activity));
                return(false);
            }

            var logManager = this.CreateLogManager();

            var globalContext = this.CreateSessionContext(logManager);

            if (globalContext.Configuration.Overrides != null && globalContext.Configuration.Overrides.SkipAll)
            {
                logManager.Information("WebGrease Skipping because of SkipAll in webgrease override file.");
                return(true);
            }

            var totalSuccess = true;

            globalContext.Cache.LockedFileCacheAction(
                "{0}\r\nWebGrease Running for Configuration Folder: {1}".InvariantFormat(DateTime.UtcNow, this.ConfigurationPath),
                () =>
            {
                if (this.CleanDestination)
                {
                    globalContext.CleanDestination();
                }

                var fileTypesToExecuteParallel = this.FileType == FileTypes.All ? new[] { FileTypes.JS, FileTypes.CSS | FileTypes.Image } : new[] { this.FileType };

                if (this.CleanCache)
                {
                    globalContext.CleanCache();
                }

                if (Directory.Exists(globalContext.Configuration.IntermediateErrorDirectory))
                {
                    Directory.Delete(globalContext.Configuration.IntermediateErrorDirectory, true);
                }

                globalContext.ParallelForEach(
                    item => new[] { SectionIdParts.WebGreaseBuildTaskSession, item.ToString() },
                    fileTypesToExecuteParallel,
                    (threadContext, item, state) =>
                {
                    logManager.Information("Starting WebGrease thread for " + item);
                    var success   = this.Execute(item, activity.Value, this.ConfigurationPath, threadContext);
                    totalSuccess &= totalSuccess;
                    return(success);
                },
                    (threadContext, item) =>
                {
                    if (this.CleanCache)
                    {
                        threadContext.CleanCache(logManager);
                    }

                    return(true);
                });

                var threadedAndGroupedMeasureResults = globalContext
                                                       .ThreadedMeasureResults
                                                       .GroupBy(mr => mr.Key)
                                                       .Select(g => new Tuple <string, bool, IEnumerable <TimeMeasureResult> >(
                                                                   g.Key + (g.HasAtLeast(2) ? " - Multi-Threaded" : string.Empty),
                                                                   g.HasAtLeast(2),
                                                                   g.SelectMany(l => l.Value)
                                                                   .GroupBy(l => l.Name)
                                                                   .Select(l => new TimeMeasureResult
                {
                    IdParts  = WebGreaseContext.ToIdParts(l.Key),
                    Count    = l.Sum(c => c.Count),
                    Duration = l.Sum(c => c.Duration)
                })));

                this.FinalizeMeasure(totalSuccess, threadedAndGroupedMeasureResults, logManager, start, activity, globalContext.Configuration);

                logManager.Information("WebGrease done");
            });

            return(totalSuccess && !this.hasErrors);
        }