Skip to content
This repository was archived by the owner on Mar 17, 2025. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ download in the
These are the changes to each version that has been released
on the official Visual Studio extension gallery.

## 1.4
- [x] Implement NuGet V2 Feed support
- [x] Change WebRequestFactory to use a static HttpClient to avoid connection socket exhaustion problem

## 1.1

- [x] Go To Definition (F12) for MSBuild imports
Expand Down
201 changes: 201 additions & 0 deletions src/ProjectFileTools.NuGetSearch/Feeds/Web/NuGetV2ServiceFeed.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,201 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Newtonsoft.Json.Linq;
using ProjectFileTools.NuGetSearch.Contracts;
using ProjectFileTools.NuGetSearch.IO;
using ProjectFileTools.NuGetSearch.Search;

namespace ProjectFileTools.NuGetSearch.Feeds.Web
{
public class NuGetV2ServiceFeedFactory : IPackageFeedFactory
{
private readonly IWebRequestFactory _webRequestFactory;

public NuGetV2ServiceFeedFactory(IWebRequestFactory webRequestFactory)
{
_webRequestFactory = webRequestFactory;
}

public bool TryHandle(string feed, out IPackageFeed instance)
{
if (Uri.TryCreate(feed, UriKind.Absolute, out Uri location) && feed.EndsWith("nuget", StringComparison.OrdinalIgnoreCase))
{
instance = new NuGetV2ServiceFeed(feed, _webRequestFactory);
return true;
}

instance = null;
return false;
}
}

public class NuGetV2ServiceFeed : IPackageFeed
{
private readonly string _feed;
private readonly FeedKind _kind;
private readonly IWebRequestFactory _webRequestFactory;

public NuGetV2ServiceFeed(string feed, IWebRequestFactory webRequestFactory)
{
_webRequestFactory = webRequestFactory;
_feed = feed;
_kind = feed.IndexOf("nuget.org", StringComparison.OrdinalIgnoreCase) > -1 ? FeedKind.NuGet : FeedKind.MyGet;
}

public string DisplayName => $"{_feed} (NuGet v2)";


public async Task<IPackageNameSearchResult> GetPackageNamesAsync(string prefix, IPackageQueryConfiguration queryConfiguration, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return PackageNameSearchResult.Failure;
}

IReadOnlyList<string> results = new List<string>();
string frameworkQuery = !string.IsNullOrEmpty(queryConfiguration.CompatibiltyTarget) ? $"&targetFramework={queryConfiguration.CompatibiltyTarget}" : "";
var serviceEndpoint = $"{_feed}/Search()";
Func<string, string> queryFunc = x => $"{x}?searchTerm='{prefix}'{frameworkQuery}&includePrerelease={queryConfiguration.IncludePreRelease}&semVerLevel=2.0.0";
XDocument document = await ExecuteAutocompleteServiceQueryAsync(serviceEndpoint, queryFunc, cancellationToken).ConfigureAwait(false);

if (document != null)
{
try
{
results = GetPackageNamesFromNuGetV2CompatibleQueryResult(document);
return new PackageNameSearchResult(results, _kind);
}
catch
{
}
}

return PackageNameSearchResult.Failure;
}

public async Task<IPackageInfo> GetPackageInfoAsync(string packageId, string version, IPackageQueryConfiguration queryConfiguration, CancellationToken cancellationToken)
{
if (packageId == null)
{
return null;
}

var serviceEndpoint = $"{_feed}/Packages(Id='{packageId}',Version='{version}')";
Func<string, string> queryFunc = x => $"{x}";
XDocument document = await ExecuteAutocompleteServiceQueryAsync(serviceEndpoint, queryFunc, cancellationToken).ConfigureAwait(false);

if (document != null)
{
var el = document.Root;

var id = GetPropertyValue(document, el, "Id");
var title = GetPropertyValue(document, el, "Title");
var authors = GetPropertyValue(document, el, "Authors");
var summary = GetPropertyValue(document, el, "Summary");
var description = GetPropertyValue(document, el, "Description");
var projectUrl = GetPropertyValue(document, el, "ProjectUrl");
var licenseUrl = GetPropertyValue(document, el, "LicenseUrl");
var iconUrl = GetPropertyValue(document, el, "IconUrl");
var tags = GetPropertyValue(document, el, "Tags");
var packageInfo = new PackageInfo(id, version, title, authors, summary, description, licenseUrl, projectUrl, iconUrl, tags, _kind);
return packageInfo;
}


return null;
}

public async Task<IPackageVersionSearchResult> GetPackageVersionsAsync(string id, IPackageQueryConfiguration queryConfiguration, CancellationToken cancellationToken)
{
IReadOnlyList<string> results = new List<string>();
var serviceEndpoint = $"{_feed}/FindPackagesById()";
Func<string, string> queryFunc = x => $"{x}?id='{id}'";
XDocument document = await ExecuteAutocompleteServiceQueryAsync(serviceEndpoint, queryFunc, cancellationToken).ConfigureAwait(false);

try
{
results = GetPackageVersionsFromNuGetV2CompatibleQueryResult(id, document);
}
catch
{
return PackageVersionSearchResult.Failure;
}

return new PackageVersionSearchResult(results, _kind);
}

private async Task<XDocument> ExecuteAutocompleteServiceQueryAsync(string endpoint, Func<string, string> query, CancellationToken cancellationToken)
{
if (endpoint == null)
{
return null;
}

try
{
string location = query(endpoint);
var xml = await _webRequestFactory.GetStringAsync(location, cancellationToken).ConfigureAwait(false);
return XDocument.Parse(xml);
}
catch (Exception)
{
}

return null;
}


private static string GetPropertyValue(XDocument document, XElement el, string propertyKey)
{
return el
.Element(document.Root.GetNamespaceOfPrefix("m") + "properties")
.Element(document.Root.GetNamespaceOfPrefix("d") + propertyKey)
?.Value;
}



private static IReadOnlyList<string> GetPackageVersionsFromNuGetV2CompatibleQueryResult(string id, XDocument document)
{
List<string> results = new List<string>();

if (document != null)
{
foreach (var el in document.Root.Elements(document.Root.GetDefaultNamespace() + "entry"))
{
var pkgId = GetPropertyValue(document, el, "Id");

var pkgVersion = GetPropertyValue(document, el, "Version");

if (pkgId.Equals(pkgId, StringComparison.OrdinalIgnoreCase))
{
results.Add(pkgVersion);
}
}
}

return results;
}

private static IReadOnlyList<string> GetPackageNamesFromNuGetV2CompatibleQueryResult(XDocument document)
{
List<string> results = new List<string>();

if (document != null)
{
foreach (var el in document.Root.Elements(document.Root.GetDefaultNamespace() + "entry"))
{
var id = GetPropertyValue(document, el, "Id");

results.Add(id);
}
}

return results.Distinct().ToList();
}
}
}
10 changes: 4 additions & 6 deletions src/ProjectFileTools.NuGetSearch/IO/WebRequestFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,14 @@ namespace ProjectFileTools.NuGetSearch.IO
{
public class WebRequestFactory : IWebRequestFactory
{
private static readonly HttpClient _httpClient = new HttpClient();
public async Task<string> GetStringAsync(string endpoint, CancellationToken cancellationToken)
{
try
{
using (HttpClient client = new HttpClient())
{
HttpResponseMessage responseMessage = await client.GetAsync(endpoint, cancellationToken).ConfigureAwait(false);
responseMessage.EnsureSuccessStatusCode();
return await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false);
}
HttpResponseMessage responseMessage = await _httpClient.GetAsync(endpoint, cancellationToken).ConfigureAwait(false);
responseMessage.EnsureSuccessStatusCode();
return await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false);
}
catch
{
Expand Down
19 changes: 19 additions & 0 deletions src/ProjectFileTools/Exports/ExportedNuGetV2ServiceFeedFactory.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.Utilities;
using ProjectFileTools.NuGetSearch.Contracts;
using ProjectFileTools.NuGetSearch.Feeds.Web;
using ProjectFileTools.NuGetSearch.IO;

namespace ProjectFileTools.Exports
{
[Export(typeof(IPackageFeedFactory))]
[Name("Default NuGet v2 Service Feed Factory")]
internal class ExportedNuGetV2ServiceFeedFactory : NuGetV2ServiceFeedFactory
{
[ImportingConstructor]
public ExportedNuGetV2ServiceFeedFactory(IWebRequestFactory webRequestFactory)
: base(webRequestFactory)
{
}
}
}
1 change: 1 addition & 0 deletions src/ProjectFileTools/ProjectFileTools.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Compile Include="Exports\ExportedNuGetV2ServiceFeedFactory.cs" />
<Compile Include="Helpers\XmlInfo.cs" />
<Compile Include="Helpers\XmlTools.cs" />
<Page Include="**\*.xaml">
Expand Down
2 changes: 1 addition & 1 deletion src/ProjectFileTools/source.extension.vsixmanifest
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
<Tags>project, csproj, vbproj</Tags>
</Metadata>
<Installation>
<InstallationTarget Id="Microsoft.VisualStudio.Community" Version="[15.0.27906.1,16.1)" />
<InstallationTarget Id="Microsoft.VisualStudio.Community" Version="[15.0.27906.1,17.0)" />
</Installation>
<Dependencies>
<Dependency Id="Microsoft.Framework.NDP" DisplayName="Microsoft .NET Framework" d:Source="Manual" Version="[4.5,)" />
Expand Down
116 changes: 116 additions & 0 deletions test/ProjectFileTools.NuGetSearch.Tests/NuGetV2ServiceFeedTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
using FluentAssertions;
using Moq;
using ProjectFileTools.NuGetSearch.Feeds;
using ProjectFileTools.NuGetSearch.Feeds.Web;
using ProjectFileTools.NuGetSearch.IO;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Xunit;

namespace ProjectFileTools.NuGetSearch.Tests
{
/// <summary>
/// The tests below only work when signing is disabled.
/// When signing enabled, no test will be found as a result of `ProjectFileTools.NuGetSearch` failing to load with signing key validation error
/// </summary>
public class NuGetV2ServiceFeedTests
{

public class TheDisplayNameProperty
{

[Theory]
[InlineData("http://localhost/nuget")]
public void GivenFeed_ReturnDisplayName(string feed)
{
var webRequestFactory = Mock.Of<IWebRequestFactory>();
var sut = new NuGetV2ServiceFeed(feed, webRequestFactory);
sut.DisplayName.Should().Be($"{feed} (NuGet v2)");
}
}

public class TheGetPackageNamesAsyncMethod
{
[Theory]
[InlineData("http://localhost/nuget", "GetPackageNames.CommonLogging.xml")]
public async Task GivenPackagesFound_ReturnListOfIds(string feed, string testFile)
{
var webRequestFactory = Mock.Of<IWebRequestFactory>();

Mock.Get(webRequestFactory)
.Setup(f => f.GetStringAsync("http://localhost/nuget/Search()?searchTerm='Common.Logging'&targetFramework=netcoreapp2.0&includePrerelease=False&semVerLevel=2.0.0", It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(GetXmlFromTestFile(testFile)));

var sut = new NuGetV2ServiceFeed(feed, webRequestFactory);

var packageNameResults = await sut.GetPackageNamesAsync("Common.Logging", new PackageQueryConfiguration("netcoreapp2.0", false), new CancellationToken());
packageNameResults.Names.Count.Should().Be(5);
}
}

public class TheGetPackageVersionsAsyncMethod
{
[Theory]
[InlineData("http://localhost/nuget", "GetPackageVersions.CommonLogging.xml")]
public async Task GivenPackagesFound_ReturnListOfVersions(string feed, string testFile)
{
var webRequestFactory = Mock.Of<IWebRequestFactory>();

Mock.Get(webRequestFactory)
.Setup(f => f.GetStringAsync("http://localhost/nuget/FindPackagesById()?id='Acme.Common.Logging.AspNetCore'", It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(GetXmlFromTestFile(testFile)));

var sut = new NuGetV2ServiceFeed(feed, webRequestFactory);

var packageNameResults = await sut.GetPackageVersionsAsync("Acme.Common.Logging.AspNetCore", new PackageQueryConfiguration("netcoreapp2.0", false), new CancellationToken());
packageNameResults.Versions.Count.Should().Be(8);
Assert.Collection(packageNameResults.Versions,
v => v.Should().Be("1.6.0.5"),
v => v.Should().Be("1.6.1"),
v => v.Should().Be("1.6.2"),
v => v.Should().Be("1.7.0"),
v => v.Should().Be("1.7.1"),
v => v.Should().Be("1.8.0"),
v => v.Should().Be("1.9.0"),
v => v.Should().Be("1.9.1"));
}
}

public class TheGetPackageInfoAsyncMethod
{
[Theory]
[InlineData("http://localhost/nuget", "GetPackageInfo.CommonLogging.xml")]
public async Task GivenPackageFound_ReturnPackageInfo(string feed, string testFile)
{
var webRequestFactory = Mock.Of<IWebRequestFactory>();

Mock.Get(webRequestFactory)
.Setup(f => f.GetStringAsync("http://localhost/nuget/Packages(Id='Acme.Common.Logging.AspNetCore',Version='1.8.0')", It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(GetXmlFromTestFile(testFile)));

var sut = new NuGetV2ServiceFeed(feed, webRequestFactory);

var pkgInfo = await sut.GetPackageInfoAsync("Acme.Common.Logging.AspNetCore", "1.8.0", new PackageQueryConfiguration("netcoreapp2.0", false), new CancellationToken());

pkgInfo.Id.Should().Be("Acme.Common.Logging.AspNetCore");
pkgInfo.Title.Should().Be("Common Logging AspNetCore");
pkgInfo.Summary.Should().BeNullOrEmpty();
pkgInfo.Description.Should().Be("Common Logging integration within Aspnet core services");
pkgInfo.Authors.Should().Be("Patrick Assuied");
pkgInfo.Version.Should().Be("1.8.0");
pkgInfo.ProjectUrl.Should().Be("https://bitbucket.acme.com/projects/Acme/repos/Acme-common-logging");
pkgInfo.LicenseUrl.Should().BeNullOrEmpty();
pkgInfo.Tags.Should().Be(" common logging aspnetcore ");


}
}

public static string GetXmlFromTestFile(string filename)
{
string path = Path.Combine(Directory.GetCurrentDirectory(), $"../../test/ProjectFileTools.NuGetSearch.Tests/TestFiles/{filename}");
return File.ReadAllText(path);
}
}
}
Loading