Execute() public method

The main entry point for the application.
public Execute ( string args, PrintDelegate printDelg, string primaryScript ) : void
args string
printDelg PrintDelegate
primaryScript string
return void
Exemplo n.º 1
0
 /// <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);
 }
Exemplo n.º 2
0
        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)
                {
                    Console.WriteLine(exec.WaitForInputBeforeExit);
                    Console.ReadKey();
                }
            }
            finally
            {
                Host.OnExit();
            }
        }
Exemplo n.º 3
0
        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();
            }
        }
Exemplo n.º 4
0
        /// <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);
        }
Exemplo n.º 5
0
        /// <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);
        }
Exemplo n.º 6
0
        /// <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();
            }
        }
Exemplo n.º 7
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();
            }
        }
Exemplo n.º 8
0
 static void Main(string[] args)
 {
     CSExecutor.Execute(args, new PrintDelegate(Print));
 }
Exemplo n.º 9
0
        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();
            }
        }
Exemplo n.º 10
0
        /// <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
                    }
                }
            }
        }
Exemplo n.º 11
0
		/// <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
				}
			}
		}
Exemplo n.º 12
0
		/// <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);
		}