Beispiel #1
0
        private void OpenToCurrent()
        {
            var    fileSystem = new FileSystem();
            string path;
            var    year  = Journal.YearDirectoryPattern.Format(Today.Date());
            var    month = Journal.MonthDirectoryPattern.Format(Today.Date());

            switch (To)
            {
            case "CurrentMonth":
                path = fileSystem.Path.Combine(Location, year, month);
                break;

            case "CurrentYear":
                path = fileSystem.Path.Combine(Location, year);
                break;

            default:
                path = fileSystem.Path.Combine(Location);
                break;
            }

            if (!fileSystem.Directory.Exists(path))
            {
                throw new PSInvalidOperationException("No directory currently exists for the selected period.");
            }

            SystemProcess.Start(path);
        }
Beispiel #2
0
        public async Task Stop(ApplicationConfig application)
        {
            if (_process != null)
            {
                // Stop running process
                var duration = TimeSpan.FromSeconds(5);
                var tasks    = new List <Task <int?> >(2)
                {
                    _process.Stop(duration)
                };

                // Execute "stop" command
                var stopStartInfo = Package.CreateProcessStop(application, _process.Id);
                var stopProcess   = SystemProcess.Start(stopStartInfo);

                if (stopProcess != null)
                {
                    tasks.Add(stopProcess.Stop(duration));
                }

                // Wait for both processes to end
                await Task.WhenAll(tasks);
            }

            _process = null;
        }
Beispiel #3
0
        protected override void ProcessRecord()
        {
            var fileSystem = new FileSystem();
            var store      = new FileStore <UserSettings>(fileSystem);

            SystemProcess.Start(store.FilePath);
        }
Beispiel #4
0
        protected override void EndProcessing()
        {
            base.EndProcessing();

            var journal = OpenJournal();

            var hour = Now.Time().Hour;

            if (hour >= 0 && hour <= 4)
            {
                var dayPrior = Date.Minus(Period.FromDays(1));
                var question = $"Did you mean to create an entry for '{dayPrior}' or '{Date}'?";
                var result   = Choice("It's after midnight!", question, 0, dayPrior.DayOfWeek.ToChoiceString(), Date.DayOfWeek.ToChoiceString());
                if (result == 0)
                {
                    Date = dayPrior;
                }
            }

            try
            {
                journal.CreateNewEntry(Date, Tags, Readme);
                new JournalTagCache().Invalidate();
            }
            catch (JournalEntryAlreadyExistsException e)
            {
                var question = $"An entry for {Date} already exists. Do you want to open it instead?";
                if (YesOrNo(question))
                {
                    SystemProcess.Start(e.EntryFilePath);
                }
            }
        }
        protected override void RunJournalCommand()
        {
            var journal   = OpenJournal();
            var entryDate = Date == null?Today.PlusDays(DateOffset) : LocalDate.FromDateTime(Date.Value).PlusDays(DateOffset);

            var hour = Now.Time().Hour;

            if (hour >= 0 && hour <= 4)
            {
                var dayPrior = entryDate.Minus(Period.FromDays(1));
                var question = $"Did you mean to create an entry for '{dayPrior}' or '{entryDate}'?";
                var result   = Choice("It's after midnight!", question, 0, dayPrior.DayOfWeek.ToChoiceString(), entryDate.DayOfWeek.ToChoiceString());
                if (result == 0)
                {
                    entryDate = dayPrior;
                }
            }

            Commit(GitCommitType.PreNewJournalEntry);

            try
            {
                journal.CreateNewEntry(entryDate, Tags, Readme);
                Commit(GitCommitType.PostNewJournalEntry);
            }
            catch (JournalEntryAlreadyExistsException e)
            {
                var question = $"An entry for {entryDate} already exists. Do you want to open it instead?";
                if (YesOrNo(question))
                {
                    SystemProcess.Start(e.EntryFilePath);
                }
            }
        }
 public void TestMethod1andabit()
 {
     using (var notepad = new SystemProcess(Environment.SystemDirectory + "\\notepad.exe", x => x.Kill()))
     {
         Thread.Sleep(500);
         notepad.Start();
     }
 }
 public void TestMethod1andabit()
 {
     using (var notepad = new SystemProcess(Environment.SystemDirectory + "\\notepad.exe", x => x.Kill()))
     {
         Thread.Sleep(500);
         notepad.Start();
     }
 }
        protected override void RunJournalCommand()
        {
            if (Last)
            {
                var journal   = OpenJournal();
                var lastEntry = journal.CreateIndex <JournalEntryFile>().SelectMany(x => x.Entries).OrderByDescending(x => x.EntryDate).First();
                SystemProcess.Start(lastEntry.FilePath);
                return;
            }

            var       fileSystem    = new FileSystem();
            var       journalWriter = new JournalWriter(fileSystem, Location);
            string    path;
            LocalDate entryDate;

            switch (ParameterSetName)
            {
            case "Name":
            {
                entryDate = EntryName.EndsWith(".md") ? Journal.FileNameWithExtensionPattern.Parse(EntryName).Value : Journal.FileNamePattern.Parse(EntryName).Value;
                path      = journalWriter.GetJournalEntryFilePath(entryDate);
                break;
            }

            case "Date":
            {
                entryDate = LocalDate.FromDateTime(Date);
                path      = journalWriter.GetJournalEntryFilePath(entryDate);
                break;
            }

            case "DateOffset":
            {
                entryDate = Today.PlusDays(DateOffset);
                path      = journalWriter.GetJournalEntryFilePath(entryDate);
                break;
            }

            case "Entry":
            {
                entryDate = Journal.FileNamePattern.Parse(Entry.EntryName).Value;
                path      = journalWriter.GetJournalEntryFilePath(entryDate);
                break;
            }

            default:
                throw new NotSupportedException();
            }

            if (!fileSystem.File.Exists(path))
            {
                throw new PSInvalidOperationException($"An entry does not exist for '{entryDate}'.");
            }

            SystemProcess.Start(path);
        }
Beispiel #9
0
        protected override void ProcessRecord()
        {
            if (!Directory.Exists(LogsDirectory))
            {
                WriteHostInverted("No logs have been created yet.");
                return;
            }

            SystemProcess.Start(LogsDirectory);
        }
Beispiel #10
0
        private void OpenToDate()
        {
            var year       = Journal.YearDirectoryPattern.Format(LocalDate.FromDateTime(Date));
            var month      = Journal.MonthDirectoryPattern.Format(LocalDate.FromDateTime(Date));
            var fileSystem = new FileSystem();
            var path       = fileSystem.Path.Combine(Location, year, month);

            if (!fileSystem.Directory.Exists(path))
            {
                throw new PSInvalidOperationException("No directory currently exists for the selected period.");
            }

            SystemProcess.Start(path);
        }
        protected override void ProcessRecord()
        {
            var fileSystem     = new FileSystem();
            var encryptedStore = EncryptedStoreFactory.Create <UserSettings>();
            var path           = UserSettings.Load(encryptedStore).BackupLocation;

            if (!string.IsNullOrEmpty(path) && fileSystem.Directory.Exists(path))
            {
                SystemProcess.Start(path);
            }
            else
            {
                throw new PSInvalidOperationException("Backup location not found");
            }
        }
Beispiel #12
0
        public static void VsStarter()
        {
            string path = Application.dataPath.Replace("\\", "/");

            path = path.Replace("/Assets", string.Empty);
            int    index       = path.LastIndexOf('/');
            string projectName = path.Substring(index, path.Length - index);

            if (path.Contains(":"))
            {
                SystemProcess.Start(@"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe", path + projectName + ".sln");
            }
            else
            {
                SystemProcess.Start(@"/Applications/Visual Studio.app", path + "/Assembly-CSharp.sln");
                SystemProcess.Start(@"/Applications/Visual Studio.app", path + "/Assembly-CSharp-Editor.sln");
            }
        }
Beispiel #13
0
        protected override void ProcessRecord()
        {
            if (MyInvocation.InvocationName == "Open-BackupLocation")
            {
                WriteWarning("'Open-BackupLocation' is obsolete and will be removed in a future release. Use 'Open-JournalBackupLocation' instead.");
            }

            var fileSystem     = new FileSystem();
            var encryptedStore = EncryptedStoreFactory.Create <UserSettings>();
            var path           = UserSettings.Load(encryptedStore).BackupLocation;

            if (!string.IsNullOrEmpty(path) && fileSystem.Directory.Exists(path))
            {
                SystemProcess.Start(path);
            }
            else
            {
                throw new PSInvalidOperationException("Backup location not found");
            }
        }
Beispiel #14
0
        public async Task <bool> Start(ApplicationConfig application, Action refresh)
        {
            if (_process != null)
            {
                await Stop(application);
            }

            var process = SystemProcess.Start(Package.CreateProcessStart(application));

            if (process == null)
            {
                return(false);
            }

            process.Exited += refresh;

            _process = process;

            return(true);
        }
        protected override void EndProcessing()
        {
            base.EndProcessing();

            if (NoWait && _entries.Count > 9)
            {
                var question = $"You're about to open {_entries.Count} journal entries at the same time. Are you sure you want to do that?";
                if (!YesOrNo(question, ConsoleColor.Red, Console.BackgroundColor))
                {
                    WriteHostInverted("Good choice. I'll open your selected entries one at a time instead.");
                    NoWait = false;
                }
            }

            if (NoWait)
            {
                while (_entries.Any())
                {
                    var entry = _entries.Dequeue();
                    SystemProcess.Start(entry.FilePath);
                }

                return;
            }

            var paginate = _entries.Count > 1;
            var count    = 1;
            var total    = _entries.Count;

            while (true)
            {
                var entry = _entries.Dequeue();
                SystemProcess.Start(entry.FilePath);

                if (!_entries.Any() || paginate && !YesOrNo($"[{count++}/{total}] Open next entry?", ConsoleColor.Green, Console.BackgroundColor, allowEnterForYes: true))
                {
                    break;
                }
            }
        }
Beispiel #16
0
        public async Task <string?> Configure(ApplicationConfig application)
        {
            var environment = application.Environment;
            var mariadb     = application.Package.MariaDb;

            // Write configuration file
            var packageDirectory = GetInstallDirectory(environment.InstallDirectoryOrDefault);
            var context          = Context.CreateCustom(new Dictionary <Value, Value>
            {
                ["dataDirectory"] = mariadb.DataDirectoryOrDefault,
                ["serverPort"]    = mariadb.ServerPortOrDefault
            });

            foreach (var name in new[] { ConfigurationMysqld })
            {
                var destinationPath = Path.Combine(packageDirectory.AbsolutePath, "config", name);
                var success         = await ResourceHelper.WriteToFile <PhpPackage>($"MariaDb.{name}", context, destinationPath);

                if (!success)
                {
                    return($"configuration failure with '{name}'");
                }
            }

            // Initialize data directory
            if (!File.Exists(Path.Join(packageDirectory.AbsolutePath, mariadb.DataDirectoryOrDefault, "my.ini")))
            {
                var process = SystemProcess.Start(CreateProcessStartInfo(environment.InstallDirectoryOrDefault,
                                                                         "mysql_install_db.exe", SystemProcess.EscapeArgument("--datadir=" + mariadb.DataDirectoryOrDefault)));

                if (process == null || await process.Stop(TimeSpan.FromSeconds(15)) != 0)
                {
                    return("could not initialize data directory");
                }
            }

            return(null);
        }
        /// <summary>
        /// Immediately stops the associated process.
        /// </summary>
        /// <exception cref="System.InvalidOperationException">Cannot Terminate Non-Running Process.</exception>
        /// <exception cref="PsExecCommandException">PSTools command did not successfully complete</exception>
        public void Kill()
        {
            if (!this.IsProcessRunning)
            {
                throw new InvalidOperationException("Cannot Terminate Non-Running Process.");
            }

            /* Command: Use PsKill http://ss64.com/nt/pskill.html
             * - accepteula: Suppress the display of the license dialog.
             */
            const string Args = @" -accepteula \\{0} ""{1}""";

            using (
                var psKillProcess = new Process()
                {
                    StartInfo =
                        new ProcessStartInfo()
                        {
                            UseShellExecute = false,
                            RedirectStandardOutput = true,
                            RedirectStandardError = false,
                            RedirectStandardInput = true,
                            FileName = this.config.KillPath,
                            Arguments = string.Format(Args, this.hostname, this.processId) // -t treekill seems to regularly cause PsKill to crash
                        }
                })
            using (var psKill = new SystemProcess(psKillProcess, x => x.Kill()))
            {
                psKill.Start();

                var standardOutput = ReadWithTimeout(psKillProcess.StandardOutput);

                if (
                    !(standardOutput.Contains(string.Format("Process {0} killed", this.processId))
                      || standardOutput.Contains(string.Format("Process {0} on {1} killed", this.processId, this.hostname))))
                {
                    throw new PsExecCommandException(string.Format("Failure running PsExec: {0}", standardOutput));
                }
            }

            this.IsProcessRunning = false;
        }
        /// <summary>
        /// Starts the process.
        /// </summary>
        /// <exception cref="System.InvalidOperationException">Cannot Start Running Process.</exception>
        /// <exception cref="ProcessHelpers.PsExecCommandException">PSTools command did not successfully complete</exception>
        public void Start()
        {
            if (this.IsProcessRunning)
            {
                throw new InvalidOperationException("Cannot Start Running Process.");
            }

            /* Command: Use PsExec http://ss64.com/nt/psexec.html
             * - i : Interactive - Run the program so that it interacts with the desktop on the remote system.
             * - d : Don’t wait for the application to terminate.
             * - accepteula: Suppress the display of the license dialog.
             */
            const string Args = @" -accepteula -i -d \\{0}{1} ""{2}""";

            using (
                var psExecProcess = new Process()
                {
                    StartInfo =
                        new ProcessStartInfo()
                        {
                            UseShellExecute = false,
                            RedirectStandardOutput = false,
                            RedirectStandardError = true,
                            RedirectStandardInput = true,
                            FileName = this.config.ExecPath,
                            Arguments = string.Format(Args, this.hostname, this.GetCredentialPowershellArgs(), this.exePath)
                        }
                })
            using (var psExec = new SystemProcess(psExecProcess, x => x.Kill()))
            {
                psExec.Start();
                var standardError = ReadWithTimeout(psExecProcess.StandardError);

                if (!standardError.Contains(string.Format("started on {0} with process ID", this.hostname)))
                {
                    throw new PsExecCommandException(string.Format("Failure running PsExec: {0}", standardError));
                }

                this.processId = this.GetPid(standardError);
            }

            this.IsProcessRunning = true;
        }
        protected override void RunJournalCommand()
        {
            if (Last)
            {
                var journal   = OpenJournal();
                var lastEntry = journal.CreateIndex <JournalEntryFile>().SelectMany(x => x.Entries).OrderByDescending(x => x.EntryDate).FirstOrDefault();
                if (lastEntry == null)
                {
                    throw new PSInvalidOperationException("No entries found!");
                }
                SystemProcess.Start(lastEntry.FilePath);
                return;
            }

            var       fileSystem    = new FileSystem();
            var       journalWriter = new JournalWriter(fileSystem, Location);
            string    path;
            LocalDate entryDate;

            switch (ParameterSetName)
            {
            case "Name":
            {
                entryDate = EntryName.EndsWith(".md") ? Journal.FileNameWithExtensionPattern.Parse(EntryName).Value : Journal.FileNamePattern.Parse(EntryName).Value;
                path      = journalWriter.GetJournalEntryFilePath(entryDate);
                break;
            }

            case "Date":
            {
                entryDate = LocalDate.FromDateTime(Date);
                path      = journalWriter.GetJournalEntryFilePath(entryDate);
                break;
            }

            case "DateOffset":
            {
                entryDate = Today.PlusDays(DateOffset);
                path      = journalWriter.GetJournalEntryFilePath(entryDate);
                break;
            }

            case "Entry":
            {
                entryDate = Journal.FileNamePattern.Parse(Entry.EntryName).Value;
                path      = journalWriter.GetJournalEntryFilePath(entryDate);
                break;
            }

            default:
                throw new NotSupportedException();
            }

            if (!fileSystem.File.Exists(path))
            {
                throw new PSInvalidOperationException($"An entry does not exist for '{entryDate}'.");
            }

            Commit(GitCommitType.PreOpenJournalEntry);
            SystemProcess.Start(path);

            if (Wait)
            {
                var result = Choice($"Reading entry for {entryDate}", "Continue on to next entry?", 0, "&Continue", "&Quit");
                Commit(GitCommitType.PostOpenJournalEntry);
                if (result == 1)
                {
                    ThrowTerminatingError("Pipeline terminated at user's request.", ErrorCategory.NotSpecified);
                }
            }
        }