Exemplo n.º 1
0
        private static async Task InitializePluginAsync(
            IPlugin plugin,
            TimeSpan requestTimeout,
            CancellationToken cancellationToken)
        {
            var clientVersion = MinClientVersionUtility.GetNuGetClientVersion().ToNormalizedString();
            var culture       = GetCurrentCultureName();

            var payload = new InitializeRequest(
                clientVersion,
                culture,
                requestTimeout);

            var response = await plugin.Connection.SendRequestAndReceiveResponseAsync <InitializeRequest, InitializeResponse>(
                MessageMethod.Initialize,
                payload,
                cancellationToken);

            if (response != null && response.ResponseCode != MessageResponseCode.Success)
            {
                throw new PluginException(Strings.Plugin_InitializationFailed);
            }

            plugin.Connection.Options.SetRequestTimeout(requestTimeout);
        }
Exemplo n.º 2
0
        public async Task Initialize_Succeeds()
        {
            using (var test = await PluginTest.CreateAsync())
            {
                Assert.Equal(PluginProtocolConstants.CurrentVersion, test.Plugin.Connection.ProtocolVersion);

                // Send canned response
                var responseSenderTask = Task.Run(() => test.ResponseSender.StartSendingAsync(test.CancellationToken));
                await test.ResponseSender.SendAsync(
                    MessageType.Response,
                    MessageMethod.Initialize,
                    new InitializeResponse(MessageResponseCode.Success));

                var clientVersion = MinClientVersionUtility.GetNuGetClientVersion().ToNormalizedString();
                var culture       = CultureInfo.CurrentCulture.Name;
                var payload       = new InitializeRequest(
                    clientVersion,
                    culture,
                    PluginConstants.RequestTimeout);

                var response = await test.Plugin.Connection.SendRequestAndReceiveResponseAsync <InitializeRequest, InitializeResponse>(
                    MessageMethod.Initialize,
                    payload,
                    test.CancellationToken);

                Assert.NotNull(response);
                Assert.Equal(MessageResponseCode.Success, response.ResponseCode);
            }
        }
Exemplo n.º 3
0
        public async Task EnsurePackageCompatibilityAsync_WithLowerMinClientVersion_Fails()
        {
            // Arrange
            var tc = new TestContext();

            tc.MinClientVersion = new NuGetVersion("10.0.0");
            var result = new DownloadResourceResult(Stream.Null, tc.PackageReader.Object, string.Empty);

            // Act & Assert
            var ex = await Assert.ThrowsAsync <MinClientVersionException>(() =>
                                                                          tc.Target.EnsurePackageCompatibilityAsync(
                                                                              tc.NuGetProject,
                                                                              tc.PackageIdentityA,
                                                                              result,
                                                                              CancellationToken.None));

            Assert.Equal(
                "The 'PackageA 1.0.0' package requires NuGet client version '10.0.0' or above, " +
                $"but the current NuGet version is '{MinClientVersionUtility.GetNuGetClientVersion()}'. " +
                "To upgrade NuGet, please go to http://docs.nuget.org/consume/installing-nuget",
                ex.Message);

            tc.PackageReader.Verify(x => x.GetMinClientVersion(), Times.Never);
            tc.PackageReader.Verify(x => x.GetPackageTypes(), Times.Never);
            tc.NuspecReader.Verify(x => x.GetMinClientVersion(), Times.AtLeastOnce);
            tc.NuspecReader.Verify(x => x.GetPackageTypes(), Times.Never);
        }
Exemplo n.º 4
0
        public UserAgentStringBuilder(string clientName)
        {
            _clientName = clientName;

            // Read the client version from the assembly metadata and normalize it.
            NuGetClientVersion = MinClientVersionUtility.GetNuGetClientVersion().ToNormalizedString();
        }
        public void MinClientVersionUtility_CurrentVersionIsCompatible()
        {
            // Arrange && Act
            var result = MinClientVersionUtility.IsMinClientVersionCompatible(MinClientVersionUtility.GetNuGetClientVersion());

            // Assert
            Assert.True(result);
        }
        public void MinClientVersionUtility_CheckCompatible(string version, bool expected)
        {
            // Arrange && Act
            var result = MinClientVersionUtility.IsMinClientVersionCompatible(NuGetVersion.Parse(version));

            // Assert
            Assert.Equal(expected, result);
        }
        public void MinClientVersionUtility_ReadFromNuspecNullDoesNotThrow()
        {
            // Arrange
            var nuspec = GetNuspec();

            // Act & Assert
            MinClientVersionUtility.VerifyMinClientVersion(nuspec);
        }
        public void MinClientVersionUtility_ReadFromNuspecInCompatThrows()
        {
            // Arrange
            var nuspec = GetNuspec("99.0.0");

            // Act & Assert
            Assert.Throws(typeof(MinClientVersionException),
                          () => MinClientVersionUtility.VerifyMinClientVersion(nuspec));
        }
        private static void EnsurePackageCompatibility(
            NuGetProject nuGetProject,
            PackageIdentity packageIdentity,
            NuspecReader nuspecReader)
        {
            // Validate that the current version of NuGet satisfies the minVersion attribute specified in the .nuspec
            MinClientVersionUtility.VerifyMinClientVersion(nuspecReader);

            // Validate the package type. There must be zero package types or exactly one package
            // type that is one of the recognized package types.
            var packageTypes   = nuspecReader.GetPackageTypes();
            var identityString = $"{packageIdentity.Id} {packageIdentity.Version.ToNormalizedString()}";

            if (packageTypes.Count > 1)
            {
                throw new PackagingException(string.Format(
                                                 CultureInfo.CurrentCulture,
                                                 Strings.MultiplePackageTypesNotSupported,
                                                 identityString));
            }
            else if (packageTypes.Count == 1)
            {
                var packageType       = packageTypes[0];
                var packageTypeString = packageType.Name;
                if (packageType.Version != PackageType.EmptyVersion)
                {
                    packageTypeString += " " + packageType.Version;
                }

                var projectName = NuGetProject.GetUniqueNameOrName(nuGetProject);

                if (packageType == PackageType.Legacy ||   // Added for "quirks mode", but not yet fully implemented.
                    packageType == PackageType.Dependency) // A package explicitly stated as a dependency.
                {
                    // These types are always acceptable.
                }
                else if (nuGetProject is ProjectKNuGetProjectBase &&
                         packageType == PackageType.DotnetCliTool)
                {
                    // ProjectKNuGetProjectBase projects are .NET Core (both "dotnet" and "dnx").
                    // .NET CLI tools are support for "dotnet" projects. The projects eventually
                    // call into INuGetPackageManager, which is not implemented by NuGet. This code
                    // will make the decision of how to install the .NET CLI tool package.
                }
                else
                {
                    throw new PackagingException(string.Format(
                                                     CultureInfo.CurrentCulture,
                                                     Strings.UnsupportedPackageType,
                                                     identityString,
                                                     packageTypeString,
                                                     projectName));
                }
            }
        }
        public void MinClientVersionUtility_ReadFromNuspecInCompat()
        {
            // Arrange
            var nuspec = GetNuspec("99.0.0");

            // Act
            var result = MinClientVersionUtility.IsMinClientVersionCompatible(nuspec);

            // Assert
            Assert.False(result);
        }
        public void MinClientVersionUtility_ReadFromNuspecCompat()
        {
            // Arrange
            var nuspec = GetNuspec("2.8.6");

            // Act
            var result = MinClientVersionUtility.IsMinClientVersionCompatible(nuspec);

            // Assert
            Assert.True(result);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Read dependency info from a nuspec.
        /// </summary>
        /// <remarks>This also verifies minClientVersion.</remarks>
        protected static FindPackageByIdDependencyInfo GetDependencyInfo(NuspecReader reader)
        {
            // Since this is the first place a package is read after selecting it as the best version
            // check the minClientVersion here to verify we are okay to read this package.
            MinClientVersionUtility.VerifyMinClientVersion(reader);

            // Create dependency info
            return(new FindPackageByIdDependencyInfo(
                       reader.GetDependencyGroups(),
                       reader.GetFrameworkReferenceGroups()));
        }
Exemplo n.º 13
0
        /// <summary>
        /// Set user agent string on HttpClient to the static string.
        /// </summary>
        /// <param name="client">Http client</param>
        public static void SetUserAgent(HttpClient client)
        {
            if (client == null)
            {
                throw new ArgumentNullException(nameof(client));
            }

            if (!string.IsNullOrEmpty(UserAgentString))
            {
                client.DefaultRequestHeaders.Add("user-agent", UserAgentString);
                client.DefaultRequestHeaders.Add("X-NuGet-Client-Version", MinClientVersionUtility.GetNuGetClientVersion().ToNormalizedString());
            }
        }
Exemplo n.º 14
0
        private static void EnsurePackageCompatibility(
            NuGetProject nuGetProject,
            PackageIdentity packageIdentity,
            NuspecReader nuspecReader)
        {
            // Validate that the current version of NuGet satisfies the minVersion attribute specified in the .nuspec
            MinClientVersionUtility.VerifyMinClientVersion(nuspecReader);

            // Validate the package type. There must be zero package types or exactly one package
            // type that is one of the recognized package types.
            var packageTypes   = nuspecReader.GetPackageTypes();
            var identityString = $"{packageIdentity.Id} {packageIdentity.Version.ToNormalizedString()}";

            if (packageTypes.Count > 1)
            {
                throw new PackagingException(string.Format(
                                                 CultureInfo.CurrentCulture,
                                                 Strings.MultiplePackageTypesNotSupported,
                                                 identityString));
            }
            else if (packageTypes.Count == 1)
            {
                var packageType       = packageTypes[0];
                var packageTypeString = packageType.Name;
                if (packageType.Version != PackageType.EmptyVersion)
                {
                    packageTypeString += " " + packageType.Version;
                }

                var projectName = NuGetProject.GetUniqueNameOrName(nuGetProject);

                if (packageType == PackageType.Legacy ||   // Added for "quirks mode", but not yet fully implemented.
                    packageType == PackageType.Dependency) // A package explicitly stated as a dependency.
                {
                    // These types are always acceptable.
                }
                else
                {
                    throw new PackagingException(string.Format(
                                                     CultureInfo.CurrentCulture,
                                                     Strings.UnsupportedPackageType,
                                                     identityString,
                                                     packageTypeString,
                                                     projectName));
                }
            }
        }
Exemplo n.º 15
0
 /// <summary>
 /// Apply standard properties in a property group.
 /// </summary>
 public static void AddNuGetProperties(
     XDocument doc,
     IEnumerable <string> packageFolders,
     string repositoryRoot,
     ProjectStyle projectStyle,
     string assetsFilePath,
     bool success)
 {
     doc.Root.AddFirst(
         new XElement(Namespace + "PropertyGroup",
                      new XAttribute("Condition", $" {ExcludeAllCondition} "),
                      GenerateProperty("RestoreSuccess", success.ToString()),
                      GenerateProperty("RestoreTool", "NuGet"),
                      GenerateProperty("ProjectAssetsFile", assetsFilePath),
                      GenerateProperty("NuGetPackageRoot", ReplacePathsWithMacros(repositoryRoot)),
                      GenerateProperty("NuGetPackageFolders", string.Join(";", packageFolders)),
                      GenerateProperty("NuGetProjectStyle", projectStyle.ToString()),
                      GenerateProperty("NuGetToolVersion", MinClientVersionUtility.GetNuGetClientVersion().ToFullString())));
 }
        public void MinClientVersionUtility_ReadFromNuspecInCompatThrowsVerifyLogMessage()
        {
            // Arrange
            var         nuspec     = GetNuspec("99.0.0");
            ILogMessage logMessage = null;

            // Act
            try
            {
                MinClientVersionUtility.VerifyMinClientVersion(nuspec);
            }
            catch (MinClientVersionException ex)
            {
                logMessage = ex.AsLogMessage();
            }

            // Assert
            Assert.Equal(NuGetLogCode.NU1401, logMessage.Code);
            Assert.Contains("requires NuGet client version", logMessage.Message);
            Assert.Equal(LogLevel.Error, logMessage.Level);
        }
        /// <summary>
        /// Get the list of service entries that best match the current clientVersion and type.
        /// </summary>
        public virtual IReadOnlyList <ServiceIndexEntry> GetServiceEntries(params string[] orderedTypes)
        {
            var clientVersion = MinClientVersionUtility.GetNuGetClientVersion();

            return(GetServiceEntries(clientVersion, orderedTypes));
        }
        /// <summary>
        /// Get the best match service URI.
        /// </summary>
        public virtual Uri GetServiceEntryUri(params string[] orderedTypes)
        {
            var clientVersion = MinClientVersionUtility.GetNuGetClientVersion();

            return(GetServiceEntryUris(clientVersion, orderedTypes).FirstOrDefault());
        }