コード例 #1
0
        private CommandResult Inspect(ScriptResult result)
        {
            if (result == null)
            {
                return(CommandResult.Error);
            }

            if (result.CompileExceptionInfo != null)
            {
                var ex = result.CompileExceptionInfo.SourceException;
                _logger.ErrorFormat("Script compilation failed: {0}.", ex, ex.Message);
                return(CommandResult.Error);
            }

            if (result.ExecuteExceptionInfo != null)
            {
                var ex = result.ExecuteExceptionInfo.SourceException;
                _logger.ErrorFormat("Script execution failed: {0}.", ex, ex.Message);
                return(CommandResult.Error);
            }

            if (!result.IsCompleteSubmission)
            {
                _logger.Error("The script is incomplete.");
                return(CommandResult.Error);
            }

            return(CommandResult.Success);
        }
コード例 #2
0
        public async Task <ScriptResult> Post([FromBody] ScriptResult result)
        {
            _dataService.AddOrUpdateScriptResult(result);

            if (result.HadErrors && result.SavedScriptId.HasValue)
            {
                var savedScript = await _dataService.GetSavedScript(result.SavedScriptId.Value);

                if (savedScript.GenerateAlertOnError)
                {
                    await _dataService.AddAlert(result.DeviceID,
                                                result.OrganizationID,
                                                $"Alert triggered while running script {savedScript.Name}.",
                                                string.Join("\n", result.ErrorOutput));
                }

                if (savedScript.SendEmailOnError)
                {
                    var device = _dataService.GetDevice(result.DeviceID);

                    await _emailSender.SendEmailAsync(savedScript.SendErrorEmailTo,
                                                      "Script Run Alert",
                                                      $"An alert was triggered while running script {savedScript.Name} on device {device.DeviceName}. <br /><br />" +
                                                      $"Error Output: <br /><br /> " +
                                                      $"{string.Join("<br /><br />", result.ErrorOutput)}");
                }
            }

            if (result.ScriptRunId.HasValue)
            {
                await _dataService.AddScriptResultToScriptRun(result.ID, result.ScriptRunId.Value);
            }

            return(result);
        }
コード例 #3
0
        private AssemblyCatalog ExecuteScripts(string[] scriptFiles)
        {
            var services = CreateScriptServices();

            ScriptResult result = null;

            if (_options.KeepScriptsSeparated && scriptFiles.Any())
            {
                foreach (var scriptFile in scriptFiles)
                {
                    var loader = GetLoader(scriptFile);
                    result = ExecuteScript(services, loader);
                }
            }
            else
            {
                var loader = GetLoader(scriptFiles);
                result = ExecuteScript(services, loader);
            }

            AssemblyCatalog catalog = null;
            var             marker  = result.ReturnValue as Type;

            if (marker != null)
            {
                catalog = new AssemblyCatalog(marker.Assembly, this);
            }

            return(catalog);
        }
コード例 #4
0
        public static void SetHeader(ScriptResult result, string fieldName, string displayText, string type, string key)
        {
            if (string.IsNullOrEmpty(displayText))
            {
                displayText = fieldName;
            }

            ScriptHeader h = new ScriptHeader()
            {
                FieldName = fieldName, DisplayText = displayText
            };

            switch (type)
            {
            case "int":
                h.Type = typeof(int);
                break;

            case "string":
                h.Type = typeof(string);
                break;

            default:
                h.Type = typeof(object);
                break;
            }

            if (!result.DataSet.ContainsKey(key))
            {
                result.DataSet.Add(key, new ScriptData());
            }

            result.DataSet[key].AddHeader(h);
        }
コード例 #5
0
        protected virtual ScriptResult Execute(string code, Session session)
        {
            Guard.AgainstNullArgument("session", session);

            var result = new ScriptResult();

            try
            {
                var submission = session.CompileSubmission <object>(code);
                try
                {
                    result.ReturnValue = submission.Execute();
                }
                catch (Exception ex)
                {
                    result.ExecuteExceptionInfo = ExceptionDispatchInfo.Capture(ex);
                }
            }
            catch (Exception ex)
            {
                result.UpdateClosingExpectation(ex);
                if (!result.IsPendingClosingChar)
                {
                    result.CompileExceptionInfo = ExceptionDispatchInfo.Capture(ex);
                }
            }
            return(result);
        }
コード例 #6
0
ファイル: BusinessTests.cs プロジェクト: Kelvysb/Grimoire
        public void VaultExecutionTest()
        {
            GrimoireScriptBlock script = TestHelper.GetSingleTestScript();

            script.ExtractResult = new PatternRange()
            {
                Start = "", End = ""
            };
            business.SaveScriptBlock(script).Wait();
            GrimoireScriptBlock result = TestHelper.GetCreatedScript(config, "Test_Script.json");

            result.Should().NotBeNull();
            savedVault.Itens = new List <VaultItem>();
            savedVault.Itens.Add(new VaultItem(true, "Key 1", "value 1"));
            savedVault.Itens.Add(new VaultItem(true, "Key 2", "value 2"));
            savedVault.Itens.Add(new VaultItem(true, "Key 3", "value 3"));
            business.LoadVault();
            business.LoadScriptRunners().Wait();
            ScriptResult scriptResult = business.ScriptRunners.First().Run().Result;

            scriptResult.Should().NotBeNull();
            scriptResult.ResultType.Should().Be(ResultType.Success);
            scriptResult.FilteredResult.Should()
            .Contain("Single line multiple keys: value 1 - value 2")
            .And
            .Contain("Single key: value 3");
            savedVault.Itens = new List <VaultItem>();
        }
コード例 #7
0
        public void Run(string script, IDictionary <object, object> parameters, bool resetResult = true)
        {
            LastException = null;

            if (resetResult)
            {
                Result = new ScriptResult();
            }

            Result.Exception = null;

            Parameters.Merge(parameters);

            Result.Title = Parameters.Replace(Result.Title);

            try
            {
                ScriptSource source = engine.CreateScriptSourceFromString(Parameters.Replace(script), SourceCodeKind.Statements);
                source.Execute(scope);
            }
            catch (Exception ex)
            {
                Result.Exception = ex;
            }
        }
コード例 #8
0
        private static void RethrowExceptionIfAny(ScriptResult result, string scriptPath)
        {
            if (result.CompileExceptionInfo != null)
            {
                log.ErrorFormat(CultureInfo.InvariantCulture, "Failed to compile {0}", result.CompileExceptionInfo, scriptPath);
                result.CompileExceptionInfo.Throw();
            }

            if (result.ExecuteExceptionInfo != null)
            {
                // HACK: waiting on https://github.com/scriptcs/scriptcs/issues/545
                if (!result.ExecuteExceptionInfo.SourceException.StackTrace.Trim()
                    .StartsWith("at Submission#", StringComparison.OrdinalIgnoreCase))
                {
                    log.Warn(
                        "Roslyn failed to execute the scripts. Any configuration in this script will not be available",
                        result.ExecuteExceptionInfo.SourceException);
                }
                else
                {
                    log.ErrorFormat(CultureInfo.InvariantCulture, "Failed to execute {0}", result.ExecuteExceptionInfo, scriptPath);
                    result.ExecuteExceptionInfo.Throw();
                }
            }
        }
コード例 #9
0
        private CommandResult Inspect(ScriptResult result)
        {
            if (result == null)
            {
                return(CommandResult.Error);
            }

            if (result.CompileExceptionInfo != null)
            {
                _logger.Error(result.CompileExceptionInfo.SourceException.Message);
                _logger.Debug(result.CompileExceptionInfo.SourceException);
                return(CommandResult.Error);
            }

            if (result.ExecuteExceptionInfo != null)
            {
                _logger.Error(result.ExecuteExceptionInfo.SourceException);
                return(CommandResult.Error);
            }

            if (!result.IsCompleteSubmission)
            {
                _logger.Error("The script is incomplete.");
                return(CommandResult.Error);
            }

            return(CommandResult.Success);
        }
コード例 #10
0
        public override void AssertScript(ScriptResult compareResult)
        {
            base.AssertScript(compareResult);
            var commands = compareResult.AllStatements.ToArray();

            Assert.That(commands.Count(), Is.EqualTo(3));
        }
コード例 #11
0
        /// <summary>
        /// Send conversation response to Osiris from web hook conversation script.
        /// </summary>
        /// <param name="passedContext">
        /// The passed context.
        /// </param>
        /// <param name="generatedResult">
        /// The conversation script result.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        public bool SendWebhookResponse(ScriptContext passedContext, ScriptResult generatedResult)
        {
            var task = Task.Run(() => this.SendWebhookResponseAsync(passedContext, generatedResult));

            task.Wait();
            return(task.Result);
        }
コード例 #12
0
ファイル: ScriptConfigLoader.cs プロジェクト: 40a/config-r
        private static void RethrowExceptionIfAny(ScriptResult result, string scriptPath)
        {
            if (result.CompileExceptionInfo != null)
            {
                log.ErrorFormat(CultureInfo.InvariantCulture, "Failed to compile {0}", result.CompileExceptionInfo, scriptPath);
                result.CompileExceptionInfo.Throw();
            }

            if (result.ExecuteExceptionInfo != null)
            {
                // HACK: waiting on https://github.com/scriptcs/scriptcs/issues/545
                if (!result.ExecuteExceptionInfo.SourceException.StackTrace.Trim()
                    .StartsWith("at Submission#", StringComparison.OrdinalIgnoreCase))
                {
                    log.Warn(
                        "Roslyn failed to execute the scripts. Any configuration in this script will not be available",
                        result.ExecuteExceptionInfo.SourceException);
                }
                else
                {
                    log.ErrorFormat(CultureInfo.InvariantCulture, "Failed to execute {0}", result.ExecuteExceptionInfo, scriptPath);
                    result.ExecuteExceptionInfo.Throw();
                }
            }
        }
コード例 #13
0
ファイル: Program.cs プロジェクト: vokenet/CommonLibrary.NET
        private static bool Execute(string[] args)
        {
            bool   success  = true;
            string fileName = ConfigurationManager.AppSettings["filepath"];

            if (fileName == null || fileName == "")
            {
                Console.WriteLine("No location stated in config file.");
            }

            List <ScriptResult> resultSet = new List <ScriptResult>();
            List <Script>       scripts   = XmlHelper.MapScriptsFromXml(fileName);

            for (int i = 0; i < scripts.Count; i++)
            {
                var script = scripts[i];

                //Get contents of a fluent script file
                string fileContent = FluentHelper.GetFluentScriptFileContent(script.Name);

                // 1. Create instance of interpreter.
                var ip = FluentHelper.GetInterpreter();

                // 2. Check if emtpy file.
                if (!string.IsNullOrEmpty(fileContent))
                {
                    // 3. Execute script.
                    Console.Write("Executing : " + script.Name);
                    ip.Execute(fileContent);

                    // 4. Check result.
                    ScriptResult result = new ScriptResult();
                    result.FilePath = script.Name;
                    result.Duration = ip.Result.Duration.TotalMilliseconds;
                    result.Succeed  = ip.Result.Success;
                    if (!result.Succeed)
                    {
                        WriteScriptError(script.Name, ip.Result.Message);
                    }
                    else
                    {
                        Console.WriteLine();
                    }
                    CheckExpectedResults(ip, fileContent, script, result);

                    if (!result.Succeed)
                    {
                        success = false;
                        WriteExpectedResultsFailedError();
                        // highlight
                    }

                    resultSet.Add(result);
                }
            }

            // Writes result in Xml file
            LogHelper.WriteInLogFile(resultSet);
            return(success);
        }
コード例 #14
0
ファイル: GrimoireRunner.cs プロジェクト: Kelvysb/Grimoire
        private async Task <ScriptResult> ExecutePowerShell(GrimoireScriptBlock scriptBlock, IList <Input> inputs)
        {
            ScriptResult result = null;
            string       script = await business.ReadScript(scriptBlock);

            if (inputs != null && inputs.Any())
            {
                foreach (var input in inputs)
                {
                    script = script.Replace(input.Key, input.Value);
                }
            }

            using (PowerShell ps = PowerShell.Create())
            {
                PSDataCollection <PSObject> outputCollection = new PSDataCollection <PSObject>();
                ps.AddScript("Set-ExecutionPolicy -Scope Process Unrestricted");
                ps.AddScript(script);
                IAsyncResult execResult = await Task.Run(() =>
                                                         ps.BeginInvoke <PSObject, PSObject>(null, outputCollection));

                WaitExecution(scriptBlock.TimeOut, execResult);
                result = GetResult(scriptBlock, ps);
            }

            return(result);
        }
コード例 #15
0
        public static ScriptResult Run(string code, hostObject_ obj)
        {
            //設定
            var ssr     = ScriptSourceResolver.Default.WithBaseDirectory(Environment.CurrentDirectory);
            var options = ScriptOptions.Default
                          .WithSourceResolver(ssr)
                          .WithReferences(typeof(object).Assembly) //参照アセンブリを指定
                          .WithReferences(Assembly.GetEntryAssembly())
                          .WithImports(                            //using する名前空間を指定
                "System",
                "System.Collections.Generic"
                );

            //コードの生成
            var script = CSharpScript.Create(
                code,
                options,
                typeof(hostObject_)
                );

            //実行
            var state = script.RunAsync(obj).Result;

            //結果の取り出し
            ScriptResult ret = new ScriptResult();

            //ret.outputPixel = (PixelDouble)state.GetVariable("result")?.Value ?? null;
            //ret.outputStr = (string)state.GetVariable("resultStr")?.Value ?? "";
            return(ret);
        }
コード例 #16
0
        /// <summary>
        /// Applies the SQL query by breaking it into stataments and executing one by one inside a transaction.
        /// </summary>
        public void ApplyScript()
        {
            ErroredOutDataRow = null;
            ScriptResult      = MySqlStatement.StatementResultType.NotApplied;
            CreateActualStatementsList();
            if (ActualStatementRowsList == null || ActualStatementRowsList.Count == 0)
            {
                return;
            }

            var connectionStringBuilder = _wbConnection.GetConnectionStringBuilder();

            connectionStringBuilder.AllowUserVariables = true;
            using (var conn = new MySqlConnection(connectionStringBuilder.ConnectionString))
            {
                conn.Open();
                MySqlTransaction transaction = conn.BeginTransaction();
                var  command        = new MySqlCommand(string.Empty, conn, transaction);
                uint executionOrder = 1;
                foreach (var mySqlRow in ActualStatementRowsList)
                {
                    // Before attempting to execute the MySqlStatement object, check if the connection is still open.
                    if (conn.State != ConnectionState.Open)
                    {
                        ErroredOutDataRow          = mySqlRow;
                        ErroredOutDataRow.RowError = Resources.ConnectionLostErrorText;
                        ScriptResult = MySqlStatement.StatementResultType.ConnectionLost;
                        break;
                    }

                    var rowStatement = mySqlRow.Statement;
                    rowStatement.Execute(command, executionOrder++, _useOptimisticUpdate);
                    ScriptResult = rowStatement.JoinResultTypes(ScriptResult);
                    if (ScriptResult.WithoutErrors())
                    {
                        continue;
                    }

                    ErroredOutDataRow = mySqlRow;
                    if (ScriptResult == MySqlStatement.StatementResultType.ErrorThrown)
                    {
                        // Check if the result was errored out because the connection was broken and if so, flip the ScriptResult to its proper value.
                        if (conn.State != ConnectionState.Open)
                        {
                            ErroredOutDataRow.RowError = Resources.ConnectionLostErrorText;
                            ScriptResult = MySqlStatement.StatementResultType.ConnectionLost;
                            break;
                        }

                        mySqlRow.ReflectError();
                    }

                    break;
                }

                PostApplyScript(transaction);
                transaction.Dispose();
            }
        }
コード例 #17
0
    public override void AssertScript(ScriptResult compareResult)
    {
        var commands      = compareResult.AllStatements.ToArray();
        var indexCommands = commands.Where(x => x.Contains(" INDEX ")).Count();

        Assert.That(indexCommands, Is.EqualTo(2));
        Assert.That(commands.Count(), Is.EqualTo(3));
    }
コード例 #18
0
    public override void AssertScript(ScriptResult compareResult)
    {
        var commands = compareResult.AllStatements
                       .Where(c => c.Contains(" CONSTRAINT "))
                       .ToArray();

        Assert.That(commands, Is.Empty);
    }
コード例 #19
0
ファイル: GrimoireRunner.cs プロジェクト: Kelvysb/Grimoire
        private ScriptResult GetResult(GrimoireScriptBlock scriptBlock, PowerShell ps)
        {
            ScriptResult result = MountResults(ps);

            result.ResultType     = GetResultStatus(scriptBlock, ps, result.RawResult);
            result.FilteredResult = ExtractFilteredResult(scriptBlock, result.RawResult);
            return(result);
        }
コード例 #20
0
        public void Execute(ScriptResult compareResult)
        {
            var commands     = compareResult.AllStatements.ToArray();
            var dropCommands = commands.Where(x => x.Contains(" DROP ")).Count();
            var addCommands  = commands.Where(x => x.Contains(" ADD ")).Count();

            Assert.That(dropCommands, Is.EqualTo(3));
            Assert.That(addCommands, Is.EqualTo(1));
        }
コード例 #21
0
        /// <summary>
        /// Function that builds the contents of the generated file based on the contents of the input file.
        /// </summary>
        /// <param name="inputFileContent">Content of the input file</param>
        /// <returns>Generated file as a byte array</returns>
        protected override byte[] GenerateCode(string inputFileContent)
        {
            // Some good examples: https://t4toolbox.svn.codeplex.com/svn/Source/DteProcessor.cs
            // And https://github.com/madskristensen/ExtensibilityTools/blob/master/src/VsixManifest/Generator/ResxFileGenerator.cs

            try
            {
                ProjectItem projectItem   = GetProjectItem();
                string      inputFilePath = projectItem.Properties.Item("FullPath").Value.ToString();
                Project     project       = projectItem.ContainingProject;
                Solution    solution      = projectItem.DTE.Solution;

                // Run the generator and get the results
                ScriptSource source = new ScriptSource(inputFilePath, inputFileContent);
                ScriptEngine engine = new ScriptEngine(project.FullName, solution.FullName, null);
                ScriptResult result = engine.Evaluate(source).Result;

                // Report errors
                if (result.Errors.Count > 0)
                {
                    foreach (ScriptError error in result.Errors)
                    {
                        GeneratorError(4, error.Message, (uint)error.Line, (uint)error.Column);
                    }
                    return(null);
                }

                // Add generated files to the project
                foreach (IOutputFileInfo outputFile in result.OutputFiles.Where(x => x.BuildAction != BuildAction.GenerateOnly))
                {
                    ProjectItem outputItem = projectItem.ProjectItems.Cast <ProjectItem>()
                                             .FirstOrDefault(x => x.Properties.Item("FullPath")?.Value?.ToString() == outputFile.FilePath)
                                             ?? projectItem.ProjectItems.AddFromFile(outputFile.FilePath);
                    outputItem.Properties.Item("ItemType").Value = outputFile.BuildAction.ToString();
                }

                // Remove/delete files from the last generation but not in this one
                string logPath = Path.ChangeExtension(inputFilePath, ".log");
                if (File.Exists(logPath))
                {
                    string[] logLines = File.ReadAllLines(logPath);
                    foreach (string fileToRemove in logLines.Where(x => result.OutputFiles.All(y => y.FilePath != x)))
                    {
                        solution.FindProjectItem(fileToRemove)?.Delete();
                    }
                }

                // Create the log file
                return(Encoding.UTF8.GetBytes(string.Join(Environment.NewLine, result.OutputFiles.Select(x => x.FilePath))));
            }
            catch (Exception ex)
            {
                GeneratorError(4, ex.ToString(), 0, 0);
                return(null);
            }
        }
コード例 #22
0
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                SqlOutput.Text    = "Generating Script...";
                CSharpOutput.Text = "Generating Script...";

                _CodeGenerator = new CodeGenerator(ConnectionString);

                await _CodeGenerator.GenerateQuerySchema(Query);

                var sqlResult = await _CodeGenerator.GetSqlScript();

                var cSharpResult = await _CodeGenerator.GetPocoScript();

                SqlOutput.Text    = sqlResult;
                CSharpOutput.Text = cSharpResult;

                if (ScriptResults == null)
                {
                    ScriptResults = new ScriptResultList();
                }

                var          lastResult = ScriptResults.FirstOrDefault(r => r.InputScript == Query);
                ScriptResult newResult  = new ScriptResult();

                // If there already is a matching result, update the run time
                if (lastResult != null)
                {
                    lastResult.ScriptTime = DateTime.Now;
                }
                else
                {
                    newResult.Server       = Server;
                    newResult.InputScript  = Query;
                    newResult.OutputCSharp = cSharpResult;
                    newResult.OutputSql    = sqlResult;
                    newResult.ScriptTime   = DateTime.Now;

                    ScriptResults.CullList(newResult);

                    ScriptResults.Add(newResult);
                }

                PriorQueryCombo.ItemsSource = ScriptResults.OrderByDescending(r => r.ScriptTime);
                PriorQueryCombo.Text        = (lastResult == null) ? newResult.ToString() : lastResult.ToString();

                SqlGenerator.Properties.Settings.Default.Save();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                SqlOutput.Text    = string.Format("/*{0}*/", ex.Message);
                CSharpOutput.Text = string.Format("/*{0}*/", ex.Message);
            }
        }
コード例 #23
0
ファイル: MapLayer.cs プロジェクト: andyhebear/mogregis3d
        public SpatialReference getOutputSRS(Session session, SpatialReference terrain_srs)
        {
            if (!grid_valid || output_srs == null)
            {
                if (levels.Count > 0 && levels[0].getFilterGraph() != null)
                {
                    FilterEnv env = session.createFilterEnv();
                    env.setTerrainSRS(terrain_srs);

                    FilterList filters = levels[0].getFilterGraph().getFilters();

                    for (int ind = filters.Count - 1; ind >= 0; ind--) //reverse iterator?
                    {
                        if (output_srs != null)
                        {
                            break;
                        }
                        Filter i = filters[ind];
                        if (i is TransformFilter)
                        {
                            TransformFilter xf = (TransformFilter)i;
                            if (xf.getUseTerrainSRS())
                            {
                                if (env.getTerrainSRS() != null)
                                {
                                    this.output_srs = env.getTerrainSRS();
                                }
                            }
                            else if (xf.getSRS())
                            {
                                this.output_srs = (SpatialReference)(xf.getSRS());
                            }
                            else if (xf.getSRSScript())
                            {
                                ScriptResult r = env.getScriptEngine().run(xf.getSRSScript(), env);
                                if (r.isValid())
                                {
                                    this.output_srs = session.getResources().getSRS(r.asString());
                                }
                                else
                                {
                                    env.getReport().error(r.asString());
                                }
                            }
                        }
                    }

                    if (output_srs == null) // no reproject..assume input srs
                    {
                        this.output_srs = levels[0].getFeatureLayer().getSRS();
                    }
                }
            }

            return(output_srs);
        }
コード例 #24
0
        public async Task <bool> ExecuteCode(string code, CancellationToken token = default, IScriptWriter sender = null)
        {
            string result = null; object returnedValue = null; bool isError = false; bool isCancelled = false;

            ScriptExecuted?.Invoke(this, new ScriptRequest {
                Script = code, Writer = sender
            });

            try
            {
                if (!await InitScript(token))
                {
                    return(false);
                }

                using (await _scriptStateLock.LockAsync(token))
                {
                    if (_executionContext != null)
                    {
                        await _executionContext(async() => _scriptState = await _scriptState.ContinueWithAsync(code, cancellationToken: token));
                    }
                    else
                    {
                        _scriptState = await _scriptState.ContinueWithAsync(code, cancellationToken : token);
                    }

                    returnedValue = _scriptState.ReturnValue;
                    result        = _scriptState.ReturnValue?.ToString();
                    if (_scriptState.ReturnValue != null && _scriptState.ReturnValue.GetType() == typeof(string))
                    {
                        result = $"\"{result}\"";
                    }
                }
            }
            catch (CompilationErrorException e)
            {
                result  = e.Message;
                isError = true;
            }
            catch (OperationCanceledException)
            {
                result      = string.Empty;
                isCancelled = true;
            }

            if (result != null)
            {
                var scriptResult = new ScriptResult {
                    Result = result, ReturnedValue = returnedValue, IsError = isError, IsCancelled = isCancelled
                };
                Results.Add(scriptResult);
                ScriptResultReceived?.Invoke(this, scriptResult);
            }

            return(!isError && !isCancelled);
        }
コード例 #25
0
        public override void AssertScript(ScriptResult compareResult)
        {
            base.AssertScript(compareResult);
            var commands     = compareResult.AllStatements.ToArray();
            var dropCommands = commands.Where(x => x.Contains(" DROP ")).Count();
            var addCommands  = commands.Where(x => x.Contains(" ADD ")).Count();

            Assert.That(dropCommands, Is.EqualTo(3));
            Assert.That(addCommands, Is.EqualTo(1));
        }
コード例 #26
0
        public static IEnumerable <dynamic> GetData(ScriptResult result, string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                key = "default";
            }
            ScriptData data = result.DataSet[key];

            return(data.Items);
        }
コード例 #27
0
    public override void AssertScript(ScriptResult compareResult)
    {
        var commands = compareResult.AllStatements.ToArray();
        var dropConstraintCommands = commands.Where(x => x.Contains(" DROP CONSTRAINT ")).Count();
        var addUniqueCommands      = commands.Where(x => x.Contains(" ADD UNIQUE ")).Count();

        Assert.That(dropConstraintCommands, Is.EqualTo(1));
        Assert.That(addUniqueCommands, Is.EqualTo(1));
        Assert.That(commands.Count(), Is.EqualTo(3));
    }
コード例 #28
0
        public void Execute(ScriptResult compareResult)
        {
            var commands = compareResult.AllStatements.ToArray();
            var dropConstraintCommands = commands.Where(x => x.Contains(" DROP CONSTRAINT ")).Count();
            var addPrimaryKeyCommands  = commands.Where(x => x.Contains(" ADD PRIMARY KEY ")).Count();

            Assert.That(dropConstraintCommands, Is.EqualTo(1));
            Assert.That(addPrimaryKeyCommands, Is.EqualTo(1));
            Assert.That(commands.Count(), Is.EqualTo(3));
        }
        public void Write(HtmlRenderer renderer, string script, bool inline)
        {
            if (!string.IsNullOrWhiteSpace(script))
            {
                if (renderer.EnableHtmlForInline || !inline)
                {
                    var          fullScript = script;
                    ScriptResult result     = null;
                    try
                    {
                        result = scriptExecutor.ExecuteScript(fullScript);
                        if (result.CompileExceptionInfo != null)
                        {
                            renderer.Write(Markdown.ToHtml(BuildMarkdownExceptionMessage(result.CompileExceptionInfo.SourceException, options.ExceptionStackTrace), pipeline));
                        }

                        if (MarkdownDocument.Instance.ReportObject != null)
                        {
                            if (MarkdownDocument.Instance.ReportObject is HtmlReportObject)
                            {
                                renderer.Write(((HtmlReportObject)MarkdownDocument.Instance.ReportObject).Html);
                            }
                            else if (MarkdownDocument.Instance.ReportObject is MarkdownReportObject)
                            {
                                var markdown = Markdown.ToHtml(((MarkdownReportObject)MarkdownDocument.Instance.ReportObject).Markdown, pipeline);
                                if (inline)
                                {
                                    if (markdown.StartsWith("<p>"))
                                    {
                                        markdown = markdown.Substring(3);
                                    }
                                    if (markdown.EndsWith("</p>\n"))
                                    {
                                        markdown = markdown.Substring(0, markdown.Length - 5);
                                    }
                                }

                                renderer.Write(markdown);
                            }
                        }
                        MarkdownDocument.Instance.Reset();
                    }
                    catch (Exception ex)
                    {
                        renderer.Write(Markdown.ToHtml(BuildMarkdownExceptionMessage(ex, options.ExceptionStackTrace), pipeline));
                    }
                }
                else
                {
                    renderer.Write(script);
                }
            }
        }
コード例 #30
0
    public override void AssertScript(ScriptResult compareResult)
    {
        var commands = compareResult.AllStatements.ToArray();
        var dropConstraintCommands = commands.Where(x => x.Contains(" DROP CONSTRAINT ")).Count();
        var addPrimaryKeyCommands  = commands.Where(x => x.Contains(" ADD PRIMARY KEY ")).Count();
        var addForeignKeyCommands  = commands.Where(x => x.Contains(" ADD FOREIGN KEY ")).Count();

        Assert.That(dropConstraintCommands, Is.EqualTo(5));
        Assert.That(addPrimaryKeyCommands, Is.EqualTo(3));
        Assert.That(addForeignKeyCommands, Is.EqualTo(2));
        Assert.That(commands.Count(), Is.EqualTo(11));
    }
コード例 #31
0
        public void Execute(ScriptResult compareResult)
        {
            var commands = compareResult.AllStatements.ToArray();
            var dropConstraintCommands = commands.Where(x => x.Contains(" DROP CONSTRAINT ")).Count();
            var addUniqueCommands      = commands.Where(x => x.Contains(" ADD UNIQUE ")).Count();
            var addForeignKeyCommands  = commands.Where(x => x.Contains(" ADD FOREIGN KEY ")).Count();

            Assert.That(dropConstraintCommands, Is.EqualTo(2));
            Assert.That(addUniqueCommands, Is.EqualTo(1));
            Assert.That(addForeignKeyCommands, Is.EqualTo(1));
            Assert.That(commands.Count(), Is.EqualTo(5));
        }
コード例 #32
0
        private static void RethrowExceptionIfAny(ScriptResult result, string script)
        {
            if (result.CompileExceptionInfo != null)
            {
                log.ErrorFormat("Failed to compile {0}", result.CompileExceptionInfo, script);
                result.CompileExceptionInfo.Throw();
            }

            if (result.ExecuteExceptionInfo != null)
            {
                log.ErrorFormat("Failed to execute {0}", result.ExecuteExceptionInfo, script);
                result.ExecuteExceptionInfo.Throw();
            }
        }
コード例 #33
0
        public virtual ScriptResult ProcessCommand(string command, ScriptPackSession scriptPackSession)
        {
            _logger.Debug("Processing REPL Command [" + command + "] >>");

            var scriptResult = new ScriptResult();

            if (_replCommands.Count.Equals(0))
            {
                if (scriptPackSession.ReplCommands != null
                    && scriptPackSession.ReplCommands.Count > 0)
                {
                    foreach (var scriptPackReplCommand in scriptPackSession.ReplCommands)
                    {
                        _replCommands.Add(scriptPackReplCommand.Key, scriptPackReplCommand.Value);
                    }
                }
            }

            var script = ParseArguments(command);

            if (!string.IsNullOrWhiteSpace(script))
            {
                script = NormaliseScript(script);

                if (_scriptEngine != null)
                    scriptResult = _scriptEngine.Execute(script,
                                                         new string[0],
                                                         scriptPackSession.References,
                                                         scriptPackSession.Namespaces,
                                                         scriptPackSession);

                _logger.Debug("<< REPL Command executed.");
            }
            else
            {
                scriptResult.ReturnValue = "REPL Command not found";
                _logger.Debug("<< REPL Command not defined.");
            }

            return scriptResult;
        }
コード例 #34
0
        public virtual ScriptResult Execute(string code)
        {
            var result = new ScriptResult();
            try
            {
                var submission = Session.CompileSubmission<object>(code);
                try
                {
                    result.ReturnValue = submission.Execute();
                }
                catch (Exception ex)
                {
                    result.ExecuteExceptionInfo = ExceptionDispatchInfo.Capture(ex);
                }
            }
            catch (Exception ex)
            {
                result.CompileExceptionInfo = ExceptionDispatchInfo.Capture(ex);
            }

            return result;
        }
コード例 #35
0
        public override ScriptResult Execute(string script, params string[] scriptArgs)
        {
            var result = new ScriptResult();
            repl.EvaluateStarted(script, null);

            try
            {
                if (script.StartsWith(":"))
                {
                    var tokens = script.Split(' ');
                    if (tokens[0].Length > 1)
                    {
                        var command = replCommands.FirstOrDefault(x => x.CommandName == tokens[0].Substring(1));

                        if (command != null)
                        {
                            var argsToPass = new List<object>();
                            foreach (var argument in tokens.Skip(1))
                            {
                                var argumentResult = ScriptEngine.Execute(argument, scriptArgs, References, Namespaces, ScriptPackSession);

                                if (argumentResult.CompileExceptionInfo != null)
                                {
                                    throw new Exception(
                                        GetInvalidCommandArgumentMessage(argument),
                                        argumentResult.CompileExceptionInfo.SourceException);
                                }

                                if (argumentResult.ExecuteExceptionInfo != null)
                                {
                                    throw new Exception(
                                        GetInvalidCommandArgumentMessage(argument),
                                        argumentResult.ExecuteExceptionInfo.SourceException);
                                }

                                if (!argumentResult.IsCompleteSubmission)
                                {
                                    throw new Exception(GetInvalidCommandArgumentMessage(argument));
                                }

                                argsToPass.Add(argumentResult.ReturnValue);
                            }

                            var commandResult = command.Execute(this, argsToPass.ToArray());
                            if (commandResult is ScriptResult)
                                result = commandResult as ScriptResult;
                            else
                                result = new ScriptResult(commandResult);
                        }
                        else
                        {
                            throw new Exception("Command not found: " + tokens[0].Substring(1));
                        }
                    }
                }
                else
                {
                    var preProcessResult = FilePreProcessor.ProcessScript(script);

                    ImportNamespaces(preProcessResult.Namespaces.ToArray());

                    foreach (var reference in preProcessResult.References)
                    {
                        var referencePath = FileSystem.GetFullPath(Path.Combine(FileSystem.BinFolder, reference));
                        AddReferences(FileSystem.FileExists(referencePath) ? referencePath : reference);
                    }

                    result = ScriptEngine.Execute(preProcessResult.Code, scriptArgs, References, Namespaces, ScriptPackSession);

                    if (result != null && result.IsCompleteSubmission)
                        PrepareVariables();
                }
            }
            catch (FileNotFoundException fileEx)
            {
                RemoveReferences(fileEx.FileName);
                result = new ScriptResult(compilationException:fileEx);
            }
            catch (Exception ex)
            {
                result = new ScriptResult(executionException:ex);
            }
            finally
            {
                repl.EvaluateCompleted(result);
            }
            return result;
        }
コード例 #36
0
        protected virtual ScriptResult Execute(string code, Session session)
        {
            Guard.AgainstNullArgument("session", session);

            var result = new ScriptResult();
            try
            {
                var submission = session.CompileSubmission<object>(code);
                try
                {
                    result.ReturnValue = submission.Execute();
                }
                catch (Exception ex)
                {
                    result.ExecuteExceptionInfo = ExceptionDispatchInfo.Capture(ex);
                }
            }
            catch (Exception ex)
            {
                 result.UpdateClosingExpectation(ex);
                if (!result.IsPendingClosingChar)
                    result.CompileExceptionInfo = ExceptionDispatchInfo.Capture(ex);
            }
            return result;
        }
コード例 #37
0
 private bool ProcessCoreCommand(string script, out ScriptResult scriptResult)
 {
     scriptResult = new ScriptResult();
     var executedCoreCommand = false;
     try
     {
         if (script.StartsWith("#reset") ||
             script.StartsWith(":reset"))
         {
             Reset();
             executedCoreCommand = true;
         }
     }
     catch (Exception ex)
     {
         Console.ForegroundColor = ConsoleColor.Red;
         Console.WriteLine("\r\n" + ex + "\r\n");
         scriptResult = new ScriptResult {ExecuteExceptionInfo = ExceptionDispatchInfo.Capture(ex)};
     }
     return executedCoreCommand;
 }
コード例 #38
0
ファイル: ReplExecutor.cs プロジェクト: nategreenwood/CShell
        public override ScriptResult Execute(string script, params string[] scriptArgs)
        {
            var result = new ScriptResult();
            repl.EvaluateStarted(script, null);

            try
            {
                if (script.StartsWith(":"))
                {
                    var arguments = script.Split(' ');
                    var command = arguments[0].Substring(1);

                    var argsToPass = new List<object>();
                    foreach (var argument in arguments.Skip(1))
                    {
                        try
                        {
                            var argumentResult = ScriptEngine.Execute(argument, scriptArgs, References, DefaultNamespaces, ScriptPackSession);
                            //if Roslyn can evaluate the argument, use its value, otherwise assume the string
                            argsToPass.Add(argumentResult.ReturnValue ?? argument);
                        }
                        catch (Exception)
                        {
                            argsToPass.Add(argument);
                        }
                    }

                    var commandResult = HandleReplCommand(command, argsToPass.ToArray());
                    result = new ScriptResult(commandResult);
                    return result;
                }

                var preProcessResult = FilePreProcessor.ProcessScript(script);

                ImportNamespaces(preProcessResult.Namespaces.ToArray());

                var referencesToAdd = preProcessResult.References.Select(reference =>
                {
                    var referencePath = FileSystem.GetFullPath(Path.Combine(Constants.BinFolder, reference));
                    return FileSystem.FileExists(referencePath) ? referencePath : reference;
                })
                    .ToArray();

                if (referencesToAdd.Length > 0)
                    AddReferencesAndNotify(referencesToAdd);
                result = ScriptEngine.Execute(preProcessResult.Code, scriptArgs, References, Namespaces, ScriptPackSession);
                if (result == null) return new ScriptResult();

                return result;
            }
            catch (FileNotFoundException fileEx)
            {
                RemoveReferences(fileEx.FileName);
                return new ScriptResult(compilationException:fileEx);
            }
            catch (Exception ex)
            {
                return new ScriptResult(executionException:ex);
            }
            finally
            {
                repl.EvaluateCompleted(result);
            }
        }
コード例 #39
0
        protected virtual ScriptResult Execute(string code, Session session)
        {
            Guard.AgainstNullArgument("session", session);

            var result = new ScriptResult();
            try
            {
                var submission = session.CompileSubmission<object>(code);
                try
                {
                    result.ReturnValue = submission.Execute();
                }
                catch (Exception ex)
                {
                    result.ExecuteException = ex;
                }
            }
            catch (Exception ex)
            {
                result.CompileException = ex;
            }
            return result;
        }
コード例 #40
0
        protected override ScriptResult Execute(string code, Session session)
        {
            Guard.AgainstNullArgument("session", session);

            var scriptResult = new ScriptResult();
            Submission<object> submission = null;

            _logger.Debug("Compiling submission");
            try
            {
                submission = session.CompileSubmission<object>(code);
            }
            catch (Exception compileException)
            {
                scriptResult.CompileExceptionInfo = ExceptionDispatchInfo.Capture(compileException);
            }

            var exeBytes = new byte[0];
            var pdbBytes = new byte[0];
            var compileSuccess = false;

            using (var exeStream = new MemoryStream())
            using (var pdbStream = new MemoryStream())
            {
                var result = submission.Compilation.Emit(exeStream, pdbStream: pdbStream);
                compileSuccess = result.Success;

                if (result.Success)
                {
                    _logger.Debug("Compilation was successful.");
                    exeBytes = exeStream.ToArray();
                    pdbBytes = pdbStream.ToArray();
                }
                else
                {
                    var errors = String.Join(Environment.NewLine, result.Diagnostics.Select(x => x.ToString()));
                    _logger.ErrorFormat("Error occurred when compiling: {0})", errors);
                }
            }

            if (compileSuccess)
            {
                _logger.Debug("Loading assembly into appdomain.");
                var assembly = AppDomain.CurrentDomain.Load(exeBytes, pdbBytes);
                _logger.Debug("Retrieving compiled script class (reflection).");
                var type = assembly.GetType(CompiledScriptClass);
                _logger.Debug("Retrieving compiled script method (reflection).");
                var method = type.GetMethod(CompiledScriptMethod, BindingFlags.Static | BindingFlags.Public);

                try
                {
                    _logger.Debug("Invoking method.");
                    scriptResult.ReturnValue = method.Invoke(null, new[] { session });
                }
                catch (Exception executeException)
                {
                    scriptResult.ExecuteExceptionInfo = ExceptionDispatchInfo.Capture(executeException);
                    _logger.Error("An error occurred when executing the scripts.");
                    var message =
                        string.Format(
                        "Exception Message: {0} {1}Stack Trace:{2}",
                        executeException.InnerException.Message,
                        Environment.NewLine,
                        executeException.InnerException.StackTrace);
                    throw new ScriptExecutionException(message, executeException);
                }
            }

            return scriptResult;
        }
コード例 #41
0
 public void Execute(string scriptFile)
 {
     Result = _script.Root.Executor.Execute(scriptFile);
 }
コード例 #42
0
ファイル: ReplEngineWrapper.cs プロジェクト: gwenzek/icsharp
 private bool IsCompleteResult(ScriptResult scriptResult)
 {
     return scriptResult.ReturnValue != null && !string.IsNullOrEmpty(scriptResult.ReturnValue.ToString());
 }
コード例 #43
0
 public void ExecuteScript(string script)
 {
     Result = _script.Root.Executor.ExecuteScript(script);
 }