Ejemplo n.º 1
0
        void RegisterScript(ref ScriptEntry scriptList, Type type, string key, string script, ScriptEntryFormat format)
        {
            ScriptEntry last  = null;
            ScriptEntry entry = scriptList;

            while (entry != null)
            {
                if (entry.Type == type && entry.Key == key)
                {
                    return;
                }
                last  = entry;
                entry = entry.Next;
            }

            entry = new ScriptEntry(type, key, script, format);

            if (last != null)
            {
                last.Next = entry;
            }
            else
            {
                scriptList = entry;
            }
        }
Ejemplo n.º 2
0
    private void _AnalysisGameobject(GameObject go, ScriptTrunk parent)
    {
        if (go == null)
        {
            return;
        }

        ScriptTrunk scriptTrunk = new ScriptTrunk();

        parent.scriptTrunks.Add(scriptTrunk);
        scriptTrunk.name  = go.name;
        scriptTrunk.path  = parent.isRoot ? go.name : string.Format("{0}/{1}", parent.path, go.name);
        scriptTrunk.depth = parent.depth + 1;

        ScriptEntry scriptEntry = new ScriptEntry();

        scriptTrunk.scriptEntries.Add(scriptEntry);
        scriptEntry.type = "GameObject";

        Component[] components = go.GetComponents <Component>();
        for (int i = 0; i < components.Length; ++i)
        {
            scriptEntry = new ScriptEntry();
            scriptTrunk.scriptEntries.Add(scriptEntry);
            scriptEntry.type = components[i].GetType().Name;
        }

        for (int i = 0; i < go.transform.childCount; ++i)
        {
            _AnalysisGameobject(go.transform.GetChild(i).gameObject, scriptTrunk);
        }
    }
Ejemplo n.º 3
0
        void WriteScripts(HtmlTextWriter writer, ScriptEntry scriptList)
        {
            if (scriptList == null)
            {
                return;
            }

            writer.WriteLine();

            while (scriptList != null)
            {
                switch (scriptList.Format)
                {
                case ScriptEntryFormat.AddScriptTag:
                    EnsureBeginScriptBlock(writer);
                    writer.Write(scriptList.Script);
                    break;

                case ScriptEntryFormat.Include:
                    EnsureEndScriptBlock(writer);
                    WriteClientScriptInclude(writer, scriptList.Script, scriptList.Type, scriptList.Key);
                    break;

                default:
                    EnsureEndScriptBlock(writer);
                    writer.WriteLine(scriptList.Script);
                    break;
                }
                scriptList = scriptList.Next;
            }
            EnsureEndScriptBlock(writer);
        }
Ejemplo n.º 4
0
        internal string WriteSubmitStatements()
        {
            if (submitStatements == null)
            {
                return(null);
            }

            StringBuilder sb    = new StringBuilder();
            ScriptEntry   entry = submitStatements;

            while (entry != null)
            {
                sb.Append(EnsureEndsWithSemicolon(entry.Script));
                entry = entry.Next;
            }
            Page page = OwnerPage;

            RegisterClientScriptBlock(GetType(), "HtmlForm-OnSubmitStatemen",
                                      @"
" + page.WebFormScriptReference + @".WebForm_OnSubmit = function () {
" + sb.ToString() + @"
return true;
}
", true);
            return("javascript:return " + page.WebFormScriptReference + ".WebForm_OnSubmit();");
        }
Ejemplo n.º 5
0
 private void startScanToolStripMenuItem_Click(object sender, EventArgs e)
 {
     string pathcook = ME3Directory.cookedPath;
     DebugOutput.StartDebugger("ScriptDB");
     string[] files = Directory.GetFiles(pathcook, "*.pcc");
     int count = 1;
     database = new List<ScriptEntry>();
     foreach (string file in files)
     {
         DebugOutput.PrintLn(count + "\\" + files.Length + " : Scanning " + Path.GetFileName(file) + " ...");
         PCCObject pcc = new PCCObject(file);
         int count2 = 0;
         foreach (PCCObject.ExportEntry ent in pcc.Exports)
         {
             if (ent.ClassName == "Function")
             {
                 Function f = new Function(ent.Data, pcc);
                 ScriptEntry n = new ScriptEntry();
                 n.file = Path.GetFileName(file);
                 n.name = ent.PackageFullName + "." + ent.ObjectName;
                 n.script = f.ToRawText(false);
                 database.Add(n);
                 DebugOutput.PrintLn("\tFound \"" + n.name + "\"",false);
             }
             count2++;
         }
         {
             pb1.Maximum = files.Length;
             pb1.Value = count;
         }
         count++;
     }
     RefreshList();
 }
Ejemplo n.º 6
0
    private void AnalysisGameobject(GameObject go)
    {
        if (go == null)
        {
            return;
        }

        scriptTrunkRoot        = new ScriptTrunk();
        scriptTrunkRoot.name   = go.name;
        scriptTrunkRoot.path   = string.Empty;
        scriptTrunkRoot.isRoot = true;
        scriptTrunkRoot.depth  = 0;

        ScriptEntry scriptEntry = new ScriptEntry();

        scriptTrunkRoot.scriptEntries.Add(scriptEntry);
        scriptEntry.type = "GameObject";

        Component[] components = go.GetComponents <Component>();
        for (int i = 0; i < components.Length; ++i)
        {
            scriptEntry = new ScriptEntry();
            scriptTrunkRoot.scriptEntries.Add(scriptEntry);
            scriptEntry.type = components[i].GetType().Name;
        }

        _AnalysisGameobject(selectedObject, scriptTrunkRoot);
    }
        public static void RunPatch(IPatcherState <ISkyrimMod, ISkyrimModGetter> state)
        {
            ScriptEntry FFCLS = new ScriptEntry
            {
                Name  = "ANDR_FollowerFavorCarryLimitScript",
                Flags = ScriptEntry.Flag.Local
            };

            ScriptObjectProperty prop = new ScriptObjectProperty
            {
                Name   = "VendorItemArrow",
                Object = Skyrim.Keyword.VendorItemArrow,
                Flags  = ScriptProperty.Flag.Edited
            };

            FFCLS.Properties.Add(prop);

            foreach (var npc in state.LoadOrder.PriorityOrder.WinningOverrides <INpcGetter>())
            {
                if (npc.Configuration.TemplateFlags.HasFlag(NpcConfiguration.TemplateFlag.SpellList) || npc.EditorID == null || npc.Factions == null)
                {
                    continue;
                }

                foreach (var faction in npc.Factions)
                {
                    if (!faction.Faction.Equals(Skyrim.Faction.PotentialFollowerFaction))
                    {
                        continue;
                    }
                    (state.PatchMod.Npcs.GetOrAddAsOverride(npc).VirtualMachineAdapter ??= new VirtualMachineAdapter()).Scripts.Add(FFCLS);
                    break;
                }
            }
        }
Ejemplo n.º 8
0
        private static bool ContainsDup(string Needle)
        {
            foreach (ArrayList ScriptEntry in Results)
            {
                if (ScriptEntry.Contains(Needle))
                {
                    return(true);
                }
            }

            return(false);
        }
Ejemplo n.º 9
0
 bool IsScriptRegistered(ScriptEntry scriptList, Type type, string key)
 {
     while (scriptList != null)
     {
         if (scriptList.Type == type && scriptList.Key == key)
         {
             return(true);
         }
         scriptList = scriptList.Next;
     }
     return(false);
 }
Ejemplo n.º 10
0
        private void startScanToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(ME3Directory.cookedPath))
            {
                MessageBox.Show("This functionality requires ME3 to be installed. Set its path at:\n Options > Set Custom Path > Mass Effect 3");
                return;
            }
            string pathcook = ME3Directory.cookedPath;

            DebugOutput.StartDebugger("ScriptDB");
            string[] files = Directory.GetFiles(pathcook, "*.pcc");
            int      count = 1;

            database = new List <ScriptEntry>();
            foreach (string file in files)
            {
                DebugOutput.PrintLn(count + "\\" + files.Length + " : Scanning " + Path.GetFileName(file) + " ...");
                try
                {
                    using (IMEPackage pcc = MEPackageHandler.OpenME3Package(file))
                    {
                        int count2 = 0;
                        foreach (ExportEntry ent in pcc.Exports)
                        {
                            if (ent.ClassName == "Function")
                            {
                                Function    f = new Function(ent.Data, ent);
                                ScriptEntry n = new ScriptEntry();
                                n.file = Path.GetFileName(file);
                                n.name = ent.InstancedFullPath;
                                f.ParseFunction();
                                n.script = f.ScriptText;
                                database.Add(n);
                                DebugOutput.PrintLn("\tFound \"" + n.name + "\"", false);
                            }
                            count2++;
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error:\n" + ex.Message);
                    DebugOutput.PrintLn("Could not open file: " + Path.GetFileName(file));
                }
                {
                    pb1.Maximum = files.Length;
                    pb1.Value   = count;
                }
                count++;
            }
            RefreshList();
        }
Ejemplo n.º 11
0
        public static ScriptEntry GetOrAddScript(this QuestAdapter vm, string script)
        {
            var se = vm.Scripts.FirstOrDefault(s => s.Name == script);

            if (se != null)
            {
                return(se);
            }
            se = new ScriptEntry {
                Name = script
            };
            vm.Scripts.Add(se);
            return(se);
        }
Ejemplo n.º 12
0
 private void startScanToolStripMenuItem_Click(object sender, EventArgs e)
 {
     if (string.IsNullOrEmpty(ME3Directory.cookedPath))
     {
         MessageBox.Show("This functionality requires ME3 to be installed. Set its path at:\n Options > Set Custom Path > Mass Effect 3");
         return;
     }
     string pathcook = ME3Directory.cookedPath;
     DebugOutput.StartDebugger("ScriptDB");
     string[] files = Directory.GetFiles(pathcook, "*.pcc");
     int count = 1;
     database = new List<ScriptEntry>();
     foreach (string file in files)
     {
         DebugOutput.PrintLn(count + "\\" + files.Length + " : Scanning " + Path.GetFileName(file) + " ...");
         try
         {
             using (ME3Package pcc = MEPackageHandler.OpenME3Package(file))
             {
                 int count2 = 0;
                 foreach (IExportEntry ent in pcc.Exports)
                 {
                     if (ent.ClassName == "Function")
                     {
                         Function f = new Function(ent.Data, pcc);
                         ScriptEntry n = new ScriptEntry();
                         n.file = Path.GetFileName(file);
                         n.name = ent.PackageFullName + "." + ent.ObjectName;
                         n.script = f.ToRawText(false);
                         database.Add(n);
                         DebugOutput.PrintLn("\tFound \"" + n.name + "\"", false);
                     }
                     count2++;
                 } 
             }
         }
         catch (Exception ex)
         {
             MessageBox.Show("Error:\n" + ex.Message);
             DebugOutput.PrintLn("Could not open file: " + Path.GetFileName(file));
         }
         {
             pb1.Maximum = files.Length;
             pb1.Value = count;
         }
         count++;
     }
     RefreshList();
 }
Ejemplo n.º 13
0
        public static ScriptEntry GetOrAddScript(this IMagicEffect shout, string script)
        {
            shout.VirtualMachineAdapter ??= new VirtualMachineAdapter();

            var se = shout.VirtualMachineAdapter.Scripts.FirstOrDefault(s => s.Name == script);

            if (se != null)
            {
                return(se);
            }
            se = new ScriptEntry {
                Name = script
            };
            shout.VirtualMachineAdapter.Scripts.Add(se);
            return(se);
        }
Ejemplo n.º 14
0
        public static ScriptEntry GetOrAddScript(this Weapon vm, string script)
        {
            vm.VirtualMachineAdapter ??= new VirtualMachineAdapter();

            var se = vm.VirtualMachineAdapter.Scripts.FirstOrDefault(s => s.Name == script);

            if (se != null)
            {
                return(se);
            }
            se = new ScriptEntry {
                Name = script
            };
            vm.VirtualMachineAdapter.Scripts.Add(se);
            return(se);
        }
            public static IEnumerable <ScriptEntry> ReadEntries(MutagenFrame frame, ushort objectFormat)
            {
                ushort count = frame.ReadUInt16();

                for (int i = 0; i < count; i++)
                {
                    var scriptName  = StringBinaryTranslation.Instance.Parse(frame, stringBinaryType: StringBinaryType.PrependLengthUShort, encoding: frame.MetaData.Encodings.NonTranslated);
                    var scriptFlags = (ScriptEntry.Flag)frame.ReadUInt8();
                    var entry       = new ScriptEntry()
                    {
                        Name  = scriptName,
                        Flags = scriptFlags,
                    };
                    FillProperties(frame, objectFormat, entry);
                    yield return(entry);
                }
            }
Ejemplo n.º 16
0
        private static string GetPathWithVersion(ScriptEntry scriptEntry)
        {
            var path = scriptEntry.Src;

            if (Cache.ContainsKey(path))
            {
                return(Cache[path]);
            }

            lock (SyncObj)
            {
                if (Cache.ContainsKey(path))
                {
                    return(Cache[path]);
                }

                string result;
                try
                {
                    // CDN resource
                    if (path.StartsWith("http://", StringComparison.CurrentCultureIgnoreCase) || path.StartsWith("//", StringComparison.CurrentCultureIgnoreCase))
                    {
                        //Replace "http://" from beginning
                        result = Regex.Replace(path, @"^http://", "//", RegexOptions.IgnoreCase);
                    }
                    else
                    {
                        var fullPath = HttpContext.Current.Server.MapPath(path.Replace("/", "\\"));
                        result = File.Exists(fullPath)
                            ? GetPathWithVersioningForPhysicalFile(path, fullPath)
                            : GetPathWithVersioningForEmbeddedFile(path);
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.logger.Error("Can not find file for: " + path + "! " + ex.ToString());
                    result = path;
                }

                Cache[path] = result;
                return(result);
            }
        }
Ejemplo n.º 17
0
    public static void DiscoverScripts()
    {
        ScriptEntry.list.Clear();
        Dictionary <string, string> dupes = new Dictionary <string, string>();

        foreach (var f in Ext.GetFilesMulti(settings.scriptPath.Split(';').Select(x => Dir.root + x), "*.*"))
        {
            var bn  = Path.GetFileNameWithoutExtension(f);
            var bnl = bn.ToLower();
            if (settings.scriptBlacklist.Contains(bnl))
            {
                Debug.Info($"Skipping {bn} because it is blacklisted");
                continue;
            }
            if (dupes.TryGetValue(bnl, out string existing))
            {
                // replace dll with script if same name
                if (f.EndsWith(".cs") && !existing.EndsWith(".cs"))
                {
                    Debug.Info($"Skipping {existing} in favor of {f}");
                }
                else
                {
                    Debug.Info($"Skipping duplicate {f}, previously seen as {dupes[bnl]}");
                    continue;
                }
            }
            dupes[bnl] = f;
        }

        foreach (var f in dupes.Values)
        {
            var bn    = Path.GetFileNameWithoutExtension(f);
            var entry = new ScriptEntry()
            {
                name    = bn,
                source  = f,
                enabled = !settings.scriptDisabled.Contains(bn.ToLower()),
            };
            entry.Add();
        }
    }
Ejemplo n.º 18
0
        private void startScanToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(ME3Directory.cookedPath))
            {
                MessageBox.Show("This functionality requires ME3 to be installed. Set its path at:\n Options > Set Custom Path > Mass Effect 3");
                return;
            }
            string pathcook = ME3Directory.cookedPath;

            DebugOutput.StartDebugger("ScriptDB");
            string[] files = Directory.GetFiles(pathcook, "*.pcc");
            int      count = 1;

            database = new List <ScriptEntry>();
            foreach (string file in files)
            {
                DebugOutput.PrintLn(count + "\\" + files.Length + " : Scanning " + Path.GetFileName(file) + " ...");
                PCCObject pcc    = new PCCObject(file);
                int       count2 = 0;
                foreach (PCCObject.ExportEntry ent in pcc.Exports)
                {
                    if (ent.ClassName == "Function")
                    {
                        Function    f = new Function(ent.Data, pcc);
                        ScriptEntry n = new ScriptEntry();
                        n.file   = Path.GetFileName(file);
                        n.name   = ent.PackageFullName + "." + ent.ObjectName;
                        n.script = f.ToRawText(false);
                        database.Add(n);
                        DebugOutput.PrintLn("\tFound \"" + n.name + "\"", false);
                    }
                    count2++;
                }
                {
                    pb1.Maximum = files.Length;
                    pb1.Value   = count;
                }
                count++;
            }
            RefreshList();
        }
Ejemplo n.º 19
0
    public static bool reload()
    {
        var oldeva = Evaluator;

        Evaluator = MonoScript.New(new Reporter(), typeof(Script), (oldeva == null && Patchwork.settings.cacheScripts)?Dir.cache:null);
        Output    = Evaluator.tw;
        Error     = Evaluator.tw;
        Assembly sass = null;

        try
        {
            sass = ScriptEntry.CompileScripts();
        } catch (Exception ex)
        {
            print(ex);
        }
        if (sass == null)
        {
            print("Script reload failed; trying to retain old script base.");
            Evaluator.Dispose();
            Evaluator = oldeva;
            return(false);
        }
        oldeva?.Dispose();
        var newbase = sass.GetType("ScriptEnv");

        if (newbase != null)
        {
            Evaluator.InteractiveBaseClass = newbase;
        }
        if (!firstRun)
        {
            firstRun = true;
            MBProxy.Attach();
            ScriptEntry.RunDLLs();
        }
        print("Scripts reloaded");
        return(true);
    }
Ejemplo n.º 20
0
        private void loadDBToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog d = new OpenFileDialog();

            d.Filter = "*.sdb|*.sdb";
            if (d.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                FileStream fs = new FileStream(d.FileName, FileMode.Open, FileAccess.Read);

                DebugOutput.PrintLn("Loading file to memory");
                byte[] buff = new byte[fs.Length];
                int    cnt;
                int    sum = 0;
                while ((cnt = fs.Read(buff, sum, buff.Length - sum)) > 0)
                {
                    sum += cnt;
                    DebugOutput.PrintLn(sum + "\\" + buff.Length);
                }
                fs.Close();
                DebugOutput.PrintLn("Reading data");
                MemoryStream m = new MemoryStream(buff);
                m.Seek(4, SeekOrigin.Begin);
                int count = BitConverter.ToInt32(buff, 0);
                database = new List <ScriptEntry>();
                for (int i = 0; i < count; i++)
                {
                    ScriptEntry n = new ScriptEntry();
                    n.file   = ReadString(m);
                    n.name   = ReadString(m);
                    n.script = ReadString(m);
                    database.Add(n);
                }
                DebugOutput.PrintLn("Reading done. Refreshing lists...");
                RefreshList();
                MessageBox.Show("Done.");
            }
        }
		bool IsScriptRegistered (ScriptEntry scriptList, Type type, string key)
		{
			while (scriptList != null) {
				if (scriptList.Type == type && scriptList.Key == key)
					return true;
				scriptList = scriptList.Next;
			}
			return false;
		}
Ejemplo n.º 22
0
 public ScriptEntry(ScriptEntry other)
 {
     Name   = other.Name;
     Shell  = other.Shell;
     Script = other.Script;
 }
Ejemplo n.º 23
0
        // Return a line of script at the location specified by index.
        public ScriptEntry Read(int index)
        {
            // TODO check possible corruption of files
            if(index >= count) return null;
            readerScript.BaseStream.Seek(index * ENTRY_SIZE, 0);

            ScriptEntry entry = new ScriptEntry();
            entry.command = readerScript.ReadUInt16();
            entry.arg = new ushort[3];	// WARNING: fixing # args = 3
            entry.arg[0] = readerScript.ReadUInt16();
            entry.arg[1] = readerScript.ReadUInt16();
            entry.arg[2] = readerScript.ReadUInt16();

            return entry;
        }
Ejemplo n.º 24
0
 private void loadDBToolStripMenuItem_Click(object sender, EventArgs e)
 {
     OpenFileDialog d = new OpenFileDialog();
     d.Filter = "*.sdb|*.sdb";
     if (d.ShowDialog() == System.Windows.Forms.DialogResult.OK)
     {
         FileStream fs = new FileStream(d.FileName, FileMode.Open, FileAccess.Read);
         
         DebugOutput.PrintLn("Loading file to memory");
         byte[] buff = new byte[fs.Length];
         int cnt;
         int sum = 0;
         while ((cnt = fs.Read(buff, sum, buff.Length - sum)) > 0)
         {
             sum += cnt;
             DebugOutput.PrintLn(sum + "\\" + buff.Length);
         }
         fs.Close();
         DebugOutput.PrintLn("Reading data");
         MemoryStream m = new MemoryStream(buff);
         m.Seek(4, SeekOrigin.Begin);
         int count = BitConverter.ToInt32(buff, 0);
         database = new List<ScriptEntry>();
         for (int i = 0; i < count; i++) 
         {
             ScriptEntry n = new ScriptEntry();
             n.file = ReadString(m);
             n.name = ReadString(m);
             n.script = ReadString(m);
             database.Add(n);
         }
         DebugOutput.PrintLn("Reading done. Refreshing lists...");
         RefreshList();
         MessageBox.Show("Done.");
     }
 }
		void RegisterScript (ref ScriptEntry scriptList, Type type, string key, string script, bool addScriptTags)
		{
			ScriptEntry last = null;
			ScriptEntry entry = scriptList;

			while (entry != null) {
				if (entry.Type == type && entry.Key == key)
					return;
				last = entry;
				entry = entry.Next;
			}
			
			if (addScriptTags)
				script = "<script language=javascript>\n<!--\n" + script + "\n// -->\n</script>";

			entry = new ScriptEntry (type, key, script);
			
			if (last != null) last.Next = entry;
			else scriptList = entry;
		}
Ejemplo n.º 26
0
        public static void RunPatch(IPatcherState <ISkyrimMod, ISkyrimModGetter> state)
        {
            badKeywordsF = (from keyword in state.LoadOrder.PriorityOrder.OnlyEnabled().Keyword().WinningOverrides() where badKeywords.Contains(keyword.EditorID) select(IFormLink <IKeyword>)(new FormLink <IKeyword>(keyword.FormKey))).ToList();
            IEnumerable <IIngredientGetter> ingredients = state.LoadOrder.PriorityOrder.OnlyEnabled().Ingredient().WinningOverrides().Where(x => !SkipPlugins.Contains(x.FormKey.ModKey.Name.ToLower())).Where(x => (!SkipIngrs.Intersect(x.Name?.ToString()?.Split() !).Any() || SkipIngrs.Contains(x.Name?.ToString()))).Where(x => !String.IsNullOrEmpty(x.Name?.String)).ToList();

            allIngredients       = ingredients;
            percent              = (int)(ingredients.Count() * outputPercentage);
            totalIngredientCount = ingredients.Count();
            Thread[] threads       = new Thread[workerThreadCount];
            int      partitionsize = (ingredients.Count() / workerThreadCount);

            /* Split ingredient list evenly across threads */
            IEnumerable <IIngredientGetter>[] ingredientsL = ingredients.Partition(partitionsize).ToArray();
            /* If there is a remainder add it to last thread */
            if (ingredientsL.Length > workerThreadCount)
            {
                ingredientsL[ingredientsL.Length - 2] = ingredientsL[ingredientsL.Length - 2].Concat(ingredientsL[ingredientsL.Length - 1]);
            }
            sw.Start();
            Console.WriteLine("Using " + workerThreadCount + " threads to handle " + partitionsize + " ingredients each.");
            int startindex = 0;

            for (int u = 0; u < workerThreadCount; u++)
            {
                ListProcessor lp = new ListProcessor(u, state, ingredientsL[u], startindex);
                threads[u] = new Thread(new ThreadStart(lp.run));
                threads[u].Start();
                startindex += partitionsize;
            }
            while (!finishedProcessing)
            {
                if (totalProcessedCount % percent == 0)
                {
                    if (reportedCount != totalProcessedCount)
                    {
                        Console.WriteLine(totalProcessedCount + " out of " + ingredients.Count() + " ingredients processed.");
                        sw.Stop();
                        Console.WriteLine("time elapsed:  " + sw.Elapsed.TotalSeconds + " seconds");
                        sw.Reset();
                        sw.Start();
                        reportedCount = totalProcessedCount;
                    }
                }
                Thread.Sleep(100);
            }
            ;
            Console.WriteLine("Terminating Threads.");
            for (int u = 0; u < workerThreadCount; u++)
            {
                threads[u].Join();
            }
            Console.WriteLine("Creating Leveled lists...");
            IEnumerable <IBookGetter> books = from book in state.LoadOrder.PriorityOrder.Book().WinningOverrides() where book.FormKey.Equals(new FormKey(new ModKey("Skyrim", ModType.Master), 0x0F5CB1)) select book;
            IBookGetter noteTemplate        = books.ToList()[0];

            Console.WriteLine("Creating " + combinations.Count + " recipes.");
            percent = (int)(combinations.Count * outputPercentage);
            int i = 0;
            /* Main leveled list that gets added to recipe drop */
            LeveledItem      mainpotionRecipeLVLI      = state.PatchMod.LeveledItems.AddNew();
            LeveledItemEntry mainpotionRecipeLVLIentry = new LeveledItemEntry();

            mainpotionRecipeLVLI.Entries = new Noggog.ExtendedList <LeveledItemEntry>();
            LeveledItemEntryData mainpotionRecipeLVLIentrydata = new LeveledItemEntryData();
            GlobalInt            mainpotionGlobal = new GlobalInt(state.PatchMod.GetNextFormKey(), SkyrimRelease.SkyrimSE);

            mainpotionGlobal.Data = new Random().Next(minChance, maxChance);
            state.PatchMod.Globals.Set(mainpotionGlobal);
            mainpotionRecipeLVLI.Global   = mainpotionGlobal;
            mainpotionRecipeLVLI.EditorID = "mainpotionRecipeList";
            /* Must split sub leveled lists because it can only hold 128 items */
            uint potionRecipeListCount       = (potionRecipeCount / 128) + 1;
            uint poisonRecipeListCount       = (poisonRecipeCount / 128) + 1;
            uint impurepotionRecipeListCount = (impurepotionRecipeCount / 128) + 1;

            LeveledItem[] potionRecipeLVLIs           = new LeveledItem[potionRecipeListCount];
            uint          masterpotionRecipeListCount = ((potionRecipeListCount + poisonRecipeListCount + impurepotionRecipeListCount) / 128) + 1;

            LeveledItem[]          masterpotionRecipeLVLIs           = new LeveledItem[masterpotionRecipeListCount];
            LeveledItemEntry[]     masterpotionRecipeLVLIentries     = new LeveledItemEntry[masterpotionRecipeListCount];
            LeveledItemEntryData[] masterpotionRecipeLVLIentriesdata = new LeveledItemEntryData[masterpotionRecipeListCount];
            GlobalInt[]            masterpotionGlobals         = new GlobalInt[masterpotionRecipeListCount];
            LeveledItemEntry[]     potionRecipeLVLIentries     = new LeveledItemEntry[potionRecipeListCount];
            LeveledItemEntryData[] potionRecipeLVLIentriesdata = new LeveledItemEntryData[potionRecipeListCount];
            GlobalInt[]            potionGlobals = new GlobalInt[potionRecipeListCount];
            for (int k = 0; k < masterpotionRecipeListCount; k++)
            {
                masterpotionRecipeLVLIentries[k]     = new LeveledItemEntry();
                masterpotionRecipeLVLIentriesdata[k] = new LeveledItemEntryData();
                masterpotionRecipeLVLIs[k]           = state.PatchMod.LeveledItems.AddNew();
                masterpotionRecipeLVLIs[k].Entries   = new Noggog.ExtendedList <LeveledItemEntry>();
                masterpotionGlobals[k]      = new GlobalInt(state.PatchMod.GetNextFormKey(), SkyrimRelease.SkyrimSE);
                masterpotionGlobals[k].Data = new Random().Next(5, 25);//Chance of picking a recipe from this list
                state.PatchMod.Globals.Set(masterpotionGlobals[k]);
                masterpotionRecipeLVLIs[k].Global              = masterpotionGlobals[k];
                masterpotionRecipeLVLIs[k].EditorID            = "masterpotionRecipeList" + k;
                masterpotionRecipeLVLIentriesdata[k].Reference = masterpotionRecipeLVLIs[k].FormKey;
                masterpotionRecipeLVLIentriesdata[k].Level     = 1;
                masterpotionRecipeLVLIentriesdata[k].Count     = 1;
            }
            for (int l = 0; l < potionRecipeListCount; l++)
            {
                potionRecipeLVLIentries[l]     = new LeveledItemEntry();
                potionRecipeLVLIentriesdata[l] = new LeveledItemEntryData();
                potionRecipeLVLIs[l]           = state.PatchMod.LeveledItems.AddNew();
                potionRecipeLVLIs[l].Entries   = new Noggog.ExtendedList <LeveledItemEntry>();
                potionGlobals[l]      = new GlobalInt(state.PatchMod.GetNextFormKey(), SkyrimRelease.SkyrimSE);
                potionGlobals[l].Data = new Random().Next(5, 25);//Chance of picking a recipe from this list
                state.PatchMod.Globals.Set(potionGlobals[l]);
                potionRecipeLVLIs[i].Global              = potionGlobals[l];
                potionRecipeLVLIs[l].EditorID            = "potionRecipeList" + l;
                potionRecipeLVLIentriesdata[l].Reference = potionRecipeLVLIs[l].FormKey;
                potionRecipeLVLIentriesdata[l].Level     = 1;
                potionRecipeLVLIentriesdata[l].Count     = 1;
            }
            LeveledItem[]          poisonRecipeLVLIs           = new LeveledItem[poisonRecipeListCount];
            LeveledItemEntry[]     poisonRecipeLVLIentries     = new LeveledItemEntry[poisonRecipeListCount];
            LeveledItemEntryData[] poisonRecipeLVLIentriesdata = new LeveledItemEntryData[poisonRecipeListCount];
            GlobalInt[]            poisonGlobals = new GlobalInt[poisonRecipeListCount];
            for (int l = 0; l < poisonRecipeListCount; l++)
            {
                poisonRecipeLVLIentries[l]     = new LeveledItemEntry();
                poisonRecipeLVLIentriesdata[l] = new LeveledItemEntryData();
                poisonRecipeLVLIs[l]           = state.PatchMod.LeveledItems.AddNew();
                poisonRecipeLVLIs[l].Entries   = new Noggog.ExtendedList <LeveledItemEntry>();
                poisonGlobals[l]      = new GlobalInt(state.PatchMod.GetNextFormKey(), SkyrimRelease.SkyrimSE);
                poisonGlobals[l].Data = new Random().Next(5, 25);//Chance of picking a recipe from this list
                state.PatchMod.Globals.Set(poisonGlobals[l]);
                poisonRecipeLVLIs[i].Global              = poisonGlobals[l];
                poisonRecipeLVLIs[l].EditorID            = "poisonRecipeList" + l;
                poisonRecipeLVLIentriesdata[l].Reference = poisonRecipeLVLIs[l].FormKey;
                poisonRecipeLVLIentriesdata[l].Level     = 1;
                poisonRecipeLVLIentriesdata[l].Count     = 1;
            }
            LeveledItem[]          impurepotionRecipeLVLIs           = new LeveledItem[impurepotionRecipeListCount];
            LeveledItemEntry[]     impurepotionRecipeLVLIentries     = new LeveledItemEntry[impurepotionRecipeListCount];
            LeveledItemEntryData[] impurepotionRecipeLVLIentriesdata = new LeveledItemEntryData[impurepotionRecipeListCount];
            GlobalInt[]            impurepotionGlobals = new GlobalInt[impurepotionRecipeListCount];
            for (int l = 0; l < impurepotionRecipeListCount; l++)
            {
                impurepotionRecipeLVLIentries[l]     = new LeveledItemEntry();
                impurepotionRecipeLVLIentriesdata[l] = new LeveledItemEntryData();
                impurepotionRecipeLVLIs[l]           = state.PatchMod.LeveledItems.AddNew();
                impurepotionRecipeLVLIs[l].Entries   = new Noggog.ExtendedList <LeveledItemEntry>();
                impurepotionGlobals[l]      = new GlobalInt(state.PatchMod.GetNextFormKey(), SkyrimRelease.SkyrimSE);
                impurepotionGlobals[l].Data = new Random().Next(5, 25);//Chance of picking a recipe from this list
                state.PatchMod.Globals.Set(impurepotionGlobals[l]);
                impurepotionRecipeLVLIs[i].Global              = impurepotionGlobals[l];
                impurepotionRecipeLVLIs[l].EditorID            = "impurepotionRecipeList" + l;
                impurepotionRecipeLVLIentriesdata[l].Reference = impurepotionRecipeLVLIs[l].FormKey;
                impurepotionRecipeLVLIentriesdata[l].Level     = 1;
                impurepotionRecipeLVLIentriesdata[l].Count     = 1;
            }
            Console.WriteLine("Splitting potions into lists (" + potionRecipeListCount + " " + poisonRecipeListCount + " " + impurepotionRecipeListCount + ")");
            uint potionIndex = 0, poisonIndex = 0, impurepotionIndex = 0;
            Dictionary <String, int> nameCache         = new Dictionary <String, int>();

            foreach (IngrCombination ic in combinations)
            {
                if (i % percent == 0)
                {
                    Console.WriteLine(i + " out of " + combinations.Count + " recipes created.");
                }
                IBook newRecipe = noteTemplate.DeepCopy();
                newRecipe.FormKey = state.PatchMod.GetNextFormKey();
                String prefix = "[Potion]";
                if (ic.Type == 1)
                {
                    prefix = "[Poison]";
                }
                if (ic.Type == 2)
                {
                    prefix = "[Impure Potion]";
                }
                newRecipe.Description = prefix + ic.RecipeName;
                newRecipe.Name        = ic.RecipeName;
                newRecipe.BookText    = ic.PotionString;
                newRecipe.Weight      = recipeWeight;
                newRecipe.Value       = recipeValue;
                String?name = "recipeof";
                foreach (String?s in ic.MyEffects !)
                {
                    name += s;
                }
                name = name.Replace(" ", String.Empty);
                int nameIndex = 0;
                if (nameCache.TryGetValue(name, out nameIndex))
                {
                    nameCache[name] = nameIndex + 1;
                    name            = name + nameCache[name];
                }
                else
                {
                    nameCache.Add(name, 0);
                    name = name + "0";
                }
                newRecipe.EditorID = name;
                /* Add ingredients to CACO learning recipe script */
                if (state.LoadOrder.ContainsKey(ModKey.FromNameAndExtension("Complete Alchemy & Cooking Overhaul.esp")))
                {
                    String[] s = (from scriptentry in newRecipe.VirtualMachineAdapter?.Scripts where scriptentry.Name.Equals("CACO_AlchemyRecipeScript") select scriptentry.Name).ToArray();
                    if (s.Length < 1 && learnEffectsFromRecipe)//For adding recipe to a brand new item (not a copy of a vanilla recipe)
                    {
                        ScriptEntry cacoscript = new ScriptEntry();
                        cacoscript.Name = "CACO_AlchemyRecipeScript";
                        newRecipe.VirtualMachineAdapter?.Scripts.Add(cacoscript);
                    }
                    if (newRecipe.VirtualMachineAdapter?.Scripts != null)//For modiying a copy of a vanilla recipe modified by CACO(default)
                    {
                        foreach (ScriptEntry se in newRecipe.VirtualMachineAdapter?.Scripts !)
                        {
                            if (se == null)
                            {
                                continue;
                            }
                            if (se.Name.Equals("CACO_AlchemyRecipeScript"))
                            {
                                if (!learnEffectsFromRecipe)
                                {
                                    newRecipe.VirtualMachineAdapter?.Scripts?.Remove(se);
                                    continue;
                                }
                                int[,] ingrEffectIndex = new int[3, 4];
                                for (int j = 0; j < ingrEffectIndex.GetLength(0); j++)
                                {
                                    for (int k = 0; k < ingrEffectIndex.GetLength(1); k++)
                                    {
                                        ingrEffectIndex[j, k] = -1;
                                    }
                                }
                                for (int j = 0; j < ic.MyIngrs.Length; j++)
                                {
                                    int offset = 0;
                                    for (int k = 0; k < ic.MyIngrs[j].Effects.Count; k++)
                                    {
                                        foreach (String mgefname in ic.MyEffects)
                                        {
                                            state.LinkCache.TryResolve <IMagicEffectGetter>(ic.MyIngrs[j].Effects[k].BaseEffect.FormKey, out var mgeffect);
                                            if (mgeffect?.Name?.String?.Equals(mgefname) ?? true)
                                            {
                                                ingrEffectIndex[j, offset++] = k;
                                            }
                                        }
                                    }
                                }
                                bool[,] exists = new bool[3, 4];
                                bool[] rexists = new bool[3];
                                bool   trexist = false, nvarexist = false, arrexist = false;
                                foreach (ScriptProperty sp in se.Properties)//Scan CACO learning script properties
                                {
                                    switch (sp.Name)
                                    {
                                    case "ThisRecipe":
                                        sp.Flags = ScriptProperty.Flag.Edited;
                                        ((ScriptObjectProperty)sp).Object = new FormLink <ISkyrimMajorRecordGetter>(newRecipe.FormKey);
                                        trexist = true;
                                        break;

                                    case "NoValueAfterRead":
                                        sp.Flags = ScriptProperty.Flag.Edited;
                                        ((ScriptBoolProperty)sp).Data = hasValueAfterRead;
                                        nvarexist = true;
                                        break;

                                    case "CACO_AlchemyRecipesRead":
                                        arrexist = true;
                                        break;
                                    }
                                    for (int j = 0; j < 3; j++)
                                    {
                                        if (sp.Name.Equals("Ingredient0" + (j + 1)))
                                        {
                                            if (ic.MyIngrs.Length > j)
                                            {
                                                sp.Flags = ScriptProperty.Flag.Edited;
                                                ((ScriptObjectProperty)sp).Object = new FormLink <ISkyrimMajorRecordGetter>(ic.MyIngrs[j].FormKey);
                                                rexists[j] = true;
                                            }
                                        }
                                    }
                                    for (int j = 0; j < 3; j++)
                                    {
                                        for (int k = 0; k < 4; k++)
                                        {
                                            if (sp.Name.Equals("Ingredient0" + (j + 1) + "Effect" + (k + 1)))
                                            {
                                                if (ingrEffectIndex[j, k] != -1)
                                                {
                                                    ((ScriptIntProperty)sp).Data = ingrEffectIndex[j, k];
                                                    exists[j, k] = true;
                                                }
                                            }
                                        }
                                    }
                                }
                                for (int j = 0; j < rexists.Length; j++)
                                {
                                    if (ic.MyIngrs.Length > j)
                                    {
                                        if (!rexists[j])
                                        {
                                            ScriptObjectProperty sop = new ScriptObjectProperty();
                                            sop.Object = new FormLink <ISkyrimMajorRecordGetter>(ic.MyIngrs[j].FormKey);
                                            sop.Name   = "Ingredient0" + (j + 1);
                                            sop.Flags  = ScriptProperty.Flag.Edited;
                                            se.Properties.Add(sop);
                                        }
                                    }
                                }
                                for (int j = 0; j < exists.GetLength(0); j++)
                                {
                                    for (int k = 0; k < exists.GetLength(1); k++)
                                    {
                                        if (ic.MyIngrs.Length > j)
                                        {
                                            if (!exists[j, k] && ingrEffectIndex[j, k] != -1)
                                            {
                                                ScriptIntProperty sip = new ScriptIntProperty();
                                                sip.Data  = ingrEffectIndex[j, k];
                                                sip.Name  = "Ingredient0" + (j + 1) + "Effect" + (k + 1);
                                                sip.Flags = ScriptProperty.Flag.Edited;
                                                se.Properties.Add(sip);
                                            }
                                        }
                                    }
                                }
                                if (!trexist)
                                {
                                    ScriptObjectProperty sop = new ScriptObjectProperty();
                                    sop.Object = new FormLink <ISkyrimMajorRecordGetter>(newRecipe.FormKey);
                                    sop.Name   = "ThisRecipe";
                                    sop.Flags  = ScriptProperty.Flag.Edited;
                                    se.Properties.Add(sop);
                                }
                                if (!nvarexist)
                                {
                                    ScriptBoolProperty sbp = new ScriptBoolProperty();
                                    sbp.Data  = hasValueAfterRead;
                                    sbp.Name  = "NoValueAfterRead";
                                    sbp.Flags = ScriptProperty.Flag.Edited;
                                    se.Properties.Add(sbp);
                                }
                                if (arrexist)
                                {
                                    FormList             fl  = new FormList(new FormKey(new ModKey("Complete Alchemy & Cooking Overhaul.esp", ModType.Plugin), 0xA2C667), SkyrimRelease.SkyrimSE);
                                    ScriptObjectProperty sop = new ScriptObjectProperty();
                                    sop.Object = fl;
                                    sop.Name   = "CACO_AlchemyRecipesRead";
                                    sop.Flags  = ScriptProperty.Flag.Edited;
                                    se.Properties.Add(sop);
                                }
                            }
                        }
                    }
                }

                state.PatchMod.Books.Set((Book)newRecipe);
                LeveledItemEntry     lie  = new LeveledItemEntry();
                LeveledItemEntryData data = new LeveledItemEntryData();
                data.Level     = 1;
                data.Count     = 1;
                data.Reference = new FormLink <IItemGetter>(newRecipe.FormKey);
                lie.Data       = data;
                switch (ic.Type)
                {
                case 0:
                    potionRecipeLVLIentriesdata[potionIndex / 128].Reference = potionRecipeLVLIs[potionIndex / 128].FormKey;
                    potionRecipeLVLIentries[potionIndex / 128].Data          = potionRecipeLVLIentriesdata[potionIndex / 128];
                    potionRecipeLVLIs[potionIndex / 128].Entries?.Add(lie);
                    potionIndex++;
                    break;

                case 1:
                    poisonRecipeLVLIentriesdata[poisonIndex / 128].Reference = poisonRecipeLVLIs[poisonIndex / 128].FormKey;
                    poisonRecipeLVLIentries[poisonIndex / 128].Data          = poisonRecipeLVLIentriesdata[poisonIndex / 128];
                    poisonRecipeLVLIs[poisonIndex / 128].Entries?.Add(lie);
                    poisonIndex++;
                    break;

                case 2:
                    impurepotionRecipeLVLIentriesdata[impurepotionIndex / 128].Reference = impurepotionRecipeLVLIs[impurepotionIndex / 128].FormKey;
                    impurepotionRecipeLVLIentries[impurepotionIndex / 128].Data          = impurepotionRecipeLVLIentriesdata[impurepotionIndex / 128];
                    impurepotionRecipeLVLIs[impurepotionIndex / 128].Entries?.Add(lie);
                    impurepotionIndex++;
                    break;
                }
                i++;
            }

            Console.WriteLine("Linking recipes to potion leveled list");
            IEnumerable <ILeveledItemGetter> lvlilists = from list in state.LoadOrder.PriorityOrder.OnlyEnabled().LeveledItem().WinningOverrides() where list.EditorID?.Equals("LItemPotionAll") ?? true select list;
            ILeveledItemGetter allList                 = lvlilists.ToList()[0];
            LeveledItem        modifiedList            = state.PatchMod.LeveledItems.GetOrAddAsOverride(allList);

            potionIndex       = 0;
            poisonIndex       = 0;
            impurepotionIndex = 0;
            for (int l = 0; l < masterpotionRecipeListCount; l++)
            {
                masterpotionRecipeLVLIentriesdata[l].Reference = masterpotionRecipeLVLIs[l].FormKey;
                masterpotionRecipeLVLIentries[l].Data          = masterpotionRecipeLVLIentriesdata[l];
                for (int k = 0; k < 128; k++)
                {
                    if (potionIndex < potionRecipeLVLIentries.Length)
                    {
                        masterpotionRecipeLVLIs[l].Entries?.Add(potionRecipeLVLIentries[potionIndex++]);
                    }
                    else if (poisonIndex < poisonRecipeLVLIentries.Length)
                    {
                        masterpotionRecipeLVLIs[l].Entries?.Add(poisonRecipeLVLIentries[poisonIndex++]);
                    }
                    else if (impurepotionIndex < impurepotionRecipeLVLIentries.Length)
                    {
                        masterpotionRecipeLVLIs[l].Entries?.Add(impurepotionRecipeLVLIentries[impurepotionIndex++]);
                    }
                    else
                    {
                        break;
                    }
                }
                mainpotionRecipeLVLI.Entries?.Add(masterpotionRecipeLVLIentries[l]);
            }
            foreach (LeveledItem li in potionRecipeLVLIs)
            {
                state.PatchMod.LeveledItems.Set(li);
            }
            foreach (LeveledItem li in poisonRecipeLVLIs)
            {
                state.PatchMod.LeveledItems.Set(li);
            }
            foreach (LeveledItem li in impurepotionRecipeLVLIs)
            {
                state.PatchMod.LeveledItems.Set(li);
            }
            foreach (LeveledItem li in masterpotionRecipeLVLIs)
            {
                state.PatchMod.LeveledItems.Set(li);
            }

            mainpotionRecipeLVLIentrydata.Reference = mainpotionRecipeLVLI.FormKey;
            mainpotionRecipeLVLIentry.Data          = mainpotionRecipeLVLIentrydata;
            mainpotionRecipeLVLIentrydata.Count     = 1;
            mainpotionRecipeLVLIentrydata.Level     = 1;
            modifiedList.Entries?.Add(mainpotionRecipeLVLIentry);
            state.PatchMod.LeveledItems.Set(mainpotionRecipeLVLI);
            Console.WriteLine("Adding recipes to defined containers");
            IEnumerable <IContainerGetter> chests   = from list in state.LoadOrder.PriorityOrder.OnlyEnabled().Container().WinningOverrides() where containerEditorIDs?.ToList().Contains(list.EditorID !) ?? true select list;
            ContainerEntry potionListContainerEntry = new ContainerEntry();
            ContainerItem  potionListContainerItem  = new ContainerItem();

            potionListContainerItem.Item  = mainpotionRecipeLVLI.FormKey;
            potionListContainerItem.Count = 1;
            potionListContainerEntry.Item = potionListContainerItem;
            foreach (IContainerGetter chest in chests)
            {
                Container rChest = state.PatchMod.Containers.GetOrAddAsOverride(chest);
                rChest.Items?.Add(potionListContainerEntry);
            }
        }
		void WriteScripts (HtmlTextWriter writer, ScriptEntry scriptList)
		{
			if (scriptList == null)
				return;

			writer.WriteLine ();

			while (scriptList != null) {
				switch (scriptList.Format) {
				case ScriptEntryFormat.AddScriptTag:
					EnsureBeginScriptBlock (writer);
					writer.Write (scriptList.Script);
					break;
				case ScriptEntryFormat.Include:
					EnsureEndScriptBlock (writer);
					WriteClientScriptInclude (writer, scriptList.Script, scriptList.Type, scriptList.Key);
					break;
				default:
					EnsureEndScriptBlock (writer);
					writer.WriteLine (scriptList.Script);
					break;
				}
				scriptList = scriptList.Next;
			}
			EnsureEndScriptBlock (writer);
		}
Ejemplo n.º 28
0
        private static System.Windows.Forms.TreeNode readNode(System.IO.BinaryReader stream, int parent = 0)
        {
            ScriptEntry entry = new ScriptEntry();

            entry.type = stream.ReadByte();
            entry.subType = stream.ReadByte();

            entry.unknown2 = stream.ReadUInt16();

            uint len = stream.ReadUInt16();
            for (int i = 0; i < len; i++)
                entry.Name += (char)stream.ReadByte();

            entry.dataLen = stream.ReadUInt32();
            entry.data = stream.ReadBytes((int)entry.dataLen);

            len = stream.ReadUInt16();
            entry.unknown3 = stream.ReadUInt16();

            System.Windows.Forms.TreeNode node = new System.Windows.Forms.TreeNode(entry.Name);
            node.Tag = entry;

            if (entry.type == 2 && len == 0)
            {
                string file = String.Format("{0:X2}", entry.unknown2) + "/" + String.Format("{0:X2}", entry.unknown2);
                if (entry.unknown2 == 0)
                    file = "Global/Global";
                System.Windows.Forms.TreeNode n = XARC.ParseFile(Form1.gamepath + "/" + file + ".xarc");
                n = n.FirstNode;// Nodes.Find(entry.Name + ".xrc", false)[0];

                XARC.FileEntry fe = (XARC.FileEntry)n.Tag;
                // Parse XRC node
                System.IO.FileStream fs = System.IO.File.OpenRead(Form1.gamepath + "/" + file + ".xarc");
                byte[] buf = new byte[fe.length];
                fs.Seek(fe.offset, System.IO.SeekOrigin.Begin);
                fs.Read(buf, 0, (int)fe.length);
                return readNode(new System.IO.BinaryReader(new System.IO.MemoryStream(buf)));
            }
            else if (entry.type == 3 && len == 0)
            {
                System.Windows.Forms.TreeNode n = XARC.ParseFile(Form1.gamepath + "/" + String.Format("{0:X2}", parent) + "/" + String.Format("{0:X2}", entry.unknown2) + "/" + String.Format("{0:X2}", entry.unknown2) + ".xarc");
                n = n.FirstNode;// Nodes.Find(entry.Name, false)[0];

                XARC.FileEntry fe = (XARC.FileEntry)n.Tag;
                // Parse XRC node
                System.IO.FileStream fs = System.IO.File.OpenRead(Form1.gamepath + "/" + String.Format("{0:X2}", parent) + "/" + String.Format("{0:X2}", entry.unknown2) + "/" + String.Format("{0:X2}", entry.unknown2) + ".xarc");
                byte[] buf = new byte[fe.length];
                fs.Seek(fe.offset, System.IO.SeekOrigin.Begin);
                fs.Read(buf, 0, (int)fe.length);
                return readNode(new System.IO.BinaryReader(new System.IO.MemoryStream(buf)));
            }
            else
            {
                for (int i = 0; i < len; i++)
                {
                    node.Nodes.Add(readNode(stream, entry.unknown2));
                }

            }

            return node;
        }
Ejemplo n.º 29
0
        protected override void OnResolveScriptReference(ScriptReferenceEventArgs e)
        {
            base.OnResolveScriptReference(e);

            // If combining scripts and this is a candidate script
            if (_combineScripts && !String.IsNullOrEmpty(e.Script.Assembly) && !String.IsNullOrEmpty(e.Script.Name))
            {
                // Initialize
                ScriptReference scriptReference = e.Script;
                ScriptEntry scriptEntry = new ScriptEntry(scriptReference);

                if (IsScriptCombinable(scriptEntry))
                {
                    if (!_scriptEntries.Contains(scriptEntry))
                    {
                        // Haven't seen this script yet; add it to the list and invalidate the Url
                        _scriptEntries.Add(scriptEntry);
                        _combinedScriptUrl = null;
                    }

                    if (null == _combinedScriptUrl)
                    {
                        // Url is invalid; update it
                        _combinedScriptUrl = String.Format(CultureInfo.InvariantCulture, "{0}?{1}={2}&{3}={4}", ((null != _combineScriptsHandlerUrl) ? _combineScriptsHandlerUrl.ToString() : Page.Request.Path), HiddenFieldParamName, HiddenFieldName, CombinedScriptsParamName, HttpUtility.UrlEncode(SerializeScriptEntries(_scriptEntries, false)));
                    }

                    // Remove the script from the list and track it
                    scriptReference.Name = "";
                    scriptReference.Assembly = "";
                    _disabledScriptReferences.Add(scriptReference);

                    // Update the common (combined) Url for all tracked scripts
                    foreach (ScriptReference disabledScriptReference in _disabledScriptReferences)
                    {
                        disabledScriptReference.Path = _combinedScriptUrl;
                    }
                }
                else
                {
                    // See if we've already seen this uncombinable script reference
                    bool alreadySeen = false;
                    foreach (ScriptReference uncombinableScriptReference in _uncombinableScriptReferences)
                    {
                        if ((uncombinableScriptReference.Assembly == scriptReference.Assembly) && (uncombinableScriptReference.Name == scriptReference.Name))
                        {
                            alreadySeen = true;
                        }
                    }
                    if (!alreadySeen)
                    {
                        // Haven't seen the script reference yet, so we need to stop building the current combined script
                        // file and let the uncombinable script reference be output so as not to alter the ordering of
                        // scripts (which may have dependencies). Update our state so we'll start building a new combined
                        // script file with the next combinable script.
                        // Note: _combinedScriptUrl was initially cleared here. While that's correct behavior (and was
                        // released without issue), not clearing it means that we can omit an unnecessary <script> tag
                        // for the scenario "CombinableA, Uncombinable?, CombinableA, Uncombinable?" because the second
                        // instance of CombinableA will reuse the URL from the first (vs. an empty one) and ScriptManager
                        // will detect and omit the redundant URL.
                        _uncombinableScriptReferences.Add(scriptReference);
                        _disabledScriptReferences.Clear();
                        foreach (ScriptEntry se in _scriptEntries)
                        {
                            se.Loaded = true;
                        }
                    }
                }
            }
        }
Ejemplo n.º 30
0
 void RegisterScript(ref ScriptEntry scriptList, Type type, string key, string script, bool addScriptTags)
 {
     RegisterScript(ref scriptList, type, key, script, addScriptTags ? ScriptEntryFormat.AddScriptTag : ScriptEntryFormat.None);
 }
Ejemplo n.º 31
0
 /// <summary>
 /// Deserialize a list of ScriptEntries
 /// </summary>
 /// <remarks>
 /// Serialized list looks like:
 /// ;Assembly1.dll Version=1:Culture:MVID1:ScriptName1Hash:ScriptName2Hash;Assembly2.dll Version=2:Culture:MVID1:ScriptName3Hash
 /// </remarks>
 /// <param name="serializedScriptEntries">serialized list</param>
 /// <param name="loaded">loaded state of the serialized scripts</param>
 /// <returns>list of scripts</returns>
 private static List<ScriptEntry> DeserializeScriptEntries(string serializedScriptEntries, bool loaded)
 {
     List<ScriptEntry> scriptEntries = new List<ScriptEntry>();
     foreach (string assemblyScripts in serializedScriptEntries.Split(';'))
     {
         // Deserialize this assembly's scripts
         string assembly = null;
         string culture = null;
         string mvid = null;
         Dictionary<string, string> resourceNameHashToResourceName = null;
         foreach (string script in assemblyScripts.Split(':'))
         {
             if (null == assembly)
             {
                 // Haven't got the assembly name yet; this is it
                 assembly = script;
             }
             else if (null == culture)
             {
                 // Haven't got the culture value yet; this is it
                 culture = script;
             }
             else if (null == mvid)
             {
                 // Haven't got the MVID value yet; this is it
                 mvid = script;
             }
             else
             {
                 if (null == resourceNameHashToResourceName)
                 {
                     // Populate the "resource name hash to resource name" dictionary for this assembly
                     resourceNameHashToResourceName = new Dictionary<string, string>();
                     foreach (string resourceName in (new ScriptEntry(assembly, null, null)).LoadAssembly().GetManifestResourceNames())
                     {
                         string hashCode = resourceName.GetHashCode().ToString("x", CultureInfo.InvariantCulture);
                         if (resourceNameHashToResourceName.ContainsKey(hashCode))
                         {
                             // Hash collisions are exceedingly rare, but possible
                             throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "Assembly \"{0}\" contains multiple scripts with hash code \"{1}\".", assembly, hashCode));
                         }
                         resourceNameHashToResourceName[hashCode] = resourceName;
                     }
                 }
                 // Map the script hash to a script name
                 string scriptName;
                 if (!resourceNameHashToResourceName.TryGetValue(script, out scriptName))
                 {
                     throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "Assembly \"{0}\" does not contain a script with hash code \"{1}\".", assembly, script));
                 }
                 // Create a ScriptEntry to represent the script
                 ScriptEntry scriptEntry = new ScriptEntry(assembly, scriptName, culture);
                 scriptEntry.Loaded = loaded;
                 scriptEntries.Add(scriptEntry);
             }
         }
     }
     return scriptEntries;
 }
		void RegisterScript (ref ScriptEntry scriptList, Type type, string key, string script, bool addScriptTags)
		{
			RegisterScript (ref scriptList, type, key, script, addScriptTags ? ScriptEntryFormat.AddScriptTag : ScriptEntryFormat.None);
		}
		void RegisterScript (ref ScriptEntry scriptList, Type type, string key, string script, ScriptEntryFormat format)
		{
			ScriptEntry last = null;
			ScriptEntry entry = scriptList;

			while (entry != null) {
				if (entry.Type == type && entry.Key == key)
					return;
				last = entry;
				entry = entry.Next;
			}

			entry = new ScriptEntry (type, key, script, format);
			
			if (last != null) last.Next = entry;
			else scriptList = entry;
		}
		void WriteScripts (HtmlTextWriter writer, ScriptEntry scriptList)
		{
			while (scriptList != null) {
				writer.WriteLine (scriptList.Script);
				scriptList = scriptList.Next;
			}
		}
Ejemplo n.º 35
0
        private async Task <ActionResult> RunEntryAsync(IVRConfig ivrConfig, ScriptData script, string called, string extension, ScriptEntry entry, int errCount)
        {
            string extensionName   = null;
            string extensionSpaced = null;

            if (!string.IsNullOrWhiteSpace(extension))
            {
                extensionSpaced = Spaced(extension);
                Extension e = script.FindExtension(extension);
                if (e != null)
                {
                    extensionName = e.Name;
                }
            }
            string digits;

            TryGetForm("Digits", out digits);

            string actionUrl = Utility.UrlFor(typeof(CallController), nameof(Process));

#if DEBUG
            actionUrl = Manager.CurrentSite.MakeFullUrl(actionUrl, SecurityType: YetaWF.Core.Pages.PageDefinition.PageSecurityType.Any);
#else
            actionUrl = Manager.CurrentSite.MakeFullUrl(actionUrl, SecurityType: YetaWF.Core.Pages.PageDefinition.PageSecurityType.httpsOnly);
#endif

            string token = DateTime.UtcNow.Ticks.ToString();
            string encryptedToken;
            RSACrypto.Encrypt(ivrConfig.PublicKey, token, out encryptedToken);

            object parms = new {
                Url             = actionUrl,
                Caller          = GetForm("Caller"),
                CallerSpaced    = Spaced(GetForm("Caller").TruncateStart("+1")),
                CallerCity      = GetForm("CallerCity"),
                CallerCountry   = GetForm("CallerCountry"),
                Digits          = digits,
                Extension       = extension,
                ExtensionSpaced = extensionSpaced,
                ExtensionName   = extensionName,
                ErrCount        = errCount,
                ErrCountPlus1   = errCount + 1,
                Token           = encryptedToken,
                Voice           = ivrConfig.Voice,
                VoiceInternal   = ivrConfig.VoiceInternal,
            };

            string    text = entry.Text;
            Variables vars = new Variables(Manager, parms)
            {
                EncodingType = Variables.EncodingTypeEnum.XML
            };

            Extension ext = script.FindExtension(digits);
            if (ext != null)
            {
                text = RepeatableNumbers(ext, text);
            }

            if (text.Contains("RECORDVOICEMAIL"))
            {
                text = text.Replace("RECORDVOICEMAIL", "");
                VoiceMailData voiceMail;
                using (VoiceMailDataProvider voiceMailDP = new VoiceMailDataProvider()) {
                    voiceMail = new VoiceMailData {
                        Caller        = GetForm("Caller").Truncate(Globals.MaxPhoneNumber),
                        CallerCity    = GetForm("CallerCity").Truncate(VoiceMailData.MaxCity),
                        CallerState   = GetForm("CallerState").Truncate(VoiceMailData.MaxState),
                        CallerZip     = GetForm("CallerZip").Truncate(VoiceMailData.MaxZip),
                        CallerCountry = GetForm("CallerCountry").Truncate(VoiceMailData.MaxCountry),
                        CallSid       = GetForm("CallSid"),
                        RecordingSid  = GetForm("RecordingSid"),
                        Duration      = ConvertToInt(GetForm("RecordingDuration")),
                        To            = called,
                        Extension     = extension,
                        RecordingUrl  = GetForm("RecordingUrl").Truncate(Globals.MaxUrl)
                    };
                    if (!await voiceMailDP.AddItemAsync(voiceMail))
                    {
                        Logging.AddErrorLog($"Couldn't record voice mail status for call from {GetForm("Caller")}");
                    }
                }
                if (!string.IsNullOrWhiteSpace(extension))
                {
                    ext = script.FindExtension(extension);
                    if (ext != null)
                    {
                        DisplayVoiceMailModule dispMod = (DisplayVoiceMailModule)await ModuleDefinition.LoadAsync(ModuleDefinition.GetPermanentGuid(typeof(DisplayVoiceMailModule)));

                        ModuleAction displayAction = await dispMod.GetAction_DisplayAsync(null, voiceMail.Id);

                        if (displayAction != null)
                        {
                            string viewUrl = displayAction.GetCompleteUrl();
                            foreach (ExtensionNumber extNumber in ext.Numbers)
                            {
                                if (extNumber.SendSMSVoiceMail)
                                {
                                    SendSMS sendSMS = new SendSMS();
                                    await sendSMS.SendMessageAsync(extNumber.Number,
                                                                   this.__ResStr("voiceSMS", "A voice mail was received for extension {0} ({1}) from {2}, {3}, {4}, {5} {6} - {7}",
                                                                                 extension, GetForm("To"), GetForm("Caller"), GetForm("CallerCity"), GetForm("CallerState"), GetForm("CallerZip"), GetForm("CallerCountry"),
                                                                                 viewUrl),
                                                                   ThrowError : false);
                                }
                            }
                        }
                    }
                }
            }

            text = vars.ReplaceVariables(text);
            Logging.AddLog($"{nameof(RunEntryAsync)}: {text}");
            return(Content(text, "text/xml"));
        }
Ejemplo n.º 36
0
 /// <summary>
 /// Checks if the specified ScriptEntry is combinable
 /// </summary>
 /// <param name="scriptEntry">ScriptEntry to check</param>
 /// <returns>true iff combinable</returns>
 private static bool IsScriptCombinable(ScriptEntry scriptEntry)
 {
     // Load the script's assembly and look for ScriptCombineAttribute
     bool combinable = false;
     Assembly assembly = scriptEntry.LoadAssembly();
     foreach (ScriptCombineAttribute scriptCombineAttribute in assembly.GetCustomAttributes(typeof(ScriptCombineAttribute), false))
     {
         if (string.IsNullOrEmpty(scriptCombineAttribute.IncludeScripts))
         {
             // If the IncludeScripts property is empty, all scripts are combinable by default
             combinable = true;
         }
         else
         {
             // IncludeScripts specifies the combinable scripts
             foreach (string includeScript in scriptCombineAttribute.IncludeScripts.Split(','))
             {
                 // If this script name matches, it's combinable
                 if (0 == string.Compare(scriptEntry.Name, includeScript.Trim(), StringComparison.OrdinalIgnoreCase))
                 {
                     combinable = true;
                     break;
                 }
             }
         }
         if (!string.IsNullOrEmpty(scriptCombineAttribute.ExcludeScripts))
         {
             // ExcludeScripts specifies the non-combinable scripts (and overrides IncludeScripts)
             foreach (string excludeScript in scriptCombineAttribute.ExcludeScripts.Split(','))
             {
                 // If the script name matches, it's not combinable
                 if (0 == string.Compare(scriptEntry.Name, excludeScript.Trim(), StringComparison.OrdinalIgnoreCase))
                 {
                     combinable = false;
                     break;
                 }
             }
         }
     }
     if (combinable)
     {
         // Make sure the script has an associated WebResourceAttribute (else ScriptManager wouldn't have served it)
         bool correspondingWebResourceAttribute = false;
         foreach (WebResourceAttribute webResourceAttribute in assembly.GetCustomAttributes(typeof(WebResourceAttribute), false))
         {
             if (scriptEntry.Name == webResourceAttribute.WebResource)
             {
                 correspondingWebResourceAttribute = true;
                 break;
             }
         }
         // Don't allow it to be combined if not
         combinable &= correspondingWebResourceAttribute;
     }
     return combinable;
 }