示例#1
0
 /// <summary>
 /// Creates a locale instance for the specified culture.
 /// </summary>
 /// <param name="culture">The culture.</param>
 public Locale(CultureId culture)
 {
     this.languages = new LanguageCollection(culture);
     this.scripts = new ScriptCollection(culture);
     this.territories = new TerritoryCollection(culture);
     this.Culture = culture;
 }
示例#2
0
 /// <summary>
 /// Creates a locale instance for the specified culture.
 /// </summary>
 /// <param name="culture">The culture.</param>
 /// <param name="languages">An enumeration of languages.</param>
 /// <param name="scripts">An enumeration of scripts.</param>
 /// <param name="territories">An enumeration of territories.</param>
 public Locale(CultureId culture, IEnumerable<Language> languages, IEnumerable<Script> scripts, IEnumerable<Territory> territories)
 {
     this.languages = new LanguageCollection(culture, languages);
     this.scripts = new ScriptCollection(culture, scripts);
     this.territories = new TerritoryCollection(culture, territories);
     this.Culture = culture;
 }
        public void SemiColonDoesNotSplitScript()
        {
            const string     script  = "CREATE PROC Blah AS SELECT FOO; SELECT Bar;";
            ScriptCollection scripts = Script.ParseScripts(script);

            Assert.AreEqual(1, scripts.Count, "Expected no scripts since they would be empty.");
        }
        //-----------------------------

        private ScriptCollection getModified()
        {
            ScriptCollection r = new ScriptCollection();

            foreach (ScriptItem script in ScriptMgr.Items)
            {
                if (!script.IsModified)
                {
                    continue;
                }
                r.AddNotExists(script);
                script.Level = 0;
                //
                string super_name = script.GetSuper();
                if (string.IsNullOrEmpty(super_name))
                {
                    continue;
                }
                ScriptItem super_script = ScriptMgr.Get(super_name);
                while (super_script != null)
                {
                    r.AddNotExists(super_script);
                    super_script.Level = 0;
                    //
                    super_name = super_script.GetSuper();
                    if (string.IsNullOrEmpty(super_name))
                    {
                        break;
                    }
                    super_script = ScriptMgr.Get(super_name);
                }
            }
            return(r);
        }
        //=============================

        private bool checkDuplicateEventHandlers(ScriptCollection modified)
        {
            bool            r = true;
            Match           m, mx;
            MatchCollection matches;
            string          exp = @"\bEventHandler\s+([\w]+)";

            foreach (ScriptItem script in modified)
            {
                matches = Regex.Matches(script.Data, exp);
                int c = matches.Count;
                for (int i = 0; i < c; i++)
                {
                    m = matches[i];
                    for (int x = 0; x < i; x++)
                    {
                        mx = matches[x];
                        if (mx.Groups[1].Value == m.Groups[1].Value)
                        {
                            CompilerError e = new CompilerError();
                            e.Message = "Duplicate EventHandler \"" + mx.Groups[1] + "\" found in \"" + script.Name + "\"!";
                            Result.Errors.Add(e);
                            r = false;
                            break;
                        }
                    }
                }
            }
            return(r);
        }
示例#6
0
        /// <summary>
        /// Initialize setup with the xml file.
        /// </summary>
        /// <param name="xmlFile">The xml file to load</param>
        /// <returns>Pass or Fail</returns>
        public bool Initalize(string xmlFile)
        {
            if (!File.Exists(xmlFile))
            {
                ServiceManager.Services.LogService.WriteLine("\"{0}\" does not exist.", ConsoleColor.Red, xmlFile);
                return(false);
            }

            FileInfo info = new FileInfo(xmlFile);

            if (!string.Equals(info.Extension, ".xml", StringComparison.OrdinalIgnoreCase))
            {
                ServiceManager.Services.LogService.WriteLine("\"{0}\" doesn't seem to be an xml file.", ConsoleColor.Red, xmlFile);
                return(false);
            }

            // Initialize Data.
            Setup result = this.Deserialize(xmlFile);

            this.Downloads = result.Downloads;
            this.Scripts   = result.Scripts;

            // Write Details.
            ServiceManager.Services.LogService.WriteSubHeader("Details");
            ServiceManager.Services.LogService.WriteLine("\"{0}\" File(s) to download.", Downloads == null ? 0 : Downloads.Count);
            ServiceManager.Services.LogService.WriteLine("\"{0}\" Script(s) to execute.", Scripts.Count);

            return(true);
        }
示例#7
0
        protected override void ProcessResource(ScriptCollection aScripts)
        {
            var files = GetXmlFiles(Directories.Scripts);

            if (files.Any())
            {
                OnCategoryProcessing(ResourceTypes.Scripts);
                var previous = SetCurrentDirectory(Directories.Scripts);

                foreach (var file in files)
                {
                    var document = LoadXml(file);

                    if (document != null)
                    {
                        aScripts.Add(new Script()
                        {
                            Name = GetElement(document, "Name").Value,
                            ID   = GetElementValue <int>(document, "ID"),
                            Code = GetElement(document, "Code").Value
                        });
                    }

                    OnAbortProcessingCallback();
                }

                OnCategoryProcessed(ResourceTypes.Scripts);
                SetCurrentDirectory(previous);
            }
        }
示例#8
0
        public void SimpleTest() {
            ScriptCollection coll = new ScriptCollection(new ScriptEnvironment {
                RelativePathRoot="c:/",
                 LibraryPath=pathList, 
                 MapPath = MapPath
            });

        }
示例#9
0
 public static void StartClientsideScripts(ScriptCollection scripts)
 {
     if (scripts.ClientsideScripts == null)
     {
         return;
     }
     JavascriptHook.StartScripts(scripts);
 }
        public void CanParseSuccessiveGoStatements()
        {
            const string     script  = @"GO
GO";
            ScriptCollection scripts = Script.ParseScripts(script);

            Assert.AreEqual(0, scripts.Count, "Expected no scripts since they would be empty.");
        }
        public void CanParseSimpleScript()
        {
            string           script  = "Test" + Environment.NewLine + "go";
            ScriptCollection scripts = Script.ParseScripts(script);

            Assert.AreEqual(1, scripts.Count);
            Assert.AreEqual("Test", scripts[0].ScriptText);
        }
示例#12
0
 public void SimpleTest()
 {
     ScriptCollection coll = new ScriptCollection(new ScriptEnvironment {
         RelativePathRoot = "c:/",
         LibraryPath      = pathList,
         MapPath          = MapPath
     });
 }
        public void AddRangeIncrementsScriptCountWhenAddingAScript()
        {
            ScriptCollection scripts = Script.ParseScripts("/* Test */");

            Assert.AreEqual(1, scripts.Count);
            scripts.AddRange(new[] { new Script("test"), new Script("test2") });
            Assert.AreEqual(3, scripts.Count);
        }
        /// <summary>
        /// Gets a script using the provided <paramref name="key"/>.
        /// </summary>
        /// <param name="key">The key referencing the SQL script.</param>
        /// <param name="param">An optional collection of parameters to be transformed into the SQL script.</param>
        /// <returns>A transformed SQL script from this collection.</returns>
        /// <exception cref="ScriptNotFoundException" />
        public string GetScriptSql(string key, object param = null)
        {
            if (!ScriptCollection.TryGetValue(key, out string sql))
            {
                throw new ScriptNotFoundException(key);
            }

            return(OnTransform(sql, param));
        }
        public void CanParseCommentBeforeGoStatement()
        {
            const string     script  = @"SELECT FOO
/*TEST*/ GO
BAR";
            ScriptCollection scripts = Script.ParseScripts(script);

            Assert.AreEqual(2, scripts.Count);
        }
        public void CanParseGoWithDashDashCommentAfter()
        {
            const string     script  = @"SELECT * FROM foo;
 GO --  Hello Phil
CREATE PROCEDURE dbo.Test AS SELECT * FROM foo";
            ScriptCollection scripts = Script.ParseScripts(script);

            Assert.AreEqual(2, scripts.Count);
        }
        public void CanParseQuotedCorrectly()
        {
            const string script = @"INSERT INTO #Indexes
	EXEC sp_helpindex 'dbo.subtext_URLs'"    ;

            ScriptCollection scripts = Script.ParseScripts(script);

            Assert.AreEqual(script, scripts[0].ScriptText, "Script text should not be modified");
        }
        public void CanParseCommentWithQuoteChar()
        {
            const string     script  = @"/* Add the Url column to the subtext_Log table if it doesn't exist */
	ADD [Url] VARCHAR(255) NULL
GO
		AND		COLUMN_NAME = 'BlogGroup') IS NULL"                ;
            ScriptCollection scripts = Script.ParseScripts(script);

            Assert.AreEqual(2, scripts.Count);
        }
        public void CanParseDashDashCommentWithQuoteChar()
        {
            const string     script  = @"-- Add the Url column to the subtext_Log table if it doesn't exist
SELECT * FROM BLAH
GO
PRINT 'FOO'";
            ScriptCollection scripts = Script.ParseScripts(script);

            Assert.AreEqual(2, scripts.Count);
        }
示例#20
0
        protected virtual List<ParsingEvent> SerializeScript(Script script)
        {
            // Wrap script in a ScriptCollection to properly handle errors
            var scriptCollection = new ScriptCollection { script };

            // Serialize with Yaml layer
            var parsingEvents = new List<ParsingEvent>();
            YamlSerializer.Serialize(new ParsingEventListEmitter(parsingEvents), scriptCollection, typeof(ScriptCollection));
            return parsingEvents;
        }
        public void CanParseLineEndingInDashDashComment()
        {
            const string     script  = @"SELECT * FROM BLAH -- Comment
GO
FOOBAR
GO";
            ScriptCollection scripts = Script.ParseScripts(script);

            Assert.AreEqual(2, scripts.Count);
        }
示例#22
0
 public static ScriptCollection ParseScripts(string fullScriptText)
 {
     ScriptCollection scripts = new ScriptCollection(fullScriptText);
     ScriptSplitter splitter = new ScriptSplitter(fullScriptText);
     foreach (string str in splitter)
     {
         scripts.Add(new Script(str));
     }
     return scripts;
 }
示例#23
0
        public MainWindow()
        {
            InitializeComponent();
            this.ExtendGlassHook();
            ScriptList            = new ScriptCollection();
            scriptBox.DataContext = ScriptList;

            Log(LogLevel.Info, "Initialized SCPT Extractor version 0.4 by NoFaTe");
            Log(LogLevel.Info, "Special thanks to 'SWTOR Fan' for figuring out the file format.");
        }
        public void ParseScriptParsesCorrectly()
        {
            const string     script  = @"SET QUOTED_IDENTIFIER OFF 
-- Comment
Go
		
SET ANSI_NULLS ON 


GO

GO

SET ANSI_NULLS ON 


CREATE TABLE [<username,varchar,dbo>].[blog_Gost] (
	[HostUserName] [nvarchar] (64) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
	[Password] [nvarchar] (64) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
	[Salt] [nvarchar] (32) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
	[DateCreated] [datetime] NOT NULL
) ON [PRIMARY]
gO

";
            ScriptCollection scripts = Script.ParseScripts(script);

            Assert.AreEqual(3, scripts.Count, "This should parse to three scripts.");
            for (int i = 0; i < scripts.Count; i++)
            {
                Script sqlScript = scripts[i];
                Assert.IsFalse(sqlScript.ScriptText.StartsWith("GO"), "Script '" + i + "' failed had a GO statement");
            }

            string expectedThirdScriptBeginning = "SET ANSI_NULLS ON "
                                                  + Environment.NewLine
                                                  + Environment.NewLine
                                                  + Environment.NewLine +
                                                  "CREATE TABLE [<username,varchar,dbo>].[blog_Gost]";

            Assert.AreEqual(expectedThirdScriptBeginning,
                            scripts[2].OriginalScriptText.Substring(0, expectedThirdScriptBeginning.Length),
                            "Script not parsed correctly");

            scripts.TemplateParameters.SetValue("username", "haacked");

            expectedThirdScriptBeginning = "SET ANSI_NULLS ON "
                                           + Environment.NewLine
                                           + Environment.NewLine
                                           + Environment.NewLine + "CREATE TABLE [haacked].[blog_Gost]";

            Assert.AreEqual(expectedThirdScriptBeginning,
                            scripts[2].ScriptText.Substring(0, expectedThirdScriptBeginning.Length),
                            "Script not parsed correctly");
        }
        public void CanParseNestedComments()
        {
            const string     script  = @"/*
select 1
/* nested comment */
go
delete from users
-- */";
            ScriptCollection scripts = Script.ParseScripts(script);

            Assert.AreEqual(1, scripts.Count, "This contains a comment and no scripts.");
        }
        public ScriptAnalyseWindow(ScriptCollection scriptFileCollection)
        {
            InitializeComponent();
            _scriptFileCollection = scriptFileCollection;
            List <string> lines = ParseScripts();

            foreach (string line in lines)
            {
                richTextBox1.AppendText(line + "\n");
            }

            HashSet <string> dictionary = CreateDictionary(lines);

            richTextBox1.AppendText("\nDictionary( " + dictionary.Count + " Symbols ):");
            foreach (string characters in dictionary)
            {
                richTextBox1.AppendText(characters + "\n");
            }

            string[] unsortedDictionary = dictionary.ToArray();
            string[] sortedDictionary   = dictionary.OrderBy(entry => entry).ToArray();

            if (ApplicationState.Instance.ProjectFile != null)
            {
                _modifiedImage = ApplicationState.Instance.ProjectFile.ModifiedImage;
            }

            if (_modifiedImage == null)
            {
                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.Filter = "Conan Font File|FONT.BIN";

                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    _fontFile = new FONTFile(openFileDialog.FileName);
                }
            }
            else
            {
                PKNFile  graphPkn = _modifiedImage.PKNFiles?.Find(pkn => pkn.Name == "GRAPH");
                BaseFile fontFile = graphPkn?.Files?.Find(file => file.FileName == "FONT.BIN");
                if (fontFile == null)
                {
                    return;
                }

                _fontFile = new FONTFile(fontFile.FilePath);
            }
            _fontFile.Load();

            _fontFile.Generate(unsortedDictionary, new Font("ConanFont", 12));
            _fontFile.Save();
        }
示例#27
0
        public void ScriptDoesNotStoreDuplicateParameters()
        {
            string scriptText = "SELECT TOP <name, int, 0> * FROM Somewhere"
                                + Environment.NewLine
                                + "GO"
                                + Environment.NewLine
                                + "SELECT TOP <name, int, 1> * FROM SomewhereElse";
            ScriptCollection scripts = Script.ParseScripts(scriptText);

            Assert.AreEqual(2, scripts.Count, "Did not parse the script.");
            Assert.AreEqual(1, scripts.TemplateParameters.Count, "did not merge or parse the template params.");
        }
示例#28
0
        public void PowershellScript_ResultFail()
        {
            Script script = new Script();

            script.Name = "Powershell test script.";

            // The powershell script.
            script.Executable = new Executable()
            {
                Path = Utilities.GetIncludedFile("Scripts/PowershellTest_ScriptFail.ps1")
            };

            // Exit Codes
            ExitCodeCollection exitCollection = new ExitCodeCollection();

            exitCollection.Add(new ExitCode()
            {
                Value = 0, Message = "Success", IsSuccess = true
            });
            exitCollection.Add(new ExitCode()
            {
                Value = 1, Message = "Failure"
            });

            // Add all elements into the single script file.
            script.ExitCodes = exitCollection;

            // Add the single script above into a collection of scripts.
            ScriptCollection scriptCollection = new ScriptCollection();

            scriptCollection.Add(script);

            // No Downloads.
            DownloadCollection downloadCollection = new DownloadCollection();

            // Add the 2 main elements, the scripts to run and the downloads to download.
            Setup setup = new Setup();

            setup.Scripts   = scriptCollection;
            setup.Downloads = downloadCollection;


            int exitCode = -1;

            if (setup.Initalize())
            {
                exitCode = setup.Execute();
            }

            // The exit code should be 1, since the script did not match IsSuccess ExitCode.
            Assert.IsTrue(exitCode == 1);
        }
示例#29
0
        protected virtual List <ParsingEvent> SerializeScript(Script script)
        {
            // Wrap script in a ScriptCollection to properly handle errors
            var scriptCollection = new ScriptCollection {
                script
            };

            // Serialize with Yaml layer
            var parsingEvents = new List <ParsingEvent>();

            YamlSerializer.Serialize(new ParsingEventListEmitter(parsingEvents), scriptCollection, typeof(ScriptCollection));
            return(parsingEvents);
        }
示例#30
0
        public void OptionParsing()
        {
            PathList list = new PathList();

            list.Add("~/libs");
            list.Add("~/libs2");

            var coll = new ScriptCollection(list, TestUtil.MapPath);

            coll.AddPath("~/scripts/test-script-3.js");

            Assert.AreEqual(coll.Count, 1);
        }
示例#31
0
        public void OptionParsing()
        {

            PathList list = new PathList();
            list.Add("~/libs");
            list.Add("~/libs2");

            var coll = new ScriptCollection(list, TestUtil.MapPath);
            coll.AddPath("~/scripts/test-script-3.js");

            Assert.AreEqual(coll.Count, 1);

        }
        public void MultiLineQuoteShouldNotBeSplitByGoKeyword()
        {
            string script = "PRINT '" + Environment.NewLine
                            + "GO" + Environment.NewLine
                            + "SELECT * FROM BLAH" + Environment.NewLine
                            + "GO" + Environment.NewLine
                            + "'";

            ScriptCollection scripts = Script.ParseScripts(script);

            UnitTestHelper.AssertStringsEqualCharacterByCharacter(script, scripts[0].ScriptText);
            Assert.AreEqual(1, scripts.Count, "expected only one script");
        }
        public void MultiLineQuoteShouldNotIgnoreDoubleQuote()
        {
            string script = "PRINT '" + Environment.NewLine
                            + "''" + Environment.NewLine
                            + "GO" + Environment.NewLine
                            + "/*" + Environment.NewLine
                            + "GO"
                            + "'";

            ScriptCollection scripts = Script.ParseScripts(script);

            Assert.AreEqual(1, scripts.Count);
            UnitTestHelper.AssertStringsEqualCharacterByCharacter(script, scripts[0].ScriptText);
        }
示例#34
0
 public GMXFile()
 {
     Sprites      = new SpriteCollection();
     Sound        = new SoundCollection();
     Backgrounds  = new BackgroundCollection();
     Paths        = new PathCollection();
     Scripts      = new ScriptCollection();
     Fonts        = new FontCollection();
     TimeLines    = new TimeLineCollection();
     Objects      = new ObjectCollection();
     Rooms        = new RoomCollection();
     Includes     = new IncludedFileCollection();
     Configs      = new ConfigCollection();
     ResourceTree = new ResourceTree();
 }
示例#35
0
        public BaseObject()
        {
            position      = new Vector3(0, 0, 0);
            rotationX     = rotationY = rotationZ = 0;
            eulerRotation = new Vector3(rotationX, rotationY, rotationZ);
            scale         = Vector3.One;
            world         = Matrix.CreateScale(scale) * Matrix.CreateFromYawPitchRoll(MathHelper.ToRadians(rotationY), MathHelper.ToRadians(rotationX), MathHelper.ToRadians(rotationZ)) * Matrix.CreateTranslation(position);
            world.Decompose(out scale, out rotation, out position);

            scripts = new ScriptCollection();

            PhysicsShapeKind = EditorModel.PhysicsShapeKind.BoxShape;

            OnRotationChanged(this, null);
        }
        public void SetUp()
        {
            settings = new Mock <ISettings>();

            first  = new Mock <IScriptConfig>();
            second = new Mock <IScriptConfig>();
            third  = new Mock <IScriptConfig>();

            subject = new ScriptCollection
            {
                first.Object,
                second.Object,
                third.Object
            };
        }
示例#37
0
        public void OptionParsing()
        {

            PathList list = new PathList();
            list.Add("~/scripts/libs");
            list.Add("~/scripts/libs2");

            var coll = new ScriptCollection(new ScriptEnvironment {
                RelativePathRoot= "/",
                LibraryPath=  list, 
                MapPath = TestUtil.MapPath
            });

            coll.AddPath("~/scripts/test-script-3.js");

            Assert.AreEqual(coll.Count, 1);

        }
 public GameMakerFile()
 {
     Sprites = new SpriteCollection();
       Sounds = new SoundCollection();
       Backgrounds = new BackgroundCollection();
       Paths = new PathCollection();
       Scripts = new ScriptCollection();
       Fonts = new FontCollection();
       TimeLines = new TimeLineCollection();
       Objects = new ObjectCollection();
       Rooms = new RoomCollection();
       Triggers = new TriggerCollection();
       Includes = new IncludedFileCollection();
       Constants = new ConstantCollection();
       Information = new GameInformation();
       Settings = new GameSettings();
       ResourceTree = new ResourceTree();
 }
示例#39
0
        public ScriptComponent()
        {
            Scripts = new ScriptCollection();
            Scripts.CollectionChanged += (sender, args) =>
            {
                var script = (Script)args.Item;
                if (script == null)
                    return;

                switch (args.Action)
                {
                    case NotifyCollectionChangedAction.Add:
                        script.ScriptComponent = this;
                        break;
                    case NotifyCollectionChangedAction.Remove:
                        script.ScriptComponent = null;
                        break;
                }
            };
        }
示例#40
0
        public ScriptCollection LoadScript( string file )
        {
            myLogger.Debug( "Processing starter script: {0}", file );

            LoadDependentAssemblies( file );

            var reader = new ValidatingXamlReader();
            var obj = reader.Read<object>( file );

            if( obj is Script )
            {
                var col = new ScriptCollection();
                col.Scripts.Add( ( Script )obj );
                return col;
            }
            else if( obj is ScriptCollection )
            {
                return ( ScriptCollection )obj;
            }
            else
            {
                throw new NotSupportedException( "Unknown root element: " + obj.GetType() );
            }
        }
示例#41
0
        /// <summary>
        /// Resolve all script dependencies in the bound CQ document. Scripts that cotain a "data-
        /// location='head'" attribute will be moved to the head.
        /// </summary>
        ///
        /// <param name="doc">
        /// The document to resolve.
        /// </param>

        public void ResolveScriptDependencies(CQ doc)
        {
           

            string scriptSelector = "script[src][type='text/javascript'], link[type='text/css']";
                
            //+ (Options.HasFlag(ViewEngineOptions.ProcessAllScripts) ?
            //        "" : ".csquery-script")
            //        + "[src]";

            // Filter out non-relative paths (remote URLs)
            CQ scripts = doc[scriptSelector].Filter(item =>
            {
                return !PathList.IsRemoteUrl(item.UrlSource());
            });



            if (scripts.Length == 0)
            {
                return;
            }
            
            // move scripts to head as needed first

            var toMove = scripts.Filter("[data-location='head']");
            var head = doc["head"];

            if (toMove.Length > 0)
            {
                
                foreach (var item in toMove)
                {
                    if (item.ParentNode != head)
                    {
                        head.Append(item);
                    }
                }
            }

            // resolve dependencies

            ScriptCollection coll = new ScriptCollection(LibraryPath,MapPath);
            coll.NoCache = Options.HasFlag(ViewEngineOptions.NoCache);
            coll.IgnoreErrors = Options.HasFlag(ViewEngineOptions.IgnoreMissingScripts);

            // identify the insertion point for the script bundle
            var firstScriptEl = coll.AddFromCq(scripts);
            var firstScript = firstScriptEl == null ? 
                head.Children().First() : 
                firstScriptEl.Cq();

            string bundleUrl;
            List<ScriptRef> dependencies = coll.GetDependencies()
                .Where(item=>!coll.Contains(item))
                .ToList();

            // find the first script with dependencies
            

            // Now add scripts directly for depenencies marked as NoCombine.

            foreach (var item in dependencies.Where(item => item.NoCombine))
            {
                firstScript.Before(GetScriptHtml(item.Path, item.ScriptHash));
            }

            // Before creating the bundle, remove any duplicates of the same script on the page
            
            


            bool hasBundle = Bundles.TryGetValue(coll, out bundleUrl);

            if (hasBundle) {
                // when nocache is set, we will regenerate the bundle, but not change the script ID. The v=
                // flag will be changed by BundleTable. 
                if (Options.HasFlag(ViewEngineOptions.NoCache))
                {
                    string removeUrl = "~" + bundleUrl.Before("?");
                    BundleTable.Bundles.Remove(BundleTable.Bundles.GetBundleFor(removeUrl));
                    hasBundle = false;
                    ScriptID++;
                    // 
                    //var bundleList = BundleTable.Bundles.ToList();
                    //BundleTable.Bundles.Clear();
                    //BundleTable.Bundles.ResetAll();
                    //BundleTable.EnableOptimizations = false;

                    //foreach (var oldBundle in bundleList)
                    //{
                    //    BundleTable.Bundles.Add(oldBundle);
                    //}

                }
            }
            else
            {
                ScriptID++;
            }

            if (!hasBundle) {

                string bundleAlias = "~/cqbundle" + ScriptID;
                var bundle = GetScriptBundle(bundleAlias);

                var activeDependencies = dependencies.Where(item => !item.NoCombine);
                foreach (var item in activeDependencies)
                {
                    bundle.Include(item.Path);
                }

               
                BundleTable.Bundles.Add(bundle);
                if (HttpContext.Current != null)
                {
                    bundleUrl = BundleTable.Bundles.ResolveBundleUrl(bundleAlias, true);
                }
                else
                {
                    bundleUrl = bundleAlias + "_no_http_context";
                }
                Bundles[coll] = bundleUrl;
            }

            var scriptPlaceholder = scripts.First();

          

            // add bundle after all noncombined scripts

            firstScript.Before(GetScriptHtml(bundleUrl));

               
            
        }
示例#42
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SqlScriptRunner"/> class.
 /// </summary>
 /// <param name="scripts">The scripts.</param>
 public SqlScriptRunner(ScriptCollection scripts)
 {
     this.scripts = scripts;
 }
示例#43
0
        public void Test() {
            ScriptCollection coll = new ScriptCollection(pathList, MapPath);

        }
示例#44
0
 /// <summary>
 /// Executes the script.
 /// </summary>
 /// <remarks>
 /// Use script.Execute(transaction) to do the work. We will also pull the
 /// status of our script exection from here.
 /// </remarks>
 /// <param name="scripts">The collection of scripts to execute.</param>
 /// <param name="transaction">The current transaction.</param>
 public static void ExecuteScript(ScriptCollection scripts, SqlTransaction transaction)
 {
     ExecuteScript(scripts, transaction, null);
 }
示例#45
0
 /// <summary>
 /// Executes the script.
 /// </summary>
 /// <remarks>
 /// Use script.Execute(transaction) to do the work. We will also pull the
 /// status of our script exection from here.
 /// </remarks>
 /// <param name="scripts">The collection of scripts to execute.</param>
 /// <param name="transaction">The current transaction.</param>
 /// <param name="dbUserName">Name of the DB owner.</param>
 public static void ExecuteScript(ScriptCollection scripts, SqlTransaction transaction, string dbUserName)
 {
     SqlScriptRunner scriptRunner = new SqlScriptRunner(scripts);
     if (!string.IsNullOrEmpty(dbUserName))
         scriptRunner.TemplateParameters.SetValue("dbUser", dbUserName);
     scriptRunner.Execute(transaction);
 }
示例#46
0
        /// <summary>
        /// Resolve all script dependencies in the bound CQ document. Scripts that cotain a "data-
        /// location='head'" attribute will be moved to the head.
        /// </summary>
        ///
        /// <param name="doc">
        /// The document to resolve.
        /// </param>

        public void ResolveScriptDependencies(CQ doc)
        {
           

            string scriptSelector = "script[src][type='text/javascript'], script[src]:not([type]), link[type='text/css']";

            CQ scripts = doc[scriptSelector];

            if (scripts.Length == 0)
            {
                return;
            }
            
            // move scripts first
            // TODO: Optimize using a query caching mechanism so
                
            foreach (var item in scripts.Filter("[data-moveto]"))
            {
                var target = doc.Select(item["data-moveto"]);
                if (target.Length>0) {
                    target.First().Append(item);
                    item.RemoveAttribute("data-moveto");
                }
            }
            

            // resolve dependencies

            ScriptCollection coll = new ScriptCollection(ScriptEnvironment);
            coll.Options= Options;

            // identify the insertion point for the script bundle. AddFromCq returns the first script with dependencies,
            // so scripts should be added right before that one. Otherwise they should be added
            // at the end of head.
            
            var firstScriptEl = coll.AddFromCq(scripts);
            CQ firstScript=null;

            if (firstScriptEl != null)
            {
                firstScript = firstScriptEl.Cq();
            }
           
            string bundleUrl;
            List<ScriptRef> dependencies = coll.GetDependencies()
                .Where(item=>!coll.Contains(item))
                .ToList();

            // Now add scripts directly for dependencies marked as NoCombine.

            
            var inlineScripts = Options.HasFlag(ViewEngineOptions.NoBundle) ?
                dependencies :
                dependencies.Where(item => item.NoCombine);


            foreach (var item in inlineScripts)
            {
                var script = GetScriptHtml(item.Path, item.ScriptHash);
                if (firstScript != null)
                {
                    firstScript.Before(script);
                }
                else
                {
                    firstScript = script;
                    doc["body"].Append(script);
                }
           }

            // Before creating the bundle, remove any duplicates of the same script on the page


            if (!Options.HasFlag(ViewEngineOptions.NoBundle))
            {

                bool hasBundle = Bundles.TryGetValue(coll, out bundleUrl);

                if (hasBundle)
                {
                    // when nocache is set, we will regenerate the bundle, but not change the script ID. The v=
                    // flag will be changed by BundleTable. 
                    
                    if (Options.HasFlag(ViewEngineOptions.NoCache))
                    {
                        string removeUrl = "~" + bundleUrl.Before("?");
                        BundleTable.Bundles.Remove(BundleTable.Bundles.GetBundleFor(removeUrl));
                        hasBundle = false;
                        ScriptID++;
                        
                        // this code attempts to un-cache the bundle, it doesn't work.
                        // leaving it here until some permanent solution is found as a reminder
                        // 
                        // http://stackoverflow.com/questions/12317391/how-to-force-bundlecollection-to-flush-cached-script-bundles-in-mvc4
                        // 
                        //var bundleList = BundleTable.Bundles.ToList();
                        //BundleTable.Bundles.Clear();
                        //BundleTable.Bundles.ResetAll();
                        //BundleTable.EnableOptimizations = false;

                        //foreach (var oldBundle in bundleList)
                        //{
                        //    BundleTable.Bundles.Add(oldBundle);
                        //}

                    }
                }
                else
                {
                    ScriptID++;
                }

                if (!hasBundle)
                {
                    var activeDependencies = dependencies.Where(item => !item.NoCombine).ToList();
                    if (activeDependencies.Count > 0)
                    {
                        string bundleAlias = "~/cqbundle" + ScriptID;
                        var bundle = GetScriptBundle(bundleAlias);



                        foreach (var item in activeDependencies)
                        {
                            bundle.Include(item.Path);
                        }


                        BundleTable.Bundles.Add(bundle);
                        if (HttpContext.Current != null)
                        {
                            bundleUrl = BundleTable.Bundles.ResolveBundleUrl(bundleAlias, true);
                        }
                        else
                        {
                            bundleUrl = bundleAlias + "_no_http_context";
                        }
                        Bundles[coll] = bundleUrl;
                    }
                }

                var scriptPlaceholder = scripts.First();



                // add bundle after all noncombined scripts
                if (!String.IsNullOrEmpty(bundleUrl))
                {
                    firstScript.Before(GetScriptHtml(bundleUrl));
                }
            }
               
            
        }
示例#47
0
 protected abstract void ProcessResource( ScriptCollection aScripts );
示例#48
0
        protected virtual Script DeserializeScript(ReloadedScriptEntry reloadedScript)
        {
            var eventReader = new EventReader(new MemoryParser(reloadedScript.YamlEvents));
            var scriptCollection = new ScriptCollection();

            // Use the newly created script during second pass for proper cycle deserialization
            var newScript = ((ReloadedScriptEntryLive)reloadedScript).NewScript;
            if (newScript != null)
                scriptCollection.Add(newScript);

            // Try to create script first
            YamlSerializer.Deserialize(eventReader, scriptCollection, typeof(ScriptCollection));
            var script = scriptCollection.Count == 1 ? scriptCollection[0] : null;
            return script;
        }
示例#49
0
        protected override List<ParsingEvent> SerializeScript(Script script)
        {
            // Wrap script in a ScriptCollection to properly handle errors
            var scriptCollection = new ScriptCollection { script };

            // Serialize with Yaml layer
            var parsingEvents = new List<ParsingEvent>();
            // We also want to serialize live scripting variables
            var serializerContextSettings = new SerializerContextSettings { MemberMask = DataMemberAttribute.DefaultMask | Script.LiveScriptingMask };
            YamlSerializer.Serialize(new ParsingEventListEmitter(parsingEvents), scriptCollection, typeof(ScriptCollection), serializerContextSettings);
            return parsingEvents;
        }
示例#50
0
        protected override void ProcessResource( ScriptCollection aScripts )
        {
            if ( !aScripts.Any() )
            return;

              OnCategoryProcessing( ResourceTypes.Scripts );
              Directory.CreateDirectory( Directories.Scripts );
              var previous = SetCurrentDirectory( Directories.Scripts );

              foreach ( var script in aScripts ) {
            var document =
              new XElement( "Script",
            CreateIndexedResourceNodes( script ),
            new XElement( "Code", EscapeText( script.Code ) )
              );

            OnResourceProcessed( script.Name );
            SaveDocument( document, SafeResourceFilename( script ) + ".xml" );
              }

              OnCategoryProcessed( ResourceTypes.Scripts );
              SetCurrentDirectory( previous );
        }