예제 #1
0
        public static void Dispatch(RunConfiguration config, TopshelfArguments args)
        {
            if (!string.IsNullOrEmpty(args.Instance))
            {
                _log.Info("Using instance name from commandline.");
                config.WinServiceSettings.ServiceName = new ServiceName(
                    config.WinServiceSettings.ServiceName.Name,
                    args.Instance);
            }

            //find the command by the args 'Command'
            var run = new RunCommand(config.Coordinator, config.WinServiceSettings.ServiceName);

            var command = new List<Command>
                                  {
                                      run,
                                      new InstallService(config.WinServiceSettings),
                                      new UninstallService(config.WinServiceSettings)
                                  }
                .Where(x => x.Name == args.ActionName)
                .DefaultIfEmpty(run)
                .SingleOrDefault();

            _log.DebugFormat("Running command: '{0}'", command.Name);

            command.Execute();
        }
예제 #2
0
 public void Writeline()
 {
     _out = new StringWriter();
     _error = new StringWriter();
     _runCommand = new RunCommand() { FileName = "FailWithError.exe",Params=new{Test="value"}, Out = _out, Error = _error };
     _exitstatus = _runCommand.Execute();
     Console.WriteLine(_out.ToString());
     Console.WriteLine(_error.ToString());
 }
예제 #3
0
 public void When_I_run_Frankie()
 {
     var options = new BaseOptions
         {
             Output = BasePath + "/_site",
             Source = BasePath,
         };
     var command = new RunCommand();
     command.ExecuteCommand(options);
 }
예제 #4
0
        public void ItCanNewRestoreBuildRunCleanMSBuildProject()
        {
            var    directory        = TestAssets.CreateTestDirectory();
            string projectDirectory = directory.FullName;

            string newArgs = "console --debug:ephemeral-hive --no-restore";

            new NewCommandShim()
            .WithWorkingDirectory(projectDirectory)
            .Execute(newArgs)
            .Should().Pass();

            string projectPath = Path.Combine(projectDirectory, directory.Name + ".csproj");
            var    project     = XDocument.Load(projectPath);
            var    ns          = project.Root.Name.Namespace;

            project.Root.Element(ns + "PropertyGroup")
            .Element(ns + "TargetFramework").Value = currentTfm;
            project.Save(projectPath);

            new RestoreCommand()
            .WithWorkingDirectory(projectDirectory)
            .Execute()
            .Should().Pass();

            new BuildCommand()
            .WithWorkingDirectory(projectDirectory)
            .Execute()
            .Should().Pass();

            var runCommand = new RunCommand()
                             .WithWorkingDirectory(projectDirectory)
                             .ExecuteWithCapturedOutput()
                             .Should().Pass().And.HaveStdOutContaining("Hello, World!");

            var binDirectory = new DirectoryInfo(projectDirectory).Sub("bin");

            binDirectory.Should().HaveFilesMatching("*.dll", SearchOption.AllDirectories);

            new CleanCommand()
            .WithWorkingDirectory(projectDirectory)
            .Execute()
            .Should().Pass();

            binDirectory.Should().NotHaveFilesMatching("*.dll", SearchOption.AllDirectories);
        }
        public void ItDoesNotImplicitlyBuildAProjectWhenRunningWithTheNoBuildOption()
        {
            var testAppName  = "MSBuildTestApp";
            var testInstance = TestAssets.Get(testAppName)
                               .CreateInstance()
                               .WithSourceFiles();

            var result = new RunCommand()
                         .WithWorkingDirectory(testInstance.Root.FullName)
                         .ExecuteWithCapturedOutput("--no-build -v:m");

            result.Should().Fail();
            if (!DotnetUnderTest.IsLocalized())
            {
                result.Should().NotHaveStdOutContaining("Restore");
            }
        }
예제 #6
0
        /// <summary>
        /// delete the user as an adminstrator for this app
        /// </summary>
        /// <param name="environment">name of service environment</param>
        /// <param name="appHandle">app handle</param>
        /// <param name="userHandle">user handle</param>
        /// <returns>true if user is deleted from admin list</returns>
        public static bool DeleteAdmin(string environment, string appHandle, string userHandle)
        {
            // step 3: use the manageapps utility to register the user as an administrator
            string command1       = "cd " + ConfigurationManager.AppSettings["ManageAppsRelativePath"] + " & " + manageAppsExecutable + " -Name=" + environment + " -DeleteAppAdmin -AppHandle=" + appHandle + " -UserHandle=" + userHandle;
            string command1Output = RunCommand.Execute(command1);

            // expected output:  "UserHandle = <user-handle> deleted from list of admins for appHandle = <app-handle>"
            string expectedOutputPattern = @"^UserHandle = ([\w-]+) deleted from list of admins for appHandle = ([\w-]+)";
            var    match = Regex.Match(command1Output, expectedOutputPattern, RegexOptions.Multiline);

            if (match.Success == false)
            {
                return(false);
            }

            return(true);
        }
예제 #7
0
        public ManualTestViewModel()
        {
            Checks.Add(CheckSize);
            Checks.Add(CheckLayout);
            Checks.Add(CheckCorner);
            Checks.Add(CheckToastCommon);
            Checks.Add(CheckDialogCommon);
            Checks.Add(CheckDialog);
            Checks.Add(CheckLoadingCommon);
            Checks.Add(CheckLoading);

            RunCommand.Subscribe(async _ =>
            {
                await ToastTest();
                await DialogTest();
                await LoadingTest();
            });

            void CheckChange(bool turned)
            {
                foreach (var check in Checks)
                {
                    check.Value = turned;
                }
            }

            AllCheckCommand.Subscribe(_ => CheckChange(true));
            NoneCheckCommand.Subscribe(_ => CheckChange(false));

            SaveCommand.Subscribe(_ =>
            {
                for (var i = 0; i < Checks.Count; i++)
                {
                    Application.Current.Properties[$"check{i}"] = Checks[i].Value;
                }
                Application.Current.SavePropertiesAsync();
            });

            for (var i = 0; i < Checks.Count; i++)
            {
                if (Application.Current.Properties.TryGetValue($"check{i}", out var check))
                {
                    Checks[i].Value = (bool)check;
                }
            }
        }
예제 #8
0
 public void RunAPSIM(object sender, EventArgs e)
 {
     try
     {
         if (!Configuration.Settings.AutoSave || this.explorerPresenter.Save())
         {
             Model model  = this.explorerPresenter.ApsimXFile.FindByPath(this.explorerPresenter.CurrentNodePath)?.Value as Model;
             var   runner = new Runner(model, runType: Runner.RunTypeEnum.MultiThreaded, wait: false);
             this.command = new RunCommand(model.Name, runner, this.explorerPresenter);
             this.command.Do();
         }
     }
     catch (Exception err)
     {
         explorerPresenter.MainPresenter.ShowError(err);
     }
 }
예제 #9
0
        public void GetHelpDetails_WithValidInput_HelpDetails()
        {
            ArrangeInputs(parseResultSections: "run InputFileForRunCommand.txt",
                          out MockedShellState shellState,
                          out HttpState httpState,
                          out ICoreParseResult parseResult);

            string expected = "\u001b[1mUsage: \u001b[39mrun {path to script}" + Environment.NewLine + Environment.NewLine +
                              "Runs the specified script." + Environment.NewLine +
                              "A script is a text file containing one CLI command per line. Each line will be run as if it was typed into the CLI." + Environment.NewLine + Environment.NewLine +
                              "When +history option is specified, commands specified in the text file will be added to command history." + Environment.NewLine;

            RunCommand runCommand = new RunCommand(new MockedFileSystem());
            string     result     = runCommand.GetHelpDetails(shellState, httpState, parseResult);

            Assert.Equal(expected, result);
        }
예제 #10
0
        public ICommand Build(string command)
        {
            string[] commandSplit = command?.Split(' ');

            ICommand createdCommand;

            switch (commandSplit[0])
            {
            case "/help":
            case "/h":
                createdCommand = new HelpCommand();
                break;

            case "/version":
            case "/v":
                createdCommand = new VersionCommand();
                break;

            case "/clear":
            case "/c":
                createdCommand = new ClearCommand();
                break;

            case "/quit":
            case "/q":
                createdCommand = new QuitCommand();
                break;

            case "/list":
            case "/l":
                createdCommand = new ListCommand();
                break;

            case "/run":
            case "/r":
                createdCommand = new RunCommand(commandSplit);
                break;

            default:
                createdCommand = new DefaultCommand();
                break;
            }

            return(createdCommand);
        }
예제 #11
0
 /// <summary>Run APSIM.</summary>
 /// <param name="multiProcessRunner">Use the multi-process runner?</param>
 private void RunAPSIMInternal(bool multiProcessRunner)
 {
     if (this.explorerPresenter.Save())
     {
         List <string> duplicates = this.explorerPresenter.ApsimXFile.FindDuplicateSimulationNames();
         if (duplicates.Count > 0)
         {
             string errorMessage = "Duplicate simulation names found " + StringUtilities.BuildString(duplicates.ToArray(), ", ");
             explorerPresenter.MainPresenter.ShowError(errorMessage);
         }
         else
         {
             Model model = Apsim.Get(this.explorerPresenter.ApsimXFile, this.explorerPresenter.CurrentNodePath) as Model;
             this.command = new RunCommand(model, this.explorerPresenter, multiProcessRunner);
             this.command.Do(null);
         }
     }
 }
        private void SetResultsPath()
        {
            var files = new SaveFileDialog()
            {
                InitialDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                Filter           = "xml files (*.xml) | *.xml",
                RestoreDirectory = true,
                DefaultExt       = ".xml"
            };

            var filesResult = files.ShowDialog();

            if (filesResult != null && filesResult == true)
            {
                Results = files.FileName;
                RunCommand.RaiseCanExecuteChanged();
            }
        }
예제 #13
0
    private void RunFile(MainPresenter mainPresenter)
    {
        ExplorerPresenter presenter = mainPresenter.Presenters1[0] as ExplorerPresenter;

        if (presenter == null)
        {
            throw new Exception("Unable to open wheat example.");
        }

        Clock clock = presenter.ApsimXFile.FindInScope <Clock>();

        clock.EndDate = clock.StartDate.AddDays(10);

        Runner     runner  = new Runner(presenter.ApsimXFile, runType: Runner.RunTypeEnum.MultiThreaded);
        RunCommand command = new RunCommand("Simulations", runner, presenter);

        command.Do(null);
    }
예제 #14
0
        public static void Dispatch(RunConfiguration config, TopshelfArguments args)
        {
            //find the command by the args 'Command'
            var run = new RunCommand(config.Coordinator, config.WinServiceSettings.ServiceName);
            var command = new List<Command>
                                  {
                                      run,
                                      new InstallService(config.WinServiceSettings),
                                      new UninstallService(config.WinServiceSettings)
                                  }
                .Where(x => x.Name == args.ActionName)
                .DefaultIfEmpty(run)
                .SingleOrDefault();

            _log.DebugFormat("Running command: '{0}'", command.Name);

            command.Execute();
        }
예제 #15
0
    static void Main()
    {
        Receiver receiver = new Receiver();
        ICommand command  = new ConcreteCommand(receiver);
        ICommand runCmd   = new RunCommand(receiver);
        ICommand sitCmd   = new SitCommand(receiver);

        Invoker invoker = new Invoker();

        invoker.SetCommand(command);
        invoker.Invoke();

        invoker.SetCommand(runCmd);
        invoker.Invoke();

        invoker.SetCommand(sitCmd);
        invoker.Invoke();
    }
예제 #16
0
        private void OperationList_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == NotifyCollectionChangedAction.Add)
            {
                IEnumerable <IOperation> newItems = e.NewItems.Cast <IOperation>();

                ScriptString += ScriptConverter.GetString(newItems);
                ScriptHex    += ScriptConverter.GetHex(newItems);
            }
            else if (e.Action == NotifyCollectionChangedAction.Reset)
            {
                ScriptString = string.Empty;
                ScriptHex    = string.Empty;
            }

            // Raise for all actions: add, remove, change,...
            RunCommand.RaiseCanExecuteChanged();
        }
예제 #17
0
        public void CreateDocumentation(object sender, EventArgs e)
        {
            try
            {
                if (this.explorerPresenter.Save())
                {
                    string destinationFolder = Path.Combine(Path.GetDirectoryName(this.explorerPresenter.ApsimXFile.FileName), "Doc");
                    if (destinationFolder != null)
                    {
                        explorerPresenter.MainPresenter.ShowMessage("Creating documentation...", Simulation.MessageType.Information);
                        explorerPresenter.MainPresenter.ShowWaitCursor(true);

                        ICommand command;
                        string   fileNameWritten;
                        var      modelToDocument = Apsim.Get(explorerPresenter.ApsimXFile, explorerPresenter.CurrentNodePath) as IModel;

                        if (modelToDocument is Simulations)
                        {
                            command         = new CreateDocCommand(explorerPresenter);
                            fileNameWritten = (command as CreateDocCommand).FileNameWritten;
                        }
                        else
                        {
                            command         = new CreateModelDescriptionDocCommand(explorerPresenter, modelToDocument);
                            fileNameWritten = (command as CreateModelDescriptionDocCommand).FileNameWritten;
                        }

                        explorerPresenter.CommandHistory.Add(command, true);
                        explorerPresenter.MainPresenter.ShowMessage("Written " + fileNameWritten, Simulation.MessageType.Information);

                        // Open the document.
                        Process.Start(fileNameWritten);
                    }
                }
            }
            catch (Exception err)
            {
                explorerPresenter.MainPresenter.ShowError(err);
            }
            finally
            {
                explorerPresenter.MainPresenter.ShowWaitCursor(false);
            }
        }
예제 #18
0
        public void ItCanNewRestoreBuildRunCleanMSBuildProject()
        {
            using (DisposableDirectory directory = Temp.CreateDirectory())
            {
                string projectDirectory = directory.Path;

                string newArgs = "console --debug:ephemeral-hive --no-restore";
                new NewCommandShim()
                .WithWorkingDirectory(projectDirectory)
                .Execute(newArgs)
                .Should().Pass();

                new RestoreCommand()
                .WithWorkingDirectory(projectDirectory)
                .Execute("/p:SkipInvalidConfigurations=true")
                .Should().Pass();

                new BuildCommand()
                .WithWorkingDirectory(projectDirectory)
                .Execute()
                .Should().Pass();

                var runCommand = new RunCommand()
                                 .WithWorkingDirectory(projectDirectory);

                //  Set DOTNET_ROOT as workaround for https://github.com/dotnet/cli/issues/10196
                runCommand = runCommand.WithEnvironmentVariable(Environment.Is64BitProcess ? "DOTNET_ROOT" : "DOTNET_ROOT(x86)",
                                                                Path.GetDirectoryName(DotnetUnderTest.FullName));

                runCommand.ExecuteWithCapturedOutput()
                .Should().Pass()
                .And.HaveStdOutContaining("Hello World!");

                var binDirectory = new DirectoryInfo(projectDirectory).Sub("bin");
                binDirectory.Should().HaveFilesMatching("*.dll", SearchOption.AllDirectories);

                new CleanCommand()
                .WithWorkingDirectory(projectDirectory)
                .Execute()
                .Should().Pass();

                binDirectory.Should().NotHaveFilesMatching("*.dll", SearchOption.AllDirectories);
            }
        }
예제 #19
0
        /// <summary>
        /// run ManageApps.exe to get the app handle
        /// </summary>
        /// <param name="environment">name of service environment</param>
        /// <returns>the app handle</returns>
        public static string GetAppHandle(string environment)
        {
            // lookup the apphandle associated with the appkey
            string command1       = "cd " + ConfigurationManager.AppSettings["ManageAppsRelativePath"] + " & " + manageAppsExecutable + " -Name=" + environment + " -GetAppHandle -AppKey=" + TestConstants.AppKey;
            string command1Output = RunCommand.Execute(command1);

            // expected output:  "AppHandle = <app-handle> for application with appKey = <app-key>"
            string expectedOutputPattern = @"^AppHandle = ([\w-]+) for application with appKey = ([\w-]+)";
            var    match = Regex.Match(command1Output, expectedOutputPattern, RegexOptions.Multiline);

            if (match.Success == true)
            {
                return(match.Groups[1].Value);
            }
            else
            {
                return(null);
            }
        }
예제 #20
0
        public void ItPrintsUsingLaunchSettingsMessageWhenNotQuiet()
        {
            var testInstance = TestAssets.Get("AppWithLaunchSettings")
                               .CreateInstance()
                               .WithSourceFiles();

            var testProjectDirectory = testInstance.Root.FullName;
            var launchSettingsPath   = Path.Combine(testProjectDirectory, "Properties", "launchSettings.json");

            var cmd = new RunCommand()
                      .WithWorkingDirectory(testProjectDirectory)
                      .ExecuteWithCapturedOutput("-v:m");

            cmd.Should().Pass()
            .And.HaveStdOutContaining(string.Format(LocalizableStrings.UsingLaunchSettingsFromMessage, launchSettingsPath))
            .And.HaveStdOutContaining("First");

            cmd.StdErr.Should().BeEmpty();
        }
예제 #21
0
        public void Run_command_tests(string name)
        {
            // Arrange
            var content  = _testSource.BinFiles[name];
            var expected = _testSource.TxtFiles[name];
            var options  = new RunOptions()
            {
                FilePath = name
            };
            var reader        = MockFactory.NewFileReader(content);
            var writer        = MockFactory.NewOutputWriter();
            var configuration = MockFactory.NewConfiguration();

            // Act
            RunCommand.Run(options, reader, writer, configuration);

            // Assert
            Assert.Equal(expected, writer.Output);
        }
예제 #22
0
        public void ItCanRunAnAppUsingTheWebSdk()
        {
            var    directory        = TestAssets.CreateTestDirectory();
            string projectDirectory = directory.FullName;

            string newArgs = "console --debug:ephemeral-hive --no-restore";

            new NewCommandShim()
            .WithWorkingDirectory(projectDirectory)
            .Execute(newArgs)
            .Should().Pass();

            string projectPath = Path.Combine(projectDirectory, directory.Name + ".csproj");

            var project = XDocument.Load(projectPath);
            var ns      = project.Root.Name.Namespace;

            project.Root.Attribute("Sdk").Value = "Microsoft.NET.Sdk.Web";

            project.Save(projectPath);

            new BuildCommand()
            .WithWorkingDirectory(projectDirectory)
            .Execute()
            .Should().Pass();

            var runCommand = new RunCommand()
                             .WithWorkingDirectory(projectDirectory);

            //  Set DOTNET_ROOT as workaround for https://github.com/dotnet/cli/issues/10196
            var dotnetRoot = Path.GetDirectoryName(RepoDirectoriesProvider.DotnetUnderTest);

            if (!string.IsNullOrEmpty(dotnetRoot))
            {
                bool useX86 = RepoDirectoriesProvider.DotnetRidUnderTest.EndsWith("x86", StringComparison.InvariantCultureIgnoreCase);
                runCommand = runCommand.WithEnvironmentVariable(useX86 ? "DOTNET_ROOT(x86)" : "DOTNET_ROOT",
                                                                dotnetRoot);
            }

            runCommand.ExecuteWithCapturedOutput()
            .Should().Pass()
            .And.HaveStdOutContaining("Hello World!");
        }
예제 #23
0
        public void ItTerminatesTheChildWhenKilled()
        {
            var asset = TestAssets.Get("TestAppThatWaits")
                        .CreateInstance()
                        .WithSourceFiles();

            var command = new RunCommand()
                          .WithWorkingDirectory(asset.Root.FullName);

            bool    killed = false;
            Process child  = null;

            command.OutputDataReceived += (s, e) =>
            {
                if (killed)
                {
                    return;
                }

                child = Process.GetProcessById(Convert.ToInt32(e.Data));
                command.CurrentProcess.Kill();

                killed = true;
            };

            // A timeout is required to prevent the `Process.WaitForExit` call to hang if `dotnet run` failed to terminate the child on Windows.
            // This is because `Process.WaitForExit()` hangs waiting for the process launched by `dotnet run` to close the redirected I/O pipes (which won't happen).
            command.TimeoutMiliseconds = WaitTimeout;

            command
            .ExecuteWithCapturedOutput()
            .Should()
            .ExitWith(-1);

            killed.Should().BeTrue();

            if (!child.WaitForExit(WaitTimeout))
            {
                child.Kill();
                throw new XunitException("child process failed to terminate.");
            }
        }
예제 #24
0
        public ConcordionBuilder()
        {
            BuildListeners = new List <IConcordionBuildListener>();
            SpecificationProcessingListeners = new List <ISpecificationProcessingListener>();
            ResourceToCopyMap  = new Dictionary <string, Resource>();
            ExceptionListeners = new List <IExceptionCaughtListener>();

            SpecificationLocator = new ClassNameBasedSpecificationLocator();
            Source               = null;
            Target               = null;
            CommandRegistry      = new CommandRegistry();
            DocumentParser       = new DocumentParser(CommandRegistry);
            EvaluatorFactory     = new SimpleEvaluatorFactory();
            SpecificationCommand = new SpecificationCommand();
            AssertEqualsCommand  = new AssertEqualsCommand();
            AssertTrueCommand    = new AssertTrueCommand();
            AssertFalseCommand   = new AssertFalseCommand();
            ExecuteCommand       = new ExecuteCommand();
            RunCommand           = new RunCommand();
            VerifyRowsCommand    = new VerifyRowsCommand();
            EchoCommand          = new EchoCommand();
            ExceptionRenderer    = new ExceptionRenderer();

            WithExceptionListener(ExceptionRenderer);

            // Set up the commands

            CommandRegistry.Register("", "specification", SpecificationCommand);

            // Wire up the command listeners

            var assertResultRenderer = new AssertResultRenderer();

            WithAssertEqualsListener(assertResultRenderer);
            WithAssertTrueListener(assertResultRenderer);
            WithAssertFalseListener(assertResultRenderer);
            WithVerifyRowsListener(new VerifyRowResultRenderer());
            WithRunListener(new RunResultRenderer());
            WithDocumentParsingListener(new DocumentStructureImprover());
            WithDocumentParsingListener(new MetadataCreator());
            WithEmbeddedCss(HtmlFramework.EMBEDDED_STYLESHEET_RESOURCE);
        }
예제 #25
0
        public async Task can_start_application()
        {
            var builder = Host.CreateDefaultBuilder();


            var input = new RunInput
            {
                HostBuilder = builder
            };

            var command = new RunCommand();

            var task = Task.Factory.StartNew(() => command.Execute(input));

            command.Started.Wait(5.Seconds());

            command.Reset.Set();

            await task;
        }
예제 #26
0
        public static void Dispatch(RunConfiguration config, TopshelfArguments args)
        {
            //find the command by the args 'Command'
            var run = new RunCommand(config.Coordinator, config.WinServiceSettings.ServiceName);
            Command command = new List<Command>
                              {
                                  run,
                                  new ServiceCommand(config.Coordinator, config.WinServiceSettings)
                              }
                .Where(x => x.Name == args.Command)
                .DefaultIfEmpty(run)
                .SingleOrDefault();

            _log.DebugFormat("Running command: '{0}'", command.Name);

            //what to do with the config?

            //flow the args down
            command.Execute(args.CommandArgs);
        }
        public void ItRunsWithTheSpecifiedVerbosity()
        {
            var testAppName  = "MSBuildTestApp";
            var testInstance = TestAssets.Get(testAppName)
                               .CreateInstance()
                               .WithSourceFiles();

            var result = new RunCommand()
                         .WithWorkingDirectory(testInstance.Root.FullName)
                         .ExecuteWithCapturedOutput("-v:n");

            result.Should().Pass()
            .And.HaveStdOutContaining("Hello World!");

            if (!DotnetUnderTest.IsLocalized())
            {
                result.Should().HaveStdOutContaining("Restore")
                .And.HaveStdOutContaining("CoreCompile");
            }
        }
예제 #28
0
        public void ItRunsKestrelStandaloneApp()
        {
            TestInstance instance = TestAssetsManager.CreateTestInstance(KestrelSampleBase)
                                    .WithLockFiles();

            var url        = NetworkHelper.GetLocalhostUrlWithFreePort();
            var args       = $"{url} {Guid.NewGuid().ToString()}";
            var runCommand = new RunCommand(Path.Combine(instance.TestRoot, KestrelStandalone));

            try
            {
                runCommand.ExecuteAsync(args);
                NetworkHelper.IsServerUp(url).Should().BeTrue($"Unable to connect to kestrel server - {KestrelStandalone} @ {url}");
                NetworkHelper.TestGetRequest(url, args);
            }
            finally
            {
                runCommand.KillTree();
            }
        }
예제 #29
0
        public void ItCanNewRestoreBuildRunCleanMSBuildProject()
        {
            var    directory        = TestAssets.CreateTestDirectory();
            string projectDirectory = directory.FullName;

            string newArgs = "console --debug:ephemeral-hive --no-restore";

            new NewCommandShim()
            .WithWorkingDirectory(projectDirectory)
            .Execute(newArgs)
            .Should().Pass();

            new RestoreCommand()
            .WithWorkingDirectory(projectDirectory)
            .Execute()
            .Should().Pass();

            new BuildCommand()
            .WithWorkingDirectory(projectDirectory)
            .Execute()
            .Should().Pass();

            var runCommand = new RunCommand()
                             .WithWorkingDirectory(projectDirectory);

            runCommand.ExecuteWithCapturedOutput()
            // Templates are still at 3.0 and will not run on 5.0, revert to commented out assertion when 5.0 templates land
            //.Should().Pass().And.HaveStdOutContaining("Hello World!");
            .Should().Fail().And.HaveStdErrContaining("https://aka.ms/dotnet-download");

            var binDirectory = new DirectoryInfo(projectDirectory).Sub("bin");

            binDirectory.Should().HaveFilesMatching("*.dll", SearchOption.AllDirectories);

            new CleanCommand()
            .WithWorkingDirectory(projectDirectory)
            .Execute()
            .Should().Pass();

            binDirectory.Should().NotHaveFilesMatching("*.dll", SearchOption.AllDirectories);
        }
예제 #30
0
        /// <summary>
        /// This method checks if the command line has a valid length and a valid editor command in the first place.
        /// </summary>
        /// <param name="commandLine">The command line the user has written.</param>
        /// <returns>
        /// A full instanced command if the command line is valid or null if the command line is not valid.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// If commandLine is null or whitespace.
        /// </exception>
        public IEditorCommand Parse(string commandLine)
        {
            if (string.IsNullOrWhiteSpace(commandLine))
            {
                throw new ArgumentNullException();
            }

            string[] possibleCommands = commandLine.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            string   editorCommand    = possibleCommands[0].ToLower();

            if (possibleCommands.Length > 4)
            {
                return(null);
            }
            else
            {
                switch (editorCommand)
                {
                case "add":
                    return(AddCommand.Parse(commandLine));

                case "clear":
                    return(ClearCommand.Parse(commandLine));

                case "insert":
                    return(InsertCommand.Parse(commandLine));

                case "remove":
                    return(RemoveCommand.Parse(commandLine));

                case "new":
                    return(NewCommand.Parse(commandLine));

                case "run":
                    return(RunCommand.Parse(commandLine));

                default:
                    return(null);
                }
            }
        }
예제 #31
0
        public void Suggest_WithSelectedSectionAtOneAndValidParseResultSection_ReturnsCompletionEntries()
        {
            string pathToScript        = Path.Combine(Directory.GetCurrentDirectory(), "InputFileForRunCommand.txt");
            string parseResultSections = "run " + pathToScript;

            ArrangeInputs(parseResultSections: parseResultSections,
                          out MockedShellState _,
                          out HttpState httpState,
                          out ICoreParseResult parseResult,
                          caretPosition: 7);

            IShellState      shellState       = GetShellState(string.Empty, httpState);
            MockedFileSystem mockedFileSystem = new MockedFileSystem();

            mockedFileSystem.AddFile(pathToScript, string.Empty);

            RunCommand           runCommand = new RunCommand(mockedFileSystem);
            IEnumerable <string> result     = runCommand.Suggest(shellState, httpState, parseResult);

            Assert.NotEmpty(result);
        }
예제 #32
0
        /// <summary>
        /// run ManageApps.exe to get the developer id
        /// </summary>
        /// <param name="environment">name of service environment</param>
        /// <returns>the developer id</returns>
        public static string GetDeveloperId(string environment)
        {
            string appHandle = ManageAppsUtils.GetAppHandle(environment);

            // lookup the developer id associated with the app handle
            string command1       = "cd " + ConfigurationManager.AppSettings["ManageAppsRelativePath"] + " & " + manageAppsExecutable + " -Name=" + environment + " -GetAppDeveloperId -AppHandle=" + appHandle;
            string command1Output = RunCommand.Execute(command1);

            // expected output:  "DeveloperId = <developer-id> for appHandle = <app-handle>"
            string expectedOutputPattern = @"^DeveloperId = ([\w-]+) for appHandle = ([\w-]+)";
            var    match = Regex.Match(command1Output, expectedOutputPattern, RegexOptions.Multiline);

            if (match.Success == true)
            {
                return(match.Groups[1].Value);
            }
            else
            {
                return(null);
            }
        }
예제 #33
0
        private void SetResultsPath(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                var files = new SaveFileDialog()
                {
                    Filter           = "xml files (*.xml) | *.xml",
                    RestoreDirectory = true,
                    DefaultExt       = ".xml"
                };

                if (Directory.Exists(Path.GetDirectoryName(TestAssembly)))
                {
                    files.InitialDirectory = TestAssembly;
                }
                else
                {
                    files.InitialDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                }

                var filesResult = files.ShowDialog();

                if (filesResult != null && filesResult == true)
                {
                    Results = files.FileName;
                    resultsFileSetByUser = true;
                    RunCommand.RaiseCanExecuteChanged();
                }
            }
            else
            {
                var fi = new FileInfo(path);
                if (fi.Extension != ".xml")
                {
                    return;
                }

                Results = path;
            }
        }
예제 #34
0
        public async Task can_start_application()
        {
#if NETCOREAPP2_2
            var builder = new WebHostBuilder()
                          .UseKestrel()
                          .UseUrls("http://localhost:5111")
                          .UseStartup <Startup>();
#else
            var builder = new HostBuilder()

                          .ConfigureWebHostDefaults(x =>
            {
                x.UseKestrel()
                .UseUrls("http://localhost:5111")
                .UseStartup <Startup>();
            });
#endif

            var input = new RunInput
            {
                HostBuilder = builder
            };

            var command = new RunCommand();

            var task = Task.Factory.StartNew(() => command.Execute(input));

            command.Started.Wait(5.Seconds());

            using (var client = new HttpClient())
            {
                var text = await client.GetStringAsync("http://localhost:5111");

                text.ShouldBe("Hello");
            }

            command.Reset.Set();

            await task;
        }
예제 #35
0
        public void ItPassesSIGTERMToChild()
        {
            var asset = TestAssets.Get("TestAppThatWaits")
                        .CreateInstance()
                        .WithSourceFiles();

            var command = new RunCommand()
                          .WithWorkingDirectory(asset.Root.FullName);

            bool    killed = false;
            Process child  = null;

            command.OutputDataReceived += (s, e) =>
            {
                if (killed)
                {
                    return;
                }

                child = Process.GetProcessById(Convert.ToInt32(e.Data));
                NativeMethods.Posix.kill(command.CurrentProcess.Id, NativeMethods.Posix.SIGTERM).Should().Be(0);

                killed = true;
            };

            command
            .ExecuteWithCapturedOutput()
            .Should()
            .ExitWith(43)
            .And
            .HaveStdOutContaining("Terminating!");

            killed.Should().BeTrue();

            if (!child.WaitForExit(WaitTimeout))
            {
                child.Kill();
                throw new XunitException("child process failed to terminate.");
            }
        }
예제 #36
0
        public JsonResult AddRunCommands(AddRunCommandsPostModel model)
        {
            var result = new AddRunCommandsPostResult();
            using (var db = DbContextFactory.CreateDbContext())
            {
                Account acc;
                if (!TokenXCodeValidation.Validate(model, db, out acc))
                    throw new HttpException(Resources.ErrorReLogin);
                var run = new RunCommand()
                {
                    IsEnable = false,
                    Title = model.Title,
                    Commands = model.Commands,
                    CommandType = model.CommandType
                };
                db.RunCommands.Add(run);
                db.SaveChanges();
                result.Id = run.Id;

            }
            return new JsonResult() { Data = result };
        }
예제 #37
0
        protected override void OnStartup(StartupEventArgs e)
        {
            var application = Application.Current;
            Window window = Bootstrapper.BootstrapShell(true);
            window.Title = "StoryTeller";

            application.DispatcherUnhandledException += application_DispatcherUnhandledException;

            window.Show();

            if (e.Args.Length > 0)
            {
                var controller = ObjectFactory.GetInstance<IProjectController>();

                var args = ArgPreprocessor.Process(e.Args);
                var queue = new Queue<string>(args);
                var input = new RunCommand().Usages.BuildInput(queue).As<RunInput>();
                var project = input.LoadProject();

                controller.StartNewProject(project);
            }

            //application.Run(window);
        }
예제 #38
0
 public JsonResult SetEnableRunCommands(SetEnableRunCommandsPostModel model)
 {
     var result = new SetEnableRunCommandsPostResult();
     using (var db = DbContextFactory.CreateDbContext())
     {
         Account acc;
         if (!TokenXCodeValidation.Validate(model, db, out acc))
             throw new HttpException(Resources.ErrorReLogin);
         var run = new RunCommand() {Id = model.Id};
         db.RunCommands.Attach(run);
         run.IsEnable = model.IsEnable;
         db.SaveChanges();
     }
     return new JsonResult() { Data = result };
 }
예제 #39
0
        /// <summary>
        /// A run has completed so re-enable the run button.
        /// </summary>
        /// <returns>True when APSIM is not running</returns>
        public bool RunAPSIMEnabled()
        {
            bool isRunning = this.command != null && this.command.IsRunning;
            if (!isRunning)
            {
                this.command = null;
            }

            return !isRunning;
        }
예제 #40
0
        public void RunAPSIM(object sender, EventArgs e)
        {
            if (this.explorerPresenter.Save())
            {
                List<string> duplicates = this.explorerPresenter.ApsimXFile.FindDuplicateSimulationNames();
                if (duplicates.Count > 0)
                {
                    string errorMessage = "Duplicate simulation names found " + StringUtilities.BuildString(duplicates.ToArray(), ", ");
                    explorerPresenter.MainPresenter.ShowMessage(errorMessage, Models.DataStore.ErrorLevel.Error);
                }
                else
                {
                    Model model = Apsim.Get(this.explorerPresenter.ApsimXFile, this.explorerPresenter.CurrentNodePath) as Model;

                    List<JobManager.IRunnable> jobs = new List<JobManager.IRunnable>();
                    jobs.Add(Runner.ForSimulations(this.explorerPresenter.ApsimXFile, model, false));

                    this.command = new Commands.RunCommand(jobs, model.Name, this.explorerPresenter);
                    this.command.Do(null);
                }
            }
        }
예제 #41
0
 public void RunAPSIM(object sender, EventArgs e)
 {
     if (this.explorerPresenter.Save())
     {
         Model model = Apsim.Get(this.explorerPresenter.ApsimXFile, this.explorerPresenter.CurrentNodePath) as Model;
         this.command = new Commands.RunCommand(this.explorerPresenter.ApsimXFile, model, this.explorerPresenter);
         this.command.Do(null);
     }
 }