Example #1
0
        private async void Publish()
        {
            if (selectedPackageList.Count == 0)
            {
                Debug.Log("No selected packages to publish");
                return;
            }

            foreach (var package in selectedPackageList)
            {
                //publishing
                Debug.Log($"Publishing {package.displayName} {package.version}");
                var   cmd  = $"npm publish Packages/{package.name} --registry http://{address}";
                var   task = ShellUtility.ExecuteCommandAsync(cmd);
                await task;
                if (!task.Result)
                {
                    Debug.LogError($"Failed to publish {package.displayName}");
                }
                else
                {
                    Debug.Log($"Published {package.displayName}");
                }
            }

            Refresh();
        }
Example #2
0
        private async void CheckInstall()
        {
            installStatus = InstallStatus.Unknown;
            var checkTask = await ShellUtility.ExecuteCommandAsync("npm version");

            installStatus = !checkTask ? InstallStatus.NotFound : InstallStatus.Installed;
        }
Example #3
0
        private void ShellWindow_Loaded(object sender, RoutedEventArgs e)
        {
            ShellUtility.SetShell(this);

            CreateFiles(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory));
            CreateFiles(Environment.GetFolderPath(Environment.SpecialFolder.CommonDesktopDirectory));
        }
Example #4
0
        public void GetFileTypeInfoTest()
        {
            // The shell functions and System.Drawing APIs may not work in services.
            if (Environment.UserInteractive)
            {
                string?typeName = ShellUtility.GetFileTypeInfo(".cs", false, IconOptions.None, null);
                typeName.ShouldNotBeNull();
                typeName.ShouldContain("C# Source File", Case.Insensitive);

                string notepadPath = Environment.ExpandEnvironmentVariables(@"%SystemRoot%\System32\Notepad.exe");
                Icon?  icon        = null;
                typeName = ShellUtility.GetFileTypeInfo(notepadPath, true, IconOptions.Large, hIcon => icon = CloneIcon(hIcon));
                typeName.ShouldBe("Application");
                icon.ShouldNotBeNull();
                icon.Size.ShouldBe(SystemInformation.IconSize);
                icon.Dispose();

                typeName = ShellUtility.GetFileTypeInfo(
                    ".dll",
                    false,
                    IconOptions.Small | IconOptions.Shortcut | IconOptions.Selected,
                    hIcon => icon = CloneIcon(hIcon));
                typeName.ShouldBe("Application extension");
                icon.Size.ShouldBe(SystemInformation.SmallIconSize);
                icon.Dispose();
            }
        }
        public void ExecuteCommand_UseShell([Values(true, false)] bool useShell)
        {
            var command = "echo \"hello\"";
            var result  = ShellUtility.ExecuteCommand(command, useShell);

            Assert.IsTrue(result, $"Failed to execute command: {command}");
        }
Example #6
0
        private static void WritePrompt()
        {
            var scheme = Program.Config.ColorScheme;

            switch (Program.Config.PromptStyle)
            {
            case PromptStyle.Default:
                Console.Write("$ ");
                Console.Write(Environment.UserName, scheme.PromptUserNameColor);
                Console.Write("@");
                Console.Write(ShellUtility.GetCurrentDirectory(), scheme.PromptDirectoryColor);
                Console.Write("> ");
                break;

            case PromptStyle.Unix:
                Console.Write(Environment.UserName, scheme.PromptUserNameColor);
                Console.Write("@");
                Console.WriteLine(Environment.MachineName, scheme.PromptUserNameColor);
                Console.Write(":");
                Console.Write(ShellUtility.GetCurrentDirectory(), scheme.PromptDirectoryColor);
                Console.Write("$ ");
                break;

            case PromptStyle.Windows:
                Console.Write(ShellUtility.GetCurrentDirectory(), scheme.PromptDirectoryColor);
                Console.Write("> ");
                break;

            default:
                throw new NotImplementedException();
            }
        }
Example #7
0
        private async void CheckLogin()
        {
            loginStatusLabel.text = "Waiting...";
            var   checkTask = ShellUtility.ExecuteCommandAsync("npm whoami");
            await checkTask;

            loginStatusLabel.text = !checkTask.Result ? "Disconnected" : "Connected";
        }
Example #8
0
        public static void RunShell1()
        {
            string command = @"C:\Users\Administrator\Desktop\TxtGenerator\TxtGenerator\bin\Debug\TxtGenerator.exe";

            ShellUtility.RunShellInSilence(command);
            Thread.Sleep(100);
            string text = TxtUtility.FileToString("C:/222.txt");

            Debug.Log(text);
        }
Example #9
0
        public void GetCopyrightInfoTest()
        {
            Assembly asm    = Assembly.GetExecutingAssembly();
            string?  actual = ShellUtility.GetCopyrightInfo(asm);

            actual.ShouldBe("Copyright For Unit Test");

            actual = ShellUtility.GetCopyrightInfo(null);
            actual.ShouldBe(ShellUtility.GetCopyrightInfo(typeof(ShellUtility).Assembly));
        }
Example #10
0
 public void ShellExecuteTest()
 {
     using (Process? process = ShellUtility.ShellExecute(null, "Notepad.exe"))
     {
         if (process != null)
         {
             process.CloseMainWindow();
             process.Kill();
         }
     }
 }
Example #11
0
        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            ShellUtility.SetDesktop(this);

            shell = new ShellWindow
            {
                Owner = this
            };

            shell.Show();
        }
Example #12
0
        /// <summary>
        /// Executes an action on the specified file using the Windows shell.
        /// </summary>
        /// <param name="owner">The parent window for any error dialogs.</param>
        /// <param name="fileName">The text or filename to execute.</param>
        /// <param name="verb">The shell action that should be taken.  Pass an empty string for the default action.</param>
        /// <returns>The process started by executing the file.</returns>
        public static Process?ShellExecute(IWin32Window?owner, string fileName, string verb)
        {
            IntPtr?ownerHandle = null;

            if (owner != null)
            {
                ownerHandle = owner.Handle;
            }

            Process?result = ShellUtility.ShellExecute(ownerHandle, fileName, verb);

            return(result);
        }
Example #13
0
        public AboutBox(Assembly callingAssembly, string?repository)
        {
            this.InitializeComponent();

            this.callingAssembly = callingAssembly;
            this.repository      = repository ?? ApplicationInfo.ApplicationName.Replace(" ", string.Empty);

            string applicationName = ApplicationInfo.ApplicationName;

            this.Text             = "About " + applicationName;
            this.productName.Text = applicationName;
            this.version.Text     = ShellUtility.GetVersionInfo(callingAssembly);
            this.copyright.Text   = ShellUtility.GetCopyrightInfo(callingAssembly);
        }
        public IEnumerator ExecuteCommandAsync_UseShell([Values(true, false)] bool useShell)
        {
            var command = "echo \"hello\"";
            var task    = ShellUtility.ExecuteCommandAsync(command, useShell);

            while (!task.IsCompleted)
            {
                yield return(null);
            }

            var result = task.Result;

            Assert.IsTrue(result, $"Failed to execute command: {command}");
        }
Example #15
0
        private void GlobalHook_MouseDragFinishedExt(object sender, MouseEventExtArgs e)
        {
            var delayTimer = new DispatcherTimer
            {
                Interval = TimeSpan.FromMilliseconds(10)
            };

            delayTimer.Tick += (tS, tE) =>
            {
                ShellUtility.SetTranspernt(this, false);
                delayTimer.Stop();
            };

            delayTimer.Start();
        }
        public void GetCommandResult_TrimOutput([Values(true, false)] bool trimOutput)
        {
            var echoText = "hello";
            var command  = $"echo \"{echoText}\"";
            var result   = ShellUtility.GetCommandResult(command, trimOutput);

            if (trimOutput)
            {
                Assert.IsTrue(result == echoText, $"Failed to execute command and get result: {echoText} != {result}");
            }
            else
            {
                Assert.IsTrue(result != echoText, $"Failed to execute command and get result: {echoText} != {result}");
                Assert.IsTrue(result.StartsWith(echoText), $"Failed to execute command and get result: {echoText} != {result}");
            }
        }
Example #17
0
        public MainForm()
        {
            this.InitializeComponent();

            // Get the OS's closed folder icon if possible.
            Icon icon = null;

            ShellUtility.GetFileTypeInfo("Folder", false, IconOptions.Small | IconOptions.Folder, hIcon => icon = (Icon)Icon.FromHandle(hIcon).Clone());
            if (icon != null)
            {
                using (Image folderImage = icon.ToBitmap())
                {
                    this.Images.Images[FolderImageIndex] = folderImage;
                }
            }
        }
Example #18
0
        public ShellResult Execute(AppConfig config, object input)
        {
            if (String.IsNullOrWhiteSpace(this.Path))
            {
                this.Path = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
            }

            var fullPath = System.IO.Path.GetFullPath(ShellUtility.ProcessTilde(this.Path));

            if (!Directory.Exists(fullPath))
            {
                throw new DirectoryNotFoundException($"cd: directory '{this.Path}' could not be found");
            }

            Directory.SetCurrentDirectory(fullPath);
            return(ShellResult.Ok());
        }
Example #19
0
        private static async void SetToggleRemoteVersionAsync(Toggle toggle, PackageManifest package)
        {
            PackageManifest remotePackage = null;

            var   task = ShellUtility.GetCommandResultAsync($"npm view {package.name} --json");
            await task;
            var   json = task.Result;

            if (json != null)
            {
                remotePackage = JsonUtility.FromJson <PackageManifest>(json);
            }

            toggle.label = remotePackage == null ? $"{toggle.label}  (not found)" : $"{toggle.label}  ({remotePackage.version})";
            toggle.SetEnabled(remotePackage == null || remotePackage.version != package.version);
            toggle.value = false;
        }
Example #20
0
        public static bool ShellExecute(string fileName)
        {
            bool result = false;

            try
            {
                using (Process process = ShellUtility.ShellExecute(null, fileName))
                {
                    result = true;
                }
            }
            catch (Win32Exception)
            {
                result = false;
            }
            catch (FileNotFoundException)
            {
                result = false;
            }

            return(result);
        }
        public IEnumerator GetCommandResultAsync_TrimOutput([Values(true, false)] bool trimOutput)
        {
            var echoText = "hello";
            var command  = $"echo \"{echoText}\"";
            var task     = ShellUtility.GetCommandResultAsync(command, trimOutput);

            while (!task.IsCompleted)
            {
                yield return(null);
            }

            var result = task.Result;

            if (trimOutput)
            {
                Assert.IsTrue(result == echoText, $"Failed to execute command and get result: {echoText} != {result}");
            }
            else
            {
                Assert.IsTrue(result != echoText, $"Failed to execute command and get result: {echoText} != {result}");
                Assert.IsTrue(result.StartsWith(echoText), $"Failed to execute command and get result: {echoText} != {result}");
            }
        }
Example #22
0
        private async void Login()
        {
            loginStatusLabel.text = "Waiting...";

            var   cmd  = $"npm-cli-login -u {username} -p {password} -e {email} -r http://{address}";
            var   task = ShellUtility.ExecuteCommandAsync(cmd);
            await task;

            if (!task.Result)
            {
                Debug.Log("Failed login");
            }

            cmd  = $"npm config set registry http://{address}";
            task = ShellUtility.ExecuteCommandAsync(cmd);
            await task;

            if (!task.Result)
            {
                Debug.Log("Failed to set registry address");
            }

            CheckLogin();
        }
Example #23
0
        public void GetVersionInfoTest()
        {
            Assembly asm    = Assembly.GetExecutingAssembly();
            string   actual = ShellUtility.GetVersionInfo(asm);
            DateTime?built  = ReflectionUtility.GetBuildTime(asm);

            built.ShouldNotBeNull();

            // Runtime bitness check from https://stackoverflow.com/a/3782556/1882616.
            string expected = "Version 1.2.3 – " + built.Value.ToLocalTime().ToShortDateString() + " – " + 8 * IntPtr.Size + "-bit";

#if NETFRAMEWORK
            expected += " – Framework";
#elif NETCOREAPP
            expected += " – Core";
#endif

            if (ApplicationInfo.IsUserRunningAsAdministrator)
            {
                expected += " – Administrator";
            }

            actual.ShouldBe(expected);
        }
Example #24
0
 public ShellResult Execute(AppConfig config, object input)
 => ShellResult.Ok(ShellUtility.GetCurrentDirectory(this.ExpandTilde));
Example #25
0
 private void MainWindow_Closed(object sender, EventArgs e)
 {
     ShellUtility.ShowFolder();
 }
Example #26
0
 private void crackSoftWebsiteToolStripMenuItem_Click(object sender, EventArgs e)
 {
     ShellUtility.OpenWebPage("http://www.cracksoft.net");
 }
Example #27
0
 private void GlobalHook_MouseDragStartedExt(object sender, MouseEventExtArgs e)
 {
     ShellUtility.SetTranspernt(this, true);
 }
Example #28
0
        public ShellResult Execute(AppConfig config, object input = null, bool captureOutput = false)
        {
            var commandSegment = this.Command.Execute(config, captureOutput: true);

            if (commandSegment.ExitCode != 0 || !(commandSegment.Value is string commandName))
            {
                throw new InvalidOperationException("Command name must evaluate to a string");
            }

            var result = default(ShellResult);
            var args   = new List <string>();

            if (this.Arguments != null)
            {
                foreach (var item in this.Arguments)
                {
                    result = item.Execute(config, captureOutput: true);
                    switch (result.Value)
                    {
                    case Exception e when !result:

                        // ReSharper disable once UnthrowableException
                        throw e;

                    case object _ when !result:
                        return(result);

                    case StandardStreams std when std.StandardOutput != null:
                        args.AddRange(std.StandardOutput);
                        break;

                    case IEnumerable <string> lines:
                        args.AddRange(lines);
                        break;

                    default:
                        args.Add(result.Value?.ToString() ?? String.Empty);
                        break;
                    }
                }
            }

            var hasBuiltInCommand = !config.DisableAllCommands &&
                                    !config.DisabledCommands.Contains(commandName) &&
                                    Commands.TryExecuteCommandByName(
                commandName,
                config,
                args.ToArray(),
                input,
                out result
                );

            if (hasBuiltInCommand)
            {
                return(result);
            }

            var inputLines = GetInputLines();
            var startInfo  = new ProcessStartInfo
            {
                FileName               = commandName,
                Arguments              = ShellUtility.Escape(args).Join(" "),
                UseShellExecute        = false,
                RedirectStandardInput  = inputLines.Count > 0,
                RedirectStandardError  = captureOutput,
                RedirectStandardOutput = captureOutput
            };

            try
            {
                var proc = Process.Start(startInfo);

                if (startInfo.RedirectStandardInput)
                {
                    inputLines.ForEach(proc.StandardInput.WriteLine);
                    proc.StandardInput.Flush();
                    proc.StandardInput.Close();
                }


                if (!captureOutput)
                {
                    proc.WaitForExit();
                    return(new ShellResult(proc.ExitCode, null));
                }

                var output = new List <string>();
                var error  = new List <string>();

                proc.OutputDataReceived += Appender(output);
                proc.ErrorDataReceived  += Appender(error);

                proc.BeginOutputReadLine();
                proc.BeginErrorReadLine();

                proc.WaitForExit();

                output.RemoveAll(x => x is null);
                error.RemoveAll(x => x is null);

                return(error.Count == 0 && output.Count == 1
                           ? new ShellResult(proc.ExitCode, output[0])
                           : new ShellResult(proc.ExitCode, new StandardStreams(output, error)));
            }
            catch (Win32Exception ex)
            {
                throw new ProgramNotFoundException(commandName, ex);
            }

            DataReceivedEventHandler Appender(List <string> destination) => (s, e) => destination.Add(e.Data);

            IReadOnlyList <string> GetInputLines()
            {
                switch (input)
                {
                case StandardStreams std when std.StandardOutput != null:
                    return(std.StandardOutput);

                case IEnumerable <string> lines:
                    return(lines.ToArray());

                default:
                    return(input is null?Array.Empty <string>() : new[] { input.ToString() });
                }
            }
        }
Example #29
0
 /// <summary>
 /// Executes an action on the specified file using the Windows shell.
 /// </summary>
 /// <param name="owner">The parent window for any error dialogs.</param>
 /// <param name="fileName">The text or filename to execute.</param>
 /// <param name="verb">The shell action that should be taken.  Pass an empty string for the default action.</param>
 /// <returns>The process started by executing the file.</returns>
 public static Process?ShellExecute(Window?owner, string fileName, string verb)
 => ShellUtility.ShellExecute(TryGetHandle(owner), fileName, verb);
Example #30
0
        public static void RunShell()
        {
            string command = @"C:\Users\Administrator\Desktop\三英逗吕布破击源码\WindowsFormsApplication2\WindowsFormsApplication2\bin\Debug\WindowsFormsApplication2.exe 4545454";

            ShellUtility.RunAsyncShell(command);
        }