/// <summary> /// This creates an RPC server that has endpoints for all the HostAPIs, then creates an elevated process that can call back into this process to report progress. /// /// /// </summary> /// <param name="script"></param> /// <returns></returns> internal int InvokeElevatedViaRPC(string script) { var guid = Guid.NewGuid(); // set up the server IPC channel var serverChannel = new IpcServerChannel(guid.ToString()); ChannelServices.RegisterChannel(serverChannel, true); // RemotingConfiguration.RegisterWellKnownServiceType( typeof(BaseRequest), "Request", WellKnownObjectMode.Singleton); var objRef = RemotingServices.Marshal(_request); // Create the client elevated var process = AsyncProcess.Start(new ProcessStartInfo { FileName = BaseRequest.NuGetExePath, Arguments = string.Format("-rpc {0}", objRef.URI), // WorkingDirectory = workingDirectory, WindowStyle = ProcessWindowStyle.Hidden, Verb = "runas", }); process.WaitForExit(); RemotingServices.Disconnect(_request); return(0); }
public bool StartChocolateyProcessAsAdmin(string statements, string exeToRun, bool minimized, bool noSleep, int[] validExitCodes, string workingDirectory) { Verbose("StartChocolateyProcessAsAdmin", "Exe '{0}', Args '{1}'", exeToRun, statements); if (exeToRun.EqualsIgnoreCase("powershell")) { // run as a powershell script if (IsElevated) { Verbose("Already Elevated", "Running PowerShell script in process"); // in proc, we're already good. return(Invoke(statements)); } Verbose("Not Elevated", "Running PowerShell script in new process"); // otherwise setup a new proc if (!ExecuteElevatedAction(ProviderName, statements, this.REQ)) { Debug("Error during elevation"); return(false); } return(true); } // just a straight exec from here. try { Verbose("Launching Process", "EXE :'{0}'", exeToRun); var process = AsyncProcess.Start(new ProcessStartInfo { FileName = exeToRun, Arguments = statements, WorkingDirectory = workingDirectory, WindowStyle = minimized ? ProcessWindowStyle.Hidden : ProcessWindowStyle.Normal, Verb = IsElevated ? "" : "runas", }); while (!process.WaitForExit(1)) { if (IsCanceled) { process.Kill(); Verbose("Process Killed", "Host requested cancellation"); throw new Exception("Killed Process {0}".format(exeToRun)); } } if (validExitCodes.Contains(process.ExitCode)) { Verbose("Process Exited Successfully.", "{0}", exeToRun); return(true); } Verbose("Process Failed {0}", exeToRun); throw new Exception("Process Exited with non-successful exit code {0} : {1} ".format(exeToRun, process.ExitCode)); } catch (Exception e) { e.Dump(this); Error("Process Execution Failed", "'{0}' -- {1}", exeToRun, e.Message); throw e; } }
public static AsyncProcess Start(ProcessStartInfo startInfo, IDictionary environment) { startInfo.RedirectStandardError = true; startInfo.RedirectStandardOutput = true; startInfo.UseShellExecute = false; startInfo.CreateNoWindow = true; startInfo.WindowStyle = ProcessWindowStyle.Hidden; bool redirecting = true; //if (AdminPrivilege.IsElevated) { //startInfo.Verb = ""; //} else { if ("runas".Equals(startInfo.Verb)) { redirecting = false; startInfo.UseShellExecute = true; startInfo.RedirectStandardError = false; startInfo.RedirectStandardOutput = false; } if (environment != null) { foreach (var i in environment.Keys) { startInfo.EnvironmentVariables[(string)i] = (string)environment[i]; } } var result = new AsyncProcess(new Process { StartInfo = startInfo }); result._process.EnableRaisingEvents = true; // set up std* access if (redirecting) { result._process.ErrorDataReceived += result.ErrorDataReceived; result._process.OutputDataReceived += result.OutputDataReceived; } result._process.Exited += result.ProcessExited; result._process.Start(); if (redirecting) { result._process.BeginErrorReadLine(); result._process.BeginOutputReadLine(); } return(result); }
internal InstallResult NuGetInstall(PackageItem item) { var result = new InstallResult(); using ( var p = AsyncProcess.Start(NuGetExePath, String.Format(@"install ""{0}"" -Version ""{1}"" -Source ""{2}"" -PackageSaveMode ""{4}"" -OutputDirectory ""{3}"" -Verbosity detailed {5}", item.Id, item.Version, item.PackageSource.Location, Destination, PackageSaveMode.Value, ExcludeVersion ? "-ExcludeVersion" : "")) ) { foreach (var l in p.StandardOutput) { if (String.IsNullOrEmpty(l)) { continue; } Verbose("NuGet: {0}", l); // Successfully installed 'ComicRack 0.9.162'. if (l.Contains("Successfully installed")) { result.GetOrAdd(InstallStatus.Successful, () => new List <PackageItem>()).Add(ParseOutputFull(item.PackageSource, item.Id, item.Version, l)); continue; } ; if (l.Contains("already installed")) { result.GetOrAdd(InstallStatus.AlreadyPresent, () => new List <PackageItem>()).Add(ParseOutputFull(item.PackageSource, item.Id, item.Version, l)); continue; } if (l.Contains("not installed")) { result.GetOrAdd(InstallStatus.Failed, () => new List <PackageItem>()).Add(ParseOutputFull(item.PackageSource, item.Id, item.Version, l)); continue; } } foreach (var l in p.StandardError.Where(l => !String.IsNullOrEmpty(l))) { Warning("NuGet: {0}", l); } // if anything failed, this is a failure. // if we have a success message (and no failure), we'll count this as a success. result.Status = result.ContainsKey(InstallStatus.Failed) ? InstallStatus.Failed : result.ContainsKey(InstallStatus.Successful) ? InstallStatus.Successful : InstallStatus.AlreadyPresent; return(result); } }
public bool InstallChocolateyVsixPackage(string packageName, string vsixUrl, string vsVersion) { Verbose("InstallChocolateyVsixPackage", packageName); var vs = Registry.LocalMachine.OpenSubKey(@"Software\Wow6432Node\Microsoft\VisualStudio"); var versions = vs.GetSubKeyNames().Select(each => { float f; if (!float.TryParse(each, out f)) { return(null); } if (f < 10.0) { return(null); } var vsv = vs.OpenSubKey(each); if (vsv.GetValueNames().Contains("InstallDir", StringComparer.OrdinalIgnoreCase)) { return(new { Version = f, InstallDir = vsv.GetValue("InstallDir").ToString() }); } return(null); }).Where(each => each != null).OrderByDescending(each => each.Version); var reqVsVersion = versions.FirstOrDefault(); if (!string.IsNullOrEmpty(vsVersion)) { float f; if (!float.TryParse(vsVersion, out f)) { throw new Exception("Unable to parse version number"); } reqVsVersion = versions.FirstOrDefault(each => each.Version == f); } if (reqVsVersion == null) { throw new Exception("Required Visual Studio Version is not installed"); } var vsixInstller = Path.Combine(reqVsVersion.InstallDir, "VsixInstaller.exe"); if (!File.Exists(vsixInstller)) { throw new Exception("Can't find Visual Studio VSixInstaller.exe {0}".format(vsixInstller)); } var file = Path.Combine(Path.GetTempPath(), packageName.MakeSafeFileName()); DownloadFile(new Uri(vsixUrl), file, this.REQ); if (string.IsNullOrEmpty(file) || !File.Exists(file)) { throw new Exception("Unable to download file {0}".format(vsixUrl)); } var process = AsyncProcess.Start(new ProcessStartInfo { FileName = vsixInstller, Arguments = @"/q ""{0}""".format(file), }); process.WaitForExit(); if (process.ExitCode > 0 && process.ExitCode != 1001) { Verbose("VsixInstall Failure {0}", file); throw new Exception("Install failure"); } return(false); }
private IEnumerable <PackageItem> SearchSourceForPackages(PackageSource source, string name, string requiredVersion, string minimumVersion, string maximumVersion) { try { if (!String.IsNullOrEmpty(name) && WildcardPattern.ContainsWildcardCharacters(name)) { // NuGet does not support PowerShell/POSIX style wildcards and supports only '*' in searchTerm with NuGet.exe // Replace the range from '[' - to ']' with * and ? with * then wildcard pattern is applied on the results from NuGet.exe var tempName = name; var squareBracketPattern = Regex.Escape("[") + "(.*?)]"; foreach (Match match in Regex.Matches(tempName, squareBracketPattern)) { tempName = tempName.Replace(match.Value, "*"); } var searchTerm = tempName.Replace("?", "*"); // Wildcard pattern matching configuration. const WildcardOptions wildcardOptions = WildcardOptions.CultureInvariant | WildcardOptions.IgnoreCase; var wildcardPattern = new WildcardPattern(searchTerm, wildcardOptions); IEnumerable <string> packageIds = null; using (var p = AsyncProcess.Start(NuGetExePath, String.Format(@"list ""{0}"" -Source ""{1}"" ", searchTerm, source.Location))) { packageIds = p.StandardOutput.Where(each => !String.IsNullOrEmpty(each)).Select(l => { Verbose("NuGet: {0}", l); if (l.Contains("No packages found.")) { return(null); } // ComicRack 0.9.162 var packageDetails = l.Split(); if (wildcardPattern.IsMatch(packageDetails[0])) { return(packageDetails[0]); } return(null); }).Where(each => each != null).ToArray(); foreach (var l in p.StandardError.Where(l => !String.IsNullOrEmpty(l))) { Warning("NuGet: {0}", l); } } return(packageIds.SelectMany(packageId => GetPackageById(source, packageId, requiredVersion, minimumVersion, maximumVersion))); // return packageIds.SelectMany(packageId => SearchSourceForPackages(source, packageId, requiredVersion, minimumVersion, maximumVersion)); // return packageIds.SelectMany(packageId => FindPackageByNameFirst(source, packageId, requiredVersion, minimumVersion, maximumVersion)); // return SearchSourceForPackages(source.Location, requiredVersion, minimumVersion, maximumVersion); /* return FilterOnVersion(source.Repository.FindPackages(packageIds), requiredVersion, minimumVersion, maximumVersion) * .Select(pkg => new PackageItem { * Package = pkg, * PackageSource = source, * FastPath = MakeFastPath(source, pkg.Id, pkg.Version.ToString()) * });*/ } } catch (Exception e) { e.Dump(this); return(Enumerable.Empty <PackageItem>()); } try { var criteria = Contains.Value; if (String.IsNullOrEmpty(criteria)) { criteria = name; } if (FilterOnTag != null) { criteria = FilterOnTag.Value.Where(tag => !string.IsNullOrEmpty(tag)).Aggregate(criteria, (current, tag) => current + " tag:" + tag); } Debug("Searching repository '{0}' for '{1}'", source.Repository.Source, criteria); // var src = PackageRepositoryFactory.Default.CreateRepository(source.Repository.Source); // var src = new AggregateRepository(new IPackageRepository[] {source.Repository}); var src = source.Repository; /* * IQueryable<IPackage> packages; * if (src is IServiceBasedRepository) { * packages = (src as IServiceBasedRepository).Search(criteria, new string[0], AllowPrereleaseVersions); * } else { * packages = src.Search(criteria, AllowPrereleaseVersions); * } */ var packages = src.Search(criteria, AllowPrereleaseVersions); /* * foreach (var p in pp) { * Console.WriteLine(p.GetFullName()); * } */ // packages = packages.OrderBy(p => p.Id); // query filtering: if (!AllVersions && (String.IsNullOrEmpty(requiredVersion) && String.IsNullOrEmpty(minimumVersion) && String.IsNullOrEmpty(maximumVersion))) { packages = packages.FindLatestVersion(); } IEnumerable <IPackage> pkgs = new PackagesEnumerable(packages); // if they passed a name, restrict the search things that actually contain the name in the FullName. if (!String.IsNullOrEmpty(name)) { pkgs = FilterOnName(pkgs, name); } pkgs = FilterOnTags(pkgs); pkgs = FilterOnContains(pkgs); return(FilterOnVersion(pkgs, requiredVersion, minimumVersion, maximumVersion) .Select(pkg => new PackageItem { Package = pkg, PackageSource = source, FastPath = MakeFastPath(source, pkg.Id, pkg.Version.ToString()) })); } catch (Exception e) { e.Dump(this); return(Enumerable.Empty <PackageItem>()); } }