protected override void ProcessPackage(PackageProvider provider, IEnumerable<string> searchKey, SoftwareIdentity package) { try { base.ProcessPackage(provider, searchKey, package); // return the object to the caller now. WriteObject(package); if (IncludeDependencies) { var missingDependencies = new HashSet<string>(); foreach (var dep in package.Dependencies) { // note: future work may be needed if the package sources currently selected by the user don't // contain the dependencies. var dependendcies = PackageManagementService.FindPackageByCanonicalId(dep, this); var depPkg = dependendcies.OrderByDescending(pp => pp, SoftwareIdentityVersionComparer.Instance).FirstOrDefault(); if (depPkg == null) { missingDependencies.Add(dep); Warning(Constants.Messages.UnableToFindDependencyPackage, dep); } else { ProcessPackage(depPkg.Provider, searchKey.Select(each => each + depPkg.Name).ToArray(), depPkg); } } if (missingDependencies.Any()) { Error(Constants.Errors.UnableToFindDependencyPackage, missingDependencies.JoinWithComma()); } } } catch (Exception ex) { Debug("Calling ProcessPackage {0}", ex.ToString()); } }
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>(); }
protected override void ProcessPackage(PackageProvider provider, IEnumerable <string> searchKey, SoftwareIdentity package) { Debug("Calling ProcessPackage SearchKey = '{0}' and provider name ='{1}'", searchKey, package.ProviderName); try { base.ProcessPackage(provider, searchKey, package); // output to console WriteObject(AddPropertyToSoftwareIdentity(package)); if (IncludeDependencies) { var missingDependencies = new HashSet <string>(); foreach (var dep in package.Dependencies) { var dependendcies = PackageManagementService.FindPackageByCanonicalId(dep, this); var depPkg = dependendcies.OrderByDescending(pp => pp, SoftwareIdentityVersionComparer.Instance).FirstOrDefault(); if (depPkg == null) { missingDependencies.Add(dep); Warning(Constants.Messages.UnableToFindDependencyPackage, dep); } else { ProcessPackage(depPkg.Provider, searchKey.Select(each => each + depPkg.Name).ToArray(), depPkg); } } if (missingDependencies.Any()) { Error(Constants.Errors.UnableToFindDependencyPackage, missingDependencies.JoinWithComma()); } } } catch (Exception ex) { Debug("Calling ProcessPackage {0}", ex.Message); } }
public PreferencesUI(PackageProvider packageProvider) { _packageProvider = packageProvider; }
private void ProcessRequests(PackageProvider[] providers) { if (providers == null || providers.Length == 0) { return; } var requests = providers.SelectMany(pv => { Verbose(Resources.Messages.SelectedProviders, pv.ProviderName); // for a given provider, if we get an error, we want just that provider to stop. var host = GetProviderSpecificOption(pv); var a = _uris.Select(uri => new { query = new List<string> { uri.AbsolutePath }, provider = pv, packages = pv.FindPackageByUri(uri, host).CancelWhen(CancellationEvent.Token) }); var b = _files.Keys.Where(file => pv.IsSupportedFile(_files[file].Item2)).Select(file => new { query = _files[file].Item1, provider = pv, packages = pv.FindPackageByFile(file, host) }); var c = _names.Select(name => new { query = new List<string> { name }, provider = pv, packages = pv.FindPackage(name, RequiredVersion, MinimumVersion, MaximumVersion, host) }); return a.Concat(b).Concat(c); }).ToArray(); Debug("Calling SearchForPackages After Select {0}", requests.Length); if (AllVersions || !SpecifiedMinimumOrMaximum) { // the user asked for every version or they didn't specify any version ranges // either way, that means that we can just return everything that we're finding. while (WaitForActivity(requests.Select(each => each.packages))) { // keep processing while any of the the queries is still going. foreach (var result in requests.Where(each => each.packages.HasData)) { // look only at requests that have data waiting. foreach (var package in result.packages.GetConsumingEnumerable()) { // process the results for that set. // check if the package is a provider package. If so we need to filter on the packages for the providers. if (EnsurePackageIsProvider(package)) { ProcessPackage(result.provider, result.query, package); } } } requests = requests.FilterWithFinalizer(each => each.packages.IsConsumed, each => each.packages.Dispose()).ToArray(); } } else { // now this is where it gets a bit funny. // the user specified a min or max // and so we have to only return the highest one in the set for a given package. while (WaitForActivity(requests.Select(each => each.packages))) { // keep processing while any of the the queries is still going. foreach (var perProvider in requests.GroupBy(each => each.provider)) { foreach (var perQuery in perProvider.GroupBy(each => each.query)) { if (perQuery.All(each => each.packages.IsCompleted && !each.packages.IsConsumed)) { foreach (var pkg in from p in perQuery.SelectMany(each => each.packages.GetConsumingEnumerable()) group p by new { p.Name, p.Source } // for a given name into grouping // get the latest version only select grouping.OrderByDescending(pp => pp, SoftwareIdentityVersionComparer.Instance).First()) { if (EnsurePackageIsProvider(pkg)) { ProcessPackage(perProvider.Key, perQuery.Key, pkg); } } } } } // filter out whatever we're done with. requests = requests.FilterWithFinalizer(each => each.packages.IsConsumed, each => each.packages.Dispose()).ToArray(); } } // dispose of any requests that didn't get cleaned up earlier. foreach (var i in requests) { i.packages.Dispose(); } }
public QueryTracker(PackageProvider packageProvider, ILogger <QueryTracker> logger, QueryItemRepository queryItemRepository) { _logger = logger; _queryItemRepository = queryItemRepository; _packageProvider = packageProvider; }
private PackageProvider AnalyzeModule(PsRequest request, string modulePath, Version requiredVersion, bool force, bool logWarning =true, PSModuleInfo psModuleInfo = null) { if (string.IsNullOrWhiteSpace(modulePath)) { return null; } request.Debug("Attempting to load PowerShell Provider Module [{0}]", modulePath); if (string.Equals(Path.GetExtension(modulePath), ".dll", StringComparison.OrdinalIgnoreCase)) { if (psModuleInfo != null) { // fake provider and returns it var result = new PackageProvider(new DefaultPackageProvider(psModuleInfo.Name, psModuleInfo.Version.ToString())) { ProviderPath = modulePath, Version = psModuleInfo.Version, IsLoaded = false }; AddToPackageProviderCacheTable(result); return result; } else { // psmoduleinfo is only null when this function is called in loadavailableprovider // but in that case we want to load the provider directly anyway so we can do this // if the path is a .dll then we ask packagemanagement to load it for us // it will also register the dll PackageManagementService.LoadProviderAssembly(request, modulePath, true); // now let's checked whether we can find it in the list of loaded providers foreach (var loadedProvider in PackageManagementService.PackageProviders) { // the one loaded should have the same path if (string.Equals(loadedProvider.ProviderPath, modulePath, StringComparison.OrdinalIgnoreCase)) { return loadedProvider; } } // if we reached here then we have failed to load the provider :( return null; } } string requiredVersionString = requiredVersion.ToString(); var provider = Create(request, modulePath, requiredVersionString, force, logWarning); if (provider != null) { var providerName = provider.GetPackageProviderName(); if (!string.IsNullOrWhiteSpace(providerName)) { request.Debug(string.Format(CultureInfo.CurrentCulture, Resources.Messages.SuccessfullyLoadedModule, modulePath)); // looks good to me, let's add this to the list of modules this meta provider can create. var packageProvider = new PackageProvider(provider.As<IPackageProvider>()) { IsLoaded = true, Version = provider.GetProviderVersion(), ProviderPath = modulePath }; // take out powershell get var psgetprovider = PackageManagementService.PackageProviders.FirstOrDefault(pv => string.Equals(pv.ProviderName, PowerShellGet, StringComparison.OrdinalIgnoreCase)); if (psModuleInfo != null) { // add swidtag information using moduleinfo // however, this won't give us as much information yet // we may have to fill this up later ProvideSwidTagInformation(packageProvider, psModuleInfo); } AddToPackageProviderCacheTable(packageProvider); _availableProviders.AddOrSet(providerName, provider); return packageProvider; } else { provider.Dispose(); provider = null; request.Debug(string.Format(CultureInfo.CurrentCulture, Resources.Messages.ProviderNameIsNullOrEmpty, modulePath)); } } return null; }
private void AddToPackageProviderCacheTable(PackageProvider provider) { PackageManagementService.AddToProviderCacheTable(provider.ProviderName, provider); }
private PackageProvider AnalyzeModule(PsRequest request, string modulePath, Version requiredVersion, bool force, PSModuleInfo psModuleInfo = null) { if (string.IsNullOrWhiteSpace(modulePath)) { return(null); } request.Debug("Attempting to load PowerShell Provider Module [{0}]", modulePath); if (string.Equals(Path.GetExtension(modulePath), ".dll", StringComparison.OrdinalIgnoreCase)) { if (psModuleInfo != null) { // fake provider and returns it var result = new PackageProvider(new DefaultPackageProvider(psModuleInfo.Name, psModuleInfo.Version.ToString())) { ProviderPath = modulePath, Version = psModuleInfo.Version, IsLoaded = false }; AddToPackageProviderCacheTable(result); return(result); } else { // psmoduleinfo is only null when this function is called in loadavailableprovider // but in that case we want to load the provider directly anyway so we can do this // if the path is a .dll then we ask packagemanagement to load it for us // it will also register the dll PackageManagementService.LoadProviderAssembly(request, modulePath, true); // now let's checked whether we can find it in the list of loaded providers foreach (var loadedProvider in PackageManagementService.PackageProviders) { // the one loaded should have the same path if (string.Equals(loadedProvider.ProviderPath, modulePath, StringComparison.OrdinalIgnoreCase)) { return(loadedProvider); } } // if we reached here then we have failed to load the provider :( return(null); } } string requiredVersionString = requiredVersion.ToString(); var provider = Create(request, modulePath, requiredVersionString, force); if (provider != null) { var providerName = provider.GetPackageProviderName(); if (!string.IsNullOrWhiteSpace(providerName)) { request.Debug(string.Format(CultureInfo.CurrentCulture, Resources.Messages.SuccessfullyLoadedModule, modulePath)); // looks good to me, let's add this to the list of moduels this meta provider can create. var packageProvider = new PackageProvider(provider.As <IPackageProvider>()) { IsLoaded = true, Version = provider.GetProviderVersion(), ProviderPath = modulePath }; // take out powershell get var psgetprovider = PackageManagementService.PackageProviders.FirstOrDefault(pv => string.Equals(pv.ProviderName, PowerShellGet, StringComparison.OrdinalIgnoreCase)); if (psModuleInfo != null) { // add swidtag information using moduleinfo // however, this won't give us as much information yet // we may have to fill this up later ProvideSwidTagInformation(packageProvider, psModuleInfo); } AddToPackageProviderCacheTable(packageProvider); _availableProviders.AddOrSet(providerName, provider); return(packageProvider); } else { provider.Dispose(); provider = null; request.Debug(string.Format(CultureInfo.CurrentCulture, Resources.Messages.ProviderNameIsNullOrEmpty, modulePath)); } } return(null); }
protected override void ProcessPackage(PackageProvider provider, IEnumerable<string> searchKey, SoftwareIdentity package) { base.ProcessPackage(provider, searchKey, package); var savePath = SaveFileName(package.PackageFilename); if (savePath.FileExists()) { if (Force) { savePath.TryHardToDelete(); if (savePath.FileExists()) { Error(Constants.Errors.UnableToOverwrite, savePath); return; } } else { Error(Constants.Errors.PackageFileExists, savePath); return; } } // if we have a valid path, make a local copy of the file. if (!string.IsNullOrWhiteSpace(savePath)) { if (ShouldProcess(savePath, Constants.Messages.SavePackage).Result) { provider.DownloadPackage(package, SaveFileName(savePath), this.ProviderSpecific(provider)).Wait(); if (File.Exists(savePath)) { package.FullPath = savePath; } } // return the object to the caller. WriteObject(package); } }
/// <summary> /// Initializes the plugin and loads its assembly but does not start it. /// To start the plugin use <see cref="Start"/> /// </summary> internal void Initialize() { Bridge.Logger.Info("Loading plugin on path \"{PATH}\"...", Path); Server = new Server(this); EntryPoints = new List <EntryPoint>(); _assembly = PluginManager.Context.Load(Path); if (_assembly == null) { ChangePluginState(PluginState.Failed); Bridge.Logger.Fatal( "Could not finish the load process of the plugin on path \"{PATH}\": An assembly is already loaded in the context!", Path); return; } foreach (Type type in _assembly.GetExportedTypes()) { if (PluginType.IsAssignableFrom(type)) { PluginMeta meta = type.GetCustomAttribute <PluginMeta>(); if (meta == null) { ChangePluginState(PluginState.Failed); Bridge.Logger.Fatal( "Onsharp found a plugin class {CLASS} in the plugin on path \"{PATH}\" which does not have a meta descriptor!", type.FullName, Path); return; } if (string.Equals(meta.Id, "native", StringComparison.CurrentCultureIgnoreCase)) { Bridge.Logger.Fatal( "Onsharp found a plugin class {CLASS} in the plugin on path \"{PATH}\" which has native as plugin id which is not allowed!", type.FullName, Path); return; } AutoUpdaterAttribute updateAttribute = type.GetCustomAttribute <AutoUpdaterAttribute>(); if (updateAttribute != null) { UpdatingData = AutoUpdater.RetrieveData(updateAttribute.Url); if (meta.Version == UpdatingData.Version) { UpdatingData = null; } } Plugin = TryCreatePlugin(type); if (Plugin != null) { Plugin.Meta = meta; Plugin.FilePath = Path; Plugin.Data = new DataStorage(Plugin); Plugin.Logger = new Logger(Plugin.Display, meta.IsDebug); Plugin.State = PluginState.Unknown; EntryPoints.Add(Plugin); PackageProvider = TryCreatePackageProvider(meta.PackageProvider); if (PackageProvider == null) { continue; } PackageProvider.Author ??= meta.Author; PackageProvider.Version ??= meta.Version; PackageProvider.Name ??= Plugin.Display; PackageProvider.Name = Regex.Replace(PackageProvider.Name, "[^0-9A-Za-z]", ""); } else { ChangePluginState(PluginState.Failed); Bridge.Logger.Fatal( "Onsharp tried to instantiate the plugin class {CLASS} in the plugin on path \"{PATH}\" but failed! Does the class have a default constructor?", type.FullName, Path); return; } } else if (EntryPointType.IsAssignableFrom(type)) { EntryPoint entryPoint = (EntryPoint)Activator.CreateInstance(type); if (entryPoint == null) { Bridge.Logger.Fatal( "Could not instantiate the entry class {CLASS} in the plugin on path \"{PATH}\"! Does it has a default constructor?", type.FullName, Path); continue; } EntryPoints.Add(entryPoint); } } if (Plugin == null) { ChangePluginState(PluginState.Failed); Bridge.Logger.Fatal( "Could not finish the load process of the plugin on path \"{PATH}\": There is no valid plugin main class!", Path); return; } if (Plugin.Meta.ApiVersion < Bridge.ApiVersion) { ChangePluginState(PluginState.Failed); Bridge.Logger.Fatal( "The plugin failed on the api version check! The plugin {PLUGIN} uses the api v{V1} but your runtime runs with v{VR}, the runtime version is too new!", Plugin.Display, Plugin.Meta.ApiVersion, Bridge.ApiVersion); return; } I18n = Plugin.Meta.I18n == I18n.Mode.Disabled ? null : new I18n(Plugin.Logger, _assembly, Plugin); Server.Inject(); foreach (EntryPoint entryPoint in EntryPoints) { entryPoint.Server = Server; entryPoint.PluginManager = Bridge.PluginManager; entryPoint.I18n = I18n; entryPoint.Runtime = Bridge.Runtime; entryPoint.Runtime.RegisterConsoleCommands(entryPoint, Plugin.Meta.Id); entryPoint.Server.RegisterExportable(entryPoint); entryPoint.Server.RegisterRemoteEvents(entryPoint); entryPoint.Server.RegisterServerEvents(entryPoint); entryPoint.Server.RegisterCommands(entryPoint); } ChangePluginState(PluginState.Loaded); }
/// <summary> /// Сконфигурировать чекер. /// </summary> /// <param name="checker">Чекер.</param> public static void Configure(this ICodeChecker checker) { var section = (AgentConfigurationSection)ConfigurationManager.GetSection("agent"); log.Trace("Загрузка контекста приложения"); var applicationContextFactory = new ApplicationContextFactory(); checker.ContextManager.Load(applicationContextFactory); log.Trace("Загрузка контекста разработки"); var developmentContextFactory = new DevelopmentContextFactory(); foreach (ContextProviderElement element in section.ContextProviders) { switch (element.Provider) { case ContextProviderType.Package: log.Trace($"Найден загрузчик контекста из пакета {element.FilePath}"); var packageProvider = new PackageProvider(element.FilePath); developmentContextFactory.Providers.Add(packageProvider); break; case ContextProviderType.Database: log.Trace($"Найден загрузчик контекста из базы данных {element.ConnectionString}"); var databaseProvider = new DatabaseProvider(element.ConnectionString); developmentContextFactory.Providers.Add(databaseProvider); break; case ContextProviderType.Folder: log.Trace($"Найден загрузчик контекста из папки {element.FolderPath}"); var folderProvider = new FolderProvider(element.FolderPath); developmentContextFactory.Providers.Add(folderProvider); break; } } checker.ContextManager.Load(developmentContextFactory); log.Trace("Загрузка сборок с правилами анализа"); if (!string.IsNullOrEmpty(section.RuleLibraryPath)) { checker.RuleManager.LoadLibraries(section.RuleLibraryPath); } log.Trace("Загрузка генераторов отчетов"); if (section.ReportPrinters != null) { foreach (ReportPrinterElement element in section.ReportPrinters) { switch (element.Printer) { case ReportPrinterType.Console: var consoleReportPrinter = new ConsoleReportPrinter(); checker.ReportManager.Printers.Add(consoleReportPrinter); break; case ReportPrinterType.CSV: var csvReportPrinter = new CsvReportPrinter(element.FilePath); checker.ReportManager.Printers.Add(csvReportPrinter); break; } } } }
public DocumentUi(PackageProvider packageProvider, DbConnectionProvider dbConnectionProvider) { _packageProvider = packageProvider; _dbConnectionProvider = dbConnectionProvider; }
protected override void ProcessPackage(PackageProvider provider, IEnumerable<string> searchKey, SoftwareIdentity package) { // if provider does not implement downloadpackage throw error saying that save-package is not implemented by provider if (!provider.IsMethodImplemented("DownloadPackage")) { Error(Constants.Errors.MethodNotImplemented, provider.ProviderName, "Save-Package"); } base.ProcessPackage(provider, searchKey, package); // if we do save-package jquery -path C:\test then savepath would be C:\test var savePath = SaveFileName(package.PackageFilename); bool mainPackageDownloaded = false; if (!string.IsNullOrWhiteSpace(savePath)) { // let the provider handles everything if (ShouldProcess(savePath, FormatMessageString(Resources.Messages.SavePackage)).Result) { foreach (var downloadedPkg in provider.DownloadPackage(package, savePath, this.ProviderSpecific(provider)).CancelWhen(CancellationEvent.Token)) { if (IsCanceled) { Error(Constants.Errors.ProviderFailToDownloadFile, downloadedPkg.PackageFilename, provider.ProviderName); return; } // check whether main package is downloaded; if (string.Equals(downloadedPkg.CanonicalId, package.CanonicalId, StringComparison.OrdinalIgnoreCase)) { mainPackageDownloaded = true; } WriteObject(downloadedPkg); } } } if (!mainPackageDownloaded) { Error(Constants.Errors.ProviderFailToDownloadFile, package.PackageFilename, provider.ProviderName); return; } }
protected virtual void ProcessPackage(PackageProvider provider, IEnumerable<string> searchKey, SoftwareIdentity package) { foreach (var key in searchKey) { _resultsPerName.GetOrSetIfDefault(key, () => new List<SoftwareIdentity>()).Add(package); } }
protected virtual IHostApi GetProviderSpecificOption(PackageProvider pv) { return this.ProviderSpecific(pv); }
protected override IHostApi GetProviderSpecificOption(PackageProvider pv) { var host = this.ProviderSpecific(pv); var host1 = host; //add filterontag for finding providers. Provider keys are: PackageManagment and Providers host = host.Extend<IRequest>( new { GetOptionValues = new Func<string, IEnumerable<string>>(key => { if (key.EqualsIgnoreCase(FilterOnTag)) { return ProviderFilters; } return host1.GetOptionValues(key); }), }); return host; }
protected virtual void ProcessPackage(PackageProvider provider, string searchKey, SoftwareIdentity package) { _resultsPerName.GetOrSetIfDefault(searchKey, () => new List <SoftwareIdentity>()).Add(package); }
/// <summary> /// Draw the Automatic Updates section of settings. /// </summary> /// <param name="settings">Serialized <see cref="GDXConfig" /> object to be modified.</param> public static void AutomaticUpdates(SerializedObject settings) { const string sectionID = "GDX.Editor.UpdateProvider"; GUI.enabled = true; bool packageSectionEnabled = Layout.CreateSettingsSection( sectionID, true, "Automatic Package Updates", null, settings.FindProperty("updateProviderCheckForUpdates"), Content.AutomaticUpdatesEnabled); if (!Layout.GetCachedEditorBoolean(sectionID)) { return; } EditorGUILayout.BeginHorizontal(Styles.InfoBoxStyle); if (UpdateProvider.LocalPackage.Definition != null) { GUILayout.BeginVertical(); GUILayout.BeginHorizontal(); GUILayout.Label("Local Version:", EditorStyles.boldLabel, Styles.FixedWidth130LayoutOptions); GUILayout.Label(UpdateProvider.LocalPackage.Definition.version); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("Installation Method:", EditorStyles.boldLabel, Styles.FixedWidth130LayoutOptions); GUILayout.Label(PackageProvider.GetFriendlyName(UpdateProvider.LocalPackage.InstallationMethod)); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); // Handle additional information switch (UpdateProvider.LocalPackage.InstallationMethod) { case PackageProvider.InstallationType.UPMBranch: case PackageProvider.InstallationType.GitHubBranch: case PackageProvider.InstallationType.GitHub: GUILayout.BeginHorizontal(); GUILayout.Label("Source Branch:", EditorStyles.boldLabel, Styles.FixedWidth130LayoutOptions); GUILayout.Label(!string.IsNullOrEmpty(UpdateProvider.LocalPackage.SourceTag) ? UpdateProvider.LocalPackage.SourceTag : "N/A"); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); break; case PackageProvider.InstallationType.UPMTag: case PackageProvider.InstallationType.GitHubTag: GUILayout.BeginHorizontal(); GUILayout.Label("Source Tag:", EditorStyles.boldLabel, Styles.FixedWidth130LayoutOptions); GUILayout.Label(!string.IsNullOrEmpty(UpdateProvider.LocalPackage.SourceTag) ? UpdateProvider.LocalPackage.SourceTag : "N/A"); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); break; case PackageProvider.InstallationType.UPMCommit: case PackageProvider.InstallationType.GitHubCommit: GUILayout.BeginHorizontal(); GUILayout.Label("Source Commit:", EditorStyles.boldLabel, Styles.FixedWidth130LayoutOptions); GUILayout.Label(!string.IsNullOrEmpty(UpdateProvider.LocalPackage.SourceTag) ? UpdateProvider.LocalPackage.SourceTag : "N/A"); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); break; } // Show remote version if we have something to show if (UpdateProvider.UpdatePackageDefinition != null) { GUILayout.BeginHorizontal(); GUILayout.Label("Remote Version:", EditorStyles.boldLabel, Styles.FixedWidth130LayoutOptions); GUILayout.Label(UpdateProvider.UpdatePackageDefinition.version); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); } GUILayout.BeginHorizontal(); GUILayout.Label("Last Checked:", EditorStyles.boldLabel, Styles.FixedWidth130LayoutOptions); GUILayout.Label(UpdateProvider.GetLastChecked().ToString(Localization.LocalTimestampFormat)); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.EndVertical(); // Force things to the right GUILayout.FlexibleSpace(); EditorGUILayout.BeginVertical(); if (UpdateProvider.HasUpdate(UpdateProvider.UpdatePackageDefinition)) { if (GUILayout.Button("Changelog", Styles.ButtonStyle)) { Application.OpenURL("https://github.com/dotBunny/GDX/blob/main/CHANGELOG.md"); } if (UpdateProvider.IsUpgradable()) { if (GUILayout.Button("Update", Styles.ButtonStyle)) { UpdateProvider.AttemptUpgrade(); } } } else { if (GUILayout.Button("Manual Check", Styles.ButtonStyle)) { UpdateProvider.CheckForUpdates(); } } EditorGUILayout.EndVertical(); } else { GUILayout.Label( $"An error occured trying to find the package definition.\nPresumed Root: {UpdateProvider.LocalPackage.PackageAssetPath}\nPresumed Manifest:{UpdateProvider.LocalPackage.PackageManifestPath})", EditorStyles.boldLabel); } EditorGUILayout.EndHorizontal(); // Disable based on if we have this enabled GUI.enabled = packageSectionEnabled; UpdateDayCountSetting = EditorGUILayout.IntSlider(Content.AutomaticUpdatesUpdateDayCount, UpdateDayCountSetting, 1, 31); }
protected override void ProcessPackage(PackageProvider provider, IEnumerable<string> searchKey, SoftwareIdentity package) { ProcessPackage(provider, searchKey, package, IncludeDependencies ? new HashSet<string>() : null); }
public void RefreshProviders(PsRequest request, string providerName, Version requiredVersion, Version minimumVersion, Version maximumVersion) { //find and load the latest versions of the providers if only providerName exists, e.g., get-pp -name or import-pp -name //find and load the particular provider if both providerName and version are provided _psProviderCacheTable.Clear(); EnsurePowerShellInitialized(); if (!string.IsNullOrWhiteSpace(providerName)) { //Get the list of available providers var modules = ScanForModules(request, requiredVersion, minimumVersion, maximumVersion, ProviderOption.AllProvider).ReEnumerable(); var tasks = modules.AsyncForEach(modulePath => AnalyzeModule(request, modulePath.Key, modulePath.Value.Version ?? new Version(0, 0), false)); tasks.WaitAll(); } else { //find all providers but only load the lastest if no name nor version exists, e.g. get-pp -list //Scan for the all available providers var results = ScanForModules(request, null, null, null, ProviderOption.AllProvider).ToArray(); if (!_psProviderCacheTable.Any()) { return; } foreach (var list in _psProviderCacheTable.Values.WhereNotNull()) { var psInfo = list.OrderByDescending(each => each.ProviderVersion).ToArray(); if (!psInfo.Any()) { continue; } PackageProvider pkgProvider = null; for (var index = 0; index < psInfo.Length; index++) { var moduleInfo = psInfo[index]; if (moduleInfo == null) { continue; } //load the provider that has the latest version if (index == 0) { pkgProvider = AnalyzeModule(request, moduleInfo.ProviderPath, moduleInfo.ProviderVersion, false); } else { if (pkgProvider != null) { //the rest of providers under the same module will just create a provider object for the output but not loaded var packageProvider = new PackageProvider(new DefaultPackageProvider(pkgProvider.ProviderName, moduleInfo.ProviderVersion.ToString())) { ProviderPath = moduleInfo.ProviderPath, Version = moduleInfo.ProviderVersion, IsLoaded = false }; AddToPackageProviderCacheTable(packageProvider); } } } } _psProviderCacheTable.Clear(); } }
protected virtual IHostApi GetProviderSpecificOption(PackageProvider pv) { return(this.ProviderSpecific(pv)); }
/// <summary> /// If we cannot use psget to get swidtag information, we will try to fill in some of the information /// </summary> /// <param name="packageProvider"></param> /// <param name="psModuleInfo"></param> private void ProvideSwidTagInformation(PackageProvider packageProvider, PSModuleInfo psModuleInfo) { if (packageProvider == null || psModuleInfo == null) { return; } packageProvider.VersionScheme = "MultiPartNumeric"; Microsoft.PackageManagement.Internal.Packaging.SoftwareMetadata softwareMetadata = new Microsoft.PackageManagement.Internal.Packaging.SoftwareMetadata(); bool changed = false; var type = psModuleInfo.GetType(); // introduced in ps 2.0 if (!string.IsNullOrWhiteSpace(psModuleInfo.Description)) { softwareMetadata.Description = psModuleInfo.Description; changed = true; } // introduced in ps 3.0 if (!string.IsNullOrWhiteSpace(psModuleInfo.Copyright)) { softwareMetadata.AddAttribute("copyright", psModuleInfo.Copyright); changed = true; } // tags is introduced in ps 5.0 var tagsProperty = type.GetProperty("Tags"); bool isV5 = tagsProperty != null; if (isV5) { // introduced in ps 5.0 var tags = tagsProperty.GetValue(psModuleInfo); // check that we have something in tags if (tags is IEnumerable <string> && (tags as IEnumerable <string>).Any()) { softwareMetadata.AddAttribute("tags", string.Join(" ", (tags as IEnumerable <string>).Distinct())); changed = true; } var releaseNotes = type.GetProperty("ReleaseNotes").GetValue(psModuleInfo); // check that we have something in releasenotes if (releaseNotes is string && !string.IsNullOrWhiteSpace(type.GetProperty("ReleaseNotes").GetValue(psModuleInfo) as string)) { softwareMetadata.AddAttribute("tags", string.Join(" ", (tags as IEnumerable <string>).Distinct())); changed = true; } } if (changed) { packageProvider.AddElement(softwareMetadata); } if (isV5) { var iconUri = type.GetProperty("IconUri").GetValue(psModuleInfo); // introduced in ps 5.0 if (iconUri is Uri) { packageProvider.AddLink(iconUri as Uri, "icon"); } var licenseUri = type.GetProperty("LicenseUri").GetValue(psModuleInfo); // introduced in ps 5.0 if (licenseUri is Uri) { packageProvider.AddLink(licenseUri as Uri, "license"); } var projectUri = type.GetProperty("ProjectUri").GetValue(psModuleInfo); // introduced in ps 5.0 if (projectUri is Uri) { packageProvider.AddLink(projectUri as Uri, "project"); } } // introduced in ps 3.0 if (!string.IsNullOrWhiteSpace(psModuleInfo.Author)) { packageProvider.AddEntity(psModuleInfo.Author, null, "author"); } // introduced in ps 3.0 if (!string.IsNullOrWhiteSpace(psModuleInfo.CompanyName)) { packageProvider.AddEntity(psModuleInfo.CompanyName, null, "owner"); } }
protected override void ProcessPackage(PackageProvider provider, IEnumerable<string> searchKey, SoftwareIdentity package) { Debug("Calling ProcessPackage SearchKey = '{0}' and provider name ='{1}'", searchKey, package.ProviderName); try { base.ProcessPackage(provider, searchKey, package); // output to console WriteObject(package); if (IncludeDependencies) { var missingDependencies = new HashSet<string>(); foreach (var dep in package.Dependencies) { var dependendcies = PackageManagementService.FindPackageByCanonicalId(dep, this); var depPkg = dependendcies.OrderByDescending(pp => pp, SoftwareIdentityVersionComparer.Instance).FirstOrDefault(); if (depPkg == null) { missingDependencies.Add(dep); Warning(Constants.Messages.UnableToFindDependencyPackage, dep); } else { ProcessPackage(depPkg.Provider, searchKey.Select(each => each + depPkg.Name).ToArray(), depPkg); } } if (missingDependencies.Any()) { Error(Constants.Errors.UnableToFindDependencyPackage, missingDependencies.JoinWithComma()); } } } catch (Exception ex) { Debug("Calling ProcessPackage {0}", ex.Message); } }
public void RefreshProviders(PsRequest request, string providerName, Version requiredVersion, Version minimumVersion, Version maximumVersion, bool logWarning) { //find and load the latest versions of the providers if only providerName exists, e.g., get-pp -name or import-pp -name //find and load the particular provider if both providerName and version are provided _psProviderCacheTable.Clear(); EnsurePowerShellInitialized(); if (!string.IsNullOrWhiteSpace(providerName)) { //Get the list of available providers var modules = ScanForModules(request, requiredVersion, minimumVersion, maximumVersion, ProviderOption.AllProvider).ReEnumerable(); var tasks = modules.AsyncForEach(modulePath => AnalyzeModule(request, modulePath.Key, modulePath.Value.Version ?? new Version(0, 0), false, logWarning, modulePath.Value)); tasks.WaitAll(); } else { //find all providers but only load the latest if no name nor version exists, e.g. get-pp -list //Scan for the all available providers var results = ScanForModules(request, null, null, null, ProviderOption.AllProvider).ToArray(); if (!_psProviderCacheTable.Any()) { return; } foreach (var list in _psProviderCacheTable.Values.WhereNotNull()) { var psInfo = list.OrderByDescending(each => each.ModuleInfo.Version).ToArray(); if (!psInfo.Any()) { continue; } PackageProvider pkgProvider = null; for (var index = 0; index < psInfo.Length; index++) { var providerItem = psInfo[index]; if (providerItem == null) { continue; } // if the provider is a dll, we will just provide a default provider, assuming the module name will be the name of the provider and add to the cache table (if it is not already loaded) if (string.Equals(Path.GetExtension(providerItem.ProviderPath), ".dll", StringComparison.OrdinalIgnoreCase)) { // check whether it is already loaded or not var loadedProvider = PackageManagementService.PackageProviders.FirstOrDefault(item => string.Equals(item.ProviderPath, providerItem.ProviderPath, StringComparison.OrdinalIgnoreCase)); // only provide default provider if it is not loaded if (loadedProvider == null) { // here moduleinfo.providercategory is the module name. // we are applying the guideline that module name is the same as provider name so we use that as the provider name AddToPackageProviderCacheTable(new PackageProvider(new DefaultPackageProvider(providerItem.ModuleInfo.Name, providerItem.ModuleInfo.Version.ToString())) { ProviderPath = providerItem.ProviderPath, Version = providerItem.ModuleInfo.Version, IsLoaded = false }); } continue; } //load the provider that has the latest version if (pkgProvider == null) { // analyze the module pkgProvider = AnalyzeModule(request, providerItem.ProviderPath, providerItem.ModuleInfo.Version, false, logWarning, providerItem.ModuleInfo); } else { //the rest of providers under the same module will just create a provider object for the output but not loaded var packageProvider = new PackageProvider(new DefaultPackageProvider(pkgProvider.ProviderName, providerItem.ModuleInfo.Version.ToString())) { ProviderPath = providerItem.ProviderPath, Version = providerItem.ModuleInfo.Version, IsLoaded = false }; AddToPackageProviderCacheTable(packageProvider); } } } _psProviderCacheTable.Clear(); } }
private static bool IsVersionMatch(PackageProvider provider, Version requiredVersion, Version minimumVersion, Version maximumVersion) { bool match = true; if (requiredVersion != null) { return (provider.Version == (FourPartVersion)requiredVersion); } else { if (minimumVersion != null) { match = (provider.Version >= (FourPartVersion)minimumVersion); } if (maximumVersion != null) { match = (provider.Version <= (FourPartVersion)maximumVersion); } } return match; }
/// <summary> /// If we cannot use psget to get swidtag information, we will try to fill in some of the information /// </summary> /// <param name="packageProvider"></param> /// <param name="psModuleInfo"></param> private void ProvideSwidTagInformation(PackageProvider packageProvider, PSModuleInfo psModuleInfo) { if (packageProvider == null || psModuleInfo == null) { return; } packageProvider.VersionScheme = "MultiPartNumeric"; Microsoft.PackageManagement.Internal.Packaging.SoftwareMetadata softwareMetadata = new Microsoft.PackageManagement.Internal.Packaging.SoftwareMetadata(); bool changed = false; var type = psModuleInfo.GetType(); // introduced in ps 2.0 if (!string.IsNullOrWhiteSpace(psModuleInfo.Description)) { softwareMetadata.Description = psModuleInfo.Description; changed = true; } // introduced in ps 3.0 if (!string.IsNullOrWhiteSpace(psModuleInfo.Copyright)) { softwareMetadata.AddAttribute("copyright", psModuleInfo.Copyright); changed = true; } // tags is introduced in ps 5.0 var tagsProperty = type.GetProperty("Tags"); bool isV5 = tagsProperty != null; if (isV5) { // introduced in ps 5.0 var tags = tagsProperty.GetValue(psModuleInfo); // check that we have something in tags if (tags is IEnumerable<string> && (tags as IEnumerable<string>).Any()) { softwareMetadata.AddAttribute("tags", string.Join(" ", (tags as IEnumerable<string>).Distinct())); changed = true; } var releaseNotes = type.GetProperty("ReleaseNotes").GetValue(psModuleInfo); // check that we have something in releasenotes if (releaseNotes is string && !string.IsNullOrWhiteSpace(type.GetProperty("ReleaseNotes").GetValue(psModuleInfo) as string)) { softwareMetadata.AddAttribute("tags", string.Join(" ", (tags as IEnumerable<string>).Distinct())); changed = true; } } if (changed) { packageProvider.AddElement(softwareMetadata); } if (isV5) { var iconUri = type.GetProperty("IconUri").GetValue(psModuleInfo); // introduced in ps 5.0 if (iconUri is Uri) { packageProvider.AddLink(iconUri as Uri, "icon"); } var licenseUri = type.GetProperty("LicenseUri").GetValue(psModuleInfo); // introduced in ps 5.0 if (licenseUri is Uri) { packageProvider.AddLink(licenseUri as Uri, "license"); } var projectUri = type.GetProperty("ProjectUri").GetValue(psModuleInfo); // introduced in ps 5.0 if (projectUri is Uri) { packageProvider.AddLink(projectUri as Uri, "project"); } } // introduced in ps 3.0 if (!string.IsNullOrWhiteSpace(psModuleInfo.Author)) { packageProvider.AddEntity(psModuleInfo.Author, null, "author"); } // introduced in ps 3.0 if (!string.IsNullOrWhiteSpace(psModuleInfo.CompanyName)) { packageProvider.AddEntity(psModuleInfo.CompanyName, null, "owner"); } }
internal void AddToProviderCacheTable(string name, PackageProvider provider) { lock (_providerCacheTable) { if (_providerCacheTable.ContainsKey(name)) { var list = _providerCacheTable[name]; var index = list.FindIndex(each => CompareProvider(each, provider)); if (index != -1) { //overwrite the cache only if the provider is loaded but the existing one not loaded if (!list[index].IsLoaded && provider.IsLoaded) { list[index] = provider; } } else { _providerCacheTable[name].Add(provider); } } else { var entry = new List<PackageProvider> { provider }; _providerCacheTable.Add(name, entry); } } }
/// <summary> /// Register the package provider /// </summary> /// <param name="provider">Package provider object</param> /// <param name="asmVersion">assembly version info</param> /// <param name="request"></param> /// <param name="shouldRefreshCache">should refresh the internal provider list</param> /// <returns></returns> private PackageProvider RegisterPackageProvider(IPackageProvider provider, FourPartVersion asmVersion, IHostApi request, bool shouldRefreshCache) { string name = null; try { if (provider == null) { return null; } FourPartVersion ver = provider.GetProviderVersion(); var version = ver == 0 ? asmVersion : ver; name = provider.GetPackageProviderName(); if (string.IsNullOrWhiteSpace(name)) { return null; } // Initialize the provider before locking the collection // that way we're not blocking others on non-deterministic actions. request.Debug("Initializing provider '{0}'".format(name)); provider.InitializeProvider(request.As<IRequest>()); request.Debug("Provider '{0}' Initialized".format(name)); lock (_packageProviders) { //Check if the provider is loaded already. if (_packageProviders.ContainsKey(name)) { //if no -force, do nothing if (!shouldRefreshCache) { request.Verbose(string.Format(CultureInfo.CurrentCulture, Resources.Messages.SkipPreviousProcessedProvider, name)); //add the provider to the list var pkgprovider = new PackageProvider(provider) { Version = version, IsLoaded = true }; AddToProviderCacheTable(name, pkgprovider); return pkgprovider; } else { //looks like -force is used, we need to remove the old provider first. // this won't remove the plugin domain and unload the code yet _packageProviders.Remove(name); } } } request.Debug("Using Package Provider {0}".format(name)); var packageProvider = new PackageProvider(provider) { Version = version }; //initialize the package provider packageProvider.Initialize(request); // addOrSet locks the collection anyway. _packageProviders.AddOrSet(name, packageProvider); packageProvider.IsLoaded = true; request.Debug("The provider '{0}' is imported".format(name)); //add the provider to the list AddToProviderCacheTable(name, packageProvider); return packageProvider; } catch (Exception e) { request.Debug("Provider '{0}' Failed to import".format(name)); e.Dump(); } return null; }
private PackageProvider AnalyzeModule(PsRequest request, string modulePath, Version requiredVersion, bool force) { if (string.IsNullOrWhiteSpace(modulePath)) { return null; } request.Debug("Attempting to load PowerShell Provider Module [{0}]", modulePath); var provider = Create(request, modulePath, requiredVersion.ToString(), force); if (provider != null) { var providerName = provider.GetPackageProviderName(); if (!string.IsNullOrWhiteSpace(providerName)) { request.Debug(string.Format(CultureInfo.CurrentCulture, Resources.Messages.SuccessfullyLoadedModule, modulePath)); // looks good to me, let's add this to the list of moduels this meta provider can create. var packageProvider = new PackageProvider(provider.As<IPackageProvider>()) { IsLoaded = true, Version = provider.GetProviderVersion(), ProviderPath = modulePath }; AddToPackageProviderCacheTable(packageProvider); _availableProviders.AddOrSet(providerName, provider); return packageProvider; } else { provider.Dispose(); provider = null; request.Debug(string.Format(CultureInfo.CurrentCulture, Resources.Messages.ProviderNameIsNullOrEmpty, modulePath)); } } return null; }
private bool CompareProvider(PackageProvider p1, PackageProvider p2) { if (p1 == null && p2 == null) { return true; } if (p1 == null || p2 == null) { return false; } if ((p1.Name != null) && (p1.Name.EqualsIgnoreCase(p2.Name)) && (p1.ProviderName != null && p1.ProviderName.EqualsIgnoreCase(p2.ProviderName) && p1.Version == p2.Version)) { return true; } return false; }
public SearchUi(PackageProvider packageProvider, DbConnectionProvider dbConnectionProvider) { _packageProvider = packageProvider; _dbConnectionProvider = dbConnectionProvider; }
//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; } } } }
protected override void ProcessPackage(PackageProvider provider, IEnumerable <string> searchKey, SoftwareIdentity package) { ProcessPackage(provider, searchKey, package, IncludeDependencies ? new HashSet <string>() : null); }
private PackageProvider RegisterPackageProvider(IPackageProvider provider, string name, FourPartVersion asmVersion, IHostApi request) { // string name = null; try { FourPartVersion ver = provider.GetProviderVersion(); var version = ver == 0 ? asmVersion : ver; //TODO: Need to write a blog file name is the provider name. Provider is no longer required to impl ProvierName property //name = provider.GetPackageProviderName(); //if (String.IsNullOrWhiteSpace(name)) { // return null; //} // Initialize the provider before locking the collection // that way we're not blocking others on non-deterministic actions. request.Debug("Initializing provider '{0}'".format(name)); provider.InitializeProvider(request.As<IRequest>()); request.Debug("Provider '{0}' Initialized".format(name)); lock (_packageProviders) { if (_packageProviders.ContainsKey(name)) { if (version > _packageProviders[name].Version) { // remove the old provider first. // todo: this won't remove the plugin domain and unload the code yet // we'll have to do that later. _packageProviders.Remove(name); } else { return null; } } } request.Debug("Using Package Provider {0}".format(name)); var packageProvider = new PackageProvider(provider) { Version = version, IsLoaded = true }; packageProvider.Initialize(request); // addOrSet locks the collection anyway. _packageProviders.AddOrSet(name, packageProvider); return packageProvider; } catch (Exception e) { request.Debug("Provider '{0}' Failed".format(name)); e.Dump(); } return null; }
public HistoryUi(PackageProvider packageProvider) { _packageProvider = packageProvider; }
protected override void ProcessPackage(PackageProvider provider, IEnumerable<string> searchKey, SoftwareIdentity package) { if (WhatIf) { // grab the dependencies and return them *first* foreach (var dep in package.Dependencies) { // note: future work may be needed if the package sources currently selected by the user don't // contain the dependencies. var dependendcies = PackageManagementService.FindPackageByCanonicalId(dep, this); foreach (var depPackage in dependendcies) { ProcessPackage(depPackage.Provider, searchKey.Select(each => each + depPackage.Name).ToArray(), depPackage); } } } base.ProcessPackage(provider, searchKey, package); }
protected override void ProcessPackage(PackageProvider provider, IEnumerable<string> searchKey, SoftwareIdentity package) { if (WhatIf) { // grab the dependencies and return them *first* bool hasDependencyLoop = false; var dependencies = GetDependenciesToInstall(package, ref hasDependencyLoop); if (!hasDependencyLoop) { foreach (var dependency in dependencies) { base.ProcessPackage(provider, searchKey.Select(each => each+dependency.Name).ToArray(), dependency); } } } base.ProcessPackage(provider, searchKey, package); }
public ObjectExplorerInteraction(PackageProvider packageProvider) { _packageProvider = packageProvider; }
public void RefreshProviders(PsRequest request, string providerName, Version requiredVersion, Version minimumVersion, Version maximumVersion) { //find and load the latest versions of the providers if only providerName exists, e.g., get-pp -name or import-pp -name //find and load the particular provider if both providerName and version are provided _psProviderCacheTable.Clear(); EnsurePowerShellInitialized(); if (!string.IsNullOrWhiteSpace(providerName)) { //Get the list of available providers var modules = ScanForModules(request, requiredVersion, minimumVersion, maximumVersion, ProviderOption.AllProvider).ReEnumerable(); var tasks = modules.AsyncForEach(modulePath => AnalyzeModule(request, modulePath.Key, modulePath.Value.Version ?? new Version(0, 0), false, modulePath.Value)); tasks.WaitAll(); } else { //find all providers but only load the lastest if no name nor version exists, e.g. get-pp -list //Scan for the all available providers var results = ScanForModules(request, null, null, null, ProviderOption.AllProvider).ToArray(); if (!_psProviderCacheTable.Any()) { return; } foreach (var list in _psProviderCacheTable.Values.WhereNotNull()) { var psInfo = list.OrderByDescending(each => each.ModuleInfo.Version).ToArray(); if (!psInfo.Any()) { continue; } PackageProvider pkgProvider = null; for (var index = 0; index < psInfo.Length; index++) { var providerItem = psInfo[index]; if (providerItem == null) { continue; } // if the provider is a dll, we will just provide a default provider, assuming the module name will be the name of the provider and add to the cache table (if it is not already loaded) if (string.Equals(Path.GetExtension(providerItem.ProviderPath), ".dll", StringComparison.OrdinalIgnoreCase)) { // check whether it is already loaded or not var loadedProvider = PackageManagementService.PackageProviders.FirstOrDefault(item => string.Equals(item.ProviderPath, providerItem.ProviderPath, StringComparison.OrdinalIgnoreCase)); // only provide default provider if it is not loaded if (loadedProvider == null) { // here moduleinfo.providercategory is the module name. // we are applying the guideline that module name is the same as provider name so we use that as the provider name AddToPackageProviderCacheTable(new PackageProvider(new DefaultPackageProvider(providerItem.ModuleInfo.Name, providerItem.ModuleInfo.Version.ToString())) { ProviderPath = providerItem.ProviderPath, Version = providerItem.ModuleInfo.Version, IsLoaded = false }); } continue; } //load the provider that has the latest version if (pkgProvider == null) { // analyze the module pkgProvider = AnalyzeModule(request, providerItem.ProviderPath, providerItem.ModuleInfo.Version, false, providerItem.ModuleInfo); } else { //the rest of providers under the same module will just create a provider object for the output but not loaded var packageProvider = new PackageProvider(new DefaultPackageProvider(pkgProvider.ProviderName, providerItem.ModuleInfo.Version.ToString())) { ProviderPath = providerItem.ProviderPath, Version = providerItem.ModuleInfo.Version, IsLoaded = false }; AddToPackageProviderCacheTable(packageProvider); } } } _psProviderCacheTable.Clear(); } }
public DbConnectionProvider(PackageProvider packageProvider) { _packageProvider = packageProvider; }