Esempio n. 1
0
 internal CatalogEntry(
     string[] urlParts,
     string type,
     string commitId,
     DateTimeOffset commitTs,
     string id,
     NuGetVersion version,
     ServiceIndexResourceV3 serviceIndex,
     Func <Uri, CancellationToken, Task <JObject> > getJson,
     Func <Uri, CancellationToken, Task <NuspecReader> > getNuspec,
     Func <Uri, CancellationToken, Task <HttpSourceResult> > getNupkg)
 {
     _urlParts = urlParts;
     Types     = new List <string>()
     {
         type
     };
     CommitId        = commitId;
     CommitTimeStamp = commitTs;
     Id            = id;
     Version       = version;
     _getJson      = getJson;
     _serviceIndex = serviceIndex;
     _getNuspec    = getNuspec;
     _getNupkg     = getNupkg;
 }
Esempio n. 2
0
 public PSAutoCompleteResourceV3(DataClient client, ServiceIndexResourceV3 serviceIndex, RegistrationResourceV3 regResource)
     : base()
 {
     _regResource  = regResource;
     _serviceIndex = serviceIndex;
     _client       = client;
 }
Esempio n. 3
0
        internal NuGetPackProvider(string name, string query, DirectoryInfo packageTempBasePath, int pageSize, bool runOnlyOnePage, bool includePreviewPacks)
        {
            Name             = name;
            _pageSize        = pageSize;
            _runOnlyOnePage  = runOnlyOnePage;
            _packageTempPath = Path.GetFullPath(Path.Combine(packageTempBasePath.FullName, DownloadedPacksDir, Name));
            _repository      = Repository.Factory.GetCoreV3(NuGetOrgFeed);
            ServiceIndexResourceV3            indexResource   = _repository.GetResource <ServiceIndexResourceV3>();
            IReadOnlyList <ServiceIndexEntry> searchResources = indexResource.GetServiceEntries("SearchQueryService");

            _downloadResource = _repository.GetResource <FindPackageByIdResource>();
            _includePreview   = includePreviewPacks;

            if (!searchResources.Any())
            {
                throw new Exception($"{NuGetOrgFeed} does not support search API (SearchQueryService)");
            }

            _searchUriFormat = $"{searchResources[0].Uri}?{query}&skip={{0}}&take={{1}}&prerelease={includePreviewPacks}&semVerLevel=2.0.0";

            if (Directory.Exists(_packageTempPath))
            {
                throw new Exception($"temp storage path for NuGet packages already exists: {_packageTempPath}");
            }
            else
            {
                Directory.CreateDirectory(_packageTempPath);
            }
        }
        internal static Uri GetCatalogServiceUri(this ServiceIndexResourceV3 serviceIndex, string[] types)
        {
            var uris = serviceIndex.GetServiceEntryUris(types);

            if (uris.Count < 1)
            {
                throw new InvalidDataException($"Unable to find a service of type: {string.Join(", ", types)} Verify the index.json file contains this entry.");
            }

            return(uris[0]);
        }
Esempio n. 5
0
        public void Constructor_InitializesProperties()
        {
            var serviceIndex        = CreateServiceIndex();
            var expectedJson        = serviceIndex.ToString();
            var expectedRequestTime = DateTime.UtcNow;
            var resource            = new ServiceIndexResourceV3(serviceIndex, expectedRequestTime);

            Assert.Equal(expectedJson, resource.Json);
            Assert.Equal(expectedRequestTime, resource.RequestTime);
            Assert.Equal(1, resource.Entries.Count);
            Assert.Equal("a", resource.Entries[0].Type);
            Assert.Equal("http://unit.test/b", resource.Entries[0].Uri.ToString());
        }
Esempio n. 6
0
        public async Task <string> GetPackageUrl(PackageId packageId,
                                                 NuGetVersion packageVersion = null,
                                                 PackageSourceLocation packageSourceLocation = null,
                                                 bool includePreview = false)
        {
            (var source, var resolvedPackageVersion) = await GetPackageSourceAndVerion(packageId, packageVersion, packageSourceLocation, includePreview);

            SourceRepository repository = GetSourceRepository(source);

            ServiceIndexResourceV3 serviceIndexResource = repository.GetResourceAsync <ServiceIndexResourceV3>().Result;
            IReadOnlyList <Uri>    packageBaseAddress   =
                serviceIndexResource?.GetServiceEntryUris(ServiceTypes.PackageBaseAddress);

            return(GetNupkgUrl(packageBaseAddress.First().ToString(), packageId, resolvedPackageVersion));
        }
Esempio n. 7
0
 internal PackageEntry(
     string id,
     NuGetVersion version,
     ServiceIndexResourceV3 serviceIndex,
     Func <Uri, CancellationToken, Task <JObject> > getJson,
     Func <Uri, CancellationToken, Task <NuspecReader> > getNuspec,
     Func <Uri, CancellationToken, Task <HttpSourceResult> > getNupkg)
 {
     Id            = id;
     Version       = version;
     _getJson      = getJson;
     _serviceIndex = serviceIndex;
     _getNuspec    = getNuspec;
     _getNupkg     = getNupkg;
 }
        public override async Task <Tuple <bool, INuGetResource> > TryCreate(SourceRepository source, CancellationToken token)
        {
            UISearchResourceV3     curResource  = null;
            ServiceIndexResourceV3 serviceIndex = await source.GetResourceAsync <ServiceIndexResourceV3>(token);

            if (serviceIndex != null)
            {
                var rawSearch = await source.GetResourceAsync <RawSearchResourceV3>(token);

                var metadataResource = await source.GetResourceAsync <UIMetadataResource>(token);

                curResource = new UISearchResourceV3(rawSearch, metadataResource);
            }

            return(new Tuple <bool, INuGetResource>(curResource != null, curResource));
        }
Esempio n. 9
0
        public async Task HandleResponseAsync_ReturnsSuccessIfServiceIndexIsFound()
        {
            using (var provider = new GetServiceIndexRequestHandler(Mock.Of <IPlugin>()))
            {
                var packageSource                = new PackageSource("https://unit.test");
                var serviceIndex                 = JObject.Parse("{}");
                var serviceIndexResource         = new ServiceIndexResourceV3(serviceIndex, DateTime.UtcNow);
                var serviceIndexResourceProvider = new Mock <INuGetResourceProvider>();

                serviceIndexResourceProvider.SetupGet(x => x.ResourceType)
                .Returns(typeof(ServiceIndexResourceV3));

                serviceIndexResourceProvider.SetupGet(x => x.Name)
                .Returns(nameof(ServiceIndexResourceV3Provider));

                serviceIndexResourceProvider.Setup(x => x.TryCreate(
                                                       It.IsNotNull <SourceRepository>(),
                                                       It.IsAny <CancellationToken>()))
                .ReturnsAsync(new Tuple <bool, INuGetResource>(true, serviceIndexResource));

                var sourceRepository = new SourceRepository(
                    packageSource,
                    new INuGetResourceProvider[] { serviceIndexResourceProvider.Object });

                provider.AddOrUpdateSourceRepository(sourceRepository);

                var request = CreateRequest(
                    MessageType.Request,
                    new GetServiceIndexRequest(packageSource.Source));
                var responseHandler = new Mock <IResponseHandler>(MockBehavior.Strict);

                responseHandler.Setup(x => x.SendResponseAsync(
                                          It.Is <Message>(r => r == request),
                                          It.Is <GetServiceIndexResponse>(r => r.ResponseCode == MessageResponseCode.Success &&
                                                                          r.ServiceIndex.ToString(Formatting.None) == serviceIndex.ToString(Formatting.None)),
                                          It.IsAny <CancellationToken>()))
                .Returns(Task.FromResult(0));

                await provider.HandleResponseAsync(
                    Mock.Of <IConnection>(),
                    request,
                    responseHandler.Object,
                    CancellationToken.None);

                responseHandler.Verify();
            }
        }
        /// <summary>
        /// Asynchronously handles responding to a request.
        /// </summary>
        /// <param name="connection">The connection.</param>
        /// <param name="request">A request message.</param>
        /// <param name="responseHandler">A response handler.</param>
        /// <param name="cancellationToken">A cancellation token.</param>
        /// <returns>A task that represents the asynchronous operation.</returns>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="connection" />
        /// is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="request" /> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="responseHandler" />
        /// is <c>null</c>.</exception>
        /// <exception cref="OperationCanceledException">Thrown if <paramref name="cancellationToken" />
        /// is cancelled.</exception>
        public async Task HandleResponseAsync(
            IConnection connection,
            Message request,
            IResponseHandler responseHandler,
            CancellationToken cancellationToken)
        {
            if (connection == null)
            {
                throw new ArgumentNullException(nameof(connection));
            }

            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            if (responseHandler == null)
            {
                throw new ArgumentNullException(nameof(responseHandler));
            }

            cancellationToken.ThrowIfCancellationRequested();

            var getRequest = MessageUtilities.DeserializePayload <GetServiceIndexRequest>(request);
            SourceRepository        sourceRepository;
            ServiceIndexResourceV3  serviceIndex = null;
            GetServiceIndexResponse responsePayload;

            if (_repositories.TryGetValue(getRequest.PackageSourceRepository, out sourceRepository))
            {
                serviceIndex = await sourceRepository.GetResourceAsync <ServiceIndexResourceV3>(cancellationToken)
                               .ConfigureAwait(false);
            }

            if (serviceIndex == null)
            {
                responsePayload = new GetServiceIndexResponse(MessageResponseCode.NotFound, serviceIndex: null);
            }
            else
            {
                var serviceIndexJson = JObject.Parse(serviceIndex.Json);

                responsePayload = new GetServiceIndexResponse(MessageResponseCode.Success, serviceIndexJson);
            }

            await responseHandler.SendResponseAsync(request, responsePayload, cancellationToken).ConfigureAwait(false);
        }
Esempio n. 11
0
        /// <summary>
        /// Ensure index.json has been loaded.
        /// </summary>
        private async Task EnsureServiceIndexAsync(Uri uri, CancellationToken token)
        {
            if (_serviceIndex == null)
            {
                await EnsureHttpSourceAsync();

                var index = await _httpSource.GetJObjectAsync(_indexUri, _cacheContext, _log, token);

                var resources = (index["resources"] as JArray);

                if (resources == null)
                {
                    throw new InvalidOperationException($"{uri.AbsoluteUri} does not contain a 'resources' property. Use the root service index.json for the nuget v3 feed.");
                }

                _serviceIndex = new ServiceIndexResourceV3(index, DateTime.UtcNow);
            }
        }
        private static SourceRepository CreateSourceRepository(
            ServiceIndexResourceV3 serviceIndexResource,
            string sourceUri)
        {
            var packageSource = new PackageSource(sourceUri);
            var provider      = new Mock <ServiceIndexResourceV3Provider>();

            provider.Setup(x => x.Name)
            .Returns(nameof(ServiceIndexResourceV3Provider));
            provider.Setup(x => x.ResourceType)
            .Returns(typeof(ServiceIndexResourceV3));

            var tryCreateResult = new Tuple <bool, INuGetResource>(serviceIndexResource != null, serviceIndexResource);

            provider.Setup(x => x.TryCreate(It.IsAny <SourceRepository>(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(tryCreateResult));

            return(new SourceRepository(packageSource, new[] { provider.Object }));
        }
Esempio n. 13
0
        public override int Execute()
        {
            if (_printDownloadLinkOnly || !string.IsNullOrWhiteSpace(_fromCacheOption))
            {
                SourceRepository source =
                    Repository.Factory.GetCoreV3("https://www.myget.org/F/mockworkloadfeed/api/v3/index.json");
                ServiceIndexResourceV3 serviceIndexResource = source.GetResourceAsync <ServiceIndexResourceV3>().Result;
                IReadOnlyList <Uri>    packageBaseAddress   =
                    serviceIndexResource?.GetServiceEntryUris(ServiceTypes.PackageBaseAddress);
                List <string> allPackageUrl = new List <string>();

                if (_printDownloadLinkOnly)
                {
                    allPackageUrl.Add(nupkgUrl(packageBaseAddress.First().ToString(), "Microsoft.iOS.Bundle",
                                               NuGetVersion.Parse("6.0.100")));

                    allPackageUrl.Add(nupkgUrl(packageBaseAddress.First().ToString(), "Microsoft.NET.Workload.Android",
                                               NuGetVersion.Parse("6.0.100")));

                    Reporter.Output.WriteLine("==allPackageLinksJsonOutputStart==");
                    Reporter.Output.WriteLine(JsonSerializer.Serialize(allPackageUrl));
                    Reporter.Output.WriteLine("==allPackageLinksJsonOutputEnd==");
                }

                if (!string.IsNullOrWhiteSpace(_fromCacheOption))
                {
                    Directory.CreateDirectory(MockUpdateDirectory);

                    File.Copy(Path.Combine(_fromCacheOption, "Microsoft.NET.Workload.Android.6.0.100.nupkg"),
                              Path.Combine(MockUpdateDirectory, "Microsoft.NET.Workload.Android.6.0.100.nupkg"));

                    File.Copy(Path.Combine(_fromCacheOption, "Microsoft.iOS.Bundle.6.0.100.nupkg"),
                              Path.Combine(MockUpdateDirectory, "Microsoft.iOS.Bundle.6.0.100.nupkg"));
                }
            }
            else
            {
                UpdateWorkloads(_includePreviews);
            }

            return(0);
        }
Esempio n. 14
0
        public override async Task <Tuple <bool, INuGetResource> > TryCreate(SourceRepository source, CancellationToken token)
        {
            ApiAppSearchResource resource = null;

            var messageHandlerResource = await source.GetResourceAsync <HttpHandlerResource>(token);

            ServiceIndexResourceV3 serviceIndex = await source.GetResourceAsync <ServiceIndexResourceV3>();

            if (messageHandlerResource != null && serviceIndex != null)
            {
                var endpoints = serviceIndex["ApiAppSearchQueryService"];

                if (endpoints.Any())
                {
                    RawSearchResourceV3 rawSearch = new RawSearchResourceV3(messageHandlerResource.MessageHandler, endpoints);

                    resource = new ApiAppSearchResource(rawSearch);
                }
            }

            return(new Tuple <bool, INuGetResource>(resource != null, resource));
        }
Esempio n. 15
0
        public async Task CanReadPackageInfo()
        {
            string nuGetOrgFeed = "https://api.nuget.org/v3/index.json";
            var    repository   = Repository.Factory.GetCoreV3(nuGetOrgFeed);
            ServiceIndexResourceV3            indexResource   = repository.GetResource <ServiceIndexResourceV3>();
            IReadOnlyList <ServiceIndexEntry> searchResources = indexResource.GetServiceEntries("SearchQueryService");
            string queryString = $"{searchResources[0].Uri}?q=Microsoft.DotNet.Common.ProjectTemplates.5.0&skip=0&take=10&prerelease=true&semVerLevel=2.0.0";
            Uri    queryUri    = new Uri(queryString);

            using (HttpClient client = new HttpClient())
                using (HttpResponseMessage response = await client.GetAsync(queryUri, CancellationToken.None).ConfigureAwait(false))
                {
                    if (response.IsSuccessStatusCode)
                    {
                        string responseText = await response.Content.ReadAsStringAsync(CancellationToken.None).ConfigureAwait(false);

                        NuGetPackageSearchResult resultsForPage = NuGetPackageSearchResult.FromJObject(JObject.Parse(responseText));
                        Assert.Equal(1, resultsForPage.TotalHits);
                        Assert.Equal(1, resultsForPage.Data.Count);

                        var packageInfo = resultsForPage.Data[0];

                        Assert.Equal("Microsoft.DotNet.Common.ProjectTemplates.5.0", packageInfo.Name);
                        Assert.NotEmpty(packageInfo.Version);
                        Assert.True(packageInfo.TotalDownloads > 0);
                        Assert.True(packageInfo.Verified);
                        Assert.Contains("Microsoft", packageInfo.Owners);
                        Assert.NotEmpty(packageInfo.Description);
                        Assert.NotEmpty(packageInfo.IconUrl);
                    }
                    else
                    {
                        Assert.True(false, "HTTP request failed.");
                    }
                }
        }
        private static ServiceIndexResourceV3Provider CreateServiceIndexResourceV3Provider(params ServiceIndexEntry[] entries)
        {
            var provider = new Mock <ServiceIndexResourceV3Provider>();

            provider.Setup(x => x.Name)
            .Returns(nameof(ServiceIndexResourceV3Provider));
            provider.Setup(x => x.ResourceType)
            .Returns(typeof(ServiceIndexResourceV3));

            var resources = new JArray();

            foreach (var entry in entries)
            {
                resources.Add(
                    new JObject(
                        new JProperty("@id", entry.Uri.AbsoluteUri),
                        new JProperty("@type", entry.Type)));
            }

            var index = new JObject();

            index.Add("version", "3.0.0");
            index.Add("resources", resources);
            index.Add("@context",
                      new JObject(
                          new JProperty("@vocab", "http://schema.nuget.org/schema#"),
                          new JProperty("comment", "http://www.w3.org/2000/01/rdf-schema#comment")));

            var serviceIndexResource = new ServiceIndexResourceV3(index, DateTime.UtcNow);
            var tryCreateResult      = new Tuple <bool, INuGetResource>(true, serviceIndexResource);

            provider.Setup(x => x.TryCreate(It.IsAny <SourceRepository>(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(tryCreateResult));

            return(provider.Object);
        }
Esempio n. 17
0
        private async Task <IEnumerable <PluginCreationResult> > GetPluginsForPackageSourceAsync(
            string packageSourceRepository,
            ServiceIndexResourceV3 serviceIndex,
            IEnumerable <PluginDiscoveryResult> results,
            CancellationToken cancellationToken)
        {
            var pluginCreationResults = new List <PluginCreationResult>();
            var serviceIndexJson      = JObject.Parse(serviceIndex.Json);

            foreach (var result in results)
            {
                PluginCreationResult pluginCreationResult = null;

                if (result.PluginFile.State == PluginFileState.Valid)
                {
                    var plugin = await _pluginFactory.GetOrCreateAsync(
                        result.PluginFile.Path,
                        PluginConstants.PluginArguments,
                        new RequestHandlers(),
                        _connectionOptions,
                        cancellationToken);

                    var utilities = _pluginUtilities.GetOrAdd(
                        plugin.Id,
                        path => new Lazy <IPluginMulticlientUtilities>(
                            () => new PluginMulticlientUtilities()));

                    await utilities.Value.DoOncePerPluginLifetimeAsync(
                        MessageMethod.MonitorNuGetProcessExit.ToString(),
                        () => plugin.Connection.SendRequestAndReceiveResponseAsync <MonitorNuGetProcessExitRequest, MonitorNuGetProcessExitResponse>(
                            MessageMethod.MonitorNuGetProcessExit,
                            new MonitorNuGetProcessExitRequest(_currentProcessId.Value),
                            cancellationToken),
                        cancellationToken);

                    await utilities.Value.DoOncePerPluginLifetimeAsync(
                        MessageMethod.Initialize.ToString(),
                        () => InitializePluginAsync(plugin, _connectionOptions.RequestTimeout, cancellationToken),
                        cancellationToken);

                    var lazyOperationClaims = _pluginOperationClaims.GetOrAdd(
                        new PluginPackageSourceKey(result.PluginFile.Path, packageSourceRepository),
                        key => new Lazy <Task <IReadOnlyList <OperationClaim> > >(() => GetPluginOperationClaimsAsync(
                                                                                      plugin,
                                                                                      packageSourceRepository,
                                                                                      serviceIndexJson,
                                                                                      cancellationToken)));

                    await lazyOperationClaims.Value;

                    pluginCreationResult = new PluginCreationResult(
                        plugin,
                        utilities.Value,
                        lazyOperationClaims.Value.Result);
                }
                else
                {
                    pluginCreationResult = new PluginCreationResult(result.Message);
                }

                pluginCreationResults.Add(pluginCreationResult);
            }

            return(pluginCreationResults);
        }
        /// <summary>
        ///     Determine the NuGet package sources configured for the current project and create clients for them.
        /// </summary>
        /// <param name="cancellationToken">
        ///     An optional <see cref="CancellationToken"/> that can be used to cancel the operation.
        /// </param>
        /// <returns>
        ///     <c>true</c>, if the package sources were loaded; otherwise, <c>false</c>.
        /// </returns>
        public virtual async Task <bool> ConfigurePackageSources(CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                _configuredPackageSources.Clear();
                _autoCompleteResources.Clear();

                bool             includeLocalSources   = Workspace.Configuration.NuGet.IncludeLocalSources;
                HashSet <string> ignoredPackageSources = Workspace.Configuration.NuGet.IgnorePackageSources;

                foreach (PackageSource packageSource in NuGetHelper.GetWorkspacePackageSources(ProjectFile.Directory.FullName))
                {
                    // Exclude package sources explicitly ignored by name.
                    string packageSourceName = packageSource.Name ?? "<unknown>";
                    if (ignoredPackageSources.Contains(packageSourceName))
                    {
                        Log.Verbose("Ignoring package source named {PackageSourceName} (the language server has been explicitly configured to ignore it).", packageSourceName);

                        continue;
                    }

                    // Exclude package sources explicitly ignored by URI.
                    Uri packageSourceUri = packageSource.TrySourceAsUri ?? new Uri("unknown:/", UriKind.Absolute);
                    if (ignoredPackageSources.Contains(packageSourceUri.AbsoluteUri))
                    {
                        Log.Verbose("Ignoring package source with URI {PackageSourceURI} (the language server has been explicitly configured to ignore it).", packageSourceUri.AbsoluteUri);

                        continue;
                    }

                    // Exclude unsupported package-source types.
                    if (!packageSource.IsHttp)
                    {
                        if (packageSourceUri.Scheme == Uri.UriSchemeFile)
                        {
                            if (!includeLocalSources)
                            {
                                Log.Verbose("Ignoring local package source {PackageSourceName} ({PackageSourcePath}) (the language server has not been configured to use local package sources).",
                                            packageSourceName,
                                            packageSourceUri.AbsolutePath
                                            );

                                continue;
                            }
                        }
                        else
                        {
                            Log.Verbose("Ignoring local package source {PackageSourceName} ({PackageSourceUri}) (the language server only supports local and HTTP-based package sources).",
                                        packageSourceName,
                                        packageSourceUri.AbsolutePath
                                        );

                            continue;
                        }
                    }

                    _configuredPackageSources.Add(packageSource);
                }

                Log.Information("{PackageSourceCount} package sources configured for project {ProjectFile}.",
                                _configuredPackageSources.Count,
                                VSCodeDocumentUri.GetFileSystemPath(DocumentUri)
                                );
                foreach (PackageSource packageSource in _configuredPackageSources)
                {
                    if (packageSource.IsMachineWide)
                    {
                        Log.Information("  Globally-configured package source {PackageSourceName} (v{PackageSourceProtocolVersion}) => {PackageSourceUri}",
                                        packageSource.Name,
                                        packageSource.ProtocolVersion,
                                        packageSource.SourceUri
                                        );
                    }
                    else
                    {
                        Log.Information("  Locally-configured package source {PackageSourceName} (v{PackageSourceProtocolVersion}) => {PackageSourceUri}",
                                        packageSource.Name,
                                        packageSource.ProtocolVersion,
                                        packageSource.SourceUri
                                        );
                    }
                }

                List <SourceRepository> sourceRepositories = _configuredPackageSources.CreateResourceRepositories();
                foreach (SourceRepository sourceRepository in sourceRepositories)
                {
                    ServiceIndexResourceV3 serviceIndex = await sourceRepository.GetResourceAsync <ServiceIndexResourceV3>(cancellationToken);

                    if (serviceIndex == null)
                    {
                        Log.Warning("    Ignoring configured package source {PackageSourceName} ({PackageSourceUri}) because the v3 service index cannot be found for this package source.",
                                    sourceRepository.PackageSource.Name ?? "<unknown>",
                                    sourceRepository.PackageSource.TrySourceAsUri?.AbsoluteUri ?? "unknown:/"
                                    );

                        continue;
                    }

                    IReadOnlyList <ServiceIndexEntry> autoCompleteServices = serviceIndex.GetServiceEntries(ServiceTypes.SearchAutocompleteService);
                    if (autoCompleteServices.Count == 0)
                    {
                        Log.Warning("    Ignoring configured package source {PackageSourceName} ({PackageSourceUri}) because it does not appear to support a compatible version of the NuGet auto-complete API.",
                                    sourceRepository.PackageSource.Name ?? "<unknown>",
                                    sourceRepository.PackageSource.TrySourceAsUri?.AbsoluteUri ?? "unknown:/"
                                    );

                        continue;
                    }

                    AutoCompleteResource autoCompleteResource = await sourceRepository.GetResourceAsync <AutoCompleteResource>(cancellationToken);

                    if (autoCompleteResource == null)
                    {
                        // Should not happen.
                        Log.Error("Failed to retrieve {ServiceName} service instance for configured package source {PackageSourceName} ({PackageSourceUri}).",
                                  "AutoComplete",
                                  sourceRepository.PackageSource.Name ?? "<unknown>",
                                  sourceRepository.PackageSource.TrySourceAsUri?.AbsoluteUri ?? "unknown:/"
                                  );

                        continue;
                    }

                    _autoCompleteResources.Add(autoCompleteResource);
                }

                return(true);
            }
            catch (Exception packageSourceLoadError)
            {
                Log.Error(packageSourceLoadError, "Error configuring NuGet package sources for MSBuild project '{ProjectFileName}'.", ProjectFile.FullName);

                return(false);
            }
        }
 internal static Uri GetSleetPackageIndexUrl(this ServiceIndexResourceV3 serviceIndex)
 {
     return(serviceIndex.GetServiceUri(SleetPackageIndexUrl));
 }
        public override int Execute()
        {
            // TODO stub
            Reporter.Output.WriteLine($"WIP workload install {string.Join("; ", _workloadIds)}");
            List <string> allowedMockWorkloads = new List <string> {
                "mobile-ios", "mobile-android"
            };

            if (!_printDownloadLinkOnly && string.IsNullOrWhiteSpace(_fromCacheOption))
            {
                Reporter.Output.WriteLine(
                    "mock currently does not support normal install. Need --print-download-link-only or --from-cache");
            }

            if (_workloadIds.Except(allowedMockWorkloads).Any())
            {
                Reporter.Output.WriteLine("Only support \"mobile-ios\", \"mobile-android\" in the mock");
            }

            SourceRepository source =
                Repository.Factory.GetCoreV3("https://www.myget.org/F/mockworkloadfeed/api/v3/index.json");
            ServiceIndexResourceV3 serviceIndexResource = source.GetResourceAsync <ServiceIndexResourceV3>().Result;
            IReadOnlyList <Uri>    packageBaseAddress   =
                serviceIndexResource?.GetServiceEntryUris(ServiceTypes.PackageBaseAddress);
            List <string> allPackageUrl = new List <string>();

            if (_printDownloadLinkOnly)
            {
                if (_workloadIds.Contains("mobile-ios"))
                {
                    allPackageUrl.Add(nupkgUrl(packageBaseAddress.First().ToString(), "Microsoft.iOS.Bundle",
                                               NuGetVersion.Parse("6.0.100")));

                    AddNewtonsoftJson(allPackageUrl);
                }

                if (_workloadIds.Contains("mobile-android"))
                {
                    allPackageUrl.Add(nupkgUrl(packageBaseAddress.First().ToString(), "Microsoft.NET.Workload.Android",
                                               NuGetVersion.Parse("6.0.100")));


                    AddNewtonsoftJson(allPackageUrl);
                }

                Reporter.Output.WriteLine("==allPackageLinksJsonOutputStart==");
                Reporter.Output.WriteLine(JsonSerializer.Serialize(allPackageUrl));
                Reporter.Output.WriteLine("==allPackageLinksJsonOutputEnd==");
            }

            if (!string.IsNullOrWhiteSpace(_fromCacheOption))
            {
                Directory.CreateDirectory(MockInstallDirectory);
                if (_workloadIds.Contains("mobile-android"))
                {
                    File.Copy(Path.Combine(_fromCacheOption, "Microsoft.NET.Workload.Android.6.0.100.nupkg"),
                              Path.Combine(MockInstallDirectory, "Microsoft.NET.Workload.Android.6.0.100.nupkg"));
                }

                if (_workloadIds.Contains("mobile-ios"))
                {
                    File.Copy(Path.Combine(_fromCacheOption, "Microsoft.iOS.Bundle.6.0.100.nupkg"),
                              Path.Combine(MockInstallDirectory, "Microsoft.iOS.Bundle.6.0.100.nupkg"));
                }
            }

            return(0);
        }
 internal static Uri GetPackageBaseAddressUri(this ServiceIndexResourceV3 serviceIndex)
 {
     return(serviceIndex.GetCatalogServiceUri(PackageBaseAddressUrl));
 }
 internal static Uri GetCatalogServiceUri(this ServiceIndexResourceV3 serviceIndex)
 {
     return(serviceIndex.GetCatalogServiceUri(CatalogServiceUrl));
 }
 internal static Uri GetRegistrationBaseUri(this ServiceIndexResourceV3 serviceIndex)
 {
     return(serviceIndex.GetCatalogServiceUri(RegistrationsBaseUrl));
 }