Inheritance: LocalPackage
        public void ReleasePackageIntegrationTest()
        {
            var inputPackage = IntegrationTestHelper.GetPath("fixtures", "Squirrel.Tests.0.1.0-pre.nupkg");
            var outputPackage = Path.GetTempFileName() + ".nupkg";
            var sourceDir = IntegrationTestHelper.GetPath("fixtures", "packages");

            var fixture = new ReleasePackage(inputPackage);
            (new DirectoryInfo(sourceDir)).Exists.ShouldBeTrue();

            try {
                fixture.CreateReleasePackage(outputPackage, sourceDir);

                this.Log().Info("Resulting package is at {0}", outputPackage);
                var pkg = new ZipPackage(outputPackage);

                int refs = pkg.FrameworkAssemblies.Count();
                this.Log().Info("Found {0} refs", refs);
                refs.ShouldEqual(0);

                this.Log().Info("Files in release package:");

                List<IPackageFile> files = pkg.GetFiles().ToList();
                files.ForEach(x => this.Log().Info(x.Path));

                List<string> nonDesktopPaths = new[] {"sl", "winrt", "netcore", "win8", "windows8", "MonoAndroid", "MonoTouch", "MonoMac", "wp", }
                    .Select(x => @"lib\" + x)
                    .ToList();

                files.Any(x => nonDesktopPaths.Any(y => x.Path.ToLowerInvariant().Contains(y.ToLowerInvariant()))).ShouldBeFalse();
                files.Any(x => x.Path.ToLowerInvariant().EndsWith(@".xml")).ShouldBeFalse();
            } finally {
                File.Delete(outputPackage);
            }
        }
Beispiel #2
0
        static void Main(string[] args)
        {
            Console.WriteLine("Create NuGet Package via Code");
            ManifestMetadata metadata = new ManifestMetadata()
            {
                Authors = "Authors Name",
                Version = "1.0.0.0",
                Id = "NuGetId",
                Description = "NuGet Package Description goes here!",
            };

            PackageBuilder builder = new PackageBuilder();


            var path = AppDomain.CurrentDomain.BaseDirectory + "..\\..\\DemoContent\\";

            builder.PopulateFiles(path, new[] { new ManifestFile { Source = "**", Target = "content" } });
            builder.Populate(metadata);

            using (FileStream stream = File.Open("test.nupkg", FileMode.OpenOrCreate))
            {
                builder.Save(stream);
            }

            Console.WriteLine("... and extract NuGet Package via Code");

            NuGet.ZipPackage package = new ZipPackage("test.nupkg");
            var content = package.GetContentFiles();

            Console.WriteLine("Package Id: " + package.Id);
            Console.WriteLine("Content-Files-Count: " + content.Count());

            Console.ReadLine();
        }
        public void EigenUpdateWithoutUpdateURL()
        {
            string dir;
            string outDir;

            using (Utility.WithTempDirectory(out outDir))
            using (IntegrationTestHelper.WithFakeInstallDirectory(out dir)) {
                var di = new DirectoryInfo(dir);
                var progress = new Subject<int>();

                var bundledRelease = ReleaseEntry.GenerateFromFile(di.GetFiles("*.nupkg").First().FullName);
                var fixture = new InstallManager(bundledRelease, outDir);
                var pkg = new ZipPackage(Path.Combine(dir, "SampleUpdatingApp.1.1.0.0.nupkg"));

                var progressValues = new List<int>();
                progress.Subscribe(progressValues.Add);

                fixture.ExecuteInstall(dir, pkg, progress).Wait();

                var filesToLookFor = new[] {
                    "SampleUpdatingApp\\app-1.1.0.0\\SampleUpdatingApp.exe",
                    "SampleUpdatingApp\\packages\\RELEASES",
                    "SampleUpdatingApp\\packages\\SampleUpdatingApp.1.1.0.0.nupkg",
                };

                filesToLookFor.ForEach(f => Assert.True(File.Exists(Path.Combine(outDir, f)), "Could not find file: " + f));

                // Progress should be monotonically increasing
                progressValues.Count.ShouldBeGreaterThan(2);
                progressValues.Zip(progressValues.Skip(1), (prev, cur) => cur - prev).All(x => x > 0).ShouldBeTrue();
            }
        }
        public void NuspecMissingRequiredFieldsThrowsExceptions()
        {
            var path = IntegrationTestHelper.GetPath("fixtures", "Squirrel.Core.1.1.0.0.nupkg");
            var zp = new ZipPackage(path);

            //Use reflection to grab an instance of the private method
            var checkIfNuspecHasRequiredFields = typeof(ParseCommands).GetMethod("checkIfNuspecHasRequiredFields",
                BindingFlags.Static | BindingFlags.NonPublic);

            zp.Id = "";
            //Blank id exception
            Assert.Throws<TargetInvocationException>(() => checkIfNuspecHasRequiredFields.Invoke(null, new object[] { zp, "Path" }));

            zp.Id = "K";
            //zp.Version = "";
            //TODO: Test a blank version somehow
            
            //zp.Version = "1.0";
            zp.Authors = new string[0];
            //Blank authors exception
            Assert.Throws<TargetInvocationException>(() => checkIfNuspecHasRequiredFields.Invoke(null, new object[] { zp, "Path" }));

            zp.Authors = new[] { "AuthorName" };
            zp.Description = "";
            
            //Blank description exception
            Assert.Throws<TargetInvocationException>(() => checkIfNuspecHasRequiredFields.Invoke(null, new object[] { zp, "Path" }));
        }
        public void ApplyDeltaPackageSmokeTest()
        {
            var basePackage = new ReleasePackage(IntegrationTestHelper.GetPath("fixtures", "Shimmer.Core.1.0.0.0-full.nupkg"));
            var deltaPackage = new ReleasePackage(IntegrationTestHelper.GetPath("fixtures", "Shimmer.Core.1.1.0.0-delta.nupkg"));
            var expectedPackageFile = IntegrationTestHelper.GetPath("fixtures", "Shimmer.Core.1.1.0.0-full.nupkg");
            var outFile = Path.GetTempFileName() + ".nupkg";

            try {
                basePackage.ApplyDeltaPackage(deltaPackage, outFile);
                var result = new ZipPackage(outFile);
                var expected = new ZipPackage(expectedPackageFile);

                result.Id.ShouldEqual(expected.Id);
                result.Version.ShouldEqual(expected.Version);

                this.Log().Info("Expected file list:");
                expected.GetFiles().Select(x => x.Path).OrderBy(x => x).ForEach(x => this.Log().Info(x));

                this.Log().Info("Actual file list:");
                result.GetFiles().Select(x => x.Path).OrderBy(x => x).ForEach(x => this.Log().Info(x));

                Enumerable.Zip(
                    expected.GetFiles().Select(x => x.Path).OrderBy(x => x),
                    result.GetFiles().Select(x => x.Path).OrderBy(x => x),
                    (e, a) => e == a
                ).All(x => x).ShouldBeTrue();
            } finally {
                if (File.Exists(outFile)) {
                    File.Delete(outFile);
                }
            }
        }
Beispiel #6
0
        public static bool IsNuGetPublished (this ICakeContext context, FilePath file, string nugetSource = DefaultNuGetSource)
        {
            var f = file.MakeAbsolute (context.Environment).FullPath;

            var pkg = new ZipPackage (f);

            return IsNuGetPublished (context, pkg.Id, pkg.Version, nugetSource);
        }
Beispiel #7
0
        public static SemanticVersion GetNuGetPackageVersion (this ICakeContext context, FilePath file)
        {
            var f = file.MakeAbsolute (context.Environment).FullPath;

            var p = new ZipPackage (f);

            return p.Version;
        }
Beispiel #8
0
        public static string GetNuGetPackageId (this ICakeContext context, FilePath file)
        {
            var f = file.MakeAbsolute (context.Environment).FullPath;

            var p = new ZipPackage (f);

            return p.Id;
        }
Beispiel #9
0
        public void PublishPackage(string file, string apiKey)
        {
            var packageServer = new PackageServer(Feed.NuGetV2.Url, "ripple");
            var package = new ZipPackage(file);

            RippleLog.Info("Publishing " + file);
            packageServer.PushPackage(apiKey, package.GetStream, (int)60.Minutes().TotalMilliseconds);
        }
        public void DetectFrameworkVersion(string packageName, FrameworkVersion expected)
        {
            var path = IntegrationTestHelper.GetPath("fixtures", packageName);

            var zip = new ZipPackage(path);

            Assert.Equal(expected, zip.DetectFrameworkVersion());
        }
        public void Push(string url, string key, Stream stream)
        {
            var package = new ZipPackage(stream);
            stream = package.GetStream();

            var server = new PackageServer(url, "SymbolSource");
            server.PushPackage(key, package, stream.Length, 5000, false);
        }
Beispiel #12
0
        public bool TryBuild(byte[] bytes, out Package package)
        {
            package = null;
            try
            {
                using (var stream = new MemoryStream(bytes))
                {
                    var zipPackage = new ZipPackage(stream);
                    if (zipPackage.Id.IsTooLargeString() || zipPackage.Version.ToString().IsTooLargeString())
                    {
                        return false;
                    }

                    var now = dateTimeService.UtcNow;
                    package = new Package
                    {
                        Id = zipPackage.Id,
                        Version = zipPackage.Version.ToString(),
                        DisplayTitle = zipPackage.Title.ToStringSafe(),
                        IsAbsoluteLatestVersion = zipPackage.IsAbsoluteLatestVersion,
                        IsLatestVersion = zipPackage.IsLatestVersion,
                        IsPrerelease = zipPackage.IsPrerelease(),
                        PackageHash = cryptoService.Hash(bytes),
                        PackageHashAlgorithm = cryptoService.HashAlgorithmId,
                        PackageSize = bytes.LongLength,
                        Created = now,
                        LastUpdated = now,
                        Published = now,
                        Owners = zipPackage.Owners.Flatten().ToStringSafe(),
                        Authors = zipPackage.Authors.Flatten().ToStringSafe(),
                        Listed = true,
                        RequireLicenseAcceptance = zipPackage.RequireLicenseAcceptance,
                        Language = zipPackage.Language.ToStringSafe(),
                        DevelopmentDependency = zipPackage.DevelopmentDependency,
                        Title = zipPackage.Title.ToStringSafe(),
                        Tags = zipPackage.Tags.ToStringSafe(),
                        Copyright = zipPackage.Copyright.ToStringSafe(),
                        Dependencies = "".ToStringSafe(),
                        IconUrl = zipPackage.IconUrl.ToStringSafe(),
                        LicenseUrl = zipPackage.LicenseUrl.ToStringSafe(),
                        ProjectUrl = zipPackage.ProjectUrl.ToStringSafe(),
                        Description = zipPackage.Description.ToStringSafe(),
                        ReleaseNotes = zipPackage.ReleaseNotes.ToStringSafe(),
                        Summary = zipPackage.Summary.ToStringSafe(),
                        DownloadCount = 0,
                        Score = 0f,
                        VersionDownloadCount = 0,
                        BlobId = guidGenerator.NewGuid()
                    };
                    return true;
                }
            }
            catch (Exception)
            {
                return false;
            }
        }
        public string GetReleaseNotes(string packageDirectory)
        {
            var zp = new ZipPackage(Path.Combine(packageDirectory, Filename));
            var t = zp.Id;

            if (String.IsNullOrWhiteSpace(zp.ReleaseNotes)) {
                throw new Exception(String.Format("Invalid 'ReleaseNotes' value in nuspec file at '{0}'", Path.Combine(packageDirectory, Filename)));
            }

            return zp.ReleaseNotes;
        }
        public override void ExecuteCommand()
        {
            Log.Info("Getting all package metadata...");
            var packages = GetAllPackages();
            Log.Info("Getting packages which have target framework data...");
            var alreadyPopulatedPackageKeys = GetAlreadyPopulatedPackageKeys();
            Log.Info("Calculating minimal difference set...");
            var packageKeysToPopulate = packages.Keys.Except(alreadyPopulatedPackageKeys).ToList();

            var totalCount = packageKeysToPopulate.Count;
            var processedCount = 0;
            Log.Info(
                "Populating frameworks for {0} packages on '{1}',",
                totalCount,
                ConnectionString);

            Parallel.ForEach(packageKeysToPopulate, new ParallelOptions { MaxDegreeOfParallelism = 10 }, packageIdToPopulate =>
            {
                var package = packages[packageIdToPopulate];

                try
                {
                    var downloadPath = DownloadPackage(package);
                    var nugetPackage = new ZipPackage(downloadPath);

                    var supportedFrameworks = GetSupportedFrameworks(nugetPackage);
                    if (!WhatIf)
                    {
                        PopulateFrameworks(package, supportedFrameworks);
                    }

                    File.Delete(downloadPath);

                    Interlocked.Increment(ref processedCount);
                    Log.Info(
                        "Populated frameworks for package '{0}.{1}' ({2} of {3}).",
                        package.Id,
                        package.Version,
                        processedCount,
                        totalCount);
                }
                catch (Exception ex)
                {
                    Interlocked.Increment(ref processedCount);
                    Log.Error(
                        "Error populating frameworks for package '{0}.{1}' ({2} of {3}): {4}.",
                        package.Id,
                        package.Version,
                        processedCount,
                        totalCount,
                        ex.Message);
                }
            });
        }
        public void AddFolder(string folderPath)
        {
            log.Debug("Using package versions from folder: " + folderPath);
            foreach (var file in Directory.GetFiles(folderPath, "*.nupkg", SearchOption.AllDirectories))
            {
                log.Debug("Package file: " + file);
                var package = new ZipPackage(file);

                Add(package.Id, package.Version.ToString());
            }
        }
Beispiel #16
0
        public async Task<Package> LoadAsync(string id, string version) {
            var logger = _loggerFactory.CreateLogger<NuGetPackageLoader>();

            var sourceProvider = new PackageSourceProvider(
                NullSettings.Instance,
                new[] {
                    new PackageSource(NuGetConstants.DefaultFeedUrl),
                    new PackageSource("https://www.myget.org/F/aspnetvnext/api/v2"),
                });

            var feeds = sourceProvider
                .LoadPackageSources()
                .Select(source =>
                    PackageSourceUtils.CreatePackageFeed(
                        source,
                        noCache: false,
                        ignoreFailedSources: false,
                        reports: logger.CreateReports()))
                .Where(f => f != null);

            logger.LogInformation($"Looking up {id} v{version} from nuget");

            var packages = (await Task.WhenAll(feeds.Select(feed => feed.FindPackagesByIdAsync(id))))
                .SelectMany(_ => _)
                .OrderByDescending(p => p.Version);

            var package = version == null
                ? packages.FirstOrDefault()
                : packages.FirstOrDefault(p => p.Version == new SemanticVersion(version));

            if (package == null) {
                logger.LogError($"Unable to locate {id} v{version}");
                return null;
            }

            logger.LogInformation($"Found version {package.Version} of {package.Id}");

            var pkgStreams = await Task.WhenAll(feeds.Select(feed => {
                try {
                    return feed.OpenNupkgStreamAsync(package);
                } catch {
                    return null;
                }
            }));
            var pkgStream = pkgStreams.FirstOrDefault(s => s != null);
            var zipPackage = new ZipPackage(pkgStream);

            if (zipPackage == null) {
                logger.LogError($"Unable to open package stream for {id} v{version}");
                return null;
            }

            return zipPackage.ToPackage(packages.Select(p => p.Version.ToString()).ToList(), logger);
        }
Beispiel #17
0
        public void AddFolder(string folderPath)
        {
            log.Debug("Using package versions from folder: " + folderPath);
            foreach (var file in Directory.GetFiles(folderPath, "*.nupkg", SearchOption.AllDirectories))
            {
                log.Debug("Package file: " + file);
                var package = new NuGet.ZipPackage(file);

                Add(package.Id, package.Version.ToString());
            }
        }
        private List <IPackageFile> GetFilesNoCache()
        {
            using (Stream stream = _streamFactory())
            {
                Package package   = Package.Open(stream);
                var     packageId = ZipPackage.GetPackageIdentifier(package);

                return((from part in package.GetParts()
                        where IsPackageFile(part, packageId)
                        select(IPackageFile) new ZipPackageFile(part)).ToList());
            }
        }
Beispiel #19
0
        public void CreateDeltaPackageIntegrationTest()
        {
            var basePackage = IntegrationTestHelper.GetPath("fixtures", "NSync.Core.1.0.0.0.nupkg");
            var newPackage = IntegrationTestHelper.GetPath("fixtures", "NSync.Core.1.1.0.0.nupkg");

            var sourceDir = IntegrationTestHelper.GetPath("..", "packages");
            (new DirectoryInfo(sourceDir)).Exists.ShouldBeTrue();

            var baseFixture = new ReleasePackage(basePackage);
            var fixture = new ReleasePackage(newPackage);

            var tempFiles = Enumerable.Range(0, 3)
                .Select(_ => Path.GetTempPath() + Guid.NewGuid().ToString() + ".nupkg")
                .ToArray();

            try {
                baseFixture.CreateReleasePackage(tempFiles[0], sourceDir);
                fixture.CreateReleasePackage(tempFiles[1], sourceDir);

                (new FileInfo(baseFixture.ReleasePackageFile)).Exists.ShouldBeTrue();
                (new FileInfo(fixture.ReleasePackageFile)).Exists.ShouldBeTrue();

                fixture.CreateDeltaPackage(baseFixture, tempFiles[2]);

                var fullPkg = new ZipPackage(tempFiles[1]);
                var deltaPkg = new ZipPackage(tempFiles[2]);

                fullPkg.Id.ShouldEqual(deltaPkg.Id);
                fullPkg.Version.CompareTo(deltaPkg.Version).ShouldEqual(0);

                // v1.1 adds a dependency on DotNetZip
                deltaPkg.GetFiles()
                    .Any(x => x.Path.ToLowerInvariant().Contains("ionic.zip"))
                    .ShouldBeTrue();

                // All the other files should be diffs
                deltaPkg.GetFiles()
                    .Where(x => !x.Path.ToLowerInvariant().Contains("ionic.zip"))
                    .All(x => x.Path.ToLowerInvariant().EndsWith("diff"))
                    .ShouldBeTrue();

                // Delta packages should be smaller than the original!
                var fileInfos = tempFiles.Select(x => new FileInfo(x)).ToArray();
                this.Log().Info("Base Size: {0}, Current Size: {1}, Delta Size: {2}",
                    fileInfos[0].Length, fileInfos[1].Length, fileInfos[2].Length);

                (fileInfos[2].Length - fileInfos[1].Length).ShouldBeLessThan(0);

            } finally {
                tempFiles.ForEach(File.Delete);
            }
        }
        public void Build_And_Packaged_XCopy_Has_Correct_Metadata()
        {
            System.Environment.CurrentDirectory = "samples".MapVcsRoot();

            MsBuild("PowerDeploy.Sample.XCopy\\PowerDeploy.Sample.XCopy.csproj /t:clean,build /p:RunOctoPack=true /p:OctoPackPackageVersion=1.3.3.7 /p:Configuration=Release /v:m");

            Assert.IsTrue(File.Exists(@"PowerDeploy.Sample.XCopy\obj\octopacked\PowerDeploy.Sample.XCopy.1.3.3.7.nupkg"));

            var nupkg = new ZipPackage(@"PowerDeploy.Sample.XCopy\obj\octopacked\PowerDeploy.Sample.XCopy.1.3.3.7.nupkg");

            Assert.AreEqual("1.3.3.7", nupkg.Version.ToString());
            Assert.AreEqual("PowerDeploy.Sample.XCopy", nupkg.Id);
            Assert.IsTrue(nupkg.GetFiles().Any(f => f.Path.Contains("powerdeploy.template.xml")));
        }
Beispiel #21
0
        private void EnsurePackageFiles()
        {
            if (_files != null && _expandedFileSystem.DirectoryExists(_expandedFolderPath))
            {
                return;
            }

            _files = new Dictionary <string, PhysicalPackageFile>();
            _supportedFrameworks = null;

            using (Stream stream = GetStream())
            {
                Package package = Package.Open(stream);

                _expandedFolderPath = GetExpandedFolderPath();

                // unzip files inside package
                var files = from part in package.GetParts()
                            where ZipPackage.IsPackageFile(part)
                            select part;

                // now copy all package's files to disk
                foreach (PackagePart file in files)
                {
                    string path     = UriUtility.GetPath(file.Uri);
                    string filePath = Path.Combine(_expandedFolderPath, path);

                    using (Stream partStream = file.GetStream())
                    {
                        // only copy the package part to disk if there doesn't exist
                        // a file with the same name.
                        if (!_expandedFileSystem.FileExists(filePath))
                        {
                            using (Stream targetStream = _expandedFileSystem.CreateFile(filePath))
                            {
                                partStream.CopyTo(targetStream);
                            }
                        }
                    }

                    var packageFile = new PhysicalPackageFile
                    {
                        SourcePath = _expandedFileSystem.GetFullPath(filePath),
                        TargetPath = path
                    };

                    _files[path] = packageFile;
                }
            }
        }
Beispiel #22
0
        protected static void AssertPackage(string packageFilePath, Action<ZipPackage> packageAssertions)
        {
            var fullPath = Path.Combine(Environment.CurrentDirectory, packageFilePath);
            if (!File.Exists(fullPath))
            {
                Assert.Fail("Could not find package file: " + fullPath);
            }

            Trace.WriteLine("Checking package: " + fullPath);
            var package = new ZipPackage(fullPath);
            packageAssertions(package);

            Trace.WriteLine("Success!");
        }
        protected override void GetMetadata(string path, string repository, out PackageProject project, out IList<MetadataEntry> metadata, out ILookup<ContentType, string> contents)
        {
            var packagePath = GetFilePath(path);

            Version version;

            using (var stream = File.OpenRead(packagePath))
                version = versionExtractor.Extract(stream);
            
            var package = new ZipPackage(packagePath);

            metadata = version.Metadata;

            project = new PackageProject
                          {
                              Name = version.Project,
                              Repository = repository,
                              Version =
                                  new PackageVersion
                                      {
                                          Project = version.Project,
                                          Name = version.Name,
                                          Metadata = version.Metadata,
                                          Compilations =
                                              package.AssemblyReferences
                                              .GroupBy(reference => reference.TargetFramework)
                                              .Select(group => new PackageCompilation
                                                                   {
                                                                       Mode = "Release",
                                                                       Platform = group.Key != null ? group.Key.ToString() : "Default",
                                                                       ImageFiles =
                                                                           group.Select(reference => new PackageImageFile
                                                                                                         {
                                                                                                             Name = reference.Path.Replace(@"\", @"/")
                                                                                                         }
                                                                           ).ToArray(),
                                                                   })

                                              .ToArray(),
                                      }

                          };


            using (var zip = new ZipFile(packagePath))
                contents = zip.EntryFileNames.ToLookup(GetContentType);
        }
        private static void CreatePart(Package package, string path, Stream sourceStream)
        {
            if (PackageHelper.IsPackageManifest(path, ZipPackage.GetPackageIdentifier(package)))
            {
                return;
            }

            Uri uri = UriUtility.CreatePartUri(path);

            // Create the part
            PackagePart packagePart = package.CreatePart(uri, DefaultContentType, CompressionOption.Maximum);

            using (Stream stream = packagePart.GetStream())
            {
                sourceStream.CopyTo(stream);
            }
        }
        public void DeployPackage(string package)
        {
            var nupkg = new ZipPackage(package);
            var packageType = nupkg.PeekPackageType();

            _logger.Info("Deploy {1} package {0}".Fmt(packageType, package));

            foreach (var deployer in _pluginsLoader.Deployers)
            {
                if (deployer.Metadata.PackageType == packageType)
                {
                    deployer.Value.Deploy(nupkg, _logger);

                    break;
                }
            }
        }
Beispiel #26
0
        public void CreatePackage(HttpContextBase context)
        {
            var request = context.Request;
            var stream = request.Files.Count > 0 ? request.Files[0].InputStream : request.InputStream;
            var package = new ZipPackage(stream);

            var symbolFiles = package.GetFiles("lib").Where(f => Path.GetExtension(f.Path) == ".pdb").ToList();

            foreach (var symbolFile in symbolFiles)
                ProcessSymbolFile(symbolFile, package);

            stream.Position = 0;

            if (IsSymbolPackage(package, symbolFiles))
                symbolPackageService.CreatePackage(context);
            else
                packageService.CreatePackage(context);
        }
        public virtual ActionResult UploadPackage(HttpPostedFileBase packageFile)
        {
            // TODO: validate package id and version don't already exist

            if (packageFile == null)
            {
                ModelState.AddModelError(string.Empty, "A package file is required.");
                return View();
            }

            // TODO: what other security checks do we need to perform for uploaded packages?
            var extension = Path.GetExtension(packageFile.FileName).ToLowerInvariant();
            if (extension != Const.PackageFileExtension)
            {
                ModelState.AddModelError(string.Empty, "The package file must be a .nupkg file.");
                return View();
            }

            var currentUser = userSvc.FindByUsername(User.Identity.Name);
            if (currentUser == null)
            {
                throw new InvalidOperationException("Current user is null. This should never happen!");
            }

            ZipPackage uploadedPackage;
            using (var uploadStream = packageFile.InputStream)
            {
                uploadedPackage = new ZipPackage(packageFile.InputStream);
            }

            Package packageVersion;
            try
            {
                packageVersion = packageSvc.CreatePackage(uploadedPackage, currentUser);
            }
            catch (EntityException ex)
            {
                ModelState.AddModelError(string.Empty, ex.Message);
                return View();
            }

            string packagePublishUrl = Url.Publish(packageVersion);
            return Redirect(packagePublishUrl);
        }
Beispiel #28
0
        internal void EnsurePackage(IPackageCacheRepository cacheRepository)
        {
            IPackageMetadata packageMetadata = this;

            if ((((this._package == null) || ((this._package is OptimizedZipPackage) && !((OptimizedZipPackage)this._package).IsValid)) || !string.Equals(this.OldHash, this.PackageHash, StringComparison.OrdinalIgnoreCase)) || (this._usingMachineCache && !cacheRepository.Exists(this.Id, packageMetadata.Version)))
            {
                IPackage package = null;
                bool     flag    = false;
                bool     flag2   = false;
                if (TryGetPackage(cacheRepository, packageMetadata, out package) && this.MatchPackageHash(package))
                {
                    flag2 = true;
                }
                else
                {
                    if (cacheRepository.InvokeOnPackage(packageMetadata.Id, packageMetadata.Version, stream => this.Downloader.DownloadPackage(this.DownloadUrl, this, stream)))
                    {
                        package = cacheRepository.FindPackage(packageMetadata.Id, packageMetadata.Version);
                    }
                    else
                    {
                        using (MemoryStream stream = new MemoryStream())
                        {
                            this.Downloader.DownloadPackage(this.DownloadUrl, this, stream);
                            stream.Seek(0L, SeekOrigin.Begin);
                            package = new ZipPackage(stream);
                        }
                        flag = true;
                    }
                    flag2 = true;
                }
                if (!flag2)
                {
                    object[] args = new object[] { this.Version, this.Id };
                    throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, NuGetResources.Error_InvalidPackage, args));
                }
                this._package           = package;
                this.Id                 = this._package.Id;
                this.Version            = this._package.Version.ToString();
                this._usingMachineCache = !flag;
                this.OldHash            = this.PackageHash;
            }
        }
		//public PackageInfo Install(string packageId, string version, string location, string applicationFolder)
		//{
		//	// instantiates the appropriate package repository
		//	IPackageRepository packageRepository = PackageRepositoryFactory.Default.CreateRepository(location);

		//	// gets an IPackage instance from the repository
		//	var packageVersion = String.IsNullOrEmpty(version) ? null : new SemanticVersion(version);
		//	var package = packageRepository.FindPackage(packageId, packageVersion);
		//	if (package == null)
		//	{
		//		throw new ArgumentException("The specified package could not be found, id:{0} version:{1}".FormatCurrent(packageId, version.IsEmpty() ? "No version" : version));
		//	}

		//	return InstallPackage(package, packageRepository, location, applicationFolder);
		//}

		public PackageInfo Install(Stream packageStream, string location, string applicationPath)
		{
			Guard.ArgumentNotNull(() => packageStream);
			
			IPackage package = null;
			try
			{
				package = new ZipPackage(packageStream);

			}
			catch (Exception ex)
			{
				throw new SmartException(T("Admin.Packaging.StreamError"), ex);
			}
			
			// instantiates the appropriate package repository
			var packageRepository = new NullSourceRepository();
			return InstallPackage(package, packageRepository, location, applicationPath);
		}
Beispiel #30
0
        public void GetSource(RequestContext context)
        {
            var packageId = context.RouteData.Values["id"].ToString();
            var version = context.RouteData.Values["version"].ToString();
            var path = Path.Combine("src", context.RouteData.Values["path"].ToString().Replace('/', '\\'));

            var package = new ZipPackage(symbolPackagePathResolver.GetSymbolPackagePath(packageId, version));

            string directory = Path.GetDirectoryName(path);
            var file = package.GetFiles(directory).FirstOrDefault(f => string.Equals(f.Path, path, StringComparison.InvariantCultureIgnoreCase));
            var response = context.HttpContext.Response;
            if (file == null)
            {
                response.StatusCode = 404;
                return;
            }
            response.ContentType = "binary/octet-stream";
            file.GetStream().CopyTo(response.OutputStream);
        }
        public void Configure_XCopy_Sample_Project_With_Mocked_Environment()
        {
            System.Environment.CurrentDirectory = "samples".MapVcsRoot();

            MsBuild("PowerDeploy.Sample.XCopy\\PowerDeploy.Sample.XCopy.csproj /t:clean,build /p:RunOctoPack=true /p:OctoPackPackageVersion=1.3.3.7 /p:Configuration=Release /v:m");

            var environmentMock = new Mock<IEnvironmentProvider>();
            environmentMock.Setup(prov => prov.GetEnvironment(It.IsAny<string>())).Returns(GetUnitEnvironment);

            var outputPath = FileSystem.CreateTempWorkingDir();

            var target = new PackageManager(environmentMock.Object);
            target.ConfigurePackageByEnvironment(@"PowerDeploy.Sample.XCopy\obj\octopacked\PowerDeploy.Sample.XCopy.1.3.3.7.nupkg", "Unit", outputPath);

            // check if all template files are parsed
            var nupkg = new ZipPackage(Path.Combine(outputPath, "PowerDeploy.Sample.XCopy_v1.3.3.7_UNIT.nupkg"));
            Assert.IsFalse(nupkg.GetFiles().Any(f => f.Path.Contains(".template.")));

            AssertPackage(Path.Combine(outputPath, "PowerDeploy.Sample.XCopy_v1.3.3.7_UNIT.nupkg"),
                pkg => pkg.AssertFileContent(new Dictionary<string, string>()
                {
                    {
                        "powerdeploy.xml",
                        @"<?xml version=""1.0"" encoding=""utf-8"" ?>
                          <package type=""xcopy"" environment=""UNIT"">
                              <destination>c:\temp</destination>
                          </package>".ToXmlOneLine()
                    },
                    {
                        "App.config",
                        @"<?xml version=""1.0"" encoding=""utf-8"" ?>
                          <configuration>
                            <appSettings>
                              <add key=""variable1"" value=""Val1"" />
                              <add key=""variable2"" value=""Val2"" />
                              <add key=""default.variable"" value=""defaultvalue"" />
                              <add key=""env"" value=""UNIT"" />
                            </appSettings>
                          </configuration>".ToXmlOneLine()
                    }
                }));
        }
        public override void ExtractContents(IFileSystem fileSystem, string extractPath)
        {
            using (Stream stream = _streamFactory())
            {
                var package   = Package.Open(stream);
                var packageId = ZipPackage.GetPackageIdentifier(package);

                foreach (var part in package.GetParts()
                         .Where(p => IsPackageFile(p, packageId)))
                {
                    var relativePath = UriUtility.GetPath(part.Uri);

                    var targetPath = Path.Combine(extractPath, relativePath);
                    using (var partStream = part.GetStream())
                    {
                        fileSystem.AddFile(targetPath, partStream);
                    }
                }
            }
        }
        public void ApplyDeltaWithBothBsdiffAndNormalDiffDoesntFail()
        {
            var basePackage = new ReleasePackage(IntegrationTestHelper.GetPath("fixtures", "slack-1.1.8-full.nupkg"));
            var deltaPackage = new ReleasePackage(IntegrationTestHelper.GetPath("fixtures", "slack-1.2.0-delta.nupkg"));
            var outFile = Path.GetTempFileName() + ".nupkg";

            try {
                var deltaBuilder = new DeltaPackageBuilder();
                deltaBuilder.ApplyDeltaPackage(basePackage, deltaPackage, outFile);

                var result = new ZipPackage(outFile);

                result.Id.ShouldEqual("slack");
                result.Version.ShouldEqual(new SemanticVersion("1.2.0"));
            } finally {
                if (File.Exists(outFile)) {
                    File.Delete(outFile);
                }
            }
        }
        private async Task EnsureNuGetExe()
        {
            if (await _fileStorageService.FileExistsAsync(Constants.DownloadsFolderName, "nuget.exe"))
            {
                // Ensure the file exists on blob storage.
                return;
            }

            var package = _packageService.FindPackageByIdAndVersion("NuGet.CommandLine", version: null, allowPrerelease: false);
            if (package == null)
            {
                throw new InvalidOperationException("Unable to find NuGet.CommandLine.");
            }

            using (Stream packageStream = await _packageFileService.DownloadPackageFileAsync(package))
            {
                var zipPackage = new ZipPackage(packageStream);
                await ExtractNuGetExe(zipPackage);
            }
        }
Beispiel #35
0
        /// <summary>
        /// Syndicates the nupkg stream for use within the system.
        /// </summary>
        /// <param name="stream">The stream.</param>
        /// <returns></returns>
        public async Task<Models.Release> SyndicateAsync(Stream stream)
        {
            ZipPackage package = new ZipPackage(stream);
            var storageFilename = string.Format("{0}.{1}.nupkg", package.Id, package.Version);

            Models.Release release = await _releaseStore.GetAsync(package.Id, package.Version.ToString());

            if (release == null)
            {
                // assume we need to publish a new release.
                release = _releaseStore.Create();
            }

            if (stream.CanSeek)
            {
                stream.Seek(0, 0);
            }

            var streamSHA = Utilities.CalculateChecksum(stream);
            if (!streamSHA.Equals(release.SHA1))
            {
                release.Description = package.Description;
                release.IconUrl = package.IconUrl;
                release.Id = package.Id;
                release.Listed = package.Listed;
                release.Published = DateTimeOffset.Now;
                release.ReleaseNotes = package.ReleaseNotes;
                release.Summary = package.Summary;
                release.Tags = package.Tags;
                release.Title = package.Title;
                release.Version = package.Version.ToString();
                release.SHA1 = streamSHA;

                // update store.
                await _fileService.DeleteAsync(storageFilename);

                release.RelativeUri = await _fileService.StoreAsync(storageFilename, package.GetStream());
            }

            return await _releaseStore.StoreAsync(release);
        }
        internal void EnsurePackage(IPackageRepository cacheRepository)
        {
            // OData caches instances of DataServicePackage while updating their property values. As a result,
            // the ZipPackage that we downloaded may no longer be valid (as indicated by a newer hash).
            // When using MachineCache, once we've verified that the hashes match (which happens the first time around),
            // we'll simply verify the file exists between successive calls.
            IPackageMetadata packageMetadata = this;
            bool             refreshPackage  = _package == null ||
                                               !String.Equals(OldHash, PackageHash, StringComparison.OrdinalIgnoreCase) ||
                                               (_usingMachineCache && !cacheRepository.Exists(Id, packageMetadata.Version));

            if (refreshPackage &&
                TryGetPackage(cacheRepository, packageMetadata, out _package) &&
                _package.GetHash(HashProvider).Equals(PackageHash, StringComparison.OrdinalIgnoreCase))
            {
                OldHash = PackageHash;

                // Reset the flag so that we no longer need to download the package since it exists and is valid.
                refreshPackage = false;

                // Make a note that we the backing store for the ZipPackage is the machine cache.
                _usingMachineCache = true;
            }

            if (refreshPackage)
            {
                // We either do not have a package available locally or they are invalid. Download the package from the server.
                _package = Downloader.DownloadPackage(DownloadUrl, this);

                // Make a note that we are using an in-memory instance of the package.
                _usingMachineCache = false;

                // Add the package to the cache
                cacheRepository.AddPackage(_package);

                OldHash = PackageHash;

                // Clear any cached items for this package
                ZipPackage.ClearCache(_package);
            }
        }
Beispiel #37
0
        //download the specified version of the package and update project reference to it. The newly downloaded package
        //will be located in /packages folder. The updated project reference can be checked in corresponding .csproj file.
        public bool Execute(string packageid, string projectFile, SemanticVersion version, string packages)
        {
            try
            {
                System.Console.WriteLine("-------------------------------------");
                System.Console.WriteLine("Project File " + projectFile);
                System.Console.WriteLine("Package "+packageid);
                System.Console.WriteLine("Version "+version);

                IPackageRepository repo = PackageRepositoryFactory.Default.CreateRepository("https://packages.nuget.org/api/v2");
                var packagePathResolver = new DefaultPackagePathResolver(packages);
                var packagesFolderFileSystem = new PhysicalFileSystem(packages);
                var projectSystem = new MSBuildProjectSystem(projectFile);
                var localRepository = new LocalPackageRepository(packagePathResolver, packagesFolderFileSystem);
                var projectManager = new ProjectManager(repo, packagePathResolver, projectSystem, localRepository);

                projectManager.RemovePackageReference(packageid,true,false);
                projectManager.AddPackageReference(packageid, version, true, false);
                projectSystem.Save();

                string filename = packageid + "." + version;
                string[] s = Directory.GetFiles(packages+ @"\"+filename);
                if (s.IsEmpty()) { System.Console.WriteLine("empty"); }
                else
                {
                    var nupkgFile = new PhysicalFileSystem(s[0]);
                    ZipPackage z = new ZipPackage(s[0]);
                    z.ExtractContents(nupkgFile, packages + @"\" + filename);
                }
                System.Console.WriteLine("Successfully updated");
                return true;
            }
            catch (Exception e)
            {
                System.Console.Write("failure");
                System.Console.Write(e.StackTrace);
                return false;
            }
        }
Beispiel #38
0
        private void EnsurePackageFiles()
        {
            if (_files != null &&
                _expandedFolderPath != null &&
                _expandedFileSystem.DirectoryExists(_expandedFolderPath))
            {
                return;
            }

            _files = new Dictionary <string, PhysicalPackageFile>();
            _supportedFrameworks = null;

            var packageName = new PackageName(Id, Version);

            // Only use the cache for expanded folders under %temp%, or set from unit tests
            if (_expandedFileSystem == _tempFileSystem || _forceUseCache)
            {
                Tuple <string, DateTimeOffset> cacheValue;
                DateTimeOffset lastModifiedTime = _fileSystem.GetLastModified(_packagePath);

                // if the cache doesn't exist, or it exists but points to a stale package,
                // then we invalidate the cache and store the new entry.
                if (!_cachedExpandedFolder.TryGetValue(packageName, out cacheValue) ||
                    cacheValue.Item2 < lastModifiedTime)
                {
                    cacheValue = Tuple.Create(GetExpandedFolderPath(), lastModifiedTime);
                    _cachedExpandedFolder[packageName] = cacheValue;
                }

                _expandedFolderPath = cacheValue.Item1;
            }
            else
            {
                _expandedFolderPath = GetExpandedFolderPath();
            }

            using (Stream stream = GetStream())
            {
                var package = new ZipArchive(stream);
                // unzip files inside package
                var files = from part in package.Entries
                            where ZipPackage.IsPackageFile(part)
                            select part;

                // now copy all package's files to disk
                foreach (ZipArchiveEntry file in files)
                {
                    string path     = file.FullName.Replace('/', '\\').Replace("%2B", "+");
                    string filePath = Path.Combine(_expandedFolderPath, path);

                    bool copyFile = true;

                    if (copyFile)
                    {
                        using (Stream partStream = file.Open())
                        {
                            try
                            {
                                using (Stream targetStream = _expandedFileSystem.CreateFile(filePath))
                                {
                                    partStream.CopyTo(targetStream);
                                }
                            }
                            catch (Exception)
                            {
                                // if the file is read-only or has an access denied issue, we just ignore it
                            }
                        }
                    }

                    var packageFile = new PhysicalPackageFile
                    {
                        SourcePath = _expandedFileSystem.GetFullPath(filePath),
                        TargetPath = path
                    };

                    _files[path] = packageFile;
                }
            }
        }
Beispiel #39
0
        private async Task <Tuple <string, string> > ResolvePackageIdAndVersion(string packageId, string packageVersion)
        {
            if (string.IsNullOrEmpty(packageId))
            {
                return(null);
            }

            // For nupkgs, get the id and version from the package
            if (packageId.EndsWith(".nupkg", StringComparison.OrdinalIgnoreCase))
            {
                if (!File.Exists(packageId))
                {
                    WriteError(string.Format("Could not find the file {0}.", packageId));
                    return(null);
                }

                var packagePath      = Path.GetFullPath(packageId);
                var packageDirectory = Path.GetDirectoryName(packagePath);
                var zipPackage       = new NuGet.ZipPackage(packagePath);
                FeedOptions.FallbackSources.Add(packageDirectory);

                return(new Tuple <string, string>(
                           zipPackage.Id,
                           zipPackage.Version.ToString()));
            }

            // If the version is missing, try to find the latest version
            if (string.IsNullOrEmpty(packageVersion))
            {
                var rootDirectory = ProjectResolver.ResolveRootDirectory(_commandsRepository.Root.Root);
                var config        = NuGetConfig.ForSolution(rootDirectory, RestoreCommand.FileSystem);

                var packageFeeds = new List <IPackageFeed>();

                var effectiveSources = PackageSourceUtils.GetEffectivePackageSources(
                    config.Sources,
                    FeedOptions.Sources,
                    FeedOptions.FallbackSources);

                foreach (var source in effectiveSources)
                {
                    var feed = PackageSourceUtils.CreatePackageFeed(
                        source,
                        FeedOptions.NoCache,
                        FeedOptions.IgnoreFailedSources,
                        Reports);
                    if (feed != null)
                    {
                        packageFeeds.Add(feed);
                    }
                }

                var package = await PackageSourceUtils.FindLatestPackage(packageFeeds, packageId);

                if (package == null)
                {
                    Reports.Error.WriteLine("Unable to locate the package {0}".Red(), packageId);
                    return(null);
                }

                return(new Tuple <string, string>(
                           packageId,
                           package.Version.ToString()));
            }

            // Otherwise, just assume that what you got is correct
            return(new Tuple <string, string>(packageId, packageVersion));
        }
Beispiel #40
0
        private void EnsurePackageFiles()
        {
            if ((this._files == null) || ((this._expandedFolderPath == null) || !this._expandedFileSystem.DirectoryExists(this._expandedFolderPath)))
            {
                this._files = new Dictionary <string, PhysicalPackageFile>();
                this._supportedFrameworks = null;
                PackageName key = new PackageName(base.Id, base.Version);
                if (!ReferenceEquals(this._expandedFileSystem, _tempFileSystem) && !this._forceUseCache)
                {
                    this._expandedFolderPath = this.GetExpandedFolderPath();
                }
                else
                {
                    Tuple <string, DateTimeOffset> tuple;
                    DateTimeOffset lastModified = this._fileSystem.GetLastModified(this._packagePath);
                    if (!_cachedExpandedFolder.TryGetValue(key, out tuple) || (tuple.Item2 < lastModified))
                    {
                        tuple = Tuple.Create <string, DateTimeOffset>(this.GetExpandedFolderPath(), lastModified);
                        _cachedExpandedFolder[key] = tuple;
                    }
                    this._expandedFolderPath = tuple.Item1;
                }
                using (Stream stream = this.GetStream())
                {
                    using (IEnumerator <PackagePart> enumerator = (from part in Package.Open(stream).GetParts()
                                                                   where ZipPackage.IsPackageFile(part)
                                                                   select part).GetEnumerator())
                    {
                        string path;
                        string str2;
                        goto TR_0023;
TR_000E:
                        PhysicalPackageFile file1 = new PhysicalPackageFile();
                        file1.SourcePath          = this._expandedFileSystem.GetFullPath(str2);
                        file1.TargetPath          = path;
                        this._files[path]         = file1;
TR_0023:
                        while (true)
                        {
                            if (enumerator.MoveNext())
                            {
                                PackagePart current = enumerator.Current;
                                path = UriUtility.GetPath(current.Uri);
                                str2 = Path.Combine(this._expandedFolderPath, path);
                                bool flag = true;
                                if (this._expandedFileSystem.FileExists(str2))
                                {
                                    using (Stream stream2 = current.GetStream())
                                    {
                                        using (Stream stream3 = this._expandedFileSystem.OpenFile(str2))
                                        {
                                            flag = stream2.Length != stream3.Length;
                                        }
                                    }
                                }
                                if (flag)
                                {
                                    Stream stream4 = current.GetStream();
                                    try
                                    {
                                        using (Stream stream5 = this._expandedFileSystem.CreateFile(str2))
                                        {
                                            stream4.CopyTo(stream5);
                                        }
                                    }
                                    catch (Exception)
                                    {
                                    }
                                    finally
                                    {
                                        if (stream4 != null)
                                        {
                                            stream4.Dispose();
                                        }
                                    }
                                }
                            }
                            else
                            {
                                return;
                            }
                            break;
                        }
                        goto TR_000E;
                    }
                }
            }
        }
Beispiel #41
0
        internal void EnsurePackage(IPackageCacheRepository cacheRepository)
        {
            // OData caches instances of DataServicePackage while updating their property values. As a result,
            // the ZipPackage that we downloaded may no longer be valid (as indicated by a newer hash).
            // When using MachineCache, once we've verified that the hashes match (which happens the first time around),
            // we'll simply verify the file exists between successive calls.
            IPackageMetadata packageMetadata = this;
            if (_package == null ||
                    (_package is OptimizedZipPackage && !((OptimizedZipPackage)_package).IsValid) ||
                    !String.Equals(OldHash, PackageHash, StringComparison.OrdinalIgnoreCase) ||
                    (_usingMachineCache && !cacheRepository.Exists(Id, packageMetadata.Version)))
            {
                IPackage newPackage = null;
                bool inMemOnly = false;
                bool isValid = false;

                // If the package exists in the cache and has the correct hash then use it. Otherwise download it.
                if (TryGetPackage(cacheRepository, packageMetadata, out newPackage) && MatchPackageHash(newPackage))
                {
                    isValid = true;
                }
                else
                {
                    // We either do not have a package available locally or they are invalid. Download the package from the server.
                    if (cacheRepository.InvokeOnPackage(packageMetadata.Id, packageMetadata.Version,
                        (stream) => Downloader.DownloadPackage(DownloadUrl, this, stream)))
                    {
                        newPackage = cacheRepository.FindPackage(packageMetadata.Id, packageMetadata.Version);
                        Debug.Assert(newPackage != null);
                    }
                    else
                    {
                        // this can happen when access to the %LocalAppData% directory is blocked, e.g. on Windows Azure Web Site build
                        using (var targetStream = new MemoryStream())
                        {
                            Downloader.DownloadPackage(DownloadUrl, this, targetStream);
                            targetStream.Seek(0, SeekOrigin.Begin);
                            newPackage = new ZipPackage(targetStream);
                        }

                        inMemOnly = true;
                    }

                    // Because of CDN caching, the hash returned in odata feed
                    // can be out of sync with the hash of the file itself.
                    // So for now, we cannot call MatchPackageHash(newPackage) to
                    // validate that the file downloaded has the right hash.
                    isValid = true;
                }

                // apply the changes if the package hash was valid
                if (isValid)
                {
                    _package = newPackage;

                    // Make a note that the backing store for the ZipPackage is the machine cache.
                    _usingMachineCache = !inMemOnly;

                    OldHash = PackageHash;
                }
                else
                {
                    // ensure package must end with a valid package, since we cannot load one we must throw.
                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,
                        NuGetResources.Error_InvalidPackage, Version, Id));
                }
            }
        }