/// <summary> /// Invokes CSExecutor (C# script engine) /// </summary> /// <param name="print">Print delegate to be used (if not null) to handle script engine output (eg. compilation errors).</param> /// <param name="args">Script arguments.</param> static public void Execute(CSScriptLibrary.PrintDelegate print, string[] args) { csscript.AppInfo.appName = new FileInfo(Application.ExecutablePath).Name; csscript.CSExecutor exec = new csscript.CSExecutor(); exec.Rethrow = Rethrow; exec.Execute(args, new csscript.PrintDelegate(print != null ? print : new CSScriptLibrary.PrintDelegate(DefaultPrint)), null); }
/// <summary> /// Compiles script file into assembly with CSExecutor /// </summary> /// <param name="scriptFile">The name of script file to be compiled.</param> /// <param name="assemblyFile">The name of compiled assembly. If set to null a temnporary file name will be used.</param> /// <param name="debugBuild">'true' if debug information should be included in assembly; otherwise, 'false'.</param> /// <param name="cssConfigFile">The name of CS-Script configuration file. If null the default config file will be used (appDir/css_config.xml).</param> /// <param name="compilerOptions">The string value to be passed directly to the language compiler.</param> /// <returns>Compiled assembly file name.</returns> static public string CompileWithConfig(string scriptFile, string assemblyFile, bool debugBuild, string cssConfigFile, string compilerOptions) { Settings settings = Settings.Load(cssConfigFile != null ? cssConfigFile : Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "css_config.xml")); if (settings == null) { throw new ApplicationException("The configuration file \"" + cssConfigFile + "\" cannot be found"); } CSExecutor exec = new csscript.CSExecutor(); exec.Rethrow = true; CSExecutor.options.altCompiler = settings.ExpandUseAlternativeCompiler(); CSExecutor.options.compilerOptions = compilerOptions != null ? compilerOptions : ""; CSExecutor.options.apartmentState = settings.DefaultApartmentState; CSExecutor.options.reportDetailedErrorInfo = settings.ReportDetailedErrorInfo; CSExecutor.options.cleanupShellCommand = settings.CleanupShellCommand; CSExecutor.options.doCleanupAfterNumberOfRuns = settings.DoCleanupAfterNumberOfRuns; CSExecutor.options.searchDirs = new string[] { Path.GetDirectoryName(scriptFile), settings == null ? "" : settings.ExpandExtraLibDirectory(), Environment.GetEnvironmentVariable("CSSCRIPT_DIR") == null ? "" : Environment.ExpandEnvironmentVariables(@"%CSSCRIPT_DIR%\lib"), }; return(exec.Compile(scriptFile, assemblyFile, debugBuild)); }
/// <summary> /// Compiles script file into assembly with CSExecutor and loads it in current AppDomain /// </summary> /// <param name="scriptFile">The name of script file to be compiled.</param> /// <param name="assemblyFile">The name of compiled assembly. If set to null a temnporary file name will be used.</param> /// <param name="debugBuild">'true' if debug information should be included in assembly; otherwise, 'false'.</param> /// <returns>Compiled assembly.</returns> static public Assembly Load(string scriptFile, string assemblyFile, bool debugBuild) { csscript.CSExecutor exec = new csscript.CSExecutor(); exec.Rethrow = true; string outputFile = exec.Compile(scriptFile, assemblyFile, debugBuild); AssemblyName asmName = AssemblyName.GetAssemblyName(outputFile); return(AppDomain.CurrentDomain.Load(asmName)); }
/// <summary> /// Implementation of displaying application messages. /// </summary> static void Print(string msg) { try { string file = Path.Combine(CSExecutor.GetScriptTempDir(), "help." + Assembly.GetExecutingAssembly().GetName().Version + ".txt"); File.WriteAllText(file, msg); Process.Start(file); } catch (Exception e) { Console.WriteLine(e); } }
static void main(string[] args) { try { var exec = new CSExecutor(); Profiler.Stopwatch.Start(); Host.OnStart(); try { if (args.Any(a => a.StartsWith($"-{AppArgs.code}"))) { args = exec.PreprocessInlineCodeArgs(args); } if (Utils.IsSpeedTest) { args = exec.PreprocessInlineCodeArgs(args); } exec.Execute(args, CSExecutor.print, null); } catch (CLIException e) { if (!(e is CLIExitRequest)) { Console.WriteLine(e.Message); Environment.ExitCode = e.ExitCode; } } if (exec.WaitForInputBeforeExit != null) { try { Console.WriteLine(exec.WaitForInputBeforeExit); Console.Read(); } catch { } } } finally { Host.OnExit(); } }
public static void OnExit() { try { if (originalEncoding != null) { Console.OutputEncoding = originalEncoding; } //collect abandoned temp files if (Environment.GetEnvironmentVariable("CSScript_Suspend_Housekeeping") == null) { Utils.CleanUnusedTmpFiles(CSExecutor.GetScriptTempDir(), "*????????-????-????-????-????????????.dll", false); } } catch { } }
/// <summary> /// The main entry point for the application. /// </summary> static void Main(string[] args) { SetEnvironmentVariable("CSScriptRuntime", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()); CSExecutor exec = new CSExecutor(); if (AppDomain.CurrentDomain.FriendlyName != "ExecutionDomain") // AppDomain.IsDefaultAppDomain is more appropriate but it is not available in .NET 1.1 { string configFile = exec.GetCustomAppConfig(args); if (configFile != "") { AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation; setup.ConfigurationFile = configFile; AppDomain appDomain = AppDomain.CreateDomain("ExecutionDomain", null, setup); appDomain.ExecuteAssembly(Assembly.GetExecutingAssembly().Location, null, args); return; } } AppInfo.appName = new FileInfo(Application.ExecutablePath).Name; exec.Execute(args, new PrintDelegate(Print), null); }
public void EnableWpf(string arg) { const string console_type = "\"name\": \"Microsoft.NETCore.App\""; const string win_type = "\"name\": \"Microsoft.WindowsDesktop.App\""; var configFile = Path.ChangeExtension(Assembly.GetExecutingAssembly().Location, ".runtimeconfig.json"); var content = File.ReadAllText(configFile); if (arg == "enable" || arg == "1") { content = content.Replace(console_type, win_type); } else if (arg == "disabled" || arg == "0") { content = content.Replace(win_type, console_type); } CSExecutor.print($"WPF support is {(content.Contains(win_type) ? "enabled" : "disabled")}"); File.WriteAllText(configFile, content); }
void EnableWpf(string arg, string configFile, bool primaryConfig) { const string console_type = "\"name\": \"Microsoft.NETCore.App\""; const string win_type = "\"name\": \"Microsoft.WindowsDesktop.App\""; var content = File.ReadAllText(configFile); if (arg == "enable" || arg == "1") { content = content.Replace(console_type, win_type); } else if (arg == "disabled" || arg == "0") { content = content.Replace(win_type, console_type); } File.WriteAllText(configFile, content); if (primaryConfig) { CSExecutor.print($"WPF support is {(content.Contains(win_type) ? "enabled" : "disabled")}"); } }
private static void main(string[] args) { try { var exec = new CSExecutor(); Profiler.Stopwatch.Start(); Host.OnStart(); try { exec.Execute(args, Console.WriteLine, null); } catch (CLIException e) { if (!(e is CLIExitRequest)) { Console.WriteLine(e.Message); Environment.ExitCode = e.ExitCode; } } if (exec.WaitForInputBeforeExit != null) { try { Console.WriteLine(exec.WaitForInputBeforeExit); Console.Read(); } catch { } } } finally { Host.OnExit(); } }
/// <summary> /// The main entry point for the application. /// </summary> static void Main(string[] rawArgs) { HostConsole.OnStart(); try { //work around of nasty Win7x64 problem. //http://superuser.com/questions/527728/cannot-resolve-windir-cannot-modify-path-or-path-being-reset-on-boot if (Environment.GetEnvironmentVariable("windir") == null) Environment.SetEnvironmentVariable("windir", Environment.GetEnvironmentVariable("SystemRoot")); Profiler.Stopwatch.Start(); string[] args = rawArgs; //Debug.Assert(false); if (Utils.IsLinux()) { //because Linux shebang does not properly split arguments we need to take care of this //http://www.daniweb.com/software-development/c/threads/268382 List<string> tempArgs = new List<string>(); foreach (string arg in rawArgs) if (arg.StartsWith(CSSUtils.cmdFlagPrefix)) { foreach (string subArg in arg.Split(CSSUtils.cmdFlagPrefix.ToCharArray())) if (subArg.Trim() != "") tempArgs.Add(CSSUtils.cmdFlagPrefix + subArg.Trim()); } else tempArgs.Add(arg); args = tempArgs.ToArray(); } try { SetEnvironmentVariable("CSScriptRuntime", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()); SetEnvironmentVariable("CSScriptRuntimeLocation", System.Reflection.Assembly.GetExecutingAssembly().Location); } catch { } //SetEnvironmentVariable will always throw an exception on Mono CSExecutor exec = new CSExecutor(); if (AppDomain.CurrentDomain.FriendlyName != "ExecutionDomain") // AppDomain.IsDefaultAppDomain is more appropriate but it is not available in .NET 1.1 { string configFile = exec.GetCustomAppConfig(args); if (configFile != "") { AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation; setup.ConfigurationFile = configFile; AppDomain appDomain = AppDomain.CreateDomain("ExecutionDomain", null, setup); #if !net4 appDomain.ExecuteAssembly(Assembly.GetExecutingAssembly().Location, null, args); #else appDomain.ExecuteAssembly(Assembly.GetExecutingAssembly().Location, args); #endif return; } } try { AppInfo.appName = Path.GetFileName(Assembly.GetExecutingAssembly().Location); exec.Execute(args, new PrintDelegate(Print), null); } catch (Surrogate86ProcessRequiredException) { #if !net4 throw new ApplicationException("Cannot build surrogate host application because this script engine is build against early version of CLR."); #else try { string thisAssembly = Assembly.GetExecutingAssembly().Location; string runner = Path.Combine(Path.GetDirectoryName(thisAssembly), "lib\\runasm32.exe"); if (!File.Exists(runner)) runner = Path.Combine(Path.GetDirectoryName(thisAssembly), "runasm32.exe"); if (!File.Exists(runner)) runner = Environment.ExpandEnvironmentVariables("CSSCRIPT_32RUNNER"); if (!File.Exists(runner)) { Print("This script requires to be executed as x86 process but no runner (e.g. runasm32.exe) can be found."); } else { RunConsoleApp(runner, "\"" + thisAssembly + "\" " + GetCommandLineArgumentsStringFromEnvironment()); } } catch { } //This will always throw an exception on Mono #endif } catch (SurrogateHostProcessRequiredException e) { #if !net4 object dummy = e; throw new ApplicationException("Cannot build surrogate host application because this script engine is build against early version of CLR."); #else try { string assemblyHost = ScriptLauncherBuilder.GetLauncherName(e.ScriptAssembly); string appArgs = CSSUtils.cmdFlagPrefix + "css_host_parent:" + Process.GetCurrentProcess().Id + " \"" + CSSUtils.cmdFlagPrefix + "css_host_asm:" + e.ScriptAssembly + "\" " + GenerateCommandLineArgumentsString(e.ScriptArgs); if (e.StartDebugger) appArgs = CSSUtils.cmdFlagPrefix + "css_host_dbg:true " + appArgs; RunConsoleApp(assemblyHost, appArgs); } catch (Exception e1) { Console.WriteLine("Cannot execute Surrogate Host Process: " + e1); } #endif } } finally { HostConsole.OnExit(); } }
public void InstallPackage(string packageNameMask, string version = null) { var packages = new string[0]; //index is 1-based, exactly as it is printed with ListPackages if (int.TryParse(packageNameMask, out int index)) { var all_packages = ListPackages(); if (0 < index && index <= all_packages.Count()) { packages = new string[] { all_packages[index - 1] } } ; else { Console.WriteLine("There is no package with the specified index"); } } else { // Regex is too much at this stage // string pattern = CSSUtils.ConvertSimpleExpToRegExp(); // Regex wildcard = new Regex(pattern, RegexOptions.IgnoreCase); if (packageNameMask.EndsWith("*")) { packages = ListPackages().Where(x => x.StartsWith(packageNameMask.Substring(0, packageNameMask.Length - 1))).ToArray(); } else { packages = new[] { packageNameMask } }; } // C:\Users\user\AppData\Local\Temp\csscript.core\.nuget\333 var nuget_dir = CSExecutor.GetScriptTempDir() .PathJoin(".nuget", Process.GetCurrentProcess().Id) .EnsureDir(); try { var proj_template = nuget_dir.PathJoin("build.csproj"); if (!File.Exists(proj_template)) { Utils.Run("dotnet", "new console", nuget_dir); foreach (var name in packages) { var ver = ""; if (version != null) { ver = "-v " + version; } Utils.Run("dotnet", $"add package {name} {ver}", nuget_dir, x => Console.WriteLine(x)); } // intercept and report incompatible packages (maybe) } } finally { Task.Run(() => { nuget_dir.DeleteDir(); ClearAnabdonedNugetDirs(nuget_dir.GetDirName()); }); } } void ClearAnabdonedNugetDirs(string nuget_root) { // not implemented yet foreach (var item in Directory.GetDirectories(nuget_root)) { if (int.TryParse(item.GetFileName(), out int proc_id)) { if (Process.GetProcessById(proc_id) == null) { try { item.DeleteDir(); } catch { } } } } } string[] GetPackageAssemblies(PackageInfo package) { var frameworks = Directory.GetDirectories(package.SpecFile.GetDirName().PathJoin("lib")) .OrderByDescending(x => x); string lib = null; if (package.PreferredRuntime != null) { lib = frameworks.FirstOrDefault(x => x.EndsWith(package.PreferredRuntime)); } else { if (CSharpCompiler.DefaultCompilerRuntime == DefaultCompilerRuntime.Standard) { lib = frameworks.FirstOrDefault(x => x.GetFileName().StartsWith("netstandard")); } else // host runtime { if (Utils.IsCore) { lib = frameworks.FirstOrDefault(x => x.GetFileName().StartsWith("netcore")); } else { lib = frameworks.FirstOrDefault(x => { var runtime = x.GetFileName(); return(runtime.StartsWith("net") && !runtime.StartsWith("netcore") && !runtime.StartsWith("netstandard")); }); } } } if (lib == null) { lib = frameworks.FirstOrDefault(x => x.GetFileName().StartsWith("netstandard")); } if (lib != null) { var asms = Directory.GetFiles(lib, "*.dll"); return(asms); } else { return(new string[0]); } }
public void InstallPackage(string packageNameMask, string version = null) { var packages = new string[0]; //index is 1-based, exactly as it is printed with ListPackages if (int.TryParse(packageNameMask, out int index)) { var all_packages = ListPackages(); if (0 < index && index <= all_packages.Count()) { packages = new string[] { all_packages[index - 1] } } ; else { Console.WriteLine("There is no package with the specified index"); } } else { // Regex is too much at this stage // string pattern = CSSUtils.ConvertSimpleExpToRegExp(); // Regex wildcard = new Regex(pattern, RegexOptions.IgnoreCase); if (packageNameMask.EndsWith("*")) { packages = ListPackages().Where(x => x.StartsWith(packageNameMask.Substring(0, packageNameMask.Length - 1))).ToArray(); } else { packages = new[] { packageNameMask } }; } // C:\Users\user\AppData\Local\Temp\csscript.core\.nuget\333 var nuget_dir = CSExecutor.GetScriptTempDir() .PathJoin(".nuget", Process.GetCurrentProcess().Id) .EnsureDir(); try { var proj_template = nuget_dir.PathJoin("build.csproj"); if (!File.Exists(proj_template)) { Utils.Run("dotnet", "new console", nuget_dir); foreach (var name in packages) { var ver = ""; if (version != null) { ver = "-v " + version; } Utils.Run("dotnet", $"add package {name} {ver}", nuget_dir, x => Console.WriteLine(x)); } // intercept and report incompatible packages (maybe) } } finally { Task.Run(() => { nuget_dir.DeleteDir(); ClearAnabdonedNugetDirs(nuget_dir.GetDirName()); }); } } void ClearAnabdonedNugetDirs(string nuget_root) { // not implemented yet foreach (var item in Directory.GetDirectories(nuget_root)) { if (int.TryParse(item.GetFileName(), out int proc_id)) { if (Process.GetProcessById(proc_id) == null) { try { item.DeleteDir(); } catch { } } } } } IEnumerable <PackageInfo> ResolveDependenciesFor(IEnumerable <PackageInfo> packages) { var result = new List <PackageInfo>(packages); var queue = new Queue <PackageInfo>(packages); while (queue.Any()) { PackageInfo item = queue.Dequeue(); IEnumerable <XElement> dependencyPackages; var dependenciesSection = XElement.Parse(File.ReadAllText(item.SpecFile)) .FindDescendants("dependencies") .FirstOrDefault(); if (dependenciesSection == null) { continue; } // <dependencies> // <group targetFramework=".NETStandard2.0"> // <dependency id="Microsoft.Extensions.Logging.Abstractions" version="2.1.0" exclude="Build,Analyzers" /> var frameworks = dependenciesSection.FindDescendants("group"); if (frameworks.Any()) { IEnumerable <XElement> frameworkGroups = dependenciesSection.FindDescendants("group"); dependencyPackages = GetCompatibleTargetFramework(frameworkGroups, item) ?.FindDescendants("dependency") ?? new XElement[0]; } else { dependencyPackages = dependenciesSection.FindDescendants("dependency"); } foreach (var element in dependencyPackages) { var newPackage = new PackageInfo { Name = element.Attribute("id").Value, Version = element.Attribute("version").Value, PreferredRuntime = item.PreferredRuntime }; newPackage.SpecFile = NuGetCache.PathJoin(newPackage.Name, newPackage.Version, newPackage.Name + ".nuspec"); if (!result.Any(x => x.Name == newPackage.Name) && File.Exists(newPackage.SpecFile)) { queue.Enqueue(newPackage); result.Add(newPackage); } } } return(result.ToArray()); } /// <summary> /// Gets the compatible target framework. Similar to `GetPackageCompatibleLib` but relies on NuGet spec file /// </summary> /// <param name="freameworks">The frameworks.</param> /// <param name="package">The package.</param> /// <returns></returns> XElement GetCompatibleTargetFramework(IEnumerable <XElement> freameworks, PackageInfo package) { // https://docs.microsoft.com/en-us/dotnet/standard/frameworks // netstandard?.? // netcoreapp?.? // net?? | net??? // "" (no framework element, meaning "any framework") // Though packages use Upper case with '.' preffix: '<group targetFramework=".NETStandard2.0">' XElement findMatch(Predicate <string> matchTest) { var items = freameworks.Select(x => new { Name = x.Attribute("targetFramework")?.Value, Element = x }) .OrderByDescending(x => x.Name) .ToArray(); var match = items.FirstOrDefault(x => matchTest(x.Name ?? ""))?.Element ?? // exact match items.FirstOrDefault(x => x.Name == null)?.Element; // universal dependency specified by not supplying targetFramework element return(match); } if (package.PreferredRuntime != null) { // by requested runtime return(findMatch(x => x.Contains(package.PreferredRuntime))); } else { if (CSharpCompiler.DefaultCompilerRuntime == DefaultCompilerRuntime.Standard) { // by configured runtime return(findMatch(x => x.Contains("netstandard", ignoreCase: true))); } else { if (Runtime.IsCore) { // by runtime of the host return(findMatch(x => x.Contains("netcore", ignoreCase: true)) ?? findMatch(x => x.Contains("netstandard", ignoreCase: true))); } else { // by .NET full as tehre is no other options return(findMatch(x => (x.StartsWith("net", ignoreCase: true) || x.StartsWith(".net", ignoreCase: true)) && !x.Contains("netcore", ignoreCase: true) && !x.Contains("netstandard", ignoreCase: true)) ?? findMatch(x => x.Contains("netstandard", ignoreCase: true))); } } } } /// <summary> /// Gets the package compatible library. Similar to `GetCompatibleTargetFramework` but relies on file structure /// </summary> /// <param name="package">The package.</param> /// <returns></returns> string GetPackageCompatibleLib(PackageInfo package) { var libDir = package.SpecFile.GetDirName().PathJoin("lib"); if (!Directory.Exists(libDir)) { return(null); } var frameworks = Directory.GetDirectories(package.SpecFile.GetDirName().PathJoin("lib")) .OrderByDescending(x => x) .Select(x => new { Runtime = x.GetFileName(), Path = x }); if (package.PreferredRuntime != null) { return(frameworks.FirstOrDefault(x => x.Runtime.EndsWith(package.PreferredRuntime))?.Path); } else { if (CSharpCompiler.DefaultCompilerRuntime == DefaultCompilerRuntime.Standard) { return(frameworks.FirstOrDefault(x => x.Runtime.StartsWith("netstandard", ignoreCase: true))?.Path); } else // host runtime { if (Runtime.IsCore) { return((frameworks.FirstOrDefault(x => x.Runtime.StartsWith("netcore", ignoreCase: true)) ?? frameworks.FirstOrDefault(x => x.Runtime.StartsWith("netstandard", ignoreCase: true)))?.Path); } else { return(frameworks.FirstOrDefault(x => x.Runtime.StartsWith("net", ignoreCase: true) && !x.Runtime.StartsWith("netcore", ignoreCase: true) && !x.Runtime.StartsWith("netstandard", ignoreCase: true))?.Path); } } } } string[] GetCompatibleAssemblies(PackageInfo package) { var lib = GetPackageCompatibleLib(package); if (lib != null) { return(Directory.GetFiles(GetPackageCompatibleLib(package), "*.dll") .Where(item => !item.EndsWith(".resources.dll", StringComparison.OrdinalIgnoreCase)) .Where(x => Utils.IsRuntimeCompatibleAsm(x)) .ToArray()); } else { return(new string[0]); } }
static void main(string[] rawArgs) { HostConsole.OnStart(); try { //work around of nasty Win7x64 problem. //http://superuser.com/questions/527728/cannot-resolve-windir-cannot-modify-path-or-path-being-reset-on-boot if (Environment.GetEnvironmentVariable("windir") == null) { Environment.SetEnvironmentVariable("windir", Environment.GetEnvironmentVariable("SystemRoot")); } Profiler.Stopwatch.Start(); string[] args = rawArgs; //Debug.Assert(false); if (Utils.IsLinux()) { //because Linux shebang does not properly split arguments we need to take care of this //http://www.daniweb.com/software-development/c/threads/268382 List <string> tempArgs = new List <string>(); foreach (string arg in rawArgs) { if (arg.StartsWith(CSSUtils.cmdFlagPrefix)) { foreach (string subArg in arg.Split(CSSUtils.cmdFlagPrefix.ToCharArray())) { if (subArg.Trim() != "") { tempArgs.Add(CSSUtils.cmdFlagPrefix + subArg.Trim()); } } } else { tempArgs.Add(arg); } } args = tempArgs.ToArray(); } try { SetEnvironmentVariable("CSScriptRuntime", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()); SetEnvironmentVariable("CSScriptRuntimeLocation", System.Reflection.Assembly.GetExecutingAssembly().Location); } catch { } //SetEnvironmentVariable will always throw an exception on Mono CSExecutor exec = new CSExecutor(); if (AppDomain.CurrentDomain.FriendlyName != "ExecutionDomain") // AppDomain.IsDefaultAppDomain is more appropriate but it is not available in .NET 1.1 { string configFile = exec.GetCustomAppConfig(args); if (configFile != "") { AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation; setup.ConfigurationFile = configFile; AppDomain appDomain = AppDomain.CreateDomain("ExecutionDomain", null, setup); #if !net4 appDomain.ExecuteAssembly(Assembly.GetExecutingAssembly().Location, null, args); #else appDomain.ExecuteAssembly(Assembly.GetExecutingAssembly().Location, args); #endif return; } } try { AppInfo.appName = Path.GetFileName(Assembly.GetExecutingAssembly().Location); exec.Execute(args, new PrintDelegate(Print), null); } catch (Surrogate86ProcessRequiredException) { #if !net4 throw new ApplicationException("Cannot build surrogate host application because this script engine is build against early version of CLR."); #else try { string thisAssembly = Assembly.GetExecutingAssembly().Location; string runner = Path.Combine(Path.GetDirectoryName(thisAssembly), "lib\\runasm32.exe"); if (!File.Exists(runner)) { runner = Path.Combine(Path.GetDirectoryName(thisAssembly), "runasm32.exe"); } if (!File.Exists(runner)) { runner = Environment.ExpandEnvironmentVariables("CSSCRIPT_32RUNNER"); } if (!File.Exists(runner)) { Print("This script requires to be executed as x86 process but no runner (e.g. runasm32.exe) can be found."); } else { RunConsoleApp(runner, "\"" + thisAssembly + "\" " + GetCommandLineArgumentsStringFromEnvironment()); } } catch { } //This will always throw an exception on Mono #endif } catch (SurrogateHostProcessRequiredException e) { #if !net4 object dummy = e; throw new ApplicationException("Cannot build surrogate host application because this script engine is build against early version of CLR."); #else try { string assemblyHost = ScriptLauncherBuilder.GetLauncherName(e.ScriptAssembly); string appArgs = CSSUtils.cmdFlagPrefix + "css_host_parent:" + Process.GetCurrentProcess().Id + " \"" + CSSUtils.cmdFlagPrefix + "css_host_asm:" + e.ScriptAssembly + "\" " + GenerateCommandLineArgumentsString(e.ScriptArgs); if (e.StartDebugger) { appArgs = CSSUtils.cmdFlagPrefix + "css_host_dbg:true " + appArgs; } RunConsoleApp(assemblyHost, appArgs); } catch (Exception e1) { Console.WriteLine("Cannot execute Surrogate Host Process: " + e1); } #endif } } finally { HostConsole.OnExit(); } }
/// <summary> /// The main entry point for the application. /// </summary> public void Execute(string[] args, PrintDelegate printDelg, string primaryScript) { try { print = printDelg != null ? printDelg : new PrintDelegate(VoidPrint); if (args.Length > 0) { #region Parse command-line arguments... //Here we need to separate application arguments from script ones. //Script engine arguments are always followed by script arguments //[appArgs][scriptFile][scriptArgs][//x] ArrayList appArgs = new ArrayList(); int firstScriptArg = ParseAppArgs(args); if (args.Length <= firstScriptArg) { Environment.ExitCode = 1; return; //no script, no script arguments } //read persistent settings from configuration file Settings settings = null; if (options.noConfig) { if (options.altConfig != "") settings = Settings.Load(Path.GetFullPath(options.altConfig)); } else settings = Settings.Load(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "css_config.xml")); if (settings != null) { options.hideTemp = settings.HideAutoGeneratedFiles; options.altCompiler = settings.ExpandUseAlternativeCompiler(); options.apartmentState = settings.DefaultApartmentState; options.reportDetailedErrorInfo = settings.ReportDetailedErrorInfo; options.cleanupShellCommand = settings.ExpandCleanupShellCommand(); options.doCleanupAfterNumberOfRuns = settings.DoCleanupAfterNumberOfRuns; options.hideCompilerWarnings = settings.HideCompilerWarnings; //process default command-line arguments string[] defaultCmdArgs = settings.DefaultArguments.Split(" ".ToCharArray()); int firstDefaultScriptArg = ParseAppArgs(defaultCmdArgs); if (firstDefaultScriptArg != defaultCmdArgs.Length) { options.scriptFileName = defaultCmdArgs[firstDefaultScriptArg]; for (int i = firstDefaultScriptArg+1; i < defaultCmdArgs.Length; i++) if (defaultCmdArgs[i].Trim().Length != 0) appArgs.Add(defaultCmdArgs[i]); } } //process original command-line arguments if (options.scriptFileName == "") { options.scriptFileName = args[firstScriptArg]; firstScriptArg++; } for (int i = firstScriptArg; i < args.Length; i++) { if (args[i].Trim().Length != 0) { if (i == args.Length - 1 && string.Compare(args[args.Length - 1], "//x", true, CultureInfo.InvariantCulture) == 0) { options.startDebugger = true; options.DBG = true; } else appArgs.Add(args[i]); } } scriptArgs = (string[])appArgs.ToArray(typeof(string)); //searchDirs[0] is the script file directory. Set it only after //the script file resolved because it can be: // CurrentDir // dir defined by the absolute/ralative script file path // %CSSCRIPT_DIR% // ExtraLibDirectory // CacheDir options.searchDirs = new string[]{ "", Environment.ExpandEnvironmentVariables(@"%CSSCRIPT_DIR%\lib"), settings == null ? "" : settings.ExpandExtraLibDirectory(), ""}; options.scriptFileName = FileParser.ResolveFile(options.scriptFileName, options.searchDirs); if (primaryScript != null) options.scriptFileNamePrimary = primaryScript; else options.scriptFileNamePrimary = options.scriptFileName; if (CSExecutor.ScriptCacheDir == "") CSExecutor.SetScriptCacheDir(options.scriptFileName); options.searchDirs[0] = Path.GetDirectoryName(Path.GetFullPath(options.scriptFileName)); if (settings != null && settings.HideAutoGeneratedFiles != Settings.HideOptions.DoNotHide) options.searchDirs[3] = CSExecutor.ScriptCacheDir; CSharpParser.CmdScriptInfo[] cmdScripts = new CSharpParser.CmdScriptInfo[0]; //analyse ThreadingModel to use it whith execution thread if (File.Exists(options.scriptFileName)) { //do quick parsing for pre/post scripts, ThreadingModel and embedded script arguments CSharpParser parser = new CSharpParser(options.scriptFileName, true); if (parser.ThreadingModel != ApartmentState.Unknown) options.apartmentState = parser.ThreadingModel; cmdScripts = parser.CmdScripts; if (primaryScript == null)//this is a primary script { int firstEmbeddedScriptArg = ParseAppArgs(parser.Args); if (firstEmbeddedScriptArg != -1) { for (int i = firstEmbeddedScriptArg; i < parser.Args.Length; i++ ) appArgs.Add(parser.Args[i]); } scriptArgs = (string[])appArgs.ToArray(typeof(string)); } } #endregion ExecuteOptions originalOptions = (ExecuteOptions)options.Clone(); //preserve master script options string originalCurrDir = Environment.CurrentDirectory; //run prescripts //Note: during the secondary script execution static options will be modified (this is required for //browsing in CSSEnvironment with reflection). So reset it back with originalOptions after the execution is completed foreach (CSharpParser.CmdScriptInfo info in cmdScripts) if (info.preScript) { Environment.CurrentDirectory = originalCurrDir; info.args[1] = FileParser.ResolveFile(info.args[1], originalOptions.searchDirs); CSExecutor exec = new CSExecutor(info.abortOnError, originalOptions); if (originalOptions.DBG) { ArrayList newArgs = new ArrayList(); newArgs.AddRange(info.args); newArgs.Insert(0, "/dbg"); info.args = (string[])newArgs.ToArray(typeof(string)); } if (info.abortOnError) exec.Execute(info.args, printDelg, originalOptions.scriptFileName); else exec.Execute(info.args, null, originalOptions.scriptFileName); } options = originalOptions; ExecuteOptions.options = originalOptions; //update static members as well Environment.CurrentDirectory = originalCurrDir; //Run main script //We need to start the execution in a new thread as it is the only way //to set desired ApartmentState under .NET 2.0 Thread newThread = new Thread(new ThreadStart(this.ExecuteImpl)); newThread.ApartmentState = options.apartmentState; newThread.Start(); newThread.Join(); if (lastException != null) throw new Exception("Script "+options.scriptFileName+" cannot be executed.", lastException); //run postscripts foreach (CSharpParser.CmdScriptInfo info in cmdScripts) if (!info.preScript) { Environment.CurrentDirectory = originalCurrDir; info.args[1] = FileParser.ResolveFile(info.args[1], originalOptions.searchDirs); CSExecutor exec = new CSExecutor(info.abortOnError, originalOptions); if (originalOptions.DBG) { ArrayList newArgs = new ArrayList(); newArgs.AddRange(info.args); newArgs.Insert(0, "/dbg"); info.args = (string[])newArgs.ToArray(typeof(string)); } if (info.abortOnError) { exec.Rethrow = true; exec.Execute(info.args, printDelg, originalOptions.scriptFileName); } else exec.Execute(info.args, null, originalOptions.scriptFileName); } } else { ShowHelp(); } } catch (Exception e) { if (rethrow) { throw; } else { Environment.ExitCode = 1; if (options.reportDetailedErrorInfo) print(e.ToString()); else print(e.Message); //Mono friendly } } }
static void main(string[] rawArgs) { Utils.SetMonoRootDirEnvvar(); if (rawArgs.Contains("-preload")) { rawArgs = SchedulePreloadCompiler(rawArgs); } for (int i = 0; i < rawArgs.Length; i++) { rawArgs[i] = Environment.ExpandEnvironmentVariables(rawArgs[i]); } HostConsole.OnStart(); try { //work around of nasty Win7x64 problem. //http://superuser.com/questions/527728/cannot-resolve-windir-cannot-modify-path-or-path-being-reset-on-boot if (Environment.GetEnvironmentVariable("windir") == null) { Environment.SetEnvironmentVariable("windir", Environment.GetEnvironmentVariable("SystemRoot")); } Environment.SetEnvironmentVariable("pid", Process.GetCurrentProcess().Id.ToString()); Profiler.Stopwatch.Start(); string[] args = rawArgs; // if (args.Contains("-check")) // Debug.Assert(false); if (Utils.IsLinux) { //because Linux shebang does not properly split arguments we need to take care of this //http://www.daniweb.com/software-development/c/threads/268382 List <string> tempArgs = new List <string>(); foreach (string arg in rawArgs) { if (arg == CSSUtils.Args.DefaultPrefix) { foreach (string subArg in arg.Split(CSSUtils.Args.DefaultPrefix[0])) { if (subArg.Trim() != "") { tempArgs.Add(CSSUtils.Args.DefaultPrefix + subArg.Trim()); } } } else { tempArgs.Add(arg); } } args = tempArgs.ToArray(); } try { Utils.SetEnvironmentVariable("CSScriptRuntime", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()); Utils.SetEnvironmentVariable("CSScriptRuntimeLocation", System.Reflection.Assembly.GetExecutingAssembly().Location); Utils.SetEnvironmentVariable("cscs_exe_dir", Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)); if (Environment.GetEnvironmentVariable("CSSCRIPT_DIR") == null && Utils.IsLinux) { // GetExecutingAssembly().Location may be empty even for the entry assembly var cscs_exe_dir = Environment.GetEnvironmentVariable("cscs_exe_dir"); if (cscs_exe_dir != null && cscs_exe_dir.StartsWith("/usr/local/")) { Utils.SetEnvironmentVariable("CSSCRIPT_DIR", cscs_exe_dir); } } } catch { } //SetEnvironmentVariable may throw an exception on Mono CSExecutor.print = new PrintDelegate(Print); CSExecutor exec = new CSExecutor(); try { if (AppDomain.CurrentDomain.FriendlyName != "ExecutionDomain") // AppDomain.IsDefaultAppDomain is more appropriate but it is not available in .NET 1.1 { string configFile = exec.GetCustomAppConfig(args); if (configFile != "") { AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation; setup.ConfigurationFile = configFile; AppDomain appDomain = AppDomain.CreateDomain("ExecutionDomain", null, setup); #if !net4 appDomain.ExecuteAssembly(Assembly.GetExecutingAssembly().Location, null, args); #else appDomain.ExecuteAssembly(Assembly.GetExecutingAssembly().Location, args); #endif return; } } #if net4 //CSSUtils.DbgInjectionCode = cscscript.Resources.dbg; CSSUtils.DbgInjectionCode = embedded_strings.dbg_source; #endif AppInfo.appName = Path.GetFileName(Assembly.GetExecutingAssembly().Location); exec.Execute(args, Print, null); } catch (Surrogate86ProcessRequiredException) { #if !net4 throw new ApplicationException("Cannot build surrogate host application because this script engine is build against early version of CLR."); #else try { string thisAssembly = Assembly.GetExecutingAssembly().Location; string runner = Path.Combine(Path.GetDirectoryName(thisAssembly), "lib\\runasm32.exe"); if (!File.Exists(runner)) { runner = Path.Combine(Path.GetDirectoryName(thisAssembly), "runasm32.exe"); } if (!File.Exists(runner)) { runner = Environment.ExpandEnvironmentVariables("%CSSCRIPT_32RUNNER%"); } if (!File.Exists(runner)) { Print("This script requires to be executed as x86 process but no runner (e.g. runasm32.exe) can be found."); } else { RunConsoleApp(runner, "\"" + thisAssembly + "\" " + GetCommandLineArgumentsStringFromEnvironment()); } } catch { } //This will always throw an exception on Mono #endif } catch (CLIException e) { if (!(e is CLIExitRequest)) { Console.WriteLine(e.Message); Environment.ExitCode = e.ExitCode; } } catch (SurrogateHostProcessRequiredException e) { #if !net4 object dummy = e; throw new ApplicationException("Cannot build surrogate host application because this script engine is build against early version of CLR."); #else try { string assemblyHost = ScriptLauncherBuilder.GetLauncherName(e.ScriptAssembly); string appArgs = CSSUtils.Args.DefaultPrefix + "css_host_parent:" + Process.GetCurrentProcess().Id + " \"" + CSSUtils.Args.DefaultPrefix + "css_host_asm:" + e.ScriptAssembly + "\" " + GenerateCommandLineArgumentsString(e.ScriptArgs); if (e.StartDebugger) { appArgs = CSSUtils.Args.DefaultPrefix + "css_host_dbg:true " + appArgs; } RunConsoleApp(assemblyHost, appArgs); } catch (Exception e1) { Console.WriteLine("Cannot execute Surrogate Host Process: " + e1); } #endif } if (exec.WaitForInputBeforeExit != null) { Console.WriteLine(exec.WaitForInputBeforeExit); Console.ReadKey(); } } finally { HostConsole.OnExit(); } }
/// <summary> /// Compiles script file into assembly with CSExecutor /// </summary> /// <param name="scriptFile">The name of script file to be compiled.</param> /// <param name="assemblyFile">The name of compiled assembly. If set to null a temnporary file name will be used.</param> /// <param name="debugBuild">'true' if debug information should be included in assembly; otherwise, 'false'.</param> /// <returns>Compiled assembly file name.</returns> static public string Compile(string scriptFile, string assemblyFile, bool debugBuild) { csscript.CSExecutor exec = new csscript.CSExecutor(); exec.Rethrow = true; return exec.Compile(scriptFile, assemblyFile, debugBuild); }
/// <summary> /// Compiles script file into assembly with CSExecutor /// </summary> /// <param name="scriptFile">The name of script file to be compiled.</param> /// <param name="assemblyFile">The name of compiled assembly. If set to null a temnporary file name will be used.</param> /// <param name="debugBuild">'true' if debug information should be included in assembly; otherwise, 'false'.</param> /// <param name="cssConfigFile">The name of CS-Script configuration file. If null the default config file will be used (appDir/css_config.xml).</param> /// <param name="compilerOptions">The string value to be passed directly to the language compiler.</param> /// <returns>Compiled assembly file name.</returns> static public string CompileWithConfig(string scriptFile, string assemblyFile, bool debugBuild, string cssConfigFile, string compilerOptions) { Settings settings = Settings.Load(cssConfigFile != null ? cssConfigFile : Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "css_config.xml")); if (settings == null) throw new ApplicationException("The configuration file \""+cssConfigFile+"\" cannot be found"); CSExecutor exec = new csscript.CSExecutor(); exec.Rethrow = true; CSExecutor.options.altCompiler = settings.ExpandUseAlternativeCompiler(); CSExecutor.options.compilerOptions = compilerOptions != null ? compilerOptions : ""; CSExecutor.options.apartmentState = settings.DefaultApartmentState; CSExecutor.options.reportDetailedErrorInfo = settings.ReportDetailedErrorInfo; CSExecutor.options.cleanupShellCommand = settings.CleanupShellCommand; CSExecutor.options.doCleanupAfterNumberOfRuns = settings.DoCleanupAfterNumberOfRuns; CSExecutor.options.searchDirs = new string[] { Path.GetDirectoryName(scriptFile), settings == null ? "" : settings.ExpandExtraLibDirectory(), Environment.GetEnvironmentVariable("CSSCRIPT_DIR") == null ? "" : Environment.ExpandEnvironmentVariables(@"%CSSCRIPT_DIR%\lib"), }; return exec.Compile(scriptFile, assemblyFile, debugBuild); }
public static string ShowHelp(string helpType, params object[] context) { switch (helpType) { case AppArgs.dir: { ExecuteOptions options = (ExecuteOptions)context[0]; Settings settings = CSExecutor.LoadSettings(options); StringBuilder builder = new StringBuilder(); builder.Append(string.Format("{0}\n", Environment.CurrentDirectory)); foreach (string dir in Environment.ExpandEnvironmentVariables(settings.SearchDirs).Split(",;".ToCharArray())) { if (dir.Trim() != "") { builder.Append(string.Format("{0}\n", dir)); } } builder.Append(string.Format("{0}\n", typeof(HelpProvider).Assembly.GetAssemblyDirectoryName())); return(builder.ToString()); } case AppArgs.syntax: return(AppArgs.syntaxHelp); case AppArgs.cmd: case AppArgs.commands: { Dictionary <string, string> map = new Dictionary <string, string>(); int longestArg = 0; foreach (FieldInfo info in typeof(AppArgs).GetFields()) { if (info.IsPublic && info.IsLiteral && info.IsStatic && info.FieldType == typeof(string)) { string arg = (string)info.GetValue(null); string description = ""; if (AppArgs.switch1Help.ContainsKey(arg)) { description = AppArgs.switch1Help[arg].Description; } if (AppArgs.switch2Help.ContainsKey(arg)) { description = AppArgs.switch2Help[arg].Description; } if (map.ContainsKey(description)) { string capturedArg = map[description]; if (capturedArg.Length > arg.Length) { map[description] = capturedArg + "|" + arg; } else { map[description] = arg + "|" + capturedArg; } } else { map[description] = arg; } longestArg = Math.Max(map[description].Length, longestArg); } } StringBuilder builder = new StringBuilder(); foreach (string key in map.Keys) { string arg = map[key].Trim(); arg = String.Format("{0,-" + longestArg + "}", arg); builder.Append(string.Format("{0} {1}\n", arg, key)); } return(builder.ToString()); } default: return("<unknown command>"); } }
/// <summary> /// Compiles script file into assembly with CSExecutor and loads it in current AppDomain /// </summary> /// <param name="scriptFile">The name of script file to be compiled.</param> /// <param name="assemblyFile">The name of compiled assembly. If set to null a temnporary file name will be used.</param> /// <param name="debugBuild">'true' if debug information should be included in assembly; otherwise, 'false'.</param> /// <returns>Compiled assembly.</returns> static public Assembly Load(string scriptFile, string assemblyFile, bool debugBuild) { csscript.CSExecutor exec = new csscript.CSExecutor(); exec.Rethrow = true; string outputFile = exec.Compile(scriptFile, assemblyFile, debugBuild); AssemblyName asmName = AssemblyName.GetAssemblyName(outputFile); return AppDomain.CurrentDomain.Load(asmName); }
/// <summary> /// Compiles script file into assembly with CSExecutor /// </summary> /// <param name="scriptFile">The name of script file to be compiled.</param> /// <param name="assemblyFile">The name of compiled assembly. If set to null a temnporary file name will be used.</param> /// <param name="debugBuild">'true' if debug information should be included in assembly; otherwise, 'false'.</param> /// <returns>Compiled assembly file name.</returns> static public string Compile(string scriptFile, string assemblyFile, bool debugBuild) { csscript.CSExecutor exec = new csscript.CSExecutor(); exec.Rethrow = true; return(exec.Compile(scriptFile, assemblyFile, debugBuild)); }
static void Main(string[] args) { CSExecutor.Execute(args, new PrintDelegate(Print)); }
/// <summary> /// Generates the name of the cache directory for the specified script file. /// </summary> /// <param name="file">Script file name.</param> /// <returns>Cache directory name.</returns> public static string GetCacheDirectory(string file) { return(Path.Combine(CSExecutor.GetScriptTempDir(), @"Cache\" + Path.GetFullPath(file).ToLower().GetHashCode().ToString())); }
/// <summary> /// The main entry point for the application. /// </summary> public void Execute(string[] args, PrintDelegate printDelg, string primaryScript) { try { print = printDelg != null ? printDelg : new PrintDelegate(VoidPrint); if (args.Length > 0) { #region Parse command-line arguments... //Here we need to separate application arguments from script ones. //Script engine arguments are always followed by script arguments //[appArgs][scriptFile][scriptArgs][//x] #if net1 ArrayList appArgs = new ArrayList(); #else List<string> appArgs = new List<string>(); #endif //The following will also update corresponding "options" members from "settings" data Settings settings = GetPersistedSettings(appArgs); int firstScriptArg = CSSUtils.ParseAppArgs(args, this); if (!options.processFile) return; //no further processing is required (e.g. print help) if (args.Length <= firstScriptArg) { Environment.ExitCode = 1; print("No script file was specified."); return; //no script, no script arguments } //process original command-line arguments if (options.scriptFileName == "") { options.scriptFileName = args[firstScriptArg]; firstScriptArg++; } for (int i = firstScriptArg; i < args.Length; i++) { if (i == args.Length - 1 && string.Compare(args[args.Length - 1], "//x", true, CultureInfo.InvariantCulture) == 0) { options.startDebugger = true; options.DBG = true; } else appArgs.Add(args[i]); } #if net1 scriptArgs = (string[])appArgs.ToArray(typeof(string)); #else scriptArgs = appArgs.ToArray(); #endif //searchDirs[0] is the script file directory. Set it only after //the script file resolved because it can be: // dir defined by the absolute/relative script file path // "%CSSCRIPT_DIR%\lib // settings.SearchDirs // CacheDir #if net1 ArrayList dirs = new ArrayList(); #else List<string> dirs = new List<string>(); #endif using (IDisposable currDir = new CurrentDirGuard()) { if (options.local) Environment.CurrentDirectory = Path.GetDirectoryName(Path.GetFullPath(options.scriptFileName)); foreach (string dir in options.searchDirs) //some directories may be already set from command-line dirs.Add(Path.GetFullPath(dir)); if (settings != null) foreach (string dir in Environment.ExpandEnvironmentVariables(settings.SearchDirs).Split(",;".ToCharArray())) if (dir.Trim() != "") dirs.Add(Path.GetFullPath(dir)); } dirs.Add(Utils.GetAssemblyDirectoryName(this.GetType().Assembly)); #if net1 options.scriptFileName = FileParser.ResolveFile(options.scriptFileName, (string[])dirs.ToArray(typeof(string))); #else options.scriptFileName = FileParser.ResolveFile(options.scriptFileName, dirs.ToArray()); #endif if (primaryScript != null) options.scriptFileNamePrimary = primaryScript; else options.scriptFileNamePrimary = options.scriptFileName; if (CSExecutor.ScriptCacheDir == "") CSExecutor.SetScriptCacheDir(options.scriptFileName); dirs.Insert(0, Path.GetDirectoryName(Path.GetFullPath(options.scriptFileName))); if (settings != null && settings.HideAutoGeneratedFiles != Settings.HideOptions.DoNotHide) dirs.Add(CSExecutor.ScriptCacheDir); #if net1 options.searchDirs = (string[])dirs.ToArray(typeof(string)); #else options.searchDirs = dirs.ToArray(); #endif CSharpParser.CmdScriptInfo[] cmdScripts = new CSharpParser.CmdScriptInfo[0]; //do quick parsing for pre/post scripts, ThreadingModel and embedded script arguments CSharpParser parser = new CSharpParser(options.scriptFileName, true, null, options.searchDirs); if (parser.Inits.Length != 0) options.initContext = parser.Inits[0]; if (parser.HostOptions.Length != 0) { if (Environment.Version.Major >= 4) { foreach (string optionsSet in parser.HostOptions) foreach (string option in optionsSet.Split(' ')) if (option == "/platform:x86") options.compilerOptions += " " + option; else if (option.StartsWith("/version:")) options.TargetFramework = option.Replace("/version:", ""); options.useSurrogateHostingProcess = true; } } //analyses ThreadingModel to use it with execution thread if (File.Exists(options.scriptFileName)) { if (parser.ThreadingModel != ApartmentState.Unknown) options.apartmentState = parser.ThreadingModel; #if net1 ArrayList preScripts = new ArrayList(parser.CmdScripts); foreach (CSharpParser.ImportInfo info in parser.Imports) { try { string file = FileParser.ResolveFile(info.file, options.searchDirs); if (file.IndexOf(".g.cs") == -1) //non auto-generated file preScripts.AddRange(new CSharpParser(file, true, options.searchDirs).CmdScripts); } catch { } //some files may not be generated yet } cmdScripts = (CSharpParser.CmdScriptInfo[])preScripts.ToArray(typeof(CSharpParser.CmdScriptInfo)); #else List<string> newSearchDirs = new List<string>(options.searchDirs); using (IDisposable currDir = new CurrentDirGuard()) { Environment.CurrentDirectory = Path.GetDirectoryName(Path.GetFullPath(options.scriptFileName)); foreach (string dir in parser.ExtraSearchDirs) newSearchDirs.Add(Path.GetFullPath(dir)); foreach (string file in parser.RefAssemblies) { string path = file.Replace("\"", ""); string dir = Path.GetDirectoryName(path); if (dir != "") newSearchDirs.Add(Path.GetFullPath(dir)); } options.searchDirs = newSearchDirs.ToArray(); } List<CSharpParser.CmdScriptInfo> preScripts = new List<CSharpParser.CmdScriptInfo>(parser.CmdScripts); foreach (CSharpParser.ImportInfo info in parser.Imports) { try { string[] files = FileParser.ResolveFiles(info.file, options.searchDirs); foreach (string file in files) if (file.IndexOf(".g.cs") == -1) //non auto-generated file { using (IDisposable currDir = new CurrentDirGuard()) { CSharpParser impParser = new CSharpParser(file, true, null, options.searchDirs); Environment.CurrentDirectory = Path.GetDirectoryName(file); string[] packageAsms = NuGet.Resolve(impParser.NuGets, true, file); foreach (string asmName in packageAsms) { var packageDir = Path.GetDirectoryName(asmName); newSearchDirs.Add(packageDir); } foreach (string dir in impParser.ExtraSearchDirs) newSearchDirs.Add(Path.GetFullPath(dir)); options.searchDirs = newSearchDirs.ToArray(); } preScripts.AddRange(new CSharpParser(file, true, null, options.searchDirs).CmdScripts); } } catch { } //some files may not be generated yet } cmdScripts = preScripts.ToArray(); #endif if (primaryScript == null)//this is a primary script { int firstEmbeddedScriptArg = CSSUtils.ParseAppArgs(parser.Args, this); if (firstEmbeddedScriptArg != -1) { for (int i = firstEmbeddedScriptArg; i < parser.Args.Length; i++) appArgs.Add(parser.Args[i]); } #if net1 scriptArgs = (string[])appArgs.ToArray(typeof(string)); #else scriptArgs = appArgs.ToArray(); #endif } } #endregion Parse command-line arguments... ExecuteOptions originalOptions = (ExecuteOptions) options.Clone(); //preserve master script options string originalCurrDir = Environment.CurrentDirectory; //run prescripts //Note: during the secondary script execution static options will be modified (this is required for //browsing in CSSEnvironment with reflection). So reset it back with originalOptions after the execution is completed foreach (CSharpParser.CmdScriptInfo info in cmdScripts) if (info.preScript) { Environment.CurrentDirectory = originalCurrDir; info.args[1] = FileParser.ResolveFile(info.args[1], originalOptions.searchDirs); CSExecutor exec = new CSExecutor(info.abortOnError, originalOptions); if (originalOptions.DBG) { #if net1 ArrayList newArgs = new ArrayList(); newArgs.AddRange(info.args); newArgs.Insert(0, CSSUtils.Args.DefaultPrefix + "dbg"); info.args = (string[])newArgs.ToArray(typeof(string)); #else List<string> newArgs = new List<string>(); newArgs.AddRange(info.args); newArgs.Insert(0, CSSUtils.Args.DefaultPrefix + "dbg"); info.args = newArgs.ToArray(); #endif } if (originalOptions.verbose) { #if net1 ArrayList newArgs = new ArrayList(); newArgs.AddRange(info.args); newArgs.Insert(0, CSSUtils.Args.DefaultPrefix + "verbose"); info.args = (string[])newArgs.ToArray(typeof(string)); #else List<string> newArgs = new List<string>(); newArgs.AddRange(info.args); newArgs.Insert(0, CSSUtils.Args.DefaultPrefix + "verbose"); info.args = newArgs.ToArray(); #endif } if (info.abortOnError) exec.Execute(info.args, printDelg, originalOptions.scriptFileName); else exec.Execute(info.args, null, originalOptions.scriptFileName); } options = originalOptions; ExecuteOptions.options = originalOptions; //update static members as well Environment.CurrentDirectory = originalCurrDir; options.compilationContext = CSSUtils.GenerateCompilationContext(parser, options); //Run main script //We need to start the execution in a new thread as it is the only way //to set desired ApartmentState under .NET 2.0 Thread newThread = new Thread(new ThreadStart(this.ExecuteImpl)); #if net1 newThread.ApartmentState = options.apartmentState; #else newThread.SetApartmentState(options.apartmentState); #endif newThread.Start(); newThread.Join(); if (lastException != null) if (lastException is SurrogateHostProcessRequiredException) throw lastException; else throw new ApplicationException("Script " + options.scriptFileName + " cannot be executed.", lastException); //run postscripts foreach (CSharpParser.CmdScriptInfo info in cmdScripts) if (!info.preScript) { Environment.CurrentDirectory = originalCurrDir; info.args[1] = FileParser.ResolveFile(info.args[1], originalOptions.searchDirs); CSExecutor exec = new CSExecutor(info.abortOnError, originalOptions); if (originalOptions.DBG) { #if net1 ArrayList newArgs = new ArrayList(); newArgs.AddRange(info.args); newArgs.Insert(0, CSSUtils.Args.DefaultPrefix + "dbg"); info.args = (string[])newArgs.ToArray(typeof(string)); #else List<string> newArgs = new List<string>(); newArgs.AddRange(info.args); newArgs.Insert(0, CSSUtils.Args.DefaultPrefix + "dbg"); info.args = newArgs.ToArray(); #endif } if (originalOptions.verbose) { #if net1 ArrayList newArgs = new ArrayList(); newArgs.AddRange(info.args); newArgs.Insert(0, CSSUtils.Args.DefaultPrefix + "verbose"); info.args = (string[])newArgs.ToArray(typeof(string)); #else List<string> newArgs = new List<string>(); newArgs.AddRange(info.args); newArgs.Insert(0, CSSUtils.Args.DefaultPrefix + "verbose"); info.args = newArgs.ToArray(); #endif } if (info.abortOnError) { exec.Rethrow = true; exec.Execute(info.args, printDelg, originalOptions.scriptFileName); } else exec.Execute(info.args, null, originalOptions.scriptFileName); } } else { ShowHelp(); } } catch (Surrogate86ProcessRequiredException) { throw; } catch (SurrogateHostProcessRequiredException) { throw; } catch (Exception e) { Exception ex = e; if (e is System.Reflection.TargetInvocationException) ex = e.InnerException; if (rethrow) { throw ex; } else { Environment.ExitCode = 1; if (!CSSUtils.IsRuntimeErrorReportingSupressed) { if (options.reportDetailedErrorInfo && !(ex is FileNotFoundException)) print(ex.ToString()); else print(ex.Message); //Mono friendly } } } }