Exemplo n.º 1
0
        private async Task <JObject> PrepareInput(XmlElement element)
        {
            var input = default(JObject);

            if (element != null)
            {
                input = new JObject();
                foreach (var inputParameter in element.ChildNodes.OfType <XmlElement>().Where(x => x.LocalName == "inputParameter"))
                {
                    var name   = inputParameter.GetAttribute("name");
                    var script = inputParameter.ChildNodes.OfType <XmlElement>().FirstOrDefault(x => x.LocalName == "script");
                    if (script != null)
                    {
                        var scriptFormat  = script.GetAttribute("scriptFormat");
                        var scriptContent = script.InnerText;
                        var result        = await _scriptExecutor.Execute <JToken>(scriptFormat, scriptContent, new Dictionary <string, object>
                        {
                            ["variables"] = _variables
                        });

                        input[name] = result;
                    }
                    else
                    {
                        var value = inputParameter.InnerText;
                        input[name] = value;
                    }
                }
            }
            return(input);
        }
Exemplo n.º 2
0
        /*public void Execute(PerformContext hangfireContext, Container container)
         * {
         *  if (!container.IsTriggrProject())
         *      return;
         *
         *  var probes = container.CheckForProbes();
         *  hangfireContext.WriteLine($"Executing ProbeControl");
         *
         *  var codeChangeProbes = probes.Where(i => i.ProbeType == ProbeType.CodeChanges).ToList();
         *
         *  var oldFiles = new Dictionary<Probe, string>();
         *  if (codeChangeProbes.Count > 0)
         *  {
         *      foreach (var probe in codeChangeProbes)
         *      {
         *          var tempFile = Path.GetTempFileName();
         *
         *          var objectPath = Path.Combine(container.Folder, probe.Object.Path);
         *          if (File.Exists(objectPath))
         *          {
         *              hangfireContext.WriteLine($"Probe {probe.Object.Path}");
         *
         *              File.Copy(objectPath, tempFile, true);
         *
         *              oldFiles.Add(probe, tempFile);
         *          }
         *      }
         *  }
         *
         *  var provider = _providerFactory.GetProvider(container.Repository.Provider);
         *  var updatedPath = provider.Update(container.Repository);
         *
         *  if (!string.IsNullOrEmpty(updatedPath))
         *  {
         *      foreach (var probe in probes)
         *      {
         *          if (probe.ProbeType == ProbeType.CodeChanges)
         *          {
         *              var tempFile = oldFiles[probe];
         *              var objectPath = Path.Combine(container.Folder, probe.Object.Path);
         *              var language = _languageService.Define(probe.Object.Path);
         *
         *              var result = _scriptExecutor.Execute(probe.ProbeType, language.FolderName,
         *                              objectPath, tempFile, probe.Object.Type, probe.Object.Name);
         *
         *              hangfireContext.WriteLine($"Result of comparision {result}");
         *
         *              // it will changed with executing shell script
         *          }
         *      }
         *  }
         *  hangfireContext.WriteLine($"Finished ProbeControl");
         *
         * }
         */
        public void Execute(PerformContext hangfireContext, string probeId, string repoId)
        {
            var repository = _dbContext.Repositories.Find(repoId); // get the repository

            if (repository != null)
            {
                var container = _containerService.GetContainer(repoId); // get the container

                // get all probes and look for probeId
                var probes = container.CheckForProbes();
                var probe  = probes.FirstOrDefault(i => i.Id.Equals(probeId));

                if (probe != null)
                {
                    hangfireContext?.WriteLine(ConsoleTextColor.Gray, $"{probe.Object.Path} is found.");
                    // define the language
                    var language = _languageService.Define(probe.Object.Path);
                    // get the provider
                    var provider = _providerFactory.GetProvider(repository.Provider);
                    // restore to previous file
                    if (provider.Restore(repository, probe.Object.Path, true))
                    {
                        hangfireContext?.WriteLine(ConsoleTextColor.Gray, $"{probe.Object.Path} is restored to old.");
                        // get the file path
                        var objectPath = Path.Combine(container.Folder, probe.Object.Path);

                        // look for the object
                        var ast1 = _scriptExecutor.Execute("AST", language.FolderName, objectPath, probe.Object.Type, probe.Object.Name);

                        hangfireContext?.WriteLine(ConsoleTextColor.Gray, $"{probe.Object.Path} old version is loaded.");

                        var temp1 = WriteToTemp(ast1);

                        // restore to original file
                        if (provider.Restore(repository, probe.Object.Path, false))
                        {
                            // look for the object
                            var ast2 = _scriptExecutor.Execute("AST", language.FolderName, objectPath, probe.Object.Type, probe.Object.Name);

                            var temp2 = WriteToTemp(ast2);

                            hangfireContext?.WriteLine(ConsoleTextColor.Gray, $"{probe.Object.Path} new version is loaded.");

                            Control(hangfireContext, probe, repository, temp1, temp2, language.FolderName);
                        }
                    }
                }
            }
        }
Exemplo n.º 3
0
        public void Execute_Should_ReturnProperValue_WhenOk()
        {
            // arrange
            var name = "testName";

            var parameters = new List <CommandParameter>
            {
                new CommandParameter("name", name)
            };

            // act
            var result = _executor.Execute(_scripts.ValidScript, parameters);

            // assert
            (result.First().BaseObject as string).Should().Be(name);
        }
Exemplo n.º 4
0
        public CommandResult Execute()
        {
            try
            {
                _fileSystemMigrator.Migrate();

                var assemblyPaths    = Enumerable.Empty <string>();
                var workingDirectory = _fileSystem.GetWorkingDirectory(_script);
                if (workingDirectory != null)
                {
                    assemblyPaths = _assemblyResolver.GetAssemblyPaths(workingDirectory);
                }

                _composer.Compose(workingDirectory);

                _scriptExecutor.Initialize(assemblyPaths, _scriptPackResolver.GetPacks(), ScriptArgs);
                var scriptResult  = _scriptExecutor.Execute(_script, ScriptArgs);
                var commandResult = Inspect(scriptResult);
                _scriptExecutor.Terminate();
                return(commandResult);
            }
            catch (FileNotFoundException ex)
            {
                _logger.ErrorFormat("{0} - '{1}'.", ex, ex.Message, ex.FileName);
                return(CommandResult.Error);
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
                return(CommandResult.Error);
            }
        }
        public MigrationResult ExecuteMigration(string connectionString, string scriptFilePath)
        {
            // Generate C# DataContext using SqlMetal
            var sqlMetalConnectionStringArg = GetSqlMetalConnectionStringArg(connectionString);
            var generatedCSharpDataContext  = new LinqToSQLDataContextGenerator().GenerateDataContext_AndGetCSharpCode(connectionString, sqlMetalConnectionStringArg, dbmlManipulator);

            // Get LinqPad Script
            var linqpadCreator = new LinqPadCSharpCreator();
            var script         = linqpadCreator.Parse(scriptFilePath);

            // Add namespace for DataContext
            script.Namespaces.Add(LinqToSQLDataContextGenerator.DataContextNamespace);

            // Convert LinqPad Script to Executable Source Code
            var executableScript = linqpadCreator.MakeScriptExecutable(script, generatedCSharpDataContext);
            Action <Exception> logExceptionWithSourceCode = (ex) =>
            {
                string primarySourceCode = executableScript.SourceCodePieces.First();
                logger.ErrorException(scriptFilePath, ex);
                logger.Error(primarySourceCode);
            };

            // Create Compiler
            var             csharpProvider = new CSharpCodeProvider();
            IScriptCompiler compiler       = new CodeDomScriptCompiler(csharpProvider);

            Assembly assembly = null;

            try
            {
                // Compile Script > .NET Assembly
                assembly = compiler.Compile(executableScript.AssemblyReferences, executableScript.SourceCodePieces);
            }
            catch (Exception ex)
            {
                var myException = new MigrationException(new MigrationResult(scriptFilePath, false, new[] { "Failed to compile script." }, ex));
                logExceptionWithSourceCode(myException);
                throw myException;
            }

            IScriptExecutor executor = GetScriptExecutor(script);

            try
            {
                // Execute!
                var result = executor.Execute(assembly, scriptFilePath);
                return(result);
            }
            catch (MigrationException ex)
            {
                logExceptionWithSourceCode(ex);
                throw ex;
            }
            catch (Exception ex)
            {
                var myException = new MigrationException(new MigrationResult(scriptFilePath, false, new[] { "Failed to execute compiled script." }, ex));
                logExceptionWithSourceCode(myException);
                throw myException;
            }
        }
Exemplo n.º 6
0
        // run script from file
        public void Run(string scriptPath)
        {
            // preserve current directory
            var previousCurrentDirectory = Environment.CurrentDirectory;

            try
            {
                // set directory to where script is
                // required to find NuGet dependencies
                Environment.CurrentDirectory = Path.GetDirectoryName(scriptPath);

                // prepare NuGet dependencies, download them if required
                var nuGetReferences = PreparePackages(
                    scriptPath,
                    fileSystem, packageAssemblyResolver,
                    packageInstaller);

                // get script packs: not fully tested yet
                var scriptPacks = scriptPackResolver.GetPacks();

                // execute script from file
                scriptExecutor.Initialize(nuGetReferences, scriptPacks);
                scriptExecutor.Execute(scriptPath);
            }
            finally
            {
                // restore current directory
                Environment.CurrentDirectory = previousCurrentDirectory;
            }
        }
Exemplo n.º 7
0
        private void ExecuteScript(Script script)
        {
            if (script.Executed)
            {
                return;
            }

            lock (script.OwnerDocument)
            {
                RaiseBeforeScriptExecute(script);

                try
                {
                    _scriptExecutor.Execute(script.Type ?? "text/javascript",
                                            script.IsExternalScript ? script.Code : script.Text);
                    script.Executed = true;
                    if (script.IsExternalScript)
                    {
                        script.RaiseEvent("load", true, false);
                    }
                }
                catch (Exception ex)
                {
                    RaiseScriptExecutionError(script, ex);
                }

                RaiseAfterScriptExecute(script);
            }
        }
        public void UninstallPackage(Project project, string packageId, bool removeDependencies)
        {
            if (project == null)
            {
                throw new ArgumentNullException("project");
            }
            if (String.IsNullOrEmpty(packageId))
            {
                throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, CommonResources.Argument_Cannot_Be_Null_Or_Empty, "packageId"));
            }

            IVsPackageManager packageManager = _packageManagerFactory.CreatePackageManager(_packageRepository, useFallbackForDependencies: false);
            IProjectManager   projectManager = packageManager.GetProjectManager(project);

            EventHandler <PackageOperationEventArgs> packageReferenceRemovingHandler = (sender, e) =>
            {
                _scriptExecutor.Execute(
                    e.InstallPath,
                    PowerShellScripts.Uninstall,
                    e.Package,
                    project,
                    projectManager.GetTargetFrameworkForPackage(packageId),
                    NullLogger.Instance);
            };

            try
            {
                projectManager.PackageReferenceRemoving += packageReferenceRemovingHandler;
                packageManager.UninstallPackage(projectManager, packageId, version: null, forceRemove: false, removeDependencies: removeDependencies);
            }
            finally
            {
                projectManager.PackageReferenceRemoving -= packageReferenceRemovingHandler;
            }
        }
Exemplo n.º 9
0
        private static CalamariResult ExecuteScript(IScriptExecutor psse, string scriptName, IVariables variables)
        {
            var runner = new TestCommandLineRunner(ConsoleLog.Instance, variables);
            var result = psse.Execute(new Script(scriptName), variables, runner);

            return(new CalamariResult(result.ExitCode, runner.Output));
        }
Exemplo n.º 10
0
        protected CalamariResult ExecuteScript(IScriptExecutor psse, string scriptName, IVariables variables)
        {
            var runner = new TestCommandLineRunner(new InMemoryLog(), variables);
            var result = psse.Execute(new Script(scriptName), variables, runner);

            return(new CalamariResult(result.ExitCode, runner.Output));
        }
Exemplo n.º 11
0
        public CommandResult Execute()
        {
            try
            {
                _fileSystemMigrator.Migrate();

                var assemblyPaths    = Enumerable.Empty <string>();
                var workingDirectory = _fileSystem.GetWorkingDirectory(_script);
                if (workingDirectory != null)
                {
                    assemblyPaths = _assemblyResolver.GetAssemblyPaths(workingDirectory);
                }

                _composer.Compose(workingDirectory);

                _scriptExecutor.Initialize(assemblyPaths, _scriptPackResolver.GetPacks(), ScriptArgs);

                // HACK: This is a (dirty) fix for #1086. This might be a temporary solution until some further refactoring can be done.
                _scriptExecutor.ScriptEngine.CacheDirectory = Path.Combine(workingDirectory ?? _fileSystem.CurrentDirectory, _fileSystem.DllCacheFolder);
                var scriptResult  = _scriptExecutor.Execute(_script, ScriptArgs);
                var commandResult = Inspect(scriptResult);
                _scriptExecutor.Terminate();
                return(commandResult);
            }
            catch (Exception ex)
            {
                _logger.ErrorException("Error executing script '{0}'", ex, _script);
                return(CommandResult.Error);
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// This executes the install script.
        /// </summary>
        /// <param name="p_tfmFileManager">The transactional file manager to use to interact with the file system.</param>
        /// <returns><c>true</c> if the script completed successfully;
        /// <c>false</c> otherwise.</returns>
        protected bool RunScript(TxFileManager p_tfmFileManager)
        {
            IModFileInstaller mfiFileInstaller = CreateFileInstaller(p_tfmFileManager, m_dlgOverwriteConfirmationDelegate);
            bool booResult = false;

            if (Mod.HasInstallScript)
            {
                IDataFileUtil dfuDataFileUtility = new DataFileUtil(GameMode.GameModeEnvironmentInfo.InstallationPath);

                IIniInstaller iniIniInstaller = CreateIniInstaller(p_tfmFileManager, m_dlgOverwriteConfirmationDelegate);
                IGameSpecificValueInstaller gviGameSpecificValueInstaller = CreateGameSpecificValueInstaller(p_tfmFileManager, m_dlgOverwriteConfirmationDelegate);

                InstallerGroup  ipgInstallers = new InstallerGroup(dfuDataFileUtility, mfiFileInstaller, iniIniInstaller, gviGameSpecificValueInstaller, PluginManager);
                IScriptExecutor sexScript     = Mod.InstallScript.Type.CreateExecutor(Mod, GameMode, EnvironmentInfo, ipgInstallers, UIContext);
                sexScript.TaskStarted      += new EventHandler <EventArgs <IBackgroundTask> >(ScriptExecutor_TaskStarted);
                sexScript.TaskSetCompleted += new EventHandler <TaskSetCompletedEventArgs>(ScriptExecutor_TaskSetCompleted);
                booResult = sexScript.Execute(Mod.InstallScript);

                iniIniInstaller.FinalizeInstall();

                if (gviGameSpecificValueInstaller != null)
                {
                    gviGameSpecificValueInstaller.FinalizeInstall();
                }
            }
            else
            {
                booResult = RunBasicInstallScript(mfiFileInstaller, ActiveMods);
            }
            mfiFileInstaller.FinalizeInstall();
            return(booResult);
        }
Exemplo n.º 13
0
 public static void ExecuteScript(this IScriptExecutor executor, string installPath, string scriptFileName, IPackage package, Project project, ILogger logger)
 {
     if (package.HasPowerShellScript(new[] { scriptFileName }))
     {
         executor.Execute(installPath, scriptFileName, package, project, logger);
     }
 }
Exemplo n.º 14
0
        private void ExecuteItemScript(IEntity user, string scriptName, IEntity item)
        {
            var script = prototypeSystem.Get(scriptName);

            var scriptText = script.Get <Script>().Text;

            scriptExecutor.Execute(user, scriptText, item);
        }
Exemplo n.º 15
0
 protected override object DoWork(object[] p_objArgs)
 {
     Thread.Sleep(0); // ensures that the main thread gets an opportunity to start the main loop
     try {
         return(m_Executor.Execute(m_Script));
     } catch (Exception e) {
         MessageBox.Show(e.Message, "Installation failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
         return(null);
     }
 }
Exemplo n.º 16
0
        /// <summary>
        /// This executes the install script.
        /// </summary>
        /// <param name="p_tfmFileManager">The transactional file manager to use to interact with the file system.</param>
        /// <returns><c>true</c> if the script completed successfully;
        /// <c>false</c> otherwise.</returns>
        protected bool RunScript(TxFileManager p_tfmFileManager)
        {
            IModFileInstaller mfiFileInstaller = CreateFileInstaller(p_tfmFileManager, m_dlgOverwriteConfirmationDelegate);
            bool          booResult            = false;
            IIniInstaller iniIniInstaller      = null;
            IGameSpecificValueInstaller gviGameSpecificValueInstaller = null;

            if (Mod.HasInstallScript)
            {
                if (CheckScriptedModLog())
                {
                    booResult = RunBasicInstallScript(mfiFileInstaller, ActiveMods, LoadXMLModFilesToInstall());
                }
                else
                {
                    try
                    {
                        IDataFileUtil dfuDataFileUtility = new DataFileUtil(GameMode.GameModeEnvironmentInfo.InstallationPath);

                        iniIniInstaller = CreateIniInstaller(p_tfmFileManager, m_dlgOverwriteConfirmationDelegate);
                        gviGameSpecificValueInstaller = CreateGameSpecificValueInstaller(p_tfmFileManager, m_dlgOverwriteConfirmationDelegate);

                        InstallerGroup  ipgInstallers = new InstallerGroup(dfuDataFileUtility, mfiFileInstaller, iniIniInstaller, gviGameSpecificValueInstaller, PluginManager);
                        IScriptExecutor sexScript     = Mod.InstallScript.Type.CreateExecutor(Mod, GameMode, EnvironmentInfo, VirtualModActivator, ipgInstallers, UIContext);
                        sexScript.TaskStarted      += new EventHandler <EventArgs <IBackgroundTask> >(ScriptExecutor_TaskStarted);
                        sexScript.TaskSetCompleted += new EventHandler <TaskSetCompletedEventArgs>(ScriptExecutor_TaskSetCompleted);
                        booResult = sexScript.Execute(Mod.InstallScript);
                    }
                    catch (Exception ex)
                    {
                        PopupErrorMessage     = ex.Message;
                        PopupErrorMessageType = "Error";
                    }

                    iniIniInstaller.FinalizeInstall();

                    if (gviGameSpecificValueInstaller != null)
                    {
                        gviGameSpecificValueInstaller.FinalizeInstall();
                    }
                }
            }
            else
            {
                booResult = RunBasicInstallScript(mfiFileInstaller, ActiveMods, null);
            }
            mfiFileInstaller.FinalizeInstall();
            return(booResult);
        }
Exemplo n.º 17
0
        public CommandResult Execute()
        {
            try
            {
                var assemblyPaths = Enumerable.Empty <string>();

                var workingDirectory = _fileSystem.GetWorkingDirectory(_script);
                if (workingDirectory != null)
                {
                    assemblyPaths = _assemblyResolver.GetAssemblyPaths(workingDirectory, _script);
                }

                _scriptExecutor.Initialize(assemblyPaths, _scriptPackResolver.GetPacks(), ScriptArgs);
                var result = _scriptExecutor.Execute(_script, ScriptArgs);
                _scriptExecutor.Terminate();

                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);
                }

                return(CommandResult.Success);
            }
            catch (FileNotFoundException fnfex)
            {
                _logger.ErrorFormat("{0} - {1}", fnfex.Message, fnfex.FileName);
                return(CommandResult.Error);
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message);
                return(CommandResult.Error);
            }
        }
Exemplo n.º 18
0
        public CommandResult Execute()
        {
            try
            {
                var assemblyPaths = Enumerable.Empty <string>();

                var workingDirectory = _fileSystem.GetWorkingDirectory(_script);
                if (workingDirectory != null)
                {
                    assemblyPaths = GetAssemblyPaths(workingDirectory);
                }

                _scriptExecutor.Execute(_script, assemblyPaths, _scriptPackResolver.GetPacks());
                return(CommandResult.Success);
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message);
                return(CommandResult.Error);
            }
        }
Exemplo n.º 19
0
        private void ExecuteScript(ScriptInfo script)
        {
            var scriptElement = script.Node;

            if (scriptElement.Executed)
            {
                return;
            }

            var document = scriptElement.OwnerDocument;

            lock (document)
            {
                RaiseBeforeScriptExecute(scriptElement);

                document.CurrentScript = scriptElement;
                try
                {
                    _scriptExecutor.Execute(
                        scriptElement.Type ?? "text/javascript",
                        script.Code);
                    scriptElement.Executed = true;
                    if (IsExternalScript(scriptElement))
                    {
                        script.Node.RaiseEvent("load", true, false);
                    }
                }
                catch (Exception ex)
                {
                    RaiseScriptExecutionError(scriptElement, ex);
                }
                finally
                {
                    document.CurrentScript = null;
                }

                RaiseAfterScriptExecute(scriptElement);
            }
        }
Exemplo n.º 20
0
 /// <summary>
 /// Executes script.
 /// </summary>
 /// <param name="index">
 /// The script index to execute.
 /// </param>
 /// <param name="executor">
 /// Virtual machine which executes the script.
 /// </param>
 /// <returns>
 /// True on success. False on failure.
 /// </returns>
 public static bool RunScript(int index, IScriptExecutor executor)
 {
     return executor.Execute(GetScript(index));
 }
Exemplo n.º 21
0
        /// <summary>
        /// This will assign all files to the proper destination.
        /// </summary>
        /// <param name="modArchive">The list of files inside the mod archive.</param>
        /// <param name="prefixPath">base path for all relative paths</param>
        /// <param name="progressDelegate">A delegate to provide progress feedback.</param>
        /// <param name="coreDelegate">A delegate for all the interactions with the js core.</param>
        protected async Task <IList <Instruction> > ScriptedModInstall(Mod modArchive, ProgressDelegate progressDelegate, CoreDelegates coreDelegate)
        {
            IScriptExecutor sexScript = modArchive.InstallScript.Type.CreateExecutor(modArchive, coreDelegate);

            return(await sexScript.Execute(modArchive.InstallScript, modArchive.TempPath));
        }
Exemplo n.º 22
0
 /// <summary>
 /// Executes script.
 /// </summary>
 /// <param name="script">
 /// The script text to execute.
 /// </param>
 /// <param name="executor">
 /// Virtual machine which executes the script.
 /// </param>
 /// <returns>
 /// True on success. False on failure.
 /// </returns>
 public static bool RunScript(string script, IScriptExecutor executor)
 {
     return(executor.Execute(script));
 }
Exemplo n.º 23
0
 /// <summary>
 /// Executes script.
 /// </summary>
 /// <param name="index">
 /// The script index to execute.
 /// </param>
 /// <param name="executor">
 /// Virtual machine which executes the script.
 /// </param>
 /// <returns>
 /// True on success. False on failure.
 /// </returns>
 public static bool RunScript(int index, IScriptExecutor executor)
 {
     return(executor.Execute(GetScript(index)));
 }
Exemplo n.º 24
0
 /// <summary>
 /// Executes script.
 /// </summary>
 /// <param name="script">
 /// The script text to execute.
 /// </param>
 /// <param name="executor">
 /// Virtual machine which executes the script.
 /// </param>
 /// <returns>
 /// True on success. False on failure.
 /// </returns>
 public static bool RunScript(string script, IScriptExecutor executor)
 {
     return executor.Execute(script);
 }
Exemplo n.º 25
0
 public void Execute_EmptyScript_Works()
 {
     ScriptExecutor.Execute(TestEntity, "", null);
 }
Exemplo n.º 26
0
        /// <inheritdoc />
        public WindowsServiceState GetState(string serviceName)
        {
            ThrowIfCantFindService(serviceName);

            var parameters = new List <CommandParameter>
            {
                new CommandParameter("serviceName", serviceName)
            };

            var result = _executor.Execute(_scripts.GetServiceState, parameters);

            ThrowServiceExceptionIfNecessary(result);

            return(_mapper.MapServiceState(result.FirstOrDefault()));
        }