示例#1
0
        public async Task SubFeed_PushAndVerifyWithNestedFeedsVerifySuccess()
        {
            using (var packagesFolder = new TestFolder())
                using (var testContext = new AzureTestContext())
                    using (var testContext2 = new AzureTestContext())
                    {
                        // Use a subfeed for the filesystem
                        var subFeedName = "testSubFeed";
                        var root        = UriUtility.GetPath(testContext.Uri, subFeedName);
                        testContext.FileSystem = new AzureFileSystem(testContext.LocalCache, root, root, testContext.StorageAccount, testContext.ContainerName, feedSubPath: subFeedName);

                        await testContext.InitAsync();

                        await testContext2.InitAsync();

                        var testPackage = new TestNupkg("packageA", "1.0.0");
                        var zipFile     = testPackage.Save(packagesFolder.Root);

                        var result = await InitCommand.RunAsync(testContext.LocalSettings,
                                                                testContext.FileSystem,
                                                                enableCatalog : true,
                                                                enableSymbols : true,
                                                                log : testContext.Logger,
                                                                token : CancellationToken.None);

                        result &= await InitCommand.RunAsync(testContext.LocalSettings,
                                                             testContext2.FileSystem,
                                                             enableCatalog : true,
                                                             enableSymbols : true,
                                                             log : testContext2.Logger,
                                                             token : CancellationToken.None);

                        result &= await PushCommand.RunAsync(testContext.LocalSettings,
                                                             testContext.FileSystem,
                                                             new List <string>() { zipFile.FullName },
                                                             force : false,
                                                             skipExisting : false,
                                                             log : testContext.Logger);

                        result &= await PushCommand.RunAsync(testContext.LocalSettings,
                                                             testContext2.FileSystem,
                                                             new List <string>() { zipFile.FullName },
                                                             force : false,
                                                             skipExisting : false,
                                                             log : testContext2.Logger);

                        result &= await ValidateCommand.RunAsync(testContext.LocalSettings,
                                                                 testContext.FileSystem,
                                                                 testContext.Logger);

                        result &= await ValidateCommand.RunAsync(testContext.LocalSettings,
                                                                 testContext2.FileSystem,
                                                                 testContext2.Logger);

                        result.Should().BeTrue();

                        await testContext.CleanupAsync();

                        await testContext2.CleanupAsync();
                    }
        }
        private bool IsSourceNuGetSymbolServer(string source)
        {
            var sourceUri = UriUtility.CreateSourceUri(source);

            return(sourceUri.Host.Equals(NuGetConstants.NuGetSymbolHostName, StringComparison.OrdinalIgnoreCase));
        }
示例#3
0
        /// <summary>
        /// Retrieves all packages with the given Id from a V2 feed.
        /// </summary>
        public async Task <IReadOnlyList <V2FeedPackageInfo> > FindPackagesByIdAsync(
            string id,
            bool includeUnlisted,
            bool includePrerelease,
            ILogger log,
            CancellationToken token)
        {
            if (string.IsNullOrEmpty(id))
            {
                throw new ArgumentException(nameof(id));
            }

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

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

            var uri = string.Format(CultureInfo.InvariantCulture, FindPackagesByIdFormat, UriUtility.UrlEncodeOdataParameter(id));
            // Set max count to -1, get all packages
            var packages = await QueryV2Feed(
                uri,
                id,
                max : -1,
                ignoreNotFounds : false,
                log : log,
                token : token);

            var filtered = packages.Where(p => (includeUnlisted || p.IsListed) &&
                                          (includePrerelease || !p.Version.IsPrerelease));

            return(filtered.OrderByDescending(p => p.Version).Distinct().ToList());
        }
示例#4
0
        public void FromPatternKeyValuePairs()
        {
            var parameters = new SortedDictionary <string, object>()
            {
                ["x"] = "r&d",
                ["y"] = "pb&j",
                ["z"] = "zed",
                ["a"] = true,
                ["b"] = 0,
                ["c"] = TimeSpan.Zero,
                ["d"] = null,
            };

            Assert.AreEqual("http://example.com/r%26d?y=pb%26j&a=true&b=0&c=00%3A00%3A00&z=zed", UriUtility.FromPattern("http://example.com/{x}?y={y}", parameters).AbsoluteUri);
        }
示例#5
0
        public void MatchesDomainArgumentException(string uristring, string domain)
        {
            Uri uri = new Uri(uristring, UriKind.Relative);

            Assert.Throws <ArgumentException>(() => UriUtility.MatchesDomain(uri, domain));
        }
示例#6
0
 public void TestExpandUriWithAbsoluteUri()
 {
     AssertEqual("http://pauthor.codeplex.com/", UriUtility.ExpandUri("http://pauthor.codeplex.com"));
     AssertEqual("http://pauthor.codeplex.com/documentation",
                 UriUtility.ExpandUri("http://pauthor.codeplex.com/documentation"));
 }
示例#7
0
 public void TestCombineWithTwoRelativeLocalPaths()
 {
     AssertEqual(Path.GetFullPath(@"..\..\Resources\DeepZoom"),
                 UriUtility.Combine(@"..\..\Resources", "DeepZoom"));
 }
示例#8
0
        public async Task GivenThatIRemoveAllPackagesWithTheCatalogDisabledVerifyItSucceeds()
        {
            // Arrange
            using (var packagesFolder = new TestFolder())
                using (var target = new TestFolder())
                    using (var cache = new LocalCache())
                    {
                        var log        = new TestLogger();
                        var fileSystem = new PhysicalFileSystem(cache, UriUtility.CreateUri(target.Root));
                        var settings   = new LocalSettings();

                        var context = new SleetContext()
                        {
                            Token          = CancellationToken.None,
                            LocalSettings  = settings,
                            Log            = log,
                            Source         = fileSystem,
                            SourceSettings = new FeedSettings()
                            {
                                CatalogEnabled = true
                            }
                        };

                        context.SourceSettings.CatalogEnabled = false;

                        var testPackage1 = new TestNupkg("packageA", "1.0.1");
                        var testPackage2 = new TestNupkg("packageA", "1.0.2");
                        var testPackage3 = new TestNupkg("packageA", "1.0.3");

                        var zipFile1 = testPackage1.Save(packagesFolder.Root);
                        var zipFile2 = testPackage2.Save(packagesFolder.Root);
                        var zipFile3 = testPackage3.Save(packagesFolder.Root);

                        var catalog      = new Catalog(context);
                        var registration = new Registrations(context);
                        var packageIndex = new PackageIndex(context);
                        var search       = new Search(context);
                        var autoComplete = new AutoComplete(context);

                        // Act
                        // run commands
                        await InitCommand.InitAsync(context);

                        await PushCommand.RunAsync(context.LocalSettings, context.Source, new List <string>() { zipFile1.FullName }, false, false, context.Log);

                        await PushCommand.RunAsync(context.LocalSettings, context.Source, new List <string>() { zipFile2.FullName }, false, false, context.Log);

                        await PushCommand.RunAsync(context.LocalSettings, context.Source, new List <string>() { zipFile3.FullName }, false, false, context.Log);

                        await DeleteCommand.RunAsync(context.LocalSettings, context.Source, "packageA", "1.0.3", "", false, context.Log);

                        await DeleteCommand.RunAsync(context.LocalSettings, context.Source, "packageA", "1.0.1", "", false, context.Log);

                        await DeleteCommand.RunAsync(context.LocalSettings, context.Source, "packageA", "1.0.2", "", false, context.Log);

                        var validateOutput = await ValidateCommand.RunAsync(context.LocalSettings, context.Source, context.Log);

                        // read outputs
                        var catalogEntries = await catalog.GetIndexEntriesAsync();

                        var catalogExistingEntries = await catalog.GetExistingPackagesIndexAsync();

                        var regPackages = await registration.GetPackagesByIdAsync("packageA");

                        var indexPackages = await packageIndex.GetPackagesAsync();

                        var searchPackages = await search.GetPackagesAsync();

                        var autoCompletePackages = await autoComplete.GetPackageIds();

                        // Assert
                        validateOutput.Should().BeTrue("the feed is valid");
                        catalogEntries.Should().BeEmpty("the catalog is disabled");
                        catalogExistingEntries.Should().BeEmpty("the catalog is disabled");
                        regPackages.Should().BeEmpty("all packages were removed");
                        indexPackages.Should().BeEmpty("all packages were removed");
                        searchPackages.Should().BeEmpty("all packages were removed");
                        autoCompletePackages.Should().BeEmpty("all packages were removed");
                    }
        }
示例#9
0
        public async Task AddRemove_AddAndRemovePackageAsync()
        {
            // Arrange
            using (var packagesFolder = new TestFolder())
                using (var target = new TestFolder())
                    using (var cache = new LocalCache())
                    {
                        var log        = new TestLogger();
                        var fileSystem = new PhysicalFileSystem(cache, UriUtility.CreateUri(target.Root));
                        var settings   = new LocalSettings();

                        var context = new SleetContext()
                        {
                            Token          = CancellationToken.None,
                            LocalSettings  = settings,
                            Log            = log,
                            Source         = fileSystem,
                            SourceSettings = new FeedSettings()
                            {
                                CatalogEnabled = true
                            }
                        };

                        var testPackage = new TestNupkg("packageA", "1.0.0");

                        var zipFile = testPackage.Save(packagesFolder.Root);
                        using (var zip = new ZipArchive(File.OpenRead(zipFile.FullName), ZipArchiveMode.Read, false))
                        {
                            var input = new PackageInput(zipFile.FullName, new PackageIdentity("packageA", NuGetVersion.Parse("1.0.0")), false)
                            {
                                Zip     = zip,
                                Package = new PackageArchiveReader(zip)
                            };

                            var catalog      = new Catalog(context);
                            var registration = new Registrations(context);
                            var packageIndex = new PackageIndex(context);
                            var search       = new Search(context);
                            var autoComplete = new AutoComplete(context);

                            // Act
                            // run commands
                            await InitCommand.InitAsync(context);

                            await PushCommand.RunAsync(context.LocalSettings, context.Source, new List <string>() { zipFile.FullName }, false, false, context.Log);

                            await DeleteCommand.RunAsync(context.LocalSettings, context.Source, "packageA", "1.0.0", string.Empty, false, context.Log);

                            var validateOutput = await ValidateCommand.RunAsync(context.LocalSettings, context.Source, context.Log);

                            // read outputs
                            var catalogEntries = await catalog.GetIndexEntriesAsync();

                            var catalogExistingEntries = await catalog.GetExistingPackagesIndexAsync();

                            var catalogLatest = await catalog.GetLatestEntryAsync(input.Identity);

                            var regPackages = await registration.GetPackagesByIdAsync(input.Identity.Id);

                            var indexPackages = await packageIndex.GetPackagesAsync();

                            var searchPackages = await search.GetPackagesAsync();

                            var autoCompletePackages = await autoComplete.GetPackageIds();

                            // Assert
                            Assert.True(validateOutput);
                            Assert.Equal(2, catalogEntries.Count);
                            Assert.Equal(0, catalogExistingEntries.Count);
                            Assert.Equal(0, regPackages.Count);
                            Assert.Equal(0, indexPackages.Count);
                            Assert.Equal(0, searchPackages.Count);
                            Assert.Equal(0, autoCompletePackages.Count);

                            Assert.Equal("packageA", catalogLatest.Id);
                            Assert.Equal("1.0.0", catalogLatest.Version.ToIdentityString());
                            Assert.Equal(SleetOperation.Remove, catalogLatest.Operation);
                        }
                    }
        }
示例#10
0
        public async Task NuGetReader_DependencyInfoResource_DependencyGroupsAsync()
        {
            // Arrange
            using (var packagesFolder = new TestFolder())
                using (var target = new TestFolder())
                    using (var cache = new LocalCache())
                    {
                        var outputRoot = Path.Combine(target.Root, "output");
                        var baseUri    = UriUtility.CreateUri("https://localhost:8080/testFeed/");

                        var log = new TestLogger();

                        var testPackage = new TestNupkg()
                        {
                            Nuspec = new TestNuspec()
                            {
                                Id           = "packageA",
                                Version      = "1.0.0",
                                Dependencies = new List <PackageDependencyGroup>()
                                {
                                    new PackageDependencyGroup(NuGetFramework.Parse("net46"), new List <PackageDependency>()
                                    {
                                    }),
                                    new PackageDependencyGroup(NuGetFramework.Parse("net45"), new[] { new PackageDependency("packageB", VersionRange.Parse("1.0.0")), new PackageDependency("packageC", VersionRange.Parse("2.0.0")) }),
                                    new PackageDependencyGroup(NuGetFramework.Parse("any"), new List <PackageDependency>()
                                    {
                                        new PackageDependency("packageB", VersionRange.Parse("1.0.0"))
                                    })
                                }
                            }
                        };

                        var sleetConfig = TestUtility.CreateConfigWithLocal("local", outputRoot, baseUri.AbsoluteUri);

                        var sleetConfigPath = Path.Combine(target.Root, "sleet.config");
                        await JsonUtility.SaveJsonAsync(new FileInfo(sleetConfigPath), sleetConfig);

                        var zipFile = testPackage.Save(packagesFolder.Root);

                        var settings   = LocalSettings.Load(sleetConfigPath);
                        var fileSystem = FileSystemFactory.CreateFileSystem(settings, cache, "local");
                        var success    = await InitCommand.RunAsync(settings, fileSystem, log);

                        // Act
                        // Run sleet
                        success &= await PushCommand.RunAsync(settings, fileSystem, new List <string>() { zipFile.FullName }, false, false, log);

                        // Create a repository abstraction for nuget
                        var nugetFileSystem = new PhysicalFileSystem(cache, UriUtility.CreateUri(outputRoot), baseUri);
                        var localSource     = GetSource(outputRoot, baseUri, nugetFileSystem);
                        var cacheContext    = new SourceCacheContext();

                        var dependencyInfoResource = await localSource.GetResourceAsync <DependencyInfoResource>();

                        var dependencyPackagesNet46 = await dependencyInfoResource.ResolvePackages("packageA", NuGetFramework.Parse("net46"), cacheContext, log, CancellationToken.None);

                        var dependencyPackageNet46 = dependencyPackagesNet46.Single();
                        var depString46            = string.Join("|", dependencyPackageNet46.Dependencies.Select(d => d.Id + " " + d.VersionRange.ToNormalizedString()));

                        var dependencyPackagesNet45 = await dependencyInfoResource.ResolvePackages("packageA", NuGetFramework.Parse("net45"), cacheContext, log, CancellationToken.None);

                        var dependencyPackageNet45 = dependencyPackagesNet45.Single();
                        var depString45            = string.Join("|", dependencyPackageNet45.Dependencies.Select(d => d.Id + " " + d.VersionRange.ToNormalizedString()));

                        var dependencyPackagesNet40 = await dependencyInfoResource.ResolvePackages("packageA", NuGetFramework.Parse("net40"), cacheContext, log, CancellationToken.None);

                        var dependencyPackageNet40 = dependencyPackagesNet40.Single();
                        var depString40            = string.Join("|", dependencyPackageNet40.Dependencies.Select(d => d.Id + " " + d.VersionRange.ToNormalizedString()));

                        // Assert
                        Assert.True(success, log.ToString());

                        Assert.Equal("https://localhost:8080/testFeed/flatcontainer/packagea/1.0.0/packagea.1.0.0.nupkg", dependencyPackageNet46.DownloadUri.AbsoluteUri);
                        Assert.True(dependencyPackageNet46.Listed);
                        Assert.Equal("packageA", dependencyPackageNet46.Id);
                        Assert.Equal("1.0.0", dependencyPackageNet46.Version.ToNormalizedString());
                        Assert.Equal("", depString46);
                        Assert.Equal("packageB [1.0.0, )|packageC [2.0.0, )", depString45);
                        Assert.Equal("packageB [1.0.0, )", depString40);
                    }
        }
示例#11
0
        public async Task GivenThatIAddAPackageWithTheCatalogDisabledVerifyItSucceeds()
        {
            // Arrange
            using (var packagesFolder = new TestFolder())
                using (var target = new TestFolder())
                    using (var cache = new LocalCache())
                    {
                        var log        = new TestLogger();
                        var fileSystem = new PhysicalFileSystem(cache, UriUtility.CreateUri(target.Root));
                        var settings   = new LocalSettings();

                        var context = new SleetContext()
                        {
                            Token          = CancellationToken.None,
                            LocalSettings  = settings,
                            Log            = log,
                            Source         = fileSystem,
                            SourceSettings = new FeedSettings()
                            {
                                CatalogEnabled = true
                            }
                        };

                        context.SourceSettings.CatalogEnabled = false;

                        var testPackage = new TestNupkg("packageA", "1.0.0");

                        var zipFile = testPackage.Save(packagesFolder.Root);
                        using (var zip = new ZipArchive(File.OpenRead(zipFile.FullName), ZipArchiveMode.Read, false))
                        {
                            var input = new PackageInput(zipFile.FullName, new PackageIdentity("packageA", NuGetVersion.Parse("1.0.0")), false)
                            {
                                Zip     = zip,
                                Package = new PackageArchiveReader(zip)
                            };

                            var catalog      = new Catalog(context);
                            var registration = new Registrations(context);
                            var packageIndex = new PackageIndex(context);
                            var search       = new Search(context);
                            var autoComplete = new AutoComplete(context);

                            // Act
                            // run commands
                            await InitCommand.InitAsync(context);

                            await PushCommand.RunAsync(context.LocalSettings, context.Source, new List <string>() { zipFile.FullName }, false, false, context.Log);

                            var validateOutput = await ValidateCommand.RunAsync(context.LocalSettings, context.Source, context.Log);

                            // read outputs
                            var catalogEntries = await catalog.GetIndexEntriesAsync();

                            var catalogExistingEntries = await catalog.GetExistingPackagesIndexAsync();

                            var catalogLatest = await catalog.GetLatestEntryAsync(input.Identity);

                            var regPackages = await registration.GetPackagesByIdAsync(input.Identity.Id);

                            var indexPackages = await packageIndex.GetPackagesAsync();

                            var searchPackages = await search.GetPackagesAsync();

                            var autoCompletePackages = await autoComplete.GetPackageIds();

                            var catalogEntry = await registration.GetCatalogEntryFromPackageBlob(input.Identity);

                            // Assert
                            validateOutput.Should().BeTrue("the feed is valid");
                            catalogEntries.Should().BeEmpty("the catalog is disabled");
                            catalogExistingEntries.Should().BeEmpty("the catalog is disabled");
                            regPackages.Should().BeEquivalentTo(new[] { input.Identity });
                            indexPackages.Should().BeEquivalentTo(new[] { input.Identity });
                            searchPackages.Should().BeEquivalentTo(new[] { input.Identity });
                            autoCompletePackages.Should().BeEquivalentTo(new[] { input.Identity.Id });

                            catalogLatest.Should().BeNull();
                            catalogEntry["version"].ToString().Should().Be("1.0.0");
                            catalogEntry["sleet:operation"].ToString().Should().Be("add");
                        }
                    }
        }
示例#12
0
        public async Task NuGetReader_PackageSearchResourceAsync()
        {
            // Arrange
            using (var packagesFolder = new TestFolder())
                using (var target = new TestFolder())
                    using (var cache = new LocalCache())
                    {
                        var outputRoot = Path.Combine(target.Root, "output");
                        var baseUri    = UriUtility.CreateUri("https://localhost:8080/testFeed/");

                        var log = new TestLogger();

                        var testPackage = new TestNupkg()
                        {
                            Nuspec = new TestNuspec()
                            {
                                Id                       = "packageA",
                                Version                  = "1.0.0",
                                Authors                  = "author",
                                Description              = "desc",
                                IconUrl                  = "http://www.tempuri.org",
                                Language                 = "en-us",
                                MinClientVersion         = "1.0.0",
                                Title                    = "title",
                                Tags                     = "a b d",
                                Summary                  = "summary",
                                LicenseUrl               = "http://www.tempuri.org/lic",
                                ProjectUrl               = "http://www.tempuri.org/proj",
                                ReleaseNotes             = "notes",
                                Owners                   = "owners",
                                Copyright                = "copyright",
                                RequireLicenseAcceptance = "true"
                            }
                        };

                        var testPackage2 = new TestNupkg()
                        {
                            Nuspec = new TestNuspec()
                            {
                                Id                       = "packageA",
                                Version                  = "2.0.0",
                                Authors                  = "author2",
                                Description              = "desc2",
                                IconUrl                  = "http://www.tempuri2.org/",
                                Language                 = "en-us",
                                MinClientVersion         = "1.0.0",
                                Title                    = "title2",
                                Tags                     = "a b c",
                                Summary                  = "summary2",
                                LicenseUrl               = "http://www.tempuri.org/lic2",
                                ProjectUrl               = "http://www.tempuri.org/proj2",
                                ReleaseNotes             = "notes2",
                                Owners                   = "owners2",
                                Copyright                = "copyright2",
                                RequireLicenseAcceptance = "true"
                            }
                        };

                        var sleetConfig = TestUtility.CreateConfigWithLocal("local", outputRoot, baseUri.AbsoluteUri);

                        var sleetConfigPath = Path.Combine(target.Root, "sleet.config");
                        await JsonUtility.SaveJsonAsync(new FileInfo(sleetConfigPath), sleetConfig);

                        var zipFile  = testPackage.Save(packagesFolder.Root);
                        var zipFile2 = testPackage2.Save(packagesFolder.Root);

                        var settings   = LocalSettings.Load(sleetConfigPath);
                        var fileSystem = FileSystemFactory.CreateFileSystem(settings, cache, "local");
                        var success    = await InitCommand.RunAsync(settings, fileSystem, log);

                        // Act
                        // Run sleet
                        success &= await PushCommand.RunAsync(settings, fileSystem, new List <string>() { zipFile2.FullName }, false, false, log);

                        success &= await PushCommand.RunAsync(settings, fileSystem, new List <string>() { zipFile.FullName }, false, false, log);

                        // Create a repository abstraction for nuget
                        var nugetFileSystem = new PhysicalFileSystem(cache, UriUtility.CreateUri(outputRoot), baseUri);
                        var localSource     = GetSource(outputRoot, baseUri, nugetFileSystem);

                        var resource = await localSource.GetResourceAsync <PackageSearchResource>();

                        var results = await resource.SearchAsync(string.Empty, new SearchFilter(includePrerelease : true), 0, 10, log, CancellationToken.None);

                        var result = results.Single();

                        var versions = await result.GetVersionsAsync();

                        // Assert
                        Assert.True(success, log.ToString());

                        Assert.Equal(testPackage2.Nuspec.Authors, result.Authors);
                        Assert.Equal(testPackage2.Nuspec.Description, result.Description);
                        Assert.Equal(0, result.DownloadCount);
                        Assert.Equal(testPackage2.Nuspec.IconUrl, result.IconUrl.AbsoluteUri);
                        Assert.Equal(testPackage2.Nuspec.Id, result.Identity.Id);
                        Assert.Equal(testPackage2.Nuspec.Version.ToString(), result.Identity.Version.ToString());
                        Assert.Equal(testPackage2.Nuspec.LicenseUrl, result.LicenseUrl.AbsoluteUri);
                        Assert.Equal(testPackage2.Nuspec.Owners, result.Owners);
                        Assert.Equal(testPackage2.Nuspec.ProjectUrl, result.ProjectUrl.AbsoluteUri);
                        Assert.Equal(testPackage2.Nuspec.Summary, result.Summary);
                        Assert.Equal("a, b, c", result.Tags);
                        Assert.Equal(testPackage2.Nuspec.Title, result.Title);

                        Assert.Equal(2, versions.Count());
                        Assert.Equal("1.0.0", versions.First().Version.ToString());
                        Assert.Equal("2.0.0", versions.Skip(1).First().Version.ToString());
                    }
        }
        public override bool Execute()
        {
            var log = new MSBuildLogger(Log);

            // Log Inputs
            BuildTasksUtility.LogInputParam(log, nameof(ProjectUniqueName), ProjectUniqueName);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreSources), RestoreSources);
            BuildTasksUtility.LogInputParam(log, nameof(RestorePackagesPath), RestorePackagesPath);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreFallbackFolders), RestoreFallbackFolders);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreConfigFile), RestoreConfigFile);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreSolutionDirectory), RestoreSolutionDirectory);
            BuildTasksUtility.LogInputParam(log, nameof(RestorePackagesPathOverride), RestorePackagesPathOverride);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreSourcesOverride), RestoreSourcesOverride);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreFallbackFoldersOverride), RestoreFallbackFoldersOverride);
            BuildTasksUtility.LogInputParam(log, nameof(MSBuildStartupDirectory), MSBuildStartupDirectory);

            try
            {
                // Validate inputs
                if (RestoreSourcesOverride == null &&
                    MSBuildRestoreUtility.LogErrorForClearIfInvalid(RestoreSources, ProjectUniqueName, log))
                {
                    // Fail due to invalid source combination
                    return(false);
                }

                if (RestoreFallbackFoldersOverride == null &&
                    MSBuildRestoreUtility.LogErrorForClearIfInvalid(RestoreFallbackFolders, ProjectUniqueName, log))
                {
                    // Fail due to invalid fallback combination
                    return(false);
                }

                // Settings
                // Find the absolute path of nuget.config, this should only be set on the command line. Setting the path in project files
                // is something that could happen, but it is not supported.
                var absoluteConfigFilePath = GetGlobalAbsolutePath(RestoreConfigFile);
                var settings = RestoreSettingsUtils.ReadSettings(RestoreSolutionDirectory, Path.GetDirectoryName(ProjectUniqueName), absoluteConfigFilePath, _machineWideSettings);
                OutputConfigFilePaths = SettingsUtility.GetConfigFilePaths(settings).ToArray();

                // PackagesPath
                OutputPackagesPath = RestoreSettingsUtils.GetValue(
                    () => GetGlobalAbsolutePath(RestorePackagesPathOverride),
                    () => string.IsNullOrEmpty(RestorePackagesPath) ? null : UriUtility.GetAbsolutePathFromFile(ProjectUniqueName, RestorePackagesPath),
                    () => SettingsUtility.GetGlobalPackagesFolder(settings));

                // Sources
                var currentSources = RestoreSettingsUtils.GetValue(
                    () => RestoreSourcesOverride?.Select(MSBuildRestoreUtility.FixSourcePath).Select(e => GetGlobalAbsolutePath(e)).ToArray(),
                    () => MSBuildRestoreUtility.ContainsClearKeyword(RestoreSources) ? new string[0] : null,
                    () => RestoreSources?.Select(MSBuildRestoreUtility.FixSourcePath).Select(e => UriUtility.GetAbsolutePathFromFile(ProjectUniqueName, e)).ToArray(),
                    () => (new PackageSourceProvider(settings)).LoadPackageSources().Where(e => e.IsEnabled).Select(e => e.Source).ToArray());

                // Append additional sources
                // Escape strings to avoid xplat path issues with msbuild.
                var additionalProjectSources = MSBuildRestoreUtility.AggregateSources(
                    values: GetPropertyValues(RestoreSettingsPerFramework, "RestoreAdditionalProjectSources"),
                    excludeValues: Enumerable.Empty <string>())
                                               .Select(MSBuildRestoreUtility.FixSourcePath)
                                               .ToArray();

                OutputSources = AppendItems(currentSources, additionalProjectSources);

                // Fallback folders
                var currentFallbackFolders = RestoreSettingsUtils.GetValue(
                    () => RestoreFallbackFoldersOverride?.Select(e => GetGlobalAbsolutePath(e)).ToArray(),
                    () => MSBuildRestoreUtility.ContainsClearKeyword(RestoreFallbackFolders) ? new string[0] : null,
                    () => RestoreFallbackFolders?.Select(e => UriUtility.GetAbsolutePathFromFile(ProjectUniqueName, e)).ToArray(),
                    () => SettingsUtility.GetFallbackPackageFolders(settings).ToArray());

                // Append additional fallback folders after removing excluded folders
                var additionalProjectFallbackFolders = MSBuildRestoreUtility.AggregateSources(
                    values: GetPropertyValues(RestoreSettingsPerFramework, "RestoreAdditionalProjectFallbackFolders"),
                    excludeValues: GetPropertyValues(RestoreSettingsPerFramework, "RestoreAdditionalProjectFallbackFoldersExcludes"))
                                                       .ToArray();

                OutputFallbackFolders = AppendItems(currentFallbackFolders, additionalProjectFallbackFolders);
            }
            catch (Exception ex)
            {
                // Log exceptions with error codes if they exist.
                ExceptionUtilities.LogException(ex, log);
                return(false);
            }

            // Log Outputs
            BuildTasksUtility.LogOutputParam(log, nameof(OutputPackagesPath), OutputPackagesPath);
            BuildTasksUtility.LogOutputParam(log, nameof(OutputSources), OutputSources);
            BuildTasksUtility.LogOutputParam(log, nameof(OutputFallbackFolders), OutputFallbackFolders);
            BuildTasksUtility.LogOutputParam(log, nameof(OutputConfigFilePaths), OutputConfigFilePaths);

            return(true);
        }
示例#14
0
        public async Task Feed_VerifyBaseUriIsAppliedToLocal(string baseUriString)
        {
            // Arrange
            using (var packagesFolder = new TestFolder())
                using (var target = new TestFolder())
                    using (var cache = new LocalCache())
                    {
                        var log = new TestLogger();

                        var fileSystemRoot = UriUtility.CreateUri(target.Root);
                        var baseUri        = new Uri(baseUriString);

                        var fileSystem = new PhysicalFileSystem(cache, fileSystemRoot, baseUri);
                        var settings   = new LocalSettings();

                        var context = new SleetContext()
                        {
                            Token          = CancellationToken.None,
                            LocalSettings  = settings,
                            Log            = log,
                            Source         = fileSystem,
                            SourceSettings = new FeedSettings()
                            {
                                CatalogEnabled = true,
                                SymbolsEnabled = true
                            }
                        };

                        var testPackage = new TestNupkg("packageA", "1.0.0");
                        var zipFile     = testPackage.Save(packagesFolder.Root);
                        using (var zip = new ZipArchive(File.OpenRead(zipFile.FullName), ZipArchiveMode.Read, false))
                        {
                            var input = new PackageInput(zipFile.FullName, new PackageIdentity("packageA", NuGetVersion.Parse("1.0.0")), false)
                            {
                                Zip     = zip,
                                Package = new PackageArchiveReader(zip)
                            };

                            var catalog      = new Catalog(context);
                            var registration = new Registrations(context);
                            var packageIndex = new PackageIndex(context);
                            var search       = new Search(context);
                            var autoComplete = new AutoComplete(context);

                            // Act
                            // run commands
                            await InitCommand.InitAsync(context);

                            await PushCommand.RunAsync(context.LocalSettings, context.Source, new List <string>() { zipFile.FullName }, false, false, context.Log);

                            var validateOutput = await ValidateCommand.RunAsync(context.LocalSettings, context.Source, context.Log);

                            // read outputs
                            var catalogEntries = await catalog.GetIndexEntriesAsync();

                            var catalogExistingEntries = await catalog.GetExistingPackagesIndexAsync();

                            var catalogLatest = await catalog.GetLatestEntryAsync(input.Identity);

                            var regPackages = await registration.GetPackagesByIdAsync(input.Identity.Id);

                            var indexPackages = await packageIndex.GetPackagesAsync();

                            var searchPackages = await search.GetPackagesAsync();

                            var autoCompletePackages = await autoComplete.GetPackageIds();

                            // Assert
                            Assert.True(validateOutput);
                            Assert.Equal(1, catalogEntries.Count);
                            Assert.Equal(1, catalogExistingEntries.Count);
                            Assert.Equal(1, regPackages.Count);
                            Assert.Equal(1, indexPackages.Count);
                            Assert.Equal(1, searchPackages.Count);
                            Assert.Equal(1, autoCompletePackages.Count);

                            // Walk json to check for bad urls
                            await TestUtility.WalkJsonAsync(target.Root, (file, json, toCheck) =>
                            {
                                // Check only URLs found
                                if (toCheck.IndexOf("://") > -1)
                                {
                                    var cleanUriSchema = toCheck.Replace(":///", string.Empty).Replace("://", string.Empty);

                                    var doubleSlash = cleanUriSchema.IndexOf("//") > -1;
                                    Assert.False(doubleSlash, toCheck);
                                }
                            });
                        }
                    }
        }
示例#15
0
 public void TestExpandUriWithAbsoluteLocalPath()
 {
     AssertEqual(@"c:\Windows", UriUtility.ExpandUri(@"c:\Windows"));
     AssertEqual(@"c:\Windows", UriUtility.ExpandUri("file:///c:/Windows"));
 }
示例#16
0
        public static XRefDetails From(HtmlNode node)
        {
            if (node.Name != "xref")
            {
                throw new NotSupportedException("Only xref node is supported!");
            }
            var rawUid = node.GetAttributeValue("uid", null);
            var xref   = new XRefDetails()
            {
                InnerHtml             = node.InnerHtml,
                Uid                   = rawUid,
                SourceFile            = node.GetAttributeValue("sourceFile", null),
                SourceStartLineNumber = node.GetAttributeValue("sourceStartLineNumber", 0),
                SourceEndLineNumber   = node.GetAttributeValue("sourceEndLineNumber", 0),
                RawSource             = node.GetAttributeValue("data-raw-source", null),
                ThrowIfNotResolved    = node.GetAttributeValue("data-throw-if-not-resolved", false),
                TemplatePath          = StringHelper.HtmlDecode(node.GetAttributeValue("template", null)),
            };

            var rawHref = node.GetAttributeValue("href", null);

            if (!string.IsNullOrEmpty(rawHref))
            {
                if (!string.IsNullOrEmpty(rawUid))
                {
                    Logger.LogWarning($"Both href and uid attribute are defined for {node.OuterHtml}, use href instead of uid.");
                }

                var(path, query, fragment) = UriUtility.Split(rawHref);
                xref.Uid    = HttpUtility.UrlDecode(path);
                xref.Anchor = fragment;

                // extract values from query
                var queryValueCollection = HttpUtility.ParseQueryString(query);
                xref.DisplayProperty = ExtractValue(queryValueCollection, "displayProperty") ?? xref.DisplayProperty;
                xref.AltProperty     = ExtractValue(queryValueCollection, "altProperty") ?? xref.AltProperty;
                xref.Text            = StringHelper.HtmlEncode(ExtractValue(queryValueCollection, "text")) ?? xref.Text;
                xref.Alt             = StringHelper.HtmlEncode(ExtractValue(queryValueCollection, "alt")) ?? xref.Alt;
                xref.Title           = ExtractValue(queryValueCollection, "title") ?? xref.Title;

                var remainingQuery = queryValueCollection.ToString();
                xref.Query = string.IsNullOrEmpty(remainingQuery) ? string.Empty : "?" + remainingQuery;
            }

            // extract values from HTML attributes
            xref.DisplayProperty = node.GetAttributeValue("displayProperty", xref.DisplayProperty);
            xref.AltProperty     = node.GetAttributeValue("altProperty", xref.AltProperty);
            xref.Text            = node.GetAttributeValue("text", node.GetAttributeValue("name", xref.Text));
            xref.Alt             = node.GetAttributeValue("alt", node.GetAttributeValue("fullname", xref.Alt));
            xref.Title           = node.GetAttributeValue("title", xref.Title);

            // Both `data-raw-html` and `data-raw-source` are html encoded. Use `data-raw-html` with higher priority.
            // `data-raw-html` will be decoded then displayed, while `data-raw-source` will be displayed directly.
            var raw = node.GetAttributeValue("data-raw-html", null);

            if (!string.IsNullOrEmpty(raw))
            {
                xref.Raw = StringHelper.HtmlDecode(raw);
            }
            else
            {
                xref.Raw = xref.RawSource;
            }

            return(xref);

            string ExtractValue(NameValueCollection collection, string properName)
            {
                var value = collection[properName];

                collection.Remove(properName);
                return(value);
            }
        }
示例#17
0
 public void TestExpandUriWithRelativeLocalPath()
 {
     AssertMatches(@".*\\Test\\PauthorTestRunner\\bin\\.*\\PauthorTestRunner.exe",
                   UriUtility.ExpandUri("PauthorTestRunner.exe"));
 }
        private DownloadResourceResult DownloadFromIdentity(
            PackageIdentity identity,
            IPackageRepository repository,
            NuGet.Common.ILogger logger,
            CancellationToken token)
        {
            var version         = SemanticVersion.Parse(identity.Version.ToString());
            var dataServiceRepo = repository as DataServicePackageRepository;

            if (dataServiceRepo != null)
            {
                // Clone the repo to allow for concurrent calls
                var sourceUri = UriUtility.CreateSourceUri(dataServiceRepo.Source);
                dataServiceRepo = new DataServicePackageRepository(sourceUri);

                var package            = dataServiceRepo.FindPackage(identity.Id, version);
                var dataServicePackage = package as DataServicePackage;

                if (dataServicePackage != null)
                {
                    token.ThrowIfCancellationRequested();

                    // For online sources get the url and retrieve it with cancel support
                    var url = dataServicePackage.DownloadUrl;

                    var downloadedPackage = DownloadToMachineCache(
                        MachineCache.Default,
                        identity,
                        dataServiceRepo,
                        url,
                        logger,
                        token);

                    if (downloadedPackage != null)
                    {
                        return(new DownloadResourceResult(downloadedPackage.GetStream()));
                    }
                }
            }
            else
            {
                var package = repository.FindPackage(identity.Id, version);

                if (package != null)
                {
                    // Use a folder reader for unzipped repos
                    if (repository is UnzippedPackageRepository)
                    {
                        var packagePath   = Path.Combine(repository.Source, identity.Id + "." + version);
                        var directoryInfo = new DirectoryInfo(packagePath);
                        if (directoryInfo.Exists)
                        {
                            return(new DownloadResourceResult(
                                       package.GetStream(),
                                       new PackageFolderReader(directoryInfo)));
                        }
                    }

                    return(new DownloadResourceResult(package.GetStream()));
                }
            }

            return(new DownloadResourceResult(DownloadResourceResultStatus.NotFound));
        }
示例#19
0
 public void TestExpandUriWithRelativeUri()
 {
     AssertEqual("foobar.html", UriUtility.ExpandUri("foobar.html"));
     AssertEqual("../../foobar.html", UriUtility.ExpandUri("../../foobar.html"));
     AssertEqual(@"..\..\foobar.html", UriUtility.ExpandUri(@"..\..\foobar.html"));
 }
示例#20
0
        public async Task CatalogTest_CreatePackageDetails_Minimal()
        {
            using (var packagesFolder = new TestFolder())
                using (var target = new TestFolder())
                    using (var cache = new LocalCache())
                    {
                        // Arrange
                        var log        = new TestLogger();
                        var fileSystem = new PhysicalFileSystem(cache, UriUtility.CreateUri(target.Root));
                        var settings   = new LocalSettings();

                        var context = new SleetContext()
                        {
                            Token          = CancellationToken.None,
                            LocalSettings  = settings,
                            Log            = log,
                            Source         = fileSystem,
                            SourceSettings = new FeedSettings()
                            {
                                CatalogEnabled = true
                            }
                        };

                        var catalog     = new Catalog(context);
                        var testPackage = new TestNupkg("packageA", "1.0.0");

                        var zipFile = testPackage.Save(packagesFolder.Root);
                        using (var zip = new ZipArchive(File.OpenRead(zipFile.FullName), ZipArchiveMode.Read, false))
                        {
                            var input = new PackageInput(zipFile.FullName, new PackageIdentity("packageA", NuGetVersion.Parse("1.0.0")), false)
                            {
                                NupkgUri = UriUtility.CreateUri("http://tempuri.org/flatcontainer/packageA/1.0.0/packageA.1.0.0.nupkg"),
                                Zip      = zip,
                                Package  = new PackageArchiveReader(zip)
                            };

                            // Act
                            var actual = await CatalogUtility.CreatePackageDetailsAsync(input, catalog.CatalogBaseURI, context.CommitId, writeFileList : true);

                            var dependencyGroups        = actual["dependencyGroups"] as JArray;
                            var frameworkAssemblyGroups = actual["frameworkAssemblyGroup"] as JArray;
                            var tags = actual["tags"] as JArray;

                            // Assert
                            Assert.EndsWith(".json", actual["@id"].ToString());
                            Assert.Equal(string.Empty, actual["authors"].ToString());
                            Assert.Equal(string.Empty, actual["copyright"].ToString());
                            Assert.Equal(string.Empty, actual["description"].ToString());
                            Assert.Equal(string.Empty, actual["iconUrl"].ToString());
                            Assert.Equal(string.Empty, actual["licenseUrl"].ToString());
                            Assert.Null(actual["minClientVersion"]);
                            Assert.Equal(string.Empty, actual["projectUrl"].ToString());
                            Assert.False(actual["requireLicenseAcceptance"].ToObject <bool>());
                            Assert.Null(actual["title"]);
                            Assert.Equal(testPackage.Nuspec.Id, actual["id"].ToString());
                            Assert.Equal(testPackage.Nuspec.Version, actual["version"].ToString());
                            Assert.EndsWith(".nupkg", actual["packageContent"].ToString());

                            Assert.Empty(dependencyGroups);
                            Assert.Empty(frameworkAssemblyGroups);
                            Assert.Empty(tags);
                        }
                    }
        }
示例#21
0
        public void TestCombineWithAbsoluteAndRelativeLocalPaths()
        {
            String basePath = Path.GetFullPath(@"..\..\Resources");

            AssertEqual(basePath + @"\DeepZoom\sample.cxml", UriUtility.Combine(basePath, "DeepZoom/sample.cxml"));
        }
示例#22
0
        public async Task CatalogTest_CreatePackageDetails()
        {
            using (var packagesFolder = new TestFolder())
                using (var target = new TestFolder())
                    using (var cache = new LocalCache())
                    {
                        // Arrange
                        var log        = new TestLogger();
                        var fileSystem = new PhysicalFileSystem(cache, UriUtility.CreateUri(target.Root));
                        var settings   = new LocalSettings();

                        var context = new SleetContext()
                        {
                            Token          = CancellationToken.None,
                            LocalSettings  = settings,
                            Log            = log,
                            Source         = fileSystem,
                            SourceSettings = new FeedSettings()
                            {
                                CatalogEnabled = true
                            }
                        };

                        var catalog = new Catalog(context);

                        var testPackage = new TestNupkg()
                        {
                            Nuspec = new TestNuspec()
                            {
                                Id                       = "packageA",
                                Version                  = "1.0.0-alpha.1",
                                Authors                  = "authorA, authorB",
                                Copyright                = "Copyright info",
                                Description              = "Package A",
                                IconUrl                  = "http://tempuri.org/icon.png",
                                LicenseUrl               = "http://tempuri.org/license.html",
                                Language                 = "en-us",
                                MinClientVersion         = "3.3.0",
                                DevelopmentDependency    = "true",
                                Owners                   = "ownerA, ownerB",
                                ProjectUrl               = "http://tempuri.org/project.html",
                                ReleaseNotes             = "release 1.0",
                                RequireLicenseAcceptance = "true",
                                Summary                  = "package summary.",
                                Tags                     = "tagA tagB tagC",
                                Title                    = "packageA title",
                                Dependencies             = new List <PackageDependencyGroup>()
                                {
                                    new PackageDependencyGroup(NuGetFramework.AnyFramework, new List <PackageDependency>()
                                    {
                                        new PackageDependency("packageB", VersionRange.Parse("1.0.0"))
                                    }),
                                    new PackageDependencyGroup(NuGetFramework.Parse("net46"), new List <PackageDependency>()),
                                    new PackageDependencyGroup(NuGetFramework.Parse("net45"), new List <PackageDependency>()
                                    {
                                        new PackageDependency("packageAll"),
                                        new PackageDependency("packageExact", VersionRange.Parse("[2.0.0]")),
                                    }),
                                },
                                FrameworkAssemblies = new List <KeyValuePair <string, List <NuGetFramework> > >()
                                {
                                    new KeyValuePair <string, List <NuGetFramework> >("System.IO.Compression", new List <NuGetFramework>()
                                    {
                                        NuGetFramework.Parse("net45"),
                                        NuGetFramework.Parse("win8")
                                    }),
                                    new KeyValuePair <string, List <NuGetFramework> >("System.Threading", new List <NuGetFramework>()
                                    {
                                        NuGetFramework.Parse("net40")
                                    }),
                                    new KeyValuePair <string, List <NuGetFramework> >("System.All", new List <NuGetFramework>()
                                    {
                                    })
                                },
                            }
                        };

                        var zipFile = testPackage.Save(packagesFolder.Root);
                        using (var zip = new ZipArchive(File.OpenRead(zipFile.FullName), ZipArchiveMode.Read, false))
                        {
                            var input = new PackageInput(zipFile.FullName, new PackageIdentity("packageA", NuGetVersion.Parse("1.0.0-alpha.1")), false)
                            {
                                NupkgUri = UriUtility.CreateUri("http://tempuri.org/flatcontainer/packageA/1.0.0-alpha.1/packageA.1.0.0-alpha.1.nupkg"),
                                Zip      = zip,
                                Package  = new PackageArchiveReader(zip)
                            };

                            // Act
                            var actual = await CatalogUtility.CreatePackageDetailsAsync(input, catalog.CatalogBaseURI, context.CommitId, writeFileList : true);

                            var dependencyGroups        = actual["dependencyGroups"] as JArray;
                            var frameworkAssemblyGroups = actual["frameworkAssemblyGroup"] as JArray;

                            // Assert
                            Assert.EndsWith(".json", actual["@id"].ToString());
                            Assert.Contains("/catalog/data/", actual["@id"].ToString());
                            Assert.Equal(testPackage.Nuspec.Authors, actual["authors"].ToString());
                            Assert.Equal(testPackage.Nuspec.Copyright, actual["copyright"].ToString());
                            Assert.Equal(testPackage.Nuspec.Description, actual["description"].ToString());
                            Assert.Equal(testPackage.Nuspec.IconUrl, actual["iconUrl"].ToString());
                            Assert.Equal(testPackage.Nuspec.LicenseUrl, actual["licenseUrl"].ToString());
                            Assert.Equal(testPackage.Nuspec.MinClientVersion, actual["minClientVersion"].ToString());
                            Assert.Equal(testPackage.Nuspec.ProjectUrl, actual["projectUrl"].ToString());
                            Assert.True(actual["requireLicenseAcceptance"].ToObject <bool>());
                            Assert.Equal(testPackage.Nuspec.Title, actual["title"].ToString());
                            Assert.Equal(testPackage.Nuspec.Id, actual["id"].ToString());
                            Assert.Equal(testPackage.Nuspec.Version, actual["version"].ToString());
                            Assert.Equal("tagA", ((JArray)actual["tags"])[0].ToString());
                            Assert.Equal("tagB", ((JArray)actual["tags"])[1].ToString());
                            Assert.Equal("tagC", ((JArray)actual["tags"])[2].ToString());
                            Assert.EndsWith(".nupkg", actual["packageContent"].ToString());

                            Assert.Null(dependencyGroups[0]["targetFramework"]);
                            Assert.Equal("packageB", ((JArray)dependencyGroups[0]["dependencies"]).Single()["id"]);
                            Assert.Equal("[1.0.0, )", ((JArray)dependencyGroups[0]["dependencies"]).Single()["range"]);

                            Assert.Equal("net45", dependencyGroups[1]["targetFramework"]);
                            Assert.NotNull(dependencyGroups[1]["dependencies"]);

                            Assert.Equal("net46", dependencyGroups[2]["targetFramework"]);
                            Assert.Null(dependencyGroups[2]["dependencies"]);

                            Assert.Null(frameworkAssemblyGroups[0]["targetFramework"]);
                            Assert.Equal("net40", frameworkAssemblyGroups[1]["targetFramework"]);
                            Assert.Equal("net45", frameworkAssemblyGroups[2]["targetFramework"]);
                            Assert.Equal("win8", frameworkAssemblyGroups[3]["targetFramework"]);

                            Assert.Equal("System.All", ((JArray)frameworkAssemblyGroups[0]["assembly"]).Single());
                            Assert.Equal("System.Threading", ((JArray)frameworkAssemblyGroups[1]["assembly"]).Single());
                            Assert.Equal("System.IO.Compression", ((JArray)frameworkAssemblyGroups[2]["assembly"]).Single());
                            Assert.Equal("System.IO.Compression", ((JArray)frameworkAssemblyGroups[3]["assembly"]).Single());
                        }
                    }
        }
示例#23
0
        public void MatchesDomainArgumentNullException(string uristring, string domain)
        {
            Uri uri = uristring != null ? new Uri(uristring) : null;

            Assert.Throws <ArgumentNullException>(() => UriUtility.MatchesDomain(uri, domain));
        }
示例#24
0
        public async Task CatalogTest_AddPackageAsync_SupportsWritingMultiplePages()
        {
            using (var packagesFolder = new TestFolder())
                using (var target = new TestFolder())
                    using (var cache = new LocalCache())
                    {
                        // Arrange
                        var log        = new TestLogger();
                        var fileSystem = new PhysicalFileSystem(cache, UriUtility.CreateUri(target.Root));
                        var settings   = new LocalSettings();

                        var context = new SleetContext()
                        {
                            Token          = CancellationToken.None,
                            LocalSettings  = settings,
                            Log            = log,
                            Source         = fileSystem,
                            SourceSettings = new FeedSettings()
                            {
                                CatalogEnabled  = true,
                                CatalogPageSize = 1,
                            }
                        };

                        var catalog      = new Catalog(context);
                        var catalogIndex = TemplateUtility.LoadTemplate(
                            "CatalogIndex",
                            DateTimeOffset.UtcNow,
                            fileSystem.BaseURI);
                        await fileSystem.Get("catalog/index.json").Write(
                            JObject.Parse(catalogIndex),
                            log,
                            context.Token);

                        var testPackageA = new TestNupkg("packageA", "1.0.0");
                        var testPackageB = new TestNupkg("packageB", "1.0.0");

                        var zipFileA = testPackageA.Save(packagesFolder.Root);
                        var zipFileB = testPackageB.Save(packagesFolder.Root);
                        using (var zipA = new ZipArchive(File.OpenRead(zipFileA.FullName), ZipArchiveMode.Read, false))
                            using (var zipB = new ZipArchive(File.OpenRead(zipFileB.FullName), ZipArchiveMode.Read, false))
                            {
                                var inputA = new PackageInput(zipFileA.FullName, new PackageIdentity("packageA", NuGetVersion.Parse("1.0.0")), false)
                                {
                                    NupkgUri = UriUtility.CreateUri("http://tempuri.org/flatcontainer/packageA/1.0.0/packageA.1.0.0.nupkg"),
                                    Zip      = zipA,
                                    Package  = new PackageArchiveReader(zipA)
                                };

                                var inputB = new PackageInput(zipFileB.FullName, new PackageIdentity("packageB", NuGetVersion.Parse("1.0.0")), false)
                                {
                                    NupkgUri = UriUtility.CreateUri("http://tempuri.org/flatcontainer/packageB/1.0.0/packageB.1.0.0.nupkg"),
                                    Zip      = zipB,
                                    Package  = new PackageArchiveReader(zipB)
                                };

                                // Act
                                await catalog.AddPackageAsync(inputA);

                                await catalog.AddPackageAsync(inputB);

                                await fileSystem.Commit(context.Log, context.Token);

                                // Assert
                                Assert.True(
                                    await fileSystem.Get("catalog/page.0.json").Exists(context.Log, context.Token),
                                    "The first catalog page should exist.");
                                Assert.True(
                                    await fileSystem.Get("catalog/page.1.json").Exists(context.Log, context.Token),
                                    "The second catalog page should exist.");
                            }
                    }
        }
示例#25
0
        protected override void HandleCore(HtmlDocument document, ManifestItem manifestItem, string inputFile, string outputFile)
        {
            _fileMapping[outputFile] = inputFile;

            // RFC 3986: relative-ref = relative-part [ "?" query ] [ "#" fragment ]
            _linksWithBookmark[outputFile] =
                (from node in GetNodesWithAttribute(document, "href")
                 let nocheck = node.GetAttributeValue("nocheck", null)
                               where !"bookmark".Equals(nocheck, StringComparison.OrdinalIgnoreCase)
                               let link = node.GetAttributeValue("href", null)
                                          let bookmark = UriUtility.GetFragment(link).TrimStart('#')
                                                         let decodedLink = RelativePath.TryParse(HttpUtility.UrlDecode(UriUtility.GetPath(link)))
                                                                           where !string.IsNullOrEmpty(bookmark) && !WhiteList.Contains(bookmark)
                                                                           where decodedLink != null
                                                                           select new LinkItem
            {
                Title = node.InnerText,
                Href = TransformPath(outputFile, decodedLink),
                Bookmark = bookmark,
                SourceFragment = WebUtility.HtmlDecode(node.GetAttributeValue("data-raw-source", null)),
                SourceFile = WebUtility.HtmlDecode(node.GetAttributeValue("sourceFile", null)),
                SourceLineNumber = node.GetAttributeValue("sourceStartLineNumber", 0),
                TargetLineNumber = node.Line
            }).ToList();
            var anchors = GetNodeAttribute(document, "id").Concat(GetNodeAttribute(document, "name"));

            _registeredBookmarks[outputFile] = new HashSet <string>(anchors);
        }
示例#26
0
 public void TestGetFileNameWithLocalPath()
 {
     AssertEqual("PauthorTestRunner.exe", UriUtility.GetFileName(@"PauthorTestRunner.exe"));
     AssertEqual("sample.cxml", UriUtility.GetFileName(@"..\..\Resources\DeepZoom\sample.cxml"));
     AssertEqual("PauthorTestRunner.exe", UriUtility.GetFileName(Path.GetFullPath("PauthorTestRunner.exe")));
 }
示例#27
0
 public Task <AlertMessage <TKey> > GetAsync(NotifyAlert <TKey> entity, UriUtility uri)
 {
     return(Task.FromResult(Get(entity, uri)));
 }
示例#28
0
 public void TestGetFileNameWithUri()
 {
     AssertEqual("documentation", UriUtility.GetFileName("http://pauthor.codeplex.com/documentation"));
     AssertEqual("documentation", UriUtility.GetFileName("sample/foo/documentation"));
     AssertNull(UriUtility.GetFileName("http://pauthor.codeplex.com"));
 }
示例#29
0
        //
        #region <<Routines>>
        /// <summary>
        /// Get request token
        /// </summary>
        public void GetRequestToken()
        {
            //Remember these for later.
            HttpContext.Current.Session["consumerKey"]    = consumerKey;
            HttpContext.Current.Session["consumerSecret"] = consumerSecret;
            IOAuthSession session      = CreateSession();
            IToken        requestToken = session.GetRequestToken();

            HttpContext.Current.Session["requestToken"] = strrequestToken;
            strrequestToken = requestToken.Token;
            tokenSecret     = requestToken.TokenSecret;
            var authUrl = string.Format("{0}?oauth_token={1}&oauth_callback={2}", AUTHORIZE_URL, strrequestToken, UriUtility.UrlEncode(oauth_callback_url));

            HttpContext.Current.Session["oauthLink"] = authUrl;
            Response.Redirect(authUrl);
        }
示例#30
0
        /// <summary>
        ///     Gets the URLs of the content item.
        /// </summary>
        /// <remarks>
        ///     <para>Use when displaying URLs. If errors occur when generating the URLs, they will show in the list.</para>
        ///     <para>Contains all the URLs that we can figure out (based upon domains, etc).</para>
        /// </remarks>
        public static async Task <IEnumerable <UrlInfo> > GetContentUrlsAsync(
            this IContent content,
            IPublishedRouter publishedRouter,
            IUmbracoContext umbracoContext,
            ILocalizationService localizationService,
            ILocalizedTextService textService,
            IContentService contentService,
            IVariationContextAccessor variationContextAccessor,
            ILogger <IContent> logger,
            UriUtility uriUtility,
            IPublishedUrlProvider publishedUrlProvider)
        {
            ArgumentNullException.ThrowIfNull(content);
            ArgumentNullException.ThrowIfNull(publishedRouter);
            ArgumentNullException.ThrowIfNull(umbracoContext);
            ArgumentNullException.ThrowIfNull(localizationService);
            ArgumentNullException.ThrowIfNull(textService);
            ArgumentNullException.ThrowIfNull(contentService);
            ArgumentNullException.ThrowIfNull(variationContextAccessor);
            ArgumentNullException.ThrowIfNull(logger);
            ArgumentNullException.ThrowIfNull(uriUtility);
            ArgumentNullException.ThrowIfNull(publishedUrlProvider);

            var result = new List <UrlInfo>();

            if (content.Published == false)
            {
                result.Add(UrlInfo.Message(textService.Localize("content", "itemNotPublished")));
                return(result);
            }

            // build a list of URLs, for the back-office
            // which will contain
            // - the 'main' URLs, which is what .Url would return, for each culture
            // - the 'other' URLs we know (based upon domains, etc)
            //
            // need to work through each installed culture:
            // on invariant nodes, each culture returns the same URL segment but,
            // we don't know if the branch to this content is invariant, so we need to ask
            // for URLs for all cultures.
            // and, not only for those assigned to domains in the branch, because we want
            // to show what GetUrl() would return, for every culture.
            var urls     = new HashSet <UrlInfo>();
            var cultures = localizationService.GetAllLanguages().Select(x => x.IsoCode).ToList();

            // get all URLs for all cultures
            // in a HashSet, so de-duplicates too
            foreach (UrlInfo cultureUrl in await GetContentUrlsByCultureAsync(content, cultures, publishedRouter, umbracoContext, contentService, textService, variationContextAccessor, logger, uriUtility, publishedUrlProvider))
            {
                urls.Add(cultureUrl);
            }

            // return the real URLs first, then the messages
            foreach (IGrouping <bool, UrlInfo> urlGroup in urls.GroupBy(x => x.IsUrl).OrderByDescending(x => x.Key))
            {
                // in some cases there will be the same URL for multiple cultures:
                // * The entire branch is invariant
                // * If there are less domain/cultures assigned to the branch than the number of cultures/languages installed
                if (urlGroup.Key)
                {
                    result.AddRange(urlGroup.DistinctBy(x => x.Text, StringComparer.OrdinalIgnoreCase).OrderBy(x => x.Text).ThenBy(x => x.Culture));
                }
                else
                {
                    result.AddRange(urlGroup);
                }
            }

            // get the 'other' URLs - ie not what you'd get with GetUrl() but URLs that would route to the document, nevertheless.
            // for these 'other' URLs, we don't check whether they are routable, collide, anything - we just report them.
            foreach (UrlInfo otherUrl in publishedUrlProvider.GetOtherUrls(content.Id).OrderBy(x => x.Text).ThenBy(x => x.Culture))
            {
                // avoid duplicates
                if (urls.Add(otherUrl))
                {
                    result.Add(otherUrl);
                }
            }

            return(result);
        }