internal static void InstallPowershellArtifacts(PackageJson package, string fastPath, PackageSourceListRequest request) { var provider1 = PackageSourceListRequest.FindProvider(request, package.Type, request, true); if (provider1 == null) return; // As the PowerShellGet may access the -source via $request.Options or PackageSources, // so we need to fill in both options and sources parameters var installRequest = PackageSourceListRequest.ExtendRequest(new Dictionary<string, string[]> { {"Source", new[] {package.Source ?? ""}} }, new[] { package.Source ?? "" }, package.IsTrustedSource, request); var psid = PackageSourceListRequest.CreateCanonicalId(package, Constants.ProviderNames.PowerShellGet); var pkgs = request.PackageManagementService.FindPackageByCanonicalId(psid, installRequest) .Where(each => new SemanticVersion(each.Version) == new SemanticVersion(package.Version)).ToArray(); switch (pkgs.Length) { case 0: request.Warning(Resources.Messages.CannotFindPackage, Constants.ProviderName, psid); break; case 1: InstallPackageViaPowerShellGet(package, request, pkgs); break; default: request.Warning(Resources.Messages.FoundMorePackages, Constants.ProviderName, pkgs.Length, psid); break; } return; }
internal PackageQuery(PackageSource packageSource, PackageSourceListRequest request) { if (packageSource == null) { throw new ArgumentNullException("packageSource"); } if(string.IsNullOrWhiteSpace(packageSource.Location) || !System.IO.File.Exists(packageSource.Location)) { request.Warning(Resources.Messages.PackageSourceManifestNotFound, packageSource.Location, Constants.ProviderName); return; } Uri uri; if (Uri.TryCreate(packageSource.Location, UriKind.Absolute, out uri)) { if (uri.IsFile) { try { //process the file _PackageSourceList = JsonParser.ReadPackageSpec(packageSource, null); } catch (Exception ex) { request.Warning(ex.Message); while (ex.InnerException != null) { ex = ex.InnerException; request.Warning(ex.Message); } request.Warning(string.Format(CultureInfo.CurrentCulture, Resources.Messages.InvalidPackageListFormat, uri.AbsolutePath)); ex.Dump(request); } } // Uri? //TODO: ask a user whether go ahead for downloading an sample PSL.json } else { //TODO: Check with GP, DSC Settings, request.Verbose(Resources.Messages.UnsupportedPackageSource, packageSource.Location); return; } }
internal PackageQuery(PackageSource packageSource, PackageSourceListRequest request) { if (packageSource == null) { throw new ArgumentNullException("packageSource"); } if (string.IsNullOrWhiteSpace(packageSource.Location) || !System.IO.File.Exists(packageSource.Location)) { request.Warning(Resources.Messages.PackageSourceManifestNotFound, packageSource.Location, Constants.ProviderName); return; } Uri uri; if (Uri.TryCreate(packageSource.Location, UriKind.Absolute, out uri)) { if (uri.IsFile) { try { //process the file _PackageSourceList = JsonParser.ReadPackageSpec(packageSource, null); } catch (Exception ex) { request.Warning(ex.Message); while (ex.InnerException != null) { ex = ex.InnerException; request.Warning(ex.Message); } request.Warning(string.Format(CultureInfo.CurrentCulture, Resources.Messages.InvalidPackageListFormat, uri.AbsolutePath)); ex.Dump(request); } } // Uri? //TODO: ask a user whether go ahead for downloading an sample PSL.json } else { //TODO: Check with GP, DSC Settings, request.Verbose(Resources.Messages.UnsupportedPackageSource, packageSource.Location); return; } }
public void InstallPackage(string fastPath, PackageSourceListRequest request) { if (request == null) { throw new ArgumentNullException("request"); } if (!ValidatePackageManagementVersion(request)) { return; } if (request.PackageSources.Any(each => each.EndsWith(".json", StringComparison.OrdinalIgnoreCase))) { // Warning that PSL won't be able to handle the uninstall-package if the source is not registered. request.Warning(Resources.Messages.UsingSourceLocation, Constants.ProviderName); } request.Debug(Resources.Messages.DebugInfoCallMethod, PackageProviderName, "InstallPackage"); promptForSampleJSON(request); var package = request.GetPackageByFastPath(fastPath); if (package == null) { request.WriteError(ErrorCategory.InvalidData, fastPath, Resources.Messages.FailedToGetPackageObject, Constants.ProviderName, fastPath); return; } InstallProviderFromInstaller(package, fastPath, request); }
/// <summary> /// Removes/Unregisters a package source /// </summary> /// <param name="name">The name or location of a package source to remove.</param> /// <param name="request">An object passed in from the PackageManagement that contains functions that can be used to interact with its Provider</param> public void RemovePackageSource(string name, PackageSourceListRequest request) { if (request == null) { throw new ArgumentNullException("request"); } if (!ValidatePackageManagementVersion(request)) { return; } request.Debug(Resources.Messages.DebugInfoCallMethod, PackageProviderName, "RemovePackageSource"); var src = request.FindRegisteredSource(name); if (src == null) { request.Warning(Constants.Messages.UnableToResolveSource, Constants.ProviderName, name); return; } request.RemovePackageSource(src.Name); request.YieldPackageSource(src.Name, src.Location, src.Trusted, false, src.IsValidated); }
public void DownloadPackage(string fastPath, string location, PackageSourceListRequest request) { if (request == null) { throw new ArgumentNullException("request"); } request.Warning("PSL:Save-Package is not supported."); }
internal PackageQuery(PackageSource packageSource, string file, PackageSourceListRequest request) { try { //process the file _PackageSourceList = JsonParser.ReadPackageSpec(packageSource, file); } catch (Exception ex) { request.Warning(ex.Message); while (ex.InnerException != null) { ex = ex.InnerException; request.Warning(ex.Message); } request.Warning(string.Format(CultureInfo.CurrentCulture, Resources.Messages.InvalidPackageListFormat, file)); ex.Dump(request); } }
internal static bool UnInstallZipPackage(PackageJson package, PackageSourceListRequest request, string fastPath) { string sourceLocation; string id; string displayName; string version; string path; string providerName; if (!request.TryParseFastPathComplex(fastPath: fastPath, regex: PackageSourceListRequest.RegexFastPathComplex, location: out sourceLocation, id: out id, displayname: out displayName, version: out version, fastpath: out path, providerName: out providerName)) { request.Error(ErrorCategory.InvalidOperation, "package", Constants.Messages.UnableToUninstallPackage); return(false); } if (request.AddToPath.Value) { request.Warning(Resources.Messages.AddOrRemovePath, Constants.ProviderName, "AddToPath", "Install-Package"); } if (!string.IsNullOrWhiteSpace(path) && Directory.Exists(path)) { //Try to delete the directory to see if we can. Error out if we donot have permission if (Directory.Exists(path)) { try { Directory.Delete(path, true); } catch (System.UnauthorizedAccessException) { request.WriteError(ErrorCategory.InvalidOperation, package.Name, Resources.Messages.UninstallFailed, "UnInstall-Package", "UnauthorizedAccessException. The requested operation likely requires elevation, i.e., launch PowerShell as administer"); } } path.TryHardToDelete(); var dir = Path.Combine(package.Destination, package.Name); // delete an empty directory if (Directory.Exists(dir) && (!Directory.GetDirectories(dir).Any()) && !(Directory.GetFiles(dir).Any())) { dir.TryHardToDelete(); } request.YieldFromSwidtag(package, path); RemoveEnvironmentVariable(request, path, SystemEnvironmentKey); RemoveEnvironmentVariable(request, path, UserEnvironmentKey); return(true); } else { request.WriteError(ErrorCategory.InvalidData, path, Resources.Messages.DirectoryNotExist, Constants.ProviderName, path); return(false); } }
private static void RemoveEnvironmentVariable(PackageSourceListRequest request, string pathToBeRemoved, string target) { try { if (!request.RemoveFromPath.Value) { return; } var envPath = GetItemProperty(Constants.PATH, target); var trimchars = new char[] { '\\', ' ' }; if (!string.IsNullOrWhiteSpace(envPath)) { pathToBeRemoved = pathToBeRemoved.TrimEnd(trimchars); var newPath = envPath.Split(';').Where(each => !each.TrimEnd(trimchars).EqualsIgnoreCase(pathToBeRemoved)) .Aggregate("", (current, each) => string.IsNullOrEmpty(current) ? each : (current + ";" + each)); request.Debug("Removing '{0}' from PATH environment variable".format(pathToBeRemoved)); SetItemProperty(Constants.PATH, newPath, UserEnvironmentKey); SetItemProperty(Constants.PATH, newPath, SystemEnvironmentKey); Environment.SetEnvironmentVariable(Constants.PATH, newPath); } else { request.Warning(Resources.Messages.FailedToRetrivePathEnvironmentVariable, Constants.ProviderName); } } catch (Exception e) { request.Warning("Failed to update Path environment variable. {0}", e.Message); e.Dump(request); } }
private static void InstallPackageFile(PackageJson package, string fastPath, PackageSourceListRequest request) { request.Debug(Resources.Messages.DebugInfoCallMethod, Constants.ProviderName, string.Format(CultureInfo.InvariantCulture, "InstallPackageFile' - name='{0}', fastPath='{1}'", package.Name, fastPath)); // get a temp file name, msi or msu var providerType = package.Type.ToLowerInvariant(); var destination = Path.ChangeExtension(Path.GetTempFileName(), providerType); //download the msi package to the temp file WebDownloader.DownloadFile(package.Source, destination, request, null); if (!File.Exists(destination)) { return; } // validate the file if (!WebDownloader.VerifyHash(destination, package, request)) { return; } if (!package.IsTrustedSource) { if (!request.ShouldContinueWithUntrustedPackageSource(package.Name, package.Source)) { request.Warning(Constants.Messages.UserDeclinedUntrustedPackageInstall, package.Name); return; } } var installRequest = PackageSourceListRequest.ExtendRequest(new Dictionary <string, string[]> { { "Source", new[] { package.Source ?? "" } } }, new[] { package.Source ?? "" }, package.IsTrustedSource, request); request.Verbose(Resources.Messages.CallMsiForInstall, package.Name); if (request.ProviderServices.Install(destination, "", installRequest)) { // it installed ok!exit request.YieldFromSwidtag(package, fastPath); return; } else { request.WriteError(ErrorCategory.InvalidOperation, Constants.ProviderName, Resources.Messages.PackageFailedInstall, package.Name); } }
internal static void InstallPowershellArtifacts(PackageJson package, string fastPath, PackageSourceListRequest request) { var provider1 = PackageSourceListRequest.FindProvider(request, package.Type, request, true); if (provider1 == null) { return; } // As the PowerShellGet may access the -source via $request.Options or PackageSources, // so we need to fill in both options and sources parameters var installRequest = PackageSourceListRequest.ExtendRequest(new Dictionary <string, string[]> { { "Source", new[] { package.Source ?? "" } } }, new[] { package.Source ?? "" }, package.IsTrustedSource, request); var psid = PackageSourceListRequest.CreateCanonicalId(package, Constants.ProviderNames.PowerShellGet); var pkgs = request.PackageManagementService.FindPackageByCanonicalId(psid, installRequest) .Where(each => new SemanticVersion(each.Version) == new SemanticVersion(package.Version)).ToArray(); switch (pkgs.Length) { case 0: request.Warning(Resources.Messages.CannotFindPackage, Constants.ProviderName, psid); break; case 1: InstallPackageViaPowerShellGet(package, request, pkgs); break; default: request.Warning(Resources.Messages.FoundMorePackages, Constants.ProviderName, pkgs.Length, psid); break; } return; }
internal static void InstallNuGetPackage(PackageJson package, string fastPath, PackageSourceListRequest request) { request.Debug(Resources.Messages.DebugInfoCallMethod, Constants.ProviderName, string.Format(CultureInfo.InvariantCulture, "InstallNuGetPackage' - name='{0}', fastPath='{1}'", package.Name, fastPath)); var canonicalId = PackageSourceListRequest.CreateCanonicalId(package, Constants.ProviderNames.NuGet); // "nuget:jquery/2.1.0#http://nuget.org/api/v2"; var pkgs = request.PackageManagementService.FindPackageByCanonicalId(canonicalId, request.As <IHostApi>()) .Where(each => string.IsNullOrWhiteSpace(package.Version) || (new SemanticVersion(each.Version) == new SemanticVersion(package.Version))).ToArray(); switch (pkgs.Length) { case 0: request.Warning(Resources.Messages.CannotFindPackage, Constants.ProviderName, canonicalId); return; case 1: InstallPackageReference(package, request, pkgs); return; default: request.Warning(Resources.Messages.FoundMorePackages, Constants.ProviderName, pkgs.Length, canonicalId); return; } }
private static void AddEnvironmentVariable(PackageSourceListRequest request, string pathToBeAdded) { // Do nothing if a user does not specify -AddToPath if (!request.AddToPath.Value) { return; } try { var scope = ((request.Scope == null) || string.IsNullOrWhiteSpace(request.Scope.Value)) ? Constants.AllUsers : request.Scope.Value; // check if the environment variable exists already var envPath = Environment.GetEnvironmentVariable(Constants.PATH); var packagePath = ";" + pathToBeAdded.Trim(); if (string.IsNullOrWhiteSpace(envPath) || !envPath.Split(';').Where(each => each.EqualsIgnoreCase(pathToBeAdded)).Any()) { request.Debug("Adding '{0}' to PATH environment variable".format(pathToBeAdded)); // allow to add the path to the environment variable switch (scope) { case Constants.AllUsers: SetItemProperty(Constants.PATH, envPath + packagePath, SystemEnvironmentKey); break; case Constants.CurrentUser: SetItemProperty(Constants.PATH, envPath + packagePath, UserEnvironmentKey); break; } Environment.SetEnvironmentVariable(Constants.PATH, envPath + packagePath); } else { request.Debug("Environment variable '{0}' already exists".format(pathToBeAdded)); } } //if we cannot set the environment variable, we should not fail the install-package catch (Exception e) { request.Warning("Failed to update Path environment variable. {0}", e.Message); e.Dump(request); } }
public void GetInstalledPackages(string name, string requiredVersion, string minimumVersion, string maximumVersion, PackageSourceListRequest request) { if (request == null) { throw new ArgumentNullException("request"); } if (!ValidatePackageManagementVersion(request)) { return; } request.Debug(Resources.Messages.DebugInfoCallMethod, PackageProviderName, string.Format(CultureInfo.InvariantCulture, "GetInstalledPackages' - name='{0}', requiredVersion='{1}',minimumVersion='{2}', maximumVersion='{3}'", name, requiredVersion, minimumVersion, maximumVersion)); IEnumerable <PackageJson> packagesDefinedInJsonSpec; if (string.IsNullOrWhiteSpace(name) || WildcardPattern.ContainsWildcardCharacters(name)) { // In the case of the package name is null or contains wildcards, error out if a user puts version info if (!string.IsNullOrWhiteSpace(requiredVersion) || !string.IsNullOrWhiteSpace(minimumVersion) || !string.IsNullOrWhiteSpace(maximumVersion)) { request.Warning(Resources.Messages.WildCardCharsAreNotSupported, name); return; } packagesDefinedInJsonSpec = request.GetPackages(name).ToArray(); } else { //return all installed packagesDefinedInJsonSpec = request.GetPackages(name, requiredVersion, minimumVersion, maximumVersion).ToArray(); } _fastPackReftable.Clear(); if (!packagesDefinedInJsonSpec.Any()) { request.Verbose(Resources.Messages.NoPackageFound, Constants.ProviderName); return; } foreach (var package in packagesDefinedInJsonSpec) { switch (package.Type.ToLowerInvariant()) { case Constants.MediaType.AppxPackage: //TODO for future break; case Constants.MediaType.PsArtifacts: PowerShellArtifactInstaller.GeInstalledPowershellArtifacts(package, requiredVersion, minimumVersion, maximumVersion, _fastPackReftable, request); break; case Constants.MediaType.ExePackage: //program provider can handle get-package git for git.exe ExePackageInstaller.GetInstalledExePackages(package, requiredVersion, minimumVersion, minimumVersion, request); break; case Constants.MediaType.MsiPackage: //msi provider can handle get-package node.js for node.js.msi GetMsiInstalledPackage(name, package, requiredVersion, minimumVersion, maximumVersion, request); break; case Constants.MediaType.ZipPackage: ZipPackageInstaller.GetInstalledZipPackage(package, request); break; case Constants.MediaType.NuGetPackage: NupkgInstaller.GeInstalledNuGetPackages(package, requiredVersion, minimumVersion, maximumVersion, _fastPackReftable, request); break; } //switch } }
public void FindPackage(string name, string requiredVersion, string minimumVersion, string maximumVersion, int id, PackageSourceListRequest request) { if (request == null) { throw new ArgumentNullException("request"); } if (!ValidatePackageManagementVersion(request)) { return; } request.Debug(Resources.Messages.DebugInfoCallMethod, PackageProviderName, string.Format(CultureInfo.InvariantCulture, "FindPackage' - name='{0}', requiredVersion='{1}',minimumVersion='{2}', maximumVersion='{3}'", name, requiredVersion, minimumVersion, maximumVersion)); // no package name or the name with wildcard if (string.IsNullOrWhiteSpace(name) || WildcardPattern.ContainsWildcardCharacters(name)) { // In the case of the package name is null or contains wildcards, error out if a user puts version info if (!string.IsNullOrWhiteSpace(requiredVersion) || !string.IsNullOrWhiteSpace(minimumVersion) || !string.IsNullOrWhiteSpace(maximumVersion)) { request.Warning(Resources.Messages.WildCardCharsAreNotSupported, name); return; } var packages = request.GetPackages(name); if (request.GetOptionValue("AllVersions").IsTrue()) { // if version is specified then name can not be empty or with wildcard. in this case the cmdlet has been errored out already. // here we just return all packages we can find if (request.FilterOnVersion(packages, requiredVersion, minimumVersion, maximumVersion, minInclusive: true, maxInclusive: true, latest: false).OrderBy(p => p.Name).Any(p => !request.YieldFromSwidtag(p, p.Name))) { return; } return; } //return the latest version if (packages.GroupBy(p => p.Name) .Select(each => each.OrderByDescending(pp => pp.Version).FirstOrDefault()).OrderBy(p => p.Name).Any(item => !request.YieldFromSwidtag(item, item.Name))) { return; } } else { // a user specifies name // asked for a specific version? if (!string.IsNullOrWhiteSpace(requiredVersion)) { request.YieldFromSwidtag(request.GetPackage(name, requiredVersion), name); return; } var allVersion = request.GetOptionValue("AllVersions").IsTrue(); // asked for a version range? if (!string.IsNullOrWhiteSpace(minimumVersion) || !string.IsNullOrEmpty(maximumVersion) || allVersion) { var packages = request.GetPackagesWithinVersionRange(name, minimumVersion, maximumVersion); if (allVersion) { if (packages.Any(p => !request.YieldFromSwidtag(p, name))) { return; } } else { if (request.YieldFromSwidtag(packages.FirstOrDefault(), name)) { return; } } return; } // just return by name request.YieldFromSwidtag(request.GetPackage(name), name); } }
public void FindPackage(string name, string requiredVersion, string minimumVersion, string maximumVersion, int id, PackageSourceListRequest request) { if (request == null) { throw new ArgumentNullException("request"); } if (!ValidatePackageManagementVersion(request)) { return; } request.Debug(Resources.Messages.DebugInfoCallMethod, PackageProviderName, string.Format(CultureInfo.InvariantCulture, "FindPackage' - name='{0}', requiredVersion='{1}',minimumVersion='{2}', maximumVersion='{3}'", name, requiredVersion, minimumVersion, maximumVersion)); // no package name or the name with wildcard if (string.IsNullOrWhiteSpace(name) || WildcardPattern.ContainsWildcardCharacters(name)) { // In the case of the package name is null or contains wildcards, error out if a user puts version info if (!string.IsNullOrWhiteSpace(requiredVersion) || !string.IsNullOrWhiteSpace(minimumVersion) || !string.IsNullOrWhiteSpace(maximumVersion)) { request.Warning(Resources.Messages.WildCardCharsAreNotSupported, name); return; } var packages = request.GetPackages(name); if (request.GetOptionValue("AllVersions").IsTrue()) { // if version is specified then name can not be empty or with wildcard. in this case the cmdlet has been errored out already. // here we just return all packages we can find if (request.FilterOnVersion(packages, requiredVersion, minimumVersion, maximumVersion, minInclusive: true, maxInclusive: true, latest: false).OrderBy(p => p.Name).Any(p => !request.YieldFromSwidtag(p, p.Name))) { return; } return; } //return the latest version if (packages.GroupBy(p => p.Name) .Select(each => each.OrderByDescending(pp => pp.Version).FirstOrDefault()).OrderBy(p=>p.Name).Any( item =>!request.YieldFromSwidtag(item, item.Name))) { return; } } else { // a user specifies name // asked for a specific version? if (!string.IsNullOrWhiteSpace(requiredVersion)) { request.YieldFromSwidtag(request.GetPackage(name, requiredVersion), name); return; } var allVersion = request.GetOptionValue("AllVersions").IsTrue(); // asked for a version range? if (!string.IsNullOrWhiteSpace(minimumVersion) || !string.IsNullOrEmpty(maximumVersion) || allVersion) { var packages = request.GetPackagesWithinVersionRange(name, minimumVersion, maximumVersion); if (allVersion) { if (packages.Any(p => !request.YieldFromSwidtag(p, name))) { return; } } else { if (request.YieldFromSwidtag(packages.FirstOrDefault(), name)) { return; } } return; } // just return by name request.YieldFromSwidtag(request.GetPackage(name), name); } }
private static void InstallPackageViaPowerShellGet(PackageJson packageJson, PackageSourceListRequest request, SoftwareIdentity[] packages) { var provider = PackageSourceListRequest.FindProvider(request, packageJson.Type, request, true); if (provider == null) return; IHostApi installRequest = request; if (provider.Name.EqualsIgnoreCase(Constants.ProviderNames.PowerShellGet) && !request.ProviderServices.IsElevated) { // if we're not elevated, we want powershellget to install to the user scope installRequest = PackageSourceListRequest.ExtendRequest( new Dictionary<string, string[]> { {"Scope", new[] {"CurrentUser"}} }, null, packageJson.IsTrustedSource, request); } else { installRequest = PackageSourceListRequest.ExtendRequest( new Dictionary<string, string[]> { {"Destination", new[] {packageJson.Destination ?? ""}} }, null, packageJson.IsTrustedSource, request); } request.Debug("Calling '{0}' provider to install the package '{1}.{2}'", provider.Name, packageJson.Name, packageJson.Version); var installing = provider.InstallPackage(packages[0], installRequest); if (installing == null || !installing.Any()) { request.Verbose(Resources.Messages.NumberOfPackagesRecevied, 0, provider.Name, "InstallPackage"); request.Warning(Resources.Messages.FailToInstallPackage, Constants.ProviderName, packages[0].Name); return; } int packagesRecevied = 0; foreach (var i in installing) { request.YieldSoftwareIdentity(i.FastPackageReference, i.Name, i.Version, i.VersionScheme, i.Summary, i.Source, i.SearchKey, i.FullPath, i.PackageFilename); if (request.IsCanceled) { installing.Cancel(); } else { request.Verbose(Resources.Messages.SuccessfullyInstalled, "{0}.{1}".format(packageJson.Name, packageJson.Version)); //load provider if (packageJson.IsPackageProvider) { //Per provider development guidance: provider name and module name should be the same otherwise we can not import it. request.PackageManagementService.ImportPackageProvider(request, packageJson.Name, null, null, null, isRooted: false, force: false); } } packagesRecevied++; } request.Verbose(Resources.Messages.NumberOfPackagesRecevied, packagesRecevied, provider.Name, "install-package"); }
internal static string DownloadFile(string queryUrl, string destination, PackageSourceListRequest request, ProgressTracker progressTracker) { try { request.Debug(Resources.Messages.DebugInfoCallMethod, Constants.ProviderName, string.Format(System.Globalization.CultureInfo.InvariantCulture, "DownloadFile - url='{0}', destination='{1}'", queryUrl, destination)); if (string.IsNullOrWhiteSpace(destination)) { throw new ArgumentNullException("destination"); } // make sure that the parent folder is created first. var folder = Path.GetDirectoryName(destination); if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } if (File.Exists(destination)) { destination.TryHardToDelete(); } if (progressTracker == null) { progressTracker = new ProgressTracker(request.StartProgress(0, Resources.Messages.DownloadingPackage, queryUrl)); } Uri uri; if (!Uri.TryCreate(queryUrl, UriKind.Absolute, out uri)) { request.Error(Internal.ErrorCategory.InvalidOperation, Resources.Messages.UnsupportedUriFormat, Constants.ProviderName, queryUrl); return(null); } if (uri.IsFile) { // downloading from a file share using (var input = File.OpenRead(queryUrl)) { using (var output = new FileStream(destination, FileMode.Create, FileAccess.Write, FileShare.Read)) { request.Progress(progressTracker.ProgressID, progressTracker.StartPercent, Resources.Messages.Downloading); input.CopyTo(output); } } request.CompleteProgress(progressTracker.ProgressID, true); } else { //Downloading from url var result = DownloadDataToFileAsync(destination, queryUrl, request, PathUtility.GetNetworkCredential(request.CredentialUsername, request.CredentialPassword), progressTracker).Result; } if (File.Exists(destination)) { request.Verbose(Resources.Messages.CompletedDownload, queryUrl); return(destination); } else { request.Error(Internal.ErrorCategory.InvalidOperation, Resources.Messages.FailedToDownload, Constants.ProviderName, queryUrl, destination); return(null); } } catch (Exception ex) { ex.Dump(request); request.Warning(ex.Message); return(null); } }
internal static void DownloadNuGetPackage(string fastPath, string location, PackageSourceListRequest request) { if (request == null) { throw new ArgumentNullException("request"); } request.Debug(Resources.Messages.DebugInfoCallMethod, Constants.ProviderName, string.Format(CultureInfo.InvariantCulture, "DownloadNuGetPackage' - fastReference='{0}', location='{1}'", fastPath, location)); var package = request.GetPackageByFastPath(fastPath); if (package == null) { request.WriteError(ErrorCategory.InvalidData, fastPath, Resources.Messages.FailedToGetPackageObject, Constants.ProviderName, fastPath); return; } // let the core figure out how to save this package var canonicalId = PackageSourceListRequest.CreateCanonicalId(package, Constants.ProviderNames.NuGet); // "nuget:jquery/2.1.0#http://nuget.org/api/v2"; var pkgs = request.PackageManagementService.FindPackageByCanonicalId(canonicalId, request.As<IHostApi>()) .Where(each => string.IsNullOrWhiteSpace(package.Version) || (new SemanticVersion(each.Version) == new SemanticVersion(package.Version))).ToArray(); switch (pkgs.Length) { case 0: request.Warning(Resources.Messages.CannotFindPackage, Constants.ProviderName, canonicalId); return; case 1: var provider = request.PackageManagementService.GetAvailableProviders(request, new[] {"NuGet"}).FirstOrDefault(); if (provider != null) { var downloadrequest = PackageSourceListRequest.ExtendRequest( new Dictionary<string, string[]> { {"Destination", new[] {package.Destination ?? ""}} }, new[] {package.Source ?? ""}, package.IsTrustedSource, request); var downloading = provider.DownloadPackage(pkgs[0], location, downloadrequest); foreach (var i in downloading) { request.YieldSoftwareIdentity(i.FastPackageReference, i.Name, i.Version, i.VersionScheme, i.Summary, i.Source, i.SearchKey, i.FullPath, i.PackageFilename); if (request.IsCanceled) { downloading.Cancel(); } } } break; default: request.Warning(Resources.Messages.FoundMorePackages, Constants.ProviderName, pkgs.Length, canonicalId); return; } }
internal PackageQuery(PackageSource packageSource, string file, PackageSourceListRequest request) { try { //process the file _PackageSourceList = JsonParser.ReadPackageSpec(packageSource, file); } catch (Exception ex) { request.Warning(ex.Message); while (ex.InnerException != null) { ex = ex.InnerException; request.Warning(ex.Message); } request.Warning(string.Format(CultureInfo.CurrentCulture, Resources.Messages.InvalidPackageListFormat, file)); ex.Dump(request); } }
private static void InstallPackageFile(PackageJson package, string fastPath, PackageSourceListRequest request) { request.Debug(Resources.Messages.DebugInfoCallMethod, Constants.ProviderName, string.Format(CultureInfo.InvariantCulture, "InstallPackageFile' - name='{0}'", package.Name)); // get a temp file name, msi or msu var providerType = package.Type.ToLowerInvariant(); var destination = Path.ChangeExtension(Path.GetTempFileName(), providerType); try { //download the msi package to the temp file WebDownloader.DownloadFile(package.Source, destination, request, null); if (!File.Exists(destination)) { return; } // validate the file if (!WebDownloader.VerifyHash(destination, package, request)) { return; } // For unsigned msi packages, the MSI provider will prompt a user if he wants to install it. // However if the signed msi package but the PackageSource is untrusted, MSI provider does not prompt. So we prompt here. if (request.ProviderServices.IsSignedAndTrusted(destination, request)) { if (!request.ShouldContinueWithUntrustedPackageSource(package.Name, package.Source)) { request.Warning(Constants.Messages.UserDeclinedUntrustedPackageInstall, package.Name); return; } } if (!string.IsNullOrWhiteSpace(package.Destination)) { request.Verbose(Resources.Messages.DestinationNotSupported, package.Type); } var installRequest = PackageSourceListRequest.ExtendRequest(new Dictionary <string, string[]> { { "Source", new[] { package.Source ?? "" } } }, new[] { package.Source ?? "" }, request); request.Verbose(Resources.Messages.CallMsiForInstall, package.Name); if (request.ProviderServices.Install(destination, "", installRequest)) { // it installed ok!exit request.YieldFromSwidtag(package, fastPath); return; } else { request.WriteError(ErrorCategory.InvalidOperation, Constants.ProviderName, Resources.Messages.PackageFailedInstall, package.Name); } } finally { if (File.Exists(destination)) { destination.TryHardToDelete(); } } }
internal static bool InstallZipPackage(PackageJson package, string fastPath, PackageSourceListRequest request) { // download the exe package var file = Path.ChangeExtension(Path.GetTempFileName(), "exe"); WebDownloader.DownloadFile(package.Source, file, request, null); if (!File.Exists(file)) { return(false); } // validate the file if (!WebDownloader.VerifyHash(file, package, request)) { return(false); } if (!package.IsTrustedSource) { if (!request.ShouldContinueWithUntrustedPackageSource(package.Name, package.Source)) { request.Warning(Constants.Messages.UserDeclinedUntrustedPackageInstall, package.Name); return(false); } } Timer timer = null; object timerLock = new object(); bool cleanUp = false; ProgressTracker tracker = new ProgressTracker(request.StartProgress(0, "Installing Zip Package............")); double percent = tracker.StartPercent; Action cleanUpAction = () => { lock (timerLock) { // check whether clean up is already done before or not if (!cleanUp) { try { if (timer != null) { // stop timer timer.Change(Timeout.Infinite, Timeout.Infinite); timer.Dispose(); timer = null; } } catch { } cleanUp = true; } } }; // extracted folder string extractedFolder = string.Concat(file.GenerateTemporaryFilename()); try { timer = new Timer(_ => { percent += 0.025; var progressPercent = tracker.ConvertPercentToProgress(percent); if (progressPercent < 90) { request.Progress(tracker.ProgressID, (int)progressPercent, string.Format(CultureInfo.CurrentCulture, "Copying files ...")); } if (request.IsCanceled) { cleanUpAction(); } }, null, 0, 1000); //unzip the file ZipFile.ExtractToDirectory(file, extractedFolder); if (Directory.Exists(extractedFolder)) { var versionFolder = Path.Combine(package.Destination, package.Name, package.Version); // create the directory version folder if not exist if (!Directory.Exists(versionFolder)) { Directory.CreateDirectory(versionFolder); } try { FileUtility.CopyDirectory(extractedFolder, versionFolder, true); request.YieldFromSwidtag(package, fastPath); } catch (Exception e) { request.CompleteProgress(tracker.ProgressID, false); request.Debug(e.StackTrace); if (!(e is UnauthorizedAccessException || e is IOException)) { // something wrong, delete the version folder versionFolder.TryHardToDelete(); return(false); } } return(true); } else { request.Warning("Failed to download a Zip package {0} from {1}", package.Name, package.Source); } } finally { cleanUpAction(); file.TryHardToDelete(); extractedFolder.TryHardToDelete(); request.CompleteProgress(tracker.ProgressID, true); } return(false); }
internal static bool InstallExePackage(PackageJson package, string fastPath, PackageSourceListRequest request) { ProgressTracker tracker = new ProgressTracker(request.StartProgress(0, Resources.Messages.Installing)); var exePackage = Path.ChangeExtension(Path.GetTempFileName(), "exe"); WebDownloader.DownloadFile(package.Source, exePackage, request, tracker); if (File.Exists(exePackage)) { request.Verbose("Package: '{0}'", exePackage); // validate the file if (!WebDownloader.VerifyHash(exePackage,package, request)) { return false; } if (!package.IsTrustedSource) { if (!request.ShouldContinueWithUntrustedPackageSource(package.Name, package.Source)) { request.Warning(Constants.Messages.UserDeclinedUntrustedPackageInstall, package.Name); return false; } } // Prepare the process to run var processArguments = string.IsNullOrWhiteSpace(package.InstallArguments) ? "/VERYSILENT /CLOSEAPPLICATIONS /NORESTART /NOCANCEL /SP /qn" : package.InstallArguments; var start = new ProcessStartInfo { FileName = exePackage, Arguments = processArguments, UseShellExecute = false, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true, CreateNoWindow = true, //LoadUserProfile = true, }; double percent = tracker.StartPercent; Timer timer = null; object timerLock = new object(); bool cleanUp = false; Action cleanUpAction = () => { lock (timerLock) { // check whether clean up is already done before or not if (!cleanUp) { try { if (timer != null) { // stop timer timer.Change(Timeout.Infinite, Timeout.Infinite); // dispose it timer.Dispose(); } } catch { } cleanUp = true; } } }; // Run the external process & wait for it to finish using (var proc = Process.Start(start)) { var timer1 = timer; timer = new Timer(_ => { percent += 0.025; // percent between startProgress and endProgress var progressPercent = tracker.ConvertPercentToProgress(percent); if (progressPercent < 90) { request.Progress(tracker.ProgressID, (int)progressPercent, Resources.Messages.InstallingPackage, package.Source); } if (request.IsCanceled) { cleanUpAction(); } }, null, 100, 3000); proc.WaitForExit(); // Retrieve the app's exit code var exitCode = proc.ExitCode; if (exitCode != 0) { request.WriteError(ErrorCategory.InvalidOperation, fastPath, Resources.Messages.InstallFailed, package.Name, proc.StandardError.ReadToEnd()); request.CompleteProgress(tracker.ProgressID, false); return false; } else { request.CompleteProgress(tracker.ProgressID, true); request.YieldFromSwidtag(package, fastPath); request.Verbose(Resources.Messages.SuccessfullyInstalled, package.Name); } cleanUpAction(); } return true; } else { request.Error(ErrorCategory.InvalidOperation, Resources.Messages.FailedToDownload, Constants.ProviderName, package.Source, exePackage); } return false; }
private static void InstallPackageFile(PackageJson package, string fastPath, PackageSourceListRequest request) { request.Debug(Resources.Messages.DebugInfoCallMethod, Constants.ProviderName, string.Format(CultureInfo.InvariantCulture, "InstallPackageFile' - name='{0}', fastPath='{1}'", package.Name, fastPath)); // get a temp file name, msi or msu var providerType = package.Type.ToLowerInvariant(); var destination = Path.ChangeExtension(Path.GetTempFileName(), providerType); //download the msi package to the temp file WebDownloader.DownloadFile(package.Source, destination, request, null); if (!File.Exists(destination)) { return; } // validate the file if (!WebDownloader.VerifyHash(destination,package, request)) { return; } if (!package.IsTrustedSource) { if (!request.ShouldContinueWithUntrustedPackageSource(package.Name, package.Source)) { request.Warning(Constants.Messages.UserDeclinedUntrustedPackageInstall, package.Name); return; } } var installRequest = PackageSourceListRequest.ExtendRequest(new Dictionary<string, string[]> { {"Source", new[] {package.Source ?? ""}} }, new[] { package.Source ?? "" }, package.IsTrustedSource, request); request.Verbose(Resources.Messages.CallMsiForInstall, package.Name); if (request.ProviderServices.Install(destination, "", installRequest)) { // it installed ok!exit request.YieldFromSwidtag(package, fastPath); return; } else { request.WriteError(ErrorCategory.InvalidOperation, Constants.ProviderName, Resources.Messages.PackageFailedInstall, package.Name); } }
public void GetInstalledPackages(string name, string requiredVersion, string minimumVersion, string maximumVersion, PackageSourceListRequest request) { if (request == null) { throw new ArgumentNullException("request"); } if (!ValidatePackageManagementVersion(request)) { return; } request.Debug(Resources.Messages.DebugInfoCallMethod, PackageProviderName, string.Format(CultureInfo.InvariantCulture, "GetInstalledPackages' - name='{0}', requiredVersion='{1}',minimumVersion='{2}', maximumVersion='{3}'", name, requiredVersion, minimumVersion, maximumVersion)); IEnumerable<PackageJson> packagesDefinedInJsonSpec; if (string.IsNullOrWhiteSpace(name) || WildcardPattern.ContainsWildcardCharacters(name)) { // In the case of the package name is null or contains wildcards, error out if a user puts version info if (!string.IsNullOrWhiteSpace(requiredVersion) || !string.IsNullOrWhiteSpace(minimumVersion) || !string.IsNullOrWhiteSpace(maximumVersion)) { request.Warning(Resources.Messages.WildCardCharsAreNotSupported, name); return; } packagesDefinedInJsonSpec = request.GetPackages(name).ToArray(); } else { //return all installed packagesDefinedInJsonSpec = request.GetPackages(name, requiredVersion, minimumVersion, maximumVersion).ToArray(); } _fastPackReftable.Clear(); if (!packagesDefinedInJsonSpec.Any()) { request.Verbose(Resources.Messages.NoPackageFound, Constants.ProviderName); return; } foreach (var package in packagesDefinedInJsonSpec) { switch (package.Type.ToLowerInvariant()) { case Constants.MediaType.AppxPackage: //TODO for future break; case Constants.MediaType.PsArtifacts: PowerShellArtifactInstaller.GeInstalledPowershellArtifacts(package, requiredVersion, minimumVersion,maximumVersion, _fastPackReftable, request); break; case Constants.MediaType.ExePackage: //program provider can handle get-package git for git.exe ExePackageInstaller.GetInstalledExePackages(package, requiredVersion, minimumVersion, minimumVersion, request); break; case Constants.MediaType.MsiPackage: //msi provider can handle get-package node.js for node.js.msi GetMsiInstalledPackage(name, package, requiredVersion, minimumVersion, maximumVersion, request); break; case Constants.MediaType.ZipPackage: ZipPackageInstaller.GetInstalledZipPackage(package, request); break; case Constants.MediaType.NuGetPackage: NupkgInstaller.GeInstalledNuGetPackages(package, requiredVersion, minimumVersion, maximumVersion, _fastPackReftable, request); break; } //switch } }
internal static PackageProvider FindProvider(PackageSourceListRequest request, string providerType, IHostApi hostApi, bool logError = false) { string providerName = null; switch (providerType.ToLowerInvariant()) { case Constants.MediaType.MsiPackage: providerName = Constants.ProviderNames.Msi; break; case Constants.MediaType.MsuPackage: providerName = Constants.ProviderNames.Msu; break; case Constants.MediaType.AppxPackage: //TODO for future whenever needed to support appx packages break; case Constants.MediaType.NuGetPackage: providerName = Constants.ProviderNames.NuGet; break; case Constants.MediaType.ZipPackage: case Constants.MediaType.ExePackage: providerName = Constants.ProviderNames.PSL; break; case Constants.MediaType.PsArtifacts: providerName = Constants.ProviderNames.PowerShellGet; break; default: request.Warning(Resources.Messages.UnsupportedProviderType, Constants.ProviderName, providerType); break; } if (string.IsNullOrWhiteSpace(providerName)) { return(null); } PackageProvider provider; if (_packageProviders.ContainsKey(providerName)) { provider = _packageProviders[providerName]; } else { provider = request.PackageManagementService.SelectProviders(providerName, request).FirstOrDefault(); if (provider != null) { _packageProviders.AddOrSet(providerName, provider); } } if (provider != null) { return(provider); } request.Verbose(Resources.Messages.ProviderNotFound, providerName); if (logError) { request.Error(ErrorCategory.InvalidOperation, providerName, Resources.Messages.ProviderNotFound, providerName); } return(null); }
internal static bool InstallZipPackage(PackageJson package, string fastPath, PackageSourceListRequest request) { if (request.RemoveFromPath.Value) { request.Warning(Resources.Messages.AddOrRemovePath, Constants.ProviderName, "RemoveFromPath", "Uninstall-Package"); } // download the exe package var providerType = package.Type.ToLowerInvariant(); var file = Path.ChangeExtension(Path.GetTempFileName(), providerType); if (string.IsNullOrWhiteSpace(package.Destination)) { request.Error(ErrorCategory.InvalidOperation, Constants.ProviderName, Resources.Messages.DestinationRequired); return(false); } WebDownloader.DownloadFile(package.Source, file, request, null); if (!File.Exists(file)) { return(false); } // validate the file if (!WebDownloader.VerifyHash(file, package, request)) { file.TryHardToDelete(); return(false); } if (!request.ShouldContinueWithUntrustedPackageSource(package.Name, package.Source)) { request.Warning(Constants.Messages.UserDeclinedUntrustedPackageInstall, package.Name); file.TryHardToDelete(); return(false); } Timer timer = null; object timerLock = new object(); bool cleanUp = false; ProgressTracker tracker = new ProgressTracker(request.StartProgress(0, "Installing Zip Package............")); double percent = tracker.StartPercent; Action cleanUpAction = () => { lock (timerLock) { // check whether clean up is already done before or not if (!cleanUp) { try { if (timer != null) { // stop timer timer.Change(Timeout.Infinite, Timeout.Infinite); timer.Dispose(); timer = null; } } catch { } cleanUp = true; } } }; // extracted folder string extractedFolder = string.Concat(file.GenerateTemporaryFilename()); var versionFolder = ""; try { timer = new Timer(_ => { percent += 0.025; var progressPercent = tracker.ConvertPercentToProgress(percent); if (progressPercent < 90) { request.Progress(tracker.ProgressID, (int)progressPercent, string.Format(CultureInfo.CurrentCulture, "Copying files ...")); } if (request.IsCanceled) { cleanUpAction(); } }, null, 0, 1000); //unzip the file ZipFile.ExtractToDirectory(file, extractedFolder); if (Directory.Exists(extractedFolder)) { versionFolder = Path.Combine(package.Destination, package.Name, package.Version); // create the directory version folder if not exist if (!Directory.Exists(versionFolder)) { Directory.CreateDirectory(versionFolder); } // The package will be installed to destination\packageName\version\ // However, a few packages have a package name as its top level folder after zip. // So the installed folder will look like this: // \destination\foobarPackage\1.0.1\foobarPackage // In this case we directly copy the files to \destination\foobarPackage\1.0.1. var extractedTopLevelFolder = Directory.EnumerateDirectories(extractedFolder, "*", SearchOption.TopDirectoryOnly); while (!Directory.GetFiles(extractedFolder).Any() && extractedTopLevelFolder.Count() == 1) { extractedFolder = extractedTopLevelFolder.FirstOrDefault(); //in case the zip contains version folder extractedTopLevelFolder = Directory.EnumerateDirectories(extractedFolder, "*", SearchOption.TopDirectoryOnly); } FileUtility.CopyDirectory(extractedFolder, versionFolder, true); request.YieldFromSwidtag(package, fastPath); request.Verbose(Resources.Messages.SuccessfullyInstalledToDestination, package.Name, package.Destination); AddEnvironmentVariable(request, versionFolder); return(true); } else { request.Warning("Failed to download a Zip package {0} from {1}", package.Name, package.Source); } } catch (Exception e) { request.Debug(e.StackTrace); if (e is System.UnauthorizedAccessException) { request.WriteError(ErrorCategory.InvalidOperation, package.Name, Resources.Messages.InstallFailed, package.Name, "UnauthorizedAccessException. The requested operation likely requires elevation, i.e., launch PowerShell as administer"); } else { request.WriteError(ErrorCategory.InvalidOperation, package.Name, Resources.Messages.InstallFailed, package.Name, e.Message); } if (!(e is UnauthorizedAccessException || e is IOException)) { // something wrong, delete the version folder versionFolder.TryHardToDelete(); } } finally { cleanUpAction(); file.TryHardToDelete(); extractedFolder.TryHardToDelete(); request.CompleteProgress(tracker.ProgressID, true); } return(false); }
internal static void InstallNuGetPackage(PackageJson package, string fastPath, PackageSourceListRequest request) { request.Debug(Resources.Messages.DebugInfoCallMethod, Constants.ProviderName, string.Format(CultureInfo.InvariantCulture, "InstallNuGetPackage' - name='{0}', fastPath='{1}'", package.Name, fastPath)); var canonicalId = PackageSourceListRequest.CreateCanonicalId(package, Constants.ProviderNames.NuGet); // "nuget:jquery/2.1.0#http://nuget.org/api/v2"; var pkgs = request.PackageManagementService.FindPackageByCanonicalId(canonicalId, request.As<IHostApi>()) .Where(each => string.IsNullOrWhiteSpace(package.Version) || (new SemanticVersion(each.Version) == new SemanticVersion(package.Version))).ToArray(); switch (pkgs.Length) { case 0: request.Warning(Resources.Messages.CannotFindPackage, Constants.ProviderName, canonicalId); return; case 1: InstallPackageReference(package, request, pkgs); return; default: request.Warning(Resources.Messages.FoundMorePackages, Constants.ProviderName, pkgs.Length, canonicalId); return; } }
internal static void DownloadNuGetPackage(string fastPath, string location, PackageSourceListRequest request) { if (request == null) { throw new ArgumentNullException("request"); } request.Debug(Resources.Messages.DebugInfoCallMethod, Constants.ProviderName, string.Format(CultureInfo.InvariantCulture, "DownloadNuGetPackage' - fastReference='{0}', location='{1}'", fastPath, location)); var package = request.GetPackageByFastPath(fastPath); if (package == null) { request.WriteError(ErrorCategory.InvalidData, fastPath, Resources.Messages.FailedToGetPackageObject, Constants.ProviderName, fastPath); return; } // let the core figure out how to save this package var canonicalId = PackageSourceListRequest.CreateCanonicalId(package, Constants.ProviderNames.NuGet); // "nuget:jquery/2.1.0#http://nuget.org/api/v2"; var pkgs = request.PackageManagementService.FindPackageByCanonicalId(canonicalId, request.As <IHostApi>()) .Where(each => string.IsNullOrWhiteSpace(package.Version) || (new SemanticVersion(each.Version) == new SemanticVersion(package.Version))).ToArray(); switch (pkgs.Length) { case 0: request.Warning(Resources.Messages.CannotFindPackage, Constants.ProviderName, canonicalId); return; case 1: var provider = request.PackageManagementService.GetAvailableProviders(request, new[] { "NuGet" }).FirstOrDefault(); if (provider != null) { var donwloadrequest = PackageSourceListRequest.ExtendRequest( new Dictionary <string, string[]> { { "Destination", new[] { package.Destination ?? "" } } }, new[] { package.Source ?? "" }, package.IsTrustedSource, request); var downloading = provider.DownloadPackage(pkgs[0], location, donwloadrequest); foreach (var i in downloading) { request.YieldSoftwareIdentity(i.FastPackageReference, i.Name, i.Version, i.VersionScheme, i.Summary, i.Source, i.SearchKey, i.FullPath, i.PackageFilename); if (request.IsCanceled) { downloading.Cancel(); } } } break; default: request.Warning(Resources.Messages.FoundMorePackages, Constants.ProviderName, pkgs.Length, canonicalId); return; } }
internal static bool InstallZipPackage(PackageJson package, string fastPath, PackageSourceListRequest request) { // download the exe package var file = Path.ChangeExtension(Path.GetTempFileName(), "exe"); WebDownloader.DownloadFile(package.Source, file, request, null); if (!File.Exists(file)) { return false; } // validate the file if (!WebDownloader.VerifyHash(file, package,request)) { return false; } if (!package.IsTrustedSource) { if (!request.ShouldContinueWithUntrustedPackageSource(package.Name, package.Source)) { request.Warning(Constants.Messages.UserDeclinedUntrustedPackageInstall, package.Name); return false; } } Timer timer = null; object timerLock = new object(); bool cleanUp = false; ProgressTracker tracker = new ProgressTracker(request.StartProgress(0, "Installing Zip Package............")); double percent = tracker.StartPercent; Action cleanUpAction = () => { lock (timerLock) { // check whether clean up is already done before or not if (!cleanUp) { try { if (timer != null) { // stop timer timer.Change(Timeout.Infinite, Timeout.Infinite); timer.Dispose(); timer = null; } } catch { } cleanUp = true; } } }; // extracted folder string extractedFolder = string.Concat(file.GenerateTemporaryFilename()); try { timer = new Timer(_ => { percent += 0.025; var progressPercent = tracker.ConvertPercentToProgress(percent); if (progressPercent < 90) { request.Progress(tracker.ProgressID, (int)progressPercent, string.Format(CultureInfo.CurrentCulture, "Copying files ...")); } if (request.IsCanceled) { cleanUpAction(); } }, null, 0, 1000); //unzip the file ZipFile.ExtractToDirectory(file, extractedFolder); if (Directory.Exists(extractedFolder)) { var versionFolder = Path.Combine(package.Destination, package.Name, package.Version); // create the directory version folder if not exist if (!Directory.Exists(versionFolder)) { Directory.CreateDirectory(versionFolder); } try { FileUtility.CopyDirectory(extractedFolder, versionFolder, true); request.YieldFromSwidtag(package, fastPath); } catch (Exception e) { request.CompleteProgress(tracker.ProgressID, false); request.Debug(e.StackTrace); if (!(e is UnauthorizedAccessException || e is IOException)) { // something wrong, delete the version folder versionFolder.TryHardToDelete(); return false; } } return true; } else { request.Warning("Failed to download a Zip package {0} from {1}", package.Name, package.Source); } } finally { cleanUpAction(); file.TryHardToDelete(); extractedFolder.TryHardToDelete(); request.CompleteProgress(tracker.ProgressID, true); } return false; }
internal static string DownloadFile(string queryUrl, string destination, PackageSourceListRequest request, ProgressTracker progressTracker) { try { request.Debug(Resources.Messages.DebugInfoCallMethod, Constants.ProviderName, string.Format(System.Globalization.CultureInfo.InvariantCulture, "DownloadFile - url='{0}', destination='{1}'", queryUrl, destination)); if (string.IsNullOrWhiteSpace(destination)) { throw new ArgumentNullException("destination"); } // make sure that the parent folder is created first. var folder = Path.GetDirectoryName(destination); if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } if (File.Exists(destination)) { destination.TryHardToDelete(); } if (progressTracker == null) { progressTracker = new ProgressTracker(request.StartProgress(0, Resources.Messages.DownloadingPackage, queryUrl)); } Uri uri; if (!Uri.TryCreate(queryUrl, UriKind.Absolute, out uri)) { request.Error(Internal.ErrorCategory.InvalidOperation, Resources.Messages.UnsupportedUriFormat, Constants.ProviderName, queryUrl); return null; } if (uri.IsFile) { // downloading from a file share using (var input = File.OpenRead(queryUrl)) { using (var output = new FileStream(destination, FileMode.Create, FileAccess.Write, FileShare.Read)) { request.Progress(progressTracker.ProgressID, progressTracker.StartPercent, Resources.Messages.Downloading); input.CopyTo(output); } } request.CompleteProgress(progressTracker.ProgressID, true); } else { //Downloading from url var result = DownloadDataToFileAsync(destination, queryUrl, request, PathUtility.GetNetworkCredential(request.CredentialUsername, request.CredentialPassword), progressTracker).Result; } if (File.Exists(destination)) { request.Verbose(Resources.Messages.CompletedDownload, queryUrl); return destination; } else { request.Error(Internal.ErrorCategory.InvalidOperation, Resources.Messages.FailedToDownload, Constants.ProviderName, queryUrl, destination); return null; } } catch (Exception ex) { ex.Dump(request); request.Warning(ex.Message); return null; } }
internal static bool InstallExePackage(PackageJson package, string fastPath, PackageSourceListRequest request) { ProgressTracker tracker = new ProgressTracker(request.StartProgress(0, Resources.Messages.Installing)); var providerType = package.Type.ToLowerInvariant(); var exePackage = Path.ChangeExtension(Path.GetTempFileName(), providerType); if (!string.IsNullOrWhiteSpace(package.Destination)) { request.Verbose(Resources.Messages.DestinationNotSupported, package.Type); } try { WebDownloader.DownloadFile(package.Source, exePackage, request, tracker); if (File.Exists(exePackage)) { request.Verbose("Package: '{0}'", exePackage); // validate the file if (!WebDownloader.VerifyHash(exePackage, package, request)) { return(false); } if (!request.ShouldContinueWithUntrustedPackageSource(package.Name, package.Source)) { request.Warning(Constants.Messages.UserDeclinedUntrustedPackageInstall, package.Name); return(false); } // Prepare the process to run var processArguments = string.IsNullOrWhiteSpace(package.InstallArguments) ? "/VERYSILENT /CLOSEAPPLICATIONS /NORESTART /NOCANCEL /SP /qn" : package.InstallArguments; var start = new ProcessStartInfo { FileName = exePackage, Arguments = processArguments, UseShellExecute = false, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true, CreateNoWindow = true, //LoadUserProfile = true, }; double percent = tracker.StartPercent; Timer timer = null; object timerLock = new object(); bool cleanUp = false; Action cleanUpAction = () => { lock (timerLock) { // check whether clean up is already done before or not if (!cleanUp) { try { if (timer != null) { // stop timer timer.Change(Timeout.Infinite, Timeout.Infinite); // dispose it timer.Dispose(); } } catch { } cleanUp = true; } } }; // Run the external process & wait for it to finish using (var proc = Process.Start(start)) { var timer1 = timer; timer = new Timer(_ => { percent += 0.025; // percent between startProgress and endProgress var progressPercent = tracker.ConvertPercentToProgress(percent); if (progressPercent < 90) { request.Progress(tracker.ProgressID, (int)progressPercent, Resources.Messages.InstallingPackage, package.Source); } if (request.IsCanceled) { cleanUpAction(); } }, null, 100, 3000); proc.WaitForExit(); // Retrieve the app's exit code var exitCode = proc.ExitCode; if (exitCode != 0) { request.WriteError(ErrorCategory.InvalidOperation, fastPath, Resources.Messages.InstallFailed, package.Name, proc.StandardError.ReadToEnd()); request.CompleteProgress(tracker.ProgressID, false); return(false); } else { request.CompleteProgress(tracker.ProgressID, true); request.YieldFromSwidtag(package, fastPath); request.Verbose(Resources.Messages.SuccessfullyInstalled, package.Name); } cleanUpAction(); } return(true); } else { request.WriteError(ErrorCategory.InvalidOperation, Constants.ProviderName, Resources.Messages.FailedToDownload, Constants.ProviderName, package.Source); } return(false); } catch (Exception ex) { request.Error(ErrorCategory.InvalidOperation, "install-package", ex.Message); ex.Dump(request); return(false); } finally { if (File.Exists(exePackage)) { exePackage.TryHardToDelete(); } } }
internal static PackageProvider FindProvider(PackageSourceListRequest request, string providerType, IHostApi hostApi, bool logError = false) { string providerName = null; switch (providerType.ToLowerInvariant()) { case Constants.MediaType.MsiPackage: providerName = Constants.ProviderNames.Msi; break; case Constants.MediaType.MsuPackage: providerName = Constants.ProviderNames.Msu; break; case Constants.MediaType.AppxPackage: //TODO for future whenever needed to support appx packages break; case Constants.MediaType.NuGetPackage: providerName = Constants.ProviderNames.NuGet; break; case Constants.MediaType.ZipPackage: case Constants.MediaType.ExePackage: providerName = Constants.ProviderNames.PSL; break; case Constants.MediaType.PsArtifacts: providerName = Constants.ProviderNames.PowerShellGet; break; default: request.Warning(Resources.Messages.UnsupportedProviderType, providerType); break; } if (string.IsNullOrWhiteSpace(providerName)) { return null; } PackageProvider provider; if (_packageProviders.ContainsKey(providerName)) { provider = _packageProviders[providerName]; } else { provider = request.PackageManagementService.SelectProviders(providerName, request).FirstOrDefault(); if (provider != null) { _packageProviders.AddOrSet(providerName, provider); } } if (provider != null) { return provider; } request.Verbose(Resources.Messages.ProviderNotFound, providerName); if (logError) { request.Error(ErrorCategory.InvalidOperation, providerName, Resources.Messages.ProviderNotFound, providerName); } return null; }
private static void InstallPackageViaPowerShellGet(PackageJson packageJson, PackageSourceListRequest request, SoftwareIdentity[] packages) { var provider = PackageSourceListRequest.FindProvider(request, packageJson.Type, request, true); if (provider == null) { return; } IHostApi installRequest = request; if (provider.Name.EqualsIgnoreCase(Constants.ProviderNames.PowerShellGet) && !request.ProviderServices.IsElevated) { // if we're not elevated, we want powershellget to install to the user scope installRequest = PackageSourceListRequest.ExtendRequest( new Dictionary <string, string[]> { { "Scope", new[] { "CurrentUser" } } }, null, packageJson.IsTrustedSource, request); } else { installRequest = PackageSourceListRequest.ExtendRequest( new Dictionary <string, string[]> { { "Destination", new[] { packageJson.Destination ?? "" } } }, null, packageJson.IsTrustedSource, request); } request.Debug("Calling '{0}' provider to install the package '{1}.{2}'", provider.Name, packageJson.Name, packageJson.Version); var installing = provider.InstallPackage(packages[0], installRequest); if (installing == null || !installing.Any()) { request.Verbose(Resources.Messages.NumberOfPackagesRecevied, 0, provider.Name, "InstallPackage"); request.Warning(Resources.Messages.FailToInstallPackage, Constants.ProviderName, packages[0].Name); return; } int packagesReceived = 0; foreach (var i in installing) { request.YieldSoftwareIdentity(i.FastPackageReference, i.Name, i.Version, i.VersionScheme, i.Summary, i.Source, i.SearchKey, i.FullPath, i.PackageFilename); if (request.IsCanceled) { installing.Cancel(); } else { request.Verbose(Resources.Messages.SuccessfullyInstalled, "{0}.{1}".format(packageJson.Name, packageJson.Version)); //load provider if (packageJson.IsPackageProvider) { //Per provider development guidance: provider name and module name should be the same otherwise we can not import it. request.PackageManagementService.ImportPackageProvider(request, packageJson.Name, null, null, null, isRooted: false, force: false); } } packagesReceived++; } request.Verbose(Resources.Messages.NumberOfPackagesRecevied, packagesReceived, provider.Name, "install-package"); }
/// <summary> /// Removes/Unregisters a package source /// </summary> /// <param name="name">The name or location of a package source to remove.</param> /// <param name="request">An object passed in from the PackageManagement that contains functions that can be used to interact with its Provider</param> public void RemovePackageSource(string name, PackageSourceListRequest request) { if (request == null) { throw new ArgumentNullException("request"); } if (!ValidatePackageManagementVersion(request)) { return; } request.Debug(Resources.Messages.DebugInfoCallMethod, PackageProviderName, "RemovePackageSource"); var src = request.FindRegisteredSource(name); if (src == null) { request.Warning(Constants.Messages.UnableToResolveSource, Constants.ProviderName, name); return; } request.RemovePackageSource(src.Name); request.YieldPackageSource(src.Name, src.Location, src.Trusted, false, src.IsValidated); }