예제 #1
0
    static void Main(string[] args)
    {
        CsScript.CleanupScScriptTempDir();

        String        hostExePath = @"C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\devenv.exe";
        String        cmdArgs     = "Exp"; // "/rootsuffix Exp" - launch experimental version of visual studio.
        List <String> csScripts   = new List <string>();

        for (int i = 0; i < args.Length; i++)
        {
            if (args[i] == "/exe")
            {
                hostExePath = args[++i];
                if (!Path.IsPathRooted(hostExePath))
                {
                    hostExePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), hostExePath);
                }

                continue;
            }

            csScripts.Add(args[i]);
        }

        ScriptServer_ConnectDebugger(null, CodeType.Managed, csScripts, hostExePath, cmdArgs);
    }
예제 #2
0
        public async Task CleanUp()
        {
            try
            {
                LOGGER.Info($"Executing cleanup script");
                LOGGER.Debug($"Cleanup script: {CSharpCleanupScript}");

                CsScript = await CsScript.ContinueWithAsync(CSharpCleanupScript, Options);

                LOGGER.Info($"Executed cleanup script");
            }
            catch (CompilationErrorException ex)
            {
                LOGGER.Error($"Couldn't execute cleanup script: {CSharpCleanupScript}", ex);
            }
        }
예제 #3
0
    static void FileReloadUIThread(String file)
    {
        DebugPrint("- File changed '" + file + "'");

        if (!scriptsToMonitor.Contains(file))
        {
            return;
        }

        //
        // Dynamically loadable .dll/assembly cannot reside next with application folder, as it gets loaded from there by default.
        // Also need to change assembly name whenever new compilation comes up.
        //
        //String destFile = Path.Combine(dirReload, Path.GetFileName(file));
        //String srcPdb = Path.Combine(Path.GetDirectoryName(file), Path.GetFileNameWithoutExtension(file) + ".pdb");
        //String destPdb = Path.Combine(Path.GetDirectoryName(destFile), Path.GetFileNameWithoutExtension(destFile) + ".pdb");
        //File.Copy(file, destFile, true);
        //File.Copy(srcPdb, destPdb, true);

        //Process p = new Process();
        //p.StartInfo.UseShellExecute = false;
        //p.StartInfo.RedirectStandardOutput = true;
        //p.StartInfo.FileName = @"C:\Users\PikarTa1\Downloads\DebugInfo\Debug\DebugInfo.exe";
        //p.StartInfo.Arguments = "\"" + destFile + "\" clean-path";
        //p.Start();
        //String error = p.StandardOutput.ReadToEnd();
        //p.WaitForExit();

        //Assembly asm = Assembly.LoadFile(destFile);
        //asm.GetTypes().Select(x => x.GetMethod("Execute", BindingFlags.Static | BindingFlags.Public)).First().Invoke(null, null);

        //String exe = @"C:\Prototyping\cppscriptcore\bin\testScript.exe";

        // Not marked as serializable.
        // AppDomainSetup setup = new AppDomainSetup();
        // setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;
        // var appDomain = AppDomain.CreateDomain("myAppDomain", null, setup);

        // // Only loads assembly in one application domain.
        // appDomain.DoCallBack(() => {
        //     Assembly asm = Assembly.LoadFile(destFile);
        //     asm.GetTypes().Select(x => x.GetMethod("Execute", BindingFlags.Static | BindingFlags.Public)).First().Invoke(null, null);
        // }

        //);

        // AppDomain.Unload(appDomain);



        // Works
        //String errors = "";
        //if (!CsScript.RunScript(dirReload, loadCount, @"C:\Prototyping\cppscriptcore\Test\testScript\testScript.cs", false, false, out errors))
        //{
        //    Console.WriteLine("Error: " + errors);
        //    Console.WriteLine("");
        //}

        //String csScript = @"C:\Prototyping\cppscriptcore\Test\testScript\testScript.cs";

        //if (!File.Exists(scriptToMonitor))
        //    return;

        //Console.WriteLine("- reload");

        // Causes .pdb lock, assembly domain unload does not help.
        //using (AsmHelper helper = new AsmHelper(exe, "LoadDomain", true))

        Exception lastException = null;

        for (int iRetry = 0; iRetry < 10; iRetry++)
        {
            try
            {
                // Works, but in isolated appDomain.
                //String[] asms = new CSharpParser(file, true).RefAssemblies;

                //using (AsmHelper helper = new AsmHelper(CSScript.CompileFile(file, null, true, asms), null, true))
                //{
                //    helper.Invoke("*.Main");
                //}

                object oRet = CsScript.RunScript(file, mainArg);

                if (!(oRet is bool) || (bool)oRet != false)
                {
                    console.ReportScriptResult(file, null);
                }
                break;
            }
            catch (IOException ex)
            {
                // File might be in a middle of save. Try to retry within 50 ms again.
                if (iRetry == 9)
                {
                    lastException = ex;
                    break;
                }
                Thread.Sleep(50);
                continue;
            }
            catch (Exception ex)
            {
                lastException = ex;
                break;
            }
        }

        if (lastException != null)
        {
            try
            {
                console.ReportScriptResult(file, lastException);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Exception handler throwed exception by itself: " + ex.Message);
            }
        }
    }
예제 #4
0
 static void Main(string[] args)
 {
     Class1.dataList.Add("ScriptHost::Main was here");
     CsScript.CleanupScScriptTempDir();
     ScriptServer_ConnectDebugger(CodeType.Managed, null);
 }
예제 #5
0
        private async Task CreateExpressionEvaluator()
        {
            Options = ScriptOptions.Default;

            var assemblyLines = ReferencedAssembliesText.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

            foreach (var line in assemblyLines)
            {
                if (!line.StartsWith("//") && !string.IsNullOrWhiteSpace(line))
                {
                    var trimmed = line.Trim();

                    LOGGER.Info($"Attempting to load assembly: '{trimmed}'");

                    try
                    {
                        var assembly = Assembly.LoadFrom(trimmed);
                        Options = Options.AddReferences(assembly);

                        LOGGER.Info($"Loaded assembly: '{trimmed}' via 'Assembly.LoadFrom'");
                    }
                    catch (Exception ex1)
                    {
                        try
                        {
                            var netAssembly = Assembly.Load(trimmed);
                            Options = Options.AddReferences(netAssembly);

                            LOGGER.Info($"Loaded assembly: '{trimmed}' via 'Assembly.Load'");
                        }
                        catch (Exception ex2)
                        {
                            try
                            {
                                var gacAssemblyPath = AssemblyNameResolver.GetAssemblyPath(trimmed);
                                var gacAssembly     = Assembly.LoadFrom(gacAssemblyPath);
                                Options = Options.AddReferences(gacAssembly);

                                LOGGER.Info($"Loaded assembly: '{trimmed}' via 'AssemblyNameResolver.GetAssemblyPath'");
                            }
                            catch (Exception ex3)
                            {
                                LOGGER.Error($"Couldn't load assembly {trimmed} via 'Assembly.LoadFrom'", ex1);
                                LOGGER.Error($"Couldn't load assembly {trimmed} via 'Assembly.Load'", ex2);
                                LOGGER.Error($"Couldn't load assembly {trimmed} via 'AssemblyNameResolver.GetAssemblyPath'", ex3);
                            }
                        }
                    }
                }
            }

            CsScript = null;

            foreach (var func in StandardFunctions.GlobalFunctions)
            {
                LOGGER.Debug($"Loading standard function: '{func}'");

                if (CsScript == null)
                {
                    CsScript = await CSharpScript.RunAsync(func);
                }
                else
                {
                    CsScript = await CsScript.ContinueWithAsync(func);
                }
            }

            foreach (var var in GlobalVariables)
            {
                string func = $"const string {var.Key} = @\"{var.Value(FilePath, TemplateName)}\";";

                LOGGER.Info($"Loading global variable: '{func}'");

                CsScript = await CsScript.ContinueWithAsync(func);
            }

            try
            {
                LOGGER.Info($"Executing preparation script");
                LOGGER.Debug($"Preparation script: {CSharpPreparationScript}");

                CsScript = await CsScript.ContinueWithAsync(CSharpPreparationScript, Options);

                LOGGER.Info($"Executed preparation script");
            }
            catch (CompilationErrorException ex)
            {
                CsScript = await CSharpScript.RunAsync("using System;");

                LOGGER.Error($"Couldn't execute preparation script: {CSharpPreparationScript}", ex);
            }

            LOGGER.Info($"Expression evaluator creation finished");
        }
예제 #6
0
        public string Evaluate(string text)
        {
            LOGGER.Info($"Starting text evaluation");
            LOGGER.Info($"Text: '{text}'");

            if (text == null)
            {
                text = string.Empty;
            }

            for (int currentPos = 0; currentPos < text.Length; currentPos++)
            {
                if (text[currentPos] == '<')
                {
                    ScriptType scriptType = FindScriptType(text, currentPos);

                    LOGGER.Info($"Found a script of type: {scriptType}");

                    // Get if it is a simple script or a C# one
                    if (scriptType == ScriptType.Simple)
                    {
                        // Old simple script interpreter
                        int closingPos = FindClosingPosition(text, currentPos);
                        if (closingPos > currentPos)
                        {
                            var field = text.Substring(currentPos + 1, closingPos - currentPos - 1);

                            var replacement = EvaluateField(field);
                            text = $"{text.Substring(0, currentPos)}{replacement}{text.Substring(closingPos + 1)}";

                            LOGGER.Info($"Replaced placeholder field: '{field}' with value: '{replacement}'");
                        }
                    }
                    else
                    {
                        int closingPos = FindComplexClosingPosition(text, currentPos);
                        if (closingPos > currentPos)
                        {
                            string wholeText = text.Substring(currentPos, closingPos + 3 - currentPos);
                            string script    = wholeText.Substring(3, closingPos - currentPos - 3);

                            string result = string.Empty;

                            try
                            {
                                LOGGER.Info($"Running found script: '{script}'");

                                var state = CsScript.ContinueWithAsync(script);

                                if (state.Status != TaskStatus.Faulted)
                                {
                                    state.Wait();

                                    result = state.Result.ReturnValue?.ToString() ?? string.Empty;

                                    LOGGER.Info($"Script returned result: '{result}'");
                                }
                            }
                            catch (CompilationErrorException ex)
                            {
                                LOGGER.Error($"Couldn't execute script: {script}", ex);
                            }

                            string before = text.Substring(0, currentPos);
                            string after  = text.Substring(closingPos + 3);

                            text = $"{before}{result}{after}";
                        }
                    }
                }
            }

            LOGGER.Info($"Final evaluated text: '{text.Replace("<", "").Replace(">", "")}'");

            return(text.Replace("<", "").Replace(">", ""));
        }