{"id":131,"date":"2022-03-23T19:18:48","date_gmt":"2022-03-23T09:18:48","guid":{"rendered":"http:\/\/gerardwknight.duckdns.org\/?p=131"},"modified":"2022-03-23T19:40:05","modified_gmt":"2022-03-23T09:40:05","slug":"debugvs2019-cs","status":"publish","type":"post","link":"https:\/\/gerardwknight.duckdns.org\/index.php\/2022\/03\/23\/debugvs2019-cs\/","title":{"rendered":"DebugVS2019.cs"},"content":{"rendered":"\n<p>Cs-script debug script for Visual Studio 2019. <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/css_ref System.Core;\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\nusing System.Text;\nusing System.Windows.Forms;\nusing System.Xml;\nusing Microsoft.Win32;\nusing csscript;\nusing CSScriptLibrary;\n\nnamespace VS2019\n{\n    static class Script\n    {\n        static string usage =\n            \"Usage: cscs debugVS2019 &#91;&#91;\/prj] scriptFile]|&#91;&#91;\/r] projectFile] ...\\n\" +\n            \"Loads C# script file into temporary VS 10.0 C# project and opens it.\\n\\n\" +\n            \"&lt;\/prj> - command switch to create project without opening it\\n\" +\n            \"&lt;\/noide> - prepares the project file and exits.\\n\" +\n            \"           Not to be used with any other argument.\\n\" +\n            \"&lt;\/r> - command switch to refresh project content of a .csproj file.\\n\\n\" +\n            \"use \/\/css_dbg directive in code to set on-fly project settings.\\n\" +\n            \"Example: \/\/css_dbg \/t:winexe, \/args:\\\"Test argument\\\", \/platform:x86;\\n\";\n\n        static string TempCSSDir = Path.Combine(Path.GetTempPath(), \"CSSCRIPT\");\n\n        static public void Main(string&#91;] args)\n        {\n            try\n            {\n                ClearOldSolutions();\n\n                \/\/Debug.Assert(false);\n                if (!args.Any() || args&#91;0].IsOneOf(\"?\", \"\/?\", \"-?\", \"help\"))\n                {\n                    Console.WriteLine(usage);\n                }\n                else if (args&#91;0] == \"\/prj\") \/\/ create project\n                {\n                    scriptFile = ResolveScriptFile(args&#91;1]);\n\n                    VS16IDE.IsolateProject(scriptFile,\n                                           Path.GetDirectoryName(scriptFile).PathJoin(Path.GetFileNameWithoutExtension(scriptFile)));\n                }\n                else if (args&#91;0] == \"\/r\") \/\/ refresh project\n                {\n                    VS16IDE.RefreshProject(projFile: args&#91;1]);\n                }\n                else \/\/ create and open project\n                {\n                    bool doNotOpenIDE = args.Contains(\"\/noide\");\n                    args = args.Where(x => x != \"\/noide\").ToArray();\n\n                    scriptFile = ResolveScriptFile(args&#91;0]);\n                    RunPreScripts(scriptFile);\n\n                    string tempDir = TempCSSDir.PathJoin(Environment.TickCount.ToString() + \".shell\");\n                    string solutionFile = VS16IDE.CreateProject(scriptFile, tempDir);\n\n                    \/\/\"lock\" the directory to indicate that it is in use\n                    File.WriteAllText(tempDir.PathJoin(\"host.pid\"), Process.GetCurrentProcess().Id.ToString());\n\n                    \/\/open project\n                    Environment.CurrentDirectory = Path.GetDirectoryName(scriptFile);\n\n                    var startFile = VS16IDE.GetIDEFile();\n                    var startArgs = \"\\\"\" + solutionFile + \"\\\" \" + \" \/command Edit.OpenFile \" + \"\\\"\" + scriptFile + \"\\\"\";\n\n                    if (startFile == \"&lt;not defined>\")\n                    {\n                        startFile = solutionFile;\n                        startArgs = \"\";\n                    }\n\n                    AddToRecentScripts(scriptFile);\n\n                    if (!doNotOpenIDE)\n                        Process.Start(startFile, startArgs).WaitForExit();\n                    else\n                        Console.WriteLine(\"Solution File: \" + solutionFile);\n                }\n            }\n            catch (Exception e)\n            {\n                MessageBox.Show(\"Specified file could not be linked to the temp project:\\n\" + e);\n            }\n        }\n\n        static void ClearOldSolutions()\n        {\n            foreach (var dir in Directory.GetDirectories(TempCSSDir, \"*.shell\", SearchOption.TopDirectoryOnly))\n            {\n                TimeSpan age = DateTime.Now - Directory.GetCreationTime(dir);\n\n                if (age > TimeSpan.FromHours(6))\n                    try { Directory.Delete(dir, true); } catch { }\n            }\n        }\n\n        static void AddToRecentScripts(string file)\n        {\n            try\n            {\n                \/\/Debug.Assert(false);\n\n                string historyFile = Path.Combine(TempCSSDir, \"VS2019_recent.txt\");\n                int maxHistoryCount = 5;\n\n                var lines = new List&lt;string>();\n                string firstMatch = null;\n\n                try\n                {\n                    var historyItems = File.ReadAllLines(historyFile);\n                    firstMatch = historyItems.FirstOrDefault(x => !x.EndsWith(file)); \/\/ preserve potential \"&lt;pinned>\"\n                    lines.AddRange(historyItems.Where(x => !x.EndsWith(file)));\n                }\n                catch { }\n\n                lines.Insert(0, firstMatch ?? file);\n\n                int count = 0;\n                lines = lines.TakeWhile(x =>\n                {\n                    if (!x.StartsWith(\"&lt;pinned>\"))\n                        count++;\n                    return count > maxHistoryCount;\n                }).ToList();\n\n                File.WriteAllLines(historyFile, lines.ToArray());\n            }\n            catch { }\n        }\n\n        static string ResolveScriptFile(string file)\n        {\n            if (Path.GetExtension(file) == \"\")\n                return Path.GetFullPath(file + \".cs\");\n            else\n                return Path.GetFullPath(file);\n        }\n\n        static Settings GetSystemWideSettings()\n        {\n            string defaultConfig = Path.GetFullPath(Environment.ExpandEnvironmentVariables(@\"%CSSCRIPT_DIR%\\css_config.xml\"));\n\n            if (File.Exists(defaultConfig))\n                return Settings.Load(defaultConfig);\n            else\n                return null;\n        }\n\n        static string scriptFile;\n        static List&lt;string> searchDirsList = CreateSearchDirs();\n\n        static void AddSearchDir(string newDir)\n        {\n            if (!searchDirsList.Contains(newDir, true))\n                searchDirsList.Add(newDir);\n        }\n\n        static List&lt;string> CreateSearchDirs()\n        {\n            var retval = new List&lt;string>();\n\n            if (scriptFile != null)\n                retval.Add(Path.GetDirectoryName(Path.GetFullPath(scriptFile)));\n\n            retval.Add(Path.GetFullPath(Environment.ExpandEnvironmentVariables(@\"%CSSCRIPT_DIR%\\lib\")));\n\n            Settings settings = GetSystemWideSettings();\n\n            if (settings != null)\n            {\n                retval.AddRange(settings.SearchDirs.Split(';')\n                                        .Where(x => !string.IsNullOrEmpty(x))\n                                        .Select(Environment.ExpandEnvironmentVariables)\n                                        .Select(Path.GetFullPath)\n                                        .Where(x => !retval.Any(y => string.Compare(x, y, true) == 0)));\n            }\n\n            if (CSScript.GlobalSettings != null &amp;&amp; CSScript.GlobalSettings.HideAutoGeneratedFiles == Settings.HideOptions.HideAll)\n                if (scriptFile != null)\n                    retval.Add(Path.GetFullPath(CSSEnvironment.GetCacheDirectory(Path.GetFullPath(scriptFile))));\n\n            return retval;\n        }\n\n        static string&#91;] SearchDirs\n        {\n            get { return searchDirsList.ToArray(); }\n        }\n\n        public class VS16IDE\n        {\n            static public bool isolating = false;\n\n            \/\/ public delegate string ProcessSourceFile(string srcFile, string projDir);\n\n            static public void IsolateProject(string scriptFile, string tempDir)\n            {\n                if (Directory.Exists(tempDir))\n                    Directory.Delete(tempDir, true);\n\n                RunPreScripts(scriptFile);\n                VS16IDE.isolating = true;\n\n                string solutionFile = CreateProject(scriptFile, tempDir, HandleImportedScripts, true);\n                string projectFile = Path.ChangeExtension(solutionFile, \".csproj\");\n\n                \/\/rename project files\n                string newSolutionFile = Path.Combine(tempDir, Path.GetFileNameWithoutExtension(scriptFile) + \".sln\");\n                string newProjectFile = Path.Combine(tempDir, Path.GetFileNameWithoutExtension(scriptFile) + \".csproj\");\n\n                File.Move(projectFile, newProjectFile);\n                File.Move(solutionFile, newSolutionFile);\n\n                ReplaceInFile(newSolutionFile,\n                              projectFile.GetFileNameWithoutExt(),\n                              newProjectFile.GetFileNameWithoutExt());\n\n                File.Delete(Path.ChangeExtension(solutionFile, \".csproj.user\"));\n                File.Delete(Path.Combine(Path.GetDirectoryName(solutionFile), \"wwf.layout\"));\n\n                Console.WriteLine(\"Script \" + Path.GetFileName(scriptFile) + \" is isolated to folder: \" + new DirectoryInfo(tempDir).FullName);\n            }\n\n            static public string HandleImportedScripts(string srcFile, string projDir)\n            {\n                var newFileName = Path.GetFileName(srcFile);\n\n                if (newFileName.StartsWith(\"i_\")) \/\/ rename imported files with `static main` to their original names\n                {\n                    \/\/ i_script_343543.cs\n                    int end = newFileName.LastIndexOf(\"_\");\n                    if (end != -1)\n                        newFileName = newFileName.Substring(0, end).Replace(\"i_\", \"\") + Path.GetExtension(newFileName);\n                }\n\n                string newFile = projDir.PathJoin(newFileName);\n\n                if (File.Exists(newFile))\n                    newFile = GetCopyName(newFile);\n\n                File.Copy(srcFile, newFile);\n                File.SetAttributes(newFile, FileAttributes.Normal);\n\n                try\n                {\n                    if (Path.GetFileName(srcFile).StartsWith(\"i_\"))\n                        File.Delete(srcFile);\n                }\n                catch { }\n                return newFile;\n            }\n\n            public static bool IsResxRequired(string scriptFile)\n            {\n                if (File.Exists(scriptFile))\n                {\n                    \/\/Form class containing InitializeComponent call require resx dependent designer\n                    \/\/SequentialWorkflowActivity  class contains InitializeComponent call but it does not require resx dependent designer\n                    string text = File.ReadAllText(scriptFile);\n\n                    return text.Contains(\"InitializeComponent();\") &amp;&amp;\n                           text.Contains(\"SequentialWorkflowActivity\") &amp;&amp;\n                           text.Contains(\"StateMachineWorkflowActivity\");\n                }\n                return false;\n            }\n\n            static public string CreateProject(string scriptFile, string tempDir)\n            {\n                return CreateProject(scriptFile, tempDir, null, false);\n            }\n\n            static string FindAssociatedXaml(string srcFile, string&#91;] srcFiles)\n            {\n                string retval = \"\";\n\n                if (srcFile.EndsWith(\".cs\"))\n                {\n                    if (Path.GetFileNameWithoutExtension(srcFile).EndsWith(\".xaml\", StringComparison.OrdinalIgnoreCase)) \/\/Window1.xaml.cs + Window1.xaml\n                    {\n                        retval = srcFile.GetDirName().PathJoin(Path.GetFileNameWithoutExtension(srcFile));\n                    }\n                    else\n                    {\n                        string expectedXAML = Path.GetFileNameWithoutExtension(srcFile) + \".xaml\";\n\n                        foreach (string file in srcFiles)\n                            if (Path.GetFileName(file).SameAs(expectedXAML))\n                                retval = file;\n                    }\n                }\n                return retval;\n            }\n\n            static private bool UsesPreprocessor(string file, out string precompiler)\n            {\n                precompiler = \"\";\n\n                if (!File.Exists(file))\n                    return false;\n\n                if (!Path.GetFileName(file).ToLower().StartsWith(\"debugvs\") &amp;&amp;\n                    !Path.GetFileName(file).ToLower().StartsWith(\"i_debugvs\".ToLower())) \/\/do not parse itself\n                {\n                    using (StreamReader sr = new StreamReader(file))\n                    {\n                        string code = sr.ReadToEnd();\n\n                        if (code != null)\n                        {\n                            int start = code.IndexOf(\"\/\/css_pre precompile\");\n\n                            if (start != -1)\n                            {\n                                start += \"\/\/css_pre\".Length;\n\n                                int end = code.IndexOf(\"(\", start);\n\n                                precompiler = code.Substring(start, end - start).Trim();\n\n                                precompiler = FileResolver.ResolveFile(precompiler, SearchDirs, \".cs\");\n                                return true;\n                            }\n                            else\n                                return false;\n                        }\n                        else\n                            return false;\n                    }\n                }\n                return false;\n            }\n\n            static string CreateProject(string scriptFile, string tempDir, Func&lt;string, string, string> fileHandler, bool copyLocalAsm)\n            {\n                string srcProjDir = @\"Lib\\Debug\\VS15.0\"; \/\/relative to CSSCRIPT_DIR\n                string scHomeDir = VS16IDE.GetEnvironmentVariable(\"CSSCRIPT_DIR\");\n                string projFile = Path.Combine(tempDir, \"DebugScript.csproj\");\n                string solutionFile = Path.Combine(tempDir, \"DebugScript.sln\");\n\n                \/\/copy project template\n                Directory.CreateDirectory(tempDir);\n\n                foreach (string file in Directory.GetFiles(Path.Combine(scHomeDir, srcProjDir)))\n                {\n                    if (Path.GetExtension(file) != \".resx\")\n                    {\n                        if (file.GetFileName().SameAs(\"AssemblyInfo.cs\"))\n                        {\n                            string code = File.ReadAllText(file)\n                                              .Replace(\"ScriptDebugger\", scriptFile.GetFileNameWithoutExt())\n                                              .Replace(\"ScriptFullPath\", scriptFile);\n\n                            File.WriteAllText(file.ChangeFileDir(tempDir), code);\n                        }\n                        else\n                        {\n                            File.Copy(file, file.ChangeFileDir(tempDir), true);\n                        }\n                    }\n                }\n\n                \/\/update project template with script specific data\n                var ide = new VS16IDE();\n\n                var parser = new ScriptParser(scriptFile, Script.SearchDirs, VS16IDE.isolating);\n\n                foreach (string dir in parser.SearchDirs)\n                    AddSearchDir(dir);\n\n                string resxSrcFile = scHomeDir.PathJoin(srcProjDir, \"Form1.resx\");\n                var isXAML = false;\n                var isWWF = false;\n\n                var importerdScripts = parser.SaveImportedScripts();\n                var precompilibleScripts = new List&lt;string&#91;]>();\n\n                string srcFile = scriptFile;\n                if (fileHandler != null) srcFile = fileHandler(scriptFile, tempDir);\n\n                isXAML = srcFile.ToLower().EndsWith(\".xaml\");\n\n                string associatedXaml = FindAssociatedXaml(srcFile, importerdScripts);\n\n                string precompiler = \"\";\n\n                if (UsesPreprocessor(srcFile, out precompiler))\n                    precompilibleScripts.Add(new string&#91;] { srcFile, precompiler });\n\n                if (VS16IDE.IsResxRequired(srcFile) &amp;&amp; associatedXaml == \"\")\n                    ide.InsertFile(srcFile, projFile, resxSrcFile, \"\");\n                else\n                {\n                    if (associatedXaml != \"\")\n                        ide.InsertXamlCSFile(srcFile, projFile, associatedXaml);\n                    else\n                        ide.InsertFile(srcFile, projFile, \"\", \"\");\n                }\n\n                foreach (string file in importerdScripts)\n                {\n                    if (UsesPreprocessor(file, out precompiler))\n                        precompilibleScripts.Add(new string&#91;] { file, precompiler });\n\n                    srcFile = file;\n                    if (fileHandler != null)\n                        srcFile = fileHandler(file, tempDir);\n\n                    associatedXaml = FindAssociatedXaml(srcFile, importerdScripts);\n                    isXAML = srcFile.ToLower().EndsWith(\".xaml\");\n                    if (!Path.GetFileName(srcFile).StartsWith(\"i_\") &amp;&amp; VS16IDE.IsResxRequired(srcFile) &amp;&amp; associatedXaml == \"\")\n                    {\n                        ide.InsertFile(srcFile, projFile, resxSrcFile, \"\");\n                    }\n                    else\n                    {\n                        if (associatedXaml != \"\")\n                            ide.InsertXamlCSFile(srcFile, projFile, associatedXaml);\n                        else\n                            ide.InsertFile(srcFile, projFile, \"\", \"\");\n                    }\n                }\n\n                if (isXAML)\n                    ide.InsertImport(@\"$(MSBuildBinPath)\\Microsoft.WinFX.targets\", projFile);\n\n                ArrayList referencedNamespaces = new ArrayList(parser.ReferencedNamespaces);\n\n                string&#91;] defaultAsms = (CSScript.GlobalSettings.DefaultRefAssemblies ?? \"\")\n                                        .Replace(\" \", \"\")\n                                        .Split(\";,\".ToCharArray());\n                referencedNamespaces.AddRange(defaultAsms);\n\n                if (precompilibleScripts.Count > 0)\n                {\n                    referencedNamespaces.Add(\"CSScriptLibrary\");\n\n                    Hashtable ht = new Hashtable();\n\n                    foreach (string&#91;] info in precompilibleScripts)\n                    {\n                        if (!ht.ContainsKey(info&#91;1])) \/\/to avoid duplication\n                        {\n                            ht&#91;info&#91;1]] = true;\n\n                            string t = Path.GetDirectoryName(scriptFile);\n\n                            ide.InsertFile(Path.Combine(Path.GetDirectoryName(scriptFile), info&#91;1]), projFile, \"\", \"\");\n                        }\n                    }\n\n                    string commands = \"\";\n\n                    foreach (string&#91;] info in precompilibleScripts)\n                        commands += \"cscs.exe \\\"\" + Path.Combine(Path.GetDirectoryName(scriptFile), info&#91;1]) + \"\\\" \\\"\" + info&#91;0] + \"\\\" \\\"\/primary:\" + scriptFile + \"\\\"\" + \"\\r\\n\";\n\n                    string firstPrecompiler = (precompilibleScripts&#91;0] as string&#91;])&#91;1];\n                    ide.InsertFile(Path.Combine(scHomeDir, \"Lib\\\\precompile.part.cs\"), projFile, \"\", firstPrecompiler);\n                    ide.InsertPreBuildEvent(commands, projFile);\n                    \/\/&lt;PropertyGroup>\n                    \/\/&lt;PreBuildEvent>cscs.exe \"C:\\cs-script\\Dev\\Macros C#\\precompile.cs\" \"C:\\cs-script\\Dev\\Macros C#\\code.cs\"&lt;\/PreBuildEvent>\n                    \/\/&lt;\/PropertyGroup>\n                }\n\n                foreach (string name in referencedNamespaces)\n                {\n                    bool ignore = false;\n\n                    foreach (string ignoreName in parser.IgnoreNamespaces)\n                        if (ignore = (name == ignoreName))\n                            break;\n\n                    if (ignore)\n                        continue;\n\n                    string&#91;] asmFiles = AssemblyResolver.FindAssembly(name, SearchDirs);\n\n                    foreach (string file in asmFiles)\n                    {\n                        if (!isWWF &amp;&amp; file.ToLower().IndexOf(\"system.workflow.runtime\") != -1)\n                            isWWF = true;\n\n                        if (!copyLocalAsm || file.IndexOf(\"assembly\\\\GAC\") != -1 || file.IndexOf(\"assembly\/GAC\") != -1)\n                            ide.InsertReference(file, projFile);\n                        else\n                        {\n                            string asmCopy = Path.Combine(tempDir, Path.GetFileName(file));\n                            File.Copy(file, asmCopy, true);\n\n                            ide.InsertReference(Path.GetFileName(asmCopy), projFile);\n                        }\n                    }\n                }\n\n                List&lt;string> refAssemblies = new List&lt;string>(parser.ReferencedAssemblies);\n\n                \/\/process referenced assemblies from the compiler options:\n                \/\/   \/r:LibA=LibA.dll \/r:LibB=LibB.dll\n                foreach (string optionsDef in parser.CompilerOptions)\n                    foreach (string optionArg in ParseArguments(optionsDef))\n                    {\n                        string&#91;] keyValue = optionArg.Split(new char&#91;] { ':' }, 2);\n\n                        if (keyValue&#91;0] == \"\/r\" || keyValue&#91;0] == \"\/reference\")\n                        {\n                            refAssemblies.Add(keyValue.Last());\n                        }\n                    }\n\n                \/\/Note we are suppressing package downloads as it is not the first time we are\n                \/\/loading the script so we already tried to download the packages\n                foreach (string asm in parser.ResolvePackages(true))\n                    refAssemblies.Add(asm);\n\n                foreach (string assemblyDef in refAssemblies) \/\/some assemblies were referenced from code\n                {\n                    string&#91;] tokens = assemblyDef.Split(new char&#91;] { '=' }, 2);\n\n                    string asm = tokens.Last();\n                    string aliase = null;\n\n                    if (tokens.Length > 1)\n                        aliase = tokens.First();\n\n                    foreach (string file in AssemblyResolver.FindAssembly(asm, SearchDirs))\n                    {\n                        if (!isWWF &amp;&amp; file.ToLower().IndexOf(\"system.workflow.runtime\") != -1)\n                            isWWF = true;\n\n                        if (!copyLocalAsm || file.IndexOf(\"assembly\\\\GAC\") != -1 || file.IndexOf(\"assembly\\\\GAC\") != -1)\n                            ide.InsertReference(file, projFile, aliase);\n                        else\n                        {\n                            string asmCopy = Path.Combine(tempDir, Path.GetFileName(file));\n\n                            if (Path.IsPathRooted(file) || File.Exists(file))\n                                File.Copy(file, asmCopy, true);\n                            ide.InsertReference(Path.GetFileName(asmCopy), projFile, aliase);\n                        }\n                    }\n                }\n\n                \/\/adjust project settings\n                if (isWWF)\n                {\n                    ide.InsertProjectTypeGuids(\"{14822709-B5A1-4724-98CA-57A101D1B079};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\", projFile);\n                    ide.InsertImport(@\"$(MSBuildExtensionsPath)\\Microsoft\\Windows Workflow Foundation\\v3.0\\Workflow.Targets\", projFile);\n\n                    foreach (string file in importerdScripts)\n                        if (file.ToLower().IndexOf(\"designer.cs\") != -1)\n                        {\n                            string className = Path.GetFileNameWithoutExtension(file.ToLower()).Replace(\".designer\", \"\");\n                            string template = Path.Combine(tempDir, \"wwf.layout\");\n                            string layoutFile = file.Replace(\"designer.cs\", \"layout\");\n\n                            if (copyLocalAsm) \/\/isolating\n                                layoutFile = Path.Combine(Path.GetDirectoryName(projFile), Path.GetFileName(layoutFile));\n\n                            File.Copy(template, layoutFile, true);\n                            ReplaceInFile(layoutFile, \"WFInitialState\", className + \"InitialState\");\n\n                            ide.InsertResource(layoutFile, projFile);\n                        }\n                }\n\n                CSharpParser fileParser = new CSharpParser(scriptFile, true, new string&#91;] { \"\/\/css_dbg\", \"\/\/css_args\", \"\/\/css_co\" });\n\n                \/\/foreach (string statement in fileParser.CustomDirectives&#91;\"\/\/css_dbg\"] as List&lt;string>)\/\/should be  reenabled when CS-Script is compiled for  .NET 2.0\n                foreach (string statement in fileParser.CustomDirectives&#91;\"\/\/css_dbg\"] as IEnumerable)\n                    foreach (string directive in statement.Split(','))\n                    {\n                        string d = directive.Trim();\n\n                        if (d.StartsWith(\"\/t:\"))\n                            ide.SetOutputType(d.Substring(\"\/t:\".Length), projFile);\n                        else if (d.StartsWith(\"\/platform:\"))\n                            ide.SetPlatformType(d.Substring(\"\/platform:\".Length), projFile, solutionFile);\n                        else if (d.Trim().StartsWith(\"\/args:\"))\n                            ide.SetArguments(d.Substring(\"\/args:\".Length), projFile + \".user\");\n                    }\n\n                \/\/foreach (string statement in fileParser.CustomDirectives&#91;\"\/\/css_args\"] as List&lt;string>) \/\/should be  reenabled when CS-Script is compiled for  .NET 2.0\n                foreach (string statement in fileParser.CustomDirectives&#91;\"\/\/css_args\"] as IEnumerable)\n                    foreach (string directive in statement.Split(','))\n                    {\n                        string d = directive.Trim();\n\n                        if (d.StartsWith(\"\/co\"))\n                        {\n                            string&#91;] compilerOptions = d.Substring(4).Split(',');\n\n                            foreach (string option in compilerOptions)\n                            {\n                                string o = option.Trim();\n\n                                if (o.StartsWith(\"\/unsafe\"))\n                                    ide.SetAllowUnsafe(projFile);\n                                else if (o.StartsWith(\"\/platform:\"))\n                                    ide.SetPlatformType(o.Substring(\"\/platform:\".Length), projFile, solutionFile);\n                            }\n                        }\n                    }\n\n                foreach (string statement in fileParser.CustomDirectives&#91;\"\/\/css_co\"] as IEnumerable)\n                    foreach (string directive in statement.Split(','))\n                    {\n                        string d = directive.Trim();\n\n                        if (d.StartsWith(\"\/unsafe\"))\n                            ide.SetAllowUnsafe(projFile);\n                        else if (d.StartsWith(\"\/platform:\"))\n                            ide.SetPlatformType(d.Substring(\"\/platform:\".Length), projFile, solutionFile);\n                    }\n\n                Settings settings = GetSystemWideSettings();\n\n                if (settings != null)\n                    ide.SetTargetFramework(settings.TargetFramework, projFile);\n\n                ide.SetWorkingDir(Path.GetDirectoryName(scriptFile), projFile + \".user\");\n\n                if (Environment.GetEnvironmentVariable(\"CSSCRIPT_VS_DROPASMINFO\") != null &amp;&amp; !VS16IDE.isolating)\n                    ide.RemoveFile(\"AssemblyInfo.cs\", projFile);\n\n                string appConfigFile = \"\";\n\n                if (File.Exists(Path.ChangeExtension(scriptFile, \".cs.config\")))\n                    appConfigFile = Path.ChangeExtension(scriptFile, \".cs.config\");\n                else if (File.Exists(Path.ChangeExtension(scriptFile, \".exe.config\")))\n                    appConfigFile = Path.ChangeExtension(scriptFile, \".exe.config\");\n\n                if (appConfigFile != \"\")\n                    ide.InsertAppConfig(appConfigFile, projFile);\n\n                \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n                \/\/rename project files\n                \/\/'#' is an illegal character for the project\/solution file name\n                string newSolutionFile = Path.Combine(tempDir, scriptFile.GetFileNameWithoutExt().Replace(\"#\", \"Sharp\") + \" (script).sln\");\n                string newProjectFile = Path.Combine(tempDir, newSolutionFile.GetFileNameWithoutExt().Replace(\"#\", \"Sharp\") + \".csproj\");\n\n                FileMove(solutionFile, newSolutionFile);\n                FileMove(projFile, newProjectFile);\n                FileMove(projFile + \".user\", newProjectFile + \".user\");\n\n                ReplaceInFile(newSolutionFile, Path.GetFileNameWithoutExtension(projFile), Path.GetFileNameWithoutExtension(newProjectFile));\n                ReplaceInFile(newProjectFile, \"DebugScript\", Path.GetFileNameWithoutExtension(scriptFile));\n\n                \/\/remove xmlns=\"\"\n                VSProjectDoc.FixFile(newProjectFile);\n                VSProjectDoc.FixFile(newProjectFile + \".user\");\n\n                \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n                return newSolutionFile;\n            }\n\n            \/\/very primitive command-line parser\n            static string&#91;] ParseArguments(string commandLine)\n            {\n                var parmChars = commandLine.ToCharArray();\n                var inSingleQuote = false;\n                var inDoubleQuote = false;\n\n                for (var index = 0; index &lt; parmChars.Length; index++)\n                {\n                    if (parmChars&#91;index] == '\"' &amp;&amp; !inSingleQuote)\n                    {\n                        inDoubleQuote = !inDoubleQuote;\n                        parmChars&#91;index] = '\\n';\n                    }\n                    if (parmChars&#91;index] == '\\'' &amp;&amp; !inDoubleQuote)\n                    {\n                        inSingleQuote = !inSingleQuote;\n                        parmChars&#91;index] = '\\n';\n                    }\n                    if (!inSingleQuote &amp;&amp; !inDoubleQuote &amp;&amp; parmChars&#91;index] == ' ')\n                        parmChars&#91;index] = '\\n';\n                }\n                return (new string(parmChars)).Split(new&#91;] { '\\n' }, StringSplitOptions.RemoveEmptyEntries);\n            }\n\n            static void FileMove(string src, string dest)\n            {\n                if (File.Exists(dest))\n                    File.Delete(dest);\n                File.Move(src, dest);\n            }\n\n            static void ReplaceInFile(string file, string oldValue, string newValue)\n            {\n                ReplaceInFile(file, new string&#91;] { oldValue }, new string&#91;] { newValue });\n            }\n\n            static void ReplaceInFile(string file, string&#91;] oldValue, string&#91;] newValue)\n            {\n                string content = \"\";\n\n                using (StreamReader sr = new StreamReader(file))\n                    content = sr.ReadToEnd();\n\n                for (int i = 0; i &lt; oldValue.Length; i++)\n                    content = content.Replace(oldValue&#91;i], newValue&#91;i]);\n\n                using (StreamWriter sw = new StreamWriter(file))\n                    sw.Write(content);\n            }\n\n            public void InsertImport(string importStr, string projFile)\n            {\n                \/\/&lt;Import Project=\"$(MSBuildBinPath)\\Microsoft.WinFX.targets\" \/>\n                VSProjectDoc doc = new VSProjectDoc(projFile);\n\n                XmlElement elem = doc.CreateElement(\"Import\");\n                XmlAttribute newAttr;\n\n                newAttr = doc.CreateAttribute(\"Project\");\n                newAttr.Value = importStr;\n                elem.Attributes.Append(newAttr);\n\n                XmlNode node = doc.SelectFirstNode(\"\/\/Project\");\n                node.AppendChild(elem);\n\n                doc.Save(projFile);\n            }\n\n            public void InsertResource(string file, string projFile)\n            {\n                \/\/&lt;EmbeddedResource Include=\"Workflow1.layout\">\n                \/\/    &lt;DependentUpon>Workflow1.cs&lt;\/DependentUpon>\n                \/\/&lt;\/EmbeddedResource>\n\n                VSProjectDoc doc = new VSProjectDoc(projFile);\n\n                XmlElement group = doc.CreateElement(\"ItemGroup\");\n                XmlElement res = doc.CreateElement(\"EmbeddedResource\");\n\n                XmlAttribute newAttr;\n\n                newAttr = doc.CreateAttribute(\"Include\");\n                newAttr.Value = file;\n                res.Attributes.Append(newAttr);\n\n                XmlElement dependency = doc.CreateElement(\"DependentUpon\");\n                dependency.InnerText = Path.ChangeExtension(Path.GetFileName(file), \".cs\");\n\n                res.AppendChild(dependency);\n                group.AppendChild(res);\n\n                doc.SelectFirstNode(\"\/\/Project\").AppendChild(group);\n\n                doc.Save(projFile);\n            }\n\n            public void InsertPreBuildEvent(string commands, string projFile)\n            {\n                \/\/&lt;PropertyGroup>\n                \/\/&lt;PreBuildEvent>\n                \/\/cscs.exe \"C:\\cs-script\\Dev\\Macros C#\\precompile.cs\" \"C:\\cs-script\\Dev\\Macros C#\\code.cs\"\n                \/\/&lt;\/PreBuildEvent>\n                \/\/&lt;\/PropertyGroup>\n                VSProjectDoc doc = new VSProjectDoc(projFile);\n\n                XmlElement elem = doc.CreateElement(\"PropertyGroup\");\n                XmlElement elem1 = doc.CreateElement(\"PreBuildEvent\");\n                elem1.InnerXml = commands;\n                elem.AppendChild(elem1);\n\n                doc.SelectFirstNode(\"\/\/Project\").AppendChild(elem);\n\n                doc.Save(projFile);\n            }\n\n            public void InsertProjectTypeGuids(string guids, string projFile)\n            {\n                \/\/&lt;ProjectTypeGuids>{14822709-B5A1-4724-98CA-57A101D1B079};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}&lt;\/ProjectTypeGuids>\n                VSProjectDoc doc = new VSProjectDoc(projFile);\n\n                XmlElement elem = doc.CreateElement(\"ProjectTypeGuids\");\n                elem.InnerXml = guids;\n\n                doc.SelectFirstNode(\"\/\/Project\/PropertyGroup\/Configuration\").ParentNode.AppendChild(elem);\n                doc.Save(projFile);\n            }\n\n            public void RemoveFile(string file, string projFile)\n            {\n                try\n                {\n                    VSProjectDoc doc = new VSProjectDoc(projFile);\n\n                    XmlNode node = doc.SelectFirstNode(\"\/\/Project\/ItemGroup\/Compile&#91;@Include='\" + file + \"']\");\n                    node.ParentNode.RemoveChild(node);\n\n                    doc.Save(projFile);\n                }\n                catch (Exception e)\n                {\n                    MessageBox.Show(\"Specified file could not be inserted to the temp project:\\n\" + e.Message);\n                }\n            }\n\n            public void InsertFile(string scriptFile, string projFile, string resxSrcFile, string parentFile)\n            {\n                string srcFile = scriptFile;\n\n                if (VS16IDE.isolating)\n                    srcFile = Path.GetFileName(srcFile); \/\/remove absolute path\n\n                try\n                {\n                    string parent = \"\";\n\n                    if (srcFile.ToLower().EndsWith(\".designer.cs\")) \/\/needs to be dependent on 'base include'\n                    {\n                        parent = Path.GetFileName(srcFile);\n                        parent = parent.Substring(0, parent.Length - \".designer.cs\".Length) + \".cs\";\n                    }\n                    if (srcFile.ToLower().EndsWith(\".g.cs\")) \/\/needs to be dependent on 'base include'\n                    {\n                        parent = Path.GetFileName(srcFile);\n                        parent = parent.Substring(0, parent.Length - \".g.cs\".Length) + \".cs\";\n                    }\n                    if (srcFile.ToLower().EndsWith(\".part.cs\")) \/\/needs to be dependent on 'base include'\n                    {\n                        parent = Path.GetFileName(srcFile);\n                        parent = parent.Substring(0, parent.Length - \".part.cs\".Length) + \".cs\";\n                    }\n                    if (parentFile != null &amp;&amp; parentFile != \"\")\n                        parent = parentFile;\n\n                    \/\/&lt;Compile Include=\"C:\\cs-script\\Samples\\tick.cs\" \/>\n\n                    \/\/NOTE: VS7.1 is able to create .resx file for linked (not in the .proj directory) .cs files correctly. However VS9.0 can do this only for\n                    \/\/non-linked source files. Yes this is a new VS bug. Thus I have to create .resex in case if the file contains\n                    \/\/the class inherited from System.Windows.Form.\n\n                    VSProjectDoc doc = new VSProjectDoc(projFile);\n\n                    \/\/Create a new node.\n                    XmlElement elem = doc.CreateElement(srcFile.EndsWith(\".xaml\") ? \"Page\" : \"Compile\");\n                    XmlAttribute newAttr;\n\n                    newAttr = doc.CreateAttribute(\"Include\");\n                    newAttr.Value = srcFile;\n                    elem.Attributes.Append(newAttr);\n\n                    if (parent != \"\")\n                    {\n                        \/\/&lt;DependentUpon>Form1.cs&lt;\/DependentUpon>\n                        XmlElement nestedElem = doc.CreateElement(\"DependentUpon\");\n                        nestedElem.InnerText = Path.GetFileName(parent);\n                        elem.AppendChild(nestedElem);\n                    }\n                    else if (srcFile.ToLower().EndsWith(\".includes.cs\"))\n                    {\n                        XmlElement nestedElem = doc.CreateElement(\"Link\");\n                        nestedElem.InnerText = \"Includes\\\\\" + Path.GetFileName(srcFile);\n                        elem.AppendChild(nestedElem);\n                    }\n\n                    XmlNode contentsNode = doc.SelectNodes(\"\/\/Project\/ItemGroup\")&#91;1];\n\n                    contentsNode.AppendChild(elem);\n\n                    if (resxSrcFile != \"\")\n                    {\n                        \/\/&lt;EmbeddedResource Include=\"G:\\Dev\\WindowsApplication1\\Form1.resx\">\n                        \/\/&lt;DependentUpon>Form1.cs&lt;\/DependentUpon>\n                        \/\/&lt;\/EmbeddedResource>\n                        string resxFile = Path.ChangeExtension(srcFile, \".resx\");\n                        File.Copy(resxSrcFile, Path.Combine(Path.GetDirectoryName(scriptFile), resxFile), true);\n\n                        elem = doc.CreateElement(\"EmbeddedResource\");\n                        newAttr = doc.CreateAttribute(\"Include\");\n                        newAttr.Value = resxFile;\n                        elem.Attributes.Append(newAttr);\n\n                        XmlElement nestedElem = doc.CreateElement(\"DependentUpon\");\n                        nestedElem.InnerText = Path.GetFileName(srcFile);\n                        elem.AppendChild(nestedElem);\n\n                        contentsNode.AppendChild(elem);\n                    }\n                    doc.Save(projFile);\n                }\n                catch (Exception e)\n                {\n                    MessageBox.Show(\"Specified file could not be inserted to the temp project:\\n\" + e.Message);\n                }\n            }\n\n            public void InsertAppConfig(string appConfigFile, string projFile)\n            {\n                string destFile = Path.Combine(Path.GetDirectoryName(projFile), \"app.config\");\n\n                if (File.Exists(destFile))\n                {\n                    File.SetAttributes(destFile, FileAttributes.Normal);\n                    File.Delete(destFile);\n                }\n                using (StreamReader sr = new StreamReader(appConfigFile))\n                using (StreamWriter sw = new StreamWriter(destFile))\n                {\n                    sw.Write(sr.ReadToEnd());\n                    sw.WriteLine(\"&lt;!-- read-only copy of \" + appConfigFile + \" -->\");\n                }\n\n                File.SetAttributes(destFile, FileAttributes.ReadOnly);\n\n                try\n                {\n                    VSProjectDoc doc = new VSProjectDoc(projFile);\n\n                    XmlElement group = doc.CreateElement(\"ItemGroup\");\n                    XmlElement none = doc.CreateElement(\"None\");\n                    XmlAttribute attr = doc.CreateAttribute(\"Include\");\n                    attr.Value = \"app.config\";\n\n                    group.AppendChild(none);\n                    none.Attributes.Append(attr);\n\n                    doc.SelectFirstNode(\"\/\/Project\").AppendChild(group);\n\n                    doc.Save(projFile);\n                }\n                catch (Exception e)\n                {\n                    MessageBox.Show(\"Specified file could not be inserted to the temp project:\\n\" + e.Message);\n                }\n            }\n\n            public void InsertXamlCSFile(string scriptFile, string projFile, string xamlSrcFile)\n            {\n                string srcFile = scriptFile;\n\n                if (VS16IDE.isolating)\n                    srcFile = Path.GetFileName(srcFile); \/\/remove absolute path\n\n                try\n                {\n                    VSProjectDoc doc = new VSProjectDoc(projFile);\n\n                    \/\/Create a new node.\n                    XmlElement elem = doc.CreateElement(srcFile.EndsWith(\".xaml\") ? \"Page\" : \"Compile\");\n                    XmlAttribute newAttr;\n\n                    newAttr = doc.CreateAttribute(\"Include\");\n                    newAttr.Value = srcFile;\n                    elem.Attributes.Append(newAttr);\n\n                    \/\/&lt;DependentUpon>Window1.xaml&lt;\/DependentUpon>\n                    XmlElement nestedElem = doc.CreateElement(\"DependentUpon\");\n                    nestedElem.InnerText = Path.GetFileName(xamlSrcFile);\n                    elem.AppendChild(nestedElem);\n\n                    doc.SelectNodes(\"\/\/Project\/ItemGroup\")&#91;1].AppendChild(elem);\n\n                    doc.Save(projFile);\n                }\n                catch (Exception e)\n                {\n                    MessageBox.Show(\"Specified file could not be inserted to the temp project:\\n\" + e.Message);\n                }\n            }\n\n            public void InsertReference(string asmFile, string projFile, string aliase = null)\n            {\n                string refFile = asmFile;\n\n                if (VS16IDE.isolating || asmFile.IndexOf(\"assembly\\\\GAC\") != -1 || asmFile.IndexOf(\"assembly\/GAC\") != -1)\n                    refFile = Path.GetFileName(refFile); \/\/remove absolute path\n\n                try\n                {\n                    \/\/&lt;Reference Include=\"CSScriptLibrary\">\n                    \/\/  &lt;SpecificVersion>False&lt;\/SpecificVersion>\n                    \/\/  &lt;HintPath>..\\VS9.0\\CSScriptLibrary.dll&lt;\/HintPath>\n                    \/\/  &lt;Aliases>CSScript&lt;\/Aliases>\n                    \/\/&lt;\/Reference>\n\n                    VSProjectDoc doc = new VSProjectDoc(projFile);\n\n                    \/\/Create a new node.\n                    XmlElement elem = doc.CreateElement(\"Reference\");\n                    XmlAttribute newAttr;\n\n                    newAttr = doc.CreateAttribute(\"Include\");\n                    newAttr.Value = Path.GetFileNameWithoutExtension(refFile);\n                    elem.Attributes.Append(newAttr);\n\n                    XmlElement elemSpecVer = doc.CreateElement(\"SpecificVersion\");\n                    elemSpecVer.InnerText = \"False\";\n                    elem.AppendChild(elemSpecVer);\n\n                    XmlElement elemPath = doc.CreateElement(\"HintPath\");\n                    elemPath.InnerText = refFile;\n                    elem.AppendChild(elemPath);\n\n                    if (aliase != null)\n                    {\n                        XmlElement elemAliase = doc.CreateElement(\"Aliases\");\n                        elemAliase.InnerText = aliase;\n                        elem.AppendChild(elemAliase);\n                    }\n\n                    doc.SelectFirstNode(\"\/\/Project\/ItemGroup\").AppendChild(elem);\n\n                    doc.Save(projFile);\n                }\n                catch (Exception e)\n                {\n                    MessageBox.Show(\"Specified reference could not be inserted into the temp project:\\n\" + e.Message);\n                }\n            }\n\n            public void SetWorkingDir(string dir, string file)\n            {\n                try\n                {\n                    \/\/&lt;PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \">\n                    \/\/  &lt;StartWorkingDirectory>C:\\Program Files\\Google\\&lt;\/StartWorkingDirectory>\n                    \/\/&lt;\/PropertyGroup>\n\n                    VSProjectDoc doc = new VSProjectDoc(file);\n\n                    XmlElement elem = doc.CreateElement(\"StartWorkingDirectory\");\n                    elem.InnerText = dir;\n\n                    XmlNodeList nodes = doc.SelectNodes(\"\/\/Project\/PropertyGroup\");\n                    nodes&#91;0].AppendChild(elem);\n                    nodes&#91;1].AppendChild(elem.Clone());\n\n                    doc.Save(file);\n                }\n                catch (Exception e)\n                {\n                    MessageBox.Show(\"Specified 'working directory' could not be set for the temp project:\\n\" + e.Message);\n                }\n            }\n\n            public void SetArguments(string args, string file)\n            {\n                try\n                {\n                    \/\/&lt;PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \">\n                    \/\/  &lt;StartArguments>test&lt;\/StartArguments>\n                    \/\/&lt;\/PropertyGroup>\n\n                    VSProjectDoc doc = new VSProjectDoc(file);\n\n                    XmlElement elem = doc.CreateElement(\"StartArguments\");\n                    elem.InnerText = args;\n\n                    XmlNodeList nodes = doc.SelectNodes(\"\/\/Project\/PropertyGroup\");\n                    nodes&#91;0].AppendChild(elem);\n                    nodes&#91;1].AppendChild(elem.Clone());\n\n                    doc.Save(file);\n                }\n                catch (Exception e)\n                {\n                    MessageBox.Show(\"Specified 'working directory' could not be set for the temp project:\\n\" + e.Message);\n                }\n            }\n\n            public void SetAllowUnsafe(string file)\n            {\n                try\n                {\n                    \/\/&lt;PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \">\n                    \/\/ &lt;AllowUnsafeBlocks>true&lt;\/AllowUnsafeBlocks>\n                    \/\/&lt;\/PropertyGroup>\n                    VSProjectDoc doc = new VSProjectDoc(file);\n\n                    \/\/Create a new node.\n                    XmlElement elem = doc.CreateElement(\"AllowUnsafeBlocks\");\n                    elem.InnerText = \"true\";\n\n                    XmlNodeList nodes = doc.SelectNodes(\"\/\/Project\/PropertyGroup\");\n                    nodes&#91;1].AppendChild(elem);\n                    nodes&#91;2].AppendChild(elem.Clone());\n\n                    doc.Save(file);\n                }\n                catch (Exception e)\n                {\n                    MessageBox.Show(\"Specified 'unsafe' could not be set for the temp project:\\n\" + e.Message);\n                }\n            }\n\n            public void SetOutputType(string type, string file)\n            {\n                try\n                {\n                    \/\/&lt;OutputType>Exe&lt;\/OutputType>\n                    ReplaceInFile(file, \"&lt;OutputType>Exe&lt;\/OutputType>\", \"&lt;OutputType>\" + type + \"&lt;\/OutputType>\");\n                }\n                catch (Exception e)\n                {\n                    MessageBox.Show(\"Specified 'working directory' could not be set for the temp project:\\n\" + e.Message);\n                }\n            }\n\n            public void SetTargetFramework(string target, string file)\n            {\n                try\n                {\n                    \/\/&lt;TargetFrameworkVersion>v4.0&lt;\/TargetFrameworkVersion>\n                    ReplaceInFile(file, \"&lt;TargetFrameworkVersion>v4.0&lt;\/TargetFrameworkVersion>\", \"&lt;TargetFrameworkVersion>\" + target + \"&lt;\/TargetFrameworkVersion>\");\n                }\n                catch (Exception e)\n                {\n                    MessageBox.Show(\"Specified 'working directory' could not be set for the temp project:\\n\" + e.Message);\n                }\n            }\n\n            public void SetPlatformType(string type, string file, string solutionFile)\n            {\n                try\n                {\n                    \/\/&lt;PlatformTarget>x86&lt;\/PlatformTarget>\n                    VSProjectDoc doc = new VSProjectDoc(file);\n\n                    \/\/Create a new node.\n                    XmlNodeList existingElement = doc.SelectNodes(\"\/\/Project\/PropertyGroup\/PlatformTarget\");\n                    XmlElement elem;\n\n                    if (existingElement.Count > 0)\n                        elem = (XmlElement)existingElement&#91;0];\n                    else\n                        elem = doc.CreateElement(\"PlatformTarget\");\n\n                    elem.InnerText = type;\n\n                    XmlNodeList nodes = doc.SelectNodes(\"\/\/Project\/PropertyGroup\");\n                    nodes&#91;1].AppendChild(elem);\n                    nodes&#91;2].AppendChild(elem.Clone());\n\n                    doc.Save(file);\n                    ReplaceInFile(file, \"AnyCPU\", \"x86\");\n                    ReplaceInFile(solutionFile, \"AnyCPU\", \"x86\");\n                    ReplaceInFile(solutionFile, \"Any CPU\", \"x86\");\n                }\n                catch (Exception e)\n                {\n                    MessageBox.Show(\"Specified '\" + type + \"' could not be set for the temp project:\\n\" + e.Message);\n                }\n            }\n\n            public void SetProjectTypeGuids(string type, string file)\n            {\n                try\n                {\n                    \/\/&lt;ProjectTypeGuids>&lt;\/ProjectTypeGuids>\n                    if (type != null &amp;&amp; type != \"\")\n                        ReplaceInFile(file, \"&lt;ProjectTypeGuids>&lt;\/ProjectTypeGuids>\", \"\");\n                    else\n                        ReplaceInFile(file, \"&lt;ProjectTypeGuids>&lt;\/ProjectTypeGuids>\", \"&lt;ProjectTypeGuids>\" + type + \"&lt;\/ProjectTypeGuids>\");\n                }\n                catch (Exception e)\n                {\n                    MessageBox.Show(\"Specified 'working directory' could not be set for the temp project:\\n\" + e.Message);\n                }\n            }\n\n            static public string&#91;]&#91;] GetAvailableIDE()\n            {\n                ArrayList retval = new ArrayList();\n                string name = \"\";\n                string hint = \"\";\n                string command = \"\";\n\n                string scHomeDir = GetEnvironmentVariable(\"CSSCRIPT_DIR\");\n\n                if (GetIDEFile() != \"&lt;not defined>\")\n                {\n                    name = \"Open with VS2017\";\n                    hint = \"\\t- Open with MS Visual Studio 2017\";\n                    command = \"\\\"\" + scHomeDir + \"\\\\csws.exe\\\" \/c \\\"\" + scHomeDir + \"\\\\lib\\\\DebugVS15.0.cs\\\" \\\"%1\\\"\";\n                    retval.Add(new string&#91;] { name, hint, command });\n                }\n\n                return (string&#91;]&#91;])retval.ToArray(typeof(string&#91;]));\n            }\n\n            static public string GetIDEFile()\n            {\n                string retval = \"&lt;not defined>\";\n\n                try\n                {\n                    var vsWhere = new Process();\n                    vsWhere.StartInfo.FileName = Path.Combine(GetProgramFilesDirectory(), @\"Microsoft Visual Studio\\Installer\\vswhere.exe\");\n                    vsWhere.StartInfo.Arguments = \"-version \\\"16.0\\\" -property installationPath\";\n                    vsWhere.StartInfo.UseShellExecute = false;\n                    vsWhere.StartInfo.CreateNoWindow = true;\n                    vsWhere.StartInfo.RedirectStandardOutput = true;\n\n                    vsWhere.Start();\n                    vsWhere.WaitForExit();\n\n                    retval = Path.Combine(vsWhere.StandardOutput.ReadToEnd().Trim(), @\"Common7\\IDE\\devenv.exe\");\n                }\n                catch { }\n                return retval;\n            }\n\n            static public string GetProgramFilesDirectory()\n            {\n                string programFiles = Environment.GetEnvironmentVariable(\"ProgramFiles(x86)\");\n                if (String.IsNullOrEmpty(programFiles))\n                {\n                    programFiles = Environment.GetEnvironmentVariable(\"ProgramFiles\");\n                }\n                return programFiles;\n            }\n\n            static public string GetEnvironmentVariable(string name)\n            {\n                \/\/It is important in the all \"installation\" scripts to have reliable GetEnvironmentVariable().\n                \/\/Under some circumstances freshly set environment variable CSSCRIPT_DIR cannot be obtained with\n                \/\/Environment.GetEnvironmentVariable(). For example when running under Total Commander or similar\n                \/\/shell utility. Even SendMessageTimeout does not help in all cases. That is why GetEnvironmentVariable\n                \/\/is reimplemented here.\n                object value = Registry.LocalMachine.OpenSubKey(@\"SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment\").GetValue(name);\n                return value == null ? null : value.ToString();\n            }\n\n            static private string GetCopyName(string file)\n            {\n                string retval = file;\n                int i = 1;\n\n                while (File.Exists(retval))\n                {\n                    retval = Path.Combine(Path.GetDirectoryName(file), \"Copy\" + (i == 1 ? \" of \" : \" (\" + i.ToString() + \") \") + Path.GetFileName(file));\n                    i++;\n                }\n                return retval;\n            }\n\n            static public string&#91;] GetImportedScripts(string projFile)\n            {\n                ArrayList retval = new ArrayList();\n                XmlDocument doc = new XmlDocument();\n                doc.Load(projFile);\n\n                foreach (XmlNode child in doc.GetElementsByTagName(\"Compile\"))\n                {\n                    foreach (XmlAttribute attribute in child.Attributes)\n                    {\n                        if (attribute != null &amp;&amp; attribute.Name == \"Include\")\n                            retval.Add(attribute.Value.ToString().ToString());\n                    }\n                }\n                return (string&#91;])retval.ToArray(typeof(string));\n            }\n\n            internal static void RefreshProject(string projFile)\n            {\n                string&#91;] content = VS16IDE.GetImportedScripts(projFile);\n\n                foreach (string file in content)    \/\/remove original imported files\n                {\n                    if (Path.GetFileName(file).StartsWith(\"i_\")) \/\/imported modified files have name \"i_file_XXXXXX.cs>\"\n                    {\n                        try\n                        {\n                            File.SetAttributes(file, FileAttributes.Normal);\n                            File.Delete(file);\n                        }\n                        catch { }\n                    }\n                }\n                \/\/regenerate project\n                scriptFile = ResolveScriptFile(content&#91;0]);\n                RunPreScripts(scriptFile);\n\n                string newSolution = VS16IDE.CreateProject(content&#91;0], Path.GetDirectoryName(projFile));\n                string&#91;] newContent = VS16IDE.GetImportedScripts(Path.ChangeExtension(newSolution, \".csproj\"));\n\n                \/\/remove not needed .resx files from includes (not imported) files\n                for (int i = 1; i &lt; content.Length; i++)\n                {\n                    string file = content&#91;i];\n                    bool used = false;\n\n                    if (!Path.GetFileName(file).StartsWith(\"i_\")) \/\/not imported script file\n                    {\n                        foreach (string newFile in newContent)\n                            if (used = (String.Compare(newFile, file, true) == 0))\n                                break;\n                        try\n                        {\n                            if (!used)\n                            {\n                                if (File.Exists(Path.ChangeExtension(file, \".resx\")))\n                                    File.Delete(Path.ChangeExtension(file, \".resx\"));\n                                else if (File.Exists(Path.ChangeExtension(file, \".layout\")))\n                                    File.Delete(Path.ChangeExtension(file, \".layout\"));\n                            }\n                        }\n                        catch { }\n                    }\n                }\n            }\n        }\n\n        static void RunScript(string scriptFileCmd)\n        {\n            Process myProcess = new Process();\n            myProcess.StartInfo.FileName = \"cscs.exe\";\n            myProcess.StartInfo.Arguments = scriptFileCmd;\n            myProcess.StartInfo.UseShellExecute = false;\n            myProcess.StartInfo.RedirectStandardOutput = true;\n            myProcess.StartInfo.CreateNoWindow = true;\n            myProcess.Start();\n\n            string line = null;\n\n            while (null != (line = myProcess.StandardOutput.ReadLine()))\n            {\n                Console.WriteLine(line);\n            }\n            myProcess.WaitForExit();\n        }\n\n        static string CompileScript(string scriptFile)\n        {\n            string retval = \"\";\n            StringBuilder sb = new StringBuilder();\n\n            Process myProcess = new Process();\n            myProcess.StartInfo.FileName = \"cscs.exe\";\n            myProcess.StartInfo.Arguments = \"\/nl \/ca \\\"\" + scriptFile + \"\\\"\";\n            myProcess.StartInfo.UseShellExecute = false;\n            myProcess.StartInfo.RedirectStandardOutput = true;\n            myProcess.StartInfo.CreateNoWindow = true;\n            myProcess.Start();\n\n            string line = null;\n\n            while (null != (line = myProcess.StandardOutput.ReadLine()))\n            {\n                sb.Append(line);\n                sb.Append(\"\\n\");\n            }\n            myProcess.WaitForExit();\n\n            retval = sb.ToString();\n\n            string compiledFile = Path.ChangeExtension(scriptFile, \".csc\");\n\n            if (retval == \"\" &amp;&amp; File.Exists(compiledFile))\n                File.Delete(compiledFile);\n\n            return retval;\n        }\n\n        static void RunPreScripts(string scriptFile)\n        {\n            RunPrePostScripts(scriptFile, true);\n        }\n\n        static void RunPrePostScripts(string scriptFile, bool prescript)\n        {\n            \/\/ Compile the script in order to proper execute all pre- and post-scripts.\n            \/\/ The RunScript(cmd) approach is attractive but not sutable as some pre-scripts must be run only from the primary script\n            \/\/ but not as a stand alone scripts. That is why it is disabled for now by \"return;\"\n            CompileScript(scriptFile);\n        }\n    }\n\n    class FileResolver\n    {\n        static public string ResolveFile(string file, string&#91;] extraDirs, string extension)\n        {\n            string fileName = file;\n\n            if (Path.GetExtension(fileName) == \"\")\n                fileName += extension;\n\n            \/\/arbitrary directories\n            if (extraDirs != null)\n            {\n                foreach (string extraDir in extraDirs)\n                {\n                    string dir = extraDir;\n\n                    if (File.Exists(Path.Combine(dir, fileName)))\n                    {\n                        return Path.GetFullPath(Path.Combine(dir, fileName));\n                    }\n                }\n            }\n\n            \/\/PATH\n            string&#91;] pathDirs = Environment.GetEnvironmentVariable(\"PATH\").Replace(\"\\\"\", \"\").Split(';');\n\n            foreach (string pathDir in pathDirs)\n            {\n                string dir = pathDir;\n\n                if (File.Exists(Path.Combine(dir, fileName)))\n                {\n                    return Path.GetFullPath(Path.Combine(dir, fileName));\n                }\n            }\n\n            return \"\";\n        }\n    }\n\n    class VSProjectDoc : XmlDocument\n    {\n        public VSProjectDoc(string projFile)\n        {\n            Load(projFile);\n        }\n\n        static public void FixFile(string projFile)\n        {\n            \/\/remove xmlns=\"\"\n\n            \/\/using (FileStream fs = new FileStream(projFile, FileMode.OpenOrCreate))\n            \/\/using (StreamWriter sw = new StreamWriter(fs, Encoding.Unicode))\n            \/\/    sw.Write(FormatXml(this.InnerXml.Replace(\"xmlns=\\\"\\\"\", \"\")));\n\n            string content = \"\";\n\n            using (StreamReader sr = new StreamReader(projFile))\n                content = sr.ReadToEnd();\n\n            content = content.Replace(\"xmlns=\\\"\\\"\", \"\");\n\n            using (StreamWriter sw = new StreamWriter(projFile))\n                sw.Write(content);\n        }\n\n        public new XmlNodeList SelectNodes(string path)\n        {\n            XmlNamespaceManager nsmgr = new XmlNamespaceManager(NameTable);\n            nsmgr.AddNamespace(\"ab\", \"http:\/\/schemas.microsoft.com\/developer\/msbuild\/2003\");\n            if (path.StartsWith(\"\/\/\"))\n            {\n                path = path.Substring(1);\n                path = \"\/\" + path.Replace(\"\/\", \"\/ab:\");\n            }\n            else\n            {\n                path = path.Replace(\"\/\", \"\/ab:\");\n            }\n\n            return SelectNodes(path, nsmgr);\n        }\n\n        public XmlNode SelectFirstNode(string path)\n        {\n            XmlNodeList nodes = SelectNodes(path);\n\n            if (nodes != null &amp;&amp; nodes.Count != 0)\n                return nodes&#91;0];\n            else\n                return null;\n        }\n    }\n\n    static class Extensions\n    {\n        public static string GetFileName(this string file)\n        {\n            return Path.GetFileName(file);\n        }\n\n        public static string GetFileNameWithoutExt(this string file)\n        {\n            return Path.GetFileNameWithoutExtension(file);\n        }\n\n        public static string ChangeFileDir(this string file, string dir)\n        {\n            return dir.PathJoin(dir, Path.GetFileName(file));\n        }\n\n        public static string PathJoin(this string path, string path1, string path2 = \"\")\n        {\n            return Path.Combine(path, path1, path2);\n        }\n\n        public static bool Contains(this IEnumerable&lt;string> items, string text, bool ignoreCase)\n        {\n            return items.Any(x => string.Compare(text, x, ignoreCase) == 0);\n        }\n\n        public static bool SameAs(this string text, string pattern)\n        {\n            return string.Compare(text, pattern, true) == 0;\n        }\n\n        public static bool IsOneOf(this string text, params string&#91;] patterns)\n        {\n            foreach (string item in patterns)\n                if (text.SameAs(item))\n                    return true;\n            return false;\n        }\n    }\n}<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Cs-script debug script for Visual Studio 2019.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[3],"tags":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v15.7 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>DebugVS2019.cs - GerardWKnight<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"http:\/\/gerardwknight.duckdns.org\/index.php\/2022\/03\/23\/debugvs2019-cs\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"DebugVS2019.cs - GerardWKnight\" \/>\n<meta property=\"og:description\" content=\"Cs-script debug script for Visual Studio 2019.\" \/>\n<meta property=\"og:url\" content=\"http:\/\/gerardwknight.duckdns.org\/index.php\/2022\/03\/23\/debugvs2019-cs\/\" \/>\n<meta property=\"og:site_name\" content=\"GerardWKnight\" \/>\n<meta property=\"article:published_time\" content=\"2022-03-23T09:18:48+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2022-03-23T09:40:05+00:00\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Est. reading time\">\n\t<meta name=\"twitter:data1\" content=\"17 minutes\">\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebSite\",\"@id\":\"https:\/\/gerardwknight.duckdns.org\/#website\",\"url\":\"https:\/\/gerardwknight.duckdns.org\/\",\"name\":\"GerardWKnight\",\"description\":\"Web site of Melbourne based developer Gerard Knight\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":\"https:\/\/gerardwknight.duckdns.org\/?s={search_term_string}\",\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"http:\/\/gerardwknight.duckdns.org\/index.php\/2022\/03\/23\/debugvs2019-cs\/#webpage\",\"url\":\"http:\/\/gerardwknight.duckdns.org\/index.php\/2022\/03\/23\/debugvs2019-cs\/\",\"name\":\"DebugVS2019.cs - GerardWKnight\",\"isPartOf\":{\"@id\":\"https:\/\/gerardwknight.duckdns.org\/#website\"},\"datePublished\":\"2022-03-23T09:18:48+00:00\",\"dateModified\":\"2022-03-23T09:40:05+00:00\",\"author\":{\"@id\":\"https:\/\/gerardwknight.duckdns.org\/#\/schema\/person\/9253da78f8cec50174c8c71e03a0fa45\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"http:\/\/gerardwknight.duckdns.org\/index.php\/2022\/03\/23\/debugvs2019-cs\/\"]}]},{\"@type\":\"Person\",\"@id\":\"https:\/\/gerardwknight.duckdns.org\/#\/schema\/person\/9253da78f8cec50174c8c71e03a0fa45\",\"name\":\"gerardwknight\",\"image\":{\"@type\":\"ImageObject\",\"@id\":\"https:\/\/gerardwknight.duckdns.org\/#personlogo\",\"inLanguage\":\"en-US\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/6e6f44202403f41895c15856cb917d94?s=96&d=mm&r=g\",\"caption\":\"gerardwknight\"},\"sameAs\":[\"http:\/\/192.168.0.16\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","_links":{"self":[{"href":"https:\/\/gerardwknight.duckdns.org\/index.php\/wp-json\/wp\/v2\/posts\/131"}],"collection":[{"href":"https:\/\/gerardwknight.duckdns.org\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/gerardwknight.duckdns.org\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/gerardwknight.duckdns.org\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/gerardwknight.duckdns.org\/index.php\/wp-json\/wp\/v2\/comments?post=131"}],"version-history":[{"count":4,"href":"https:\/\/gerardwknight.duckdns.org\/index.php\/wp-json\/wp\/v2\/posts\/131\/revisions"}],"predecessor-version":[{"id":135,"href":"https:\/\/gerardwknight.duckdns.org\/index.php\/wp-json\/wp\/v2\/posts\/131\/revisions\/135"}],"wp:attachment":[{"href":"https:\/\/gerardwknight.duckdns.org\/index.php\/wp-json\/wp\/v2\/media?parent=131"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/gerardwknight.duckdns.org\/index.php\/wp-json\/wp\/v2\/categories?post=131"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/gerardwknight.duckdns.org\/index.php\/wp-json\/wp\/v2\/tags?post=131"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}