Example #1
0
 public override void WarnBeforeResponsivenessCancellation()
 {
     if (CanCallHost)
     {
         _hostApi.Warning((GetMessageString(Constants.Messages.ProviderNotResponsive, null) ?? "Provider '{0}' is not respecting the responsiveness threshold in a timely fashion; Canceling request.").format(Provider.ProviderName));
     }
 }
Example #2
0
        public IAsyncEnumerable <SoftwareIdentity> InstallPackage(SoftwareIdentity softwareIdentity, IHostApi requestObject)
        {
            if (requestObject == null)
            {
                throw new ArgumentNullException("requestObject");
            }

            if (softwareIdentity == null)
            {
                throw new ArgumentNullException("softwareIdentity");
            }

            // if the provider didn't say this was trusted, we should ask the user if it's ok.
            if (!softwareIdentity.FromTrustedSource)
            {
                try {
                    if (!requestObject.ShouldContinueWithUntrustedPackageSource(softwareIdentity.Name, softwareIdentity.Source))
                    {
                        requestObject.Warning(requestObject.FormatMessageString(Constants.Messages.UserDeclinedUntrustedPackageInstall, softwareIdentity.Name));
                        return(new EmptyAsyncEnumerable <SoftwareIdentity>());
                    }
                } catch {
                    return(new EmptyAsyncEnumerable <SoftwareIdentity>());
                }
            }

            return(new SoftwareIdentityRequestObject(this, requestObject ?? new object().As <IHostApi>(), request => Provider.InstallPackage(softwareIdentity.FastPackageReference, request), Constants.PackageStatus.Installed));
        }
        public IEnumerable <PackageProvider> SelectProviders(string providerName, IHostApi hostApi)
        {
            if (!string.IsNullOrWhiteSpace(providerName))
            {
                // match with wildcards
                var results = _packageProviders.Values.Where(each => each.ProviderName.IsWildcardMatch(providerName)).ReEnumerable();
                if (results.Any())
                {
                    return(results);
                }
                if (hostApi != null && !providerName.ContainsWildcards())
                {
                    // if the end user requested a provider that's not there. perhaps the bootstrap provider can find it.
                    if (RequirePackageProvider(null, providerName, Constants.MinVersion, hostApi))
                    {
                        // seems to think we found it.
                        if (_packageProviders.ContainsKey(providerName))
                        {
                            return(_packageProviders[providerName].SingleItemAsEnumerable());
                        }
                    }

                    // warn the user that that provider wasn't found.
                    hostApi.Warning(hostApi.FormatMessageString(Constants.Messages.UnknownProvider, providerName));
                }
                return(Enumerable.Empty <PackageProvider>());
            }

            return(PackageProviders);
        }
Example #4
0
 public bool Warning(string messageText)
 {
     if (CanCallHost)
     {
         return(_hostApi.Warning(messageText));
     }
     return(true);
 }
        internal static IHostApi ProviderSpecific(this IHostApi parent, PackageProvider provider)
        {
            var thisProviderIsCanceled = false;

            return(new object[] {
                new {
                    Error = new Func <string, string, string, string, bool>((id, cat, targetobjectvalue, messageText) => {
                        // turn errors into warnings when we're working in parallel
                        parent.Warning(messageText);

                        thisProviderIsCanceled = true;
                        // tell the provider that yeah, this request is canceled.
                        return thisProviderIsCanceled;
                    }),

                    GetIsCanceled = new Func <bool>(() => parent.IsCanceled || thisProviderIsCanceled)
                },
                parent,
            }.As <IHostApi>());
        }
Example #6
0
 public bool Warning(string messageText)
 {
     return(_hostApi.Warning(messageText));
 }
        private IEnumerable<PackageProvider> ImportPackageProviderViaPath(IHostApi request, string providerName) {
            var extension = Path.GetExtension(providerName);
            if (extension != null && extension.Equals(".dll")) {
                //TODO need to check if the assembly is from the known designated folder

               // List<string> knownAssemblyFolders = new List<string>();
                //todo: get the current ps module folder instead of program files
                //todo build a internal asemlby table for Get-packageprovider to display.
                //todo: PackageProviderItem: providername, version, path, loaded, type (PS or dll), providerobject sorted by loaded

                var exist = AutoloadedAssemblyLocations.Where(each => each.Equals(Path.GetDirectoryName(providerName))).Any();

                
                //if (knownAssemblyFolders.Contains(Path.GetDirectoryName(providerName))) {
                if (exist)
                {
                    //If so, load it.
                    var loaded = LoadProviderAssembly(request, providerName);
                    if (loaded)
                    {
                        request.Verbose("loaded successfully");
                        //TODO  not need to be so sily, reference to the key of master list is enough
                        yield return _packageProviders[Path.GetFileNameWithoutExtension(providerName)];
                        //return SelectProviders(Path.GetFileNameWithoutExtension(providerName), request);
                    }

                    request.Warning(string.Format("cannot load assembly '{0}'. you need to add your assembly here...", providerName));
                    yield return null;
                }
                else
                {
                    request.Warning(string.Format("The specified provider '{0}' was not loaded because no valid provider file was found", providerName));
                }
                
            }

            //deal with modules with full path
            var powerShellMetaProvider = GetMetaProviderObject(request);
            if (powerShellMetaProvider == null)
            {
                yield return null;
            }

            //load the proviver
            //TODO firstordefault
            yield return ImportProvider(request, providerName, powerShellMetaProvider);
        }
        //TODO Name, Version,....
        public IEnumerable<PackageProvider> ImportPackageProvider(IHostApi request, string providerName, bool isPathRooted) {
            if (providerName.IsNullOrEmpty())
            {
                return Enumerable.Empty<PackageProvider>();
            }

            //foreach (var name in providerNames) {
                //check if it;s loaded.
            var results = _packageProviders.Values.Where(each => each.ProviderName.IsWildcardMatch(providerName)).ReEnumerable();

            if (results.Any())
            {
                //the provider is already loaded and tracked in the loaded master list: _packageProviders 
                request.Verbose(string.Format("The provider '{0}' has already been imported.", providerName));
                return Enumerable.Empty<PackageProvider>();
                
            }

                if (isPathRooted)
                {
                    if (File.Exists(providerName))
                    {
                        // looks like we have something that could definitely be a
                        // a module path.
                        //yield return new KeyValuePair<string, string>(fullPath, (moduleVersion ?? new Version(0, 0)).ToString());
                        return ImportPackageProviderViaPath(request, providerName);
                    } else {
                        //error out
                        request.Warning(String.Format("{0} is not found", providerName));
                    }
                } else {
                     return ImportPackageProviderViaName(request, providerName);
                }
                // return providerNames.SelectMany(each => ImportPackageProvider(request, each));
           // }
            return Enumerable.Empty<PackageProvider>();

        }
        //Scan through the well-known providerAssemblies folder to find the providers that met the condition.
        internal IEnumerable<string> ScanAllProvidersFromProviderAssembliesLocation(
            IHostApi request,
            string providerName,
            Version requiredVersion,
            Version minimumVersion,
            Version maximumVersion,
            ProviderOption providerOption = ProviderOption.LatestVersion) {

            //if provider is installed in providername\version format
            var providerFolder = ProviderAssembliesLocation.Distinct(new PathEqualityComparer(PathCompareOption.Full)).SelectMany(Directory.EnumerateDirectories);

            foreach (var providerNameFolder in providerFolder) {

                var name = Path.GetFileName(providerNameFolder);

                //check the providername folder
                if (!string.IsNullOrWhiteSpace(providerName)) {

                    if (string.IsNullOrWhiteSpace(providerNameFolder)) {
                        continue;
                    }
                   
                    if (string.IsNullOrWhiteSpace(name) || !name.IsWildcardMatch(providerName)) {
                        continue;
                    }
                }

                var selectedVersions = Directory.EnumerateDirectories(providerNameFolder).Select(versionFolder => {
                    //check if the version is in a valid format. Ver will be 0 if TryParse fails and it won't be selected
                    Version ver;
                    if (System.Version.TryParse(Path.GetFileName(versionFolder), out ver)) {
                        return new {
                            folder = versionFolder,
                            version = (FourPartVersion)ver
                        };
                    }
                    return null;
                }).Where(each => each != null && each.version > 0L);

                selectedVersions = selectedVersions.Where(eachVersion => {
                    if ((requiredVersion == null) || eachVersion.version == (FourPartVersion)requiredVersion) {
                        if ((minimumVersion == null) || eachVersion.version >= (FourPartVersion)minimumVersion) {
                            if ((maximumVersion == null) || eachVersion.version <= (FourPartVersion)maximumVersion) {
                                return true;
                            }
                        }
                    }
                    return false;
                });

                //Get the version folders
                var versionFolders = (providerOption == ProviderOption.AllProvider) ?
                    selectedVersions.Select(each => each.folder).Where(Directory.Exists) :
                    new[] {selectedVersions.OrderByDescending(each => each.version).Select(each => each.folder).FirstOrDefault(Directory.Exists)};

                foreach (var assemblyFolder in versionFolders.WhereNotNull()) {
                    //we reached the provider assembly file path now

                    var files = Directory.EnumerateFiles(assemblyFolder)
                        .Where(file => (file != null) && (Path.GetExtension(file).EqualsIgnoreCase(".dll") || Path.GetExtension(file).EqualsIgnoreCase(".exe"))).ToArray();

                    //if found more than one dll is installed under a version folder, this is not allowed. warning here as enumerating for providers should continue
                    if (files.Any() && files.Count() > 1) {
                        request.Warning(string.Format(CultureInfo.CurrentCulture, Resources.Messages.SingleAssemblyAllowed, files.JoinWithComma()));
                        continue;
                    }
                    // find modules that have the provider manifests
                    var filelist = files.Where(each => Manifest.LoadFrom(each).Any(manifest => Swidtag.IsSwidtag(manifest) && new Swidtag(manifest).IsApplicable(new Hashtable())));

                    if (!filelist.Any()) {
                        continue;
                    }
                    var version = Path.GetFileName(assemblyFolder);
                    var defaultPkgProvider = new DefaultPackageProvider(name, version);
                    var providerPath = files.FirstOrDefault();

                    var pkgProvider = new PackageProvider(defaultPkgProvider)
                    {
                        ProviderPath = providerPath,
                        Version = version,
                        IsLoaded = false
                    };

                    AddToProviderCacheTable(name, pkgProvider);
                    yield return providerPath;
                }
            }

            //check if assembly is installed at the top leverl folder.
            var providerFiles = ProviderAssembliesLocation.Distinct(new PathEqualityComparer(PathCompareOption.Full)).SelectMany(Directory.EnumerateFiles)
                .Where(each => each.FileExists() && (Path.GetExtension(each).EqualsIgnoreCase(".dll") || Path.GetExtension(each).EqualsIgnoreCase(".exe"))).ReEnumerable();

            // found the assemblies at the top level folder.
            // if a user is looking for a specific version & provider name, we are not be able to know the provider name or version without loading it.
            // Thus, for the top level providers, we just need to load them for the backward compatibility. 
            if (providerFiles.Any()) {
                request.Verbose(string.Format(CultureInfo.CurrentCulture, Resources.Messages.ProviderNameAndVersionNotAvailableFromFilePath, providerFiles.JoinWithComma()));
                foreach (var provider in providerFiles) {
                    //the provider is installed at the top level.

                    // find modules that have the provider manifests
                    if (Manifest.LoadFrom(provider).Any(manifest => Swidtag.IsSwidtag(manifest) && new Swidtag(manifest).IsApplicable(new Hashtable()))) {

                        yield return provider;
                    }
                }
            }
        }
        public IEnumerable<PackageProvider> SelectProviders(string providerName, IHostApi hostApi)
        {
            if (!string.IsNullOrWhiteSpace(providerName)) {
                // match with wildcards
                var results = _packageProviders.Values.Where(each => each.ProviderName.IsWildcardMatch(providerName)).ReEnumerable();
                if (results.Any()) {
                    return results;
                }
                if (hostApi != null && !providerName.ContainsWildcards()) {
                    // if the end user requested a provider that's not there. perhaps the bootstrap provider can find it.
                    if (RequirePackageProvider(null, providerName, Constants.MinVersion, hostApi)) {
                        // seems to think we found it.
                        if (_packageProviders.ContainsKey(providerName)) {
                            return _packageProviders[providerName].SingleItemAsEnumerable();
                        }
                    }

                    // warn the user that that provider wasn't found.
                    hostApi.Warning(hostApi.FormatMessageString(Constants.Messages.UnknownProvider, providerName));
                }
                return Enumerable.Empty<PackageProvider>();
            }

            return PackageProviders;
        }