예제 #1
0
        public void CtorWithStream()
        {
            // Arrange
            var builder = new PackageBuilder();
            builder.Id = "Package";
            builder.Version = new SemanticVersion("1.0");
            builder.Authors.Add("David");
            builder.Description = "This is a test package";
            builder.ReleaseNotes = "This is a release note.";
            builder.Copyright = "Copyright";
            builder.Files.AddRange(PackageUtility.CreateFiles(new[] { @"lib\40\A.dll", @"content\foo" }));

            var ms = new MemoryStream();
            builder.Save(ms);
            ms.Seek(0, SeekOrigin.Begin);

            // Act
            var package = new ZipPackage(ms);

            // Assert
            Assert.Equal("Package", package.Id);
            Assert.Equal(new SemanticVersion("1.0"), package.Version);
            Assert.Equal("David", package.Authors.First());
            Assert.Equal("Copyright", package.Copyright);
            var files = package.GetFiles().ToList();
            Assert.Equal(2, files.Count);
            Assert.Equal(@"content\foo", files[0].Path);
            Assert.Equal(@"lib\40\A.dll", files[1].Path);
            var assemblyReferences = package.AssemblyReferences.ToList();
            Assert.Equal(1, assemblyReferences.Count);
            Assert.Equal("A.dll", assemblyReferences[0].Name);
            Assert.Equal(new FrameworkName(".NETFramework", new Version("4.0")), assemblyReferences[0].TargetFramework);
            Assert.Equal("This is a release note.", package.ReleaseNotes);
        }
예제 #2
0
        public void CreatePackage(HttpContextBase context)
        {
            var request = context.Request;

            // Get the api key from the header
            string apiKey = request.Headers[ApiKeyHeader];

            // Get the package from the request body
            Stream stream = request.Files.Count > 0 ? request.Files[0].InputStream : request.InputStream;

            var package = new ZipPackage(stream);

            // Make sure they can access this package
            if (Authenticate(context, apiKey, package.Id))
            {
                try
                {
                    _serverRepository.AddPackage(package);
                    WriteStatus(context, HttpStatusCode.Created, "");
                }
                catch (InvalidOperationException ex)
                {
                    WriteStatus(context, HttpStatusCode.InternalServerError, ex.Message);
                }
            }
        }
        /// <summary>
        /// Checks whether an IPackage exists within a PackageManager.  By default, will use the UseSideBySide settings of the DefaultPackagePathProvider the PackageManager is instantiated with.
        /// If passed in TRUE for exhaustive, will check both with and without UseSideBySide set.
        /// </summary>
        /// <param name="packageManager"></param>
        /// <param name="package"></param>
        /// <param name="exhaustive"></param>
        /// <returns></returns>
        public static bool IsPackageInstalled(this PackageManager packageManager,  IPackage package, bool exhaustive = false)
        {

            var pathsDictionary = new Dictionary<string, bool>();
            //Oh god oh god. The <center> cannot hold it is too late.
            var useSideBySide = packageManager.PathResolver.GetPrivateField<bool>("_useSideBySidePaths");
            pathsDictionary.Add(Path.Combine(packageManager.PathResolver.GetInstallPath(package), 
                packageManager.PathResolver.GetPackageFileName(package.Id, package.Version)), useSideBySide);

            //We need to also check the inverse, to see if it was installed with the other setting....
            if (exhaustive)
            {
                var inversePathResolver = new DefaultPackagePathResolver(packageManager.PathResolver.GetPrivateField<IFileSystem>("_fileSystem"), !useSideBySide);
                pathsDictionary.Add(Path.Combine(inversePathResolver.GetInstallPath(package), inversePathResolver.GetPackageFileName(package.Id, package.Version)), !useSideBySide);
            }

            foreach (var path in pathsDictionary.Where(path => packageManager.FileSystem.FileExists(path.Key)))
            {
                if (path.Value)
                {
                    return true;
                }
                
                //If not useSideBySide, we need to crack open the zip file.
                //Need to crack the package open at this point and check the version, otherwise we just need to download it regardless
                var zipPackage = new ZipPackage(packageManager.FileSystem.OpenFile(path.Key));
                if (zipPackage.Version == package.Version)
                {
                    return true;
                }
            }

            //Its not here.  Really.  We tried.
            return false;
        }
예제 #4
0
파일: ZipHelper.cs 프로젝트: ctddjyds/npoi
        /**
         * Retrieve the zip entry of the core properties part.
         *
         * @throws OpenXml4NetException
         *             Throws if internal error occurs.
         */
        public static ZipEntry GetCorePropertiesZipEntry(ZipPackage pkg)
        {
            PackageRelationship corePropsRel = pkg.GetRelationshipsByType(
                    PackageRelationshipTypes.CORE_PROPERTIES).GetRelationship(0);

            if (corePropsRel == null)
                return null;

            ZipEntry ze = new ZipEntry(corePropsRel.TargetUri.OriginalString);
            return ze;
        }
예제 #5
0
        public ActionResult AddLocalPackage(HttpPostedFileBase file)
        {
            if (file == null)
            {
                ModelState.AddModelError("PackageFileValidation", "No file selected. Please select a package file to upload.");
                return(LocalRepository());
            }

            if (!Path.GetExtension(file.FileName).EndsWith("nupkg"))
            {
                ModelState.AddModelError("PackageFileValidation", "The file uploaded is not a valid package file, only Nuget packages are supported");
                return(LocalRepository());
            }

            IPackage package;

            try
            {
                package = new ZipPackage(file.InputStream);
            }
            catch (Exception ex)
            {
                LogHelper.Error <PackagingEditorController>("Package could not be unziped.", ex);

                ModelState.AddModelError("PackageFileValidation", "The Nuget package file uploaded could not be read");
                return(LocalRepository());
            }

            try
            {
                var fileName = Path.Combine(BackOfficeRequestContext.PackageContext.LocalPackageManager.SourceRepository.Source, file.FileName);
                file.SaveAs(fileName);
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("PackageFileValidation", "The package file could not be saved. " + ex.Message);
                return(LocalRepository());
            }

            if (!string.IsNullOrWhiteSpace(Request.Form["autoinstall"]))
            {
                BackOfficeRequestContext.PackageContext.LocalPackageManager.InstallPackage(package, false);

                Notifications.Add(new NotificationMessage(package.Title + " has been installed", "Package installed", NotificationType.Success));
                SuccessfulOnRedirectAttribute.EnsureRouteData(this, "id", package.Id);

                return(RedirectToAction("RecycleApplication", new { id = package.Id, state = PackageInstallationState.Installing }));
            }

            Notifications.Add(new NotificationMessage(package.Title + " added to local repository", "Package added", NotificationType.Success));
            SuccessfulOnRedirectAttribute.EnsureRouteData(this, "id", package.Id);
            return(RedirectToAction("LocalRepository"));
        }
            public Dictionary <ShortcutLocation, ShellLink> GetShortcutsForExecutable(string exeName, ShortcutLocation locations, string programArguments)
            {
                this.Log().Info("About to create shortcuts for {0}, rootAppDir {1}", exeName, rootAppDirectory);

                var releases    = Utility.LoadLocalReleases(Utility.LocalReleaseFileForAppDir(rootAppDirectory));
                var thisRelease = Utility.FindCurrentVersion(releases);

                var zf = new ZipPackage(Path.Combine(
                                            Utility.PackageDirectoryForAppDir(rootAppDirectory),
                                            thisRelease.Filename));

                var exePath     = Path.Combine(Utility.AppDirForRelease(rootAppDirectory, thisRelease), exeName);
                var fileVerInfo = FileVersionInfo.GetVersionInfo(exePath);

                var ret = new Dictionary <ShortcutLocation, ShellLink>();

                foreach (var f in (ShortcutLocation[])Enum.GetValues(typeof(ShortcutLocation)))
                {
                    if (!locations.HasFlag(f))
                    {
                        continue;
                    }

                    var file                 = linkTargetForVersionInfo(f, zf, fileVerInfo);
                    var appUserModelId       = String.Format("com.squirrel.{0}.{1}", zf.Id.Replace(" ", ""), exeName.Replace(".exe", "").Replace(" ", ""));
                    var toastActivatorCLSDID = Utility.CreateGuidFromHash(appUserModelId).ToString();

                    this.Log().Info("Creating shortcut for {0} => {1}", exeName, file);
                    this.Log().Info("appUserModelId: {0} | toastActivatorCLSID: {1}", appUserModelId, toastActivatorCLSDID);

                    var target = Path.Combine(rootAppDirectory, exeName);
                    var sl     = new ShellLink
                    {
                        Target           = target,
                        IconPath         = target,
                        IconIndex        = 0,
                        WorkingDirectory = Path.GetDirectoryName(exePath),
                        Description      = zf.Description,
                    };

                    if (!String.IsNullOrWhiteSpace(programArguments))
                    {
                        sl.Arguments += String.Format(" -a \"{0}\"", programArguments);
                    }

                    sl.SetAppUserModelId(appUserModelId);
                    sl.SetToastActivatorCLSID(toastActivatorCLSDID);

                    ret.Add(f, sl);
                }

                return(ret);
            }
예제 #7
0
        private bool OpenLocalPackageCore(string packagePath)
        {
            IPackage package = null;

            string tempFile = null;

            try
            {
                tempFile = Path.GetTempFileName();
                File.Copy(packagePath, tempFile, overwrite: true);

                var extension = Path.GetExtension(packagePath);
                if (extension.Equals(Constants.PackageExtension, StringComparison.OrdinalIgnoreCase) ||
                    extension.Equals(Constants.SymbolPackageExtension, StringComparison.OrdinalIgnoreCase))
                {
                    package = new ZipPackage(tempFile);
                }
                else if (extension.Equals(Constants.ManifestExtension, StringComparison.OrdinalIgnoreCase))
                {
                    using (var str = ManifestUtility.ReadManifest(tempFile))
                    {
                        var builder = new PackageBuilder(str, Path.GetDirectoryName(packagePath));
                        package = builder.Build();
                    }
                }

                if (package != null)
                {
                    LoadPackage(package, packagePath, PackageType.LocalPackage);
                    _tempFile = tempFile;
                    return(true);
                }
            }
            catch (Exception ex)
            {
                package = null;
                UIServices.Show(ex.Message, MessageLevel.Error);
                return(false);
            }
            finally
            {
                if (package == null && tempFile != null && File.Exists(tempFile))
                {
                    try
                    {
                        File.Delete(tempFile);
                    }
                    catch { /* ignore */ }
                }
            }

            return(false);
        }
        private async void LoadSignatureData(ZipPackage package)
        {
            if (package.IsSigned)
            {
                PublisherSignature   = package.PublisherSignature;
                RepositorySignatures = package.RepositorySignatures;

                await Task.Run(() => package.VerifySignatureAsync());

                ValidationResult = new ValidationResultViewModel(package.VerificationResult);
            }
        }
예제 #9
0
        public void ListCommand_VerboseOutput()
        {
            var nugetexe = Util.GetNuGetExePath();

            using (var packageDirectory = TestDirectory.Create())
                using (var randomTestFolder = TestDirectory.Create())
                {
                    // Arrange
                    var packageFileName1 = Util.CreateTestPackage("testPackage1", "1.1.0", packageDirectory);
                    var packageFileName2 = Util.CreateTestPackage("testPackage2", "2.1", packageDirectory);
                    var package1         = new ZipPackage(packageFileName1);
                    var package2         = new ZipPackage(packageFileName2);

                    using (var server = new MockServer())
                    {
                        string searchRequest = string.Empty;

                        server.Get.Add("/nuget/$metadata", r =>
                                       Util.GetMockServerResource());
                        server.Get.Add("/nuget/Search()", r =>
                                       new Action <HttpListenerResponse>(response =>
                        {
                            searchRequest        = r.Url.ToString();
                            response.ContentType = "application/atom+xml;type=feed;charset=utf-8";
                            string feed          = server.ToODataFeed(new[] { package1, package2 }, "Search");
                            MockServer.SetResponseContent(response, feed);
                        }));
                        server.Get.Add("/nuget", r => "OK");

                        server.Start();

                        // Act
                        var args = "list test -Verbosity detailed -Source " + server.Uri + "nuget";
                        var r1   = CommandRunner.Run(
                            nugetexe,
                            randomTestFolder,
                            args,
                            waitForExit: true);
                        server.Stop();

                        // Assert
                        Assert.Equal(0, r1.Item1);

                        // verify that the output is detailed
                        Assert.Contains(package1.Description, r1.Item2);
                        Assert.Contains(package2.Description, r1.Item2);

                        Assert.Contains("$filter=IsLatestVersion", searchRequest);
                        Assert.Contains("searchTerm='test", searchRequest);
                        Assert.Contains("includePrerelease=false", searchRequest);
                    }
                }
        }
예제 #10
0
        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);
        }
예제 #11
0
        void AttemptToFindAndDownloadPackage(int attempt, string packageId, string packageVersion, string feed, string cacheDirectory, out IPackage downloadedPackage, out string path)
        {
            NuGet.PackageDownloader downloader;
            var package = FindPackage(attempt, packageId, packageVersion, feed, out downloader);

            var fullPathToDownloadTo = GetFilePathToDownloadPackageTo(cacheDirectory, package);

            DownloadPackage(package, fullPathToDownloadTo, downloader);

            path = fullPathToDownloadTo;
            downloadedPackage = new ZipPackage(fullPathToDownloadTo);
        }
        public bool InstallPackage(string packageFullPath, out string installationMessage, bool updateAll = false)
        {
            this.PackageFullPath = packageFullPath;
            ZipPackage zipPackage = new ZipPackage(PackageFullPath);

            PackageId      = zipPackage.Id;
            PackageVersion = zipPackage.Version.ToString();
            bool installed = vsProjectManager.InstallPackage(PackageId, PackageVersion, 10 * 60 * 1000, updateAll);

            installationMessage = GetPackageInstallationOutput();
            return(installed);
        }
예제 #13
0
        public void Initialize()
        {
            //extract package id and version.
            packagePath = AppSettingsHelper.PackageFullPathKeyValue;
            ZipPackage zipPackage = new ZipPackage(packagePath);

            packageId      = zipPackage.Id;
            packageVersion = zipPackage.Version.ToString();

            //set package sources.
            string PackageSource = Path.GetDirectoryName(packagePath);

            if (string.IsNullOrEmpty(PackageSource))
            {
                PackageSource = Environment.CurrentDirectory;
            }
            IList <KeyValuePair <string, string> > sources = new List <KeyValuePair <string, string> >();

            sources.Add(new KeyValuePair <string, string>("TestSource", PackageSource));
            //If additional sources are specified in the app.config file, add them too.
            if (!string.IsNullOrEmpty(AppSettingsHelper.PackageSourceKeyValue))
            {
                string[] additionalPackageSources = AppSettingsHelper.PackageSourceKeyValue.Split(new char[] { ',', ';' });
                int      i = 1;
                foreach (string additionalSource in additionalPackageSources)
                {
                    sources.Add(new KeyValuePair <string, string>("AdditionalSources_" + i.ToString(), additionalSource));
                    i++;
                }
            }
            NugetSettingsUtility.SetPackageSources(sources);
            NugetSettingsUtility.SetActivePackageSource("TestSource", PackageSource);

            //Set test run directory.
            if (string.IsNullOrEmpty(AppSettingsHelper.TestResultsPathKeyValue))
            {
                TestRunPath = Path.Combine(Environment.CurrentDirectory, packageId);
            }
            else
            {
                TestRunPath = AppSettingsHelper.TestResultsPathKeyValue;
            }
            //Create root level test run Dir
            if (!Directory.Exists(TestRunPath))
            {
                Directory.CreateDirectory(TestRunPath);
            }

            //initialize other values.
            projName  = DateTime.Now.Ticks.ToString();
            vsVersion = (VSVersion)Enum.Parse(typeof(VSVersion), AppSettingsHelper.VSVersionKeyValue, true);
            vsSKU     = (VSSKU)Enum.Parse(typeof(VSSKU), AppSettingsHelper.VSSKUKeyValue, true);
        }
예제 #14
0
        private void PushPackageCore(string source, string apiKey, PackageServer packageServer, string packageToPush, TimeSpan timeout)
        {
            // Push the package to the server
            var package = new ZipPackage(packageToPush);

            string sourceName = CommandLineUtility.GetSourceDisplayName(source);

            Console.WriteLine(NuGetResources.PushCommandPushingPackage, package.GetFullName(), sourceName);

            packageServer.PushPackage(apiKey, package.GetStream, Convert.ToInt32(timeout.TotalMilliseconds));
            Console.WriteLine(NuGetResources.PushCommandPackagePushed);
        }
예제 #15
0
        //  -------------------------- CreatePackage --------------------------
        /// <summary>
        ///   Creates a package zip file containing specified
        ///   content and resource files.</summary>
        private static void CreatePackage(string packagePath, bool withFiles, bool withDB, Player p)
        {
            // Create the Package
            if (withDB)
            {
                Server.s.Log("Saving DB...");
                SaveDatabase("SQL.sql");
                Server.s.Log("Saved DB to SQL.sql");
            }

            Server.s.Log("Creating package...");
            using (ZipPackage package = (ZipPackage)ZipPackage.Open(packagePath, FileMode.Create))
            {
                if (withFiles)
                {
                    Server.s.Log("Collecting Directory structure...");
                    string     currDir  = Directory.GetCurrentDirectory() + "\\";
                    List <Uri> partURIs = GetAllFiles(new DirectoryInfo("./"), new Uri(currDir));
                    Server.s.Log("Structure complete");

                    Server.s.Log("Saving data...");
                    foreach (Uri loc in partURIs)
                    {
                        if (!Uri.UnescapeDataString(loc.ToString()).Contains(packagePath))
                        {
                            // Add the part to the Package

                            ZipPackagePart packagePart =
                                (ZipPackagePart)package.CreatePart(loc, "");

                            // Copy the data to the Document Part
                            using (FileStream fileStream = new FileStream(
                                       "./" + Uri.UnescapeDataString(loc.ToString()), FileMode.Open, FileAccess.Read))
                            {
                                CopyStream(fileStream, packagePart.GetStream());
                            } // end:using(fileStream) - Close and dispose fileStream.
                        }
                    }         // end:foreach(Uri loc)
                }
                if (withDB)
                { // If we don't want to back up database, we don't do this part.
                    Server.s.Log("Compressing Database...");
                    ZipPackagePart packagePart =
                        (ZipPackagePart)package.CreatePart(new Uri("/SQL.sql", UriKind.Relative), "", CompressionOption.Normal);
                    CopyStream(File.OpenRead("SQL.sql"), packagePart.GetStream());
                    Server.s.Log("Database compressed.");
                } // end:if(withFiles)
                Server.s.Log("Data saved!");
            }     // end:using (Package package) - Close and dispose package.
            Player.SendMessage(p, "Server backup (" + (withFiles ? "Everything" + (withDB ? "" : " but Database") : "Database") + "): Complete!");
            Server.s.Log("Server backed up!");
        }// end:CreatePackage()
예제 #16
0
        private async void SignAndSaveAs()
        {
            var signViewModel = new SignPackageViewModel(ViewModel, ViewModel.UIServices, ViewModel.SettingsManager);

            if (ViewModel.UIServices.OpenSignPackageDialog(signViewModel, out var signedPackagePath))
            {
                var          packageName      = ViewModel.PackageMetadata + NuGetPe.Constants.PackageExtension;
                var          title            = "Save " + packageName;
                const string filter           = "NuGet package file (*.nupkg)|*.nupkg|NuGet Symbols package file (*.snupkg)|*.snupkg|All files (*.*)|*.*";
                var          initialDirectory = Path.IsPathRooted(ViewModel.PackageSource) ? ViewModel.PackageSource : null;
                if (ViewModel.UIServices.OpenSaveFileDialog(title, packageName, initialDirectory, filter, /* overwritePrompt */ false,
                                                            out var selectedPackagePath, out var filterIndex))
                {
                    if (filterIndex == 1 &&
                        !selectedPackagePath.EndsWith(NuGetPe.Constants.PackageExtension, StringComparison.OrdinalIgnoreCase))
                    {
                        selectedPackagePath += NuGetPe.Constants.PackageExtension;
                    }

                    // prompt if the file already exists on disk
                    if (File.Exists(selectedPackagePath))
                    {
                        var confirmed = ViewModel.UIServices.Confirm(
                            Resources.ConfirmToReplaceFile_Title,
                            string.Format(CultureInfo.CurrentCulture, Resources.ConfirmToReplaceFile, selectedPackagePath));
                        if (!confirmed)
                        {
                            return;
                        }
                    }

                    try
                    {
                        File.Copy(signedPackagePath, selectedPackagePath, overwrite: true);
                        ViewModel.OnSaved(selectedPackagePath);
                        ViewModel.PackageSource = selectedPackagePath;
                        ViewModel.PackageMetadata.ClearSignatures();
                        using (var package = new ZipPackage(selectedPackagePath))
                        {
                            await package.LoadSignatureDataAsync();

                            ViewModel.PackageMetadata.LoadSignatureData(package);
                        }
                        ViewModel.IsSigned = true;
                    }
                    catch (Exception ex)
                    {
                        ViewModel.UIServices.Show(ex.Message, MessageLevel.Error);
                    }
                }
            }
        }
예제 #17
0
        public async Task <IPackage> DownloadAsync(Revision revision)
        {
            var request = new GetArchiveLinkRequest(
                accountName: AccountName,
                repositoryName: RepositoryName,
                revision: revision,
                format: GitArchiveFormat.Zipball
                );

            var link = await client.GetArchiveLinkAsync(request).ConfigureAwait(false);

            return(await ZipPackage.DownloadAsync(link, stripFirstLevel : true).ConfigureAwait(false));
        }
예제 #18
0
        /// <summary>
        /// Function to unzip and restore a set of singing keys
        /// </summary>
        /// <param name="fromZipFile"></param>
        /// <param name="certPath"></param>
        public void Restore(string fromZipFile)
        {
            Package zipFilePackage = ZipPackage.Open(fromZipFile, FileMode.Open, FileAccess.ReadWrite);

            //Iterate through the all the files that
            //is added within the collection and
            foreach (ZipPackagePart contentFile in zipFilePackage.GetParts())
            {
                createFile(contentFile);
            }

            zipFilePackage.Close();
        }
예제 #19
0
        internal void Save()
        {
            _sectionProperties.WriteToBody(_currentPart.Writer.TextWriter, _currentHeaderFooterReferences);
            _firstSection = true;
            _sectionProperties.Continuous = false;
            WriteCloseTag(CT_Document.BodyElementName);
            WriteCloseTag(_currentPart.Part.Tag);
            Stream stream = ZipPackage.GetPart(new Uri(PartManager.CleanName(_currentPart.PartName), UriKind.Relative)).GetStream();

            _currentPart.Writer.Interleave(stream, WriteInterleaverToDocument);
            WriteNumberingPart();
            _manager.Write();
        }
예제 #20
0
        private void FinishHeaderOrFooter()
        {
            if (_currentPart.Writer.Location == _currentPart.StartingLocation)
            {
                OpenXmlParagraphModel.WriteInvisibleParagraph(_currentPart.Writer.TextWriter);
            }
            WriteCloseTag(_currentPart.Part.Tag);
            Stream stream = ZipPackage.GetPart(new Uri(PartManager.CleanName(_currentPart.PartName), UriKind.Relative)).GetStream();

            _currentPart.Writer.Interleave(stream, WriteInterleaverToHeaderOrFooter);
            _currentPart.Stream.Dispose();
            _currentPart = _documentPart;
        }
예제 #21
0
 /// <summary>
 /// Given the path to the nupkg file, returns the corresponding package ID.
 /// </summary>
 public string GetPackageIdFromNupkgFile(string filePath)
 {
     try
     {
         ZipPackage pack = new ZipPackage(filePath);
         return(pack.Id);
     }
     catch (Exception e)
     {
         WriteLine(" Exception thrown while trying to create zippackage for :{0}. Message {1}", filePath, e.Message);
         return(null);
     }
 }
예제 #22
0
        /// <summary>
        /// Extract snapshot file
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        internal static LoadActionParts LoadSnapshotZip(string path)
        {
            using (FileStream str = File.Open(path, FileMode.Open, FileAccess.Read))
                using (Package package = ZipPackage.Open(str, FileMode.Open, FileAccess.Read))
                {
                    var parts = package.GetParts();

                    var         elementPart = (from p in parts where p.Uri.OriginalString == "/" + SaveAction.elementFileName select p.GetStream()).First();
                    A11yElement element     = A11yElement.FromStream(elementPart);
                    elementPart.Close();

                    Bitmap bmp;
                    try
                    {
                        var bmpPart = (from p in parts where p.Uri.OriginalString == "/" + SaveAction.screenshotFileName select p.GetStream()).First();
                        bmp = LoadBmp(bmpPart);
                        bmpPart.Close();
                    }
                    catch (InvalidOperationException e) // Gets thrown if screenshot doesn't exist in file
                    {
                        e.ReportException();
                        bmp = null;
                    }

                    var metadataPart      = (from p in parts where p.Uri.OriginalString == "/" + SaveAction.metadataFileName select p.GetStream()).First();
                    SnapshotMetaInfo meta = SnapshotMetaInfo.DeserializeFromStream(metadataPart);
                    metadataPart.Close();

                    IReadOnlyDictionary <int, CustomProperty> CustomProperties;
                    try
                    {
                        var customPropertiesPart = (from p in parts where p.Uri.OriginalString == "/" + SaveAction.customPropsFileName select p.GetStream()).First();
                        CustomProperties = LoadCustomProperties(customPropertiesPart);
                        customPropertiesPart.Close();
                    }
#pragma warning disable CA1031                                 // Do not catch general exception types: specific handlers placed in conditional below
                    catch (Exception e)
#pragma warning restore CA1031                                 // Do not catch general exception types: specific handlers placed in conditional below
                    {
                        if (!(e is InvalidOperationException)) // An expected exception thrown when file does not exist, such as in old a11ytest files
                        {
                            e.ReportException();
                        }
                        CustomProperties = null;
                    }

                    var selectedElement = element.FindDescendant(k => k.UniqueId == meta.ScreenshotElementId);

                    return(new LoadActionParts(element, bmp, selectedElement.SynthesizeBitmapFromElements(), meta));
                }
        }
예제 #23
0
        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")));
        }
예제 #24
0
        public static void Export(string savePath)
        {
            // save configuration, as we're going to change it
            Configuration.Save();

            // create zipfile
            using (var zipFile = ZipPackage.Open(savePath, FileMode.Create))
            {
                // copy log files
                DirectoryInfo logDir = new DirectoryInfo(Installation.GetLogDirectory());
                foreach (FileInfo file in logDir.GetFiles("*.log").Concat(logDir.GetFiles("*.bak")))
                {
                    var logPart = zipFile.CreatePart(new Uri("/" + file.Name, UriKind.Relative), "", CompressionOption.Maximum);
                    File.Open(file.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite).CopyTo(logPart.GetStream());
                }

                // copy WebMediaPortal configuration (these don't contain any passwords, so we can copy them literally if they exist)
                CopyConfigurationFile(zipFile, "WebMediaPortal.xml");
                CopyConfigurationFile(zipFile, "StreamingPlatforms.xml");

                // copy literal config files
                WriteConfigFile(zipFile, (IConfigurationSerializer <MediaAccess>)Configuration.GetSerializer(ConfigurationFile.MediaAccess));
                WriteConfigFile(zipFile, (IConfigurationSerializer <StreamingProfiles>)Configuration.GetSerializer(ConfigurationFile.StreamingProfiles));

                // copy Authentication.xml without the passwords
                var authPart       = zipFile.CreatePart(new Uri("/Authentication.xml", UriKind.Relative), "", CompressionOption.Maximum);
                var authSerializer = (IConfigurationSerializer <Authentication>)Configuration.GetSerializer(ConfigurationFile.Authentication);
                foreach (var user in authSerializer.Get().Users)
                {
                    user.SetPasswordFromPlaintext(PASSWORD_SUBSTITUTE);
                }
                authSerializer.Save(authSerializer.Get(), authPart.GetStream());

                // copy Services.xml without network password
                var servicePart       = zipFile.CreatePart(new Uri("/Services.xml", UriKind.Relative), "", CompressionOption.Maximum);
                var serviceSerializer = (IConfigurationSerializer <ServicesConfig>)Configuration.GetSerializer(ConfigurationFile.Services);
                serviceSerializer.Get().NetworkImpersonation.SetPasswordFromPlaintext(PASSWORD_SUBSTITUTE);
                serviceSerializer.Save(serviceSerializer.Get(), servicePart.GetStream());

                // copy Streaming.xml without watch sharing password
                var streamingPart = zipFile.CreatePart(new Uri("/Streaming.xml", UriKind.Relative), "", CompressionOption.Maximum);
                var streamingSerializer = (IConfigurationSerializer <Streaming>)Configuration.GetSerializer(ConfigurationFile.Streaming);
                streamingSerializer.Get().WatchSharing.FollwitConfiguration["passwordHash"] = PASSWORD_SUBSTITUTE;
                streamingSerializer.Get().WatchSharing.TraktConfiguration["passwordHash"] = PASSWORD_SUBSTITUTE;
                streamingSerializer.Save(streamingSerializer.Get(), streamingPart.GetStream());
            }

            // reset the configuration after the changes we made to the passwords
            Configuration.Reset();
        }
예제 #25
0
            public Dictionary <ShortcutLocation, ShellLink> GetShortcutsForExecutable(string exeName, ShortcutLocation locations, string programArguments)
            {
                this.Log().Info("About to create shortcuts for {0}, rootAppDir {1}", exeName, rootAppDirectory);

                var releases    = Utility.LoadLocalReleases(Utility.LocalReleaseFileForAppDir(rootAppDirectory));
                var thisRelease = Utility.FindCurrentVersion(releases);
                var updateExe   = Path.Combine(rootAppDirectory, "update.exe");

                var zf = new ZipPackage(Path.Combine(
                                            Utility.PackageDirectoryForAppDir(rootAppDirectory),
                                            thisRelease.Filename));

                var exePath     = Path.Combine(Utility.AppDirForRelease(rootAppDirectory, thisRelease), exeName);
                var fileVerInfo = FileVersionInfo.GetVersionInfo(exePath);

                var ret = new Dictionary <ShortcutLocation, ShellLink>();

                foreach (var f in (ShortcutLocation[])Enum.GetValues(typeof(ShortcutLocation)))
                {
                    if (!locations.HasFlag(f))
                    {
                        continue;
                    }

                    var file = linkTargetForVersionInfo(f, zf, fileVerInfo);

                    this.Log().Info("Creating shortcut for {0} => {1}", exeName, file);

                    ShellLink sl;
                    sl = new ShellLink {
                        Target           = updateExe,
                        IconPath         = exePath,
                        IconIndex        = 0,
                        WorkingDirectory = Path.GetDirectoryName(exePath),
                        Description      = zf.Description,
                        Arguments        = "--processStart " + exeName,
                    };

                    if (!String.IsNullOrWhiteSpace(programArguments))
                    {
                        sl.Arguments += String.Format(" -a \"{0}\"", programArguments);
                    }

                    sl.SetAppUserModelId(String.Format("com.squirrel.{0}.{1}", zf.Id, exeName.Replace(".exe", "")));
                    sl.SetAppUserModelRelaunchCommand(String.Format("{0} {1}", sl.Target, sl.Arguments));
                    ret.Add(f, sl);
                }

                return(ret);
            }
예제 #26
0
        public static void ZipFiles(List <string> filesPath, string sZipPath, bool bOverwrite)
        {
            FileMode fileMode = bOverwrite ? FileMode.Create : FileMode.OpenOrCreate;

            //Open the zip file if it exists, else create a new one
            using (Package zip = ZipPackage.Open(sZipPath, fileMode, FileAccess.ReadWrite))
            {
                //Add as many files as you like:
                foreach (var file in filesPath)
                {
                    AddToArchive(zip, file);
                }
            }
        }        //End ZipFiles
        private IEnumerable <NugetPackage> GetPackageDependencies(string name, string version, Project project)
        {
            const string keyDelimiter     = "@@@";
            var          mapping          = _packageList.ToDictionary(c => c.Name + keyDelimiter + c.Version, StringComparer.InvariantCultureIgnoreCase);
            var          dependencies     = new List <NugetPackage>();
            var          nugetPackageFile = _solutionFolder + $@"\packages\{name}.{version}\{name}.{version}.nupkg";

            if (File.Exists(nugetPackageFile))
            {
                var package = new ZipPackage(nugetPackageFile);

                foreach (var dependency in package.GetCompatiblePackageDependencies(null))
                {
                    var keys = mapping.Keys.Where(k => k.StartsWith(dependency.Id + keyDelimiter, StringComparison.InvariantCultureIgnoreCase));

                    string key = null;

                    if (keys.Count().Equals(1))
                    {
                        key = keys.First();
                    }
                    else if (keys.Count() > 1 && project != null) //if we have multiple packages with various versions, figure out which version is being used for this project
                    {
                        var projectPackage = project.Packages.FirstOrDefault(k => k.Name.StartsWith(dependency.Id, StringComparison.InvariantCultureIgnoreCase));
                        if (projectPackage != null)
                        {
                            key = keys.FirstOrDefault(k => k.Equals(dependency.Id + keyDelimiter + projectPackage.Version, StringComparison.InvariantCultureIgnoreCase));
                        }
                    }

                    if (key != null)
                    {
                        var dependentPackage = mapping[key];

                        if (
                            !dependencies.Any(
                                d => d.Name.Equals(dependentPackage.Name) && d.Version.Equals(dependentPackage.Version)))
                        {
                            dependencies.Add(new NugetPackage
                            {
                                Name    = dependentPackage.Name,
                                Version = dependentPackage.Version
                            });
                        }
                    }
                }
            }

            return(dependencies);
        }
예제 #28
0
파일: ZipHelper.cs 프로젝트: purehzj/npoi-1
        /**
         * Retrieve the zip entry of the core properties part.
         *
         * @throws OpenXml4NetException
         *             Throws if internal error occurs.
         */
        public static ZipEntry GetCorePropertiesZipEntry(ZipPackage pkg)
        {
            PackageRelationship corePropsRel = pkg.GetRelationshipsByType(
                PackageRelationshipTypes.CORE_PROPERTIES).GetRelationship(0);

            if (corePropsRel == null)
            {
                return(null);
            }

            ZipEntry ze = new ZipEntry(corePropsRel.TargetUri.OriginalString);

            return(ze);
        }
예제 #29
0
        public static void UnzipFiles(string zipLocation, string directory)
        {
            ZipPackage zipFile = ZipPackage.Open(zipLocation, FileMode.Open) as ZipPackage;

            foreach (ZipPackagePart part in zipFile.GetParts())
            {
                using (Stream source = part.GetStream(FileMode.Open, FileAccess.Read))
                {
                    FileStream targetFile = File.OpenWrite(Path.Combine(directory, part.Uri.OriginalString.TrimStart('/')));
                    source.CopyTo(targetFile);
                    targetFile.Close();
                }
            }
        }
예제 #30
0
파일: ZipHelper.cs 프로젝트: ctddjyds/npoi
 /**
  * Retrieve the Zip entry of the content types part.
  */
 public static ZipEntry GetContentTypeZipEntry(ZipPackage pkg)
 {
     IEnumerator entries = pkg.ZipArchive.Entries;
     // Enumerate through the Zip entries until we find the one named
     // '[Content_Types].xml'.
     while (entries.MoveNext())
     {
         ZipEntry entry = (ZipEntry)entries.Current;
         if (entry.Name.Equals(
                 ContentTypeManager.CONTENT_TYPES_PART_NAME))
             return entry;
     }
     return null;
 }
예제 #31
0
        /// <summary>
        /// Decompress multiple files from a single zip file.
        /// </summary>
        /// <param name="bytBuffer">Byte array that contains the zip file.</param>
        public void DecompressNPCs(byte[] bytBuffer)
        {
            string strFilePath = Path.Combine(GlobalOptions.ApplicationPath(), "saves");

            // If the directory does not exist, create it.
            if (!Directory.Exists(strFilePath))
            {
                Directory.CreateDirectory(strFilePath);
            }

            MemoryStream objStream = new MemoryStream();

            objStream.Write(bytBuffer, 0, bytBuffer.Length);
            Package objPackage = ZipPackage.Open(objStream, FileMode.Open, FileAccess.Read);

            foreach (PackagePart objPart in objPackage.GetParts())
            {
                string strTarget = Path.Combine(strFilePath, objPart.Uri.ToString().Replace('_', ' '));

                Stream objSource = objPart.GetStream(FileMode.Open, FileAccess.Read);

                string[] strDirectory = strTarget.Split('/');
                if (!strDirectory[1].EndsWith(".chum"))
                {
                    if (!Directory.Exists(Path.Combine(strFilePath, strDirectory[1])))
                    {
                        Directory.CreateDirectory(Path.Combine(strFilePath, strDirectory[1]));
                    }
                }
                if (!strDirectory[2].EndsWith(".chum"))
                {
                    if (!Directory.Exists(Path.Combine(strFilePath, strDirectory[1] + Path.DirectorySeparatorChar + strDirectory[2])))
                    {
                        Directory.CreateDirectory(Path.Combine(strFilePath, strDirectory[1] + Path.DirectorySeparatorChar + strDirectory[2]));
                    }
                }

                Stream objDestination = File.OpenWrite(strFilePath + strTarget.Replace('/', Path.DirectorySeparatorChar));
                byte[] bytFileBuffer  = new byte[100000];
                int    intRead;
                intRead = objSource.Read(bytFileBuffer, 0, bytFileBuffer.Length);
                while (intRead > 0)
                {
                    objDestination.Write(bytFileBuffer, 0, intRead);
                    intRead = objSource.Read(bytFileBuffer, 0, bytFileBuffer.Length);
                }
                objDestination.Close();
                objSource.Close();
            }
        }
예제 #32
0
        /// <summary>
        /// Adds a file to the zip file
        /// </summary>
        /// <param name="File">File to add</param>
        public virtual void AddFile(string File)
        {
            File.ThrowIfNullOrEmpty("File");
            FileInfo TempFileInfo = new FileInfo(File);

            if (!TempFileInfo.Exists)
            {
                throw new ArgumentException("File");
            }
            using (Package Package = ZipPackage.Open(ZipFileStream, FileMode.OpenOrCreate))
            {
                AddFile(TempFileInfo.Name, TempFileInfo, Package);
            }
        }
예제 #33
0
        public static byte[] ReplaceApplicationRibbonDiffXmlInSolutionBody(byte[] solutionBodyBinary, XElement newRibbonDiffXml)
        {
            using (var memStream = new MemoryStream())
            {
                memStream.Write(solutionBodyBinary, 0, solutionBodyBinary.Length);

                using (ZipPackage package = (ZipPackage)ZipPackage.Open(memStream, FileMode.Open, FileAccess.ReadWrite))
                {
                    ZipPackagePart part = (ZipPackagePart)package.GetPart(new Uri("/customizations.xml", UriKind.Relative));

                    if (part != null)
                    {
                        XDocument doc = null;

                        using (Stream streamPart = part.GetStream(FileMode.Open, FileAccess.Read))
                        {
                            doc = XDocument.Load(streamPart);
                        }

                        var ribbonDiffXml = doc.XPathSelectElement("ImportExportXml/RibbonDiffXml");

                        if (ribbonDiffXml != null)
                        {
                            ribbonDiffXml.ReplaceWith(newRibbonDiffXml);
                        }

                        using (Stream streamPart = part.GetStream(FileMode.Create, FileAccess.Write))
                        {
                            XmlWriterSettings settings = new XmlWriterSettings
                            {
                                OmitXmlDeclaration = true,
                                Indent             = true,
                                Encoding           = Encoding.UTF8
                            };

                            using (XmlWriter xmlWriter = XmlWriter.Create(streamPart, settings))
                            {
                                doc.Save(xmlWriter);
                                xmlWriter.Flush();
                            }
                        }
                    }
                }

                memStream.Position = 0;
                byte[] result = memStream.ToArray();

                return(result);
            }
        }
        public PlatformExportManifest ReadPlatformExportManifest(Stream stream)
        {
            PlatformExportManifest retVal = null;

            using (var package = ZipPackage.Open(stream, FileMode.Open))
            {
                var manifestPart = package.GetPart(_manifestPartUri);
                using (var streamReader = new StreamReader(manifestPart.GetStream()))
                {
                    retVal = streamReader.ReadToEnd().DeserializeXML <PlatformExportManifest>();
                }
            }
            return(retVal);
        }
예제 #35
0
        /// <summary>
        /// Adds a file to the zip file
        /// </summary>
        /// <param name="File">File to add</param>
        public virtual void AddFile(string File)
        {
            Contract.Requires <ArgumentNullException>(!string.IsNullOrEmpty(File), "File");
            FileInfo TempFileInfo = new FileInfo(File);

            if (!TempFileInfo.Exists)
            {
                throw new ArgumentException("File does not exist");
            }
            using (Package Package = ZipPackage.Open(ZipFileStream, FileMode.OpenOrCreate))
            {
                AddFile(TempFileInfo.Name, TempFileInfo, Package);
            }
        }
예제 #36
0
        public void CreatePackage(HttpContextBase context)
        {
            RouteData routeData = GetRouteData(context);
            var request = context.Request;

            // Get the api key from the header
            string apiKey = request.Headers[ApiKeyHeader];

            // Get the package from the request body
            Stream stream = request.Files.Count > 0 ? request.Files[0].InputStream : request.InputStream;

            var package = new ZipPackage(stream);

            // Make sure they can access this package
            Authenticate(context, apiKey, package.Id,
                         () => _serverRepository.AddPackage(package));
        }
예제 #37
0
		public void CreatePackage(HttpContextBase context)
		{
			try {
				_logger.Trace("Creating package...");
				var request = context.Request;

				_logger.Trace("Request context collected");
				// Get the api key from the header
				string apiKey = request.Headers[ApiKeyHeader];

				if (!string.IsNullOrEmpty(apiKey))
				_logger.Trace("apiKey collected (length={0})", apiKey.Length);

				// Get the package from the request body
				Stream stream = request.Files.Count > 0 ? request.Files[0].InputStream : request.InputStream;

				var package = new ZipPackage(stream);

				// Make sure they can access this package
					_logger.Trace("Attempting to authenticate...");
				if (Authenticate(context, apiKey, package.Id))
				{
					try
					{
						_logger.Trace("Adding package...");
						_serverRepository.AddPackage(package);
						WriteStatus(context, HttpStatusCode.Created, "");
					}
					catch (InvalidOperationException ex)
					{
						WriteStatus(context, HttpStatusCode.InternalServerError, ex.Message);
					}
				}
			}
			catch(Exception ex)
			{
				_logger.Error(ex, "CreatePackage(HttpContextBase)");
				throw;
			}
		}
예제 #38
0
        public void CtorWithStream()
        {
            // Arrange
            var builder = new PackageBuilder();
            builder.Id = "Package";
            builder.Version = new SemanticVersion("1.0");
            builder.Authors.Add("David");
            builder.Description = "This is a test package";
            builder.ReleaseNotes = "This is a release note.";
            builder.Copyright = "Copyright";
            builder.Files.AddRange(PackageUtility.CreateFiles(new[] { PathFixUtility.FixPath(@"lib\40\A.dll"), PathFixUtility.FixPath(@"content\foo") }));

            var ms = new MemoryStream();
            builder.Save(ms);
            ms.Seek(0, SeekOrigin.Begin);

            // Act
            var package = new ZipPackage(ms);

            // Assert
            Assert.Equal("Package", package.Id);
            Assert.Equal(new SemanticVersion("1.0"), package.Version);
            Assert.Equal("David", package.Authors.First());
            Assert.Equal("Copyright", package.Copyright);

            //Order is not gauranteed (or required) from GetFiles(), 
            //but we rely on the order for a few of the asserts, 
            //and it appears to not behave the same way on Mono,
            //so we call "order by" here to force a specific order.
            var files = package.GetFiles().OrderBy(k => k.Path).ToList();

            Assert.Equal(2, files.Count);
            Assert.Equal(PathFixUtility.FixPath(@"content\foo"), files[0].Path);
            Assert.Equal(PathFixUtility.FixPath(@"lib\40\A.dll"), files[1].Path);
            var assemblyReferences = package.AssemblyReferences.ToList();
            Assert.Equal(1, assemblyReferences.Count);
            Assert.Equal("A.dll", assemblyReferences[0].Name);
            Assert.Equal(new FrameworkName(".NETFramework", new Version("4.0")), assemblyReferences[0].TargetFramework);
            Assert.Equal("This is a release note.", package.ReleaseNotes);
        }
예제 #39
0
		public void Publish(string packagePath, string apiKey)
		{
			var logPath = _pathService.GetRelative(packagePath);
			_context.WriteTrace(LogEntryType.Information,
				$"Pushing \"{logPath}\" to NuGet repository");
			var packageServer = new PackageServer(_sourceUrl, _userAgent);
			try
			{
				var package = new ZipPackage(packagePath);
				using (var stream = package.GetStream())
				{
					packageServer.PushPackage(apiKey, package, stream.Length, _publishTimeout, true);
					_context.WriteTrace(LogEntryType.Information,
						$"\"{logPath}\" was pushed successfully");
				}
			}
			catch (Exception ex)
			{
				Trace.TraceError("*Exception: {0}, StackTrace", ex.Message, ex.StackTrace);
				throw;
			}
		}
예제 #40
0
            public bool Deploy(ZipPackage package, ILog logger)
            {
                var options = package.GetPackageOptions<WebOptions>();

                logger.Info("Deploying iis package to {0}:{1} using {2}".Fmt(options.WebsiteName, options.WebsitePort, options.DeployService));

                var client = new JsonServiceClient(options.DeployService); // todo
                var request = new TriggerDeployment()
                {
                    AppPoolName = "ZZZ_Integration_PoolName",
                    AppPoolUser = "******",
                    AppPoolPassword = "******",
                    WebsiteName = "ZZZ_Integration_Website_Simple",
                    AppRoot = "/",
                    PackageId = "IntegrationTest",
                    PackageVersion = "1.3.3.7",
                    WebsitePhysicalPath = @"C:\temp\integrationtests",
                    RuntimeVersion = RuntimeVersion.Version40,
                };

                var response = client.PostFileWithRequest<TriggerDeploymentResponse>("/deployments", new FileInfo("package.zip"), request);

                return true;
            }
예제 #41
0
        public Stream OpenPackageSourceFile(IPackageName package, string relativePath)
        {
            relativePath = relativePath.Replace('/', Path.DirectorySeparatorChar);

            // Try to return the source file from its uncompressed location
            var parts = new[] {
                package.Id,
                package.Version.ToString(),
                "src",
                relativePath
            };

            var stream = OpenFile(Path.Combine(parts));

            if (stream != null) return stream;

            // If the file wasn't found uncompressed look for it in symbol package zip file
            var packagePath = GetNupkgPath(package);
            if (!File.Exists(packagePath)) return null;

            var srcPath = Path.Combine("src", relativePath);
            var packageFile = new ZipPackage(packagePath);
            var file = packageFile.GetFiles().SingleOrDefault(f => f.Path.Equals(srcPath, StringComparison.InvariantCultureIgnoreCase));
            return file != null ? file.GetStream() : null;
        }
예제 #42
0
        IEnumerable<ICommandOutput> ValidateInputs()
        {
            // TODO: HACK HACK HACK
            var namedRepository = Remotes.PublishRepositories(Remote).SelectMany(_ => _).FirstOrDefault();

            if (namedRepository == null)
            {
                yield return new UnknownRemoteName(Remote);
                foreach (var _ in HintRemoteRepositories()) yield return _;
                yield break;
            }

            if ((Username != null && Password == null) || (Username == null && Password != null))
            {
                yield return new IncompleteCredentials();
                yield break;
            }

            bool hasAuth = Username != null && Password != null;
            if (hasAuth) _credentials = new NetworkCredential(Username, Password);
            _authenticationSupport = namedRepository.Feature<ISupportAuthentication>();
            if (hasAuth && _authenticationSupport == null)
            {
                yield return new RemoteAuthenticatioNotSupported(namedRepository);
                yield break;
            }

            _authenticationSupport = _authenticationSupport ?? new NullAuthentication();

            //_repositories = namedRepository.
            _remoteRepository = namedRepository;
            var publishingRepo = _remoteRepository.Feature<ISupportPublishing>();

            if (publishingRepo == null)
            {
                yield return new Error("Repository '{0}' doesn't support publishing.", namedRepository.Name);
                yield break;
            }
            if (Path != null)
            {
                var packageFile = FileSystem.GetFile(Path);
                if (!packageFile.Exists)
                {
                    yield return new FileNotFound(Path);
                    yield break;
                }
                _packageStream = packageFile.OpenRead;
                _packageFileName = packageFile.Name;
                // TODO: This looks iffy at best
                var package = new ZipPackage(packageFile);
                _packageName = package.Name;
                _packageVersion = package.Version;
            }
            else if (Name != null)
            {
                // get latest version of the Named package
                if (!HostEnvironment.CurrentDirectoryRepository.PackagesByName.Contains(Name))
                {
                    yield return new Error("No package named '{0}' was found.", Name);
                    yield break;
                }
                var packageToCopy = HostEnvironment.CurrentDirectoryRepository.PackagesByName[Name].OrderByDescending(x => x.Version).First();
                _packageStream = () => packageToCopy.Load().OpenStream();
                _packageFileName = packageToCopy.FullName + ".wrap";
                _packageName = packageToCopy.Name;
                _packageVersion = packageToCopy.Version;
            }
            else
            {
                yield return new Error("Please specify either a file path using the -Path input, or a name using -Name.");
            }
        }
예제 #43
0
 public static ZipPackage GetZipPackage(string id, string version)
 {
     PackageBuilder builder = new PackageBuilder();
     builder.Id = id;
     builder.Version = SemanticVersion.Parse(version);
     builder.Authors.Add("David");
     builder.Description = "This is a test package";
     builder.ReleaseNotes = "This is a release note.";
     builder.Copyright = "Copyright";
     builder.Files.AddRange(PackageUtility.CreateFiles(new[] { @"lib\foo" }));
     var ms = new MemoryStream();
     builder.Save(ms);
     ms.Seek(0, SeekOrigin.Begin);
     var p = new ZipPackage(ms);
     return p;
 }
예제 #44
0
        public void PackageBuilderWorksWithFileNamesContainingSpecialCharacters()
        {
            // Arrange
            var fileNames = new[] {
                @"lib\regular.file.dll",
                @"lib\name with spaces.dll",
                @"lib\C#\test.dll",
                @"content\images\logo123?#78.png",
                @"content\images\bread&butter.jpg",
            };

            // Act
            var builder = new PackageBuilder { Id = "test", Version = new SemanticVersion("1.0"), Description = "test" };
            builder.Authors.Add("test");
            foreach (var name in fileNames)
            {
                builder.Files.Add(CreatePackageFile(name));
            }

            // Assert
            using (MemoryStream stream = new MemoryStream())
            {
                builder.Save(stream);

                var zipPackage = new ZipPackage(() => new MemoryStream(stream.ToArray()), enableCaching: false);
                Assert.Equal(@"content\images\bread&butter.jpg", zipPackage.GetFiles().ElementAt(0).Path);
                Assert.Equal(@"content\images\logo123?#78.png", zipPackage.GetFiles().ElementAt(1).Path);
                Assert.Equal(@"lib\C#\test.dll", zipPackage.GetFiles().ElementAt(2).Path);
                Assert.Equal(@"lib\name with spaces.dll", zipPackage.GetFiles().ElementAt(3).Path);
                Assert.Equal(@"lib\regular.file.dll", zipPackage.GetFiles().ElementAt(4).Path);
            }
        }
예제 #45
0
        private void PushPackage(string packagePath, string source, string apiKey = null)
        {
            var gallery = new GalleryServer(source);

            // Use the specified api key or fall back to default behavior
            apiKey = apiKey ?? GetApiKey(source);

            // Push the package to the server
            var package = new ZipPackage(packagePath);

            Console.WriteLine(NuGetResources.PushCommandPushingPackage, package.GetFullName(), CommandLineUtility.GetSourceDisplayName(source));

            using (Stream stream = package.GetStream()) {
                gallery.CreatePackage(apiKey, stream);
            }

            // Publish the package on the server
            if (!CreateOnly) {
                var cmd = new PublishCommand();
                cmd.Console = Console;
                cmd.Source = source;
                cmd.Arguments = new List<string> { package.Id, package.Version.ToString(), apiKey };
                cmd.Execute();
            }
            else {
                Console.WriteLine(NuGetResources.PushCommandPackageCreated, source);
            }
        }
예제 #46
0
        private void PrintVerbose(string outputPath)
        {
            Console.WriteLine();
            var package = new ZipPackage(outputPath);

            Console.WriteLine("Id: {0}", package.Id);
            Console.WriteLine("Version: {0}", package.Version);
            Console.WriteLine("Authors: {0}", String.Join(", ", package.Authors));
            Console.WriteLine("Description: {0}", package.Description);
            if (package.LicenseUrl != null)
            {
                Console.WriteLine("License Url: {0}", package.LicenseUrl);
            }
            if (package.ProjectUrl != null)
            {
                Console.WriteLine("Project Url: {0}", package.ProjectUrl);
            }
            if (!String.IsNullOrEmpty(package.Tags))
            {
                Console.WriteLine("Tags: {0}", package.Tags.Trim());
            }
            if (package.DependencySets.Any())
            {
                Console.WriteLine("Dependencies: {0}", String.Join(", ", package.DependencySets.SelectMany(d => d.Dependencies).Select(d => d.ToString())));
            }
            else
            {
                Console.WriteLine("Dependencies: None");
            }

            Console.WriteLine();

            foreach (var file in package.GetFiles().OrderBy(p => p.Path))
            {
                Console.WriteLine(NuGetResources.PackageCommandAddedFile, file.Path);
            }

            Console.WriteLine();
        }
예제 #47
0
        public void ListCommand_AllVersionsPrerelease()
        {
            var targetDir = ConfigurationManager.AppSettings["TargetDir"];
            var nugetexe = Path.Combine(targetDir, "nuget.exe");
            var tempPath = Path.GetTempPath();
            var packageDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());
            var mockServerEndPoint = "http://localhost:1234/";

            try
            {
                // Arrange
                Util.CreateDirectory(packageDirectory);
                var packageFileName1 = Util.CreateTestPackage("testPackage1", "1.1.0", packageDirectory);
                var packageFileName2 = Util.CreateTestPackage("testPackage2", "2.1", packageDirectory);
                var package1 = new ZipPackage(packageFileName1);
                var package2 = new ZipPackage(packageFileName2);

                var server = new MockServer(mockServerEndPoint);
                string searchRequest = string.Empty;

                server.Get.Add("/nuget/$metadata", r =>
                    MockServerResource.NuGetV2APIMetadata);
                server.Get.Add("/nuget/Search()", r =>
                    new Action<HttpListenerResponse>(response =>
                    {
                        searchRequest = r.Url.ToString();
                        response.ContentType = "application/atom+xml;type=feed;charset=utf-8";
                        string feed = server.ToODataFeed(new[] { package1, package2 }, "Search");
                        MockServer.SetResponseContent(response, feed);
                    }));
                server.Get.Add("/nuget", r => "OK");

                server.Start();

                // Act
                var args = "list test -AllVersions -Prerelease -Source " + mockServerEndPoint + "nuget";
                var r1 = CommandRunner.Run(
                    nugetexe,
                    tempPath,
                    args,
                    waitForExit: true);
                server.Stop();

                // Assert
                Assert.Equal(0, r1.Item1);

                // verify that the output is detailed
                var expectedOutput = "testPackage1 1.1.0" + Environment.NewLine +
                    "testPackage2 2.1" + Environment.NewLine;
                Assert.Equal(expectedOutput, r1.Item2);

                Assert.DoesNotContain("$filter", searchRequest);
                Assert.Contains("searchTerm='test", searchRequest);
                Assert.Contains("includePrerelease=true", searchRequest);
            }
            finally
            {
                // Cleanup
                Util.DeleteDirectory(packageDirectory);
            }
        }
예제 #48
0
        private void PushPackage(string packagePath, string source, string apiKey) {
            var packageServer = new PackageServer(source, "NuGet Command Line");

            // Push the package to the server
            var package = new ZipPackage(packagePath);

            //HACK no pretty source name, as they have made the call to  CommandLineUtility.GetSourceDisplayName(source) internal
            Console.WriteLine("Pushing {0} to {1}", package.GetFullName(), source);

            try 
            {
                using (package.GetStream())
                {
                    packageServer.PushPackage(apiKey, package, 60000);
                }
            }
            catch 
            {
                Console.WriteLine();
                throw;
            }
        }
예제 #49
0
        public void InstallCommand_DownloadPackageWhenHashChanges()
        {
            var targetDir = ConfigurationManager.AppSettings["TargetDir"];
            var nugetexe = Path.Combine(targetDir, "nuget.exe");
            var tempPath = Path.GetTempPath();
            var packageDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());
            var workingDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());
            var mockServerEndPoint = "http://localhost:1234/";

            try
            {
                // Arrange
                Util.CreateDirectory(packageDirectory);
                Util.CreateDirectory(workingDirectory);
                var packageFileName = Util.CreateTestPackage("testPackage1", "1.1.0", packageDirectory);
                var package = new ZipPackage(packageFileName);
                MachineCache.Default.RemovePackage(package);

                // add the package to machine cache
                MachineCache.Default.AddPackage(package);

                // create a new package. Now this package has different hash value from the package in
                // the machine cache.
                packageFileName = Util.CreateTestPackage("testPackage1", "1.1.0", packageDirectory);
                package = new ZipPackage(packageFileName);

                var server = new MockServer(mockServerEndPoint);
                string findPackagesByIdRequest = string.Empty;
                bool packageDownloadIsCalled = false;

                server.Get.Add("/nuget/FindPackagesById()", r =>
                    new Action<HttpListenerResponse>(response =>
                    {
                        findPackagesByIdRequest = r.Url.ToString();
                        response.ContentType = "application/atom+xml;type=feed;charset=utf-8";
                        string feed = server.ToODataFeed(new[] { package }, "FindPackagesById");
                        MockServer.SetResponseContent(response, feed);
                    }));

                server.Get.Add("/nuget/Packages(Id='testPackage1',Version='1.1.0')", r =>
                    new Action<HttpListenerResponse>(response =>
                    {
                        response.ContentType = "application/atom+xml;type=entry;charset=utf-8";
                        var p1 = server.ToOData(package);
                        MockServer.SetResponseContent(response, p1);
                    }));

                server.Get.Add("/package/testPackage1", r =>
                    new Action<HttpListenerResponse>(response =>
                    {
                        packageDownloadIsCalled = true;
                        response.ContentType = "application/zip";
                        using (var stream = package.GetStream())
                        {
                            var content = stream.ReadAllBytes();
                            MockServer.SetResponseContent(response, content);
                        }
                    }));

                server.Get.Add("/nuget", r => "OK");

                server.Start();

                // Act
                var args = "install testPackage1 -Source " + mockServerEndPoint + "nuget";
                var r1 = CommandRunner.Run(
                    nugetexe,
                    workingDirectory,
                    args,
                    waitForExit: true);
                server.Stop();

                // Assert
                Assert.Equal(0, r1.Item1);
                Assert.Contains("$filter=IsLatestVersion", findPackagesByIdRequest);

                // verifies that package is downloaded from server since the cached version has
                // a different hash from the package on the server.
                Assert.True(packageDownloadIsCalled);
            }
            finally
            {
                // Cleanup
                Util.DeleteDirectory(packageDirectory);
                Util.DeleteDirectory(workingDirectory);
            }
        }
예제 #50
0
        private void PushPackage(string packagePath, string source, string apiKey)
        {
            var packageServer = new PackageServer(source, CommandLineConstants.UserAgent);

            // Push the package to the server
            var package = new ZipPackage(packagePath);

            string sourceName = CommandLineUtility.GetSourceDisplayName(source);
            Console.WriteLine(NuGetResources.PushCommandPushingPackage, package.GetFullName(), sourceName);

            using (Stream stream = package.GetStream())
            {
                packageServer.PushPackage(apiKey, stream);
            }

            if (CreateOnly)
            {
                Console.WriteWarning(NuGetResources.Warning_PublishPackageDeprecated);
            }
            Console.WriteLine(NuGetResources.PushCommandPackagePushed);
        }
        private void AddPackagesFromDropFolder()
        {
            _logger.Log(LogLevel.Info, "Start adding packages from drop folder.");

            MonitorFileSystem(false);

            try
            {
                var serverPackages = new HashSet<ServerPackage>(PackageEqualityComparer.IdAndVersion);

                foreach (var packageFile in _fileSystem.GetFiles(_fileSystem.Root, "*.nupkg", false))
                {
                    try
                    {
                        // Copy to correct filesystem location
                        var package = new ZipPackage(_fileSystem.OpenFile(packageFile));
                        _expandedPackageRepository.AddPackage(package);
                        _fileSystem.DeleteFile(packageFile);

                        // Mark for addition to metadata store
                        serverPackages.Add(CreateServerPackage(package, EnableDelisting));
                    }
                    catch (UnauthorizedAccessException ex)
                    {
                        // The file may be in use (still being copied) - ignore the error
                        _logger.Log(LogLevel.Error, "Error adding package file {0} from drop folder: {1}", packageFile, ex.Message);
                    }
                    catch (IOException ex)
                    {
                        // The file may be in use (still being copied) - ignore the error
                        _logger.Log(LogLevel.Error, "Error adding package file {0} from drop folder: {1}", packageFile, ex.Message);
                    }
                }

                // Add packages to metadata store in bulk
                _serverPackageStore.StoreRange(serverPackages);
                _serverPackageStore.PersistIfDirty();

                _logger.Log(LogLevel.Info, "Finished adding packages from drop folder.");
            }
            finally
            {
                MonitorFileSystem(true);
            }
        }
예제 #52
0
        internal static IPackage GetPackage(IPackageCacheRepository packageCache, PackageIdentity packageIdentity, Uri downloadUri)
        {
            var packageSemVer = CoreConverters.SafeToSemanticVersion(packageIdentity.Version);
            var packageName = CoreConverters.SafeToPackageName(packageIdentity);
            var downloader = new PackageDownloader();

            IPackage package = null;
            if (packageCache != null)
            {
                package = packageCache.FindPackage(packageName.Id, packageSemVer);
                if (package != null)
                {
                    NuGetTraceSources.ActionExecutor.Info(
                        "download/cachehit",
                        "[{0}] Download: Cache Hit!",
                        packageIdentity);
                    // Success!
                    return package;
                }

                if (downloadUri == null)
                {
                    throw new InvalidOperationException(String.Format(
                        CultureInfo.CurrentCulture,
                        Strings.DownloadActionHandler_NoDownloadUrl,
                        packageIdentity));
                }

                // Try to download the package through the cache.
                bool success = packageCache.InvokeOnPackage(
                    packageIdentity.Id,
                    packageSemVer,
                    (targetStream) =>
                        downloader.DownloadPackage(
                            new HttpClient(downloadUri),
                            packageName,
                            targetStream));
                if (success)
                {
                    NuGetTraceSources.ActionExecutor.Info(
                        "download/downloadedtocache",
                        "[{0}] Download: Downloaded to cache",
                        packageName);

                    // Try to get it from the cache again
                    package = packageCache.FindPackage(packageIdentity.Id, packageSemVer);
                }
            }

            // Either:
            //  1. We failed to load the package into the cache, which can happen when
            //       access to the %LocalAppData% directory is blocked,
            //       e.g. on Windows Azure Web Site build OR
            //  B. It was purged from the cache before it could be retrieved again.
            // Regardless, the cache isn't working for us, so download it in to memory.
            if (package == null)
            {
                NuGetTraceSources.ActionExecutor.Info(
                    "download/cachefailing",
                    "[{0}] Download: Cache isn't working. Downloading to RAM",
                    packageName);

                using (var targetStream = new MemoryStream())
                {
                    downloader.DownloadPackage(
                        new HttpClient(downloadUri),
                        packageName,
                        targetStream);

                    targetStream.Seek(0, SeekOrigin.Begin);
                    package = new ZipPackage(targetStream);
                }
            }
            return package;
        }
예제 #53
0
        public void RestoreCommand_FromHttpSource()
        {
            var targetDir = ConfigurationManager.AppSettings["TargetDir"];
            var nugetexe = Path.Combine(targetDir, "nuget.exe");
            var tempPath = Path.GetTempPath();
            var workingDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());
            var packageDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());
            var mockServerEndPoint = "http://*****:*****@"
<packages>
  <package id=""testPackage1"" version=""1.1.0"" />
</packages>");

                var server = new MockServer(mockServerEndPoint);
                bool getPackageByVersionIsCalled = false;
                bool packageDownloadIsCalled = false;

                server.Get.Add("/nuget/Packages(Id='testPackage1',Version='1.1.0')", r =>
                    new Action<HttpListenerResponse>(response =>
                    {
                        getPackageByVersionIsCalled = true;
                        response.ContentType = "application/atom+xml;type=entry;charset=utf-8";
                        var odata = server.ToOData(package);
                        MockServer.SetResponseContent(response, odata);
                    }));

                server.Get.Add("/package/testPackage1", r =>
                    new Action<HttpListenerResponse>(response =>
                    {
                        packageDownloadIsCalled = true;
                        response.ContentType = "application/zip";
                        using (var stream = package.GetStream())
                        {
                            var content = stream.ReadAllBytes();
                            MockServer.SetResponseContent(response, content);
                        }
                    }));

                server.Get.Add("/nuget", r => "OK");

                server.Start();

                // Act
                var args = "restore packages.config -PackagesDirectory . -Source " + mockServerEndPoint + "nuget";
                var r1 = CommandRunner.Run(
                    nugetexe,
                    workingDirectory,
                    args,
                    waitForExit: true);
                server.Stop();

                // Assert
                Assert.Equal(0, r1.Item1);
                Assert.True(getPackageByVersionIsCalled);
                Assert.True(packageDownloadIsCalled);
            }
            finally
            {
                // Cleanup
                Util.DeleteDirectory(packageDirectory);
                Util.DeleteDirectory(workingDirectory);
            }
        }
예제 #54
0
    void ImagesListView_ItemCommand(object sender, RadListViewCommandEventArgs e)
    {
        if (e.CommandName == "DownloadAllAsZip")
        {
            RadListViewDataItem item = ListViewAlbums.SelectedItems[0];
            int parentID = Convert.ToInt32(item.GetDataKeyValue("ID").ToString());
            string albumName = item.GetDataKeyValue("Name").ToString();
            List<DataContext.Image> allImagesFromAlbum = (from a in context.Images
                                                          where a.AlbumID == parentID
                                                          select a).ToList();

            MemoryStream memStream = new MemoryStream();

            Package = ZipPackage.Create(memStream);

            foreach (var image in allImagesFromAlbum)
            {
                Stream stream = new MemoryStream(image.Data);
                Package.AddStream(stream, image.FileName);
            }

            Package.Close(false);

            memStream.Position = 0;

            if (memStream != null && memStream.Length > 0)
            {
                Response.Clear();
                Response.AddHeader("content-disposition", "attachment; filename=" + albumName + ".zip");
                Response.ContentType = "application/zip";
                Response.BinaryWrite(memStream.ToArray());
                Response.End();
            }
        }
        if (e.CommandName == "DownloadImage")
        {
            RadListViewDataItem item = e.ListViewItem as RadListViewDataItem;
            int imageID = Convert.ToInt32(item.GetDataKeyValue("ID").ToString());
            DataContext.Image image = (from i in context.Images
                                       where i.ID == imageID
                                       select i).First();
            byte[] data = image.Data;
            string name = image.FileName;

            if (data != null && data.Length > 0)
            {
                Response.Clear();
                Response.ContentType = "application/octet-stream";
                Response.AddHeader("content-disposition", "attachment; filename=" + name);
                Response.BinaryWrite(data);
                Response.End();
            }
        }
    }
예제 #55
0
        private void PushPackage(string packagePath, string source, string apiKey) {
            var gallery = new GalleryServer(source);

            // Push the package to the server
            var package = new ZipPackage(packagePath);

            bool complete = false;
            gallery.ProgressAvailable += (sender, e) => {
                                             Console.Write("\r" + "Pushing: {0}", e.PercentComplete);

                                             if (e.PercentComplete == 100) {
                                                 Console.WriteLine();
                                                 complete = true;
                                             }
                                         };

            Console.WriteLine("Pushing {0} to {1}", package.GetFullName(), SourceProvider.GetDisplayName(source));

            try {
                using (Stream stream = package.GetStream()) {
                    gallery.CreatePackage(apiKey, stream);
                }
            }
            catch {
                if (!complete) {
                    Console.WriteLine();
                }
                throw;
            }

            // Publish the package on the server

            var cmd = new PublishCommand(SourceProvider);
            cmd.Console = Console;
            cmd.Source = source;
            cmd.Arguments = new List<string> {
                                                 package.Id,
                                                 package.Version.ToString(),
                                                 apiKey
                                             };
            cmd.Execute();
        }
예제 #56
0
        private void PushPackageCore(string source, string apiKey, PackageServer packageServer, string packageToPush, TimeSpan timeout)
        {
            // Push the package to the server
            var package = new ZipPackage(packageToPush);

            string sourceName = CommandLineUtility.GetSourceDisplayName(source);
            Console.WriteLine(NuGetResources.PushCommandPushingPackage, package.GetFullName(), sourceName);

            packageServer.PushPackage(apiKey, package, Convert.ToInt32(timeout.TotalMilliseconds));
            Console.WriteLine(NuGetResources.PushCommandPackagePushed);
        }
예제 #57
0
        private void PushPackage(string packagePath, string source, string apiKey) {
            var packageServer = new PackageServer(source, "NuGet Command Line");

            // Push the package to the server
            var package = new ZipPackage(packagePath);

            bool complete = false;

            //HACK no pretty source name, as they have made the call to  CommandLineUtility.GetSourceDisplayName(source) internal
            Console.WriteLine("Pushing {0} to {1}", package.GetFullName(), source);

            try {
                using (Stream stream = package.GetStream()) {
                    packageServer.PushPackage(apiKey, stream, 60000);
                }
            }
            catch {
                if (!complete) {
                    Console.WriteLine();
                }
                throw;
            }

            // Publish the package on the server

            var cmd = new PublishCommand();
            cmd.Console = Console;
            cmd.Source = source;
            cmd.Arguments.AddRange(new List<string> {
                                                 package.Id,
                                                 package.Version.ToString(),
                                                 apiKey
                                             });
            cmd.Execute();
        }
예제 #58
0
        private void PushPackageCore(string source, string apiKey, PackageServer packageServer, string packageToPush, TimeSpan timeout)
        {
            // Push the package to the server
            var package = new ZipPackage(packageToPush);

            string sourceName = CommandLineUtility.GetSourceDisplayName(source);
            Console.WriteLine(NuGetResources.PushCommandPushingPackage, package.GetFullName(), sourceName);

            using (Stream stream = package.GetStream())
            {
                packageServer.PushPackage(apiKey, stream, Convert.ToInt32(timeout.TotalMilliseconds));
            }

            if (CreateOnly)
            {
                Console.WriteWarning(NuGetResources.Warning_PublishPackageDeprecated);
            }
            Console.WriteLine(NuGetResources.PushCommandPackagePushed);
        }